@threenative/core 0.3.10 → 0.3.12

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 (158) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10565 -22533
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-camera-cull.ts +32 -1
  84. package/src/render-pass-budget.ts +34 -7
  85. package/src/renderProjection.ts +22 -0
  86. package/src/renderer.ts +92 -37
  87. package/src/snow-field.ts +1 -1
  88. package/src/spells/cast-pool.ts +361 -0
  89. package/src/spells/index.ts +177 -0
  90. package/src/spells/mechanisms.ts +295 -0
  91. package/src/spells/reaction-field.ts +415 -0
  92. package/src/spells/spell-lights.ts +139 -0
  93. package/src/spells/spell-world.ts +187 -0
  94. package/src/spells/spell.ts +397 -0
  95. package/src/spells/spells.ts +283 -0
  96. package/src/spells/ultra/engine/camera.ts +184 -0
  97. package/src/spells/ultra/engine/quality.ts +96 -0
  98. package/src/spells/ultra/index.ts +52 -0
  99. package/src/spells/ultra/main.ts +305 -0
  100. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  101. package/src/spells/ultra/spells/cast.ts +233 -0
  102. package/src/spells/ultra/spells/fire.ts +1267 -0
  103. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  104. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  105. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  106. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  107. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  108. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  109. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  110. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  111. package/src/spells/ultra/vfx/common.ts +1195 -0
  112. package/src/spells/ultra/vfx/noise.ts +441 -0
  113. package/src/startup-readiness.ts +128 -34
  114. package/src/version.ts +1 -1
  115. package/src/warmup.ts +56 -8
  116. package/src/water-surface.ts +9 -3
  117. package/src/world-bundle-safety.ts +401 -0
  118. package/src/world-cell-batches.ts +1216 -0
  119. package/src/world-cell-chunks.ts +1132 -0
  120. package/src/world-cell-data.ts +995 -0
  121. package/src/world-cell-impostors.ts +1449 -0
  122. package/src/world-cell-lod-bias.ts +151 -0
  123. package/src/world-cell-models.ts +1074 -0
  124. package/src/world-cell-options.ts +189 -0
  125. package/src/world-cell-placements.ts +694 -0
  126. package/src/world-cell-prewarm.ts +557 -0
  127. package/src/world-cell-readiness.ts +357 -0
  128. package/src/world-cell-render-bundles.ts +459 -0
  129. package/src/world-cell-render-gpu-dress.ts +714 -0
  130. package/src/world-cell-render-main-cull.ts +484 -0
  131. package/src/world-cell-render-shadow-claims.ts +198 -0
  132. package/src/world-cell-render-util.ts +246 -0
  133. package/src/world-cell-render.ts +1493 -0
  134. package/src/world-cell-residency.ts +745 -0
  135. package/src/world-cells.ts +1318 -10418
  136. package/src/world-chunk-shadow.ts +308 -0
  137. package/src/world-collar.ts +315 -0
  138. package/src/world-gpu-flags.ts +163 -0
  139. package/src/world-gpu-readback.ts +881 -0
  140. package/src/world-gpu-reference.ts +510 -0
  141. package/src/world-gpu-scene.ts +214 -2264
  142. package/src/world-gpu-shadow.ts +190 -0
  143. package/src/world-gpu-types.ts +381 -0
  144. package/src/world-gpu-validation.ts +518 -0
  145. package/src/world-heightfield.ts +802 -0
  146. package/src/world-load-limiter.ts +106 -0
  147. package/src/world-noise.ts +241 -0
  148. package/src/world-package.ts +42 -0
  149. package/src/world-region.ts +1 -1
  150. package/src/world-terrain-splat.ts +365 -149
  151. package/src/world-tile-budget.ts +256 -0
  152. package/src/world-tile-geometry.ts +469 -0
  153. package/src/world-tile-lod.ts +408 -0
  154. package/src/world-tile-observation.ts +566 -0
  155. package/src/world-tile-stitch.ts +166 -0
  156. package/src/world-tiles.ts +170 -1745
  157. package/src/world-water-bodies.ts +359 -0
  158. package/src/world.ts +35 -741
