"""Deterministic quantized triangle-mesh codec; no pretrained generator or mesh simplification.""" from pathlib import Path import numpy as np def quantize_mesh(vertices, faces, bins: int = 512, max_vertices: int = 128, max_faces: int = 128): v, f = np.asarray(vertices, dtype=np.float64), np.asarray(faces) if v.ndim != 2 or v.shape[1] != 3 or not 3 <= len(v) <= max_vertices or not np.isfinite(v).all(): raise ValueError("expected finite mesh vertices; simplify externally if over the vertex budget") if f.ndim != 2 or f.shape[1] != 3 or not 1 <= len(f) <= max_faces or f.dtype.kind not in "iu" or f.min() < 0 or f.max() >= len(v): raise ValueError("invalid triangle faces or face budget exceeded") center = (v.min(0) + v.max(0)) / 2 scale = float(np.ptp(v, axis=0).max()) if scale <= 1e-12: raise ValueError("zero-extent mesh") q = np.rint(((v - center) / scale + 0.5) * (bins - 1)).clip(0, bins - 1).astype(np.int32) # Quantization can merge vertices or collapse skinny triangles: reject these samples. if len(np.unique(q, axis=0)) != len(q) or np.any(np.linalg.norm(np.cross(q[f[:, 1]] - q[f[:, 0]], q[f[:, 2]] - q[f[:, 0]]), axis=1) == 0): raise ValueError("degenerate geometry after quantization") return {"type": "mesh", "vertices": q.tolist(), "faces": f.tolist()}, {"center": center.tolist(), "scale": scale, "bins": bins} def decode_mesh(packet: dict, transform: dict | None = None, bins: int = 512): v = np.asarray(packet["vertices"], dtype=np.float64) / (bins - 1) - 0.5 if transform is not None: v = v * transform["scale"] + transform["center"] return v, np.asarray(packet["faces"], dtype=np.int32) def write_obj(packet: dict, path: str | Path, transform: dict | None = None): """Export geometry as a real OBJ; materials/textures are deliberately outside this codec.""" v, f = decode_mesh(packet, transform) text = "".join(f"v {x:.7f} {y:.7f} {z:.7f}\n" for x, y, z in v) text += "".join(f"f {a+1} {b+1} {c+1}\n" for a, b, c in f) Path(path).write_text(text, encoding="utf-8")