Datasets:
File size: 13,381 Bytes
3f15e9f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | """Add source-native fruit and decor to a derivative of the reviewed house."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import rhg_paths
import argparse
import copy
import json
import math
import sys
from pathlib import Path
import bpy
from mathutils import Matrix, Quaternion, Vector
def main():
parser = argparse.ArgumentParser()
for key in ('tree', 'scene', 'output', 'materials'):
parser.add_argument('--' + key, type=Path, required=True)
args = parser.parse_args(sys.argv[sys.argv.index('--') + 1:])
code = args.tree / 'engine/source/scripts/internal/scene_generation'
sys.path[:0] = [str(args.tree), str(args.tree / 'engine'), str(code / 'real_assets')]
from supplemental_scene_decor import validate_plan
from supplemental_asset_sources import SOURCES as source_templates
SOURCES = {name: Path(rhg_paths.resolve(str(path))) for name, path in source_templates.items()}
from supplemental_blender_assets import (
digest, fingerprint, horizontal_surfaces, import_asset, mesh_bounds,
place_bottom_center, tree_for)
from real_test.render_wholehouse import snapshot
from asset_import import material_record
if args.output.exists():
raise ValueError('Output exists: ' + str(args.output))
before_files = snapshot(args.scene)
mp = args.scene / 'composition_manifest.runtime.json'
manifest = json.loads(mp.read_text())
source = args.scene / (manifest['scene_id'] + '.blend')
parent_receipt = json.loads((args.scene / 'home_revision_receipt.json').read_text())
assert parent_receipt['source_blend_sha256'] == digest(source)
assert parent_receipt['source_manifest_sha256'] == digest(mp)
prepared = json.loads(args.materials.read_text())
plan = validate_plan()
bpy.ops.wm.open_mainfile(filepath=str(source))
entities = {e['entity_id']: e for e in manifest['entities']}
shifted = {'completion__002', 'completion__003', 'completion__004',
'completion__006', 'completion__007', 'completion__prop_01'}
protected = {o.name: fingerprint(o) for o in bpy.context.scene.objects
if o.get('entity_id') not in shifted | {'refrigerator'}}
original_materials = {slot.material.name: material_record(slot.material)['signature_sha256']
for o in bpy.context.scene.objects if o.get('entity_id') != 'refrigerator'
for slot in o.material_slots if slot.material}
child_entities = copy.deepcopy([e for e in manifest['entities'] if e.get('room_id') == 'guest'])
retired = copy.deepcopy(entities['refrigerator'])
old_fridge = [o for o in bpy.context.scene.objects if o.get('entity_id') == 'refrigerator']
assert len(old_fridge) == 3
for obj in old_fridge:
bpy.data.objects.remove(obj, do_unlink=True)
movements = []
for eid in sorted(shifted):
group = [o for o in bpy.context.scene.objects if o.get('entity_id') == eid]
assert group and all(o.parent is None for o in group)
before = mesh_bounds(group)
for obj in group:
obj.matrix_world = Matrix.Translation((0, -.20, 0)) @ obj.matrix_world
e = entities[eid]
for key in ('center_xy_m', 'actual_center_xy_m'):
if key in e:
e[key][1] -= .20
if e.get('visual_footprint_polygon_xy_m'):
e['visual_footprint_polygon_xy_m'] = [[p[0], p[1] - .20] for p in e['visual_footprint_polygon_xy_m']]
e['world_bbox_m'] = mesh_bounds(group)
e['supplemental_translation_m'] = [0, -.20, 0]
movements.append(dict(entity_id=eid, before=before, after=e['world_bbox_m']))
fridge = import_asset('fridge', 'refrigerator', prepared)
native_box = mesh_bounds(fridge)
body = [o for o in fridge if 'Body001' in o['source_mesh_name']]
assert len(body) == 1
native_tree = tree_for(body)
levels = horizontal_surfaces(native_tree, 0., 0., .81, .15)
print('NATIVE_SHELF_LEVELS', levels, flush=True)
assert levels, 'No actual refrigerator shelf surface'
level = levels[0]
translation = Vector((10.875 - native_box[1][1],
3.555 - max(abs(native_box[0][0]), abs(native_box[1][0])),
-native_box[0][2]))
transform = Matrix.Translation(translation) @ Matrix.Rotation(-math.pi / 2, 4, 'Z')
root = bpy.data.objects.new('refrigerator__assembly', None)
bpy.context.collection.objects.link(root)
root.matrix_world = transform
root['entity_id'] = 'refrigerator'
root['open_angle_deg'] = 0.
root.id_properties_ui('open_angle_deg').update(min=0., max=90., description='Refrigerator door opening in degrees')
joint = prepared['fridge']['joints'][0]
pivot = Vector(joint['physics:localPos0'])
axis = Quaternion(joint['physics:localRot0']) @ Vector((1, 0, 0))
assert (axis - Vector((0, 0, 1))).length < 1e-5
hinge = bpy.data.objects.new('refrigerator__door_hinge', None)
bpy.context.collection.objects.link(hinge)
hinge.parent = root
hinge.location = pivot
hinge['source_joint_path'] = joint['path']
hinge['joint_limits_deg'] = [joint['physics:lowerLimit'], joint['physics:upperLimit']]
hinge['entity_id'] = 'refrigerator'
door = [o for o in fridge if 'fridge_door' in o['source_mesh_name']]
assert len(door) == 2
for obj in fridge:
if obj in door:
obj.parent = hinge
obj.matrix_basis = Matrix.Translation(-pivot)
else:
obj.parent = root
obj.matrix_basis = Matrix.Identity(4)
driver = hinge.driver_add('rotation_euler', 2).driver
var = driver.variables.new()
var.name = 'angle'
var.targets[0].id = root
var.targets[0].data_path = '["open_angle_deg"]'
driver.expression = 'min(90,max(0,angle))*0.017453292519943295'
bpy.context.view_layer.update()
closed_box = mesh_bounds(fridge)
assert closed_box[1][0] <= 10.8751 and closed_box[1][1] <= 3.5551
assert closed_box[0][1] - entities['completion__002']['world_bbox_m'][1][1] > .035
additions, support_checks = [], []
def register(eid, name, room, meshes, **extra):
box = mesh_bounds(meshes)
row = dict(entity_id=eid, asset_id='supplemental:' + name,
canonical_path=str(SOURCES[name]), runtime_path=str(SOURCES[name]),
asset_sha256=digest(SOURCES[name]), runtime_sha256=digest(SOURCES[name]),
category='fruit' if name == 'orange' else 'decoration', role=name,
room_id=room, world_bbox_m=box,
dimensions_m=[box[1][i] - box[0][i] for i in range(3)],
center_xy_m=[(box[0][i] + box[1][i]) / 2 for i in range(2)],
base_z_m=box[0][2], uniform_scale=1.,
source_mesh_object_names=[o.name for o in meshes], **extra)
for obj in meshes:
obj['room_id'] = room
obj['role'] = name
additions.append(row)
return row
for spec in plan['refrigerator']['fruit']:
x, y, _ = spec['center']
local_levels = horizontal_surfaces(native_tree, x, y, level + .04, level - .04)
assert local_levels, ('Fruit lacks actual shelf support', spec['id'])
fruit = import_asset('orange', spec['id'], prepared)
place_bottom_center(fruit, (x, y), local_levels[0] + .0015)
native_fruit_box = mesh_bounds(fruit)
assert native_fruit_box[0][0] >= -.28 and native_fruit_box[1][0] <= .28
assert native_fruit_box[0][1] >= -.14 and native_fruit_box[1][1] <= .30
assert native_fruit_box[1][2] <= .82, 'Fruit exceeds refrigerator cavity'
for obj in fruit:
obj.matrix_world = transform @ obj.matrix_world
bpy.context.view_layer.update()
register(spec['id'], 'orange', 'kitchen', fruit,
contained_by_entity_id='refrigerator', supported_by_entity_id='refrigerator',
native_cavity_bbox_m=native_fruit_box)
support_checks.append(dict(entity_id=spec['id'], support='authored_refrigerator_shelf',
shelf_z_native_m=local_levels[0], gap_m=.0015))
root['open_angle_deg'] = float(plan['refrigerator']['open_angle_deg'])
root.update_tag()
bpy.context.view_layer.update()
open_box = mesh_bounds(fridge)
fridge_row = dict(entity_id='refrigerator', category='refrigerator', role='refrigerator',
room_id='kitchen', asset_id='lightwheel:Refrigerator034',
runtime_path=str(SOURCES['fridge']), canonical_path=str(SOURCES['fridge']),
asset_sha256=digest(SOURCES['fridge']), runtime_sha256=digest(SOURCES['fridge']),
uniform_scale=1., dimensions_m=[native_box[1][i] - native_box[0][i] for i in range(3)],
world_bbox_m=open_box, closed_world_bbox_m=closed_box,
center_xy_m=list(translation[:2]), base_z_m=0.,
articulation=dict(control_object=root.name, property='open_angle_deg',
angle_deg=root['open_angle_deg'], range_deg=[0, 90],
source_joint=joint, physics_simulation_tested=False))
manifest['entities'] = [fridge_row if e['entity_id'] == 'refrigerator' else e for e in manifest['entities']]
for spec in plan['decor']:
meshes = import_asset(spec['source'], spec['id'], prepared)
if 'support' in spec:
group = [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.get('entity_id') == spec['support']]
box = mesh_bounds(group)
point, _, _, _ = tree_for(group).ray_cast(Vector((*spec['xy'], box[1][2] + .05)), Vector((0, 0, -1)), 1.)
assert point is not None, ('No tabletop support', spec['id'])
z = point.z + .0015
support_checks.append(dict(entity_id=spec['id'], support=spec['support'], gap_m=.0015))
else:
z = spec['base_z']
place_bottom_center(meshes, spec['xy'], z, spec.get('yaw', 0))
row = register(spec['id'], spec['source'], spec['room_id'], meshes,
supported_by_entity_id=spec.get('support'), group=spec['group'])
for old in manifest['entities'] + additions[:-1]:
if old['entity_id'] == spec.get('support'):
continue
a, b = row['world_bbox_m'], old.get('world_bbox_m')
if b and all(min(a[1][i], b[1][i]) - max(a[0][i], b[0][i]) > .002 for i in range(3)):
raise ValueError('Decor intersects existing entity: ' + spec['id'] + ' / ' + old['entity_id'])
manifest['entities'].extend(additions)
def verify():
bpy.context.view_layer.update()
assert all(name in bpy.data.objects and fingerprint(bpy.data.objects[name]) == value
for name, value in protected.items()), 'Unrelated object changed'
assert all(name in bpy.data.materials and material_record(bpy.data.materials[name])['signature_sha256'] == value
for name, value in original_materials.items()), 'Original material changed'
assert child_entities == [e for e in manifest['entities'] if e.get('room_id') == 'guest']
assert abs(hinge.rotation_euler.z - math.radians(root['open_angle_deg'])) < 1e-5
verify()
args.output.mkdir(parents=True)
out = args.output / source.name
bpy.ops.wm.save_as_mainfile(filepath=str(out), relative_remap=False)
bpy.ops.wm.open_mainfile(filepath=str(out))
root = bpy.data.objects['refrigerator__assembly']
hinge = bpy.data.objects['refrigerator__door_hinge']
verify()
assert snapshot(args.scene) == before_files
receipt = dict(schema='rhg.supplemental-scene.v1', passed=True,
parent_blend_sha256=digest(source), parent_manifest_sha256=digest(mp),
source_scene_unchanged=True, children_room_preserved=True,
cream_white_wall_material_preserved=True, original_other_objects_preserved=len(protected),
moved_entities=movements, replaced_refrigerator=retired,
refrigerator_closed_bbox=closed_box, refrigerator_open_bbox=open_box,
additions=[e['entity_id'] for e in additions], native_scale_preserved=True,
support_checks=support_checks, saved_reopen_passed=True,
physical_simulation_certified=False, materials_preparation_path=str(args.materials),
materials_preparation_sha256=digest(args.materials))
manifest['supplemental_scene_revision'] = {k: v for k, v in receipt.items() if k != 'replaced_refrigerator'}
(args.output / 'composition_manifest.runtime.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
receipt['source_blend_sha256'] = digest(out)
receipt['source_manifest_sha256'] = digest(args.output / 'composition_manifest.runtime.json')
for name in ('supplemental_scene_receipt.json', 'home_revision_receipt.json'):
(args.output / name).write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(dict(passed=True, output=str(out), added=len(additions), source_preserved=True)), flush=True)
if __name__ == '__main__':
main()
|