File size: 26,848 Bytes
812a0b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
#!/usr/bin/env python3
"""
批量渲染 IDesign 生成的场景 - 使用 bpy 直接渲染
需要在 blender conda 环境下运行: conda activate blender

高质量渲染设置:与 InternScenes 项目的 blender 渲染器对齐
"""

import bpy
import json
import math
import os
import sys
from pathlib import Path
from datetime import datetime
from mathutils import Vector

try:
    from PIL import Image
    HAS_PIL = True
except ImportError:
    HAS_PIL = False


# ============================================================================
# 渲染参数配置(与 InternScenes 对齐)
# ============================================================================
RENDER_CONFIG = {
    # 分辨率
    "width": 1600,
    "height": 900,
    # 渲染引擎设置
    "engine": "CYCLES",
    "samples": 256,
    "exposure": 0.0,
    # 相机设置
    "camera_lens": 35.0,  # mm
    "camera_clip_start": 0.01,
    "camera_clip_end": 1000.0,
    # 视角模式:diagonal, diagonal2, diagonal3, diagonal4, topdown, side_front, side_back, side_left, side_right
    "view_mode": "diagonal",
    "diagonal_distance": 2.2,  # 增大距离,拉远相机
    "diagonal_height_offset": 0.1,  # 稍微降低视角
    "topdown_height": 1.5,
    "topdown_scale": 1.0,
    # 灯光设置
    "sun_intensity": 3.5,
    "sun_color": (1.0, 0.98, 0.94),  # 暖色调
    "ambient_intensity": 1.0,
    "use_fill_lights": True,
    "fill_intensity": 0.5,
    # 背景设置
    "background": (1.0, 1.0, 1.0, 1.0),
    "use_transparent_background": True,
    # 后处理
    "auto_crop": True,
    "crop_padding": 10,
}

# 清除默认 Cube
def clear_default_cube():
    obj = bpy.data.objects.get('Cube')
    if obj:
        bpy.data.objects.remove(obj, do_unlink=True)

def clear_scene():
    """完全清空场景"""
    bpy.ops.object.select_all(action='SELECT')
    bpy.ops.object.delete()
    
    # 清除所有 mesh 数据
    for mesh in bpy.data.meshes:
        bpy.data.meshes.remove(mesh)
    for material in bpy.data.materials:
        bpy.data.materials.remove(material)

def import_glb(file_path, object_name):
    """导入 GLB 文件"""
    try:
        bpy.ops.import_scene.gltf(filepath=file_path)
        imported_object = bpy.context.view_layer.objects.active
        if imported_object is not None:
            imported_object.name = object_name
        return imported_object
    except Exception as e:
        print(f"导入失败 {object_name}: {e}")
        return None

def find_glb_files(directories):
    """在多个目录中查找 GLB 文件"""
    glb_files = {}
    for directory in directories:
        if not os.path.exists(directory):
            continue
        for root, dirs, files in os.walk(directory):
            for file in files:
                if file.endswith(".glb"):
                    key = file.replace(".glb", "")
                    if key not in glb_files:
                        glb_files[key] = os.path.join(root, file)
    return glb_files

def get_highest_parent_objects():
    """获取最高层父对象"""
    return [obj for obj in bpy.data.objects if obj.parent is None]

def select_meshes_under_empty(empty_object_name):
    """递归选择 Empty 下的所有 Mesh"""
    empty_object = bpy.data.objects.get(empty_object_name)
    if empty_object is not None and empty_object.type == 'EMPTY':
        for child in empty_object.children:
            if child.type == 'MESH':
                child.select_set(True)
                bpy.context.view_layer.objects.active = child
            else:
                select_meshes_under_empty(child.name)

def delete_empty_objects():
    """删除所有 Empty 对象"""
    empties = [obj for obj in bpy.context.scene.objects if obj.type == 'EMPTY']
    for obj in empties:
        bpy.data.objects.remove(obj)

