Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,9 @@ python inlayer.py --help
The console shows progress messages, per-step timings and the wall check.
If the check fails, every finding is listed with its file name (e.g.
`fig2.stl: side wall 1.40 mm (target 2.00 mm)`) and the STL is still written so
you can inspect it.
you can inspect it. A complete side or floor breakthrough, or contact between
cavities, fails the check even for targets below 0.05 mm (for example,
`-w 0.02` or `--figure-gap 0.04`).

| Exit code | Meaning |
|---|---|
Expand Down Expand Up @@ -551,8 +553,8 @@ value as a usage error before any work starts.
- **Cavities stay open:** each cavity is extruded up through the top face. With `depth_fraction = 1.0` and a negative Z offset the pocket used to close at the top — a sealed void in the print.
- **Repair only when needed:** `prepare_figure` skips `pymeshfix` when the loaded mesh is already watertight **and** consistently wound — the normal case for cleanly exported STLs. That halves the step's runtime (measured 1.99 s → 1.08 s at 82k triangles) and does not change the geometry. Watertightness alone is not a sufficient criterion: a mesh with inverted faces is watertight but would corrupt the subsequent voxel fill. When the repair does run, it keeps **every** shell of the file: pymeshfix's default drops all but the shell with the most triangles, so a miniature with a separate base used to lose the base as soon as the file had a single hole anywhere.
- **Low-poly meshes:** input meshes are voxelised by sampling each triangle in rows along its longest edge, so the cost follows the surface area. trimesh's own voxeliser subdivides until *every* edge is below `voxel_pitch / 2`, which costs (edge length / pitch)² per triangle — the long, thin triangles of CAD exports (rods, pins, profiles) took gigabytes or aborted with "max_iter exceeded". The same sampler now voxelizes the later steps too and works in batches: the tolerance offset used to be the memory peak of a run (3.8 GB for a 60 mm cube at the default settings, more than 10 GB for 100 mm) and now needs roughly an eighth of that (0.5 GB and 1.3 GB), the step itself a third of the time. Cavities can differ from earlier versions by a few hundredths of a millimetre. A figure whose voxel grid would exceed `MAX_GRID_VOXELS` (10⁹ voxels at `voxel_pitch / 2`, the finest grid in the pipeline) is refused with a message suggesting a larger pitch, instead of exhausting the machine's memory. The bound is checked wherever a grid is built — on the upload, on the rotated figure plus its clearance padding, and on every cutter — so neither a rotation nor a large Z offset slips past it.
- **Broken files:** an empty or unreadable STL is rejected with a message naming the file (in the web app: the upload, not the temporary file it is read from). So is a file whose coordinates are all NaN or infinite. The instant preview skips files without usable triangles or area with a warning and still shows the others. A flat surface with nonzero area can appear in this lightweight preview; generation rejects it if mesh repair cannot turn it into a solid.
- **Wall check:** measured exactly on the meshes (manifold3d) while `build_inlay` still has every figure's cutter: side and floor walls per figure, the wall between each pair of cavities, sealed voids and figures without a cavity. Each finding names its figure; `passes_min_wall` is true only without any finding. The tolerance is 0.05 mm (float rounding, the cylinder's chord error). The earlier voxel-based check overestimated walls by up to one pitch, ignored the walls between cavities and passed an inlay without any cavity.
- **Broken files:** an empty or unreadable STL is rejected with a message naming the file (in the web app: the upload, not the temporary file it is read from). So is a file whose coordinates are all NaN or infinite, and one without volume — a flat surface or triangles collapsed to a line cannot be closed into a solid. In the web app the instant preview skips such a file with a warning and still shows the others.
- **Wall check:** measured on the meshes (manifold3d) while `build_inlay` still has every figure's cutter: side and floor walls per figure, the wall between each pair of cavities, sealed voids and figures without a cavity. Each finding names its figure; `passes_min_wall` is true only without any finding. The tolerance is the smaller of 0.05 mm and half the respective wall or gap target, so it cannot accept a missing wall. A cylinder's conservative radial wall estimate is checked against its actual polygon side planes when it would fail. The earlier voxel-based check overestimated walls by up to one pitch, ignored the walls between cavities and passed an inlay without any cavity.

---

Expand Down
35 changes: 27 additions & 8 deletions inlayer.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ def _log(msg: str, t0: float | None = None) -> float:

# The wall check measures the real meshes (float32 inside manifold3d), not a
# voxel grid, so its tolerance only has to absorb rounding and the cylinder's
# chord error (< 0.02 mm at ~1 mm segments).
# chord error (< 0.02 mm at ~1 mm segments), capped at half each target.
WALL_TOLERANCE_MM: Final[float] = 0.05

