partforge 0.121.1 → 0.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/docs/AUTHORING-PARTS.md +164 -3
  2. package/docs/KERNEL-CONTRACT.md +10 -0
  3. package/package.json +3 -1
  4. package/src/app-materials.js +23 -0
  5. package/src/framework/app.css +16 -1
  6. package/src/framework/cutaway.js +12 -0
  7. package/src/framework/geometry/blend-surfaces.js +256 -0
  8. package/src/framework/geometry/creased-normals.js +121 -7
  9. package/src/framework/geometry/manifold-backend.js +56 -15
  10. package/src/framework/geometry/mesh-fillet.js +55 -5
  11. package/src/framework/geometry/threemf.js +32 -3
  12. package/src/framework/jobs.js +2 -1
  13. package/src/framework/lint/index.js +2 -1
  14. package/src/framework/lint/rules-materials.js +56 -0
  15. package/src/framework/materials/assets/SOURCES.md +90 -0
  16. package/src/framework/materials/assets/env-outdoor.jpg +0 -0
  17. package/src/framework/materials/assets/env-print-bed.jpg +0 -0
  18. package/src/framework/materials/assets/env-studio.jpg +0 -0
  19. package/src/framework/materials/assets/env-workshop.jpg +0 -0
  20. package/src/framework/materials/assets/ground-concrete-normal.jpg +0 -0
  21. package/src/framework/materials/assets/ground-concrete-rough.jpg +0 -0
  22. package/src/framework/materials/assets/ground-concrete.jpg +0 -0
  23. package/src/framework/materials/assets/ground-maple-color.jpg +0 -0
  24. package/src/framework/materials/assets/ground-maple-normal.jpg +0 -0
  25. package/src/framework/materials/assets/ground-paper-normal.jpg +0 -0
  26. package/src/framework/materials/assets/ground-paper-rough.jpg +0 -0
  27. package/src/framework/materials/assets/ground-paper.jpg +0 -0
  28. package/src/framework/materials/assets/ground-pei-rough.jpg +0 -0
  29. package/src/framework/materials/assets/ground-pei.jpg +0 -0
  30. package/src/framework/materials/assets/pattern-carbon.jpg +0 -0
  31. package/src/framework/materials/assets/pattern-oak-color.jpg +0 -0
  32. package/src/framework/materials/assets/pattern-oak-normal.jpg +0 -0
  33. package/src/framework/materials/assets/pattern-oak-rough.jpg +0 -0
  34. package/src/framework/materials/assets/pattern-walnut-color.jpg +0 -0
  35. package/src/framework/materials/assets/pattern-walnut-normal.jpg +0 -0
  36. package/src/framework/materials/assets/pattern-walnut-rough.jpg +0 -0
  37. package/src/framework/materials/assets.js +39 -0
  38. package/src/framework/materials/contact-shadow.js +155 -0
  39. package/src/framework/materials/environment.js +157 -0
  40. package/src/framework/materials/environments.js +82 -0
  41. package/src/framework/materials/patterns.js +243 -0
  42. package/src/framework/materials/physical.js +88 -0
  43. package/src/framework/materials/presets.js +89 -0
  44. package/src/framework/materials/print-bed.js +169 -0
  45. package/src/framework/materials/print-frame.js +18 -0
  46. package/src/framework/materials/resolve.js +117 -0
  47. package/src/framework/materials/tonemap-readback.js +36 -0
  48. package/src/framework/materials/uv.js +42 -0
  49. package/src/framework/mount.js +121 -4
  50. package/src/framework/realistic-controls.js +78 -0
  51. package/src/framework/selection/feature-highlight.js +3 -0
  52. package/src/framework/view-state.js +27 -1
  53. package/src/framework/viewer.js +623 -34
  54. package/src/materials-worker.js +3 -0
  55. package/src/parts/bracket.js +2 -1
  56. package/src/parts/hinged-box.js +3 -1
  57. package/src/parts/material-swatches.js +40 -0
  58. package/src/parts/planter.js +2 -1
  59. package/src/parts/propeller.js +2 -1
  60. package/src/parts/scott-label.js +3 -2
  61. package/src/parts/screw.js +2 -1
  62. package/types/index.d.ts +48 -3
  63. package/types/part.d.ts +15 -2
@@ -69,7 +69,7 @@ A part is a default-exported object. Full shape (optional fields marked `?`):
69
69
 