def rescale_object(obj, scale):
    """缩放对象到指定尺寸"""
    if obj.type == 'MESH':
        bbox_dimensions = obj.dimensions
        if bbox_dimensions.x > 0 and bbox_dimensions.y > 0 and bbox_dimensions.z > 0:
            scale_factors = (
                scale.get("length", 1) / bbox_dimensions.x,
                scale.get("width", 1) / bbox_dimensions.y,
                scale.get("height", 1) / bbox_dimensions.z
            )
            obj.scale = scale_factors


def ensure_principled_materials(objects):
    """确保所有网格对象有正确的 Principled BSDF 材质(与 InternScenes 渲染器对齐)
    
    增强现有材质的 PBR 参数以获得更好的渲染效果。
    """
    for obj in objects:
        if obj.type != "MESH" or not obj.data.materials:
            continue
        
        for mat_idx, material in enumerate(obj.data.materials):
            if material is None:
                continue
            
            # 跳过地板材质
            if material.name == "FloorMaterial":
                continue
            
            # 启用节点
            material.use_nodes = True
            nodes = material.node_tree.nodes
            
            # 查找或创建 Principled BSDF
            principled = None
            for node in nodes:
                if node.type == "BSDF_PRINCIPLED":
                    principled = node
                    break
            
            if principled is None:
                # 如果没有 Principled BSDF,创建新的着色器设置
                nodes.clear()
                principled = nodes.new(type="ShaderNodeBsdfPrincipled")
                output = nodes.new(type="ShaderNodeOutputMaterial")
                material.node_tree.links.new(principled.outputs["BSDF"], output.inputs["Surface"])
            
            # 增强 PBR 参数
            if "Base Color" in principled.inputs:
                bc = principled.inputs["Base Color"].default_value
                if bc[0] == 0 and bc[1] == 0 and bc[2] == 0:
                    principled.inputs["Base Color"].default_value = (0.8, 0.8, 0.8, 1.0)
            
            if "Roughness" in principled.inputs:
                current_rough = principled.inputs["Roughness"].default_value
                if current_rough < 0.1 or current_rough > 0.99:
                    principled.inputs["Roughness"].default_value = 0.5
            
            if "Metallic" in principled.inputs:
                principled.inputs["Metallic"].default_value = 0.0


def create_room(width, depth, height):
    """创建地板(纯白色材质)"""
    # 只创建地板
    bpy.ops.mesh.primitive_plane_add(size=1, location=(width/2, depth/2, 0))
    floor = bpy.context.active_object
    floor.scale = (width, depth, 1)
    floor.name = "Floor"
    
    # 地板材质:纯白色 Principled BSDF
    mat = bpy.data.materials.new(name="FloorMaterial")
    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    links = mat.node_tree.links
    nodes.clear()
    
    # 创建 Principled BSDF 节点
    bsdf = nodes.new(type="ShaderNodeBsdfPrincipled")
    bsdf.inputs["Base Color"].default_value = (1.0, 1.0, 1.0, 1.0)  # 纯白色
    bsdf.inputs["Roughness"].default_value = 0.35
    bsdf.inputs["Metallic"].default_value = 0.0
    
    # 创建输出节点
    output = nodes.new(type="ShaderNodeOutputMaterial")
    links.new(bsdf.outputs["BSDF"], output.inputs["Surface"])
    
    # 材质设置
    mat.blend_method = "OPAQUE"
    if hasattr(mat, 'shadow_method'):
        mat.shadow_method = "OPAQUE"
    mat.use_backface_culling = False  # 双面渲染
    
    floor.data.materials.append(mat)
    return floor

