214 lines
11 KiB
Python
214 lines
11 KiB
Python
"""Fit named convex pieces to complete source triangles in link coordinates."""
|
|
|
|
import importlib.util
|
|
from pathlib import Path
|
|
import re
|
|
import sys
|
|
|
|
import numpy as np
|
|
import trimesh
|
|
|
|
|
|
FITTER_PATH = (Path(__file__).resolve().parents[3] /
|
|
"scripts/isaac_sim/generate_collision_primitives.py")
|
|
|
|
|
|
def shared_fitter():
|
|
name = "xiaozhao_shared_primitive_fitter"
|
|
if name not in sys.modules:
|
|
spec = importlib.util.spec_from_file_location(name, FITTER_PATH)
|
|
module = importlib.util.module_from_spec(spec)
|
|
sys.modules[name] = module
|
|
spec.loader.exec_module(module)
|
|
return sys.modules[name]
|
|
|
|
|
|
def link_triangles(link):
|
|
"""Input mesh URIs must already identify the current local model assets."""
|
|
fitter = shared_fitter()
|
|
triangles = []
|
|
for visual in link.findall("visual"):
|
|
mesh_element = visual.find("geometry/mesh")
|
|
if mesh_element is None:
|
|
continue
|
|
path = Path(mesh_element.get("filename", ""))
|
|
if not path.is_absolute() or not path.is_file():
|
|
raise ValueError(f"expected an absolute current-model mesh path: {path}")
|
|
mesh = trimesh.load(path, force="mesh", process=False)
|
|
scale = fitter._parse_vector(mesh_element.get("scale"), 3, (1, 1, 1))
|
|
transform = fitter._urdf_origin_transform(visual.find("origin"))
|
|
vertices = trimesh.transform_points(np.asarray(mesh.vertices) * scale, transform)
|
|
triangles.append(vertices[np.asarray(mesh.faces)])
|
|
if not triangles:
|
|
raise ValueError(f"no visual triangles on {link.get('name')}")
|
|
result = np.concatenate(triangles)
|
|
if result.ndim != 3 or result.shape[1:] != (3, 3) or not np.isfinite(result).all():
|
|
raise ValueError(f"invalid source triangles on {link.get('name')}")
|
|
return result
|
|
|
|
|
|
def partition_triangles(triangles, pieces):
|
|
"""Assign each complete face to exactly one half-open centroid region."""
|
|
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()):
|
|
raise ValueError("expected finite, nonempty triangles with shape (N, 3, 3)")
|
|
if not pieces:
|
|
raise ValueError("pieces must not be empty")
|
|
centroids = triangles.mean(axis=1)
|
|
owner = np.full(len(triangles), -1, dtype=np.int32)
|
|
names = set()
|
|
for index, piece in enumerate(pieces):
|
|
name = piece.get("name", "")
|
|
if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_\-]+", name) or name in names:
|
|
raise ValueError(f"piece names must be unique simple identifiers: {name!r}")
|
|
names.add(name)
|
|
if not isinstance(piece.get("enabled", True), bool):
|
|
raise ValueError(f"enabled must be a boolean on {name}")
|
|
lower = np.asarray(piece.get("bounds_min", [-np.inf] * 3), dtype=float)
|
|
upper = np.asarray(piece.get("bounds_max", [np.inf] * 3), dtype=float)
|
|
if (lower.shape != (3,) or upper.shape != (3,) or
|
|
np.isnan(lower).any() or np.isnan(upper).any() or not (lower < upper).all()):
|
|
raise ValueError(f"invalid region bounds for {name}")
|
|
selected = np.all((centroids >= lower) & (centroids < upper), axis=1)
|
|
if not selected.any():
|
|
raise ValueError(f"empty piece: {name}")
|
|
if np.any(owner[selected] >= 0):
|
|
raise ValueError(f"overlapping triangle assignments at piece: {name}")
|
|
owner[selected] = index
|
|
missing = int(np.count_nonzero(owner < 0))
|
|
if missing:
|
|
raise ValueError(f"{missing} source triangles are not assigned to a piece")
|
|
return owner
|
|
|
|
|
|
def connected_face_groups(faces):
|
|
"""Split only at disconnected triangle edges; retain even isolated faces."""
|
|
mesh = trimesh.Trimesh(vertices=faces.reshape(-1, 3),
|
|
faces=np.arange(len(faces) * 3).reshape(-1, 3), process=False)
|
|
# STL repeats the vertices of each face. Weld identical positions to recover
|
|
# adjacency without processing/removing any original faces.
|
|
mesh.merge_vertices(digits_vertex=12)
|
|
components = trimesh.graph.connected_components(mesh.face_adjacency,
|
|
nodes=np.arange(len(faces)),
|
|
min_len=1, engine="scipy")
|
|
return [faces[indices] for indices in sorted(components, key=lambda item: int(np.min(item)))]
|
|
|
|
|
|
def axial_layer_points(name, faces, axis, layers):
|
|
"""Get all vertices of each triangle portion clipped to an axial slab."""
|
|
coordinates = faces[:, :, axis]
|
|
axial_min = coordinates.min(axis=1)
|
|
axial_max = coordinates.max(axis=1)
|
|
if axial_max.max() <= axial_min.min():
|
|
raise ValueError(f"cannot split a flat piece along its cylinder axis: {name}")
|
|
cuts = np.linspace(axial_min.min(), axial_max.max(), layers + 1)
|
|
for index, (lower, upper) in enumerate(zip(cuts[:-1], cuts[1:])):
|
|
selected = faces[(axial_max >= lower) & (axial_min <= upper)]
|
|
if not len(selected):
|
|
raise ValueError(f"empty axial layer {index} on {name}")
|
|
starts = selected.reshape(-1, 3)
|
|
ends = np.roll(selected, -1, axis=1).reshape(-1, 3)
|
|
a, b = starts[:, axis], ends[:, axis]
|
|
vertices = [starts[(a >= lower) & (a <= upper)]]
|
|
# The clipped polygon's vertices are the source vertices in the slab
|
|
# and the intersections of its edges with either boundary plane.
|
|
for plane in (lower, upper):
|
|
crosses = (np.minimum(a, b) < plane) & (plane < np.maximum(a, b))
|
|
fraction = (plane - a[crosses]) / (b[crosses] - a[crosses])
|
|
vertices.append(starts[crosses] + fraction[:, None] *
|
|
(ends[crosses] - starts[crosses]))
|
|
yield f"{name}_slice{index:02d}", np.concatenate(vertices), len(selected)
|
|
|
|
|
|
def fit_pieces(triangles, settings):
|
|
fitter = shared_fitter()
|
|
pieces = settings["pieces"]
|
|
owner = partition_triangles(triangles, pieces)
|
|
result = []
|
|
for index, piece in enumerate(pieces):
|
|
if not piece.get("enabled", True):
|
|
continue
|
|
config = {**settings, **piece}
|
|
kind = piece.get("primitive", "box")
|
|
if kind not in ("box", "cylinder", "auto"):
|
|
raise ValueError(f"piece must be box, cylinder or auto: {piece['name']}")
|
|
allowed = config.get("allowed_primitives", ["box", "cylinder"])
|
|
if not isinstance(allowed, list) or not allowed or set(allowed) - {"box", "cylinder"}:
|
|
raise ValueError("piece allowed_primitives must select box and/or cylinder")
|
|
alignment = config.get("alignment", "link")
|
|
if alignment not in ("link", "oriented"):
|
|
raise ValueError(f"invalid alignment on {piece['name']}")
|
|
axis = config.get("axis")
|
|
if (kind == "cylinder" or (kind == "auto" and "cylinder" in allowed)) and axis not in ("x", "y", "z", "auto"):
|
|
raise ValueError(f"piece cylinder requires x/y/z/auto axis: {piece['name']}")
|
|
if axis == "auto":
|
|
axis = None
|
|
layers = config.get("axial_layers", 1)
|
|
if type(layers) is not int or layers < 1:
|
|
raise ValueError("axial_layers must be a positive integer")
|
|
if layers > 1 and (kind != "cylinder" or axis not in ("x", "y", "z")):
|
|
raise ValueError("axial_layers requires a cylinder with a fixed axis")
|
|
padding, scale = float(config.get("padding", 0.001)), float(config.get("scale", 1.0))
|
|
if not np.isfinite([padding, scale]).all() or padding < 0 or scale < 1:
|
|
raise ValueError("piece padding must be nonnegative; scale must be at least 1")
|
|
selected = triangles[owner == index]
|
|
split_normals = config.get("split_normals", False)
|
|
if not isinstance(split_normals, bool):
|
|
raise ValueError("split_normals must be a boolean")
|
|
groups = [(piece["name"], selected)]
|
|
if split_normals:
|
|
normals = np.cross(selected[:, 1] - selected[:, 0], selected[:, 2] - selected[:, 0])
|
|
dominant = np.argmax(np.abs(normals), axis=1)
|
|
negative = normals[np.arange(len(normals)), dominant] < 0
|
|
direction = 2 * dominant + negative.astype(int)
|
|
# Six deterministic normal groups; zero-area triangles go to x_pos
|
|
# and are retained. Empty derived groups emit no geometry.
|
|
labels = ("x_pos", "x_neg", "y_pos", "y_neg", "z_pos", "z_neg")
|
|
groups = [(piece["name"] + "_" + label, selected[direction == group])
|
|
for group, label in enumerate(labels) if np.any(direction == group)]
|
|
split_components = config.get("split_components", False)
|
|
if not isinstance(split_components, bool):
|
|
raise ValueError("split_components must be a boolean")
|
|
if split_components:
|
|
groups = [(name + f"_part{index:03d}", component)
|
|
for name, faces in groups
|
|
for index, component in enumerate(connected_face_groups(faces))]
|
|
if layers > 1:
|
|
samples = (sample for name, faces in groups for sample in
|
|
axial_layer_points(name, faces, "xyz".index(axis), layers))
|
|
else:
|
|
samples = ((name, faces.reshape(-1, 3), len(faces)) for name, faces in groups)
|
|
for name, points, face_count in samples:
|
|
if len(points) == 3:
|
|
points = np.concatenate([points, points[:1]])
|
|
fit_alignment = alignment
|
|
if kind in ("box", "auto") and alignment == "oriented" and np.linalg.matrix_rank(points - points[0]) < 2:
|
|
fit_alignment = "link" # AABB also encloses degenerate line/point faces.
|
|
center = np.zeros(3)
|
|
unit = 1.0
|
|
fit_points = points
|
|
if kind == "auto" or (kind == "cylinder" and axis is None):
|
|
# The shared minimum-cylinder solver optimizes volume with an
|
|
# absolute tolerance. SI-sized thin parts otherwise stop at a
|
|
# coarse sampled axis. Normalize before fitting, keeping the
|
|
# physical padding unchanged when restoring metric dimensions.
|
|
center = (points.min(axis=0) + points.max(axis=0)) / 2
|
|
unit = float(np.ptp(points, axis=0).max()) or 1.0
|
|
fit_points = (points - center) / unit
|
|
fit = fitter.fit_primitive(fit_points, kind, allowed=allowed, padding=padding / unit,
|
|
scale=scale, cylinder_sample_count=6,
|
|
cylinder_angle_tol=1e-7, alignment=fit_alignment, axis=axis)
|
|
transform = fit.transform.copy()
|
|
transform[:3, 3] = transform[:3, 3] * unit + center
|
|
fit = fitter.PrimitiveFit(fit.kind, transform,
|
|
tuple(value * unit for value in fit.dimensions),
|
|
fit.volume * unit ** 3)
|
|
if not np.isfinite(fit.dimensions).all() or min(fit.dimensions) <= 0:
|
|
raise ValueError(f"invalid fitted dimensions on {name}")
|
|
result.append((name, fit, face_count))
|
|
names = [name for name, _, _ in result]
|
|
if len(set(names)) != len(names):
|
|
raise ValueError("derived normal-group names collide with explicit piece names")
|
|
return result
|