70
70
  ```js
71
71
  export default {
72
- meta: { title, units, background? }, // title string; units e.g. "mm"; background = 0xRRGGBB scene colour
72
+ meta: { title, units, background?, environment? }, // title string; units e.g. "mm"; background = 0xRRGGBB scene colour
73
73
  parameters, // the control-panel schema (array of sections — see below)
74
74
  defaults, // flat { paramKey: value } — seeds params + control values
75
75
  fonts?, // { name: source } — or (p) => ({ name: source }) when a control drives the typeface
@@ -83,7 +83,7 @@ export default {
83
83
  place?: (solid, { view, purpose, p, d }) => Solid, // optional reposition; default identity
84
84
  views, // string[] — which views show this sub-part
85
85
  enabled?: (p) => boolean, // optional — gate a conditional sub-part
86
- display?: { color?, opacity? }, // optional viewer-only override (0xRRGGBB / 0..1) — e.g. a reference/ghost part
86
+ display?: { color?, opacity?, material?, …overrides }, // viewer-only appearance — see "Materials and appearance"
87
87
  export?: { name }, // filename/object name on export; defaults to the key
88
88
  reference?: string, // name of a declared import — measure() computes a deviation fact against it (see below)
89
89
  },
@@ -294,6 +294,97 @@ and asks for the existing positional view argument
294
294
 
295
295
  ---
296
296
 
297
+ ## Materials and appearance
298
+
299
+ A sub-part's `display` block says how it LOOKS. Appearance never changes
300
+ geometry, exports (other than 3MF colour, below), `measure` or `verify`, and a
301
+ mistake in it never fails a build — lint warns and the viewer falls back.
302
+
303
+ ```js
304
+ parts: {
305
+ body: { build: …, display: { material: "anodized-aluminum", color: 0xb3261e } },
306
+ knob: { build: …, display: { material: "abs-plastic", color: 0x111111, roughness: 0.25 } },
307
+ gasket: { build: …, display: { material: "rubber" } },
308
+ },
309
+ meta: { title: "…", units: "mm", environment: "studio" },
310
+ ```
311
+
312
+ - `material` — a preset id from the table below. Without one the sub-part keeps
313
+ the default look.
314
+ - `color` — the base colour (`0xRRGGBB`). With a preset it is the TINT. Presets
315
+ marked tintable are normally coloured this way (anodizing, plastic, paint);
316
+ the others have an intrinsic colour (brass) but still accept one.
317
+ - Overrides — each clamped to its range: `roughness` (0–1), `metalness` (0–1),
318
+ `clearcoat` (0–1), `clearcoatRoughness` (0–1), `anisotropy` (0–1), `textureScale` (0.01–1000).
319
+ Transmission, index of refraction, sheen and iridescence come only from a preset.
320
+ - `opacity` — unchanged: a ghost stays a ghost and casts no shadow.
321
+ - **One material per sub-part.** Something that needs two finishes (a knurled
322
+ grip in rubber on an aluminium body) is two sub-parts.
323
+
324
+ **Where it shows.** The CAD view (with feature lines) shows each material's
325
+ colour, flattened so dark materials stay readable. **Realistic** mode — the
326
+ viewer's toggle — shows the full material under environment lighting, with a
327
+ ground and soft shadow and no feature lines. The part never moves when the
328
+ mode changes.
329
+
330
+ **3D-print layer lines** (`pla-print`, `petg-print`) run perpendicular to the
331
+ **export** pose's +Z — the way the part will be printed, not the way it is
332
+ displayed. If the lines run the wrong way, fix the export pose with `place()`
333
+ (`purpose: "export"`), not the material. Wood, carbon fibre and SLS grain are
334
+ fixed to the sub-part, so they never slide when the camera or an animation
335
+ moves.
336
+
337
+ **`textureScale` is millimetres, and what it measures depends on the preset's
338
+ pattern** — so a value copied from one preset family is wrong on another (0.2
339
+ on oak shrinks the grain to a 0.2 mm tile, i.e. invisible noise):
340
+
341
+ | Pattern | Presets | `textureScale` means | Default |
342
+ | --- | --- | --- | --- |
343
+ | layer lines | `pla-print`, `petg-print` | layer height | 0.2 |
344
+ | SLS grain | `nylon-sls` | grain size | 0.15 |
345
+ | wood | `oak`, `walnut` | size of one texture tile (the grain repeats every this many mm) | 250 (`oak`), 400 (`walnut`) |
346
+ | carbon weave | `carbon-fiber` | size of one texture tile | 48 |
347
+
348
+ Presets without a pattern ignore it.
349
+
350
+ **3MF export** carries each sub-part's colour (its `color`, else its preset's
351
+ colour), so a multi-colour print opens in a slicer already split and coloured.
352
+ A part with no `color` or `material` exports exactly as before.
353
+
354
+ | Preset | Name | Tintable | Use |
355
+ | --- | --- | --- | --- |
356
+ | `machined-aluminum` | Machined aluminium | — | Bare CNC-milled aluminium, fine tool marks, satin sheen. |
357
+ | `brushed-aluminum` | Brushed aluminium | — | Directionally brushed aluminium panels and enclosures. |
358
+ | `anodized-aluminum` | Anodized aluminium | yes | Dyed anodized aluminium; tint with `color` (e.g. red, black, blue). |
359
+ | `bead-blasted-aluminum` | Bead-blasted aluminium | — | Matte, even-textured aluminium (laptop-shell finish). |
360
+ | `brushed-stainless` | Brushed stainless steel | — | Brushed 304 stainless: kitchen, marine and fastener hardware. |
361
+ | `polished-chrome` | Polished chrome | — | Mirror chrome plating; shows the environment strongly. |
362
+ | `black-oxide-steel` | Black-oxide steel | — | Blackened steel tooling and fasteners with a slight oily sheen. |
363
+ | `cast-iron` | Cast iron | — | Raw sand-cast iron: dark, rough and matte. |
364
+ | `titanium` | Titanium | — | Bare titanium: slightly warm grey, satin. |
365
+ | `brass` | Brass | — | Yellow brass fittings and decorative hardware. |
366
+ | `copper` | Copper | — | Bare copper: busbars, heat sinks, decorative parts. |
367
+ | `bronze` | Bronze | — | Cast bronze bushings and sculpture. |
368
+ | `powder-coat` | Powder coat | yes | Durable textured paint over metal; tint with `color`. |
369
+ | `painted-metal` | Painted metal | yes | Glossy enamel or automotive-style paint; tint with `color`. |
370
+ | `pla-print` | PLA print | yes | FDM-printed PLA with visible layer lines; tint with `color`. |
371
+ | `petg-print` | PETG print | yes | FDM-printed PETG: glossier than PLA, visible layers; tint with `color`. |
372
+ | `resin-print` | Resin print | yes | SLA/MSLA resin print: smooth, faintly waxy; tint with `color`. |
373
+ | `nylon-sls` | Nylon SLS | yes | Powder-bed nylon: matte, grainy, usually white or dyed black. |
374
+ | `abs-plastic` | ABS plastic | yes | Injection-moulded ABS housings and knobs; tint with `color`. |
375
+ | `clear-acrylic` | Clear acrylic | yes | Transparent PMMA/polycarbonate windows and covers; tint for coloured acrylic. |
376
+ | `rubber` | Rubber | yes | Matte elastomer: gaskets, feet, grips; tint with `color`. |
377
+ | `oak` | Oak | — | Light oak with open grain. |
378
+ | `walnut` | Walnut | — | Dark oiled walnut. |
379
+ | `carbon-fiber` | Carbon fibre | — | 2x2 twill carbon fibre under clear coat. |
380
+
381
+ **Environments** (`meta.environment`, default `studio`; viewers can switch):
382
+ `studio` (neutral soft boxes, paper sweep), `workshop` (warm interior, unfinished
383
+ maple table), `print-bed` (a dim, hard-lit enclosure over a standard-size PEI build plate (180, 220, 256 or 350 mm) marked with its size), `outdoor` (overcast sky,
384
+ concrete).
385
+
386
+ ---
387
+
297
388
  ## Geometry: the kernel / `Solid` API
298
389
 
299
390
  `build` receives a backend-agnostic `kernel` (`k`). It returns and combines `Solid`
@@ -2498,7 +2589,7 @@ stylesheet). `mount` looks up these element IDs:
2498
2589
  | `#part` | view-tab bar — leave the div **empty**; `mount` generates one button per entry in `part.views` and opens the resolved default (see the "Which view the viewer opens on" rule above) |