def setup_camera(width, depth, height, view_mode="diagonal"):
    """设置相机(与 InternScenes 渲染器对齐)
    
    Args:
        width, depth, height: 房间尺寸
        view_mode: 相机视角模式
            - diagonal: 前右角对角线视角
            - diagonal2: 后左角对角线视角  
            - diagonal3: 后右角对角线视角
            - diagonal4: 前左角对角线视角
            - topdown: 俯视图(正交)
            - side_front/side_back/side_left/side_right: 侧视图
    """
    # 计算场景边界
    center = Vector((width/2, depth/2, height/2))
    extent = Vector((width, depth, height))
    radius = extent.length / 2
    
    bpy.ops.object.camera_add()
    camera = bpy.context.active_object
    camera.name = "Camera"
    
    config = RENDER_CONFIG
    diagonal_distance = config.get("diagonal_distance", 1.2)
    diagonal_height_offset = config.get("diagonal_height_offset", 0.15)
    topdown_height = config.get("topdown_height", 1.5)
    topdown_scale = config.get("topdown_scale", 1.0)
    
    if view_mode == "topdown":
        # 正交俯视图
        camera.data.type = "ORTHO"
        camera.data.ortho_scale = radius * topdown_scale
        eye = center + Vector((0.0, 0.0, radius * topdown_height))
        camera.location = eye
        camera.data.lens = 50.0
        # 朝下看
        _look_at(camera, center)
    elif view_mode.startswith("side_"):
        # 侧视图(带仰角)
        camera.data.type = "PERSP"
        camera.data.lens = config.get("camera_lens", 35.0)
        
        elev_rad = math.radians(30.0)  # 30度仰角
        horizontal_dist = math.cos(elev_rad)
        vertical_dist = math.sin(elev_rad)
        
        if view_mode == "side_front":
            horiz_dir = Vector((0.0, 1.0, 0.0))
        elif view_mode == "side_back":
            horiz_dir = Vector((0.0, -1.0, 0.0))
        elif view_mode == "side_left":
            horiz_dir = Vector((-1.0, 0.0, 0.0))
        elif view_mode == "side_right":
            horiz_dir = Vector((1.0, 0.0, 0.0))
        else:
            horiz_dir = Vector((0.0, 1.0, 0.0))
        
        distance = radius * max(1.0, diagonal_distance * 1.5)
        direction = Vector((
            horiz_dir.x * horizontal_dist,
            horiz_dir.y * horizontal_dist,
            vertical_dist
        ))
        direction.normalize()
        
        eye = center + direction * distance
        camera.location = eye
        _look_at(camera, center)
    else:
        # 对角线透视视角(diagonal, diagonal2, diagonal3, diagonal4)
        camera.data.type = "PERSP"
        camera.data.lens = config.get("camera_lens", 35.0)
        
        if view_mode == "diagonal":
            diag_direction = Vector((1.0, 1.0, 1.0))  # 前右角
        elif view_mode == "diagonal2":
            diag_direction = Vector((-1.0, -1.0, 1.0))  # 后左角
        elif view_mode == "diagonal3":
            diag_direction = Vector((1.0, -1.0, 1.0))  # 后右角
        elif view_mode == "diagonal4":
            diag_direction = Vector((-1.0, 1.0, 1.0))  # 前左角
        else:
            diag_direction = Vector((1.0, 1.0, 1.0))
        diag_direction.normalize()
        
        distance = radius * max(1.0, diagonal_distance * 1.5)
        eye = center + diag_direction * distance
        
        look_target = center.copy()
        z_offset = radius * diagonal_height_offset
        eye.z -= z_offset
        look_target.z -= z_offset
        
        camera.location = eye
        _look_at(camera, look_target)
    
    # 相机参数
    camera.data.clip_start = config.get("camera_clip_start", 0.01)
    camera.data.clip_end = config.get("camera_clip_end", radius * 100.0)
    
    bpy.context.scene.camera = camera
    return camera


def _look_at(camera, target):
    """让相机朝向目标点"""
    direction = target - camera.location
    if direction.length < 1e-6:
        direction = Vector((0.0, 0.0, -1.0))
    else:
        direction.normalize()
    quat = direction.to_track_quat("-Z", "Y")
    camera.rotation_euler = quat.to_euler()

