File size: 33,882 Bytes
8f2154a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
"""
测试 layout_instr_bench_test 数据集 (700 samples)

7 种房间类型,每种 100 个样本:
- bathroom, bedroom, dining_room, kitchen, living_room, office, study_room

使用 generated_prompt 作为输入,走完整的 end_to_end_pipeline 流程:
1. 从 user_input 生成房间规格和物体列表 (在主进程使用 Azure OpenAI)
2. 用 OpenShape 从 objaverse_processed 检索 3D 资产 (在主进程使用 CUDA)
3. 用 LayoutVLM 优化布局 (单线程)
4. 计算碰撞和出界指标 (使用 voxel, pitch=0.05)

架构说明:
- 第一阶段 (主进程): 对所有样本进行 LLM 调用和 CUDA 资产检索
- 第二阶段 (单线程): 运行 LayoutVLM 优化
"""

import os
import json
import argparse
import numpy as np
import collections
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
from tqdm import tqdm
import trimesh
from scipy.spatial import ConvexHull
from shapely.geometry import Polygon, Point
from multiprocessing import current_process
import traceback

# 复用 end_to_end_pipeline.py 的功能
from end_to_end_pipeline import (
    setup_azure_client,
    generate_room_specification,
    generate_object_list,
    retrieve_3d_assets,
    generate_scene_json,
    prepare_task_assets,
    load_openclip_model,
    load_openshape_embeddings,
)

from src.layoutvlm.layoutvlm import LayoutVLM
from utils.blender_render import render_existing_scene
from utils.blender_utils import reset_blender


# ============================================================================
# 数据加载 (从 JSONL 文件加载 bench 数据)
# ============================================================================

def load_bench_test_data(data_dir: str) -> List[Dict]:
    """加载 layout_instr_bench_test 中的数据"""
    print(f"\n📂 加载数据: {data_dir}")
    
    room_types = [
        'bathroom', 'bedroom', 'dining_room', 'kitchen', 
        'living_room', 'office', 'study_room'
    ]
    
    all_samples = []
    
    for room_type in room_types:
        jsonl_path = os.path.join(data_dir, room_type, 'instructions.jsonl')
        if not os.path.exists(jsonl_path):
            print(f"   ⚠️ 文件不存在: {jsonl_path}")
            continue
        
        with open(jsonl_path, 'r') as f:
            for line_idx, line in enumerate(f):
                try:
                    data = json.loads(line.strip())
                    sample = {
                        'id': f"{room_type}_{line_idx:03d}",
                        'room_type': room_type,
                        'user_input': data.get('generated_prompt', ''),
                        'source': data.get('source', {}),
                        'complexity': data.get('complexity', ''),
                    }
                    all_samples.append(sample)
                except json.JSONDecodeError as e:
                    print(f"   ⚠️ JSON 解析错误 {room_type}:{line_idx}: {e}")
        
        print(f"   {room_type}: 加载完成")
    
    print(f"   总计 {len(all_samples)} 个样本")
    return all_samples


# ============================================================================
# 碰撞和出界检测 (使用 voxel, pitch=0.05)
# ============================================================================

@dataclass
class CollisionResult:
    total_assets: int
    collision_pairs: List[Tuple[str, str]]
    collision_count: int
    collision_ratio: float
    # 碰撞体积指标
    collision_volume: float  # 总碰撞体积 (立方米)
    collision_volume_per_pair: Dict[str, float]  # 每对碰撞的体积
    # 出界指标
    out_of_bounds_assets: List[str]
    out_of_bounds_count: int
    out_of_bounds_ratio: float
    # 出界体积指标
    out_of_bounds_volume: float  # 总出界体积 (立方米)
    out_of_bounds_volume_per_asset: Dict[str, float]  # 每个物体的出界体积
    # 总体积(用于计算比例)
    total_asset_volume: float  # 所有资产的总体积


def load_mesh_from_glb(glb_path: str) -> Optional[trimesh.Trimesh]:
    """从 glb 文件加载 mesh"""
    if not os.path.exists(glb_path):
        return None
    try:
        mesh = trimesh.load(glb_path)
        if isinstance(mesh, trimesh.Scene):
            meshes = [g for g in mesh.geometry.values() if isinstance(g, trimesh.Trimesh)]
            if meshes:
                mesh = trimesh.util.concatenate(meshes)
            else:
                return None
        return mesh
    except Exception as e:
        print(f"      ⚠️ 加载mesh失败: {e}")
        return None