2499
2590
  | `#download-step` / `#download` / `#download-3mf` | STEP / STL / 3MF export buttons |
2500
2591
  | `#status`, `#busy`, `#phase` | status line + busy overlay |
2501
- | `#viewbar` with `#annotate` / `#measure` / `#cutaway` / `#reframe` / `#theme` | optional viewer controls (omit any you don't want) |
2592
+ | `#viewbar` with `#annotate` / `#measure` / `#cutaway` / `#reframe` / `#realistic` / `#environment` / `#theme` | optional viewer controls (omit any you don't want) |
2502
2593
  | `#panel` | the full-height controls rail (`class="pf-rail"`); programmatic hosts pass `elements.rail` instead |
2503
2594
  | `#rail-toggle` | optional — collapses/restores the rail; resolved the same way as `#reframe`/`#theme`. A sibling of `#viewbar`, not a child of it: give it `class="pf-float-rail-toggle"` and it floats at the stage's top right |
2504
2595
 
@@ -2506,6 +2597,17 @@ Copy `demo.html` and change the title, the panel heading, and the `<script src>`
2506
2597
  workers are spawned from your one worker entry (`name` = `"manifold"` for preview/STL/3MF,
2507
2598
  `"occt"` for STEP — handled for you).
2508
2599
 
2600
+ **`#realistic` (a `<button>`) / `#environment` (an empty `<select>`) are the
2601
+ realistic-mode viewbar controls**, resolved by id or as `elements.chrome.realistic`
2602
+ / `elements.chrome.environment`. Both optional and independent: supply `#realistic`
2603
+ alone for a bare toggle, or add `#environment` too and `mount` fills it with the
2604
+ part's available environments (see "Materials and appearance" above) and keeps it
2605
+ in sync — hidden while the view is in CAD mode, showing the environment in effect
2606
+ once realistic lands. Omit either and drive `runtime.renderMode` /
2607
+ `runtime.environment` from your own UI instead (see below). Both preferences
2608
+ persist across reloads the same way the theme does, and are carried in
2609
+ `viewerState` (below), which outranks what is stored.
2610
+
2509
2611
  **`#reframe` is supported but no longer shipped.** The framework's own pages dropped
2510
2612
  the button on 2026-08-20: clicking a face, edge or corner on the view cube reframes
2511
2613
  too, so a separate control was one more thing in a crowded bottom-right corner. The
@@ -2660,6 +2762,58 @@ them, and the sketch that gets sent is misaligned, not merely mis-labelled.
2660
2762
  Deliberately unguarded, the same way it's always been free to call
2661
2763
  `setCameraState` during Sketch.
2662
2764
 
2765
+ ### `runtime.renderMode`, `runtime.environment`, `runtime.renderViews`, `runtime.declaresMaterials`
2766
+
2767
+ For an embedder driving realistic mode from its own UI instead of (or in
2768
+ addition to) the `#realistic` / `#environment` viewbar controls above:
2769
+
2770
+ - `runtime.renderMode` — `{ get(), set(mode), onChange(cb) }` where `mode` is
2771
+ `"cad"` or `"realistic"`. `set()` resolves to the mode actually in effect —
2772
+ `"cad"` if the realistic environment's assets fail to load — and
2773
+ `onChange` receives `{ mode, busy, error }` so a host can show its own
2774
+ loading/error state. Same shape as `runtime.projection`. It drives the live
2775
+ view, and `runtime.captureCurrent()` follows it by default (a "capture from
2776
+ viewer" captures what the user sees). It never changes what an agent sees:
2777
+ `runtime.captureViews()` is always CAD, in either live mode, and a
2778
+ realistic agent render is only ever an explicit
2779
+ `renderViews(…, { renderMode: "realistic" })`.
2780
+ - `runtime.captureCurrent({ renderMode })` — pins the showcase capture's look
2781
+ instead of following the live view. `"cad"` always works. `"realistic"` from
2782
+ a CAD view works only once the current environment's assets have loaded
2783
+ (the call is synchronous and can't wait for them); before that it falls
2784
+ back to the live look. Use `renderViews` when realistic must be guaranteed.
2785
+ - `runtime.environment` — `{ get(), set(id), onChange(cb), list() }` for the
2786
+ realistic environment (`"studio"` | `"workshop"` | `"print-bed"` |
2787
+ `"outdoor"`, per "Materials and appearance" above). `list()` returns every
2788
+ environment as `[{ id, label }]`, for building your own picker. `set()`
2789
+ resolves to the id actually in effect; a failed switch while realistic is
2790
+ showing reverts to the environment still on screen, and `onChange` hears the
2791
+ revert too.
2792
+ - `runtime.declaresMaterials` — `true` when any sub-part names a
2793
+ `display.material`. A part with none still supports realistic mode (every
2794
+ sub-part just renders under the library's `default` look), so use this to
2795
+ decide whether to surface the realistic toggle at all, not whether it works.
2796
+ - `await runtime.renderViews(viewNames, { renderMode? })` — the appearance-aware
2797
+ sibling of `runtime.captureViews` (canonical angles, framed to the visible
2798
+ assembly, grid hidden): `{ renderMode: "cad" }` (the default) is exactly
2799
+ `captureViews` — CAD whatever the live view shows — and `{ renderMode: "realistic" }` borrows the realistic look
2800
+ for the capture — waiting on the chosen environment's assets — **without**
2801
+ switching the live view. Rejects if the realistic assets fail to load.
2802
+
2803
+ Both preferences round-trip through `mount()`'s `viewerState`: a
2804
+ previous mount's `runtime.getViewerState()` carries `viewerState.renderMode`
2805
+ (`"cad"` or `"realistic"`) and, only when the viewer's environment was
2806
+ actually CHOSEN rather than merely defaulted from `meta.environment`,
2807
+ `viewerState.environment`. `renderMode` reports the mode the user is **headed
2808
+ for**, not only the one on screen: a realistic restore or switch that's still
2809
+ loading reports `"realistic"`, so a host that remounts on every edit (as an
2810
+ embedder applying edits by remounting typically does) doesn't drop the
2811
+ in-flight choice — a load that ultimately fails still settles back to
2812
+ `"cad"`. Pass `viewerState` back into the next `mount()` call to resume both
2813
+ where the previous mount left them; omit it on a first mount and the viewer
2814
+ restores its own persisted choice instead, the same way it does for the
2815
+ camera and projection.
2816
+
2663
2817
  ### The annotation payload's camera block
2664
2818
 
2665
2819
  `onAnnotationSend(payload)` receives a `camera` block in two frames — `world`
@@ -3121,6 +3275,13 @@ motion — translate/rotate — never a reshape) (both errors). An untrusted pro
3121
3275
  nothing either way and stays silent, matching `animation-track-rebuilds`'s own
3122
3276
  trust handling.
3123
3277
 
3278
+ **Appearance** (all warnings) — `unknown-material` (a `display.material` the
3279
+ library does not know; the viewer shows the default look), `unknown-environment`
3280
+ (`meta.environment` not known; realistic mode uses `studio`),
3281
+ `material-key-unknown` (a `display` key that is not colour, opacity, material
3282
+ or one of the six overrides; ignored), `material-override-clamped` (an override
3283
+ outside its range, or not a number; clamped).
3284
+
3124
3285
  **Geometry imports** — `import-unknown-name` (a build calls `k.import` with a
3125
3286
  name the part's `imports` field doesn't declare — this throws at build time;
3126
3287
  lint reaches it in microseconds instead), `import-mesh-on-occt` (a declared
@@ -406,6 +406,16 @@ are present:
406
406
  - `normals` — per-vertex shading normals. Smooth within one surface, hard
407
407
  across boolean-cut seams. OCCT ships analytic B-rep normals; Manifold ships
408
408
  the policy-aware crease pass (`src/framework/geometry/creased-normals.js`).
409
+ Fillet bands are analytic on both backends: each Manifold fillet tool registers
410
+ its rolling-ball spine (`src/framework/geometry/blend-surfaces.js` — a line,
411
+ circle, point or planar path), and the crease pass shades any smooth group the
412
+ band takes part in with that exact normal, so a band meets the faces it is
413
+ tangent to with matching normals (within 0.1° of the true surface on a
414
+ filleted box — `test/mesh-fillet-normals.test.js`, with its OCCT twin in
415
+ `test/occt-shading.test.js`). The spine follows the band through later
416
+ booleans, poses and `label()`. Planar-path bands (rims of extrusions) shade
417
+ the smooth curve their polyline samples; at a line-to-arc junction in that
418
+ polyline the normal is off by up to half an arc segment, as before.
409
419
  - `edges` — flat feature-edge segment pairs (6 floats per segment). An EMPTY
410
420
  array means "this solid has no feature edges"; it is not "unknown". OCCT
411
421
  ships true B-rep edges with tangent edges (fillet blends, seam lines)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "partforge",
3
- "version": "0.121.1",
3
+ "version": "0.123.0",
4
4
  "description": "Turn a declarative part definition into a parametric-CAD web app (three.js + Manifold/Replicad). Requires a Vite-based consumer.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -132,11 +132,13 @@
132
132
  "@eslint/js": "^10.0.1",
133
133
  "@fontsource-variable/geist": "^5.3.0",
134
134
  "@fontsource-variable/geist-mono": "^5.3.0",
135
+ "@monogrid/gainmap-js": "^3.4.0",
135
136
  "eslint": "^10.10.0",
136
137
  "globals": "^17.12.0",
137
138
  "happy-dom": "^20.10.6",
138
139
  "knip": "^6.35.1",
139
140
  "playwright": "^1.49.0",
141
+ "sharp": "^0.35.4",
140
142
  "typescript": "^5.9.3",
141
143
  "vite": "^8.0.16",
142
144
  "vitest": "^4.1.9"
@@ -0,0 +1,23 @@
1
+ // Self-hosted Geist + Geist Mono for the dev demos, so a standalone forge looks
2
+ // like the product. Dev-only: --pf-sans/--pf-mono fall back to system stacks for
3
+ // any consumer that doesn't load them (spec §2.2).
4
+ import "@fontsource-variable/geist";
5
+ import "@fontsource-variable/geist-mono";
6
+ import materialSwatchesPart from "./parts/material-swatches.js";
7
+ import { mount } from "./framework/index.js";
8
+
9
+ // Dev-only contact sheet app for the material library (parts/material-swatches.js).
10
+ // Identical wiring to app.js — the only thing that differs per part is which
11
+ // definition you import and which worker entry you point at. `npm run dev`, then
12
+ // open /materials.html. Not part of the production build — check materials.html
13
+ // by eye after any preset or shader change (see AGENTS.md "Architecture").
14
+ // Dev-only: the handle is stashed on window so scripts/check-app.mjs can drive
15
+ // the embedding contract (runtime.captureCurrent) the way an embedder would.
16
+ window.__pfRuntime = mount(materialSwatchesPart, {
17
+ createWorker: (name) =>
18
+ new Worker(new URL("./materials-worker.js", import.meta.url), { type: "module", name }),
19
+ onAnnotationSend: (payload) => {
20
+ window.__pfLastAnnotation = payload;
21
+ console.log("annotation payload", payload);
22
+ },
23
+ });
@@ -476,7 +476,7 @@ button.action:disabled { opacity: .5; cursor: default; }
476
476
  /* keyboard focus ring shared across the panel's interactive controls */
477
477
  .seg button:focus-visible, select.preset:focus-visible, .dl-row button:focus-visible,
478
478
  button.action:focus-visible, .adv-toggle:focus-visible, .sec-title:focus-visible, #viewbar button:focus-visible,
479
- .pf-view-select:focus-visible,
479
+ #viewbar select:focus-visible, .pf-view-select:focus-visible,
480
480
  .pf-viewcube-toggle:focus-visible, .pf-float-rail-toggle:focus-visible, .pf-sketch-toolbar button:focus-visible {
481
481
  outline: none;
482
482
  box-shadow: 0 0 0 3px color-mix(in oklab, var(--pf-accent) 35%, transparent);
@@ -595,6 +595,21 @@ button.action:focus-visible, .adv-toggle:focus-visible, .sec-title:focus-visible
595
595
  #viewbar button:disabled:hover { color: var(--pf-muted-2); background: transparent; }
596
596
  #viewbar button:hover { color: var(--pf-text); background: var(--pf-surface-2); }
597
597
  #viewbar button.on { background: var(--pf-accent); color: var(--pf-on-accent); }
598
+ /* Realistic view (realistic-controls.js). The toggle is an ordinary viewbar
599
+ button that pulses while its environment loads; the environment picker is a
600
+ native <select> — the accessible choice on a phone — dressed as a viewbar
601
+ button, shown only while realistic. Keyed on `#viewbar select` rather than
602
+ an id so a host's own element in the pill gets the same look. */
603
+ #viewbar button[data-busy] { animation: pf-busy-pulse .8s ease-in-out infinite alternate; }
604
+ @keyframes pf-busy-pulse { from { opacity: 1; } to { opacity: .45; } }
605
+ @media (prefers-reduced-motion: reduce) { #viewbar button[data-busy] { animation: none; opacity: .6; } }
606
+ #viewbar select {
607
+ height: 34px; padding: 0 8px; border: 0; border-radius: var(--pf-radius-control);
608
+ background: transparent; color: var(--pf-muted-2); cursor: pointer;
609
+ font: inherit; font-size: 13px;
610
+ }
611
+ #viewbar select:hover { color: var(--pf-text); background: var(--pf-surface-2); }
612
+ #viewbar select[hidden] { display: none; }
598
613
 
599
614
  /* Sketch-mode toolbar: the #viewbar pill idiom, top-centre, owning the mode
600
615
  while the viewbar itself is hidden (mount toggles both).
@@ -493,6 +493,17 @@ export function createCutaway({
493
493
  return true;
494
494
  }
495
495
 
496
+ // Swap one sub-part's SOURCE material (realistic mode). The render set
497
+ // re-derives its clipped clone and cap colour from it and reassigns
498
+ // mesh.material for the current enabled state.
499
+ function refreshSubpartMaterial(name, meshMaterial) {
500
+ if (disposed) return false;
501
+ const entry = renderSets.get(name);
502
+ if (!entry) return false;
503
+ entry.renderSet.refreshSourceMaterial(meshMaterial);
504
+ return true;
505
+ }
506
+
496
507
  // Per-frame maintenance while the cutaway is on: the gizmo rescales for the
497
508
  // camera, and every visible section re-slices its outline if anything it
498
509
  // depends on moved. Both are cheap no-ops when nothing changed.
@@ -581,6 +592,7 @@ export function createCutaway({
581
592
  setVisible,
582
593
  setEnabled,
583
594
  resyncSubpart,
595
+ refreshSubpartMaterial,
584
596
  reset,
585
597
  flip,
586
598
  getState,
@@ -0,0 +1,256 @@
1
+ // Analytic blend-surface descriptors — the exact normal field of a mesh fillet band.
2
+ //
3
+ // A mesh fillet (mesh-fillet.js) is a boolean against tool solids whose curved wall
4
+ // IS the rolling-ball surface. Facet-averaged vertex normals on that wall are only
5
+ // approximately right: one-sided at the band's tangent boundary (half a facet off
6
+ // the face it is tangent to — ~1-2° at preview density), biased by the boolean's
7
+ // uneven fans, and on a coarse corner sphere several degrees off the edge cylinders
8
+ // it meets. Every blend surface is a canal surface — the envelope of a ball rolling
9
+ // along a SPINE — so its exact normal at any point is the direction from the nearest
10
+ // spine point, and the spine is known when the tool is built. A descriptor records
11
+ // that spine:
12
+ //
13
+ // { kind: "line", p, d } straight edge → cylinder (prism tools)
14
+ // { kind: "circle", c, a, R } arc edge → torus (revolve / pivot tools); R may
15
+ // be 0 (a sphere about c)
16
+ // { kind: "point", c } sphere (corner patches)
17
+ // { kind: "path", pts, closed, dirs, f, kf, kd }
18
+ // planar polyline edge (planar sweep tools): pts is
19
+ // the swept path, f its face normal, dirs[i] the
20
+ // in-plane wall-side direction at vertex i, and the
21
+ // ball centre sits at kf·f + kd·dir off the edge
22
+ //
23
+ // A path's polyline usually STANDS FOR a smooth curve (a circle's rim, an outline's
24
+ // rounded corner): its per-segment cylinders would shade faceted around the curve,
25
+ // while the facet average this replaces blurred those joints smooth. So the path
26
+ // normal is Phong-style: the in-plane direction is interpolated between the vertex
27
+ // directions (each the bisector of its two segments), giving the normal of the
28
+ // smooth canal surface the polyline samples — exact on a straight stretch, and on
29
+ // a sampled curve exact at the samples and continuous between them.
30
+ //
31
+ // The normal is sign-free here (a spine direction); the caller orients it against
32
+ // the facet, which also makes one descriptor serve cutters and fillers alike.
33
+ //
34
+ // Descriptors are registered per Manifold originalID in the tool's ORIGINAL frame
35
+ // (the inverse of the run's runTransform at registration), and evaluated per output
36
+ // run through that run's transform — so they follow every later translate, rotate,
37
+ // boolean and re-stamp that carries runTransform along (Manifold does, verified).
38
+ // Pure module: no DOM, no node:, no three.
39
+
40
+ const EPS = 1e-12;
41
+
42
+ // --- 3x4 column-major affine helpers (Manifold's runTransform layout) -------------
43
+ export function affineAt(rt, run) {
44
+ const o = run * 12;
45
+ return [rt[o], rt[o + 1], rt[o + 2], rt[o + 3], rt[o + 4], rt[o + 5],
46
+ rt[o + 6], rt[o + 7], rt[o + 8], rt[o + 9], rt[o + 10], rt[o + 11]];
47
+ }
48
+ export const IDENTITY = Object.freeze([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
49
+ const applyPt = (M, p) => [
50
+ M[0] * p[0] + M[3] * p[1] + M[6] * p[2] + M[9],
51
+ M[1] * p[0] + M[4] * p[1] + M[7] * p[2] + M[10],
52
+ M[2] * p[0] + M[5] * p[1] + M[8] * p[2] + M[11],
53
+ ];
54
+ const applyDir = (M, d) => [
55
+ M[0] * d[0] + M[3] * d[1] + M[6] * d[2],
56
+ M[1] * d[0] + M[4] * d[1] + M[7] * d[2],
57
+ M[2] * d[0] + M[5] * d[1] + M[8] * d[2],
58
+ ];
59
+ // Inverse of an affine; null when singular.
60
+ export function invertAffine(M) {
61
+ const [a, b, c, d, e, f, g, h, i] = M; // columns (a,b,c) (d,e,f) (g,h,i)
62
+ const A = e * i - f * h, B = f * g - d * i, C = d * h - e * g;
63
+ const det = a * A + b * B + c * C;
64
+ if (!(Math.abs(det) > EPS)) return null;
65
+ const s = 1 / det;
66
+ // rows of the inverse = cofactor columns; stored column-major
67
+ const L = [
68
+ A * s, (c * h - b * i) * s, (b * f - c * e) * s,
69
+ B * s, (a * i - c * g) * s, (c * d - a * f) * s,
70
+ C * s, (b * g - a * h) * s, (a * e - b * d) * s,
71
+ ];
72
+ const t = applyDir([...L, 0, 0, 0], [M[9], M[10], M[11]]);
73
+ return [...L, -t[0], -t[1], -t[2]];
74
+ }
75
+
76
+ const norm = (v) => {
77
+ const l = Math.hypot(v[0], v[1], v[2]);
78
+ return l > EPS ? [v[0] / l, v[1] / l, v[2] / l] : null;
79
+ };
80
+
81
+ // Map a descriptor through an affine (used with the INVERSE run transform at
82
+ // registration: world → original frame). Exact for rigid maps, which is what the
83
+ // tools are posed with; radii scale by the map's mean axis stretch.
84
+ export function mapSurface(desc, M) {
85
+ switch (desc.kind) {
86
+ case "line": return { kind: "line", p: applyPt(M, desc.p), d: norm(applyDir(M, desc.d)) ?? desc.d };
87
+ case "point": return { kind: "point", c: applyPt(M, desc.c) };
88
+ case "circle": {
89
+ const s = Math.cbrt(Math.abs(
90
+ M[0] * (M[4] * M[8] - M[5] * M[7]) - M[3] * (M[1] * M[8] - M[2] * M[7]) + M[6] * (M[1] * M[5] - M[2] * M[4])));
91
+ return { kind: "circle", c: applyPt(M, desc.c), a: norm(applyDir(M, desc.a)) ?? desc.a, R: desc.R * s };
92
+ }
93
+ case "path": {
94
+ const s = Math.cbrt(Math.abs(
95
+ M[0] * (M[4] * M[8] - M[5] * M[7]) - M[3] * (M[1] * M[8] - M[2] * M[7]) + M[6] * (M[1] * M[5] - M[2] * M[4])));
96
+ return { kind: "path", closed: desc.closed, pts: desc.pts.map((p) => applyPt(M, p)),
97
+ dirs: desc.dirs.map((d) => norm(applyDir(M, d)) ?? d), f: norm(applyDir(M, desc.f)) ?? desc.f,
98
+ kf: desc.kf * s, kd: desc.kd * s };
99
+ }
100
+ default: throw new Error(`blend surface: unknown kind ${desc.kind}`);
101
+ }
102
+ }
103
+
104
+ // Nearest spine point to x, in the descriptor's own frame.
105
+ function spinePoint(desc, x) {
106
+ switch (desc.kind) {
107
+ case "point": return desc.c;
108
+ case "line": {
109
+ const { p, d } = desc;
110
+ const t = (x[0] - p[0]) * d[0] + (x[1] - p[1]) * d[1] + (x[2] - p[2]) * d[2];
111
+ return [p[0] + t * d[0], p[1] + t * d[1], p[2] + t * d[2]];
112
+ }
113
+ case "circle": {
114
+ const { c, a, R } = desc;
115
+ const q = [x[0] - c[0], x[1] - c[1], x[2] - c[2]];
116
+ const t = q[0] * a[0] + q[1] * a[1] + q[2] * a[2];
117
+ const rad = norm([q[0] - t * a[0], q[1] - t * a[1], q[2] - t * a[2]]);
118
+ if (!rad) return R > 0 ? null : c; // on the axis: the normal is undefined unless the spine is a point
119
+ return [c[0] + R * rad[0], c[1] + R * rad[1], c[2] + R * rad[2]];
120
+ }
121
+ default: return null;
122
+ }
123
+ }
124
+
125
+ // Path normal (see the header): nearest edge segment i at parameter t, the in-plane
126
+ // direction lerped between its vertex directions, the ball centre offset along it,
127
+ // and the normal rebuilt from x's height above the centre (along f) and its signed
128
+ // in-plane distance across the segment.
129
+ function pathNormal(desc, x) {
130
+ const { pts, dirs, f, kf, kd } = desc;
131
+ const n = pts.length;
132
+ const { bi, bt } = nearestSegment(desc, x);
133
+ if (bi < 0) return null;
134
+ const p = pts[bi], q = pts[(bi + 1) % n], d0 = dirs[bi], d1 = dirs[(bi + 1) % n];
135
+ const dir = norm([d0[0] + (d1[0] - d0[0]) * bt, d0[1] + (d1[1] - d0[1]) * bt, d0[2] + (d1[2] - d0[2]) * bt]);
136
+ if (!dir) return null;
137
+ const e = [p[0] + (q[0] - p[0]) * bt, p[1] + (q[1] - p[1]) * bt, p[2] + (q[2] - p[2]) * bt];
138
+ const c = [e[0] + kf * f[0] + kd * dir[0], e[1] + kf * f[1] + kd * dir[1], e[2] + kf * f[2] + kd * dir[2]];
139
+ const v = [x[0] - c[0], x[1] - c[1], x[2] - c[2]];
140
+ const h = v[0] * f[0] + v[1] * f[1] + v[2] * f[2];
141
+ // signed in-plane distance across the SEGMENT (the local surface's own measure)
142
+ const segN = norm([q[0] - p[0], q[1] - p[1], q[2] - p[2]]);
143
+ const perp = segN ? norm([f[1] * segN[2] - f[2] * segN[1], f[2] * segN[0] - f[0] * segN[2], f[0] * segN[1] - f[1] * segN[0]]) : null;
144
+ if (!perp) return null;
145
+ const sgn = perp[0] * dir[0] + perp[1] * dir[1] + perp[2] * dir[2] >= 0 ? 1 : -1;
146
+ const w = sgn * (v[0] * perp[0] + v[1] * perp[1] + v[2] * perp[2]);
147
+ return norm([h * f[0] + w * dir[0], h * f[1] + w * dir[1], h * f[2] + w * dir[2]]);
148
+ }
149
+
150
+ // Nearest path segment to x (index + clamped parameter). A text rim's path runs to
151
+ // hundreds of segments and every band vertex asks, so the segments are bucketed
152
+ // once per descriptor into a uniform grid (lazily, off the enumerable fields) and
153
+ // the query widens ring by ring only until no unvisited cell can hold a closer one.
154
+ // squared distance from x to segment pq; the clamped parameter lands in segT
155
+ let segT = 0;
156
+ function segDist2(p, q, x) {
157
+ const dx = q[0] - p[0], dy = q[1] - p[1], dz = q[2] - p[2];
158
+ const dd = dx * dx + dy * dy + dz * dz;
159
+ let t = dd > EPS ? ((x[0] - p[0]) * dx + (x[1] - p[1]) * dy + (x[2] - p[2]) * dz) / dd : 0;
160
+ t = t < 0 ? 0 : t > 1 ? 1 : t;
161
+ segT = t;
162
+ return (x[0] - p[0] - t * dx) ** 2 + (x[1] - p[1] - t * dy) ** 2 + (x[2] - p[2] - t * dz) ** 2;
163
+ }
164
+ const GRID_MIN_SEGS = 16;
165
+ function segmentGrid(desc) {
166
+ let g = desc[GRID];
167
+ if (g) return g;
168
+ const { pts, closed } = desc, n = pts.length, nSeg = closed ? n : n - 1;
169
+ let total = 0;
170
+ for (let i = 0; i < nSeg; i++) { const p = pts[i], q = pts[(i + 1) % n]; total += Math.hypot(q[0] - p[0], q[1] - p[1], q[2] - p[2]); }
171
+ const h = Math.max(total / Math.max(1, nSeg), Math.abs(desc.kf) + Math.abs(desc.kd), 1e-6);
172
+ const cells = new Map();
173
+ // numeric hashed cell keys: a collision only adds candidates, each distance-checked
174
+ const key = (a, b, c) => (Math.imul(a, 73856093) ^ Math.imul(b, 19349663) ^ Math.imul(c, 83492791)) | 0;
175
+ for (let i = 0; i < nSeg; i++) {
176
+ const p = pts[i], q = pts[(i + 1) % n];
177
+ const lo = [0, 1, 2].map((a) => Math.floor(Math.min(p[a], q[a]) / h));
178
+ const hi = [0, 1, 2].map((a) => Math.floor(Math.max(p[a], q[a]) / h));
179
+ for (let a = lo[0]; a <= hi[0]; a++) for (let b = lo[1]; b <= hi[1]; b++) for (let c = lo[2]; c <= hi[2]; c++) {
180
+ const k = key(a, b, c);
181
+ const list = cells.get(k);
182
+ if (list) list.push(i); else cells.set(k, [i]);
183
+ }
184
+ }
185
+ g = { h, cells, key, nSeg, stamp: new Uint32Array(nSeg), epoch: 0 };
186
+ Object.defineProperty(desc, GRID, { value: g, enumerable: false });
187
+ return g;
188
+ }
189
+ const GRID = Symbol("segmentGrid");
190
+ function nearestSegment(desc, x) {
191
+ const { pts, closed } = desc, n = pts.length, nSeg = closed ? n : n - 1;
192
+ let bi = -1, bt = 0, bestD = Infinity;
193
+ if (nSeg < GRID_MIN_SEGS) {
194
+ for (let i = 0; i < nSeg; i++) {
195
+ const D = segDist2(pts[i], pts[(i + 1) % n], x);
196
+ if (D < bestD) { bestD = D; bi = i; bt = segT; }
197
+ }
198
+ return { bi, bt };
199
+ }
200
+ const g = segmentGrid(desc), { h, cells, key, stamp } = g;
201
+ const epoch = ++g.epoch;
202
+ const c0 = Math.floor(x[0] / h), c1 = Math.floor(x[1] / h), c2 = Math.floor(x[2] / h);
203
+ for (let ring = 0; ; ring++) {
204
+ // every cell at Chebyshev distance `ring`; its points lie ≥ (ring-1)·h away
205
+ if (bi >= 0 && (ring - 1) * h > Math.sqrt(bestD)) break;
206
+ let any = false;
207
+ for (let a = -ring; a <= ring; a++) for (let b = -ring; b <= ring; b++) for (let c = -ring; c <= ring; c++) {
208
+ if (Math.max(Math.abs(a), Math.abs(b), Math.abs(c)) !== ring) continue;
209
+ const list = cells.get(key(c0 + a, c1 + b, c2 + c));
210
+ if (!list) continue;
211
+ any = true;
212
+ for (const i of list) {
213
+ if (stamp[i] === epoch) continue;
214
+ stamp[i] = epoch;
215
+ const D = segDist2(pts[i], pts[(i + 1) % n], x);
216
+ if (D < bestD) { bestD = D; bi = i; bt = segT; }
217
+ }
218
+ }
219
+ // h ≥ the ball-centre offset, so a band point finds its segment within a ring or
220
+ // two; a point this far from the path is not on the band — scan and be done
221
+ if (!any && bi < 0 && ring >= 3) {
222
+ for (let i = 0; i < nSeg; i++) {
223
+ const D = segDist2(pts[i], pts[(i + 1) % n], x);
224
+ if (D < bestD) { bestD = D; bi = i; bt = segT; }
225
+ }
226
+ break;
227
+ }
228
+ }
229
+ return { bi, bt };
230
+ }
231
+
232
+ // Unit spine→point direction at x in the descriptor's frame, or null where undefined.
233
+ export function surfaceNormal(desc, x) {
234
+ if (desc.kind === "path") return pathNormal(desc, x);
235
+ const s = spinePoint(desc, x);
236
+ return s ? norm([x[0] - s[0], x[1] - s[1], x[2] - s[2]]) : null;
237
+ }
238
+
239
+ // Per-run evaluator for creased-normals: world-frame analytic normal at world point
240
+ // x for a run whose original-frame descriptor is `desc` and whose runTransform is M.
241
+ // Normals map by the inverse-transpose of M's linear part, so this stays exact under
242
+ // any affine a part applies after the fillet (mirrors, non-uniform scales).
243
+ export function runEvaluator(desc, M) {
244
+ const inv = invertAffine(M);
245
+ if (!inv) return null;
246
+ return (x) => {
247
+ const n0 = surfaceNormal(desc, applyPt(inv, x));
248
+ if (!n0) return null;
249
+ // (M^-1)^T n0: the inverse's COLUMNS dotted with n0
250
+ return norm([
251
+ inv[0] * n0[0] + inv[1] * n0[1] + inv[2] * n0[2],
252
+ inv[3] * n0[0] + inv[4] * n0[1] + inv[5] * n0[2],
253
+ inv[6] * n0[0] + inv[7] * n0[1] + inv[8] * n0[2],
254
+ ]);
255
+ };
256
+ }