robot-usds / scripts /build_openarm.py
mishig's picture
mishig HF Staff
Claude Opus 5.5
Restore NVIDIA's original OpenArm materials
49f5371 verified
Raw History Blame Contribute Delete
7.64 kB
"""OpenArm bimanual USD from NVIDIA's Isaac Sim asset, with the links and joints of
openarm_bimanual_web.urdf, materials as UsdPreviewSurface and geometry decimated for the web."""
import json
import sys
import fast_simplification
import numpy as np
from pxr import Gf, Sdf, Usd, UsdGeom, UsdPhysics, UsdShade
import robotusd as ru
SOURCE, URDF, OUT = sys.argv[1:4]
KEEP = float(sys.argv[4]) if len(sys.argv) > 4 else 0.08 # share of triangles kept
SIDES = ("left", "right")
layer = ru.flatten(SOURCE, {"Sensor": "None"})
stage = Usd.Stage.Open(layer)
root = str(stage.GetDefaultPrim().GetPath())
# Omniverse render settings, colliders (not drawn, and most of the bytes) and the TCP bodies,
# which sit 13 mm from the URDF's hand_tcp.
ru.remove(layer, "/Render")
for path in [p.GetPath() for p in stage.Traverse() if p.GetName() == "collisions"]:
ru.remove(layer, path)
for side in SIDES:
ru.remove(layer, f"{root}/joints/openarm_{side}_ee_tcp_joint")
ru.remove(layer, f"{root}/openarm_{side}_ee_tcp")
# link7 -> hand is fixed in the URDF; NVIDIA made it a revolute with a zero range.
for side in SIDES:
path = f"{root}/joints/openarm_{side}_hand"
spec = layer.GetPrimAtPath(path)
spec.typeName = "PhysicsFixedJoint"
for name in list(spec.attributes.keys()):
if not name.startswith(("physics:body", "physics:localPos", "physics:localRot", "physics:jointEnabled", "physics:collisionEnabled", "physics:breakForce", "physics:breakTorque", "physics:excludeFromArticulation")):
spec.RemoveProperty(spec.attributes[name])
spec.SetInfo("apiSchemas", Sdf.TokenListOp())
ru.rename(layer, path, f"{side}_openarm_hand_joint")
ru.rename(layer, f"{root}/openarm_body_link", "openarm_body_link0")
# The URDF's mimic finger moves over the same range as the finger it follows.
for side in SIDES:
joint = UsdPhysics.PrismaticJoint(stage.GetPrimAtPath(f"{root}/joints/openarm_{side}_finger_joint2"))
joint.GetLowerLimitAttr().Set(0.0)
joint.GetUpperLimitAttr().Set(0.044)
# OmniPBR (MDL) only sets a diffuse color here: the same material as UsdPreviewSurface.
for path in [p.GetPath() for p in stage.Traverse() if p.IsA(UsdShade.Material)]:
p = stage.GetPrimAtPath(path)
material = UsdShade.Material(p)
mdl = next(c for c in p.GetChildren() if c.IsA(UsdShade.Shader))
shader = UsdShade.Shader(mdl)
def value(name, default):
i = shader.GetInput(name)
return i.Get() if i and i.Get() is not None else default
color = value("diffuse_color_constant", Gf.Vec3f(0.2, 0.2, 0.2))
roughness = value("reflection_roughness_constant", 0.5)
metallic = value("metallic_constant", 0.0)
ru.remove(layer, mdl.GetPath())
mspec = layer.GetPrimAtPath(p.GetPath())
for name in list(mspec.attributes.keys()):
if name.startswith("outputs:"):
mspec.RemoveProperty(mspec.attributes[name])
preview = UsdShade.Shader.Define(stage, p.GetPath().AppendChild("PreviewSurface"))
preview.CreateIdAttr("UsdPreviewSurface")
preview.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set(color)
preview.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(roughness)
preview.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(metallic)
material.CreateSurfaceOutput().ConnectToSource(preview.ConnectableAPI(), "surface")
# One mesh per material, welded, decimated, with crease-split vertex normals.
before = after = 0
for path in [p.GetPath() for p in stage.Traverse() if p.IsA(UsdGeom.Mesh) and UsdGeom.Imageable(p).ComputePurpose() == "default"]:
p = stage.GetPrimAtPath(path)
mesh = UsdGeom.Mesh(p)
points = np.array(mesh.GetPointsAttr().Get(), dtype=np.float64)
counts = np.array(mesh.GetFaceVertexCountsAttr().Get())
assert (counts == 3).all(), p.GetPath()
faces = np.array(mesh.GetFaceVertexIndicesAttr().Get()).reshape(-1, 3)
groups = {}
for subset in UsdGeom.Subset.GetAllGeomSubsets(mesh):
bound = UsdShade.MaterialBindingAPI(subset.GetPrim()).ComputeBoundMaterial()[0]
groups.setdefault(str(bound.GetPath()), []).append(np.array(subset.GetIndicesAttr().Get()))
assigned = np.concatenate([i for v in groups.values() for i in v]) if groups else np.array([], int)
rest = np.setdiff1d(np.arange(len(faces)), assigned)
if len(rest):
bound = UsdShade.MaterialBindingAPI(p).ComputeBoundMaterial()[0]
groups.setdefault(str(bound.GetPath()) if bound else None, []).append(rest)
parent, base_name = p.GetParent().GetPath(), p.GetName()
local = UsdGeom.Xformable(p).GetLocalTransformation()
ru.remove(layer, p.GetPath())
for k, (material, parts) in enumerate(sorted(groups.items(), key=lambda kv: str(kv[0]))):
idx = np.concatenate(parts)
pts, fcs = ru.weld(points, faces[idx])
used, remap = np.unique(fcs, return_inverse=True)
pts, fcs = pts[used], remap.reshape(-1, 3)
before += len(fcs)
if len(fcs) > 200:
pts, fcs = fast_simplification.simplify(pts.astype(np.float32), fcs.astype(np.int32), target_reduction=1 - KEEP)
pts = pts.astype(np.float64)
after += len(fcs)
pts, fcs, normals = ru.crease_normals(pts, np.asarray(fcs, dtype=np.int64))
name = base_name if len(groups) == 1 else f"{base_name}_{k}"
made = ru.author_mesh(stage, str(parent.AppendChild(name)), pts, fcs, normals, material)
made.AddTransformOp().Set(local)
# The trail tips, where the URDF puts them. Bodies may use other frame conventions than the URDF
# links, so the URDF is placed by a best fit of every shared link origin.
rest = ru.urdf_fk(URDF, {})
cache = UsdGeom.XformCache()
names = {p.GetName(): p for p in stage.Traverse() if p.HasAPI(UsdPhysics.RigidBodyAPI)}
shared = [l for l in rest if l in names]
src = np.array([rest[l][:3, 3] for l in shared])
dst = np.array([ru.np_matrix(cache.GetLocalToWorldTransform(names[l]))[:3, 3] for l in shared])
cs, cd = src.mean(0), dst.mean(0)
U, _, Vt = np.linalg.svd((src - cs).T @ (dst - cd))
R = (U @ Vt).T
if np.linalg.det(R) < 0:
Vt[-1] *= -1
R = (U @ Vt).T
align = np.eye(4)
align[:3, :3] = R
align[:3, 3] = cd - R @ cs
for side in SIDES:
ru.add_frame(stage, f"{root}/openarm_{side}_hand", f"openarm_{side}_hand_tcp", align @ rest[f"openarm_{side}_hand_tcp"])
layer.documentation = (
"OpenArm bimanual for LeRobot. Modified by LeRobot from NVIDIA Isaac Sim 6.0 Robots/OpenArm/openarm_bimanual "
"(Apache-2.0): flattened into one layer; sensors, render settings and colliders removed; the ee_tcp bodies "
"replaced by the URDF's hand_tcp frames; link7-to-hand joints made fixed and renamed, and the body link renamed, "
"to match the openarm_bimanual URDF; OmniPBR materials converted to UsdPreviewSurface; visual meshes decimated."
)
layer.customLayerData = {
"lerobot:source": "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.0/Isaac/Robots/OpenArm/openarm_bimanual/openarm_bimanual.usd",
"lerobot:urdf": "https://huggingface.co/buckets/lerobot/robot-urdfs/resolve/openarm/openarm_bimanual_web.urdf",
}
layer.Export(OUT)
out = Usd.Stage.Open(OUT)
report = ru.check_against_urdf(out, URDF)
report["visual_bounds_vs_source_mm"] = ru.compare_visual_bounds(Usd.Stage.Open(SOURCE), out, {"openarm_body_link": "openarm_body_link0"})
report["triangles"] = {"before": before, "after": after}
report["meshes"] = sum(1 for p in out.Traverse() if p.IsA(UsdGeom.Mesh))
report["fit_residual_mm"] = float(np.abs((R @ src.T).T + align[:3, 3] - dst).max() * 1000)
print(json.dumps(report, indent=1, default=str))