@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
@@ -94,6 +94,7 @@ interface IImpostorRecord {
94
94
  readonly atlas: WorldImpostorAtlas;
95
95
  readonly center: Vector3;
96
96
  readonly radius: number;
97
+ readonly halfExtents: Vector3;
97
98
  readonly bytes: number;
98
99
  users: number;
99
100
  }
@@ -601,9 +602,9 @@ export class CellImpostors {
601
602
  const staged: IImpostorPart[] = impostorParts(parts);
602
603
  try {
603
604
  this.#baker.begin(asset.id, staged, { pixels: IMPOSTOR_FRAME_PIXELS });
604
- } catch {
605
+ } catch (error) {
605
606
  this.#host.addFailure();
606
- this.#reportImpostor(asset, "begin-failed");
607
+ this.#reportImpostor(asset, "begin-failed", error);
607
608
  continue;
608
609
  }
609
610
  this.#impostorReservedBytes = IMPOSTOR_ATLAS_BYTES;
@@ -623,11 +624,11 @@ export class CellImpostors {
623
624
  atlas = this.#baker.step(raw);
624
625
  if (atlas !== undefined || this.#baker.pending?.view === view) break;
625
626
  }
626
- } catch {
627
+ } catch (error) {
627
628
  this.#host.addFailure();
628
629
  this.#impostorBaking = undefined;
629
630
  this.#impostorReservedBytes = 0;
630
- this.#reportImpostor(baking, "bake-failed");
631
+ this.#reportImpostor(baking, "bake-failed", error);
631
632
  return;
632
633
  }
633
634
  if (atlas === undefined) return;
@@ -686,6 +687,7 @@ export class CellImpostors {
686
687
  atlas,
687
688
  bytes: atlas.bytes,
688
689
  center: bounds.center,
690
+ halfExtents: bounds.halfExtents,
689
691
  key,
690
692
  radius: bounds.radius,
691
693
  users: 0,
@@ -722,12 +724,13 @@ export class CellImpostors {
722
724
  alphaTest: source.alphaTest,
723
725
  atlas: record.atlas,
724
726
  center: record.center,
727
+ halfExtents: record.halfExtents,
725
728
  radius: record.radius,
726
729
  source: source.source,
727
730
  });
728
- } catch {
731
+ } catch (error) {
729
732
  this.#host.addFailure();
730
- this.#reportImpostor(asset, "surface-failed");
733
+ this.#reportImpostor(asset, "surface-failed", error);
731
734
  return;
732
735
  }
733
736
  // The terminal gate is stored as the BASE-sphere projected distance — the distance at which the
@@ -952,6 +955,7 @@ export class CellImpostors {
952
955
  atlas: cohort.record.atlas,
953
956
  center: cohort.record.center,
954
957
  cull: true,
958
+ halfExtents: cohort.record.halfExtents,
955
959
  radius: cohort.record.radius,
956
960
  source: cohort.source,
957
961
  });
