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
9 changes: 5 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ High-signal context for OpenCode sessions in this repo.

## Testing

- A `pytest` suite lives in `tests/` (config validation, each pipeline step, `app_helpers`, end-to-end, CLI). Run with `pytest` (full suite ~70 s) or `pytest -m "not slow"` to skip subprocess/CLI tests and the finest-pitch geometry runs.
- A `pytest` suite lives in `tests/` (config validation, each pipeline step, `app_helpers`, end-to-end, CLI). Run with `pytest` (full suite ~70 s) or `pytest -m "not slow"` to skip the subprocess tests and the finest-pitch geometry runs. The CLI itself is tested in-process through `inlayer.main(argv)` and stays in the quick loop: `tests/test_pipeline.py::TestCLIWiring` holds every flag against the inlay the library builds for the matching `Config` and reads back the STL the CLI wrote. A new flag gets a row in its `WIRING` table - an exit code and a non-empty file prove nothing about what was written.
- **Never test a re-implementation of shipped code.** If a helper is hard to import, move it somewhere importable (see `app_helpers.py`) instead of copying its body into the test file — a copied test passes even when the real function is broken.
- **After every code change, run the tests.** If the suite fails, fix the regression before considering the change done.
- **Extend the suite when you add or modify behavior.** New functions, new branches, new edge cases or bug fixes must come with matching tests. Keep test docstrings and comments in English per the language convention below.
Expand All @@ -40,7 +40,7 @@ High-signal context for OpenCode sessions in this repo.

