"""Run inside Isaac Lab's Python (isaaclab.bat -p). Simulation-tested · Not built. Supervised use only, with a human pilot holding a kill capability. Flattens the URDF importer's layered output (robot.usda + payloads/, default Physics variant) into one self-contained robot.usd and dumps its physics properties for MODEL-CONSIST (src/model_checks.py reads the dump). Adapted from the VR Goggles sibling project's tool (read-only reference) for AquaSalvage. usage: isaaclab.bat -p usd_flatten_dump.py """ import json import math import os import sys import xml.etree.ElementTree as ET from pxr import Sdf, Usd, UsdGeom, UsdPhysics, UsdUtils src, out_usd, out_json, urdf = sys.argv[1:5] src_stage = Usd.Stage.Open(src) variants = {} dp = src_stage.GetDefaultPrim() if dp and dp.GetVariantSets(): for name in dp.GetVariantSets().GetNames(): vs = dp.GetVariantSets().GetVariantSet(name) variants[name] = {"selected": vs.GetVariantSelection(), "options": vs.GetVariantNames()} creator = src_stage.GetRootLayer().customLayerData.get("creator") # Post-processing. postprocess = [] # De-instance before flattening: Flatten() numbers instance prototypes (Flattened_Prototype_N) in a run-dependent # order, so the same input gave a different file on every run. Without instancing the output is byte-reproducible. n_inst = 0 with Usd.EditContext(src_stage, src_stage.GetSessionLayer()): for prim in src_stage.Traverse(): if prim.IsInstanceable(): prim.SetInstanceable(False) n_inst += 1 postprocess.append({"step": "de-instance before Flatten (session layer only; importer output untouched)", "prims": n_inst}) flat = src_stage.Flatten() # Mimic followers here (prong_b_hinge, prong_c_hinge) are revolute followers of a revolute leader: the importer's # dimensionless coefficient needs no unit change. fl_stage = Usd.Stage.Open(flat) ur_root = ET.parse(urdf).getroot() ujtype = {e.get('name'): e.get('type') for e in ur_root.findall('joint')} # ASCII encoding inside robot.usd: the binary crate writer gave a different byte size on every run (same values), # the text encoding is byte-reproducible (rule 6) and diffable. USD reads either encoding from a .usd file. # Flatten() writes the absolute path of the importer layer into the layer documentation; that would make the file differ # by clone folder. Replace it by the repo-relative source path (rule 6: byte-identical from any folder). flat.documentation = "Generated from Composed Stage of root layer " + "runs/usd_import/" + "/".join(os.path.normpath(src).split(os.sep)[-2:]) flat.Export(out_usd, args={"format": "usda"}) stage = Usd.Stage.Open(out_usd) mpu = UsdGeom.GetStageMetersPerUnit(stage) dump = { "generator": "package/simulation/isaac/tools/usd_flatten_dump.py", "status_label": "Simulation-tested · Not built", "source": "runs/usd_import/" + "/".join(os.path.normpath(src).split(os.sep)[-2:]), "importer": creator, "physics_variant": variants, "postprocess": postprocess, "usd_version": ".".join(str(v) for v in Usd.GetVersion()), "meters_per_unit": mpu, "kilograms_per_unit": UsdPhysics.GetStageKilogramsPerUnit(stage), "up_axis": str(UsdGeom.GetStageUpAxis(stage)), "default_prim": str(stage.GetDefaultPrim().GetPath()) if stage.GetDefaultPrim() else None, "file_bytes": os.path.getsize(out_usd), "file_format": Sdf.Layer.FindOrOpen(out_usd).GetFileFormat().formatId, "links": {}, "joints": {}, "fixed_joints": [], "other_joints": [], "articulation_roots": [], "mimic": [], "collision_prims": 0, "mesh_prims": 0, } def drive_attrs(prim) -> dict: out = {} for a in prim.GetAttributes(): n = a.GetName() if n.startswith("drive:") or "maxjointvelocity" in n.lower().replace(":", ""): v = a.Get() out[n] = float(v) if isinstance(v, (int, float)) else str(v) return out def newton_attrs(prim) -> dict: out = {} for a in prim.GetAttributes(): n = a.GetName() if n.startswith("newton:") or n.startswith("urdf:") or n.startswith("physxJoint:"): v = a.Get() out[n] = float(v) if isinstance(v, (int, float)) else (list(v) if hasattr(v, "__len__") and not isinstance(v, str) else str(v)) return out def raw_schemas(prim) -> list: """apiSchemas as authored (list-op), including schemas this plain pxr build has no plugin for (Newton*, Physx*).""" op = prim.GetMetadata("apiSchemas") if op is None: return [] items = list(op.explicitItems) + list(op.prependedItems) + list(op.appendedItems) + list(op.addedItems) return [str(i) for i in items] def quat_wxyz(q): return [q.GetReal(), *q.GetImaginary()] if q is not None else None mesh_names = set() for prim in stage.Traverse(Usd.TraverseInstanceProxies()): if prim.HasAPI(UsdPhysics.CollisionAPI): dump["collision_prims"] += 1 if prim.IsA(UsdGeom.Mesh): dump["mesh_prims"] += 1 mesh_names.add(prim.GetParent().GetName() if prim.GetName() in ("mesh", "Mesh") else prim.GetName()) dump["instance_prototypes"] = len(stage.GetPrototypes()) for prim in stage.Traverse(): if prim.HasAPI(UsdPhysics.ArticulationRootAPI): dump["articulation_roots"].append(str(prim.GetPath())) if prim.HasAPI(UsdPhysics.RigidBodyAPI): m = UsdPhysics.MassAPI(prim) com = m.GetCenterOfMassAttr().Get() di = m.GetDiagonalInertiaAttr().Get() pa = m.GetPrincipalAxesAttr().Get() dump["links"][prim.GetName()] = { "path": str(prim.GetPath()), "mass": m.GetMassAttr().Get(), "com": [c * mpu for c in com] if com is not None else None, "diag_inertia": list(di) if di is not None else None, "principal_axes_wxyz": quat_wxyz(pa), } is_rev, is_pri = prim.IsA(UsdPhysics.RevoluteJoint), prim.IsA(UsdPhysics.PrismaticJoint) if is_rev or is_pri: j = UsdPhysics.RevoluteJoint(prim) if is_rev else UsdPhysics.PrismaticJoint(prim) lo, hi = j.GetLowerLimitAttr().Get(), j.GetUpperLimitAttr().Get() na = newton_attrs(prim) rec = { "path": str(prim.GetPath()), "type": "revolute" if is_rev else "prismatic", "axis": j.GetAxisAttr().Get(), "body0": [str(t) for t in j.GetBody0Rel().GetTargets()], "body1": [str(t) for t in j.GetBody1Rel().GetTargets()], "local_pos0": [v * mpu for v in j.GetLocalPos0Attr().Get()], "local_pos1": [v * mpu for v in j.GetLocalPos1Attr().Get()], "local_rot0_wxyz": quat_wxyz(j.GetLocalRot0Attr().Get()), "local_rot1_wxyz": quat_wxyz(j.GetLocalRot1Attr().Get()), "drive": drive_attrs(prim), "newton": na, "api_schemas": raw_schemas(prim), } if is_rev: rec.update(lower_deg=lo, upper_deg=hi) # Newton joint dynamics are per degree for revolute joints (USD angular units); converted to SI here. if "newton:damping" in na: rec["damping_si"] = na["newton:damping"] * 180.0 / math.pi if "newton:velocityLimit" in na: rec["velocity_si"] = math.radians(na["newton:velocityLimit"]) else: rec.update(lower_m=lo * mpu, upper_m=hi * mpu) if "newton:damping" in na: rec["damping_si"] = na["newton:damping"] if "newton:velocityLimit" in na: rec["velocity_si"] = na["newton:velocityLimit"] * mpu if "newton:friction" in na: rec["friction_si"] = na["newton:friction"] if "NewtonMimicAPI" in raw_schemas(prim) or "newton:mimicJoint" in [r.GetName() for r in prim.GetRelationships()]: rel = prim.GetRelationship("newton:mimicJoint") tg = [str(t) for t in rel.GetTargets()] if rel else [] c0 = prim.GetAttribute("newton:mimicCoef0") c1 = prim.GetAttribute("newton:mimicCoef1") rec["mimic"] = { "schema": "NewtonMimicAPI", "leader": tg[0].rsplit("/", 1)[-1] if tg else None, "leader_path": tg[0] if tg else None, # follower = coef0 + coef1 * leader (schema defaults 0 and 1 apply when the attribute is unauthored) "offset": float(c0.Get()) if c0 and c0.Get() is not None else 0.0, "multiplier": float(c1.Get()) if c1 and c1.Get() is not None else 1.0, "multiplier_si": (float(prim.GetAttribute("aquasalvage:mimicMultiplierSI").Get()) if prim.GetAttribute("aquasalvage:mimicMultiplierSI") else float(c1.Get()) if c1 and c1.Get() is not None else 1.0), "convention": (str(prim.GetAttribute("aquasalvage:mimicCoef1Convention").Get()) if prim.GetAttribute("aquasalvage:mimicCoef1Convention") else "same joint type: dimensionless"), "coef0_authored": bool(c0 and c0.HasAuthoredValue()), "coef1_authored": bool(c1 and c1.HasAuthoredValue()), } dump["joints"][prim.GetName()] = rec elif prim.IsA(UsdPhysics.FixedJoint): j = UsdPhysics.FixedJoint(prim) dump["fixed_joints"].append({"path": str(prim.GetPath()), "body0": [str(t) for t in j.GetBody0Rel().GetTargets()], "body1": [str(t) for t in j.GetBody1Rel().GetTargets()]}) elif prim.IsA(UsdPhysics.Joint): dump["other_joints"].append({"path": str(prim.GetPath()), "type": prim.GetTypeName()}) # Raptor-format generic mimic listing (any schema, attributes and relationships) for a in prim.GetAttributes(): if "mimic" in a.GetName().lower(): v = a.Get() dump["mimic"].append({"prim": str(prim.GetPath()), "attr": a.GetName(), "value": float(v) if isinstance(v, (int, float)) else str(v)}) for r in prim.GetRelationships(): if "mimic" in r.GetName().lower(): dump["mimic"].append({"prim": str(prim.GetPath()), "rel": r.GetName(), "targets": [str(t) for t in r.GetTargets()]}) dump["mesh_names"] = sorted(mesh_names) # self-containment: a flattened layer must not reference other layers or asset files layers, assets, unresolved = UsdUtils.ComputeAllDependencies(Sdf.AssetPath(out_usd)) dump["dependencies"] = {"layers": [os.path.basename(l.realPath) for l in layers], "assets": [str(a) for a in assets], "unresolved": [str(u) for u in unresolved]} dump["self_contained"] = len(layers) == 1 and not assets and not unresolved # cross-check names against the URDF the USD was converted from root = ET.parse(urdf).getroot() ulinks = {e.get("name") for e in root.findall("link")} ujoints = {e.get("name"): e.get("type") for e in root.findall("joint")} dump["urdf_cross_check"] = { "links_missing_in_usd": sorted(ulinks - set(dump["links"])), "links_extra_in_usd": sorted(set(dump["links"]) - ulinks), "joints_missing_in_usd": sorted(j for j, t in ujoints.items() if t != "fixed" and j not in dump["joints"]), "joints_extra_in_usd": sorted(set(dump["joints"]) - set(ujoints)), "urdf_mimic_joints": sorted(e.get("name") for e in root.findall("joint") if e.find("mimic") is not None), "usd_mimic_joints": sorted(k for k, v in dump["joints"].items() if "mimic" in v), "urdf_has_world_link": "world" in ulinks, } # hash of the URDF this USD was converted from (line ends normalised); src/model_checks.py compares it with the current # robot.urdf and reports the USD columns as NOT RUN (stale) when they differ import hashlib # noqa: E402 with open(urdf, encoding="utf-8") as fh: dump["urdf_sha256"] = hashlib.sha256(fh.read().replace("\r\n", "\n").encode("utf-8")).hexdigest() with open(out_json, "w", encoding="utf-8") as fh: json.dump(dump, fh, indent=1, default=str) print(f"flattened -> {out_usd} ({dump['file_bytes'] / 1e6:.2f} MB, {dump['file_format']}); {len(dump['links'])} rigid bodies, " f"{len(dump['joints'])} revolute/prismatic joints, {len(dump['fixed_joints'])} fixed, " f"{sum('mimic' in v for v in dump['joints'].values())} mimic followers, self-contained={dump['self_contained']}") print("urdf cross-check:", json.dumps(dump["urdf_cross_check"]))