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
+20
View File
@@ -0,0 +1,20 @@
__pycache__/
*.py[cod]
# Mesh output is rebuildable in ~30 s (40 mm) to ~2 min (160 mm) from the
# committed map set plus these scripts, and it is hundreds of MB, so it is not
# tracked. See README and rebuild.sh.
*.stl
*.3mf
*.blend
*.blend[0-9]
# The scan is an unzip of ~/Downloads/food_0015_2k_sc65C6.zip, not our asset:
# unzip -o ~/Downloads/food_0015_2k_sc65C6.zip -x "__MACOSX/*" -d tex/
tex/
# Baseline runs from earlier iterations. Their renders survive as the A/B
# sheets in out/ (fusing_ab.png, relief_ab.png, scan_vs_procedural.png), which
# is why the runs themselves are not tracked.
out_scan/
out_crisp/
+226
View File
@@ -0,0 +1,226 @@
# Rice cube
A filleted cube surfaced with real rice relief and exported to STL + 3MF. Size
and fillet radius are flags: the two bodies that were built are 40 mm / 4 mm and
160 mm / 8 mm.
Two sources, same pipeline:
- **`tex_proc/` — procedural short-grain rice.** Grain shapes are modelled and
scattered on a torus, then baked to a seamless texture set. **This is the good
one**, and it is the only texture set committed.
- **`tex/` — the ambientCG `food_0015` photo scan.** The baseline the procedural
version is measured against. Not committed: it is an unzip of a downloaded
archive, see `rebuild.sh`.
Start with `out/size_ab.png`, then `tex_proc/maps_sheet.png` and
`out/scan_vs_procedural.png`.
```
make_rice_texture.py python3 procedural maps -> tex_proc/
preview_maps.py python3 maps_sheet.png, fake-lit preview
make_rice_cube.py blender -b -P ... -- args displaced cube -> <out>/
verify.py python3 verify.py <out> [3mf|stl] checks exported files
compare.py python3 labelled A/B sheet, full + zoom
contact_sheet.py python3 variant ladder
measure_scan_scale.py python3 derives the scan's mm scale
rebuild.sh ./rebuild.sh everything not tracked here
```
```sh
python3 make_rice_texture.py && python3 preview_maps.py
blender -b -P make_rice_cube.py -- --height tex_proc/rice_height_16bit.png \
--sidecar tex_proc/rice_maps.json --patch 60 --voxel 0.2 --relief-ratio 0.6
```
Texture bake ~14 s, 40 mm cube ~30 s, 160 mm cube ~2 min, all CPU only.
## What is tracked, and what is not
Committed: the seven scripts, this README, `rebuild.sh`, the procedural map set
(`tex_proc/`, 23 MB, the good one), the render of each body that was kept, and
the five A/B sheets in `out/`.
Not committed, because it is all rebuildable from the above in a couple of
minutes: every `.stl` / `.3mf` / `.blend` (560 MB, and 384 MB of that is the
single 160 mm STL), the scan extract (`tex/`, 57 MB), and the baseline runs
`out_scan/` and `out_crisp/` whose renders survive inside the A/B sheets.
`./rebuild.sh` regenerates the lot, in dependency order, including the sheets.
## How the material is made, and why that way
A bump map is a height map with a strength scalar; a normal map is the *gradient*
of that same field, stored so the shader does not have to differentiate it per
pixel. So the real outputs are height and its derivative — deriving the normal is
a gradient, not a render.
The standard pipeline is author-in-3D → bake-out-to-maps, and that is what
`make_rice_texture.py` does. The part that is easy to get wrong is seamlessness.
Baking a photo gives a map that does not tile, which is exactly the wall the scan
hit: its patch had to stay ≥ one cube face to keep the seam off the surface. So
here the *source* is periodic:
1. **Grain model: a rotated ellipsoid, solved not approximated.** The body is a
3D ellipsoid with a random 3D orientation; for each texel the surface height
is where the vertical line leaves the ellipsoid, i.e. the larger root of a
quadratic (each local coordinate is affine in z, so the equation is quadratic
in z). That is exact for any orientation and is what makes a *standing* grain
possible — laid flat its footprint is a whole grain, stood on end it is the
cross-section with the height of most of a grain. Length lognormal around
5 mm, aspect ~1.78, thickness ~0.44 × length, drawn per grain.
2. **Orientation mixture.** 34% of grains are tilted 30–65° out of plane, the
rest lie down within ~12° of flat. A blanket of shingled grains does not look
like pressed rice; the grains jutting out end-on are most of what the
reference photograph reads as.
3. **Scatter on a torus.** Poisson-disk (blue noise) with torus distance, five
layers spaced 0.38 mm apart — closer than a grain is thick, so upper grains
rest *on* lower ones rather than forming a second storey.
4. **Wrap by index.** Every grain rasterises through `index % N`, so a grain
straddling an edge reappears on the opposite edge without any special case.
5. **Gap filling, not coverage tuning.** Nominal layer coverage is a bad proxy
for closure: an upright grain covers ~2.4 mm² against ~11 mm² for a flat one,
so a pile with many standing grains leaves holes straight down to the plate.
Remaining floor texels are found by connected-component labelling and a grain
dropped into each, until the surface is closed (measured: 0.0000%).
6. **Union by `max()`**, then a wrap-mode blur to soften the creases, then
horizon-marched AO and a per-grain albedo tint.
Outputs (`tex_proc/`): `rice_height_16bit.png` (the bump map, and the
displacement source), `rice_normal_opengl.png` + `rice_normal_directx.png`,
`rice_ao_8bit.png`, `rice_albedo.png`, and `rice_maps.json`.
Two modelling fixes worth recording, both found by looking rather than by
reasoning:
- **A lengthwise groove cut into each grain's top was the "depression at the top
of every grain".** The crease on a real grain is on its *hidden* side; carving
it into a domed top reads as a dent. Removed.
- **Seating grains by their lowest point made upright grains stand a full
grain-length proud of their layer**, which compounds across layers into a spike
field (9.55 mm peak-to-valley for a 5 mm grain). Placing grain *centres* on the
layer plane is what compaction does and bounds the protrusion; with layer
spacing tightened as well, PV came down to 4.48 mm.
**Periodicity is proven, not sampled.** The first check compared one seam line
against interior gradient statistics; across seeds that statistic landed anywhere
from the 4th to the 99th percentile on *correct* fields, so it was a coin flip in
disguise. The test is now: translate the whole scatter by a quarter patch on the
torus and require the same field back, rolled. Reported error: **0.0 mm**
(bitwise identical).
## Cube pipeline
1. Cube + fillet (8 segments), applied. Size and fillet radius are CLI flags:
`--size` and `--fillet` (defaults 40 mm and 4 mm). The preview camera and fill
light are derived from the body size, so framing does not change with scale.
2. **Voxel remesh, 0.2 mm** (`--voxel`). Subdivision surface was the first plan
and is wrong here: it distributes vertices per face, not per millimetre, so on
a filleted cube the fillet strips get ~8× the density of the flats and the
displacement gets 2 mm sampling exactly where it needs 0.2 mm. Voxel remesh is
uniform by construction and watertight. Cost: tri soup, one global density
knob, and that knob is what controls fusing (below).
3. **Triplanar displacement in Geometry Nodes** from object-space `Position`.
Cube UVs slice grains at all 12 edges and give uneven texel density across
bevels. Sampling `position / patch` on the three axis planes and blending by
`|normal|^8` gives one continuous field, no unwrap. The exponent barely
matters between 8 and 48; a hard select leaves a visible height cliff along
every bevel.
4. **Relief derived, not chosen.** `relief = ratio × apparent grain size`, where
the ratio comes from the map's sidecar: 4.48/5.0 = 0.90 for the procedural set,
0.42 for the scan. Relief larger than the grain is what turns rice into
popcorn — tried at 1.25, unmistakable. `--relief-ratio 0.6` is the composition
that was liked; see the relief A/B below for why 0.90 is not it.
5. **Export** STL via `bpy.ops.wm.stl_export` and 3MF via a small stdlib writer.
## The two bodies that were kept
| body | fillet | rice | relief | triangles |
|---|---|---|---|---|
| `out_calm/` | 40 mm | 4 mm | 5.00 mm grains, 60 mm patch | 3.00 mm | 479,532 |
| `out_160/` | 160 mm | 8 mm | 5.00 mm grains, 60 mm patch | 3.00 mm | 7,680,300 |
The rice is the same in both; only the body scales. Patch size is a free choice
because the procedural map tiles exactly — the scan needed patch ≥ face size to
hide its seam.
Grain scale is set by the patch, `grain = 0.0833 × patch`: a 60 mm patch gives
5 mm grains (~8 across a 40 mm face), 36 mm gives 3 mm (~13), 21 mm gives 1.75 mm
(~23). `out/variants.png` is that ladder at 0.3 mm voxel.
Three single-variable A/Bs are rendered rather than described:
`out/fusing_ab.png`, `out/relief_ab.png`, `out/size_ab.png`.
- **Fusing is voxel resolution, nothing else** (`out/fusing_ab.png`).
`BLUR_TEXELS` is 0.5 texels = 0.015 mm, which cannot matter next to a 0.3 mm
voxel — the remesher is the whole story, because it cannot resolve
sub-millimetre valleys and rounds them shut. 0.2 mm (480k tris, 24 MB) keeps
crevices open; 0.3 mm is the coarse pane of that sheet.
- **Relief ratio** (`out/relief_ab.png`). 0.90 × grain is the map's own
peak-to-valley over its grain size, which is right for a flat material but eats
the cube's silhouette: at 4.48 mm the body reads as a lumpy blob. 0.60 × grain
(3.00 mm) keeps the grains clearly modelled while the cube still reads as a
cube. The default follows the map, so `--relief-ratio 0.6` is what the kept
runs use.
- **Body size** (`out/size_ab.png`). At 40 mm the 4 mm fillet is the same order
as the relief, so the rice buries it and the body reads as a lumpy blob; at
160 mm / 8 mm the fillet is a visible band and the cube reads as a cube, with
the rice unchanged at its physical scale.
## Size is not free
Scaling the *body* while keeping the rice at its physical size (5 mm grains,
0.2 mm voxel) scales the surface area, and therefore the triangle count, with the
square. `--size 160 --fillet 8` gives a 16x surface: **7,680,300 triangles,
384 MB STL, 70 MB 3MF, 2 minutes, and a peak of ~3.1 GB RSS**. That is the honest
cost of "same rice, bigger cube"; the alternative is to scale the rice with the
body, which is a different object.
## Verification
`verify.py` reads the delivered files the way a slicer would — welding STL
vertices by coordinate, then an edge census, signed volume, and a structural
check of the 3MF zip/XML.
Verified: 4,070,164 mm³ for the 160 mm body against 4,096,000 for a bare cube,
0 boundary / non-manifold / misoriented / degenerate. At 7.7M triangles the check
runs on the 3MF only — see the note below.
All smaller files: 479,532 triangles, **0 boundary / 0 non-manifold / 0 misoriented /
0 degenerate**, positive signed volume 62,341–63,681 mm³ against 64,000 for a bare
40 mm cube (corner rounding plus relief). 3MF declares `unit="millimeter"`; STL is
unitless and every slicer will assume mm.
Two fixes were needed to check a mesh that size, both real rather than
workarounds. `verify.py` welded STL vertices by sorting N x 3 coordinate keys,
which is enough to get OOM-killed at 8M triangles — but a 3MF already carries
shared indices, so that path needs no welding at all (`verify.py out 3mf`). And
`read_3mf` built the whole XML tree with ElementTree, i.e. 11.5M Python element
objects; it now streams events into flat arrays and clears each container as it
goes, which drops it to the size of the data.
Self-intersection (which manifoldness does not catch) via BVH overlap: **0
intersecting non-adjacent triangle pairs**, with the check controlled against
interpenetrating cubes (12 detected) and a single cube (0). Caveat: it does not
detect coincident coplanar surfaces, and an unwelded triangle soup produced ~59k
false positives at this coordinate scale — weld before testing.
## Still open
- **3MF is hand-rolled** (~50 lines, core-1.0, no extensions) because this
Blender has no 3MF support and the nix store is read-only. Worth one manual
import into PrusaSlicer/Bambu Studio before trusting it in anger.
- **Grains are all separate objects on a common floor.** A real pile has grains
partially covered by others, which happens here via overlap, but there is no
friability, no broken grains, and no dust. Those are what would push it from
"clearly rice" to "scan".
- **The triplanar band along the fillets is the largest remaining artifact.** An
8 mm fillet is 1.6 grains wide, so the crossfade between the two face
projections shows up as a band of stretched grains down every edge. Options
are a wider fillet (~3 grains, so ~15 mm on this body) or fading displacement
out on the fillet so the corners are smooth — the latter is a composition
decision, not a fix, and is not implemented.
- **The generator emits maps, not geometry.** For printing, the baked height map
resamples through the 0.3 mm voxel mesh anyway; scattering the grains as real
meshes and taking the union directly would avoid that resampling step
entirely, and would also give free undercuts that a height field cannot
represent.
+74
View File
@@ -0,0 +1,74 @@
"""Side-by-side A/B sheet: full frame on top, zoomed crop underneath.
python3 compare.py --title "voxel 0.3 vs 0.2" \
"voxel 0.3=out/preview_g5_00.png" "voxel 0.2=out_crisp/preview_g5_00.png"
The zoom row is the point: fusing and crease softness are invisible at full
frame and obvious at 3x. Panes must share a camera for the crop to line up, which
the cube renders do.
"""
import argparse
import os
from PIL import Image, ImageDraw, ImageFont
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
BOLD = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
PANEL_W = 760
def parse_pane(text):
if "=" not in text:
raise SystemExit(f"expected label=path, got {text!r}")
label, path = text.split("=", 1)
if not os.path.exists(path):
raise SystemExit(f"missing {path}")
return label, path
def main():
parser = argparse.ArgumentParser()
parser.add_argument("panes", nargs="+")
parser.add_argument("--title", default="comparison")
parser.add_argument("--out", default="compare.png")
parser.add_argument("--crop", default="0.36,0.24,0.80,0.62",
help="left,top,right,bottom as fractions")
args = parser.parse_args()
panes = [parse_pane(text) for text in args.panes]
left, top, right, bottom = (float(v) for v in args.crop.split(","))
full, zoom = [], []
for _, path in panes:
image = Image.open(path).convert("RGB")
height = int(image.height * PANEL_W / image.width)
full.append(image.resize((PANEL_W, height), Image.LANCZOS))
box = (int(left * image.width), int(top * image.height),
int(right * image.width), int(bottom * image.height))
zoom.append(image.crop(box).resize((PANEL_W, height), Image.LANCZOS))
gap, header = 10, 96
width = PANEL_W * len(panes) + gap * (len(panes) + 1)
height = header + full[0].height * 2 + gap * 3
sheet = Image.new("RGB", (width, height), (28, 29, 31))
draw = ImageDraw.Draw(sheet)
draw.text((gap, 12), args.title, font=ImageFont.truetype(BOLD, 26),
fill=(238, 238, 238))
draw.text((gap, 46), "top: full frame · bottom: "
"same crop, not resampled from the other pane",
font=ImageFont.truetype(FONT, 16), fill=(150, 152, 155))
label_font = ImageFont.truetype(FONT, 18)
for index, (label, _) in enumerate(panes):
x = gap + index * (PANEL_W + gap)
draw.text((x + 2, 70), label, font=label_font, fill=(205, 205, 208))
sheet.paste(full[index], (x, header))
sheet.paste(zoom[index], (x, header + full[index].height + gap))
sheet.save(args.out)
print(f"wrote {args.out} ({sheet.width}x{sheet.height})")
if __name__ == "__main__":
main()
+78
View File
@@ -0,0 +1,78 @@
"""Compose the rendered variants into one labelled sheet.
python3 contact_sheet.py out/
"""
import json
import os
import sys
from PIL import Image, ImageDraw, ImageFont
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
FONT_BOLD = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"
PANEL_W = 820
PAD = 18
TITLE_H = 74
def main(out_dir):
with open(os.path.join(out_dir, "summary.json")) as f:
summary = json.load(f)
with open(os.path.join(out_dir, "verify.json")) as f:
verified = json.load(f)
names = list(summary["variants"])
panels = []
for name in names:
img = Image.open(os.path.join(out_dir, f"preview_{name}.png"))
ratio = PANEL_W / img.width
panels.append(img.resize((PANEL_W, int(img.height * ratio)),
Image.LANCZOS))
panel_h = panels[0].height
label_h = 96
width = PANEL_W * len(panels) + PAD * (len(panels) + 1)
height = TITLE_H + panel_h + label_h + PAD
sheet = Image.new("RGB", (width, height), (32, 34, 36))
draw = ImageDraw.Draw(sheet)
title = ImageFont.truetype(FONT_BOLD, 30)
body = ImageFont.truetype(FONT, 20)
small = ImageFont.truetype(FONT, 17)
draw.text((PAD, 20),
f"Rice cube — {summary['cube_mm']:.0f} mm rounded cube, "
f"displacement from {summary['height_map']}",
font=title, fill=(235, 235, 235))
draw.text((PAD, 52),
f"source: {summary['source']} · one height field at three "
f"apparent grain scales · relief = "
f"{summary['relief_ratio']:.2f} x grain (from the map itself)",
font=small, fill=(150, 152, 155))
for index, (name, panel) in enumerate(zip(names, panels)):
x = PAD + index * (PANEL_W + PAD)
sheet.paste(panel, (x, TITLE_H))
info = summary["variants"][name]
check = verified.get(f"rice_cube_{name}.3mf", {})
lines = [
f"{name} {info['grain_mm']} mm grains",
f"texture spans {info['patch_mm']:.0f} mm "
f"relief {info['displacement_mm']:.2f} mm",
f"{check.get('triangles', 0):,} tris "
f"{check.get('signed_volume_mm3', 0):,.0f} mm3 "
f"boundary edges {check.get('boundary_edges', '?')}",
]
for row, text in enumerate(lines):
draw.text((x + 4, TITLE_H + panel_h + 10 + row * 27), text,
font=body if row == 0 else small,
fill=(232, 232, 232) if row == 0 else (158, 160, 163))
path = os.path.join(out_dir, "variants.png")
sheet.save(path)
print(f"wrote {path} ({sheet.width}x{sheet.height})")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "out")
+537
View File
@@ -0,0 +1,537 @@
"""Rice-textured rounded cube -> STL/3MF.
blender -b -P make_rice_cube.py -- --height tex_proc/rice_height_16bit.png \
--sidecar tex_proc/rice_maps.json
blender -b -P make_rice_cube.py # scanned texture, as it started
Design notes:
* Displacement, not bump: an exported mesh has no materials, so the height
field has to become vertices.
* Triplanar sampling in Geometry Nodes from object-space Position. Cube UVs
would slice grains at each of the 12 edges and give non-uniform texel
density across bevels.
* Voxel remesh provides the vertex density so displacement has something to
sample; it is also what makes the result watertight and print-ready.
* Relief is derived from the apparent grain size, never set independently:
relief larger than the grain turns rice into popcorn. The ratio comes from
the map itself when a sidecar is given, so the cube reproduces the source's
own relief-to-grain proportion at whatever scale it is tiled.
"""
import argparse
import json
import os
import sys
import zipfile
import bpy
import numpy as np
from mathutils import Vector
HERE = os.path.dirname(os.path.abspath(__file__))
TEX = os.path.join(HERE, "tex")
DEFAULT_OUT = os.path.join(HERE, "out")
DEFAULT_SIZE_MM = 40.0
BEVEL_MM = 4.0
BEVEL_SEGMENTS = 8
# Voxel remesh resolution. This is the single biggest control on how much
# adjacent grains fuse: at 0.3 mm the remesher cannot resolve sub-millimetre
# valleys and rounds them away, at 0.2 mm crevices stay open. Cost is quadratic
# in triangles -- 0.3 mm gives 210k tris / 10.5 MB, 0.2 mm gives 480k / 24 MB.
VOXEL_MM = 0.2
# Triplanar blend exponent. The weights already resolve the axis hand-off to
# under a millimetre at 8, so anything from 8 upwards looks the same until it
# becomes a hard select, which leaves a visible height cliff along the bevel.
AXIS_SHARPNESS = 8.0
DEFAULT_HEIGHT = os.path.join(TEX, "food_0015_height_2k.png")
DEFAULT_ALBEDO = os.path.join(TEX, "food_0015_color_2k.jpg")
# For the scan, measured by measure_scan_scale.py: median grain crown is 95 px
# long in a 2048 px map, so a grain is 4.64% of the map's width. A procedural
# map states its own numbers in the sidecar instead.
DEFAULT_GRAIN_FRACTION = 95.0 / 2048.0
DEFAULT_GRAIN_MM = 6.5
# The map at 1:1: a 6.5 mm grain is 4.64% of the map's width, so the map spans
# ~140 mm of rice. Tiling it at that patch reproduces the scan's true scale.
DEFAULT_TRUE_SCALE_MM = DEFAULT_GRAIN_MM / DEFAULT_GRAIN_FRACTION
DEFAULT_RELIEF_RATIO = 0.42
# Map patches are derived from the grain scale, so the variants are the same
# pile at three apparent grain sizes rather than three arbitrary crops.
SCALE_STEPS = (1.0, 0.6, 0.35)
def parse_args(argv):
parser = argparse.ArgumentParser(prog="make_rice_cube")
parser.add_argument("--height", default=DEFAULT_HEIGHT,
help="greyscale height map used as displacement")
parser.add_argument("--albedo", default=None,
help="colour map for the preview renders")
parser.add_argument("--sidecar", default=None,
help="rice_maps.json: supplies grain size and relief")
parser.add_argument("--patch", nargs="*", type=float, default=None,
help="texture width on the cube, in mm (one per variant)")
parser.add_argument("--relief-ratio", type=float, default=None,
help="peak-to-valley relief as a fraction of grain size")
parser.add_argument("--size", type=float, default=DEFAULT_SIZE_MM,
help="cube edge length in mm")
parser.add_argument("--fillet", type=float, default=BEVEL_MM,
help="edge fillet radius in mm (must be < cube/2)")
parser.add_argument("--voxel", type=float, default=VOXEL_MM)
parser.add_argument("--out", default=DEFAULT_OUT)
known = argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
return parser.parse_args(known)
def load_recipe(args):
"""Physical truth about the height map, from its own sidecar if it has one."""
recipe = {
"height": args.height,
"albedo": args.albedo or DEFAULT_ALBEDO,
"grain_fraction": DEFAULT_GRAIN_FRACTION,
"true_scale_mm": DEFAULT_TRUE_SCALE_MM,
"relief_ratio": args.relief_ratio or DEFAULT_RELIEF_RATIO,
"out": args.out,
"voxel": args.voxel,
"fillet": args.fillet,
"size": args.size,
"source": "scanned",
}
if args.sidecar:
with open(args.sidecar) as handle:
sidecar = json.load(handle)
recipe["source"] = os.path.basename(os.path.dirname(
os.path.abspath(args.sidecar)))
recipe["grain_fraction"] = sidecar["grain_fraction_of_patch"]
recipe["true_scale_mm"] = sidecar["patch_mm"]
# Reproduce the source's own relief-to-grain proportion.
recipe["relief_ratio"] = sidecar["relief_mm"] / sidecar["grain_mm"]
albedo = os.path.join(os.path.dirname(os.path.abspath(args.sidecar)),
sidecar["maps"]["albedo"])
recipe["albedo"] = args.albedo or albedo
if args.relief_ratio is not None:
recipe["relief_ratio"] = args.relief_ratio
if args.patch:
patches = list(args.patch)
else:
patches = [recipe["true_scale_mm"] * step for step in SCALE_STEPS]
recipe["variants"] = [(f"g{grain_mm(p, recipe):.2f}".replace(".", "_"), p)
for p in patches]
return recipe
def grain_mm(patch_mm, recipe):
return patch_mm * recipe["grain_fraction"]
def relief_mm(patch_mm, recipe):
return round(recipe["relief_ratio"] * grain_mm(patch_mm, recipe), 3)
def scene_setup():
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
scene.unit_settings.system = "METRIC"
scene.unit_settings.length_unit = "MILLIMETERS"
scene.unit_settings.scale_length = 0.001 # one Blender unit = 1 mm
def load_height_image(path):
"""Height image plus the statistics the displacement scale depends on."""
img = bpy.data.images.load(path, check_existing=True)
img.colorspace_settings.name = "Non-Color"
width, height = img.size
buf = np.empty(width * height * 4, dtype=np.float32)
img.pixels.foreach_get(buf)
values = buf[0::4]
return img, {
"mid": float(values.mean()),
"lo": float(values.min()),
"hi": float(values.max()),
}
def rounded_cube(size_mm, fillet_mm):
if not 0.0 < fillet_mm < size_mm / 2.0:
raise SystemExit(f"fillet must be in (0, {size_mm / 2.0}) mm")
bpy.ops.mesh.primitive_cube_add(size=size_mm, location=(0, 0, 0))
obj = bpy.context.active_object
obj.name = "rice_cube"
bevel = obj.modifiers.new("bevel", "BEVEL")
bevel.width = fillet_mm
bevel.segments = BEVEL_SEGMENTS
bevel.limit_method = "NONE"
bevel.profile = 0.5
with bpy.context.temp_override(object=obj, active_object=obj):
bpy.ops.object.modifier_apply(modifier=bevel.name)
remesh = obj.modifiers.new("remesh", "REMESH")
remesh.mode = "VOXEL"
remesh.voxel_size = VOXEL_MM
remesh.use_smooth_shade = True
bpy.ops.object.shade_smooth()
return obj
class Tree:
"""Terse node-tree builder, to keep the topology of the graph legible."""
def __init__(self, name):
self.nt = bpy.data.node_groups.new(name, "GeometryNodeTree")
self.nt.interface.new_socket("Geometry", in_out="INPUT",
socket_type="NodeSocketGeometry")
self.nt.interface.new_socket("Geometry", in_out="OUTPUT",
socket_type="NodeSocketGeometry")
self.gin = self.nt.nodes.new("NodeGroupInput")
self.gout = self.nt.nodes.new("NodeGroupOutput")
self.n = 0
def new(self, kind, **props):
node = self.nt.nodes.new(kind)
node.location = ((self.n % 8) * 220, -(self.n // 8) * 260)
self.n += 1
for key, value in props.items():
setattr(node, key, value)
return node
def link(self, out_socket, in_socket):
self.nt.links.new(out_socket, in_socket)
return in_socket
def math(self, op, a, b=None):
node = self.new("ShaderNodeMath", operation=op)
self._feed(node.inputs[0], a)
if b is not None:
self._feed(node.inputs[1], b)
return node.outputs[0]
def vmath(self, op, a, b=None, scale=None):
node = self.new("ShaderNodeVectorMath", operation=op)
self._feed(node.inputs[0], a)
if b is not None:
self._feed(node.inputs[1], b)
if scale is not None:
self._feed(node.inputs["Scale"], scale)
return node.outputs["Vector"]
def _feed(self, socket, value):
if hasattr(value, "is_output"):
self.nt.links.new(value, socket)
else:
socket.default_value = value
def sample(self, image, u, v):
"""Image lookup at (u, v), returning the scalar height."""
combine = self.new("ShaderNodeCombineXYZ")
self._feed(combine.inputs["X"], u)
self._feed(combine.inputs["Y"], v)
tex = self.new("GeometryNodeImageTexture",
interpolation="Linear", extension="REPEAT")
tex.inputs["Image"].default_value = image
self.link(combine.outputs["Vector"], tex.inputs["Vector"])
sep = self.new("FunctionNodeSeparateColor")
self.link(tex.outputs["Color"], sep.inputs["Color"])
return sep.outputs["Red"]
def displace_group(name, image, stats, patch_mm, relief, sharpness):
"""Position += normal * (triplanar_height - mid) * scale.
Triplanar rather than UV: the bevels make UV texel density wildly uneven
and slice grains open at every edge. Projecting object-space position onto
the three axis planes and blending by normal keeps one continuous field.
"""
t = Tree(name)
pos = t.new("GeometryNodeInputPosition").outputs["Position"]
normal = t.new("GeometryNodeInputNormal").outputs["Normal"]
scaled = t.vmath("SCALE", pos, scale=1.0 / patch_mm)
xyz = t.new("ShaderNodeSeparateXYZ")
t.link(scaled, xyz.inputs["Vector"])
x, y, z = xyz.outputs["X"], xyz.outputs["Y"], xyz.outputs["Z"]
weights = []
heights = []
normal_xyz = t.new("ShaderNodeSeparateXYZ")
t.link(normal, normal_xyz.inputs["Vector"])
for axis, (u, v) in enumerate([(y, z), (x, z), (x, y)]):
heights.append(t.sample(image, u, v))
component = normal_xyz.outputs[("X", "Y", "Z")[axis]]
weights.append(
t.math("POWER", t.math("ABSOLUTE", component), sharpness))
total_w = t.math("ADD", weights[0], t.math("ADD", weights[1], weights[2]))
accum = t.math("MULTIPLY", weights[0], heights[0])
for w, h in zip(weights[1:], heights[1:]):
accum = t.math("ADD", accum, t.math("MULTIPLY", w, h))
blended = t.math("DIVIDE", accum, total_w)
# Scale so the texture's full range maps to the relief peak-to-valley, and
# subtract the mean so the body does not inflate.
span = stats["hi"] - stats["lo"]
offset = t.math("MULTIPLY", t.math("SUBTRACT", blended, stats["mid"]),
relief / span)
setpos = t.new("GeometryNodeSetPosition")
t.link(t.vmath("SCALE", normal, scale=offset), setpos.inputs["Offset"])
t.link(t.gin.outputs["Geometry"], setpos.inputs["Geometry"])
t.link(setpos.outputs["Geometry"], t.gout.inputs["Geometry"])
return t.nt
def apply_displacement(obj, image, stats, patch_mm, relief):
group = displace_group(f"rice_{patch_mm:.1f}_{relief:.2f}", image, stats,
patch_mm, relief, AXIS_SHARPNESS)
modifier = obj.modifiers.new("rice", "NODES")
modifier.node_group = group
def evaluated_mesh(obj):
depsgraph = bpy.context.evaluated_depsgraph_get()
return obj.evaluated_get(depsgraph).to_mesh()
def write_3mf(path, mesh, scale=1.0, chunk=200_000):
"""Minimal 3MF core 1.0 writer: zip of XML, millimetre units.
Written in chunks straight into the zip. Assembling the whole model string
first is fine at 200k triangles and several GB of text at 8M, which is where
a 160 mm cube lands.
"""
mesh.calc_loop_triangles()
verts = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
mesh.vertices.foreach_get("co", verts)
verts = (verts.reshape(-1, 3) * scale).round(5)
tris = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int32)
mesh.loop_triangles.foreach_get("vertices", tris)
tris = tris.reshape(-1, 3)
header = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<model unit="millimeter" xml:lang="en-US" '
'xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">'
"<resources>"
'<object id="1" type="model"><mesh><vertices>'
)
middle = "</vertices><triangles>"
footer = "</triangles></mesh></object></resources>" \
'<build><item objectid="1"/></build></model>'
content_types = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-'
'package.relationships+xml"/>'
'<Default Extension="model" ContentType="application/vnd.ms-package.'
'3dmanufacturing-3dmodel+xml"/>'
"</Types>"
)
rels = (
'<?xml version="1.0" encoding="UTF-8"?>\n'
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/'
'relationships"><Relationship Id="rel0" Target="/3D/3dmodel.model" '
'Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/'
'3dmodelrelationship"/></Relationships>'
)
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as z:
z.writestr("[Content_Types].xml", content_types)
z.writestr("_rels/.rels", rels)
with z.open("3D/3dmodel.model", "w") as out:
out.write(header.encode())
for start in range(0, len(verts), chunk):
out.write("".join(
f'<vertex x="{a}" y="{b}" z="{c}"/>'
for a, b, c in verts[start:start + chunk].tolist()
).encode())
out.write(middle.encode())
for start in range(0, len(tris), chunk):
out.write("".join(
f'<triangle v1="{a}" v2="{b}" v3="{c}"/>'
for a, b, c in tris[start:start + chunk].tolist()
).encode())
out.write(footer.encode())
def mesh_stats(mesh):
"""Cheap in-process sanity numbers. verify.py is the authoritative check,
run against the exported files rather than Blender's idea of them."""
mesh.calc_loop_triangles()
verts = np.empty(len(mesh.vertices) * 3, dtype=np.float64)
mesh.vertices.foreach_get("co", verts)
verts = verts.reshape(-1, 3)
return {
"vertices": len(mesh.vertices),
"triangles": len(mesh.loop_triangles),
"bbox_mm": [round(float(v), 3) for v in
(verts.max(axis=0) - verts.min(axis=0))],
"wire_edges": sum(1 for e in mesh.edges if len(e.vertices) != 2),
}
def select_only(obj):
bpy.ops.object.select_all(action="DESELECT")
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
def export(obj, name, out_dir):
mesh = evaluated_mesh(obj)
stats = mesh_stats(mesh)
select_only(obj)
stl = os.path.join(out_dir, f"rice_cube_{name}.stl")
bpy.ops.wm.stl_export(filepath=stl, ascii_format=False,
export_selected_objects=True, global_scale=1.0,
apply_modifiers=True)
three_mf = os.path.join(out_dir, f"rice_cube_{name}.3mf")
write_3mf(three_mf, mesh)
stats["stl_mb"] = round(os.path.getsize(stl) / 1e6, 2)
stats["3mf_mb"] = round(os.path.getsize(three_mf) / 1e6, 2)
return stats
def rice_material(patch_mm, albedo_path):
mat = bpy.data.materials.new("rice")
mat.use_nodes = True
nt = mat.node_tree
bsdf = nt.nodes["Principled BSDF"]
# Cosmetic: cooked rice is wet and glossy, and that specular is much of what
# makes the surface read as rice rather than as plaster. Irrelevant to print.
bsdf.inputs["Roughness"].default_value = 0.38
bsdf.inputs["Specular IOR Level"].default_value = 0.5
# World-space position / patch: the same field the displacement samples,
# so colour and relief stay registered. Generated coords would be off by
# the displacement's share of the bbox.
geo = nt.nodes.new("ShaderNodeNewGeometry")
scale = nt.nodes.new("ShaderNodeVectorMath")
scale.operation = "DIVIDE"
scale.inputs[1].default_value = (patch_mm, patch_mm, patch_mm)
nt.links.new(geo.outputs["Position"], scale.inputs[0])
color = nt.nodes.new("ShaderNodeTexImage")
color.image = bpy.data.images.load(albedo_path, check_existing=True)
color.projection = "BOX"
color.projection_blend = 0.35
nt.links.new(scale.outputs[0], color.inputs["Vector"])
nt.links.new(color.outputs["Color"], bsdf.inputs["Base Color"])
return mat
def preview_stage(obj, patch_mm, albedo_path, size_mm):
# Framing and fill light are derived from the body size, so the preview
# looks the same whether the cube is 40 mm or 160 mm.
scale = size_mm / DEFAULT_SIZE_MM
scene = bpy.context.scene
scene.render.engine = "CYCLES"
scene.cycles.device = "CPU"
scene.cycles.samples = 64
scene.render.resolution_x = 1100
scene.render.resolution_y = 900
scene.view_settings.view_transform = "AgX"
world = bpy.data.worlds.new("w")
world.use_nodes = True
bg = world.node_tree.nodes["Background"]
bg.inputs[0].default_value = (0.42, 0.45, 0.5, 1)
bg.inputs[1].default_value = 0.35
scene.world = world
obj.data.materials.clear()
obj.data.materials.append(rice_material(patch_mm, albedo_path))
# Sun rather than an area light: irradiance is independent of the scene's
# unit scale, so exposure does not have to be re-derived per variant.
bpy.ops.object.light_add(type="SUN", location=(0, 0, 200))
key = bpy.context.active_object
key.data.energy = 3.2
key.data.angle = 0.12
key.rotation_euler = (0.95, 0.12, -0.55)
bpy.ops.object.light_add(type="AREA", location=(-140 * scale, -80 * scale,
30 * scale))
fill = bpy.context.active_object
fill.data.energy = 6.0e4 * scale ** 2 # same illuminance at any size
fill.data.size = 200 * scale
fill.rotation_euler = (1.35, 0, -1.15)
# 45 deg azimuth: both visible faces foreshorten equally, so nothing reads
# as a streak. Grazing angles make grains look smeared even when the field
# is continuous.
bpy.ops.object.camera_add(location=(105 * scale, -105 * scale, 62 * scale))
cam = bpy.context.active_object
scene.camera = cam
cam.rotation_euler = (Vector((0, 0, 0)) - cam.location).to_track_quat(
"-Z", "Y").to_euler()
cam.data.lens = 100
def set_material(obj, patch_mm, albedo_path):
obj.data.materials.clear()
obj.data.materials.append(rice_material(patch_mm, albedo_path))
def render(obj, name, patch_mm, albedo_path, out_dir, size_mm, stage=False):
if stage:
preview_stage(obj, patch_mm, albedo_path, size_mm)
else:
set_material(obj, patch_mm, albedo_path)
bpy.context.scene.render.filepath = os.path.join(out_dir,
f"preview_{name}.png")
bpy.ops.render.render(write_still=True)
def main():
args = parse_args(sys.argv)
recipe = load_recipe(args)
out_dir = recipe["out"]
os.makedirs(out_dir, exist_ok=True)
scene_setup()
image, height_stats = load_height_image(recipe["height"])
print(f"[info] source {recipe['source']}: grain "
f"{recipe['grain_fraction'] * 100:.2f}% of the patch, "
f"relief ratio {recipe['relief_ratio']:.3f}")
obj = rounded_cube(recipe["size"], recipe["fillet"])
obj.modifiers["remesh"].voxel_size = recipe["voxel"]
print(f"[info] remeshed base: {mesh_stats(evaluated_mesh(obj))}")
summary = {
"cube_mm": recipe["size"],
"fillet_mm": recipe["fillet"],
"voxel_mm": recipe["voxel"],
"source": recipe["source"],
"height_map": os.path.basename(recipe["height"]),
"relief_ratio": round(recipe["relief_ratio"], 4),
"height_stats": {k: round(v, 5) for k, v in height_stats.items()},
"variants": {},
}
for index, (name, patch) in enumerate(recipe["variants"]):
relief = relief_mm(patch, recipe)
apply_displacement(obj, image, height_stats, patch, relief)
info = export(obj, name, out_dir)
info.update(patch_mm=round(patch, 3), displacement_mm=relief,
grain_mm=round(grain_mm(patch, recipe), 2))
summary["variants"][name] = info
print(f"[info] {name}: {info}")
render(obj, name, patch, recipe["albedo"], out_dir,
recipe["size"], stage=index == 0)
obj.modifiers.remove(obj.modifiers["rice"])
canonical_name, canonical_patch = recipe["variants"][0]
apply_displacement(obj, image, height_stats, canonical_patch,
relief_mm(canonical_patch, recipe))
set_material(obj, canonical_patch, recipe["albedo"])
bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_dir, "rice_cube.blend"))
with open(os.path.join(out_dir, "summary.json"), "w") as handle:
json.dump(summary, handle, indent=2)
print(f"[done] canonical variant {canonical_name}")
if __name__ == "__main__":
main()
+402
View File
@@ -0,0 +1,402 @@
"""Procedural, seamlessly tiling short-grain rice material.
python3 make_rice_texture.py
Bakes a texture set out of a 3D-ish model of a rice pile:
height (the bump map) -> 16-bit PNG, the displacement source
normal -> gradient of height, OpenGL and DirectX
ao -> horizon march over the height field
albedo -> per-grain tint darkened by AO
Seamlessness comes from the source, not from post-processing: every grain is
placed on a torus, and grains straddling an edge are wrapped into the opposite
edge by index modulo, so the height field is exactly periodic. Filters that
must not break that (blur, AO marching) wrap too.
Grains are modelled as a superellipse silhouette with an elliptical dome, plus
a slight bend along the length and a random tilt, unioned by max(). Shapes and
sizes are drawn per grain, so the pile is not a repeated tile of one grain.
"""
import json
import os
import numpy as np
from PIL import Image
from scipy import ndimage as ndi
OUT = "tex_proc"
SIZE = 2048 # texture resolution
PATCH_MM = 60.0 # real rice this square covers; sets texel density
SEED = 7
# Short-grain rice: ~5 mm long, aspect ~1.8, ~2.2 mm thick. Distributions are
# lognormal/normal around these medians.
LENGTH_MM = 5.0
LENGTH_SIGMA = 0.13 # lognormal sigma
ASPECT = 1.78 # length / width
ASPECT_SIGMA = 0.09
THICKNESS_RATIO = 0.44 # thickness / length
THICKNESS_SIGMA = 0.06
# Orientation. Pressed nigiri rice is not a shingled carpet: a good fraction of
# grains jut out end-on, which is most of what the reference photograph reads as.
FLAT_TILT_DEG = 12.0 # std dev for the grains that lie down
UPRIGHT_FRACTION = 0.34 # of grains, tilted this far out of plane
UPRIGHT_TILT_DEG = (30.0, 65.0)
# (coverage of a monolayer, base height in mm). More layers, spaced closer than
# a grain is thick, so upper grains sit on lower ones instead of forming a
# second storey: the gaps are then shallow V-crevices between grains rather than
# holes down to a floor. That is what keeps peak-to-valley near one grain
# thickness even as the pile gets deeper.
LAYERS = [(1.20, 0.00), (1.05, 0.38), (0.95, 0.76), (0.80, 1.14), (0.60, 1.50)]
PACKING = 0.42 # accepted centre spacing, fraction of semi-length
BLUR_TEXELS = 0.5 # soften union creases without erasing grain edges
AO_DIRECTIONS = 8
AO_STEPS = 40
AO_MAX_MM = 1.6
BLUR_TEXELS = 0.7 # soften the max() creases between grains
def torus_delta(delta, span):
delta = np.abs(delta)
return np.minimum(delta, span - delta)
def scatter(rng, count, min_spacing_mm):
"""Poisson-disk (blue noise) centres on a torus, so packing wraps too."""
accepted = np.empty((count, 2), dtype=np.float64)
found = 0
tries = 0
max_tries = count * 400
while found < count and tries < max_tries:
tries += 1
candidate = rng.uniform(0.0, PATCH_MM, 2)
if found:
dx = torus_delta(candidate[0] - accepted[:found, 0], PATCH_MM)
dy = torus_delta(candidate[1] - accepted[:found, 1], PATCH_MM)
if np.hypot(dx, dy).min() < min_spacing_mm:
continue
accepted[found] = candidate
found += 1
return accepted[:found]
def draw_grain(rng, centre, base_z):
"""A grain as a rotated ellipsoid: three axes and a centre height.
Modelling the body in 3D rather than as a dome plus a slope term is what
makes an upright grain possible at all -- laid flat, its footprint is the
full grain; stood on end, the footprint is its cross-section and its height
is most of a grain length, which is exactly what the reference shows.
"""
length = LENGTH_MM * rng.lognormal(0.0, LENGTH_SIGMA)
aspect = np.clip(ASPECT + rng.normal(0.0, ASPECT_SIGMA), 1.35, 2.4)
thickness = length * np.clip(
THICKNESS_RATIO + rng.normal(0.0, THICKNESS_SIGMA), 0.30, 0.55)
semi_u, semi_v, semi_w = length / 2.0, length / aspect / 2.0, thickness / 2.0
azimuth = rng.uniform(0.0, np.pi)
upright = rng.random() < UPRIGHT_FRACTION
if upright:
tilt = np.deg2rad(rng.uniform(*UPRIGHT_TILT_DEG))
else:
tilt = np.deg2rad(abs(rng.normal(0.0, FLAT_TILT_DEG)))
long_axis = np.array([np.cos(azimuth) * np.cos(tilt),
np.sin(azimuth) * np.cos(tilt),
np.sin(tilt)])
mid_axis = np.array([-np.sin(azimuth), np.cos(azimuth), 0.0])
short_axis = np.cross(long_axis, mid_axis)
# Centres sit on the layer plane, not bottoms. Seating each grain on its
# lowest point instead makes an upright grain stand a full grain-length
# proud of its layer, which compounds across layers into a spike field
# (peak-to-valley 9.5 mm for a 5 mm grain). Aligning centres is what
# compaction does, and it bounds how far a standing grain can protrude.
return {
"x": centre[0],
"y": centre[1],
"semi_u": semi_u,
"semi_v": semi_v,
"semi_w": semi_w,
"axes": (long_axis, mid_axis, short_axis),
"centre_z": base_z + rng.uniform(-0.12, 0.12),
"tilt_deg": float(np.rad2deg(tilt)),
"upright": bool(upright),
}
def rasterise(height, owner, grain, texel_mm, grain_id):
"""Union one grain's top surface into the height field, wrapping at edges.
For a vertical line through a texel, the grain's surface height is where that
line leaves the ellipsoid, which is the larger root of a quadratic: with the
local axes fixed, each local coordinate is affine in z, so the ellipsoid
equation in z is quadratic. That keeps the solve exact for any orientation
rather than approximating a tilted grain as a squashed dome.
"""
n = height.shape[0]
long_axis, mid_axis, short_axis = grain["axes"]
a, b, c = grain["semi_u"], grain["semi_v"], grain["semi_w"]
# Exact projected bounding half-extents of a rotated ellipsoid.
reach_x = np.sqrt((a * long_axis[0]) ** 2 + (b * mid_axis[0]) ** 2
+ (c * short_axis[0]) ** 2)
reach_y = np.sqrt((a * long_axis[1]) ** 2 + (b * mid_axis[1]) ** 2
+ (c * short_axis[1]) ** 2)
cx = grain["x"] / texel_mm
cy = grain["y"] / texel_mm
half_x = int(np.ceil(reach_x / texel_mm)) + 1
half_y = int(np.ceil(reach_y / texel_mm)) + 1
columns = np.arange(int(round(cx)) - half_x, int(round(cx)) + half_x + 1)
rows = np.arange(int(round(cy)) - half_y, int(round(cy)) + half_y + 1)
dx, dy = np.meshgrid((columns - cx) * texel_mm, (rows - cy) * texel_mm)
# Local coordinates as (value at z=0) + (rate per unit z).
u0 = long_axis[0] * dx + long_axis[1] * dy
v0 = mid_axis[0] * dx + mid_axis[1] * dy
w0 = short_axis[0] * dx + short_axis[1] * dy
uz, vz, wz = long_axis[2], mid_axis[2], short_axis[2]
quad_a = (uz / a) ** 2 + (vz / b) ** 2 + (wz / c) ** 2
quad_b = 2.0 * (u0 * uz / a ** 2 + v0 * vz / b ** 2 + w0 * wz / c ** 2)
quad_c = (u0 / a) ** 2 + (v0 / b) ** 2 + (w0 / c) ** 2 - 1.0
disc = quad_b ** 2 - 4.0 * quad_a * quad_c
inside = disc >= 0.0
surface = grain["centre_z"] + (-quad_b + np.sqrt(np.clip(disc, 0, None))) \
/ (2.0 * quad_a)
rows, columns = rows % n, columns % n
block = height[np.ix_(rows, columns)]
taken = inside & (surface > block)
height[np.ix_(rows, columns)] = np.where(taken, surface, block)
owner[np.ix_(rows, columns)] = np.where(taken, grain_id,
owner[np.ix_(rows, columns)])
return grain_id + 1
def place_grains(rng):
grains = []
for coverage, base_z in LAYERS:
grain_area = LENGTH_MM * (LENGTH_MM / ASPECT) * 0.8
count = int(coverage * PATCH_MM ** 2 / grain_area)
spacing = PACKING * LENGTH_MM / 2.0
for centre in scatter(rng, count, spacing):
grains.append(draw_grain(rng, centre, base_z))
return grains
FLOOR_MM = -1.0 # the un-modelled plate; must never be visible
def rasterise_grains(grains, texel_mm):
height = np.full((SIZE, SIZE), FLOOR_MM, dtype=np.float32)
owner = np.zeros((SIZE, SIZE), dtype=np.int32)
for grain_id, grain in enumerate(grains, start=1):
rasterise(height, owner, grain, texel_mm, grain_id)
return height, owner
def uncovered_fraction(height):
return float((height <= FLOOR_MM + 1e-6).mean())
def fill_gaps(height, owner, grains, rng, texel_mm, base_z=-0.35, rounds=10):
"""Drop grains into whatever is still floor.
Nominal layer coverage is a poor proxy for whether the surface is closed: an
upright grain covers a fifth of what a flat one does, so a pile with a lot of
standing grains leaves holes straight down to the plate. Filling the actual
remaining holes makes the surface closed by construction instead of by
tuning a multiplier.
"""
next_id = len(grains) + 1
for _ in range(rounds):
holes = height <= FLOOR_MM + 1e-6
if holes.mean() < 1e-5:
break
labels, count = ndi.label(holes)
if count == 0:
break
for row, column in ndi.center_of_mass(holes, labels,
np.arange(1, count + 1)):
grain = draw_grain(rng, (column * texel_mm, row * texel_mm), base_z)
rasterise(height, owner, grain, texel_mm, next_id)
grains.append(grain)
next_id += 1
return next_id
def periodicity_error(grains, texel_mm):
"""Shift every grain by a quarter patch and require a rolled copy back.
Sampling one seam line and comparing it to interior statistics is a weak
test: that quantity is heavy-tailed, and across seeds it lands anywhere
from the 4th to the 99th percentile even when the field is exactly
periodic. Translating the whole scatter on the torus and demanding the same
field, rolled, tests the property instead of sampling it.
"""
baseline, _ = rasterise_grains(grains, texel_mm)
shift_px = SIZE // 4
shift_mm = shift_px * texel_mm
moved = [dict(grain,
x=(grain["x"] + shift_mm) % PATCH_MM,
y=(grain["y"] + shift_mm) % PATCH_MM) for grain in grains]
shifted, _ = rasterise_grains(moved, texel_mm)
expected = np.roll(baseline, (shift_px, shift_px), axis=(0, 1))
return float(np.abs(shifted - expected).max())
def normals(height, texel_mm):
grad_row, grad_col = np.gradient(height, texel_mm)
# Rows increase downward, so +Y (up) is the negative row gradient.
nx = -grad_col
ny = grad_row
nz = np.ones_like(height)
length = np.sqrt(nx ** 2 + ny ** 2 + nz ** 2)
return np.stack([nx / length, ny / length, nz / length], axis=-1)
def ambient_occlusion(height, texel_mm):
"""Horizon-based: march each compass direction, keep the steepest slope."""
visibility = np.zeros_like(height)
step = AO_MAX_MM / AO_STEPS / texel_mm
for index in range(AO_DIRECTIONS):
angle = 2 * np.pi * index / AO_DIRECTIONS
dx, dy = np.cos(angle), np.sin(angle)
steepest = np.zeros_like(height)
for k in range(1, AO_STEPS + 1):
distance = k * step * texel_mm
sampled = np.roll(height, (int(round(dy * k * step)),
int(round(dx * k * step))), axis=(0, 1))
steepest = np.maximum(steepest, (sampled - height) / distance)
# 1 - sin(atan(slope)) : sky fraction still open along this direction
visibility += 1.0 - steepest / np.sqrt(1.0 + steepest ** 2)
return visibility / AO_DIRECTIONS
def normals_to_rgb(n, directx=False):
if directx:
n = n * np.array([1.0, -1.0, 1.0])
return np.clip((n * 0.5 + 0.5) * 255.0 + 0.5, 0, 255).astype(np.uint8)
def albedo_map(height, owner, ao, grains, rng):
"""Per-grain tint, so the pile is not one flat colour."""
tints = np.random.default_rng(1234).uniform(
-1.0, 1.0, size=len(grains) + 2)
per_grain = tints[np.clip(owner, 0, len(tints) - 1)]
variation = 1.0 + 0.05 * per_grain
# Milled rice is not pure white; the tips read slightly warmer.
base = np.array([0.90, 0.885, 0.845])
shade = (0.55 + 0.45 * ao) * variation
rgb = base[None, None, :] * shade[..., None]
return np.clip(rgb * 255.0 + 0.5, 0, 255).astype(np.uint8)
def seam_report(height):
"""Is the field actually periodic, or does it just look tiled?
A ratio against the mean interior step is too crude -- the seam is a single
line of pixels, so it has sampling noise of its own. Ranking the seam step
within the distribution of every interior step says whether it is
statistically ordinary, which is the question that matters.
"""
col_steps = np.abs(np.diff(height, axis=1)).mean(axis=0)
row_steps = np.abs(np.diff(height, axis=0)).mean(axis=1)
seam_cols = float(np.abs(height[:, 0] - height[:, -1]).mean())
seam_rows = float(np.abs(height[0, :] - height[-1, :]).mean())
col_pct = float((col_steps < seam_cols).mean() * 100.0)
row_pct = float((row_steps < seam_rows).mean() * 100.0)
return {
"seam_cols_mm": round(seam_cols, 5),
"interior_col_step_mm": round(float(col_steps.mean()), 5),
"seam_cols_percentile": round(col_pct, 1),
"seam_rows_mm": round(seam_rows, 5),
"interior_row_step_mm": round(float(row_steps.mean()), 5),
"seam_rows_percentile": round(row_pct, 1),
}
def save_grey16(path, array, lo, hi):
scaled = np.clip((array - lo) / (hi - lo), 0.0, 1.0)
Image.fromarray((scaled * 65535.0 + 0.5).astype(np.uint16)).save(path)
def save_grey8(path, array):
Image.fromarray(np.clip(array * 255.0 + 0.5, 0, 255).astype(np.uint8)).save(path)
def main():
os.makedirs(OUT, exist_ok=True)
rng = np.random.default_rng(SEED)
texel_mm = PATCH_MM / SIZE
grains = place_grains(rng)
height, owner = rasterise_grains(grains, texel_mm)
fill_gaps(height, owner, grains, rng, texel_mm)
unfilled = uncovered_fraction(height)
# Wrap-mode blur: softening the union creases must not create a seam.
height = ndi.gaussian_filter(height, BLUR_TEXELS, mode="wrap")
periodicity_mm = periodicity_error(grains, texel_mm)
lo, hi = float(height.min()), float(height.max())
n = normals(height, texel_mm)
ao = ambient_occlusion(height, texel_mm)
albedo = albedo_map(height, owner, ao, grains, rng)
save_grey16(os.path.join(OUT, "rice_height_16bit.png"), height, lo, hi)
save_grey8(os.path.join(OUT, "rice_ao_8bit.png"), ao)
Image.fromarray(normals_to_rgb(n)).save(
os.path.join(OUT, "rice_normal_opengl.png"))
Image.fromarray(normals_to_rgb(n, directx=True)).save(
os.path.join(OUT, "rice_normal_directx.png"))
Image.fromarray(albedo).save(os.path.join(OUT, "rice_albedo.png"))
report = seam_report(height)
summary = {
"patch_mm": PATCH_MM,
"texture_px": SIZE,
"texel_mm": round(texel_mm, 6),
"grain_mm": LENGTH_MM,
"grain_fraction_of_patch": round(LENGTH_MM / PATCH_MM, 6),
"grains": len(grains),
"layers": len(LAYERS),
"upright_fraction": round(
sum(g["upright"] for g in grains) / max(len(grains), 1), 3),
"uncovered_fraction": round(unfilled, 6),
"median_tilt_deg": round(float(np.median([g["tilt_deg"] for g in grains])), 1),
"height_mm": [round(lo, 3), round(hi, 3)],
"relief_mm": round(hi - lo, 3),
"seed": SEED,
"tileable": periodicity_mm < 1e-6,
"periodicity_error_mm": periodicity_mm,
"seam": report,
"maps": {
"height": "rice_height_16bit.png",
"normal_opengl": "rice_normal_opengl.png",
"normal_directx": "rice_normal_directx.png",
"ao": "rice_ao_8bit.png",
"albedo": "rice_albedo.png",
},
}
with open(os.path.join(OUT, "rice_maps.json"), "w") as f:
json.dump(summary, f, indent=2)
upright = sum(g["upright"] for g in grains)
print(f"[info] {len(grains)} grains in {len(LAYERS)} layers over "
f"{PATCH_MM:.0f} mm; {upright} upright "
f"({upright / len(grains) * 100:.0f}%)")
print(f"[info] uncovered floor after gap fill: {unfilled * 100:.4f}%")
print(f"[info] relief {hi - lo:.2f} mm, texel {texel_mm * 1000:.2f} um")
print(f"[info] periodicity error {periodicity_mm:.2e} mm (0 = exactly tiles)")
print(f"[info] seam diagnostic: {json.dumps(report)}")
print("[done]")
if __name__ == "__main__":
main()
+60
View File
@@ -0,0 +1,60 @@
"""Measure the physical scale of the rice scan from the height map.
python3 measure_scan_scale.py
Everything about apparent grain size depends on how much real rice the texture
covers, and ambientCG does not publish that. A spectral peak is useless here:
the radial average is dominated by pile-scale undulation (~240 px). Counting
grain crowns and measuring their second moments gives the grain scale directly.
"""
import numpy as np
from PIL import Image
from scipy import ndimage as ndi
HEIGHT = "tex/food_0015_height_2k.png"
TEX_PX = 2048.0
# Long-grain white rice, typical figure used to convert pixels to millimetres.
GRAIN_LENGTH_MM = 6.5
def measure(path=HEIGHT):
height = np.array(Image.open(path)).astype(np.float64)
# Remove pile-scale undulation so individual grains dominate.
flattened = height - ndi.gaussian_filter(height, 40)
crowns = flattened > np.percentile(flattened, 62)
labels, count = ndi.label(ndi.binary_opening(crowns, np.ones((5, 5))))
lengths, widths = [], []
for index, window in enumerate(ndi.find_objects(labels)):
if window is None:
continue
mask = labels[window] == index + 1
ys, xs = np.nonzero(mask)
if len(ys) < 300:
continue
values = np.sort(np.linalg.eigvalsh(np.cov(np.vstack([ys, xs]))))
if values[0] <= 0 or values[1] <= 0:
continue
lengths.append(4.0 * np.sqrt(values[1])) # 2 sigma each side
widths.append(4.0 * np.sqrt(values[0]))
return (count, len(lengths), float(np.median(lengths)),
float(np.median(widths)))
def main():
count, kept, length_px, width_px = measure()
print(f"grain crowns: {kept} used of {count} components")
print(f"median crown length {length_px:.1f} px, width {width_px:.1f} px, "
f"aspect {length_px / width_px:.2f}")
mm_per_px = GRAIN_LENGTH_MM / length_px
print(f"if a grain is {GRAIN_LENGTH_MM} mm long, the map spans "
f"{TEX_PX * mm_per_px:.0f} mm of rice")
print(f"grain as a fraction of the patch: {length_px / TEX_PX:.4f}")
print(f"true-scale patch for a 40 mm face: {GRAIN_LENGTH_MM * TEX_PX / length_px:.0f} mm")
if __name__ == "__main__":
main()
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 942 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 MiB

