File size: 21,678 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
"""Apply the current-scene-only style and exterior-shell revision.

The source scene remains untouched.  This patch keeps the existing window glass
and structure, moves scenic imagery to four exterior vertical cards, and makes
the requested furniture, balcony cabinet, curtain, and plant changes in a
separate saved scene.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import shutil
import sys
from pathlib import Path

import bpy
from mathutils import Matrix, Vector


def parse_args():
    argv = sys.argv
    args = argv[argv.index("--") + 1:] if "--" in argv else []
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True)
    parser.add_argument("--render", action="store_true")
    return parser.parse_args(args)


def world_bounds(objects):
    points = [obj.matrix_world @ v.co for obj in objects if obj.type == "MESH" for v in obj.data.vertices]
    if not points:
        raise ValueError("empty mesh group")
    return [[min(p[i] for p in points) for i in range(3)],
            [max(p[i] for p in points) for i in range(3)]]


def group(entity_id):
    return [obj for obj in bpy.context.scene.objects if obj.get("entity_id") == entity_id]


def group_roots(entity_id):
    members = set(group(entity_id))
    return [obj for obj in members if obj.parent not in members]


def group_bounds(entity_id):
    return world_bounds(group(entity_id))


def translate_group(entity_id, delta):
    transform = Matrix.Translation(Vector(delta))
    for obj in group_roots(entity_id):
        obj.matrix_world = transform @ obj.matrix_world
    bpy.context.view_layer.update()


def scale_group_axis(entity_id, axis, pivot, factor):
    scale = Matrix.Identity(4)
    scale[axis][axis] = factor
    to_pivot = Matrix.Translation(Vector(pivot))
    from_pivot = Matrix.Translation(Vector((-pivot[0], -pivot[1], -pivot[2])))
    transform = to_pivot @ scale @ from_pivot
    for obj in group_roots(entity_id):
        obj.matrix_world = transform @ obj.matrix_world
    bpy.context.view_layer.update()


def make_principled(name, color, roughness=0.7, metallic=0.0):
    mat = bpy.data.materials.get(name)
    if mat is None:
        mat = bpy.data.materials.new(name)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    nodes.clear()
    output = nodes.new("ShaderNodeOutputMaterial")
    shader = nodes.new("ShaderNodeBsdfPrincipled")
    shader.inputs["Base Color"].default_value = (*color, 1.0)
    shader.inputs["Roughness"].default_value = roughness
    shader.inputs["Metallic"].default_value = metallic
    if shader.inputs.get("Specular IOR Level"):
        shader.inputs["Specular IOR Level"].default_value = 0.22
    links.new(shader.outputs["BSDF"], output.inputs["Surface"])
    mat.diffuse_color = (*color, 1.0)
    return mat


def copy_wood_material():
    source = (bpy.data.materials.get("RHG_Selected_floor_dry_ambientcg_WoodFloor052")
              or bpy.data.materials.get("Wood_walnut") or bpy.data.materials.get("Walnutd"))
    if source is None:
        return make_principled("RHG_balcony_cabinet_oak_veneer", (0.38, 0.20, 0.09), 0.62)
    mat = source.copy()
    mat.name = "RHG_balcony_cabinet_oak_veneer"
    mat.diffuse_color = (0.72, 0.56, 0.36, 1.0)
    for node in mat.node_tree.nodes:
        if node.type == "MAPPING":
            node.inputs["Scale"].default_value = (1.35, 1.35, 1.35)
    return mat


def assign_slots(objects, material, predicate=None):
    changed = []
    for obj in objects:
        if obj.type != "MESH":
            continue
        for slot in obj.material_slots:
            if predicate is None or predicate(slot.material):
                old = slot.material.name if slot.material else None
                slot.material = material
                changed.append((obj.name, old, material.name))
    return changed


def material_by_name(name):
    return bpy.data.materials.get(name)


def apply_curtains():
    source = material_by_name("window_sheer__white_translucent")
    if source is None:
        raise ValueError("window_sheer__white_translucent is missing")
    mat = source.copy()
    mat.name = "RHG_curtain_warm_taupe_nonwhite"
    mat.diffuse_color = (0.27, 0.23, 0.19, 0.72)
    if mat.use_nodes:
        for node in mat.node_tree.nodes:
            if node.type == "BSDF_PRINCIPLED":
                node.inputs["Base Color"].default_value = (0.27, 0.23, 0.19, 1.0)
                node.inputs["Roughness"].default_value = 0.78
                if node.inputs.get("Alpha"):
                    node.inputs["Alpha"].default_value = 0.72
                if node.inputs.get("Transmission Weight"):
                    node.inputs["Transmission Weight"].default_value = 0.04
    changed = []
    for obj in bpy.context.scene.objects:
        text = (obj.name + " " + str(dict(obj.items()))).lower()
        if obj.type != "MESH":
            continue
        if obj.get("kind") == "curtain_track" or obj.get("role") == "window_sheer" or "curtain_asset" in text:
            for slot in obj.material_slots:
                old = slot.material.name if slot.material else None
                slot.material = mat
                changed.append((obj.name, old, mat.name))
    return {"material": mat.name, "source_material": source.name, "changed_slots": changed}


def apply_living_style():
    sofa_mat = make_principled("RHG_living_sofa_warm_ivory_fabric", (0.72, 0.68, 0.59), 0.86)
    coffee_mat = make_principled("RHG_living_coffee_table_charcoal_taupe", (0.075, 0.064, 0.052), 0.34)
    sofa_changed = assign_slots(group("sofa"), sofa_mat,
                                 lambda material: material is None or material.name != "unicolor_black")
    coffee_changed = assign_slots(group("coffee_table"), coffee_mat)
    bevels = []
    for obj in group("coffee_table"):
        if obj.type != "MESH":
            continue
        if not any(mod.type == "BEVEL" for mod in obj.modifiers):
            mod = obj.modifiers.new("rounded_reference_coffee_table_edges", "BEVEL")
            mod.width = 0.045
            mod.segments = 5
            mod.limit_method = "ANGLE"
            bevels.append(obj.name)
    art_scale = []
    for eid in ("living__wall_art__01", "living__wall_art__02"):
        for obj in group(eid):
            if obj.type == "MESH":
                obj.scale = obj.scale * 1.18
                art_scale.append(obj.name)
    return {
        "sofa_material": sofa_mat.name,
        "sofa_changed_slots": sofa_changed,
        "coffee_table_material": coffee_mat.name,
        "coffee_table_changed_slots": coffee_changed,
        "coffee_table_bevel_objects": bevels,
        "living_wall_art_scale_factor": 1.18,
        "living_wall_art_objects": art_scale,
    }


def apply_balcony_cabinets():
    ids = ("balcony__laundry_sink__01", "balcony__washer_dryer__01",
           "balcony__laundry_tall_cabinet__01", "balcony__laundry_upper__01",
           "balcony__laundry_upper__02")
    if not all(group(eid) for eid in ids):
        raise ValueError("balcony laundry group is incomplete")
    before = {eid: group_bounds(eid) for eid in ids}
    wood = copy_wood_material()
    # Make the cabinet fronts share one depth plane while keeping their rear
    # edge against the existing west wall.
    cabinet_front = 8.975
    for eid in ids:
        bb = group_bounds(eid)
        if bb[1][0] < cabinet_front - 0.002:
            scale_group_axis(eid, 0, [bb[0][0], 0.0, 0.0],
                             (cabinet_front - bb[0][0]) / max(1e-6, bb[1][0] - bb[0][0]))
        translate_group(eid, [-0.005, 0.0, 0.0])
    # Close the measured run gaps along the balcony wall.
    sink_max_y = group_bounds("balcony__laundry_sink__01")[1][1]
    washer_min_y = group_bounds("balcony__washer_dryer__01")[0][1]
    translate_group("balcony__washer_dryer__01", [0.0, sink_max_y - washer_min_y, 0.0])
    washer_max_y = group_bounds("balcony__washer_dryer__01")[1][1]
    tall_min_y = group_bounds("balcony__laundry_tall_cabinet__01")[0][1]
    translate_group("balcony__laundry_tall_cabinet__01", [0.0, washer_max_y - tall_min_y, 0.0])
    upper1_max_y = group_bounds("balcony__laundry_upper__01")[1][1]
    upper2_min_y = group_bounds("balcony__laundry_upper__02")[0][1]
    translate_group("balcony__laundry_upper__02", [0.0, upper1_max_y - upper2_min_y, 0.0])
    upper2 = group_bounds("balcony__laundry_upper__02")
    target_upper2_max = washer_max_y
    if upper2[1][1] < target_upper2_max - 0.002:
        scale_group_axis("balcony__laundry_upper__02", 1, [0.0, upper2[0][1], 0.0],
                         (target_upper2_max - upper2[0][1]) / max(1e-6, upper2[1][1] - upper2[0][1]))
    # Only the sink's lower cabinet material is changed; basin and faucet
    # retain their existing ceramic and chrome materials.
    assign_slots(group("balcony__laundry_tall_cabinet__01"), wood)
    assign_slots(group("balcony__laundry_upper__01"), wood)
    assign_slots(group("balcony__laundry_upper__02"), wood)
    assign_slots(group("balcony__laundry_sink__01"), wood,
                 lambda material: material is not None and material.name.startswith("Shader3"))
    # Re-read and normalize the final world-space rear/front planes after all
    # asset transforms. This removes transform-order drift from imported GLBs.
    target_rear = 8.295
    target_front = cabinet_front - 0.005
    target_depth = target_front - target_rear
    for eid in ids:
        bb = group_bounds(eid)
        current_depth = bb[1][0] - bb[0][0]
        if abs(current_depth - target_depth) > 1e-4:
            scale_group_axis(eid, 0, [bb[0][0], 0.0, 0.0], target_depth / max(1e-6, current_depth))
        bb = group_bounds(eid)
        translate_group(eid, [target_rear - bb[0][0], 0.0, 0.0])
    # Final run alignment is based on the saved world bounds, not source asset
    # transforms, so every adjacent cabinet edge meets exactly.
    sink_max_y = group_bounds("balcony__laundry_sink__01")[1][1]
    translate_group("balcony__washer_dryer__01", [0.0, sink_max_y - group_bounds("balcony__washer_dryer__01")[0][1], 0.0])
    washer_max_y = group_bounds("balcony__washer_dryer__01")[1][1]
    translate_group("balcony__laundry_tall_cabinet__01", [0.0, washer_max_y - group_bounds("balcony__laundry_tall_cabinet__01")[0][1], 0.0])
    upper1_max_y = group_bounds("balcony__laundry_upper__01")[1][1]
    translate_group("balcony__laundry_upper__02", [0.0, upper1_max_y - group_bounds("balcony__laundry_upper__02")[0][1], 0.0])
    after = {eid: group_bounds(eid) for eid in ids}
    return {
        "wood_material": wood.name,
        "before_bounds": before,
        "after_bounds": after,
        "front_plane_x_m": cabinet_front - 0.005,
        "wall_inner_x_m": 8.29,
        "run_gap_policy": "zero_gap_measured_world_bounds",
        "cabinet_material_scope": "upper_tall_and_sink_lower_cabinet_only",
    }


def duplicate_high_fidelity_plant(source_eid, target_eid, target_height):
    source_objs = group(source_eid)
    old_objs = group(target_eid)
    if not source_objs or not old_objs:
        raise ValueError(f"plant groups missing: {source_eid}, {target_eid}")
    source_bb = world_bounds(source_objs)
    old_bb = world_bounds(old_objs)
    source_height = source_bb[1][2] - source_bb[0][2]
    target_center = Vector(((old_bb[0][0] + old_bb[1][0]) / 2,
                            (old_bb[0][1] + old_bb[1][1]) / 2,
                            target_height / 2))
    source_center = Vector(((source_bb[0][0] + source_bb[1][0]) / 2,
                            (source_bb[0][1] + source_bb[1][1]) / 2,
                            (source_bb[0][2] + source_bb[1][2]) / 2))
    factor = target_height / max(1e-6, source_height)
    transform = Matrix.Translation(target_center) @ Matrix.Scale(factor, 4) @ Matrix.Translation(-source_center)
    new_objects = []
    for old in old_objs:
        old.hide_render = True
        old.hide_viewport = True
    for src in source_objs:
        new = src.copy()
        if src.data:
            new.data = src.data.copy()
        bpy.context.scene.collection.objects.link(new)
        new.parent = None
        new.matrix_world = transform @ src.matrix_world
        new.name = f"{target_eid}__high_fidelity__{src.name}"
        new["entity_id"] = target_eid
        new["role"] = "high_fidelity_greenery"
        new["category"] = "plant"
        new["asset_id"] = src.get("asset_id") or "hssd:objects/7/7c8c31b60d695dee8aa102f34cba9b2070167a48"
        new["asset_source"] = src.get("asset_source") or "asset_library:hssd_restored/sansevieria"
        new["high_fidelity_asset"] = True
        new["replaced_entity_id"] = target_eid
        new_objects.append(new)
    bpy.context.view_layer.update()
    return {"target_entity_id": target_eid, "source_entity_id": source_eid,
            "target_height_m": target_height, "factor": factor,
            "old_objects_hidden": [obj.name for obj in old_objs],
            "new_objects": [obj.name for obj in new_objects],
            "new_bounds": world_bounds(new_objects)}


def apply_plants():
    return [
        duplicate_high_fidelity_plant("bedroom_3__marked_greenery__01", "living__greenery__01", 0.85),
        duplicate_high_fidelity_plant("bedroom_3__marked_greenery__01", "balcony__outdoor_greenery__01", 0.65),
    ]


def image_material(name, image):
    mat = bpy.data.materials.get(name) or bpy.data.materials.new(name)
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    nodes.clear()
    output = nodes.new("ShaderNodeOutputMaterial")
    shader = nodes.new("ShaderNodeBsdfPrincipled")
    texture = nodes.new("ShaderNodeTexImage")
    texture.image = image
    shader.inputs["Roughness"].default_value = 0.82
    if shader.inputs.get("Specular IOR Level"):
        shader.inputs["Specular IOR Level"].default_value = 0.08
    links.new(texture.outputs["Color"], shader.inputs["Base Color"])
    links.new(shader.outputs["BSDF"], output.inputs["Surface"])
    return mat


def make_vertical_face(name, axis, coordinate, u0, u1, z0, z1, material, image_name):
    if axis == "y":
        vertices = [(u0, coordinate, z0), (u1, coordinate, z0),
                    (u1, coordinate, z1), (u0, coordinate, z1)]
    else:
        vertices = [(coordinate, u0, z0), (coordinate, u1, z0),
                    (coordinate, u1, z1), (coordinate, u0, z1)]
    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(vertices, [], [(0, 1, 2, 3)])
    mesh.update()
    uv = mesh.uv_layers.new(name="UVMap")
    for loop, uv_coord in zip(mesh.polygons[0].loop_indices, ((0, 0), (1, 0), (1, 1), (0, 1))):
        uv.data[loop].uv = uv_coord
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(obj)
    obj.data.materials.append(material)
    obj["delivery_visual_only"] = True
    obj["presentation_only"] = False
    obj["exterior_shell_hdr_face"] = axis + ("+" if coordinate >= 0 else "-")
    obj["collision_enabled"] = False
    obj["scope"] = "vertical_shell_exterior_backdrop_outside_window_glass"
    obj["asset_image"] = image_name
    return obj


def apply_exterior_shell_faces():
    removed = []
    for obj in list(bpy.context.scene.objects):
        if obj.get("delivery_visual_only") and obj.get("delivery_window_id"):
            removed.append(obj.name)
            bpy.data.objects.remove(obj, do_unlink=True)
    floor = bpy.data.objects.get("floor__whole_house")
    if floor is None:
        raise ValueError("floor__whole_house missing")
    floor_bb = world_bounds([floor])
    min_x, min_y = floor_bb[0][0], floor_bb[0][1]
    max_x, max_y = floor_bb[1][0], floor_bb[1][1]
    z0, z1, offset, margin = 0.04, 3.20, 0.42, 0.55
    images = {img.name: img for img in bpy.data.images}
    chosen = {
        "north": images.get("green_point_park_central.png"),
        "south": images.get("green_point_park_west.png"),
        "east": images.get("green_point_park_east.png"),
        "west": images.get("green_point_park_west.png"),
    }
    if not all(chosen.values()):
        raise ValueError("packed window scenery images are missing")
    faces = []
    specs = [
        ("north", "y", max_y + offset, min_x - margin, max_x + margin),
        ("south", "y", min_y - offset, min_x - margin, max_x + margin),
        ("east", "x", max_x + offset, min_y - margin, max_y + margin),
        ("west", "x", min_x - offset, min_y - margin, max_y + margin),
    ]
    for label, axis, coordinate, u0, u1 in specs:
        image = chosen[label]
        material = image_material("RHG_exterior_shell_hdr_face_" + label, image)
        faces.append(make_vertical_face("exterior_shell_hdr_face_" + label, axis, coordinate,
                                         u0, u1, z0, z1, material, image.name))
    return {"removed_window_backdrops": removed,
            "faces": [{"name": obj.name, "bounds": world_bounds([obj]),
                       "image": obj.get("asset_image"), "scope": obj.get("scope")} for obj in faces],
            "shell_bounds": floor_bb, "offset_m": offset, "height_m": z1 - z0}


def render_review(output_dir):
    scene = bpy.context.scene
    try:
        scene.render.engine = "BLENDER_EEVEE_NEXT"
    except TypeError:
        scene.render.engine = "BLENDER_EEVEE"
    scene.render.resolution_x = 640
    scene.render.resolution_y = 480
    scene.render.resolution_percentage = 100
    scene.render.image_settings.file_format = "PNG"
    scene.render.film_transparent = False
    if hasattr(scene, "eevee"):
        scene.eevee.taa_render_samples = 32
    def render_one(name, location, target):
        camera_data = bpy.data.cameras.new("style_review_camera_" + name)
        camera = bpy.data.objects.new("style_review_camera_" + name, camera_data)
        scene.collection.objects.link(camera)
        camera.location = Vector(location)
        camera.rotation_euler = (Vector(target) - camera.location).to_track_quat("-Z", "Y").to_euler()
        camera_data.type = "PERSP"
        camera_data.lens = 31
        scene.camera = camera
        path = Path(output_dir) / ("review_" + name + ".png")
        scene.render.filepath = str(path)
        bpy.ops.render.render(write_still=True)
        return str(path)
    results = {
        "living": render_one("living", (12.55, 7.15, 1.65), (11.0, 9.35, 0.9)),
        "balcony": render_one("balcony", (10.8, 12.5, 2.05), (9.2, 12.9, 1.25)),
    }
    temporary_hidden = [obj for obj in bpy.context.scene.objects
                        if obj.get("exterior_shell_hdr_face")
                        or obj.get("geometry_role") == "full_house_top_plate"]
    states = {obj.name: obj.hide_render for obj in temporary_hidden}
    for obj in temporary_hidden:
        obj.hide_render = True
    results["overview"] = render_one("overview", (6.5, 7.0, 12.0), (6.5, 7.0, 0.25))
    for obj in temporary_hidden:
        obj.hide_render = states[obj.name]
    return results


def sha256(path):
    digest = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def main():
    args = parse_args()
    output_dir = Path(args.output)
    output_dir.mkdir(parents=True, exist_ok=True)
    source_blend = Path(bpy.data.filepath)
    curtain = apply_curtains()
    exterior = apply_exterior_shell_faces()
    sofa = apply_living_style()
    cabinets = apply_balcony_cabinets()
    plants = apply_plants()
    bpy.context.scene["rhg_current_scene_style_revision"] = "current-scene-only-v2"
    bpy.context.scene["rhg_exterior_shell_faces"] = json.dumps(exterior, ensure_ascii=False)
    bpy.context.scene["rhg_curtain_revision"] = json.dumps(curtain, ensure_ascii=False)
    bpy.context.scene["rhg_balcony_cabinet_revision"] = json.dumps(cabinets, ensure_ascii=False)
    bpy.context.scene["rhg_high_fidelity_plants"] = json.dumps(plants, ensure_ascii=False)
    blend_path = output_dir / source_blend.name
    bpy.ops.wm.save_as_mainfile(filepath=str(blend_path))
    render_results = render_review(output_dir) if args.render else {}
    bpy.ops.wm.save_as_mainfile(filepath=str(blend_path))
    receipt = {
        "schema": "rhg.current-scene-style-window-shell.v2",
        "passed": True,
        "scope": "current_scene_only",
        "source_blend": str(source_blend),
        "source_blend_sha256": sha256(source_blend) if source_blend.exists() else None,
        "output_blend": str(blend_path),
        "output_blend_sha256": sha256(blend_path),
        "changes": {"curtains": curtain, "exterior_shell_faces": exterior,
                     "living_style": sofa, "balcony_cabinets": cabinets,
                     "high_fidelity_plants": plants},
        "render_review": render_results,
    }
    (output_dir / "current_scene_style_receipt.json").write_text(json.dumps(receipt, ensure_ascii=False, indent=2), encoding="utf-8")
    source_manifest = source_blend.parent / "composition_manifest.runtime.json"
    if source_manifest.exists():
        manifest = json.loads(source_manifest.read_text(encoding="utf-8"))
        manifest["current_scene_style_revision"] = receipt
        (output_dir / "composition_manifest.runtime.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
    for name in ("home_revision_receipt.json", "balcony_floor_receipt.json", "structural_material_manifest.json"):
        source = source_blend.parent / name
        if source.exists():
            shutil.copy2(source, output_dir / name)
    print(json.dumps(receipt, ensure_ascii=False))


if __name__ == "__main__":
    main()