playful / chess-sim /code /sim /prepare_arm_collision.py
Ali-Uraish's picture
Add files using upload-large-folder tool
33c14d6 verified
Raw History Blame Contribute Delete
5.88 kB
"""Build convex-decomposition collision shapes for the bulky SO-101 arm parts.
MuJoCo collides a mesh geom through its single convex hull. For several arm parts
that hull is 1.7 to 4.3 times the part's own volume (the wrist camera mount 4.3x,
the wrist motor holder 3.8x), so in folded poses the hand "hits" the shoulder or
upper arm in empty space. The expert then rejects rank 7 and 8 moves the real arm
can make.
This script splits each such part into convex pieces with CoACD, then grows any
piece that misses a mesh vertex so the pieces together never undercut the real
part (a policy trained on shapes smaller than the arm would learn contacts that
break real hardware). Hulls stay in the part's mesh frame, in metres, so
`make_scene.py` gives them the geom pos/quat of the upstream collision geom they
replace. Visual meshes, joints, actuators and inertials are untouched.
The finger slab hulls from `prepare_gripper_assets.py` share the same manifest;
each script replaces only its own entries.
Run only when rebuilding assets: uv pip install --python .venv/bin/python -e '.[assets]'
Then: .venv/bin/python sim/prepare_arm_collision.py
"""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
import coacd
import numpy as np
import trimesh
ROOT = Path(__file__).resolve().parent / "assets" / "so101"
OUT = ROOT / "collision"
# part: scale of the source STL as declared in the upstream model (the wrist camera
# mount is drawn in millimetres). Parts whose hull is close to their volume (the
# STS3215 servos, 1.1x) keep the upstream single hull.
PARTS = {
"motor_holder_so101_base_v1": 1.0, # shoulder
"rotation_pitch_so101_v1": 1.0, # shoulder
"upper_arm_so101_v1": 1.0, # upper arm
"under_arm_so101_v1": 1.0, # lower arm
"motor_holder_so101_wrist_v1": 1.0, # lower arm
"wrist_roll_pitch_so101_v2": 1.0, # wrist
"wrist_camera_mount_so101_v1": 0.001, # hand
"wrist_camera_so101_v1": 1.0, # hand
}
THRESHOLD = 0.05 # CoACD concavity limit, relative to the part's size
MAX_HULLS = 12 # per part; every extra hull costs collision time in each simulated step
PREPROCESS_RESOLUTION = 120 # voxel remesh of non-manifold sources (only when needed)
COVER_TOL_MM = 0.05 # a mesh vertex further than this outside every piece grows its nearest piece
SAMPLES = 50_000 # surface samples for the coverage report
def outside_distance(hull: trimesh.Trimesh, points: np.ndarray) -> np.ndarray:
"""How far each point lies outside a convex hull (<= 0 inside); a lower bound near edges."""
keep = hull.area_faces > 1e-14 # degenerate faces have no normal
n = hull.face_normals[keep]
c = np.einsum("ij,ij->i", n, hull.triangles[keep, 0])
return (points @ n.T - c).max(axis=1)
def decompose(name: str, scale: float) -> dict:
source = ROOT / f"{name}.stl"
mesh = trimesh.load_mesh(source)
mesh.apply_scale(scale)
parts = coacd.run_coacd(coacd.Mesh(mesh.vertices, mesh.faces), threshold=THRESHOLD,
max_convex_hull=MAX_HULLS, preprocess_resolution=PREPROCESS_RESOLUTION, seed=0)
hulls = [trimesh.Trimesh(v, f).convex_hull for v, f in parts]
# Grow pieces until every source vertex is inside one of them.
grown = 0
for _ in range(3):
d = np.stack([outside_distance(h, mesh.vertices) for h in hulls])
missing = d.min(axis=0) > COVER_TOL_MM / 1000
if not missing.any():
break
owner = d.argmin(axis=0)
for k in np.unique(owner[missing]):
extra = mesh.vertices[missing & (owner == k)]
hulls[k] = trimesh.Trimesh(np.vstack([hulls[k].vertices, extra])).convex_hull
grown += len(extra)
samples, _ = trimesh.sample.sample_surface(mesh, SAMPLES, seed=0)
gap = np.stack([outside_distance(h, samples) for h in hulls]).min(axis=0)
files = []
for h in hulls:
if not h.is_watertight or h.volume <= 0:
raise ValueError(f"invalid hull for {name}")
path = OUT / f"{name}_{len(files):02d}.stl"
h.export(path)
files.append(path.name)
for stale in OUT.glob(f"{name}_*.stl"):
if stale.name not in files:
stale.unlink()
single = mesh.convex_hull.volume
return dict(method="coacd", source_file=source.name,
source_sha256=hashlib.sha256(source.read_bytes()).hexdigest(), scale=scale,
threshold=THRESHOLD, max_hulls=MAX_HULLS, vertices_grown=int(grown),
single_hull_cm3=round(single * 1e6, 3),
pieces_cm3=round(sum(h.volume for h in hulls) * 1e6, 3),
mesh_cm3=round(mesh.volume * 1e6, 3) if mesh.is_watertight else None,
surface_gap_max_mm=round(float(max(gap.max(), 0.0)) * 1000, 4),
collision=[f"collision/{f}" for f in files])
def main():
OUT.mkdir(exist_ok=True)
path = OUT / "manifest.json"
manifest = json.loads(path.read_text()) if path.exists() else dict(parts={})
manifest["note"] = ("Collision hulls replacing upstream single-hull arm geoms: slab hulls for the fingers "
"(prepare_gripper_assets.py), convex decompositions for bulky links (prepare_arm_collision.py).")
for name, scale in PARTS.items():
info = decompose(name, scale)
manifest["parts"][name] = info
mesh_cm3 = info["mesh_cm3"] or float("nan")
print(f"{name}: {len(info['collision'])} hulls, {info['pieces_cm3']:.1f} cm3 "
f"(single hull {info['single_hull_cm3']:.1f}, part {mesh_cm3:.1f}), "
f"{info['vertices_grown']} vertices grown, surface gap {info['surface_gap_max_mm']} mm")
path.write_text(json.dumps(manifest, indent=2) + "\n")
if __name__ == "__main__":
main()