"""NVIDIA Omniverse Kit Visualizer Extension for Warehouse Robot Fleet Digital Twin. Provides interactive trajectory playback, real-time stage prim transform updates, status beacon color indicators, and fleet operational HUD inside Omniverse Kit. """ from __future__ import annotations import json import logging import os import sys import time from pathlib import Path from typing import Any, Dict, List, Optional, Tuple # Attempt Omniverse Kit imports with graceful fallback for headless testing try: import carb import omni.ext import omni.kit.app import omni.ui as ui import omni.usd from pxr import Gf, UsdGeom, Vt HAS_KIT = True ExtBase = omni.ext.IExt except ImportError: HAS_KIT = False class ExtBase: # type: ignore pass # Discover repository root dynamically and ensure src is on sys.path _p = Path(__file__).resolve() REPO_ROOT: Optional[Path] = None while _p != _p.parent: _candidate = _p / "src" if (_candidate / "warehouse_twin").exists(): REPO_ROOT = _p _src_str = str(_candidate) if _src_str not in sys.path: sys.path.insert(0, _src_str) break _p = _p.parent if REPO_ROOT is None: _fb = Path("/home/dmhai/warehouse-digital-twin") if (_fb / "src" / "warehouse_twin").exists(): REPO_ROOT = _fb _fb_str = str(_fb / "src") if _fb_str not in sys.path: sys.path.insert(0, _fb_str) # Import core simulation visualization player from warehouse_twin.visualization.trajectory_player import ( RobotPlaybackState, TrajectoryData, TrajectoryPlayer, interpolate_robot_state, ) class WarehouseVisualizerExtension(ExtBase): """Main Omniverse Kit Extension managing trajectory playback, stage switching, and fleet HUD.""" FROZEN_WORKLOAD_PATH = "data/input/demo_orders.csv" FROZEN_WORKLOAD_SHA256 = "f4eff4790759dd243337db1ec3c57ea41546f7f4db47d642acdb3708702ba238" FROZEN_WORKLOAD_TASKS = 86 def __init__(self) -> None: super().__init__() self._repo_root: Path = REPO_ROOT or Path("/home/dmhai/warehouse-digital-twin").resolve() self._window: Any = None self._menu_item: Any = None self._player: Optional[TrajectoryPlayer] = None self._update_sub: Any = None self._last_wall_time: float = 0.0 self._trajectory_path: str = "" self._status_label: Any = None self._time_slider: Any = None self._time_label: Any = None self._speed_label: Any = None self._robot_labels: Dict[str, Any] = {} self.is_active: bool = False # Staged Demo HUD state self._selected_stage: int = 1 self._stage_info_label: Any = None self._kpi_thru_label: Any = None self._kpi_turnaround_label: Any = None self._kpi_distance_label: Any = None self._kpi_energy_label: Any = None self._kpi_conflicts_label: Any = None self._kpi_wait_label: Any = None self._kpi_tasks_label: Any = None self._stage_data_cache: Dict[int, Dict[str, Any]] = {} self._stage_event_sub: Any = None def on_startup(self, ext_id: str) -> None: """Invoked when the Omniverse Kit extension is activated.""" print(f"[omni.warehouse.twin.visualizer] Starting up extension: {ext_id}") self.is_active = True self._last_wall_time = time.time() # Pre-cache staged demo metrics self._load_staged_data() # Locate default trajectory file if available default_traj = (self._repo_root / "results/demo_staged/stage_01_baseline/trajectory.json").resolve() if not default_traj.exists(): default_traj = (self._repo_root / "results/demo/initial/trajectory.json").resolve() if not default_traj.exists(): default_traj = (self._repo_root / "results/trajectories/trajectory_default.json").resolve() if default_traj.exists(): self.load_trajectory(str(default_traj)) # Build UI if Kit UI is available if HAS_KIT: self._build_ui() self._start_update_loop() self._subscribe_stage_events() self._register_menu() def on_shutdown(self) -> None: """Invoked when the Omniverse Kit extension is deactivated. Guarantees clean resource teardown.""" print("[omni.warehouse.twin.visualizer] Shutting down extension and releasing subscriptions") self.is_active = False # Unregister custom Kit menu item self._unregister_menu() # 1. Cancel Kit update loop and stage event subscriptions if self._update_sub is not None: self._update_sub = None if self._stage_event_sub is not None: self._stage_event_sub = None # 2. Halt playback and clear player callbacks if self._player is not None: self._player.cleanup() self._player = None # 3. Destroy UI Window if self._window is not None: self._window.destroy() self._window = None self._robot_labels.clear() def _register_menu(self) -> None: """Add menu item under Window to toggle HUD window visibility.""" try: import omni.kit.menu.utils def _toggle_menu_cb(): if self._window is not None: self._window.visible = not self._window.visible if self._window.visible: self._window.focus() else: self._build_ui() self._menu_item = [ omni.kit.menu.utils.MenuItemDescription( name="Warehouse Twin Visualizer & Optimization HUD", onclick_fn=_toggle_menu_cb, ) ] omni.kit.menu.utils.add_menu_items(self._menu_item, "Window") print("[omni.warehouse.twin.visualizer] Registered menu item: Window -> Warehouse Twin Visualizer & Optimization HUD") except Exception as e: self._menu_item = None print(f"[omni.warehouse.twin.visualizer] Menu registration note: {e}") def _unregister_menu(self) -> None: """Unregister menu item on extension shutdown.""" if hasattr(self, "_menu_item") and self._menu_item: try: import omni.kit.menu.utils omni.kit.menu.utils.remove_menu_items(self._menu_item, "Window") except Exception: pass self._menu_item = None def _subscribe_stage_events(self) -> None: """Subscribe to USD Context stage open events to auto-detect loaded stage.""" if not HAS_KIT: return try: usd_context = omni.usd.get_context() self._stage_event_sub = usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="omni.warehouse.twin.visualizer.stage_event" ) print("[omni.warehouse.twin.visualizer] Subscribed to USD stage open events.") except Exception as e: print(f"[omni.warehouse.twin.visualizer] Failed to subscribe to stage events: {e}") def _on_stage_event(self, event: Any) -> None: """Auto-detect active stage when a USD file is loaded in Omniverse Kit.""" if not HAS_KIT: return try: if event.type == int(omni.usd.StageEventType.OPENED): stage_url = omni.usd.get_context().get_stage_url() or "" print(f"[omni.warehouse.twin.visualizer] USD Stage Opened: {stage_url}") if "stage_03_1" in stage_url or "efficiency" in stage_url: self.select_stage(4) self.load_current_stage_trajectory() elif "stage_03" in stage_url or "stage_03_final" in stage_url: self.select_stage(3) self.load_current_stage_trajectory() elif "stage_02" in stage_url: self.select_stage(2) elif "stage_01" in stage_url or "baseline" in stage_url: self.select_stage(1) self.load_current_stage_trajectory() # Ensure HUD window is visible and focused if self._window is not None: self._window.visible = True try: self._window.focus() except Exception: pass except Exception as e: print(f"[omni.warehouse.twin.visualizer] Error in stage event handler: {e}") def _load_staged_data(self) -> None: """Inspect demo output directories and load KPI data for HUD display.""" base_paths = [ self._repo_root / "results/demo_staged", self._repo_root / "results/demo", self._repo_root / "results/demonstration/staged_demo", Path("results/demo_staged").resolve(), Path("results/demo").resolve(), ] active_base = None for bp in base_paths: if bp.exists(): active_base = bp break if not active_base: return # Stage 1 s1_dirs = [active_base / "stage_01_baseline", active_base / "initial"] for d in s1_dirs: kpi_p = d / "kpis.json" if (d / "kpis.json").exists() else (d / "kpi_summary.json") if kpi_p.exists(): try: with open(kpi_p, "r", encoding="utf-8") as f: kpi_data = json.load(f) usd_p = active_base / "usd" / "stage_01_baseline.usda" if not usd_p.exists(): usd_p = d / "warehouse.usda" traj_p = d / "trajectory.json" self._stage_data_cache[1] = { "name": "Stage 1: Centralized Baseline", "kpis": kpi_data, "usd": str(usd_p) if usd_p.exists() else "", "trajectory": str(traj_p) if traj_p.exists() else "", "coordination": "Passive Conflict Monitoring (Unmitigated)", "chargers": "8 Bays (Centralized NW Cluster)", "slotting": "Default Catalog Layout", } break except Exception: pass # Stage 2 s2_dirs = [active_base / "stage_02_optimization_progress", active_base / "optimizing"] for d in s2_dirs: cand_p = d / "candidate_results.json" if cand_p.exists(): try: with open(cand_p, "r", encoding="utf-8") as f: cand_data = json.load(f) usd_p = active_base / "usd" / "stage_02_optimization_progress.usda" if not usd_p.exists(): usd_p = d / "warehouse.usda" self._stage_data_cache[2] = { "name": "Stage 2: Systematic 5-Candidate Search", "candidates": cand_data, "usd": str(usd_p) if usd_p.exists() else "", "trajectory": "", "coordination": "Preventive Coordination Active Across All Candidates", "chargers": "Decentralized Zone Placement Tested", "slotting": "Velocity ABC Slotting Evaluated", } break except Exception: pass # Stage 3 s3_dirs = [active_base / "stage_03_final_optimized", active_base / "optimized"] for d in s3_dirs: kpi_p = d / "kpis.json" if (d / "kpis.json").exists() else (d / "kpi_summary.json") if kpi_p.exists(): try: with open(kpi_p, "r", encoding="utf-8") as f: kpi_data = json.load(f) usd_p = active_base / "usd" / "stage_03_final_optimized.usda" if not usd_p.exists(): usd_p = d / "warehouse.usda" traj_p = d / "trajectory.json" self._stage_data_cache[3] = { "name": "Stage 3: Hybrid Optimal Facility", "kpis": kpi_data, "usd": str(usd_p) if usd_p.exists() else "", "trajectory": str(traj_p) if traj_p.exists() else "", "coordination": "Preventive Traffic Coordination (0 Unresolved)", "chargers": "8 Bays (Decentralized Zones A, B, C)", "slotting": "Velocity ABC Slotting (-21.5% Distance)", } break except Exception: pass # Stage 3.1: Efficiency-Optimized Hybrid Facility s3_1_dirs = [active_base / "stage_03_1_efficiency_optimized", active_base / "stage_03_1"] for d in s3_1_dirs: kpi_p = d / "kpis.json" if (d / "kpis.json").exists() else (d / "kpi_summary.json") if kpi_p.exists(): try: with open(kpi_p, "r", encoding="utf-8") as f: kpi_data = json.load(f) usd_p = active_base / "usd" / "stage_03_1_efficiency_optimized.usda" if not usd_p.exists(): usd_p = d / "warehouse_efficiency_optimized.usda" traj_p = d / "trajectory.json" self._stage_data_cache[4] = { "name": "Stage 3.1: Efficiency-Optimized Hybrid Facility", "kpis": kpi_data, "usd": str(usd_p) if usd_p.exists() else "", "trajectory": str(traj_p) if traj_p.exists() else "", "coordination": "Dedicated Northbound Arterial & Preventive Traffic Coordination (0 Unresolved)", "chargers": "8 Bays (Decentralized 3/3/2 Across Zones A, B, C)", "slotting": "Velocity ABC Slotting (-33.8% Travel Distance)", } break except Exception: pass def select_stage(self, stage_num: int) -> None: """Select active demonstration stage and refresh HUD indicators.""" self._selected_stage = stage_num self._load_staged_data() data = self._stage_data_cache.get(stage_num) if not data: if self._stage_info_label: self._stage_info_label.text = f"Stage {stage_num}: No simulation telemetry loaded yet." return if self._stage_info_label: self._stage_info_label.text = f"{data['name']}\n{data.get('coordination', '')}" if stage_num in (1, 3, 4): kpi = data.get("kpis", {}) thru = kpi.get("throughput_tasks_per_hour", 0.0) tt = kpi.get("turnaround_time") or kpi.get("turnaround_time_seconds") or {} t_mean = tt.get("mean", 0.0) if isinstance(tt, dict) else 0.0 t_p50 = tt.get("p50", 0.0) if isinstance(tt, dict) else (float(tt) if isinstance(tt, (int, float)) else 0.0) t_p90 = tt.get("p90", 0.0) if isinstance(tt, dict) else (float(tt) if isinstance(tt, (int, float)) else 0.0) conflicts = kpi.get("conflicts_detected", 0) unresolved = kpi.get("unresolved_conflicts", 0) wait = kpi.get("total_yield_wait_time_seconds", kpi.get("total_yield_wait_seconds", 0.0)) tasks_comp = kpi.get("tasks_completed", kpi.get("completed_tasks", 0)) tasks_tot = kpi.get("tasks_created", kpi.get("total_tasks", self.FROZEN_WORKLOAD_TASKS)) dist = kpi.get("total_travel_distance_meters", kpi.get("total_distance_meters", 0.0)) empty_dist = kpi.get("empty_travel_distance_meters", 0.0) loaded_dist = kpi.get("loaded_travel_distance_meters", 0.0) energy = kpi.get("total_energy_consumed_kwh", kpi.get("total_energy_kwh", 0.0)) energy_per_task = kpi.get("energy_intensity_kwh_per_task", 0.0) if self._kpi_thru_label: self._kpi_thru_label.text = f"Throughput: {thru:.1f} tasks/hr" if self._kpi_turnaround_label: self._kpi_turnaround_label.text = f"Turnaround: mean={t_mean:.1f}s | p50={t_p50:.1f}s | p90={t_p90:.1f}s" if self._kpi_distance_label: self._kpi_distance_label.text = f"Travel Distance: {dist:.1f}m (Loaded: {loaded_dist:.1f}m | Empty: {empty_dist:.1f}m)" if self._kpi_energy_label: self._kpi_energy_label.text = f"Fleet Energy: {energy:.4f} kWh ({energy_per_task:.4f} kWh/task)" if self._kpi_conflicts_label: self._kpi_conflicts_label.text = f"Conflicts: {conflicts} detected | {unresolved} unmitigated" if self._kpi_wait_label: self._kpi_wait_label.text = f"Yield Contention Wait: {wait:.2f}s" if self._kpi_tasks_label: self._kpi_tasks_label.text = f"Tasks: {tasks_comp}/{tasks_tot} completed" elif stage_num == 2: cands = data.get("candidates", []) cand_count = len(cands) if self._kpi_thru_label: self._kpi_thru_label.text = f"Candidates Evaluated: {cand_count} architectures" if self._kpi_turnaround_label: self._kpi_turnaround_label.text = "Variants: Baseline, Decentr Charger, Highways, Slotting, Hybrid" if self._kpi_distance_label: self._kpi_distance_label.text = "Circulation: One-Way High-Speed Perimeter Arterials" if self._kpi_energy_label: self._kpi_energy_label.text = "Charging: Decentralized 3-Zone Clusters (A, B, C)" if self._kpi_conflicts_label: self._kpi_conflicts_label.text = "Traffic Policy: Preventive Arbitration on all candidates" if self._kpi_wait_label: self._kpi_wait_label.text = "Winning Selection: Candidate 5 (Hybrid Optimal Facility)" if self._kpi_tasks_label: self._kpi_tasks_label.text = f"Workload: {self.FROZEN_WORKLOAD_TASKS} frozen tasks tested" if self._window is not None: self._window.visible = True try: self._window.focus() except Exception: pass def open_current_stage_usd(self) -> None: """Open the selected stage's OpenUSD scene in Omniverse Kit viewport.""" data = self._stage_data_cache.get(self._selected_stage, {}) usd_path = data.get("usd", "") if not usd_path or not Path(usd_path).exists(): print(f"[omni.warehouse.twin.visualizer] Stage USD not found: {usd_path}") if self._status_label: self._status_label.text = "Stage USD file not found." return if HAS_KIT: try: omni.usd.get_context().open_stage(str(Path(usd_path).resolve())) print(f"[omni.warehouse.twin.visualizer] Opened USD scene in Kit: {usd_path}") if self._status_label: self._status_label.text = f"Loaded Stage {self._selected_stage} USD" except Exception as e: print(f"[omni.warehouse.twin.visualizer] Error opening USD stage: {e}") def load_current_stage_trajectory(self) -> None: """Load selected stage's trajectory file into the visualizer player.""" data = self._stage_data_cache.get(self._selected_stage, {}) traj_path = data.get("trajectory", "") if not traj_path or not Path(traj_path).exists(): print(f"[omni.warehouse.twin.visualizer] Trajectory file not found for Stage {self._selected_stage}: {traj_path}") if self._status_label: self._status_label.text = "Stage trajectory not found." return self.load_trajectory(traj_path) def load_trajectory(self, filepath: str) -> bool: """Load and initialize trajectory data from JSON file.""" try: path = Path(filepath).resolve() if not path.exists(): print(f"[omni.warehouse.twin.visualizer] File not found: {path}") if self._status_label: self._status_label.text = f"File not found: {path.name}" return False data = TrajectoryData.from_file(path) self._player = TrajectoryPlayer(data, playback_speed=1.0, loop=True) self._trajectory_path = str(path) print( f"[omni.warehouse.twin.visualizer] Loaded trajectory: {len(data.robots)} AMRs, " f"{data.get_point_count()} points, duration: {data.duration:.1f}s" ) if self._status_label: self._status_label.text = f"Loaded {len(data.robots)} AMRs ({data.duration:.0f}s)" if self._time_slider: self._time_slider.max = data.duration self._time_slider.value = 0.0 # Seek to start and apply initial frame self.seek(0.0) return True except Exception as err: print(f"[omni.warehouse.twin.visualizer] Failed to load trajectory: {err}") if self._status_label: self._status_label.text = f"Error: {err}" return False def play(self) -> None: """Resume or start trajectory playback.""" if self._player: self._last_wall_time = time.time() self._player.play() if self._status_label: self._status_label.text = "Playback: Playing" def pause(self) -> None: """Pause trajectory playback.""" if self._player: self._player.pause() if self._status_label: self._status_label.text = "Playback: Paused" def reset(self) -> None: """Reset trajectory playback to origin timestamp.""" if self._player: self._player.reset() self._update_stage_prims(self._player.get_fleet_state()) self._update_ui_state(self._player.get_fleet_state()) if self._status_label: self._status_label.text = "Playback: Reset" def seek(self, sim_time: float) -> None: """Seek to a specific simulation time.""" if self._player: state = self._player.seek(sim_time) self._update_stage_prims(state) self._update_ui_state(state) def set_speed(self, speed: float) -> None: """Set playback speed multiplier.""" if self._player: self._player.set_speed(speed) if self._speed_label: self._speed_label.text = f"{speed:.1f}x" def _start_update_loop(self) -> None: """Subscribe to Kit frame update stream.""" if not HAS_KIT: return app = omni.kit.app.get_app() self._update_sub = app.get_update_event_stream().create_subscription_to_pop( self._on_kit_update, name="omni.warehouse.twin.visualizer.update" ) def _on_kit_update(self, event: Any) -> None: """Kit per-frame callback: advances playback time and updates USD stage.""" now = time.time() dt = max(0.0, min(0.1, now - self._last_wall_time)) self._last_wall_time = now if self._player and self._player.is_playing: fleet_state = self._player.advance(dt) self._update_stage_prims(fleet_state) self._update_ui_state(fleet_state) def _update_stage_prims(self, fleet_state: Dict[str, RobotPlaybackState]) -> None: """Drive OpenUSD prim transformations and visual indicators on the active Kit stage.""" if not HAS_KIT: return stage = omni.usd.get_context().get_stage() if stage is None: return for r_id, state in fleet_state.items(): prim_path = f"/World/Robots/{r_id}" prim = stage.GetPrimAtPath(prim_path) if not prim.IsValid(): continue # 1. Update Position & Orientation trans_attr = prim.GetAttribute("xformOp:translate") if trans_attr.IsValid(): elev_z = 0.225 if "heavy" in r_id else 0.175 trans_attr.Set(Gf.Vec3d(state.x, state.y, elev_z)) rot_attr = prim.GetAttribute("xformOp:rotateXYZ") if rot_attr.IsValid(): rot_attr.Set(Gf.Vec3d(0.0, 0.0, state.yaw_degrees)) # 2. Update Status Beacon Color dome_prim = stage.GetPrimAtPath(f"{prim_path}/StatusDome") if dome_prim.IsValid(): color_attr = dome_prim.GetAttribute("primvars:displayColor") if color_attr.IsValid(): r, g, b = state.status_color color_attr.Set(Vt.Vec3fArray([Gf.Vec3f(r, g, b)])) # 3. Update Carried Payload Visibility payload_prim = stage.GetPrimAtPath(f"{prim_path}/Payload") if payload_prim.IsValid(): vis_attr = payload_prim.GetAttribute("visibility") if vis_attr.IsValid(): vis_attr.Set("inherited" if state.is_loaded else "invisible") def _update_ui_state(self, fleet_state: Dict[str, RobotPlaybackState]) -> None: """Synchronize UI sliders, labels, and fleet HUD table.""" if not self._player: return cur_t = self._player.current_time dur = max(1.0, self._player.duration) # Update Time Label if self._time_label: cur_fmt = time.strftime("%H:%M:%S", time.gmtime(cur_t)) tot_fmt = time.strftime("%H:%M:%S", time.gmtime(dur)) self._time_label.text = f"{cur_fmt} / {tot_fmt}" # Update Slider without triggering re-entrant seek if self._time_slider and abs(self._time_slider.value - cur_t) > 0.5: self._time_slider.value = cur_t # Update Robot HUD entries for r_id, state in fleet_state.items(): if r_id in self._robot_labels: lbl = self._robot_labels[r_id] load_str = "LOADED" if state.is_loaded else "EMPTY" lbl.text = ( f"{state.state:<14} | Bat: {state.battery_percent:>5.1f}% | " f"{load_str:<6} | ({state.x:>5.1f}, {state.y:>5.1f})" ) def _build_ui(self) -> None: """Construct the interactive Omniverse UI window with Staged Demo HUD.""" self._window = ui.Window("Warehouse Twin Visualizer & Optimization HUD", width=480, height=640) self._window.visible = True try: self._window.focus() except Exception: pass print("[omni.warehouse.twin.visualizer] Built and displayed Warehouse Twin Visualizer & Optimization HUD window.") with self._window.frame: with ui.VStack(spacing=6): ui.Label("Warehouse Digital Twin: 3-Stage Optimization", style={"font_size": 18, "font_weight": "bold"}) # Section 1: Frozen Workload & Fleet Configuration Card with ui.CollapsableFrame("Workload & Fleet Specification", collapsed=False): with ui.VStack(spacing=3): ui.Label(f"Workload: {self.FROZEN_WORKLOAD_PATH} ({self.FROZEN_WORKLOAD_TASKS} orders)", style={"color": 0xFF00DDFF}) ui.Label(f"SHA-256: {self.FROZEN_WORKLOAD_SHA256[:20]}...", style={"color": 0xFF888888, "font_size": 11}) ui.Label("Fleet: 10 AMRs (5 Light amr_light_01..05 + 5 Heavy amr_heavy_01..05)") ui.Label("Charging: 8 Charging Bays (charge_bay_1..08 in all stages)") # Section 2: Stage Selector & KPI Scorecard with ui.CollapsableFrame("Three-Stage Optimization & KPI Scorecard", collapsed=False): with ui.VStack(spacing=4): with ui.HStack(height=32): ui.Button("Stage 1: Baseline", clicked_fn=lambda: self.select_stage(1)) ui.Button("Stage 2: Candidates", clicked_fn=lambda: self.select_stage(2)) ui.Button("Stage 3: Optimal", clicked_fn=lambda: self.select_stage(3)) ui.Button("Stage 3.1: Efficiency", clicked_fn=lambda: self.select_stage(4)) self._stage_info_label = ui.Label("Select a stage above to view metrics", style={"font_size": 13, "font_weight": "bold"}) self._kpi_thru_label = ui.Label("Throughput: --") self._kpi_turnaround_label = ui.Label("Turnaround: --") self._kpi_distance_label = ui.Label("Travel Distance: --") self._kpi_energy_label = ui.Label("Fleet Energy: --") self._kpi_conflicts_label = ui.Label("Conflicts: --") self._kpi_wait_label = ui.Label("Yield Wait: --") self._kpi_tasks_label = ui.Label("Tasks: --") with ui.HStack(height=28): ui.Button("Load USD Scene in Kit", clicked_fn=self.open_current_stage_usd) ui.Button("Load Stage Trajectory", clicked_fn=self.load_current_stage_trajectory) ui.Line() # Section 3: Interactive Trajectory Playback ui.Label("Dynamic Kinematic AMR Playback", style={"font_size": 15, "font_weight": "bold"}) self._status_label = ui.Label("No trajectory loaded", style={"color": 0xFF888888}) # Playback Controls with ui.HStack(height=32): ui.Button("▶ Play", clicked_fn=self.play) ui.Button("⏸ Pause", clicked_fn=self.pause) ui.Button("⏮ Reset", clicked_fn=self.reset) # Speed Multipliers with ui.HStack(height=24): ui.Label("Speed:", width=50) for spd in [0.5, 1.0, 2.0, 5.0, 10.0]: def make_spd_fn(s=spd): return lambda: self.set_speed(s) ui.Button(f"{spd}x", clicked_fn=make_spd_fn(spd), width=45) self._speed_label = ui.Label("1.0x", width=40) # Time Scrubber with ui.HStack(height=28): self._time_label = ui.Label("00:00:00 / 00:00:00", width=140) self._time_slider = ui.FloatSlider(min=0.0, max=100.0, step=1.0) def on_slider_changed(model): self.seek(model.as_float) self._time_slider.model.add_value_changed_fn(on_slider_changed) ui.Line() # Section 4: AMR Fleet Live Telemetry (10 AMRs) ui.Label("Active AMR Fleet Telemetry (10 Robots)", style={"font_size": 13}) with ui.ScrollingFrame(height=140): with ui.VStack(spacing=3): if self._player: for r_id in self._player.data.get_robot_ids(): with ui.HStack(): ui.Label(f"[{r_id}]", width=110, style={"font_weight": "bold"}) self._robot_labels[r_id] = ui.Label("IDLE | Bat: 100.0% | EMPTY | (0.0, 0.0)") # Initialize with Stage 1 self.select_stage(1)