@@ -0,0 +1,802 @@
1
+ /**
2
+ * `Heightfield`: one height buffer shared by world queries, rendered geometry, and a physics
3
+ * heightfield. Split out of `world.ts` so `world-tiles.ts` reads the field it streams without
4
+ * importing the module that re-exports the tiles (PRD-797); `world.ts` re-exports all of it, so
5
+ * `@threenative/core/world` keeps its surface.
6
+ */
7
+ import { BufferAttribute, BufferGeometry, Group, Sphere, Vector3 } from "three";
8
+ import type { IComputeDriven } from "./compute-driven.js";
9
+ import { GPUReadback, type IGPUReadbackSample } from "./gpu-readback.js";
10
+ import type { IRendererLike } from "./renderer.js";
11
+ import {
12
+ type IWorldErosionOptions,
13
+ type IWorldGpuPasses,
14
+ createWorldGpuPasses,
15
+ simulateWorldPassesCpu,
16
+ } from "./world-passes.js";
17
+ import { unionBounds } from "./world-region.js";
18
+
19
+ export interface IHeightfieldOrigin {
20
+ readonly x: number;
21
+ readonly z: number;
22
+ }
23
+
24
+ export interface IHeightfieldOptions {
25
+ readonly columns: number;
26
+ readonly depth: number;
27
+ readonly heights: Float32Array;
28
+ readonly origin: IHeightfieldOrigin;
29
+ readonly rows: number;
30
+ readonly width: number;
31
+ readonly worldPasses?: IHeightfieldWorldPassOptions;
32
+ }
33
+
34
+ /** A rectangular window of a heightfield's canonical samples, in grid indices. */
35
+ /** Hands out the union of every window `updateHeights` wrote since the last `take`. */
36
+ export interface IHeightfieldChangeTracker {
37
+ /** The changed window since the previous take, or undefined when nothing changed. */
38
+ take(): IHeightfieldRegionBounds | undefined;
39
+ /** Stop tracking. Idempotent. */
40
+ dispose(): void;
41
+ }
42
+
43
+ export interface IHeightfieldRegionBounds {
44
+ /** First column (x index), inclusive. */
45
+ readonly column: number;
46
+ /** Number of columns covered. */
47
+ readonly columns: number;
48
+ /** First row (z index), inclusive. */
49
+ readonly row: number;
50
+ /** Number of rows covered. */
51
+ readonly rows: number;
52
+ }
53
+
54
+ /** A rectangular window plus the replacement samples written over it. */
55
+ export interface IHeightfieldRegion extends IHeightfieldRegionBounds {
56
+ /** Row-major samples, `columns * rows` long and read with the region's own stride. */
57
+ readonly heights: Float32Array;
58
+ }
59
+
60
+ export interface IHeightfieldWorldPassOptions {
61
+ /** Maximum TSL compute dispatches submitted by one rendered frame. */
62
+ readonly dispatchBudget: number;
63
+ /** Reserved GPU path; true is rejected until GPU readback owns the canonical field. */
64
+ readonly gpu?: boolean;
65
+ /** Every physical coefficient is game supplied; core owns no terrain preset. */
66
+ readonly erosion: IWorldErosionOptions;
67
+ }
68
+
69
+ export interface IHeightfieldSamplerOptions extends Omit<IHeightfieldOptions, "heights"> {
70
+ /** Game-owned terrain function. It is evaluated once and never retained. */
71
+ readonly sampleHeight: (x: number, z: number) => number;
72
+ }
73
+
74
+ interface IStoredHeightfieldChannels {
75
+ readonly flow?: Float32Array;
76
+ readonly moisture?: Float32Array;
77
+ }
78
+
79
+ function finite(value: number, name: string): number {
80
+ if (!Number.isFinite(value)) throw new Error(`Heightfield ${name} must be finite.`);
81
+ return value;
82
+ }
83
+
84
+ function positive(value: number, name: string): number {
85
+ finite(value, name);
86
+ if (value <= 0) throw new Error(`Heightfield ${name} must be greater than zero.`);
87
+ return value;
88
+ }
89
+
90
+ function count(value: number, name: string): number {
91
+ if (!Number.isInteger(value) || value < 2)
92
+ throw new Error(`Heightfield ${name} must be an integer of at least 2.`);
93
+ return value;
94
+ }
95
+
96
+ /** Validates one axis of an update window against the field's own sample count. */
97
+ function regionAxis(
98
+ start: number,
99
+ size: number,
100
+ total: number,
101
+ names: readonly [string, string],
102
+ ): { readonly count: number; readonly start: number } {
103
+ if (!Number.isInteger(start) || start < 0)
104
+ throw new Error(`Heightfield region ${names[0]} must be an integer of at least 0.`);
105
+ if (!Number.isInteger(size) || size < 1)
106
+ throw new Error(`Heightfield region ${names[1]} must be an integer of at least 1.`);
107
+ if (start + size > total)
108
+ throw new Error(
109
+ `Heightfield region ${names[0]} ${String(start)} + ${names[1]} ${String(size)} exceeds the field's ${String(total)} samples.`,
110
+ );
111
+ return { count: size, start };
112
+ }
113
+
114
+ function regionColumns(
115
+ region: IHeightfieldRegionBounds,
116
+ total: number,
117
+ ): { readonly count: number; readonly start: number } {
118
+ return regionAxis(region.column, region.columns, total, ["column", "columns"]);
119
+ }
120
+
121
+ function regionRows(
122
+ region: IHeightfieldRegionBounds,
123
+ total: number,
124
+ ): { readonly count: number; readonly start: number } {
125
+ return regionAxis(region.row, region.rows, total, ["row", "rows"]);
126
+ }
127
+
128
+ function shouldBuildGpuPasses(options: IHeightfieldWorldPassOptions | undefined): boolean {
129
+ return options?.gpu === true;
130
+ }
131
+
132
+ function validateWorldPassBudget(options: IHeightfieldWorldPassOptions): void {
133
+ if (!Number.isInteger(options.dispatchBudget) || options.dispatchBudget <= 0)
134
+ throw new Error("Heightfield world passes dispatchBudget must be a positive integer.");
135
+ if (options.gpu === true) return;
136
+ if (!Number.isInteger(options.erosion.iterations) || options.erosion.iterations < 0) return;
137
+ if (options.erosion.iterations > options.dispatchBudget)
138
+ throw new Error("Heightfield dispatchBudget cannot cover synchronous CPU erosion iterations.");
139
+ }
140
+
141
+ /**
142
+ * One height buffer shared by world queries, rendered geometry, and a physics heightfield.
143
+ *
144
+ * The game supplies every value, so changing the terrain's shape never requires a package edit.
145
+ * `fromSampler` evaluates that game function exactly once at each vertex and retains only the
146
+ * resulting numbers. Queries interpolate those same numbers instead of evaluating the function
147
+ * again.
148
+ *
149
+ * @situation build terrain geometry and collision from one game-authored height function
150
+ * @situation generate a terrain a player can walk across
151
+ * @situation query the same ground height or normal that a player sees and collides with
152
+ * @situation ask how high the ground is here
153
+ * @situation build islands and coastlines from terrain
154
+ * @situation keep a collider or other copy of a deforming terrain in step without rescanning the whole field (`trackChanges`)
155
+ * @constraint sampleHeight owns the terrain shape and stays in game source; the framework stores and interpolates its output
156
+ * @constraint rows and columns are vertex counts; geometry is row-major z-then-x and collider export transposes once into Rapier's column-major matrix order
157
+ * @override rows, columns, width, depth, origin, and sampleHeight are explicit on every field
158
+ * @example const field = Heightfield.fromSampler({ rows: 65, columns: 65, width: 64, depth: 64, origin: { x: 0, z: 0 }, sampleHeight: terrainHeight });
159
+ */
160
+ export class Heightfield extends Group implements IComputeDriven {
161
+ readonly columns: number;
162
+ readonly depth: number;
163
+ readonly origin: IHeightfieldOrigin;
164
+ readonly rows: number;
165
+ readonly width: number;
166
+ readonly processCadence = "render" as const;
167
+ readonly warmupNodes: readonly unknown[];
168
+ readonly #cellDepth: number;
169
+ readonly #cellWidth: number;
170
+ readonly #colliderHeights: Float32Array;
171
+ readonly #trackers = new Set<{ region: IHeightfieldRegionBounds | undefined }>();
172
+ readonly #heights: Float32Array;
173
+ readonly #minimumX: number;
174
+ readonly #minimumZ: number;
175
+ readonly #flow: Float32Array | undefined;
176
+ readonly #moisture: Float32Array | undefined;
177
+ readonly #gpu: IWorldGpuPasses | undefined;
178
+ readonly #heightReadback: GPUReadback | undefined;
179
+ readonly #flowReadback: GPUReadback | undefined;
180
+ readonly #moistureReadback: GPUReadback | undefined;
181
+ #renderer: IRendererLike | undefined;
182
+ #gpuCompletionObserved = false;
183
+ #released = false;
184
+ #version = 0;
185
+
186
+ constructor(options: IHeightfieldOptions & IStoredHeightfieldChannels) {
187
+ super();
188
+ this.columns = count(options.columns, "columns");
189
+ this.rows = count(options.rows, "rows");
190
+ this.width = positive(options.width, "width");
191
+ this.depth = positive(options.depth, "depth");
192
+ this.origin = {
193
+ x: finite(options.origin.x, "origin.x"),
194
+ z: finite(options.origin.z, "origin.z"),
195
+ };
196
+ const expected = this.rows * this.columns;
197
+ if (options.heights.length !== expected)
198
+ throw new Error(
199
+ `Heightfield expected ${expected} heights, received ${options.heights.length}.`,
200
+ );
201
+ if (options.flow !== undefined && options.flow.length !== expected)
202
+ throw new Error(
203
+ `Heightfield expected ${expected} flow samples, received ${options.flow.length}.`,
204
+ );
205
+ if (options.moisture !== undefined && options.moisture.length !== expected)
206
+ throw new Error(
207
+ `Heightfield expected ${expected} moisture samples, received ${options.moisture.length}.`,
208
+ );
209
+ for (const height of options.heights) finite(height, "height sample");
210
+ for (const value of options.flow ?? []) finite(value, "flow sample");
211
+ for (const value of options.moisture ?? []) finite(value, "moisture sample");
212
+ const baseHeights = options.heights.slice();
213
+ const storedFlow = options.flow?.slice();
214
+ const storedMoisture = options.moisture?.slice();
215
+ const passOptions = options.worldPasses;
216
+ if (passOptions !== undefined) validateWorldPassBudget(passOptions);
217
+ if (passOptions?.gpu === true)
218
+ throw new Error(
219
+ "Heightfield GPU generation cannot be canonical; use gpu: false until GPU readback owns the field.",
220
+ );
221
+ const cpu =
222
+ passOptions === undefined
223
+ ? undefined
224
+ : simulateWorldPassesCpu({
225
+ cellDepth: this.depth / (this.rows - 1),
226
+ cellWidth: this.width / (this.columns - 1),
227
+ columns: this.columns,
228
+ erosion: passOptions.erosion,
229
+ heights: baseHeights,
230
+ rows: this.rows,
231
+ });
232
+ this.#heights = cpu?.heights ?? baseHeights;
233
+ this.#flow = cpu?.flow ?? storedFlow;
234
+ this.#moisture = cpu?.moisture ?? storedMoisture;
235
+ // The explicit GPU request is rejected above; omitted and CPU-fallback paths never create GPU
236
+ // state and cannot accidentally expose a CPU-canonical field as GPU-generated.
237
+ this.#gpu =
238
+ passOptions === undefined || !shouldBuildGpuPasses(passOptions)
239
+ ? undefined
240
+ : createWorldGpuPasses({
241
+ cellDepth: this.depth / (this.rows - 1),
242
+ cellWidth: this.width / (this.columns - 1),
243
+ columns: this.columns,
244
+ dispatchBudget: passOptions.dispatchBudget,
245
+ erosion: passOptions.erosion,
246
+ heights: baseHeights,
247
+ rows: this.rows,
248
+ });
249
+ this.warmupNodes = this.#gpu?.stages.flatMap((stage) => stage.nodes) ?? [];
250
+ this.#heightReadback =
251
+ this.#gpu === undefined
252
+ ? undefined
253
+ : new GPUReadback({ attribute: this.#gpu.height.value, everyFrames: 1 });
254
+ this.#flowReadback =
255
+ this.#gpu === undefined
256
+ ? undefined
257
+ : new GPUReadback({ attribute: this.#gpu.flow.value, everyFrames: 1 });
258
+ this.#moistureReadback =
259
+ this.#gpu === undefined
260
+ ? undefined
261
+ : new GPUReadback({ attribute: this.#gpu.moisture.value, everyFrames: 1 });
262
+ this.#colliderHeights = new Float32Array(expected);
263
+ for (let column = 0; column < this.columns; column += 1) {
264
+ for (let row = 0; row < this.rows; row += 1) {
265
+ this.#colliderHeights[column * this.rows + row] = this.#height(row * this.columns + column);
266
+ }
267
+ }
268
+ this.#cellWidth = this.width / (this.columns - 1);
269
+ this.#cellDepth = this.depth / (this.rows - 1);
270
+ this.#minimumX = this.origin.x - this.width / 2;
271
+ this.#minimumZ = this.origin.z - this.depth / 2;
272
+ }
273
+
274
+ static fromSampler(options: IHeightfieldSamplerOptions): Heightfield {
275
+ const columns = count(options.columns, "columns");
276
+ const rows = count(options.rows, "rows");
277
+ const width = positive(options.width, "width");
278
+ const depth = positive(options.depth, "depth");
279
+ const originX = finite(options.origin.x, "origin.x");
280
+ const originZ = finite(options.origin.z, "origin.z");
281
+ const minimumX = originX - width / 2;
282
+ const minimumZ = originZ - depth / 2;
283
+ const cellWidth = width / (columns - 1);
284
+ const cellDepth = depth / (rows - 1);
285
+ const heights = new Float32Array(rows * columns);
286
+
287
+ for (let row = 0; row < rows; row += 1) {
288
+ const z = minimumZ + row * cellDepth;
289
+ for (let column = 0; column < columns; column += 1) {
290
+ const x = minimumX + column * cellWidth;
291
+ heights[row * columns + column] = finite(options.sampleHeight(x, z), "sampleHeight result");
292
+ }
293
+ }
294
+
295
+ return new Heightfield({
296
+ columns,
297
+ depth,
298
+ heights,
299
+ origin: options.origin,
300
+ rows,
301
+ width,
302
+ ...(options.worldPasses === undefined ? {} : { worldPasses: options.worldPasses }),
303
+ });
304
+ }
305
+
306
+ sample(channel: string, x: number, z: number): number {
307
+ if (channel === "height") return this.heightAt(x, z);
308
+ if (channel === "slope") return 1 - this.normalAt(x, z).y;
309
+ const values =
310
+ channel === "flow" ? this.#flow : channel === "moisture" ? this.#moisture : undefined;
311
+ if (values === undefined) throw new Error(`Heightfield unknown channel '${channel}'.`);
312
+ return this.#interpolateValues(values, x, z);
313
+ }
314
+
315
+ get released(): boolean {
316
+ return this.#released;
317
+ }
318
+
319
+ get generationComplete(): boolean {
320
+ return this.#gpu?.queue.complete ?? true;
321
+ }
322
+
323
+ get gpuHeightSample(): IGPUReadbackSample | undefined {
324
+ return this.#heightReadback?.sample;
325
+ }
326
+
327
+ attachRenderer(renderer: IRendererLike): void {
328
+ if (this.#released) throw new Error("Heightfield cannot be attached after release.");
329
+ if (this.#gpu === undefined) return;
330
+ if (renderer.kind !== "webgpu") throw new Error("Heightfield world passes require WebGPU.");
331
+ if (this.#renderer !== undefined && this.#renderer !== renderer)
332
+ throw new Error("Heightfield is already attached to a renderer.");
333
+ this.#renderer = renderer;
334
+ }
335
+
336
+ process(renderer = this.#renderer): void {
337
+ if (this.#released || this.#gpu === undefined) return;
338
+ if (renderer === undefined) throw new Error("Heightfield is not attached to a renderer.");
339
+ const submitted = this.#gpu.queue.process(renderer);
340
+ if (submitted > 0 || !this.#gpu.queue.complete) {
341
+ this.#gpuCompletionObserved = false;
342
+ return;
343
+ }
344
+ // Compute is scheduled before the renderer's draw. Delay the first copy until the next loop
345
+ // turn so the submitted passes have actually run; an immediate getArrayBufferAsync observes
346
+ // the previous storage contents on WebGPU and turns parity into a false no-data report.
347
+ if (!this.#gpuCompletionObserved) {
348
+ this.#gpuCompletionObserved = true;
349
+ return;
350
+ }
351
+ if (this.#heightReadback?.sample === undefined) {
352
+ this.#heightReadback?.request(renderer);
353
+ return;
354
+ }
355
+ if (this.#flowReadback?.sample === undefined) {
356
+ this.#flowReadback?.request(renderer);
357
+ return;
358
+ }
359
+ if (this.#moistureReadback?.sample === undefined) this.#moistureReadback?.request(renderer);
360
+ }
361
+
362
+ debug(): Record<string, unknown> {
363
+ return {
364
+ complete: this.generationComplete,
365
+ dispatched: this.#gpu?.queue.dispatched ?? 0,
366
+ gpuHeightMaxError: this.#sampleError(this.#heightReadback?.sample, this.#heights),
367
+ gpuFlowMaxError: this.#sampleError(this.#flowReadback?.sample, this.#flow),
368
+ gpuMoistureMaxError: this.#sampleError(this.#moistureReadback?.sample, this.#moisture),
369
+ released: this.#released,
370
+ };
371
+ }
372
+
373
+ detach(): void {
374
+ if (this.#released) return;
375
+ this.#renderer = undefined;
376
+ this.#heightReadback?.dispose();
377
+ this.#flowReadback?.dispose();
378
+ this.#moistureReadback?.dispose();
379
+ this.#gpu?.dispose();
380
+ this.#released = true;
381
+ }
382
+
383
+ /** A copy of the canonical row-major samples, safe for game-side analysis. */
384
+ get heights(): Float32Array {
385
+ return this.#heights.slice();
386
+ }
387
+
388
+ /** A copy of the normalized routed-flow channel, when world passes were requested. */
389
+ get flow(): Float32Array | undefined {
390
+ return this.#flow?.slice();
391
+ }
392
+
393
+ /** Bytes retained by this field's CPU channels and its conservative GPU allowance. */
394
+ get memoryBytes(): number {
395
+ const sampleBytes = this.rows * this.columns * Float32Array.BYTES_PER_ELEMENT;
396
+ const cpuBytes =
397
+ sampleBytes * 2 +
398
+ (this.#flow === undefined ? 0 : sampleBytes) +
399
+ (this.#moisture === undefined ? 0 : sampleBytes);
400
+ return this.#gpu === undefined ? cpuBytes : Math.max(cpuBytes, sampleBytes * 24);
401
+ }
402
+
403
+ heightAt(x: number, z: number): number {
404
+ finite(x, "query x");
405
+ finite(z, "query z");
406
+ const column = (x - this.#minimumX) / this.#cellWidth;
407
+ const row = (z - this.#minimumZ) / this.#cellDepth;
408
+ const epsilon = 1e-9;
409
+ if (
410
+ column < -epsilon ||
411
+ row < -epsilon ||
412
+ column > this.columns - 1 + epsilon ||
413
+ row > this.rows - 1 + epsilon
414
+ )
415
+ throw new Error(`Heightfield query (${x}, ${z}) is outside its resident region.`);
416
+ return this.#interpolate(
417
+ Math.min(this.columns - 1, Math.max(0, column)),
418
+ Math.min(this.rows - 1, Math.max(0, row)),
419
+ );
420
+ }
421
+
422
+ /**
423
+ * The drawn surface's height under `(x, z)`: the triangle plane `toGeometry` emits, not the
424
+ * bilinear `heightAt`.
425
+ *
426
+ * A heightfield renders as two triangles per cell and collides as the same two, so a prop or a
427
+ * player grounded on the bilinear height stands up to half a cell's relief off the surface the
428
+ * eye sees — worst on a saddle, where the two disagree by the cell's whole diagonal. This answers
429
+ * the plane the drawn triangle actually is, from the canonical samples, so a caller needs neither
430
+ * the geometry nor a matrix to ask.
431
+ * @situation ground a prop or a player on the same triangle the eye sees and the collider uses
432
+ * @constraint the point must be inside the field; a query outside it throws like `heightAt`
433
+ * @example const resting = field.surfaceAt(player.position.x, player.position.z);
434
+ */
435
+ surfaceAt(x: number, z: number): number {
436
+ finite(x, "query x");
437
+ finite(z, "query z");
438
+ const column = (x - this.#minimumX) / this.#cellWidth;
439
+ const row = (z - this.#minimumZ) / this.#cellDepth;
440
+ const epsilon = 1e-9;
441
+ if (
442
+ column < -epsilon ||
443
+ row < -epsilon ||
444
+ column > this.columns - 1 + epsilon ||
445
+ row > this.rows - 1 + epsilon
446
+ )
447
+ throw new Error(`Heightfield query (${x}, ${z}) is outside its resident region.`);
448
+ const column0 = Math.min(this.columns - 2, Math.max(0, Math.floor(column)));
449
+ const row0 = Math.min(this.rows - 2, Math.max(0, Math.floor(row)));
450
+ const fractionX = column - column0;
451
+ const fractionZ = row - row0;
452
+ const upperLeft = row0 * this.columns + column0;
453
+ const upperRight = upperLeft + 1;
454
+ const lowerLeft = upperLeft + this.columns;
455
+ const lowerRight = lowerLeft + 1;
456
+ // `toGeometry` splits each cell on the lower-left-to-upper-right diagonal: the half a point
457
+ // falls in decides which of the two planes is the surface there.
458
+ if (fractionX + fractionZ <= 1) {
459
+ const a = this.#height(upperLeft);
460
+ return (
461
+ a + (this.#height(upperRight) - a) * fractionX + (this.#height(lowerLeft) - a) * fractionZ
462
+ );
463
+ }
464
+ const upperRightHeight = this.#height(upperRight);
465
+ const lowerLeftHeight = this.#height(lowerLeft);
466
+ const lowerRightHeight = this.#height(lowerRight);
467
+ return (
468
+ upperRightHeight +
469
+ lowerLeftHeight -
470
+ lowerRightHeight +
471
+ (lowerRightHeight - lowerLeftHeight) * fractionX +
472
+ (lowerRightHeight - upperRightHeight) * fractionZ
473
+ );
474
+ }
475
+
476
+ normalAt(x: number, z: number, target = new Vector3()): Vector3 {
477
+ this.heightAt(x, z);
478
+ const leftX = Math.max(this.#minimumX, x - this.#cellWidth);
479
+ const rightX = Math.min(this.#minimumX + this.width, x + this.#cellWidth);
480
+ const nearZ = Math.max(this.#minimumZ, z - this.#cellDepth);
481
+ const farZ = Math.min(this.#minimumZ + this.depth, z + this.#cellDepth);
482
+ const slopeX = (this.heightAt(rightX, z) - this.heightAt(leftX, z)) / (rightX - leftX);
483
+ const slopeZ = (this.heightAt(x, farZ) - this.heightAt(x, nearZ)) / (farZ - nearZ);
484
+ return target.set(-slopeX, 1, -slopeZ).normalize();
485
+ }
486
+
487
+ /**
488
+ * Monotonic sample version, incremented by every `updateHeights` call.
489
+ *
490
+ * A renderer or collider that caches derived data compares this against its own last-seen value
491
+ * instead of diffing the whole grid each frame.
492
+ */
493
+ get version(): number {
494
+ return this.#version;
495
+ }
496
+
497
+ /**
498
+ * Overwrite one rectangular window of the canonical samples.
499
+ *
500
+ * Height is the one buffer queries, rendered geometry and collider export share, so a second
501
+ * terrain representation is never needed: a simulation writes its surface here and every
502
+ * consumer already reads it. The whole window is validated before any sample changes, so a
503
+ * malformed call leaves the field untouched rather than half-written.
504
+ * @situation deform terrain, snow or water in place and have queries and collision follow
505
+ * @constraint the region must lie inside the field; an out-of-bounds window throws and writes nothing
506
+ * @constraint heights is `columns * rows` long, row-major, and every sample must be finite
507
+ */
508
+ updateHeights(region: IHeightfieldRegion): void {
509
+ if (this.#released) throw new Error("Heightfield cannot be updated after release.");
510
+ const column = regionColumns(region, this.columns);
511
+ const row = regionRows(region, this.rows);
512
+ const expected = column.count * row.count;
513
+ if (region.heights.length !== expected)
514
+ throw new Error(
515
+ `Heightfield region expected ${expected} heights, received ${region.heights.length}.`,
516
+ );
517
+ for (const height of region.heights) finite(height, "region sample");
518
+ for (let index = 0; index < row.count; index += 1) {
519
+ for (let offset = 0; offset < column.count; offset += 1) {
520
+ const target = row.start + index;
521
+ const source = column.start + offset;
522
+ this.#heights[target * this.columns + source] = region.heights[
523
+ index * column.count + offset
524
+ ] as number;
525
+ this.#colliderHeights[source * this.rows + target] = this.#height(
526
+ target * this.columns + source,
527
+ );
528
+ }
529
+ }
530
+ const written = {
531
+ column: column.start,
532
+ columns: column.count,
533
+ row: row.start,
534
+ rows: row.count,
535
+ };
536
+ for (const tracker of this.#trackers) tracker.region = unionBounds(tracker.region, written);
537
+ this.#version += 1;
538
+ }
539
+
540
+ /**
541
+ * Follow which samples change, independently of every other follower.
542
+ *
543
+ * A consumer that mirrors the surface — a collider, a GPU copy, a cache — needs the window that
544
+ * changed since *it* last looked; comparing the whole field instead costs every sample on every
545
+ * change. Each tracker keeps its own union of the windows `updateHeights` wrote, so two
546
+ * consumers never take each other's changes.
547
+ *
548
+ * ```ts
549
+ * const changes = field.trackChanges();
550
+ * const changed = changes.take(); // undefined when nothing was written
551
+ * ```
552
+ */
553
+ trackChanges(): IHeightfieldChangeTracker {
554
+ const state: { region: IHeightfieldRegionBounds | undefined } = { region: undefined };
555
+ this.#trackers.add(state);
556
+ return {
557
+ take: () => {
558
+ const region = state.region;
559
+ state.region = undefined;
560
+ return region;
561
+ },
562
+ dispose: () => {
563
+ this.#trackers.delete(state);
564
+ },
565
+ };
566
+ }
567
+
568
+ /** The collider sample at `row`, `column`: what `toColliderHeights()` holds there, without a copy. */
569
+ colliderHeight(row: number, column: number): number {
570
+ if (
571
+ !Number.isInteger(row) ||
572
+ !Number.isInteger(column) ||
573
+ row < 0 ||
574
+ column < 0 ||
575
+ row >= this.rows ||
576
+ column >= this.columns
577
+ )
578
+ throw new Error(`Heightfield sample ${row},${column} is outside the field.`);
579
+ return this.#colliderHeights[column * this.rows + row] as number;
580
+ }
581
+
582
+ /**
583
+ * Rewrite an existing `toGeometry()` result from the current canonical samples.
584
+ *
585
+ * Positions carry over unchanged because only the surface moves; y and normals are refreshed
586
+ * from the same sampler queries use, which is what keeps a rendered vertex and a height query
587
+ * from disagreeing. Pass a region to touch only the window a simulation just changed.
588
+ * @situation redraw a terrain, snow or water mesh after its samples changed
589
+ * @constraint geometry must come from `toGeometry()` with the same rows and columns
590
+ */
591
+ refreshGeometry(geometry: BufferGeometry, bounds?: IHeightfieldRegionBounds): void {
592
+ const position = geometry.getAttribute("position");
593
+ const normalAttribute = geometry.getAttribute("normal");
594
+ if (position.count !== this.rows * this.columns)
595
+ throw new Error(
596
+ `Heightfield geometry has ${position.count} vertices, expected ${this.rows * this.columns}.`,
597
+ );
598
+ // Only a plain BufferAttribute exposes its lanes raw; a custom subclass or an own setter would be bypassed.
599
+ const floatLanes = (attribute: typeof position): Float32Array | undefined => {
600
+ if (Object.getPrototypeOf(attribute) !== BufferAttribute.prototype) return undefined;
601
+ if (Object.hasOwn(attribute, "setY") || Object.hasOwn(attribute, "setXYZ")) return undefined;
602
+ if (attribute.itemSize !== 3 || attribute.normalized === true) return undefined;
603
+ if (
604
+ (attribute as { isInterleavedBufferAttribute?: boolean }).isInterleavedBufferAttribute ===
605
+ true
606
+ )
607
+ return undefined;
608
+ const array: unknown = attribute.array;
609
+ return array instanceof Float32Array && array.length === position.count * 3
610
+ ? array
611
+ : undefined;
612
+ };
613
+ const positionArray = floatLanes(position);
614
+ const normalArray = normalAttribute === undefined ? undefined : floatLanes(normalAttribute);
615
+ const column =
616
+ bounds === undefined
617
+ ? { count: this.columns, start: 0 }
618
+ : regionColumns(bounds, this.columns);
619
+ const row =
620
+ bounds === undefined ? { count: this.rows, start: 0 } : regionRows(bounds, this.rows);
621
+ let lowest = Number.POSITIVE_INFINITY;
622
+ let highest = Number.NEGATIVE_INFINITY;
623
+ for (let index = 0; index < row.count; index += 1) {
624
+ const target = row.start + index;
625
+ for (let offset = 0; offset < column.count; offset += 1) {
626
+ const source = column.start + offset;
627
+ const vertex = target * this.columns + source;
628
+ const height = this.#height(vertex);
629
+ if (positionArray === undefined) position.setY(vertex, height);
630
+ else positionArray[vertex * 3 + 1] = height;
631
+ lowest = Math.min(lowest, height);
632
+ highest = Math.max(highest, height);
633
+ if (normalAttribute === undefined) continue;
634
+ this.#gridNormal(source, target, normalArray ?? normalAttribute, vertex);
635
+ }
636
+ }
637
+ // Upload only the rows this refresh touched. Ranges accumulate until the renderer uploads, and
638
+ // an unbounded refresh records the full range so a later window cannot shrink a pending one.
639
+ const first = row.start * this.columns + column.start;
640
+ const last = (row.start + row.count - 1) * this.columns + column.start + column.count;
641
+ for (const attribute of normalAttribute === undefined
642
+ ? [position]
643
+ : [position, normalAttribute]) {
644
+ if (attribute instanceof BufferAttribute && row.count > 0 && column.count > 0)
645
+ attribute.addUpdateRange(first * 3, (last - first) * 3);
646
+ attribute.needsUpdate = true;
647
+ }
648
+ // Only heights move, so a windowed refresh grows the existing bounds by the window's own
649
+ // range instead of walking every vertex again: on a 321-sample field the full recompute cost
650
+ // two milliseconds for a footprint-sized window. Bounds may stay conservative after a refill.
651
+ const box = geometry.boundingBox;
652
+ if (bounds === undefined || box === null) {
653
+ geometry.computeBoundingBox();
654
+ geometry.computeBoundingSphere();
655
+ return;
656
+ }
657
+ box.min.y = Math.min(box.min.y, lowest);
658
+ box.max.y = Math.max(box.max.y, highest);
659
+ geometry.boundingSphere = box.getBoundingSphere(geometry.boundingSphere ?? new Sphere());
660
+ }
661
+
662
+ /** The same values transposed once into Rapier's column-major height-matrix order. */
663
+ toColliderHeights(): Float32Array {
664
+ return this.#colliderHeights.slice();
665
+ }
666
+
667
+ /** Builds an ordinary Three.js geometry without choosing its surface. */
668
+ toGeometry(): BufferGeometry {
669
+ const count = this.rows * this.columns;
670
+ const positions = new Float32Array(count * 3);
671
+ const normals = new Float32Array(count * 3);
672
+ const normal = new Vector3();
673
+ for (let row = 0; row < this.rows; row += 1) {
674
+ const localZ = -this.depth / 2 + row * this.#cellDepth;
675
+ const worldZ = this.origin.z + localZ;
676
+ for (let column = 0; column < this.columns; column += 1) {
677
+ const index = row * this.columns + column;
678
+ const localX = -this.width / 2 + column * this.#cellWidth;
679
+ const worldX = this.origin.x + localX;
680
+ positions[index * 3] = localX;
681
+ positions[index * 3 + 1] = this.#height(index);
682
+ positions[index * 3 + 2] = localZ;
683
+ this.normalAt(worldX, worldZ, normal);
684
+ normals[index * 3] = normal.x;
685
+ normals[index * 3 + 1] = normal.y;
686
+ normals[index * 3 + 2] = normal.z;
687
+ }
688
+ }
689
+
690
+ const indices = new Uint32Array((this.rows - 1) * (this.columns - 1) * 6);
691
+ let offset = 0;
692
+ for (let row = 0; row < this.rows - 1; row += 1) {
693
+ for (let column = 0; column < this.columns - 1; column += 1) {
694
+ const upperLeft = row * this.columns + column;
695
+ const upperRight = upperLeft + 1;
696
+ const lowerLeft = upperLeft + this.columns;
697
+ const lowerRight = lowerLeft + 1;
698
+ indices.set([upperLeft, lowerLeft, upperRight, upperRight, lowerLeft, lowerRight], offset);
699
+ offset += 6;
700
+ }
701
+ }
702
+
703
+ const geometry = new BufferGeometry();
704
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
705
+ geometry.setAttribute("normal", new BufferAttribute(normals, 3));
706
+ geometry.setIndex(new BufferAttribute(indices, 1));
707
+ return geometry;
708
+ }
709
+
710
+ #interpolate(column: number, row: number): number {
711
+ const column0 = Math.floor(column);
712
+ const row0 = Math.floor(row);
713
+ const column1 = Math.min(this.columns - 1, column0 + 1);
714
+ const row1 = Math.min(this.rows - 1, row0 + 1);
715
+ const columnMix = column - column0;
716
+ const rowMix = row - row0;
717
+ const upperLeft = this.#height(row0 * this.columns + column0);
718
+ const upperRight = this.#height(row0 * this.columns + column1);
719
+ const lowerLeft = this.#height(row1 * this.columns + column0);
720
+ const lowerRight = this.#height(row1 * this.columns + column1);
721
+ const upper = upperLeft + (upperRight - upperLeft) * columnMix;
722
+ const lower = lowerLeft + (lowerRight - lowerLeft) * columnMix;
723
+ return upper + (lower - upper) * rowMix;
724
+ }
725
+
726
+ #interpolateValues(values: Float32Array, x: number, z: number): number {
727
+ finite(x, "query x");
728
+ finite(z, "query z");
729
+ const column = (x - this.#minimumX) / this.#cellWidth;
730
+ const row = (z - this.#minimumZ) / this.#cellDepth;
731
+ if (column < 0 || row < 0 || column > this.columns - 1 || row > this.rows - 1)
732
+ throw new Error(`Heightfield query (${x}, ${z}) is outside its resident region.`);
733
+ const column0 = Math.floor(column);
734
+ const row0 = Math.floor(row);
735
+ const column1 = Math.min(this.columns - 1, column0 + 1);
736
+ const row1 = Math.min(this.rows - 1, row0 + 1);
737
+ const columnMix = column - column0;
738
+ const rowMix = row - row0;
739
+ const upper =
740
+ (values[row0 * this.columns + column0] as number) * (1 - columnMix) +
741
+ (values[row0 * this.columns + column1] as number) * columnMix;
742
+ const lower =
743
+ (values[row1 * this.columns + column0] as number) * (1 - columnMix) +
744
+ (values[row1 * this.columns + column1] as number) * columnMix;
745
+ return upper * (1 - rowMix) + lower * rowMix;
746
+ }
747
+
748
+ #sampleError(
749
+ sample: IGPUReadbackSample | undefined,
750
+ expected: Float32Array | undefined,
751
+ ): number | undefined {
752
+ if (sample === undefined || expected === undefined) return undefined;
753
+ if (sample.data.length !== expected.length) return Number.POSITIVE_INFINITY;
754
+ let maximum = 0;
755
+ for (let index = 0; index < expected.length; index += 1)
756
+ maximum = Math.max(
757
+ maximum,
758
+ Math.abs((sample.data[index] as number) - (expected[index] as number)),
759
+ );
760
+ return maximum;
761
+ }
762
+
763
+ /**
764
+ * `normalAt` at a sample, read straight from the grid: the same central differences, one-sided
765
+ * at the border, without five validated bilinear queries per vertex. On a 401-sample field a
766
+ * windowed refresh spent most of its time in those queries.
767
+ */
768
+ #gridNormal(
769
+ column: number,
770
+ row: number,
771
+ target: { setXYZ(index: number, x: number, y: number, z: number): unknown } | Float32Array,
772
+ vertex: number,
773
+ ): void {
774
+ const left = Math.max(0, column - 1);
775
+ const right = Math.min(this.columns - 1, column + 1);
776
+ const near = Math.max(0, row - 1);
777
+ const far = Math.min(this.rows - 1, row + 1);
778
+ const slopeX =
779
+ (this.#height(row * this.columns + right) - this.#height(row * this.columns + left)) /
780
+ ((right - left) * this.#cellWidth);
781
+ const slopeZ =
782
+ (this.#height(far * this.columns + column) - this.#height(near * this.columns + column)) /
783
+ ((far - near) * this.#cellDepth);
784
+ const length = Math.hypot(slopeX, 1, slopeZ);
785
+ const x = -slopeX / length;
786
+ const y = 1 / length;
787
+ const z = -slopeZ / length;
788
+ if (target instanceof Float32Array) {
789
+ target[vertex * 3] = x;
790
+ target[vertex * 3 + 1] = y;
791
+ target[vertex * 3 + 2] = z;
792
+ } else {
793
+ target.setXYZ(vertex, x, y, z);
794
+ }
795
+ }
796
+
797
+ #height(index: number): number {
798
+ const height = this.#heights[index];
799
+ if (height === undefined) throw new Error(`Heightfield internal sample ${index} is missing.`);
800
+ return height;
801
+ }
802
+ }