GenieSimAssets / tools /generate_recorder_usda.py
jonasdee
update 3.2.0 assets
f23abff
Raw History Blame
7.24 kB
#!/usr/bin/env python3
# Copyright (c) 2023-2026, AgiBot Inc. All Rights Reserved.
# Author: Genie Sim Team
# License: Mozilla Public License Version 2.0
"""
list_usd_prims.py
Walk through ./assets, read object_parameters.json, open the referenced USD file
and list every prim's full path and name.
"""
import os
import sys
from pathlib import Path
import numpy as np
try:
from pxr import Usd, UsdGeom, UsdPhysics, Gf, Sdf, Tf
except ImportError:
sys.exit("❌ Missing pxr.Usd. Install OpenUSD: pip install usd-core")
from geniesim_assets import ASSETS_INDEX, ASSETS_PATH
def compute_bbox_info(prim: Usd.Prim) -> Gf.Range3d:
bbox_cache = UsdGeom.BBoxCache(
Usd.TimeCode.Default(),
[
UsdGeom.Tokens.default_,
UsdGeom.Tokens.render,
UsdGeom.Tokens.proxy,
UsdGeom.Tokens.guide,
],
# useExtentsHint=True,
useExtentsHint=False,
)
bbox_cache.Clear()
# world_xform = bbox_cache.ComputeRelativeTransform(
# prim, # prim whose bbox we want
# stage.GetPseudoRoot() # relative to world
# )
# UsdGeom.BBoxCache already gives a *world-space* Gf.BBox3d
world_bbox = bbox_cache.ComputeWorldBound(prim)
waligned_range = world_bbox.ComputeAlignedRange()
woriented_box = world_bbox.GetBox()
wmatrix = world_bbox.GetMatrix()
wrot = Gf.Quatd(wmatrix.ExtractRotationQuat())
wcenter = waligned_range.GetMidpoint()
wsize = waligned_range.GetSize()
local_bbox = bbox_cache.ComputeLocalBound(prim)
laligned_range = local_bbox.ComputeAlignedRange()
lsize = laligned_range.GetSize()
lcenter = laligned_range.GetMidpoint()
def compute_true_bbox(parent_prim):
bbox_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), [UsdGeom.Tokens.default_], useExtentsHint=False)
merged = None
for p in Usd.PrimRange(parent_prim):
if p.IsA(UsdGeom.Mesh):
b = bbox_cache.ComputeWorldBound(p).ComputeAlignedRange()
if merged is None:
merged = Gf.Range3d(b.GetMin(), b.GetMax())
else:
merged = merged.UnionWith(b) # ✅ correct method
return merged
bbox = compute_true_bbox(prim)
return bbox.GetMidpoint(), bbox.GetSize(), Gf.Quatd(1, 0, 0, 0)
ASSETS_PATH_OBJ = ASSETS_PATH / "objects"
def load_scene(scene_path: str) -> Usd.Stage:
abs_scene_path = os.path.join(ASSETS_PATH, scene_path)
if scene_path and os.path.exists(abs_scene_path):
print(f"Loading scene file: {abs_scene_path}")
# usd_context = Usd.Stage.CreateNew("s.usda")
usd_context = Usd.Stage.Open(abs_scene_path) # , load=Usd.Stage.LoadNone
print("Scene load complete")
else:
print(f"Scene file not found: {abs_scene_path}; creating new empty stage")
# usd_context = Usd.Stage.CreateInMemory()
usd_context = Usd.Stage.CreateNew(scene_path)
return usd_context
def check_item(object_id, info):
usda_url = str(ASSETS_PATH / info["url"])
thumnail_url = usda_url.replace("Aligned.usda", "recorder.usda")
if os.path.exists(thumnail_url):
os.remove(thumnail_url)
stage = load_scene(thumnail_url)
# Set up units and stage
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
stage.SetMetadata(UsdGeom.Tokens.metersPerUnit, 1.0)
# Root /World
xform0 = UsdGeom.Xform.Define(stage, Sdf.Path("/World"))
UsdGeom.Xformable(xform0.GetPrim()).AddOrientOp().Set(Gf.Quatf(1, 0, 0, 0))
stage.SetDefaultPrim(stage.GetPrimAtPath("/World"))
# Object prim
xform = UsdGeom.Xform.Define(stage, Sdf.Path("/World/object"))
xform.ClearXformOpOrder()
prim = xform.GetPrim()
prim.GetPayloads().AddPayload(usda_url)
# prim.GetPayloads().AddPayload(str(usda_url)[:-1])
# Compute bounding box info
bbox_center, bbox_size, bbox_rotq = compute_bbox_info(prim)
# Compute camera distance based on object size
max_dimension = max(bbox_size[0], bbox_size[1], bbox_size[2])
if max_dimension < 0.5:
camera_distance = max_dimension * 2.0 + 0.1
else:
camera_distance = max_dimension * 2.0
camera_distance = float(camera_distance) # ensure scalar
# Create 3 cameras at 45°, -45° pitch angles
num_cameras = 2
pitch_angles = [45.0, -45.0] # degrees: top, horizontal, bottom
rot = Gf.Matrix3d(bbox_rotq)
camera_paths = []
camera_names = []
cam_idx = 0
for i in range(num_cameras):
# Use fixed pitch angles: 45°, 0°, -45°
pitch_deg = pitch_angles[i]
# Yaw: keep at 0° (cameras in same vertical plane)
yaw_deg = 0.0
yaw = np.radians(yaw_deg)
pitch = np.radians(pitch_deg)
# Spherical direction vector
d = Gf.Vec3d(
np.cos(pitch) * np.cos(yaw),
np.cos(pitch) * np.sin(yaw),
np.sin(pitch),
)
world_dir = rot * d
world_dir.Normalize()
pos = bbox_center + world_dir * camera_distance
# Define camera
name = f"Camera{cam_idx+1}"
camera_names.append(name)
cam_idx += 1
cam_prim = UsdGeom.Camera.Define(stage, Sdf.Path(f"/World/{name}"))
camera = UsdGeom.Camera(cam_prim)
# Set FOV and clipping
camera.CreateFocalLengthAttr(18.14756) # in mm (optional)
camera.CreateHorizontalApertureAttr(15.290) # default in mm
camera.CreateVerticalApertureAttr(15.290) # default in mm
camera.CreateFStopAttr(0.0) # optional, for depth of field
camera.CreateFocusDistanceAttr(camera_distance) # optional
camera.CreateClippingRangeAttr().Set(Gf.Vec2f(0.05, 100.0))
camera.GetVisibilityAttr().Set(UsdGeom.Tokens.invisible)
xf = UsdGeom.Xformable(cam_prim)
# Build look-at matrix (camera always looks at bbox_center)
forward = (bbox_center - pos).GetNormalized()
z_axis = -forward
up = Gf.Vec3d(0, 0, 1)
x_axis = Gf.Cross(up, z_axis)
if x_axis.GetLength() < 1e-4:
up = Gf.Vec3d(0, 1, 0)
x_axis = Gf.Cross(up, z_axis)
x_axis = x_axis.GetNormalized()
y_axis = Gf.Cross(z_axis, x_axis).GetNormalized()
M = Gf.Matrix4d(
x_axis[0],
x_axis[1],
x_axis[2],
0.0,
y_axis[0],
y_axis[1],
y_axis[2],
0.0,
z_axis[0],
z_axis[1],
z_axis[2],
0.0,
pos[0],
pos[1],
pos[2],
1.0,
)
xf.ClearXformOpOrder()
xf.AddTransformOp().Set(M)
camera_paths.append(str(cam_prim.GetPath()))
stage.GetRootLayer().Save()
def main():
for object_id in ASSETS_INDEX:
info = ASSETS_INDEX[object_id]
usd_filepath = info["url"]
visualization_path = ASSETS_PATH / "extra" / "visualization" / object_id
video_path = visualization_path / "video" / "merged.mp4"
if os.path.exists(video_path):
continue
print(usd_filepath)
check_item(object_id, info)
if __name__ == "__main__":
main()