feat(phase-1): add OpenUSD 3D scene generator and export-usd CLI command

This commit is contained in:
Warehouse Twin Dev
2026-10-19 15:18:56 +05:30
parent 88b922a3e1
commit 0427ab273d
5 changed files with 772 additions and 0 deletions
+53
View File
@@ -188,6 +188,42 @@ 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."""
setup_logging()
logger = get_logger("cli")
try:
from warehouse_twin.domain.warehouse import WarehouseModel
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
loader = ConfigLoader(config_dir)
bundle = loader.load_all()
model = WarehouseModel.from_config_dict(bundle.warehouse)
generator = WarehouseUSDGenerator(model)
default_out = Path("omniverse/scenes/warehouse_phase1.usda")
out_file = Path(output_path).resolve() if output_path else default_out.resolve()
saved_path = generator.export_usda(out_file)
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("-" * 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 main(argv: Optional[list[str]] = None) -> int:
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
@@ -238,6 +274,21 @@ def main(argv: Optional[list[str]] = None) -> int:
help="Output JSON file path (defaults to results/reports/warehouse_graph.json)",
)
# Subcommand: export-usd
usd_exp_parser = subparsers.add_parser("export-usd", help="Build and export warehouse 3D scene to OpenUSD (.usda)")
usd_exp_parser.add_argument(
"--config-dir",
type=str,
default=None,
help="Path to directory containing configuration JSON files",
)
usd_exp_parser.add_argument(
"--output",
type=str,
default=None,
help="Output USD file path (defaults to omniverse/scenes/warehouse_phase1.usda)",
)
args = parser.parse_args(argv)
if args.command == "validate-env":
@@ -248,6 +299,8 @@ def main(argv: Optional[list[str]] = None) -> int:
return validate_graph(args.config_dir)
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)
else:
parser.print_help()
return 0
@@ -0,0 +1,5 @@
"""Interfaces and external export modules for Warehouse Digital Twin."""
from warehouse_twin.interfaces.usd_generator import WarehouseUSDGenerator
__all__ = ["WarehouseUSDGenerator"]
@@ -0,0 +1,259 @@
"""OpenUSD scene generator for Warehouse Robot Fleet Digital Twin.
Exports an ASCII OpenUSD (.usda) scene compliant with NVIDIA Omniverse Kit 110.4
and standard USD specifications (Z-up, 1.0 meter units).
"""
from __future__ import annotations
from pathlib import Path
from typing import Any, Dict, List, Optional
from warehouse_twin.domain.warehouse import WarehouseModel
class WarehouseUSDGenerator:
"""Generates OpenUSD (.usda) 3D scenes from a WarehouseModel."""
def __init__(self, model: WarehouseModel) -> None:
"""Initialize generator with physical warehouse layout model."""
self.model = model
def generate_usda_content(self) -> str:
"""Construct valid ASCII OpenUSD 3D stage content representing the warehouse."""
dims = self.model.dimensions
w = dims.width
d = dims.depth
h = dims.height
lines: List[str] = [
"#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]",
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.35]",
" }",
"",
' def Cube "NorthWallGuide"',
" {",
f" double3 xformOp:translate = ({w / 2.0}, {d + 0.5}, 1.0)",
f" double3 xformOp:scale = ({w / 2.0}, 0.15, 1.0)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
" color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]",
" }",
"",
' def Cube "SouthWallGuide"',
" {",
f" double3 xformOp:translate = ({w / 2.0}, -0.5, 1.0)",
f" double3 xformOp:scale = ({w / 2.0}, 0.15, 1.0)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
" color3f[] primvars:displayColor = [(0.3, 0.35, 0.4)]",
" }",
"",
' def Cube "EastWallGuide"',
" {",
f" double3 xformOp:translate = ({w + 0.5}, {d / 2.0}, 1.0)",
f" double3 xformOp:scale = (0.15, {d / 2.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"',
" {",
]
# Zone floor pads
zone_colors = {
"zone_a": "(0.15, 0.45, 0.85)", # Vibrant blue
"zone_b": "(0.85, 0.55, 0.12)", # Warning amber
"zone_c": "(0.12, 0.68, 0.38)", # Production green
}
for z_id, zone in self.model.zones.items():
area = zone.area
zx = (area.x_min + area.x_max) / 2.0
zy = (area.y_min + area.y_max) / 2.0
sx = (area.x_max - area.x_min) / 2.0
sy = (area.y_max - area.y_min) / 2.0
color = zone_colors.get(z_id, "(0.5, 0.5, 0.5)")
lines.extend([
f' def Cube "{z_id}"',
" {",
f" double3 xformOp:translate = ({zx:.2f}, {zy:.2f}, 0.005)",
f" double3 xformOp:scale = ({sx:.2f}, {sy:.2f}, 0.005)",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
f" color3f[] primvars:displayColor = [{color}]",
" float[] primvars:displayOpacity = [0.25]",
" }",
])
lines.extend([
" }",
"",
" # -------------------------------------------------------------------------",
" # Storage Racks (13 Inventory Catalog Locations)",
" # -------------------------------------------------------------------------",
' def Scope "StorageRacks"',
" {",
])
# Storage Rack Primitives
rack_specs = {
"zone_a": {"color": "(0.2, 0.4, 0.7)", "scale": (0.9, 0.5, 1.8)}, # High-density parts shelving
"zone_b": {"color": "(0.8, 0.5, 0.1)", "scale": (1.4, 0.7, 2.2)}, # Heavy pallet racks
"zone_c": {"color": "(0.2, 0.6, 0.4)", "scale": (1.2, 0.6, 1.6)}, # Raw material racks
}
for loc_id, loc in self.model.storage_locations.items():
spec = rack_specs.get(loc.zone, {"color": "(0.5, 0.5, 0.5)", "scale": (1.0, 0.5, 1.5)})
col = spec["color"]
sx, sy, sz = spec["scale"]
rz = sz # base is at z=0, center is at z=sz
lines.extend([
f' def Xform "{loc_id}"',
" {",
f" double3 xformOp:translate = ({loc.position.x:.2f}, {loc.position.y:.2f}, {rz:.2f})",
f" double3 xformOp:scale = ({sx:.2f}, {sy:.2f}, {sz:.2f})",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
"",
' def Cube "RackFrame"',
" {",
f" color3f[] primvars:displayColor = [{col}]",
" float[] primvars:displayRoughness = [0.4]",
" }",
" }",
])
lines.extend([
" }",
"",
" # -------------------------------------------------------------------------",
" # Operational Stations",
" # -------------------------------------------------------------------------",
' def Scope "Stations"',
" {",
])
for st_id, st in self.model.stations.items():
pos = st.position
# Distinguish station visuals
if "inbound" in st.station_type.value:
st_col = "(0.85, 0.25, 0.2)" # Inbound red/orange
st_dim = (1.5, 2.0, 0.15)
elif "outbound" in st.station_type.value:
st_col = "(0.9, 0.4, 0.1)" # Outbound amber
st_dim = (1.5, 2.0, 0.15)
elif "picking" in st.station_type.value:
st_col = "(0.2, 0.75, 0.85)" # Picking teal/cyan
st_dim = (2.0, 1.2, 0.4)
else:
st_col = "(0.25, 0.8, 0.35)" # Production feed green
st_dim = (1.8, 1.8, 0.25)
lines.extend([
f' def Xform "{st_id}"',
" {",
f" double3 xformOp:translate = ({pos.x:.2f}, {pos.y:.2f}, {st_dim[2]:.2f})",
f" double3 xformOp:scale = ({st_dim[0]:.2f}, {st_dim[1]:.2f}, {st_dim[2]:.2f})",
' uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:scale"]',
"",
' def Cube "Platform"',
" {",
f" color3f[] primvars:displayColor = [{st_col}]",
" }",
" }",
])
lines.extend([
" }",
"",
" # -------------------------------------------------------------------------",
" # Autonomous Mobile Robot (AMR) Charging Bays",
" # -------------------------------------------------------------------------",
' def Scope "ChargingStations"',
" {",
])
for ch_id, ch in self.model.charging_stations.items():
pos = ch.position
lines.extend([
f' def Xform "{ch_id}"',
" {",
f" double3 xformOp:translate = ({pos.x:.2f}, {pos.y:.2f}, 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)]", # Electric cyan pad
" }",
"",
' 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)]",
" }",
" }",
])
lines.extend([
" }",
"}",
"",
])
return "\n".join(lines)
def export_usda(self, filepath: Path | str) -> Path:
"""Generate and save the ASCII OpenUSD (.usda) scene to disk."""
target_path = Path(filepath).resolve()
target_path.parent.mkdir(parents=True, exist_ok=True)
content = self.generate_usda_content()
target_path.write_text(content, encoding="utf-8")
return target_path