def transform_mesh(mesh: trimesh.Trimesh, position: List[float], 
                   rotation: float, scale: List[float]) -> trimesh.Trimesh:
    """变换 mesh 到世界坐标"""
    mesh_copy = mesh.copy()
    
    # 缩放到目标尺寸
    current_extents = mesh_copy.bounding_box.extents
    if all(e > 0 for e in current_extents):
        scale_factors = [s / e for s, e in zip(scale, current_extents)]
        mesh_copy.apply_scale(scale_factors)
    
    # 旋转 (绕 Z 轴)
    rotation_matrix = trimesh.transformations.rotation_matrix(
        np.radians(rotation), [0, 0, 1]
    )
    mesh_copy.apply_transform(rotation_matrix)
    
    # 平移
    mesh_copy.apply_translation(position)
    
    return mesh_copy


def voxelize_mesh(mesh: trimesh.Trimesh, pitch: float = 0.05) -> Optional[set]:
    """将 mesh 体素化,返回体素坐标集合"""
    try:
        voxels = mesh.voxelized(pitch=pitch)
        # 获取填充的体素索引
        indices = voxels.sparse_indices
        # 转换为世界坐标并量化
        world_coords = indices * pitch + voxels.transform[:3, 3]
        # 量化为整数索引
        quantized = set(map(tuple, np.round(world_coords / pitch).astype(int)))
        return quantized
    except Exception as e:
        return None


def check_voxel_collision(voxels1: set, voxels2: set, voxel_pitch: float = 0.05) -> Tuple[bool, int, float]:
    """检测两个体素集合是否碰撞,返回碰撞体素数和碰撞体积"""
    if voxels1 is None or voxels2 is None:
        return False, 0, 0.0
    overlap = voxels1 & voxels2
    overlap_count = len(overlap)
    # 每个体素的体积 = pitch^3
    overlap_volume = overlap_count * (voxel_pitch ** 3)
    return overlap_count > 0, overlap_count, overlap_volume


def check_out_of_bounds_voxel(voxels: set, boundary_polygon: List[List[float]], 
                               height: float, voxel_pitch: float = 0.05) -> Tuple[bool, int, float]:
    """
    检测物体体素是否出界,返回出界体素数和出界体积
    """
    if voxels is None or len(voxels) == 0:
        return False, 0, 0.0
    
    try:
        boundary = Polygon([(p[0], p[1]) for p in boundary_polygon])
        if not boundary.is_valid:
            boundary = boundary.buffer(0)
        
        out_count = 0
        for voxel in voxels:
            # 转换体素索引回世界坐标
            x = voxel[0] * voxel_pitch
            y = voxel[1] * voxel_pitch
            z = voxel[2] * voxel_pitch if len(voxel) > 2 else 0
            
            # 检查 XY 平面是否在边界内
            point = Point(x, y)
            if not boundary.contains(point):
                out_count += 1
            # 检查高度
            elif z < 0 or z > height:
                out_count += 1
        
        out_volume = out_count * (voxel_pitch ** 3)
        return out_count > 0, out_count, out_volume
        
    except Exception as e:
        return False, 0, 0.0


