Skip to content

Official Codebase of 3DCodeVerse

Python

urdf: the lint parses joints through the loader's parse_joint, so lint-clean text never raises in load_urdf

gaoypeng4f6cb11d01cf
diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.py
index 179ee318..f6842d9b 100644
--- a/harness/codeverse3d/languages/urdf/__init__.py
+++ b/harness/codeverse3d/languages/urdf/__init__.py
@@ -44,6 +44,9 @@ from codeverse3d.spatial.joints_model import (
invert_transform,
load_urdf,
matrix_to_rpy,
+ parse_floats,
+ parse_joint,
+ parse_origin,
)
from codeverse3d.spatial.joints_sweep import sweep_collisions, sweep_findings
from codeverse3d.workspace import ArtifactStage, Workspace
@@ -240,16 +243,11 @@ def _lint_mimics(joints: list[ET.Element], out: list[GateFinding]) -> None:
mim = el.find("mimic")
src = (mim.get("joint") or "").strip() if mim is not None else ""
mult, off = 1.0, 0.0
- if mim is not None and not src:
- out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> without joint=", target=jname,
- fix='<mimic joint="runner_slide" multiplier="1" offset="0"/>'))
- src = ""
- elif mim is not None:
+ if src: # a <mimic> with no joint= or non-numeric factors is parse_joint's ERROR (_lint_joint)
try:
mult = float(mim.get("multiplier", 1) or 1)
off = float(mim.get("offset", 0) or 0)
except ValueError:
- out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> multiplier/offset must be numbers", target=jname))
src = ""
specs.append(MimicSpec(key=jname, name=jname, movable=movable, target=src or None,
multiplier=mult, offset=off, lower=lo, upper=hi))
@@ -312,11 +310,18 @@ def _lint_link(el: ET.Element, name: str, out: list[GateFinding]) -> None:
if fn != expected:
out.append(_f(Severity.ERROR, f"link '{name}': mesh filename '{fn}' must be '{expected}'", target=name,
fix=f'<mesh filename="{expected}"/>'))
- sc = _floats(mesh.get("scale")) if mesh.get("scale") else None
+ try:
+ sc = parse_floats(mesh.get("scale"), 3, f"link {name} mesh scale") if mesh.get("scale") else None
+ except UrdfError as e:
+ out.append(_f(Severity.ERROR, str(e), target=name, fix="Drop the scale attribute and size the geometry in model.py."))
+ sc = None
if sc is not None and any(abs(s - 1) > 1e-9 for s in sc):
- out.append(_f(Severity.WARN, f"link '{name}': mesh scale {sc} — model in meters in model.py instead", target=name,
+ out.append(_f(Severity.WARN, f"link '{name}': mesh scale {list(sc)} — model in meters in model.py instead", target=name,
fix="Drop the scale attribute and size the geometry in model.py."))
- _lint_origin(vis.find("origin"), f"link '{name}' visual", name, out)
+ try:
+ parse_origin(vis, f"link {name} visual")
+ except UrdfError as e:
+ out.append(_f(Severity.ERROR, str(e), target=name, fix='<origin xyz="0 0 0" rpy="0 0 0"/>'))
col = el.find("collision")
if col is None:
out.append(_f(Severity.WARN, f"link '{name}' has no <collision> twin of its visual", target=name,
@@ -337,18 +342,6 @@ def _origin_sig(o: ET.Element | None) -> tuple[tuple[float, ...], tuple[float, .
return (tuple(_floats(o.get("xyz")) or (0.0, 0.0, 0.0)), tuple(_floats(o.get("rpy")) or (0.0, 0.0, 0.0)))
-def _lint_origin(o: ET.Element | None, what: str, target: str, out: list[GateFinding]) -> None:
- if o is None:
- return
- for attr in ("xyz", "rpy"):
- if o.get(attr) is None:
- continue
- vals = _floats(o.get(attr))
- if vals is None or len(vals) != 3 or any(not math.isfinite(v) for v in vals):
- out.append(_f(Severity.ERROR, f"{what}: origin {attr}='{o.get(attr)}' must be 3 finite numbers", target=target,
- fix=f'<origin {attr}="0 0 0"/>'))
-
-
def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: dict[str, str],
out: list[GateFinding]) -> None:
jtype = el.get("type", "")
@@ -372,43 +365,35 @@ def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: di
out.append(_f(Severity.ERROR, f"link '{child}' is the child of two joints ('{jname}' and another)", target=jname,
fix="Each link has exactly one parent joint (tree)."))
parent_of[child] = parent
- _lint_origin(el.find("origin"), f"joint '{jname}'", jname, out)
- o = el.find("origin")
- if o is not None and o.get("rpy") and any(abs(v) > 1e-9 for v in (_floats(o.get("rpy")) or [])):
+ if jtype not in JOINT_TYPES or not parent or not child:
+ return
+ # the numbers (origin, axis, limit, mimic) and the per-joint rules are the loader's own:
+ # the build parses this element through the same function, so lint-clean never raises there
+ try:
+ j = parse_joint(el)
+ except UrdfError as e:
+ out.append(_f(Severity.ERROR, str(e), target=jname))
+ return
+ rpy = matrix_to_rpy(j.origin[:3, :3])
+ if any(abs(v) > 1e-9 for v in rpy):
out.append(_f(Severity.INFO, f"joint '{jname}' uses a rotated origin (rpy); allowed, but point the <axis> instead where possible", target=jname))
ax = el.find("axis")
if jtype in MOVABLE_TYPES:
if ax is None or ax.get("xyz") is None:
out.append(_f(Severity.WARN, f"joint '{jname}': no <axis>; URDF defaults to '1 0 0'", target=jname, fix='<axis xyz="0 0 1"/>'))
else:
- vals = _floats(ax.get("xyz"))
- if vals is None or len(vals) != 3:
- out.append(_f(Severity.ERROR, f"joint '{jname}': axis '{ax.get('xyz')}' must be 3 numbers", target=jname, fix='<axis xyz="0 0 1"/>'))
- else:
- n = math.sqrt(sum(v * v for v in vals))
- if n < 1e-9:
- out.append(_f(Severity.ERROR, f"joint '{jname}': zero axis", target=jname, fix='<axis xyz="0 0 1"/>'))
- elif abs(n - 1) > 1e-3:
- unit = " ".join(f"{v / n:.6g}" for v in vals)
- out.append(_f(Severity.WARN, f"joint '{jname}': axis not unit length (|a|={n:.4g}); auto-normalised", target=jname,
- fix=f'<axis xyz="{unit}"/>'))
+ n = math.sqrt(sum(v * v for v in parse_floats(ax.get("xyz"), 3, "axis")))
+ if abs(n - 1) > 1e-3:
+ unit = " ".join(f"{v:.6g}" for v in j.axis)
+ out.append(_f(Severity.WARN, f"joint '{jname}': axis not unit length (|a|={n:.4g}); auto-normalised", target=jname,
+ fix=f'<axis xyz="{unit}"/>'))
lim = el.find("limit")
- if jtype in ("revolute", "prismatic"):
- lo = _floats(lim.get("lower")) if lim is not None and lim.get("lower") is not None else None
- hi = _floats(lim.get("upper")) if lim is not None and lim.get("upper") is not None else None
- if lim is None or not lo or not hi:
- unit = "rad" if jtype == "revolute" else "m"
- out.append(_f(Severity.ERROR, f"joint '{jname}': {jtype} joints need <limit lower upper effort velocity> ({unit})", target=jname,
- fix='<limit lower="0" upper="1.57" effort="10" velocity="1"/>'))
- else:
- if hi[0] < lo[0]:
- out.append(_f(Severity.ERROR, f"joint '{jname}': upper {hi[0]} < lower {lo[0]}", target=jname,
- fix="Swap lower/upper; if the motion should go the other way, negate the <axis> instead."))
- if abs(hi[0] - lo[0]) < 1e-9:
- out.append(_f(Severity.WARN, f"joint '{jname}': lower == upper (joint cannot move)", target=jname,
- fix="Give the joint a range, or make it type=fixed."))
- if jtype == "revolute" and hi[0] - lo[0] > 2 * math.pi + 1e-6:
- out.append(_f(Severity.WARN, f"joint '{jname}': revolute range > 2π — use type=continuous", target=jname))
+ if jtype in ("revolute", "prismatic") and j.lower is not None and j.upper is not None:
+ if abs(j.upper - j.lower) < 1e-9:
+ out.append(_f(Severity.WARN, f"joint '{jname}': lower == upper (joint cannot move)", target=jname,
+ fix="Give the joint a range, or make it type=fixed."))
+ if jtype == "revolute" and j.upper - j.lower > 2 * math.pi + 1e-6:
+ out.append(_f(Severity.WARN, f"joint '{jname}': revolute range > 2π — use type=continuous", target=jname))
if lim is not None and (lim.get("effort") is None or lim.get("velocity") is None):
out.append(_f(Severity.WARN, f"joint '{jname}': <limit> should carry effort and velocity", target=jname,
fix='effort="10" velocity="1"'))
diff --git a/harness/codeverse3d/spatial/joints_model.py b/harness/codeverse3d/spatial/joints_model.py
index 0cf1b0aa..28e48551 100644
--- a/harness/codeverse3d/spatial/joints_model.py
+++ b/harness/codeverse3d/spatial/joints_model.py
@@ -40,14 +40,25 @@ class UrdfError(ValueError):
# ------------------------------------------------------------------ small math
def parse_floats(text: str | None, n: int, what: str) -> tuple[float, ...]:
- """Parse ``"a b c"`` → floats; raises ``UrdfError`` with ``what`` on bad input."""
+ """Parse ``"a b c"`` → ``n`` finite floats; raises ``UrdfError`` with ``what`` on bad input.
+ The ONE number reader of a URDF: the loader and the lint both parse through it, so
+ lint-clean text cannot raise here at build time (``lower="0 1"`` did, 2026-09-24)."""
parts = (text or "").split()
if len(parts) != n:
- raise UrdfError(f"{what}: expected {n} numbers, got {text!r}")
+ raise UrdfError(f"{what}: expected {n} number{'s' if n > 1 else ''}, got {text!r}")
try:
- return tuple(float(p) for p in parts)
+ vals = tuple(float(p) for p in parts)
except ValueError as e:
raise UrdfError(f"{what}: not numeric: {text!r}") from e
+ if not all(math.isfinite(v) for v in vals):
+ raise UrdfError(f"{what}: not finite: {text!r}")
+ return vals
+
+
+def _scalar(el: ET.Element, attr: str, what: str, default: float | None = None) -> float | None:
+ """One optional numeric attribute (``default`` when absent or empty)."""
+ text = el.get(attr)
+ return default if text is None or not text.strip() else parse_floats(text, 1, f"{what} {attr}")[0]
def rpy_to_matrix(rpy: tuple[float, float, float] | np.ndarray) -> np.ndarray:
@@ -220,9 +231,9 @@ def _primitive_mesh(geom: ET.Element, what: str) -> trimesh.Trimesh:
if (b := geom.find("box")) is not None:
return trimesh.creation.box(parse_floats(b.get("size"), 3, f"{what} box size"))
if (c := geom.find("cylinder")) is not None:
- return trimesh.creation.cylinder(radius=float(c.get("radius", 0)), height=float(c.get("length", 0)))
+ return trimesh.creation.cylinder(radius=_scalar(c, "radius", what, 0.0), height=_scalar(c, "length", what, 0.0))
if (s := geom.find("sphere")) is not None:
- return trimesh.creation.icosphere(subdivisions=3, radius=float(s.get("radius", 0)))
+ return trimesh.creation.icosphere(subdivisions=3, radius=_scalar(s, "radius", what, 0.0))
raise UrdfError(f"{what}: unsupported geometry {[e.tag for e in geom]}")
@@ -285,7 +296,9 @@ def _link_from_xml(el: ET.Element, urdf_dir: Path, meshes_dir: Path | None, *, l
return link
-def _joint_from_xml(el: ET.Element) -> Joint:
+def parse_joint(el: ET.Element) -> Joint:
+ """One ``<joint>`` element → :class:`Joint` (strict: raises ``UrdfError``). The URDF
+ lint calls it too, so every rule it enforces is a lint ERROR before any Blender run."""
name = el.get("name", "")
jtype = el.get("type", "")
if jtype not in JOINT_TYPES:
@@ -305,27 +318,26 @@ def _joint_from_xml(el: ET.Element) -> Joint:
j.axis = a / n
lim = el.find("limit")
if lim is not None:
- j.effort = float(lim.get("effort", 0) or 0)
- j.velocity = float(lim.get("velocity", 0) or 0)
- if lim.get("lower") is not None:
- j.lower = float(lim.get("lower"))
- if lim.get("upper") is not None:
- j.upper = float(lim.get("upper"))
+ what = f"joint {name} <limit>"
+ j.effort = _scalar(lim, "effort", what, 0.0)
+ j.velocity = _scalar(lim, "velocity", what, 0.0)
+ j.lower = _scalar(lim, "lower", what)
+ j.upper = _scalar(lim, "upper", what)
if jtype in ("revolute", "prismatic"):
if j.lower is None or j.upper is None:
- raise UrdfError(f"joint {name}: {jtype} joints need <limit lower upper>")
+ unit = "rad" if jtype == "revolute" else "m"
+ raise UrdfError(f"joint {name}: {jtype} joints need <limit lower upper effort velocity> ({unit}), "
+ 'e.g. <limit lower="0" upper="1.57" effort="10" velocity="1"/>')
if j.upper < j.lower:
- raise UrdfError(f"joint {name}: upper {j.upper} < lower {j.lower}")
+ raise UrdfError(f"joint {name}: upper {j.upper} < lower {j.lower}; swap them "
+ "(to move the other way, negate the <axis> instead)")
mim = el.find("mimic")
if mim is not None:
src = mim.get("joint")
if not src:
raise UrdfError(f"joint {name}: <mimic> needs joint=\"<other joint>\"")
- try:
- mult = float(mim.get("multiplier", 1.0) or 1.0)
- off = float(mim.get("offset", 0.0) or 0.0)
- except ValueError as e:
- raise UrdfError(f"joint {name}: <mimic> multiplier/offset must be numbers") from e
+ mult = _scalar(mim, "multiplier", f"joint {name} <mimic>", 1.0)
+ off = _scalar(mim, "offset", f"joint {name} <mimic>", 0.0)
# the multiplier floor is NOT checked here: mimic_issues owns every coupling rule,
# and a copy at parse time makes the shared one unreachable (review, 2026-09-03)
j.mimic = Mimic(joint=src, multiplier=mult, offset=off)
@@ -372,7 +384,7 @@ def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, lo
links[link.name] = link
joints = {}
for el in root_el.findall("joint"):
- j = _joint_from_xml(el)
+ j = parse_joint(el)
if j.name in joints:
raise UrdfError(f"duplicate joint name {j.name!r}")
if j.parent not in links or j.child not in links:
diff --git a/harness/tests/urdf_joints/test_lint.py b/harness/tests/urdf_joints/test_lint.py
index a334c06a..c501f694 100644
--- a/harness/tests/urdf_joints/test_lint.py
+++ b/harness/tests/urdf_joints/test_lint.py
@@ -2,8 +2,11 @@
from __future__ import annotations
+import pytest
+
from codeverse3d.contracts.artifacts import Severity
from codeverse3d.languages.urdf import lint_model_text, lint_urdf_text, lint_workspace
+from codeverse3d.spatial.joints_model import UrdfError, load_urdf
from codeverse3d.workspace import Workspace
GOOD = """<?xml version="1.0"?>
@@ -75,7 +78,7 @@ def test_joint_rules():
f, _ = lint_urdf_text(GOOD.replace('type="revolute"', 'type="hinge"'))
assert any("must be one of" in m for m in _msgs(f, Severity.ERROR))
f, _ = lint_urdf_text(GOOD.replace('<origin xyz="-0.29 -0.2 0" rpy="0 0 0"/>', '<origin xyz="-0.29 -0.2" rpy="0 0 0"/>'))
- assert any("3 finite numbers" in m for m in _msgs(f, Severity.ERROR))
+ assert any("origin xyz: expected 3 numbers" in m for m in _msgs(f, Severity.ERROR))
f, _ = lint_urdf_text(GOOD.replace('<axis xyz="0 0 -1"/>', ""))
assert any("no <axis>" in m for m in _msgs(f, Severity.WARN))
@@ -133,3 +136,24 @@ def test_reserved_link_name_world():
# glTF readers use 'world' as the scene-graph base frame: a link of that name cannot become a GLB node
f, _ = lint_urdf_text(GOOD.replace('name="body"', 'name="world"').replace('link="body"', 'link="world"').replace("meshes/body.glb", "meshes/world.glb"))
assert any("reserved" in m for m in _msgs(f, Severity.ERROR))
+
+
[email protected]("old,new", [
+ ('lower="0" upper="1.57"', 'lower="0 1" upper="1.57"'), # raised a bare ValueError in the build
+ ('effort="10"', 'effort="ten"'), # ditto
+ ('lower="0" upper="1.57"', 'lower="0" upper="inf"'),
+ ('<axis xyz="0 0 -1"/>', '<axis xyz="0 0"/>'),
+ ('type="revolute"', 'type="fixed"'), # the loader checks a FIXED joint's axis too
+ ('<limit lower="0" upper="1.57" effort="10" velocity="1"/>', '<mimic/>'),
+])
+def test_lint_clean_means_the_loader_parses(tmp_path, old, new):
+ """Regression (audit 2026-09-24 N18): the lint and the build parse joints through one
+ ``parse_joint``, so a URDF the lint passes never fails (or raises) in ``load_urdf``."""
+ text = GOOD.replace(old, new)
+ if new == 'type="fixed"':
+ text = text.replace('<axis xyz="0 0 -1"/>', '<axis xyz="0 0 0"/>')
+ (tmp_path / "robot.urdf").write_text(text)
+ with pytest.raises(UrdfError) as e:
+ load_urdf(tmp_path / "robot.urdf", load_meshes=False)
+ f, _ = lint_urdf_text(text)
+ assert str(e.value) in _msgs(f, Severity.ERROR)