def setup_lighting(width, depth, height):
    """设置灯光(与 InternScenes 渲染器对齐)"""
    center = Vector((width/2, depth/2, height/2))
    extent = Vector((width, depth, height))
    radius = extent.length / 2
    
    config = RENDER_CONFIG
    sun_intensity = config.get("sun_intensity", 3.5)
    sun_color = config.get("sun_color", (1.0, 0.98, 0.94))
    use_fill_lights = config.get("use_fill_lights", True)
    fill_intensity = config.get("fill_intensity", 0.5)
    
    # ========== 主光源:太阳光 ==========
    sun_light_data = bpy.data.lights.new("Sun", type="SUN")
    sun = bpy.data.objects.new("Sun", sun_light_data)
    bpy.context.collection.objects.link(sun)
    
    # 太阳光位置和方向:从相机方向偏移
    camera = bpy.context.scene.camera
    if camera:
        view_dir = center - camera.location
        if view_dir.length < 1e-6:
            view_dir = Vector((0.0, 0.0, -1.0))
        else:
            view_dir.normalize()
        sun_dir = view_dir * 0.6 + Vector((0.0, 0.0, -0.8))
        if sun_dir.length < 1e-6:
            sun_dir = Vector((0.0, 0.0, -1.0))
        else:
            sun_dir.normalize()
    else:
        sun_dir = Vector((-0.5, -0.5, -0.8))
        sun_dir.normalize()
    
    sun.location = center + sun_dir * radius * 2.0
    quat = sun_dir.to_track_quat("-Z", "Y")
    sun.rotation_euler = quat.to_euler()
    
    sun.data.energy = max(0.01, sun_intensity)
    sun.data.color = sun_color
    
    # 太阳光柔和阴影
    if hasattr(sun.data, "angle"):
        sun.data.angle = math.radians(1.0)
    
    if not use_fill_lights:
        return
    
    # ========== 填充光:Area Light ==========
    fill_light_data = bpy.data.lights.new("FillLight", type="AREA")
    fill_light = bpy.data.objects.new("FillLight", fill_light_data)
    bpy.context.collection.objects.link(fill_light)
    
    fill_light.location = center + Vector((0.0, -radius * 0.5, radius * 1.5))
    fill_light.rotation_euler = (math.radians(45), 0, 0)
    fill_light_data.energy = fill_intensity * 100
    fill_light_data.color = (1.0, 0.98, 0.95)  # 微暖色
    fill_light_data.size = radius * 2
    
    # ========== 轮廓光:Rim Light ==========
    rim_light_data = bpy.data.lights.new("RimLight", type="AREA")
    rim_light = bpy.data.objects.new("RimLight", rim_light_data)
    bpy.context.collection.objects.link(rim_light)
    
    rim_light.location = center + Vector((radius * 0.5, radius, radius))
    rim_light.rotation_euler = (math.radians(-45), math.radians(30), 0)
    rim_light_data.energy = fill_intensity * 50
    rim_light_data.color = (0.95, 0.97, 1.0)  # 微冷色形成对比
    rim_light_data.size = radius


def setup_world():
    """设置世界/环境(与 InternScenes 渲染器对齐)"""
    scene = bpy.context.scene
    config = RENDER_CONFIG
    background = config.get("background", (1.0, 1.0, 1.0, 1.0))
    ambient_intensity = config.get("ambient_intensity", 1.0)
    use_transparent = config.get("use_transparent_background", True)
    
    # 创建或获取世界
    if scene.world is None:
        scene.world = bpy.data.worlds.new("World")
    world = scene.world
    world.use_nodes = True
    nodes = world.node_tree.nodes
    links = world.node_tree.links
    
    # 清除现有节点
    nodes.clear()
    
    # 创建输出节点
    output_node = nodes.new(type="ShaderNodeOutputWorld")
    output_node.location = (400, 0)
    
    # 简单纯色背景
    background_node = nodes.new(type="ShaderNodeBackground")
    background_node.location = (200, 0)
    background_node.inputs[0].default_value = (
        background[0],
        background[1],
        background[2],
        background[3] if len(background) > 3 else 1.0,
    )
    background_node.inputs[1].default_value = max(0.0, ambient_intensity)
    links.new(background_node.outputs["Background"], output_node.inputs["Surface"])
    
    # 透明背景设置
    scene.render.film_transparent = use_transparent
    scene.render.image_settings.color_mode = "RGBA"