@@ -1097,6 +1101,12 @@ export class CellImpostors {
1097
1101
  const mesh = new InstancedMesh(surface.geometry, surface.material, capacity);
1098
1102
  mesh.count = capacity;
1099
1103
  mesh.frustumCulled = false;
1104
+ // Every nearer draw occludes the far tier, so it draws after them and depth rejects its hidden
1105
+ // quads. three sorts opaques front to back anyway; the owned engine orders a pass's rows by state
1106
+ // with no depth prepass, where drawn first the far quads shaded every pixel the trees then covered
1107
+ // (UE 5.8.3: Engine/Source/Runtime/Renderer/Private/BasePassRendering.cpp:333-341 orders by
1108
+ // occlusion class for the same reason when there is no early-Z pass).
1109
+ mesh.renderOrder = 1;
1100
1110
  // Three's default usage uploads by version; grow/write/zero announce every matrix change through
1101
1111
  // needsUpdate. DynamicDrawUsage would upload the same whole-map buffer on every settled draw.
1102
1112
  mesh.name = `tn-far:${assetId}`;
@@ -1421,7 +1431,8 @@ export class CellImpostors {
1421
1431
  * `TN_WORLD_IMPOSTOR`, one bounded line per asset: its terminal level, the metres it takes over at,
1422
1432
  * the views the atlas holds, its GPU bytes, and — when the world can name it — why it did not land.
1423
1433
  */
1424
- #reportImpostor(asset: IAssetState, reason: string): void {
1434
+ /** One line per asset; a failure carries its error, so the cause is on the line and not swallowed. */
1435
+ #reportImpostor(asset: IAssetState, reason: string, error?: unknown): void {
1425
1436
  if (this.#impostorReported.has(asset.id)) return;
1426
1437
  this.#impostorReported.add(asset.id);
1427
1438
  const impostor = asset.impostor;
@@ -1430,7 +1441,8 @@ export class CellImpostors {
1430
1441
  `${WORLD_IMPOSTOR_MARKER} asset=${asset.id} level=${String(asset.levels.length - 1)} ` +
1431
1442
  `switch=${(asset.distances.at(-1) ?? 0).toFixed(1)} ` +
1432
1443
  `views=${String(atlas === undefined ? 0 : IMPOSTOR_VIEWS)} ` +
1433
- `bytes=${String(atlas?.bytes ?? 0)} reason=${reason}`,
1444
+ `bytes=${String(atlas?.bytes ?? 0)} reason=${reason}` +
1445
+ `${error === undefined ? "" : ` error=${error instanceof Error ? error.message : String(error)}`}`,
1434
1446
  );
1435
1447
  }
1436
1448
  }
@@ -1,3 +1,4 @@
1
+ import { readLaunchValue } from "./debug.js";
1
2
  import { INSTANCED_LOD_MAX_PIXEL_ERROR } from "./instanced-batch-lod.js";
2
3
  import type { IWorldCellsLoadOptions } from "./world-cell-data.js";
3
4
  import type { IWorldCell, IWorldPackage } from "./world-package.js";
@@ -134,20 +135,7 @@ export const DEFAULT_MAIN_GPU_SHARE = 0.5;
134
135
  * be parsed by the caller rather than rounded here.
135
136
  */
136
137
  function launchValue(parameter: string, flag: string, globalName: string): string | undefined {
137
- const host = globalThis as { process?: { env?: Record<string, unknown> } } & Record<
138
- string,
139
- unknown
140
- >;
141
- const env = host.process?.env?.[flag];
142
- if (typeof env === "string" && env !== "") return env;
143
- const query = globalThis.location?.search;
144
- if (typeof query === "string") {
145
- const value = new URLSearchParams(query).get(parameter);
146
- if (value !== null) return value;
147
- }
148
- const global = host[globalName];
149
- if (typeof global === "number") return String(global);
150
- return typeof global === "string" ? global : undefined;
138
+ return readLaunchValue({ environment: flag, global: globalName, query: parameter });
151
139
  }
152
140
 
153
141
  /**
@@ -1,4 +1,4 @@
1
- import { Box3, Matrix4, Quaternion, Vector3 } from "three";
1
+ import { Box3, Matrix4, Object3D, Quaternion, Vector3 } from "three";
2
2
  import { InstancedBatch } from "./instanced-batch.js";
3
3
  import { biasedLodDistance } from "./model-lod.js";
4
4
  import {
@@ -15,6 +15,14 @@ import {
15
15
  } from "./world-cell-impostors.js";
16
16
  import type { IAssetState } from "./world-cell-models.js";
17
17
  import { LEVEL_REFILTER_STEP_METRES } from "./world-cell-options.js";
18
+ import { placedBox } from "./world-cell-records.js";
19
+ import {
20
+ STALE_ENTRY,
21
+ STALE_HEADER,
22
+ STALE_QUERY,
23
+ patchRows,
24
+ staleRows,
25
+ } from "./world-cell-stale.js";
18
26
  import { levelAtGates } from "./world-gpu-scene.js";
19
27
  import {
20
28
  type IWorldAsset,
@@ -60,6 +68,24 @@ export function newBoxes(batches: readonly InstancedBatch[][]): Box3[][] {
60
68
  return boxes;
61
69
  }
62
70
 
71
+ /** One more block in a `patchRows` plan, merged into the run before it when the two are contiguous. */
72
+ function extendPlan(plan: number[], source: number, count: number): void {
73
+ const last = plan.length - 2;
74
+ const runSource = plan[last];
75
+ const runCount = plan[last + 1] as number;
76
+ const joins =
77
+ runSource !== undefined &&
78
+ (source === -1 ? runSource === -1 : runSource >= 0 && runSource + runCount === source);
79
+ if (joins) plan[last + 1] = runCount + count;
80
+ else plan.push(source, count);
81
+ }
82
+
83
+ /** The owned engine's stale scan (`bindings_scene.cpp`); see `world-cell-stale.ts`. */
84
+ interface IStaleEngine {
85
+ __tnStaleRows?: (blocks: Float64Array, plan: Float64Array) => number;
86
+ __tnStaleEntries?: (gates: Float64Array, query: Float64Array) => ArrayLike<number>;
87
+ }
88
+
63
89
  /** What the placement build asks its world for. Every read is the world's own state, not a copy. */
64
90
  export interface ICellPlacementsHost {
65
91
  extent(): { readonly cellSize: number; readonly minX: number; readonly minZ: number };
@@ -111,13 +137,26 @@ export class CellPlacements {
111
137
  readonly #placementRanges: Uint8Array | undefined;
112
138
  /** Every distinct gate distance the world's assets have, ascending; see `noteGate`. */
113
139
  readonly #gates: number[] = [];
114
- /** The reused hit list and the reused per-cell seen set; see `#staleIn`. */
140
+ /** The reused hit list; see `#collectStale`. */
115
141
  readonly #stale: Array<{
116
142
  cell: IResidentCell;
117
143
  distance: number;
118
144
  id: string;
119
145
  }> = [];
120
- readonly #staleSeen = new Set<string>();
146
+ /** Per cell, its block of the stale scan's slab, dropped when the cell's batches change. */
147
+ readonly #rows = new WeakMap<IResidentCell, { rows: Float64Array; batches: number }>();
148
+ /** The resident cells' blocks laid end to end, and the cells in block order; see `#collectStale`. */
149
+ #slab = new Float64Array(0);
150
+ #slabCells: IResidentCell[] = [];
151
+ /** Where each cell's block sits in the slab the last pack sent; an unchanged block is not sent again. */
152
+ #slabAt = new Map<IResidentCell, { at: number; rows: Float64Array }>();
153
+ #slabEpoch = -1;
154
+ #slabStale = true;
155
+ /** Asset ids by the index the slab names them with; the index only ever grows. */
156
+ readonly #assetIds: string[] = [];
157
+ readonly #assetIndex = new Map<string, number>();
158
+ /** The owned engine's `__tnStaleEntries` host; on upstream three it has no such method. */
159
+ readonly #engine = new Object3D() as Object3D & IStaleEngine;
121
160
  /** Stale cell-assets the passes found, cumulative; see `IWorldCellsStats.refilterEntries`. */
122
161
  #staleEntries = 0;
123
162
  /** Refilter passes run, whether or not they queued anything; see `IWorldCellsStats.refilters`. */
@@ -207,9 +246,7 @@ export class CellPlacements {
207
246
 
208
247
  /** Borrowed scratch box: consume its transformed volume before the next bounds query. */
209
248
  #boundsAt(bounds: IWorldAsset["bounds"], matrix: Matrix4): Box3 {
210
- this.#recordBounds.min.fromArray(bounds.min);
211
- this.#recordBounds.max.fromArray(bounds.max);
212
- return this.#recordBounds.applyMatrix4(matrix);
249
+ return placedBox(this.#recordBounds, bounds.min, bounds.max, matrix);
213
250
  }
214
251
 
215
252
  /**
@@ -433,9 +470,9 @@ export class CellPlacements {
433
470
  z: centre.z,
434
471
  });
435
472
  }
436
- // Authored bounds include model-part offsets; apply the whole placement transform so
437
- // rotated, mirrored and off-centre casters cannot fall outside visibility/shadow regions.
438
- this.#boundsAt(bounds, this.#matrix);
473
+ // `#recordBounds` still holds `placedBox`: the authored bounds (model-part offsets included)
474
+ // under the whole placement transform, so rotated, mirrored and off-centre casters cannot fall
475
+ // outside visibility/shadow regions. Measured once per placement, not once per level.
439
476
  const parts = asset.levels[level] as readonly IAssetPart[];
440
477
  const levelBatches = job.batches?.[level] as InstancedBatch[];
441
478
  const levelBoxes = job.boxes?.[level] as Box3[] | undefined;
@@ -470,6 +507,13 @@ export class CellPlacements {
470
507
  const [near, far] = this.#span(cell, filterX, filterZ);
471
508
  if (near < cell.filterNear) cell.filterNear = near;
472
509
  if (far > cell.filterFar) cell.filterFar = far;
510
+ this.cellBatchesChanged(cell);
511
+ }
512
+
513
+ /** The cell's batches or bracket changed, so its block of the stale scan is rebuilt. */
514
+ cellBatchesChanged(cell: IResidentCell): void {
515
+ this.#rows.delete(cell);
516
+ this.#slabStale = true;
473
517
  }
474
518
 
475
519
  buildOne(job: IBuildJob, batches: readonly InstancedBatch[][]): void {
@@ -541,80 +585,6 @@ export class CellPlacements {
541
585
  ];
542
586
  }
543
587
 
544
- /**
545
- * One entry per asset of `cell` the follow point has moved a gate of, nearest placement first.
546
- *
547
- * The cell's own bracket is the caller's: it was derived once for the cell, and every batch of a
548
- * cell is measured against the same rectangle, so deriving it per batch was the same four
549
- * `Math.max` and two `Math.hypot` calls as many times as the cell had batches. What is left here is
550
- * per batch: one moved-point test and, for a batch that moved, its own bracket.
551
- *
552
- * Nothing is allocated to find them: the entries go into one reused array, the per-cell "already
553
- * seen" set into another, and a pass that crossed no gate anywhere pushes nothing at all.
554
- */
555
- #staleIn(cell: IResidentCell, x: number, z: number, near: number, far: number): void {
556
- const seen = this.#staleSeen;
557
- seen.clear();
558
- const eye = this.#host.eye();
559
- const [eyeNear, eyeFar] = this.#span(cell, eye.x, eye.z);
560
- for (const entry of cell.batches) {
561
- const reach = this.#reachRanges.get(cell.cell)?.get(entry.asset);
562
- if ((entry.threshold === undefined && reach === undefined) || seen.has(entry.asset)) continue;
563
- // Deferred runs of one asset can start at different camera snapshots. Only deduplicate
564
- // after one entry proves the asset stale: an earlier matching run cannot settle the others.
565
- const step = (entry.threshold ?? 6) / 8;
566
- if (
567
- Math.hypot(
568
- x - entry.lastFilterX,
569
- this.followY() - entry.lastFilterY,
570
- z - entry.lastFilterZ,
571
- ) <= step &&
572
- Math.hypot(eye.x - entry.lastLodX, eye.y - entry.lastLodY, eye.z - entry.lastLodZ) <= step
573
- )
574
- continue;
575
- const asset = this.#host.asset(entry.asset);
576
- if (asset === undefined) continue;
577
- // GPU dispatch handles maxDistance and LOD gates; placementReach remains a CPU boundary.
578
- const gates = this.#host.gpuOn() ? [] : asset.gates;
579
- // Gates bracket the LOD eye's distances, reach the follow point's: see `#addPlacements`.
580
- const [builtNear, builtFar] = this.#span(cell, entry.lastLodX, entry.lastLodZ);
581
- let low = Math.min(eyeNear, builtNear);
582
- // Ends included, so a placement exactly on a gate is one of the reasons to rebuild.
583
- let high = Math.max(eyeFar, builtFar);
584
- let reachCrossed = false;
585
- if (reach !== undefined) {
586
- const vertical = (y: number): [number, number] => [
587
- Math.max(reach.minY - y, y - reach.maxY, 0),
588
- Math.max(Math.abs(y - reach.minY), Math.abs(y - reach.maxY)),
589
- ];
590
- const eyeNow = vertical(eye.y);
591
- const eyeBefore = vertical(entry.lastLodY);
592
- low = Math.min(Math.hypot(eyeNear, eyeNow[0]), Math.hypot(builtNear, eyeBefore[0]));
593
- high = Math.max(Math.hypot(eyeFar, eyeNow[1]), Math.hypot(builtFar, eyeBefore[1]));
594
- const [reachBuiltNear, reachBuiltFar] = this.#span(
595
- cell,
596
- entry.lastFilterX,
597
- entry.lastFilterZ,
598
- );
599
- const current = vertical(this.followY());
600
- const previous = vertical(entry.lastFilterY);
601
- const reachLow = Math.min(
602
- Math.hypot(near, current[0]),
603
- Math.hypot(reachBuiltNear, previous[0]),
604
- );
605
- const reachHigh = Math.max(
606
- Math.hypot(far, current[1]),
607
- Math.hypot(reachBuiltFar, previous[1]),
608
- );
609
- reachCrossed = reach.min <= reachHigh && reach.max >= reachLow;
610
- }
611
- if (!reachCrossed && !gates.some((gate) => gate >= low && gate <= high)) continue;
612
- seen.add(entry.asset);
613
- this.#stale.push({ cell, distance: eyeNear, id: entry.asset });
614
- this.#staleEntries += 1;
615
- }
616
- }
617
-
618
588
  /**
619
589
  * Record that one more gate distance exists, keeping the world's list ascending so
620
590
  * {@link crossesGate} can binary search it. A gate is never withdrawn: an asset whose ring left
@@ -681,14 +651,148 @@ export class CellPlacements {
681
651
  * which the follow point has not yet reached anything that switches.
682
652
  */
683
653
  #collectStale(x: number, z: number): void {
654
+ const epoch = this.#host.residencyEpoch();
655
+ if (this.#slabStale || this.#slabEpoch !== epoch) this.#packSlab(epoch);
656
+ const eye = this.#host.eye();
657
+ const query = new Float64Array(STALE_QUERY + this.#gates.length);
658
+ query.set([
659
+ x,
660
+ this.followY(),
661
+ z,
662
+ eye.x,
663
+ eye.y,
664
+ eye.z,
665
+ this.#host.gpuOn() ? 1 : 0,
666
+ this.#gates.length,
667
+ ]);
668
+ query.set(this.#gates, STALE_QUERY);
669
+ const gates = this.#gateTable();
670
+ const found =
671
+ typeof this.#engine.__tnStaleEntries === "function"
672
+ ? this.#engine.__tnStaleEntries(gates, query)
673
+ : staleRows(this.#slab, gates, query);
674
+ for (let at = 0; at < found.length; at += 3) {
675
+ this.#stale.push({
676
+ cell: this.#slabCells[found[at] as number] as IResidentCell,
677
+ distance: found[at + 2] as number,
678
+ id: this.#assetIds[found[at + 1] as number] as string,
679
+ });
680
+ this.#staleEntries += 1;
681
+ }
682
+ }
683
+
684
+ /**
685
+ * The resident cells' blocks end to end; only a changed cell builds its block again, and only the
686
+ * changed blocks are sent: an unchanged one is a `[source, count]` run of the slab already held
687
+ * (see `patchRows`).
688
+ */
689
+ #packSlab(epoch: number): void {
690
+ const plan: number[] = [];
691
+ const changed: Float64Array[] = [];
692
+ const cells: IResidentCell[] = [];
693
+ const placed = new Map<IResidentCell, { at: number; rows: Float64Array }>();
694
+ let length = 0;
695
+ let sent = 0;
684
696
  for (const cell of this.#host.resident()) {
685
- // Gates are measured from the LOD eye, and `filterNear`/`filterFar` hold the eyes built from.
686
- const [eyeNear, eyeFar] = this.#span(cell, this.#host.eye().x, this.#host.eye().z);
687
- const low = eyeNear < cell.filterNear ? eyeNear : cell.filterNear;
688
- const high = eyeFar > cell.filterFar ? eyeFar : cell.filterFar;
689
- if (!this.#reachRanges.has(cell.cell) && !crossesGate(this.#gates, low, high)) continue;
690
- const [near, far] = this.#span(cell, x, z);
691
- this.#staleIn(cell, x, z, near, far);
697
+ const rows = this.#rowsOf(cell);
698
+ const held = this.#slabAt.get(cell);
699
+ const source = held !== undefined && held.rows === rows ? held.at : -1;
700
+ extendPlan(plan, source, rows.length);
701
+ if (source === -1) {
702
+ changed.push(rows);
703
+ sent += rows.length;
704
+ }
705
+ placed.set(cell, { at: length, rows });
706
+ cells.push(cell);
707
+ length += rows.length;
708
+ }
709
+ const blocks = new Float64Array(sent);
710
+ let at = 0;
711
+ for (const block of changed) {
712
+ blocks.set(block, at);
713
+ at += block.length;
714
+ }
715
+ if (typeof this.#engine.__tnStaleEntries === "function") {
716
+ // A scan without its rows would read an empty slab and find nothing stale, silently.
717
+ if (typeof this.#engine.__tnStaleRows !== "function")
718
+ throw new Error("TN_WORLD_STALE: the engine has __tnStaleEntries but no __tnStaleRows");
719
+ this.#engine.__tnStaleRows(blocks, Float64Array.from(plan));
720
+ } else this.#slab = patchRows(this.#slab, blocks, plan);
721
+ this.#slabAt = placed;
722
+ this.#slabCells = cells;
723
+ this.#slabEpoch = epoch;
724
+ this.#slabStale = false;
725
+ }
726
+
727
+ /** One cell's block: its rectangle and bracket, then each batch entry's filter state. */
728
+ #rowsOf(cell: IResidentCell): Float64Array {
729
+ const cached = this.#rows.get(cell);
730
+ if (cached !== undefined && cached.batches === cell.batches.length) return cached.rows;
731
+ this.#grid ??= this.#host.extent();
732
+ const { cellSize, minX, minZ } = this.#grid;
733
+ const reach = this.#reachRanges.get(cell.cell);
734
+ const rows = new Float64Array(STALE_HEADER + cell.batches.length * STALE_ENTRY);
735
+ rows.set([
736
+ minX + cell.x * cellSize,
737
+ minZ + cell.z * cellSize,
738
+ cellSize,
739
+ cell.filterNear,
740
+ cell.filterFar,
741
+ reach === undefined ? 0 : 1,
742
+ cell.batches.length,
743
+ 0,
744
+ ]);
745
+ let at = STALE_HEADER;
746
+ for (const entry of cell.batches) {
747
+ const range = reach?.get(entry.asset);
748
+ rows.set(
749
+ [
750
+ this.#assetSlot(entry.asset),
751
+ entry.lastFilterX,
752
+ entry.lastFilterY,
753
+ entry.lastFilterZ,
754
+ entry.lastLodX,
755
+ entry.lastLodY,
756
+ entry.lastLodZ,
757
+ entry.threshold ?? Number.NaN,
758
+ range?.min ?? Number.NaN,
759
+ range?.max ?? Number.NaN,
760
+ range?.minY ?? Number.NaN,
761
+ range?.maxY ?? Number.NaN,
762
+ ],
763
+ at,
764
+ );
765
+ at += STALE_ENTRY;
766
+ }
767
+ this.#rows.set(cell, { rows, batches: cell.batches.length });
768
+ return rows;
769
+ }
770
+
771
+ #assetSlot(id: string): number {
772
+ let slot = this.#assetIndex.get(id);
773
+ if (slot === undefined) {
774
+ slot = this.#assetIds.length;
775
+ this.#assetIds.push(id);
776
+ this.#assetIndex.set(id, slot);
777
+ }
778
+ return slot;
779
+ }
780
+
781
+ /** Each slab asset's gates, read live: `[count, [at, count]..., values]`, `at` -1 for a gone asset. */
782
+ #gateTable(): Float64Array {
783
+ const ids = this.#assetIds;
784
+ let values = 0;
785
+ for (const id of ids) values += this.#host.asset(id)?.gates.length ?? 0;
786
+ const table = new Float64Array(1 + ids.length * 2 + values);
787
+ table[0] = ids.length;
788
+ let at = 1 + ids.length * 2;
789
+ for (const [slot, id] of ids.entries()) {
790
+ const gates = this.#host.asset(id)?.gates;
791
+ table[1 + slot * 2] = gates === undefined ? -1 : at;
792
+ table[2 + slot * 2] = gates?.length ?? 0;
793
+ if (gates !== undefined) table.set(gates, at);
794
+ at += gates?.length ?? 0;
692
795
  }
796
+ return table;
693
797
  }
