#!/usr/bin/env python3 """ Progressive Visualization of Functional Zones in a 3D Indoor Scene Layout. This script renders a series of images showing zones being added one by one, starting from an empty scene and progressively adding each zone with its assets. Each zone's bounding box can be optionally visualized. Output: - step_0_empty.png: Empty scene (floor only) - step_1_zone_.png: First zone added - step_2_zone_.png: First + second zone - ... - step_N_all_zones.png: All zones with bboxes Materials available: - tiled_wood, herringbone, ceramic_tile, marble_tile, carpet, solid, dark_wood, light_wood """ import os import json import argparse import subprocess import sys import shutil from pathlib import Path from typing import List, Dict, Any, Optional, Tuple from copy import deepcopy import numpy as np import trimesh from trimesh.visual.material import PBRMaterial # Add project root SCRIPT_DIR = Path(__file__).parent REPO_ROOT = SCRIPT_DIR.parent.parent sys.path.insert(0, str(REPO_ROOT)) # Import from visualize_zones from tools.utils.visualize_zones import ( ZONE_COLORS, compute_zone_bbox, compute_all_zone_bboxes, get_scene_bounds, clamp_bbox_to_bounds, create_zone_bbox_glb, run_command, add_zone_labels_to_image, ) # Available floor materials FLOOR_MATERIALS = [ "ceramic_tile", "tiled_wood", "herringbone", "marble_tile", "carpet", "solid", "dark_wood", "light_wood", ] def compose_partial_scene( layout: Dict, zone_indices: List[int], output_path: str, use_retrieval: bool = True, embedding_manager=None, asset_finder=None, ) -> str: """ Compose a scene with only specified zones. Args: layout: Full layout dictionary zone_indices: Indices of zones to include (0-based) output_path: Output GLB path use_retrieval: Whether to run asset retrieval embedding_manager: Pre-initialized embedding manager (optional, for reuse) asset_finder: Pre-initialized asset finder (optional, for reuse) Returns: Path to composed GLB """ from tools.data_gen.compose_generated import compose_scene # Create partial layout with only selected zones partial_layout = deepcopy(layout) all_zones = layout.get('functional_zones', []) # Filter to only the specified zone indices partial_zones = [all_zones[i] for i in zone_indices if i < len(all_zones)] partial_layout['functional_zones'] = partial_zones # Remove top-level assets to avoid duplication partial_layout.pop('assets', None) partial_layout.pop('groups', None) if use_retrieval: from tools.data_gen.layout_retrieval import process_layout # Use provided managers or create new ones if embedding_manager is None or asset_finder is None: from tools.asset_description.asset_embedding_manager import AssetEmbeddingManager from tools.asset_description.asset_finder import AssetFinder asset_library_dir = os.path.join(REPO_ROOT, "data/asset_library") embeddings_file = os.path.join(REPO_ROOT, "tools/asset_embeddings.pkl") embedding_manager = AssetEmbeddingManager(embeddings_file=embeddings_file) asset_finder = AssetFinder(asset_library_dir) partial_layout = process_layout(partial_layout, embedding_manager, asset_finder) # Compose scene compose_scene( layout=partial_layout, output_path=output_path, add_walls=False, add_ceiling=False, ) return output_path def create_single_zone_bbox_glb( zone_info: Dict, output_path: str, scene_bounds: Optional[Dict] = None, face_alpha: float = 0.15, edge_alpha: float = 0.8, edge_radius: float = 0.015, render_faces: bool = True, render_edges: bool = True, ): """ Create a GLB file containing bounding box for a single zone with transparent faces. Args: zone_info: Zone info dict with bbox, color, etc. output_path: Output GLB path scene_bounds: Optional scene bounds to clamp bbox after padding face_alpha: Alpha value for box faces (0.0-1.0, default 0.25) edge_alpha: Alpha value for wireframe edges (0.0-1.0, default 0.8) edge_radius: Radius of edge cylinders (default 0.015m) render_faces: Whether to render transparent box faces (default True) render_edges: Whether to render wireframe edges (default True) """ create_zone_bbox_glb( [zone_info], output_path, scene_bounds=scene_bounds, face_alpha=face_alpha, edge_alpha=edge_alpha, edge_radius=edge_radius, render_faces=render_faces, render_edges=render_edges, ) def create_multi_zone_bbox_glb( zones_info: List[Dict], output_path: str, scene_bounds: Optional[Dict] = None, face_alpha: float = 0.25, edge_alpha: float = 0.8, edge_radius: float = 0.015, render_faces: bool = True, render_edges: bool = True, ): """ Create a GLB file containing bounding boxes for multiple zones with transparent faces. Args: zones_info: List of zone info dicts output_path: Output GLB path scene_bounds: Optional scene bounds to clamp bbox after padding face_alpha: Alpha value for box faces (0.0-1.0, default 0.25) edge_alpha: Alpha value for wireframe edges (0.0-1.0, default 0.8) edge_radius: Radius of edge cylinders (default 0.015m) render_faces: Whether to render transparent box faces (default True) render_edges: Whether to render wireframe edges (default True) """ create_zone_bbox_glb( zones_info, output_path, scene_bounds=scene_bounds, face_alpha=face_alpha, edge_alpha=edge_alpha, edge_radius=edge_radius, render_faces=render_faces, render_edges=render_edges, ) def merge_glb_files(base_glb: str, overlay_glb: str, output_glb: str): """ Merge two GLB files (scene + zone bboxes). Args: base_glb: Base scene GLB path overlay_glb: Overlay GLB (zone bboxes) path output_glb: Output merged GLB path """ try: base_mesh = trimesh.load(base_glb) overlay_mesh = trimesh.load(overlay_glb) if isinstance(base_mesh, trimesh.Scene): if isinstance(overlay_mesh, trimesh.Scene): for name, geom in overlay_mesh.geometry.items(): base_mesh.add_geometry(geom, node_name=f"overlay_{name}") else: base_mesh.add_geometry(overlay_mesh, node_name="overlay") 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") base_mesh = scene base_mesh.export(output_glb) except Exception as e: print(f" Warning: Could not merge GLBs: {e}") shutil.copy(base_glb, output_glb) def render_scene( glb_path: str, output_path: str, zones_info: List[Dict] = None, scene_bounds: Dict = None, show_labels: bool = True, floor_material: str = "ceramic_tile", view_mode: str = "diagonal", width: int = 1600, height: int = 900, engine: str = "BLENDER_EEVEE", samples: int = 64, ): """ Render a GLB scene using Blender and add zone labels. Args: glb_path: Input GLB path output_path: Output PNG path zones_info: List of zone info dicts for label annotation scene_bounds: Dict with 'center' and 'radius' for 3D->2D projection show_labels: Whether to add semantic label text overlays floor_material: Floor material type view_mode: Camera view mode (diagonal, diagonal2, topdown) width: Image width height: Image height engine: Blender render engine samples: Number of samples """ 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 {engine} --samples {samples} " f"--view-mode {view_mode} --auto-crop " f"--floor-material {floor_material}" ) run_command(cmd, env=current_env, quiet=True) # Add zone labels as text overlays if zones_info provided and show_labels is True if show_labels and zones_info and scene_bounds: add_zone_labels_to_image(output_path, zones_info, scene_bounds, view_mode=view_mode) def visualize_zones_progressive( layout_path: str, output_dir: str, floor_material: str = "ceramic_tile", view_mode: str = "diagonal", show_bboxes: bool = True, show_labels: bool = True, use_retrieval: bool = True, render_all_materials: bool = False, render_all_views: bool = False, width: int = 1600, height: int = 900, engine: str = "BLENDER_EEVEE", samples: int = 64, # Zone bbox visualization parameters face_alpha: float = 0.25, edge_alpha: float = 0.8, edge_radius: float = 0.015, render_faces: bool = True, render_edges: bool = True, ): """ Main function: progressively visualize zones being added one by one. Args: layout_path: Path to layout.json file output_dir: Directory to save outputs floor_material: Floor material type (or "all" for all materials) view_mode: Camera view mode show_bboxes: Whether to show zone bounding boxes show_labels: Whether to add semantic label text overlays on rendered images use_retrieval: Whether to run asset retrieval render_all_materials: Whether to render with all available materials render_all_views: Whether to render all view modes (diagonal, diagonal2, topdown) width: Image width height: Image height engine: Blender render engine (BLENDER_EEVEE, CYCLES, etc.) samples: Number of render samples face_alpha: Alpha value for zone bbox faces (0.0-1.0, default 0.25) edge_alpha: Alpha value for zone bbox edges (0.0-1.0, default 0.8) edge_radius: Radius of edge cylinders in meters (default 0.015) render_faces: Whether to render transparent box faces (default True) render_edges: Whether to render wireframe edges (default True) """ print(f"\n{'='*60}") print(f"Progressive Zone Visualization") print(f"{'='*60}") print(f"Input: {layout_path}") print(f"Output: {output_dir}") print(f"Floor Material: {floor_material}") print(f"View Mode: {view_mode}") print(f"Show BBoxes: {show_bboxes}") 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) # Get zones functional_zones = layout.get('functional_zones', []) n_zones = len(functional_zones) if n_zones == 0: print("Error: No functional zones found in layout!") return print(f"Found {n_zones} functional zones:") # Compute zone bboxes using the same logic as visualize_zones.py # This ensures bbox computation is exactly the same print("\nComputing zone bounding boxes...") zones_info = compute_all_zone_bboxes(layout) # zones_info already has correct colors based on original zone indices # Add original_index to track which zone in functional_zones this corresponds to # We need to match zones_info back to functional_zones by zone_id zone_id_to_original_idx = {} for i, zone in enumerate(functional_zones): zone_id = zone.get('id', f'zone_{i}') zone_id_to_original_idx[zone_id] = i for zone_info in zones_info: zone_info['original_index'] = zone_id_to_original_idx.get(zone_info['zone_id'], -1) color = zone_info['color'] color_str = f"RGB({int(color[0]*255)}, {int(color[1]*255)}, {int(color[2]*255)})" print(f" [orig:{zone_info['original_index']}] {zone_info['zone_id']}: {zone_info['semantic_label']} ({zone_info['asset_count']} assets) - {color_str}") if len(zones_info) == 0: print("Error: No valid zones with bbox found!") return n_valid_zones = len(zones_info) # Get scene bounds for clamping bbox visualization scene_bounds = get_scene_bounds(layout) # Calculate scene center and radius for 3D->2D projection import numpy as np scene_min = np.array(scene_bounds['min']) scene_max = np.array(scene_bounds['max']) scene_center_arr = (scene_min + scene_max) / 2.0 scene_radius = np.linalg.norm(scene_max - scene_min) / 2.0 scene_bounds_for_projection = { 'center': scene_center_arr.tolist(), 'radius': float(scene_radius) } # Save zones info zones_info_path = os.path.join(output_dir, "zones_info.json") with open(zones_info_path, 'w') as f: json.dump(zones_info, f, indent=2) print(f"\nSaved zones info to: {zones_info_path}") # Determine materials to render materials_to_render = FLOOR_MATERIALS if render_all_materials else [floor_material] # Determine views to render # 4 diagonal views + 4 side views ALL_VIEWS = ["diagonal", "diagonal2", "diagonal3", "diagonal4", "side_front", "side_back", "side_left", "side_right"] views_to_render = ALL_VIEWS if render_all_views else [view_mode] # Create temp directory for intermediate GLBs temp_dir = os.path.join(output_dir, "_temp") os.makedirs(temp_dir, exist_ok=True) # Initialize embedding manager and asset finder once (for reuse) embedding_manager = None asset_finder = None if use_retrieval: print("\nInitializing asset retrieval system...") from tools.asset_description.asset_embedding_manager import AssetEmbeddingManager from tools.asset_description.asset_finder import AssetFinder asset_library_dir = os.path.join(REPO_ROOT, "data/asset_library") embeddings_file = os.path.join(REPO_ROOT, "tools/asset_embeddings.pkl") embedding_manager = AssetEmbeddingManager(embeddings_file=embeddings_file) asset_finder = AssetFinder(asset_library_dir) print(" Asset retrieval system initialized.") # --- Step 0: Empty scene (floor only) --- print(f"\n[Step 0] Creating empty scene (floor only)...") # Create layout with no zones/assets for floor-only scene empty_layout = deepcopy(layout) empty_layout['functional_zones'] = [] empty_layout.pop('assets', None) empty_layout.pop('groups', None) empty_glb_path = os.path.join(temp_dir, "step_0_empty.glb") from tools.data_gen.compose_generated import compose_scene compose_scene( layout=empty_layout, output_path=empty_glb_path, add_walls=False, add_ceiling=False, ) for mat in materials_to_render: for view in views_to_render: mat_suffix = f"_{mat}" if render_all_materials else "" view_suffix = f"_{view}" if render_all_views else "" render_path = os.path.join(output_dir, f"step_0_empty{view_suffix}{mat_suffix}.png") print(f" Rendering {view} with {mat}...") render_scene( glb_path=empty_glb_path, output_path=render_path, floor_material=mat, view_mode=view, width=width, height=height, engine=engine, samples=samples, zones_info=None, # Empty scene, no zones scene_bounds=None, # No zones to label show_labels=False, # No zones to label ) # --- Steps 1 to N: Add zones progressively --- for step in range(1, n_valid_zones + 1): # Get original zone indices for zones up to this step zone_indices = [zones_info[i]['original_index'] for i in range(step)] current_zone = zones_info[step - 1] zone_id = current_zone['zone_id'] semantic_label = current_zone['semantic_label'] print(f"\n[Step {step}] Adding zone: {zone_id} ({semantic_label})") print(f" Original zone indices: {zone_indices}") # Compose partial scene scene_glb_path = os.path.join(temp_dir, f"step_{step}_scene.glb") compose_partial_scene( layout=layout, zone_indices=zone_indices, output_path=scene_glb_path, use_retrieval=use_retrieval, embedding_manager=embedding_manager, asset_finder=asset_finder, ) # Create zone bbox GLB (for all zones up to this step) if show_bboxes: bbox_glb_path = os.path.join(temp_dir, f"step_{step}_bboxes.glb") current_zones_info = zones_info[:step] create_multi_zone_bbox_glb( current_zones_info, bbox_glb_path, scene_bounds=scene_bounds, face_alpha=face_alpha, edge_alpha=edge_alpha, edge_radius=edge_radius, render_faces=render_faces, render_edges=render_edges, ) # Merge scene with bboxes merged_glb_path = os.path.join(temp_dir, f"step_{step}_merged.glb") merge_glb_files(scene_glb_path, bbox_glb_path, merged_glb_path) render_glb = merged_glb_path else: render_glb = scene_glb_path # Render for mat in materials_to_render: for view in views_to_render: mat_suffix = f"_{mat}" if render_all_materials else "" view_suffix = f"_{view}" if render_all_views else "" render_path = os.path.join(output_dir, f"step_{step}_zone_{zone_id}{view_suffix}{mat_suffix}.png") print(f" Rendering {view} with {mat}...") # Get zones info for labels (zones up to this step) current_zones_info = zones_info[:step] render_scene( glb_path=render_glb, output_path=render_path, floor_material=mat, view_mode=view, width=width, height=height, engine=engine, samples=samples, zones_info=current_zones_info, scene_bounds=scene_bounds_for_projection, show_labels=show_labels, ) # --- Final: Render with all bboxes highlighted --- if show_bboxes: print(f"\n[Final] Rendering complete scene with all zone bboxes...") # Create final bbox GLB final_bbox_glb = os.path.join(temp_dir, "final_bboxes.glb") create_multi_zone_bbox_glb( zones_info, final_bbox_glb, scene_bounds=scene_bounds, face_alpha=face_alpha, edge_alpha=edge_alpha, edge_radius=edge_radius, render_faces=render_faces, render_edges=render_edges, ) # Use last step's scene final_scene_glb = os.path.join(temp_dir, f"step_{n_valid_zones}_scene.glb") final_merged_glb = os.path.join(temp_dir, "final_merged.glb") merge_glb_files(final_scene_glb, final_bbox_glb, final_merged_glb) for mat in materials_to_render: for view in views_to_render: mat_suffix = f"_{mat}" if render_all_materials else "" view_suffix = f"_{view}" if render_all_views else "" render_path = os.path.join(output_dir, f"final_all_zones{view_suffix}{mat_suffix}.png") print(f" Rendering {view} with {mat}...") render_scene( glb_path=final_merged_glb, output_path=render_path, floor_material=mat, view_mode=view, width=width, height=height, engine=engine, samples=samples, zones_info=zones_info, # All zones scene_bounds=scene_bounds_for_projection, show_labels=show_labels, ) # Clean up temp directory (optional - comment out to keep intermediate files) # shutil.rmtree(temp_dir) print(f"\n{'='*60}") print(f"Done! Outputs saved to: {output_dir}") print(f"{'='*60}") # Print legend print("\n=== Zone Color Legend ===") for zone in zones_info: color = zone['color'] color_str = f"RGB({int(color[0]*255)}, {int(color[1]*255)}, {int(color[2]*255)})" print(f" {zone['zone_id']}: {zone['semantic_label']} - {color_str}") print(f"\n=== Output Files ===") for f in sorted(os.listdir(output_dir)): if f.endswith('.png'): print(f" {f}") return zones_info def main(): parser = argparse.ArgumentParser( description="Progressive visualization of functional zones in a 3D scene layout", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Basic usage with default settings (diagonal view, ceramic_tile floor) python visualize_zones_progressive.py --input layout.json --output output_dir # Render with different floor material python visualize_zones_progressive.py --input layout.json --output output_dir --floor-material herringbone # Render all available floor materials python visualize_zones_progressive.py --input layout.json --output output_dir --all-materials # Use diagonal2 view (opposite corner) python visualize_zones_progressive.py --input layout.json --output output_dir --view-mode diagonal2 # Render all views (4 diagonal + 4 side views) python visualize_zones_progressive.py --input layout.json --output output_dir --all-views # Without bounding boxes python visualize_zones_progressive.py --input layout.json --output output_dir --no-bboxes # Use CYCLES engine for higher quality python visualize_zones_progressive.py --input layout.json --output output_dir --engine CYCLES --samples 128 # Full combination: all views + all materials python visualize_zones_progressive.py --input layout.json --output output_dir --all-views --all-materials Available floor materials: tiled_wood, herringbone, ceramic_tile, marble_tile, carpet, solid, dark_wood, light_wood View modes: diagonal, diagonal2, diagonal3, diagonal4 (4 corners), side_front, side_back, side_left, side_right (4 sides), topdown (bird's eye) Engines: BLENDER_EEVEE (fast), CYCLES (high quality) """ ) parser.add_argument("--input", default="case_hq/H-shaped_01_001536_1766364802273481/layout_retrieved/layout_retrieved.json", help="Path to layout.json file") parser.add_argument("--output", default="progressive_zone_output_start", help="Output directory") parser.add_argument("--floor-material", default="tiled_wood", choices=FLOOR_MATERIALS, help="Floor material type (default: ceramic_tile)") parser.add_argument("--all-materials", action="store_true", help="Render with all available floor materials") parser.add_argument("--view-mode", default="diagonal", choices=["diagonal", "diagonal2", "diagonal3", "diagonal4", "side_front", "side_back", "side_left", "side_right", "topdown"], help="Camera view mode (default: diagonal)") parser.add_argument("--all-views", action="store_true", help="Render all view modes (diagonal, diagonal2, topdown)") parser.add_argument("--no-bboxes", dest="show_bboxes", action="store_false", help="Don't show zone bounding boxes") parser.add_argument("--no-labels", dest="show_labels", action="store_false", help="Don't add semantic label text overlays on rendered images") parser.add_argument("--no-retrieval", action="store_true", help="Skip asset retrieval (use existing model_uids)") parser.add_argument("--width", type=int, default=1600, help="Image width (default: 1600)") parser.add_argument("--height", type=int, default=900, help="Image height (default: 900)") parser.add_argument("--engine", default="BLENDER_EEVEE", choices=["BLENDER_EEVEE", "CYCLES", "BLENDER_EEVEE_NEXT"], help="Blender render engine (default: BLENDER_EEVEE)") parser.add_argument("--samples", type=int, default=64, help="Number of render samples (default: 64)") # Zone bbox visualization options parser.add_argument("--face-alpha", type=float, default=0.25, help="Alpha value for zone bbox faces (0.0-1.0, default 0.25)") parser.add_argument("--edge-alpha", type=float, default=0.8, help="Alpha value for zone bbox edges (0.0-1.0, default 0.8)") parser.add_argument("--edge-radius", type=float, default=0.015, help="Radius of edge cylinders in meters (default 0.015)") parser.add_argument("--no-faces", dest="render_faces", action="store_false", default=True, help="Don't render transparent box faces (wireframe only)") parser.add_argument("--no-edges", dest="render_edges", action="store_false", default=True, help="Don't render wireframe edges (faces only)") args = parser.parse_args() visualize_zones_progressive( layout_path=args.input, output_dir=args.output, floor_material=args.floor_material, view_mode=args.view_mode, show_bboxes=args.show_bboxes, show_labels=args.show_labels, use_retrieval=not args.no_retrieval, render_all_materials=args.all_materials, render_all_views=args.all_views, width=args.width, height=args.height, engine=args.engine, samples=args.samples, face_alpha=args.face_alpha, edge_alpha=args.edge_alpha, edge_radius=args.edge_radius, render_faces=args.render_faces, render_edges=args.render_edges, ) if __name__ == "__main__": main()