@woosh/meep-engine 2.157.0 → 2.159.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 (71) hide show
  1. package/package.json +1 -1
  2. package/src/core/binary/BitSet.d.ts.map +1 -1
  3. package/src/core/binary/BitSet.js +6 -1
  4. package/src/core/binary/float_to_uint8.d.ts +4 -1
  5. package/src/core/binary/float_to_uint8.d.ts.map +1 -1
  6. package/src/core/binary/float_to_uint8.js +7 -2
  7. package/src/core/bvh2/bvh3/query/compute_tight_near_far_clipping_planes.d.ts +11 -1
  8. package/src/core/bvh2/bvh3/query/compute_tight_near_far_clipping_planes.d.ts.map +1 -1
  9. package/src/core/bvh2/bvh3/query/compute_tight_near_far_clipping_planes.js +37 -14
  10. package/src/core/geom/3d/shape/PosedShape3D.d.ts +17 -0
  11. package/src/core/geom/3d/shape/PosedShape3D.d.ts.map +1 -1
  12. package/src/core/geom/3d/shape/PosedShape3D.js +50 -0
  13. package/src/core/math/gaussian.d.ts +7 -6
  14. package/src/core/math/gaussian.d.ts.map +1 -1
  15. package/src/core/math/gaussian.js +9 -8
  16. package/src/engine/graphics/ecs/trail2d/Trail2D.d.ts.map +1 -1
  17. package/src/engine/graphics/ecs/trail2d/Trail2D.js +21 -0
  18. package/src/engine/graphics/ecs/trail2d/Trail2DFlags.d.ts +1 -0
  19. package/src/engine/graphics/ecs/trail2d/Trail2DFlags.js +9 -1
  20. package/src/engine/physics/fluid/FluidField.d.ts +53 -9
  21. package/src/engine/physics/fluid/FluidField.d.ts.map +1 -1
  22. package/src/engine/physics/fluid/FluidField.js +684 -600
  23. package/src/engine/physics/fluid/FluidSimulator.d.ts +53 -38
  24. package/src/engine/physics/fluid/FluidSimulator.d.ts.map +1 -1
  25. package/src/engine/physics/fluid/FluidSimulator.js +252 -178
  26. package/src/engine/physics/fluid/REVIEW_02_PLAN.md +155 -26
  27. package/src/engine/physics/fluid/ecs/FluidObstacle.d.ts +72 -0
  28. package/src/engine/physics/fluid/ecs/FluidObstacle.d.ts.map +1 -0
  29. package/src/engine/physics/fluid/ecs/FluidObstacle.js +97 -0
  30. package/src/engine/physics/fluid/ecs/FluidObstacleSystem.d.ts +117 -0
  31. package/src/engine/physics/fluid/ecs/FluidObstacleSystem.d.ts.map +1 -0
  32. package/src/engine/physics/fluid/ecs/FluidObstacleSystem.js +348 -0
  33. package/src/engine/physics/fluid/ecs/FluidSystem.d.ts +3 -3
  34. package/src/engine/physics/fluid/effector/GlobalFluidEffector.d.ts +62 -12
  35. package/src/engine/physics/fluid/effector/GlobalFluidEffector.d.ts.map +1 -1
  36. package/src/engine/physics/fluid/effector/GlobalFluidEffector.js +135 -38
  37. package/src/engine/physics/fluid/effector/ImpulseFluidEffector.d.ts.map +1 -1
  38. package/src/engine/physics/fluid/effector/ImpulseFluidEffector.js +85 -38
  39. package/src/engine/physics/fluid/effector/WakeFluidEffector.d.ts.map +1 -1
  40. package/src/engine/physics/fluid/effector/WakeFluidEffector.js +104 -50
  41. package/src/engine/physics/fluid/prototype.js +25 -1
  42. package/src/engine/physics/fluid/solver/v3_grid_sample_scalar_masked.d.ts +30 -0
  43. package/src/engine/physics/fluid/solver/v3_grid_sample_scalar_masked.d.ts.map +1 -0
  44. package/src/engine/physics/fluid/solver/v3_grid_sample_scalar_masked.js +92 -0
  45. package/src/engine/physics/fluid/solver/v3_mac_advect_maccormack_velocity.d.ts +42 -0
  46. package/src/engine/physics/fluid/solver/v3_mac_advect_maccormack_velocity.d.ts.map +1 -0
  47. package/src/engine/physics/fluid/solver/v3_mac_advect_maccormack_velocity.js +319 -0
  48. package/src/engine/physics/fluid/solver/v3_mac_advect_scalar.d.ts +53 -0
  49. package/src/engine/physics/fluid/solver/v3_mac_advect_scalar.d.ts.map +1 -0
  50. package/src/engine/physics/fluid/solver/v3_mac_advect_scalar.js +236 -0
  51. package/src/engine/physics/fluid/solver/v3_mac_advect_sl_velocity.d.ts +46 -0
  52. package/src/engine/physics/fluid/solver/v3_mac_advect_sl_velocity.d.ts.map +1 -0
  53. package/src/engine/physics/fluid/solver/v3_mac_advect_sl_velocity.js +217 -0
  54. package/src/engine/physics/fluid/solver/v3_mac_apply_vorticity_confinement.d.ts +40 -0
  55. package/src/engine/physics/fluid/solver/v3_mac_apply_vorticity_confinement.d.ts.map +1 -0
  56. package/src/engine/physics/fluid/solver/v3_mac_apply_vorticity_confinement.js +165 -0
  57. package/src/engine/physics/fluid/solver/v3_mac_clip_trace.d.ts +44 -0
  58. package/src/engine/physics/fluid/solver/v3_mac_clip_trace.d.ts.map +1 -0
  59. package/src/engine/physics/fluid/solver/v3_mac_clip_trace.js +95 -0
  60. package/src/engine/physics/fluid/solver/v3_mac_compute_divergence.d.ts +38 -0
  61. package/src/engine/physics/fluid/solver/v3_mac_compute_divergence.d.ts.map +1 -0
  62. package/src/engine/physics/fluid/solver/v3_mac_compute_divergence.js +77 -0
  63. package/src/engine/physics/fluid/solver/v3_mac_compute_face_solid.d.ts +52 -0
  64. package/src/engine/physics/fluid/solver/v3_mac_compute_face_solid.d.ts.map +1 -0
  65. package/src/engine/physics/fluid/solver/v3_mac_compute_face_solid.js +131 -0
  66. package/src/engine/physics/fluid/solver/v3_mac_subtract_pressure_gradient.d.ts +38 -0
  67. package/src/engine/physics/fluid/solver/v3_mac_subtract_pressure_gradient.d.ts.map +1 -0
  68. package/src/engine/physics/fluid/solver/v3_mac_subtract_pressure_gradient.js +104 -0
  69. package/src/engine/physics/fluid/effector/AmbientWindFluidEffector.d.ts +0 -41
  70. package/src/engine/physics/fluid/effector/AmbientWindFluidEffector.d.ts.map +0 -1
  71. package/src/engine/physics/fluid/effector/AmbientWindFluidEffector.js +0 -124
