@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
@@ -9,7 +9,8 @@ import {
9
9
  Vector3,
10
10
  } from "three";
11
11
  import type { InstancedBatch } from "./instanced-batch.js";
12
- import { currentWriteEpoch, pooledCapacity, pooledMesh } from "./render/mesh-pool.js";
12
+ import { pooledCapacity, pooledMesh } from "./render/mesh-pool.js";
13
+ import { type IRecordWriter, batchRecords } from "./world-cell-records.js";
13
14
 
14
15
  /**
15
16
  * Records a retired batch's instance buffer is shrunk to; see `SharedBatch.park`.
@@ -73,25 +74,12 @@ type ISquareSizes = Map<string, number>;
73
74
  * main batch is the only bound on it. Module-level like the upload epoch, because there is one world
74
75
  * drawing at a time.
75
76
  */
76
- let regroupScratch = new Float32Array(0);
77
- let lodRangeScratch = new Float32Array(0);
78
-
79
77
  const LOD_RANGE_ATTRIBUTE = "tnPublishedLodRange";
78
+ /** The local box of a part with no readable bounds: the record box is then its origins' extent. */
79
+ const ZERO = new Vector3();
80
80
  /** Floats per record in it: the levels published (min, max), the level a fade starts from (-1: none) and when. */
81
81
  export const LOD_RANGE_STRIDE = 4;
82
82
 
83
- function lodScratchFor(floats: number): Float32Array {
84
- if (lodRangeScratch.length < floats) lodRangeScratch = new Float32Array(floats * 2);
85
- return lodRangeScratch;
86
- }
87
-
88
- /** A scratch with room for `floats`, kept between regroups so a walk allocates it once. */
89
- function scratchFor(floats: number): Float32Array {
90
- if (regroupScratch.length < floats) regroupScratch = new Float32Array(floats * 2);
91
- return regroupScratch;
92
- }
93
-
94
- /** Records a square's blocks hold, which is its share of the batch. */
95
83
  function sizeOf(square: { blocks: Array<[number, number, number, string]> }): number {
96
84
  let size = 0;
97
85
  for (const block of square.blocks) size += block[2];
@@ -104,7 +92,7 @@ export function sameSquares(next: Set<string>, was: Set<string> | undefined): bo
104
92
  return true;
105
93
  }
106
94
 