def render_single_scene(scene_dir, output_name="render.png"):
    """渲染单个场景"""
    scene_dir = Path(scene_dir)
    
    # 找场景文件 - 支持 scene_graph.json 或 scene.json
    scene_json = None
    for json_name in ["scene_graph.json", "scene.json"]:
        candidate = scene_dir / json_name
        if candidate.exists():
            scene_json = candidate
            break
    
    if scene_json is None:
        print(f"  ⚠️ scene_graph.json/scene.json 不存在,跳过")
        return False
    
    # 读取场景数据
    with open(scene_json, 'r') as f:
        data = json.load(f)
    
    # 提取物体信息
    objects_in_room = {}
    room_dims = [4, 4, 2.8]  # 默认
    
    for item in data:
        obj_id = item.get("new_object_id", "")
        if obj_id == "middle of the room":
            size = item.get("size_in_meters", {})
            room_dims = [size.get("length", 4), size.get("width", 4), 2.8]
        elif obj_id == "ceiling":
            pos = item.get("position", {})
            room_dims[2] = pos.get("z", 2.8)
        elif obj_id not in ["south_wall", "north_wall", "east_wall", "west_wall"]:
            if item.get("position"):  # 只处理有位置的物体
                objects_in_room[obj_id] = item
    
    if not objects_in_room:
        print(f"  ⚠️ 无有效物体,跳过")
        return False
    
    # 查找 GLB 文件
    glb_dirs = [
        scene_dir / "Assets",
        scene_dir / "assets", 
        scene_dir / "glb",
        scene_dir / "objects"
    ]
    glb_file_paths = find_glb_files([str(d) for d in glb_dirs])
    
    if not glb_file_paths:
        print(f"  ⚠️ 无 GLB 文件,跳过")
        return False
    
    # 清空场景
    clear_scene()
    
    # 导入物体
    for item_id in objects_in_room:
        if item_id in glb_file_paths:
            import_glb(glb_file_paths[item_id], item_id)
    
    # 处理导入的物体:合并 Empty 下的 Mesh
    parents = get_highest_parent_objects()
    empty_parents = [p for p in parents if p.type == "EMPTY"]
    
    for empty_parent in empty_parents:
        bpy.ops.object.select_all(action='DESELECT')
        select_meshes_under_empty(empty_parent.name)
        
        if bpy.context.selected_objects:
            bpy.ops.object.join()
            bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS')
            
            joined_object = bpy.context.view_layer.objects.active
            if joined_object:
                joined_object.name = empty_parent.name + "-joined"
    
    # 清除父子关系,重置变换
    MSH_OBJS = [m for m in bpy.context.scene.objects if m.type == 'MESH']
    for obj in MSH_OBJS:
        bpy.context.view_layer.objects.active = obj
        bpy.ops.object.parent_clear(type='CLEAR_KEEP_TRANSFORM')
        obj.location = (0.0, 0.0, 0.0)
        obj.select_set(True)
        bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
        bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS')
    
    # 设置物体位置和旋转
    loaded_count = 0
    MSH_OBJS = [m for m in bpy.context.scene.objects if m.type == 'MESH']
    for obj in MSH_OBJS:
        # 匹配物体名
        key_variants = [
            obj.name,
            obj.name.replace("-joined", ""),
            obj.name.replace(".001", ""),
            obj.name.replace(".002", ""),
        ]
        key = next((k for k in key_variants if k in objects_in_room), None)
        if key is None:
            continue
        
        item = objects_in_room[key]
        pos = item.get("position", {})
        rot = item.get("rotation", {})
        size = item.get("size_in_meters", {})
        
        # 设置位置
        obj.location = (pos.get("x", 0), pos.get("y", 0), pos.get("z", 0))
        
        # 设置旋转 (z_angle 度数转弧度,加 180 度)
        z_angle = rot.get("z_angle", 0)
        bpy.ops.object.select_all(action='DESELECT')
        obj.select_set(True)
        bpy.ops.transform.rotate(value=(z_angle / 180.0) * math.pi + math.pi, orient_axis='Z')
        
        # 缩放
        if size:
            rescale_object(obj, size)
        
        loaded_count += 1
    
    # 删除 Empty
    delete_empty_objects()
    
    # 增强所有网格对象的材质
    mesh_objects = [m for m in bpy.context.scene.objects if m.type == 'MESH']
    ensure_principled_materials(mesh_objects)
    
    # 创建房间
    create_room(room_dims[0], room_dims[1], room_dims[2])
    
    # 设置世界/环境
    setup_world()
    
    # 设置相机和灯光
    view_mode = RENDER_CONFIG.get("view_mode", "diagonal")
    setup_camera(room_dims[0], room_dims[1], room_dims[2], view_mode)
    setup_lighting(room_dims[0], room_dims[1], room_dims[2])
    
    # 配置渲染设置(与 InternScenes 渲染器对齐)
    configure_render_settings()
    
    # 渲染
    output_path = scene_dir / output_name
    scene = bpy.context.scene
    scene.render.filepath = str(output_path)
    bpy.ops.render.render(write_still=True)
    
    # 自动裁剪透明边距
    if RENDER_CONFIG.get("auto_crop", True) and HAS_PIL:
        auto_crop_image(str(output_path), RENDER_CONFIG.get("crop_padding", 10))
    
    print(f"  ✅ 渲染完成 ({loaded_count} 个物体): {output_path}")
    return True