def evaluate_layout_collisions(layout: Dict, scene_config: Dict, 
                               voxel_pitch: float = 0.05) -> CollisionResult:
    """
    评估布局的碰撞和出界情况,计算碰撞体积和出界体积
    """
    print("   📊 评估碰撞和出界...")
    
    # 获取边界多边形和房间高度
    boundary = scene_config.get('boundary', {})
    floor_vertices = boundary.get('floor_vertices', [[0,0,0], [5,0,0], [5,5,0], [0,5,0]])
    boundary_polygon = [[v[0], v[1]] for v in floor_vertices]
    room_height = boundary.get('ceiling_height', 2.7)
    
    # 加载所有资产的 mesh 并体素化
    asset_voxels = {}
    asset_positions = {}
    asset_volumes = {}  # 每个资产的体积
    
    for asset_id, asset_info in layout.items():
        if asset_id not in scene_config.get('assets', {}):
            continue
        
        asset_meta = scene_config['assets'][asset_id]
        glb_path = asset_meta.get('path')
        
        position = asset_info.get('position', [0, 0, 0])
        if len(position) == 2:
            bbox = asset_meta.get('assetMetadata', {}).get('boundingBox', {})
            z_height = bbox.get('z', 1.0)
            position = [position[0], position[1], z_height / 2]
        
        rotation = asset_info.get('rotation', 0)
        if isinstance(rotation, (list, tuple)):
            rotation = rotation[2] if len(rotation) > 2 else rotation[0]
        
        scale_factor = asset_info.get('scale', 1.0)
        bbox = asset_meta.get('assetMetadata', {}).get('boundingBox', {})
        size = [
            bbox.get('x', 1.0) * scale_factor,
            bbox.get('y', 1.0) * scale_factor,
            bbox.get('z', 1.0) * scale_factor
        ]
        
        asset_positions[asset_id] = {
            'position': position,
            'rotation': rotation,
            'size': size,
        }
        
        # 加载并变换 mesh
        if glb_path and os.path.exists(glb_path):
            mesh = load_mesh_from_glb(glb_path)
            if mesh:
                transformed = transform_mesh(mesh, position, rotation, size)
                voxels = voxelize_mesh(transformed, voxel_pitch)
                if voxels:
                    asset_voxels[asset_id] = voxels
                    asset_volumes[asset_id] = len(voxels) * (voxel_pitch ** 3)
    
    # 碰撞检测
    print(f"      检测碰撞 (voxel pitch={voxel_pitch})...")
    collision_pairs = []
    collision_volume_per_pair = {}
    total_collision_volume = 0.0
    
    asset_ids = list(asset_voxels.keys())
    for i in range(len(asset_ids)):
        for j in range(i + 1, len(asset_ids)):
            id1, id2 = asset_ids[i], asset_ids[j]
            is_collision, overlap_count, overlap_volume = check_voxel_collision(
                asset_voxels[id1], asset_voxels[id2], voxel_pitch
            )
            if is_collision:
                pair_key = f"{id1}--{id2}"
                collision_pairs.append((id1, id2))
                collision_volume_per_pair[pair_key] = overlap_volume
                total_collision_volume += overlap_volume
    
    # 出界检测
    print("      检测出界...")
    out_of_bounds = []
    out_of_bounds_volume_per_asset = {}
    total_out_of_bounds_volume = 0.0
    
    for asset_id in asset_voxels.keys():
        is_out, out_count, out_volume = check_out_of_bounds_voxel(
            asset_voxels[asset_id], boundary_polygon, room_height, voxel_pitch
        )
        if is_out:
            out_of_bounds.append(asset_id)
            out_of_bounds_volume_per_asset[asset_id] = out_volume
            total_out_of_bounds_volume += out_volume
    
    # 计算统计
    n = len(asset_positions)
    max_pairs = n * (n - 1) // 2 if n > 1 else 1
    total_asset_volume = sum(asset_volumes.values())
    
    print(f"      📊 碰撞: {len(collision_pairs)} 对, 碰撞体积: {total_collision_volume:.6f} m³")
    print(f"      📊 出界: {len(out_of_bounds)} 个, 出界体积: {total_out_of_bounds_volume:.6f} m³")
    print(f"      📊 总资产体积: {total_asset_volume:.6f} m³")
    
    return CollisionResult(
        total_assets=n,
        collision_pairs=collision_pairs,
        collision_count=len(collision_pairs),
        collision_ratio=len(collision_pairs) / max_pairs if max_pairs > 0 else 0,
        collision_volume=total_collision_volume,
        collision_volume_per_pair=collision_volume_per_pair,
        out_of_bounds_assets=out_of_bounds,
        out_of_bounds_count=len(out_of_bounds),
        out_of_bounds_ratio=len(out_of_bounds) / n if n > 0 else 0,
        out_of_bounds_volume=total_out_of_bounds_volume,
        out_of_bounds_volume_per_asset=out_of_bounds_volume_per_asset,
        total_asset_volume=total_asset_volume,
    )