107
- export class SharedBatch {
95
+ export class SharedBatch implements IRecordWriter {
108
96
  mesh: ICasterScaleMesh;
109
97
  #sourceGeometry: BufferGeometry;
110
98
  readonly #rangeLevel: number;
@@ -228,17 +216,19 @@ export class SharedBatch {
228
216
  readonly #boxes = new Map<number, Box3>();
229
217
  /** Block handle -> the largest instance scale in it; the union is published on the mesh. */
230
218
  readonly #scales = new Map<number, number>();
231
- /** Carried out of the last `#boxOf` pass, which already reads every record's basis. */
232
- #maxScale = 0;
233
219
  #localGeometry: BufferGeometry | undefined;
234
220
  readonly #localCenter = new Vector3();
235
221
  readonly #localHalf = new Vector3();
236
222
  readonly #union = new Box3();
237
223
  readonly #point = new Vector3();
238
- /** This batch's own pending upload span, and the `update` it was opened in. See `#touched`. */
224
+ /** This batch's pending upload span, in floats of the instance buffer, until the next flush. See `#touched`. */
239
225
  #pendingLow = 0;
240
226
  #pendingHigh = 0;
241
- #pendingEpoch = -1;
227
+ /** The buffers that span belongs to: the ones this batch wrote last, whatever a later dress swaps in. */
228
+ #pendingMatrix: InstancedBufferAttribute | undefined;
229
+ #pendingRanges: InstancedBufferAttribute | undefined;
230
+ /** Block handle -> where its box starts in the flush's answer; see {@link settleRecords}. */
231
+ readonly #pendingBoxes = new Map<number, number>();
242
232
 
243
233
  constructor(
244
234
  geometry: BufferGeometry,
@@ -347,8 +337,8 @@ export class SharedBatch {
347
337
  mesh.frustumCulled = true;
348
338
  mesh.castShadow = false;
349
339
  mesh.receiveShadow = false;
350
- (mesh.instanceMatrix.array as Float32Array).fill(0);
351
- mesh.instanceMatrix.needsUpdate = true;
340
+ batchRecords.fill(mesh.instanceMatrix, 0, records * 16);
341
+ batchRecords.upload(mesh.instanceMatrix, 0, 0);
352
342
  // A pooled mesh arrives carrying the last user's scale; nothing lives here yet.
353
343
  mesh.casterInstanceScale = 0;
354
344
  // Nor the last user's bundle membership: a mesh is only bundled while `WorldCells#bundleIn` says
@@ -388,13 +378,8 @@ export class SharedBatch {
388
378
  this.#setGeometry(this.#geometryFor(this.mesh.instanceMatrix.count));
389
379
  const ranges = this.#lodRangeAttribute();
390
380
  if (ranges === undefined) return;
391
- const values = ranges.array as Float32Array;
392
- for (let at = 0; at < values.length; at += LOD_RANGE_STRIDE) {
393
- values[at] = this.#rangeLevel;
394
- values[at + 1] = this.#rangeLevel;
395
- values[at + 2] = -1;
396
- }
397
- ranges.needsUpdate = true;
381
+ batchRecords.lanes(ranges, LOD_RANGE_STRIDE, [this.#rangeLevel, this.#rangeLevel, -1]);
382
+ batchRecords.upload(ranges, 0, 0);
398
383
  }
399
384
 
400
385
  /** The capacity this batch had when it was parked; see {@link park}. */
@@ -464,76 +449,28 @@ export class SharedBatch {
464
449
  }
465
450
 
466
451
  /**
467
- * The AABB of records `[from, from + count)` of the instance buffer, read from the bytes just
468
- * written rather than from the batch that wrote them, so it is the same numbers the GPU gets. The
469
- * half-extents are `|basis| * half`, which is the box a rotated or stretched instance of the part
470
- * actually covers — a translate-only box would let a scaled trunk through the shadow cull.
452
+ * The part's local box centre and half size, read once per geometry: the input of the record box
453
+ * the engine measures from the bytes as written (see {@link write}). False when the geometry has
454
+ * no readable box, and the package extent stands in for the block's records.
471
455
  */
472
- #boxOf(from: number, count: number): Box3 {
473
- const array = this.mesh.instanceMatrix.array as Float32Array;
456
+ #localBox(): boolean {
474
457
  const geometry = this.mesh.geometry;
475
458
  if (this.#localGeometry !== geometry) {
476
459
  this.#localGeometry = geometry;
477
460
  if (geometry?.boundingBox === null || geometry?.boundingBox === undefined)
478
461
  geometry?.computeBoundingBox?.();
479
462
  const local = geometry?.boundingBox;
480
- // No readable local box means no readable instances either; the package extent is the answer
481
- // that cannot be wrong, and it is what these meshes carried before the blocks were sized.
482
- if (local === undefined || local === null || local.isEmpty()) return this.#bounds;
483
- this.#localCenter.copy(local.getCenter(this.#point));
484
- this.#localHalf.copy(local.getSize(this.#point)).multiplyScalar(0.5);
485
- }
486
- const cx = this.#localCenter.x;
487
- const cy = this.#localCenter.y;
488
- const cz = this.#localCenter.z;
489
- const hx = this.#localHalf.x;
490
- const hy = this.#localHalf.y;
491
- const hz = this.#localHalf.z;
492
- const out = new Box3();
493
- let minX = Number.POSITIVE_INFINITY;
494
- let minY = Number.POSITIVE_INFINITY;
495
- let minZ = Number.POSITIVE_INFINITY;
496
- let maxX = Number.NEGATIVE_INFINITY;
497
- let maxY = Number.NEGATIVE_INFINITY;
498
- let maxZ = Number.NEGATIVE_INFINITY;
499
- let scale = 0;
500
- for (let index = from; index < from + count; index += 1) {
501
- const at = index * 16;
502
- const m0 = array[at] as number;
503
- const m1 = array[at + 1] as number;
504
- const m2 = array[at + 2] as number;
505
- const m4 = array[at + 4] as number;
506
- const m5 = array[at + 5] as number;
507
- const m6 = array[at + 6] as number;
508
- const m8 = array[at + 8] as number;
509
- const m9 = array[at + 9] as number;
510
- const m10 = array[at + 10] as number;
511
- const px = m0 * cx + m4 * cy + m8 * cz + (array[at + 12] as number);
512
- const py = m1 * cx + m5 * cy + m9 * cz + (array[at + 13] as number);
513
- const pz = m2 * cx + m6 * cy + m10 * cz + (array[at + 14] as number);
514
- const ex = Math.abs(m0) * hx + Math.abs(m4) * hy + Math.abs(m8) * hz;
515
- const ey = Math.abs(m1) * hx + Math.abs(m5) * hy + Math.abs(m9) * hz;
516
- const ez = Math.abs(m2) * hx + Math.abs(m6) * hy + Math.abs(m10) * hz;
517
- if (px - ex < minX) minX = px - ex;
518
- if (py - ey < minY) minY = py - ey;
519
- if (pz - ez < minZ) minZ = pz - ez;
520
- if (px + ex > maxX) maxX = px + ex;
521
- if (py + ey > maxY) maxY = py + ey;
522
- if (pz + ez > maxZ) maxZ = pz + ez;
523
- // The largest column of the instance basis: the scale a fern or a trunk is drawn at.
524
- const basis = Math.max(
525
- Math.hypot(m0, m1, m2),
526
- Math.hypot(m4, m5, m6),
527
- Math.hypot(m8, m9, m10),
528
- );
529
- if (basis > scale) scale = basis;
463
+ this.#localReadable = !(local === undefined || local === null || local.isEmpty());
464
+ if (local !== undefined && local !== null && this.#localReadable) {
465
+ this.#localCenter.copy(local.getCenter(this.#point));
466
+ this.#localHalf.copy(local.getSize(this.#point)).multiplyScalar(0.5);
467
+ }
530
468
  }
531
- this.#maxScale = scale;
532
- out.min.set(minX, minY, minZ);
533
- out.max.set(maxX, maxY, maxZ);
534
- return out;
469
+ return this.#localReadable;
535
470
  }
536
471
 
472
+ #localReadable = false;
473
+
537
474
  /** A handle for `count` free records, or `undefined` when the buffer has none and must grow. */
538
475
  allocate(count: number, cluster?: string): number | undefined {
539
476
  const at = this.#take(count);
@@ -575,16 +512,15 @@ export class SharedBatch {
575
512
  old.name,
576
513
  this.#bounds,
577
514
  );
578
- (mesh.instanceMatrix.array as Float32Array).set(old.instanceMatrix.array as Float32Array);
515
+ const records = old.instanceMatrix.count;
516
+ batchRecords.copy(mesh.instanceMatrix, old.instanceMatrix, records * 16);
579
517
  const oldRanges = old.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
580
518
  const nextRanges = mesh.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
581
519
  if (
582
520
  oldRanges instanceof InstancedBufferAttribute &&
583
521
  nextRanges instanceof InstancedBufferAttribute
584
- ) {
585
- (nextRanges.array as Float32Array).set(oldRanges.array as Float32Array);
586
- nextRanges.needsUpdate = true;
587
- }
522
+ )
523
+ batchRecords.copy(nextRanges, oldRanges, records * LOD_RANGE_STRIDE);
588
524
  mesh.castShadow = old.castShadow;
589
525
  mesh.receiveShadow = old.receiveShadow;
590
526
  this.mesh = mesh;
@@ -597,7 +533,6 @@ export class SharedBatch {
597
533
  // of the old array reached the GPU. A narrow range here would leave the new buffer's first
598
534
  // records as the zeros it was created with.
599
535
  this.#touched(0, this.#drawn);
600
- this.#rebound();
601
536
  return old;
602
537
  }
603
538
 
@@ -637,39 +572,59 @@ export class SharedBatch {
637
572
  this.#publish(this.#drawn);
638
573
  return;
639
574
  }
640
- const array = this.mesh.instanceMatrix.array as Float32Array;
641
- const written = batch.writeMatrices(array, start);
642
- const ranges = this.#lodRangeAttribute();
643
- if (ranges !== undefined) {
644
- const values = ranges.array as Float32Array;
645
- if (lodRanges !== undefined)
646
- values.set(lodRanges.subarray(0, written * LOD_RANGE_STRIDE), start * LOD_RANGE_STRIDE);
647
- else
648
- for (let index = 0; index < written; index += 1) {
649
- const at = (start + index) * LOD_RANGE_STRIDE;
650
- values[at] = this.#rangeLevel;
651
- values[at + 1] = this.#rangeLevel;
652
- values[at + 2] = -1;
653
- values[at + 3] = 0;
654
- }
655
- values.fill(0, (start + written) * LOD_RANGE_STRIDE, (start + reserved) * LOD_RANGE_STRIDE);
656
- ranges.needsUpdate = true;
657
- }
658
- array.fill(0, (start + written) * 16, (start + reserved) * 16);
575
+ // The records go to the engine as ops (see `world-cell-records.ts`): the matrices are written
576
+ // straight into the frame's payload, and this batch never holds the buffer's bytes.
577
+ const matrix = this.mesh.instanceMatrix;
578
+ const payloadAt = batchRecords.reserve(batch.count * 16);
579
+ const written = batch.writeMatrices(batchRecords.payload, payloadAt / 16);
580
+ batchRecords.write(matrix, start * 16, written * 16, payloadAt);
581
+ this.#writeRanges(start, written, reserved, lodRanges);
582
+ batchRecords.fill(matrix, (start + written) * 16, (reserved - written) * 16);
659
583
  if (written < reserved) this.#hole(start + written, start + reserved);
660
584
  this.#size.set(segment, written);
661
- // The block's extent, read from the records where they are now, because `#compact` is about to
662
- // move them. The box is keyed by handle, so the move cannot falsify it.
585
+ // The block's extent, measured by the engine from the records where they are now, because
586
+ // `#compact` is about to move them. The box is keyed by handle, so the move cannot falsify it;
587
+ // it lands in `#boxes` when the flush answers (`settleRecords`).
663
588
  if (written > 0) {
664
- this.#boxes.set(segment, this.#boxOf(start, written));
665
- this.#scales.set(segment, this.#maxScale);
589
+ const readable = this.#localBox();
590
+ const index = batchRecords.box(
591
+ matrix,
592
+ start,
593
+ written,
594
+ readable ? this.#localCenter : ZERO,
595
+ readable ? this.#localHalf : ZERO,
596
+ );
597
+ this.#pendingBoxes.set(segment, readable ? index : -1 - index);
666
598
  } else {
667
599
  this.#boxes.delete(segment);
668
600
  this.#scales.delete(segment);
601
+ this.#pendingBoxes.delete(segment);
669
602
  }
670
603
  this.#settle();
671
604
  this.#touched(start, written);
672
- this.#rebound();
605
+ }
606
+
607
+ /** The block's LOD-range column: the published ranges, or each record whole at this batch's level. */
608
+ #writeRanges(start: number, written: number, reserved: number, lodRanges?: Float32Array): void {
609
+ const ranges = this.#lodRangeAttribute();
610
+ if (ranges === undefined) return;
611
+ const at = batchRecords.reserve(written * LOD_RANGE_STRIDE);
612
+ const values = batchRecords.payload;
613
+ if (lodRanges !== undefined) values.set(lodRanges.subarray(0, written * LOD_RANGE_STRIDE), at);
614
+ else
615
+ for (let index = 0; index < written; index += 1) {
616
+ const record = at + index * LOD_RANGE_STRIDE;
617
+ values[record] = this.#rangeLevel;
618
+ values[record + 1] = this.#rangeLevel;
619
+ values[record + 2] = -1;
620
+ values[record + 3] = 0;
621
+ }
622
+ batchRecords.write(ranges, start * LOD_RANGE_STRIDE, written * LOD_RANGE_STRIDE, at);
623
+ batchRecords.fill(
624
+ ranges,
625
+ (start + written) * LOD_RANGE_STRIDE,
626
+ (reserved - written) * LOD_RANGE_STRIDE,
627
+ );
673
628
  }
674
629
 
675
630
  clear(segment: number): void {
@@ -695,16 +650,10 @@ export class SharedBatch {
695
650
  this.#publish(this.#drawn);
696
651
  return;
697
652
  }
698
- (this.mesh.instanceMatrix.array as Float32Array).fill(0, start * 16, (start + size) * 16);
653
+ batchRecords.fill(this.mesh.instanceMatrix, start * 16, size * 16);
699
654
  const ranges = this.#lodRangeAttribute();
700
- if (ranges !== undefined) {
701
- (ranges.array as Float32Array).fill(
702
- 0,
703
- start * LOD_RANGE_STRIDE,
704
- (start + size) * LOD_RANGE_STRIDE,
705
- );
706
- ranges.needsUpdate = true;
707
- }
655
+ if (ranges !== undefined)
656
+ batchRecords.fill(ranges, start * LOD_RANGE_STRIDE, size * LOD_RANGE_STRIDE);
708
657
  this.#hole(start, start + size);
709
658
  this.#settle();
710
659
  // The drawn range, not nothing. `#compact` closed the hole by moving the topmost block down
@@ -713,7 +662,7 @@ export class SharedBatch {
713
662
  this.#touched(0, this.#drawn);
714
663
  this.#boxes.delete(segment);
715
664
  this.#scales.delete(segment);
716
- this.#rebound();
665
+ this.#pendingBoxes.delete(segment);
717
666
  }
718
667
 
719
668
  /** The first free range with room for `count` records, taken out of the list; -1 when there is none. */
@@ -754,7 +703,8 @@ export class SharedBatch {
754
703
  * instead of a `grow`, and the free list is left as the single tail range `[drawn, capacity)`.
755
704
  */
756
705
  #compact(): void {
757
- const array = this.mesh.instanceMatrix.array as Float32Array;
706
+ const matrix = this.mesh.instanceMatrix;
707
+ const ranges = this.#lodRangeAttribute();
758
708
  for (;;) {
759
709
  let drawn = 0;
760
710
  let top = -1;
@@ -772,12 +722,14 @@ export class SharedBatch {
772
722
  const [holeStart, holeEnd] = lowest;
773
723
  const size = this.#size.get(top) ?? 0;
774
724
  if (size <= holeEnd - holeStart) {
775
- array.copyWithin(holeStart * 16, topFrom * 16, drawn * 16);
776
- this.#lodRangeAttribute()?.array.copyWithin(
777
- holeStart * LOD_RANGE_STRIDE,
778
- topFrom * LOD_RANGE_STRIDE,
779
- drawn * LOD_RANGE_STRIDE,
780
- );
725
+ batchRecords.move(matrix, topFrom * 16, holeStart * 16, (drawn - topFrom) * 16);
726
+ if (ranges !== undefined)
727
+ batchRecords.move(
728
+ ranges,
729
+ topFrom * LOD_RANGE_STRIDE,
730
+ holeStart * LOD_RANGE_STRIDE,
731
+ (drawn - topFrom) * LOD_RANGE_STRIDE,
732
+ );
781
733
  this.#start.set(top, holeStart);
782
734
  if (holeEnd - holeStart > size) this.#free[0] = [holeStart + size, holeEnd];
783
735
  else this.#free.shift();
@@ -786,12 +738,14 @@ export class SharedBatch {
786
738
  this.#touched(holeStart, size);
787
739
  } else {
788
740
  const shift = holeEnd - holeStart;
789
- array.copyWithin(holeStart * 16, holeEnd * 16, drawn * 16);
790
- this.#lodRangeAttribute()?.array.copyWithin(
791
- holeStart * LOD_RANGE_STRIDE,
792
- holeEnd * LOD_RANGE_STRIDE,
793
- drawn * LOD_RANGE_STRIDE,
794
- );
741
+ batchRecords.move(matrix, holeEnd * 16, holeStart * 16, (drawn - holeEnd) * 16);
742
+ if (ranges !== undefined)
743
+ batchRecords.move(
744
+ ranges,
745
+ holeEnd * LOD_RANGE_STRIDE,
746
+ holeStart * LOD_RANGE_STRIDE,
747
+ (drawn - holeEnd) * LOD_RANGE_STRIDE,
748
+ );
795
749
  this.#free.shift();
796
750
  for (const [handle, start] of this.#start) {
797
751
  if (start >= holeEnd) this.#start.set(handle, start - shift);
@@ -840,8 +794,8 @@ export class SharedBatch {
840
794
  *
841
795
  * A regroup is a permutation of `[0, drawn)` and there is no in-place order for one: writing the
842
796
  * visible squares to the front necessarily lands on squares whose records have not been read out
843
- * yet, in either direction. So every block is copied into {@link regroupScratch} and the new order
844
- * is copied back — two passes over the drawn range, and only when a square entered or left the
797
+ * yet, in either direction. So the engine's gather op reads every block out before it writes the
798
+ * new order back — two passes over the drawn range, and only when a square entered or left the
845
799
  * window, which on a settled camera is not once a frame.
846
800
  *
847
801
  * Squares keep their relative order within each half, so a residency change regroups in place and
@@ -860,15 +814,7 @@ export class SharedBatch {
860
814
  * stay few and large rather than many and small.
861
815
  */
862
816
  #regroup(visible = this.#visible): void {
863
- const array = this.mesh.instanceMatrix.array as Float32Array;
864
- const rangeAttribute = this.#lodRangeAttribute();
865
- const rangeArray = rangeAttribute?.array as Float32Array | undefined;
866
817
  const squares = this.#squares();
867
- let total = 0;
868
- for (const square of squares) total += sizeOf(square);
869
- const scratch = scratchFor(total * 16);
870
- const rangeScratch =
871
- rangeArray === undefined ? undefined : lodScratchFor(total * LOD_RANGE_STRIDE);
872
818
  // The visible squares first. `filter` is stable, so both halves keep the order the buffer had
873
819
  // them in and a residency change lays out exactly what the last one did.
874
820
  const front = squares.filter((one) => visible?.has(one.cluster) ?? true);
@@ -879,36 +825,27 @@ export class SharedBatch {
879
825
  // identity reorder touches nothing.
880
826
  let movedFrom = -1;
881
827
  let movedTo = 0;
828
+ const blocks: number[] = [];
882
829
  this.#squareSizes.clear();
883
830
  for (const square of [...front, ...back]) {
884
- const union = new Box3();
885
831
  for (const [handle, start, count] of square.blocks) {
886
- scratch.set(array.subarray(start * 16, (start + count) * 16), written * 16);
887
- if (rangeScratch !== undefined && rangeArray !== undefined)
888
- rangeScratch.set(
889
- rangeArray.subarray(start * LOD_RANGE_STRIDE, (start + count) * LOD_RANGE_STRIDE),
890
- written * LOD_RANGE_STRIDE,
891
- );
892
- // Read before it is overwritten: a block written back to its own offset is a record the GPU
893
- // already holds, and is the whole difference between a repack that costs nothing and one
894
- // that re-uploads the key.
832
+ blocks.push(start, count);
833
+ // A block written back to its own offset is a record the GPU already holds, and is the
834
+ // whole difference between a repack that costs nothing and one that re-uploads the key.
895
835
  if (this.#start.get(handle) !== written) {
896
836
  if (movedFrom < 0) movedFrom = written;
897
837
  movedTo = written + count;
898
838
  }
899
839
  this.#start.set(handle, written);
900
- const box = this.#boxes.get(handle);
901
- // A fresh `Box3` is already empty, so the first block's box is the square's and every block
902
- // after it unions into it.
903
- if (box !== undefined) union.union(box);
904
840
  written += count;
905
841
  }
906
842
  this.#squareSizes.set(square.cluster, sizeOf(square));
907
843
  }
908
- array.set(scratch.subarray(0, written * 16));
909
- if (rangeArray !== undefined && rangeScratch !== undefined && rangeAttribute !== undefined) {
910
- rangeArray.set(rangeScratch.subarray(0, written * LOD_RANGE_STRIDE));
911
- rangeAttribute.needsUpdate = true;
844
+ // The permutation itself is the engine's: one gather per buffer, read whole before it is written.
845
+ if (movedFrom >= 0) {
846
+ batchRecords.gather(this.mesh.instanceMatrix, 16, blocks);
847
+ const ranges = this.#lodRangeAttribute();
848
+ if (ranges !== undefined) batchRecords.gather(ranges, LOD_RANGE_STRIDE, blocks);
912
849
  }
913
850
  this.#drawn = written;
914
851
  const capacity = this.mesh.instanceMatrix.count;
@@ -1060,22 +997,15 @@ export class SharedBatch {
1060
997
  // A dressed batch's records were never in this attribute, so there is nothing to upload and
1061
998
  // nothing to put back in charge of culling: the dispatch decided what it drew.
1062
999
  if (this.gpu !== undefined) return;
1063
- const matrix = this.mesh.instanceMatrix;
1064
1000
  // A record is 16 array elements, and that is the unit `updateRanges` is in: three reads them
1065
1001
  // as element offsets into `array`, not as bytes.
1066
1002
  const drawn = this.#drawn * 16;
1067
- const low0 = from * 16;
1068
- const high0 = (from + count) * 16;
1069
- // The pending span is ours, and it lasts one update. Three's WebGPU path uploads through the
1070
- // interleaved buffer it derives from `instanceMatrix.array` and only that buffer's ranges are
1071
- // cleared after the write, so the ranges on `instanceMatrix` are never consumed: they were
1072
- // unioned in here forever, and after one wide write every later write re-uploaded the whole
1073
- // drawn range. The epoch moves once per `update()`, and the render at the end of an update is
1074
- // what consumes the span, so a fresh epoch is a fresh span.
1075
- let low = low0;
1076
- let high = high0;
1077
- const epoch = currentWriteEpoch();
1078
- if (this.#pendingEpoch === epoch) {
1003
+ let low = from * 16;
1004
+ let high = (from + count) * 16;
1005
+ // The pending span is ours, and it lasts until the flush at the end of this `update`, which is
1006
+ // what hands it to the engine: a frame that touches a mesh from several directions still
1007
+ // uploads one range.
1008
+ if (this.#pendingMatrix !== undefined) {
1079
1009
  if (this.#pendingLow < low) low = this.#pendingLow;
1080
1010
  if (this.#pendingHigh > high) high = this.#pendingHigh;
1081
1011
  }
@@ -1085,26 +1015,58 @@ export class SharedBatch {
1085
1015
  }
1086
1016
  this.#pendingLow = low;
1087
1017
  this.#pendingHigh = high;
1088
- this.#pendingEpoch = epoch;
1089
- matrix.clearUpdateRanges();
1090
- if (high > low) matrix.addUpdateRange(low, high - low);
1091
- matrix.needsUpdate = true;
1092
- const ranges = this.#lodRangeAttribute();
1093
- if (ranges !== undefined) {
1094
- ranges.clearUpdateRanges();
1095
- if (high > low)
1096
- ranges.addUpdateRange(
1097
- (low / 16) * LOD_RANGE_STRIDE,
1098
- ((high - low) / 16) * LOD_RANGE_STRIDE,
1099
- );
1100
- ranges.needsUpdate = true;
1101
- }
1018
+ this.#pendingMatrix = this.mesh.instanceMatrix;
1019
+ this.#pendingRanges = this.#lodRangeAttribute();
1020
+ batchRecords.touch(this);
1102
1021
  this.#publish(this.#drawn);
1103
- // Records are real, so the bounds are the ones `#rebound` just wrote and the mesh goes back to
1104
- // being culled.
1022
+ // Records are real, so the bounds `settleRecords` publishes are the ones to cull by.
1105
1023
  this.mesh.frustumCulled = true;
1106
1024
  }
1107
1025
 
1026
+ /** The flush asks for this frame's upload span, one range per buffer; see {@link #touched}. */
1027
+ uploadRecords(): void {
1028
+ const matrix = this.#pendingMatrix;
1029
+ if (matrix === undefined) return;
1030
+ const low = this.#pendingLow;
1031
+ const high = this.#pendingHigh;
1032
+ batchRecords.upload(matrix, low, high - low);
1033
+ if (this.#pendingRanges !== undefined)
1034
+ batchRecords.upload(
1035
+ this.#pendingRanges,
1036
+ (low / 16) * LOD_RANGE_STRIDE,
1037
+ ((high - low) / 16) * LOD_RANGE_STRIDE,
1038
+ );
1039
+ this.#pendingMatrix = undefined;
1040
+ this.#pendingRanges = undefined;
1041
+ }
1042
+
1043
+ /**
1044
+ * The flush answered: each block written this frame gets the box the engine measured, and the
1045
+ * mesh's bounds are published once from all of them.
1046
+ */
1047
+ settleRecords(boxes: ArrayLike<number>): void {
1048
+ for (const [segment, encoded] of this.#pendingBoxes) {
1049
+ // A block cleared after its write in the same frame has no box left to keep.
1050
+ if (!this.#start.has(segment)) continue;
1051
+ const at = encoded < 0 ? -1 - encoded : encoded;
1052
+ const box =
1053
+ encoded < 0
1054
+ ? this.#bounds
1055
+ : new Box3(
1056
+ new Vector3(boxes[at] as number, boxes[at + 1] as number, boxes[at + 2] as number),
1057
+ new Vector3(
1058
+ boxes[at + 3] as number,
1059
+ boxes[at + 4] as number,
1060
+ boxes[at + 5] as number,
1061
+ ),
1062
+ );
1063
+ this.#boxes.set(segment, box);
1064
+ this.#scales.set(segment, boxes[at + 6] as number);
1065
+ }
1066
+ this.#pendingBoxes.clear();
1067
+ this.#rebound();
1068
+ }
1069
+
1108
1070
  /**
1109
1071
  * The one place `mesh.count` is written, so a batch that would draw nothing is not submitted.
1110
1072
  *
@@ -11,9 +11,10 @@ import {
11
11
  import { markEngineRenderHook } from "./engine-render-hook.js";
12
12
  import { mergeByMaterial } from "./merge-parts.js";
13
13
  import {
14
- conservativeViewDepth,
14
+ LOD_NEAR_PLANE,
15
15
  isLodJoinProxy,
16
16
  lodChainOf,
17
+ selectLodFor,
17
18
  setModelLodLayers,
18
19
  } from "./model-lod.js";
19
20
  import { displacesVertices } from "./projection-plan.js";
@@ -777,12 +778,7 @@ export class CellChunks {
777
778
  const view =
778
779
  camera === undefined
779
780
  ? undefined
780
- : conservativeViewDepth(
781
- camera,
782
- sphere.center,
783
- sphere.radius,
784
- Reflect.get(camera, "near") ?? 0.1,
785
- );
781
+ : selectLodFor(camera, sphere, Reflect.get(camera, "near") ?? LOD_NEAR_PLANE);
786
782
  const height = renderer?.domElement.height;
787
783
  const selected = state.selector.select({
788
784
  sourceReady: cellLoaded(cell),