def configure_render_settings():
    """配置渲染设置(与 InternScenes 渲染器对齐)"""
    scene = bpy.context.scene
    render = scene.render
    config = RENDER_CONFIG
    
    engine = config.get("engine", "CYCLES")
    width = config.get("width", 1600)
    height = config.get("height", 900)
    samples = config.get("samples", 256)
    exposure = config.get("exposure", 0.0)
    
    # 检查可用引擎
    available_engines = {item.identifier for item in render.bl_rna.properties["engine"].enum_items}
    target_engine = engine
    if target_engine not in available_engines:
        if target_engine == "BLENDER_EEVEE" and "BLENDER_EEVEE_NEXT" in available_engines:
            target_engine = "BLENDER_EEVEE_NEXT"
        elif "CYCLES" in available_engines:
            target_engine = "CYCLES"
    
    render.engine = target_engine
    render.resolution_x = width
    render.resolution_y = height
    render.image_settings.file_format = "PNG"
    render.image_settings.color_mode = "RGBA"
    render.film_transparent = config.get("use_transparent_background", True)
    render.use_persistent_data = False
    
    scene.view_settings.exposure = exposure
    
    if target_engine == "CYCLES":
        scene.cycles.samples = max(1, samples)
        scene.cycles.preview_samples = min(scene.cycles.samples, 64)
        scene.cycles.use_denoising = True
        scene.cycles.use_adaptive_sampling = True
        scene.cycles.max_bounces = 12
        scene.cycles.diffuse_bounces = 4
        scene.cycles.glossy_bounces = 4
        scene.cycles.transmission_bounces = 8
        scene.cycles.volume_bounces = 2
        
        # 尝试使用 GPU
        try:
            prefs = bpy.context.preferences.addons['cycles'].preferences
            prefs.compute_device_type = 'CUDA'
            prefs.get_devices()
            scene.cycles.device = 'GPU'
            for device in prefs.devices:
                device.use = True
        except:
            pass
    elif target_engine in {"BLENDER_EEVEE", "BLENDER_EEVEE_NEXT"}:
        eevee = scene.eevee
        if hasattr(eevee, "taa_render_samples"):
            eevee.taa_render_samples = max(1, samples)
        elif hasattr(eevee, "samples"):
            eevee.samples = max(1, samples)
        # AO
        if hasattr(eevee, "use_gtao"):
            eevee.use_gtao = True
            if hasattr(eevee, "gtao_distance"):
                eevee.gtao_distance = 0.5
            if hasattr(eevee, "gtao_quality"):
                eevee.gtao_quality = 0.5
        # Bloom
        if hasattr(eevee, "use_bloom"):
            eevee.use_bloom = True
            if hasattr(eevee, "bloom_threshold"):
                eevee.bloom_threshold = 0.8
            if hasattr(eevee, "bloom_intensity"):
                eevee.bloom_intensity = 0.1
        # SSR
        if hasattr(eevee, "use_ssr"):
            eevee.use_ssr = True
            if hasattr(eevee, "use_ssr_refraction"):
                eevee.use_ssr_refraction = True
        # 软阴影
        if hasattr(eevee, "use_soft_shadows"):
            eevee.use_soft_shadows = True
        if hasattr(eevee, "shadow_cube_size"):
            eevee.shadow_cube_size = '1024'
        if hasattr(eevee, "shadow_cascade_size"):
            eevee.shadow_cascade_size = '2048'
        if hasattr(eevee, "use_denoise"):
            eevee.use_denoise = True