# ============================================================================
# 渲染 (使用 blender_render.py,无墙壁天花板)
# ============================================================================

def render_scene(scene_config: Dict, layout: Dict, save_dir: str) -> List[str]:
    """渲染场景 (diagonal + top 视角,无墙壁天花板)"""
    print("   🎨 渲染场景...")
    
    output_dir = os.path.join(save_dir, "renders")
    os.makedirs(output_dir, exist_ok=True)
    
    render_paths = []
    
    try:
        print("      渲染 top-down 视角...")
        top_images, _ = render_existing_scene(
            placed_assets=layout,
            task=scene_config,
            save_dir=output_dir,
            high_res=True,
            render_top_down=True,
            add_coordinate_mark=False,
            annotate_object=False,
            annotate_wall=False,
            combine_obj_components=True,
            fov_multiplier=1.3,
            topdown_save_file=os.path.join(output_dir, 'render_top.png'),
            sideview_save_file=os.path.join(output_dir, 'render_diagonal.png'),
            side_view_indices=[3],
        )
        reset_blender()
        render_paths.extend(top_images)
        print(f"      ✅ 渲染完成: {len(render_paths)} 张图片")
        
    except Exception as e:
        print(f"      ❌ 渲染失败: {e}")
        traceback.print_exc()
    
    return render_paths


# ============================================================================
# 第一阶段: 主进程预处理 (LLM + CUDA 资产检索)
# ============================================================================

def preprocess_sample(sample: Dict, asset_dir: str, client, use_openshape: bool = True) -> Dict:
    """
    在主进程中预处理单个样本:
    1. 调用 LLM 生成房间规格和物体列表
    2. 使用 CUDA 进行 OpenShape 资产检索
    3. 生成 scene_json
    
    返回预处理结果,供后续 LayoutVLM 优化使用
    """
    sample_id = sample['id']
    user_input = sample['user_input']
    
    result = {
        'sample_id': sample_id,
        'user_input': user_input,
        'room_type': sample.get('room_type', ''),
        'success': False,
        'scene_json': None,
        'room_spec': None,
        'object_list': None,
        'num_assets': 0,
        'error': None,
    }
    
    try:
        # Step 1: 生成房间规格
        room_spec = generate_room_specification(client, user_input)
        result['room_spec'] = room_spec
        
        # Step 2: 生成物体列表
        object_list = generate_object_list(
            client,
            room_spec['task_description'],
            room_spec['layout_criteria'],
            room_spec['room_size']
        )
        result['object_list'] = object_list
        
        # Step 3: 检索 3D 资产 (CUDA 操作)
        assets = retrieve_3d_assets(object_list, asset_dir, use_openshape=use_openshape)
        result['num_assets'] = len(assets)
        
        if not assets:
            raise ValueError("未检索到任何资产")
        
        # Step 4: 生成 scene JSON
        scene_json = generate_scene_json(
            room_spec['task_description'],
            room_spec['layout_criteria'],
            room_spec['room_size'],
            assets
        )
        result['scene_json'] = scene_json
        result['success'] = True
        
    except Exception as e:
        result['error'] = str(e)
        print(f"   ❌ 预处理失败 [{sample_id}]: {e}")
    
    return result


