feat(phase-7): implement OpenUSD animation, trajectory player, and Omniverse Kit extension
This commit is contained in:
@@ -5,6 +5,36 @@ All notable changes to the Warehouse Robot Fleet Digital Twin will be documented
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [0.8.0] - 2026-10-21
|
||||||
|
|
||||||
|
### Added - Phase 7: NVIDIA Omniverse USD 3D Visualization & Trajectory Playback
|
||||||
|
- **Continuous Spatial Interpolation & Playback Engine** (`warehouse_twin.visualization.trajectory_player`):
|
||||||
|
- Linear Cartesian interpolation of position coordinates $(X, Y, Z)$ between simulation waypoints.
|
||||||
|
- Shortest-arc circular angular interpolation of heading angle (`yaw_degrees`) with $-180^\circ \leftrightarrow 180^\circ$ wrap-around handling.
|
||||||
|
- Continuous battery SoC interpolation and discrete payload cargo attachment.
|
||||||
|
- Complete playback state machine (`play`, `pause`, `toggle`, `reset`, `seek`, `advance`, `set_speed`) supporting $0.5\times$ to $50.0\times$ speeds.
|
||||||
|
- Safe subscriber callback registration and leak-free unregistration.
|
||||||
|
- **Time-Sampled OpenUSD Scene Generator** (`warehouse_twin.visualization.animated_usd`):
|
||||||
|
- Direct export of time-sampled OpenUSD ASCII stages (`warehouse_phase7_animated.usda`).
|
||||||
|
- Native playback support via Omniverse Kit's timeline (`omni.timeline`) without extension dependencies.
|
||||||
|
- Time-sampled translation (`xformOp:translate.timeSamples`) and rotation (`xformOp:rotateXYZ.timeSamples`).
|
||||||
|
- Dynamic status dome color samples (`primvars:displayColor.timeSamples`) reflecting robot operational states.
|
||||||
|
- Dynamic battery LED bar color samples reflecting battery health.
|
||||||
|
- Dynamic payload carton box visibility samples (`visibility.timeSamples`).
|
||||||
|
- **NVIDIA Omniverse Kit 110.4 Extension** (`omni.warehouse.twin.visualizer`):
|
||||||
|
- Native Kit extension (`omni.ext.IExt`) compatible with Kit 110.4.
|
||||||
|
- Interactive UI Window (`omni.ui.Window`): trajectory file loader, playback buttons, scrub slider, speed selectors, and live AMR fleet HUD table.
|
||||||
|
- Frame-by-frame stage prim transformation updates driven by Kit's update loop (`omni.kit.app.get_app().get_update_event_stream()`).
|
||||||
|
- Clean shutdown handler guaranteeing zero dangling update callbacks or lingering subscriptions.
|
||||||
|
- Symlinked directly into Kit release `exts/` directory for automatic discovery.
|
||||||
|
- **CLI Subcommands**:
|
||||||
|
- `warehouse-twin export-usd --trajectory <path> --output <path>`: Generates time-sampled animated USD scenes.
|
||||||
|
- `warehouse-twin play-trajectory <path> --step <secs>`: Validates kinematics and previews fleet playback in terminal.
|
||||||
|
- Updated `validate-env` to detect host Kit at `/home/dmhai/Desktop/nvidia-omniverse/kit-app-template`.
|
||||||
|
- **Unit Test Suite**:
|
||||||
|
- Added 8 unit tests across `test_trajectory_player.py`, `test_animated_usd.py`, and `test_kit_extension.py`.
|
||||||
|
- Expanded test suite to **137 passed unit tests (100% pass rate in 1.01s)**.
|
||||||
|
|
||||||
## [0.7.0] - 2026-10-21
|
## [0.7.0] - 2026-10-21
|
||||||
|
|
||||||
### Added - Phase 6: Analytics and Experiment Framework
|
### Added - Phase 6: Analytics and Experiment Framework
|
||||||
|
|||||||
+43
-7
@@ -1,7 +1,7 @@
|
|||||||
# Project Status: Warehouse Robot Fleet Digital Twin
|
# Project Status: Warehouse Robot Fleet Digital Twin
|
||||||
|
|
||||||
**Last Updated**: October 21, 2026
|
**Last Updated**: October 21, 2026
|
||||||
**Current Phase**: **Phase 6: Analytics and Experiment Framework (COMPLETED)**
|
**Current Phase**: **Phase 7: Omniverse USD Visualization (COMPLETED)**
|
||||||
**Status**: Ready for User Review and Approval
|
**Status**: Ready for User Review and Approval
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -16,13 +16,46 @@
|
|||||||
| **Phase 3** | **Discrete-event simulation** | **COMPLETED** | **72 passed** |
|
| **Phase 3** | **Discrete-event simulation** | **COMPLETED** | **72 passed** |
|
||||||
| **Phase 4** | **Routing and fleet assignment** | **COMPLETED** | **95 passed** |
|
| **Phase 4** | **Routing and fleet assignment** | **COMPLETED** | **95 passed** |
|
||||||
| **Phase 5** | **Charging and operational constraints** | **COMPLETED** | **110 passed** |
|
| **Phase 5** | **Charging and operational constraints** | **COMPLETED** | **110 passed** |
|
||||||
| **Phase 6** | **Analytics and experiment framework** | **COMPLETED** | **129 passed (100%)** |
|
| **Phase 6** | **Analytics and experiment framework** | **COMPLETED** | **129 passed** |
|
||||||
| Phase 7 | Omniverse USD visualization | Planned (Next) | - |
|
| **Phase 7** | **Omniverse USD visualization** | **COMPLETED** | **137 passed (100%)** |
|
||||||
| Phase 8 | Operational dashboard | Planned | - |
|
| Phase 8 | Operational dashboard | Planned (Next) | - |
|
||||||
| Phase 9 | Optimization and final demonstration | Planned | - |
|
| Phase 9 | Optimization and final demonstration | Planned | - |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 2. Completed Tasks (Phase 7)
|
||||||
|
|
||||||
|
- [x] Implemented Continuous Spatial Interpolation & Playback Engine (`src/warehouse_twin/visualization/trajectory_player.py`):
|
||||||
|
- Linear Cartesian interpolation between simulation waypoints.
|
||||||
|
- Shortest-arc circular angular interpolation of heading angle (`yaw_degrees`) with $-180^\circ \leftrightarrow 180^\circ$ wrap-around handling.
|
||||||
|
- Continuous battery SoC interpolation and discrete payload cargo attachment.
|
||||||
|
- Complete playback state machine (`play`, `pause`, `toggle`, `reset`, `seek`, `advance`, `set_speed`) supporting $0.5\times$ to $50.0\times$ speeds.
|
||||||
|
- Safe subscriber callback registration and leak-free unregistration.
|
||||||
|
- Unit test suite: 4 passed in `tests/unit/test_trajectory_player.py`.
|
||||||
|
- [x] Implemented Time-Sampled OpenUSD Scene Generator (`src/warehouse_twin/visualization/animated_usd.py`):
|
||||||
|
- Direct export of time-sampled OpenUSD ASCII stages (`warehouse_phase7_animated.usda`).
|
||||||
|
- Native playback support via Omniverse Kit's timeline (`omni.timeline`) without extension dependencies.
|
||||||
|
- Time-sampled translation (`xformOp:translate.timeSamples`) and rotation (`xformOp:rotateXYZ.timeSamples`).
|
||||||
|
- Dynamic status dome color samples (`primvars:displayColor.timeSamples`) reflecting robot operational states.
|
||||||
|
- Dynamic battery LED bar color samples reflecting battery health.
|
||||||
|
- Dynamic payload carton box visibility samples (`visibility.timeSamples`).
|
||||||
|
- Unit test suite: 2 passed in `tests/unit/test_animated_usd.py`.
|
||||||
|
- [x] Implemented NVIDIA Omniverse Kit 110.4 Extension (`omniverse/extensions/omni.warehouse.twin.visualizer`):
|
||||||
|
- Native Kit extension (`omni.ext.IExt`) compatible with Kit 110.4.
|
||||||
|
- Interactive UI Window (`omni.ui.Window`): trajectory file loader, playback buttons, scrub slider, speed selectors, and live AMR fleet HUD table.
|
||||||
|
- Frame-by-frame stage prim transformation updates driven by Kit's update loop (`omni.kit.app.get_app().get_update_event_stream()`).
|
||||||
|
- Clean shutdown handler guaranteeing zero dangling update callbacks or lingering subscriptions.
|
||||||
|
- Symlinked directly into Kit release `exts/` directory for automatic discovery.
|
||||||
|
- Unit test suite: 2 passed in `tests/unit/test_kit_extension.py`.
|
||||||
|
- [x] CLI Subcommands Added & Enhanced (`src/warehouse_twin/cli.py`):
|
||||||
|
- `warehouse-twin export-usd --trajectory <path> --output <path>`: Generates time-sampled animated USD scenes.
|
||||||
|
- `warehouse-twin play-trajectory <path> --step <secs>`: Validates kinematics and previews fleet playback in terminal.
|
||||||
|
- Updated `validate-env` to detect host Kit at `/home/dmhai/Desktop/nvidia-omniverse/kit-app-template`.
|
||||||
|
- [x] Documentation & Changelog: Created `docs/phases/phase_7_omniverse_usd_visualization.md`, updated `CHANGELOG.md`, `README.md`, and `omniverse/README.md`.
|
||||||
|
- [x] Test Suite: Expanded to **137 passed unit tests (100% pass rate in 1.01s)**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 2. Completed Tasks (Phase 6)
|
## 2. Completed Tasks (Phase 6)
|
||||||
|
|
||||||
- [x] Implemented Comprehensive KPI Calculator (`src/warehouse_twin/analytics/kpi_calculator.py`):
|
- [x] Implemented Comprehensive KPI Calculator (`src/warehouse_twin/analytics/kpi_calculator.py`):
|
||||||
@@ -59,10 +92,10 @@
|
|||||||
|
|
||||||
## 3. Test & Validation Summary
|
## 3. Test & Validation Summary
|
||||||
|
|
||||||
- **Total Unit Tests Executed**: 129
|
- **Total Unit Tests Executed**: 137
|
||||||
- **Passed**: 129
|
- **Passed**: 137
|
||||||
- **Failed**: 0
|
- **Failed**: 0
|
||||||
- **Execution Time**: ~0.99 seconds
|
- **Execution Time**: ~1.01 seconds
|
||||||
- **Test Suites**:
|
- **Test Suites**:
|
||||||
- `test_environment.py`: 5 passed
|
- `test_environment.py`: 5 passed
|
||||||
- `test_logging.py`: 3 passed
|
- `test_logging.py`: 3 passed
|
||||||
@@ -89,6 +122,9 @@
|
|||||||
- `test_heatmap.py`: 4 passed
|
- `test_heatmap.py`: 4 passed
|
||||||
- `test_experiment_runner.py`: 4 passed
|
- `test_experiment_runner.py`: 4 passed
|
||||||
- `test_scenario_comparison.py`: 2 passed
|
- `test_scenario_comparison.py`: 2 passed
|
||||||
|
- `test_trajectory_player.py`: 4 passed
|
||||||
|
- `test_animated_usd.py`: 2 passed
|
||||||
|
- `test_kit_extension.py`: 2 passed
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -93,8 +93,15 @@ The system decouples discrete-event simulation from 3D visualization, enabling d
|
|||||||
- [x] Experiment execution & scenario comparison framework (`ExperimentRunner`, `ScenarioComparator`, Monte Carlo multi-seed execution, fleet size sweeps).
|
- [x] Experiment execution & scenario comparison framework (`ExperimentRunner`, `ScenarioComparator`, Monte Carlo multi-seed execution, fleet size sweeps).
|
||||||
- [x] Comprehensive unit test suite (129 passed in 0.97s).
|
- [x] Comprehensive unit test suite (129 passed in 0.97s).
|
||||||
|
|
||||||
|
### Completed - Phase 7: NVIDIA Omniverse USD 3D Visualization
|
||||||
|
- [x] Time-sampled OpenUSD animation stage generator (`AnimatedUSDGenerator`, `warehouse_phase7_animated.usda`).
|
||||||
|
- [x] Native timeline scrubbing and playback in Omniverse Kit with zero extension dependencies.
|
||||||
|
- [x] Continuous trajectory player and spatial interpolator (`TrajectoryPlayer`, angular wrap-around handling, continuous battery SoC).
|
||||||
|
- [x] Interactive Omniverse Kit 110.4 extension (`omni.warehouse.twin.visualizer`, `omni.ui.Window`, live fleet HUD, playback controls).
|
||||||
|
- [x] Synchronized visual indicators (Status dome glow, battery health LED, cargo box attachment).
|
||||||
|
- [x] Comprehensive unit test suite (137 passed in 1.01s).
|
||||||
|
|
||||||
### Planned Roadmap
|
### Planned Roadmap
|
||||||
- **Phase 7**: NVIDIA Omniverse USD 3D visualization and trajectory playback (Planned - Next).
|
|
||||||
- **Phase 8**: Interactive operational dashboard.
|
- **Phase 8**: Interactive operational dashboard.
|
||||||
- **Phase 9**: Optimization scenarios, layout variations, and final demonstration.
|
- **Phase 9**: Optimization scenarios, layout variations, and final demonstration.
|
||||||
|
|
||||||
@@ -106,7 +113,7 @@ The system decouples discrete-event simulation from 3D visualization, enabling d
|
|||||||
- **Python**: Python 3.12 (Host has 3.12.3; compatible with >= 3.10).
|
- **Python**: Python 3.12 (Host has 3.12.3; compatible with >= 3.10).
|
||||||
- **Core Dependencies**: `simpy` 4.1.2, `networkx` 3.7, `pytest` 9.1.1.
|
- **Core Dependencies**: `simpy` 4.1.2, `networkx` 3.7, `pytest` 9.1.1.
|
||||||
- **NVIDIA GPU**: NVIDIA GeForce RTX 5090 (Driver 580.178.04, CUDA 13.0).
|
- **NVIDIA GPU**: NVIDIA GeForce RTX 5090 (Driver 580.178.04, CUDA 13.0).
|
||||||
- **NVIDIA Omniverse Kit**: Kit 110.4.0 (located at `/home/dmhai/nvidia-omniverse/kit-app-template`).
|
- **NVIDIA Omniverse Kit**: Kit 110.4.0 (located at `/home/dmhai/Desktop/nvidia-omniverse/kit-app-template`).
|
||||||
- **Isaac Sim**: **NOT required**. The core simulation operates completely independently of Isaac Sim.
|
- **Isaac Sim**: **NOT required**. The core simulation operates completely independently of Isaac Sim.
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -209,19 +216,31 @@ The primary drive (`/`) has constrained free space (~8.9 GB free). To prevent di
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 9. Omniverse Visualization (Phase 7 Preview)
|
## 9. Omniverse Visualization (Phase 7)
|
||||||
|
|
||||||
The visualizer connects via file-based trajectory playback:
|
The visualizer connects via file-based trajectory playback and time-sampled OpenUSD scenes:
|
||||||
- Simulation writes time-stamped Cartesian coordinates to `results/trajectories/`.
|
|
||||||
- Omniverse Kit 110.4 loads the warehouse USD stage (`omniverse/scenes/`) and moves robot prims along the scheduled trajectory.
|
### Option A: Native OpenUSD Timeline Playback (Zero Extensions Required)
|
||||||
- Run command (available in Phase 7):
|
1. Generate the animated OpenUSD scene:
|
||||||
```bash
|
```bash
|
||||||
/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit /home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/apps/warehouse_twin.kit --ext-folder omniverse/extensions
|
warehouse-twin export-usd \
|
||||||
```
|
--trajectory results/trajectories/trajectory_default.json \
|
||||||
|
--output omniverse/scenes/warehouse_phase7_animated.usda
|
||||||
|
```
|
||||||
|
2. Launch Omniverse Kit:
|
||||||
|
```bash
|
||||||
|
/home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/warehouse_twin.kit.sh
|
||||||
|
```
|
||||||
|
3. Open `omniverse/scenes/warehouse_phase7_animated.usda` via `File -> Open` and click **Play** (or press `Spacebar`) on the timeline toolbar!
|
||||||
|
|
||||||
|
### Option B: Interactive Trajectory Playback Extension
|
||||||
|
1. Launch Omniverse Kit.
|
||||||
|
2. Open `omniverse/scenes/warehouse_phase7.usda`.
|
||||||
|
3. The `omni.warehouse.twin.visualizer` window automatically provides Play/Pause controls, time scrubbing slider, speed multipliers ($0.5\times$ to $10.0\times$), and real-time fleet telemetry HUD.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 10. Current Implementation Phase
|
## 10. Current Implementation Phase
|
||||||
|
|
||||||
**Current Phase**: **Phase 1: Warehouse Model (Completed)**.
|
**Current Phase**: **Phase 7: Omniverse USD Visualization (COMPLETED)**.
|
||||||
**Next Phase**: **Phase 2: Robot and Task Models** (Awaiting user confirmation).
|
**Next Phase**: **Phase 8: Operational Dashboard** (Planned).
|
||||||
|
|||||||
@@ -0,0 +1,149 @@
|
|||||||
|
# Phase 7: NVIDIA Omniverse USD 3D Visualization and Trajectory Playback
|
||||||
|
|
||||||
|
## 1. Executive Summary & Objectives
|
||||||
|
|
||||||
|
Phase 7 delivers the complete 3D visualization and simulation playback layer for the Warehouse Robot Fleet Digital Twin using **OpenUSD** and **NVIDIA Omniverse Kit 110.4**.
|
||||||
|
|
||||||
|
The primary design principle is **clean architectural decoupling**:
|
||||||
|
- The discrete-event simulation engine remains 100% headless, fast, and pure Python (zero heavy graphics or Isaac Sim dependencies during simulation runs).
|
||||||
|
- Simulation runs export standardized, time-stamped trajectory recordings (`results/trajectories/trajectory_*.json`).
|
||||||
|
- Visualization operates in two complementary modes:
|
||||||
|
1. **Natively Animated OpenUSD (`warehouse_phase7_animated.usda`)**: Time-sampled kinematic tracks (`xformOp:translate.timeSamples`, `xformOp:rotateXYZ.timeSamples`, `primvars:displayColor.timeSamples`, and `visibility.timeSamples`) that can be opened and scrubbed in Omniverse Kit's timeline or any standard USD tool (usdview, Blender, Unreal Engine) with zero extension dependencies.
|
||||||
|
2. **Interactive Omniverse Kit Extension (`omni.warehouse.twin.visualizer`)**: An interactive UI window within Kit that provides live trajectory playback controls (Play, Pause, Reset, Seek, Speed Multipliers $0.5\times$ to $10.0\times$), real-time stage prim transform updates, state beacon color indicators, and a live fleet operational HUD.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Host Environment & Kit 110.4 Integration
|
||||||
|
|
||||||
|
Inspection of the host system verified:
|
||||||
|
- **Kit Executable**: `/home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit`
|
||||||
|
- **Application Target**: `warehouse_twin.kit` launched via:
|
||||||
|
```bash
|
||||||
|
/home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/warehouse_twin.kit.sh
|
||||||
|
```
|
||||||
|
- **Kit Kernel Version**: `110.4.0+feature.386251.187cf21b.gl`
|
||||||
|
- **Extension Symlink**: Automatically linked to `_build/linux-x86_64/release/exts/omni.warehouse.twin.visualizer` for immediate runtime discovery.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Architecture & Delivered Modules
|
||||||
|
|
||||||
|
```
|
||||||
|
warehouse-digital-twin/
|
||||||
|
├── src/warehouse_twin/
|
||||||
|
│ ├── interfaces/
|
||||||
|
│ │ └── usd_generator.py # Static OpenUSD facility & fleet scene generator
|
||||||
|
│ └── visualization/
|
||||||
|
│ ├── __init__.py # Visualization module exports
|
||||||
|
│ ├── trajectory_player.py # Continuous spatial interpolation & playback engine
|
||||||
|
│ └── animated_usd.py # Time-sampled OpenUSD stage generator
|
||||||
|
├── omniverse/
|
||||||
|
│ ├── scenes/
|
||||||
|
│ │ ├── warehouse_phase7.usda # Static facility stage with AMR fleet
|
||||||
|
│ │ └── warehouse_phase7_animated.usda # Dynamic time-sampled stage with playback tracks
|
||||||
|
│ └── extensions/
|
||||||
|
│ └── omni.warehouse.twin.visualizer/ # Omniverse Kit 110.4 extension
|
||||||
|
│ ├── config/extension.toml
|
||||||
|
│ ├── omni/warehouse/twin/visualizer/
|
||||||
|
│ │ ├── __init__.py
|
||||||
|
│ │ └── extension.py # UI window & update loop prim transform driver
|
||||||
|
│ └── docs/
|
||||||
|
│ ├── README.md
|
||||||
|
│ └── CHANGELOG.md
|
||||||
|
└── tests/unit/
|
||||||
|
├── test_trajectory_player.py # 4 passed tests
|
||||||
|
├── test_animated_usd.py # 2 passed tests
|
||||||
|
└── test_kit_extension.py # 2 passed tests
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Continuous Spatial Interpolation (`trajectory_player.py`)
|
||||||
|
|
||||||
|
The `TrajectoryPlayer` provides continuous queries at any arbitrary simulation timestamp $t \in [t_{\text{start}}, t_{\text{end}}]$:
|
||||||
|
|
||||||
|
1. **Binary Search Lookup**: $O(\log N)$ bisect lookup locating consecutive waypoints $(t_1, \mathbf{p}_1)$ and $(t_2, \mathbf{p}_2)$.
|
||||||
|
2. **Normalized Progress**:
|
||||||
|
$$\alpha = \frac{t - t_1}{t_2 - t_1}, \quad \alpha \in [0.0, 1.0]$$
|
||||||
|
3. **Cartesian Translation**:
|
||||||
|
$$\mathbf{p}(t) = (1 - \alpha)\mathbf{p}_1 + \alpha \mathbf{p}_2$$
|
||||||
|
4. **Shortest-Arc Angular Interpolation (Yaw)**:
|
||||||
|
$$\Delta \theta = (\theta_2 - \theta_1 + 180^\circ) \pmod{360^\circ} - 180^\circ$$
|
||||||
|
$$\theta(t) = \theta_1 + \alpha \Delta \theta$$
|
||||||
|
*Eliminates unnatural full-revolution spins across the $180^\circ \leftrightarrow -180^\circ$ boundary.*
|
||||||
|
5. **Continuous Battery & Discrete Payload**:
|
||||||
|
- Linear battery interpolation: $\text{SoC}(t) = \text{SoC}_1 + \alpha(\text{SoC}_2 - \text{SoC}_1)$.
|
||||||
|
- Midpoint state transition for carried payload attachment and LED beacon colors.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Visual State Indicators & Prim Structure
|
||||||
|
|
||||||
|
Each AMR on the USD stage (`/World/Robots/{robot_id}`) features synchronized visual cues:
|
||||||
|
|
||||||
|
| Robot Component | USD Prim Path | Visual Representation | Dynamic Behavior |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Chassis** | `/World/Robots/{id}/Chassis` | Light AMR: Pearl White (agile)<br>Heavy AMR: Industrial Amber (rugged) | Translates and rotates along trajectory |
|
||||||
|
| **Status Beacon** | `/World/Robots/{id}/StatusDome` | High-visibility status dome on top of chassis | Changes RGB color based on state:<br>- **Cyan** `(0.15, 0.75, 0.95)`: `IDLE`<br>- **Blue** `(0.30, 0.60, 1.00)`: `DISPATCHED`<br>- **Green** `(0.20, 0.90, 0.35)`: `PICKING` / `DROPPING`<br>- **Gold** `(0.95, 0.75, 0.10)`: `LOADED_TRANSIT`<br>- **Orange** `(0.95, 0.50, 0.15)`: `TRANSIT_TO_CHARGE`<br>- **Neon Red** `(1.00, 0.30, 0.10)`: `CHARGING` |
|
||||||
|
| **Battery LED** | `/World/Robots/{id}/BatteryLED` | Rear indicator bar | **Green** (>50%) $\rightarrow$ **Amber** (20–50%) $\rightarrow$ **Red** (<20%) |
|
||||||
|
| **Carried Cargo** | `/World/Robots/{id}/Payload` | Pallet carton box on chassis | Visibility toggles: `"inherited"` when loaded, `"invisible"` when empty |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. How to View in Omniverse Kit
|
||||||
|
|
||||||
|
### Option A: Native OpenUSD Timeline Playback (No Extension Needed)
|
||||||
|
1. Launch Omniverse Kit:
|
||||||
|
```bash
|
||||||
|
/home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/warehouse_twin.kit.sh
|
||||||
|
```
|
||||||
|
2. Open the animated scene:
|
||||||
|
- In the Kit menu: `File -> Open`
|
||||||
|
- Select `/home/dmhai/warehouse-digital-twin/omniverse/scenes/warehouse_phase7_animated.usda`
|
||||||
|
3. Click **Play** (or press `Spacebar`) on the bottom timeline toolbar.
|
||||||
|
4. Scrub the timeline slider backwards or forwards to inspect robot movements, pick/drop actions, and charging sessions.
|
||||||
|
|
||||||
|
### Option B: Interactive Trajectory Playback Extension
|
||||||
|
1. Open the static facility scene: `omniverse/scenes/warehouse_phase7.usda`.
|
||||||
|
2. The `omni.warehouse.twin.visualizer` window opens automatically.
|
||||||
|
3. Verify the trajectory path (`results/trajectories/trajectory_default.json`) and click **Load**.
|
||||||
|
4. Use the playback controls:
|
||||||
|
- **Play / Pause / Reset**
|
||||||
|
- **Speed Multipliers**: $0.5\times, 1.0\times, 2.0\times, 5.0\times, 10.0\times$
|
||||||
|
- **Time Scrubber**: Real-time slider with `HH:MM:SS` display
|
||||||
|
- **Fleet HUD**: Live status matrix tracking every robot's position, battery %, and carried payload.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. CLI Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Export static 3D facility scene
|
||||||
|
warehouse-twin export-usd --output omniverse/scenes/warehouse_phase7.usda
|
||||||
|
|
||||||
|
# 2. Run simulation and export trajectory
|
||||||
|
warehouse-twin run-sim --duration 600 --output-trajectories results/trajectories/trajectory_default.json
|
||||||
|
|
||||||
|
# 3. Export time-sampled animated USD stage
|
||||||
|
warehouse-twin export-usd \
|
||||||
|
--trajectory results/trajectories/trajectory_default.json \
|
||||||
|
--output omniverse/scenes/warehouse_phase7_animated.usda \
|
||||||
|
--step-seconds 1.0
|
||||||
|
|
||||||
|
# 4. Preview and validate trajectory kinematics in terminal
|
||||||
|
warehouse-twin play-trajectory results/trajectories/trajectory_default.json --step 30
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Test & Validation Summary
|
||||||
|
|
||||||
|
```
|
||||||
|
============================= 137 passed in 1.01s ==============================
|
||||||
|
```
|
||||||
|
- **Total Tests**: 137 passed (100% pass rate).
|
||||||
|
- **Phase 7 Test Suites Added**:
|
||||||
|
- `tests/unit/test_trajectory_player.py`: 4 passed
|
||||||
|
- `tests/unit/test_animated_usd.py`: 2 passed
|
||||||
|
- `tests/unit/test_kit_extension.py`: 2 passed
|
||||||
|
- **Teardown Safety**: Extension properly unregisters all update subscriptions and releases event callbacks on shutdown without dangling references.
|
||||||
+20
-8
@@ -13,10 +13,11 @@ The visualizer connects to the discrete-event simulation engine via decoupled da
|
|||||||
## 2. Inspected Environment Findings
|
## 2. Inspected Environment Findings
|
||||||
|
|
||||||
Inspection of the host system confirmed:
|
Inspection of the host system confirmed:
|
||||||
- **Kit Application Directory**: `/home/dmhai/nvidia-omniverse/kit-app-template`
|
- **Kit Application Directory**: `/home/dmhai/Desktop/nvidia-omniverse/kit-app-template`
|
||||||
- **Kit Kernel Version**: `110.4.0+feature.386251.187cf21b.gl`
|
- **Kit Kernel Version**: `110.4.0+feature.386251.187cf21b.gl`
|
||||||
- **Application Target**: `_build/linux-x86_64/release/apps/warehouse_twin.kit`
|
- **Application Target**: `_build/linux-x86_64/release/apps/warehouse_twin.kit`
|
||||||
- **Kit Launch Executable**: `_build/linux-x86_64/release/kit/kit`
|
- **Kit Launch Executable**: `_build/linux-x86_64/release/kit/kit`
|
||||||
|
- **Launch Script**: `_build/linux-x86_64/release/warehouse_twin.kit.sh`
|
||||||
- **Embedded Python Version**: Python 3.12 (cp312)
|
- **Embedded Python Version**: Python 3.12 (cp312)
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -27,17 +28,28 @@ Inspection of the host system confirmed:
|
|||||||
omniverse/
|
omniverse/
|
||||||
├── README.md # Integration guide and Kit version documentation
|
├── README.md # Integration guide and Kit version documentation
|
||||||
├── extensions/ # Verified Kit extension structure (Phase 7)
|
├── extensions/ # Verified Kit extension structure (Phase 7)
|
||||||
|
│ └── omni.warehouse.twin.visualizer/ # Interactive playback extension
|
||||||
├── scenes/ # Generated warehouse OpenUSD scene files (.usda / .usd)
|
├── scenes/ # Generated warehouse OpenUSD scene files (.usda / .usd)
|
||||||
|
│ ├── warehouse_phase7.usda # Static facility stage with AMR fleet
|
||||||
|
│ └── warehouse_phase7_animated.usda # Dynamic time-sampled stage with playback tracks
|
||||||
└── assets/ # Lightweight USD primitives for AMRs, racks, and stations
|
└── assets/ # Lightweight USD primitives for AMRs, racks, and stations
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Phase 7 Visualization Architecture Preview
|
## 4. Phase 7 Visualization Architecture
|
||||||
|
|
||||||
In Phase 7, the visualizer extension will:
|
The visualizer provides two decoupled visualization workflows:
|
||||||
1. Load a parameterized USD stage representing the warehouse (Zones A, B, and C, picking stations, inbound docks, charging bays).
|
|
||||||
2. Instantiate lightweight AMR prims (`/World/Robots/amr_light_01`, etc.).
|
1. **Native OpenUSD Timeline Animation (`warehouse_phase7_animated.usda`)**:
|
||||||
3. Subscribe to the Kit update loop via `omni.kit.app.get_app().get_update_event_stream()`.
|
- Embeds time-sampled transform tracks (`xformOp:translate.timeSamples`, `xformOp:rotateXYZ.timeSamples`).
|
||||||
4. Synchronize simulation playback time with Kit wall-clock frames and update robot translation `(x, y, z)` and orientation `yaw`.
|
- Dynamic status beacon colors (`primvars:displayColor.timeSamples`) reflecting robot operational states.
|
||||||
5. Ensure clean teardown on extension shutdown or stage closing so no orphan subscriptions remain.
|
- Dynamic battery LED colors reflecting SoC degradation.
|
||||||
|
- Dynamic payload visibility toggling (`visibility.timeSamples`).
|
||||||
|
- Opens and scrubs directly in Omniverse Kit or any standard OpenUSD application without custom plugins.
|
||||||
|
|
||||||
|
2. **Interactive Omniverse Kit Extension (`omni.warehouse.twin.visualizer`)**:
|
||||||
|
- Subscribes to the Kit update loop via `omni.kit.app.get_app().get_update_event_stream()`.
|
||||||
|
- Provides an interactive `omni.ui.Window` with Play, Pause, Reset, Seek (scrub slider), and Speed Multipliers ($0.5\times$ to $10.0\times$).
|
||||||
|
- Real-time fleet telemetry HUD table showing states, coordinates, battery %, and carried payload.
|
||||||
|
- Clean unsubscription and resource teardown on shutdown.
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# SPDX-FileCopyrightText: Copyright (c) 2026 Warehouse Robot Fleet Digital Twin
|
||||||
|
# SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
[package]
|
||||||
|
title = "Warehouse Robot Fleet Digital Twin Visualizer"
|
||||||
|
version = "0.7.0"
|
||||||
|
description = "Interactive 3D trajectory playback and telemetry visualization for warehouse AMR fleets in NVIDIA Omniverse Kit."
|
||||||
|
category = "Simulation"
|
||||||
|
keywords = ["warehouse", "amr", "robotics", "digital-twin", "trajectory", "simulation"]
|
||||||
|
repository = "https://github.com/warehouse-digital-twin"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
"omni.kit.uiapp" = {}
|
||||||
|
"omni.usd" = {}
|
||||||
|
|
||||||
|
[[python.module]]
|
||||||
|
name = "omni.warehouse.twin.visualizer"
|
||||||
|
|
||||||
|
[documentation]
|
||||||
|
pages = [
|
||||||
|
"docs/README.md",
|
||||||
|
"docs/CHANGELOG.md",
|
||||||
|
]
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Changelog - omni.warehouse.twin.visualizer
|
||||||
|
|
||||||
|
## [0.7.0] - 2026-10-21
|
||||||
|
### Added
|
||||||
|
- Initial release of Omniverse Kit 110.4 visualizer extension.
|
||||||
|
- File-based trajectory loading for JSON simulation exports.
|
||||||
|
- Continuous spatial and heading interpolation engine (`TrajectoryPlayer`).
|
||||||
|
- Prim transform updates for robot translation and planar yaw.
|
||||||
|
- Status dome display color updates reflecting operational states.
|
||||||
|
- Payload visibility toggling during picking, transit, and dropping.
|
||||||
|
- Interactive playback controls: Play, Pause, Reset, Seek, Speed multipliers.
|
||||||
|
- Live Fleet Telemetry table in `omni.ui.Window`.
|
||||||
|
- Clean teardown and safe unsubscription handling.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Warehouse Robot Fleet Digital Twin - Omniverse Visualizer Extension
|
||||||
|
|
||||||
|
## 1. Overview
|
||||||
|
The `omni.warehouse.twin.visualizer` extension brings discrete-event simulation recordings to life in NVIDIA Omniverse Kit.
|
||||||
|
|
||||||
|
It reads time-indexed AMR trajectory files (`results/trajectories/trajectory_*.json`), smoothly interpolates continuous 3D robot poses, and updates USD stage prims (`/World/Robots/{robot_id}`) along with visual status beacons and payload attachments.
|
||||||
|
|
||||||
|
## 2. Features
|
||||||
|
- **Dynamic 3D Trajectory Playback**: Real-time kinematic interpolation of AMR translations and rotations ($Z$-up, planar yaw).
|
||||||
|
- **Status Beacon Glow**: Visual state indications on `/World/Robots/{robot_id}/StatusDome` (Cyan for Idle, Blue for Dispatched, Green for Handling, Gold for Loaded Transit, Orange/Red for Charging).
|
||||||
|
- **Payload Box Attachment**: Automatic visibility toggling of carried pallet boxes on top of AMRs.
|
||||||
|
- **Interactive Playback Controls**: Play, Pause, Reset, Loop, Seek (scrub slider), and Speed Multipliers ($0.5\times, 1.0\times, 2.0\times, 5.0\times, 10.0\times$).
|
||||||
|
- **Live Fleet HUD**: Real-time matrix of all AMR states, battery levels, payload masses, and $(X, Y)$ coordinates.
|
||||||
|
- **Clean Subscription Teardown**: Automatically unsubscribes from Kit update loops upon shutdown to prevent memory leaks or dangling callbacks.
|
||||||
|
|
||||||
|
## 3. How to Enable in Omniverse Kit
|
||||||
|
1. Open Omniverse Kit using the project script:
|
||||||
|
```bash
|
||||||
|
/home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/warehouse_twin.kit.sh
|
||||||
|
```
|
||||||
|
2. Open the warehouse USD scene (`File -> Open -> omniverse/scenes/warehouse_phase7.usda`).
|
||||||
|
3. Enable the extension in Extension Manager or load via Kit settings.
|
||||||
|
4. In the "Warehouse Twin Visualizer" window, select a trajectory file and press **Play**.
|
||||||
+5
@@ -0,0 +1,5 @@
|
|||||||
|
"""Omniverse Kit extension for Warehouse Robot Fleet Digital Twin visualization."""
|
||||||
|
|
||||||
|
from omni.warehouse.twin.visualizer.extension import WarehouseVisualizerExtension
|
||||||
|
|
||||||
|
__all__ = ["WarehouseVisualizerExtension"]
|
||||||
+331
@@ -0,0 +1,331 @@
|
|||||||
|
"""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
|
||||||
|
|
||||||
|
# Import core simulation visualization player
|
||||||
|
try:
|
||||||
|
from warehouse_twin.visualization.trajectory_player import (
|
||||||
|
RobotPlaybackState,
|
||||||
|
TrajectoryData,
|
||||||
|
TrajectoryPlayer,
|
||||||
|
interpolate_robot_state,
|
||||||
|
)
|
||||||
|
except ImportError:
|
||||||
|
# Handle sys.path when running standalone inside Kit Python
|
||||||
|
current_dir = Path(__file__).resolve().parent
|
||||||
|
repo_root = current_dir.parents[4]
|
||||||
|
src_path = repo_root / "src"
|
||||||
|
if str(src_path) not in sys.path:
|
||||||
|
sys.path.insert(0, str(src_path))
|
||||||
|
from warehouse_twin.visualization.trajectory_player import (
|
||||||
|
RobotPlaybackState,
|
||||||
|
TrajectoryData,
|
||||||
|
TrajectoryPlayer,
|
||||||
|
interpolate_robot_state,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class WarehouseVisualizerExtension(ExtBase):
|
||||||
|
"""Main Omniverse Kit Extension managing trajectory playback and stage updates."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._window: 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
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
# Locate default trajectory file if available
|
||||||
|
default_traj = Path("results/trajectories/trajectory_default.json").resolve()
|
||||||
|
if not default_traj.exists():
|
||||||
|
# Check baseline experiment directory
|
||||||
|
alt = Path("results/experiments/baseline_1hr/events.jsonl").resolve()
|
||||||
|
# Search for any trajectory json in results/
|
||||||
|
found = list(Path("results").glob("**/trajectory*.json"))
|
||||||
|
if found:
|
||||||
|
default_traj = found[0].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()
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# 1. Cancel Kit update loop subscription
|
||||||
|
if self._update_sub is not None:
|
||||||
|
self._update_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 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."""
|
||||||
|
self._window = ui.Window("Warehouse Twin Visualizer", width=440, height=480)
|
||||||
|
with self._window.frame:
|
||||||
|
with ui.VStack(spacing=8):
|
||||||
|
ui.Label("Warehouse Fleet Trajectory Playback", style={"font_size": 18})
|
||||||
|
|
||||||
|
# Status & File Info
|
||||||
|
self._status_label = ui.Label("No trajectory loaded", style={"color": 0xFF888888})
|
||||||
|
|
||||||
|
# File load button
|
||||||
|
with ui.HStack(height=30):
|
||||||
|
traj_field = ui.StringField()
|
||||||
|
traj_field.model.set_value(self._trajectory_path or "results/trajectories/trajectory_default.json")
|
||||||
|
|
||||||
|
def on_load_clicked():
|
||||||
|
self.load_trajectory(traj_field.model.get_value_as_string())
|
||||||
|
|
||||||
|
ui.Button("Load", clicked_fn=on_load_clicked, width=70)
|
||||||
|
|
||||||
|
# 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()
|
||||||
|
ui.Label("Active AMR Fleet Telemetry", style={"font_size": 14})
|
||||||
|
|
||||||
|
# Fleet HUD List
|
||||||
|
with ui.ScrollingFrame(height=180):
|
||||||
|
with ui.VStack(spacing=4):
|
||||||
|
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)")
|
||||||
@@ -0,0 +1,617 @@
|
|||||||
|
#usda 1.0
|
||||||
|
(
|
||||||
|
defaultPrim = "World"
|
||||||
|
metersPerUnit = 1.0
|
||||||
|
upAxis = "Z"
|
||||||
|
doc = "Warehouse Robot Fleet Digital Twin - 3D Facility Model"
|
||||||
|
)
|
||||||
|
|
||||||
|
def Xform "World"
|
||||||
|
{
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Environment Lighting
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
def DistantLight "SunLight"
|
||||||
|
{
|
||||||
|
float inputs:intensity = 3500.0
|
||||||
|
color3f inputs:color = (0.98, 0.96, 0.92)
|
||||||
|
float inputs:angle = 1.0
|
||||||
|
double3 xformOp:rotateXYZ = (-45.0, 30.0, 0.0)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:rotateXYZ"]
|
||||||
|
}
|
||||||
|
|
||||||
|
def DomeLight "SkyLight"
|
||||||
|
{
|
||||||
|
float inputs:intensity = 800.0
|
||||||
|
color3f inputs:color = (0.85, 0.90, 0.98)
|
||||||
|
}
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Facility Shell: Ground Floor & Boundary Markers
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
def Scope "Architecture"
|
||||||
|
{
|
||||||
|
def Mesh "GroundFloor"
|
||||||
|
{
|
||||||
|
float3[] extent = [(-2.0, -2.0, -0.2), (62.0, 42.0, 0.0)]
|
||||||
|
int[] faceVertexCounts = [4]
|
||||||
|
int[] faceVertexIndices = [0, 1, 2, 3]
|
||||||
|
point3f[] points = [(-2.0, -2.0, 0.0), (62.0, -2.0, 0.0), (62.0, 42.0, 0.0), (-2.0, 42.0, 0.0)]
|
||||||
|
normal3f[] normals = [(0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0)]
|
||||||
|
color3f[] primvars:displayColor = [(0.14, 0.16, 0.19)]
|
||||||
|
float[] primvars:displayRoughness = [0.35]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "NorthWallGuide"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (30.0, 40.5, 1.0)
|
||||||
|
double3 xformOp:scale = (30.0, 0.15, 1.0)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "SouthWallGuide"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (30.0, -0.5, 1.0)
|
||||||
|
double3 xformOp:scale = (30.0, 0.15, 1.0)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "EastWallGuide"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (60.5, 20.0, 1.0)
|
||||||
|
double3 xformOp:scale = (0.15, 20.0, 1.0)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Inventory Zones (Zone A, Zone B, Zone C Demarcations)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
def Scope "Zones"
|
||||||
|
{
|
||||||
|
def Cube "zone_a"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (15.00, 20.00, 0.005)
|
||||||
|
double3 xformOp:scale = (10.00, 15.00, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.45, 0.85)]
|
||||||
|
float[] primvars:displayOpacity = [0.25]
|
||||||
|
}
|
||||||
|
def Cube "zone_b"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (37.50, 20.00, 0.005)
|
||||||
|
double3 xformOp:scale = (7.50, 15.00, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.85, 0.55, 0.12)]
|
||||||
|
float[] primvars:displayOpacity = [0.25]
|
||||||
|
}
|
||||||
|
def Cube "zone_c"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (53.00, 20.00, 0.005)
|
||||||
|
double3 xformOp:scale = (5.00, 15.00, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.12, 0.68, 0.38)]
|
||||||
|
float[] primvars:displayOpacity = [0.25]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Storage Racks (13 Inventory Catalog Locations)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
def Scope "StorageRacks"
|
||||||
|
{
|
||||||
|
def Xform "rack_a_01"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (8.00, 10.00, 1.80)
|
||||||
|
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_a_02"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (8.00, 20.00, 1.80)
|
||||||
|
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_a_03"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (16.00, 10.00, 1.80)
|
||||||
|
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_a_04"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (16.00, 20.00, 1.80)
|
||||||
|
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_a_05"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (20.00, 30.00, 1.80)
|
||||||
|
double3 xformOp:scale = (0.90, 0.50, 1.80)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.4, 0.7)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_b_01"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (34.00, 10.00, 2.20)
|
||||||
|
double3 xformOp:scale = (1.40, 0.70, 2.20)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.8, 0.5, 0.1)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_b_02"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (34.00, 22.00, 2.20)
|
||||||
|
double3 xformOp:scale = (1.40, 0.70, 2.20)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.8, 0.5, 0.1)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_b_03"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (40.00, 10.00, 2.20)
|
||||||
|
double3 xformOp:scale = (1.40, 0.70, 2.20)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.8, 0.5, 0.1)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_b_04"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (40.00, 22.00, 2.20)
|
||||||
|
double3 xformOp:scale = (1.40, 0.70, 2.20)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.8, 0.5, 0.1)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_c_01"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (50.00, 10.00, 1.60)
|
||||||
|
double3 xformOp:scale = (1.20, 0.60, 1.60)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.6, 0.4)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_c_02"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (50.00, 22.00, 1.60)
|
||||||
|
double3 xformOp:scale = (1.20, 0.60, 1.60)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.6, 0.4)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_c_03"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (54.00, 10.00, 1.60)
|
||||||
|
double3 xformOp:scale = (1.20, 0.60, 1.60)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.6, 0.4)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "rack_c_04"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (54.00, 22.00, 1.60)
|
||||||
|
double3 xformOp:scale = (1.20, 0.60, 1.60)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "RackFrame"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.6, 0.4)]
|
||||||
|
float[] primvars:displayRoughness = [0.4]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Operational Stations
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
def Scope "Stations"
|
||||||
|
{
|
||||||
|
def Xform "dock_inbound_1"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (2.00, 10.00, 0.15)
|
||||||
|
double3 xformOp:scale = (1.50, 2.00, 0.15)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "Platform"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.85, 0.25, 0.2)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "dock_inbound_2"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (2.00, 20.00, 0.15)
|
||||||
|
double3 xformOp:scale = (1.50, 2.00, 0.15)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "Platform"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.85, 0.25, 0.2)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "picking_station_a1"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (25.00, 2.00, 0.40)
|
||||||
|
double3 xformOp:scale = (2.00, 1.20, 0.40)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "Platform"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.75, 0.85)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "picking_station_b1"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (40.00, 2.00, 0.40)
|
||||||
|
double3 xformOp:scale = (2.00, 1.20, 0.40)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "Platform"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.75, 0.85)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "production_dropoff_c1"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (55.00, 38.00, 0.25)
|
||||||
|
double3 xformOp:scale = (1.80, 1.80, 0.25)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "Platform"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.25, 0.8, 0.35)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "outbound_pack_1"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (2.00, 30.00, 0.15)
|
||||||
|
double3 xformOp:scale = (1.50, 2.00, 0.15)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "Platform"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.9, 0.4, 0.1)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Autonomous Mobile Robot (AMR) Charging Bays
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
def Scope "ChargingStations"
|
||||||
|
{
|
||||||
|
def Xform "charge_bay_1"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (2.00, 36.00, 0.05)
|
||||||
|
double3 xformOp:scale = (0.75, 0.75, 0.05)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "ChargePad"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "StationPedestal"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (0.0, 0.6, 0.6)
|
||||||
|
double3 xformOp:scale = (0.2, 0.1, 0.6)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "charge_bay_2"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (4.00, 36.00, 0.05)
|
||||||
|
double3 xformOp:scale = (0.75, 0.75, 0.05)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "ChargePad"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "StationPedestal"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (0.0, 0.6, 0.6)
|
||||||
|
double3 xformOp:scale = (0.2, 0.1, 0.6)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "charge_bay_3"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (6.00, 36.00, 0.05)
|
||||||
|
double3 xformOp:scale = (0.75, 0.75, 0.05)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "ChargePad"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "StationPedestal"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (0.0, 0.6, 0.6)
|
||||||
|
double3 xformOp:scale = (0.2, 0.1, 0.6)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "charge_bay_4"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (8.00, 36.00, 0.05)
|
||||||
|
double3 xformOp:scale = (0.75, 0.75, 0.05)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "ChargePad"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.85, 0.95)]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "StationPedestal"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (0.0, 0.6, 0.6)
|
||||||
|
double3 xformOp:scale = (0.2, 0.1, 0.6)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.2, 0.25, 0.3)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Topological Navigation Corridors & Wide Aisles (Phase 4)
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
def Scope "NavigationNetwork"
|
||||||
|
{
|
||||||
|
def Xform "Highway_West_Dock"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (2.00, 20.00, 0.01)
|
||||||
|
double3 xformOp:scale = (0.200, 18.000, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "LaneVisualizer"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.25, 0.65, 0.95)]
|
||||||
|
float[] primvars:displayRoughness = [0.8]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "Highway_Transfer_AB"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (26.00, 20.00, 0.01)
|
||||||
|
double3 xformOp:scale = (0.200, 18.000, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "LaneVisualizer"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.35, 0.75, 0.95)]
|
||||||
|
float[] primvars:displayRoughness = [0.8]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "Highway_Transfer_BC"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (46.00, 20.00, 0.01)
|
||||||
|
double3 xformOp:scale = (0.200, 18.000, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "LaneVisualizer"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.35, 0.75, 0.95)]
|
||||||
|
float[] primvars:displayRoughness = [0.8]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "Highway_East_Perimeter"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (58.00, 20.00, 0.01)
|
||||||
|
double3 xformOp:scale = (0.200, 18.000, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "LaneVisualizer"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.25, 0.65, 0.95)]
|
||||||
|
float[] primvars:displayRoughness = [0.8]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "Highway_South_Picking"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (30.00, 2.00, 0.01)
|
||||||
|
double3 xformOp:scale = (28.000, 0.200, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "LaneVisualizer"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.25, 0.7, 0.85)]
|
||||||
|
float[] primvars:displayRoughness = [0.8]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "Highway_North_Charging"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (30.00, 38.00, 0.01)
|
||||||
|
double3 xformOp:scale = (28.000, 0.200, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "LaneVisualizer"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.25, 0.7, 0.85)]
|
||||||
|
float[] primvars:displayRoughness = [0.8]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "Aisle_B1_Wide_Aisle"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (34.00, 20.00, 0.01)
|
||||||
|
double3 xformOp:scale = (0.250, 14.000, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "LaneVisualizer"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.95, 0.65, 0.15)]
|
||||||
|
float[] primvars:displayRoughness = [0.8]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "Aisle_B2_Wide_Aisle"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (40.00, 20.00, 0.01)
|
||||||
|
double3 xformOp:scale = (0.250, 14.000, 0.005)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
|
||||||
|
def Cube "LaneVisualizer"
|
||||||
|
{
|
||||||
|
color3f[] primvars:displayColor = [(0.95, 0.65, 0.15)]
|
||||||
|
float[] primvars:displayRoughness = [0.8]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Autonomous Mobile Robot (AMR) Fleet
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
def Scope "Robots"
|
||||||
|
{
|
||||||
|
def Xform "amr_light_01"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (2.00, 36.00, 0.175)
|
||||||
|
double3 xformOp:rotateXYZ = (0.0, 0.0, 0.0)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]
|
||||||
|
|
||||||
|
def Cube "Chassis"
|
||||||
|
{
|
||||||
|
double3 xformOp:scale = (0.4, 0.3, 0.175)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.88, 0.90, 0.95)]
|
||||||
|
float[] primvars:displayRoughness = [0.25]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "StatusDome"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (0.0, 0.0, 0.255)
|
||||||
|
double3 xformOp:scale = (0.160, 0.120, 0.05)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.75, 0.95)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "amr_light_02"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (4.00, 36.00, 0.175)
|
||||||
|
double3 xformOp:rotateXYZ = (0.0, 0.0, 0.0)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]
|
||||||
|
|
||||||
|
def Cube "Chassis"
|
||||||
|
{
|
||||||
|
double3 xformOp:scale = (0.4, 0.3, 0.175)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.88, 0.90, 0.95)]
|
||||||
|
float[] primvars:displayRoughness = [0.25]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "StatusDome"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (0.0, 0.0, 0.255)
|
||||||
|
double3 xformOp:scale = (0.160, 0.120, 0.05)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.75, 0.95)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "amr_heavy_01"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (6.00, 36.00, 0.225)
|
||||||
|
double3 xformOp:rotateXYZ = (0.0, 0.0, 0.0)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]
|
||||||
|
|
||||||
|
def Cube "Chassis"
|
||||||
|
{
|
||||||
|
double3 xformOp:scale = (0.7, 0.5, 0.225)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.92, 0.65, 0.08)]
|
||||||
|
float[] primvars:displayRoughness = [0.25]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "StatusDome"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (0.0, 0.0, 0.305)
|
||||||
|
double3 xformOp:scale = (0.280, 0.200, 0.05)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.85, 0.3)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def Xform "amr_heavy_02"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (8.00, 36.00, 0.225)
|
||||||
|
double3 xformOp:rotateXYZ = (0.0, 0.0, 0.0)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]
|
||||||
|
|
||||||
|
def Cube "Chassis"
|
||||||
|
{
|
||||||
|
double3 xformOp:scale = (0.7, 0.5, 0.225)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.92, 0.65, 0.08)]
|
||||||
|
float[] primvars:displayRoughness = [0.25]
|
||||||
|
}
|
||||||
|
|
||||||
|
def Cube "StatusDome"
|
||||||
|
{
|
||||||
|
double3 xformOp:translate = (0.0, 0.0, 0.305)
|
||||||
|
double3 xformOp:scale = (0.280, 0.200, 0.05)
|
||||||
|
uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]
|
||||||
|
color3f[] primvars:displayColor = [(0.15, 0.85, 0.3)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -55,4 +55,5 @@ testpaths = ["tests"]
|
|||||||
python_files = ["test_*.py"]
|
python_files = ["test_*.py"]
|
||||||
python_functions = ["test_*"]
|
python_functions = ["test_*"]
|
||||||
python_classes = ["Test*"]
|
python_classes = ["Test*"]
|
||||||
|
pythonpath = ["src", "omniverse/extensions/omni.warehouse.twin.visualizer"]
|
||||||
addopts = "-v --strict-markers"
|
addopts = "-v --strict-markers"
|
||||||
|
|||||||
@@ -44,12 +44,24 @@ fi
|
|||||||
# Omniverse Kit Check
|
# Omniverse Kit Check
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== NVIDIA Omniverse Kit Status ==="
|
echo "=== NVIDIA Omniverse Kit Status ==="
|
||||||
KIT_DEFAULT="/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit"
|
KIT_CANDIDATES=(
|
||||||
KIT_EXEC="${KIT_PATH:-$KIT_DEFAULT}"
|
"$KIT_PATH"
|
||||||
if [ -x "$KIT_EXEC" ]; then
|
"/home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit"
|
||||||
|
"/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit"
|
||||||
|
"/home/dmhai/Documents/Kit/apps/kit"
|
||||||
|
)
|
||||||
|
KIT_EXEC=""
|
||||||
|
for candidate in "${KIT_CANDIDATES[@]}"; do
|
||||||
|
if [ -n "$candidate" ] && [ -x "$candidate" ]; then
|
||||||
|
KIT_EXEC="$candidate"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -n "$KIT_EXEC" ]; then
|
||||||
echo "[OK] Found Omniverse Kit executable at: $KIT_EXEC"
|
echo "[OK] Found Omniverse Kit executable at: $KIT_EXEC"
|
||||||
else
|
else
|
||||||
echo "[INFO] Omniverse Kit executable not found at: $KIT_EXEC (Required only for Phase 7 visualization)"
|
echo "[INFO] Omniverse Kit executable not found. (Required for Phase 7 live visualization)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Run Python-level Environment Check
|
# Run Python-level Environment Check
|
||||||
|
|||||||
+150
-33
@@ -70,15 +70,24 @@ def check_environment() -> int:
|
|||||||
failures += 1
|
failures += 1
|
||||||
|
|
||||||
# 5. NVIDIA Omniverse Kit Check (Optional for Simulation, Required for Visualizer)
|
# 5. NVIDIA Omniverse Kit Check (Optional for Simulation, Required for Visualizer)
|
||||||
kit_env_path = os.environ.get(
|
kit_candidates = [
|
||||||
"KIT_PATH",
|
os.environ.get("KIT_PATH"),
|
||||||
"/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit"
|
"/home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit",
|
||||||
)
|
"/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit",
|
||||||
kit_path = Path(kit_env_path)
|
"/home/dmhai/Documents/Kit/apps/kit",
|
||||||
if kit_path.exists() and os.access(kit_path, os.X_OK):
|
]
|
||||||
print(f"[OK] NVIDIA Omniverse Kit found at: {kit_path}")
|
detected_kit = None
|
||||||
|
for candidate in kit_candidates:
|
||||||
|
if candidate:
|
||||||
|
p = Path(candidate)
|
||||||
|
if p.exists() and os.access(p, os.X_OK):
|
||||||
|
detected_kit = p
|
||||||
|
break
|
||||||
|
|
||||||
|
if detected_kit:
|
||||||
|
print(f"[OK] NVIDIA Omniverse Kit found at: {detected_kit}")
|
||||||
else:
|
else:
|
||||||
print(f"[INFO] Omniverse Kit not detected at default path ({kit_path}). Phase 7 will require Kit.")
|
print("[INFO] Omniverse Kit not detected at known paths. Phase 7 live visualizer will require Kit.")
|
||||||
|
|
||||||
print("-" * 65)
|
print("-" * 65)
|
||||||
if failures > 0:
|
if failures > 0:
|
||||||
@@ -188,44 +197,132 @@ def export_graph(config_dir: Optional[str] = None, output_path: Optional[str] =
|
|||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
|
||||||
def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = None) -> int:
|
def export_usd(
|
||||||
"""Build and export the warehouse 3D scene to an OpenUSD (.usda) file."""
|
config_dir: Optional[str] = None,
|
||||||
|
output_path: Optional[str] = None,
|
||||||
|
trajectory_path: Optional[str] = None,
|
||||||
|
step_seconds: float = 1.0,
|
||||||
|
) -> int:
|
||||||
|
"""Build and export warehouse 3D scene to OpenUSD (.usda), with optional time-sampled animation."""
|
||||||
setup_logging()
|
setup_logging()
|
||||||
logger = get_logger("cli")
|
logger = get_logger("cli")
|
||||||
try:
|
try:
|
||||||
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
|
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
|
||||||
|
from warehouse_twin.visualization.animated_usd import AnimatedUSDGenerator
|
||||||
|
from warehouse_twin.visualization.trajectory_player import TrajectoryData
|
||||||
|
|
||||||
loader = ConfigLoader(config_dir)
|
loader = ConfigLoader(config_dir)
|
||||||
bundle = loader.load_all()
|
bundle = loader.load_all()
|
||||||
|
|
||||||
generator = WarehouseUSDGenerator.from_config_bundle(bundle, include_routing_network=True)
|
if trajectory_path:
|
||||||
default_out = Path("omniverse/scenes/warehouse_phase5.usda")
|
traj_file = Path(trajectory_path).resolve()
|
||||||
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
|
if not traj_file.exists():
|
||||||
|
print(f"[FAIL] Trajectory file not found: {traj_file}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
saved_path = generator.export_usda(out_file)
|
traj_data = TrajectoryData.from_file(traj_file)
|
||||||
model = generator.model
|
anim_gen = AnimatedUSDGenerator.from_config_and_trajectory(
|
||||||
print("=" * 65)
|
bundle=bundle,
|
||||||
print("Warehouse 3D OpenUSD Scene Successfully Generated")
|
trajectory_data=traj_data,
|
||||||
print("=" * 65)
|
sample_step_seconds=step_seconds,
|
||||||
print(f"Scene Path: {saved_path}")
|
)
|
||||||
print(f"Facility: {model.dimensions.width}m x {model.dimensions.depth}m x {model.dimensions.height}m")
|
default_out = Path("omniverse/scenes/warehouse_phase7_animated.usda")
|
||||||
print(f"Zones: Zone A (Blue), Zone B (Amber), Zone C (Green)")
|
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
|
||||||
print(f"Entities: {len(model.storage_locations)} Storage Racks, {len(model.stations)} Stations, {len(model.charging_stations)} Chargers")
|
saved_path = anim_gen.export_usda(out_file)
|
||||||
print(f"AMR Fleet: {len(generator.robots)} Autonomous Mobile Robots")
|
print("=" * 65)
|
||||||
for r in generator.robots:
|
print("Warehouse Animated OpenUSD Scene Successfully Generated")
|
||||||
print(f" - {r.robot_id} ({r.robot_type}) at ({r.position.x}, {r.position.y}, {r.position.z}) [battery: {r.battery_percent:.0f}%]")
|
print("=" * 65)
|
||||||
print("-" * 65)
|
print(f"Scene Path: {saved_path}")
|
||||||
print("How to view in Omniverse Kit:")
|
print(f"Animation Range: 0.0s to {traj_data.duration:.1f}s ({round(traj_data.duration * anim_gen.timecodes_per_second)} frames)")
|
||||||
print(f" 1. In the active Kit App window, select File -> Open")
|
print(f"Sample Step: {step_seconds}s ({anim_gen.timecodes_per_second} fps)")
|
||||||
print(f" 2. Navigate to: {saved_path}")
|
print(f"AMRs Animated: {len(traj_data.robots)}")
|
||||||
print("=" * 65)
|
print("-" * 65)
|
||||||
return 0
|
print("How to view in Omniverse Kit:")
|
||||||
|
print(f" 1. Launch Kit: /home/dmhai/Desktop/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/warehouse_twin.kit.sh")
|
||||||
|
print(f" 2. In Kit App, select File -> Open -> {saved_path}")
|
||||||
|
print(f" 3. Press Spacebar or Play on the Timeline toolbar to view the simulation!")
|
||||||
|
print("=" * 65)
|
||||||
|
return 0
|
||||||
|
else:
|
||||||
|
generator = WarehouseUSDGenerator.from_config_bundle(bundle, include_routing_network=True)
|
||||||
|
default_out = Path("omniverse/scenes/warehouse_phase7.usda")
|
||||||
|
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
|
||||||
|
saved_path = generator.export_usda(out_file)
|
||||||
|
model = generator.model
|
||||||
|
print("=" * 65)
|
||||||
|
print("Warehouse 3D OpenUSD Scene Successfully Generated")
|
||||||
|
print("=" * 65)
|
||||||
|
print(f"Scene Path: {saved_path}")
|
||||||
|
print(f"Facility: {model.dimensions.width}m x {model.dimensions.depth}m x {model.dimensions.height}m")
|
||||||
|
print(f"Zones: Zone A (Blue), Zone B (Amber), Zone C (Green)")
|
||||||
|
print(f"Entities: {len(model.storage_locations)} Storage Racks, {len(model.stations)} Stations, {len(model.charging_stations)} Chargers")
|
||||||
|
print(f"AMR Fleet: {len(generator.robots)} Autonomous Mobile Robots")
|
||||||
|
for r in generator.robots:
|
||||||
|
print(f" - {r.robot_id} ({r.robot_type}) at ({r.position.x}, {r.position.y}, {r.position.z}) [battery: {r.battery_percent:.0f}%]")
|
||||||
|
print("-" * 65)
|
||||||
|
print("How to view in Omniverse Kit:")
|
||||||
|
print(f" 1. In the active Kit App window, select File -> Open")
|
||||||
|
print(f" 2. Navigate to: {saved_path}")
|
||||||
|
print("=" * 65)
|
||||||
|
return 0
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
logger.error("USD export failed: %s", err)
|
logger.error("USD export failed: %s", err)
|
||||||
print(f"[FAIL] USD Export Error: {err}", file=sys.stderr)
|
print(f"[FAIL] USD Export Error: {err}", file=sys.stderr)
|
||||||
return 1
|
return 1
|
||||||
|
|
||||||
|
|
||||||
|
def play_trajectory_cmd(
|
||||||
|
trajectory_path: str,
|
||||||
|
speed: float = 1.0,
|
||||||
|
step: float = 5.0,
|
||||||
|
) -> int:
|
||||||
|
"""Validate and simulate playback of an exported AMR trajectory file."""
|
||||||
|
setup_logging()
|
||||||
|
logger = get_logger("cli")
|
||||||
|
try:
|
||||||
|
from warehouse_twin.visualization.trajectory_player import TrajectoryData, TrajectoryPlayer
|
||||||
|
|
||||||
|
target = Path(trajectory_path).resolve()
|
||||||
|
if not target.exists():
|
||||||
|
print(f"[FAIL] Trajectory file not found: {target}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
data = TrajectoryData.from_file(target)
|
||||||
|
player = TrajectoryPlayer(data, playback_speed=speed)
|
||||||
|
|
||||||
|
print("=" * 65)
|
||||||
|
print("AMR Trajectory Playback Verification")
|
||||||
|
print("=" * 65)
|
||||||
|
print(f"Source File: {target}")
|
||||||
|
print(f"Fleet Size: {len(data.robots)} AMRs ({', '.join(data.get_robot_ids())})")
|
||||||
|
print(f"Waypoints: {data.get_point_count()} recorded positions")
|
||||||
|
print(f"Duration: {data.duration:.1f} simulation seconds ({player.duration / 60.0:.2f} mins)")
|
||||||
|
print(f"Speed: {speed:.1f}x")
|
||||||
|
print("-" * 65)
|
||||||
|
print(f"{'Time':<10} | {'Robot':<14} | {'State':<16} | {'Battery':<8} | {'Payload':<8} | {'Position (X, Y)':<16}")
|
||||||
|
print("-" * 65)
|
||||||
|
|
||||||
|
cur_t = data.start_time
|
||||||
|
max_samples = 20
|
||||||
|
sample_count = 0
|
||||||
|
while cur_t <= data.end_time and sample_count < max_samples:
|
||||||
|
st = player.seek(cur_t)
|
||||||
|
for r_id, r_state in st.items():
|
||||||
|
load_str = "LOADED" if r_state.is_loaded else "EMPTY"
|
||||||
|
pos_str = f"({r_state.x:5.1f}, {r_state.y:5.1f})"
|
||||||
|
print(f"{r_state.formatted_time:<10} | {r_id:<14} | {r_state.state:<16} | {r_state.battery_percent:>6.1f}% | {load_str:<8} | {pos_str:<16}")
|
||||||
|
cur_t += step
|
||||||
|
sample_count += 1
|
||||||
|
|
||||||
|
print("=" * 65)
|
||||||
|
print("[OK] Trajectory validation passed: Kinematics and coordinate mapping verified.")
|
||||||
|
return 0
|
||||||
|
except Exception as err:
|
||||||
|
logger.error("Playback failed: %s", err)
|
||||||
|
print(f"[FAIL] Trajectory Playback Error: {err}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
|
||||||
def run_simulation(
|
def run_simulation(
|
||||||
config_dir: Optional[str] = None,
|
config_dir: Optional[str] = None,
|
||||||
duration: Optional[float] = None,
|
duration: Optional[float] = None,
|
||||||
@@ -528,8 +625,26 @@ def main(argv: Optional[list[str]] = None) -> int:
|
|||||||
"--output",
|
"--output",
|
||||||
type=str,
|
type=str,
|
||||||
default=None,
|
default=None,
|
||||||
help="Output USD file path (defaults to omniverse/scenes/warehouse_phase2.usda)",
|
help="Output USD file path (defaults to omniverse/scenes/warehouse_phase7.usda or warehouse_phase7_animated.usda)",
|
||||||
)
|
)
|
||||||
|
usd_exp_parser.add_argument(
|
||||||
|
"--trajectory",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Path to AMR trajectory JSON for generating time-sampled animation tracks",
|
||||||
|
)
|
||||||
|
usd_exp_parser.add_argument(
|
||||||
|
"--step-seconds",
|
||||||
|
type=float,
|
||||||
|
default=1.0,
|
||||||
|
help="Sample step in seconds for time-sampled animation (default: 1.0)",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subcommand: play-trajectory (Phase 7)
|
||||||
|
play_parser = subparsers.add_parser("play-trajectory", help="Validate and preview AMR trajectory playback kinematics")
|
||||||
|
play_parser.add_argument("trajectory", type=str, help="Path to AMR trajectory JSON file")
|
||||||
|
play_parser.add_argument("--speed", type=float, default=1.0, help="Playback speed multiplier")
|
||||||
|
play_parser.add_argument("--step", type=float, default=5.0, help="Sample step interval in seconds for terminal preview")
|
||||||
|
|
||||||
# Subcommand: run-sim
|
# Subcommand: run-sim
|
||||||
sim_parser = subparsers.add_parser("run-sim", help="Run SimPy discrete-event simulation")
|
sim_parser = subparsers.add_parser("run-sim", help="Run SimPy discrete-event simulation")
|
||||||
@@ -597,7 +712,9 @@ def main(argv: Optional[list[str]] = None) -> int:
|
|||||||
elif args.command == "export-graph":
|
elif args.command == "export-graph":
|
||||||
return export_graph(args.config_dir, args.output)
|
return export_graph(args.config_dir, args.output)
|
||||||
elif args.command == "export-usd":
|
elif args.command == "export-usd":
|
||||||
return export_usd(args.config_dir, args.output)
|
return export_usd(args.config_dir, args.output, args.trajectory, args.step_seconds)
|
||||||
|
elif args.command == "play-trajectory":
|
||||||
|
return play_trajectory_cmd(args.trajectory, args.speed, args.step)
|
||||||
elif args.command == "run-sim":
|
elif args.command == "run-sim":
|
||||||
return run_simulation(args.config_dir, args.duration, args.seed, args.output_events, args.output_trajectories)
|
return run_simulation(args.config_dir, args.duration, args.seed, args.output_events, args.output_trajectories)
|
||||||
elif args.command == "run-experiment":
|
elif args.command == "run-experiment":
|
||||||
|
|||||||
@@ -223,6 +223,16 @@ class Robot:
|
|||||||
return True
|
return True
|
||||||
return zone_id in self.allowed_zones
|
return zone_id in self.allowed_zones
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_loaded(self) -> bool:
|
||||||
|
"""Check if robot is actively carrying cargo."""
|
||||||
|
return self.current_state in (RobotState.LOADED_TRANSIT, RobotState.DROPPING)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def current_payload_kg(self) -> float:
|
||||||
|
"""Active payload weight carried in kg."""
|
||||||
|
return self.payload_capacity if self.is_loaded else 0.0
|
||||||
|
|
||||||
def update_position(
|
def update_position(
|
||||||
self,
|
self,
|
||||||
new_position: Position3D,
|
new_position: Position3D,
|
||||||
|
|||||||
@@ -239,6 +239,8 @@ class SimulationEnvironment:
|
|||||||
"pos": [round(robot.position.x, 2), round(robot.position.y, 2), round(robot.position.z, 2)],
|
"pos": [round(robot.position.x, 2), round(robot.position.y, 2), round(robot.position.z, 2)],
|
||||||
"yaw_deg": round(robot.yaw_degrees, 1),
|
"yaw_deg": round(robot.yaw_degrees, 1),
|
||||||
"state": robot.current_state.value,
|
"state": robot.current_state.value,
|
||||||
|
"battery_percent": round(robot.battery_percent, 1),
|
||||||
|
"is_loaded": robot.current_payload_kg > 0.0,
|
||||||
})
|
})
|
||||||
|
|
||||||
def record_event(
|
def record_event(
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
"""Visualization package for Omniverse USD and trajectory playback."""
|
||||||
|
|
||||||
|
from warehouse_twin.visualization.animated_usd import (
|
||||||
|
AnimatedUSDGenerator,
|
||||||
|
compute_battery_indicator_color,
|
||||||
|
)
|
||||||
|
from warehouse_twin.visualization.trajectory_player import (
|
||||||
|
RobotPlaybackState,
|
||||||
|
TrajectoryData,
|
||||||
|
TrajectoryPlayer,
|
||||||
|
interpolate_robot_state,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"AnimatedUSDGenerator",
|
||||||
|
"compute_battery_indicator_color",
|
||||||
|
"RobotPlaybackState",
|
||||||
|
"TrajectoryData",
|
||||||
|
"TrajectoryPlayer",
|
||||||
|
"interpolate_robot_state",
|
||||||
|
]
|
||||||
@@ -0,0 +1,322 @@
|
|||||||
|
"""Time-sampled OpenUSD animation stage generator for Omniverse visualization.
|
||||||
|
|
||||||
|
Generates valid ASCII OpenUSD (.usda) scenes containing time-sampled AMR kinematic tracks
|
||||||
|
(translation, rotation, status beacon colors, battery indicators, and payload visibility).
|
||||||
|
Stages can be played back natively in NVIDIA Omniverse Kit's timeline without external plugins.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
from warehouse_twin.domain.robot import Robot, RobotTypeSpec
|
||||||
|
from warehouse_twin.domain.warehouse import WarehouseModel
|
||||||
|
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
|
||||||
|
from warehouse_twin.visualization.trajectory_player import (
|
||||||
|
RobotPlaybackState,
|
||||||
|
TrajectoryData,
|
||||||
|
interpolate_robot_state,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def compute_battery_indicator_color(battery_percent: float) -> Tuple[float, float, float]:
|
||||||
|
"""Return RGB color reflecting battery health: Green (>50%) -> Yellow (>20%) -> Red (<=20%)."""
|
||||||
|
if battery_percent > 50.0:
|
||||||
|
return (0.15, 0.85, 0.25) # Healthy Green
|
||||||
|
elif battery_percent > 20.0:
|
||||||
|
return (0.95, 0.75, 0.10) # Warning Amber
|
||||||
|
else:
|
||||||
|
return (0.95, 0.15, 0.15) # Critical Red
|
||||||
|
|
||||||
|
|
||||||
|
class AnimatedUSDGenerator:
|
||||||
|
"""Generates time-sampled OpenUSD (.usda) scenes with kinematic playback tracks."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
model: WarehouseModel,
|
||||||
|
trajectory_data: TrajectoryData,
|
||||||
|
robots: Optional[List[Robot]] = None,
|
||||||
|
sample_step_seconds: float = 1.0,
|
||||||
|
timecodes_per_second: float = 24.0,
|
||||||
|
include_routing_network: bool = True,
|
||||||
|
) -> None:
|
||||||
|
self.model = model
|
||||||
|
self.trajectory_data = trajectory_data
|
||||||
|
self.robots = robots or []
|
||||||
|
self.sample_step = max(0.1, sample_step_seconds)
|
||||||
|
self.timecodes_per_second = max(1.0, timecodes_per_second)
|
||||||
|
self.include_routing_network = include_routing_network
|
||||||
|
|
||||||
|
# Fallback robots if not explicitly provided
|
||||||
|
if not self.robots and self.trajectory_data:
|
||||||
|
robot_ids = self.trajectory_data.get_robot_ids()
|
||||||
|
# Infer basic robot types from ID naming
|
||||||
|
for r_id in robot_ids:
|
||||||
|
is_heavy = "heavy" in r_id
|
||||||
|
t_spec = RobotTypeSpec(
|
||||||
|
type_id="heavy_amr" if is_heavy else "light_amr",
|
||||||
|
description="Inferred AMR",
|
||||||
|
maximum_speed=1.2 if is_heavy else 1.8,
|
||||||
|
payload_capacity_kg=1000.0 if is_heavy else 100.0,
|
||||||
|
battery_capacity_kwh=20.0 if is_heavy else 8.0,
|
||||||
|
charging_power_kw=50.0 if is_heavy else 25.0,
|
||||||
|
energy_consumption={"idle": 0.05, "moving_empty": 0.5, "moving_loaded": 0.9, "handling": 0.3},
|
||||||
|
allowed_zones={"zone_a", "zone_b", "zone_c"} if is_heavy else {"zone_a", "zone_c"},
|
||||||
|
)
|
||||||
|
self.robots.append(Robot(
|
||||||
|
robot_id=r_id,
|
||||||
|
robot_type=t_spec.type_id,
|
||||||
|
position=self.model.dimensions.center(),
|
||||||
|
maximum_speed=t_spec.maximum_speed,
|
||||||
|
payload_capacity=t_spec.payload_capacity_kg,
|
||||||
|
battery_level=t_spec.battery_capacity_kwh,
|
||||||
|
battery_capacity=t_spec.battery_capacity_kwh,
|
||||||
|
energy_consumption=t_spec.energy_consumption,
|
||||||
|
allowed_zones=t_spec.allowed_zones,
|
||||||
|
))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_config_and_trajectory(
|
||||||
|
cls,
|
||||||
|
bundle: Any,
|
||||||
|
trajectory_data: TrajectoryData,
|
||||||
|
sample_step_seconds: float = 1.0,
|
||||||
|
timecodes_per_second: float = 24.0,
|
||||||
|
) -> AnimatedUSDGenerator:
|
||||||
|
"""Construct animated generator from ConfigBundle and TrajectoryData."""
|
||||||
|
model = WarehouseModel.from_config_dict(bundle.warehouse)
|
||||||
|
|
||||||
|
type_specs: Dict[str, RobotTypeSpec] = {}
|
||||||
|
for t_id, t_data in bundle.robots.get("robot_types", {}).items():
|
||||||
|
type_specs[t_id] = RobotTypeSpec.from_dict(t_id, t_data)
|
||||||
|
|
||||||
|
robots: List[Robot] = []
|
||||||
|
for r_data in bundle.robots.get("fleet", []):
|
||||||
|
robots.append(Robot.from_fleet_dict(r_data, type_specs))
|
||||||
|
|
||||||
|
return cls(
|
||||||
|
model=model,
|
||||||
|
trajectory_data=trajectory_data,
|
||||||
|
robots=robots,
|
||||||
|
sample_step_seconds=sample_step_seconds,
|
||||||
|
timecodes_per_second=timecodes_per_second,
|
||||||
|
)
|
||||||
|
|
||||||
|
def generate_animated_usda(self) -> str:
|
||||||
|
"""Render complete ASCII OpenUSD stage with time-sampled robot animation."""
|
||||||
|
dims = self.model.dimensions
|
||||||
|
w, d, h = dims.width, dims.depth, dims.height
|
||||||
|
duration = self.trajectory_data.duration
|
||||||
|
fps = self.timecodes_per_second
|
||||||
|
end_frame = round(duration * fps)
|
||||||
|
|
||||||
|
lines: List[str] = [
|
||||||
|
"#usda 1.0",
|
||||||
|
"(",
|
||||||
|
' defaultPrim = "World"',
|
||||||
|
" metersPerUnit = 1.0",
|
||||||
|
' upAxis = "Z"',
|
||||||
|
" startTimeCode = 0.0",
|
||||||
|
f" endTimeCode = {end_frame:.1f}",
|
||||||
|
f" timeCodesPerSecond = {fps:.1f}",
|
||||||
|
' doc = "Warehouse Robot Fleet Digital Twin - Time-Sampled Dynamic Stage (Phase 7)"',
|
||||||
|
")",
|
||||||
|
"",
|
||||||
|
'def Xform "World"',
|
||||||
|
"{",
|
||||||
|
" # -------------------------------------------------------------------------",
|
||||||
|
" # Environment Lighting",
|
||||||
|
" # -------------------------------------------------------------------------",
|
||||||
|
' def DistantLight "SunLight"',
|
||||||
|
" {",
|
||||||
|
" float inputs:intensity = 3500.0",
|
||||||
|
" color3f inputs:color = (0.98, 0.96, 0.92)",
|
||||||
|
" float inputs:angle = 1.0",
|
||||||
|
" double3 xformOp:rotateXYZ = (-45.0, 30.0, 0.0)",
|
||||||
|
' uniform token[] xformOpOrder = ["xformOp:rotateXYZ"]',
|
||||||
|
" }",
|
||||||
|
"",
|
||||||
|
' def DomeLight "SkyLight"',
|
||||||
|
" {",
|
||||||
|
" float inputs:intensity = 800.0",
|
||||||
|
" color3f inputs:color = (0.85, 0.90, 0.98)",
|
||||||
|
" }",
|
||||||
|
"",
|
||||||
|
" # -------------------------------------------------------------------------",
|
||||||
|
" # Facility Shell: Ground Floor & Boundary Markers",
|
||||||
|
" # -------------------------------------------------------------------------",
|
||||||
|
' def Scope "Architecture"',
|
||||||
|
" {",
|
||||||
|
' def Mesh "GroundFloor"',
|
||||||
|
" {",
|
||||||
|
" float3[] extent = [(-2.0, -2.0, -0.2), (62.0, 42.0, 0.0)]",
|
||||||
|
" int[] faceVertexCounts = [4]",
|
||||||
|
" int[] faceVertexIndices = [0, 1, 2, 3]",
|
||||||
|
f" point3f[] points = [(-2.0, -2.0, 0.0), ({w + 2.0}, -2.0, 0.0), ({w + 2.0}, {d + 2.0}, 0.0), (-2.0, {d + 2.0}, 0.0)]",
|
||||||
|
" normal3f[] normals = [(0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 1.0)]",
|
||||||
|
" color3f[] primvars:displayColor = [(0.14, 0.16, 0.19)]",
|
||||||
|
" float[] primvars:displayRoughness = [0.9]",
|
||||||
|
" }",
|
||||||
|
" }",
|
||||||
|
]
|
||||||
|
|
||||||
|
# Reuse base USD generator static elements (Zones, Racks, Stations, Chargers, Corridors)
|
||||||
|
base_gen = WarehouseUSDGenerator(
|
||||||
|
model=self.model,
|
||||||
|
robots=[],
|
||||||
|
include_routing_network=self.include_routing_network,
|
||||||
|
)
|
||||||
|
base_content = base_gen.generate_usda_content()
|
||||||
|
|
||||||
|
# Extract intermediate static scopes (Zones, StorageRacks, Stations, ChargingStations, NavigationNetwork)
|
||||||
|
# from base content to avoid duplicating hundreds of lines of static geometry code
|
||||||
|
start_marker = ' def Scope "Zones"'
|
||||||
|
end_marker = ' def Scope "Robots"'
|
||||||
|
if end_marker not in base_content:
|
||||||
|
end_marker = "\n}" # End of World if no robots in base_content
|
||||||
|
|
||||||
|
idx_start = base_content.find(start_marker)
|
||||||
|
idx_end = base_content.find(end_marker, idx_start) if idx_start != -1 else -1
|
||||||
|
|
||||||
|
if idx_start != -1 and idx_end != -1:
|
||||||
|
static_body = base_content[idx_start:idx_end].rstrip()
|
||||||
|
lines.append("")
|
||||||
|
lines.append(static_body)
|
||||||
|
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
# Dynamic Time-Sampled Robots Scope
|
||||||
|
# -------------------------------------------------------------------------
|
||||||
|
lines.extend([
|
||||||
|
"",
|
||||||
|
" # -------------------------------------------------------------------------",
|
||||||
|
" # Time-Sampled Animated AMR Fleet (Phase 7 Kinematic Playback)",
|
||||||
|
" # -------------------------------------------------------------------------",
|
||||||
|
' def Scope "Robots"',
|
||||||
|
" {",
|
||||||
|
])
|
||||||
|
|
||||||
|
# Generate sample timestamps in simulation seconds
|
||||||
|
sim_times: List[float] = []
|
||||||
|
cur_t = self.trajectory_data.start_time
|
||||||
|
while cur_t <= self.trajectory_data.end_time:
|
||||||
|
sim_times.append(round(cur_t, 3))
|
||||||
|
cur_t += self.sample_step
|
||||||
|
if not sim_times or sim_times[-1] < self.trajectory_data.end_time:
|
||||||
|
sim_times.append(round(self.trajectory_data.end_time, 3))
|
||||||
|
|
||||||
|
# Build trajectory tracks for each robot
|
||||||
|
for robot in self.robots:
|
||||||
|
r_id = robot.robot_id
|
||||||
|
pts = self.trajectory_data.robots.get(r_id, [])
|
||||||
|
is_heavy = "heavy" in robot.robot_type
|
||||||
|
|
||||||
|
if is_heavy:
|
||||||
|
chassis_col = "(0.92, 0.65, 0.08)"
|
||||||
|
scale_chassis = (0.70, 0.50, 0.225)
|
||||||
|
scale_payload = (0.60, 0.45, 0.35)
|
||||||
|
elev_z = 0.225
|
||||||
|
else:
|
||||||
|
chassis_col = "(0.88, 0.90, 0.95)"
|
||||||
|
scale_chassis = (0.40, 0.30, 0.175)
|
||||||
|
scale_payload = (0.35, 0.25, 0.25)
|
||||||
|
elev_z = 0.175
|
||||||
|
|
||||||
|
# Compute sampled states
|
||||||
|
trans_samples: List[str] = []
|
||||||
|
rot_samples: List[str] = []
|
||||||
|
beacon_color_samples: List[str] = []
|
||||||
|
battery_color_samples: List[str] = []
|
||||||
|
payload_vis_samples: List[str] = []
|
||||||
|
|
||||||
|
for st_time in sim_times:
|
||||||
|
frame_code = round((st_time - self.trajectory_data.start_time) * fps, 2)
|
||||||
|
state = interpolate_robot_state(r_id, pts, st_time)
|
||||||
|
|
||||||
|
# Translation & Rotation
|
||||||
|
trans_samples.append(f" {frame_code:.1f}: ({state.x:.2f}, {state.y:.2f}, {elev_z:.3f}),")
|
||||||
|
rot_samples.append(f" {frame_code:.1f}: (0.0, 0.0, {state.yaw_degrees:.1f}),")
|
||||||
|
|
||||||
|
# Beacon color
|
||||||
|
r, g, b = state.status_color
|
||||||
|
beacon_color_samples.append(f" {frame_code:.1f}: [({r:.2f}, {g:.2f}, {b:.2f})],")
|
||||||
|
|
||||||
|
# Battery LED color
|
||||||
|
br, bg, bb = compute_battery_indicator_color(state.battery_percent)
|
||||||
|
battery_color_samples.append(f" {frame_code:.1f}: [({br:.2f}, {bg:.2f}, {bb:.2f})],")
|
||||||
|
|
||||||
|
# Payload visibility
|
||||||
|
vis_tok = '"inherited"' if state.is_loaded else '"invisible"'
|
||||||
|
payload_vis_samples.append(f" {frame_code:.1f}: {vis_tok},")
|
||||||
|
|
||||||
|
# Format robot USD definition
|
||||||
|
lines.extend([
|
||||||
|
f' def Xform "{r_id}"',
|
||||||
|
" {",
|
||||||
|
" double3 xformOp:translate.timeSamples = {",
|
||||||
|
*trans_samples,
|
||||||
|
" }",
|
||||||
|
" double3 xformOp:rotateXYZ.timeSamples = {",
|
||||||
|
*rot_samples,
|
||||||
|
" }",
|
||||||
|
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]',
|
||||||
|
"",
|
||||||
|
' def Cube "Chassis"',
|
||||||
|
" {",
|
||||||
|
f" double3 xformOp:scale = ({scale_chassis[0]}, {scale_chassis[1]}, {scale_chassis[2]})",
|
||||||
|
' uniform token[] xformOpOrder = ["xformOp:scale"]',
|
||||||
|
f" color3f[] primvars:displayColor = [{chassis_col}]",
|
||||||
|
" float[] primvars:displayRoughness = [0.25]",
|
||||||
|
" }",
|
||||||
|
"",
|
||||||
|
' def Cube "StatusDome"',
|
||||||
|
" {",
|
||||||
|
f" double3 xformOp:translate = (0.0, 0.0, {scale_chassis[2] + 0.08:.3f})",
|
||||||
|
f" double3 xformOp:scale = ({scale_chassis[0] * 0.4:.3f}, {scale_chassis[1] * 0.4:.3f}, 0.05)",
|
||||||
|
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
|
||||||
|
" color3f[] primvars:displayColor.timeSamples = {",
|
||||||
|
*beacon_color_samples,
|
||||||
|
" }",
|
||||||
|
" }",
|
||||||
|
"",
|
||||||
|
' def Cube "BatteryLED"',
|
||||||
|
" {",
|
||||||
|
f" double3 xformOp:translate = (0.0, {-scale_chassis[1] * 0.75:.3f}, {scale_chassis[2] + 0.02:.3f})",
|
||||||
|
" double3 xformOp:scale = (0.08, 0.02, 0.02)",
|
||||||
|
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
|
||||||
|
" color3f[] primvars:displayColor.timeSamples = {",
|
||||||
|
*battery_color_samples,
|
||||||
|
" }",
|
||||||
|
" }",
|
||||||
|
"",
|
||||||
|
' def Cube "Payload"',
|
||||||
|
" {",
|
||||||
|
f" double3 xformOp:translate = (0.0, 0.0, {scale_chassis[2] + scale_payload[2] + 0.02:.3f})",
|
||||||
|
f" double3 xformOp:scale = ({scale_payload[0]}, {scale_payload[1]}, {scale_payload[2]})",
|
||||||
|
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
|
||||||
|
" color3f[] primvars:displayColor = [(0.82, 0.62, 0.35)]",
|
||||||
|
" float[] primvars:displayRoughness = [0.8]",
|
||||||
|
" token visibility.timeSamples = {",
|
||||||
|
*payload_vis_samples,
|
||||||
|
" }",
|
||||||
|
" }",
|
||||||
|
" }",
|
||||||
|
])
|
||||||
|
|
||||||
|
lines.extend([
|
||||||
|
" }",
|
||||||
|
"}",
|
||||||
|
"",
|
||||||
|
])
|
||||||
|
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def export_usda(self, filepath: Path | str) -> Path:
|
||||||
|
"""Render and save the animated OpenUSD scene to disk."""
|
||||||
|
target_path = Path(filepath).resolve()
|
||||||
|
target_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
content = self.generate_animated_usda()
|
||||||
|
target_path.write_text(content, encoding="utf-8")
|
||||||
|
return target_path
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
"""Trajectory playback and spatial interpolation engine for Omniverse visualization.
|
||||||
|
|
||||||
|
Provides smooth, continuous time-interpolated 3D poses, heading angles,
|
||||||
|
battery state, payload attachment, and status beacon colors from discrete-event
|
||||||
|
simulation trajectory recordings.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import bisect
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
|
||||||
|
# Semantic status color palette for AMR indicator dome
|
||||||
|
STATUS_COLOR_MAP: Dict[str, Tuple[float, float, float]] = {
|
||||||
|
"IDLE": (0.15, 0.75, 0.95), # Electric Cyan
|
||||||
|
"DISPATCHED": (0.30, 0.60, 1.00), # Soft Sky Blue
|
||||||
|
"PICKING": (0.20, 0.90, 0.35), # Bright Emerald
|
||||||
|
"LOADED_TRANSIT": (0.95, 0.75, 0.10), # Industrial Gold / Amber
|
||||||
|
"DROPPING": (0.20, 0.90, 0.35), # Bright Emerald
|
||||||
|
"TRANSIT_TO_CHARGE": (0.95, 0.50, 0.15),# Caution Orange
|
||||||
|
"CHARGING": (1.00, 0.30, 0.10), # High-Energy Neon Orange/Red
|
||||||
|
"MAINTENANCE": (0.90, 0.15, 0.15), # Fault Red
|
||||||
|
}
|
||||||
|
DEFAULT_STATUS_COLOR: Tuple[float, float, float] = (0.7, 0.7, 0.7)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RobotPlaybackState:
|
||||||
|
"""Continuous playback state of an individual AMR at a specific timestamp."""
|
||||||
|
|
||||||
|
robot_id: str
|
||||||
|
time: float
|
||||||
|
x: float
|
||||||
|
y: float
|
||||||
|
z: float
|
||||||
|
yaw_degrees: float
|
||||||
|
state: str
|
||||||
|
battery_percent: float
|
||||||
|
is_loaded: bool
|
||||||
|
status_color: Tuple[float, float, float] = field(default_factory=lambda: (0.15, 0.75, 0.95))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def position(self) -> Tuple[float, float, float]:
|
||||||
|
"""Return (x, y, z) tuple in standard meters."""
|
||||||
|
return (self.x, self.y, self.z)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def formatted_time(self) -> str:
|
||||||
|
"""Format timestamp into HH:MM:SS format."""
|
||||||
|
total_seconds = int(self.time)
|
||||||
|
hours = total_seconds // 3600
|
||||||
|
minutes = (total_seconds % 3600) // 60
|
||||||
|
seconds = total_seconds % 60
|
||||||
|
return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
|
||||||
|
|
||||||
|
|
||||||
|
def interpolate_yaw(yaw1: float, yaw2: float, alpha: float) -> float:
|
||||||
|
"""Interpolate angle in degrees along the shortest circular arc.
|
||||||
|
|
||||||
|
Handles angle wrap-around across -180/180 or 0/360 boundary to prevent
|
||||||
|
unnatural full-circle rotations.
|
||||||
|
"""
|
||||||
|
diff = (yaw2 - yaw1 + 180.0) % 360.0 - 180.0
|
||||||
|
interpolated = yaw1 + alpha * diff
|
||||||
|
return (interpolated + 180.0) % 360.0 - 180.0
|
||||||
|
|
||||||
|
|
||||||
|
def interpolate_robot_state(
|
||||||
|
robot_id: str,
|
||||||
|
points: List[Dict[str, Any]],
|
||||||
|
query_time: float,
|
||||||
|
) -> RobotPlaybackState:
|
||||||
|
"""Compute interpolated AMR state from discrete trajectory waypoints.
|
||||||
|
|
||||||
|
Uses binary search for O(log N) lookup and linear interpolation for
|
||||||
|
continuous kinematic properties (x, y, z, yaw, battery).
|
||||||
|
"""
|
||||||
|
if not points:
|
||||||
|
return RobotPlaybackState(
|
||||||
|
robot_id=robot_id,
|
||||||
|
time=query_time,
|
||||||
|
x=0.0,
|
||||||
|
y=0.0,
|
||||||
|
z=0.0,
|
||||||
|
yaw_degrees=0.0,
|
||||||
|
state="IDLE",
|
||||||
|
battery_percent=100.0,
|
||||||
|
is_loaded=False,
|
||||||
|
status_color=STATUS_COLOR_MAP["IDLE"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Boundary conditions
|
||||||
|
if query_time <= points[0]["t"]:
|
||||||
|
p = points[0]
|
||||||
|
state_str = str(p.get("state", "IDLE"))
|
||||||
|
pos = p.get("pos", [0.0, 0.0, 0.0])
|
||||||
|
return RobotPlaybackState(
|
||||||
|
robot_id=robot_id,
|
||||||
|
time=query_time,
|
||||||
|
x=float(pos[0]),
|
||||||
|
y=float(pos[1]),
|
||||||
|
z=float(pos[2]) if len(pos) > 2 else 0.0,
|
||||||
|
yaw_degrees=float(p.get("yaw_deg", 0.0)),
|
||||||
|
state=state_str,
|
||||||
|
battery_percent=float(p.get("battery_percent", 100.0)),
|
||||||
|
is_loaded=bool(p.get("is_loaded", state_str in ("LOADED_TRANSIT", "DROPPING"))),
|
||||||
|
status_color=STATUS_COLOR_MAP.get(state_str, DEFAULT_STATUS_COLOR),
|
||||||
|
)
|
||||||
|
|
||||||
|
if query_time >= points[-1]["t"]:
|
||||||
|
p = points[-1]
|
||||||
|
state_str = str(p.get("state", "IDLE"))
|
||||||
|
pos = p.get("pos", [0.0, 0.0, 0.0])
|
||||||
|
return RobotPlaybackState(
|
||||||
|
robot_id=robot_id,
|
||||||
|
time=query_time,
|
||||||
|
x=float(pos[0]),
|
||||||
|
y=float(pos[1]),
|
||||||
|
z=float(pos[2]) if len(pos) > 2 else 0.0,
|
||||||
|
yaw_degrees=float(p.get("yaw_deg", 0.0)),
|
||||||
|
state=state_str,
|
||||||
|
battery_percent=float(p.get("battery_percent", 100.0)),
|
||||||
|
is_loaded=bool(p.get("is_loaded", state_str in ("LOADED_TRANSIT", "DROPPING"))),
|
||||||
|
status_color=STATUS_COLOR_MAP.get(state_str, DEFAULT_STATUS_COLOR),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Binary search for interval
|
||||||
|
timestamps = [pt["t"] for pt in points]
|
||||||
|
idx = bisect.bisect_right(timestamps, query_time) - 1
|
||||||
|
p1 = points[idx]
|
||||||
|
p2 = points[idx + 1]
|
||||||
|
|
||||||
|
t1, t2 = p1["t"], p2["t"]
|
||||||
|
dt = t2 - t1
|
||||||
|
alpha = (query_time - t1) / dt if dt > 1e-6 else 0.0
|
||||||
|
alpha = max(0.0, min(1.0, alpha))
|
||||||
|
|
||||||
|
# Position interpolation
|
||||||
|
pos1 = p1.get("pos", [0.0, 0.0, 0.0])
|
||||||
|
pos2 = p2.get("pos", [0.0, 0.0, 0.0])
|
||||||
|
x = pos1[0] + alpha * (pos2[0] - pos1[0])
|
||||||
|
y = pos1[1] + alpha * (pos2[1] - pos1[1])
|
||||||
|
z1 = pos1[2] if len(pos1) > 2 else 0.0
|
||||||
|
z2 = pos2[2] if len(pos2) > 2 else 0.0
|
||||||
|
z = z1 + alpha * (z2 - z1)
|
||||||
|
|
||||||
|
# Heading interpolation with angle wrap handling
|
||||||
|
yaw1 = float(p1.get("yaw_deg", 0.0))
|
||||||
|
yaw2 = float(p2.get("yaw_deg", 0.0))
|
||||||
|
yaw = interpolate_yaw(yaw1, yaw2, alpha)
|
||||||
|
|
||||||
|
# Battery interpolation
|
||||||
|
bat1 = float(p1.get("battery_percent", 100.0))
|
||||||
|
bat2 = float(p2.get("battery_percent", 100.0))
|
||||||
|
battery = bat1 + alpha * (bat2 - bat1)
|
||||||
|
|
||||||
|
# Discrete state and payload (step transition at midpoint)
|
||||||
|
source_pt = p1 if alpha < 0.5 else p2
|
||||||
|
state_str = str(source_pt.get("state", "IDLE"))
|
||||||
|
is_loaded = bool(source_pt.get("is_loaded", state_str in ("LOADED_TRANSIT", "DROPPING")))
|
||||||
|
color = STATUS_COLOR_MAP.get(state_str, DEFAULT_STATUS_COLOR)
|
||||||
|
|
||||||
|
return RobotPlaybackState(
|
||||||
|
robot_id=robot_id,
|
||||||
|
time=query_time,
|
||||||
|
x=round(x, 4),
|
||||||
|
y=round(y, 4),
|
||||||
|
z=round(z, 4),
|
||||||
|
yaw_degrees=round(yaw, 2),
|
||||||
|
state=state_str,
|
||||||
|
battery_percent=round(battery, 2),
|
||||||
|
is_loaded=is_loaded,
|
||||||
|
status_color=color,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TrajectoryData:
|
||||||
|
"""Container for fleet trajectory recordings loaded from disk or memory."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
robots: Dict[str, List[Dict[str, Any]]],
|
||||||
|
metadata: Optional[Dict[str, Any]] = None,
|
||||||
|
) -> None:
|
||||||
|
self.robots = {r_id: sorted(pts, key=lambda p: p["t"]) for r_id, pts in robots.items()}
|
||||||
|
self.metadata = metadata or {}
|
||||||
|
|
||||||
|
# Compute fleet-wide time boundaries
|
||||||
|
all_times: List[float] = []
|
||||||
|
for pts in self.robots.values():
|
||||||
|
if pts:
|
||||||
|
all_times.append(pts[0]["t"])
|
||||||
|
all_times.append(pts[-1]["t"])
|
||||||
|
|
||||||
|
self.start_time: float = min(all_times) if all_times else 0.0
|
||||||
|
self.end_time: float = max(all_times) if all_times else 0.0
|
||||||
|
self.duration: float = max(0.0, self.end_time - self.start_time)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_file(cls, filepath: Path | str) -> TrajectoryData:
|
||||||
|
"""Load trajectory dataset from JSON file."""
|
||||||
|
target = Path(filepath).resolve()
|
||||||
|
if not target.exists():
|
||||||
|
raise FileNotFoundError(f"Trajectory file not found: {target}")
|
||||||
|
|
||||||
|
with open(target, "r", encoding="utf-8") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
|
return cls.from_dict(data)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_dict(cls, data: Dict[str, Any]) -> TrajectoryData:
|
||||||
|
"""Load trajectory dataset from dictionary structure."""
|
||||||
|
robots_raw = data.get("robots", {})
|
||||||
|
metadata = data.get("metadata", {})
|
||||||
|
return cls(robots=robots_raw, metadata=metadata)
|
||||||
|
|
||||||
|
def get_robot_ids(self) -> List[str]:
|
||||||
|
"""Return list of all robot identifiers in trajectory dataset."""
|
||||||
|
return sorted(self.robots.keys())
|
||||||
|
|
||||||
|
def get_point_count(self) -> int:
|
||||||
|
"""Total number of recorded trajectory waypoints."""
|
||||||
|
return sum(len(pts) for pts in self.robots.values())
|
||||||
|
|
||||||
|
|
||||||
|
class TrajectoryPlayer:
|
||||||
|
"""Coordinates simulation time playback and dispatches interpolated fleet poses."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
data: TrajectoryData,
|
||||||
|
playback_speed: float = 1.0,
|
||||||
|
loop: bool = False,
|
||||||
|
) -> None:
|
||||||
|
self.data = data
|
||||||
|
self.current_time = self.data.start_time
|
||||||
|
self.playback_speed = max(0.1, min(50.0, playback_speed))
|
||||||
|
self.loop = loop
|
||||||
|
self.is_playing = False
|
||||||
|
self._callbacks: List[Callable[[Dict[str, RobotPlaybackState]], None]] = []
|
||||||
|
|
||||||
|
@property
|
||||||
|
def start_time(self) -> float:
|
||||||
|
return self.data.start_time
|
||||||
|
|
||||||
|
@property
|
||||||
|
def end_time(self) -> float:
|
||||||
|
return self.data.end_time
|
||||||
|
|
||||||
|
@property
|
||||||
|
def duration(self) -> float:
|
||||||
|
return self.data.duration
|
||||||
|
|
||||||
|
@property
|
||||||
|
def progress_fraction(self) -> float:
|
||||||
|
"""Playback progress normalized between 0.0 and 1.0."""
|
||||||
|
if self.duration <= 1e-4:
|
||||||
|
return 1.0
|
||||||
|
return max(0.0, min(1.0, (self.current_time - self.start_time) / self.duration))
|
||||||
|
|
||||||
|
def play(self) -> None:
|
||||||
|
"""Start or resume playback."""
|
||||||
|
if self.current_time >= self.end_time and not self.loop:
|
||||||
|
self.current_time = self.start_time
|
||||||
|
self.is_playing = True
|
||||||
|
|
||||||
|
def pause(self) -> None:
|
||||||
|
"""Pause playback at current time."""
|
||||||
|
self.is_playing = False
|
||||||
|
|
||||||
|
def toggle_play(self) -> bool:
|
||||||
|
"""Toggle play/pause state. Returns new is_playing value."""
|
||||||
|
if self.is_playing:
|
||||||
|
self.pause()
|
||||||
|
else:
|
||||||
|
self.play()
|
||||||
|
return self.is_playing
|
||||||
|
|
||||||
|
def reset(self) -> None:
|
||||||
|
"""Stop playback and rewind to beginning."""
|
||||||
|
self.is_playing = False
|
||||||
|
self.seek(self.start_time)
|
||||||
|
|
||||||
|
def seek(self, target_time: float) -> Dict[str, RobotPlaybackState]:
|
||||||
|
"""Seek to a specific simulation timestamp and notify observers."""
|
||||||
|
self.current_time = max(self.start_time, min(self.end_time, target_time))
|
||||||
|
state = self.get_fleet_state(self.current_time)
|
||||||
|
self._notify_callbacks(state)
|
||||||
|
return state
|
||||||
|
|
||||||
|
def set_speed(self, speed: float) -> None:
|
||||||
|
"""Set playback speed multiplier (e.g., 0.5, 1.0, 2.0, 5.0, 10.0)."""
|
||||||
|
self.playback_speed = max(0.1, min(50.0, speed))
|
||||||
|
|
||||||
|
def advance(self, wall_dt_seconds: float) -> Dict[str, RobotPlaybackState]:
|
||||||
|
"""Advance playback time by wall-clock delta seconds multiplied by speed."""
|
||||||
|
if not self.is_playing or wall_dt_seconds <= 0.0:
|
||||||
|
return self.get_fleet_state(self.current_time)
|
||||||
|
|
||||||
|
sim_dt = wall_dt_seconds * self.playback_speed
|
||||||
|
next_time = self.current_time + sim_dt
|
||||||
|
|
||||||
|
if next_time >= self.end_time:
|
||||||
|
if self.loop:
|
||||||
|
# Wrap around
|
||||||
|
overshoot = next_time - self.end_time
|
||||||
|
self.current_time = self.start_time + (overshoot % max(1.0, self.duration))
|
||||||
|
else:
|
||||||
|
self.current_time = self.end_time
|
||||||
|
self.is_playing = False
|
||||||
|
else:
|
||||||
|
self.current_time = next_time
|
||||||
|
|
||||||
|
state = self.get_fleet_state(self.current_time)
|
||||||
|
self._notify_callbacks(state)
|
||||||
|
return state
|
||||||
|
|
||||||
|
def get_fleet_state(self, time: Optional[float] = None) -> Dict[str, RobotPlaybackState]:
|
||||||
|
"""Compute the continuous state of every AMR in the fleet at given or current time."""
|
||||||
|
t = self.current_time if time is None else time
|
||||||
|
fleet_state: Dict[str, RobotPlaybackState] = {}
|
||||||
|
for r_id, points in self.data.robots.items():
|
||||||
|
fleet_state[r_id] = interpolate_robot_state(r_id, points, t)
|
||||||
|
return fleet_state
|
||||||
|
|
||||||
|
def register_callback(self, callback: Callable[[Dict[str, RobotPlaybackState]], None]) -> None:
|
||||||
|
"""Register a subscriber callback invoked whenever playback state updates."""
|
||||||
|
if callback not in self._callbacks:
|
||||||
|
self._callbacks.append(callback)
|
||||||
|
|
||||||
|
def unregister_callback(self, callback: Callable[[Dict[str, RobotPlaybackState]], None]) -> None:
|
||||||
|
"""Unregister a subscriber callback."""
|
||||||
|
if callback in self._callbacks:
|
||||||
|
self._callbacks.remove(callback)
|
||||||
|
|
||||||
|
def _notify_callbacks(self, state: Dict[str, RobotPlaybackState]) -> None:
|
||||||
|
"""Safely invoke registered callbacks."""
|
||||||
|
for cb in list(self._callbacks):
|
||||||
|
try:
|
||||||
|
cb(state)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def cleanup(self) -> None:
|
||||||
|
"""Halt playback and release all subscriber references to prevent memory leaks."""
|
||||||
|
self.is_playing = False
|
||||||
|
self._callbacks.clear()
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
"""Unit tests for time-sampled OpenUSD animation stage generator."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from warehouse_twin.config.loader import ConfigLoader
|
||||||
|
from warehouse_twin.visualization.animated_usd import (
|
||||||
|
AnimatedUSDGenerator,
|
||||||
|
compute_battery_indicator_color,
|
||||||
|
)
|
||||||
|
from warehouse_twin.visualization.trajectory_player import TrajectoryData
|
||||||
|
|
||||||
|
|
||||||
|
def test_battery_indicator_colors():
|
||||||
|
"""Verify RGB color codes across high, medium, and low battery levels."""
|
||||||
|
green = compute_battery_indicator_color(85.0)
|
||||||
|
assert green[1] > 0.8 # Strong green channel
|
||||||
|
|
||||||
|
amber = compute_battery_indicator_color(35.0)
|
||||||
|
assert amber[0] > 0.8 and amber[1] > 0.7 # Amber / Yellow
|
||||||
|
|
||||||
|
red = compute_battery_indicator_color(15.0)
|
||||||
|
assert red[0] > 0.8 and red[1] < 0.3 # Bright red
|
||||||
|
|
||||||
|
|
||||||
|
def test_animated_usd_generation_and_export(project_config_dir: Path, tmp_path: Path):
|
||||||
|
"""Verify generated USDA syntax, time-sampled attributes, and file export."""
|
||||||
|
loader = ConfigLoader(project_config_dir)
|
||||||
|
bundle = loader.load_all()
|
||||||
|
|
||||||
|
mock_trajectory = {
|
||||||
|
"metadata": {"simulation_duration": 10.0},
|
||||||
|
"robots": {
|
||||||
|
"amr_light_01": [
|
||||||
|
{"t": 0.0, "pos": [2.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "IDLE", "battery_percent": 100.0, "is_loaded": False},
|
||||||
|
{"t": 5.0, "pos": [10.0, 36.0, 0.0], "yaw_deg": 0.0, "state": "LOADED_TRANSIT", "battery_percent": 98.0, "is_loaded": True},
|
||||||
|
{"t": 10.0, "pos": [15.0, 36.0, 0.0], "yaw_deg": 90.0, "state": "DROPPING", "battery_percent": 96.0, "is_loaded": True},
|
||||||
|
],
|
||||||
|
"amr_heavy_01": [
|
||||||
|
{"t": 0.0, "pos": [2.0, 38.0, 0.0], "yaw_deg": 0.0, "state": "IDLE", "battery_percent": 100.0, "is_loaded": False},
|
||||||
|
{"t": 10.0, "pos": [5.0, 38.0, 0.0], "yaw_deg": 0.0, "state": "CHARGING", "battery_percent": 80.0, "is_loaded": False},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
data = TrajectoryData.from_dict(mock_trajectory)
|
||||||
|
|
||||||
|
generator = AnimatedUSDGenerator.from_config_and_trajectory(
|
||||||
|
bundle=bundle,
|
||||||
|
trajectory_data=data,
|
||||||
|
sample_step_seconds=2.0,
|
||||||
|
timecodes_per_second=24.0,
|
||||||
|
)
|
||||||
|
|
||||||
|
usda_text = generator.generate_animated_usda()
|
||||||
|
|
||||||
|
# Verify stage-level animation header
|
||||||
|
assert 'upAxis = "Z"' in usda_text
|
||||||
|
assert "startTimeCode = 0.0" in usda_text
|
||||||
|
assert "endTimeCode = 240.0" in usda_text # 10s * 24 fps
|
||||||
|
assert "timeCodesPerSecond = 24.0" in usda_text
|
||||||
|
|
||||||
|
# Verify time-sampled kinematic tracks
|
||||||
|
assert 'double3 xformOp:translate.timeSamples = {' in usda_text
|
||||||
|
assert 'double3 xformOp:rotateXYZ.timeSamples = {' in usda_text
|
||||||
|
assert 'color3f[] primvars:displayColor.timeSamples = {' in usda_text
|
||||||
|
assert 'token visibility.timeSamples = {' in usda_text
|
||||||
|
|
||||||
|
# Verify robot prims
|
||||||
|
assert 'def Xform "amr_light_01"' in usda_text
|
||||||
|
assert 'def Xform "amr_heavy_01"' in usda_text
|
||||||
|
assert 'def Cube "StatusDome"' in usda_text
|
||||||
|
assert 'def Cube "BatteryLED"' in usda_text
|
||||||
|
assert 'def Cube "Payload"' in usda_text
|
||||||
|
|
||||||
|
# Test file export
|
||||||
|
out_file = tmp_path / "warehouse_animated.usda"
|
||||||
|
saved = generator.export_usda(out_file)
|
||||||
|
assert saved.exists()
|
||||||
|
assert saved.stat().st_size > 5000
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"""Unit tests for Omniverse Kit extension structure and lifecycle."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import pytest
|
||||||
|
try:
|
||||||
|
import tomllib
|
||||||
|
except ImportError:
|
||||||
|
import tomli as tomllib
|
||||||
|
|
||||||
|
from omni.warehouse.twin.visualizer.extension import WarehouseVisualizerExtension
|
||||||
|
|
||||||
|
|
||||||
|
def test_extension_toml_metadata():
|
||||||
|
"""Verify extension.toml adheres to Omniverse Kit 110.4 schema requirements."""
|
||||||
|
toml_path = Path("omniverse/extensions/omni.warehouse.twin.visualizer/config/extension.toml").resolve()
|
||||||
|
assert toml_path.exists()
|
||||||
|
|
||||||
|
with open(toml_path, "rb") as f:
|
||||||
|
config = tomllib.load(f)
|
||||||
|
|
||||||
|
assert "package" in config
|
||||||
|
pkg = config["package"]
|
||||||
|
assert pkg["title"] == "Warehouse Robot Fleet Digital Twin Visualizer"
|
||||||
|
assert pkg["version"] == "0.7.0"
|
||||||
|
assert "python.module" in config or "python" in config
|
||||||
|
mod_name = config["python"]["module"][0]["name"] if "python" in config else config["python.module"][0]["name"]
|
||||||
|
assert mod_name == "omni.warehouse.twin.visualizer"
|
||||||
|
|
||||||
|
|
||||||
|
def test_extension_lifecycle_and_teardown(tmp_path: Path):
|
||||||
|
"""Verify extension instantiation, trajectory loading, playback controls, and safe shutdown."""
|
||||||
|
ext = WarehouseVisualizerExtension()
|
||||||
|
assert not ext.is_active
|
||||||
|
|
||||||
|
# Create dummy trajectory file
|
||||||
|
mock_traj = {
|
||||||
|
"metadata": {"simulation_duration": 60.0},
|
||||||
|
"robots": {
|
||||||
|
"amr_01": [
|
||||||
|
{"t": 0.0, "pos": [5.0, 5.0, 0.0], "yaw_deg": 0.0, "state": "IDLE"},
|
||||||
|
{"t": 60.0, "pos": [25.0, 5.0, 0.0], "yaw_deg": 0.0, "state": "LOADED_TRANSIT"},
|
||||||
|
]
|
||||||
|
},
|
||||||
|
}
|
||||||
|
traj_file = tmp_path / "test_lifecycle_traj.json"
|
||||||
|
traj_file.write_text(json.dumps(mock_traj), encoding="utf-8")
|
||||||
|
|
||||||
|
# Start up extension
|
||||||
|
ext.on_startup("omni.warehouse.twin.visualizer-0.7.0")
|
||||||
|
assert ext.is_active
|
||||||
|
|
||||||
|
# Load trajectory
|
||||||
|
loaded = ext.load_trajectory(str(traj_file))
|
||||||
|
assert loaded
|
||||||
|
assert ext._player is not None
|
||||||
|
assert ext._player.duration == 60.0
|
||||||
|
|
||||||
|
# Test playback controls
|
||||||
|
ext.play()
|
||||||
|
assert ext._player.is_playing
|
||||||
|
|
||||||
|
ext.pause()
|
||||||
|
assert not ext._player.is_playing
|
||||||
|
|
||||||
|
ext.set_speed(5.0)
|
||||||
|
assert ext._player.playback_speed == 5.0
|
||||||
|
|
||||||
|
ext.seek(30.0)
|
||||||
|
assert ext._player.current_time == 30.0
|
||||||
|
|
||||||
|
ext.reset()
|
||||||
|
assert ext._player.current_time == 0.0
|
||||||
|
|
||||||
|
# Test clean shutdown and resource teardown
|
||||||
|
ext.on_shutdown()
|
||||||
|
assert not ext.is_active
|
||||||
|
assert ext._player is None
|
||||||
|
assert ext._update_sub is None
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
"""Unit tests for trajectory playback and spatial interpolation engine."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from warehouse_twin.visualization.trajectory_player import (
|
||||||
|
RobotPlaybackState,
|
||||||
|
TrajectoryData,
|
||||||
|
TrajectoryPlayer,
|
||||||
|
interpolate_robot_state,
|
||||||
|
interpolate_yaw,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_interpolate_yaw_standard_and_wrap():
|
||||||
|
"""Verify angular interpolation along shortest circular arc."""
|
||||||
|
# Standard interpolation
|
||||||
|
assert pytest.approx(interpolate_yaw(0.0, 90.0, 0.5)) == 45.0
|
||||||
|
assert pytest.approx(interpolate_yaw(10.0, 50.0, 0.25)) == 20.0
|
||||||
|
|
||||||
|
# Wrap-around across 180 / -180 boundary
|
||||||
|
# e.g. from 170 to -170 is a 20 degree positive rotation through 180
|
||||||
|
res = interpolate_yaw(170.0, -170.0, 0.5)
|
||||||
|
assert pytest.approx(abs(res)) == 180.0
|
||||||
|
|
||||||
|
# From -170 to 170 (negative direction through -180)
|
||||||
|
res2 = interpolate_yaw(-170.0, 170.0, 0.5)
|
||||||
|
assert pytest.approx(abs(res2)) == 180.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_interpolate_robot_state_endpoints_and_interior():
|
||||||
|
"""Verify state interpolation at endpoints and midway between trajectory waypoints."""
|
||||||
|
points = [
|
||||||
|
{
|
||||||
|
"t": 0.0,
|
||||||
|
"pos": [10.0, 5.0, 0.2],
|
||||||
|
"yaw_deg": 0.0,
|
||||||
|
"state": "IDLE",
|
||||||
|
"battery_percent": 100.0,
|
||||||
|
"is_loaded": False,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"t": 10.0,
|
||||||
|
"pos": [20.0, 15.0, 0.2],
|
||||||
|
"yaw_deg": 90.0,
|
||||||
|
"state": "LOADED_TRANSIT",
|
||||||
|
"battery_percent": 98.0,
|
||||||
|
"is_loaded": True,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
# Before start
|
||||||
|
s_before = interpolate_robot_state("robot_1", points, -5.0)
|
||||||
|
assert s_before.x == 10.0
|
||||||
|
assert s_before.y == 5.0
|
||||||
|
assert s_before.yaw_degrees == 0.0
|
||||||
|
assert s_before.state == "IDLE"
|
||||||
|
assert s_before.battery_percent == 100.0
|
||||||
|
assert not s_before.is_loaded
|
||||||
|
|
||||||
|
# After end
|
||||||
|
s_after = interpolate_robot_state("robot_1", points, 15.0)
|
||||||
|
assert s_after.x == 20.0
|
||||||
|
assert s_after.y == 15.0
|
||||||
|
assert s_after.yaw_degrees == 90.0
|
||||||
|
assert s_after.state == "LOADED_TRANSIT"
|
||||||
|
assert s_after.battery_percent == 98.0
|
||||||
|
assert s_after.is_loaded
|
||||||
|
|
||||||
|
# Midpoint (t = 5.0)
|
||||||
|
s_mid = interpolate_robot_state("robot_1", points, 5.0)
|
||||||
|
assert pytest.approx(s_mid.x) == 15.0
|
||||||
|
assert pytest.approx(s_mid.y) == 10.0
|
||||||
|
assert pytest.approx(s_mid.yaw_degrees) == 45.0
|
||||||
|
assert pytest.approx(s_mid.battery_percent) == 99.0
|
||||||
|
# At alpha = 0.5, picks p2 discrete state
|
||||||
|
assert s_mid.state == "LOADED_TRANSIT"
|
||||||
|
assert s_mid.is_loaded
|
||||||
|
|
||||||
|
|
||||||
|
def test_trajectory_data_loading(tmp_path: Path):
|
||||||
|
"""Verify TrajectoryData parsing from dict and json file."""
|
||||||
|
mock_payload = {
|
||||||
|
"metadata": {"simulation_duration": 100.0, "coordinate_system": "meters_z_up"},
|
||||||
|
"robots": {
|
||||||
|
"amr_1": [
|
||||||
|
{"t": 0.0, "pos": [0, 0, 0], "yaw_deg": 0, "state": "IDLE"},
|
||||||
|
{"t": 50.0, "pos": [10, 0, 0], "yaw_deg": 0, "state": "DISPATCHED"},
|
||||||
|
],
|
||||||
|
"amr_2": [
|
||||||
|
{"t": 10.0, "pos": [5, 5, 0], "yaw_deg": 90, "state": "PICKING"},
|
||||||
|
{"t": 80.0, "pos": [5, 20, 0], "yaw_deg": 90, "state": "DROPPING"},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
file_path = tmp_path / "test_traj.json"
|
||||||
|
file_path.write_text(json.dumps(mock_payload), encoding="utf-8")
|
||||||
|
|
||||||
|
data = TrajectoryData.from_file(file_path)
|
||||||
|
assert data.get_robot_ids() == ["amr_1", "amr_2"]
|
||||||
|
assert data.get_point_count() == 4
|
||||||
|
assert data.start_time == 0.0
|
||||||
|
assert data.end_time == 80.0
|
||||||
|
assert data.duration == 80.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_trajectory_player_playback_flow():
|
||||||
|
"""Verify player play, pause, seek, speed, advance, and callbacks."""
|
||||||
|
raw_data = {
|
||||||
|
"robots": {
|
||||||
|
"r1": [
|
||||||
|
{"t": 0.0, "pos": [0.0, 0.0, 0.0], "yaw_deg": 0.0, "state": "IDLE"},
|
||||||
|
{"t": 100.0, "pos": [100.0, 0.0, 0.0], "yaw_deg": 0.0, "state": "LOADED_TRANSIT"},
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data = TrajectoryData.from_dict(raw_data)
|
||||||
|
player = TrajectoryPlayer(data, playback_speed=2.0)
|
||||||
|
|
||||||
|
callback_states = []
|
||||||
|
|
||||||
|
def on_frame(state):
|
||||||
|
callback_states.append(state)
|
||||||
|
|
||||||
|
player.register_callback(on_frame)
|
||||||
|
|
||||||
|
assert not player.is_playing
|
||||||
|
assert player.current_time == 0.0
|
||||||
|
assert player.progress_fraction == 0.0
|
||||||
|
|
||||||
|
# Advance when paused does not change time
|
||||||
|
st = player.advance(1.0)
|
||||||
|
assert player.current_time == 0.0
|
||||||
|
|
||||||
|
# Start playback
|
||||||
|
player.play()
|
||||||
|
assert player.is_playing
|
||||||
|
|
||||||
|
# Advance 5 wall-clock seconds at 2.0x speed = 10 simulation seconds
|
||||||
|
st = player.advance(5.0)
|
||||||
|
assert player.current_time == 10.0
|
||||||
|
assert pytest.approx(st["r1"].x) == 10.0
|
||||||
|
assert len(callback_states) == 1
|
||||||
|
|
||||||
|
# Seek
|
||||||
|
player.seek(50.0)
|
||||||
|
assert player.current_time == 50.0
|
||||||
|
assert player.progress_fraction == 0.5
|
||||||
|
assert len(callback_states) == 2
|
||||||
|
|
||||||
|
# Advance past end without loop
|
||||||
|
player.advance(40.0) # 40 * 2 = 80s -> 50 + 80 = 130 >= 100
|
||||||
|
assert player.current_time == 100.0
|
||||||
|
assert not player.is_playing
|
||||||
|
|
||||||
|
# Test loop wrap-around
|
||||||
|
player.loop = True
|
||||||
|
player.reset()
|
||||||
|
player.play()
|
||||||
|
player.advance(60.0) # 60 * 2 = 120s -> wraps to 20s
|
||||||
|
assert player.is_playing
|
||||||
|
assert pytest.approx(player.current_time) == 20.0
|
||||||
|
|
||||||
|
# Clean teardown
|
||||||
|
player.cleanup()
|
||||||
|
assert not player.is_playing
|
||||||
|
assert len(player._callbacks) == 0
|
||||||
Reference in New Issue
Block a user