2026-11-18 15:05:55 +08:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
"""Audit single- and multi-primitive xiaozhao collision URDFs.
|
|
|
|
|
|
|
|
|
|
Each retained source triangle normally fits inside one convex primitive.
|
|
|
|
|
Faces assigned to disabled configuration pieces are reported separately.
|
2026-11-18 20:09:48 +08:00
|
|
|
Measured rim cylinders are checked against the STL and their actual face
|
|
|
|
|
coverage is reported independently of the fitted envelopes.
|
2026-11-18 15:05:55 +08:00
|
|
|
Explicitly named parallel-axis cylinder slices may instead cover a triangle by
|
|
|
|
|
independently verified, closed subfaces cut from the complete original face.
|
|
|
|
|
This proves surface coverage, not solid-volume or pose/path collision safety.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
|
import copy
|
|
|
|
|
import hashlib
|
|
|
|
|
import json
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
import re
|
|
|
|
|
import sys
|
|
|
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
|
|
|
|
import numpy as np
|
|
|
|
|
import trimesh
|
|
|
|
|
|
|
|
|
|
from collision_pieces import partition_triangles, shared_fitter
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
|
|
|
MODEL = HERE.parent
|
|
|
|
|
SOURCE = MODEL / "urdf/xiaozhao.urdf"
|
|
|
|
|
COVERAGE_TOLERANCE = 1e-9
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def signature(element):
|
|
|
|
|
return (element.tag, sorted(element.attrib.items()), (element.text or "").strip(),
|
|
|
|
|
[signature(child) for child in element])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def origin(element):
|
|
|
|
|
if element is None:
|
|
|
|
|
return np.eye(4)
|
|
|
|
|
transform = trimesh.transformations.euler_matrix(
|
|
|
|
|
*np.fromstring(element.get("rpy", "0 0 0"), sep=" "))
|
|
|
|
|
transform[:3, 3] = np.fromstring(element.get("xyz", "0 0 0"), sep=" ")
|
|
|
|
|
return transform
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def current_asset(mesh):
|
|
|
|
|
path = (MODEL / "meshes" / Path(mesh.get("filename", "")).name).resolve()
|
|
|
|
|
if not path.is_file() or path.parent != (MODEL / "meshes").resolve():
|
|
|
|
|
raise RuntimeError(f"source mesh missing from current xiaozhao assets: {path}")
|
|
|
|
|
return path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def generated_asset(mesh, collision_path):
|
|
|
|
|
filename = mesh.get("filename", "")
|
|
|
|
|
if filename.startswith("package://"):
|
|
|
|
|
raise RuntimeError(f"generated visual retains ambiguous package URI: {filename}")
|
|
|
|
|
path = Path(filename.removeprefix("file://"))
|
|
|
|
|
if not path.is_absolute():
|
|
|
|
|
path = collision_path.parent / path
|
|
|
|
|
path = path.resolve()
|
|
|
|
|
if not path.is_file():
|
|
|
|
|
raise RuntimeError(f"generated visual asset is not readable: {path}")
|
|
|
|
|
return path
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def strip_collisions(root):
|
|
|
|
|
for link in root.findall("link"):
|
|
|
|
|
for collision in list(link.findall("collision")):
|
|
|
|
|
link.remove(collision)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def best_face_margins(triangles, colliders, batch_size=32768):
|
|
|
|
|
"""Independently test whole faces; vertices may not use different pieces."""
|
|
|
|
|
triangles = np.asarray(triangles, dtype=float)
|
|
|
|
|
if (triangles.ndim != 3 or triangles.shape[1:] != (3, 3) or not len(triangles)
|
|
|
|
|
or not np.isfinite(triangles).all() or not colliders):
|
|
|
|
|
raise RuntimeError("expected finite source triangles and nonempty collision pieces")
|
|
|
|
|
best = np.full(len(triangles), -np.inf)
|
|
|
|
|
for collision in colliders:
|
|
|
|
|
geometry = collision.find("geometry")
|
|
|
|
|
if geometry is None or len(geometry) != 1 or geometry[0].tag not in ("box", "cylinder"):
|
|
|
|
|
raise RuntimeError("expected one box or cylinder per collision piece")
|
|
|
|
|
primitive = geometry[0]
|
|
|
|
|
transform = np.linalg.inv(origin(collision.find("origin")))
|
|
|
|
|
if not np.isfinite(transform).all():
|
|
|
|
|
raise RuntimeError("nonfinite collision origin")
|
|
|
|
|
if primitive.tag == "box":
|
|
|
|
|
half_size = np.fromstring(primitive.get("size", ""), sep=" ") / 2
|
|
|
|
|
if len(half_size) != 3 or not np.isfinite(half_size).all() or (half_size <= 0).any():
|
|
|
|
|
raise RuntimeError("invalid box dimensions")
|
|
|
|
|
else:
|
|
|
|
|
radius = float(primitive.get("radius", "nan"))
|
|
|
|
|
length = float(primitive.get("length", "nan"))
|
|
|
|
|
if not np.isfinite([radius, length]).all() or min(radius, length) <= 0:
|
|
|
|
|
raise RuntimeError("invalid cylinder dimensions")
|
|
|
|
|
for start in range(0, len(triangles), batch_size):
|
|
|
|
|
stop = min(start + batch_size, len(triangles))
|
|
|
|
|
local = trimesh.transform_points(triangles[start:stop].reshape(-1, 3), transform)
|
|
|
|
|
local = local.reshape(-1, 3, 3)
|
|
|
|
|
if primitive.tag == "box":
|
|
|
|
|
margin = np.min(half_size - np.abs(local), axis=(1, 2))
|
|
|
|
|
else:
|
|
|
|
|
radial = radius - np.linalg.norm(local[:, :, :2], axis=2)
|
|
|
|
|
axial = length / 2 - np.abs(local[:, :, 2])
|
|
|
|
|
margin = np.minimum(radial.min(axis=1), axial.min(axis=1))
|
|
|
|
|
best[start:stop] = np.maximum(best[start:stop], margin)
|
|
|
|
|
return best
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _axial_cylinder_groups(colliders, required_margin):
|
|
|
|
|
"""Recognize explicit slice groups without trusting generation settings.
|
|
|
|
|
|
|
|
|
|
Slice numbering must be contiguous from 00, and all pieces must be
|
|
|
|
|
cylinders with parallel axes. Their fitted radial centers may differ: the
|
|
|
|
|
proof below tests against each actual transform and radius independently;
|
|
|
|
|
this grouping tolerance cannot relax the geometric coverage check.
|
|
|
|
|
"""
|
|
|
|
|
named = {}
|
|
|
|
|
for collider in colliders:
|
|
|
|
|
match = re.fullmatch(r"(collision_.+)_slice([0-9]{2,})", collider.get("name", ""))
|
|
|
|
|
if match:
|
|
|
|
|
named.setdefault(match[1], []).append((int(match[2]), collider))
|
|
|
|
|
groups = []
|
|
|
|
|
for name, entries in sorted(named.items()):
|
|
|
|
|
entries.sort(key=lambda item: item[0])
|
|
|
|
|
if len(entries) < 2 or [index for index, _ in entries] != list(range(len(entries))):
|
|
|
|
|
continue
|
|
|
|
|
cylinders = [collider for _, collider in entries]
|
|
|
|
|
if any(c.find("geometry/cylinder") is None for c in cylinders):
|
|
|
|
|
continue
|
|
|
|
|
frames = [origin(c.find("origin")) for c in cylinders]
|
|
|
|
|
axis = frames[0][:3, 2]
|
|
|
|
|
if any(np.linalg.norm(np.cross(axis, frame[:3, 2])) > COVERAGE_TOLERANCE
|
|
|
|
|
for frame in frames[1:]):
|
|
|
|
|
continue
|
|
|
|
|
intervals = []
|
|
|
|
|
for collider, frame in zip(cylinders, frames):
|
|
|
|
|
primitive = collider.find("geometry/cylinder")
|
|
|
|
|
half_length = float(primitive.get("length")) / 2 - required_margin
|
|
|
|
|
if half_length < 0 or float(primitive.get("radius")) < required_margin:
|
|
|
|
|
break
|
|
|
|
|
center = float(frame[:3, 3] @ axis)
|
|
|
|
|
intervals.append((center, center - half_length, center + half_length))
|
|
|
|
|
if len(intervals) != len(cylinders):
|
|
|
|
|
continue
|
|
|
|
|
intervals.sort()
|
|
|
|
|
# The actual inset end caps locate the seam even when CLI margin is
|
|
|
|
|
# smaller than fitting padding. A real gap is NOT removed: its middle
|
|
|
|
|
# becomes a cut and must itself pass the subsequent primitive test.
|
|
|
|
|
cuts = sorted(set((left[2] + right[1]) / 2
|
|
|
|
|
for left, right in zip(intervals, intervals[1:])))
|
|
|
|
|
groups.append((name, axis, cuts, cylinders))
|
|
|
|
|
return groups
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _clip_polygon(polygon, axis, cut, keep_lower):
|
|
|
|
|
"""Closed half-space clipping, including seam vertices and degenerates.
|
|
|
|
|
|
|
|
|
|
No epsilon or small-area filter is used here: neither a narrow uncovered
|
|
|
|
|
strip nor a line/point on the seam may disappear from the proof.
|
|
|
|
|
"""
|
|
|
|
|
if not len(polygon):
|
|
|
|
|
return np.empty((0, 3))
|
|
|
|
|
sign = 1 if keep_lower else -1
|
|
|
|
|
distances = sign * (polygon @ axis - cut)
|
|
|
|
|
result = []
|
|
|
|
|
previous, previous_distance = polygon[-1], distances[-1]
|
|
|
|
|
for current, distance in zip(polygon, distances):
|
|
|
|
|
if (previous_distance <= 0) != (distance <= 0):
|
|
|
|
|
fraction = previous_distance / (previous_distance - distance)
|
|
|
|
|
result.append(previous + fraction * (current - previous))
|
|
|
|
|
if distance <= 0:
|
|
|
|
|
result.append(current)
|
|
|
|
|
previous, previous_distance = current, distance
|
|
|
|
|
return np.asarray(result, dtype=float).reshape(-1, 3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _polygon_margin(polygon, colliders):
|
|
|
|
|
# A fan exactly covers a convex clipped polygon. Each complete fan triangle
|
|
|
|
|
# must fit one primitive; its vertices cannot choose different cylinders.
|
|
|
|
|
# Lines and points remain explicit, rather than being discarded as zero area.
|
|
|
|
|
if len(polygon) < 3:
|
|
|
|
|
triangles = np.array([[polygon[0], polygon[-1], polygon[-1]]])
|
|
|
|
|
else:
|
|
|
|
|
triangles = np.array([[polygon[0], polygon[index], polygon[index + 1]]
|
|
|
|
|
for index in range(1, len(polygon) - 1)])
|
|
|
|
|
return float(best_face_margins(triangles, colliders).min())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def face_coverage_margins(triangles, colliders, required_margin):
|
|
|
|
|
"""Return proven face-margin lower bounds and the slice-rescued face count.
|
|
|
|
|
|
|
|
|
|
The ordinary whole-face result is unchanged. Only failed faces may use an
|
|
|
|
|
explicit slice group; each group's cuts partition the WHOLE triangle into
|
|
|
|
|
closed polygons, including the portions outside the group's axial extent.
|
|
|
|
|
A successful proof covers every subface at the requested margin.
|
|
|
|
|
"""
|
|
|
|
|
if not np.isfinite(required_margin) or required_margin < 0:
|
|
|
|
|
raise ValueError("minimum margin must be finite and nonnegative")
|
|
|
|
|
triangles = np.asarray(triangles, dtype=float)
|
|
|
|
|
margins = best_face_margins(triangles, colliders)
|
|
|
|
|
failed = np.flatnonzero(margins < required_margin - COVERAGE_TOLERANCE)
|
|
|
|
|
if not len(failed):
|
|
|
|
|
return margins, 0
|
|
|
|
|
groups = _axial_cylinder_groups(colliders, required_margin)
|
|
|
|
|
rescued = 0
|
|
|
|
|
for index in failed:
|
|
|
|
|
for _, axis, cuts, cylinders in groups:
|
|
|
|
|
remaining = triangles[index]
|
|
|
|
|
lower_bound = float("inf")
|
|
|
|
|
for cut in cuts:
|
|
|
|
|
lower = _clip_polygon(remaining, axis, cut, True)
|
|
|
|
|
remaining = _clip_polygon(remaining, axis, cut, False)
|
|
|
|
|
if len(lower):
|
|
|
|
|
lower_bound = min(lower_bound, _polygon_margin(lower, cylinders))
|
|
|
|
|
if lower_bound < required_margin - COVERAGE_TOLERANCE or not len(remaining):
|
|
|
|
|
break
|
|
|
|
|
if len(remaining):
|
|
|
|
|
lower_bound = min(lower_bound, _polygon_margin(remaining, cylinders))
|
|
|
|
|
if np.isfinite(lower_bound) and lower_bound >= required_margin - COVERAGE_TOLERANCE:
|
|
|
|
|
margins[index] = max(margins[index], lower_bound)
|
|
|
|
|
rescued += 1
|
|
|
|
|
break
|
|
|
|
|
return margins, rescued
|
|
|
|
|
|
|
|
|
|
|
2026-11-18 20:09:48 +08:00
|
|
|
def coverage_selection(triangles, pieces, collider_names, owner=None):
|
2026-11-18 15:05:55 +08:00
|
|
|
"""Remove only complete faces assigned to explicitly disabled pieces."""
|
|
|
|
|
retained = np.ones(len(triangles), dtype=bool)
|
|
|
|
|
disabled = [(i, piece["name"]) for i, piece in enumerate(pieces)
|
|
|
|
|
if not piece.get("enabled", True)]
|
|
|
|
|
counts = {}
|
|
|
|
|
if disabled:
|
2026-11-18 20:09:48 +08:00
|
|
|
if owner is None:
|
|
|
|
|
owner = partition_triangles(triangles, pieces)
|
2026-11-18 15:05:55 +08:00
|
|
|
for index, name in disabled:
|
|
|
|
|
pattern = (rf"collision_{re.escape(name)}(?:_[xyz]_(?:pos|neg))?"
|
|
|
|
|
r"(?:_part[0-9]+)?(?:_slice[0-9]+)?")
|
|
|
|
|
if any(re.fullmatch(pattern, collider) for collider in collider_names):
|
|
|
|
|
raise RuntimeError(f"disabled piece still has collision geometry: {name}")
|
|
|
|
|
selected = owner == index
|
|
|
|
|
counts[name] = int(np.count_nonzero(selected))
|
|
|
|
|
retained[selected] = False
|
|
|
|
|
return retained, counts
|
|
|
|
|
|
|
|
|
|
|
2026-11-18 20:09:48 +08:00
|
|
|
def verify_rim_cylinder(piece, collision, triangles):
|
|
|
|
|
"""Compare the exported cylinder with the outer radius of the STL end face."""
|
|
|
|
|
name = piece["name"]
|
|
|
|
|
rim = piece["rim_cylinder"]
|
|
|
|
|
if (piece.get("primitive") != "cylinder" or not isinstance(rim, dict)
|
|
|
|
|
or not {"start_y", "end_y", "center_xz"} <= rim.keys()):
|
|
|
|
|
raise ValueError(f"invalid rim cylinder configuration on {name}")
|
|
|
|
|
start, end = float(rim["start_y"]), float(rim["end_y"])
|
|
|
|
|
center = np.asarray(rim["center_xz"], dtype=float)
|
|
|
|
|
if (center.shape != (2,) or not np.isfinite(center).all()
|
|
|
|
|
or not np.isfinite([start, end]).all() or start == end):
|
|
|
|
|
raise ValueError(f"invalid rim cylinder axis or center on {name}")
|
|
|
|
|
|
|
|
|
|
vertices = triangles.reshape(-1, 3)
|
|
|
|
|
section = vertices[np.abs(vertices[:, 1] - end) <= 1e-7][:, [0, 2]]
|
|
|
|
|
if (not len(section) or not np.isfinite(section).all()
|
|
|
|
|
or np.linalg.matrix_rank(section - section[0]) < 2):
|
|
|
|
|
raise RuntimeError(f"no measurable STL rim at Y={end} on {name}")
|
|
|
|
|
radius = float(np.linalg.norm(section - center, axis=1).max())
|
|
|
|
|
geometry = collision.find("geometry") if collision is not None else None
|
|
|
|
|
if geometry is None or len(geometry) != 1 or geometry[0].tag != "cylinder":
|
|
|
|
|
raise RuntimeError(f"expected the named rim cylinder collision_{name}")
|
|
|
|
|
spec = geometry[0]
|
|
|
|
|
frame = origin(collision.find("origin"))
|
|
|
|
|
actual = [float(spec.get("radius", "nan")), float(spec.get("length", "nan")),
|
|
|
|
|
*frame[:3, 3], *frame[:3, 2]]
|
|
|
|
|
expected = [radius, abs(end - start), center[0], (start + end) / 2, center[1],
|
|
|
|
|
0, np.sign(end - start), 0]
|
|
|
|
|
if not np.allclose(actual, expected, rtol=0, atol=1e-8):
|
|
|
|
|
raise RuntimeError(f"rim cylinder {name} differs from the STL radius or configured axis")
|
|
|
|
|
return {"radius_m": radius, "length_m": abs(end - start)}
|
|
|
|
|
|
|
|
|
|
|
2026-11-18 15:05:55 +08:00
|
|
|
def verify(collision_path, required_margin, config=None):
|
2026-11-18 20:09:48 +08:00
|
|
|
if not np.isfinite(required_margin) or required_margin < 0:
|
|
|
|
|
raise ValueError("minimum margin must be finite and nonnegative")
|
2026-11-18 15:05:55 +08:00
|
|
|
source_bytes = SOURCE.read_bytes()
|
|
|
|
|
collision_bytes = collision_path.read_bytes()
|
|
|
|
|
source = ET.fromstring(source_bytes)
|
|
|
|
|
generated = ET.fromstring(collision_bytes)
|
|
|
|
|
source_joints = source.findall("joint")
|
|
|
|
|
if [signature(j) for j in source_joints] != [signature(j) for j in generated.findall("joint")]:
|
|
|
|
|
raise RuntimeError("joint definitions differ from source (including origins/limits/axes)")
|
|
|
|
|
|
|
|
|
|
# Check every other source field as well, except replaced collisions and
|
|
|
|
|
# mesh URI spelling. Resolve both documents to the same verified assets.
|
|
|
|
|
source_structure, generated_structure = copy.deepcopy(source), copy.deepcopy(generated)
|
|
|
|
|
strip_collisions(source_structure)
|
|
|
|
|
strip_collisions(generated_structure)
|
|
|
|
|
for mesh in source_structure.iter("mesh"):
|
|
|
|
|
mesh.set("filename", str(current_asset(mesh)))
|
|
|
|
|
for mesh in generated_structure.iter("mesh"):
|
|
|
|
|
actual = generated_asset(mesh, collision_path)
|
|
|
|
|
if actual != current_asset(mesh):
|
|
|
|
|
raise RuntimeError(f"visual uses an asset outside the current model: {actual}")
|
|
|
|
|
mesh.set("filename", str(actual))
|
|
|
|
|
if signature(source_structure) != signature(generated_structure):
|
|
|
|
|
raise RuntimeError("non-collision model fields differ from source")
|
|
|
|
|
|
|
|
|
|
result = []
|
|
|
|
|
for source_link in source.findall("link"):
|
|
|
|
|
name = source_link.get("name")
|
|
|
|
|
link = generated.find(f"link[@name='{name}']")
|
|
|
|
|
colliders = link.findall("collision")
|
|
|
|
|
if not source_link.findall("collision"):
|
|
|
|
|
if colliders:
|
|
|
|
|
raise RuntimeError(f"visual-only link gained a collider: {name}")
|
|
|
|
|
continue
|
|
|
|
|
if not colliders:
|
|
|
|
|
raise RuntimeError(f"source collision link has no generated pieces: {name}")
|
|
|
|
|
piece_names = [collision.get("name", "") for collision in colliders]
|
|
|
|
|
if any(not value for value in piece_names) or len(set(piece_names)) != len(piece_names):
|
|
|
|
|
raise RuntimeError(f"collision pieces must have unique nonempty names on {name}")
|
|
|
|
|
vertex_count = 0
|
|
|
|
|
triangles_by_mesh = []
|
|
|
|
|
indices_by_mesh = []
|
|
|
|
|
for visual in source_link.findall("visual"):
|
|
|
|
|
mesh_element = visual.find("geometry/mesh")
|
|
|
|
|
if mesh_element is None:
|
|
|
|
|
continue
|
|
|
|
|
mesh = trimesh.load(current_asset(mesh_element), force="mesh", process=False)
|
|
|
|
|
scale = np.fromstring(mesh_element.get("scale", "1 1 1"), sep=" ")
|
|
|
|
|
vertices = trimesh.transform_points(np.asarray(mesh.vertices) * scale,
|
|
|
|
|
origin(visual.find("origin")))
|
|
|
|
|
faces = np.asarray(mesh.faces)
|
|
|
|
|
triangles_by_mesh.append(vertices[faces])
|
|
|
|
|
indices_by_mesh.append(faces + vertex_count)
|
|
|
|
|
vertex_count += len(vertices)
|
|
|
|
|
if not vertex_count:
|
|
|
|
|
raise RuntimeError(f"no source mesh vertices checked on {name}")
|
|
|
|
|
triangles = (triangles_by_mesh[0] if len(triangles_by_mesh) == 1
|
|
|
|
|
else np.concatenate(triangles_by_mesh))
|
|
|
|
|
pieces = shared_fitter().link_settings(config or {}, name).get("pieces", [])
|
2026-11-18 20:09:48 +08:00
|
|
|
rim_pieces = [(i, p) for i, p in enumerate(pieces)
|
|
|
|
|
if "rim_cylinder" in p and p.get("enabled", True)]
|
|
|
|
|
owner = partition_triangles(triangles, pieces) if rim_pieces else None
|
|
|
|
|
retained, excluded = coverage_selection(triangles, pieces, piece_names, owner)
|
2026-11-18 15:05:55 +08:00
|
|
|
if excluded:
|
|
|
|
|
if not np.any(retained):
|
|
|
|
|
raise RuntimeError(f"no retained source triangles on {name}")
|
|
|
|
|
vertex_count = len(np.unique(np.concatenate(indices_by_mesh)[retained]))
|
2026-11-18 20:09:48 +08:00
|
|
|
strict = retained.copy()
|
|
|
|
|
margins = np.full(len(triangles), np.nan)
|
|
|
|
|
rim_reports = {}
|
|
|
|
|
fitted_colliders = colliders.copy()
|
|
|
|
|
for index, piece in rim_pieces:
|
|
|
|
|
collider = link.find(f"collision[@name='collision_{piece['name']}']")
|
|
|
|
|
report = verify_rim_cylinder(piece, collider, triangles)
|
|
|
|
|
selected = owner == index
|
|
|
|
|
actual = best_face_margins(triangles[selected], [collider])
|
|
|
|
|
below = int(np.count_nonzero(actual < required_margin - COVERAGE_TOLERANCE))
|
|
|
|
|
report.update(triangles_covered=len(actual) - below, triangles_below_margin=below,
|
|
|
|
|
triangles_outside=int(np.count_nonzero(actual < -COVERAGE_TOLERANCE)),
|
|
|
|
|
minimum_margin_m=float(actual.min()))
|
|
|
|
|
rim_reports[piece["name"]] = report
|
|
|
|
|
margins[selected] = actual
|
|
|
|
|
strict[selected] = False
|
|
|
|
|
fitted_colliders.remove(collider)
|
|
|
|
|
rescued = 0
|
|
|
|
|
if strict.any():
|
|
|
|
|
fitted, rescued = face_coverage_margins(triangles[strict], fitted_colliders, required_margin)
|
|
|
|
|
minimum = float(fitted.min())
|
|
|
|
|
if not np.isfinite(minimum) or minimum < required_margin - COVERAGE_TOLERANCE:
|
|
|
|
|
missed = int(np.count_nonzero(fitted < required_margin - COVERAGE_TOLERANCE))
|
|
|
|
|
raise RuntimeError(f"whole-triangle coverage failed on {name}: {missed} faces "
|
|
|
|
|
f"(including optional axial-slice union proof), "
|
|
|
|
|
f"margin {minimum:.9g} m, required {required_margin:.9g} m")
|
|
|
|
|
margins[strict] = fitted
|
|
|
|
|
covered = margins[margins >= required_margin - COVERAGE_TOLERANCE]
|
|
|
|
|
below_rim = sum(report["triangles_below_margin"] for report in rim_reports.values())
|
|
|
|
|
if len(covered) + below_rim + sum(excluded.values()) != len(triangles):
|
|
|
|
|
raise RuntimeError(f"source triangle counts disagree on {name}")
|
2026-11-18 15:05:55 +08:00
|
|
|
result.append({"link": name, "primitive_count": len(colliders), "pieces": piece_names,
|
|
|
|
|
"vertices_checked": vertex_count,
|
2026-11-18 20:09:48 +08:00
|
|
|
"triangles_covered": len(covered),
|
|
|
|
|
"triangles_below_margin_on_rim_cylinders": below_rim,
|
|
|
|
|
"rim_cylinders": rim_reports,
|
2026-11-18 15:05:55 +08:00
|
|
|
"triangles_excluded": sum(excluded.values()),
|
|
|
|
|
"excluded_pieces": excluded,
|
|
|
|
|
"triangles_covered_by_slice_union": rescued,
|
2026-11-18 20:09:48 +08:00
|
|
|
"minimum_margin_m": float(covered.min()) if len(covered) else None})
|
2026-11-18 15:05:55 +08:00
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
"status": "passed",
|
|
|
|
|
"source": str(SOURCE),
|
|
|
|
|
"collision": str(collision_path),
|
|
|
|
|
"source_sha256": hashlib.sha256(source_bytes).hexdigest(),
|
|
|
|
|
"collision_sha256": hashlib.sha256(collision_bytes).hexdigest(),
|
|
|
|
|
"joints_preserved": len(source_joints),
|
|
|
|
|
"movable_joints_preserved": sum(j.get("type") != "fixed" for j in source_joints),
|
|
|
|
|
"all_non_collision_fields_preserved": True,
|
|
|
|
|
"visual_asset_resolution": "absolute or URDF-relative paths; verified current model assets",
|
|
|
|
|
"primitive_count": sum(item["primitive_count"] for item in result),
|
|
|
|
|
"vertices_checked": sum(item["vertices_checked"] for item in result),
|
|
|
|
|
"triangles_covered": sum(item["triangles_covered"] for item in result),
|
2026-11-18 20:09:48 +08:00
|
|
|
"triangles_below_margin_on_rim_cylinders":
|
|
|
|
|
sum(item["triangles_below_margin_on_rim_cylinders"] for item in result),
|
2026-11-18 15:05:55 +08:00
|
|
|
"triangles_excluded": sum(item["triangles_excluded"] for item in result),
|
|
|
|
|
"triangles_covered_by_slice_union": sum(item["triangles_covered_by_slice_union"] for item in result),
|
|
|
|
|
"required_margin_m": required_margin,
|
2026-11-18 20:09:48 +08:00
|
|
|
"minimum_margin_m": min((item["minimum_margin_m"] for item in result
|
|
|
|
|
if item["minimum_margin_m"] is not None), default=None),
|
|
|
|
|
"coverage_scope": ("each triangle counted as covered fits inside one convex primitive, "
|
2026-11-18 15:05:55 +08:00
|
|
|
"or is fully partitioned into closed subfaces covered by an explicitly named "
|
|
|
|
|
"parallel-axis cylinder-slice group, with the required margin. "
|
2026-11-18 20:09:48 +08:00
|
|
|
"Faces below the margin on measured rim cylinders and faces assigned to "
|
|
|
|
|
"disabled pieces are counted separately."),
|
2026-11-18 15:05:55 +08:00
|
|
|
"solid_volume_coverage_validated": False,
|
|
|
|
|
"pose_or_path_safety_validated": False,
|
|
|
|
|
"links": result,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
|
|
|
parser.add_argument("--collision", type=Path, default=HERE / "xiaozhao_collision.urdf")
|
|
|
|
|
parser.add_argument("--config", type=Path, default=HERE / "xiaozhao_collision.toml",
|
|
|
|
|
help="piece configuration used to generate this collision URDF")
|
|
|
|
|
parser.add_argument("--minimum-margin", type=float, default=0.001)
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
|
if not np.isfinite(args.minimum_margin) or args.minimum_margin < 0:
|
|
|
|
|
parser.error("minimum margin must be finite and nonnegative")
|
|
|
|
|
try:
|
|
|
|
|
config = shared_fitter().load_config(args.config.resolve())
|
|
|
|
|
report = verify(args.collision.resolve(), args.minimum_margin, config)
|
|
|
|
|
except (RuntimeError, ValueError, OSError, ET.ParseError) as error:
|
|
|
|
|
print(f"FAIL: {error}", file=sys.stderr)
|
|
|
|
|
return 1
|
|
|
|
|
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
raise SystemExit(main())
|