+60
View File
@@ -0,0 +1,60 @@
{
"cube_mm": 40.0,
"bevel_mm": 4.0,
"voxel_mm": 0.3,
"source": "tex_proc",
"height_map": "rice_height_16bit.png",
"relief_ratio": 0.8956,
"height_stats": {
"mid": 0.56913,
"lo": 0.0,
"hi": 1.0
},
"variants": {
"g5_00": {
"vertices": 105320,
"triangles": 210636,
"bbox_mm": [
43.836,
43.836,
43.836
],
"wire_edges": 0,
"stl_mb": 10.53,
"3mf_mb": 2.02,
"patch_mm": 60.0,
"displacement_mm": 4.478,
"grain_mm": 5.0
},
"g3_00": {
"vertices": 105320,
"triangles": 210636,
"bbox_mm": [
42.268,
42.268,
42.268
],
"wire_edges": 0,
"stl_mb": 10.53,
"3mf_mb": 2.01,
"patch_mm": 36.0,
"displacement_mm": 2.687,
"grain_mm": 3.0
},
"g1_75": {
"vertices": 105320,
"triangles": 210636,
"bbox_mm": [
41.326,
41.326,
41.326
],
"wire_edges": 0,
"stl_mb": 10.53,
"3mf_mb": 2.0,
"patch_mm": 21.0,
"displacement_mm": 1.567,
"grain_mm": 1.75
}
}
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

+104
View File
@@ -0,0 +1,104 @@
{
"rice_cube_g1_75.3mf": {
"triangles": 210636,
"welded_vertices": 105320,
"boundary_edges": 0,
"nonmanifold_edges": 0,
"misoriented_edges": 0,
"degenerate_triangles": 0,
"signed_volume_mm3": 62397.3,
"area_mm2": 11161.3,
"bbox_mm": [
41.33,
41.33,
41.33
],
"unit": "millimeter",
"file_mb": 2.0
},
"rice_cube_g1_75.stl": {
"triangles": 210636,
"welded_vertices": 105320,
"boundary_edges": 0,
"nonmanifold_edges": 0,
"misoriented_edges": 0,
"degenerate_triangles": 0,
"signed_volume_mm3": 62397.3,
"area_mm2": 11161.3,
"bbox_mm": [
41.33,
41.33,
41.33
],
"unit": "millimetre (implied)",
"file_mb": 10.53
},
"rice_cube_g3_00.3mf": {
"triangles": 210636,
"welded_vertices": 105320,
"boundary_edges": 0,
"nonmanifold_edges": 0,
"misoriented_edges": 0,
"degenerate_triangles": 0,
"signed_volume_mm3": 62389.6,
"area_mm2": 11842.4,
"bbox_mm": [
42.27,
42.27,
42.27
],
"unit": "millimeter",
"file_mb": 2.01
},
"rice_cube_g3_00.stl": {
"triangles": 210636,
"welded_vertices": 105320,
"boundary_edges": 0,
"nonmanifold_edges": 0,
"misoriented_edges": 0,
"degenerate_triangles": 0,
"signed_volume_mm3": 62389.6,
"area_mm2": 11842.4,
"bbox_mm": [
42.27,
42.27,
42.27
],
"unit": "millimetre (implied)",
"file_mb": 10.53
},
"rice_cube_g5_00.3mf": {
"triangles": 210636,
"welded_vertices": 105320,
"boundary_edges": 0,
"nonmanifold_edges": 0,
"misoriented_edges": 0,
"degenerate_triangles": 0,
"signed_volume_mm3": 62445.3,
"area_mm2": 12065.9,
"bbox_mm": [
43.84,
43.84,
43.84
],
"unit": "millimeter",
"file_mb": 2.02
},
"rice_cube_g5_00.stl": {
"triangles": 210636,
"welded_vertices": 105320,
"boundary_edges": 0,
"nonmanifold_edges": 0,
"misoriented_edges": 0,
"degenerate_triangles": 0,
"signed_volume_mm3": 62445.3,
"area_mm2": 12065.9,
"bbox_mm": [
43.84,
43.84,
43.84
],
"unit": "millimetre (implied)",
"file_mb": 10.53
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+30
View File
@@ -0,0 +1,30 @@
{
"cube_mm": 160.0,
"fillet_mm": 8.0,
"voxel_mm": 0.2,
"source": "tex_proc",
"height_map": "rice_height_16bit.png",
"relief_ratio": 0.6,
"height_stats": {
"mid": 0.56913,
"lo": 0.0,
"hi": 1.0
},
"variants": {
"g5_00": {
"vertices": 3840152,
"triangles": 7680300,
"bbox_mm": [
162.578,
162.578,
162.578
],
"wire_edges": 0,
"stl_mb": 384.02,
"3mf_mb": 69.62,
"patch_mm": 60.0,
"displacement_mm": 3.0,
"grain_mm": 5.0
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"rice_cube_g5_00.3mf": {
"triangles": 7680300,
"welded_vertices": 3840152,
"boundary_edges": 0,
"nonmanifold_edges": 0,
"misoriented_edges": 0,
"degenerate_triangles": 0,
"signed_volume_mm3": 4070163.5,
"area_mm2": 180389.2,
"bbox_mm": [
162.58,
162.58,
162.58
],
"unit": "millimeter",
"file_mb": 69.62
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+30
View File
@@ -0,0 +1,30 @@
{
"cube_mm": 40.0,
"fillet_mm": 4.0,
"voxel_mm": 0.2,
"source": "tex_proc",
"height_map": "rice_height_16bit.png",
"relief_ratio": 0.6,
"height_stats": {
"mid": 0.56913,
"lo": 0.0,
"hi": 1.0
},
"variants": {
"g5_00": {
"vertices": 239768,
"triangles": 479532,
"bbox_mm": [
42.578,
42.578,
42.578
],
"wire_edges": 0,
"stl_mb": 23.98,
"3mf_mb": 4.48,
"patch_mm": 60.0,
"displacement_mm": 3.0,
"grain_mm": 5.0
}
}
}
+19
View File
@@ -0,0 +1,19 @@
{
"rice_cube_g5_00.3mf": {
"triangles": 479532,
"welded_vertices": 239768,
"boundary_edges": 0,
"nonmanifold_edges": 0,
"misoriented_edges": 0,
"degenerate_triangles": 0,
"signed_volume_mm3": 62413.8,
"area_mm2": 10670.7,
"bbox_mm": [
42.58,
42.58,
42.58
],
"unit": "millimeter",
"file_mb": 4.48
}
}
+70
View File
@@ -0,0 +1,70 @@
"""Contact sheet + fake-lit preview for the procedural rice maps.
python3 preview_maps.py [tex_proc]
The lit panel shades the baked normal map with a directional light and the AO
map, which is the fastest way to judge whether the bake is right without a full
render.
"""
import os
import sys
import numpy as np
from PIL import Image, ImageDraw, ImageFont
FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
PANEL = 440
def load(directory):
def grey(name):
return np.array(Image.open(os.path.join(directory, name))).astype(np.float32)
height = grey("rice_height_16bit.png") / 65535.0
normal = grey("rice_normal_opengl.png").reshape(*height.shape, 3) / 255.0 * 2 - 1
ao = grey("rice_ao_8bit.png") / 255.0
albedo = np.array(Image.open(os.path.join(directory, "rice_albedo.png"))
).astype(np.float32) / 255.0
return height, normal, ao, albedo
def shade(normal, ao, albedo, azimuth=-40.0, elevation=35.0):
az, el = np.deg2rad(azimuth), np.deg2rad(elevation)
light = np.array([np.cos(el) * np.cos(az), np.cos(el) * np.sin(az), np.sin(el)])
lambert = np.clip((normal * light).sum(-1), 0.0, 1.0)
return np.clip(albedo * ((0.10 + 0.90 * lambert) * (0.45 + 0.55 * ao))[..., None],
0.0, 1.0)
def to_tile(array):
if array.ndim == 2:
array = np.repeat(array[..., None], 3, axis=2)
return Image.fromarray((np.clip(array, 0, 1) * 255).astype(np.uint8)).resize(
(PANEL, PANEL), Image.LANCZOS)
def main(directory="tex_proc"):
height, normal, ao, albedo = load(directory)
lit = shade(normal, ao, albedo)
# A 2x2 repeat proves the tiling, not just the single tile.
tiled = np.tile(lit, (2, 2, 1))
panels = [("height", height), ("normal", normal * 0.5 + 0.5),
("ao", ao), ("albedo", albedo), ("lit", lit), ("2x2 lit", tiled)]
width = PANEL * len(panels) + 10 * (len(panels) + 1)
sheet = Image.new("RGB", (width, PANEL + 34), (28, 29, 31))
draw = ImageDraw.Draw(sheet)
font = ImageFont.truetype(FONT, 17)
for index, (label, data) in enumerate(panels):
x = 10 + index * (PANEL + 10)
sheet.paste(to_tile(data), (x, 30))
draw.text((x + 2, 6), label, font=font, fill=(225, 225, 225))
sheet.save(os.path.join(directory, "maps_sheet.png"))
Image.fromarray((lit * 255).astype(np.uint8)).save(
os.path.join(directory, "maps_lit.png"))
print(f"wrote {directory}/maps_sheet.png")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "tex_proc")
Executable
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# Rebuild everything .gitignore leaves out, including the committed A/B sheets.
# Order matters only in that the sheets need the runs first; the 160 mm body is
# last of the meshes because it is the only expensive one (~3 GB RSS, ~2 min).
set -euo pipefail
cd "$(dirname "$0")"
SCAN=~/Downloads/food_0015_2k_sc65C6.zip
CUBE=(blender -b --factory-startup -P make_rice_cube.py --)
PROC=(--height tex_proc/rice_height_16bit.png --sidecar tex_proc/rice_maps.json)
# 1. The scanned baseline's source: external asset, not ours.
unzip -o "$SCAN" -x "__MACOSX/*" -d tex/
# 2. Procedural map set. 14 s, deterministic from SEED in the script.
python3 make_rice_texture.py
python3 preview_maps.py
# 3. The one that was liked: 40 mm, 0.2 mm voxel, relief 0.6 x grain.
"${CUBE[@]}" "${PROC[@]}" --patch 60 --voxel 0.2 --relief-ratio 0.6 --out out_calm
# 4. The 160 mm body with 8 mm fillets: 7.68M triangles.
"${CUBE[@]}" "${PROC[@]}" --size 160 --fillet 8 --patch 60 --voxel 0.2 \
--relief-ratio 0.6 --out out_160
# 5. Baselines kept only as A/B panes.
"${CUBE[@]}" "${PROC[@]}" --patch 60 --voxel 0.3 --out out # fusing, coarse
"${CUBE[@]}" "${PROC[@]}" --patch 60 --voxel 0.2 --out out_crisp # fusing, fine
"${CUBE[@]}" --out out_scan # scanned rice
# 6. The comparison sheets that are committed.
python3 contact_sheet.py out # variant ladder
python3 compare.py --out out/fusing_ab.png \
--title "fusing: voxel 0.3 mm vs 0.2 mm (everything else identical)" \
"voxel 0.3 · 210k tris · 10.5 MB=out/preview_g5_00.png" \
"voxel 0.2 · 480k tris · 24 MB=out_crisp/preview_g5_00.png"
python3 compare.py --out out/relief_ab.png \
--title "relief A/B: 0.90 x grain (4.48 mm) vs 0.60 x grain (3.00 mm)" \
"relief 4.48 mm · ratio 0.90=out_crisp/preview_g5_00.png" \
"relief 3.00 mm · ratio 0.60=out_calm/preview_g5_00.png"
python3 compare.py --out out/size_ab.png --crop 0.36,0.26,0.70,0.68 \
--title "same rice, body scaled: 40 mm cube / 4 mm fillet vs 160 mm cube / 8 mm fillet" \
"40 mm · fillet 4 · 480k tris=out_calm/preview_g5_00.png" \
"160 mm · fillet 8 · 7.68M tris=out_160/preview_g5_00.png"
python3 compare.py --out out/scan_vs_procedural.png \
--title "rice cube — scanned vs procedural rice" \
"scanned · grain 6.5 mm=out_scan/preview_g6_50.png" \
"procedural · grain 5.0 mm=out_calm/preview_g5_00.png"
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 MiB

+35
View File
@@ -0,0 +1,35 @@
{
"patch_mm": 60.0,
"texture_px": 2048,
"texel_mm": 0.029297,
"grain_mm": 5.0,
"grain_fraction_of_patch": 0.083333,
"grains": 1568,
"layers": 5,
"upright_fraction": 0.32,
"uncovered_fraction": 0.0,
"median_tilt_deg": 13.5,
"height_mm": [
-0.312,
4.166
],
"relief_mm": 4.478,
"seed": 7,
"tileable": true,
"periodicity_error_mm": 0.0,
"seam": {
"seam_cols_mm": 0.01656,
"interior_col_step_mm": 0.01691,
"seam_cols_percentile": 50.5,
"seam_rows_mm": 0.01722,
"interior_row_step_mm": 0.01627,
"seam_rows_percentile": 65.7
},
"maps": {
"height": "rice_height_16bit.png",
"normal_opengl": "rice_normal_opengl.png",
"normal_directx": "rice_normal_directx.png",
"ao": "rice_ao_8bit.png",
"albedo": "rice_albedo.png"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 MiB

+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)