File size: 9,819 Bytes
e967b44 | 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | #!/usr/bin/env python3
"""Apply Robot-Customization-Assets morph specs to an official URDF.
Stdlib only. Keep the scale rules in sync with
``unirobo.data_pipeline.config_catalog.write_joint_origin_urdf``.
Does **not** rewrite triangle-mesh scale (mplib/FCL rejects anisotropic mesh
scale). Only joint-origin ``xyz`` and prismatic gripper limits change.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
SKIP_LINK_TOKENS = (
"world", "finger", "gripper", "knuckle", "camera", "wsg", "pad",
"footprint", "inertial", "wheel", "castor", "caster",
)
SKIP_EXACT = frozenset({"base", "base_link", "ee_link", "tool0", "panda_link0"})
ARM_LINK_RE = re.compile(
r"^(?:(?:fl_|fr_)link[1-6]|link[1-6]|panda_link[1-7]|"
r"(?:shoulder|upper_arm|forearm|wrist_\d+)_link)$",
re.I,
)
FINGER_WIDTH_MIN = 0.85
FINGER_WIDTH_MAX = 1.12
def _vec(text: str | None) -> list[float]:
if not text:
return [0.0, 0.0, 0.0]
return [float(item) for item in text.replace(",", " ").split()]
def _fmt(values: list[float]) -> str:
return " ".join(f"{float(item):.10g}" for item in values)
def _is_gripper_name(*parts: str | None) -> bool:
blob = " ".join(part or "" for part in parts).lower()
return any(token in blob for token in ("finger", "gripper", "knuckle", "wsg"))
def arm_links(urdf: Path) -> list[str]:
names: list[str] = []
fallback: list[str] = []
for link in ET.parse(urdf).getroot().findall("link"):
name = link.get("name") or ""
lowered = name.lower()
if ARM_LINK_RE.match(name):
names.append(name)
continue
if lowered in SKIP_EXACT:
continue
if any(token in lowered for token in SKIP_LINK_TOKENS):
continue
fallback.append(name)
if names:
return names
if not fallback:
raise RuntimeError(f"no scalable arm links in {urdf}")
return fallback
def link_scale_map(link_names: list[str], spec: dict[str, Any]) -> dict[str, float]:
groups: dict[str, list[str]] = {}
for name in link_names:
if name.startswith("fl_"):
groups.setdefault("fl", []).append(name)
elif name.startswith("fr_"):
groups.setdefault("fr", []).append(name)
else:
groups.setdefault("arm", []).append(name)
link_scale: dict[str, float] = {}
for members in groups.values():
split = max(1, len(members) // 2)
for index, name in enumerate(members):
link_scale[name] = spec["proximal"] if index < split else spec["distal"]
return link_scale
def _retarget_meshes(root: ET.Element, source_urdf: Path, output_urdf: Path) -> None:
src_dir = source_urdf.parent.resolve()
out_dir = output_urdf.parent.resolve()
if src_dir == out_dir:
return
for mesh in root.findall(".//mesh"):
filename = mesh.get("filename")
if not filename or filename.startswith("package://"):
continue
path = Path(filename)
if not path.is_absolute():
path = (src_dir / path).resolve()
try:
mesh.set("filename", os.path.relpath(path, out_dir))
except ValueError:
mesh.set("filename", str(path))
def write_joint_origin_urdf(
source_urdf: Path, output_urdf: Path, spec: dict[str, Any],
) -> dict[str, Any]:
tree = ET.parse(source_urdf)
root = tree.getroot()
links = arm_links(source_urdf)
scales = link_scale_map(links, spec)
finger_length = float(spec["finger_length"])
opening = min(FINGER_WIDTH_MAX, max(FINGER_WIDTH_MIN, float(spec["finger_width"])))
joint_updates = []
gripper_updates = []
for joint in root.findall("joint"):
parent = joint.find("parent")
origin = joint.find("origin")
parent_name = parent.get("link") if parent is not None else ""
child = joint.find("child")
child_name = child.get("link") if child is not None else ""
name = joint.get("name") or ""
gripper = _is_gripper_name(name, parent_name, child_name)
scale = finger_length if gripper else float(scales.get(parent_name, 1.0))
if origin is not None and origin.get("xyz") and scale != 1.0:
before = _vec(origin.get("xyz"))
after = [item * scale for item in before]
origin.set("xyz", _fmt(after))
joint_updates.append({
"joint": name, "parent": parent_name, "scale": scale,
"before_xyz": before, "after_xyz": after,
})
if gripper and joint.get("type") == "prismatic" and opening != 1.0:
limit = joint.find("limit")
if limit is not None:
row: dict[str, Any] = {"joint": name, "opening_scale": opening}
for bound in ("lower", "upper"):
if limit.get(bound) is not None:
before_v = float(limit.get(bound))
limit.set(bound, f"{before_v * opening:.10g}")
row[bound] = {"before": before_v, "after": before_v * opening}
gripper_updates.append(row)
for mesh in root.findall(".//mesh"):
scale = mesh.get("scale")
if scale and any(abs(float(item) - 1.0) > 1e-9 for item in _vec(scale)):
raise RuntimeError(
f"refusing non-unit mesh scale {scale} in {source_urdf}; "
"mplib/FCL requires unit scale")
_retarget_meshes(root, source_urdf, output_urdf)
output_urdf.parent.mkdir(parents=True, exist_ok=True)
tree.write(output_urdf, encoding="utf-8", xml_declaration=True)
digest = hashlib.sha256(output_urdf.read_bytes()).hexdigest()
return {
"link_scale": scales,
"finger_length_scale": finger_length,
"opening_scale": opening,
"n_joint_origin_updates": len(joint_updates),
"n_gripper_limit_updates": len(gripper_updates),
"mesh_scale_policy": "unchanged_unit",
"output": str(output_urdf),
"output_sha256": digest,
}
def _load_specs(path: Path) -> dict[str, dict[str, Any]]:
payload = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise ValueError(f"{path} must be an object of morph_id -> spec")
return payload
def resolve_source_urdf(source: Path | None, embodiment_dir: Path | None) -> Path:
if source is not None:
if not source.is_file():
raise FileNotFoundError(source)
return source.resolve()
if embodiment_dir is None:
raise ValueError("pass --source or --embodiment-dir")
config = embodiment_dir / "config.yml"
if config.is_file():
match = re.search(r"urdf_path:\s*(\S+)", config.read_text(encoding="utf-8"))
if match:
raw = match.group(1).strip().strip("\"'")
raw = re.sub(r"^\$\{ASSETS_PATH\}/", "", raw)
candidate = Path(raw)
if candidate.is_file():
return candidate.resolve()
local = embodiment_dir / candidate.name
if local.is_file():
return local.resolve()
nested = embodiment_dir / candidate
if nested.is_file():
return nested.resolve()
found = sorted(embodiment_dir.glob("*.urdf"))
if len(found) == 1:
return found[0].resolve()
raise FileNotFoundError(
f"could not resolve a URDF under {embodiment_dir}; pass --source")
def main() -> int:
here = Path(__file__).resolve()
default_spec = here.parents[1] / "morph_specs" / "morphs.json"
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", type=Path, help="Official URDF path")
parser.add_argument(
"--embodiment-dir", type=Path,
help="RoboTwin assets/embodiments/<name> (reads config.yml urdf_path)")
parser.add_argument("--spec", type=Path, default=default_spec,
help="morphs.json from this dataset")
parser.add_argument("--morph-id", help="One key from morphs.json")
parser.add_argument("--all", action="store_true",
help="Write one URDF per morph id")
parser.add_argument("--output", type=Path, help="Output URDF (single morph)")
parser.add_argument("--output-dir", type=Path,
help="Directory for --all (default: next to the source URDF)")
parser.add_argument("--list", action="store_true", help="Print morph ids")
args = parser.parse_args()
specs = _load_specs(args.spec)
if args.list:
for name, spec in specs.items():
print(f"{name}\t{spec.get('description', '')}")
return 0
source = resolve_source_urdf(args.source, args.embodiment_dir)
wanted = list(specs) if args.all else [args.morph_id]
if not args.all and not args.morph_id:
parser.error("pass --morph-id, --all, or --list")
unknown = [name for name in wanted if name not in specs]
if unknown:
raise KeyError(f"unknown morph id: {unknown[:8]}")
reports = []
if args.all:
out_dir = args.output_dir or source.parent
for name in wanted:
output = out_dir / f"{source.stem}__{name}{source.suffix}"
reports.append(write_joint_origin_urdf(source, output, specs[name]))
else:
output = args.output
if output is None:
output = source.with_name(f"{source.stem}__{args.morph_id}{source.suffix}")
reports.append(write_joint_origin_urdf(source, output, specs[args.morph_id]))
print(json.dumps(reports if args.all else reports[0], indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
|