fast-mesh-wasm 0.2.0 → 0.3.1

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 +490 -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-BpnthBYQ.js +1927 -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-BFd6nYRe.js +1256 -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 +475 -0
  31. package/dist/wasm/fast_mesh_wasm.js +1184 -0
  32. package/dist/wasm/fast_mesh_wasm_bg.wasm +0 -0
  33. package/dist/wasm/fast_mesh_wasm_bg.wasm.d.ts +76 -0
  34. package/dist/wasm-threads/fast_mesh_wasm.d.ts +557 -0
  35. package/dist/wasm-threads/fast_mesh_wasm.js +1547 -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 +95 -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 +255 -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
@@ -0,0 +1,925 @@
1
+ import { InitInput, WasmScene } from "./wasm/fast_mesh_wasm.js";
2
+ //#region src/api.d.ts
3
+ /** A 3D vector `[x, y, z]`. */
4
+ type Vec3 = [x: number, y: number, z: number];
5
+ /**
6
+ * Flat vertex positions `[x0, y0, z0, x1, y1, z1, ...]`.
7
+ * A `Float32Array` is used as is; any other array is converted once.
8
+ */
9
+ type Positions = Float32Array | ArrayLike<number>;
10
+ /**
11
+ * Flat vertex positions in world space for `Scene.addMesh`, kept in double
12
+ * precision until the mesh origin is subtracted.
13
+ * A `Float64Array` is used as is; any other array is converted once.
14
+ */
15
+ type Positions64 = Float32Array | Float64Array | ArrayLike<number>;
16
+ /**
17
+ * Flat triangle indices `[a0, b0, c0, a1, ...]`.
18
+ * A `Uint32Array` is used as is; `Uint16Array` (common in three.js) and plain arrays are converted once.
19
+ */
20
+ type Indices = Uint32Array | Uint16Array | ArrayLike<number>;
21
+ /** A unit quaternion `[x, y, z, w]`; it is normalised before use. */
22
+ type Quat = readonly [x: number, y: number, z: number, w: number];
23
+ /** A 3×3 rotation matrix as 9 numbers, row-major. */
24
+ type Mat3 = readonly number[];
25
+ /**
26
+ * When a mesh's derived data (BVH, normals, fields, sections) follows its edits:
27
+ * right away (`"eager"`), on the next query or `flush()` (`"lazy"`), or only on
28
+ * `update(mesh)` (`"manual"`).
29
+ */
30
+ type UpdateMode = "eager" | "lazy" | "manual";
31
+ /** A placement to set: a rotation (row-major matrix or quaternion) and a translation. */
32
+ interface PlacementInput {
33
+ /** A proper rotation: 9 numbers row-major, or a quaternion `[x, y, z, w]`. */
34
+ rotation: Mat3 | Quat;
35
+ translation: Readonly<Vec3>;
36
+ }
37
+ /** A mesh placement: world = rotation · local + translation. */
38
+ interface Placement {
39
+ /** 9 numbers, row-major. */
40
+ rotation: number[];
41
+ translation: Vec3;
42
+ }
43
+ /** Axis-aligned bounding box. */
44
+ interface Bounds {
45
+ /** Smallest coordinate on each axis. */
46
+ min: Vec3;
47
+ /** Largest coordinate on each axis. */
48
+ max: Vec3;
49
+ /** Box center. */
50
+ center: Vec3;
51
+ /** Box extent: `[width, height, depth]`. */
52
+ size: Vec3;
53
+ }
54
+ /**
55
+ * Computes smooth, area-weighted per-vertex normals.
56
+ *
57
+ * @param positions - Vertex positions. Length must be a multiple of 3.
58
+ * @param indices - Triangle indices. Length must be a multiple of 3.
59
+ * @returns Normals with the same length as `positions`. Vertices not used by any triangle get `[0, 0, 0]`.
60
+ * @throws If a length is not a multiple of 3 or an index is out of range.
61
+ */
62
+ declare function computeVertexNormals(positions: Positions, indices: Indices): Float32Array;
63
+ /**
64
+ * Computes the axis-aligned bounding box of a mesh.
65
+ *
66
+ * @param positions - Vertex positions. Length must be a non-zero multiple of 3.
67
+ * @throws If `positions` is empty or its length is not a multiple of 3.
68
+ */
69
+ declare function computeBounds(positions: Positions): Bounds;
70
+ //#endregion
71
+ //#region src/views.d.ts
72
+ /**
73
+ * Zero-copy views of one mesh's render buffers, slot-aligned.
74
+ *
75
+ * Each getter builds a fresh view over the current wasm memory. A view is
76
+ * only valid until the next scene call that may allocate or move buffers
77
+ * (any edit, add, undo, query, ...): the buffer may have moved, so a kept
78
+ * view may read other data, or be empty once the memory grew. Re-acquire
79
+ * views after every scene call and do not keep them. With
80
+ * `new Scene({ debug: true })` reading a kept view warns.
81
+ */
82
+ interface MeshViews {
83
+ /** Local positions, 3 floats per vertex slot; dead slots hold stale data. */
84
+ positions(): Float32Array;
85
+ /**
86
+ * Vertex normals, 3 floats per vertex slot, or `null` when normals are off.
87
+ * For a `"lazy"` or `"manual"` mesh it can be shorter than 3 · vertex slots
88
+ * after a growth, until the mesh is updated ({@link Scene.update}).
89
+ */
90
+ normals(): Float32Array | null;
91
+ /** RGBA8 colours, 4 bytes per vertex slot, or `null` without colouring. */
92
+ colors(): Uint8Array | null;
93
+ /**
94
+ * The values the colours are made from (the colouring field's values), 1
95
+ * float per vertex slot, or `null` without colouring. They change only at
96
+ * the colours' dirty slots, so they follow the `colors` change ranges.
97
+ * Optional for other {@link SceneLike} hosts; `Scene` and `WorkerScene`
98
+ * provide it.
99
+ */
100
+ values?(): Float32Array | null;
101
+ /** 3 vertex indices per triangle slot; a removed triangle reads `0, 0, 0`. */
102
+ indices(): Uint32Array;
103
+ }
104
+ //#endregion
105
+ //#region src/changes.d.ts
106
+ /** `[start, count]` in elements: vertex slots, or triangle slots for indices. */
107
+ type Range = readonly [start: number, count: number];
108
+ //#endregion
109
+ //#region src/handles.d.ts
110
+ /**
111
+ * A mesh in a {@link Scene}. Opaque: pass it to the scene's methods. The same
112
+ * mesh always gives the same handle object, so handles compare with `===`.
113
+ */
114
+ declare class MeshHandle {
115
+ private readonly brand;
116
+ }
117
+ /**
118
+ * A field in a {@link Scene}. Opaque and deduplicated like {@link MeshHandle}.
119
+ * The scene keeps every field handle it gave out for its own lifetime, even
120
+ * after the field is removed, so a removal in a change record names the same
121
+ * object you hold.
122
+ */
123
+ declare class FieldHandle {
124
+ private readonly brand;
125
+ }
126
+ /**
127
+ * A section in a {@link Scene}. Opaque and deduplicated like {@link MeshHandle},
128
+ * and kept for the scene's lifetime like {@link FieldHandle}.
129
+ */
130
+ declare class SectionHandle {
131
+ private readonly brand;
132
+ }
133
+ //#endregion
134
+ //#region src/scene.d.ts
135
+ /**
136
+ * What changed in one mesh since the previous {@link Scene.takeChanges}.
137
+ * Range lists are ascending; `"all"` means re-upload the whole buffer.
138
+ */
139
+ interface MeshChange {
140
+ mesh: MeshHandle;
141
+ /** The mesh was added; every buffer is `"all"`. */
142
+ added: boolean;
143
+ /** The mesh was removed; drop its GPU buffers. Nothing else is set. */
144
+ removed: boolean;
145
+ /** Its placement changed: read {@link Scene.matrix4} again. */
146
+ placementChanged: boolean;
147
+ /**
148
+ * Its vertex or triangle slot count changed: recreate its GPU buffers. Every
149
+ * buffer is then `"all"`, so upload each one whole.
150
+ */
151
+ capacityChanged: boolean;
152
+ /** Vertex slots. */
153
+ positions: Range[] | "all";
154
+ /** Vertex slots. */
155
+ normals: Range[] | "all";
156
+ /** Vertex slots. */
157
+ colors: Range[] | "all";
158
+ /** Triangle slots. */
159
+ indices: Range[] | "all";
160
+ fieldsChanged: FieldHandle[];
161
+ sectionsChanged: SectionHandle[];
162
+ }
163
+ /**
164
+ * A drag of one mesh: every {@link DragSession.move} until
165
+ * {@link DragSession.end} is one undo step.
166
+ *
167
+ * The drag is over once it is ended or cancelled, and also when its step goes
168
+ * away without it: an `undo()`, `redo()`, `clearHistory()` or `removeMesh()` of
169
+ * the dragged mesh ends it first, and a `cancelStep()` (or an `endStep()` that closes the drag's step) abandons it.
170
+ */
171
+ interface DragSession {
172
+ /**
173
+ * Sets the mesh's placement. Throws `INVALID_ARGUMENT` once the drag is over.
174
+ *
175
+ * Each move recomputes the eager fields that depend on the mesh, so
176
+ * coalesce pointer events to one move per animation frame (keep the latest
177
+ * pose and apply it before {@link Scene.commitFrame}).
178
+ */
179
+ move(placement: PlacementInput): void;
180
+ /**
181
+ * False once the drag is over: ended, cancelled, or ended or abandoned by
182
+ * the scene (`undo()`, `redo()`, `clearHistory()`, `endStep()`,
183
+ * `cancelStep()`, `removeMesh()` of the dragged mesh).
184
+ */
185
+ readonly active: boolean;
186
+ /**
187
+ * Finishes the drag, recording it as one undo step (closing any step levels
188
+ * opened inside it too). A no-op once it is over.
189
+ */
190
+ end(): void;
191
+ /**
192
+ * Puts the placement back to where the drag started and records nothing. A
193
+ * no-op once it is over.
194
+ *
195
+ * When no step was open at `drag()`, this reverts the drag's whole step, so
196
+ * edits made during the drag (including in steps opened inside it) are
197
+ * reverted too. Inside a caller's step, it restores the placement and closes
198
+ * the drag's levels, leaving the caller's step open.
199
+ */
200
+ cancel(): void;
201
+ }
202
+ /** Options of {@link Scene.addMesh}. */
203
+ interface AddMeshOptions {
204
+ /**
205
+ * The point subtracted from every position before it is stored as `f32`.
206
+ * Defaults to the bounding-box centre, which keeps local coordinates small.
207
+ */
208
+ origin?: Readonly<Vec3>;
209
+ /** Defaults to `"eager"`. */
210
+ mode?: UpdateMode;
211
+ /** Keep vertex normals up to date. Defaults to `true`. */
212
+ normals?: boolean;
213
+ }
214
+ /** Options of the {@link Scene} constructor. */
215
+ interface SceneOptions {
216
+ /**
217
+ * Development checks, off by default. Render views ({@link Scene.views},
218
+ * {@link Scene.fieldValues}) are then `Proxy` objects that warn once per
219
+ * scene (`console.warn`, no throw) when read after a scene call that may
220
+ * have moved or freed their buffer. Read-only calls (slot counts,
221
+ * `placement`, `matrix4`, `canUndo`, ...) keep views valid. Proxies are
222
+ * slower and are not genuine typed arrays: pass `view.subarray()` (a plain
223
+ * typed array) to APIs that need one, such as `queue.writeBuffer`. Without
224
+ * `debug`, views are plain typed arrays with no overhead.
225
+ */
226
+ debug?: boolean;
227
+ }
228
+ /** A ray hit from {@link Scene.raycast}, in world coordinates. */
229
+ interface RayHit {
230
+ mesh: MeshHandle;
231
+ /** The triangle slot hit. */
232
+ triangle: number;
233
+ point: Vec3;
234
+ /** The world distance from the ray origin. */
235
+ distance: number;
236
+ /** Barycentric coordinates of `point` in the triangle. */
237
+ barycentric: Vec3;
238
+ }
239
+ /** Options of {@link Scene.raycast}, in world units. */
240
+ interface RaycastOptions {
241
+ /** Smallest distance that counts as a hit (inclusive). Defaults to 0. */
242
+ minDistance?: number;
243
+ /** Largest distance that counts as a hit (inclusive). Defaults to `Infinity`. */
244
+ maxDistance?: number;
245
+ /** Faces to ignore, by the triangle winding. Defaults to `"none"`. */
246
+ cull?: "none" | "back" | "front";
247
+ }
248
+ /** The nearest surface point from {@link Scene.closestPoint}, in world coordinates. */
249
+ interface ClosestHit {
250
+ mesh: MeshHandle;
251
+ /** The triangle slot the point lies on. */
252
+ triangle: number;
253
+ point: Vec3;
254
+ distance: number;
255
+ }
256
+ /** Options of {@link Scene.closestPoint}, in world units. */
257
+ interface ClosestPointOptions {
258
+ /** Largest distance that counts as found (inclusive). Defaults to `Infinity`. */
259
+ maxDistance?: number;
260
+ /** Search this mesh only. Defaults to every mesh. */
261
+ mesh?: MeshHandle;
262
+ }
263
+ /** The closest pair between two meshes from {@link Scene.meshDistance}, in world coordinates. */
264
+ interface MeshDistance {
265
+ /** 0 when the surfaces touch or intersect. */
266
+ distance: number;
267
+ /** The point on the first mesh. */
268
+ a: Vec3;
269
+ /** The point on the second mesh. */
270
+ b: Vec3;
271
+ /** The first mesh's triangle slot that `a` lies on. */
272
+ triangleA: number;
273
+ /** The second mesh's triangle slot that `b` lies on. */
274
+ triangleB: number;
275
+ }
276
+ /** Two meshes within the margin of {@link Scene.findContacts}. */
277
+ interface Contact {
278
+ /** The mesh with the lower id. */
279
+ a: MeshHandle;
280
+ b: MeshHandle;
281
+ /** Whether the meshes intersect or touch, decided exactly. */
282
+ intersecting: boolean;
283
+ /** The distance between the surfaces; 0 when `intersecting`. */
284
+ distance: number;
285
+ /** Triangle slots of `a` within the margin of `b`, ascending. */
286
+ trianglesA: Uint32Array;
287
+ /** Triangle slots of `b` within the margin of `a`, ascending. */
288
+ trianglesB: Uint32Array;
289
+ }
290
+ /** Options of {@link Scene.findContacts}. */
291
+ interface FindContactsOptions {
292
+ /** Report pairs whose surfaces are at most this far apart (world units). Defaults to 0. */
293
+ margin?: number;
294
+ /** Only these pairs, either way round. Defaults to every pair of meshes. */
295
+ pairs?: readonly (readonly [MeshHandle, MeshHandle])[];
296
+ }
297
+ /** How a distance field decides which side of the target surface is inside. */
298
+ type SignMode = "auto" | "pseudonormal" | "winding";
299
+ /** A signed distance field to add with {@link Scene.addDistanceField}. */
300
+ interface DistanceFieldDesc {
301
+ /** Unique among the fields on `on`. */
302
+ name: string;
303
+ /** The mesh whose vertices carry the values. */
304
+ on: MeshHandle;
305
+ /**
306
+ * The mesh the distances are measured to, or several (at least one, all
307
+ * different, not `on`): a vertex then holds the smallest signed distance
308
+ * over them (the nearest surface, or the deepest penetration), and
309
+ * {@link Scene.fieldNearest} tells which one it came from.
310
+ */
311
+ to: MeshHandle | readonly MeshHandle[];
312
+ /** Largest distance computed (inclusive); farther vertices hold `Infinity`. May be `Infinity`. */
313
+ maxDistance: number;
314
+ /** Defaults to `"auto"`. */
315
+ sign?: SignMode;
316
+ }
317
+ /** The state of a field, from {@link Scene.fieldStatus}. */
318
+ interface FieldStatus {
319
+ /** True when the values match the meshes and placements as they are now. */
320
+ current: boolean;
321
+ /**
322
+ * What the latest sign data builds found out about the target meshes,
323
+ * together: `closed` and `consistentOrientation` when every target is, the
324
+ * counts summed, and the first target's `mode`. See
325
+ * {@link Scene.fieldTargetStatus} for each target.
326
+ */
327
+ sign: {
328
+ /** The mode in use (never `"auto"`). */
329
+ mode: Exclude<SignMode, "auto">;
330
+ /** No boundary or non-manifold edge. */
331
+ closed: boolean;
332
+ consistentOrientation: boolean;
333
+ nonManifoldVertices: number;
334
+ degenerateTriangles: number;
335
+ };
336
+ }
337
+ /** An RGBA8 colour, each channel an integer in 0..255. */
338
+ type Rgba = readonly [r: number, g: number, b: number, a: number];
339
+ /**
340
+ * A colormap: a built-in one, or colour stops `[t, rgba]` (at least two, `t`
341
+ * in [0, 1] strictly increasing) interpolated linearly.
342
+ */
343
+ type Colormap = "turbo" | "viridis" | "coolwarm" | "grayscale" | {
344
+ stops: readonly (readonly [t: number, color: Rgba])[];
345
+ };
346
+ /** What to show for a value outside the colour range. */
347
+ type OutOfRange = "clamp" | "base";
348
+ /** How {@link Scene.setColoring} turns a field into vertex colours. */
349
+ interface ColorRule {
350
+ /** A field on the coloured mesh. */
351
+ field: FieldHandle;
352
+ map: Colormap;
353
+ /** `[lo, hi]` mapped onto the colormap; finite, `lo < hi`. */
354
+ range: readonly [lo: number, hi: number];
355
+ /** Values below `lo`: the colormap's end colour or `base`. Defaults to `"clamp"`. */
356
+ below?: OutOfRange;
357
+ /** Values above `hi`, including far (`Infinity`): defaults to `"base"`. */
358
+ above?: OutOfRange;
359
+ /** A value within `range` pinned to the middle of the colormap. */
360
+ center?: number;
361
+ /** The `"base"` colour. Defaults to light grey `[200, 200, 200, 255]`. */
362
+ base?: Rgba;
363
+ /** The colour of NaN (dead or unused vertices). Defaults to `[128, 128, 128, 255]`. */
364
+ nan?: Rgba;
365
+ }
366
+ /** A section plane in world coordinates. */
367
+ interface SectionPlane {
368
+ origin: Readonly<Vec3>;
369
+ /** Points to the plane's `+` side; normalised. */
370
+ normal: Readonly<Vec3>;
371
+ }
372
+ /** A plane section to add with {@link Scene.addSection}. */
373
+ interface SectionDesc {
374
+ plane: SectionPlane;
375
+ /** The meshes cut, each once. */
376
+ meshes: readonly MeshHandle[];
377
+ /** Whether results carry the filled cross-section. Defaults to `false`. */
378
+ fill?: boolean;
379
+ }
380
+ /** One chain of a section: a closed loop or an open polyline. */
381
+ interface SectionContour {
382
+ /** World xyz, 3 floats per point. A copy. */
383
+ points: Float32Array;
384
+ closed: boolean;
385
+ }
386
+ /** A section's result for one mesh, from {@link Scene.section}. Copies, in world coordinates. */
387
+ interface SectionResult {
388
+ /** `"stale"` when not computed yet or something changed since: call {@link Scene.updateSections}. */
389
+ status: "current" | "stale";
390
+ contours: SectionContour[];
391
+ /** Summed length of every contour. */
392
+ length: number;
393
+ /** Summed signed area of the closed, oriented contours (positive counter-clockwise about the normal). */
394
+ area: number;
395
+ /** The filled cross-section, when the section has fill on and it was computed. */
396
+ fill?: {
397
+ positions: Float32Array;
398
+ indices: Uint32Array;
399
+ };
400
+ }
401
+ /** The closest pair between two meshes' contours, from {@link Scene.sectionGap}. */
402
+ interface SectionGap {
403
+ /** Measured in the plane; 0 when the contours cross or touch. */
404
+ distance: number;
405
+ /** World point on the first mesh's contours. */
406
+ a: Vec3;
407
+ /** World point on the second mesh's contours. */
408
+ b: Vec3;
409
+ }
410
+ /**
411
+ * An id produced by an earlier op of the same {@link Scene.edit} list: id `i`
412
+ * of the result of op `opIndex` (a vertex of `addVertices`, a triangle of
413
+ * `addTriangles`).
414
+ */
415
+ interface EditRef {
416
+ ref: readonly [opIndex: number, i: number];
417
+ }
418
+ /**
419
+ * One op of {@link Scene.edit}. Positions are in world space (3 per vertex);
420
+ * ids are vertex or triangle slots, or {@link EditRef}s to ids added earlier
421
+ * in the same list.
422
+ */
423
+ type EditOp = {
424
+ op: "setPositions";
425
+ vertices: Uint32Array | readonly number[];
426
+ positions: Positions64;
427
+ } | {
428
+ op: "addVertices";
429
+ positions: Positions64;
430
+ } | {
431
+ op: "addTriangles";
432
+ triangles: readonly (number | EditRef)[] | Uint32Array;
433
+ } | {
434
+ op: "removeTriangles";
435
+ triangles: Uint32Array | readonly number[];
436
+ } | {
437
+ op: "removeVertices";
438
+ vertices: Uint32Array | readonly number[] | readonly EditRef[];
439
+ };
440
+ /** What {@link Scene.edit} added. */
441
+ interface EditResult {
442
+ /** Per op, in order: the new vertex or triangle ids (empty for ops that add nothing). */
443
+ added: Uint32Array[];
444
+ }
445
+ /**
446
+ * A boundary loop's content fingerprint, valid while its vertex sequence is
447
+ * unchanged: pass it back to `fillHoles` to pick that loop.
448
+ */
449
+ interface LoopId {
450
+ /** The smallest vertex id on the loop. */
451
+ minVertex: number;
452
+ /** The number of vertices on the loop. */
453
+ len: number;
454
+ /** FNV-1a 64 of the loop's vertex ids. */
455
+ hash: bigint;
456
+ }
457
+ /** A chain of boundary edges, from {@link Scene.analyze}. */
458
+ interface BoundaryLoop {
459
+ id: LoopId;
460
+ /** In loop order; a closed loop starts at `id.minVertex`. */
461
+ vertices: Uint32Array;
462
+ /** Length of the closed polygon. */
463
+ perimeter: number;
464
+ /** Vector area of the closed polygon. */
465
+ area: number;
466
+ /** `false` for an open chain (never filled). */
467
+ closed: boolean;
468
+ /** `false` when the loop touches a non-manifold edge, an unordered pinch or an orientation seam. */
469
+ clean: boolean;
470
+ }
471
+ /** Triangles connected through shared edges, from {@link Scene.analyze}. */
472
+ interface MeshComponent {
473
+ /** Ascending. */
474
+ triangles: Uint32Array;
475
+ area: number;
476
+ /** No boundary and no non-manifold edge. */
477
+ closed: boolean;
478
+ }
479
+ /**
480
+ * The defects of a mesh, from {@link Scene.analyze}. Lists with a count beside
481
+ * them keep their first `maxListed` entries; counts are exact.
482
+ */
483
+ interface Analysis {
484
+ loops: BoundaryLoop[];
485
+ /** Groups of two or more coincident vertices. */
486
+ coincidentGroups: number;
487
+ /** The groups, by smallest id, each ascending. */
488
+ coincident: Uint32Array[];
489
+ /** Degenerate triangles (repeated vertex or near-zero area). */
490
+ degenerate: number;
491
+ degenerateList: Uint32Array;
492
+ /** Triangles repeating the vertex set of a triangle with a smaller id. */
493
+ duplicate: number;
494
+ duplicateList: Uint32Array;
495
+ /** Edges with three or more triangles. */
496
+ nonManifoldEdges: number;
497
+ /** Those edges as `[min, max]`, ascending. */
498
+ nonManifoldEdgeList: [number, number][];
499
+ nonManifoldVertices: Uint32Array;
500
+ /** Vertices whose triangle fan splits into several pieces. */
501
+ pinchVertices: Uint32Array;
502
+ components: MeshComponent[];
503
+ /** Interior edges used in the same direction by both their triangles. */
504
+ orientationConflicts: number;
505
+ /** Whether two triangles sharing no vertex intersect; `null` when not checked. */
506
+ selfIntersects: boolean | null;
507
+ }
508
+ /**
509
+ * Options of {@link Scene.analyze}. Distances are in mesh units: placements are
510
+ * rigid, so local and world distances agree.
511
+ */
512
+ interface AnalyzeOptions {
513
+ /**
514
+ * Vertices at most this far apart count as coincident. Defaults to 0 (exact
515
+ * duplicates). Converted to `f32`: a value below the `f32` range rounds to 0.
516
+ */
517
+ weldTolerance?: number;
518
+ /**
519
+ * Check for self-intersection with the mesh's BVH. A stale `"manual"` mesh
520
+ * throws `STALE_BVH`; others are brought up to date first. Defaults to `false`.
521
+ */
522
+ selfIntersection?: boolean;
523
+ /** The most entries kept in each counted list. Defaults to 1000. */
524
+ maxListed?: number;
525
+ }
526
+ /**
527
+ * One repair operation for {@link Scene.repair}. Distances and areas are in
528
+ * mesh units (equal to world units). They are converted to `f32`, so a
529
+ * tolerance or area below the `f32` range rounds to 0.
530
+ */
531
+ type RepairOp = {
532
+ op: "weld";
533
+ tolerance: number;
534
+ } | {
535
+ op: "removeDegenerate";
536
+ areaEpsilon?: number;
537
+ removeUnusedVertices?: boolean;
538
+ } | {
539
+ op: "removeSmallComponents";
540
+ minTriangles?: number;
541
+ minArea?: number;
542
+ keepLargest?: boolean;
543
+ } | {
544
+ op: "orient";
545
+ } | {
546
+ op: "fillHoles";
547
+ maxEdges?: number;
548
+ maxPerimeter?: number;
549
+ maxArea?: number;
550
+ loops?: readonly LoopId[];
551
+ allowUnclean?: boolean;
552
+ fair?: boolean;
553
+ dpLimit?: number;
554
+ };
555
+ /** What `weld` did. */
556
+ interface WeldReport {
557
+ mergedVertices: number;
558
+ removedTriangles: number;
559
+ }
560
+ /** What `removeDegenerate` did. */
561
+ interface DegenerateReport {
562
+ removedTriangles: number;
563
+ removedVertices: number;
564
+ }
565
+ /** What `removeSmallComponents` did. */
566
+ interface RemoveReport {
567
+ removedComponents: number;
568
+ removedTriangles: number;
569
+ removedVertices: number;
570
+ }
571
+ /** What `orient` did. */
572
+ interface OrientReport {
573
+ flippedTriangles: number;
574
+ patches: number;
575
+ nonOrientablePatches: number;
576
+ flippedOutwardComponents: number;
577
+ }
578
+ /** A loop `fillHoles` filled. */
579
+ interface FilledLoop {
580
+ /** The loop as it was before the fill. */
581
+ id: LoopId;
582
+ trianglesAdded: number;
583
+ /** Vertices added by refinement. */
584
+ verticesAdded: number;
585
+ /** Whether fairing converged; `true` when it did not run. */
586
+ converged: boolean;
587
+ /** The Laplacian weights fairing used; `null` when it did not run. */
588
+ weights: "cotangent" | "uniform" | null;
589
+ }
590
+ /** What `fillHoles` did, each list in loop order. */
591
+ interface FillReport {
592
+ filled: FilledLoop[];
593
+ /** Loops left out: beyond a bound, or unclean (or open). */
594
+ skipped: {
595
+ id: LoopId;
596
+ reason: "bounds" | "unclean";
597
+ }[];
598
+ /** Selected loops that could not be filled; they stay open. */
599
+ failed: {
600
+ id: LoopId;
601
+ reason: "projectionFolds" | "noValidTriangulation" | "solver";
602
+ }[];
603
+ }
604
+ /** The report of a {@link RepairOp}. */
605
+ type RepairReport = WeldReport | DegenerateReport | RemoveReport | OrientReport | FillReport;
606
+ /** The report type of a repair op. */
607
+ type RepairReportOf<O extends RepairOp> = O extends {
608
+ op: "weld";
609
+ } ? WeldReport : O extends {
610
+ op: "removeDegenerate";
611
+ } ? DegenerateReport : O extends {
612
+ op: "removeSmallComponents";
613
+ } ? RemoveReport : O extends {
614
+ op: "orient";
615
+ } ? OrientReport : O extends {
616
+ op: "fillHoles";
617
+ } ? FillReport : RepairReport;
618
+ /**
619
+ * A scene of editable meshes. Create it after `await init()`; release it with
620
+ * {@link Scene.free} or a `using` declaration (otherwise it is freed when
621
+ * garbage collected).
622
+ *
623
+ * Render views ({@link Scene.views}) point into WebAssembly memory and are
624
+ * only valid until the next scene call that may allocate or move buffers: a
625
+ * kept view may read other data or be empty. Re-acquire them after every
626
+ * scene call; see {@link MeshViews}.
627
+ */
628
+ declare class Scene implements SceneLike {
629
+ #private;
630
+ constructor(options?: SceneOptions);
631
+ /** Releases the scene and everything in it. Later calls throw `INVALID_ARGUMENT`; calling it again does nothing. */
632
+ free(): void;
633
+ /** Same as {@link Scene.free}, for `using scene = new Scene()`. */
634
+ [Symbol.dispose](): void;
635
+ /**
636
+ * Adds a mesh from world positions. They are stored as `p − origin` in
637
+ * `f32` (see {@link AddMeshOptions.origin}); the placement starts as the
638
+ * identity, so {@link Scene.matrix4} maps the local coordinates back to
639
+ * where they were given.
640
+ *
641
+ * @throws `INVALID_ARGUMENT` for bad lengths or options, `INVALID_INDEX` for an index out of range.
642
+ */
643
+ addMesh(positions: Positions64, indices: Indices, options?: AddMeshOptions): MeshHandle;
644
+ /**
645
+ * Removes a mesh. Its handle then gives `UNKNOWN_MESH`. An active drag of
646
+ * the mesh is ended first, closing its step; the mesh's history entries
647
+ * (the drag's included) are then dropped with it.
648
+ */
649
+ removeMesh(mesh: MeshHandle): void;
650
+ /**
651
+ * Sets a mesh's placement: world = rotation · local + translation, where
652
+ * local is relative to the mesh origin. A quaternion is normalised and
653
+ * converted in double precision.
654
+ *
655
+ * @throws `INVALID_ARGUMENT` when the rotation is not a proper rotation or a quaternion is zero.
656
+ */
657
+ setPlacement(mesh: MeshHandle, placement: PlacementInput): void;
658
+ /** A mesh's placement, with the rotation as a row-major matrix. */
659
+ placement(mesh: MeshHandle): Placement;
660
+ /**
661
+ * The column-major world matrix of the local render coordinates,
662
+ * `placement · translate(origin)`, ready for renderers (convert to `f32`
663
+ * yourself).
664
+ */
665
+ matrix4(mesh: MeshHandle): Float64Array;
666
+ /** Sets when the mesh's derived data follows its edits; see {@link UpdateMode}. */
667
+ setMode(mesh: MeshHandle, mode: UpdateMode): void;
668
+ /** Brings the mesh's derived data up to date now, whatever its mode. */
669
+ update(mesh: MeshHandle): void;
670
+ /** Brings every mesh that is not `"manual"` up to date. */
671
+ flush(): void;
672
+ /** Vertex slots, alive or dead: the vertex length of the render buffers. */
673
+ vertexSlots(mesh: MeshHandle): number;
674
+ /** Triangle slots, alive or dead: the triangle length of the index buffer. */
675
+ triangleSlots(mesh: MeshHandle): number;
676
+ /** Alive vertices. */
677
+ vertexCount(mesh: MeshHandle): number;
678
+ /** Alive triangles. */
679
+ triangleCount(mesh: MeshHandle): number;
680
+ /**
681
+ * Zero-copy views of the mesh's render buffers. Each getter builds a fresh
682
+ * view; re-acquire views after every scene call that may allocate, since a
683
+ * kept one may read other data or be empty (see {@link MeshViews}).
684
+ */
685
+ views(mesh: MeshHandle): MeshViews;
686
+ /**
687
+ * Everything that changed since the previous call, one record per mesh.
688
+ * There is a single consumer: apps that use {@link Scene.onChanges} call
689
+ * {@link Scene.commitFrame} instead.
690
+ */
691
+ takeChanges(): MeshChange[];
692
+ /**
693
+ * Registers a listener for {@link Scene.commitFrame}. Returns a function
694
+ * that unregisters it.
695
+ */
696
+ onChanges(listener: (changes: MeshChange[]) => void): () => void;
697
+ /**
698
+ * Takes the changes once and delivers the same array to every listener,
699
+ * then returns it. Call it once per animation frame. Every listener runs
700
+ * even if one throws; the first error is rethrown afterwards.
701
+ */
702
+ commitFrame(): MeshChange[];
703
+ /**
704
+ * Undoes the latest step; an active drag is ended first. Without an open
705
+ * step around the drag, the drag is what gets undone; inside a caller's
706
+ * open step, that whole step (drag included) is closed and undone. Returns
707
+ * `false` when there is nothing to undo.
708
+ */
709
+ undo(): boolean;
710
+ /** Redoes the latest undone step. Returns `false` when there is nothing to redo. */
711
+ redo(): boolean;
712
+ /** True if {@link Scene.undo} would undo something. */
713
+ canUndo(): boolean;
714
+ /** True if {@link Scene.redo} would redo something. */
715
+ canRedo(): boolean;
716
+ /** Closes an open step, then drops every undo and redo step. */
717
+ clearHistory(): void;
718
+ /**
719
+ * Opens a history step, or one more nesting level of the open one. Edits
720
+ * and placement changes until the matching {@link Scene.endStep} are
721
+ * undone together.
722
+ */
723
+ beginStep(): void;
724
+ /** Ends one nesting level of the open step. Throws `STEP_NOT_OPEN` when none is open. */
725
+ endStep(): void;
726
+ /** Reverts and discards the open step, however deeply nested. Throws `STEP_NOT_OPEN` when none is open. */
727
+ cancelStep(): void;
728
+ /**
729
+ * Starts dragging a mesh: the moves until {@link DragSession.end} form one
730
+ * undo step (nested in the open step, if there is one). One drag at a time.
731
+ * Every {@link DragSession.move} recomputes the eager fields, so make at most
732
+ * one move per animation frame, with the latest pointer pose.
733
+ */
734
+ drag(mesh: MeshHandle): DragSession;
735
+ /**
736
+ * Edits a mesh's geometry with a list of ops, run in Rust as one
737
+ * transaction: one undo step (or part of the open step), and when any op
738
+ * fails nothing changes and nothing is recorded. Positions are world
739
+ * coordinates, mapped to local with the mesh's placement and origin. Ids
740
+ * may be {@link EditRef}s to ids added by earlier ops of the list; every
741
+ * ref is checked before anything is written. Normals, colours, fields,
742
+ * sections and the BVH follow by the mesh's mode.
743
+ *
744
+ * @throws `INVALID_INDEX` for a bad ref or an id that is not alive;
745
+ * `INVALID_ARGUMENT` for a malformed op, positions not 3 per vertex or not
746
+ * finite in local `f32`, or removing a vertex still in use.
747
+ */
748
+ edit(mesh: MeshHandle, ops: readonly EditOp[]): EditResult;
749
+ /**
750
+ * Removes the mesh's dead slots and renumbers the rest. Its next change
751
+ * record has every buffer `"all"` and `capacityChanged` when the slot counts
752
+ * shrank. The mesh's earlier edits leave the history (its placement changes
753
+ * stay undoable).
754
+ */
755
+ compact(mesh: MeshHandle): void;
756
+ /**
757
+ * A read-only report of the mesh's defects: boundary loops (whose ids
758
+ * `fillHoles` takes), coincident vertices, degenerate and duplicate
759
+ * triangles, non-manifold edges and vertices, components, orientation
760
+ * conflicts and, on request, self-intersection.
761
+ *
762
+ * @throws `INVALID_ARGUMENT` for a negative or non-finite `weldTolerance`; `STALE_BVH`, see {@link AnalyzeOptions.selfIntersection}.
763
+ */
764
+ analyze(mesh: MeshHandle, options?: AnalyzeOptions): Analysis;
765
+ /**
766
+ * Runs one repair operation and returns its report, or a list of them in
767
+ * order and returns their reports. A list is one transaction: one undo step,
768
+ * and when any operation fails nothing changes and nothing is recorded.
769
+ *
770
+ * @throws `INVALID_ARGUMENT` for invalid options (`fillHoles` needs a bound or `loops`); `STALE_LOOPS` when a loop id of `fillHoles` no longer matches a loop of the mesh.
771
+ */
772
+ repair<const O extends RepairOp>(mesh: MeshHandle, op: O): RepairReportOf<O>;
773
+ repair<const O extends readonly RepairOp[]>(mesh: MeshHandle, ops: O): { -readonly [K in keyof O]: RepairReportOf<O[K]>; };
774
+ /**
775
+ * The nearest hit of a world ray over every mesh, or `null`. `direction`
776
+ * need not be unit length; `distance` is in world units. Lazy meshes are
777
+ * brought up to date first.
778
+ *
779
+ * @throws `INVALID_ARGUMENT` for a non-finite origin or a zero direction; `STALE_BVH` for a stale `"manual"` mesh.
780
+ */
781
+ raycast(origin: Readonly<Vec3>, direction: Readonly<Vec3>, options?: RaycastOptions): RayHit | null;
782
+ /**
783
+ * The surface point nearest to a world point, over every mesh or one, or
784
+ * `null` when none is within `maxDistance`.
785
+ */
786
+ closestPoint(point: Readonly<Vec3>, options?: ClosestPointOptions): ClosestHit | null;
787
+ /**
788
+ * The distance between two meshes' surfaces as placed, with a closest pair
789
+ * of points, or `null` when it exceeds `maxDistance` (default `Infinity`)
790
+ * or a mesh has no triangle.
791
+ */
792
+ meshDistance(a: MeshHandle, b: MeshHandle, options?: {
793
+ maxDistance?: number;
794
+ }): MeshDistance | null;
795
+ /** Whether two meshes intersect or touch as placed. */
796
+ intersects(a: MeshHandle, b: MeshHandle): boolean;
797
+ /** Every mesh pair (or every pair of `pairs`) within `margin`, sorted by mesh id. */
798
+ findContacts(options?: FindContactsOptions): Contact[];
799
+ /**
800
+ * Adds a signed distance field: one value per vertex slot of `on`, the
801
+ * distance to `to` as placed (negative inside), `Infinity` beyond
802
+ * `maxDistance`, NaN for dead or unused vertices. With several meshes in
803
+ * `to`, the smallest over them, ties going to the earliest. It follows
804
+ * edits and placements by the mesh modes, like normals. Removing a mesh of
805
+ * `to` removes it from the field, or the field with its last target.
806
+ *
807
+ * @throws `INVALID_ARGUMENT` when `to` is empty, holds `on` or a mesh twice, `maxDistance` is negative or NaN, or the name is taken.
808
+ */
809
+ addDistanceField(desc: DistanceFieldDesc): FieldHandle;
810
+ /** Removes a field, and a colouring by it. Its handle then gives `UNKNOWN_FIELD`. */
811
+ removeField(field: FieldHandle): void;
812
+ /**
813
+ * A zero-copy view of the field's values as of its last update, one per
814
+ * vertex slot. Like render views, it is only valid until the next call
815
+ * that may allocate (a kept one may read other data or be empty): get it
816
+ * right before use.
817
+ */
818
+ fieldValues(field: FieldHandle): Float32Array;
819
+ /**
820
+ * Per vertex slot, the index in {@link Scene.fieldTargets} of the target
821
+ * the field's value came from, or `0xffffffff` for none (`Infinity` or
822
+ * NaN). A copy, as of the field's last update.
823
+ */
824
+ fieldNearest(field: FieldHandle): Uint32Array;
825
+ /** The field's target meshes, in index order (a removed target leaves the list). */
826
+ fieldTargets(field: FieldHandle): MeshHandle[];
827
+ /**
828
+ * What the sign data found out about each of the field's targets, in the
829
+ * order of {@link Scene.fieldTargets}.
830
+ */
831
+ fieldTargetStatus(field: FieldHandle): FieldStatus["sign"][];
832
+ /**
833
+ * Whether the field is current, and what its sign data found out about the
834
+ * target meshes, together (see {@link FieldStatus.sign}).
835
+ */
836
+ fieldStatus(field: FieldHandle): FieldStatus;
837
+ /**
838
+ * Colours a mesh from one of its fields (`views(mesh).colors()`), or turns
839
+ * colouring off with `null`, after which `colors()` returns `null`. Every
840
+ * vertex is recoloured and reported as `"all"`; later field updates (edits,
841
+ * drags) report only the vertices whose colour may change. A display
842
+ * setting: never recorded in history.
843
+ *
844
+ * @throws `INVALID_ARGUMENT` when the field is not on `mesh` or the rule is invalid; `UNKNOWN_FIELD`.
845
+ */
846
+ setColoring(mesh: MeshHandle, rule: ColorRule | null): void;
847
+ /**
848
+ * The rule the mesh is coloured by (a frozen copy of the one given to
849
+ * {@link Scene.setColoring}, the same object on every read), or `null`
850
+ * without colouring (never set, turned off, or its field removed).
851
+ *
852
+ * @throws `UNKNOWN_MESH`.
853
+ */
854
+ coloring(mesh: MeshHandle): ColorRule | null;
855
+ /**
856
+ * Adds a plane section of `meshes`. Results of `"eager"` meshes are computed
857
+ * right away; others on {@link Scene.updateSections} or `flush()`.
858
+ *
859
+ * @throws `INVALID_ARGUMENT` for a zero normal or a mesh listed twice.
860
+ */
861
+ addSection(desc: SectionDesc): SectionHandle;
862
+ /** Moves a section's plane. */
863
+ setSectionPlane(section: SectionHandle, plane: SectionPlane): void;
864
+ /**
865
+ * A section's plane as last set by {@link Scene.addSection} or
866
+ * {@link Scene.setSectionPlane}, the normal normalised. Results not yet
867
+ * recomputed (`"stale"`) may still be cut with an earlier plane.
868
+ */
869
+ sectionPlane(section: SectionHandle): SectionPlane;
870
+ /** Changes the meshes a section cuts. */
871
+ setSectionMeshes(section: SectionHandle, meshes: readonly MeshHandle[]): void;
872
+ /** Turns a section's fill on or off. */
873
+ setSectionFill(section: SectionHandle, fill: boolean): void;
874
+ /** Removes a section. Its handle then gives `UNKNOWN_SECTION`. */
875
+ removeSection(section: SectionHandle): void;
876
+ /** Computes every stale section result, whatever the mesh modes. */
877
+ updateSections(): void;
878
+ /**
879
+ * A section's result for one of its meshes as of its last computation
880
+ * (empty before the first), copied, in world coordinates.
881
+ *
882
+ * @throws `INVALID_ARGUMENT` when the section does not cut `mesh`.
883
+ */
884
+ section(section: SectionHandle, mesh: MeshHandle): SectionResult;
885
+ /**
886
+ * The closest pair between two meshes' contours in a section, measured in
887
+ * the plane, or `null` when either has none or their results were cut with
888
+ * different planes (call {@link Scene.updateSections} first).
889
+ */
890
+ sectionGap(section: SectionHandle, a: MeshHandle, b: MeshHandle): SectionGap | null;
891
+ }
892
+ //#endregion
893
+ //#region src/scene-like.d.ts
894
+ /**
895
+ * What the adapters need from a scene: render buffers, placements, section
896
+ * results, change notification and drags. All methods are synchronous.
897
+ */
898
+ interface SceneLike {
899
+ /**
900
+ * Views of the mesh's render buffers. Slot counts follow from them, so
901
+ * `positions()` must be exactly 3 × vertex slots long and `indices()`
902
+ * exactly 3 × triangle slots long (normals 3 and colours 4 per vertex slot,
903
+ * when present): `positions().length / 3` vertex slots and
904
+ * `indices().length / 3` triangle slots.
905
+ */
906
+ views(mesh: MeshHandle): MeshViews;
907
+ /** The column-major world matrix of the mesh's local render coordinates. */
908
+ matrix4(mesh: MeshHandle): Float64Array;
909
+ placement(mesh: MeshHandle): Placement;
910
+ section(s: SectionHandle, mesh: MeshHandle): SectionResult;
911
+ sectionPlane(s: SectionHandle): SectionPlane;
912
+ /** Registers a change listener; returns the function that removes it. */
913
+ onChanges(listener: (c: MeshChange[]) => void): () => void;
914
+ /** Flushes pending changes to the listeners and returns them. */
915
+ commitFrame(): MeshChange[];
916
+ drag(mesh: MeshHandle): DragSession;
917
+ /**
918
+ * The rule the mesh is coloured by, or `null` without colouring. Optional:
919
+ * `bindMesh`'s fragment shading needs it (with `views(mesh).values`) and
920
+ * falls back to vertex colours on a host without it.
921
+ */
922
+ coloring?(mesh: MeshHandle): ColorRule | null;
923
+ }
924
+ //#endregion
925
+ export { PlacementInput as $, RepairOp as A, SectionResult as B, MeshComponent as C, RayHit as D, OutOfRange as E, SceneOptions as F, SectionHandle as G, WeldReport as H, SectionContour as I, Bounds as J, Range as K, SectionDesc as L, RepairReportOf as M, Rgba as N, RaycastOptions as O, Scene as P, Placement as Q, SectionGap as R, MeshChange as S, OrientReport as T, FieldHandle as U, SignMode as V, MeshHandle as W, InitInput as X, Indices as Y, Mat3 as Z, FieldStatus as _, BoundaryLoop as a, computeBounds as at, FindContactsOptions as b, ColorRule as c, DegenerateReport as d, Positions as et, DistanceFieldDesc as f, EditResult as g, EditRef as h, AnalyzeOptions as i, Vec3 as it, RepairReport as j, RemoveReport as k, Colormap as l, EditOp as m, AddMeshOptions as n, Quat as nt, ClosestHit as o, computeVertexNormals as ot, DragSession as p, MeshViews as q, Analysis as r, UpdateMode as rt, ClosestPointOptions as s, SceneLike as t, Positions64 as tt, Contact as u, FillReport as v, MeshDistance as w, LoopId as x, FilledLoop as y, SectionPlane as z };