Update xiaozhao geometry, base axes, TCPs, neck joints and actuators. Add mesh generation tools, simplified visuals, screen and hand tags, and hand/head camera attachments. Configure both arms and enable the right-arm visual touch workflow with updated calibration, a camera-visible initial pose and higher-resolution external perception. Keep touch tests distance-limited with ZeroSimTouch. Release MuJoCo joint state control on torqueOff, latch the disabled state until torqueOn, and add regression coverage for actuator and fallback modes. Validation: isolated device/task initialization, camera acquisition and AprilTag pose checks passed. Full visual-servo motion was not validated.
189 lines
9.3 KiB
Python
189 lines
9.3 KiB
Python
"""Regenerate xiaozhao.xml from the current URDF using bundled MuJoCo 3.3.7.
|
|
|
|
Uses simplified visual meshes when available and retains original collision
|
|
meshes. URDF TCP visual spheres become massless, non-colliding MuJoCo sites.
|
|
Environment, actuator and contact-exclusion configuration remain in separate
|
|
XML files included by scene.xml; load scene.xml for the complete simulation.
|
|
Camera attachments are loaded from xml/hand_camera.xml and xml/head_camera.xml.
|
|
"""
|
|
|
|
import argparse
|
|
import copy
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import stat
|
|
import subprocess
|
|
import tempfile
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
MODEL = Path(__file__).resolve().parent
|
|
REPO = MODEL.parents[1]
|
|
MESHES = MODEL / "meshes"
|
|
XML = MODEL / "xml/xiaozhao.xml"
|
|
CAMERA_ATTACHMENTS = (
|
|
(MODEL / "xml/hand_camera.xml", "link7-right"),
|
|
(MODEL / "xml/head_camera.xml", "neck_Link3"),
|
|
)
|
|
# Hand STLs are now lightweight too. Keep their original OBJ collision geometry;
|
|
# those OBJ files also serve as the source for repeatable hand simplification.
|
|
LARGE_MESHES = {"base_link.STL", "link7-left.STL", "link7-right.STL", "hand-right-mirrored.STL"}
|
|
|
|
|
|
def incorporate_inertial_rotation(link):
|
|
"""Express URDF inertia in link axes, preserving its physical tensor.
|
|
|
|
The native 3.3.7 importer otherwise drops inertial-origin rotation when
|
|
diagonalizing full tensors. Normalize only the temporary conversion copy.
|
|
"""
|
|
inertial = link.find("inertial")
|
|
if inertial is None:
|
|
return
|
|
origin = inertial.find("origin")
|
|
if origin is None:
|
|
return
|
|
r, p, y = map(float, origin.get("rpy", "0 0 0").split())
|
|
if (r, p, y) == (0., 0., 0.):
|
|
return
|
|
cr, sr, cp, sp, cy, sy = math.cos(r), math.sin(r), math.cos(p), math.sin(p), math.cos(y), math.sin(y)
|
|
rotation = [[cy*cp, cy*sp*sr-sy*cr, cy*sp*cr+sy*sr],
|
|
[sy*cp, sy*sp*sr+cy*cr, sy*sp*cr-cy*sr], [-sp, cp*sr, cp*cr]]
|
|
tensor = inertial.find("inertia")
|
|
a = {k: float(v) for k, v in tensor.attrib.items()}
|
|
inertia = [[a["ixx"], a["ixy"], a["ixz"]],
|
|
[a["ixy"], a["iyy"], a["iyz"]], [a["ixz"], a["iyz"], a["izz"]]]
|
|
rotated = [[sum(rotation[i][k]*inertia[k][l]*rotation[j][l]
|
|
for k in range(3) for l in range(3)) for j in range(3)] for i in range(3)]
|
|
for key, i, j in [("ixx", 0, 0), ("ixy", 0, 1), ("ixz", 0, 2),
|
|
("iyy", 1, 1), ("iyz", 1, 2), ("izz", 2, 2)]:
|
|
tensor.set(key, format(rotated[i][j], ".17g"))
|
|
origin.set("rpy", "0 0 0")
|
|
|
|
|
|
def compile_model(compiler, source, destination):
|
|
result = subprocess.run([str(compiler), str(source), str(destination)],
|
|
capture_output=True, text=True)
|
|
# The bundled utility can return zero even when model compilation fails.
|
|
if result.returncode or not destination.exists():
|
|
raise RuntimeError(result.stdout + result.stderr)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--compiler", type=Path,
|
|
default=REPO / "dependency/x86/third_party/mujoco/v3.3.7/bin/compile")
|
|
parser.add_argument("--output", type=Path, default=XML)
|
|
args = parser.parse_args()
|
|
output = args.output.resolve()
|
|
source_path = MODEL / "urdf/xiaozhao.urdf"
|
|
original = source_path.read_bytes()
|
|
camera_sources = [(path, parent, path.read_bytes()) for path, parent in CAMERA_ATTACHMENTS]
|
|
previous = output.read_bytes() if output.exists() else None
|
|
source = ET.fromstring(original)
|
|
|
|
with tempfile.TemporaryDirectory(prefix="xiaozhao-convert-") as temporary:
|
|
work = Path(temporary)
|
|
(work / "visual").mkdir()
|
|
asset_paths = {}
|
|
for link in source.findall("link"):
|
|
incorporate_inertial_rotation(link)
|
|
for kind in ("visual", "collision"):
|
|
for element in link.findall(kind):
|
|
mesh = element.find("geometry/mesh")
|
|
if mesh is None:
|
|
continue
|
|
name = Path(mesh.get("filename")).name
|
|
simplified = MESHES / "visual" / name
|
|
if kind == "visual" and simplified.exists():
|
|
local = work / "visual" / (Path(name).stem + "_visual" + Path(name).suffix)
|
|
if not local.exists():
|
|
local.symlink_to(simplified)
|
|
relative = "visual/" + name
|
|
else:
|
|
if name in LARGE_MESHES:
|
|
name = Path(name).with_suffix(".obj").name
|
|
local, relative = MESHES / name, name
|
|
if not local.exists():
|
|
raise FileNotFoundError(local)
|
|
mesh.set("filename", str(local))
|
|
asset_paths[str(local)] = relative
|
|
extension = source.find("mujoco")
|
|
if extension is None:
|
|
extension = ET.SubElement(source, "mujoco")
|
|
compiler = extension.find("compiler")
|
|
if compiler is None:
|
|
compiler = ET.SubElement(extension, "compiler")
|
|
compiler.attrib.update(discardvisual="false", fusestatic="false", strippath="false")
|
|
ET.ElementTree(source).write(work / "source.urdf", encoding="utf-8", xml_declaration=True)
|
|
compile_model(args.compiler, work / "source.urdf", work / "generated.xml")
|
|
robot = ET.parse(work / "generated.xml").getroot()
|
|
robot.find("compiler").set("meshdir", os.path.relpath(MESHES, output.parent))
|
|
for asset in robot.findall("asset/mesh"):
|
|
asset.set("file", asset_paths[asset.get("file")])
|
|
for geom in robot.findall(".//geom"):
|
|
if geom.get("contype", "1") != "0" or geom.get("conaffinity", "1") != "0":
|
|
geom.set("group", "3")
|
|
for side in ("left", "right"):
|
|
name = "tcp-" + side
|
|
link = source.find(f'link[@name="{name}"]')
|
|
body = robot.find(f'.//body[@name="{name}"]')
|
|
if link is None or body is None or link.find("visual/geometry/sphere") is None:
|
|
continue
|
|
geoms = body.findall("geom")
|
|
if (link.find("inertial") is not None or link.find("collision") is not None
|
|
or body.find("inertial") is not None or len(geoms) != 1
|
|
or geoms[0].get("type", "sphere") != "sphere"):
|
|
raise ValueError(f"{name}: expected a massless TCP with one visual sphere")
|
|
geom = geoms[0]
|
|
site = {k: v for k, v in geom.attrib.items() if k in ("pos", "quat", "size", "rgba")}
|
|
site.update(name=name, type="sphere", group="1")
|
|
body.remove(geom)
|
|
ET.SubElement(body, "site", site)
|
|
# Mount the independent camera modules on their robot links. Their
|
|
# assets are included so the standalone robot also compiles directly.
|
|
for module_path, parent_name, module_source in camera_sources:
|
|
module = ET.fromstring(module_source)
|
|
for asset in module.findall("asset/*"):
|
|
if "file" in asset.attrib:
|
|
asset.set("file", os.path.relpath(
|
|
(module_path.parent / asset.get("file")).resolve(), output.parent))
|
|
robot.find("asset").append(copy.deepcopy(asset))
|
|
parent = robot.find(f'.//body[@name="{parent_name}"]')
|
|
if parent is None:
|
|
raise ValueError(f"{module_path.name} requires URDF {parent_name}")
|
|
for attachment in module.findall("worldbody/*"):
|
|
parent.append(copy.deepcopy(attachment))
|
|
comments = [
|
|
" Generated from ../urdf/xiaozhao.urdf with MuJoCo 3.3.7; base_link is the single fixed root. ",
|
|
" Simplified visuals are in meshes/visual; original collision meshes and inertias are retained. ",
|
|
" Collision group 3 is hidden by default. Contact exclusions, environment and actuators are included by scene.xml. ",
|
|
" Inertial-origin rotations are incorporated in link-frame tensors before conversion. ",
|
|
" TCP visual spheres from URDF are represented by non-colliding, massless sites. ",
|
|
" Cameras and hand AprilTag are mounted from hand_camera.xml and head_camera.xml by the generator. ",
|
|
]
|
|
for i, comment in enumerate(comments):
|
|
robot.insert(i, ET.Comment(comment))
|
|
ET.indent(robot, space=" ")
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.NamedTemporaryFile(dir=output.parent, prefix=".xiaozhao-", suffix=".xml", delete=False) as f:
|
|
staged = Path(f.name)
|
|
try:
|
|
ET.ElementTree(robot).write(staged, encoding="utf-8", xml_declaration=True)
|
|
with staged.open("ab") as f:
|
|
f.write(b"\n")
|
|
compile_model(args.compiler, staged, work / "verified.mjb")
|
|
if (source_path.read_bytes() != original
|
|
or any(path.read_bytes() != content for path, _, content in camera_sources)
|
|
or (output.read_bytes() if output.exists() else None) != previous):
|
|
raise RuntimeError("URDF or target XML changed during conversion; output not replaced")
|
|
staged.chmod(stat.S_IMODE(output.stat().st_mode) if output.exists() else 0o644)
|
|
os.replace(staged, output)
|
|
finally:
|
|
staged.unlink(missing_ok=True)
|
|
print(f"Generated and compiled {output}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|