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
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,15 +196,15 @@ The web app is a full GUI with live preview:
| Feature | Description |
|---|---|
| 🌍 **English / German** | Switch the interface language in the sidebar at any time |
| 📂 **File upload** | Upload one or **several** STL models straight from the sidebar. Without an upload, *Generate* takes a `figure.stl` from the working directory, like the CLI |
| 🪞 **Instant preview** | Uploaded figures appear in the 3D viewer immediately, rotations update live — without running the pipeline. After a run the viewer shows that result until you generate again; if settings or uploads have changed since, a warning says it is out of date |
| 📂 **File upload** | Upload one or **several** STL models straight from the sidebar. Without an upload, *Generate* takes a `figure.stl` from the working directory, like the CLI; replacing or removing that file marks an earlier result as out of date |
| 🪞 **Instant preview** | Uploaded figures appear in the 3D viewer immediately, rotations update live — without running the pipeline. This lightweight preview can show flat surfaces; *Generate* checks whether a model can form a solid. After a run the viewer shows that result until you generate again; if settings or inputs have changed since, a warning says it is out of date |
| 🧩 **Auto arrangement** | Multiple figures are placed without collisions (`compact` / `horizontal` / `vertical`) with an adjustable gap — it follows the wall thickness until you set it yourself |
| 🎚️ **Interactive parameters** | Clearance, wall thickness, insert depth and voxel resolution via sliders |
| 🎯 **Manual positioning** | Move each figure (or all of them together) in X/Y/Z inside the box, in steps of 1, 5 or 10 mm |
| 🔄 **Manual rotation** | Rotate each figure (or all of them together) about X/Y/Z, in steps of 1, 5, 10 or 45° |
| 🖐️ **Finger recesses** | Optional hemispherical cut-outs beside each figure as a removal aid (adjustable radius, axis and depth; the position along the figure is set **per figure**) |
| 🖐️ **Finger recesses** | Optional hemispherical cut-outs beside each figure as a removal aid (adjustable radius, axis and depth; the position along the figure is set **per figure**). Settings survive switching recesses off and on |
| ⚡ **Multi-threading** | Optionally process several figures in parallel across CPU cores (checkbox in the sidebar) |
| 📐 **Box overrides** | Optionally force fixed box dimensions |
| 📐 **Box overrides** | Optionally force fixed box dimensions; dimensions survive switching overrides off and on or changing the box shape |
| 🧷 **Settings per file** | Offsets, rotations and grip positions belong to each upload — two files with the same name appear as `model.stl` and `model.stl (2)` and are positioned separately; a removed file takes its settings along |
| 🔍 **Wall check** | Every wall is measured on the finished geometry — sides, floor and the walls between cavities; each finding names its figure |
| 👁️ **3D preview** | Interactive Plotly viewer (rotate, zoom, show/hide) |
Expand Down Expand Up @@ -533,7 +533,7 @@ 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, 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.
- **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.

---
Expand Down
75 changes: 59 additions & 16 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,23 @@ def log(self, msg, t0=None):
}
st.session_state["_hash_by_file_id"] = content_hashes

# The fallback file has no upload id. Hash it on every rerun so replacing or
# removing it changes the staleness snapshot just like an uploaded input.
fallback_path = inlayer.DEFAULT_INPUT
fallback_hash = None
fallback_read_error = None
if not uploaded_files and os.path.isfile(fallback_path):
try:
fallback_hash = app_helpers.file_hash(fallback_path)
except OSError as error:
# An unavailable input marks old results stale; Generate reports why.
fallback_read_error = error
input_snapshot = (
[(uf.name, content_hashes[uf.file_id]) for uf in uploaded_files]
if uploaded_files
else [(fallback_path, fallback_hash)] if fallback_hash is not None else []
)

# --- Per-figure state -------------------------------------------------------
# Deliberately right after the upload: the finger recess controls sit further
# up the sidebar than the manual offsets and already address single figures.
Expand Down Expand Up @@ -281,6 +298,21 @@ def _select(label: str, labels: dict, key: str, default, **kwargs):
)


def _persistent_number(widget, label: str, key: str, default: float, **kwargs):
"""Numeric widget whose value survives Streamlit dropping a hidden widget."""
stored_key = f"_{key}_value"
st.session_state.setdefault(stored_key, default)
if key not in st.session_state:
st.session_state[key] = st.session_state[stored_key]
value = widget(
label, key=key,
on_change=lambda: st.session_state.update({stored_key: st.session_state[key]}),
**kwargs,
)
st.session_state[stored_key] = value
return value


