Source code for joltsim.mjcf

from __future__ import annotations

import math
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Optional, Tuple

import numpy as np

from joltsim._core import (
    ArticulationDesc,
    BodyDesc,
    JointDesc,
    JointType,
    MotorConfig,
    MotorMode,
    ShapeDesc,
    ShapeType,
    SiteDesc,
)


def _floats(text: Optional[str], default: Tuple[float, ...]) -> Tuple[float, ...]:
    if not text:
        return default
    return tuple(float(x) for x in text.strip().split())


def _quat_mul(q1: np.ndarray, q2: np.ndarray) -> np.ndarray:
    x1, y1, z1, w1 = q1
    x2, y2, z2, w2 = q2
    return np.array([
        w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
        w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
        w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2,
        w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
    ], dtype=np.float64)


def _quat_to_mat3(q: np.ndarray) -> np.ndarray:
    x, y, z, w = q
    xx, yy, zz = x * x, y * y, z * z
    xy, xz, yz = x * y, x * z, y * z
    wx, wy, wz = w * x, w * y, w * z
    return np.array([
        [1.0 - 2.0 * (yy + zz), 2.0 * (xy - wz), 2.0 * (xz + wy)],
        [2.0 * (xy + wz), 1.0 - 2.0 * (xx + zz), 2.0 * (yz - wx)],
        [2.0 * (xz - wy), 2.0 * (yz + wx), 1.0 - 2.0 * (xx + yy)],
    ], dtype=np.float64)


def _quat_rotate(q: np.ndarray, v: np.ndarray) -> np.ndarray:
    return _quat_to_mat3(q) @ v


def _quat_inv(q: np.ndarray) -> np.ndarray:
    return np.array([-q[0], -q[1], -q[2], q[3]], dtype=np.float64)


def _axisangle_to_quat(axis: np.ndarray, angle_rad: float) -> np.ndarray:
    n = np.linalg.norm(axis)
    if n < 1e-12:
        return np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
    a = axis / n
    s = math.sin(0.5 * angle_rad)
    c = math.cos(0.5 * angle_rad)
    return np.array([a[0] * s, a[1] * s, a[2] * s, c], dtype=np.float64)


def _euler_xyz_to_quat(rx: float, ry: float, rz: float) -> np.ndarray:
    qx = _axisangle_to_quat(np.array([1.0, 0.0, 0.0]), rx)
    qy = _axisangle_to_quat(np.array([0.0, 1.0, 0.0]), ry)
    qz = _axisangle_to_quat(np.array([0.0, 0.0, 1.0]), rz)
    return _quat_mul(_quat_mul(qx, qy), qz)


def _quat_from_z_to_dir(direction: np.ndarray) -> np.ndarray:
    n = np.linalg.norm(direction)
    if n < 1e-12:
        return np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
    d = direction / n
    z = np.array([0.0, 0.0, 1.0], dtype=np.float64)
    dot = float(np.dot(z, d))
    if dot > 0.999999:
        return np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
    if dot < -0.999999:
        return np.array([1.0, 0.0, 0.0, 0.0], dtype=np.float64)
    axis = np.cross(z, d)
    w = 1.0 + dot
    q = np.array([axis[0], axis[1], axis[2], w], dtype=np.float64)
    return q / np.linalg.norm(q)


def _parse_mjcf_quat(elem: ET.Element, angle_scale: float) -> np.ndarray:
    if "quat" in elem.attrib:
        w, x, y, z = _floats(elem.attrib["quat"], (1.0, 0.0, 0.0, 0.0))
        q = np.array([x, y, z, w], dtype=np.float64)
        n = np.linalg.norm(q)
        return q / n if n > 1e-12 else np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)
    if "axisangle" in elem.attrib:
        ax, ay, az, ang = _floats(elem.attrib["axisangle"], (0.0, 0.0, 1.0, 0.0))
        return _axisangle_to_quat(np.array([ax, ay, az], dtype=np.float64), ang * angle_scale)
    if "euler" in elem.attrib:
        ex, ey, ez = _floats(elem.attrib["euler"], (0.0, 0.0, 0.0))
        return _euler_xyz_to_quat(ex * angle_scale, ey * angle_scale, ez * angle_scale)
    return np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64)