694
798
  }
@@ -1,4 +1,12 @@
1
- import { type Box3, type Camera, Frustum, InstancedMesh, Matrix4, type Object3D } from "three";
1
+ import {
2
+ type Box3,
3
+ type Camera,
4
+ Frustum,
5
+ InstancedMesh,
6
+ type Material,
7
+ Matrix4,
8
+ type Object3D,
9
+ } from "three";
2
10
  import { markEngineRenderHook } from "./engine-render-hook.js";
3
11
  import type { IRendererLike } from "./renderer.js";
4
12
  import { SharedBatch } from "./world-cell-batches.js";
@@ -38,6 +46,8 @@ export interface ICellPrewarmHost {
38
46
  part: number,
39
47
  fallback: IBatchShape,
40
48
  ): IBatchShape;
49
+ /** The material the swap draws this level and part with; see `CellGpuDress#lodSurface`. */
50
+ lodSurface(asset: string, level: number, part: number, source: Material): Material;
41
51
  }
42
52
 
43
53
  /**
@@ -72,7 +82,10 @@ export const WIDE_CLUSTER = "*";
72
82
  export class CellPrewarm {
73
83
  readonly #drawBatches = new WeakMap<InstancedMesh, SharedBatch>();
74
84
  readonly #submitted = new WeakSet<InstancedMesh>();
75
- readonly #drawBorrows = new Map<InstancedMesh, { before: unknown; release(): void }>();
85
+ readonly #drawBorrows = new Map<
86
+ InstancedMesh,
87
+ { before: unknown; release(): void; settle(): void }
88
+ >();
76
89
 
77
90
  /** Strict CPU submission gate; idle legacy prewarm settlement is not a submitted draw. */
