"""URDF -> robot/robot.usd with Isaac Lab's URDF converter, then a physics dump and a PhysX load test. Simulation-tested ยท Not built. Runs inside Isaac Lab's own Python (GPU-queue step only), never in the project venv: C:\\isaac-sim\\IsaacLab\\isaaclab.bat -p /simulation/isaac/usd_params.json `uv run tasks.py usd` (package/src/cmds/usd.py) writes usd_params.json from spec.yaml + cad/parts.json and runs this script with VIRTUAL_ENV / PYTHONPATH stripped. Only files cross over; every number used here comes from that JSON. Steps 1. isaaclab.sim.converters.UrdfConverter (Isaac Lab 3.0 -> Isaac Sim URDF importer 3.0) into a scratch directory (runs/usd_import, git-ignored): floating base (fix_base False), no fixed-joint merging, self-collision on, drive gains 0 (authored in step 3 instead, see below). 2. Select the importer's "physx" Physics variant (UsdPhysics + PhysxJointAPI), de-instance (deterministic output) and flatten the layered asset (interface, payloads, geometry, materials) into ONE self-contained package/robot/robot.usd (no external asset paths remain; checked). Identical inputs give a byte-identical file. 3. Author the Isaac config from usd_params.json on the flattened stage (USD angular units are degrees): - servo joints (visor_flip, focus): position drive kp / kv (SG90 model of spec.yaml), maxForce = stall torque at the rail, PhysX armature and maxJointVelocity (no-load speed); - passive temple hinges: the clamp spring as a drive toward springref (stiffness, damping), no force cap; - focus_slide (coupled to focus by the cam): the importer's NewtonMimicAPI is kept (PhysxMimicJointAPI is deprecated in Isaac Sim 6's schema) but coef1 is re-authored in USD units, m/deg = URDF m/rad * pi/180: the importer copies the URDF multiplier unchanged, which is wrong for a prismatic follower of a revolute leader (DESIGN_LOG D17); the carriage preload spring is a drive toward its springref; - articulation self-collision on (as the MJCF: only parent-child pairs excluded). Coulomb joint friction (MJCF frictionloss) stays only in newton:friction (N*m): PhysX's jointFriction is a coefficient on the constraint force, not a constant torque, so it is not authored (DESIGN_LOG D17). 4. Dump links (mass, com, principal inertia) and joints (axis, frames, limits, drives, mimic) to docs/sim-tests/usd_dump.json in the format src/model_checks.py reads. 5. PhysX load test (MODEL-LOAD, USD part) -> docs/sim-tests/usd_load.json: two copies of robot.usd in one stage, gravity on, physics dt = spec control.sim_dt_s: - "free": floating base dropped onto a ground plane; - "held": root link held in the air by a world fixed joint added at runtime, servos commanded to targets inside their ranges; records tracking error, focus_slide coupling error and hinge rest angle. The hold is a world fixed joint excluded from the articulation (runtime only; the USD stays floating). PASS when the asset spawns with the URDF's bodies and joints, keeps every URDF collision primitive and visual, is self-contained, every state stays finite and the file is within ZMass's per-file limit. Tracking, coupling and rest values are information. """ from __future__ import annotations import argparse import json import math import os import shutil import sys import time import traceback from pathlib import Path from isaaclab.app import AppLauncher parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("params", help="package/simulation/isaac/usd_params.json") parser.add_argument("--skip_load_test", action="store_true") AppLauncher.add_app_launcher_args(parser) args = parser.parse_args() P = json.loads(Path(args.params).read_text(encoding="utf-8")) PKG = Path(args.params).resolve().parents[2] SCRATCH = PKG.parent / P["scratch_dir"] # repo-root relative, git-ignored OUT_USD = PKG / P["usd"] OUT_DUMP = PKG / P["dump"] OUT_LOAD = PKG / P["load"] JOINTS = P["joints"] args.device = P.get("device", "cuda:0") app = AppLauncher(args).app import numpy as np # noqa: E402 from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics # noqa: E402 try: from pxr import PhysxSchema # noqa: E402 except ImportError: # pragma: no cover PhysxSchema = None from isaaclab.sim.converters import UrdfConverter, UrdfConverterCfg # noqa: E402 DEG = 180.0 / math.pi def log(*a): print("[urdf_to_usd]", *a, flush=True) # ----------------------------------------------------------------------------------------------------------- 1. convert def convert() -> Path: shutil.rmtree(SCRATCH, ignore_errors=True) SCRATCH.mkdir(parents=True, exist_ok=True) cfg = UrdfConverterCfg( asset_path=str(PKG / P["urdf"]), usd_dir=str(SCRATCH), fix_base=False, merge_fixed_joints=False, self_collision=True, force_usd_conversion=True, collision_from_visuals=False, joint_drive=UrdfConverterCfg.JointDriveCfg( gains=UrdfConverterCfg.JointDriveCfg.PDGainsCfg(stiffness=0.0, damping=0.0), target_type="position")) conv = UrdfConverter(cfg) log("importer output", conv.usd_path) return Path(conv.usd_path) # ----------------------------------------------------------------------------------------------------------- 2. flatten def flatten(src: Path) -> Usd.Stage: stage = Usd.Stage.Open(str(src)) root = stage.GetDefaultPrim() vs = root.GetVariantSets() variant = None if vs.HasVariantSet("Physics"): names = vs.GetVariantSet("Physics").GetVariantNames() variant = P["physics_variant"] if P["physics_variant"] in names else vs.GetVariantSet("Physics").GetVariantSelection() vs.GetVariantSet("Physics").SetVariantSelection(variant) log("Physics variant", variant, "of", vs.GetVariantSet("Physics").GetVariantNames() if vs.HasVariantSet("Physics") else None) # De-instance first: Flatten() names instancing prototypes "Flattened_Prototype_" in hash order, which made # robot.usd differ byte-wise between identical runs. Every instance here is used once, so nothing is duplicated. n_inst = 0 while True: inst = [p for p in stage.Traverse(Usd.TraverseInstanceProxies()) if p.IsInstance()] inst = [p for p in inst if not p.IsInstanceProxy()] if not inst: break for p in inst: p.SetInstanceable(False) n_inst += 1 log("de-instanced", n_inst, "prims") flat = stage.Flatten() OUT_USD.parent.mkdir(parents=True, exist_ok=True) tmp = SCRATCH / "flat.usda" flat.Export(str(tmp)) st = Usd.Stage.Open(str(tmp)) st.GetRootLayer().customLayerData = { **dict(st.GetRootLayer().customLayerData), "zmass_package": P["package"], "generated_by": "package/simulation/isaac/tools/urdf_to_usd.py (tasks.py usd)", "status": "Simulation-tested - Not built", "physics_variant": str(variant)} return st, variant def joint_prims(stage) -> dict[str, Usd.Prim]: out = {} for prim in stage.Traverse(): if prim.IsA(UsdPhysics.Joint) and prim.GetName() in JOINTS: out[prim.GetName()] = prim return out def link_prims(stage) -> dict[str, Usd.Prim]: return {p.GetName(): p for p in stage.Traverse() if p.HasAPI(UsdPhysics.RigidBodyAPI)} # ----------------------------------------------------------------------------------------------- 3. author Isaac config def author(stage) -> dict: jp = joint_prims(stage) missing = sorted(set(JOINTS) - set(jp)) assert not missing, f"joints missing in the USD: {missing}" notes = {} for name, j in JOINTS.items(): prim = jp[name] ang = j["type"] == "revolute" kind = "angular" if ang else "linear" k = (math.pi / 180.0) if ang else 1.0 # per-rad -> per-deg for angular gains tgt = (lambda v: v * DEG) if ang else (lambda v: v) d = j["drive"] drive = UsdPhysics.DriveAPI.Apply(prim, kind) drive.CreateTypeAttr().Set("force") drive.CreateStiffnessAttr().Set(float(d["stiffness"]) * k) drive.CreateDampingAttr().Set(float(d["damping"]) * k) drive.CreateTargetPositionAttr().Set(float(tgt(d["target"]))) drive.CreateTargetVelocityAttr().Set(0.0) if d["max_force"] is not None: drive.CreateMaxForceAttr().Set(float(d["max_force"])) elif drive.GetMaxForceAttr().HasAuthoredValue(): drive.GetMaxForceAttr().Set(float("inf")) if PhysxSchema is not None: pj = PhysxSchema.PhysxJointAPI.Apply(prim) pj.CreateArmatureAttr().Set(float(j["armature"])) pj.CreateMaxJointVelocityAttr().Set(float(tgt(j["velocity"]))) prim.CreateAttribute("zmass:role", Sdf.ValueTypeNames.Token, custom=True).Set(j["role"]) prim.CreateAttribute("zmass:frictionloss", Sdf.ValueTypeNames.Float, custom=True).Set(float(j["frictionloss"])) if j["role"] == "coupled": # The importer's NewtonMimicAPI (newton:mimicCoef1 = multiplier, newton:mimicCoef0 = offset) is what the # Isaac Sim 6 runtime consumes; PhysxMimicJointAPI is deprecated in this schema version, so none is added. # USD joint positions are degrees for revolute and metres for prismatic joints, and the runtime applies # follower = coef0 + coef1 * leader in those units. The importer copies the URDF multiplier unchanged, which # is only right when both joints have the same type; here the follower is prismatic (m) and the leader # revolute (deg), so coef1 must be m/deg = multiplier [m/rad] * pi/180. Found by the Phase 3b load test: # with the importer's value the slide locked the cam at focus = 1.047 deg (DESIGN_LOG D17). m = j["mimic"] lead = JOINTS[m["joint"]] u_f = DEG if j["type"] == "revolute" else 1.0 # USD units per SI unit, follower u_l = DEG if lead["type"] == "revolute" else 1.0 # USD units per SI unit, leader coef1, coef0 = float(m["multiplier"]) * u_f / u_l, float(m["offset"]) * u_f before = {"coef1": prim.GetAttribute("newton:mimicCoef1").Get(), "coef0": prim.GetAttribute("newton:mimicCoef0").Get()} assert prim.HasAPI("NewtonMimicAPI"), "the importer dropped the URDF (no NewtonMimicAPI on focus_slide)" refs = [str(t) for t in prim.GetRelationship("newton:mimicJoint").GetTargets()] assert refs == [str(jp[m["joint"]].GetPath())], f"mimic reference {refs} is not {m['joint']}" prim.GetAttribute("newton:mimicCoef1").Set(coef1) prim.GetAttribute("newton:mimicCoef0").Set(coef0) notes["mimic"] = {"joint": name, "api": "NewtonMimicAPI (kept from the importer)", "reference": m["joint"], "urdf_multiplier_si": m["multiplier"], "urdf_offset_si": m["offset"], "importer_coefs": before, "authored_coefs_usd_units": {"coef1": coef1, "coef0": coef0}, "units": f"follower {'deg' if u_f != 1 else 'm'}, leader {'deg' if u_l != 1 else 'm'}"} root = stage.GetDefaultPrim() art = [p for p in stage.Traverse() if p.HasAPI(UsdPhysics.ArticulationRootAPI)] assert len(art) == 1, f"expected one articulation root, found {[str(p.GetPath()) for p in art]}" if PhysxSchema is not None: pa = PhysxSchema.PhysxArticulationAPI.Apply(art[0]) pa.CreateEnabledSelfCollisionsAttr().Set(True) notes["articulation_root"] = str(art[0].GetPath()) notes["default_prim"] = str(root.GetPath()) return notes def external_assets(layer: Sdf.Layer) -> list[str]: """Asset paths and composition arcs still pointing outside robot.usd (should be none after flattening).""" out = [] def visit(path): spec = layer.GetObjectAtPath(path) if isinstance(spec, Sdf.PrimSpec): for lst in (spec.referenceList, spec.payloadList): for it in lst.GetAddedOrExplicitItems(): if it.assetPath: out.append(f"{path}: arc {it.assetPath}") if isinstance(spec, Sdf.AttributeSpec): v = spec.default vals = v if isinstance(v, (list, tuple)) or (hasattr(v, "__len__") and not isinstance(v, str)) else [v] try: for x in vals: if isinstance(x, Sdf.AssetPath) and x.path: out.append(f"{path}: asset {x.path}") except TypeError: pass layer.Traverse(Sdf.Path.absoluteRootPath, visit) out += [f"sublayer {s}" for s in layer.subLayerPaths] return out # ------------------------------------------------------------------------------------------------------------- 4. dump def q_wxyz(q) -> list[float]: return [float(q.GetReal()), *[float(x) for x in q.GetImaginary()]] def dump(stage, variant, notes) -> dict: d = {"source": P["urdf"], "usd": P["usd"], "physics_variant": variant, "meters_per_unit": UsdGeom.GetStageMetersPerUnit(stage), "kilograms_per_unit": UsdPhysics.GetStageKilogramsPerUnit(stage), "up_axis": str(UsdGeom.GetStageUpAxis(stage)), "default_prim": notes["default_prim"], "articulation_root": notes["articulation_root"], "units": {"revolute": "deg in USD; lower/upper here in deg as lower_deg/upper_deg", "prismatic": "m (lower/upper)", "drive": "stiffness/damping as authored (per deg for revolute) and *_si per rad"}, "links": {}, "joints": {}, "mimic": {}, "author_notes": notes} for name, prim in link_prims(stage).items(): m = UsdPhysics.MassAPI(prim) pa = m.GetPrincipalAxesAttr().Get() d["links"][name] = {"path": str(prim.GetPath()), "mass": float(m.GetMassAttr().Get()), "com": [float(x) for x in m.GetCenterOfMassAttr().Get()], "diag_inertia": [float(x) for x in m.GetDiagonalInertiaAttr().Get()], "principal_axes_wxyz": q_wxyz(pa) if pa is not None else None, "collision_prims": sum(1 for c in Usd.PrimRange(prim) if c.HasAPI(UsdPhysics.CollisionAPI) and link_of(c) == prim), "visual_meshes": sum(1 for c in Usd.PrimRange(prim) if c.IsA(UsdGeom.Mesh) and not c.HasAPI(UsdPhysics.CollisionAPI) and link_of(c) == prim)} for name, prim in joint_prims(stage).items(): j = UsdPhysics.Joint(prim) ang = prim.IsA(UsdPhysics.RevoluteJoint) typed = UsdPhysics.RevoluteJoint(prim) if ang else UsdPhysics.PrismaticJoint(prim) kind = "angular" if ang else "linear" drv = UsdPhysics.DriveAPI(prim, kind) k = (180.0 / math.pi) if ang else 1.0 row = {"path": str(prim.GetPath()), "type": "revolute" if ang else "prismatic", "axis": typed.GetAxisAttr().Get(), "body0": [str(t) for t in j.GetBody0Rel().GetTargets()], "body1": [str(t) for t in j.GetBody1Rel().GetTargets()], "local_pos0": [float(x) for x in j.GetLocalPos0Attr().Get()], "local_pos1": [float(x) for x in j.GetLocalPos1Attr().Get()], "local_rot0_wxyz": q_wxyz(j.GetLocalRot0Attr().Get()), "local_rot1_wxyz": q_wxyz(j.GetLocalRot1Attr().Get())} lo, hi = typed.GetLowerLimitAttr().Get(), typed.GetUpperLimitAttr().Get() if ang: row.update(lower_deg=float(lo), upper_deg=float(hi)) else: row.update(lower=float(lo), upper=float(hi)) if prim.HasAPI(UsdPhysics.DriveAPI, kind): mf = drv.GetMaxForceAttr().Get() stf, dmp, tp = drv.GetStiffnessAttr().Get(), drv.GetDampingAttr().Get(), drv.GetTargetPositionAttr().Get() row["drive"] = {"type": drv.GetTypeAttr().Get(), "stiffness": stf, "damping": dmp, "target_position": tp, "max_force": mf, "stiffness_si": stf * k if stf is not None else None, "damping_si": dmp * k if dmp is not None else None, "target_si": tp / k if tp is not None else None} if mf is not None and math.isfinite(mf): row["max_force"] = float(mf) if PhysxSchema is not None and prim.HasAPI(PhysxSchema.PhysxJointAPI): pj = PhysxSchema.PhysxJointAPI(prim) mv = pj.GetMaxJointVelocityAttr().Get() row["physx"] = {"armature": pj.GetArmatureAttr().Get(), "max_joint_velocity": mv, "max_joint_velocity_si": (mv / k if mv is not None else None), "joint_friction": pj.GetJointFrictionAttr().Get()} nw = {a.GetName(): a.Get() for a in prim.GetAttributes() if a.GetName().startswith("newton:")} row["newton"] = {kk: (float(v) if isinstance(v, (int, float)) else str(v)) for kk, v in nw.items()} row["role"] = prim.GetAttribute("zmass:role").Get() row["frictionloss"] = prim.GetAttribute("zmass:frictionloss").Get() if prim.HasAPI("NewtonMimicAPI") or any(a.startswith("newton:mimic") for a in nw): refs = [str(t) for t in prim.GetRelationship("newton:mimicJoint").GetTargets()] lead = stage.GetPrimAtPath(refs[0]) if refs else None u_f = DEG if ang else 1.0 u_l = DEG if (lead is not None and lead.IsA(UsdPhysics.RevoluteJoint)) else 1.0 c1, c0 = nw.get("newton:mimicCoef1"), nw.get("newton:mimicCoef0") d["mimic"][name] = {"newton": {"coef0_offset": c0, "coef1_multiplier": c1, "joint": refs}, "joint": lead.GetName() if lead is not None else None, "multiplier": float(c1) * u_l / u_f if c1 is not None else None, # SI (m/rad here) "offset": float(c0) / u_f if c0 is not None else None, # SI (m) "note": "multiplier/offset converted to SI from USD units (revolute positions in deg)"} d["joints"][name] = row return d def notes_root_rel() -> str: """Path of the articulation-root link relative to the asset's default prim, e.g. /Geometry/frame.""" st = Usd.Stage.Open(str(OUT_USD)) root = st.GetDefaultPrim().GetPath() art = [p for p in st.Traverse() if p.HasAPI(UsdPhysics.ArticulationRootAPI)][0] return str(art.GetPath())[len(str(root)):] def link_of(prim): p = prim.GetParent() while p and p.IsValid(): if p.HasAPI(UsdPhysics.RigidBodyAPI): return p p = p.GetParent() return None # -------------------------------------------------------------------------------------------------------- 5. load test def load_test() -> dict: import torch import isaaclab.sim as sim_utils from isaaclab.actuators import ImplicitActuatorCfg from isaaclab.assets import Articulation, ArticulationCfg LT = P["load_test"] sim = sim_utils.SimulationContext(sim_utils.SimulationCfg(dt=P["physics_dt"], device=args.device)) gp = sim_utils.GroundPlaneCfg() gp.func("/World/ground", gp) names = list(JOINTS) acts = {"all": ImplicitActuatorCfg(joint_names_expr=names, stiffness=None, damping=None)} def cfg(path, pos): return ArticulationCfg( prim_path=path, spawn=sim_utils.UsdFileCfg(usd_path=str(OUT_USD)), init_state=ArticulationCfg.InitialStateCfg(pos=tuple(pos), rot=(0.0, 0.0, 0.0, 1.0), joint_pos=P["home_qpos"], joint_vel={".*": 0.0}), actuators=acts) free = Articulation(cfg("/World/Free", LT["free_pos_m"])) held = Articulation(cfg("/World/Held", LT["held_pos_m"])) # Hold the second copy's root link in the air with a world fixed joint kept OUT of the articulation (a loop # constraint), so robot.usd itself stays floating-base. (ArticulationRootPropertiesCfg(fix_root_link=True) tries to # move the articulation root and cannot remove the importer's newton:selfCollisionEnabled from the referenced layer.) stage = sim_utils.get_current_stage() root_rel = notes_root_rel() fj = UsdPhysics.FixedJoint.Define(stage, "/World/HeldAnchor") fj.CreateBody1Rel().SetTargets([Sdf.Path("/World/Held" + root_rel)]) fj.CreateLocalPos0Attr().Set(Gf.Vec3f(*[float(x) for x in LT["held_pos_m"]])) fj.CreateLocalRot0Attr().Set(Gf.Quatf(1.0, 0.0, 0.0, 0.0)) fj.CreateLocalPos1Attr().Set(Gf.Vec3f(0.0, 0.0, 0.0)) fj.CreateLocalRot1Attr().Set(Gf.Quatf(1.0, 0.0, 0.0, 0.0)) fj.CreateExcludeFromArticulationAttr().Set(True) sim.reset() dt = sim.get_physics_dt() res = {"physics_dt": dt, "device": args.device, "gravity": [0.0, 0.0, -9.81]} for tag, art in (("free", free), ("held", held)): res[tag] = {"num_bodies": art.num_bodies, "num_joints": art.num_joints, "body_names": list(art.body_names), "joint_names": list(art.joint_names)} jn = list(held.joint_names) idx = {n: i for i, n in enumerate(jn)} def targets(cmd: dict) -> torch.Tensor: t = torch.zeros(1, len(jn), device=sim.device) for n, j in JOINTS.items(): t[0, idx[n]] = cmd.get(n, j["drive"]["target"]) return t def apply(art, cmd): art.actuators.target_command.set_position_index(value=targets(cmd)) art.write_data_to_sim() def jpos(art): return art.data.joint_pos.torch[0].detach().cpu().numpy().astype(float) mim = next(n for n, j in JOINTS.items() if j["role"] == "coupled") m = JOINTS[mim]["mimic"] finite = True coup_max = 0.0 traj = [] settle = int(round(LT["settle_s"] / dt)) hold = int(round(LT["command_s"] / dt)) cmd = {} t0 = time.time() for k in range(settle + hold): if k == settle: cmd = LT["servo_targets"] apply(free, {}) apply(held, cmd) sim.step(render=False) free.update(dt) held.update(dt) for art in (free, held): for arr in (art.data.joint_pos.torch, art.data.joint_vel.torch, art.data.root_link_pos_w.torch): if not bool(torch.isfinite(arr).all()): finite = False q = jpos(held) coup = abs(q[idx[mim]] - (m["multiplier"] * q[idx[m["joint"]]] + m["offset"])) if k > 10: coup_max = max(coup_max, float(coup)) if k % int(round(0.05 / dt)) == 0 or k == settle + hold - 1: traj.append({"t": round((k + 1) * dt, 4), "held_q": {n: float(q[idx[n]]) for n in jn}, "free_root_z": float(free.data.root_link_pos_w.torch[0, 2])}) if not finite: break q = jpos(held) qf = jpos(free) res["steps"] = k + 1 log(f"load test: {k + 1} steps in {time.time() - t0:.1f} s wall") # wall time is not written (deterministic outputs) res["finite"] = finite res["held"].update({ "servo_targets": LT["servo_targets"], "final_q": {n: float(q[idx[n]]) for n in jn}, "servo_error_deg": {n: float((q[idx[n]] - LT["servo_targets"][n]) * DEG) for n in LT["servo_targets"]}, "coupling_error_max_m": coup_max, "coupling_error_final_m": float(abs(q[idx[mim]] - (m["multiplier"] * q[idx[m["joint"]]] + m["offset"]))), "hinge_rest_rad": {n: float(q[idx[n]]) for n, j in JOINTS.items() if j["role"] == "passive"}, "hinge_springref_rad": {n: j["drive"]["target"] for n, j in JOINTS.items() if j["role"] == "passive"}}) res["free"].update({ "final_root_pos_m": [float(x) for x in free.data.root_link_pos_w.torch[0]], "final_root_lin_speed_m_s": float(torch.linalg.norm(free.data.root_link_lin_vel_w.torch[0])), "final_q": {n: float(qf[idx[n]]) for n in jn}, "body_min_z_m": float(free.data.body_link_pos_w.torch[0, :, 2].min())}) res["trajectory"] = traj return res def main() -> int: t0 = time.time() src = convert() stage, variant = flatten(src) notes = author(stage) stage.GetRootLayer().Export(str(OUT_USD)) stage.GetRootLayer().Export(str(SCRATCH / "robot_text_copy.usda")) # git-ignored text copy for diffs between runs log("wrote", OUT_USD, f"{OUT_USD.stat().st_size / 1e6:.3f} MB") st = Usd.Stage.Open(str(OUT_USD)) ext = external_assets(st.GetRootLayer()) d = dump(st, variant, notes) d["external_assets"] = ext d["file_mb"] = round(OUT_USD.stat().st_size / 1e6, 4) OUT_DUMP.write_text(json.dumps(d, indent=1, default=str), encoding="utf-8", newline="\n") log("dump", OUT_DUMP, len(d["links"]), "links", len(d["joints"]), "joints", "external assets:", ext, f"({time.time() - t0:.1f} s)") load = {"status": "NOT RUN", "reason": "--skip_load_test"} if not args.skip_load_test: try: r = load_test() exp_b, exp_j = P["expected"]["links"], P["expected"]["joints"] ok_struct = all(sorted(r[t]["body_names"]) == sorted(exp_b) and sorted(r[t]["joint_names"]) == sorted(exp_j) for t in ("free", "held")) ok_size = d["file_mb"] < P["limits"]["zmass_file_mb_max"] ok_self = not ext got_c = {n: v["collision_prims"] for n, v in d["links"].items()} got_v = {n: v["visual_meshes"] for n, v in d["links"].items()} ok_geom = got_c == P["expected"]["collisions_per_link"] and got_v == P["expected"]["visuals_per_link"] r["geometry"] = {"collisions_per_link": got_c, "visuals_per_link": got_v, "expected_collisions": P["expected"]["collisions_per_link"], "expected_visuals": P["expected"]["visuals_per_link"]} r["checks"] = {"spawned_bodies_joints_match_urdf": ok_struct, "finite_state": r["finite"], "file_within_zmass_limit": ok_size, "self_contained": ok_self, "collision_and_visual_counts_match_urdf": ok_geom} load = {"status": "PASS" if all(r["checks"].values()) else "FAIL", **r} except Exception: # noqa: BLE001 load = {"status": "FAIL", "error": traceback.format_exc()} load["usd"] = P["usd"] load["criterion"] = "MODEL-LOAD (USD part): robot.usd spawns in Isaac Sim PhysX with the URDF's links and joints and steps with a finite state" OUT_LOAD.write_text(json.dumps(load, indent=1, default=str), encoding="utf-8", newline="\n") log("load test", load["status"], "->", OUT_LOAD) return 0 if load["status"] in ("PASS", "NOT RUN") else 3 if __name__ == "__main__": rc = 1 try: rc = main() except Exception: # noqa: BLE001 traceback.print_exc() rc = 1 finally: sys.stdout.flush() app.close() os._exit(rc)