# Below this a clipped cutter counts as empty (boolean slivers, not pockets)
Expand Down Expand Up @@ -819,16 +819,31 @@ def _wall_check(

Each figure's cutter (cavity plus its recesses) is clipped to the box;
for axis-parallel walls the thinnest point of a pocket is exactly its
bounds' distance to the box face, for the cylinder the farthest vertex
(a convex function peaks at a vertex). Walls between two pockets come
from manifold3d's min_gap. Findings name the figure (index) they belong
bounds' distance to the box face. For cylinders, a radial lower bound
suffices unless it fails; then the prism's actual side planes decide.
Walls between two pockets come from manifold3d's min_gap.
Findings name the figure (index) they belong
to - the old voxel check overestimated walls by up to a pitch, ignored
the walls between cavities and passed an inlay without any cavity.
"""
wall, gap = config.wall_thickness, config.effective_figure_gap
tol = WALL_TOLERANCE_MM
# Rounding must never erase a positive wall or gap target.
min_wall = wall - min(WALL_TOLERANCE_MM, wall / 2)
min_gap = gap - min(WALL_TOLERANCE_MM, gap / 2)
bx = np.array(box.bounding_box()) # x0, y0, z0, x1, y1, z1
centre = (bx[:2] + bx[3:5]) / 2
side_planes = []
if apothem is not None:
mesh = box.to_mesh()
vertices = np.asarray(mesh.vert_properties[:, :3], dtype=float)
centre = vertices[:, :2].mean(axis=0)
triangles = vertices[mesh.tri_verts]
normals = np.cross(triangles[:, 1] - triangles[:, 0], triangles[:, 2] - triangles[:, 0])
vertical = normals[:, 2] == 0
side_normals = normals[vertical, :2]
side_normals /= np.linalg.norm(side_normals, axis=1, keepdims=True)
side_distances = np.einsum("ij,ij->i", side_normals, triangles[vertical, 0, :2])
side_planes = list(zip(side_normals, side_distances))
violations: list[dict] = []
outer: list[float] = []

Expand All @@ -851,13 +866,17 @@ def flag(kind: str, figure: int | None, measured: float, target: float,
if apothem is not None:
xy = clip.to_mesh().vert_properties[:, :2]
side = apothem - float(np.linalg.norm(xy - centre, axis=1).max())
if side < min_wall:
# Near polygon corners the radial bound can be negative for an intact wall.
side = min(float(distance - (xy @ normal).max())
for normal, distance in side_planes)
else:
side = float(min(bb[0] - bx[0], bx[3] - bb[3], bb[1] - bx[1], bx[4] - bb[4]))
floor = float(bb[2] - bx[2])
outer += [side, floor]
if side < wall - tol:
if side < min_wall:
flag("side", i, side, wall)
if floor < wall - tol:
if floor < min_wall:
flag("floor", i, floor, wall)

for i, a in enumerate(bounds):
Expand All @@ -869,7 +888,7 @@ def flag(kind: str, figure: int | None, measured: float, target: float,
flag("merged", i, 0.0, gap, j)
else:
measured = clips[i].min_gap(clips[j], gap)
if measured < gap - tol:
if measured < min_gap:
flag("inner", i, measured, gap, j)

# An enclosed void is a separate shell with negative volume
Expand Down
111 changes: 111 additions & 0 deletions tests/test_wall_thickness.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

from __future__ import annotations

import math

import pytest
import trimesh
from manifold3d import Manifold
Expand Down Expand Up @@ -137,6 +139,91 @@ def test_violating_indices_follow_the_findings(self, dilated_cube):
assert inlay.metadata["violating_indices"] == [1]


class TestSmallTargets:
@pytest.mark.parametrize("kind,offset", [
("side", (0.1, 0.0, 0.0)),
("floor", (0.0, 0.0, -0.1)),
])
def test_outer_breakthrough_is_a_finding(self, dilated_cube, tmp_path, kind, offset):
"""A target below the rounding tolerance must still reject an open wall."""
cfg = Config(voxel_pitch=1.0, decimate_faces=1000, wall_thickness=0.02)
inlay, *_ = _build([dilated_cube], cfg, individual_offsets=[offset])
path = tmp_path / "inlay.stl"
inlay.export(path)
exported = trimesh.load_mesh(path)
assert gp.outer_walls(exported, *exported.extents)[kind] <= 0.0011
assert (kind, 0) in _kinds(inlay)
assert inlay.metadata["wall_check"]["passes_min_wall"] is False
assert inlay.metadata["wall_check"]["min_wall_mm"] == pytest.approx(0.0, abs=1e-5)

@pytest.mark.parametrize("flag,value,kind", [
("--offset-x", "0.1", "side"),
("--offset-z", "-0.1", "floor"),
])
def test_cli_returns_three_for_exported_breakthrough(
self, cube_stl_path, tmp_path, flag, value, kind,
):
path = tmp_path / "inlay.stl"
code = inlayer.main([
"-i", cube_stl_path, "-o", str(path), "-w", "0.02", "-vp", "1",
"--decimate-faces", "1000", flag, value,
])
exported = trimesh.load_mesh(path)
assert gp.outer_walls(exported, *exported.extents)[kind] <= 0.0011
assert code == inlayer.EXIT_CHECK_FAILED == 3

def test_touching_pockets_are_a_finding(self, dilated_cube, tmp_path):
"""Face contact merges the exported cavities without positive overlap volume."""
cfg = Config(voxel_pitch=1.0, decimate_faces=1000,
figure_gap=0.04, layout_style="horizontal")
inlay, *_ = _build([dilated_cube, dilated_cube.copy()], cfg,
individual_offsets=[(0.0, 0.0, 0.0), (-0.04, 0.0, 0.0)])
path = tmp_path / "inlay.stl"
inlay.export(path)
exported = trimesh.load_mesh(path)
assert len(gp.cavities(exported, *exported.extents)) == 1
check = inlay.metadata["wall_check"]
assert check["passes_min_wall"] is False
(finding,) = check["violations"]
assert finding["kind"] in {"inner", "merged"}
assert {finding["figure"], finding["other"]} == {0, 1}
assert finding["measured_mm"] == pytest.approx(0.0, abs=1e-5)
assert check["min_wall_mm"] == pytest.approx(0.0, abs=1e-5)

@pytest.mark.parametrize("offset,measured,passes", [(-0.03, 0.01, False), (-0.01, 0.03, True)])
def test_small_gap_tolerance_preserves_half_the_target(
self, dilated_cube, tmp_path, offset, measured, passes,
):
cfg = Config(voxel_pitch=1.0, decimate_faces=1000,
figure_gap=0.04, layout_style="horizontal")
inlay, *_ = _build([dilated_cube, dilated_cube.copy()], cfg,
individual_offsets=[(0.0, 0.0, 0.0), (offset, 0.0, 0.0)])
path = tmp_path / "inlay.stl"
inlay.export(path)
exported = trimesh.load_mesh(path)
assert len(gp.cavities(exported, *exported.extents)) == 2
assert gp.inner_gap(exported, *exported.extents) == pytest.approx(measured, abs=1e-4)
assert inlay.metadata["wall_check"]["passes_min_wall"] is passes
if not passes:
assert _kinds(inlay) == [("inner", 0)]

@pytest.mark.parametrize("wall,offset,side", [(0.02, 0.0, 0.02), (2.0, 0.04, 1.96)])
def test_positive_walls_and_gap_still_pass(self, dilated_cube, tmp_path, wall, offset, side):
"""Keep valid tiny targets and the normal rounding allowance usable."""
cfg = Config(voxel_pitch=1.0, decimate_faces=1000, wall_thickness=wall,
figure_gap=0.04, layout_style="horizontal")
inlay, *_ = _build([dilated_cube, dilated_cube.copy()], cfg,
individual_offsets=[(offset, 0.0, 0.0)] * 2)
path = tmp_path / "inlay.stl"
inlay.export(path)
exported = trimesh.load_mesh(path)
assert len(gp.cavities(exported, *exported.extents)) == 2
assert gp.inner_gap(exported, *exported.extents) == pytest.approx(0.04, abs=1e-4)
assert gp.outer_walls(exported, *exported.extents)["side"] == pytest.approx(side, abs=1e-4)
assert inlay.metadata["wall_check"]["passes_min_wall"] is True
assert _kinds(inlay) == []


class TestCylinder:
def _cfg(self):
return Config(voxel_pitch=1.0, decimate_faces=1000, box_shape="cylinder")
Expand All @@ -145,6 +232,30 @@ def test_centred_figure_passes(self, dilated_cube):
inlay, *_ = _build([dilated_cube], self._cfg())
assert inlay.metadata["wall_check"]["passes_min_wall"] is True

@pytest.mark.parametrize("sections", [64, 65])
@pytest.mark.parametrize("margin", [0.01, 0.0, -0.01])
def test_tiny_walls_at_prism_vertex(self, tmp_path, sections, margin):
"""Distinguish intact walls from contact and breaches at even and odd rims."""
box = Manifold.cylinder(10.0, 10.0, circular_segments=sections).translate((0.0, 0.0, -10.0))
cutter = Manifold.cube((1.0, 0.01, 5.0)).translate((9.0 - margin, -0.005, -2.0))
inlay = box - cutter
cfg = Config(box_shape="cylinder", wall_thickness=0.005)
check = inlayer._wall_check(box, [cutter], inlay, cfg,
apothem=10.0 * math.cos(math.pi / sections))
path = tmp_path / "inlay.stl"
inlayer._to_trimesh(inlay).export(path)
exported = trimesh.load_mesh(path)
hits = gp.to_manifold(exported).ray_cast((12.0, 0.0, -1.0), (-12.0, 0.0, -1.0))
if margin > 0:
assert len(hits) == 4
assert hits[0].position[0] - hits[1].position[0] == pytest.approx(margin, abs=1e-5)
assert check["passes_min_wall"] is True
assert check["violations"] == []
else:
assert len(hits) == 2
assert check["passes_min_wall"] is False
assert [(v["kind"], v["figure"]) for v in check["violations"]] == [("side", 0)]

def test_radial_wall_is_measured(self, dilated_cube):
"""An off-centre figure cuts into the mantle: the check reports the
real radial wall (the voxel check reported 0.50 for a breakthrough)."""
Expand Down
Loading