#!/usr/bin/env python3 # Copyright (c) 2023-2026, AgiBot Inc. All Rights Reserved. # Author: Genie Sim Team # License: Mozilla Public License Version 2.0 import os import glob from pathlib import Path import numpy as np import cv2 from isaacsim import SimulationApp simulation_app = SimulationApp({"headless": True}) import carb import omni.usd import omni.kit.viewport.utility settings = carb.settings.get_settings() settings.set_bool("/rtx/post/aa/alpha", True) # enable alpha settings.set_bool("/rtx/background/visible", False) # hide dome/background settings.set_bool("/app/viewport/grid/enabled", False) settings.set_bool("/app/viewport/showViewportAxis", False) settings.set_bool("/app/viewport/showWireframe", False) settings.set_float("/rtx/post/resample/clearColorR", 0.0) settings.set_float("/rtx/post/resample/clearColorG", 0.0) settings.set_float("/rtx/post/resample/clearColorB", 0.0) settings.set_float("/rtx/post/resample/clearColorA", 0.0) settings.set_bool("/app/viewport/showGizmos", False) settings.set_bool("/gui/ui/visible", False) settings.set_bool("/rtx/post/tonemap/enabled", False) # Tonemapping can bake alpha to 1.0 settings.set_bool("/rtx/post/composite/enabled", True) settings.set_bool("/rtx/post/dlss/execMode", 0) # DLSS can interfere with alpha settings.set_bool("/rtx/domeLight/cameraVisible", False) settings.set_int("/rtx/rendermode", 0) from omni.isaac.core.utils.stage import open_stage from pxr import UsdLux, UsdGeom, Sdf, Gf import sys from geniesim_assets import ASSETS_INDEX, ASSETS_PATH def render_thumbnails(usd_path: str, visualization_path: Path): usd_path = str(Path(usd_path).resolve()) print(f"Opening: {usd_path}") os.makedirs(visualization_path, exist_ok=True) # Open the stage open_stage(usd_path) # 2. Add Lighting (CRITICAL for non-black images) # The builtin utility just captures pixels; it does not auto-light the scene. # We must add a light if the scene doesn't have one. stage = omni.usd.get_context().get_stage() # Create a Dome Light dome_light = UsdLux.DomeLight.Define(stage, Sdf.Path("/World/DomwLight")) dome_light.GetEnableColorTemperatureAttr().Set(True) dome_light.GetColorTemperatureAttr().Set(6150.0) dome_light.GetIntensityAttr().Set(1) dome_light.GetExposureAttr().Set(9.0) dome_light.GetPrim().CreateAttribute("cameraVisibility", Sdf.ValueTypeNames.Bool).Set(False) dome_light.GetPrim().CreateAttribute("visibleInPrimaryRay", Sdf.ValueTypeNames.Bool).Set(False) xform_dome = UsdGeom.Xformable(dome_light) xform_dome.ClearXformOpOrder() # Ensure a clean slate xform_dome.AddTranslateOp().Set(Gf.Vec3d(0, 0, 305)) # Create a Distant Light (Sun) distant_light = UsdLux.DistantLight.Define(stage, Sdf.Path("/World/DistantLight")) # Apply your specific parameters distant_light.GetIntensityAttr().Set(1.0) distant_light.GetExposureAttr().Set(10.0) distant_light.GetAngleAttr().Set(0.53) # Set Temperature (Must enable colorTemperature first) distant_light.GetEnableColorTemperatureAttr().Set(True) distant_light.GetColorTemperatureAttr().Set(7250.0) # CRITICAL: Ensure this light doesn't create a solid background distant_light.GetPrim().CreateAttribute("visibleInPrimaryRay", Sdf.ValueTypeNames.Bool).Set(False) xform_dist = UsdGeom.Xformable(distant_light) xform_dist.ClearXformOpOrder() xform_dist.AddTranslateOp().Set(Gf.Vec3d(0, 0, 305)) # AddRotateXYZOp is specifically for the (Roll, Pitch, Yaw) in XYZ sequence xform_dist.AddRotateXYZOp().Set(Gf.Vec3f(55, 0, 135)) # 3. Warmup Render Loop # We must step the physics/render engine to let textures load print(" -> Warming up engine...") for _ in range(20): # Reduced from 50 to 20 simulation_app.update() # Setup output directory # out_dir = Path(usd_path).parent / "thumbnails" out_dir = visualization_path / "snapshot" out_dir.mkdir(exist_ok=True) # 4. Capture from Cameras # Find all cameras in the stage cameras = [] for prim in stage.Traverse(): if prim.IsA(UsdGeom.Camera) and prim.GetTypeName() == "Camera" and "/World/Camera" in prim.GetPath().pathString: cameras.append(prim.GetPath().pathString) if not cameras: # If no cameras, create a default one looking at origin? print(" -> No cameras found in stage.") return # Find the object prim to rotate object_prim_path = "/World/object" object_prim = stage.GetPrimAtPath(object_prim_path) if not object_prim.IsValid(): print(f" -> Object prim not found at {object_prim_path}") return # Get the active viewport to switch cameras viewport_api = omni.kit.viewport.utility.get_active_viewport() viewport_api.resolution = (720, 720) # Rotation angles: 0, 60, 120, 180, 240, 300 degrees (6 angles) rotation_angles = [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330] # Store all captured images for video creation all_images = [] # List of (camera_idx, rotation_idx, image_path) for i, cam_path in enumerate(cameras): # Switch Viewport to this camera viewport_api.set_active_camera(cam_path) for _ in range(5): # Reduced from 10 to 5 simulation_app.update() # Rotate object and capture at each angle for rot_idx, angle_deg in enumerate(rotation_angles): # Apply rotation around Z-axis xform = UsdGeom.Xformable(object_prim) xform.ClearXformOpOrder() angle_rad = np.radians(angle_deg) rot_quat = Gf.Quatf(np.cos(angle_rad / 2.0), 0.0, 0.0, np.sin(angle_rad / 2.0)) xform.AddOrientOp().Set(rot_quat) for _ in range(5): # Reduced from 10 to 5 simulation_app.update() # Define output path for this rotation out_path = out_dir / f"Camera{i+1}_rot{rot_idx:02d}.png" if out_path.exists(): os.remove(str(out_path)) # Capture the viewport print(f" -> Capturing {cam_path} at rotation {angle_deg}°") omni.kit.viewport.utility.capture_viewport_to_file( viewport_api=viewport_api, file_path=str(out_path), is_hdr=False, ) # Wait for the file to actually write (reduced max wait time) frames_waited = 0 while not out_path.exists() and frames_waited < 50: # Reduced from 100 to 50 simulation_app.update() frames_waited += 1 if out_path.exists(): all_images.append((i, rot_idx, str(out_path))) # Create videos for each camera video_dir = out_dir.parent / "video" video_dir.mkdir(exist_ok=True) individual_video_paths = [] for i, cam_path in enumerate(cameras): # Collect all images for this camera, sorted by rotation index camera_data = [(rot_idx, img_path) for cam_idx, rot_idx, img_path in all_images if cam_idx == i] camera_data.sort(key=lambda x: x[0]) camera_images = [img_path for _, img_path in camera_data] if not camera_images: continue # Create video from images video_path = video_dir / f"Camera{i+1}.mp4" if video_path.exists(): os.remove(str(video_path)) print(f" -> Creating video for Camera{i+1} from {len(camera_images)} images") # Read first image to get dimensions first_img = cv2.imread(camera_images[0]) if first_img is None: continue height, width = first_img.shape[:2] fps = 6 # Increased from 2 to 6 for faster playback (3x speed) # Create video writer fourcc = cv2.VideoWriter_fourcc(*"mp4v") video_writer = cv2.VideoWriter(str(video_path), fourcc, fps, (width, height)) # Write all frames (optimized: read and write in one loop) for img_path in camera_images: img = cv2.imread(img_path) if img is not None: video_writer.write(img) video_writer.release() print(f" -> Video saved to {video_path}") individual_video_paths.append(str(video_path)) # Create merged video from all cameras (or single camera) if len(individual_video_paths) >= 1: print(f" -> Creating merged video from {len(individual_video_paths)} camera(s)") # Read first video to get dimensions and fps first_cap = cv2.VideoCapture(individual_video_paths[0]) if first_cap.isOpened(): width = int(first_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(first_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = first_cap.get(cv2.CAP_PROP_FPS) first_cap.release() merged_video_path = video_dir / "merged.mp4" if merged_video_path.exists(): os.remove(str(merged_video_path)) fourcc = cv2.VideoWriter_fourcc(*"mp4v") merged_writer = cv2.VideoWriter(str(merged_video_path), fourcc, fps, (width, height)) # Read and write frames from each video sequentially total_frames = 0 for video_path in individual_video_paths: cap = cv2.VideoCapture(video_path) if cap.isOpened(): while True: ret, frame = cap.read() if not ret: break merged_writer.write(frame) total_frames += 1 cap.release() merged_writer.release() print(f" -> Merged video saved ({total_frames} frames)") # Delete individual camera videos after merging for video_path in individual_video_paths: try: if os.path.exists(video_path): os.remove(video_path) print(f" -> Deleted {Path(video_path).name}") except Exception as e: print(f" -> Failed to delete {video_path}: {e}") def main(): # Find all recorder.usda files usds = glob.glob(f"{ASSETS_PATH}/**/recorder.usda", recursive=True) for idx, usd in enumerate(usds): asset_id = Path(usd).parent.name visualization_path = ASSETS_PATH / "extra" / "visualization" / asset_id video_path = visualization_path / "video" / "merged.mp4" if os.path.exists(video_path): continue print(f"{idx+1}/{len(usds)}") render_thumbnails(usd, visualization_path) if __name__ == "__main__": main() simulation_app.close()