@threenative/core 0.3.12 → 0.3.13

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 (150) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +746 -32
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-4SRAQFTU.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-DIPIJICH.js} +1590 -375
  7. package/dist/{chunk-OKXUCASC.js → chunk-EEABDLUC.js} +3 -4
  8. package/dist/{chunk-5O73CDMR.js → chunk-EFWZWLPY.js} +62 -16
  9. package/dist/{chunk-N5LRP4BR.js → chunk-GYUZJQ7U.js} +63 -3
  10. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  11. package/dist/{chunk-2Z44XSI2.js → chunk-SV4QVUTQ.js} +3 -7
  12. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  13. package/dist/chunk-VP43GIWW.js +18 -0
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +289 -1034
  20. package/dist/index.js +3096 -1305
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BYqKGAwo.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +269 -15
  33. package/dist/world.js +1372 -628
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +105 -7
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/src/animation-batch.ts +193 -0
  39. package/src/animation-layers.ts +7 -3
  40. package/src/animation.ts +209 -29
  41. package/src/asset-cache.ts +3 -3
  42. package/src/asset-memo.ts +202 -0
  43. package/src/assets.ts +436 -131
  44. package/src/auto-batch.ts +190 -44
  45. package/src/compute-driven.ts +1 -1
  46. package/src/config.ts +8 -0
  47. package/src/debug.ts +103 -22
  48. package/src/dev-global.ts +54 -0
  49. package/src/engine-hooks.ts +37 -0
  50. package/src/frame-budget.ts +19 -3
  51. package/src/game-boot-phase.ts +269 -0
  52. package/src/game-dev-tools.ts +7 -14
  53. package/src/game-frame-loop.ts +45 -82
  54. package/src/game-startup.ts +145 -70
  55. package/src/game-ui.ts +84 -0
  56. package/src/game.ts +168 -552
  57. package/src/gamepad-mappings.ts +269 -0
  58. package/src/generated/console-markers.ts +13 -0
  59. package/src/geometry-capture.ts +28 -4
  60. package/src/gpu-readings.ts +98 -0
  61. package/src/gpu-scene-bvh.ts +149 -36
  62. package/src/hot.ts +4 -7
  63. package/src/index.ts +115 -8
  64. package/src/input.ts +237 -25
  65. package/src/instanced-batch-lod.ts +3 -8
  66. package/src/interpolation.ts +171 -40
  67. package/src/look/ao-admission.ts +4 -3
  68. package/src/look/auto-exposure.ts +5 -16
  69. package/src/look/default-tone-mapping.ts +41 -5
  70. package/src/look/local-exposure.ts +2 -7
  71. package/src/look/quad-pass.ts +21 -0
  72. package/src/look/quality.ts +4 -0
  73. package/src/look/unreal-bloom.ts +4 -13
  74. package/src/look/world-environment.ts +58 -115
  75. package/src/merge-parts.ts +20 -24
  76. package/src/model-lod.ts +97 -14
  77. package/src/particle-significance.ts +12 -0
  78. package/src/particles.ts +19 -10
  79. package/src/platform.ts +23 -4
  80. package/src/profiling/FrameStages.ts +5 -6
  81. package/src/profiling/Spans.ts +3 -17
  82. package/src/profiling/debug-telemetry.ts +2 -6
  83. package/src/profiling/render-list-validate.ts +6 -15
  84. package/src/projection-marker.ts +2 -1
  85. package/src/quiet-markers.ts +3 -10
  86. package/src/render/cpu-bvh.ts +100 -0
  87. package/src/render/depth-pyramid.ts +6 -14
  88. package/src/render/environment/environmentContribution.ts +202 -0
  89. package/src/render/environment/environmentRadiance.ts +44 -0
  90. package/src/render/environment/environmentSampleCache.ts +56 -0
  91. package/src/render/environment/environmentSampling.ts +201 -0
  92. package/src/render/environment/environmentSnapshot.ts +71 -0
  93. package/src/render/environment/gate.ts +57 -0
  94. package/src/render/mesh-pool.ts +3 -19
  95. package/src/render/probe-trace.ts +872 -0
  96. package/src/render/probe-volume.ts +780 -34
  97. package/src/render/radiance-cache.ts +17 -0
  98. package/src/render/virtual-shadow-partial.ts +13 -0
  99. package/src/render/virtual-shadow.ts +18 -16
  100. package/src/render/world-impostor-surface.ts +109 -6
  101. package/src/render/world-impostor.ts +5 -2
  102. package/src/render-camera-cull.ts +98 -3
  103. package/src/render-environment.ts +41 -0
  104. package/src/renderer-config.ts +36 -0
  105. package/src/renderer-facts.ts +37 -0
  106. package/src/renderer.ts +52 -28
  107. package/src/resolution-scaler.ts +3 -2
  108. package/src/scene-entry-inspectors.ts +61 -0
  109. package/src/snow-field.ts +1 -0
  110. package/src/startup-offscreen-bytes.ts +78 -0
  111. package/src/static-transform.ts +25 -19
  112. package/src/streamed-textures.ts +112 -0
  113. package/src/streaming.ts +68 -4
  114. package/src/texture-streaming.ts +331 -0
  115. package/src/version.ts +1 -1
  116. package/src/worker.ts +12 -2
  117. package/src/world-bundle-safety.ts +55 -10
  118. package/src/world-cell-batches.ts +162 -200
  119. package/src/world-cell-chunks.ts +3 -7
  120. package/src/world-cell-impostors.ts +20 -8
  121. package/src/world-cell-options.ts +2 -14
  122. package/src/world-cell-placements.ts +194 -90
  123. package/src/world-cell-prewarm.ts +39 -4
  124. package/src/world-cell-records.ts +401 -0
  125. package/src/world-cell-render-bundles.ts +2 -2
  126. package/src/world-cell-render-gpu-dress.ts +13 -17
  127. package/src/world-cell-render-main-cull.ts +73 -17
  128. package/src/world-cell-render-util.ts +17 -4
  129. package/src/world-cell-render.ts +13 -5
  130. package/src/world-cell-residency.ts +15 -6
  131. package/src/world-cell-stale.ts +238 -0
  132. package/src/world-cells.ts +22 -5
  133. package/src/world-gpu-flags.ts +18 -50
  134. package/src/world-gpu-reference.ts +22 -8
  135. package/src/world-gpu-scene.ts +44 -24
  136. package/src/world-gpu-shadow.ts +21 -8
  137. package/src/world-gpu-types.ts +41 -13
  138. package/src/world-load-limiter.ts +5 -0
  139. package/src/world-model-sections.ts +80 -0
  140. package/src/world-river-ribbon.ts +282 -0
  141. package/src/world-root-frame.ts +39 -0
  142. package/src/world-shore-field.ts +91 -0
  143. package/src/world-static-pose.ts +163 -0
  144. package/src/world-surface-sampler.ts +48 -0
  145. package/src/world-terrain-splat.ts +10 -18
  146. package/src/world-tile-budget.ts +4 -11
  147. package/src/world-tiles.ts +79 -12
  148. package/src/world-validate.ts +6 -14
  149. package/src/world-warm.ts +51 -0
  150. package/src/world.ts +13 -0