def preprocess_all_samples(samples: List[Dict], asset_dir: str, 
                          use_openshape: bool = True, save_dir: str = None) -> List[Dict]:
    """
    主进程中预处理所有样本 (LLM 调用 + CUDA 资产检索)
    """
    print("\n" + "=" * 80)
    print("📦 第一阶段: 预处理 (LLM + OpenShape 检索)")
    print("=" * 80)
    
    # 预加载 CUDA 模型
    if use_openshape:
        print("🔄 加载 CLIP 模型和 OpenShape embeddings...")
        load_openclip_model()
        load_openshape_embeddings()
        print("✅ 模型加载完成\n")
    
    # 创建 Azure 客户端
    client = setup_azure_client()
    
    preprocessed = []
    for i, sample in enumerate(tqdm(samples, desc="预处理进度")):
        sample_id = sample['id']
        
        # 检查是否已完成预处理
        if save_dir:
            sample_save_dir = os.path.join(save_dir, f"sample_{i:04d}")
            scene_path = os.path.join(sample_save_dir, 'scene_config.json')
            if os.path.exists(scene_path):
                # 加载已有的预处理结果
                try:
                    with open(scene_path, 'r') as f:
                        scene_json = json.load(f)
                    preprocessed.append({
                        'sample_id': sample_id,
                        'user_input': sample['user_input'],
                        'room_type': sample.get('room_type', ''),
                        'success': True,
                        'scene_json': scene_json,
                        'room_spec': None,  # 不需要保存
                        'object_list': None,
                        'num_assets': len(scene_json.get('objects', [])),
                        'error': None,
                        'skipped': True,
                    })
                    print(f"   ⏭️ 跳过已预处理: {sample_id}")
                    continue
                except:
                    pass
        
        # 预处理
        result = preprocess_sample(sample, asset_dir, client, use_openshape)
        preprocessed.append(result)
        
        # 保存 scene_json
        if result['success'] and save_dir:
            sample_save_dir = os.path.join(save_dir, f"sample_{i:04d}")
            os.makedirs(sample_save_dir, exist_ok=True)
            scene_path = os.path.join(sample_save_dir, 'scene_config.json')
            with open(scene_path, 'w') as f:
                json.dump(result['scene_json'], f, indent=2)
    
    # 统计
    success_count = sum(1 for p in preprocessed if p['success'])
    print(f"\n📊 预处理完成: {success_count}/{len(samples)} 成功")
    
    return preprocessed


# ============================================================================
# 第二阶段: LayoutVLM 优化 (单线程)
# ============================================================================

def layoutvlm_worker(args_tuple) -> Dict:
    """
    LayoutVLM 优化 worker (单线程模式)
    """
    idx, preprocessed, save_dir, asset_dir, do_render = args_tuple
    
    sample_id = preprocessed['sample_id']
    sample_save_dir = os.path.join(save_dir, f"sample_{idx:04d}")
    
    proc_name = current_process().name
    
    result = {
        'sample_id': sample_id,
        'user_input': preprocessed['user_input'],
        'room_type': preprocessed.get('room_type', ''),
        'success': False,
        'room_spec': preprocessed.get('room_spec'),
        'object_list': preprocessed.get('object_list'),
        'num_assets': preprocessed.get('num_assets', 0),
        'collision_result': None,
        'render_paths': [],
        'error': None,
    }
    
    # 检查是否已完成
    layout_path = os.path.join(sample_save_dir, 'layout.json')
    result_json_path = os.path.join(sample_save_dir, 'result.json')
    
    if os.path.exists(layout_path):
        if os.path.exists(result_json_path):
            try:
                with open(result_json_path, 'r') as f:
                    cached_result = json.load(f)
                print(f"[{proc_name}] ⏭️ 跳过已完成: {sample_id}")
                cached_result['skipped'] = True
                return cached_result
            except:
                pass
        result['success'] = True
        result['skipped'] = True
        print(f"[{proc_name}] ⏭️ 跳过已完成: {sample_id}")
        return result
    
    # 检查预处理是否成功
    if not preprocessed['success']:
        result['error'] = preprocessed.get('error', '预处理失败')
        print(f"[{proc_name}] ⏭️ 跳过预处理失败: {sample_id}")
        return result
    
    try:
        print(f"\n[{proc_name}] {'='*50}")
        print(f"[{proc_name}] 📋 处理样本: {sample_id}")
        
        scene_json = preprocessed['scene_json']
        os.makedirs(sample_save_dir, exist_ok=True)
        
        # 准备资产元数据
        scene_config = prepare_task_assets(scene_json, asset_dir)
        
        if not scene_config.get('assets'):
            raise ValueError("没有有效的资产")
        
        # LayoutVLM 优化 (会在内部创建新的 Azure 客户端)
        print(f"[{proc_name}]    LayoutVLM 布局优化...")
        layout_solver = LayoutVLM(
            mode="one_shot",
            save_dir=sample_save_dir,
            asset_source="objaverse",
        )
        layout = layout_solver.solve(scene_config)
        
        # 保存布局
        with open(layout_path, 'w') as f:
            json.dump(layout, f, indent=2)
        
        # 计算碰撞和出界
        print(f"[{proc_name}]    计算碰撞和出界...")
        collision_result = evaluate_layout_collisions(
            layout, scene_config, voxel_pitch=0.05
        )
        
        result['collision_result'] = {
            'total_assets': collision_result.total_assets,
            'collision_count': collision_result.collision_count,
            'collision_ratio': collision_result.collision_ratio,
            'collision_volume': collision_result.collision_volume,
            'collision_volume_per_pair': collision_result.collision_volume_per_pair,
            'out_of_bounds_count': collision_result.out_of_bounds_count,
            'out_of_bounds_ratio': collision_result.out_of_bounds_ratio,
            'out_of_bounds_volume': collision_result.out_of_bounds_volume,
            'out_of_bounds_volume_per_asset': collision_result.out_of_bounds_volume_per_asset,
            'total_asset_volume': collision_result.total_asset_volume,
            'collision_pairs': collision_result.collision_pairs,
            'out_of_bounds_assets': collision_result.out_of_bounds_assets,
        }
        
        # 渲染 (可选)
        if do_render:
            print(f"[{proc_name}]    Blender 渲染...")
            render_paths = render_scene(scene_config, layout, sample_save_dir)
            result['render_paths'] = render_paths
        
        result['success'] = True
        print(f"[{proc_name}]    ✅ 完成")
        
    except Exception as e:
        result['error'] = str(e)
        print(f"[{proc_name}]    ❌ 失败: {e}")
        traceback.print_exc()
    
    # 保存单个样本结果
    with open(result_json_path, 'w') as f:
        json.dump(result, f, indent=2, default=str)
    
    return result


