feat(phase-7): implement OpenUSD animation, trajectory player, and Omniverse Kit extension
This commit is contained in:
+150
-33
@@ -70,15 +70,24 @@ def check_environment() -> int:
|
||||
failures += 1
|
||||
|
||||
# 5. NVIDIA Omniverse Kit Check (Optional for Simulation, Required for Visualizer)
|
||||
kit_env_path = os.environ.get(
|
||||
"KIT_PATH",
|
||||
"/home/dmhai/nvidia-omniverse/kit-app-template/_build/linux-x86_64/release/kit/kit"
|
||||
)
|
||||
kit_path = Path(kit_env_path)
|
||||
if kit_path.exists() and os.access(kit_path, os.X_OK):
|
||||
print(f"[OK] NVIDIA Omniverse Kit found at: {kit_path}")
|
||||
kit_candidates = [
|
||||
os.environ.get("KIT_PATH"),
|
||||
"/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",
|
||||
]
|
||||
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:
|
||||
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)
|
||||
if failures > 0:
|
||||
@@ -188,44 +197,132 @@ def export_graph(config_dir: Optional[str] = None, output_path: Optional[str] =
|
||||
return 1
|
||||
|
||||
|
||||
def export_usd(config_dir: Optional[str] = None, output_path: Optional[str] = None) -> int:
|
||||
"""Build and export the warehouse 3D scene to an OpenUSD (.usda) file."""
|
||||
def export_usd(
|
||||
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()
|
||||
logger = get_logger("cli")
|
||||
try:
|
||||
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)
|
||||
bundle = loader.load_all()
|
||||
|
||||
generator = WarehouseUSDGenerator.from_config_bundle(bundle, include_routing_network=True)
|
||||
default_out = Path("omniverse/scenes/warehouse_phase5.usda")
|
||||
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
|
||||
if trajectory_path:
|
||||
traj_file = Path(trajectory_path).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)
|
||||
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
|
||||
traj_data = TrajectoryData.from_file(traj_file)
|
||||
anim_gen = AnimatedUSDGenerator.from_config_and_trajectory(
|
||||
bundle=bundle,
|
||||
trajectory_data=traj_data,
|
||||
sample_step_seconds=step_seconds,
|
||||
)
|
||||
default_out = Path("omniverse/scenes/warehouse_phase7_animated.usda")
|
||||
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
|
||||
saved_path = anim_gen.export_usda(out_file)
|
||||
print("=" * 65)
|
||||
print("Warehouse Animated OpenUSD Scene Successfully Generated")
|
||||
print("=" * 65)
|
||||
print(f"Scene Path: {saved_path}")
|
||||
print(f"Animation Range: 0.0s to {traj_data.duration:.1f}s ({round(traj_data.duration * anim_gen.timecodes_per_second)} frames)")
|
||||
print(f"Sample Step: {step_seconds}s ({anim_gen.timecodes_per_second} fps)")
|
||||
print(f"AMRs Animated: {len(traj_data.robots)}")
|
||||
print("-" * 65)
|
||||
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:
|
||||
logger.error("USD export failed: %s", err)
|
||||
print(f"[FAIL] USD Export Error: {err}", file=sys.stderr)
|
||||
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(
|
||||
config_dir: Optional[str] = None,
|
||||
duration: Optional[float] = None,
|
||||
@@ -528,8 +625,26 @@ def main(argv: Optional[list[str]] = None) -> int:
|
||||
"--output",
|
||||
type=str,
|
||||
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
|
||||
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":
|
||||
return export_graph(args.config_dir, args.output)
|
||||
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":
|
||||
return run_simulation(args.config_dir, args.duration, args.seed, args.output_events, args.output_trajectories)
|
||||
elif args.command == "run-experiment":
|
||||
|
||||
@@ -223,6 +223,16 @@ class Robot:
|
||||
return True
|
||||
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(
|
||||
self,
|
||||
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)],
|
||||
"yaw_deg": round(robot.yaw_degrees, 1),
|
||||
"state": robot.current_state.value,
|
||||
"battery_percent": round(robot.battery_percent, 1),
|
||||
"is_loaded": robot.current_payload_kg > 0.0,
|
||||
})
|
||||
|
||||
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()
|
||||
Reference in New Issue
Block a user