def _geom_mass_inertia(sd: ShapeDesc, density: float) -> Tuple[float, np.ndarray]:
    if sd.type == ShapeType.Sphere:
        r = sd.radius
        m = (4.0 / 3.0) * math.pi * (r ** 3) * density
        i = 0.4 * m * (r ** 2) * np.eye(3, dtype=np.float64)
        return m, i
    if sd.type == ShapeType.Box:
        hx, hy, hz = sd.half_extents
        m = 8.0 * hx * hy * hz * density
        ixx = (1.0 / 3.0) * m * (hy ** 2 + hz ** 2)
        iyy = (1.0 / 3.0) * m * (hx ** 2 + hz ** 2)
        izz = (1.0 / 3.0) * m * (hx ** 2 + hy ** 2)
        return m, np.diag([ixx, iyy, izz])
    if sd.type in (ShapeType.Cylinder, ShapeType.Capsule):
        r = sd.radius
        h = 2.0 * sd.half_height
        m_cyl = math.pi * (r ** 2) * h * density
        m_cap = (4.0 / 3.0) * math.pi * (r ** 3) * density if sd.type == ShapeType.Capsule else 0.0
        m = max(1e-5, m_cyl + m_cap)
        izz = 0.5 * m_cyl * (r ** 2) + 0.4 * m_cap * (r ** 2)
        ixx = (1.0 / 12.0) * m_cyl * (3.0 * r ** 2 + h ** 2) + m_cap * (0.4 * r ** 2 + 0.25 * h ** 2)
        return m, np.diag([ixx, ixx, izz])
    return 1.0, 0.01 * np.eye(3, dtype=np.float64)


def _parallel_axis_combine(
    m1: float, c1: np.ndarray, i1: np.ndarray,
    m2: float, c2: np.ndarray, i2: np.ndarray,
) -> Tuple[float, np.ndarray, np.ndarray]:
    m_tot = m1 + m2
    if m_tot <= 1e-12:
        return 0.0, np.zeros(3, dtype=np.float64), np.zeros((3, 3), dtype=np.float64)
    c_new = (m1 * c1 + m2 * c2) / m_tot
    d1 = c1 - c_new
    d2 = c2 - c_new
    eye = np.eye(3, dtype=np.float64)
    i_new = (
        i1 + m1 * (float(np.dot(d1, d1)) * eye - np.outer(d1, d1))
        + i2 + m2 * (float(np.dot(d2, d2)) * eye - np.outer(d2, d2))
    )
    return m_tot, c_new, i_new