def _step_select(label: str, options: list[float], unit: str, step_key: str) -> float:
"""Step size of the offset or rotation sliders."""
return float(_select(label, {x: f"{int(x)}{unit}" for x in options},
Expand Down Expand Up @@ -441,29 +473,27 @@ def _figure_select(label: str, sel_key: str):
finger_recess_axis = inlayer.Config.finger_recess_axis
finger_recess_z_offset = inlayer.Config.finger_recess_z_offset
if enable_finger_recesses:
finger_radius = st.sidebar.slider(
t("app.finger.radius.label"),
finger_radius = _persistent_number(
st.sidebar.slider, t("app.finger.radius.label"), "finger_radius",
inlayer.Config.finger_radius,
min_value=5.0,
max_value=15.0,
value=inlayer.Config.finger_radius,
step=0.5,
help=t("app.finger.radius.help"),
key="finger_radius",
)
finger_recess_axis = _select(
t("app.finger.axis.label"),
{"x": t("app.finger.axis.x"), "y": t("app.finger.axis.y")}, "finger_axis",
inlayer.Config.finger_recess_axis,
help=t("app.finger.axis.help"),
)
finger_recess_z_offset = st.sidebar.slider(
t("app.finger.z_offset.label"),
finger_recess_z_offset = _persistent_number(
st.sidebar.slider, t("app.finger.z_offset.label"), "finger_z_offset",
inlayer.Config.finger_recess_z_offset,
min_value=0.0,
max_value=30.0,
value=inlayer.Config.finger_recess_z_offset,
step=0.5,
help=t("app.finger.z_offset.help"),
key="finger_z_offset",
)
# Position along the figure. Unlike radius, axis and depth this one is
# stored per figure: the best grip point follows the figure's shape, so one
Expand Down Expand Up @@ -505,11 +535,23 @@ def _figure_select(label: str, sel_key: str):
box_diameter = None
if use_custom_box:
if box_shape == "cylinder":
box_diameter = st.sidebar.number_input(t("app.box.diameter.label"), min_value=10.0, max_value=300.0, value=50.0, step=5.0, key="box_diameter")
box_diameter = _persistent_number(
st.sidebar.number_input, t("app.box.diameter.label"), "box_diameter", 50.0,
min_value=10.0, max_value=300.0, step=5.0,
)
else:
box_width = st.sidebar.number_input(t("app.box.width.label"), min_value=10.0, max_value=300.0, value=50.0, step=5.0, key="box_width")
box_depth = st.sidebar.number_input(t("app.box.depth.label"), min_value=10.0, max_value=300.0, value=50.0, step=5.0, key="box_depth")
box_height = st.sidebar.number_input(t("app.box.height.label"), min_value=5.0, max_value=200.0, value=20.0, step=2.0, key="box_height")
box_width = _persistent_number(
st.sidebar.number_input, t("app.box.width.label"), "box_width", 50.0,
min_value=10.0, max_value=300.0, step=5.0,
)
box_depth = _persistent_number(
st.sidebar.number_input, t("app.box.depth.label"), "box_depth", 50.0,
min_value=10.0, max_value=300.0, step=5.0,
)
box_height = _persistent_number(
st.sidebar.number_input, t("app.box.height.label"), "box_height", 20.0,
min_value=5.0, max_value=200.0, step=2.0,
)

st.sidebar.markdown("---")
st.sidebar.markdown(t("app.position.heading"))
Expand Down Expand Up @@ -654,7 +696,7 @@ def _params_snapshot() -> dict:
enable_parallel is left out on purpose - it only changes the runtime.
"""
return {
"files": [(uf.name, content_hashes[uf.file_id]) for uf in uploaded_files],
"files": input_snapshot,
"clearance": clearance,
"wall_thickness": wall_thickness,
"depth_fraction": depth_fraction,
Expand Down Expand Up @@ -691,7 +733,6 @@ def _params_snapshot() -> dict:
tmp_paths: list[str] = []
try:
# Input: the uploads, or the default file next to the app
fallback_path = inlayer.DEFAULT_INPUT
input_paths: list[str] = []
file_names: list[str] = []
file_hashes: list[str] = []
Expand All @@ -709,10 +750,12 @@ def _params_snapshot() -> dict:
input_paths.append(tmp_paths[-1])
file_names.append(_labels[uf.file_id])
file_hashes.append(content_hashes[uf.file_id])
elif os.path.isfile(fallback_path):
elif fallback_read_error is not None:
raise fallback_read_error
elif fallback_hash is not None:
input_paths = [fallback_path]
file_names = [fallback_path]
file_hashes = [app_helpers.file_hash(fallback_path)]
file_hashes = [fallback_hash]
else:
st.error(t("app.error.no_input", path=fallback_path))
st.stop()
Expand Down
5 changes: 3 additions & 2 deletions app_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,9 @@ def preview_copy(mesh: trimesh.Trimesh, face_count: int) -> trimesh.Trimesh:
def load_preview_mesh(data: bytes, scale: float, name: str) -> trimesh.Trimesh:
"""Loads an uploaded STL, decimated for the instant preview.

Raises ValueError naming the file if it holds no triangles (same loader as
the pipeline, so preview and run reject the same files).
Rejects unreadable files and meshes without usable triangles or area,
naming the upload. Flat surfaces can appear here; only generation repairs
the mesh and checks whether it can form a solid.
"""
mesh = inlayer.load_mesh(io.BytesIO(data), name, file_type="stl")
if scale != 1.0:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_app_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,19 @@ def test_large_mesh_is_decimated(self):
out = app_helpers.load_preview_mesh(data, 1.0, "box.stl")
assert len(out.faces) < len(sphere.faces)

@pytest.mark.parametrize("angle", [0.0, np.pi / 4])
def test_flat_surface_can_be_previewed(self, angle):
"""Preview checks usable area; generation decides whether it forms a solid."""
sheet = trimesh.Trimesh(
vertices=[[0, 0, 0], [10, 0, 0], [10, 10, 0], [0, 10, 0]],
faces=[[0, 1, 2], [0, 2, 3]],
)
sheet.apply_transform(trimesh.transformations.rotation_matrix(angle, [1, 1, 1]))
data = cast(bytes, sheet.export(file_type="stl"))
out = app_helpers.load_preview_mesh(data, 1.0, "sheet.stl")
assert len(out.faces) == 2
assert out.area == pytest.approx(100.0)

@pytest.mark.parametrize(
"data",
[b"", bytes(84), b"solid x\nendsolid x\n", bytes(range(256)) * 2,
Expand Down
Loading
Loading