File size: 25,850 Bytes
4f9eed9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Compose Generated Scene Script

This script takes a layout JSON (with model_uids) and composes a GLB scene.
It handles flattening of functional zones/groups and applies transforms.
Also generates room geometry (floor, walls, ceiling) from boundary_polygon.

Supports both:
- Original asset library (with per-asset-type rotation handling)
- Normalized asset library (pre-processed, no rotation needed)
"""

import os
import json
import trimesh
import numpy as np
import argparse
import sys
from pathlib import Path
from shapely.geometry import Polygon as ShapelyPolygon
from trimesh.visual import ColorVisuals

# Add project root
SCRIPT_DIR = Path(__file__).parent
REPO_ROOT = SCRIPT_DIR.parent.parent
sys.path.insert(0, str(REPO_ROOT))

# Add InternScenes_Real2Sim to path to import compose_scenes
sys.path.insert(0, os.path.join(REPO_ROOT, "InternScenes", "InternScenes_Real2Sim"))

# Import loaders
from compose_scenes import AssetMeshLoader

# Try to import normalized asset loader
try:
    from tools.asset_description.normalized_asset_loader import NormalizedAssetMeshLoader
    NORMALIZED_LOADER_AVAILABLE = True
except ImportError:
    NORMALIZED_LOADER_AVAILABLE = False

def normalize_rotation(rot):
    """
    Normalize rotation to radians.
    Heuristic: if any value is outside [-2pi, 2pi], assume degrees.
    """
    rot = np.array(rot, dtype=np.float64)
    if np.any(np.abs(rot) > 2 * np.pi + 1e-3):
        return np.radians(rot)
    return rot

def get_scale_transform(mesh_size, target_size, category):
    """
    Calculate scale matrix based on target size and mesh size.
    Includes special handling for carpets/clothes similar to compose_scenes.py
    """
    scale_matrix = np.eye(4)
    
    # Avoid division by zero
    mesh_size = np.maximum(mesh_size, 1e-6)
    
    if category == "carpet":
        scale_factors = target_size / mesh_size
        # Check for orientation issues (carpet standing up)
        # Heuristic from compose_scenes.py
        if target_size[2]/target_size[0] > 150 or target_size[2]/target_size[1] > 150:
             if target_size[2]/target_size[0] > target_size[2]/target_size[1]:
                 # Rotate 90 around Y
                 rot_mat = trimesh.transformations.rotation_matrix(0.5 * np.pi, [0, 1, 0])
                 new_target = np.array([target_size[2], target_size[0], target_size[1]])
                 scale_factors = new_target / mesh_size
                 scale_matrix = np.diag([scale_factors[0], scale_factors[1], scale_factors[2]/100.0, 1])
                 return scale_matrix @ rot_mat
             else:
                 # Rotate 90 around X
                 rot_mat = trimesh.transformations.rotation_matrix(0.5 * np.pi, [1, 0, 0])
                 new_target = np.array([target_size[0], target_size[2], target_size[1]])
                 scale_factors = new_target / mesh_size
                 scale_matrix = np.diag([scale_factors[0], scale_factors[1], scale_factors[2]/100.0, 1])
                 return scale_matrix @ rot_mat
        else:
             scale_matrix = np.diag([scale_factors[0], scale_factors[1], scale_factors[2]/100.0, 1])
             return scale_matrix
             
    elif category == "clothes":
        scale = target_size / mesh_size
        min_scale = min(scale)
        scale_matrix = np.diag([min_scale, min_scale, min_scale, 1])
        return scale_matrix
        
    else:
        scale = target_size / mesh_size
        scale_matrix = np.diag([scale[0], scale[1], scale[2], 1])
        return scale_matrix


# ============================================
# Room Geometry Generation from Boundary
# ============================================

# Default colors for room structure
FLOOR_COLOR = np.array([200, 200, 200, 255], dtype=np.uint8)  # Light gray
WALL_COLOR = np.array([240, 240, 240, 180], dtype=np.uint8)   # White with some transparency
CEILING_COLOR = np.array([250, 250, 250, 128], dtype=np.uint8)  # Very light, more transparent


def triangulate_polygon(vertices_2d: np.ndarray) -> tuple:
    """
    Triangulate a 2D polygon (supports concave polygons like L-shape, H-shape).
    
    Uses trimesh's triangulate_polygon which handles concave polygons correctly
    via earcut algorithm.
    
    Args:
        vertices_2d: Nx2 array of (x, y) coordinates in order (CCW or CW)
    
    Returns:
        tuple: (vertices_2d, faces) where vertices may have additional points added
               and faces is Mx3 array of face indices
    """
    from shapely.geometry import Polygon as ShapelyPolygon
    
    # Create a proper shapely polygon
    polygon = ShapelyPolygon(vertices_2d)
    
    # Fix invalid polygons
    if not polygon.is_valid:
        polygon = polygon.buffer(0)
    
    # Use trimesh's triangulation which uses mapbox_earcut for concave polygons
    try:
        # trimesh.creation.triangulate_polygon returns (vertices, faces)
        result_vertices, result_faces = trimesh.creation.triangulate_polygon(
            polygon, 
            triangle_args=None,  # Use default earcut
            engine='earcut'  # Explicitly use earcut for concave support
        )
        
        # Return both vertices and faces - trimesh may add/reorder vertices
        return np.array(result_vertices), result_faces
        
    except Exception as e:
        print(f"Warning: trimesh triangulation failed: {e}, trying earcut directly")
        
    # Fallback: use mapbox_earcut directly if available
    try:
        import mapbox_earcut as earcut
        
        # earcut expects flattened coordinates and ring indices
        rings = np.array([len(vertices_2d)])  # Single ring (no holes)
        flat_coords = vertices_2d.flatten()
        
        # Triangulate - returns flat array of triangle vertex indices
        triangle_indices = earcut.triangulate_float64(flat_coords, rings)
        
        # Reshape to Nx3
        faces = np.array(triangle_indices).reshape(-1, 3)
        return vertices_2d, faces
        
    except ImportError:
        print("Warning: mapbox_earcut not available, using fan triangulation")
    except Exception as e:
        print(f"Warning: earcut failed: {e}")
    
    # Last resort: simple fan triangulation (only works for convex polygons)
    n = len(vertices_2d)
    faces = np.array([[0, i, i+1] for i in range(1, n-1)])
    return vertices_2d, faces


def create_floor_mesh(floor_vertices_2d: np.ndarray, z_height: float = 0.0) -> trimesh.Trimesh:
    """
    Create a floor mesh from 2D polygon vertices.
    Supports concave polygons (L-shape, H-shape, etc.)
    
    Args:
        floor_vertices_2d: Nx2 array of (x, y) coordinates in order
        z_height: Z coordinate for the floor (default 0)
    
    Returns:
        trimesh.Trimesh: Floor mesh
    """
    try:
        # Triangulate using earcut (supports concave polygons)
        # triangulate_polygon returns (vertices_2d, faces) - vertices may be different from input
        result_vertices_2d, faces = triangulate_polygon(floor_vertices_2d)
        
        # Create 3D vertices from the triangulation result
        vertices_3d = np.column_stack([result_vertices_2d, np.full(len(result_vertices_2d), z_height)])
        
        floor_mesh = trimesh.Trimesh(vertices=vertices_3d, faces=faces)
        floor_mesh.visual = ColorVisuals(mesh=floor_mesh, vertex_colors=np.tile(FLOOR_COLOR, (len(vertices_3d), 1)))
        
        return floor_mesh
    except Exception as e:
        print(f"Warning: Failed to create floor mesh: {e}")
        import traceback
        traceback.print_exc()
        return None


def create_ceiling_mesh(floor_vertices_2d: np.ndarray, z_height: float) -> trimesh.Trimesh:
    """
    Create a ceiling mesh from 2D polygon vertices.
    Supports concave polygons (L-shape, H-shape, etc.)
    
    Args:
        floor_vertices_2d: Nx2 array of (x, y) coordinates
        z_height: Z coordinate for the ceiling
    
    Returns:
        trimesh.Trimesh: Ceiling mesh
    """
    try:
        # Triangulate using earcut (supports concave polygons)
        # triangulate_polygon returns (vertices_2d, faces) - vertices may be different from input
        result_vertices_2d, faces = triangulate_polygon(floor_vertices_2d)
        
        # Create 3D vertices from the triangulation result
        vertices_3d = np.column_stack([result_vertices_2d, np.full(len(result_vertices_2d), z_height)])
        
        # Reverse face winding for ceiling (faces down)
        faces = faces[:, ::-1]
        
        ceiling_mesh = trimesh.Trimesh(vertices=vertices_3d, faces=faces)
        ceiling_mesh.visual = ColorVisuals(mesh=ceiling_mesh, vertex_colors=np.tile(CEILING_COLOR, (len(vertices_3d), 1)))
        
        return ceiling_mesh
    except Exception as e:
        print(f"Warning: Failed to create ceiling mesh: {e}")
        import traceback
        traceback.print_exc()
        return None


def create_wall_mesh(v1_bottom: np.ndarray, v2_bottom: np.ndarray, height: float) -> trimesh.Trimesh:
    """
    Create a single wall segment mesh.
    
    Args:
        v1_bottom: First bottom vertex (x, y, z)
        v2_bottom: Second bottom vertex (x, y, z)
        height: Wall height
    
    Returns:
        trimesh.Trimesh: Wall mesh
    """
    v1_top = v1_bottom.copy()
    v1_top[2] = v1_bottom[2] + height
    v2_top = v2_bottom.copy()
    v2_top[2] = v2_bottom[2] + height
    
    # Create quad as two triangles
    vertices = np.array([v1_bottom, v2_bottom, v2_top, v1_top])
    faces = np.array([[0, 1, 2], [0, 2, 3]])
    
    wall_mesh = trimesh.Trimesh(vertices=vertices, faces=faces)
    wall_mesh.visual = ColorVisuals(mesh=wall_mesh, vertex_colors=np.tile(WALL_COLOR, (4, 1)))
    
    return wall_mesh


def create_walls_mesh(floor_vertices_2d: np.ndarray, floor_z: float, height: float) -> trimesh.Trimesh:
    """
    Create all wall meshes from floor polygon.
    
    Args:
        floor_vertices_2d: Nx2 array of (x, y) floor coordinates
        floor_z: Z coordinate of the floor
        height: Wall height
    
    Returns:
        trimesh.Trimesh: Combined walls mesh
    """
    wall_meshes = []
    n = len(floor_vertices_2d)
    
    for i in range(n):
        v1_2d = floor_vertices_2d[i]
        v2_2d = floor_vertices_2d[(i + 1) % n]
        
        v1_bottom = np.array([v1_2d[0], v1_2d[1], floor_z])
        v2_bottom = np.array([v2_2d[0], v2_2d[1], floor_z])
        
        wall = create_wall_mesh(v1_bottom, v2_bottom, height)
        if wall is not None:
            wall_meshes.append(wall)
    
    if wall_meshes:
        return trimesh.util.concatenate(wall_meshes)
    return None


def generate_room_geometry(layout: dict, add_floor: bool = True, add_walls: bool = True, add_ceiling: bool = True) -> list:
    """
    Generate room geometry (floor, walls, ceiling) from layout's architecture data.
    
    Args:
        layout: Layout dictionary containing 'architecture' with 'boundary_polygon' and 'height'
        add_floor: Whether to add floor mesh
        add_walls: Whether to add wall meshes
        add_ceiling: Whether to add ceiling mesh
    
    Returns:
        List of (name, mesh) tuples
    """
    geometries = []
    
    architecture = layout.get("architecture", {})
    boundary_polygon = architecture.get("boundary_polygon", [])
    height = architecture.get("height", 2.6)  # Default 2.6m height
    
    if not boundary_polygon:
        print("Warning: No boundary_polygon found in architecture, skipping room geometry")
        return geometries
    
    # Parse boundary polygon
    # Format: [[x, y, z], ...] - first half are floor vertices, second half are ceiling vertices
    # Or it could be just floor vertices with separate height
    boundary_polygon = np.array(boundary_polygon)
    
    if len(boundary_polygon) == 0:
        return geometries
    
    # Determine floor and ceiling vertices
    # Usually boundary_polygon contains floor vertices (z=0) and ceiling vertices (z=height)
    # Split by z coordinate
    if boundary_polygon.shape[1] >= 3:
        z_values = boundary_polygon[:, 2]
        z_min = np.min(z_values)
        z_max = np.max(z_values)
        
        # If all z values are the same, use height parameter
        if abs(z_max - z_min) < 0.01:
            floor_vertices = boundary_polygon
            floor_z = z_min
            ceiling_z = z_min + height
        else:
            # Split into floor and ceiling based on z
            z_mid = (z_min + z_max) / 2
            floor_mask = z_values < z_mid
            
            floor_vertices = boundary_polygon[floor_mask]
            ceiling_vertices = boundary_polygon[~floor_mask]
            
            if len(floor_vertices) == 0:
                floor_vertices = ceiling_vertices
                floor_z = z_min
            else:
                floor_z = floor_vertices[0, 2] if len(floor_vertices) > 0 else z_min
            
            ceiling_z = z_max
            height = ceiling_z - floor_z
    else:
        # 2D polygon, assume z=0 for floor
        floor_vertices = np.column_stack([boundary_polygon, np.zeros(len(boundary_polygon))])
        floor_z = 0
        ceiling_z = height
    
    # Extract 2D coordinates (x, y) for triangulation
    floor_vertices_2d = floor_vertices[:, :2]
    
    # Create floor
    if add_floor:
        floor_mesh = create_floor_mesh(floor_vertices_2d, floor_z)
        if floor_mesh is not None:
            geometries.append(("floor", floor_mesh))
    
    # Create walls
    if add_walls:
        walls_mesh = create_walls_mesh(floor_vertices_2d, floor_z, height)
        if walls_mesh is not None:
            geometries.append(("walls", walls_mesh))
    
    # Create ceiling
    if add_ceiling:
        ceiling_mesh = create_ceiling_mesh(floor_vertices_2d, ceiling_z)
        if ceiling_mesh is not None:
            geometries.append(("ceiling", ceiling_mesh))
    
    return geometries


def compose_scene(layout, output_path, add_floor=True, add_walls=True, add_ceiling=True, 
                  input_coord_system="z-up", use_normalized_assets=True, normalized_asset_dir=None):
    """
    Compose a scene from layout JSON.
    
    Args:
        layout: layout JSON
        output_path: Path to output GLB file
        add_floor: Whether to add floor mesh
        add_walls: Whether to add wall meshes
        add_ceiling: Whether to add ceiling mesh
        input_coord_system: Coordinate system of input data. "z-up" (default) or "y-up"
        use_normalized_assets: If True, use pre-normalized assets (no per-type rotation)
        normalized_asset_dir: Path to normalized asset library (only if use_normalized_assets=True)
    """
    # 如果没有指定路径,从环境变量读取
    if normalized_asset_dir is None:
        normalized_asset_dir = os.environ.get('PTH_ASSET_NORMALIZED_LIBRARY')
        if not normalized_asset_dir:
            # 优先使用 ~/backup (本地环境),如果不存在则使用 /backup (集群环境)
            home_path = os.path.expanduser("~/backup/datas/InternScenes/asset_library_normalized")
            if os.path.exists(home_path):
                normalized_asset_dir = home_path
            else:
                normalized_asset_dir = "/backup/datas/InternScenes/asset_library_normalized"
    
    # with open(layout_path, 'r') as f:
    #     layout = json.load(f)
    
    # Auto-detect coordinate system from meta if available
    meta = layout.get("meta", {})
    if "coordinate_system" in meta:
        detected = meta["coordinate_system"].lower().replace("_", "-")
        if detected in ["z-up", "zup"]:
            input_coord_system = "z-up"
        elif detected in ["y-up", "yup"]:
            input_coord_system = "y-up"
    
    print(f"Using coordinate system: {input_coord_system}")
    
    # Select asset loader
    if use_normalized_assets:
        if not NORMALIZED_LOADER_AVAILABLE:
            raise ImportError("NormalizedAssetMeshLoader not available. Please check installation.")
        loader = NormalizedAssetMeshLoader(normalized_asset_dir)
        print(f"Using normalized asset library: {loader.asset_dir}")
    else:
        loader = AssetMeshLoader()
        print("Using original asset library with per-type rotation")
    
    scene = trimesh.Scene()
    
    # Flatten assets
    instances = []
    if "assets" in layout:
        instances.extend(layout["assets"])
    if "functional_zones" in layout:
        for zone in layout["functional_zones"]:
            if "assets" in zone:
                instances.extend(zone["assets"])
    if "groups" in layout:
        for group in layout["groups"]:
            if "objects" in group:
                instances.extend(group["objects"])
                
    print(f"Composing scene with {len(instances)} instances...")
    
    for i, instance in enumerate(instances):
        uid = instance.get("model_uid")
        if not uid:
            continue
            
        try:
            # Load canonical mesh (centers and aligns)
            # use_texture=True is important for rendering
            mesh = loader.load_canonical_mesh(uid, use_texture=True)
            if mesh is None:
                print(f"Warning: Mesh not found for {uid}")
                continue
            
            # Extract transform data
            pos = None
            rot = None
            size = None
            
            # Case 1: Nested transform (Unified Layout / 3D-FRONT)
            if "transform" in instance and isinstance(instance["transform"], dict):
                t = instance["transform"]
                pos = t.get("pos")
                rot = t.get("rot")
                size = t.get("size")
            
            # Case 2: Flat structure (Zones Data / Model Output)
            if pos is None:
                pos = instance.get("pos")
            if rot is None:
                rot = instance.get("rot")
            if size is None:
                size = instance.get("size")
                
            # Case 3: Legacy bbox (9 elements)
            if pos is None and "bbox" in instance:
                bbox = instance["bbox"]
                pos = bbox[0:3]
                size = bbox[3:6]
                rot = bbox[6:9]

            # Case 4: Matrix transform (fallback)
            if pos is None and "transform" in instance and isinstance(instance["transform"], list):
                 # This is a raw matrix, we can just use it directly if we trust it
                 # But usually we want to use the decomposed values if available
                 transform_matrix = np.array(instance["transform"]).reshape(4, 4)
                 # Apply directly
                 scene.add_geometry(mesh, transform=transform_matrix)
                 continue

            if pos is None or rot is None or size is None:
                print(f"Warning: Missing transform data for {uid}")
                continue

            # Convert to numpy
            pos = np.array(pos, dtype=np.float64)
            rot = np.array(rot, dtype=np.float64)
            size = np.array(size, dtype=np.float64)
            
            # --- Coordinate System Handling ---
            if input_coord_system == "y-up":
                # Convert Y-up to Z-up: [x, y, z]_Yup -> [x, z, y]_Zup
                pos = np.array([pos[0], pos[2], pos[1]])
                size = np.array([size[0], size[2], size[1]])
                rot = np.array([rot[0], rot[2], rot[1]])
            # else: input is already Z-up, no conversion needed
            
            # Adjust for Floor Alignment
            # In Z-up, Z is height. If pos[2] ≈ 0 (object on floor),
            # we need to lift it by half its height (size[2]) since mesh is centered.
            if abs(pos[2]) < 1e-3:
                pos[2] = size[2] / 2.0
            # ---------------------------------------------------
            
            # Normalize rotation (degrees -> radians if needed)
            rot = normalize_rotation(rot)
            
            # Start with identity
            transform_final = np.eye(4)
            
            # 1. Scale
            mesh_size = mesh.bounding_box.extents
            category = instance.get("category", "")
            scale_mat = get_scale_transform(mesh_size, size, category)
            transform_final = scale_mat @ transform_final
            
            # 2. Rotation
            # Use rzxy order as per compose_scenes.py
            # Note: compose_scenes.py uses euler_matrix(rot[0], rot[1], rot[2], axes='rzxy')
            # where rot is [rx, ry, rz] (or [rx, rz, ry] after our conversion).
            # 'rzxy' means rotate around Z, then X, then Y.
            # The input 'rot' from layout is typically [0, rotation_y, 0] for simple objects.
            # After our conversion to Z-up, it becomes [0, 0, rotation_y].
            # So rot[0]=0, rot[1]=0, rot[2]=rotation_y.
            # euler_matrix(0, 0, rotation_y, 'rzxy') -> rotates around Z by rotation_y. Correct.
            rot_mat = trimesh.transformations.euler_matrix(rot[0], rot[1], rot[2], axes='rzxy')
            transform_final = rot_mat @ transform_final
            
            # 3. Translation
            transform_final[:3, 3] = pos
            
            # 4. Global Rotation (Z-up to Y-up)
            # compose_scenes.py applies -90 deg around X at the end
            global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
            transform_final = global_rot @ transform_final
            
            # Add to scene
            # We use a unique node name to avoid conflicts
            node_name = f"{i}_{uid.replace('/', '_')}"
            
            # Create a parent node with the transform (same as compose_scenes.py)
            scene.graph.update(frame_to=node_name, matrix=transform_final)
            
            # Handle both Trimesh and Scene types
            if isinstance(mesh, trimesh.Scene):
                # Add all geometries from the sub-scene as children
                for geom_name, mesh_part in mesh.geometry.items():
                    nodes_for_geom = mesh.graph.geometry_nodes.get(geom_name, [])
                    for j, sub_node in enumerate(nodes_for_geom):
                        internal_transform, _ = mesh.graph.get(sub_node)
                        scene.add_geometry(
                            mesh_part,
                            geom_name=f"{node_name}_{geom_name}_{j}",
                            transform=internal_transform,
                            parent_node_name=node_name
                        )
            else:
                # Simple Trimesh - add as child of parent node (same as compose_scenes.py)
                scene.add_geometry(
                    mesh,
                    geom_name=f"{node_name}_geom",
                    parent_node_name=node_name
                )
            
        except Exception as e:
            print(f"Error processing {uid}: {e}")
            import traceback
            traceback.print_exc()
            continue
    
    # Generate and add room geometry (floor, walls, ceiling)
    print("Generating room geometry from boundary polygon...")
    room_geometries = generate_room_geometry(layout, add_floor=add_floor, add_walls=add_walls, add_ceiling=add_ceiling)
    
    for name, geom in room_geometries:
        # Apply the same global rotation to room geometry
        global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
        scene.add_geometry(geom, node_name=name, transform=global_rot)
        print(f"  Added {name} geometry")
    
    if not room_geometries:
        print("  Warning: No room geometry generated (missing boundary_polygon in architecture)")
            
    # Export
    print(f"Exporting scene to {output_path}")
    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    scene.export(output_path)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--input", required=True, help="Input layout JSON file")
    parser.add_argument("--output", required=True, help="Output GLB file")
    parser.add_argument("--no-floor", action="store_true", help="Don't add floor mesh")
    parser.add_argument("--no-walls", action="store_true", help="Don't add wall meshes")
    parser.add_argument("--no-ceiling", action="store_true", help="Don't add ceiling mesh")
    parser.add_argument("--coord-system", type=str, default="z-up", choices=["z-up", "y-up"],
                        help="Input coordinate system (default: z-up)")
    parser.add_argument("--use-normalized", default=True,
                        help="Use pre-normalized asset library (no per-type rotations needed)")
    # 默认路径逻辑:优先 ~/backup,否则 /backup
    _default_normalized_dir = os.environ.get('PTH_ASSET_NORMALIZED_LIBRARY')
    if not _default_normalized_dir:
        _home_path = os.path.expanduser("~/backup/datas/InternScenes/asset_library_normalized")
        _default_normalized_dir = _home_path if os.path.exists(_home_path) else "/backup/datas/InternScenes/asset_library_normalized"
    parser.add_argument("--normalized-dir", type=str, default=_default_normalized_dir,
                        help="Path to normalized asset directory (required if --use-normalized)")
    args = parser.parse_args()
    
    # Validate normalized asset arguments
    if args.use_normalized and not args.normalized_dir:
        parser.error("--normalized-dir is required when using --use-normalized")
    
    compose_scene(
        args.input, 
        args.output,
        add_floor=not args.no_floor,
        add_walls=not args.no_walls,
        add_ceiling=not args.no_ceiling,
        input_coord_system=args.coord_system,
        use_normalized_assets=args.use_normalized,
        normalized_asset_dir=args.normalized_dir
    )