@@ -43,7 +43,6 @@ import {
43
43
  type BufferAttribute,
44
44
  type Camera,
45
45
  type DepthTexture,
46
- Frustum,
47
46
  Matrix4,
48
47
  PerspectiveCamera,
49
48
  Vector3,
@@ -103,8 +102,8 @@ export type {
103
102
  export {
104
103
  DRAW_ARGS_BYTES,
105
104
  NO_LOCAL,
105
+ PLACEMENT_ROWS,
106
106
  PLACEMENT_WORDS,
107
- PlacementStruct,
108
107
  SLOT_NONE,
109
108
  SOURCE_FLOOR,
110
109
  STORAGE_PLAIN,
@@ -165,8 +164,8 @@ import {
165
164
  type IValidationReadbacks,
166
165
  type IValidationSnapshot,
167
166
  NO_LOCAL,
167
+ PLACEMENT_ROWS,
168
168
  PLACEMENT_WORDS,
169
- PlacementStruct,
170
169
  SLOT_NONE,
171
170
  SOURCE_FLOOR,
172
171
  STORAGE_PLAIN,
@@ -176,9 +175,11 @@ import {
176
175
  VEC4_WORDS,
177
176
  addRange,
178
177
  argsWords,
178
+ frustumPlanes,
179
179
  growBuffer,
180
180
  storageAttribute,
181
181
  } from "./world-gpu-types.js";
182
+ import { localClip, localPoint } from "./world-root-frame.js";
182
183
 
183
184
  /**
184
185
  * The GPU-driven main pass of a streamed world: one compute dispatch culls and LOD-selects every
@@ -258,23 +259,18 @@ export function gpuSceneUnsupported(renderer: IRendererLike): string {
258
259
  return "";
259
260
  }
260
261
 
261
- /** The six planes of a camera's frustum, as the kernel reads them, into `out`. */
262
- function cameraPlanes(camera: Camera, out: Float32Array): void {
263
- _cullFrustum.setFromProjectionMatrix(
264
- _proj.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse),
265
- );
266
- for (const [index, plane] of _cullFrustum.planes.entries()) {
267
- const at = index * 4;
268
- out[at] = plane.normal.x;
269
- out[at + 1] = plane.normal.y;
270
- out[at + 2] = plane.normal.z;
271
- out[at + 3] = plane.constant;
272
- }
262
+ /**
263
+ * The six planes of a camera's frustum, as the kernel reads them, into `out`.
264
+ *
265
+ * The kernel tests them against placements, which are in the root's local frame, so the planes are
266
+ * taken in that frame too: a game that moves its world root culls the camera that is actually over
267
+ * the ring rather than the one it would be if the ring were still at the origin. See `localClip`.
268
+ */
269
+ function cameraPlanes(camera: Camera, out: Float32Array, root: Matrix4 | undefined): void {
270
+ frustumPlanes(localClip(_proj, camera, root), out);
273
271
  }
274
272
 
275
273
  const _proj = new Matrix4();
276
- const _cullFrustum = new Frustum();
277
- const _eye = new Vector3();
278
274
 
279
275
  /** Camera travel in one dispatch that the occlusion test reads as a cut rather than a turn. */
280
276
  const OCCLUSION_CUT_METRES = 2;
@@ -858,10 +854,28 @@ export class WorldGpuScene {
858
854
  * One frame of the main pass: zero every key's instance count, then cull and LOD-select every
859
855
  * resident placement into the shared drawn buffer. Nothing else is written.
860
856
  */
861
- dispatch(renderer: IRendererLike, camera: Camera): void {
857
+ /**
858
+ * The LOD eye `WorldCells` grades its CPU path from (`updateLodEye`): the camera, pulled to within
859
+ * the first gate of `follow`. Levels and `maxDistance` then read one eye on both paths (PRD-857).
860
+ * Unset, the dispatch measures from the camera.
861
+ */
862
+ lodEye(x: number, y: number, z: number): void {
863
+ this.#lodEye.set(x, y, z);
864
+ this.#lodEyeSet = true;
865
+ }
866
+
867
+ readonly #lodEye = new Vector3();
868
+ #lodEyeSet = false;
869
+
870
+ /**
871
+ * `root` is the world's own `matrixWorld`: the frame its placements are recorded in, which is the
872
+ * frame the planes and the eye have to be taken in. A harness driving the scene on its own leaves
873
+ * it out, and then the records are read in world space, as they were before the root could move.
874
+ */
875
+ dispatch(renderer: IRendererLike, camera: Camera, root?: Matrix4): void {
862
876
  if (this.#on === false) return;
863
877
  if (this.#buffers === undefined) return;
864
- cameraPlanes(camera, this.#planes);
878
+ cameraPlanes(camera, this.#planes, root);
865
879
  for (const [index, plane] of this.#planeVectors.entries()) {
866
880
  const at = index * 4;
867
881
  plane.set(
@@ -871,8 +885,8 @@ export class WorldGpuScene {
871
885
  this.#planes[at + 3] as number,
872
886
  );
873
887
  }
874
- _eye.setFromMatrixPosition(camera.matrixWorld);
875
- this.#eye.value.copy(_eye);
888
+ if (this.#lodEyeSet) this.#eye.value.copy(this.#lodEye);
889
+ else localPoint(this.#eye.value.setFromMatrixPosition(camera.matrixWorld), root);
876
890
  // `(placements, slots, keys, keys)`: the last two are the same count, and the clear dispatch is
877
891
  // one thread per key.
878
892
  if (this.#readback.measuring) this.#readback.measure(renderer, camera);
@@ -1016,7 +1030,10 @@ export class WorldGpuScene {
1016
1030
  keys: storageAttribute(StorageBufferAttribute, "vec4", 1),
1017
1031
  levels: storageAttribute(StorageBufferAttribute, "vec4", 1),
1018
1032
  locals: storageAttribute(StorageBufferAttribute, "mat4", 1),
1019
- source: storageAttribute(StorageBufferAttribute, "GpuPlacement", SOURCE_FLOOR),
1033
+ // Six `vec4` rows per placement, so the count is the rows the kernels index by rather than
1034
+ // the placements: one placement record is 24 words either way, and the CPU's `Float32Array`
1035
+ // stays the GPU's buffer with no repacking.
1036
+ source: storageAttribute(StorageBufferAttribute, "vec4", SOURCE_FLOOR * PLACEMENT_ROWS),
1020
1037
  };
1021
1038
  this.#version += 1;
1022
1039
  return this.#buffers;
@@ -1061,8 +1078,11 @@ export class WorldGpuScene {
1061
1078
  }
1062
1079
 
1063
1080
  #reserve(count: number): boolean {
1064
- // A ring-sized floor, so the first few placements do not each pay a reallocation.
1065
- return this.#growOf("source", Math.max(SOURCE_FLOOR, count));
1081
+ // A ring-sized floor, so the first few placements do not each pay a reallocation. The count is
1082
+ // `vec4` rows, the type the kernels bind the source buffer as: `PLACEMENT_ROWS` of them hold
1083
+ // one placement, and the buffer stays a whole number of placements because the floor and every
1084
+ // doubling of it are whole ones.
1085
+ return this.#growOf("source", Math.max(SOURCE_FLOOR, count) * PLACEMENT_ROWS);
1066
1086
  }
1067
1087
 
1068
1088
  #writePlacement(index: number): void {
@@ -9,15 +9,17 @@ import {
9
9
  instanceIndex,
10
10
  int,
11
11
  length,
12
+ mat4,
12
13
  max,
13
14
  min,
14
15
  storage,
16
+ uint,
15
17
  vec3,
16
18
  } from "three/tsl";
17
19
  import type { IndirectStorageBufferAttribute, StorageInstancedBufferAttribute } from "three/webgpu";
18
20
  import { GATE_STEP } from "./world-gpu-reference.js";
19
21
  import type { IGpuKernel, IGpuSceneBuffers } from "./world-gpu-types.js";
20
- import { PlacementStruct, nodes } from "./world-gpu-types.js";
22
+ import { PLACEMENT_ROWS, nodes } from "./world-gpu-types.js";
21
23
  import { DRAW_ARGS_WORDS } from "./world-gpu-validation.js";
22
24
 
23
25
  /**
@@ -75,7 +77,7 @@ export interface IShadowKernelInput {
75
77
  */
76
78
  export function buildShadowKernel(input: IShadowKernelInput): IGpuKernel {
77
79
  const { buffers, shadow } = input;
78
- const source = nodes(storage(buffers.source, PlacementStruct, buffers.source.count));
80
+ const source = nodes(storage(buffers.source, "vec4", buffers.source.count));
79
81
  const drawn = nodes(storage(shadow.drawn, "mat4", shadow.drawn.count));
80
82
  const argsPlain = nodes(storage(shadow.args, "uint", shadow.args.count));
81
83
  const argsAtomic = nodes(storage(shadow.args, "uint", shadow.args.count).toAtomic());
@@ -113,10 +115,18 @@ export function buildShadowKernel(input: IShadowKernelInput): IGpuKernel {
113
115
  })().compute(Math.max(1, buffers.keys.count * clearWidth));
114
116
  const cull = Fn(() => {
115
117
  If(instanceIndex.greaterThanEqual(counts.x), () => Return());
116
- const placement = source.element(instanceIndex);
117
- const centre = placement.get("centre");
118
- const matrix = placement.get("matrix");
119
- const slot = placement.get("info").x;
118
+ // One placement is `PLACEMENT_ROWS` consecutive `vec4` rows: the world matrix's four columns,
119
+ // then the sphere, then `info`. The main kernel reads the same rows; see `world-gpu-reference.ts`.
120
+ const base = instanceIndex.mul(uint(PLACEMENT_ROWS));
121
+ const matrix = mat4(
122
+ source.element(base),
123
+ source.element(base.add(uint(1))),
124
+ source.element(base.add(uint(2))),
125
+ source.element(base.add(uint(3))),
126
+ );
127
+ const centre = source.element(base.add(uint(4)));
128
+ const info = source.element(base.add(uint(5)));
129
+ const slot = info.x;
120
130
  If(slot.lessThan(0.0), () => Return());
121
131
  If(slot.greaterThanEqual(counts.y), () => Return());
122
132
  const radius = centre.w;
@@ -130,7 +140,7 @@ export function buildShadowKernel(input: IShadowKernelInput): IGpuKernel {
130
140
  // The main pass's own biased distance and level; see `shadowLevel`, which the reference runs.
131
141
  const lodDistance = nodes(distance).mul(bias as never);
132
142
  const level = int(0).toVar();
133
- const scale = abs(placement.get("info").y);
143
+ const scale = abs(info.y);
134
144
  Loop({ start: int(1), end: asset.y, type: "int", condition: "<" }, ({ i }: { i: unknown }) => {
135
145
  const candidate = levels.element(asset.x.add(i as never));
136
146
  const threshold = nodes(candidate.x).toVar();
@@ -183,7 +193,10 @@ export function buildShadowKernel(input: IShadowKernelInput): IGpuKernel {
183
193
  drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
184
194
  });
185
195
  });
186
- })().compute(Math.max(1, buffers.source.count));
196
+ })().compute(
197
+ // One thread per placement record, not per `vec4` row of the source buffer.
198
+ Math.max(1, Math.ceil(buffers.source.count / PLACEMENT_ROWS)),
199
+ );
187
200
  clear.setName("worldGpuSceneShadowClear");
188
201
  cull.setName("worldGpuSceneShadowCull");
189
202
  return { clear, cull };
@@ -1,5 +1,4 @@
1
- import type { BufferAttribute } from "three";
2
- import { struct } from "three/tsl";
1
+ import type { BufferAttribute, Matrix4 } from "three";
3
2
  import type {
4
3
  IndirectStorageBufferAttribute,
5
4
  ReadbackBuffer,
@@ -8,6 +7,33 @@ import type {
8
7
  } from "three/webgpu";
9
8
  import type { IKernelOcclusion } from "./render/depth-pyramid.js";
10
9
 
10
+ /**
11
+ * The six frustum planes of `matrix` (projection times view) into `out` as `[nx, ny, nz, d]` rows,
12
+ * the planes three's `Frustum.setFromProjectionMatrix` writes with its default (WebGL) near plane.
13
+ * Read straight from the elements, not through a `Frustum`: the owned engine's facade has no
14
+ * `planes` array (`planes.entries()` threw and stopped the render loop, PRD-857), and one
15
+ * `elements` read replaces 24 bridged getters a frame.
16
+ */
17
+ export function frustumPlanes(matrix: Matrix4, out: Float32Array): void {
18
+ const m = matrix.elements;
19
+ // [column, sign]: left, right, bottom, top, far, near; each plane is row 3 plus sign times row k.
20
+ const rows = [0, -1, 0, 1, 1, 1, 1, -1, 2, -1, 2, 1] as const;
21
+ for (let plane = 0; plane < 6; plane += 1) {
22
+ const k = rows[plane * 2] as number;
23
+ const sign = rows[plane * 2 + 1] as number;
24
+ const x = (m[3] as number) + sign * (m[k] as number);
25
+ const y = (m[7] as number) + sign * (m[4 + k] as number);
26
+ const z = (m[11] as number) + sign * (m[8 + k] as number);
27
+ const w = (m[15] as number) + sign * (m[12 + k] as number);
28
+ const inverse = 1 / Math.hypot(x, y, z);
29
+ const at = plane * 4;
30
+ out[at] = x * inverse;
31
+ out[at + 1] = y * inverse;
32
+ out[at + 2] = z * inverse;
33
+ out[at + 3] = w * inverse;
34
+ }
35
+ }
36
+
11
37
  /** `DrawIndexedIndirect`: indexCount, instanceCount, firstIndex, baseVertex, firstInstance. */
12
38
  export const DRAW_ARGS_WORDS = 5;
13
39
  /** `mat4` per key: the part's own offset inside the model, the same matrix the CPU composes. */
@@ -54,9 +80,14 @@ export const SLOT_NONE = -1;
54
80
  * together, once, and every buffer is allocated from this table and nowhere else.
55
81
  */
56
82
  export const STORAGE_WORDS = {
57
- /** `mat4` + `centre` (vec4) + `info` (vec4), so one placement is 96 bytes and one stride. */
58
- // quality-allow: the object key is the WGSL type name the kernel reads, so it keeps that spelling.
59
- // biome-ignore lint/style/useNamingConvention: the key is the WGSL type, spelled as the kernel declares it.
83
+ /**
84
+ * `mat4` + `centre` (vec4) + `info` (vec4), so one placement is 96 bytes and one stride. Nothing
85
+ * is allocated from this key any more: the kernels read one placement as {@link PLACEMENT_ROWS}
86
+ * consecutive `vec4` rows, and the source buffer is allocated in those rows. The key stays as the
87
+ * name of the record's whole stride.
88
+ */
89
+ // quality-allow: the object key names one placement's whole stride, so it keeps that spelling.
90
+ // biome-ignore lint/style/useNamingConvention: the key names one placement's whole stride, spelled as its record.
60
91
  GpuPlacement: PLACEMENT_WORDS,
61
92
  /** `mat4`, one per key: the part's own offset inside the model, the same one the CPU composes. */
62
93
  mat4: LOCAL_WORDS,
@@ -107,14 +138,11 @@ export const VALIDATE_EVERY = 30;
107
138
  export const TALLY_EVERY = 30;
108
139
 
109
140
  /**
110
- * A `mat4` world matrix, the placement's bounding-sphere centre and radius, and the asset slot whose
111
- * gates pick its level. One stride, so the CPU's `Float32Array` is the GPU's storage buffer with no
112
- * repacking and no type punning: the radius and the slot are small and exactly representable.
141
+ * How many `vec4` rows one placement record is: the world matrix's four columns, then `centre`, then
142
+ * `info`. The kernels read the source buffer as these rows rather than as one struct element, which
143
+ * the owned engine refuses, and the 24 words are the same words either way.
113
144
  */
114
- export const PlacementStruct = struct(
115
- { matrix: "mat4", centre: "vec4", info: "vec4" },
116
- "GpuPlacement",
117
- );
145
+ export const PLACEMENT_ROWS = PLACEMENT_WORDS / VEC4_WORDS;
118
146
 
119
147
  /** One resident placement as the source buffer holds it. */
120
148
  export interface IGpuPlacement {
@@ -361,7 +389,7 @@ export const STORAGE_PLAIN: Record<Exclude<BufferName, "args" | "drawn">, Storag
361
389
  keys: "vec4",
362
390
  levels: "vec4",
363
391
  locals: "mat4",
364
- source: "GpuPlacement",
392
+ source: "vec4",
365
393
  };
366
394
 
367
395
  /** Resident placements the source buffer is sized to hold before the first reallocation. */
@@ -81,6 +81,11 @@ export class ModelLoadLimiter {
81
81
  * The budget is opened once per `update` and drawn down by the units it admits. A unit always
82
82
  * finishes, so a frame spends at most the limit plus the unit that crossed it, and the rest of the
83
83
  * backlog waits for the next frame rather than being dropped.
84
+ *
85
+ * @situation streamed terrain tiles or cells hitch the frame that admits them
86
+ * @situation cap how many milliseconds a frame spends building streamed content
87
+ * @constraint open a new budget each frame; a unit always finishes, so one unit can cross the limit
88
+ * @example tiles.follow(player.position, new AdmissionBudget(2, () => performance.now()));
84
89
  */
85
90
  export class AdmissionBudget implements IAdmissionBudget {
86
91
  readonly #limitMs: number;
@@ -0,0 +1,80 @@
1
+ import { type Box3, type BufferGeometry, type Material, type Mesh, Vector3 } from "three";
2
+ import { baseGeometryOf } from "./model-lod.js";
3
+
4
+ /** One material section of a mesh: the whole mesh, or one group of a multi-material mesh. */
5
+ export interface IMeshSection {
6
+ readonly material: Material;
7
+ readonly group?: { readonly start: number; readonly count: number };
8
+ }
9
+
10
+ /**
11
+ * A mesh's material sections: one per geometry group for a material array, else the whole mesh.
12
+ * Instanced props draw one batch per material, so an imported model splits here first.
13
+ *
14
+ * @situation scatter or instance an imported glTF model that has several materials
15
+ * @constraint a section's `material` can be `undefined` for a group naming a missing material slot; skip it
16
+ * @example for (const section of meshSections(mesh)) parts.push(sectionGeometry(mesh, box, section));
17
+ */
18
+ export function meshSections(mesh: Mesh): IMeshSection[] {
19
+ const materials = mesh.material;
20
+ return Array.isArray(materials)
21
+ ? mesh.geometry.groups.map((group) => ({
22
+ material: materials[group.materialIndex ?? 0] as Material,
23
+ group,
24
+ }))
25
+ : [{ material: materials }];
26
+ }
27
+
28
+ /**
29
+ * One section's geometry in model space, standing on y = 0. Every section of a model takes the same
30
+ * base from the whole model's `box`, so a crown keeps its place on its trunk: basing each section on
31
+ * its own bounds detaches them. The mesh's LOD0 geometry is cloned under its world matrix, and a
32
+ * group becomes the clone's draw range.
33
+ *
34
+ * @situation the crown of an instanced tree floats off its trunk, or the parts of a model separate
35
+ * @situation turn each part of an imported model into a geometry for an instanced prop batch
36
+ * @constraint `box` is the whole model's world bounds after any unit normalisation; call `mesh.updateWorldMatrix` first
37
+ * @example const box = new Box3().setFromObject(root); const geometry = sectionGeometry(mesh, box, section);
38
+ */
39
+ export function sectionGeometry(
40
+ mesh: Mesh,
41
+ box: Box3,
42
+ section: IMeshSection,
43
+ options: { readonly centreXZ?: boolean } = {},
44
+ ): BufferGeometry {
45
+ const geometry = baseGeometryOf(mesh).clone().applyMatrix4(mesh.matrixWorld);
46
+ const { group } = section;
47
+ if (group) {
48
+ const start = Math.max(group.start, geometry.drawRange.start);
49
+ const end = Math.min(
50
+ group.start + group.count,
51
+ geometry.drawRange.start + geometry.drawRange.count,
52
+ );
53
+ geometry.clearGroups();
54
+ geometry.setDrawRange(start, Math.max(0, end - start));
55
+ }
56
+ const centre = box.getCenter(new Vector3());
57
+ const centred = options.centreXZ === true;
58
+ geometry.translate(centred ? -centre.x : 0, -box.min.y, centred ? -centre.z : 0);
59
+ return geometry;
60
+ }
61
+
62
+ /**
63
+ * Recompute the normals of a geometry whose normals are missing, zero or not finite, and leave
64
+ * authored normals alone. Some exported art ships zero normals and draws black under any light.
65
+ * Run it after any reshape, so the recomputed normals fit the final shape.
66
+ *
67
+ * @situation an imported model draws black or unlit because it ships zero normals
68
+ * @constraint one bad normal recomputes them all; an intentionally hard-edged model loses its authored split normals only if one is bad
69
+ * @example geometry.scale(1.1, 1, 1.1); repairZeroNormals(geometry);
70
+ */
71
+ export function repairZeroNormals(geometry: BufferGeometry): boolean {
72
+ const normals = geometry.getAttribute("normal");
73
+ let valid = normals !== undefined;
74
+ for (let i = 0; valid && normals && i < normals.count; i++) {
75
+ const length = Math.hypot(normals.getX(i), normals.getY(i), normals.getZ(i));
76
+ valid = Number.isFinite(length) && length >= 0.01;
77
+ }
78
+ if (!valid) geometry.computeVertexNormals();
79
+ return !valid;
80
+ }
@@ -0,0 +1,282 @@
1
+ import { BufferAttribute, BufferGeometry } from "three";
2
+ import type { Heightfield } from "./world-heightfield.js";
3
+ import { type IWaterLake, WATER_RIBBON_REACH, lakeReach } from "./world-water-bodies.js";
4
+
5
+ /** How a ribbon is cut; every value has the default `WaterBodies` and the Strata preview use. */
6
+ export interface IRiverRibbonOptions {
7
+ /** Vertices across each station. Default 25. */
8
+ readonly columns?: number;
9
+ /** Reach either side of the centreline, per metre of channel width. Default `WATER_RIBBON_REACH`. */
10
+ readonly reach?: number;
11
+ /** Deepest water the `metres` attribute records. Default unbounded. */
12
+ readonly maxDepth?: number;
13
+ /** Metres of depth lost per metre toward the ribbon's edge, so the edges read shallow. Default 0.2. */
14
+ readonly edgeSlope?: number;
15
+ }
16
+
17
+ /**
18
+ * The water surface of every river, as one geometry with one group per river.
19
+ *
20
+ * Each station is a row across the river at its own surface height, out to `reach` widths either side
21
+ * of the centreline, the reach `WaterBodies` floods; one more row a reach past each end stands where
22
+ * `WaterBodies` clamps a segment, so the water a swimmer finds past a river's end is drawn there too
23
+ * (cut at the end station, the surface stopped in a straight edge with its carved bed dry beyond).
24
+ * Quads dry on both rows against `field` are dropped, so the surface ends at the shore.
25
+ * Past an end where the ground falls below the end's bed, the water would run off: that cap is not
26
+ * drawn, and the end stays cut at its last station.
27
+ *
28
+ * Attributes for the game's water material: `flow` (the unit downstream heading), `flowUv` (metres
29
+ * down the centreline, metres across it) and `metres` (water depth over the ground). It decides no
30
+ * colour, ripple or opacity: the game shades it.
31
+ *
32
+ * @situation draw a river's water surface from the baked stations
33
+ * @situation a river's water stops in a straight edge, or a swimmer floats where no water is drawn
34
+ * @situation share one river shape between the drawn water and the swimmer
35
+ * @situation river water hangs over dry ground past the river's head or tail
36
+ * @constraint stations, width and reach come from the game's bake; the game's material shades the geometry
37
+ * @example const geometry = riverRibbonGeometry(rivers, field, { maxDepth: 1.6 });
38
+ */
39
+ export function riverRibbonGeometry(
40
+ rivers: readonly { readonly points: readonly (readonly number[])[]; readonly width: number }[],
41
+ field: Heightfield,
42
+ options: IRiverRibbonOptions = {},
43
+ ): BufferGeometry {
44
+ const columns = options.columns ?? 25;
45
+ if (!Number.isInteger(columns) || columns < 2)
46
+ throw new Error(
47
+ `TN_RIVER_RIBBON_INVALID: columns must be an integer of at least 2, received ${columns}.`,
48
+ );
49
+ const perWidth = options.reach ?? WATER_RIBBON_REACH;
50
+ const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
51
+ const edgeSlope = options.edgeSlope ?? 0.2;
52
+ if (!(perWidth > 0) || !(maxDepth > 0) || !(edgeSlope >= 0))
53
+ throw new Error(
54
+ "TN_RIVER_RIBBON_INVALID: reach and maxDepth must be positive, edgeSlope not negative.",
55
+ );
56
+ const positions: number[] = [];
57
+ const flows: number[] = [];
58
+ const uvs: number[] = [];
59
+ const depths: number[] = [];
60
+ const indices: number[] = [];
61
+ const geometry = new BufferGeometry();
62
+ for (const river of rivers) {
63
+ if (!(river.width > 0) || river.points.length < 2)
64
+ throw new Error(
65
+ `TN_RIVER_RIBBON_INVALID: a river needs a positive width and two stations, received width ${river.width} and ${river.points.length} stations.`,
66
+ );
67
+ const start = indices.length;
68
+ ribbon(field, river.points, river.width * perWidth, columns, maxDepth, edgeSlope, {
69
+ depths,
70
+ flows,
71
+ indices,
72
+ positions,
73
+ uvs,
74
+ });
75
+ geometry.addGroup(start, indices.length - start, 0);
76
+ }
77
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
78
+ geometry.setAttribute("flow", new BufferAttribute(new Float32Array(flows), 2));
79
+ geometry.setAttribute("flowUv", new BufferAttribute(new Float32Array(uvs), 2));
80
+ geometry.setAttribute("metres", new BufferAttribute(new Float32Array(depths), 1));
81
+ geometry.setIndex(indices);
82
+ geometry.computeVertexNormals();
83
+ geometry.computeBoundingBox();
84
+ geometry.computeBoundingSphere();
85
+ return geometry;
86
+ }
87
+
88
+ /** Metres the ground past an end may sit under its bed before the cap there counts as drained. */
89
+ const DRAIN_TOLERANCE = 0.05;
90
+
91
+ /** A station `reach` metres past `end`, away from `inner`, at the end's surface height. */
92
+ function beyond(
93
+ end: readonly number[],
94
+ inner: readonly number[],
95
+ reach: number,
96
+ ): readonly number[] {
97
+ const dx = (end[0] ?? 0) - (inner[0] ?? 0);
98
+ const dz = (end[2] ?? 0) - (inner[2] ?? 0);
99
+ const length = Math.hypot(dx, dz) || 1;
100
+ return [
101
+ (end[0] ?? 0) + (dx / length) * reach,
102
+ end[1] ?? 0,
103
+ (end[2] ?? 0) + (dz / length) * reach,
104
+ ];
105
+ }
106
+
107
+ function ribbon(
108
+ field: Heightfield,
109
+ stations: readonly (readonly number[])[],
110
+ reach: number,
111
+ columns: number,
112
+ maxDepth: number,
113
+ edgeSlope: number,
114
+ out: { positions: number[]; flows: number[]; uvs: number[]; depths: number[]; indices: number[] },
115
+ ): void {
116
+ const points = [
117
+ beyond(stations[0] as readonly number[], stations[1] as readonly number[], reach),
118
+ ...stations,
119
+ beyond(stations.at(-1) as readonly number[], stations.at(-2) as readonly number[], reach),
120
+ ];
121
+ const base = out.positions.length / 3;
122
+ // A cap past a river that ends at the field's edge samples the edge: no ground is known past it.
123
+ const minX = field.origin.x - field.width / 2;
124
+ const minZ = field.origin.z - field.depth / 2;
125
+ const ground = (x: number, z: number): number =>
126
+ field.heightAt(
127
+ Math.min(minX + field.width, Math.max(minX, x)),
128
+ Math.min(minZ + field.depth, Math.max(minZ, z)),
129
+ );
130
+ const wet: number[] = [];
131
+ // A cap vertex over ground below the bed at its end station is drained: water there would run off,
132
+ // not stand at the end's level, so the quads that reach it are dropped and that end stays cut.
133
+ const last = points.length - 1;
134
+ const bedAt = (station: readonly number[]): number => ground(station[0] ?? 0, station[2] ?? 0);
135
+ const capBed = [
136
+ bedAt(stations[0] as readonly number[]),
137
+ bedAt(stations.at(-1) as readonly number[]),
138
+ ];
139
+ const drained: boolean[] = [];
140
+ // Metres down the centreline, as Unreal builds a river's sections by distance along its spline and
141
+ // carries the flow per vertex (UE 5.8.3:
142
+ // Engine/Plugins/Experimental/Water/Source/Runtime/Private/WaterBodyRiverComponent.cpp:104-138).
143
+ let downstream = 0;
144
+ for (let k = 0; k < points.length; k += 1) {
145
+ const [x = 0, y = 0, z = 0] = points[k] as readonly number[];
146
+ if (k > 0) {
147
+ const [px = 0, , pz = 0] = points[k - 1] as readonly number[];
148
+ downstream += Math.hypot(x - px, z - pz);
149
+ }
150
+ const before = points[Math.max(0, k - 1)] as readonly number[];
151
+ const after = points[Math.min(points.length - 1, k + 1)] as readonly number[];
152
+ let dx = (after[0] ?? 0) - (before[0] ?? 0);
153
+ let dz = (after[2] ?? 0) - (before[2] ?? 0);
154
+ const length = Math.hypot(dx, dz) || 1;
155
+ dx /= length;
156
+ dz /= length;
157
+ for (let c = 0; c < columns; c += 1) {
158
+ const across = (c / (columns - 1) - 0.5) * 2 * reach;
159
+ const vx = x - dz * across;
160
+ const vz = z + dx * across;
161
+ out.positions.push(vx, y, vz);
162
+ out.flows.push(dx, dz);
163
+ out.uvs.push(downstream, across);
164
+ const below = ground(vx, vz);
165
+ const bed = k === 0 ? capBed[0] : k === last ? capBed[1] : undefined;
166
+ const dry = bed !== undefined && below < bed - DRAIN_TOLERANCE;
167
+ const depth = dry
168
+ ? 0
169
+ : Math.min(
170
+ maxDepth,
171
+ Math.max(0, y - below),
172
+ Math.max(0, (reach - Math.abs(across)) * edgeSlope),
173
+ );
174
+ out.depths.push(depth);
175
+ wet.push(depth > 0 ? 1 : 0);
176
+ drained.push(dry);
177
+ }
178
+ }
179
+ for (let k = 1; k < points.length; k += 1) {
180
+ for (let c = 1; c < columns; c += 1) {
181
+ const a = (k - 1) * columns + c - 1;
182
+ const d = k * columns + c - 1;
183
+ // A quad with a dry corner stays, so the game's depth ramp has dry ground to dissolve across;
184
+ // only a quad dry on both rows is dropped, which takes the surface off the hillside.
185
+ const rowA = (wet[a - 1] ?? 0) + (wet[a + 1] ?? 0) + (wet[d - 1] ?? 0) + (wet[d + 1] ?? 0);
186
+ const rowB = (wet[a] ?? 0) + (wet[a + 1] ?? 0) + (wet[d] ?? 0) + (wet[d + 1] ?? 0);
187
+ if (rowA === 0 && rowB === 0) continue;
188
+ if (drained[a] || drained[a + 1] || drained[d] || drained[d + 1]) continue;
189
+ // Wound so the face points up: along × across points down, so the pair is taken the other way.
190
+ out.indices.push(base + a, base + a + 1, base + d, base + a + 1, base + d + 1, base + d);
191
+ }
192
+ }
193
+ }
194
+
195
+ /** How a lake's disc is meshed; every default is the Strata preview's. */
196
+ export interface ILakeSurfaceOptions {
197
+ /** Rings from the centre to the reach. Default 44. */
198
+ readonly rings?: number;
199
+ /** Vertices around each ring. Default 88. */
200
+ readonly spokes?: number;
201
+ /** How the ring spacing grows outwards; above 1 packs vertices into the near water. Default 1.7. */
202
+ readonly packing?: number;
203
+ /** Deepest water the `metres` attribute records. Default unbounded. */
204
+ readonly maxDepth?: number;
205
+ }
206
+
207
+ /**
208
+ * A lake's water surface: a level disc out to `lakeReach`, the footprint `WaterBodies` floods, with a
209
+ * `metres` attribute (water depth over the ground). Only cells with water at a corner get triangles,
210
+ * so the surface does not hover over dry hillside and the shore follows the ground's contour. The
211
+ * rings pack towards the middle, so an irregular basin costs vertices where the camera sees them.
212
+ * Returns `undefined` when the basin holds no water at its level.
213
+ *
214
+ * @situation draw a lake's water surface from the baked level and seed
215
+ * @situation a lake's drawn water and the swimmer's water disagree
216
+ * @constraint the lake row and field come from the game's bake; the game's material shades the geometry
217
+ * @example const geometry = lakeSurfaceGeometry({ ...lake, margin: 1.12 }, field, { maxDepth: 1.6 });
218
+ */
219
+ export function lakeSurfaceGeometry(
220
+ lake: IWaterLake,
221
+ field: Heightfield,
222
+ options: ILakeSurfaceOptions = {},
223
+ ): BufferGeometry | undefined {
224
+ const rings = options.rings ?? 44;
225
+ const spokes = options.spokes ?? 88;
226
+ const packing = options.packing ?? 1.7;
227
+ const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
228
+ if (!Number.isInteger(rings) || rings < 2 || !Number.isInteger(spokes) || spokes < 3)
229
+ throw new Error(
230
+ `TN_LAKE_SURFACE_INVALID: rings must be an integer of at least 2 and spokes of at least 3, received ${rings} and ${spokes}.`,
231
+ );
232
+ if (!(packing > 0) || !(maxDepth > 0))
233
+ throw new Error("TN_LAKE_SURFACE_INVALID: packing and maxDepth must be positive.");
234
+ const reach = lakeReach(field, lake);
235
+ if (!(reach > 0)) return undefined;
236
+ const [cx = 0, cz = 0] = lake.at;
237
+ const minX = field.origin.x - field.width / 2;
238
+ const minZ = field.origin.z - field.depth / 2;
239
+ const count = (rings - 1) * spokes + 1;
240
+ const positions = new Float32Array(count * 3);
241
+ const depths = new Float32Array(count);
242
+ const place = (index: number, radius: number, spoke: number): void => {
243
+ const angle = (spoke / spokes) * Math.PI * 2;
244
+ const x = Math.max(minX, Math.min(minX + field.width, cx + Math.cos(angle) * radius));
245
+ const z = Math.max(minZ, Math.min(minZ + field.depth, cz + Math.sin(angle) * radius));
246
+ positions[index * 3] = x;
247
+ positions[index * 3 + 1] = lake.level;
248
+ positions[index * 3 + 2] = z;
249
+ depths[index] = Math.min(maxDepth, Math.max(0, lake.level - field.heightAt(x, z)));
250
+ };
251
+ place(0, 0, 0);
252
+ for (let ring = 1; ring < rings; ring += 1) {
253
+ const radius = reach * (ring / (rings - 1)) ** packing;
254
+ for (let spoke = 0; spoke < spokes; spoke += 1)
255
+ place(1 + (ring - 1) * spokes + spoke, radius, spoke);
256
+ }
257
+ const depth = (index: number): number => depths[index] ?? 0;
258
+ const indices: number[] = [];
259
+ // A cell with one wet corner stays, so the game's depth ramp has dry ground to fade across.
260
+ for (let spoke = 0; spoke < spokes; spoke += 1) {
261
+ const first = 1 + spoke;
262
+ const next = 1 + ((spoke + 1) % spokes);
263
+ if (depth(0) + depth(first) + depth(next) > 0) indices.push(0, first, next);
264
+ }
265
+ for (let ring = 2; ring < rings; ring += 1)
266
+ for (let spoke = 0; spoke < spokes; spoke += 1) {
267
+ const next = (spoke + 1) % spokes;
268
+ const inner = 1 + (ring - 2) * spokes + spoke;
269
+ const innerNext = 1 + (ring - 2) * spokes + next;
270
+ const outer = 1 + (ring - 1) * spokes + spoke;
271
+ const outerNext = 1 + (ring - 1) * spokes + next;
272
+ if (depth(inner) + depth(innerNext) + depth(outer) + depth(outerNext) <= 0) continue;
273
+ indices.push(inner, outer, innerNext, innerNext, outer, outerNext);
274
+ }
275
+ const geometry = new BufferGeometry();
276
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
277
+ geometry.setAttribute("metres", new BufferAttribute(depths, 1));
278
+ geometry.setIndex(indices);
279
+ geometry.computeVertexNormals();
280
+ geometry.computeBoundingSphere();
281
+ return geometry;
282
+ }