78
91
  pendingCpuDrawsInView(root: Object3D, camera: Camera, renderer?: IRendererLike): number {
@@ -96,6 +109,9 @@ export class CellPrewarm {
96
109
  !frustum.intersectsObject(object)
97
110
  )
98
111
  return;
112
+ // An engine that calls onBeforeRender alone (the owned engine, for a main draw it submits) counts
113
+ // the frame once render() returns: the next query settles it.
114
+ this.#drawBorrows.get(object)?.settle();
99
115
  if (this.#submitted.has(object)) return;
100
116
  pending++;
101
117
  active.add(object);
@@ -107,6 +123,12 @@ export class CellPrewarm {
107
123
  const hadBefore = Object.hasOwn(object, "onBeforeRender");
108
124
  const hadAfter = Object.hasOwn(object, "onAfterRender");
109
125
  let before: number | undefined;
126
+ // Renders finished when the hook ran: three's `info.render.calls` and the facade's both only grow.
127
+ let hookedAt: number | undefined;
128
+ const renders = (): number | undefined => {
129
+ const value = (renderer.info as { render?: { calls?: number } }).render?.calls;
130
+ return Number.isSafeInteger(value) ? value : undefined;
131
+ };
110
132
  const calls = (): number | undefined => {
111
133
  const value = (renderer.info as { render?: { drawCalls?: number; calls?: number } }).render;
112
134
  const count = value?.drawCalls ?? value?.calls;
@@ -125,6 +147,7 @@ export class CellPrewarm {
125
147
  before = undefined;
126
148
  ownBefore.apply(this, args);
127
149
  before = args[2] === camera && renderer.compiling !== true ? calls() : undefined;
150
+ hookedAt = before === undefined ? undefined : renders();
128
151
  };
129
152
  const afterHook: typeof object.onAfterRender = function (this: InstancedMesh, ...args) {
130
153
  const after = calls();
@@ -140,13 +163,23 @@ export class CellPrewarm {
140
163
  release();
141
164
  }
142
165
  before = undefined;
166
+ hookedAt = undefined;
143
167
  ownAfter.apply(this, args);
144
168
  };
145
169
  markEngineRenderHook(beforeHook);
146
170
  markEngineRenderHook(afterHook);
147
171
  object.onBeforeRender = beforeHook;
148
172
  object.onAfterRender = afterHook;
149
- this.#drawBorrows.set(object, { before: beforeHook, release });
173
+ // The owned engine calls onBeforeRender alone, and only for a main draw it submits after its cull,
174
+ // so the hook plus a render that finished after it is the draw. three's after-hook clears `hookedAt`.
175
+ const settle = () => {
176
+ const now = hookedAt === undefined ? undefined : renders();
177
+ if (object.count > 0 && now !== undefined && hookedAt !== undefined && now > hookedAt) {
178
+ submitted.add(object);
179
+ release();
180
+ }
181
+ };
182
+ this.#drawBorrows.set(object, { before: beforeHook, release, settle });
150
183
  });
151
184
  for (const [mesh, borrow] of this.#drawBorrows) if (!active.has(mesh)) borrow.release();
152
185
  return pending;
@@ -303,9 +336,11 @@ export class CellPrewarm {
303
336
  this.#host.hasRetired(entry.key)
304
337
  )
305
338
  return;
339
+ // Minted with the material the swap draws (`shapeFor`): the raw part material builds a program no
340
+ // placement ever draws, and the LOD-masked one is then built by the first placement, after the reveal.
306
341
  const shared = new SharedBatch(
307
342
  entry.geometry,
308
- entry.material,
343
+ this.#host.lodSurface(entry.asset, entry.level, entry.part, entry.material),
309
344
  this.#host.runMax(entry.asset) ?? 1,
310
345
  this.#host.residentCells() + 1,
311
346
  entry.key,