@@ -1,600 +1,684 @@
1
- import { assert } from "../../../core/assert.js";
2
- import { combine_hash } from "../../../core/collection/array/combine_hash.js";
3
- import { is_typed_array_equals } from "../../../core/collection/array/typed/is_typed_array_equals.js";
4
- import { sparse_typed_array_hash } from "../../../core/collection/array/typed/sparse_typed_array_hash.js";
5
- import { scs3d_sample_linear } from "../../graphics/texture/3d/scs3d_sample_linear.js";
6
- import { v3_grid_compute_solid_neighbour_mask } from "./solver/v3_grid_compute_solid_neighbour_mask.js";
7
- import { v3_grid_patch_edges_constant } from "./solver/v3_grid_patch_edges_constant.js";
8
- import { v3_grid_patch_edges_uniform } from "./solver/v3_grid_patch_edges_uniform.js";
9
- import { v3_grid_shift_in_place } from "./solver/v3_grid_shift_in_place.js";
10
-
11
- /**
12
- * Cell-centered 3D Eulerian grid for the fluid simulator.
13
- *
14
- * Holds three velocity components (x, y, z), an optional per-cell `solid` mask, and any
15
- * number of user-defined passive scalar attributes that get transported by the flow.
16
- *
17
- * Holds only state whose value carries information across step boundaries. The
18
- * simulator's transient working memory (per-step velocity snapshots, divergence,
19
- * diffusion / scalar ping-pong scratch) lives on the simulator. `pressure` is the
20
- * one exception: it's warm-started each step from the previous solve, so its value
21
- * is genuine cross-step state and belongs here.
22
- *
23
- * All typed array references are STABLE for the lifetime of the field. External
24
- * consumers can safely cache references returned from {@link getScalarData},
25
- * {@link velocity_x}, etc.
26
- *
27
- * @see "Real-Time Fluid Dynamics for Games" (Stam, 2003)
28
- * @see GDC 2019 talk "Wind Simulation in God of War" (Rupert Renard) for the wider
29
- * effector-driven design pattern this package is moving toward.
30
- */
31
- export class FluidField {
32
-
33
- /**
34
- * Grid dimensions in cells, `[x, y, z]`.
35
- * @type {[number, number, number]}
36
- */
37
- #resolution = [0, 0, 0];
38
-
39
- /**
40
- * Velocity X component, length = cell count. Cell-centered, indexed by
41
- * `z * res_x * res_y + y * res_x + x`.
42
- * @type {Float32Array|null}
43
- */
44
- velocity_x = null;
45
-
46
- /**
47
- * @type {Float32Array|null}
48
- */
49
- velocity_y = null;
50
-
51
- /**
52
- * @type {Float32Array|null}
53
- */
54
- velocity_z = null;
55
-
56
- /**
57
- * Per-cell solid flag. `0` = fluid, non-zero = solid (wall). Always allocated by
58
- * {@link build} (zero-filled — every cell defaults to fluid). The solver and every
59
- * effector read this unconditionally, so the array is part of the field's
60
- * uniform shape, not an optional add-on.
61
- * @type {Uint8Array|null}
62
- */
63
- solid = null;
64
-
65
- /**
66
- * Per-cell pre-baked neighbourhood mask consumed by the pressure SOR loop.
67
- * One byte per cell encoding which of the 6 cardinal neighbours are fluid:
68
- *
69
- * bit 0 (= 1) : -x neighbour is fluid (in-bounds AND non-solid)
70
- * bit 1 (= 2) : +x neighbour is fluid
71
- * bit 2 (= 4) : -y neighbour is fluid
72
- * bit 3 (= 8) : +y neighbour is fluid
73
- * bit 4 (= 16) : -z neighbour is fluid
74
- * bit 5 (= 32) : +z neighbour is fluid
75
- * bit 7 (= 128) : this cell is itself solid
76
- *
77
- * A solid cell encodes as `128` (bit 7 set, neighbour bits clear) and an
78
- * isolated fluid cell as `0`, so the SOR / PCG loops' `if ((mask & 63) === 0)
79
- * continue` skip handles both "this cell is solid" and "this fluid cell is
80
- * isolated" with a single comparison instead of one solid-self-check plus six
81
- * solid-neighbour-checks plus six boundary checks. Bit 7 additionally lets
82
- * {@link v3_grid_subtract_pressure_gradient} zero solid-cell velocity without
83
- * consulting the {@link solid} array.
84
- *
85
- * Computed once by {@link recomputeSolidNeighbourMask} after every solid-mask
86
- * mutation. The simulator runs that recompute once per step (after effectors,
87
- * which may splat solids) and at the top of every direct project() call, so
88
- * callers never have to remember to invalidate it; the per-step cost is one
89
- * O(N) byte-pass against the bandwidth-bound SOR sweep that runs many
90
- * iterations per call. {@link shift} also refreshes it after migrating the
91
- * solid mask.
92
- *
93
- * @type {Uint8Array|null}
94
- */
95
- solid_neighbour_mask = null;
96
-
97
- /**
98
- * Per-cell pressure-Laplacian diagonal, baked alongside
99
- * {@link solid_neighbour_mask} by the same kernel pass:
100
- *
101
- * diag = (# fluid neighbours) + (# open faces)
102
- *
103
- * where an open face is one on the domain edge (out-of-bounds neighbour).
104
- * The domain edge is an OPEN boundary ghost pressure 0 so flow can
105
- * vent through it; solid faces are reflecting (Neumann) and drop out of
106
- * the diagonal. A solid cell, or a fluid cell sealed on all six faces,
107
- * has `diag = 0`, which is the solvers' single skip test. Sealed domains
108
- * are built explicitly by lining the boundary with solid cells.
109
- *
110
- * Same freshness contract as {@link solid_neighbour_mask}.
111
- *
112
- * @type {Uint8Array|null}
113
- */
114
- pressure_diag = null;
115
-
116
- /**
117
- * Pressure field from the most recent projection. Owned by the field rather than
118
- * the simulator because the simulator warm-starts each solve from the previous
119
- * result step N+1 depends on the value step N wrote here. If this lived on the
120
- * simulator, replacing the simulator instance between steps would silently degrade
121
- * convergence at the same iteration count.
122
- *
123
- * Storage type is {@link Float32Array} by default, or {@link Float16Array} when
124
- * {@link half_precision_pressure} is enabled before build — see that field for
125
- * the bandwidth-vs-quality trade-off.
126
- *
127
- * Safe to read for debug visualisation. Don't mutate.
128
- * @type {Float32Array|Float16Array|null}
129
- */
130
- pressure = null;
131
-
132
- /**
133
- * Allocate {@link pressure} as {@link Float16Array} instead of {@link Float32Array}.
134
- *
135
- * **Currently slower in V8 — keep `false`.** The intent of this option is to
136
- * halve the memory bandwidth on the pressure SOR sweep (the simulator's
137
- * hottest, bandwidth-bound loop). On hardware with F16C the per-cell f16↔f32
138
- * conversion is ~1 cycle and the bandwidth saving wins. In V8 as of Node 24
139
- * the conversion path is not yet specialized — each read of `pressure[i]`
140
- * goes through a slow generic Float16 unboxing routine, and the result is
141
- * the opposite of what you'd expect: bench at 64³ shows **49% slower** with
142
- * f16, at 128³ **28% slower** (see `bench: half_precision_pressure on/off`
143
- * in bench.spec.js). The bandwidth-savings story still holds in principle;
144
- * it'll likely become a real win once V8 adds inline support for
145
- * Float16Array access (the typed array landed in Node 24 / TC39 Stage 4 only
146
- * recently).
147
- *
148
- * Cost when it does win: Float16 has ~3 decimal digits of precision. The SOR
149
- * iterate rounds to f16 on every write, so iteration error can't fall below
150
- * ~10⁻³ relative. Bench currently shows max|div| within 8% of the f32
151
- * baseline at 64³ and 128³ — acceptable for visual sim but not for
152
- * quantitative pressure use.
153
- *
154
- * Must be set before {@link build}.
155
- *
156
- * The simulator's internal divergence scratch follows this type automatically
157
- * (re-allocated to match `pressure.constructor` on each project call).
158
- *
159
- * @type {boolean}
160
- */
161
- half_precision_pressure = false;
162
-
163
- /**
164
- * @type {{ name: string, data: Float32Array }[]}
165
- */
166
- #scalar_attributes = [];
167
-
168
- #built = false;
169
-
170
- /**
171
- * Set the grid dimensions in cells. Must be called before {@link build}; throws if
172
- * the field is already built.
173
- * @param {number} res_x positive integer
174
- * @param {number} res_y positive integer
175
- * @param {number} res_z positive integer
176
- */
177
- setResolution(res_x, res_y, res_z) {
178
- assert.notOk(this.#built, "resolution cannot be changed after build()");
179
- assert.isPositiveInteger(res_x, "res_x");
180
- assert.isPositiveInteger(res_y, "res_y");
181
- assert.isPositiveInteger(res_z, "res_z");
182
-
183
- this.#resolution[0] = res_x;
184
- this.#resolution[1] = res_y;
185
- this.#resolution[2] = res_z;
186
- }
187
-
188
- /**
189
- * @return {[number, number, number]} A reference to the internal resolution array.
190
- * Do not mutate.
191
- */
192
- getResolution() {
193
- return this.#resolution;
194
- }
195
-
196
- /**
197
- * @return {number} `res_x * res_y * res_z`. Zero until {@link setResolution} is
198
- * called.
199
- */
200
- cellCount() {
201
- return this.#resolution[0] * this.#resolution[1] * this.#resolution[2];
202
- }
203
-
204
- /**
205
- * Register a passive scalar attribute (density, temperature, dye, etc.) that will be
206
- * advected by the velocity field each step. Idempotent — re-adding an existing name
207
- * returns the existing index.
208
- *
209
- * Must be called before {@link build}.
210
- *
211
- * @param {string} name
212
- * @return {number} index of the attribute (use with {@link setScalarAtIndex})
213
- */
214
- addScalar(name) {
215
- assert.notOk(this.#built, "addScalar cannot be called after build()");
216
- assert.isString(name, "name");
217
- assert.greaterThan(name.length, 0, "name must be non-empty");
218
-
219
- const existing = this.#scalar_attributes.findIndex(a => a.name === name);
220
- if (existing !== -1) {
221
- return existing;
222
- }
223
-
224
- const index = this.#scalar_attributes.length;
225
- this.#scalar_attributes.push({ name, data: null });
226
- return index;
227
- }
228
-
229
- /**
230
- * @param {string} name
231
- * @return {number} index the attribute was registered with, or -1 if not present.
232
- */
233
- scalarIndex(name) {
234
- return this.#scalar_attributes.findIndex(a => a.name === name);
235
- }
236
-
237
- /**
238
- * @param {string} name
239
- * @return {Float32Array|null} live buffer for the named scalar, or null if not
240
- * registered.
241
- */
242
- getScalarData(name) {
243
- const a = this.#scalar_attributes.find(a => a.name === name);
244
- return a === undefined ? null : a.data;
245
- }
246
-
247
- /**
248
- * @return {{ name: string, data: Float32Array }[]} Live reference; do not mutate.
249
- */
250
- getScalarAttributes() {
251
- return this.#scalar_attributes;
252
- }
253
-
254
- /**
255
- * Allocate all buffers. Must be called before any read/write. After this point,
256
- * resolution and attribute set are frozen.
257
- */
258
- build() {
259
- assert.notOk(this.#built, "build() called twice");
260
- assert.greaterThanOrEqual(this.#resolution[0], 1, "setResolution(...) must be called before build()");
261
-
262
- const cell_count = this.cellCount();
263
-
264
- this.velocity_x = new Float32Array(cell_count);
265
- this.velocity_y = new Float32Array(cell_count);
266
- this.velocity_z = new Float32Array(cell_count);
267
- this.solid = new Uint8Array(cell_count);
268
- this.solid_neighbour_mask = new Uint8Array(cell_count);
269
- this.pressure_diag = new Uint8Array(cell_count);
270
- const PressureCtor = this.half_precision_pressure ? Float16Array : Float32Array;
271
- this.pressure = new PressureCtor(cell_count);
272
-
273
- for (const attr of this.#scalar_attributes) {
274
- attr.data = new Float32Array(cell_count);
275
- }
276
-
277
- this.#built = true;
278
- }
279
-
280
- /**
281
- * Linear cell index for integer grid coordinates.
282
- * @param {number} x integer in [0, res_x)
283
- * @param {number} y integer in [0, res_y)
284
- * @param {number} z integer in [0, res_z)
285
- * @return {number} flat index `z * res_x * res_y + y * res_x + x`
286
- */
287
- cellIndex(x, y, z) {
288
- const res_x = this.#resolution[0];
289
- const res_y = this.#resolution[1];
290
- const res_z = this.#resolution[2];
291
- assert.greaterThanOrEqual(x, 0, "x");
292
- assert.lessThan(x, res_x, "x");
293
- assert.greaterThanOrEqual(y, 0, "y");
294
- assert.lessThan(y, res_y, "y");
295
- assert.greaterThanOrEqual(z, 0, "z");
296
- assert.lessThan(z, res_z, "z");
297
- return z * res_x * res_y + y * res_x + x;
298
- }
299
-
300
- /**
301
- * Set the velocity at an integer grid cell.
302
- * @param {number} x
303
- * @param {number} y
304
- * @param {number} z
305
- * @param {number} vx
306
- * @param {number} vy
307
- * @param {number} vz
308
- */
309
- setVelocityAt(x, y, z, vx, vy, vz) {
310
- const c = this.cellIndex(x, y, z);
311
- this.velocity_x[c] = vx;
312
- this.velocity_y[c] = vy;
313
- this.velocity_z[c] = vz;
314
- }
315
-
316
- /**
317
- * Add to the velocity at an integer grid cell (impulse).
318
- * @param {number} x
319
- * @param {number} y
320
- * @param {number} z
321
- * @param {number} dvx
322
- * @param {number} dvy
323
- * @param {number} dvz
324
- */
325
- addVelocityAt(x, y, z, dvx, dvy, dvz) {
326
- const c = this.cellIndex(x, y, z);
327
- this.velocity_x[c] += dvx;
328
- this.velocity_y[c] += dvy;
329
- this.velocity_z[c] += dvz;
330
- }
331
-
332
- /**
333
- * @param {number} attribute_index
334
- * @param {number} x
335
- * @param {number} y
336
- * @param {number} z
337
- * @param {number} value
338
- */
339
- setScalarAtIndex(attribute_index, x, y, z, value) {
340
- assert.greaterThanOrEqual(attribute_index, 0, "attribute_index");
341
- assert.lessThan(attribute_index, this.#scalar_attributes.length, "attribute_index");
342
- const c = this.cellIndex(x, y, z);
343
- this.#scalar_attributes[attribute_index].data[c] = value;
344
- }
345
-
346
- /**
347
- * Mark a cell as solid (wall) or fluid.
348
- * @param {number} x
349
- * @param {number} y
350
- * @param {number} z
351
- * @param {boolean} is_solid
352
- */
353
- setSolidAt(x, y, z, is_solid) {
354
- this.solid[this.cellIndex(x, y, z)] = is_solid ? 1 : 0;
355
- }
356
-
357
- /**
358
- * @param {number} x
359
- * @param {number} y
360
- * @param {number} z
361
- * @return {boolean} true if the cell is marked solid.
362
- */
363
- isSolidAt(x, y, z) {
364
- return this.solid[this.cellIndex(x, y, z)] !== 0;
365
- }
366
-
367
- /**
368
- * Sample velocity at a fractional grid position (positions outside the grid are
369
- * clamped). Writes into `out` and returns it.
370
- * @param {Float32Array|number[]} out Length-3 destination.
371
- * @param {number} x
372
- * @param {number} y
373
- * @param {number} z
374
- * @return {Float32Array|number[]} `out`, for chaining.
375
- */
376
- sampleVelocity(out, x, y, z) {
377
- const res_x = this.#resolution[0];
378
- const res_y = this.#resolution[1];
379
- const res_z = this.#resolution[2];
380
- out[0] = scs3d_sample_linear(this.velocity_x, res_x, res_y, res_z, x, y, z);
381
- out[1] = scs3d_sample_linear(this.velocity_y, res_x, res_y, res_z, x, y, z);
382
- out[2] = scs3d_sample_linear(this.velocity_z, res_x, res_y, res_z, x, y, z);
383
- return out;
384
- }
385
-
386
- /**
387
- * Sample a scalar attribute at a fractional grid position.
388
- * @param {string} name
389
- * @param {number} x
390
- * @param {number} y
391
- * @param {number} z
392
- * @return {number} trilinearly-interpolated value at `(x, y, z)`.
393
- */
394
- sampleScalar(name, x, y, z) {
395
- const data = this.getScalarData(name);
396
- assert.notNull(data, `scalar attribute '${name}'`);
397
- return scs3d_sample_linear(data, this.#resolution[0], this.#resolution[1], this.#resolution[2], x, y, z);
398
- }
399
-
400
- /**
401
- * Strict value equality. Two fields are equal iff they have the same resolution,
402
- * the same set of scalar attributes (matched by name AND index), and the same
403
- * buffer contents in `velocity_*`, `solid`, `pressure`, and each scalar. Pre-build
404
- * fields compare by resolution + attribute names only (their buffers are null).
405
- *
406
- * O(N) — walks every cell. Use {@link hash} for change-detection on hot paths.
407
- *
408
- * @param {FluidField} other
409
- * @return {boolean}
410
- */
411
- equals(other) {
412
- if (other === this) {
413
- return true;
414
- }
415
- if (!(other instanceof FluidField)) {
416
- return false;
417
- }
418
-
419
- if (this.#resolution[0] !== other.#resolution[0]
420
- || this.#resolution[1] !== other.#resolution[1]
421
- || this.#resolution[2] !== other.#resolution[2]) {
422
- return false;
423
- }
424
-
425
- if (this.#built !== other.#built) {
426
- return false;
427
- }
428
-
429
- const my_attrs = this.#scalar_attributes;
430
- const other_attrs = other.#scalar_attributes;
431
- if (my_attrs.length !== other_attrs.length) {
432
- return false;
433
- }
434
- for (let i = 0; i < my_attrs.length; i++) {
435
- if (my_attrs[i].name !== other_attrs[i].name) {
436
- return false;
437
- }
438
- }
439
-
440
- if (!this.#built) {
441
- // Buffers are null on both sides; resolution + names already matched.
442
- return true;
443
- }
444
-
445
- if (!is_typed_array_equals(this.velocity_x, other.velocity_x)
446
- || !is_typed_array_equals(this.velocity_y, other.velocity_y)
447
- || !is_typed_array_equals(this.velocity_z, other.velocity_z)) {
448
- return false;
449
- }
450
- if (!is_typed_array_equals(this.solid, other.solid)) {
451
- return false;
452
- }
453
- if (!is_typed_array_equals(this.pressure, other.pressure)) {
454
- return false;
455
- }
456
- for (let i = 0; i < my_attrs.length; i++) {
457
- if (!is_typed_array_equals(my_attrs[i].data, other_attrs[i].data)) {
458
- return false;
459
- }
460
- }
461
- return true;
462
- }
463
-
464
- /**
465
- * Fast hash suitable for change-detection. Combines the resolution and a *sparse*
466
- * sample of the velocity_x buffer — {@link sparse_typed_array_hash} only inspects
467
- * the first ~1024 cells with stride enough to take ~31 samples, regardless of how
468
- * large the field is. The hash will catch most local edits to the velocity field
469
- * but is not a content-perfect fingerprint; for that, fall through to
470
- * {@link equals}.
471
- *
472
- * Constant-time relative to grid size in the common case.
473
- *
474
- * @return {number}
475
- */
476
- hash() {
477
- const velocity_sample = this.#built
478
- ? sparse_typed_array_hash(this.velocity_x, 0, this.velocity_x.length)
479
- : 0;
480
- return combine_hash(
481
- this.#resolution[0],
482
- this.#resolution[1],
483
- this.#resolution[2],
484
- this.#scalar_attributes.length,
485
- velocity_sample
486
- );
487
- }
488
-
489
- /**
490
- * Rebuild {@link solid_neighbour_mask} and {@link pressure_diag} from the
491
- * current {@link solid} buffer.
492
- *
493
- * O(N) — two byte-writes per cell, six byte-reads per cell. Called by the
494
- * simulator once per step and at the top of each direct project() call, so
495
- * callers never have to remember to invalidate the mask after mutating
496
- * solids; the cost is amortized across the SOR sweep's many iterations.
497
- *
498
- * Encoding: see {@link solid_neighbour_mask} and {@link pressure_diag}.
499
- */
500
- recomputeSolidNeighbourMask() {
501
- if (!this.#built) {
502
- return;
503
- }
504
- v3_grid_compute_solid_neighbour_mask(
505
- this.solid_neighbour_mask,
506
- this.pressure_diag,
507
- this.solid,
508
- this.#resolution[0], this.#resolution[1], this.#resolution[2]
509
- );
510
- }
511
-
512
- /**
513
- * Translate the field's contents by `(shift_x, shift_y, shift_z)` grid cells —
514
- * called when the field's world-space origin moves, so the fluid data (anchored
515
- * to world space) follows. Every owned buffer (velocity_x/y/z, solid, pressure,
516
- * each scalar attribute) is shifted, then the newly-exposed edges are patched
517
- * via {@link v3_grid_patch_edges_uniform} (zero-gradient Neumann extrapolation —
518
- * "the field is locally uniform").
519
- *
520
- * Direction convention matches the primitive: positive shift means the grid's
521
- * world origin moved in that direction, so each cell takes the value previously
522
- * at its `+shift` neighbour.
523
- *
524
- * `(0, 0, 0)` is a no-op; |shift| ≥ res on any axis zero-fills (no valid source
525
- * left to replicate from). Pre-build fields (buffers null) are no-op'd.
526
- *
527
- * The solid mask is migrated like every other buffer — solids are anchored to
528
- * world space exactly like the fluid they bound, so a wall must stay where the
529
- * world says it is when the grid hops a cell. Newly scrolled-in cells become
530
- * fluid (`0`): the field knows nothing about un-simulated space, and "empty
531
- * until a voxelizer says otherwise" is the only honest default. Callers that
532
- * voxelize scene geometry can keep overwriting the mask each tick — the
533
- * migrated values are then simply replaced. (Earlier behaviour cleared the
534
- * whole mask on shift, which made every grid hop simulate one tick with no
535
- * walls anywhere — fluid leaked through geometry until the caller re-splatted.)
536
- *
537
- * The derived {@link solid_neighbour_mask} is refreshed here too, so the field
538
- * stays self-consistent for direct kernel users; the simulator's per-step
539
- * refresh makes this redundant in the ECS path but shifts are rare (once per
540
- * cell crossing) and the pass is one byte-write per cell.
541
- *
542
- * @param {number} shift_x integer
543
- * @param {number} shift_y integer
544
- * @param {number} shift_z integer
545
- */
546
- shift(shift_x, shift_y, shift_z) {
547
- if (!this.#built) {
548
- return;
549
- }
550
- if (shift_x === 0 && shift_y === 0 && shift_z === 0) {
551
- return;
552
- }
553
-
554
- const rx = this.#resolution[0];
555
- const ry = this.#resolution[1];
556
- const rz = this.#resolution[2];
557
-
558
- // Velocity components.
559
- v3_grid_shift_in_place(this.velocity_x, rx, ry, rz, shift_x, shift_y, shift_z);
560
- v3_grid_patch_edges_uniform(this.velocity_x, rx, ry, rz, shift_x, shift_y, shift_z);
561
-
562
- v3_grid_shift_in_place(this.velocity_y, rx, ry, rz, shift_x, shift_y, shift_z);
563
- v3_grid_patch_edges_uniform(this.velocity_y, rx, ry, rz, shift_x, shift_y, shift_z);
564
-
565
- v3_grid_shift_in_place(this.velocity_z, rx, ry, rz, shift_x, shift_y, shift_z);
566
- v3_grid_patch_edges_uniform(this.velocity_z, rx, ry, rz, shift_x, shift_y, shift_z);
567
-
568
- // Solid mask world-anchored like the fluid; scrolled-in cells are fluid.
569
- v3_grid_shift_in_place(this.solid, rx, ry, rz, shift_x, shift_y, shift_z);
570
- v3_grid_patch_edges_constant(this.solid, rx, ry, rz, shift_x, shift_y, shift_z, 0);
571
- v3_grid_compute_solid_neighbour_mask(this.solid_neighbour_mask, this.pressure_diag, this.solid, rx, ry, rz);
572
-
573
- // Pressure (warm-start state, carried across steps).
574
- v3_grid_shift_in_place(this.pressure, rx, ry, rz, shift_x, shift_y, shift_z);
575
- v3_grid_patch_edges_uniform(this.pressure, rx, ry, rz, shift_x, shift_y, shift_z);
576
-
577
- // Scalar attributes.
578
- for (let i = 0; i < this.#scalar_attributes.length; i++) {
579
- const data = this.#scalar_attributes[i].data;
580
- v3_grid_shift_in_place(data, rx, ry, rz, shift_x, shift_y, shift_z);
581
- v3_grid_patch_edges_uniform(data, rx, ry, rz, shift_x, shift_y, shift_z);
582
- }
583
- }
584
-
585
- /**
586
- * Zero velocity, pressure, and all scalar attributes. Solid mask is preserved.
587
- * Pressure is cleared to drop the warm-start (otherwise the next step's solve
588
- * begins from a stale solution that no longer matches the zero velocity).
589
- */
590
- clear() {
591
- assert.ok(this.#built, "build() must be called before clear()");
592
- this.velocity_x.fill(0);
593
- this.velocity_y.fill(0);
594
- this.velocity_z.fill(0);
595
- this.pressure.fill(0);
596
- for (const attr of this.#scalar_attributes) {
597
- attr.data.fill(0);
598
- }
599
- }
600
- }
1
+ import { assert } from "../../../core/assert.js";
2
+ import { combine_hash } from "../../../core/collection/array/combine_hash.js";
3
+ import { is_typed_array_equals } from "../../../core/collection/array/typed/is_typed_array_equals.js";
4
+ import { sparse_typed_array_hash } from "../../../core/collection/array/typed/sparse_typed_array_hash.js";
5
+ import { scs3d_sample_linear } from "../../graphics/texture/3d/scs3d_sample_linear.js";
6
+ import { v3_grid_compute_solid_neighbour_mask } from "./solver/v3_grid_compute_solid_neighbour_mask.js";
7
+ import { v3_grid_patch_edges_constant } from "./solver/v3_grid_patch_edges_constant.js";
8
+ import { v3_grid_patch_edges_uniform } from "./solver/v3_grid_patch_edges_uniform.js";
9
+ import { v3_grid_shift_in_place } from "./solver/v3_grid_shift_in_place.js";
10
+ import { v3_mac_compute_face_solid } from "./solver/v3_mac_compute_face_solid.js";
11
+
12
+ /**
13
+ * 3D Eulerian grid for the fluid simulator — MAC (marker-and-cell) staggered
14
+ * layout: pressure, solids and scalars live at cell centers; each velocity
15
+ * component lives on the cell FACES normal to it (Harlow & Welch 1965).
16
+ *
17
+ * Staggering makes the discrete divergence and pressure gradient exact
18
+ * adjoints, so projection drives divergence to actual zero (no collocated
19
+ * operator-mismatch floor, no projection-invisible checkerboard modes) and
20
+ * solid boundaries pin the exact normal face velocity (true no-penetration).
21
+ *
22
+ * Holds three face-centered velocity components, a per-cell `solid` mask, and any
23
+ * number of user-defined cell-centered passive scalar attributes transported by
24
+ * the flow.
25
+ *
26
+ * Holds only state whose value carries information across step boundaries. The
27
+ * simulator's transient working memory (per-step velocity snapshots, divergence,
28
+ * diffusion / scalar ping-pong scratch) lives on the simulator. `pressure` is the
29
+ * one exception: it's warm-started each step from the previous solve, so its value
30
+ * is genuine cross-step state and belongs here.
31
+ *
32
+ * All typed array references are STABLE for the lifetime of the field. External
33
+ * consumers can safely cache references returned from {@link getScalarData},
34
+ * {@link velocity_x}, etc.
35
+ *
36
+ * @see "Real-Time Fluid Dynamics for Games" (Stam, 2003)
37
+ * @see GDC 2019 talk "Wind Simulation in God of War" (Rupert Renard) for the wider
38
+ * effector-driven design pattern this package is moving toward.
39
+ */
40
+ export class FluidField {
41
+
42
+ /**
43
+ * Grid dimensions in cells, `[x, y, z]`.
44
+ * @type {[number, number, number]}
45
+ */
46
+ #resolution = [0, 0, 0];
47
+
48
+ /**
49
+ * Velocity X component on x-faces. Length `(res_x+1) * res_y * res_z`,
50
+ * indexed by `z * (res_x+1) * res_y + y * (res_x+1) + x` with
51
+ * `x ∈ [0, res_x]`. Face `(x, y, z)` sits between cells `(x−1, y, z)` and
52
+ * `(x, y, z)` — at grid-space position `(x − 0.5, y, z)` in the
53
+ * cell-center coordinate frame.
54
+ * @type {Float32Array|null}
55
+ */
56
+ velocity_x = null;
57
+
58
+ /**
59
+ * Velocity Y component on y-faces. Length `res_x * (res_y+1) * res_z`,
60
+ * indexed by `z * res_x * (res_y+1) + y * res_x + x` with `y ∈ [0, res_y]`.
61
+ * @type {Float32Array|null}
62
+ */
63
+ velocity_y = null;
64
+
65
+ /**
66
+ * Velocity Z component on z-faces. Length `res_x * res_y * (res_z+1)`,
67
+ * indexed by `z * res_x * res_y + y * res_x + x` with `z ∈ [0, res_z]`
68
+ * (the face slice size equals the cell slice size).
69
+ * @type {Float32Array|null}
70
+ */
71
+ velocity_z = null;
72
+
73
+ /**
74
+ * Per-cell solid flag. `0` = fluid, non-zero = solid (wall). Always allocated by
75
+ * {@link build} (zero-filled every cell defaults to fluid). The solver and every
76
+ * effector read this unconditionally, so the array is part of the field's
77
+ * uniform shape, not an optional add-on.
78
+ * @type {Uint8Array|null}
79
+ */
80
+ solid = null;
81
+
82
+ /**
83
+ * Per-cell pre-baked neighbourhood mask consumed by the pressure SOR loop.
84
+ * One byte per cell encoding which of the 6 cardinal neighbours are fluid:
85
+ *
86
+ * bit 0 (= 1) : -x neighbour is fluid (in-bounds AND non-solid)
87
+ * bit 1 (= 2) : +x neighbour is fluid
88
+ * bit 2 (= 4) : -y neighbour is fluid
89
+ * bit 3 (= 8) : +y neighbour is fluid
90
+ * bit 4 (= 16) : -z neighbour is fluid
91
+ * bit 5 (= 32) : +z neighbour is fluid
92
+ * bit 7 (= 128) : this cell is itself solid
93
+ *
94
+ * A solid cell encodes as `128` (bit 7 set, neighbour bits clear) and an
95
+ * isolated fluid cell as `0`, so the SOR / PCG loops' `if ((mask & 63) === 0)
96
+ * continue` skip handles both "this cell is solid" and "this fluid cell is
97
+ * isolated" with a single comparison instead of one solid-self-check plus six
98
+ * solid-neighbour-checks plus six boundary checks. Bit 7 additionally lets
99
+ * {@link v3_grid_subtract_pressure_gradient} zero solid-cell velocity without
100
+ * consulting the {@link solid} array.
101
+ *
102
+ * Computed once by {@link recomputeSolidNeighbourMask} after every solid-mask
103
+ * mutation. The simulator runs that recompute once per step (after effectors,
104
+ * which may splat solids) and at the top of every direct project() call, so
105
+ * callers never have to remember to invalidate it; the per-step cost is one
106
+ * O(N) byte-pass against the bandwidth-bound SOR sweep that runs many
107
+ * iterations per call. {@link shift} also refreshes it after migrating the
108
+ * solid mask.
109
+ *
110
+ * @type {Uint8Array|null}
111
+ */
112
+ solid_neighbour_mask = null;
113
+
114
+ /**
115
+ * Per-face "pinned" mask for x-faces: `1` where either adjacent cell is
116
+ * solid — the face's normal velocity is a boundary condition (0 for
117
+ * static solids), not a degree of freedom. Same length and indexing as
118
+ * {@link velocity_x}. Baked by {@link recomputeSolidNeighbourMask} via
119
+ * {@link v3_mac_compute_face_solid}; domain-edge faces stay 0 (open).
120
+ * @type {Uint8Array|null}
121
+ */
122
+ face_solid_x = null;
123
+
124
+ /**
125
+ * y-face pinned mask — see {@link face_solid_x}.
126
+ * @type {Uint8Array|null}
127
+ */
128
+ face_solid_y = null;
129
+
130
+ /**
131
+ * z-face pinned mask — see {@link face_solid_x}.
132
+ * @type {Uint8Array|null}
133
+ */
134
+ face_solid_z = null;
135
+
136
+ /**
137
+ * Per-cell pressure-Laplacian diagonal, baked alongside
138
+ * {@link solid_neighbour_mask} by the same kernel pass:
139
+ *
140
+ * diag = (# fluid neighbours) + (# open faces)
141
+ *
142
+ * where an open face is one on the domain edge (out-of-bounds neighbour).
143
+ * The domain edge is an OPEN boundary ghost pressure 0 — so flow can
144
+ * vent through it; solid faces are reflecting (Neumann) and drop out of
145
+ * the diagonal. A solid cell, or a fluid cell sealed on all six faces,
146
+ * has `diag = 0`, which is the solvers' single skip test. Sealed domains
147
+ * are built explicitly by lining the boundary with solid cells.
148
+ *
149
+ * Same freshness contract as {@link solid_neighbour_mask}.
150
+ *
151
+ * @type {Uint8Array|null}
152
+ */
153
+ pressure_diag = null;
154
+
155
+ /**
156
+ * Pressure field from the most recent projection. Owned by the field rather than
157
+ * the simulator because the simulator warm-starts each solve from the previous
158
+ * result — step N+1 depends on the value step N wrote here. If this lived on the
159
+ * simulator, replacing the simulator instance between steps would silently degrade
160
+ * convergence at the same iteration count.
161
+ *
162
+ * Storage type is {@link Float32Array} by default, or {@link Float16Array} when
163
+ * {@link half_precision_pressure} is enabled before build — see that field for
164
+ * the bandwidth-vs-quality trade-off.
165
+ *
166
+ * Safe to read for debug visualisation. Don't mutate.
167
+ * @type {Float32Array|Float16Array|null}
168
+ */
169
+ pressure = null;
170
+
171
+ /**
172
+ * Allocate {@link pressure} as {@link Float16Array} instead of {@link Float32Array}.
173
+ *
174
+ * **Currently slower in V8 — keep `false`.** The intent of this option is to
175
+ * halve the memory bandwidth on the pressure SOR sweep (the simulator's
176
+ * hottest, bandwidth-bound loop). On hardware with F16C the per-cell f16↔f32
177
+ * conversion is ~1 cycle and the bandwidth saving wins. In V8 as of Node 24
178
+ * the conversion path is not yet specialized — each read of `pressure[i]`
179
+ * goes through a slow generic Float16 unboxing routine, and the result is
180
+ * the opposite of what you'd expect: bench at 64³ shows **49% slower** with
181
+ * f16, at 128³ **28% slower** (see `bench: half_precision_pressure on/off`
182
+ * in bench.spec.js). The bandwidth-savings story still holds in principle;
183
+ * it'll likely become a real win once V8 adds inline support for
184
+ * Float16Array access (the typed array landed in Node 24 / TC39 Stage 4 only
185
+ * recently).
186
+ *
187
+ * Cost when it does win: Float16 has ~3 decimal digits of precision. The SOR
188
+ * iterate rounds to f16 on every write, so iteration error can't fall below
189
+ * ~10⁻³ relative. Bench currently shows max|div| within 8% of the f32
190
+ * baseline at 64³ and 128³ — acceptable for visual sim but not for
191
+ * quantitative pressure use.
192
+ *
193
+ * Must be set before {@link build}.
194
+ *
195
+ * The simulator's internal divergence scratch follows this type automatically
196
+ * (re-allocated to match `pressure.constructor` on each project call).
197
+ *
198
+ * @type {boolean}
199
+ */
200
+ half_precision_pressure = false;
201
+
202
+ /**
203
+ * @type {{ name: string, data: Float32Array }[]}
204
+ */
205
+ #scalar_attributes = [];
206
+
207
+ #built = false;
208
+
209
+ /**
210
+ * Set the grid dimensions in cells. Must be called before {@link build}; throws if
211
+ * the field is already built.
212
+ * @param {number} res_x positive integer
213
+ * @param {number} res_y positive integer
214
+ * @param {number} res_z positive integer
215
+ */
216
+ setResolution(res_x, res_y, res_z) {
217
+ assert.notOk(this.#built, "resolution cannot be changed after build()");
218
+ assert.isPositiveInteger(res_x, "res_x");
219
+ assert.isPositiveInteger(res_y, "res_y");
220
+ assert.isPositiveInteger(res_z, "res_z");
221
+
222
+ this.#resolution[0] = res_x;
223
+ this.#resolution[1] = res_y;
224
+ this.#resolution[2] = res_z;
225
+ }
226
+
227
+ /**
228
+ * @return {[number, number, number]} A reference to the internal resolution array.
229
+ * Do not mutate.
230
+ */
231
+ getResolution() {
232
+ return this.#resolution;
233
+ }
234
+
235
+ /**
236
+ * @return {number} `res_x * res_y * res_z`. Zero until {@link setResolution} is
237
+ * called.
238
+ */
239
+ cellCount() {
240
+ return this.#resolution[0] * this.#resolution[1] * this.#resolution[2];
241
+ }
242
+
243
+ /**
244
+ * Register a passive scalar attribute (density, temperature, dye, etc.) that will be
245
+ * advected by the velocity field each step. Idempotent — re-adding an existing name
246
+ * returns the existing index.
247
+ *
248
+ * Must be called before {@link build}.
249
+ *
250
+ * @param {string} name
251
+ * @return {number} index of the attribute (use with {@link setScalarAtIndex})
252
+ */
253
+ addScalar(name) {
254
+ assert.notOk(this.#built, "addScalar cannot be called after build()");
255
+ assert.isString(name, "name");
256
+ assert.greaterThan(name.length, 0, "name must be non-empty");
257
+
258
+ const existing = this.#scalar_attributes.findIndex(a => a.name === name);
259
+ if (existing !== -1) {
260
+ return existing;
261
+ }
262
+
263
+ const index = this.#scalar_attributes.length;
264
+ this.#scalar_attributes.push({ name, data: null });
265
+ return index;
266
+ }
267
+
268
+ /**
269
+ * @param {string} name
270
+ * @return {number} index the attribute was registered with, or -1 if not present.
271
+ */
272
+ scalarIndex(name) {
273
+ return this.#scalar_attributes.findIndex(a => a.name === name);
274
+ }
275
+
276
+ /**
277
+ * @param {string} name
278
+ * @return {Float32Array|null} live buffer for the named scalar, or null if not
279
+ * registered.
280
+ */
281
+ getScalarData(name) {
282
+ const a = this.#scalar_attributes.find(a => a.name === name);
283
+ return a === undefined ? null : a.data;
284
+ }
285
+
286
+ /**
287
+ * @return {{ name: string, data: Float32Array }[]} Live reference; do not mutate.
288
+ */
289
+ getScalarAttributes() {
290
+ return this.#scalar_attributes;
291
+ }
292
+
293
+ /**
294
+ * Allocate all buffers. Must be called before any read/write. After this point,
295
+ * resolution and attribute set are frozen.
296
+ */
297
+ build() {
298
+ assert.notOk(this.#built, "build() called twice");
299
+ assert.greaterThanOrEqual(this.#resolution[0], 1, "setResolution(...) must be called before build()");
300
+
301
+ const cell_count = this.cellCount();
302
+ const rx = this.#resolution[0];
303
+ const ry = this.#resolution[1];
304
+ const rz = this.#resolution[2];
305
+ const face_count_x = (rx + 1) * ry * rz;
306
+ const face_count_y = rx * (ry + 1) * rz;
307
+ const face_count_z = rx * ry * (rz + 1);
308
+
309
+ this.velocity_x = new Float32Array(face_count_x);
310
+ this.velocity_y = new Float32Array(face_count_y);
311
+ this.velocity_z = new Float32Array(face_count_z);
312
+ this.face_solid_x = new Uint8Array(face_count_x);
313
+ this.face_solid_y = new Uint8Array(face_count_y);
314
+ this.face_solid_z = new Uint8Array(face_count_z);
315
+ this.solid = new Uint8Array(cell_count);
316
+ this.solid_neighbour_mask = new Uint8Array(cell_count);
317
+ this.pressure_diag = new Uint8Array(cell_count);
318
+ const PressureCtor = this.half_precision_pressure ? Float16Array : Float32Array;
319
+ this.pressure = new PressureCtor(cell_count);
320
+
321
+ for (const attr of this.#scalar_attributes) {
322
+ attr.data = new Float32Array(cell_count);
323
+ }
324
+
325
+ this.#built = true;
326
+ }
327
+
328
+ /**
329
+ * Linear cell index for integer grid coordinates.
330
+ * @param {number} x integer in [0, res_x)
331
+ * @param {number} y integer in [0, res_y)
332
+ * @param {number} z integer in [0, res_z)
333
+ * @return {number} flat index `z * res_x * res_y + y * res_x + x`
334
+ */
335
+ cellIndex(x, y, z) {
336
+ const res_x = this.#resolution[0];
337
+ const res_y = this.#resolution[1];
338
+ const res_z = this.#resolution[2];
339
+ assert.greaterThanOrEqual(x, 0, "x");
340
+ assert.lessThan(x, res_x, "x");
341
+ assert.greaterThanOrEqual(y, 0, "y");
342
+ assert.lessThan(y, res_y, "y");
343
+ assert.greaterThanOrEqual(z, 0, "z");
344
+ assert.lessThan(z, res_z, "z");
345
+ return z * res_x * res_y + y * res_x + x;
346
+ }
347
+
348
+ /**
349
+ * Set the velocity of an integer grid cell: each component is written to
350
+ * BOTH faces of the cell along its axis, so sampling at the cell centre
351
+ * reads back exactly `(vx, vy, vz)`. Adjacent cells share faces — the
352
+ * later write wins on a shared face, exactly like overlapping
353
+ * cell-centered writes used to.
354
+ * @param {number} x
355
+ * @param {number} y
356
+ * @param {number} z
357
+ * @param {number} vx
358
+ * @param {number} vy
359
+ * @param {number} vz
360
+ */
361
+ setVelocityAt(x, y, z, vx, vy, vz) {
362
+ this.cellIndex(x, y, z); // asserts bounds
363
+ const rx = this.#resolution[0];
364
+ const ry = this.#resolution[1];
365
+ const sx = rx + 1;
366
+ const u = z * sx * ry + y * sx + x;
367
+ this.velocity_x[u] = vx;
368
+ this.velocity_x[u + 1] = vx;
369
+ const v = z * rx * (ry + 1) + y * rx + x;
370
+ this.velocity_y[v] = vy;
371
+ this.velocity_y[v + rx] = vy;
372
+ const w = z * rx * ry + y * rx + x;
373
+ this.velocity_z[w] = vz;
374
+ this.velocity_z[w + rx * ry] = vz;
375
+ }
376
+
377
+ /**
378
+ * Add to the velocity of an integer grid cell (impulse). Deposits each
379
+ * component onto BOTH faces of the cell along its axis; the centre-sampled
380
+ * velocity increases by exactly `(dvx, dvy, dvz)`.
381
+ * @param {number} x
382
+ * @param {number} y
383
+ * @param {number} z
384
+ * @param {number} dvx
385
+ * @param {number} dvy
386
+ * @param {number} dvz
387
+ */
388
+ addVelocityAt(x, y, z, dvx, dvy, dvz) {
389
+ this.cellIndex(x, y, z); // asserts bounds
390
+ const rx = this.#resolution[0];
391
+ const ry = this.#resolution[1];
392
+ const sx = rx + 1;
393
+ const u = z * sx * ry + y * sx + x;
394
+ this.velocity_x[u] += dvx;
395
+ this.velocity_x[u + 1] += dvx;
396
+ const v = z * rx * (ry + 1) + y * rx + x;
397
+ this.velocity_y[v] += dvy;
398
+ this.velocity_y[v + rx] += dvy;
399
+ const w = z * rx * ry + y * rx + x;
400
+ this.velocity_z[w] += dvz;
401
+ this.velocity_z[w + rx * ry] += dvz;
402
+ }
403
+
404
+ /**
405
+ * @param {number} attribute_index
406
+ * @param {number} x
407
+ * @param {number} y
408
+ * @param {number} z
409
+ * @param {number} value
410
+ */
411
+ setScalarAtIndex(attribute_index, x, y, z, value) {
412
+ assert.greaterThanOrEqual(attribute_index, 0, "attribute_index");
413
+ assert.lessThan(attribute_index, this.#scalar_attributes.length, "attribute_index");
414
+ const c = this.cellIndex(x, y, z);
415
+ this.#scalar_attributes[attribute_index].data[c] = value;
416
+ }
417
+
418
+ /**
419
+ * Mark a cell as solid (wall) or fluid.
420
+ * @param {number} x
421
+ * @param {number} y
422
+ * @param {number} z
423
+ * @param {boolean} is_solid
424
+ */
425
+ setSolidAt(x, y, z, is_solid) {
426
+ this.solid[this.cellIndex(x, y, z)] = is_solid ? 1 : 0;
427
+ }
428
+
429
+ /**
430
+ * @param {number} x
431
+ * @param {number} y
432
+ * @param {number} z
433
+ * @return {boolean} true if the cell is marked solid.
434
+ */
435
+ isSolidAt(x, y, z) {
436
+ return this.solid[this.cellIndex(x, y, z)] !== 0;
437
+ }
438
+
439
+ /**
440
+ * Sample velocity at a fractional grid position in CELL-CENTER coordinates
441
+ * (positions outside the grid are clamped). Each component is trilinearly
442
+ * interpolated on its own staggered face lattice — x-face `i` sits at
443
+ * `x = i − 0.5`, so the component is sampled at `x + 0.5` in face-index
444
+ * space, and likewise per axis. Writes into `out` and returns it.
445
+ * @param {Float32Array|number[]} out Length-3 destination.
446
+ * @param {number} x
447
+ * @param {number} y
448
+ * @param {number} z
449
+ * @return {Float32Array|number[]} `out`, for chaining.
450
+ */
451
+ sampleVelocity(out, x, y, z) {
452
+ const res_x = this.#resolution[0];
453
+ const res_y = this.#resolution[1];
454
+ const res_z = this.#resolution[2];
455
+ out[0] = scs3d_sample_linear(this.velocity_x, res_x + 1, res_y, res_z, x + 0.5, y, z);
456
+ out[1] = scs3d_sample_linear(this.velocity_y, res_x, res_y + 1, res_z, x, y + 0.5, z);
457
+ out[2] = scs3d_sample_linear(this.velocity_z, res_x, res_y, res_z + 1, x, y, z + 0.5);
458
+ return out;
459
+ }
460
+
461
+ /**
462
+ * Sample a scalar attribute at a fractional grid position.
463
+ * @param {string} name
464
+ * @param {number} x
465
+ * @param {number} y
466
+ * @param {number} z
467
+ * @return {number} trilinearly-interpolated value at `(x, y, z)`.
468
+ */
469
+ sampleScalar(name, x, y, z) {
470
+ const data = this.getScalarData(name);
471
+ assert.notNull(data, `scalar attribute '${name}'`);
472
+ return scs3d_sample_linear(data, this.#resolution[0], this.#resolution[1], this.#resolution[2], x, y, z);
473
+ }
474
+
475
+ /**
476
+ * Strict value equality. Two fields are equal iff they have the same resolution,
477
+ * the same set of scalar attributes (matched by name AND index), and the same
478
+ * buffer contents in `velocity_*`, `solid`, `pressure`, and each scalar. Pre-build
479
+ * fields compare by resolution + attribute names only (their buffers are null).
480
+ *
481
+ * O(N) — walks every cell. Use {@link hash} for change-detection on hot paths.
482
+ *
483
+ * @param {FluidField} other
484
+ * @return {boolean}
485
+ */
486
+ equals(other) {
487
+ if (other === this) {
488
+ return true;
489
+ }
490
+ if (!(other instanceof FluidField)) {
491
+ return false;
492
+ }
493
+
494
+ if (this.#resolution[0] !== other.#resolution[0]
495
+ || this.#resolution[1] !== other.#resolution[1]
496
+ || this.#resolution[2] !== other.#resolution[2]) {
497
+ return false;
498
+ }
499
+
500
+ if (this.#built !== other.#built) {
501
+ return false;
502
+ }
503
+
504
+ const my_attrs = this.#scalar_attributes;
505
+ const other_attrs = other.#scalar_attributes;
506
+ if (my_attrs.length !== other_attrs.length) {
507
+ return false;
508
+ }
509
+ for (let i = 0; i < my_attrs.length; i++) {
510
+ if (my_attrs[i].name !== other_attrs[i].name) {
511
+ return false;
512
+ }
513
+ }
514
+
515
+ if (!this.#built) {
516
+ // Buffers are null on both sides; resolution + names already matched.
517
+ return true;
518
+ }
519
+
520
+ if (!is_typed_array_equals(this.velocity_x, other.velocity_x)
521
+ || !is_typed_array_equals(this.velocity_y, other.velocity_y)
522
+ || !is_typed_array_equals(this.velocity_z, other.velocity_z)) {
523
+ return false;
524
+ }
525
+ if (!is_typed_array_equals(this.solid, other.solid)) {
526
+ return false;
527
+ }
528
+ if (!is_typed_array_equals(this.pressure, other.pressure)) {
529
+ return false;
530
+ }
531
+ for (let i = 0; i < my_attrs.length; i++) {
532
+ if (!is_typed_array_equals(my_attrs[i].data, other_attrs[i].data)) {
533
+ return false;
534
+ }
535
+ }
536
+ return true;
537
+ }
538
+
539
+ /**
540
+ * Fast hash suitable for change-detection. Combines the resolution and a *sparse*
541
+ * sample of the velocity_x buffer — {@link sparse_typed_array_hash} only inspects
542
+ * the first ~1024 cells with stride enough to take ~31 samples, regardless of how
543
+ * large the field is. The hash will catch most local edits to the velocity field
544
+ * but is not a content-perfect fingerprint; for that, fall through to
545
+ * {@link equals}.
546
+ *
547
+ * Constant-time relative to grid size in the common case.
548
+ *
549
+ * @return {number}
550
+ */
551
+ hash() {
552
+ const velocity_sample = this.#built
553
+ ? sparse_typed_array_hash(this.velocity_x, 0, this.velocity_x.length)
554
+ : 0;
555
+ return combine_hash(
556
+ this.#resolution[0],
557
+ this.#resolution[1],
558
+ this.#resolution[2],
559
+ this.#scalar_attributes.length,
560
+ velocity_sample
561
+ );
562
+ }
563
+
564
+ /**
565
+ * Rebuild {@link solid_neighbour_mask} and {@link pressure_diag} from the
566
+ * current {@link solid} buffer.
567
+ *
568
+ * O(N)two byte-writes per cell, six byte-reads per cell. Called by the
569
+ * simulator once per step and at the top of each direct project() call, so
570
+ * callers never have to remember to invalidate the mask after mutating
571
+ * solids; the cost is amortized across the SOR sweep's many iterations.
572
+ *
573
+ * Encoding: see {@link solid_neighbour_mask} and {@link pressure_diag}.
574
+ */
575
+ recomputeSolidNeighbourMask() {
576
+ if (!this.#built) {
577
+ return;
578
+ }
579
+ v3_grid_compute_solid_neighbour_mask(
580
+ this.solid_neighbour_mask,
581
+ this.pressure_diag,
582
+ this.solid,
583
+ this.#resolution[0], this.#resolution[1], this.#resolution[2]
584
+ );
585
+ v3_mac_compute_face_solid(
586
+ this.face_solid_x, this.face_solid_y, this.face_solid_z,
587
+ this.velocity_x, this.velocity_y, this.velocity_z,
588
+ this.solid,
589
+ this.#resolution[0], this.#resolution[1], this.#resolution[2]
590
+ );
591
+ }
592
+
593
+ /**
594
+ * Translate the field's contents by `(shift_x, shift_y, shift_z)` grid cells —
595
+ * called when the field's world-space origin moves, so the fluid data (anchored
596
+ * to world space) follows. Every owned buffer (velocity_x/y/z, solid, pressure,
597
+ * each scalar attribute) is shifted, then the newly-exposed edges are patched
598
+ * via {@link v3_grid_patch_edges_uniform} (zero-gradient Neumann extrapolation —
599
+ * "the field is locally uniform").
600
+ *
601
+ * Direction convention matches the primitive: positive shift means the grid's
602
+ * world origin moved in that direction, so each cell takes the value previously
603
+ * at its `+shift` neighbour.
604
+ *
605
+ * `(0, 0, 0)` is a no-op; |shift| ≥ res on any axis zero-fills (no valid source
606
+ * left to replicate from). Pre-build fields (buffers null) are no-op'd.
607
+ *
608
+ * The solid mask is migrated like every other buffer — solids are anchored to
609
+ * world space exactly like the fluid they bound, so a wall must stay where the
610
+ * world says it is when the grid hops a cell. Newly scrolled-in cells become
611
+ * fluid (`0`): the field knows nothing about un-simulated space, and "empty
612
+ * until a voxelizer says otherwise" is the only honest default. Callers that
613
+ * voxelize scene geometry can keep overwriting the mask each tick — the
614
+ * migrated values are then simply replaced. (Earlier behaviour cleared the
615
+ * whole mask on shift, which made every grid hop simulate one tick with no
616
+ * walls anywhere — fluid leaked through geometry until the caller re-splatted.)
617
+ *
618
+ * The derived {@link solid_neighbour_mask} is refreshed here too, so the field
619
+ * stays self-consistent for direct kernel users; the simulator's per-step
620
+ * refresh makes this redundant in the ECS path but shifts are rare (once per
621
+ * cell crossing) and the pass is one byte-write per cell.
622
+ *
623
+ * @param {number} shift_x integer
624
+ * @param {number} shift_y integer
625
+ * @param {number} shift_z integer
626
+ */
627
+ shift(shift_x, shift_y, shift_z) {
628
+ if (!this.#built) {
629
+ return;
630
+ }
631
+ if (shift_x === 0 && shift_y === 0 && shift_z === 0) {
632
+ return;
633
+ }
634
+
635
+ const rx = this.#resolution[0];
636
+ const ry = this.#resolution[1];
637
+ const rz = this.#resolution[2];
638
+
639
+ // Velocity components — each face grid shifts with its own dimensions.
640
+ // Faces ride along with the cells (face i sits between cells i−1 and
641
+ // i), so the integer cell shift applies unchanged on the face lattice.
642
+ v3_grid_shift_in_place(this.velocity_x, rx + 1, ry, rz, shift_x, shift_y, shift_z);
643
+ v3_grid_patch_edges_uniform(this.velocity_x, rx + 1, ry, rz, shift_x, shift_y, shift_z);
644
+
645
+ v3_grid_shift_in_place(this.velocity_y, rx, ry + 1, rz, shift_x, shift_y, shift_z);
646
+ v3_grid_patch_edges_uniform(this.velocity_y, rx, ry + 1, rz, shift_x, shift_y, shift_z);
647
+
648
+ v3_grid_shift_in_place(this.velocity_z, rx, ry, rz + 1, shift_x, shift_y, shift_z);
649
+ v3_grid_patch_edges_uniform(this.velocity_z, rx, ry, rz + 1, shift_x, shift_y, shift_z);
650
+
651
+ // Solid mask — world-anchored like the fluid; scrolled-in cells are fluid.
652
+ // recomputeSolidNeighbourMask refreshes every derived mask (cell + face).
653
+ v3_grid_shift_in_place(this.solid, rx, ry, rz, shift_x, shift_y, shift_z);
654
+ v3_grid_patch_edges_constant(this.solid, rx, ry, rz, shift_x, shift_y, shift_z, 0);
655
+ this.recomputeSolidNeighbourMask();
656
+
657
+ // Pressure (warm-start state, carried across steps).
658
+ v3_grid_shift_in_place(this.pressure, rx, ry, rz, shift_x, shift_y, shift_z);
659
+ v3_grid_patch_edges_uniform(this.pressure, rx, ry, rz, shift_x, shift_y, shift_z);
660
+
661
+ // Scalar attributes.
662
+ for (let i = 0; i < this.#scalar_attributes.length; i++) {
663
+ const data = this.#scalar_attributes[i].data;
664
+ v3_grid_shift_in_place(data, rx, ry, rz, shift_x, shift_y, shift_z);
665
+ v3_grid_patch_edges_uniform(data, rx, ry, rz, shift_x, shift_y, shift_z);
666
+ }
667
+ }
668
+
669
+ /**
670
+ * Zero velocity, pressure, and all scalar attributes. Solid mask is preserved.
671
+ * Pressure is cleared to drop the warm-start (otherwise the next step's solve
672
+ * begins from a stale solution that no longer matches the zero velocity).
673
+ */
674
+ clear() {
675
+ assert.ok(this.#built, "build() must be called before clear()");
676
+ this.velocity_x.fill(0);
677
+ this.velocity_y.fill(0);
678
+ this.velocity_z.fill(0);
679
+ this.pressure.fill(0);
680
+ for (const attr of this.#scalar_attributes) {
681
+ attr.data.fill(0);
682
+ }
683
+ }
684
+ }