Rice cube: procedural rice material and displaced filleted cubes

Two halves, one pipeline.

make_rice_texture.py models short-grain rice as randomly oriented 3D
ellipsoids (surface height solved as the quadratic root, so any orientation
works -- including grains standing on end), scattered by Poisson disk on a
torus and unioned into a height field. Because the scatter wraps by index, the
baked height/normal/AO/albedo set tiles exactly; that is proven by translating
the whole scatter a quarter patch and requiring a rolled copy back (0.0 mm
error), not by sampling a seam line, which turned out to be a coin flip.

make_rice_cube.py displaces a filleted cube with that height map: voxel remesh
for uniform vertex density, then triplanar sampling of the height field in
Geometry Nodes on object-space position. Exports STL via Blender and a
hand-rolled core-1.0 3MF, because this Blender build has no 3MF support and the
nix store is read-only.

Kept here: the procedural map set, the render of each body that was built
(40 mm / 4 mm fillet, and 160 mm / 8 mm), and the A/B sheets that record why --
fusing is voxel resolution, relief ratio 0.6 beats the map's own 0.9 on a small
body, and the fillet only reads once the body is large relative to the relief.

Not kept: mesh binaries (560 MB, 384 MB of it one STL), the scan extract, and
the baseline runs whose renders survive inside the sheets. rebuild.sh
regenerates all of it, in dependency order, including the sheets.
This commit is contained in:
2026-11-12 10:54:43 +01:00
commit 8104e01d6b
31 changed files with 1975 additions and 0 deletions
+163
View File
@@ -0,0 +1,163 @@
"""Check the exported files as a slicer would see them, not as Blender does.
python3 verify.py out/
Manifold check works on the triangle soup alone (STL carries no topology, so
vertices are welded by exact coordinate match). Signed volume is the cheap
global test: a closed, consistently outward-oriented surface gives a positive
volume close to the intended body volume.
"""
import glob
import json
import os
import struct
import sys
from array import array
import xml.etree.ElementTree as ET
import zipfile
import numpy as np
CORE_NS = "{http://schemas.microsoft.com/3dmanufacturing/core/2015/02}"
def read_stl(path):
with open(path, "rb") as f:
f.read(80)
(count,) = struct.unpack("<I", f.read(4))
raw = f.read(count * 50)
assert len(raw) == count * 50, f"{path}: truncated triangle data"
faces = np.frombuffer(raw, dtype=np.uint8).reshape(count, 50)[:, 12:48]
tris = faces.copy().view("<f4").reshape(count, 3, 3)
return tris.astype(np.float64)
def read_3mf(path):
"""Stream the model out of the zip.
Building the whole tree with ElementTree is fine for a small model and fatal
for an 8M-triangle one: 11.5M element objects is several GB. Parsing events
into flat arrays and clearing each container as it goes keeps it at the size
of the data itself.
"""
with zipfile.ZipFile(path) as z:
bad = z.testzip()
assert bad is None, f"{path}: corrupt member {bad}"
names = set(z.namelist())
for required in ("[Content_Types].xml", "_rels/.rels", "3D/3dmodel.model"):
assert required in names, f"{path}: missing {required}"
verts = array("d")
tris = array("i")
unit = None
container = None
with z.open("3D/3dmodel.model") as handle:
for event, elem in ET.iterparse(handle, events=("start", "end")):
tag = elem.tag
if event == "start":
if tag == f"{CORE_NS}model":
unit = elem.get("unit")
elif tag in (f"{CORE_NS}vertices", f"{CORE_NS}triangles"):
container = elem
continue
if tag == f"{CORE_NS}vertex":
verts.extend((float(elem.get("x")), float(elem.get("y")),
float(elem.get("z"))))
elif tag == f"{CORE_NS}triangle":
tris.extend((int(elem.get("v1")), int(elem.get("v2")),
int(elem.get("v3"))))
if container is not None:
container.clear() # drop the child we just consumed
verts = np.frombuffer(memoryview(verts), dtype=np.float64).reshape(-1, 3)
tris = np.frombuffer(memoryview(tris), dtype=np.int32).reshape(-1, 3)
assert tris.min() >= 0 and tris.max() < len(verts), \
f"{path}: triangle index out of range"
return unit, verts, tris
def topology(verts, tris, weld=True):
"""Edge census, plus signed volume.
STL carries no topology, so vertices have to be welded by coordinate, which
costs a sort over N x 3 keys -- at 8M triangles that is enough to get the
process OOM-killed. A 3MF already carries shared indices, so there is nothing
to weld and the census runs directly.
"""
if weld:
key = np.round(verts / 1e-6).astype(np.int64)
unique, index = np.unique(key, axis=0, return_inverse=True)
tris = index[tris]
welded = unique.astype(np.float64) * 1e-6
else:
welded = verts
degenerate = int(((tris[:, 0] == tris[:, 1]) | (tris[:, 1] == tris[:, 2])
| (tris[:, 0] == tris[:, 2])).sum())
# Every edge appears once per incident triangle. A closed, consistently
# oriented surface therefore shows each undirected edge exactly twice,
# once in each direction.
directed = np.vstack([tris[:, [0, 1]], tris[:, [1, 2]], tris[:, [2, 0]]])
forward = directed[:, 0] < directed[:, 1]
undirected = np.sort(directed, axis=1)
edges, inverse, counts = np.unique(undirected, axis=0, return_inverse=True,
return_counts=True)
forward_per_edge = np.bincount(inverse, weights=forward,
minlength=len(edges))
boundary = int((counts == 1).sum())
nonmanifold = int((counts > 2).sum())
misoriented = int(((counts == 2) & (forward_per_edge != 1)).sum())
a, b, c = welded[tris[:, 0]], welded[tris[:, 1]], welded[tris[:, 2]]
signed_vol = float(np.einsum("ij,ij->i", a, np.cross(b, c)).sum() / 6.0)
area = float(np.linalg.norm(np.cross(b - a, c - a), axis=1).sum() / 2.0)
return {
"triangles": int(len(tris)),
"welded_vertices": int(len(welded)),
"boundary_edges": boundary,
"nonmanifold_edges": nonmanifold,
"misoriented_edges": misoriented,
"degenerate_triangles": degenerate,
"signed_volume_mm3": round(signed_vol, 1),
"area_mm2": round(area, 1),
"bbox_mm": [round(float(v), 2) for v in np.ptp(verts, axis=0)],
}
def main(out_dir, only=None):
report = {}
paths = sorted(glob.glob(os.path.join(out_dir, "*.stl")) +
glob.glob(os.path.join(out_dir, "*.3mf")))
for path in paths:
name = os.path.basename(path)
kind = "3mf" if path.endswith(".3mf") else "stl"
if only and kind != only:
continue
if kind == "stl":
tris = read_stl(path)
verts = tris.reshape(-1, 3)
shape = (verts, np.arange(len(verts)).reshape(-1, 3), True)
unit = "millimetre (implied)"
else:
unit, verts, idx = read_3mf(path)
shape = (verts, idx, False)
info = topology(*shape)
info["unit"] = unit
info["file_mb"] = round(os.path.getsize(path) / 1e6, 2)
report[name] = info
print(f"\n== {name} [{info['unit']}]")
for key, value in info.items():
if key != "unit":
print(f" {key:22s} {value}")
with open(os.path.join(out_dir, "verify.json"), "w") as f:
json.dump(report, f, indent=2)
if __name__ == "__main__":
directory = sys.argv[1] if len(sys.argv) > 1 else "out"
only = sys.argv[2] if len(sys.argv) > 2 else None
main(directory, only)