- `inlayer.py` is the pipeline library module. It exposes a frozen `Config` dataclass plus pipeline functions (`apply_euler_rotation`, `prepare_figure`, `dilate`, `build_inlay`, `wall_thickness_stats_3d`; `arrange_footprints` is the layout `build_inlay` uses). All parameters flow through `Config`.
- `app_helpers.py` holds the **Streamlit-free** helpers of the web app (`file_hash`/`bytes_hash`, `quantize_axis_value`, `resolve_selection`, `applied_figure_params`, `figure_labels`, `load_preview_mesh`, `preview_copy`, `scene_layout`, `selection_key`, plus `decimate_mesh` re-exported from `inlayer`). `app.py` imports and thinly wraps them (caching decorators, session-state lookups). Reason: `app.py` calls `st.set_page_config()` and builds the whole sidebar at import time, so it cannot be imported in tests — anything pure belongs in `app_helpers.py` so the suite tests the shipped code instead of a copy. Do not re-inline this logic into `app.py`. (`tests/test_app_render.py` does run `app.py` through Streamlit's `AppTest`, which catches render errors — but that is an integration check, not a licence to move logic back into the frontend.)
- `app.py` is a Streamlit frontend. It builds an `inlayer.Config` from the sidebar widgets and passes it into the pipeline functions (no global mutation). Its widgets start at `Config`'s defaults (`inlayer.Config.<field>`, read the way the CLI reads them), never at literals of their own: `tests/test_app_render.py` checks that both entry points start from the same values.
- `app.py` is a Streamlit frontend. It builds an `inlayer.Config` from the sidebar widgets and passes it into the pipeline functions (no global mutation). Its widgets start at `Config`'s defaults (`inlayer.Config.<field>`, read the way the CLI reads them), never at literals of their own: `tests/test_app_render.py` checks that the widgets start from `Config`'s values, `tests/test_pipeline.py::TestCLIDefaults` that the parser does. The same goes for a default quoted in a help text - pass it into the translation (`default=Config.<field>`), don't type it into `i18n.py`.
- `i18n.py` holds the **bilingual UI** (English/German). `t(key, **kwargs)` looks up `TRANSLATIONS` and fills named placeholders; unknown keys return the key itself rather than raising, so a missing string can never abort a running computation. Keys are namespaced `app.*` / `cli.*` / `pipeline.*` / `config.*` / `error.*` / `check.*` (wall-check findings, shared by CLI and app through `inlayer.describe_violation`).
- **The current language is a `ContextVar`, not a module global.** Streamlit runs each session's script in its own thread; a shared global would let one session's language selection bleed into another's. Do not "simplify" this into a plain variable.
- **`ThreadPoolExecutor` workers do not inherit ContextVars.** `_parallel_map` captures the language before submitting and re-applies it inside each worker — without that, parallel steps log in the default language. `tests/test_i18n.py` pins this behaviour *and* the assumption behind it. Any new thread pool that logs needs the same treatment.
Expand All @@ -62,6 +62,7 @@ High-signal context for OpenCode sessions in this repo.
- **`build_inlay` never rotates.** Rotations are applied in step 1 via `apply_euler_rotation` and are already baked into the meshes handed to `build_inlay`. It used to accept an `individual_rotations` argument that was silently ignored — that parameter is gone; don't reintroduce it.
- There are **two entry points:**
- CLI: `python inlayer.py [-i figure.stl] [-o inlay.stl] [-c 0.4] [--lang de] …` — `--lang` is parsed *before* the main parser is built, because argparse renders help strings at construction time; `INLAYER_LANG` is the fallback.
The CLI is `inlayer.main(argv)` (parser in `_build_parser()`) and returns its exit code; `__main__` is only `sys.exit(main())`. Keep it that way: code under `__main__` cannot be imported, so the tests could only start it as a subprocess and never looked at the STL it wrote.
- Web UI: `streamlit run app.py`

## trimesh 4.x quirk
Expand All @@ -72,7 +73,7 @@ High-signal context for OpenCode sessions in this repo.
## Algorithmic choices

- **Voxel dilation** is used for the tolerance offset (`dilate`) instead of normal-shifted surface offset. This is intentional: voxel offsetting survives cracks and non-manifold edges that vertex-normal offsets choke on.
- **Voxel inflation is compensated in `dilate`.** Marching cubes inflates surfaces: ~`voxel_pitch/2` per side in `prepare_figure` plus ~`voxel_pitch/4` in `dilate`'s own reconstruction. Measured surplus without compensation: `0.75 * voxel_pitch`, geometry-independent (cube == sphere, 2026-07). `dilate` subtracts this from the requested distance; consequence: the effective clearance cannot drop below ~`0.75 * voxel_pitch`.
- **Voxel inflation is compensated in `dilate`.** Marching cubes inflates surfaces: ~`voxel_pitch/2` per side in `prepare_figure` plus ~`voxel_pitch/4` in `dilate`'s own reconstruction. Measured surplus without compensation: `0.75 * voxel_pitch`, geometry-independent (cube == sphere, 2026-07). `dilate` subtracts this from the requested distance; consequence: the effective clearance cannot drop below ~`0.75 * voxel_pitch`. **That number describes `dilate`'s output, not the finished cavity:** `_solidify_figure` voxelizes the dilated figure once more at the full pitch, which nothing compensates. Measured on the inlay, flat walls end up 1-2 x `voxel_pitch` from the figure (0.40-0.80 mm at the defaults for a configured 0.4) and the setting takes effect in steps of `voxel_pitch / 2`; README says so. Calibrate against the finished cavity, not against `dilate`, if this is ever tightened - and no test measures it yet.
- **The dilation is (nearly) isotropic.** scipy's default element (6-neighbourhood) grows an octahedron - 2 mm of clearance along the axes left 1.5 mm on a 45° slope. `dilate` does a share of `(√3 − 1)/2` of its steps with the full 3×3×3 cube, which makes axis and space-diagonal growth equal (every direction within 0.97–1.06). The growth *along the axes* stays one voxel per step, so `_dilation_iterations`' calibration holds. There is deliberately no `binary_closing` before the dilation: dilating a closing with the same element equals dilating the input (bit for bit), it only cost time.
- **Pad voxel grids before morphological ops.** scipy's `binary_closing`/`binary_dilation` clip at array borders — without `np.pad` by the iteration count, the erosion step eats the figure's extremes (a sphere literally turns into a cube at coarse pitch). Both `prepare_figure` and `dilate` pad and then correct the grid transform for the padding offset.
- Boolean CSG runs in manifold3d, never in trimesh's default engine: `build_inlay` calls `manifold3d` directly (`_to_manifold`/`_to_trimesh`, the same float32 conversion `trimesh.boolean` uses with `engine='manifold'`), because the wall check needs the `Manifold` objects anyway.
Expand All @@ -87,5 +88,5 @@ High-signal context for OpenCode sessions in this repo.
- In `app.py`, expensive preview decimation must go through the cached `_decimated_for_viz(mesh, cache_key, face_count)` with a stable cache key, so Streamlit reruns don't re-decimate. It returns `app_helpers.preview_copy`, a geometry-only copy: under the face budget `decimate_mesh` returns its input, and the process-wide cache then held whole meshes with their metadata. The result stored in the session keeps only what the view reads (decimated inlay, placements, recesses, stats).
- **Keys of process-wide caches identify the cached object by content, never by name or size.** `st.cache_resource` is shared by every session in the process: keyed by `name:size`, a second user uploading a different `model.stl` of the same size saw the first user's model. Uploads are identified by their content hash (`content_hashes[uf.file_id]`, computed once per upload); a cached figure's key carries everything that determines it (content hash, scale, pitch, decimation, rotation) - the inlay's hash does not determine a figure.
- **Never repair with pymeshfix's defaults.** `MeshFix.repair()` defaults to `remove_smallest_components=True`, which keeps only the shell with the most triangles: a holed figure lost its separate base (or, sorted by triangle count, its body). `prepare_figure` passes `remove_smallest_components=False`.
- **Raw input meshes are voxelized through `_voxelize_surface`, never `mesh.voxelized()`.** trimesh's voxelizer subdivides until every edge is below `pitch / 2`, so its cost grows with edge length² - a low-poly CAD rod took 1.95 GB, a 250 mm bar aborted. `_voxelize_surface` samples triangles in rows and scales with area. `dilate` and `_solidify_figure` may keep `mesh.voxelized()`: they voxelize marching-cubes output with edges of about one pitch. `_check_grid_size` refuses grids above `MAX_GRID_VOXELS` before anything is allocated.
- **Every mesh is voxelized through `_voxelize_surface`, never `mesh.voxelized()`.** trimesh's voxelizer subdivides until every edge is below `pitch / 2`, so its cost grows with edge length² - a low-poly CAD rod took 1.95 GB, a 250 mm bar aborted. That is not only a problem of raw input: `dilate` voxelizes marching-cubes output at *half* the pitch, where every triangle was split into 64, and that one call was the memory peak of a whole run (3.8 GB for a 60 mm cube at the defaults, more than 10 GB for 100 mm). `_voxelize_surface` samples triangles in rows, scales with area and marks its samples in batches (`_SURFACE_SAMPLE_BATCH`), so beyond the grid itself its memory does not depend on the mesh - don't collect all samples in one array again. `_check_grid_size` refuses grids above `MAX_GRID_VOXELS` before anything is allocated - in `prepare_figure` (the upload), in `dilate` (the rotated mesh plus its padding) and in `_solidify_figure` (the cutter up to the top face). The upload's extents say nothing about a rotated figure: any new step that builds a grid needs its own call.
- **Streamlit drops a widget's state while the widget is not rendered.** Values that must survive a hidden section live in plain session keys and the widget only writes through to them (`app._select`); otherwise hiding the rotation section reset the step to 45° and a stored 350° crashed every rerun. **Streamlit 1.62 also sends a selectbox value as its label**, so after a language switch the old label matches no option: every selectbox with translated labels goes through `_select` (raw value in a plain key, labels resolved once per run, unknown values map to no label). A lenient `format_func` (`"x" if a == "x" else <y label>`) turned the stale label into the value `"left/right"` and crashed the next run.
Loading
Loading