cmvr-es/model/xiaozhao/simplify_visual_meshes.py

221 lines
9.2 KiB
Python

"""Generate MuJoCo visual meshes from the STL files referenced by the URDF.
Run with Blender 4.5 from any directory:
blender --background --factory-startup --python simplify_visual_meshes.py
blender --background --factory-startup --python simplify_visual_meshes.py -- --hands-only
The sampled surface-distance check is a quality check, not a Hausdorff bound.
All generated meshes and the manifest are written to meshes/visual.
"""
from pathlib import Path
import argparse
import hashlib
import json
import os
import stat
import struct
import sys
import tempfile
import xml.etree.ElementTree as ET
import bpy
import numpy as np
from mathutils.bvhtree import BVHTree
MESHES = Path(__file__).resolve().parent / "meshes"
URDF = MESHES.parent / "urdf" / "xiaozhao.urdf"
OUTPUT = MESHES / "visual"
TARGET_RATIO = 0.10
MIN_FACES = 2000
MAX_SAMPLED_ERROR = 0.0005 # metres; retain more faces if necessary
SAMPLES_PER_KIND = 6000
HAND_TARGET_RATIO = 0.08
HAND_MAX_SAMPLED_ERROR = 0.0009
# Covers every vertex and triangle centre of the current hand meshes.
HAND_SAMPLES_PER_KIND = 300000
HAND_NAMES = {"link7-left.STL", "link7-right.STL"}
STL_DTYPE = np.dtype([
("normal", "<f4", (3,)), ("vertices", "<f4", (3, 3)), ("attribute", "<u2")
])
def read_stl(path):
with path.open("rb") as stream:
header = stream.read(84)
count = struct.unpack("<I", header[80:84])[0]
assert path.stat().st_size == 84 + 50 * count, path
triangles = np.fromfile(stream, dtype=STL_DTYPE, count=count)["vertices"]
vertices, indices = np.unique(triangles.reshape(-1, 3), axis=0, return_inverse=True)
return vertices, indices.reshape(-1, 3)
def atomic_write(path, data):
mode = stat.S_IMODE(path.stat().st_mode) if path.exists() else 0o644
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
temporary = Path(stream.name)
stream.write(data)
try:
temporary.chmod(mode)
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def write_stl(path, vertices, faces):
triangles = vertices[faces].astype(np.float32)
precise = triangles.astype(np.float64)
normal = np.cross(precise[:, 1] - precise[:, 0], precise[:, 2] - precise[:, 0])
length = np.linalg.norm(normal, axis=1)
assert np.all(length > 0), f"Degenerate triangles in {path.name}"
records = np.zeros(len(faces), dtype=STL_DTYPE)
records["normal"] = normal / length[:, None]
records["vertices"] = triangles
atomic_write(path, b"xiaozhao visual mesh; original coordinates in metres".ljust(80, b"\0")
+ struct.pack("<I", len(faces)) + records.tobytes())
def sample_points(vertices, faces, count=SAMPLES_PER_KIND):
rng = np.random.default_rng(17)
vi = rng.choice(len(vertices), min(count, len(vertices)), replace=False)
fi = rng.choice(len(faces), min(count, len(faces)), replace=False)
return np.concatenate((vertices[vi], vertices[faces[fi]].mean(axis=1)))
def surface_tree(vertices, faces):
return BVHTree.FromPolygons(vertices.tolist(), faces.tolist(), all_triangles=True)
def distances(points, tree):
return np.array([tree.find_nearest(point)[3] for point in points])
def simplify(path, *, target_ratio=TARGET_RATIO,
max_error=MAX_SAMPLED_ERROR, samples_per_kind=SAMPLES_PER_KIND):
vertices, faces = read_stl(path)
original_tree = surface_tree(vertices, faces)
original_samples = sample_points(vertices, faces, samples_per_kind)
mesh = bpy.data.meshes.new(path.stem + "_source")
mesh.from_pydata(vertices.tolist(), [], faces.tolist())
mesh.update()
obj = bpy.data.objects.new(path.stem + "_simplify", mesh)
bpy.context.scene.collection.objects.link(obj)
modifier = obj.modifiers.new("Visual simplification", "DECIMATE")
modifier.decimate_type = "COLLAPSE"
modifier.use_collapse_triangulate = True
ratio = min(1., max(target_ratio, MIN_FACES / len(faces)))
try:
while True:
modifier.ratio = ratio
bpy.context.view_layer.update()
evaluated = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
result = evaluated.to_mesh()
try:
result.calc_loop_triangles()
out_vertices = np.empty((len(result.vertices), 3), dtype=np.float32)
out_faces = np.empty((len(result.loop_triangles), 3), dtype=np.int32)
result.vertices.foreach_get("co", out_vertices.ravel())
result.loop_triangles.foreach_get("vertices", out_faces.ravel())
finally:
evaluated.to_mesh_clear()
# Discard zero-area faces produced by CAD tessellation/collapse.
precise = out_vertices[out_faces].astype(np.float64)
areas = np.linalg.norm(np.cross(
precise[:, 1] - precise[:, 0], precise[:, 2] - precise[:, 0]
), axis=1)
out_faces = out_faces[areas > 0]
used, indices = np.unique(out_faces.ravel(), return_inverse=True)
out_vertices = out_vertices[used]
out_faces = indices.reshape(-1, 3).astype(np.int32)
out_tree = surface_tree(out_vertices, out_faces)
errors = np.concatenate((
distances(original_samples, out_tree),
distances(sample_points(out_vertices, out_faces, samples_per_kind), original_tree),
))
bounds_error = float(np.max(np.abs(
np.array([vertices.min(axis=0), vertices.max(axis=0)])
- np.array([out_vertices.min(axis=0), out_vertices.max(axis=0)])
)))
if max(float(errors.max()), bounds_error) <= max_error:
break
if ratio >= 1.:
raise ValueError(f"Surface check failed for {path.name}")
ratio = min(1., ratio * 2)
print(f"Retaining more detail in {path.name}: ratio={ratio:.3f}; "
f"sampled error={errors.max() * 1000:.3f} mm", flush=True)
output = OUTPUT / path.name
write_stl(output, out_vertices, out_faces)
report = {
"source": path.name,
"source_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
"output": "visual/" + output.name,
"source_faces": len(faces),
"output_faces": len(out_faces),
"sampled_surface_max_m": float(errors.max()),
"sampled_surface_rms_m": float(np.sqrt(np.mean(errors ** 2))),
"bounds_max_change_m": bounds_error,
"target_ratio": target_ratio,
"max_sampled_error_m": max_error,
"samples_per_kind": samples_per_kind,
}
print(json.dumps(report), flush=True)
return report
finally:
bpy.data.objects.remove(obj, do_unlink=True)
bpy.data.meshes.remove(mesh)
def simplify_hands():
"""Preserve the exact mirror relationship of the two URDF hand meshes."""
left_source, right_source = MESHES / "link7-left.STL", MESHES / "link7-right.STL"
lv, lf = read_stl(left_source)
rv, rf = read_stl(right_source)
if not np.array_equal(rv[rf], lv[lf][:, [0, 2, 1], :] * [1, 1, -1]):
raise ValueError("URDF hand STL files are not exact mirrors; review before simplifying")
left = simplify(left_source,
target_ratio=HAND_TARGET_RATIO, max_error=HAND_MAX_SAMPLED_ERROR,
samples_per_kind=HAND_SAMPLES_PER_KIND)
vertices, faces = read_stl(OUTPUT / "link7-left.STL")
vertices[:, 2] *= -1
write_stl(OUTPUT / "link7-right.STL", vertices, faces[:, [0, 2, 1]])
right = dict(left, source=right_source.name,
source_sha256=hashlib.sha256(right_source.read_bytes()).hexdigest(),
output="visual/link7-right.STL",
mirror_of="visual/link7-left.STL", mirror_axis="z")
return [left, right]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--hands-only", action="store_true",
help="Update only the hand visuals from the URDF hand STL files")
args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [])
OUTPUT.mkdir(exist_ok=True)
sources = {Path(mesh.attrib["filename"]).name
for mesh in ET.parse(URDF).iterfind("link/visual/geometry/mesh")}
if args.hands_only:
previous = json.loads((OUTPUT / "manifest.json").read_text())
reports = [item for item in previous["meshes"]
if Path(item["output"]).name in sources - HAND_NAMES]
else:
reports = [simplify(MESHES / name) for name in sorted(sources - HAND_NAMES)]
reports.extend(simplify_hands())
reports.sort(key=lambda item: item["output"])
report = {
"blender_version": bpy.app.version_string,
"target_ratio": TARGET_RATIO,
"min_faces": MIN_FACES,
"max_sampled_error_m": MAX_SAMPLED_ERROR,
"samples_per_kind": SAMPLES_PER_KIND,
"source_faces": sum(item["source_faces"] for item in reports),
"output_faces": sum(item["output_faces"] for item in reports),
"meshes": reports,
}
atomic_write(OUTPUT / "manifest.json", (json.dumps(report, indent=2) + "\n").encode())
print(f"TOTAL {report['source_faces']} -> {report['output_faces']} faces", flush=True)
if __name__ == "__main__":
main()