fast-mesh-wasm 0.2.0 → 0.3.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 (50) hide show
  1. package/README.md +488 -1
  2. package/dist/{api-D0o2HjaU.js → api-BUy7FRx7.js} +11 -11
  3. package/dist/client-Bp9FRd70.js +2278 -0
  4. package/dist/client-m2zSdFlu.d.ts +305 -0
  5. package/dist/colormap-D_xH5hI5.js +303 -0
  6. package/dist/core-Cke_kZ2e.js +113 -0
  7. package/dist/core-D2X9GPfK.d.ts +15 -0
  8. package/dist/engine-B-ZEzR1c.js +1818 -0
  9. package/dist/mesh-B16gV3oX.d.ts +130 -0
  10. package/dist/mesh-B8pae8WA.js +428 -0
  11. package/dist/node.d.ts +3 -2
  12. package/dist/node.js +5 -4
  13. package/dist/protocol-CAUYm1gd.js +68 -0
  14. package/dist/protocol-W9R-iGl5.d.ts +293 -0
  15. package/dist/r3f.d.ts +59 -0
  16. package/dist/r3f.js +165 -0
  17. package/dist/react-CTADh3NN.js +124 -0
  18. package/dist/react.d.ts +65 -0
  19. package/dist/react.js +1 -0
  20. package/dist/scene-BG3EEyfw.js +1243 -0
  21. package/dist/scene-like-B_3qm0u6.d.ts +925 -0
  22. package/dist/snapshot-Cf6NgDl7.js +104 -0
  23. package/dist/store-D3ErV6o-.js +1379 -0
  24. package/dist/store-DNnHN33A.d.ts +285 -0
  25. package/dist/store.d.ts +61 -0
  26. package/dist/store.js +105 -0
  27. package/dist/three.d.ts +118 -0
  28. package/dist/three.js +390 -0
  29. package/dist/views-BaZqBxlX.js +189 -0
  30. package/dist/wasm/fast_mesh_wasm.d.ts +458 -0
  31. package/dist/wasm/fast_mesh_wasm.js +1150 -0
  32. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  33. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +74 -0
  34. package/dist/wasm-threads/fast_mesh_wasm.d.ts +540 -0
  35. package/dist/wasm-threads/fast_mesh_wasm.js +1513 -0
  36. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm +0 -0
  37. package/dist/wasm-threads/fast_mesh_wasm_bg.wasm.d.ts +93 -0
  38. package/dist/wasm-threads/package.json +7 -0
  39. package/dist/wasm-threads/snippets/fast-mesh-wasm-ae14781a92c2789e/inline0.js +16 -0
  40. package/dist/wasm-threads/snippets/wasm-bindgen-rayon-38edf6e439f6d70d/src/workerHelpers.js +107 -0
  41. package/dist/web.d.ts +3 -2
  42. package/dist/web.js +4 -2
  43. package/dist/worker-engine.d.ts +248 -0
  44. package/dist/worker-engine.js +1 -0
  45. package/dist/worker-entry.d.ts +1 -0
  46. package/dist/worker-entry.js +11 -0
  47. package/dist/worker.d.ts +2 -0
  48. package/dist/worker.js +1 -0
  49. package/package.json +53 -4
  50. package/dist/api-HcskOwd7.d.ts +0 -43
package/README.md CHANGED
@@ -9,6 +9,7 @@ Fast triangle mesh utilities for JavaScript and TypeScript, written in Rust and
9
9
  - Works in browsers (Vite, webpack, Next.js), Node.js and Bun
10
10
  - Installs the same way with npm, pnpm and bun. No native build step, no install scripts, zero dependencies
11
11
  - Full TypeScript types and inline docs, generated from the Rust source
12
+ - A `Scene` for interactive work: placements, queries, distance-field colouring, sections, repair and undo/redo
12
13
  - Uses the flat buffer layout of WebGL and three.js `BufferGeometry`, so data goes in and out without conversion
13
14
 
14
15
  > **Status:** early development (0.x). The API may change between minor versions.