[docs] @dataclass class MjcfModel: desc: ArticulationDesc link_names: List[str] joint_names: List[str] actuated_joint_names: List[str] motor_joint_names: List[str] has_ground_plane: bool ground_z: float sites: List[SiteDesc] = field(default_factory=list)
[docs] def load_mjcf( mjcf_path: str | Path, base_pos: Optional[Tuple[float, float, float]] = None, fixed_base: Optional[bool] = None, default_kp: float = 120.0, default_kd: float = 12.0, default_effort: float = 150.0, inertia_scale: float = 1.0, min_inertia_diag: float = 1e-3, motor_mode: MotorMode = MotorMode.Position, ) -> MjcfModel: """Parse a MuJoCo MJCF XML into a JoltSim ArticulationDesc.""" path = Path(mjcf_path) tree = ET.parse(path) root = tree.getroot() compiler = root.find("compiler") angle_unit = compiler.attrib.get("angle", "degree").lower() if compiler is not None else "degree" angle_scale = (math.pi / 180.0) if angle_unit == "degree" else 1.0 coord_mode = compiler.attrib.get("coordinate", "local").lower() if compiler is not None else "local" set_total_mass = float(compiler.attrib["settotalmass"]) if (compiler is not None and "settotalmass" in compiler.attrib) else None # Parse <default> def_geom_attrib: Dict[str, str] = {} def_joint_attrib: Dict[str, str] = {} def_motor_attrib: Dict[str, str] = {} default_el = root.find("default") if default_el is not None: g_def = default_el.find("geom") if g_def is not None: def_geom_attrib.update(g_def.attrib) j_def = default_el.find("joint") if j_def is not None: def_joint_attrib.update(j_def.attrib) m_def = default_el.find("motor") if m_def is not None: def_motor_attrib.update(m_def.attrib) # Parse <actuator>/<motor> motor_specs: Dict[str, Dict[str, float]] = {} actuator_el = root.find("actuator") if actuator_el is not None: for m_el in actuator_el.findall("motor"): attrib = {**def_motor_attrib, **m_el.attrib} jname = attrib.get("joint") if not jname: continue gear = float(attrib.get("gear", "1.0")) cr = _floats(attrib.get("ctrlrange"), (-1.0, 1.0)) max_eff = abs(gear) * max(abs(cr[0]), abs(cr[1])) motor_specs[jname] = {"gear": gear, "max_effort": max(1.0, max_eff)} worldbody = root.find("worldbody") if worldbody is None: raise ValueError(f"No <worldbody> found in MJCF: {path}") has_ground_plane = False ground_z = 0.0 for wg in worldbody.findall("geom"): if wg.attrib.get("type", "sphere").lower() == "plane": has_ground_plane = True p = _floats(wg.attrib.get("pos"), (0.0, 0.0, 0.0)) ground_z = float(p[2]) top_bodies = worldbody.findall("body") if not top_bodies: raise ValueError(f"No <body> found inside <worldbody> in MJCF: {path}") root_body_el = top_bodies[0] # Determine if root has non-free joints (planar/fixed-to-world like hopper/cheetah/walker2d) root_joints = [j for j in root_body_el.findall("joint") if j.attrib.get("type", "hinge").lower() != "free"] if fixed_base is None: inferred_fixed_base = len(root_joints) > 0 else: inferred_fixed_base = fixed_base links: List[BodyDesc] = [] joints: List[JointDesc] = [] link_names: List[str] = [] joint_names: List[str] = [] actuated_joint_names: List[str] = [] motor_joint_names: List[str] = [] mjcf_sites: List[SiteDesc] = [] if inferred_fixed_base and len(root_joints) > 0: wb = BodyDesc() wb.name = "world_base" wb.is_static = True wb.pos = [0.0, 0.0, 0.0] wb.quat = [0.0, 0.0, 0.0, 1.0] links.append(wb) link_names.append("world_base") def _add_virtual_link(name: str, w_pos: np.ndarray, w_quat: np.ndarray) -> int: vb = BodyDesc() vb.name = name vb.pos = [float(w_pos[0]), float(w_pos[1]), float(w_pos[2])] vb.quat = [float(w_quat[0]), float(w_quat[1]), float(w_quat[2]), float(w_quat[3])] vb.mass = 0.5 vb.has_explicit_inertia = True vb.inertia_3x3 = [1e-2, 0, 0, 0, 1e-2, 0, 0, 0, 1e-2] vb.min_inertia_diag = float(min_inertia_diag) links.append(vb) link_names.append(name) return len(links) - 1 def _build_body( b_el: ET.Element, parent_link_idx: Optional[int], parent_w_pos: np.ndarray, parent_w_quat: np.ndarray, is_root: bool, ) -> None: bname = b_el.attrib.get("name", f"body_{len(links)}") raw_pos = np.array(_floats(b_el.attrib.get("pos"), (0.0, 0.0, 0.0)), dtype=np.float64) raw_quat = _parse_mjcf_quat(b_el, angle_scale) if coord_mode == "global": w_pos = raw_pos if "pos" in b_el.attrib else parent_w_pos.copy() w_quat = raw_quat else: w_pos = parent_w_pos + _quat_rotate(parent_w_quat, raw_pos) w_quat = _quat_mul(parent_w_quat, raw_quat) if is_root and base_pos is not None: w_pos = np.asarray(base_pos, dtype=np.float64) w_quat_inv = _quat_inv(w_quat) # Parse geoms & compute mass/inertia shapes: List[ShapeDesc] = [] tot_m = 0.0 tot_com = np.zeros(3, dtype=np.float64) tot_i = np.zeros((3, 3), dtype=np.float64) body_friction = 0.8 for g_el in b_el.findall("geom"): ga = {**def_geom_attrib, **g_el.attrib} gtype = ga.get("type", "sphere").lower() density = float(ga.get("density", "1000.0")) fric_vals = _floats(ga.get("friction"), (0.8, 0.1, 0.1)) body_friction = float(fric_vals[0]) sd = ShapeDesc() if "fromto" in ga: ft = _floats(ga["fromto"], (0.0, 0.0, 0.0, 0.0, 0.0, 0.1)) p1 = np.array(ft[0:3], dtype=np.float64) p2 = np.array(ft[3:6], dtype=np.float64) if coord_mode == "global": p1 = _quat_rotate(w_quat_inv, p1 - w_pos) p2 = _quat_rotate(w_quat_inv, p2 - w_pos) mid = 0.5 * (p1 + p2) vec = p2 - p1 length = float(np.linalg.norm(vec)) q_local = _quat_from_z_to_dir(vec) r = _floats(ga.get("size"), (0.05,))[0] sd.type = ShapeType.Cylinder if gtype == "cylinder" else ShapeType.Capsule sd.radius = float(r) sd.half_height = float(max(1e-4, 0.5 * length)) sd.local_pos = [float(mid[0]), float(mid[1]), float(mid[2])] sd.local_quat = [float(q_local[0]), float(q_local[1]), float(q_local[2]), float(q_local[3])] else: gp = np.array(_floats(ga.get("pos"), (0.0, 0.0, 0.0)), dtype=np.float64) gq = _parse_mjcf_quat(g_el, angle_scale) if coord_mode == "global": gp = _quat_rotate(w_quat_inv, gp - w_pos) sizes = _floats(ga.get("size"), (0.05,)) if gtype == "sphere": sd.type = ShapeType.Sphere sd.radius = float(sizes[0]) elif gtype == "box": sd.type = ShapeType.Box hx = sizes[0] hy = sizes[1] if len(sizes) > 1 else sizes[0] hz = sizes[2] if len(sizes) > 2 else sizes[0] sd.half_extents = [float(hx), float(hy), float(hz)] elif gtype in ("capsule", "cylinder"): sd.type = ShapeType.Cylinder if gtype == "cylinder" else ShapeType.Capsule sd.radius = float(sizes[0]) sd.half_height = float(sizes[1] if len(sizes) > 1 else 0.1) else: sd.type = ShapeType.Sphere sd.radius = float(sizes[0]) sd.local_pos = [float(gp[0]), float(gp[1]), float(gp[2])] sd.local_quat = [float(gq[0]), float(gq[1]), float(gq[2]), float(gq[3])] shapes.append(sd) gm, gi_local = _geom_mass_inertia(sd, density) rm = _quat_to_mat3(np.asarray(sd.local_quat, dtype=np.float64)) gi_body = rm @ gi_local @ rm.T tot_m, tot_com, tot_i = _parallel_axis_combine( tot_m, tot_com, tot_i, gm, np.asarray(sd.local_pos, dtype=np.float64), gi_body, ) in_el = b_el.find("inertial") if in_el is not None and "mass" in in_el.attrib: override_m = float(in_el.attrib["mass"]) if tot_m > 1e-12: tot_i *= (override_m / tot_m) else: tot_i = 0.01 * override_m * np.eye(3, dtype=np.float64) tot_m = override_m bd = BodyDesc() bd.name = bname bd.pos = [float(w_pos[0]), float(w_pos[1]), float(w_pos[2])] bd.quat = [float(w_quat[0]), float(w_quat[1]), float(w_quat[2]), float(w_quat[3])] bd.mass = float(max(0.05, tot_m)) bd.has_explicit_inertia = True bd.com_offset = [float(tot_com[0]), float(tot_com[1]), float(tot_com[2])] bd.inertia_3x3 = [float(x) for x in tot_i.ravel()] bd.inertia_scale = float(inertia_scale) bd.min_inertia_diag = float(min_inertia_diag) bd.friction = body_friction bd.is_kinematic = b_el.attrib.get("mocap", "false").lower() == "true" bd.collision_shapes = shapes # Collect non-free joints on this body b_joints = [j for j in b_el.findall("joint") if j.attrib.get("type", "hinge").lower() != "free"] if parent_link_idx is None: # Floating root body links.append(bd) link_names.append(bname) cur_link_idx = len(links) - 1 elif not b_joints: # Rigidly attached child body (0 joints in MJCF) links.append(bd) link_names.append(bname) cur_link_idx = len(links) - 1 jd = JointDesc() jd.name = f"{bname}_fixed" jd.type = JointType.Fixed jd.parent_link_idx = parent_link_idx jd.child_link_idx = cur_link_idx jd.anchor_world = [float(w_pos[0]), float(w_pos[1]), float(w_pos[2])] jd.axis_world = [0.0, 0.0, 1.0] joints.append(jd) joint_names.append(jd.name) else: # 1 or more joints attaching parent_link_idx -> ... -> cur_link_idx prev_idx = parent_link_idx for ji, j_el in enumerate(b_joints): ja = {**def_joint_attrib, **j_el.attrib} jname = ja.get("name", f"{bname}_j{ji}") jtype_str = ja.get("type", "hinge").lower() jp = np.array(_floats(ja.get("pos"), (0.0, 0.0, 0.0)), dtype=np.float64) jaxis = np.array(_floats(ja.get("axis"), (0.0, 0.0, 1.0)), dtype=np.float64) if coord_mode == "global": anchor_w = jp if "pos" in ja else w_pos axis_w = jaxis else: anchor_w = w_pos + _quat_rotate(w_quat, jp) axis_w = _quat_rotate(w_quat, jaxis) an = np.linalg.norm(axis_w) axis_w = axis_w / an if an > 1e-12 else np.array([0.0, 0.0, 1.0], dtype=np.float64) is_last = (ji == len(b_joints) - 1) if is_last: links.append(bd) link_names.append(bname) child_idx = len(links) - 1 else: child_idx = _add_virtual_link(f"{bname}_v{ji}", anchor_w, w_quat) jd = JointDesc() jd.name = jname jd.parent_link_idx = prev_idx jd.child_link_idx = child_idx jd.anchor_world = [float(anchor_w[0]), float(anchor_w[1]), float(anchor_w[2])] jd.axis_world = [float(axis_w[0]), float(axis_w[1]), float(axis_w[2])] limited = ja.get("limited", "true").lower() == "true" if jtype_str == "slide": jd.type = JointType.Prismatic if limited and "range" in ja: lo, hi = _floats(ja["range"], (-10.0, 10.0)) jd.lower_limit, jd.upper_limit = float(lo), float(hi) else: jd.lower_limit, jd.upper_limit = -1000.0, 1000.0 elif jtype_str == "ball": jd.type = JointType.Spherical else: if limited and "range" in ja: jd.type = JointType.Revolute lo, hi = _floats(ja["range"], (-180.0, 180.0)) jd.lower_limit = float(lo * angle_scale) jd.upper_limit = float(hi * angle_scale) else: jd.type = JointType.Continuous mc = MotorConfig() if jname in motor_specs: mc.mode = motor_mode mc.kp = float(default_kp) mc.kd = float(default_kd) mc.max_effort = float(motor_specs[jname]["max_effort"]) motor_joint_names.append(jname) else: mc.mode = MotorMode.Off mc.kp = 0.0 mc.kd = 0.0 mc.max_effort = float(default_effort) mc.max_friction = float(ja.get("damping", "0.0")) * 0.1 jd.motor = mc joints.append(jd) joint_names.append(jname) if jd.type != JointType.Spherical: actuated_joint_names.append(jname) prev_idx = child_idx cur_link_idx = prev_idx for s_el in b_el.findall("site"): sa = s_el.attrib sd = SiteDesc() sd.name = sa.get("name", f"{b_el.attrib.get('name', 'link')}_site") sd.body_idx = cur_link_idx sd.local_pos = list(_floats(sa.get("pos"), (0.0, 0.0, 0.0))) sd.local_quat = _parse_mjcf_quat(s_el, angle_scale).tolist() mjcf_sites.append(sd) for child_el in b_el.findall("body"): _build_body(child_el, cur_link_idx, w_pos, w_quat, False) init_parent = 0 if (inferred_fixed_base and len(root_joints) > 0) else None _build_body( root_body_el, init_parent, np.zeros(3, dtype=np.float64), np.array([0.0, 0.0, 0.0, 1.0], dtype=np.float64), True, ) if set_total_mass is not None and set_total_mass > 0.0: cur_mass = sum(l.mass for l in links if not l.is_static) if cur_mass > 1e-6: scale = set_total_mass / cur_mass for l in links: if not l.is_static: l.mass *= scale l.inertia_3x3 = [v * scale for v in l.inertia_3x3] desc = ArticulationDesc() desc.fixed_base = inferred_fixed_base desc.disable_adjacent_collisions = True desc.links = links desc.joints = joints # Disable self-collision across the robot to avoid capsule overlap jitter at joints n_l = len(links) desc.disabled_collision_pairs = [(i, j) for i in range(n_l) for j in range(i + 1, n_l)] return MjcfModel( desc=desc, link_names=link_names, joint_names=joint_names, actuated_joint_names=actuated_joint_names, motor_joint_names=motor_joint_names, has_ground_plane=has_ground_plane, ground_z=ground_z, sites=mjcf_sites, )