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 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Visualize collision between 3D assets in a scene layout.
Finds a pair of colliding assets and renders them with a red transparent bounding box
highlighting the collision region.
"""

import os
import json
import argparse
import subprocess
import sys
import tempfile
import shutil
import numpy as np
import trimesh
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple
from copy import deepcopy

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

from trimesh.visual.material import PBRMaterial


def get_asset_position_size(asset: Dict) -> Tuple[Optional[List[float]], Optional[List[float]]]:
    """
    Extract position and size from asset, handling different data formats.
    """
    pos = None
    size = None
    
    # Try transform format first
    if 'transform' in asset:
        transform = asset['transform']
        pos = transform.get('pos') or transform.get('position')
        size = transform.get('size')
    
    # Fallback to direct fields
    if pos is None:
        pos = asset.get('pos') or asset.get('position')
    if size is None:
        size = asset.get('size')
    
    return pos, size


def get_asset_rotation(asset: Dict) -> Optional[List[float]]:
    """Extract rotation from asset."""
    rot = None
    if 'transform' in asset:
        rot = asset['transform'].get('rot')
    if rot is None:
        rot = asset.get('rot')
    return rot


def compute_bbox_intersection(pos1: List, size1: List, pos2: List, size2: List) -> Optional[Dict]:
    """
    Compute the intersection bounding box between two objects.
    Returns None if no intersection, otherwise returns the intersection bbox.
    """
    # Object 1 bounds
    min1 = [pos1[i] - size1[i]/2 for i in range(3)]
    max1 = [pos1[i] + size1[i]/2 for i in range(3)]
    
    # Object 2 bounds
    min2 = [pos2[i] - size2[i]/2 for i in range(3)]
    max2 = [pos2[i] + size2[i]/2 for i in range(3)]
    
    # Calculate intersection bounds
    inter_min = [max(min1[i], min2[i]) for i in range(3)]
    inter_max = [min(max1[i], max2[i]) for i in range(3)]
    
    # Check if there's actually an intersection
    for i in range(3):
        if inter_min[i] >= inter_max[i]:
            return None
    
    # Calculate intersection volume
    volume = (inter_max[0] - inter_min[0]) * (inter_max[1] - inter_min[1]) * (inter_max[2] - inter_min[2])
    
    return {
        'min': inter_min,
        'max': inter_max,
        'center': [(inter_min[i] + inter_max[i]) / 2 for i in range(3)],
        'size': [inter_max[i] - inter_min[i] for i in range(3)],
        'volume': volume
    }


def compute_object_volume(size: List) -> float:
    """Compute volume of an object given its size."""
    return size[0] * size[1] * size[2]


def size_similarity(size1: List, size2: List) -> float:
    """
    Compute similarity between two sizes (0-1, higher is more similar).
    Uses ratio of smaller to larger volume.
    """
    vol1 = compute_object_volume(size1)
    vol2 = compute_object_volume(size2)
    if vol1 == 0 or vol2 == 0:
        return 0.0
    return min(vol1, vol2) / max(vol1, vol2)


def find_collision_pairs(layout: Dict, min_collision_volume: float = 0.001) -> List[Dict]:
    """
    Find all pairs of colliding assets in the layout.
    
    Returns list of collision info dicts sorted by:
    1. Size similarity (more similar sizes preferred)
    2. Collision volume (larger collisions preferred)
    """
    # Flatten all assets
    assets = []
    
    if "assets" in layout:
        for asset in layout["assets"]:
            assets.append(asset)
    
    if "functional_zones" in layout:
        for zone in layout["functional_zones"]:
            for asset in zone.get("assets", []):
                assets.append(asset)
    
    if "groups" in layout:
        for group in layout["groups"]:
            for obj in group.get("objects", []):
                assets.append(obj)
    
    # Find all collision pairs
    collision_pairs = []
    
    for i, asset1 in enumerate(assets):
        pos1, size1 = get_asset_position_size(asset1)
        if pos1 is None or size1 is None:
            continue
        if all(s == 0 for s in size1):
            continue
            
        for j, asset2 in enumerate(assets):
            if j <= i:  # Avoid duplicates and self-collision
                continue
                
            pos2, size2 = get_asset_position_size(asset2)
            if pos2 is None or size2 is None:
                continue
            if all(s == 0 for s in size2):
                continue
            
            # Check for intersection
            intersection = compute_bbox_intersection(pos1, size1, pos2, size2)
            
            if intersection and intersection['volume'] >= min_collision_volume:
                similarity = size_similarity(size1, size2)
                
                collision_pairs.append({
                    'asset1': asset1,
                    'asset2': asset2,
                    'asset1_idx': i,
                    'asset2_idx': j,
                    'pos1': pos1,
                    'size1': size1,
                    'pos2': pos2,
                    'size2': size2,
                    'intersection': intersection,
                    'size_similarity': similarity,
                    'collision_volume': intersection['volume'],
                })
    
    # Sort by collision volume (descending) - largest collision first
    collision_pairs.sort(key=lambda x: x['collision_volume'], reverse=True)
    
    return collision_pairs


def create_collision_bbox_glb(intersection: Dict, output_path: str):
    """
    Create a GLB file with a semi-transparent red bounding box for the collision region.
    """
    min_pt = np.array(intersection['min'])
    max_pt = np.array(intersection['max'])
    
    # Global rotation matrix (same as compose_generated.py)
    global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
    
    # Create a solid box for the collision region
    center = (min_pt + max_pt) / 2
    size = max_pt - min_pt
    
    # Create box mesh
    box = trimesh.creation.box(extents=size)
    box.apply_translation(center)
    box.apply_transform(global_rot)
    
    # Apply semi-transparent red material
    # Red with ~70% opacity for better visibility
    red_material = PBRMaterial(
        baseColorFactor=[255, 30, 30, 200],  # RGBA: bright red with alpha=200 (~78% opacity)
        metallicFactor=0.0,
        roughnessFactor=0.5,
        alphaMode='BLEND',
    )
    box.visual = trimesh.visual.TextureVisuals(material=red_material)
    
    # Export
    scene = trimesh.Scene()
    scene.add_geometry(box, node_name="collision_region")
    scene.export(output_path)
    print(f"  Created collision bbox GLB: {output_path}")


def create_object_bbox_glb(pos: List, size: List, color: Tuple, output_path: str, label: str = "object"):
    """
    Create a GLB file with a wireframe bounding box for an object.
    """
    min_pt = np.array([pos[i] - size[i]/2 for i in range(3)])
    max_pt = np.array([pos[i] + size[i]/2 for i in range(3)])
    
    # Global rotation matrix
    global_rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
    
    scene = trimesh.Scene()
    
    # Create wireframe edges
    vertices = np.array([
        [min_pt[0], min_pt[1], min_pt[2]],
        [max_pt[0], min_pt[1], min_pt[2]],
        [max_pt[0], max_pt[1], min_pt[2]],
        [min_pt[0], max_pt[1], min_pt[2]],
        [min_pt[0], min_pt[1], max_pt[2]],
        [max_pt[0], min_pt[1], max_pt[2]],
        [max_pt[0], max_pt[1], max_pt[2]],
        [min_pt[0], max_pt[1], max_pt[2]],
    ])
    
    edges = [
        [0, 1], [1, 2], [2, 3], [3, 0],
        [4, 5], [5, 6], [6, 7], [7, 4],
        [0, 4], [1, 5], [2, 6], [3, 7],
    ]
    
    rgba = [int(c * 255) for c in color] + [255]
    material = PBRMaterial(
        baseColorFactor=rgba,
        metallicFactor=0.0,
        roughnessFactor=0.5,
    )
    
    edge_radius = 0.015
    
    for i, edge in enumerate(edges):
        start = vertices[edge[0]]
        end = vertices[edge[1]]
        segment = end - start
        length = np.linalg.norm(segment)
        
        if length < 0.001:
            continue
        
        cylinder = trimesh.creation.cylinder(radius=edge_radius, height=length, sections=8)
        
        direction = segment / length
        z_axis = np.array([0, 0, 1])
        
        if np.allclose(direction, z_axis):
            rotation = np.eye(4)
        elif np.allclose(direction, -z_axis):
            rotation = trimesh.transformations.rotation_matrix(np.pi, [1, 0, 0])
        else:
            axis = np.cross(z_axis, direction)
            axis = axis / np.linalg.norm(axis)
            angle = np.arccos(np.clip(np.dot(z_axis, direction), -1, 1))
            rotation = trimesh.transformations.rotation_matrix(angle, axis)
        
        midpoint = (start + end) / 2
        translation = trimesh.transformations.translation_matrix(midpoint)
        
        cylinder.apply_transform(rotation)
        cylinder.apply_transform(translation)
        cylinder.apply_transform(global_rot)
        cylinder.visual = trimesh.visual.TextureVisuals(material=material)
        
        scene.add_geometry(cylinder, node_name=f"{label}_edge_{i}")
    
    scene.export(output_path)
    print(f"  Created object bbox GLB: {output_path}")


def compose_collision_scene(asset1: Dict, asset2: Dict, output_path: str):
    """
    Compose a scene with only the two colliding assets.
    """
    from tools.data_gen.compose_generated import compose_scene
    
    # Create a minimal layout with just these two assets
    layout = {
        "meta": {"scene_type": "collision_vis"},
        "architecture": {"boundary_polygon": []},  # No boundary needed
        "assets": [asset1, asset2]
    }
    
    compose_scene(
        layout=layout,
        output_path=output_path,
        add_floor=False,
        add_walls=False,
        add_ceiling=False,
    )
    print(f"  Composed collision scene: {output_path}")


def merge_glb_files(base_path: str, overlay_path: str, output_path: str):
    """Merge two GLB files."""
    base_mesh = trimesh.load(base_path)
    overlay_mesh = trimesh.load(overlay_path)
    
    if isinstance(base_mesh, trimesh.Scene):
        scene = base_mesh
    else:
        scene = trimesh.Scene()
        scene.add_geometry(base_mesh, node_name="base")
    
    if isinstance(overlay_mesh, trimesh.Scene):
        for name, geom in overlay_mesh.geometry.items():
            scene.add_geometry(geom, node_name=f"overlay_{name}")
    else:
        scene.add_geometry(overlay_mesh, node_name="overlay")
    
    scene.export(output_path)


def run_command(cmd, env=None, quiet=False):
    """Run a shell command."""
    print(f"  Running: {cmd[:100]}...")
    try:
        if quiet:
            subprocess.check_call(cmd, shell=True, env=env,
                                  stdout=subprocess.DEVNULL,
                                  stderr=subprocess.DEVNULL)
        else:
            subprocess.check_call(cmd, shell=True, env=env)
        return True
    except subprocess.CalledProcessError as e:
        print(f"  Command failed: {e}")
        return False


def render_scene(glb_path: str, output_path: str, view_mode: str = "diagonal",
                 width: int = 1200, height: int = 900):
    """Render a GLB scene using Blender."""
    current_env = os.environ.copy()
    
    cmd = (
        f"conda run -n blender python InternScenes/InternScenes_Real2Sim/blender_renderer.py "
        f"--input '{glb_path}' "
        f"--output '{output_path}' "
        f"--width {width} --height {height} "
        f"--engine BLENDER_EEVEE --samples 64 "
        f"--view-mode {view_mode} --auto-crop "
        f"--floor-material solid "
        f"--diagonal-distance 2.0 "  # Farther view for better overview
        f"--camera-factor 1.5 "  # Wider angle
    )
    
    run_command(cmd, env=current_env, quiet=True)


def visualize_collision(
    layout_path: str,
    output_dir: str,
    collision_idx: int = 0,
    render_views: List[str] = None,
):
    """
    Main function to visualize collision between assets.
    
    Args:
        layout_path: Path to layout.json file
        output_dir: Directory to save outputs
        collision_idx: Index of collision pair to visualize (0 = best match)
        render_views: List of view modes to render
    """
    if render_views is None:
        render_views = ["diagonal", "diagonal2"]
    
    print(f"\n{'='*60}")
    print(f"Collision Visualization")
    print(f"{'='*60}")
    print(f"Input: {layout_path}")
    print(f"Output: {output_dir}")
    print(f"{'='*60}\n")
    
    # Load layout
    with open(layout_path, 'r') as f:
        layout = json.load(f)
    
    # Create output directory
    os.makedirs(output_dir, exist_ok=True)
    
    # Find collision pairs
    print("Finding collision pairs...")
    collision_pairs = find_collision_pairs(layout)
    
    if not collision_pairs:
        print("No collisions found in this layout!")
        return
    
    print(f"Found {len(collision_pairs)} collision pairs")
    
    # Save all collision pairs info
    collision_info_path = os.path.join(output_dir, "collision_pairs.json")
    collision_info = []
    for i, pair in enumerate(collision_pairs):
        info = {
            'index': i,
            'asset1_category': pair['asset1'].get('category', 'unknown'),
            'asset2_category': pair['asset2'].get('category', 'unknown'),
            'asset1_description': pair['asset1'].get('description', '')[:50] + '...',
            'asset2_description': pair['asset2'].get('description', '')[:50] + '...',
            'collision_volume': pair['collision_volume'],
            'size_similarity': pair['size_similarity'],
            'intersection': pair['intersection'],
        }
        collision_info.append(info)
        print(f"  [{i}] {info['asset1_category']} vs {info['asset2_category']}: "
              f"vol={pair['collision_volume']:.4f}, sim={pair['size_similarity']:.2f}")
    
    with open(collision_info_path, 'w') as f:
        json.dump(collision_info, f, indent=2)
    print(f"\nSaved collision info to: {collision_info_path}")
    
    # Select collision pair to visualize
    if collision_idx >= len(collision_pairs):
        print(f"Warning: collision_idx {collision_idx} out of range, using 0")
        collision_idx = 0
    
    pair = collision_pairs[collision_idx]
    print(f"\nVisualizing collision pair [{collision_idx}]:")
    print(f"  Asset 1: {pair['asset1'].get('category', 'unknown')}")
    print(f"  Asset 2: {pair['asset2'].get('category', 'unknown')}")
    print(f"  Collision volume: {pair['collision_volume']:.4f}")
    print(f"  Size similarity: {pair['size_similarity']:.2f}")
    
    # Create temp directory
    temp_dir = os.path.join(output_dir, "_temp")
    os.makedirs(temp_dir, exist_ok=True)
    
    # Step 1: Compose scene with just the two assets
    print("\nComposing collision scene...")
    scene_glb = os.path.join(temp_dir, "collision_scene.glb")
    compose_collision_scene(pair['asset1'], pair['asset2'], scene_glb)
    
    # Step 2: Create collision region bbox (red transparent) - only this, no object bboxes
    print("\nCreating collision region bbox...")
    collision_glb = os.path.join(temp_dir, "collision_region.glb")
    create_collision_bbox_glb(pair['intersection'], collision_glb)
    
    # Step 3: Merge scene with collision bbox only
    print("\nMerging scene components...")
    final_glb = os.path.join(temp_dir, "final.glb")
    merge_glb_files(scene_glb, collision_glb, final_glb)
    
    # Copy final GLB to output
    final_output_glb = os.path.join(output_dir, "collision_scene.glb")
    shutil.copy(final_glb, final_output_glb)
    print(f"  Final GLB saved to: {final_output_glb}")
    
    # Step 5: Render
    print("\nRendering...")
    for view in render_views:
        render_path = os.path.join(output_dir, f"collision_{view}.png")
        print(f"  Rendering {view} view...")
        render_scene(final_glb, render_path, view_mode=view)
    
    # Clean up
    # shutil.rmtree(temp_dir)  # Uncomment to clean up temp files
    
    print(f"\n{'='*60}")
    print(f"Done! Outputs saved to: {output_dir}")
    print(f"{'='*60}")
    
    return pair


def main():
    parser = argparse.ArgumentParser(description="Visualize collision between 3D assets")
    parser.add_argument("--input", 
                        default="test_vis_output6/3rscan_422885ce-192d-25fc-851a-df2d675a6559_fine/layout_retrieved.json",
                        help="Path to layout.json file")
    parser.add_argument("--output", default="collision_vis_output", help="Output directory")
    parser.add_argument("--collision-idx", type=int, default=0,
                        help="Index of collision pair to visualize (0 = best size match)")
    parser.add_argument("--all-views", action="store_true",
                        help="Render all view modes (diagonal, diagonal2, side views)")
    
    args = parser.parse_args()
    
    views = ["diagonal", "diagonal2"]
    if args.all_views:
        views = ["diagonal", "diagonal2", "side_front", "side_back", "side_left", "side_right"]
    
    visualize_collision(
        layout_path=args.input,
        output_dir=args.output,
        collision_idx=args.collision_idx,
        render_views=views,
    )


if __name__ == "__main__":
    main()