File size: 6,508 Bytes
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""Build slab-hull collision shapes for the two SO-101 gripper fingers.

MuJoCo collides a mesh geom through its convex hull. The upstream fixed-jaw part
(`wrist_roll_follower_so101_v1`) carries the finger and the wrist mount in one mesh,
so its hull fills the gap between the jaws: 7 mm into the gap 8 mm above the tip,
13 mm at 18 mm. Nothing can be pinched the way the real gripper pinches.

This script cuts each finger mesh into thin slabs along the finger and keeps the
convex hull of each slab, like the knight's neck in `prepare_chess_assets.py`.
Hulls stay in the original mesh frame, so `make_scene.py` gives them the same
geom pos/quat as the upstream collision geom they replace. Visual meshes, joints,
actuators and inertials are untouched.

Run only when rebuilding assets: uv pip install --python .venv/bin/python -e '.[assets]'
Then: .venv/bin/python sim/prepare_gripper_assets.py
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path

import numpy as np
import trimesh

from grasp_geometry import section_extent

ROOT = Path(__file__).resolve().parent / "assets" / "so101"
OUT = ROOT / "collision"

# axis: mesh axis running along the finger. fine: range (mm) covering the finger,
# cut into FINE_MM slabs. The rest of the part (mount, horn) uses COARSE_MM slabs.
# grip: the 40 mm nearest the fingertip, which touches pieces; validate_scene.py
# checks the hulls against the mesh there.
FINGERS = {
    "wrist_roll_follower_so101_v1": dict(axis=2, fine=(40.0, 105.5), grip=(65.5, 105.4)),
    "moving_jaw_so101_v1": dict(axis=1, fine=(-82.1, -22.0), grip=(-82.0, -42.0)),
}
FINE_MM = 2.0
COARSE_MM = 6.0
STEP_SCAN_MM = 0.05      # resolution of the search for steps in the finger profile
STEP_JUMP_MM = 0.15      # a section extent jumping this much between samples is a step


def convex_slab(mesh: trimesh.Trimesh, axis: int, lo: float, hi: float):
    """Convex hull of the part of `mesh` between two planes normal to `axis`."""
    v = mesh.vertices
    points = [v[(v[:, axis] >= lo) & (v[:, axis] <= hi)]]
    a, b = v[mesh.edges_unique[:, 0]], v[mesh.edges_unique[:, 1]]
    for c in (lo, hi):
        mask = ((a[:, axis] <= c) & (b[:, axis] > c)) | ((b[:, axis] <= c) & (a[:, axis] > c))
        aa, bb = a[mask], b[mask]
        points.append(aa + (bb - aa) * ((c - aa[:, axis]) / (bb[:, axis] - aa[:, axis]))[:, None])
    points = np.concatenate(points)
    if len(points) < 4 or np.ptp(points[:, axis]) < 1e-7:
        return None
    hull = trimesh.Trimesh(vertices=points * 1000, process=False).convex_hull
    hull.apply_scale(0.001)
    return hull


def profile_steps(mesh: trimesh.Trimesh, axis: int, fine: tuple[float, float]) -> np.ndarray:
    """Heights (mm) along the finger where its cross-section changes abruptly.

    A slab spanning such a step would fill it in, so a cut is placed at each step.
    """
    perm = [i for i in range(3) if i != axis] + [axis]
    tris = mesh.triangles[:, :, perm]
    h = np.arange(fine[0], fine[1], STEP_SCAN_MM) / 1000
    extents = []
    for along in (np.array([1.0, 0.0]), np.array([0.0, 1.0])):
        extents += section_extent(tris, h, along, np.array([-along[1], along[0]]), 1.0)
    jumps = np.flatnonzero(np.nanmax(np.abs(np.diff(np.array(extents), axis=1)), axis=0) > STEP_JUMP_MM / 1000)
    # Cut at the last sample before a step and the first sample after it, so only a
    # sliver as thin as the scan spacing straddles it. A sloped step is a run of jumps.
    cuts, run = [], []
    for j in jumps:
        if run and j > run[-1] + 2:
            cuts += [h[run[0]], h[run[-1] + 1]]
            run = []
        run.append(j)
    if run:
        cuts += [h[run[0]], h[run[-1] + 1]]
    return np.array(cuts) * 1000


def slab_edges(lo_mm, hi_mm, fine, steps) -> np.ndarray:
    edges = [np.arange(lo_mm, fine[0], COARSE_MM), np.arange(fine[0], fine[1], FINE_MM),
             np.arange(fine[1], hi_mm, COARSE_MM), [fine[0], fine[1], lo_mm, hi_mm]]
    edges = np.unique(np.round(np.concatenate(edges), 6))
    # Regular cuts closer than 0.4 mm to a step cut are dropped to avoid sliver slabs.
    edges = [e for e in edges if len(steps) == 0 or np.all(np.abs(e - steps) > 0.4)] + list(steps)
    edges = np.unique(np.round(edges, 6))
    return edges[(edges >= lo_mm - 1e-6) & (edges <= hi_mm + 1e-6)] / 1000


def prepare(name: str, axis: int, fine: tuple[float, float], grip: tuple[float, float]) -> dict:
    source = ROOT / f"{name}.stl"
    mesh = trimesh.load_mesh(source)
    lo, hi = mesh.bounds[:, axis] * 1000
    files = []
    steps = profile_steps(mesh, axis, fine)
    edges = slab_edges(lo - 0.01, hi + 0.01, fine, steps)
    for i, (a, b) in enumerate(zip(edges[:-1], edges[1:])):
        hull = convex_slab(mesh, axis, a, b)
        # A cut lying exactly on a flat face can leave a degenerate hull; nudge it.
        for nudge in (1e-5, -1e-5, 2e-5):
            if hull is None or (hull.is_watertight and hull.volume > 0):
                break
            hull = convex_slab(mesh, axis, a + nudge, b - nudge)
        if hull is None:
            continue
        if not hull.is_watertight or hull.volume <= 0:
            raise ValueError(f"invalid hull {name} slab {i}")
        path = OUT / f"{name}_{len(files):02d}.stl"
        hull.export(path)
        files.append(path.name)
    for stale in OUT.glob(f"{name}_*.stl"):
        if stale.name not in files:
            stale.unlink()
    return dict(source_file=source.name, source_sha256=hashlib.sha256(source.read_bytes()).hexdigest(),
                axis=axis, fine_range_mm=list(fine), grip_range_mm=list(grip),
                fine_slab_mm=FINE_MM, coarse_slab_mm=COARSE_MM,
                step_cuts_mm=np.round(steps, 3).tolist(), slab_edges_mm=np.round(edges * 1000, 4).tolist(),
                collision=[f"collision/{f}" for f in files])


def main():
    OUT.mkdir(exist_ok=True)
    # The manifest also lists prepare_arm_collision.py's parts; replace only the fingers.
    path = OUT / "manifest.json"
    manifest = json.loads(path.read_text()) if path.exists() else dict(parts={})
    manifest.setdefault("note", "Slab convex hulls replacing the upstream single-hull finger collision geoms.")
    for name, cfg in FINGERS.items():
        manifest["parts"][name] = dict(method="slab", **prepare(name, **cfg))
        print(f"{name}: {len(manifest['parts'][name]['collision'])} hulls")
    path.write_text(json.dumps(manifest, indent=2) + "\n")


if __name__ == "__main__":
    main()