def auto_crop_image(image_path, padding=10):
    """裁剪图像透明边距
    
    Args:
        image_path: PNG 图像路径
        padding: 保留的边距像素
    """
    img = Image.open(image_path)
    
    if img.mode != "RGBA":
        img = img.convert("RGBA")
    
    # 获取 alpha 通道并找到非透明边界
    alpha = img.split()[-1]
    bbox = alpha.getbbox()
    
    if bbox is None:
        return
    
    # 添加边距
    left = max(0, bbox[0] - padding)
    top = max(0, bbox[1] - padding)
    right = min(img.width, bbox[2] + padding)
    bottom = min(img.height, bbox[3] + padding)
    
    # 裁剪并保存
    cropped = img.crop((left, top, right, bottom))
    cropped.save(image_path)


def batch_render(results_dir, dataset_name=""):
    """批量渲染"""
    results_dir = Path(results_dir)
    if not results_dir.exists():
        print(f"⚠️ 目录不存在: {results_dir}")
        return 0
    
    # 找所有有 scene_graph.json 或 scene.json 的目录
    scene_dirs = [d for d in results_dir.iterdir() 
                  if d.is_dir() and ((d / "scene_graph.json").exists() or (d / "scene.json").exists())]
    
    print(f"\n📂 {dataset_name}: 找到 {len(scene_dirs)} 个场景")
    
    success = 0
    for i, scene_dir in enumerate(scene_dirs, 1):
        # 跳过已渲染的
        if (scene_dir / "render.png").exists():
            print(f"[{i}/{len(scene_dirs)}] {scene_dir.name} - 已存在,跳过")
            success += 1
            success += 1
            continue
        
        print(f"[{i}/{len(scene_dirs)}] {scene_dir.name}")
        if render_single_scene(scene_dir):
            success += 1
    
    print(f"\n✅ {dataset_name} 完成: {success}/{len(scene_dirs)}")
    return success


def main():
    print(f"\n{'='*60}")
    print("🎬 IDesign 批量渲染 (bpy)")
    print(f"{'='*60}")
    print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    
    # 删除默认 Cube
    clear_default_cube()
    
    # 渲染 zones
    zones_dir = "/home/v-meiszhang/amlt-project/MetaSpatial/IDesign/evaluation/evaluation_results"
    batch_render(zones_dir, "zones")
    
    # 渲染 bench
    bench_dir = "/home/v-meiszhang/amlt-project/MetaSpatial/IDesign/evaluation/layout_bench_results"
    batch_render(bench_dir, "bench")
    
    print(f"\n{'='*60}")
    print("✅ 全部完成")
    print(f"{'='*60}")


if __name__ == "__main__":
    main()