@@ -52,7 +53,493 @@ const normals = computeVertexNormals(geometry.attributes.position.array, geometr
52
53
  geometry.setAttribute("normal", new THREE.BufferAttribute(normals, 3));
53
54
  ```
54
55
 
55
- ## API
56
+ ### three.js adapter
57
+
58
+ `fast-mesh-wasm/three` binds `Scene` meshes to `THREE.Mesh` objects that follow the scene on every `scene.commitFrame()`. It needs `three` (an optional peer dependency, `>=0.160`) and, for TypeScript, `@types/three`:
59
+
60
+ ```sh
61
+ npm install three
62
+ npm install -D @types/three
63
+ ```
64
+
65
+ ```ts
66
+ import * as THREE from "three";
67
+ import { TransformControls } from "three/addons/controls/TransformControls.js";
68
+ import { Scene } from "fast-mesh-wasm";
69
+ import { attachTransformControls, bindMesh, bindSection } from "fast-mesh-wasm/three";
70
+
71
+ const scene = new Scene();
72
+ const a = scene.addMesh(positionsA, indicesA);
73
+ const b = scene.addMesh(positionsB, indicesB);
74
+
75
+ const threeScene = new THREE.Scene();
76
+ const renderer = new THREE.WebGLRenderer();
77
+ renderer.localClippingEnabled = true; // needed for bindSection's clipping plane
78
+
79
+ const boundA = bindMesh(scene, a); // a THREE.Mesh in boundA.object
80
+ const boundB = bindMesh(scene, b, { color: 0x88aaff, opacity: 0.6 });
81
+ threeScene.add(boundA.object, boundB.object);
82
+
83
+ // Drag B with a TransformControls gizmo: one gesture is one scene drag and one undo step.
84
+ const controls = new TransformControls(camera, renderer.domElement);
85
+ controls.attach(boundB.object);
86
+ threeScene.add(controls.getHelper()); // three >= 0.169; on older three use threeScene.add(controls)
87
+ attachTransformControls(controls, scene, boundB);
88
+
89
+ // A section: contours and fill, and the bound meshes are clipped at its plane
90
+ // (the side the section normal points to stays).
91
+ const section = scene.addSection({ meshes: [a, b], plane: { origin: [0, 0, 0], normal: [0, 0, 1] } });
92
+ const boundSection = bindSection(scene, section, [boundA, boundB]);
93
+ threeScene.add(boundSection.group);
94
+
95
+ function frame() {
96
+ scene.commitFrame(); // once per animation frame, before rendering: the adapters apply the changes here
97
+ renderer.render(threeScene, camera);
98
+ requestAnimationFrame(frame);
99
+ }
100
+ requestAnimationFrame(frame);
101
+ ```
102
+
103
+ - Colouring (`scene.setColoring`) shows up as a vertex-colour attribute with no code in the app. Undo and redo move the objects through the same change stream.
104
+ - The engine's colour maps are sRGB-encoded bytes. The adapter converts them to three's linear working space as it copies them (a normalized `Uint16` colour attribute), so they look the same as in a renderer that passes the bytes through to a non-sRGB canvas.
105
+ - A material you pass to `bindMesh` is used as given and must not be shared between bound meshes (the adapter controls its `color`, `vertexColors`, `opacity`, `transparent` and `depthWrite`). With `shading: "fragment"` it also patches the material's shaders and disposes its compiled program on bind and on restore (see [Fragment shading](#fragment-shading)).
106
+ - The adapter only reads `scene.onChanges`; it never calls `takeChanges`.
107
+
108
+ #### Fragment shading
109
+
110
+ Vertex colours interpolate across each triangle, so the edge between coloured and base-coloured vertices blurs over a triangle's width. `bindMesh(scene, mesh, { shading: "fragment", edgeSoftness })` colours every pixel from the interpolated field value through the colouring's rule instead (a lookup texture and a shader chunk added with `onBeforeCompile`): range edges and colour steps, such as a contact heatmap's tolerance band, are crisp iso-lines, and at a vertex the colour equals its vertex colour. Far (`Infinity`) and NaN values never tint their neighbours.
111
+
112
+ - `edgeSoftness` (distance units, default 0 for a hard edge) widens those edges into a blend; `bound.setEdgeSoftness(width)` changes it with no recompile. Both throw `INVALID_ARGUMENT` unless the width is a finite number `>= 0`. `<FastMesh>` draws a bad width as 0, with a warning.
113
+ - `bound.shading` says what is in use. It is `"vertex"` (the default) unless you ask for `"fragment"` and it can be done. Fragment shading is `WebGLRenderer` only: with a material three does not build from its own shader chunks (a node material for `WebGPURenderer`, say) or a scene host without `coloring()` and `views(mesh).values`, the binding falls back to `"vertex"` with a console warning.
114
+ - The binding patches the material, so each fragment-shaded binding needs its own (`material.clone()`); binding one that another live fragment-shaded binding uses throws `INVALID_ARGUMENT`. While patched, the material's `vertexColors` is off. It calls the material's `dispose()` when it binds and again when the binding is disposed and puts the material back (handler, cache key and `vertexColors`), so its compiled program is rebuilt with the shading and then without it.
115
+ - It reads `views(mesh).values()`: the values the colours are made from, one `f32` per vertex slot, changing only at the colours' dirty slots. On a `WorkerScene` that mirror is opt-in: it turns on at the first `values()` read and fills with the next result (until then results carry no value bytes, so vertex shading pays nothing).
116
+ - It reads `scene.coloring(mesh)` to follow the rule: on `Scene` the rule last set, on `WorkerScene` the rule applied (a new one shows with the batch that applies it, a rejected one never). Either way it is a frozen copy of the rule given to `setColoring`, the same object until the rule changes, or `null` without colouring.
117
+
118
+ A renderer-neutral version of the same loop, with raw WebGPU and no 3D library, is in [`examples/webgpu`](examples/webgpu).
119
+
120
+ ## Scene API
121
+
122
+ For interactive work with several meshes, the `Scene` class keeps the meshes in WebAssembly memory and does the heavy parts in Rust: placements, a BVH per mesh, queries, signed distance fields with colour maps, planar sections, hole repair and undo/redo. Your renderer reads the results through zero-copy typed-array views, and you upload only the ranges that changed.
123
+
124
+ ```ts
125
+ import { init, type MeshHandle, Scene, type Quat, type Vec3 } from "fast-mesh-wasm";
126
+
127
+ await init();
128
+ const scene = new Scene();
129
+
130
+ // Provided by your app (not part of this package): mesh data and the
131
+ // renderer's upload functions.
132
+ declare const upperPositions: Float64Array, upperIndices: Uint32Array;
133
+ declare const lowerPositions: Float64Array, lowerIndices: Uint32Array;
134
+ declare function uploadMatrix(mesh: MeshHandle, matrix: Float64Array): void;
135
+ declare function uploadColors(mesh: MeshHandle, startVertex: number, rgba: Uint8Array): void;
136
+
137
+ // Add meshes. Positions are in world space; the scene stores them relative to
138
+ // the mesh's bounding-box centre so single precision stays accurate.
139
+ const upper = scene.addMesh(upperPositions, upperIndices);
140
+ const lower = scene.addMesh(lowerPositions, lowerIndices);
141
+
142
+ // Colour the upper mesh by its signed distance to the lower one.
143
+ const gap = scene.addDistanceField({ name: "gap", on: upper, to: lower, maxDistance: 2 });
144
+ const colour = (field: typeof gap) =>
145
+ scene.setColoring(upper, { field, map: "turbo", range: [-0.5, 1] });
146
+ colour(gap);
147
+
148
+ // Drag the lower mesh. The whole drag is one undo step. Each `move`
149
+ // recomputes the eager fields, so coalesce pointer events to one `move` per
150
+ // animation frame.
151
+ const drag = scene.drag(lower);
152
+ let pending: { rotation: Quat; translation: Vec3 } | undefined;
153
+ function onPointerMove(rotation: Quat, translation: Vec3) {
154
+ pending = { rotation, translation }; // keep only the latest pose
155
+ }
156
+ function onPointerUp() {
157
+ if (pending !== undefined) drag.move(pending);
158
+ pending = undefined;
159
+ drag.end();
160
+ }
161
+
162
+ // Once per animation frame: take what changed and upload only that.
163
+ function frame() {
164
+ if (pending !== undefined) {
165
+ drag.move(pending); // fields and colours follow
166
+ pending = undefined;
167
+ }
168
+ for (const change of scene.commitFrame()) {
169
+ const views = scene.views(change.mesh); // fresh views; do not keep them
170
+ if (change.placementChanged) {
171
+ uploadMatrix(change.mesh, scene.matrix4(change.mesh)); // Float64Array(16)
172
+ }
173
+ const colors = views.colors();
174
+ if (colors !== null && change.colors !== "all") {
175
+ for (const [start, count] of change.colors) {
176
+ uploadColors(change.mesh, start, colors.subarray(4 * start, 4 * (start + count)));
177
+ }
178
+ } // "all" (a new mesh, or buffers that grew): re-upload the whole buffer
179
+ // positions, normals and indices work the same way
180
+ }
181
+ requestAnimationFrame(frame);
182
+ }
183
+ requestAnimationFrame(frame);
184
+
185
+ // Toggle the colouring (display settings are not part of the undo history).
186
+ scene.setColoring(upper, null);
187
+ colour(gap);
188
+
189
+ // Undo and redo placements and edits.
190
+ if (scene.canUndo()) scene.undo();
191
+ scene.redo();
192
+
193
+ // Queries are in world space.
194
+ const hit = scene.raycast([0, 0, 50], [0, 0, -1]); // nearest hit over all meshes, or null
195
+ const closest = scene.meshDistance(upper, lower); // { distance, a, b, ... }
196
+
197
+ scene.free(); // or `using scene = new Scene()`
198
+ ```
199
+
200
+ Errors are `FastMeshError`s with a `code` (`UNKNOWN_MESH`, `INVALID_ARGUMENT`, `STALE_BVH`, ...). After a trap inside the WebAssembly module every later call throws `INSTANCE_POISONED`. A view is only valid until the next scene call that may allocate or move buffers: a kept view may read other data or be empty, so re-acquire views after any scene call. `new Scene({ debug: true })` makes views warn when they are read after such a call. Mesh edits (`scene.edit`), `analyze`, `repair`, sections (`addSection`, `section`, `sectionGap`) and `findContacts` are documented in the types.
201
+
202
+ ### Contact groups: fields to several meshes
203
+
204
+ A distance field can measure to several meshes at once. Give `to` a list, and each vertex holds the smallest signed distance over them: the nearest surface, or the deepest penetration. So a mesh touching several others shows one colour scale, whichever partner it touches.
205
+
206
+ ```ts
207
+ // a, b, c, d: MeshHandles. Contacts a-b, b-c, a-c and a-d: one field per mesh, to its partners.
208
+ const fa = scene.addDistanceField({ name: "contact", on: a, to: [b, c, d], maxDistance: 1 });
209
+ const fb = scene.addDistanceField({ name: "contact", on: b, to: [a, c], maxDistance: 1 });
210
+ scene.fieldTargets(fa); // [b, c, d]
211
+ scene.fieldNearest(fa); // Uint32Array: per vertex, the index in [b, c, d] it came from (0xffffffff: none)
212
+ ```
213
+
214
+ - **Exact.** The values are bit for bit the minimum of separate single-target fields, ties going to the earliest target, with the `parallel` feature on or off.
215
+ - **Only related fields recompute.** Moving `d` recomputes `a`'s field (`d` is one of its targets) and `d`'s own. Moving `a` recomputes every field that has `a`, and `b`'s field to `[a, c]` is left alone when only `d` moves. Within a field, only the vertices near the moved target, or whose value came from it, are recomputed.
216
+ - **The best value so far bounds the next target's search where that stays exact.** Once a vertex has a negative value (a penetration), a later target can only win by being deeper, so its search stops at that depth. In `"winding"` sign mode a positive value bounds the search too, with a winding-number test for a deeper inside. A positive value cannot bound a pseudonormal target, since a vertex inside it is negative however far its surface is. Either way a field to three targets is one field to keep, one colour pass and one value per vertex.
217
+ - **Removing a target mesh** removes it from the field; removing the last one removes the field (and its colouring). `fieldStatus(field).sign` sums up the targets (closed only if every target is closed); `fieldTargetStatus(field)` gives each one.
218
+ - **Rust.** `fast_mesh_scene::DistanceField::to` is now a `Vec<MeshId>`; `DistanceField::new(name, on, to, max_distance, sign)` builds the single-target form.
219
+
220
+ On a `WorkerScene` the same `to: [...]` works; read the indices with `await scene.fetchFieldNearest(field)` and the per-target status with `await scene.fieldTargetStatus(field)`. With the store, see `setContactGroup` below.
221
+
222
+ ## Worker scene
223
+
224
+ `fast-mesh-wasm/worker` runs the same engine in a Web Worker, so adding a large mesh, building fields or recolouring never blocks the page. `createWorkerScene()` starts the Worker and resolves to a `WorkerScene` with the `Scene` methods. Your renderer keeps reading synchronous views: every result carries the bytes of its dirty ranges, which are copied into main-thread mirrors.
225
+
226
+ ```ts
227
+ import * as THREE from "three";
228
+ import type { DragSession, PlacementInput } from "fast-mesh-wasm";
229
+ import { createWorkerScene } from "fast-mesh-wasm/worker";
230
+ import { bindMesh } from "fast-mesh-wasm/three"; // optional: the three.js adapter works on a WorkerScene too
231
+
232
+ // Provided by your app (not part of this package).
233
+ declare const upperPositions: Float64Array, upperIndices: Uint32Array;
234
+ declare const lowerPositions: Float64Array, lowerIndices: Uint32Array;
235
+ declare const renderer: THREE.WebGLRenderer, threeScene: THREE.Scene, camera: THREE.Camera;
236
+ declare const button: HTMLButtonElement, undoButton: HTMLButtonElement;
237
+
238
+ const scene = await createWorkerScene(); // no init() needed: the Worker loads the wasm
239
+
240
+ // Handles come back at once; the work runs in the Worker.
241
+ const upper = scene.addMesh(upperPositions, upperIndices);
242
+ const lower = scene.addMesh(lowerPositions, lowerIndices);
243
+ const gap = scene.addDistanceField({ name: "gap", on: upper, to: lower, maxDistance: 2 });
244
+ scene.setColoring(upper, { field: gap, map: "turbo", range: [-0.5, 1] });
245
+ const boundUpper = bindMesh(scene, upper);
246
+ threeScene.add(boundUpper.object);
247
+
248
+ // Drag the lower mesh: one drag per gesture, the latest pose kept until the next frame.
249
+ let drag: DragSession | undefined;
250
+ let pending: PlacementInput | undefined;
251
+ function onPointerDown() {
252
+ drag = scene.drag(lower); // the whole drag is one undo step
253
+ }
254
+ function onPointerMove(pose: PlacementInput) {
255
+ pending = pose; // keep only the latest pose
256
+ }
257
+ function onPointerUp() {
258
+ if (pending !== undefined) drag?.move(pending);
259
+ pending = undefined;
260
+ drag?.end(); // returns at once
261
+ drag = undefined;
262
+ }
263
+
264
+ // Once per animation frame: send this frame's requests, receive the results so far.
265
+ function frame() {
266
+ if (pending !== undefined) drag?.move(pending); // at most one move per frame
267
+ pending = undefined;
268
+ scene.commitFrame(); // the adapters' listeners apply the changes here, as with Scene
269
+ renderer.render(threeScene, camera);
270
+ requestAnimationFrame(frame);
271
+ }
272
+ requestAnimationFrame(frame);
273
+
274
+ // Status of each piece of state: "idle" | "computing" | "ready" | "error".
275
+ scene.onStatus(() => {
276
+ const coloring = scene.status(`display:${scene.idOf(upper)}`);
277
+ button.classList.toggle("busy", coloring.status === "computing");
278
+ undoButton.disabled = !scene.canUndo; // canUndo / canRedo are getters here
279
+ });
280
+
281
+ // Queries are async.
282
+ const hit = await scene.raycast([0, 0, 50], [0, 0, -1]);
283
+ const distance = await scene.meshDistance(upper, lower);
284
+ const values = await scene.fetchFieldValues(gap); // `fieldValues` on Scene
285
+ ```
286
+
287
+ - **The frame loop.** `commitFrame()` sends everything queued since the last frame as one batch and returns the change records of the results received meanwhile (already applied to the mirrors, so `views`, `matrix4`, `placement`, `section` and `sectionPlane` read the new state). Results arrive between frames; nothing changes in the mirrors outside a message.
288
+ - **Requests run in order.** A newer colouring, section plane/meshes/fill or drag move drops the older one if it has not started yet, so fast toggling settles on the last state without doing the steps in between. Edits, repairs, `setPlacement`, adds, removals and undo/redo are never dropped. Each `setPlacement` is an undo step: for pointer-rate updates use a drag. Long work runs in steps: the Worker yields every few milliseconds during a field build, a field update or a large add, so newer batches are received (and coalesced) meanwhile.
289
+ - **Drags are optimistic.** `scene.drag(mesh).move(pose)` moves the placement mirror at once, so the object follows the pointer; colours and sections catch up when the Worker's result arrives. In 9a a key's status covers only requests made under that key: a drag, `setPlacement` or edit puts its own key (`placement:<id>`, `edit:<id>`) into `"computing"`, not the `display:<id>` or `section:<id>:*` keys of the state that catches up after it. `end()` and `cancel()` return at once; `cancel()` restores the start pose and records nothing.
290
+ - **Wide-range colouring during a drag.** After each batch the Worker recomputes the fields the batch made due in small steps, and drops the recompute when a newer move, `setPlacement`, edit, repair, compact, undo/redo or removal of either mesh is already queued; other requests wait for it. A pose's colours are applied all at once, never partly. So while the pointer keeps moving and one recompute takes longer than a frame, newer moves drop the recompute, until 200 ms have passed since the last colours were applied: then the recompute under way finishes and is shown, and the newest pose follows. During a sustained drag the colours therefore update about every 200 ms plus one recompute, each update exactly one pose, and when the drag ends (`end()`) the last pose's colours arrive within about one recompute (measured: one at 1M, but about 1.5 at 10M when most of the mesh is in range): the end drops a recompute kept for an older pose. A pointer that only pauses, without ending the drag, may wait up to two recomputes. Edits, undo/redo, removals and cancels always drop a stale recompute. `fetchFieldValues()` and `fieldStatus()` first bring every due field up to date in one go, which cannot be dropped, so do not poll them during a drag. On two touching 1M-triangle meshes with `maxDistance` 8, a recompute takes from about 0.07 s to 0.7 s depending on how much of the mesh is in range, and about ten times that at 10M; the Worker is never blocked for long, since a recompute runs in steps: about 12 ms at a time at 1M, and 14 to 18 ms for field builds and edits at 10M (see [docs/benchmarks.md](docs/benchmarks.md)). These are single-threaded figures; on a cross-origin isolated page the threaded engine makes a recompute 1.4 to 4.5 times faster (see [Multithreading (COOP/COEP)](#multithreading-coopcoep)). A contact range (a small `maxDistance`) keeps up with the pointer.
291
+ - **Queries and anything that returns data** (`raycast`, `closestPoint`, `meshDistance`, `intersects`, `findContacts`, `analyze`, `edit`, `repair`, `fetchFieldValues`, `fieldStatus`, `sectionGap`) return promises. Once a frame loop runs they go out with the next `commitFrame()` (or after 100 ms if no frame comes); before the first `commitFrame()` they are sent on a microtask. For latency-critical picking, keep a light picking copy in a main-thread `Scene`.
292
+ - **Errors.** A failed state change shows on its key (`status(key).error`, a `FastMeshError` with the same `code` as on `Scene`); a failed promise rejects with it. After a trap inside the Worker every call fails with `INSTANCE_POISONED`, also when it happens on one of the multithreaded engine's pool threads (a panic or a trap in work split across threads); a few kinds of pool-thread failure still cannot be detected (see [Multithreading (COOP/COEP)](#multithreading-coopcoep)). `await scene.restart()` starts a new Worker and replays the scene from the main thread's mirrors: meshes (compacted: slot ids change, handles do not), placements, fields, colourings and sections. History is cleared, and edits or queries that had not finished fail and must be re-issued.
293
+ - **Not in the Worker scene:** user-opened steps (`beginStep`/`endStep`/`cancelStep`), Lazy and Manual modes (it is always eager) and `takeChanges` (use `onChanges` or the return value of `commitFrame()`). `terminate()` stops the Worker.
294
+ - **Large meshes.** `addMesh` copies its inputs on the main thread (they are then transferred to the Worker) and, without an `origin` option, scans the positions for the bounding-box centre. That takes about 9 ms for 1M triangles and about 63 ms for 10M (see [docs/benchmarks.md](docs/benchmarks.md)); passing `origin` skips the scan.
295
+ - **Large meshes are added in the background.** A mesh of 65,536 triangles or more is built in steps inside the Worker (about 1.1 s at 1M and 12 s at 10M, single-threaded) while the requests sent after it that do not need it run: toggles, edits, drags and queries of other meshes are answered within milliseconds instead of waiting. A request that names the new mesh (or a field not built yet that is measured on or to it), adds or removes a mesh, or queries every mesh (`raycast`, `closestPoint` without a mesh, `findContacts` without pairs) waits for it and finishes it first (in one call on a threaded engine, in steps that still yield on a single-threaded one), so the engine's state is the same as running the requests in order. Replies can come in another order, though: until the mesh lands, `status("mesh:<id>")` reads `"computing"` and its views are empty; its buffers arrive with that status turning `"ready"`, so a reply to an unrelated request sent after the add can arrive first. `createWorkerScene({ backgroundAddTriangles })` sets the threshold; `Infinity` turns background adds off (every add then comes back with its own batch's result).
296
+
297
+ **Bundlers.** The Worker script is a separate file, `worker-entry.js`, loaded with `new Worker(new URL("./worker-entry.js", import.meta.url), { type: "module" })`. Vite and other bundlers that understand this pattern pick it up and emit it with the `.wasm` it loads: [`examples/webgpu`](examples/webgpu) uses the default with Vite, in both `vite build` and `vite dev` (open it with `?worker`). If your setup does not handle the pattern, serve the package's `dist/` folder (the Worker script loads the files next to it) and pass the script's URL, or create the Worker yourself:
298
+
299
+ ```ts
300
+ const scene = await createWorkerScene({ workerUrl: "/fast-mesh-wasm/worker-entry.js" });
301
+ // or
302
+ const scene = await createWorkerScene({ createWorker: () => new Worker(myUrl, { type: "module" }) });
303
+ ```
304
+
305
+ `fast-mesh-wasm/worker` is for browsers and is not supported in Node.js (its tests run it on Node's `worker_threads` as a harness only).
306
+
307
+ ## Multithreading (COOP/COEP)
308
+
309
+ On a cross-origin isolated page the Worker scene runs a multithreaded engine: its WebAssembly runs on a pool of Workers that share its memory, and the work that the Rust crates' `parallel` feature splits (BVH builds, sign data, distance and closest-point queries, near-triangle searches, see "Parallel" in [docs/benchmarks.md](docs/benchmarks.md)) is split across them. Results are bit-identical to the single-threaded engine. On two touching 1M-triangle meshes with a wide distance field, 8 threads made a drag's recompute about 1.6 to 4.5 times faster and halved the longest Worker block (headless Chrome; see "Threaded Worker" in [docs/benchmarks.md](docs/benchmarks.md)). Nothing changes in your code: the same `createWorkerScene()` picks the engine.
310
+
311
+ A page is cross-origin isolated (`crossOriginIsolated === true`) when its document is served with these two headers:
312
+
313
+ ```
314
+ Cross-Origin-Opener-Policy: same-origin
315
+ Cross-Origin-Embedder-Policy: require-corp
316
+ ```
317
+
318
+ Send them on **every** response, including 304 (Not Modified) responses: Safari refuses to start a Worker whose script it revalidated with a 304 that lacks them.
319
+
320
+ **Vite** (dev and preview). Use a small plugin rather than `server.headers`/`preview.headers`, which Vite leaves off its 304 responses ([`examples/webgpu/vite.config.ts`](examples/webgpu/vite.config.ts) does this):
321
+
322
+ ```ts
323
+ import { defineConfig, type Plugin } from "vite";
324
+
325
+ function crossOriginIsolation(): Plugin {
326
+ const isolate = (_req: unknown, res: { setHeader(name: string, value: string): void }, next: () => void) => {
327
+ res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
328
+ res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
329
+ next();
330
+ };
331
+ return {
332
+ name: "cross-origin-isolation",
333
+ configureServer: (server) => void server.middlewares.use(isolate),
334
+ configurePreviewServer: (server) => void server.middlewares.use(isolate),
335
+ };
336
+ }
337
+
338
+ export default defineConfig({ plugins: [crossOriginIsolation()] });
339
+ ```
340
+
341
+ **webpack-dev-server** (a middleware ahead of the others, so every response gets the headers):
342
+
343
+ ```js
344
+ // webpack.config.js
345
+ module.exports = {
346
+ devServer: {
347
+ setupMiddlewares: (middlewares) => {
348
+ middlewares.unshift((req, res, next) => {
349
+ res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
350
+ res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
351
+ next();
352
+ });
353
+ return middlewares;
354
+ },
355
+ },
356
+ };
357
+ ```
358
+
359
+ **nginx** (`add_header` already covers 200, 304 and the other success and redirect statuses; `always` adds the 4xx and 5xx ones too):
360
+
361
+ ```nginx
362
+ add_header Cross-Origin-Opener-Policy "same-origin" always;
363
+ add_header Cross-Origin-Embedder-Policy "require-corp" always;
364
+ ```
365
+
366
+ A `location` (or other block) with any `add_header` of its own, such as a `Cache-Control` for assets, inherits none of the server-level ones: repeat the two headers in every such block, or keep them in a file you `include` in each.
367
+
368
+ **Express** (before `express.static`):
369
+
370
+ ```js
371
+ app.use((req, res, next) => {
372
+ res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
373
+ res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
374
+ next();
375
+ });
376
+ app.use(express.static("dist"));
377
+ ```
378
+
379
+ **What the headers change for the rest of the page.** With COEP `require-corp`, the page and its Workers may only load cross-origin resources (images and textures, scripts, fonts, models, `fetch` from a CDN or API) that opt in: load them with CORS (`crossorigin` on `<img>`/`<script>`/`<link>`, `img.crossOrigin = "anonymous"` or three.js's `TextureLoader`, whose default is `anonymous`) from a server that sends `Access-Control-Allow-Origin`, or have that server send `Cross-Origin-Resource-Policy: cross-origin` (meant for public assets only: it lets any site embed them). Anything else is blocked, so check third-party embeds before turning isolation on. COOP `same-origin` also cuts the link between your page and cross-origin popups it opens (`window.opener`), which some sign-in flows rely on. Same-origin assets, including this package's files, need nothing. `Cross-Origin-Embedder-Policy: credentialless` also makes a page isolated and loads cross-origin resources without credentials instead of blocking those that do not opt in; Chrome and Firefox support it, Safari does not (the page is then not isolated there, and the scene runs single-threaded).
380
+
381
+ **The `threads` option.**
382
+
383
+ ```ts
384
+ const scene = await createWorkerScene(); // default: navigator.hardwareConcurrency, at most 8
385
+ const fixed = await createWorkerScene({ threads: 4 }); // clamped to 1..64; a non-integer rejects with INVALID_ARGUMENT
386
+ const single = await createWorkerScene({ threads: 1 }); // the single-threaded engine; the threaded files are never fetched
387
+ console.log(scene.threads); // the threads the engine computes with: 1 when single-threaded (and until the Worker is ready)
388
+ ```
389
+
390
+ **Fallback.** The scene always starts. On a page that is not cross-origin isolated it runs single-threaded and never fetches the threaded files. On an isolated page, if the threaded engine cannot start (its import or instantiation fails, the shared memory cannot be allocated, or the thread pool rejects or has not started within 10 s, for example because its nested Workers cannot load), the scene runs single-threaded. When the failure comes after the threaded engine was instantiated, its Worker is replaced by a fresh single-threaded one, and requests made meanwhile are kept and run there. A scene that fell back this way stays single-threaded across `restart()`, so a restart does not wait 10 s again. `scene.threads` tells which engine runs.
391
+
392
+ **Older WebKit.** WebKit 26 (as in Playwright 1.56's build; Safari 26 may be affected) cannot share a growing WebAssembly memory between threads. After one thread grows the shared memory, another thread's `memory.fill` and `memory.copy` still check against the old size and trap, though plain loads and stores see the new size. The thread pool grows the memory as it starts, so its start traps there, and any later growth on a pool thread would crash the engine too. So while it imports the threaded glue, the Worker runs a probe that takes about 10 ms: a nested Worker grows a tiny shared memory, then the Worker fills a byte of the new page and copies one into it. When either traps, the scene runs single-threaded right away, with the development warning, instead of waiting out the 10 s pool timeout. The verdict is kept for the page: that scene's restarts and later scenes on the page start single-threaded without probing again (in development each scene still logs why, once). If the probe cannot run or gets no answer within 1 s (no nested Workers, or a Content Security Policy that blocks `blob:` Workers), the threaded engine is tried as before. WebKit 27.2 passes the probe and runs threaded.
393
+
394
+ **Crashes on a pool thread.** With the single-threaded engine, a trap in the WebAssembly module poisons the scene (every call fails with `INSTANCE_POISONED`). With the multithreaded engine, a crash on a pool thread ends only that thread, and the engine's Worker keeps waiting for it. Each pool thread therefore reports its own crash to the scene on the main thread, through a `BroadcastChannel` with a name unique to that Worker. The scene then fails every pending call with `INSTANCE_POISONED` and terminates the Worker and its pool, as it does after a Worker error; `restart()` recovers with a new pool. This covers Rust panics (the panic hook reports the message before the abort) and WebAssembly traps on a pool thread. Panics and the `unreachable` trap are tested in Chrome, Firefox and WebKit. Other traps are expected to be detected through the same path as `unreachable`, but are not tested: out-of-bounds access, the abort after a failed allocation, and the JavaScript call stack running out. It costs nothing until a thread crashes: no polling, just one idle channel per threaded Worker. The following still cannot be detected, and leave the scene waiting (pending promises never settle, statuses stay `"computing"`), with `restart()` and `terminate()` still working:
395
+ - an overflow of a pool thread's stack in WebAssembly memory. WebAssembly has no guard page, so this is not a trap: it overwrites other memory, and is only noticed if that later traps;
396
+ - a nested Worker that the browser ends without an exception (for example when the tab's process runs out of memory);
397
+ - a pool thread that loops or deadlocks instead of crashing;
398
+ - a browser with no `BroadcastChannel` in Workers.
399
+
400
+ Applications that cannot accept these cases should pass `threads: 1`.
401
+
402
+ **The development warning.** In development builds (`import.meta.env.DEV`, as Vite sets it) or with the `debug` option, the scene logs once (per scene, also across restarts) why it runs single-threaded when more threads were asked for: the page is not isolated, or the threaded engine failed to start, with the cause. Production builds are silent.
403
+
404
+ **Bundlers.** No setting beyond the headers is needed: Vite (dev and build) and webpack 5 work as installed from npm, and so does a page without a bundler that serves the package's `dist/` folder as is (checked by `scripts/bundler-check.mjs`). Bundlers emit the threaded engine into your build output next to the single-threaded one: a chunk, its `.wasm` (about 988 KB, 372 KB gzipped, against 772 KB and 307 KB) and the thread pool's Worker helper. Pages that run single-threaded never download them.
405
+
406
+ **Without header control** (some static hosts), a service worker such as [coi-serviceworker](https://github.com/gzuidhof/coi-serviceworker) can make a page cross-origin isolated by adding the headers itself. This package does not ship or test one.
407
+
408
+ **Browsers.** Current Chrome and Edge, Firefox and Safari support it. Checked: headless Chrome 155, Firefox 157 and Playwright's WebKit 27.2 on Windows (bit-identical results in all three). Known issue: Playwright's Windows WebKit build crashed its web process in 2 of about 20 development-server runs of the check that crashes a threaded Worker on purpose and restarts it; the cause is unknown, and real Safari on macOS has not been checked.
409
+
410
+ The threaded engine adds memory: its shared memory starts at about 1 MB (18 pages) and may grow to 4 GiB (wasm32's limit), and each pool Worker has its own stack. A 10M-triangle wide-drag scene used about 2.4 GB threaded against 2.1 GB single-threaded.
411
+
412
+ ## React
413
+
414
+ Three subpaths connect a scene to UI code:
415
+
416
+ - `fast-mesh-wasm/store`: `SceneStore`, an observable store over a `Scene` or a `WorkerScene`. It has no dependencies, so it also works without React.
417
+ - `fast-mesh-wasm/react`: hooks over the store. Needs `react` (optional peer, `>=18`; tested with React 19).
418
+ - `fast-mesh-wasm/r3f`: `<FastMesh>` for React Three Fiber. Needs `@react-three/fiber` (optional peer, `>=9`) and `three`.
419
+
420
+ ```tsx
421
+ import { createSceneStore } from "fast-mesh-wasm/store";
422
+ import { createWorkerScene } from "fast-mesh-wasm/worker";
423
+ import { SceneProvider, useHistory, useMeshDisplay } from "fast-mesh-wasm/react";
424
+ import { FastMesh } from "fast-mesh-wasm/r3f";
425
+ import { Canvas } from "@react-three/fiber";
426
+ import type { MeshHandle } from "fast-mesh-wasm";
427
+
428
+ // Provided by your app (not part of this package).
429
+ declare const upperPositions: Float64Array, upperIndices: Uint32Array;
430
+ declare const lowerPositions: Float64Array, lowerIndices: Uint32Array;
431
+
432
+ // One store per scene. With the synchronous Scene: `await init(); createSceneStore(new Scene())`.
433
+ const store = createSceneStore(await createWorkerScene());
434
+ const upper = store.addMesh(upperPositions, upperIndices);
435
+ const lower = store.addMesh(lowerPositions, lowerIndices);
436
+
437
+ function ColourButton({ mesh, to }: { mesh: MeshHandle; to: MeshHandle }) {
438
+ const [state, setDisplay] = useMeshDisplay(mesh);
439
+ const pressed = state.desired.coloring !== null; // what was requested
440
+ const busy = state.status === "computing"; // not shown yet
441
+ return (
442
+ <button
443
+ aria-pressed={pressed}
444
+ aria-busy={busy}
445
+ onClick={() =>
446
+ setDisplay({ coloring: pressed ? null : { distanceTo: to, maxDistance: 2, map: "turbo", range: [0, 2] } })
447
+ }
448
+ >
449
+ Distance colours
450
+ </button>
451
+ );
452
+ }
453
+
454
+ function UndoButton() {
455
+ const { canUndo, undo } = useHistory();
456
+ return <button disabled={!canUndo} onClick={undo}>Undo</button>;
457
+ }
458
+
459
+ export function App() {
460
+ return (
461
+ <SceneProvider store={store}>
462
+ <Canvas>
463
+ <ambientLight />
464
+ <FastMesh mesh={upper} />
465
+ <FastMesh mesh={lower} />
466
+ </Canvas>
467
+ <ColourButton mesh={upper} to={lower} />
468
+ <UndoButton />
469
+ </SceneProvider>
470
+ );
471
+ }
472
+ ```
473
+
474
+ **The store.** `store.getSnapshot()` returns a frozen `SceneSnapshot` (meshes, sections, history, selection and an overall status), replaced on every change, with unchanged parts shared between versions. `store.subscribe(listener)` notifies after each new snapshot: at once for an action, and once per task for the scene's events (on a microtask; `getSnapshot()` is up to date before then). An update re-derives only the meshes and sections it touches. What still grows with the scene is one copy of the snapshot's mesh map per change: a native `Map` copy, about 45 µs at 1500 meshes. Actions mirror the scene: `addMesh`, `removeMesh`, `setPlacement`, `drag`, `edit`, `repair`, `undo`, `redo`, `addSection`, `removeSection` and `restart` (Worker only). The declarative ones are new:
475
+
476
+ - `setDisplay(mesh, { coloring?, opacity?, visible? })`. A `coloring` colours the mesh by its distance to `distanceTo`: one mesh, or a list of them (the smallest signed distance over them; see [Contact groups](#contact-groups-fields-to-several-meshes)). The store owns the distance field behind it: one per coloured mesh, named `fast-mesh-store:<n>`, kept while the colouring is off, reused when it comes back with the same `distanceTo` (as a set: the order does not matter), `maxDistance` and `sign`, and replaced only when one of them changes. `opacity` (in [0, 1], default 1) and `visible` (default true) live only in the store; the engine never sees them. Display changes never enter the undo history.
477
+ - `setContactGroup(id, { meshes, pairs?, coloring } | null)` colours a group of meshes by contact. Each member gets `coloring` with its partners as `distanceTo`: the members it is paired with in `pairs` (either way round), or every other member with `pairs: "all"` (the default). `coloring` is a `DistanceColoring` without `distanceTo`, so any preset spreads into it. Moving a member recomputes only its own field and its partners'. Setting the group again updates the members; a member dropped from it, or all of them with `null`, is uncoloured and its store-owned field removed. A member the app has coloured itself since (with `setDisplay`) is left alone by those changes. A removed mesh leaves its groups: the others keep their remaining partners, and a member left with none is uncoloured. The colouring is checked when the group is set (`INVALID_ARGUMENT`). Groups are not in the snapshot: the members' `display` and `desired` colourings show them.
478
+
479
+ ```ts
480
+ store.setContactGroup("parts", {
481
+ meshes: [a, b, c, d],
482
+ pairs: [[a, b], [b, c], [a, c], [a, d]],
483
+ coloring: { maxDistance: 1, map: "coolwarm", range: [-0.5, 0.5], center: 0, above: "base" },
484
+ });
485
+ ```
486
+
487
+ - `setSection(section, { plane?, meshes?, fill? })` changes a section.
488
+ - `select(mesh | null)` sets the selection. It is UI state only, and it clears when the selected mesh is removed.
489
+
490
+ **Contact heatmap.** `contactHeatmap({ depth, gap, tolerance?, exactDepth?, sign?, colors? })` builds a colouring (everything but `distanceTo`) that shows how two meshes touch. Spread it into `setDisplay`, colouring each mesh against the other:
491
+
492
+ ```ts
493
+ import { contactHeatmap } from "fast-mesh-wasm/store";
494
+
495
+ const heat = contactHeatmap({ depth: 0.5, gap: 1, tolerance: 0.05 });
496
+ store.setDisplay(upper, { coloring: { distanceTo: lower, ...heat } });
497
+ store.setDisplay(lower, { coloring: { distanceTo: upper, ...heat } });
498
+ ```
499
+
500
+ - The range is `[-depth, gap]`. Penetration runs from `deep` (`#7f0000`) at `-depth` to `shallow` (`#ff6b6b`) at the contact band, which is `contact` (`#ffffff`) across `[-tolerance, +tolerance]` (one stop at 0 when the tolerance is 0, the default). The gap runs from `near` (`#4caf50`) to `far` (`#1e3a8a`) at `gap`. Deeper than `depth` clamps to `deep`; farther than `gap` shows the base colour. `gap: 0` colours penetration only: the range is then `[-depth, tolerance]`, with no gap ramp, and anything beyond the contact band shows the base colour. `colors` overrides any of the five.
501
+ - `exactDepth: false` (the default) bounds the field at `2 · max(depth, gap)`, past the range ends, so the coloured area's outer edge is a value boundary: the fast path for contact, but a vertex deeper than the bound is beyond the field and shows the base colour. `exactDepth: true` computes every vertex's distance (`maxDistance: Infinity`), so any penetration shows, at the cost of a full recompute on every update.
502
+ - `sign` (default `"auto"`) is passed through. On an open or inconsistently oriented target, the penetration side follows its surface normals (`fieldStatus` tells you which).
503
+ - Changing only `tolerance` or `colors` keeps `maxDistance` and `sign`, so the store reuses its field and only recolours.
504
+ - It throws `INVALID_ARGUMENT` unless `depth > 0`, `gap >= 0` (both finite) and `0 <= tolerance < min(depth, gap)` (`< depth` when `gap` is 0).
505
+
506
+ `store.fetchColoringValues(mesh)` resolves to a copy of the values of the field behind the mesh's colouring (one per vertex slot), or `null` when the mesh has no colouring: for readouts such as the deepest penetration, `-min(values)`. It uses `fetchFieldValues` on a Worker scene and copies `fieldValues` on a synchronous one. It works the same for a member of a contact group (`setContactGroup`): the values are those of its field measured to all of its partners, each vertex holding the smallest over them; the field's `nearest` buffer (`fieldNearest`, `fetchFieldNearest` on a Worker scene, through `scene.coloring(mesh).field`) tells which partner each came from. Its indices follow `store.coloringTargets(mesh)`, the targets of the field behind the colouring in the field's order (ascending scene id, not the order of `distanceTo` or of the group's members; on a `Scene`, `scene.fieldTargets(field)` gives the same), frozen, or `null` without a colouring. It rejects with `UNKNOWN_MESH` for a mesh not in the store.
507
+
508
+ Declarative changes update `desired` at once and reach the scene at the next `store.commitFrame()`, the last value per mesh or section in a frame winning (on both scenes, so rapid toggling never queues work). Without a frame loop they apply on a microtask. Call `store.commitFrame()` once per animation frame instead of `scene.commitFrame()`; `<FastMesh>` does it for you. The first `store.commitFrame()` switches the store to frame flushing: from then on, declarative changes wait for a frame. When the last `<FastMesh>` (or `useFrameDriver`) of a store unmounts, the store switches back to flushing on a microtask, so changes made with no canvas mounted still apply.
509
+
510
+ Meshes must be added through the store (`store.addMesh`). A mesh added straight to `store.scene` is not in the store: its hooks read it as removed, and `<FastMesh>` renders nothing for it.
511
+
512
+ `store.dispose()` removes the distance fields the store owns (and so their colourings) and stops listening to the scene; the rest of the scene is left as it is. On a Worker scene the removals go with the scene's next `commitFrame()`.
513
+
514
+ **Reading state in components.**
515
+
516
+ | Hook | Returns |
517
+ | --- | --- |
518
+ | `useScene()` | The store of the nearest `<SceneProvider store>` |
519
+ | `useMeshDisplay(mesh)` | `[state, setDisplay]`: the mesh's applied `coloring`, `opacity` and `visible`, plus `desired`, `status` and `error` |
520
+ | `useSection(section)` | `[state, setSection]`: the applied `plane`, `meshes` and `fill`, plus `desired`, `status` and `error` |
521
+ | `useHistory()` | `{ canUndo, canRedo, undo, redo }` |
522
+ | `useSceneStatus()` | `{ status, error? }` for the whole scene: `"error"` if anything failed, else `"computing"` while anything is pending, else `"idle"` |
523
+ | `useSelection()` | `[mesh \| null, select]` |
524
+ | `useStoreSelector(selector, isEqual?)` | Any slice of the snapshot; re-renders only when it changes |
525
+
526
+ - **Bind controlled inputs (sliders, toggles, checkboxes) to `state.desired.*`.** That is what the user last asked for, so the input follows them at once. The top-level `state.coloring`, `state.opacity` and `state.visible` (and a section's top-level `plane`, `meshes` and `fill`) are the applied values: what is on screen.
527
+ - **`status === "computing"` covers the pending window of colourings and sections**: the time between a request (the button is pressed) and the scene showing it, whether the change is waiting for the next frame or a colouring is being computed in the Worker. Opacity and visibility never read as pending: they live in the store and apply at the next flush. Show it as busy; the button never reads "on" while the mesh shows colours off outside this window. A mesh is also `"computing"` while something it depends on is pending: its placement or an edit, those of the mesh it is coloured by distance to, or an undo/redo. A section depends the same way on its meshes. Only a state's own requests can make it `"error"`; a failed edit rejects its own promise instead.
528
+ - **On the synchronous `Scene`** every status is `"ready"` right after the frame that applied it, or `"error"` if the call threw. `store.restart()` rejects with `INVALID_ARGUMENT` there.
529
+ - **A removed mesh or section** reads as `"idle"` with the default display (or no meshes) and its setter throws `UNKNOWN_MESH` or `UNKNOWN_SECTION`, so a component still mounted for it renders without throwing. Removing the mesh another mesh is coloured by distance to (alone) leaves that mesh uncoloured, its rule kept in `desired` and its status `"error"` (`UNKNOWN_MESH`) until its colouring changes; a colouring to several meshes keeps the others. A rule the engine rejected is not re-sent until it changes.
530
+ - **SSR.** On the server the hooks render an empty snapshot (`EMPTY_SNAPSHOT`) and never throw for missing data.
531
+
532
+ **`<FastMesh>`.** `<FastMesh mesh store? material? color? shading? edgeSoftness? onBind? onClick?… />` binds a scene mesh (added through the store) with `bindMesh` on mount, follows the applied opacity and visibility, and disposes the binding on unmount or when the mesh is removed (it then renders nothing). Opacity and visibility apply inside the frame's `store.commitFrame()`, so they show in the same frame as a colouring flushed with them. R3F pointer events are passed to the mesh. Adding or removing the `store` prop remounts it (and rebinds the mesh). Give each `<FastMesh>` its own `material`, and dispose it yourself. Every `<FastMesh>` calls `useFrameDriver(store)`, which calls `store.commitFrame()` once per rendered frame however many are mounted (do not call `commitFrame()` yourself as well), and invalidates the canvas when the store or the scene changes, so `<Canvas frameloop="demand">` renders every change. Use `useFrameDriver()` on its own when you draw the scene without `<FastMesh>`.
533
+
534
+ - **`shading`** and **`edgeSoftness`** pass through to `bindMesh` (see [Fragment shading](#fragment-shading)). A new `shading` rebinds; a new `edgeSoftness` is set on the binding without one, and NaN or a negative width draws as 0 with a warning.
535
+ - **`onBind(bound)`** delivers the `BoundMesh` once the mesh is bound, and `null` when that binding is disposed (unmount, removal, or a rebind after a `material` or `color` change, which then delivers the new one). Pass it to `bindSection` or `attachTransformControls` (`fast-mesh-wasm/three`), which take any `MeshBinding` (`Pick<BoundMesh, "mesh" | "object">`). `bindSection` clips the materials it sees when it is called, so bind the section again when `onBind` delivers a new binding. An inline callback is fine: a new callback never rebinds. [`examples/react`](examples/react) keeps the bindings in a map for its section and its gizmo.
536
+ - **One store across two `<Canvas>` roots.** The first mounted driver for a store does the committing; every canvas is invalidated on change. If the committing canvas does not render at all (`frameloop="never"`, say) while another one runs, the store stops committing. Drive such a store from one canvas only, or call `useFrameDriver` in the canvas that always renders.
537
+
538
+ [`examples/react`](examples/react) is a complete app on the Worker store (`?local` for the synchronous one): colouring toggles, opacity and visibility, a section, undo/redo, the scene status with Restart, dragging with three's TransformControls and STL drop.
539
+
540
+ **Showcase.** [`examples/showcase`](examples/showcase) is a small mesh tool on the same stack: load STL, OBJ and PLY files (parsed in a Worker), move meshes with a gizmo, analyse and repair them (weld, remove degenerate triangles, orient, remove small components, fill holes; each one undo step), and see how two meshes touch as a contact heatmap (`contactHeatmap`) with live readouts of the deepest penetration, the gap and the contacts.
541
+
542
+ ## Functions
56
543
 
57
544
  | Function | Returns | Description |
58
545
  | --- | --- | --- |
@@ -1,12 +1,12 @@
1
+ import { n as call, r as ensureInitialized, s as setMemory } from "./core-Cke_kZ2e.js";
1
2
  import * as wasm from "./wasm/fast_mesh_wasm.js";
2
3
  //#region src/api.ts
3
- let initialized = false;
4
- /** Called by the entry point once the WebAssembly module is instantiated. */
5
- function markInitialized() {
6
- initialized = true;
7
- }
8
- function ensureInitialized(fn) {
9
- if (!initialized) throw new Error(`fast-mesh-wasm is not initialized: call \`await init()\` before ${fn}().`);
4
+ /**
5
+ * Called by the entry point once the WebAssembly module is instantiated, with
6
+ * what `initSync` / the default init returned; keeps its memory for views.
7
+ */
8
+ function markInitialized(output) {
9
+ setMemory(output.memory);
10
10
  }
11
11
  function toFloat32(values) {
12
12
  return values instanceof Float32Array ? values : Float32Array.from(values);
@@ -23,8 +23,8 @@ function toUint32(values) {
23
23
  * @throws If a length is not a multiple of 3 or an index is out of range.
24
24
  */
25
25
  function computeVertexNormals(positions, indices) {
26
- ensureInitialized("computeVertexNormals");
27
- return wasm.computeVertexNormals(toFloat32(positions), toUint32(indices));
26
+ ensureInitialized("computeVertexNormals()");
27
+ return call(() => wasm.computeVertexNormals(toFloat32(positions), toUint32(indices)));
28
28
  }
29
29
  /**
30
30
  * Computes the axis-aligned bounding box of a mesh.
@@ -33,8 +33,8 @@ function computeVertexNormals(positions, indices) {
33
33
  * @throws If `positions` is empty or its length is not a multiple of 3.
34
34
  */
35
35
  function computeBounds(positions) {
36
- ensureInitialized("computeBounds");
37
- const b = wasm.computeBounds(toFloat32(positions));
36
+ ensureInitialized("computeBounds()");
37
+ const b = call(() => wasm.computeBounds(toFloat32(positions)));
38
38
  const min = [
39
39
  b[0],
40
40
  b[1],