# ============================================================================
# 主函数
# ============================================================================

def main():
    parser = argparse.ArgumentParser(description='测试 layout_instr_bench_test 数据集')
    parser.add_argument('--data_dir', type=str,
                        default='/home/v-meiszhang/amlt-project/Qwen-Image/layout_instr_bench_test',
                        help='数据目录路径')
    parser.add_argument('--save_dir', type=str,
                        default='./results/bench_test_700',
                        help='结果保存目录')
    parser.add_argument('--asset_dir', type=str,
                        default='/home/v-meiszhang/backup/objaverse_processed',
                        help='Objaverse 资产目录')
    parser.add_argument('--num_samples', type=int, default=0,
                        help='测试样本数量 (0 表示全部 700 个)')
    parser.add_argument('--start_idx', type=int, default=0,
                        help='起始索引')
    parser.add_argument('--random_selection', action='store_true',
                        help='使用随机选择而非 OpenShape 检索')
    parser.add_argument('--skip_render', action='store_true', default=True,
                        help='跳过渲染 (默认开启)')
    parser.add_argument('--enable_render', action='store_true',
                        help='启用渲染')
    parser.add_argument('--room_type', type=str, default=None,
                        help='仅测试指定房间类型 (bathroom/bedroom/dining_room/kitchen/living_room/office/study_room)')
    
    args = parser.parse_args()
    
    do_render = args.enable_render
    use_openshape = not args.random_selection
    
    print("=" * 80)
    print("🧪 Bench Data 测试脚本 (单线程)")
    print("=" * 80)
    print(f"📁 数据路径: {args.data_dir}")
    print(f"💾 保存目录: {args.save_dir}")
    print(f"📦 资产目录: {args.asset_dir}")
    print(f"📊 测试数量: {args.num_samples if args.num_samples > 0 else '全部'}")
    print(f"🎨 渲染: {'启用' if do_render else '跳过'}")
    print(f"🔍 资产检索: {'OpenShape' if use_openshape else '随机选择'}")
    if args.room_type:
        print(f"🏠 房间类型: {args.room_type}")
    print()
    
    os.makedirs(args.save_dir, exist_ok=True)
    
    # 加载测试数据
    test_data = load_bench_test_data(args.data_dir)
    
    # 过滤房间类型
    if args.room_type:
        test_data = [s for s in test_data if s.get('room_type') == args.room_type]
        print(f"📊 过滤后样本数: {len(test_data)}")
    
    # 选择测试范围
    if args.num_samples > 0:
        test_data = test_data[args.start_idx:args.start_idx + args.num_samples]
    elif args.start_idx > 0:
        test_data = test_data[args.start_idx:]
    
    print(f"📊 实际测试样本数: {len(test_data)}")
    
    # ===== 第一阶段: 主进程预处理 (LLM + CUDA) =====
    preprocessed = preprocess_all_samples(
        test_data, 
        args.asset_dir, 
        use_openshape=use_openshape,
        save_dir=args.save_dir
    )
    
    # ===== 第二阶段: 单线程 LayoutVLM 优化 =====
    print("\n" + "=" * 80)
    print("🚀 第二阶段: LayoutVLM 优化 (单线程)")
    print("=" * 80)
    
    # 准备 worker 参数
    worker_args = [
        (i, preprocessed[i], args.save_dir, args.asset_dir, do_render)
        for i in range(len(preprocessed))
    ]
    
    all_results = []
    for args_tuple in tqdm(worker_args, desc="LayoutVLM 进度"):
        result = layoutvlm_worker(args_tuple)
        all_results.append(result)
        
        # 每完成10个保存一次中间结果
        if len(all_results) % 10 == 0:
            results_path = os.path.join(args.save_dir, 'all_results.json')
            with open(results_path, 'w') as f:
                json.dump(all_results, f, indent=2, default=str)
    
    # ===== 统计结果 =====
    summary = {
        'total_samples': len(test_data),
        'successful': 0,
        'failed': 0,
        'skipped': 0,
        'total_collisions': 0,
        'total_out_of_bounds': 0,
        'avg_collision_ratio': 0,
        'avg_out_of_bounds_ratio': 0,
        # 按房间类型统计
        'by_room_type': {},
    }
    
    collision_ratios = []
    out_of_bounds_ratios = []
    collision_volumes = []
    out_of_bounds_volumes = []
    total_asset_volumes = []
    
    # 按房间类型统计
    room_type_stats = {}
    
    for result in all_results:
        room_type = result.get('room_type', 'unknown')
        if room_type not in room_type_stats:
            room_type_stats[room_type] = {
                'total': 0,
                'successful': 0,
                'failed': 0,
                'collision_volumes': [],
                'out_of_bounds_volumes': [],
                'total_asset_volumes': [],
            }
        room_type_stats[room_type]['total'] += 1
        
        if result.get('skipped'):
            summary['skipped'] += 1
            summary['successful'] += 1
            room_type_stats[room_type]['successful'] += 1
        elif result.get('success'):
            summary['successful'] += 1
            room_type_stats[room_type]['successful'] += 1
            if result.get('collision_result'):
                cr = result['collision_result']
                summary['total_collisions'] += cr['collision_count']
                summary['total_out_of_bounds'] += cr['out_of_bounds_count']
                collision_ratios.append(cr['collision_ratio'])
                out_of_bounds_ratios.append(cr['out_of_bounds_ratio'])
                collision_volumes.append(cr.get('collision_volume', 0))
                out_of_bounds_volumes.append(cr.get('out_of_bounds_volume', 0))
                total_asset_volumes.append(cr.get('total_asset_volume', 0))
                
                room_type_stats[room_type]['collision_volumes'].append(cr.get('collision_volume', 0))
                room_type_stats[room_type]['out_of_bounds_volumes'].append(cr.get('out_of_bounds_volume', 0))
                room_type_stats[room_type]['total_asset_volumes'].append(cr.get('total_asset_volume', 0))
        else:
            summary['failed'] += 1
            room_type_stats[room_type]['failed'] += 1
    
    if collision_ratios:
        summary['avg_collision_ratio'] = sum(collision_ratios) / len(collision_ratios)
    if out_of_bounds_ratios:
        summary['avg_out_of_bounds_ratio'] = sum(out_of_bounds_ratios) / len(out_of_bounds_ratios)
    
    summary['total_collision_volume'] = sum(collision_volumes)
    summary['total_out_of_bounds_volume'] = sum(out_of_bounds_volumes)
    summary['total_asset_volume'] = sum(total_asset_volumes)
    summary['avg_collision_volume'] = sum(collision_volumes) / len(collision_volumes) if collision_volumes else 0
    summary['avg_out_of_bounds_volume'] = sum(out_of_bounds_volumes) / len(out_of_bounds_volumes) if out_of_bounds_volumes else 0
    summary['collision_volume_ratio'] = summary['total_collision_volume'] / summary['total_asset_volume'] if summary['total_asset_volume'] > 0 else 0
    summary['out_of_bounds_volume_ratio'] = summary['total_out_of_bounds_volume'] / summary['total_asset_volume'] if summary['total_asset_volume'] > 0 else 0
    
    # 计算每个房间类型的统计
    for room_type, stats in room_type_stats.items():
        summary['by_room_type'][room_type] = {
            'total': stats['total'],
            'successful': stats['successful'],
            'failed': stats['failed'],
            'total_collision_volume': sum(stats['collision_volumes']),
            'total_out_of_bounds_volume': sum(stats['out_of_bounds_volumes']),
            'total_asset_volume': sum(stats['total_asset_volumes']),
            'avg_collision_volume': sum(stats['collision_volumes']) / len(stats['collision_volumes']) if stats['collision_volumes'] else 0,
            'avg_out_of_bounds_volume': sum(stats['out_of_bounds_volumes']) / len(stats['out_of_bounds_volumes']) if stats['out_of_bounds_volumes'] else 0,
        }
        if sum(stats['total_asset_volumes']) > 0:
            summary['by_room_type'][room_type]['collision_volume_ratio'] = sum(stats['collision_volumes']) / sum(stats['total_asset_volumes'])
            summary['by_room_type'][room_type]['out_of_bounds_volume_ratio'] = sum(stats['out_of_bounds_volumes']) / sum(stats['total_asset_volumes'])
    
    # 保存结果
    summary_path = os.path.join(args.save_dir, 'summary.json')
    with open(summary_path, 'w') as f:
        json.dump(summary, f, indent=2)
    
    results_path = os.path.join(args.save_dir, 'all_results.json')
    with open(results_path, 'w') as f:
        json.dump(all_results, f, indent=2, default=str)
    
    # 打印总结
    print("\n" + "=" * 80)
    print("📊 测试总结")
    print("=" * 80)
    print(f"总样本数: {summary['total_samples']}")
    print(f"成功: {summary['successful']}")
    print(f"失败: {summary['failed']}")
    print(f"跳过: {summary['skipped']}")
    print(f"\n--- 碰撞指标 ---")
    print(f"总碰撞对数: {summary['total_collisions']}")
    print(f"平均碰撞比例: {summary['avg_collision_ratio']:.2%}")
    print(f"总碰撞体积: {summary['total_collision_volume']:.6f} m³")
    print(f"平均碰撞体积: {summary['avg_collision_volume']:.6f} m³")
    print(f"碰撞体积比例: {summary['collision_volume_ratio']:.4%}")
    print(f"\n--- 出界指标 ---")
    print(f"总出界物体数: {summary['total_out_of_bounds']}")
    print(f"平均出界比例: {summary['avg_out_of_bounds_ratio']:.2%}")
    print(f"总出界体积: {summary['total_out_of_bounds_volume']:.6f} m³")
    print(f"平均出界体积: {summary['avg_out_of_bounds_volume']:.6f} m³")
    print(f"出界体积比例: {summary['out_of_bounds_volume_ratio']:.4%}")
    print(f"\n--- 资产体积 ---")
    print(f"总资产体积: {summary['total_asset_volume']:.6f} m³")
    
    # 打印每个房间类型的统计
    print(f"\n--- 按房间类型统计 ---")
    for room_type in sorted(summary['by_room_type'].keys()):
        rt_stats = summary['by_room_type'][room_type]
        print(f"\n  {room_type}:")
        print(f"    样本数: {rt_stats['total']} (成功: {rt_stats['successful']}, 失败: {rt_stats['failed']})")
        print(f"    平均碰撞体积: {rt_stats['avg_collision_volume']:.6f} m³")
        print(f"    平均出界体积: {rt_stats['avg_out_of_bounds_volume']:.6f} m³")
    
    print(f"\n结果保存在: {args.save_dir}")


if __name__ == '__main__':
    main()