Datasets:
File size: 20,078 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 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | """Apply source-backed floor and show-home assets to a verified saved scene."""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import rhg_paths
import argparse
import copy
import hashlib
import importlib.util
import json
import math
import sys
from pathlib import Path
import bpy
from mathutils import Matrix, Vector
from mathutils.bvhtree import BVHTree
def geometry_signature(obj):
value = (tuple(tuple(r) for r in obj.matrix_world),
[tuple(v.co) for v in obj.data.vertices],
[(tuple(p.vertices), p.material_index) for p in obj.data.polygons],
[[tuple(v.uv) for v in layer.data] for layer in obj.data.uv_layers])
return hashlib.sha256(repr(value).encode()).hexdigest()
def main():
parser = argparse.ArgumentParser()
for key in ('tree', 'scene', 'output', 'sources', 'structural-manifest'):
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_blender_assets import digest, fingerprint, horizontal_surfaces, import_asset, mesh_bounds, place_bottom_center, tree_for
from asset_import import material_record
from structural_material_application import _build_material
from real_test.render_wholehouse import snapshot
from stage_checkpoint import fingerprint as json_fingerprint
assert not args.output.exists(), 'Use a new derivative directory'
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')
receipt = json.loads((args.scene / 'home_revision_receipt.json').read_text())
assert receipt['passed'] and receipt['source_blend_sha256'] == digest(source)
assert receipt['source_manifest_sha256'] == digest(mp)
assert digest(args.structural_manifest) == manifest['structural_material_manifest']['sha256']
structural = json.loads(args.structural_manifest.read_text())
plan = json.loads((args.tree / 'showhome_plan.json').read_text())
sources = {k: Path(v) for k, v in rhg_paths.resolve(json.loads(args.sources.read_text())).items()}
bpy.ops.wm.open_mainfile(filepath=str(source))
changed = set(plan['move']) | {s['id'] for s in plan['replace']}
protected = {o.name: fingerprint(o) for o in bpy.context.scene.objects
if o.get('entity_id') not in changed and o.name != 'floor__whole_house'}
original_materials = {s.material.name: material_record(s.material)['signature_sha256']
for o in bpy.context.scene.objects for s in o.material_slots if s.material}
original_entities = copy.deepcopy([e for e in manifest['entities'] if e['entity_id'] not in changed])
floor = bpy.data.objects['floor__whole_house']
floor_geometry = geometry_signature(floor)
floor_slots = [m.name for m in floor.data.materials]
entities = {e['entity_id']: e for e in manifest['entities']}
replaced = {eid: copy.deepcopy(entities[eid]) for eid in changed if eid not in plan['move']}
def meshes(eid):
if eid.startswith('structure:'):
return [bpy.data.objects[eid.split(':', 1)[1]]]
return [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.get('entity_id') == eid]
def support_height(eid, xy, hint):
group = meshes(eid)
box = mesh_bounds(group)
hits = horizontal_surfaces(tree_for(group), *xy, box[1][2] + .02, box[0][2] - .02)
assert hits, ('No supporting face', eid, xy)
z = min(hits, key=lambda v: abs(v - hint))
assert abs(z - hint) < .3, ('Support level differs', eid, hits, hint)
return z
texture_root = args.tree / 'assets/floors/WoodFloor052'
provenance = json.loads((texture_root / 'provenance.json').read_text())
floor_spec = dict(asset_id=provenance['asset_id'], material_id=provenance['asset_id'],
family_id=provenance['asset_id'], role='floor_dry', source='ambientCG',
license=provenance['license'], source_url=provenance['source_url'],
texture_scale_m=provenance['texture_scale_m'],
texture_scale_provenance=provenance['texture_scale_provenance'],
channels={}, normal_convention='OpenGL', normal_strength=.4,
uv_policy='world_box_metres', selection_reason='user_requested_chevron_floor')
for channel, item in provenance['channels'].items():
path = texture_root / item['file']
assert digest(path) == item['sha256']
floor_spec['channels'][channel] = dict(source_path=str(path), sha256=item['sha256'],
image_size=[2048, 2048], color_space='sRGB' if channel == 'baseColor' else 'raw')
renderer_path = code.parent / 'render/rhg_render_cinematic_v0_2_v10_49_asset_library_hdr_pbr.py'
module_spec = importlib.util.spec_from_file_location('showhome_material_renderer', renderer_path)
renderer = importlib.util.module_from_spec(module_spec)
module_spec.loader.exec_module(renderer)
material = _build_material(bpy, floor.data.materials[1], 'floor_dry', floor_spec, renderer)
for node in material.node_tree.nodes:
if node.type == 'NORMAL_MAP':
# The floor uses world XY projection and has no tangent UV layer.
node.space = 'WORLD'
if node.type == 'TEX_IMAGE':
assert list(node.image.size) == [2048, 2048]
node.image.pack()
dry_assignments = [r for r in structural['assignments'] if r['object_name'] == floor.name and r['role'] == 'floor_dry']
assert {r['room_id'] for r in dry_assignments} == {'hallway', 'dining', 'master', 'living', 'guest', 'bedroom_3'}
new_signature = material_record(material)['signature_sha256']
for row in dry_assignments:
index = row['material_slot_index']
assert floor.data.materials[index].name == row['material_name']
floor.data.materials[index] = material
row.update(material_id=floor_spec['material_id'], family_id=floor_spec['family_id'],
material_name=material.name, texture_scale_m=[1.8, 1.8], material_signature_sha256=new_signature)
structural['showhome_parent_floor_spec'] = structural['roles']['floor_dry']
structural['roles']['floor_dry'] = floor_spec
for row in structural['usage_choices']:
if row['surface_role'] == 'floor_dry':
row.update(asset_id='structural_material:floor_dry:' + floor_spec['asset_id'],
family_id=floor_spec['family_id'], source_content_identity='material_signature_sha256:' + new_signature)
structural['assignment_fingerprint'] = json_fingerprint(structural['assignments'])
wall_objects = [o for o in bpy.context.scene.objects if o.type == 'MESH' and o.name.startswith('wall__')]
wall_tree = tree_for(wall_objects)
additions, installations, moved = [], [], []
for spec in plan['replace'] + plan['add']:
eid = spec['id']
if eid in replaced:
for obj in list(bpy.context.scene.objects):
if obj.get('entity_id') == eid:
bpy.data.objects.remove(obj, do_unlink=True)
manifest['entities'] = [e for e in manifest['entities'] if e['entity_id'] != eid]
else:
assert eid not in entities
group = import_asset(spec['source'], eid, {}, sources=sources)
native_box = mesh_bounds(group)
support = spec.get('support')
if spec.get('wall_mount'):
rotation = Matrix.Rotation(math.pi / 2, 4, 'Z') @ Matrix.Rotation(math.pi / 2, 4, 'X')
for obj in group:
obj.matrix_world = rotation @ obj.matrix_world
bpy.context.view_layer.update()
box = mesh_bounds(group)
height = box[1][2] - box[0][2]
hit, normal, _, _ = wall_tree.ray_cast(Vector((*spec['xy'], spec['bottom_z'] + height / 2)), Vector((-1, 0, 0)), 1.)
assert hit is not None and normal.x > .8, ('Missing west wall', eid)
xy = [hit.x + .004 + (box[1][0] - box[0][0]) / 2, spec['xy'][1]]
box = place_bottom_center(group, xy, spec['bottom_z'])
mount = dict(kind='wall', wall_x=hit.x, gap_m=.004)
elif 'ceiling_z' in spec:
extension = spec['cord_extension_m']
for obj in group:
bounds = mesh_bounds([obj])
is_cord = bounds[1][0] - bounds[0][0] < .01 and bounds[1][2] - bounds[0][2] > .5
if is_cord:
top, bottom = bounds[1][2], bounds[0][2]
for vertex in obj.data.vertices:
vertex.co.z -= extension * (top - vertex.co.z) / (top - bottom)
else:
assert all(not (min(obj.data.vertices[i].co.z for i in p.vertices) < -.5 < max(obj.data.vertices[i].co.z for i in p.vertices)) for p in obj.data.polygons)
for vertex in obj.data.vertices:
if vertex.co.z < -.5:
vertex.co.z -= extension
box = mesh_bounds(group)
box = place_bottom_center(group, spec['xy'], spec['ceiling_z'] - (box[1][2] - box[0][2]))
mount = dict(kind='ceiling', ceiling_z=spec['ceiling_z'], cord_extension_m=extension)
else:
z = support_height(support, spec['xy'], spec['level_hint'])
box = place_bottom_center(group, spec['xy'], z + .0015, spec.get('yaw', 0))
mount = dict(kind='surface', support=support, surface_z=z)
path = sources[spec['source']]
row = dict(entity_id=eid, asset_id='hssd:objects/' + path.stem[0] + '/' + path.stem,
name=spec['name'], category=spec['category'], role=spec['category'], room_id=spec['room'],
canonical_path=str(path), runtime_path=str(path), asset_sha256=digest(path), runtime_sha256=digest(path),
world_bbox_m=box, center_xy_m=[sum(box[j][i] for j in (0, 1)) / 2 for i in (0, 1)],
base_z_m=box[0][2], dimensions_m=[box[1][i] - box[0][i] for i in range(3)],
uniform_scale=1., source_mesh_object_names=[o.name for o in group],
supported_by_entity_id=support, showhome_installation=mount, native_bounds_m=native_box)
for obj in group:
obj['category'], obj['role'], obj['room_id'] = spec['category'], spec['category'], spec['room']
manifest['entities'].append(row)
entities[eid] = row
installations.append(row)
if eid not in replaced:
additions.append(eid)
print('PLACED', eid, box, mount, flush=True)
for eid in plan['move']:
row = entities[eid]
box = mesh_bounds(meshes(eid))
xy = [sum(box[j][i] for j in (0, 1)) / 2 for i in (0, 1)]
z = support_height('dining_table', xy, .76)
box = place_bottom_center(meshes(eid), xy, z + .0015)
row.update(world_bbox_m=box, base_z_m=box[0][2],
showhome_installation=dict(kind='surface', support='dining_table', surface_z=z))
moved.append(eid)
pendant = entities['dining__table_pendant__01']
bpy.ops.object.light_add(type='AREA', location=(*pendant['center_xy_m'], pendant['base_z_m'] - .015))
light = bpy.context.object
light.name = 'showhome__dining_pendant_light'
light.data.energy, light.data.shape, light.data.size = 35., 'DISK', .25
light.data.color = (1., .84, .68)
target_ids = [r['entity_id'] for r in installations] + moved
support_checks = []
retained_names = {s.material.name for o in bpy.context.scene.objects for s in o.material_slots if s.material}
retired_materials = sorted(set(original_materials) - retained_names)
original_materials = {name: value for name, value in original_materials.items() if name in retained_names}
def verify():
bpy.context.view_layer.update()
assert all(name in bpy.data.objects and fingerprint(bpy.data.objects[name]) == h for name, h in protected.items()), 'Unrelated object changed'
assert all(material_record(bpy.data.materials[name])['signature_sha256'] == h for name, h in original_materials.items()), 'Existing material changed'
assert original_entities == [e for e in manifest['entities'] if e['entity_id'] not in changed | set(additions)]
floor_now = bpy.data.objects['floor__whole_house']
assert geometry_signature(floor_now) == floor_geometry
for i in (0, 2, 4, 8):
assert floor_now.data.materials[i].name == floor_slots[i], ('Wet floor or slab material changed', i)
for row in dry_assignments:
assert material_record(floor_now.data.materials[row['material_slot_index']])['signature_sha256'] == new_signature
groups = {}
for obj in bpy.context.scene.objects:
if obj.type == 'MESH' and not obj.hide_render:
groups.setdefault(obj.get('entity_id', 'structure:' + obj.name), []).append(obj)
boxes = {k: mesh_bounds(v) for k, v in groups.items()}
trees = {}
def tree(eid):
if eid not in trees:
trees[eid] = tree_for(groups[eid])
return trees[eid]
def overlaps(a, b):
return all(min(a[1][i], b[1][i]) - max(a[0][i], b[0][i]) > 1e-5 for i in range(3))
support_checks.clear()
for eid in target_ids:
row, box = entities[eid], boxes[eid]
assert max(abs(box[j][i] - row['world_bbox_m'][j][i]) for j in (0, 1) for i in range(3)) < 1e-5
mount = row['showhome_installation']
gaps = []
if mount['kind'] == 'surface':
sid, z = mount['support'], mount['surface_z']
for u in (.05, .5, .95):
for v in (.05, .5, .95):
x, y = [box[0][i] + t * (box[1][i] - box[0][i]) for i, t in enumerate((u, v))]
hit, normal, _, _ = tree(sid).ray_cast(Vector((x, y, z + .02)), Vector((0, 0, -1)), .04)
assert hit is not None and normal.z > .7, ('Unsupported footprint', eid, x, y)
gap = box[0][2] - hit.z
assert 0 <= gap <= .004, ('Support gap', eid, gap)
gaps.append(gap)
elif mount['kind'] == 'wall':
for u in (.05, .5, .95):
for v in (.05, .5, .95):
y, z = [box[0][i] + t * (box[1][i] - box[0][i]) for i, t in zip((1, 2), (u, v))]
hit, normal, _, _ = wall_tree.ray_cast(Vector((box[0][0], y, z)), Vector((-1, 0, 0)), .03)
assert hit is not None and normal.x > .8, ('Missing wall mounting face', eid)
gaps.append(box[0][0] - hit.x)
else:
assert abs(box[1][2] - mount['ceiling_z']) < 1e-5
assert box[0][2] - boxes['dining_table'][1][2] > .75
support_checks.append(dict(entity_id=eid, kind=mount['kind'], gaps_m=gaps))
for other, other_box in boxes.items():
if other != eid and overlaps(box, other_box):
assert not tree(eid).overlap(tree(other)), ('Geometry intersection', eid, other)
for obj in groups[eid]:
assert all(abs(s - 1.) < 1e-5 for s in obj.matrix_world.to_scale()), ('Unexpected scale', eid)
for slot in obj.material_slots:
for image in material_record(slot.material)['images']:
assert all(image['size']) and (image['packed'] or Path(image['path']).is_file()), ('Missing texture', eid, image)
corridor = plan['balcony_clear_corridor']
vertices = [Vector((x, y, z)) for z in (corridor[0][2], corridor[1][2]) for y in (corridor[0][1], corridor[1][1]) for x in (corridor[0][0], corridor[1][0])]
corridor_tree = BVHTree.FromPolygons(vertices, [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)])
for eid, box in boxes.items():
if overlaps(corridor, box):
contained = all(corridor[0][i] <= box[0][i] <= box[1][i] <= corridor[1][i] for i in range(3))
assert not contained and not corridor_tree.overlap(tree(eid)), ('Blocked balcony corridor', eid)
plates = [entities[e] for e in moved if entities[e]['category'] == 'dinner_plate']
assert len(plates) == 4 and len({e['paired_chair_entity_id'] for e in plates}) == 4
root = bpy.data.objects['refrigerator__assembly']
hinge = bpy.data.objects['refrigerator__door_hinge']
original_angle = root['open_angle_deg']
door = [o for o in groups['refrigerator'] if 'fridge_door' in o.get('source_mesh_name', '')]
for angle in (0, 30, 70, 90):
root['open_angle_deg'] = float(angle)
root.update_tag()
bpy.context.view_layer.update()
assert abs(math.degrees(hinge.rotation_euler.z) - angle) < 1e-4
box = mesh_bounds(door)
for eid in target_ids:
if overlaps(box, boxes[eid]):
assert not tree_for(door).overlap(tree(eid)), ('Fridge door collision', angle, eid)
root['open_angle_deg'] = original_angle
root.update_tag()
bpy.context.view_layer.update()
assert all(fingerprint(bpy.data.objects[name]) == h for name, h in protected.items())
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))
wall_tree = tree_for([o for o in bpy.context.scene.objects if o.type == 'MESH' and o.name.startswith('wall__')])
verify()
assert snapshot(args.scene) == before_files
sp = args.output / 'structural_material_manifest.json'
sp.write_text(json.dumps(structural, ensure_ascii=False, indent=2) + '\n')
manifest['structural_material_manifest'] = dict(path=sp.name, sha256=digest(sp))
result = dict(schema='rhg.showhome-enrichment.v1', passed=True, source_scene_unchanged=True,
saved_reopen_passed=True, parent_blend_sha256=digest(source), parent_manifest_sha256=digest(mp),
protected_object_count=len(protected), existing_materials_preserved=True,
retired_unused_material_names=retired_materials,
original_floor_geometry_preserved=True, wet_floor_slots_preserved=[2, 4, 8],
floor_material=floor_spec, floor_rooms=[r['room_id'] for r in dry_assignments],
replaced=replaced, added=additions, moved=moved, support_checks=support_checks,
balcony_clear_corridor_m=plan['balcony_clear_corridor'], balcony_clear_width_m=.9,
triangle_intersections_checked=True, four_dining_places_preserved=True,
refrigerator_angles_checked=[0, 30, 70, 90], physics_simulation_tested=False,
plan_sha256=digest(args.tree / 'showhome_plan.json'), sources_sha256=digest(args.sources))
manifest['showhome_revision'] = copy.deepcopy(result)
manifest_path = args.output / 'composition_manifest.runtime.json'
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
result.update(source_blend_sha256=digest(out), source_manifest_sha256=digest(manifest_path))
for name in ('showhome_receipt.json', 'home_revision_receipt.json'):
(args.output / name).write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
print(json.dumps(dict(passed=True, output=str(out), added=len(additions), replaced=len(replaced), protected=len(protected))), flush=True)
if __name__ == '__main__':
main()
|