@threenative/core 0.3.12 → 0.3.15

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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  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-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  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 +871 -1018
  20. package/dist/index.js +4786 -1631
  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-BADStsTn.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 +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -9,8 +9,10 @@ import {
9
9
  instanceIndex,
10
10
  int,
11
11
  length,
12
+ mat4,
12
13
  max,
13
14
  storage,
15
+ uint,
14
16
  vec3,
15
17
  } from "three/tsl";
16
18
  import { biasedLodDistance } from "./model-lod.js";
@@ -24,7 +26,7 @@ import type {
24
26
  IKernelResult,
25
27
  IRegion,
26
28
  } from "./world-gpu-types.js";
27
- import { PlacementStruct, nodes } from "./world-gpu-types.js";
29
+ import { PLACEMENT_ROWS, nodes } from "./world-gpu-types.js";
28
30
  import { DRAW_ARGS_WORDS, LIVE_MATRIX, LOCAL_WORDS, compose } from "./world-gpu-validation.js";
29
31
 
30
32
  /**
@@ -402,7 +404,7 @@ export interface ICullKernelInput {
402
404
  */
403
405
  export function buildCullKernel(input: ICullKernelInput): IGpuKernel {
404
406
  const { buffers } = input;
405
- const source = nodes(storage(buffers.source, PlacementStruct, buffers.source.count));
407
+ const source = nodes(storage(buffers.source, "vec4", buffers.source.count));
406
408
  const drawn = nodes(storage(buffers.drawn, "mat4", buffers.drawn.count));
407
409
  const argsPlain = nodes(storage(buffers.args, "uint", buffers.args.count));
408
410
  const argsAtomic = nodes(storage(buffers.args, "uint", buffers.args.count).toAtomic());
@@ -436,10 +438,19 @@ export function buildCullKernel(input: ICullKernelInput): IGpuKernel {
436
438
  })().compute(Math.max(1, buffers.keys.count * clearWidth));
437
439
  const cull = Fn(() => {
438
440
  If(instanceIndex.greaterThanEqual(counts.x), () => Return());
439
- const placement = source.element(instanceIndex);
440
- const centre = placement.get("centre");
441
- const matrix = placement.get("matrix");
442
- const slot = placement.get("info").x;
441
+ // One placement is `PLACEMENT_ROWS` consecutive `vec4` rows: the world matrix's four columns,
442
+ // then the sphere, then `info`. Read as rows rather than as a struct element, which the owned
443
+ // engine refuses; the words are the ones `#writePlacement` wrote either way.
444
+ const base = instanceIndex.mul(uint(PLACEMENT_ROWS));
445
+ const matrix = mat4(
446
+ source.element(base),
447
+ source.element(base.add(uint(1))),
448
+ source.element(base.add(uint(2))),
449
+ source.element(base.add(uint(3))),
450
+ );
451
+ const centre = source.element(base.add(uint(4)));
452
+ const info = source.element(base.add(uint(5)));
453
+ const slot = info.x;
443
454
  If(slot.lessThan(0.0), () => Return());
444
455
  If(slot.greaterThanEqual(counts.y), () => Return());
445
456
  const radius = centre.w;
@@ -459,7 +470,7 @@ export function buildCullKernel(input: ICullKernelInput): IGpuKernel {
459
470
  // gate is the base projected distance and is scaled by it. A mirrored placement's scale is
460
471
  // negative, and the extent it reaches is the same, so the kernel takes the magnitude exactly as
461
472
  // `levelAtGates` does; `info.y` is already finite-sanitised when the record is written.
462
- const scale = abs(placement.get("info").y);
473
+ const scale = abs(info.y);
463
474
  Loop({ start: int(1), end: gate.y, type: "int", condition: "<" }, ({ i }: { i: unknown }) => {
464
475
  const candidate = levels.element(gate.x.add(i as never));
465
476
  const threshold = nodes(candidate.x).toVar();
@@ -503,7 +514,10 @@ export function buildCullKernel(input: ICullKernelInput): IGpuKernel {
503
514
  drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
504
515
  });
505
516
  });
506
- })().compute(Math.max(1, buffers.source.count));
517
+ })().compute(
518
+ // One thread per placement record, not per `vec4` row of the source buffer.
519
+ Math.max(1, Math.ceil(buffers.source.count / PLACEMENT_ROWS)),
520
+ );
507
521
  clear.setName("worldGpuSceneClear");
508
522
  cull.setName("worldGpuSceneCull");
509
523
  return { clear, cull };
@@ -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
+ }