File size: 13,525 Bytes
9ff5f84 dfbee67 9ff5f84 dfbee67 9ff5f84 dfbee67 9ff5f84 dfbee67 9ff5f84 dfbee67 9ff5f84 dfbee67 9ff5f84 dfbee67 9ff5f84 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | """Convert every pinned URDF plus the AlienGo/Z1 Xacro assembly to portable USD.
Run in the supplied Linux container. Source files remain unmodified. Converter
inputs live in a temporary directory; all published USD geometry is embedded.
"""
import argparse, concurrent.futures, json, os, pathlib, re, shutil, subprocess, sys, tempfile, traceback
from lxml import etree as ET
ROOT = pathlib.Path(__file__).resolve().parent
OUT = ROOT.parent if ROOT.name == 'scripts' else ROOT / 'dataset'
ROS = OUT / 'sources/unitree_ros/robots'
def jobs():
result = []
for p in sorted(ROS.rglob('*.urdf')):
result.append((p, p.relative_to(ROS).parts[0] + '/' + p.stem))
result += [
(ROS / 'aliengoZ1_description/xacro/robot.xacro', 'aliengoZ1_description/aliengo_z1'),
(OUT / 'sources/Qmini/urdf/Qmini.urdf', 'Qmini/Qmini'),
(OUT / 'sources/UniArmL1/assets/uniarml1/urdf/UniArmL1.urdf', 'UniArmL1/UniArmL1'),
(OUT / 'sources/z1_ros/z1_controller/config/z1.urdf', 'z1_ros/z1'),
(OUT / 'sources/xr_teleoperate/assets/brainco_hand/brainco_left.urdf', 'brainco_hand/brainco_left'),
(OUT / 'sources/xr_teleoperate/assets/brainco_hand/brainco_right.urdf', 'brainco_hand/brainco_right'),
(OUT / 'sources/unitree_rl_gym/resources/robots/g1_description/g1_12dof.urdf', 'unitree_rl_gym/g1_12dof'),
(OUT / 'sources/unitree_rl_gym/resources/robots/h1_2/h1_2_12dof.urdf', 'unitree_rl_gym/h1_2_12dof'),
(OUT / 'sources/unitree_rl_gym/resources/robots/h1_2/h1_2_simplified.urdf', 'unitree_rl_gym/h1_2_simplified'),
]
return result
def flatten_bodies(stage):
from pxr import Usd, UsdGeom, UsdPhysics, Sdf
root = stage.GetDefaultPrim()
root_world = UsdGeom.XformCache().GetLocalToWorldTransform(root)
bodies = [p for p in stage.Traverse() if p.HasAPI(UsdPhysics.RigidBodyAPI)]
worlds = {str(p.GetPath()): UsdGeom.XformCache().GetLocalToWorldTransform(p) for p in bodies}
scope = root.GetPath().AppendChild('Bodies')
UsdGeom.Xform.Define(stage, scope)
for p in sorted(bodies, key=lambda p: len(str(p.GetPath())), reverse=True):
old = str(p.GetPath())
new = scope.AppendChild(p.GetName())
if stage.GetPrimAtPath(new): raise RuntimeError('Duplicate rigid body name: ' + p.GetName())
edit = Usd.NamespaceEditor(stage)
if not edit.MovePrimAtPath(Sdf.Path(old), new): raise RuntimeError('Cannot move: ' + old)
if not edit.CanApplyEdits(): raise RuntimeError('Cannot apply body flattening: ' + old)
if not edit.ApplyEdits(): raise RuntimeError('Body flattening failed: ' + old)
xform = UsdGeom.Xformable(stage.GetPrimAtPath(new))
xform.ClearXformOpOrder()
xform.AddTransformOp().Set(worlds[old] * root_world.GetInverse())
for p in stage.Traverse():
if p.HasAPI(UsdPhysics.ArticulationRootAPI): p.RemoveAPI(UsdPhysics.ArticulationRootAPI)
UsdPhysics.ArticulationRootAPI.Apply(root)
def convert_one(source, ident):
from pxr import Usd, UsdGeom, UsdPhysics, Sdf, Gf
import urdf_usd_converter
changes = []
packages = {p.name: p for p in ROS.iterdir() if p.is_dir()}
if source.suffix == '.xacro':
import xacro, xacro.substitution_args
xacro.substitution_args._eval_find = lambda name: str(packages[name])
doc = xacro.process_file(str(source), mappings={'DEBUG': 'false'})
tree = ET.fromstring(doc.toxml().encode())
changes.append('Expanded Xacro with DEBUG=false and default gripper enabled.')
else:
tree = ET.parse(str(source)).getroot()
tree.set('name', re.sub(r'[^a-zA-Z0-9_]', '_', ident.rsplit('/', 1)[-1]))
for i, material in enumerate(tree.iter('material')):
if not material.get('name'):
material.set('name', 'unnamed_material_' + str(i))
changes.append('Assigned missing material name at index ' + str(i))
for mesh in list(tree.iter('mesh')) + list(tree.iter('texture')):
name = mesh.get('filename')
if not name: continue
if name.startswith('package://'):
pkg, rel = name[len('package://'):].split('/', 1)
p = packages.get(pkg, source.parent) / rel
elif name.startswith('file://'): p = pathlib.Path(name[7:])
else: p = source.parent / name
p = p.resolve()
if not p.is_file():
candidates = sorted(set(source.parent.rglob(pathlib.Path(name).name)))
if not candidates:
pkgroot = next((q for q in source.parents if q.parent == ROS), source.parent)
candidates = sorted(set(pkgroot.rglob(pathlib.Path(name).name)))
if len(candidates) != 1: raise FileNotFoundError(f'{name}: expected {p}; found {len(candidates)} alternatives')
p = candidates[0]
changes.append(f'Resolved mesh {name} to {p.relative_to(OUT)}')
if p.stat().st_size < 256 and p.read_bytes().startswith(b'version https://git-lfs'): raise ValueError('Unresolved Git LFS pointer: ' + str(p))
mesh.set('filename', str(p))
dest = OUT / 'generated' / ident
dest.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
normalized = pathlib.Path(tmp) / (tree.get('name') + '.urdf')
ET.ElementTree(tree).write(str(normalized), encoding='utf-8', xml_declaration=True)
converter = urdf_usd_converter.Converter(layer_structure=False, scene=False,
comment=f'Converted from {source.relative_to(OUT)}; see manifest.json for provenance.',
ros_packages=[{'name': n, 'path': str(p)} for n, p in packages.items()])
asset = converter.convert(str(normalized), str(dest))
path = pathlib.Path(asset.path)
stage = Usd.Stage.Open(str(path))
if not stage or not stage.GetDefaultPrim(): raise RuntimeError('No default prim')
flatten_bodies(stage)
# USD's unauthored centerOfMass means automatic collider-based inference;
# URDF's omitted inertial origin means an explicit zero offset instead.
links = {link.get('name'): link for link in tree.findall('link')}
for prim in stage.Traverse():
if not prim.HasAPI(UsdPhysics.RigidBodyAPI): continue
name = prim.GetDisplayName() or prim.GetName()
inertial = links[name].find('inertial')
if inertial is None: continue
origin = inertial.find('origin')
xyz = origin.get('xyz', '0 0 0') if origin is not None else '0 0 0'
UsdPhysics.MassAPI(prim).CreateCenterOfMassAttr(Gf.Vec3f(*map(float, xyz.split())))
fixed_packages = ('r1_7a_description', 'r1_a5_description', 'r1_a7_description', 'z1_description', 'z1_ros', 'dexterous_hand_description', 'UniArmL1', 'brainco_hand')
fixed_base = ident.split('/')[0] in fixed_packages or 'dual_arm' in ident or '/inspire_hand/' in str(source)
if not fixed_base:
root_joint = stage.GetDefaultPrim().GetPath().AppendPath('Physics/root_joint')
if stage.GetPrimAtPath(root_joint): stage.RemovePrim(root_joint)
stage.GetRootLayer().Save()
checks = validate_stage(path)
active_types = ('revolute', 'continuous', 'prismatic')
source_active = sum(j.get('type') in active_types for j in tree.findall('joint'))
usd_active = sum(p.IsA(UsdPhysics.RevoluteJoint) or p.IsA(UsdPhysics.PrismaticJoint) for p in stage.Traverse())
if source_active != usd_active:
raise RuntimeError(f'Active joint loss: source={source_active}, USD={usd_active}')
source_mass = sum(float(n.get('value')) for n in tree.findall('link/inertial/mass'))
usd_mass = sum(UsdPhysics.MassAPI(p).GetMassAttr().Get() or 0 for p in stage.Traverse() if p.HasAPI(UsdPhysics.MassAPI))
if abs(source_mass - usd_mass) > max(1e-5, source_mass * 1e-5):
raise RuntimeError(f'Mass mismatch: source={source_mass}, USD={usd_mass}')
checks.update({'source_active_joints': source_active, 'usd_active_joints': usd_active,
'source_mass_kg': source_mass, 'usd_mass_kg': usd_mass})
# Preserve a portable copy of the exact normalized converter input.
for mesh in list(tree.iter('mesh')) + list(tree.iter('texture')):
if mesh.get('filename'):
mesh.set('filename', os.path.relpath(mesh.get('filename'), dest))
ET.ElementTree(tree).write(str(dest / 'input.urdf'), encoding='utf-8', xml_declaration=True, pretty_print=True)
return {'id': ident, 'source': str(source.relative_to(OUT)), 'usd': str(path.relative_to(OUT)),
'status': 'converted', 'fixed_base': fixed_base, 'normalizations': changes,
'source_links': len(tree.findall('link')), 'source_joints': len(tree.findall('joint')),
'validation': checks}
def validate_stage(path):
from pxr import Usd, UsdGeom, UsdPhysics, UsdUtils, Sdf
stage = Usd.Stage.Open(str(path))
if not stage: raise RuntimeError('USD cannot be opened')
layers, assets, unresolved = UsdUtils.ComputeAllDependencies(str(path))
if unresolved: raise RuntimeError('Unresolved USD dependencies: ' + repr(unresolved))
meshes = bodies = colliders = joints = 0
for p in stage.Traverse():
if p.IsA(UsdGeom.Mesh):
m = UsdGeom.Mesh(p)
if not m.GetPointsAttr().Get() or not m.GetFaceVertexCountsAttr().Get(): raise RuntimeError('Empty mesh: '+str(p.GetPath()))
meshes += 1
bodies += int(p.HasAPI(UsdPhysics.RigidBodyAPI))
colliders += int(p.HasAPI(UsdPhysics.CollisionAPI))
if p.IsA(UsdPhysics.Joint):
joints += 1
j = UsdPhysics.Joint(p)
for target in j.GetBody0Rel().GetTargets() + j.GetBody1Rel().GetTargets():
if not stage.GetPrimAtPath(target): raise RuntimeError('Dangling joint body: '+str(target))
if p.HasAPI(UsdPhysics.RigidBodyAPI):
parent = p.GetParent()
while parent and not parent.IsPseudoRoot():
if parent.HasAPI(UsdPhysics.RigidBodyAPI): raise RuntimeError('Nested rigid bodies: '+str(p.GetPath()))
parent = parent.GetParent()
if not meshes or not bodies or not joints: raise RuntimeError('Incomplete robot geometry or physics')
return {'usd_opens': True, 'unresolved_dependencies': 0, 'meshes': meshes,
'rigid_bodies': bodies, 'colliders': colliders, 'joints': joints,
'flat_rigid_body_hierarchy': True, 'isaac_sim_runtime_tested': False}
def run_job(job):
source, ident = job
logdir = ROOT / 'logs'
logdir.mkdir(exist_ok=True)
target = ROOT / 'results' / (ident.replace('/', '__') + '.json')
target.parent.mkdir(exist_ok=True)
with (logdir / (ident.replace('/', '__') + '.log')).open('w') as log:
result = subprocess.run([sys.executable, __file__, '--one', str(source), '--id', ident, '--result', str(target)], stdout=log, stderr=log)
if result.returncode:
data = {'id': ident, 'source': str(source.relative_to(OUT)), 'status': 'failed',
'error': (logdir / (ident.replace('/', '__') + '.log')).read_text()[-4000:]}
target.write_text(json.dumps(data, indent=2))
else:
data = json.loads(target.read_text())
warnings = [line.split(' -- ', 1)[-1] for line in (logdir / (ident.replace('/', '__') + '.log')).read_text().splitlines() if line.startswith('Warning:')]
data['conversion_warnings'] = warnings
if any('Failed to convert mesh' in w for w in warnings):
data['status'] = 'failed'
data['error'] = 'Converter omitted source mesh geometry; see conversion_warnings.'
target.write_text(json.dumps(data, indent=2) + '\n')
print(data['status'], ident, flush=True)
return data
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--one')
parser.add_argument('--id')
parser.add_argument('--result')
parser.add_argument('--only-new', action='store_true', help='Preserve existing manifest entries and convert newly added source jobs only')
args = parser.parse_args()
if args.one:
result = convert_one(pathlib.Path(args.one), args.id)
pathlib.Path(args.result).write_text(json.dumps(result, indent=2) + '\n')
else:
previous = json.loads((OUT / 'manifest.json').read_text())['models'] if args.only_new else []
existing = {m['id']: m for m in previous}
selected = [(p, ident) for p, ident in jobs() if ident not in existing]
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
added = list(pool.map(run_job, selected))
if any(m['status'] != 'converted' for m in added):
raise SystemExit('Conversion failed; existing manifest preserved. Inspect results and logs.')
existing.update({m['id']: m for m in added})
results = [existing[ident] for _, ident in jobs()]
(OUT / 'manifest.json').write_text(json.dumps({'converter': 'urdf-usd-converter==0.3.4',
'postprocessing': 'Flatten rigid bodies, preserve world transforms and joint relationships, explicitly author source centers of mass (including zero offsets), remove synthetic world fixation for mobile robots. No controller gain tuning.',
'limitations_document': 'KNOWN_LIMITATIONS.md',
'simulation_validation': {'isaac_sim_runtime_tested': False, 'closed_loop_mjcf_constraints_translated': False, 'physx_mimic_joints_authored': False},
'models': results}, indent=2) + '\n')
print('Converted', sum(x['status']=='converted' for x in results), 'of', len(results), flush=True)
|