@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
@@ -1,5 +1,10 @@
1
1
  import { BufferGeometry, InstancedMesh, type Material, type Mesh, type Object3D } from "three";
2
- import { isStatic, markStatic } from "./static-transform.js";
2
+ import {
3
+ composeSilencedByFreeze,
4
+ isStatic,
5
+ markStatic,
6
+ worldSilencedByFreeze,
7
+ } from "./static-transform.js";
3
8
  import type { SharedBatch } from "./world-cell-batches.js";
4
9
  import { clusterOf } from "./world-cell-data.js";
5
10
 
@@ -193,10 +198,16 @@ export function freshMeshFor(
193
198
  next.receiveShadow = old.receiveShadow;
194
199
  next.renderOrder = old.renderOrder;
195
200
  next.userData = old.userData;
201
+ next.position.copy(old.position);
202
+ next.quaternion.copy(old.quaternion);
203
+ next.scale.copy(old.scale);
196
204
  next.matrix.copy(old.matrix);
197
- next.matrixAutoUpdate = old.matrixAutoUpdate;
198
205
  next.matrixWorld.copy(old.matrixWorld);
199
- next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate;
206
+ // The authored flags, not the freeze's: a copied `matrixWorldAutoUpdate = false` reads to the new
207
+ // freeze as a game-owned world matrix, and a seated world drew every dressed tree at the package's
208
+ // absolute height.
209
+ next.matrixAutoUpdate = old.matrixAutoUpdate || composeSilencedByFreeze(old);
210
+ next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate || worldSilencedByFreeze(old);
200
211
  // A dressed batch is frozen, and the freeze is keyed by the object: a replacement that did not
201
212
  // re-arm it would compose its own world matrix every walk forever.
202
213
  if (isStatic(old)) markStatic(next);
@@ -228,7 +239,9 @@ export function followCluster(
228
239
 
229
240
  /** What a released batch costs to keep: its instance buffer, which is all of it. */
230
241
  export function heldBytes(shared: SharedBatch): number {
231
- return (shared.mesh.instanceMatrix.array as Float32Array).byteLength;
242
+ // The count, never `array`: the records live in the engine (`world-cell-records.ts`), and a read
243
+ // of a JS copy would upload that stale copy over them.
244
+ return shared.mesh.instanceMatrix.count * 16 * Float32Array.BYTES_PER_ELEMENT;
232
245
  }
233
246
 
234
247
  export function redressMaterial(mesh: InstancedMesh): void {
@@ -24,7 +24,7 @@ import {
24
24
  Frustum,
25
25
  type InstancedMesh,
26
26
  type Material,
27
- Matrix4,
27
+ type Matrix4,
28
28
  type Mesh,
29
29
  type Object3D,
30
30
  Quaternion,
@@ -121,11 +121,15 @@ export interface ICellRenderHost {
121
121
  canonical(id: string): string;
122
122
  renderer(): IRendererLike | undefined;
123
123
  camera(): Camera | undefined;
124
+ /** The world root's own `matrixWorld`: the frame its placements are recorded in. */
125
+ root(): Matrix4;
124
126
  now(): number;
125
127
  stats(): IWorldCellsStats;
126
128
  residentCells(): IterableIterator<IResidentCell>;
127
129
  runMax(asset: string): number | undefined;
128
130
  widenFilterRange(cell: IResidentCell, x: number, z: number): void;
131
+ /** The cell's batch list changed, so the refilter's stale scan rebuilds its rows. */
132
+ cellBatchesChanged(cell: IResidentCell): void;
129
133
  addUnchanged(): void;
130
134
  disableFar(run: IWorldRun): void;
131
135
  deferWide(id: string): void;
@@ -386,6 +390,7 @@ export class CellRender {
386
390
  if (entry.wide !== undefined)
387
391
  entry.wide.write(entry.wideSegment, entry.wideRoot ?? entry.batch, entry.lodRanges);
388
392
  }
393
+ this.#host.cellBatchesChanged(cell);
389
394
  // A batch the walk just wrote to, cleared or compacted holds new records, so the shadow levels
390
395
  // that drew the old ones are stale. One flag, told at most once a second.
391
396
  this.publishGpuGates(job.asset);
@@ -1108,6 +1113,7 @@ export class CellRender {
1108
1113
  renderer: () => this.#host.renderer(),
1109
1114
  resident: () => this.#gpuResident,
1110
1115
  retired: () => this.#retired,
1116
+ root: () => this.#host.root(),
1111
1117
  shadowFloorOf: (assetId) => this.shadowFloorOf(assetId),
1112
1118
  shadowKeyFor: (key, part) => this.shadowKeyFor(key, part),
1113
1119
  shared: () => this.#shared,
@@ -1314,12 +1320,17 @@ export class CellRender {
1314
1320
 
1315
1321
  updateLodEye(x: number, y: number, z: number): void {
1316
1322
  this.#dress.updateLodEye(x, y, z);
1323
+ this.#gpuScene.lodEye(x, y, z);
1317
1324
  }
1318
1325
 
1319
1326
  refreshLodMaterials(asset: IAssetState): void {
1320
1327
  this.#dress.refreshLodMaterials(asset);
1321
1328
  }
1322
1329
 
1330
+ lodSurface(asset: string, level: number, part: number, source: Material): Material {
1331
+ return this.#dress.lodSurface(asset, level, part, source);
1332
+ }
1333
+
1323
1334
  impostorDrawn(): number {
1324
1335
  return this.#dress.impostorDrawn();
1325
1336
  }
@@ -1455,10 +1466,7 @@ export class CellRender {
1455
1466
  // whenever a neighbour still holds the cluster, and a stale box only ever shows a cell that
1456
1467
  // is there.
1457
1468
  if (this.#bundles.wanted)
1458
- this.#cull
1459
- .cells()
1460
- .get(clusterOf(cell.x, cell.z, this.#cellsPerCullCell))
1461
- ?.box.union(box);
1469
+ this.#cull.widenCell(clusterOf(cell.x, cell.z, this.#cellsPerCullCell), box);
1462
1470
  }
1463
1471
  }
1464
1472
 
@@ -1,4 +1,4 @@
1
- import { type Box3, Vector3 } from "three";
1
+ import { type Box3, type Matrix4, Vector3 } from "three";
2
2
  import type { Camera } from "three";
3
3
  import type { IRendererLike } from "./renderer.js";
4
4
  import type { CellChunks } from "./world-cell-chunks.js";
@@ -23,6 +23,7 @@ import {
23
23
  import type { CellPrewarm } from "./world-cell-prewarm.js";
24
24
  import type { CellRender } from "./world-cell-render.js";
25
25
  import type { IWorldCell, IWorldRun } from "./world-package.js";
26
+ import { localPoint } from "./world-root-frame.js";
26
27
  import {
27
28
  type IAdmissionBudget,
28
29
  type IWorldTilesLodView,
@@ -63,6 +64,8 @@ export interface ICellResidencyHost {
63
64
  lodHysteresis(): number;
64
65
  /** `camera` or `follow`: where the LOD eye is measured from. */
65
66
  lodFrom(): "camera" | "follow";
67
+ /** The world root's own `matrixWorld`: the frame its placements are recorded in. */
68
+ root(): Matrix4;
66
69
  asset(id: string): IAssetState | undefined;
67
70
  canonical(id: string): string;
68
71
  parts(): ICellResidencyParts;
@@ -249,17 +252,23 @@ export class CellResidency {
249
252
  * resting near the gate does not flip the eye between the two.
250
253
  */
251
254
  updateEye(): void {
252
- const follow = this.#eyeFollow.set(
253
- this.#host.follow().position.x,
254
- this.#host.parts().placements.followY(),
255
- this.#host.follow().position.z,
255
+ // The camera and the player are in world space; the placements the eye grades are in the root's
256
+ // own frame, so both points are read there before the pull below measures between them.
257
+ const root = this.#host.root();
258
+ const follow = localPoint(
259
+ this.#eyeFollow.set(
260
+ this.#host.follow().position.x,
261
+ this.#host.parts().placements.followY(),
262
+ this.#host.follow().position.z,
263
+ ),
264
+ root,
256
265
  );
257
266
  const camera = this.#host.lodFrom() === "camera" ? this.#host.parts().chunks.camera : undefined;
258
267
  if (camera === undefined) {
259
268
  this.#eye.copy(follow);
260
269
  return;
261
270
  }
262
- this.#eye.setFromMatrixPosition(camera.matrixWorld);
271
+ localPoint(this.#eye.setFromMatrixPosition(camera.matrixWorld), root);
263
272
  if (this.#host.parts().placements.placementReach === undefined) this.#eye.y = 0;
264
273
  const inside = this.#host.parts().placements.firstGate;
265
274
  const offset = this.#eye.distanceTo(follow);
@@ -0,0 +1,238 @@
1
+ /**
2
+ * The refilter's stale scan over packed rows, run by one engine call a pass.
3
+ *
4
+ * `CellPlacements.refilter` asks which resident cell-assets the follow point or the LOD eye moved
5
+ * across a gate of. That scan visited every batch entry of every resident cell in JS: 0.9 ms a frame
6
+ * on the forest walk, where every cell carries a `placementReach`. The entries' state now lives in a
7
+ * slab of rows, kept per cell and rebuilt only when a cell's batches change, and the scan runs on the
8
+ * slab in the owned engine: `Object3D.__tnStaleRows(blocks, plan)` keeps it there, sent only when it
9
+ * changes and then only the blocks that changed ({@link patchRows}), and `__tnStaleEntries(gates,
10
+ * query)` scans it (`bindings_scene.cpp`). Upstream three runs {@link staleRows}, its twin.
11
+ *
12
+ * Slab: one block per resident cell, a header of {@link STALE_HEADER} numbers, then
13
+ * {@link STALE_ENTRY} numbers per batch entry.
14
+ * - header: cell left x, near z, size, filterNear, filterFar, has reach (0 or 1), entries, 0.
15
+ * - entry: asset index, lastFilter x y z, lastLod x y z, threshold (NaN: none), reach min, max,
16
+ * minY, maxY (NaN: no reach).
17
+ *
18
+ * Gates: the asset count, then `[at, count]` per asset index into the values that follow (`at` -1:
19
+ * the asset is gone), then the values.
20
+ *
21
+ * Query: follow x, follow y, follow z, eye x y z, GPU scene on (0 or 1), the world gate count, then
22
+ * the world's gates ascending.
23
+ *
24
+ * Answer: `[cell block ordinal, asset index, eye distance]` per stale cell-asset, in scan order.
25
+ */
26
+ export const STALE_HEADER = 8;
27
+ export const STALE_ENTRY = 12;
28
+ /** The query's fixed numbers, before the world's gates. */
29
+ export const STALE_QUERY = 8;
30
+
31
+ /** sqrt of the sum of squares, as the engine's twin computes it; `Math.hypot` costs more. */
32
+ function length(x: number, y: number, z = 0): number {
33
+ return Math.sqrt(x * x + y * y + z * z);
34
+ }
35
+
36
+ function span(
37
+ left: number,
38
+ near: number,
39
+ size: number,
40
+ x: number,
41
+ z: number,
42
+ ): readonly [number, number] {
43
+ const right = left + size;
44
+ const far = near + size;
45
+ return [
46
+ length(Math.max(left - x, x - right, 0), Math.max(near - z, z - far, 0)),
47
+ length(
48
+ Math.max(Math.abs(x - left), Math.abs(x - right)),
49
+ Math.max(Math.abs(z - near), Math.abs(z - far)),
50
+ ),
51
+ ];
52
+ }
53
+
54
+ /** The binary search of `crossesGate`, over the query's own gates. */
55
+ function crossesWorldGate(query: Float64Array, low: number, high: number): boolean {
56
+ const count = query[7] as number;
57
+ let start = 0;
58
+ let end = count;
59
+ while (start < end) {
60
+ const middle = (start + end) >> 1;
61
+ if ((query[STALE_QUERY + middle] as number) < low) start = middle + 1;
62
+ else end = middle;
63
+ }
64
+ return start < count && (query[STALE_QUERY + start] as number) <= high;
65
+ }
66
+
67
+ function vertical(y: number, minY: number, maxY: number): readonly [number, number] {
68
+ return [Math.max(minY - y, y - maxY, 0), Math.max(Math.abs(y - minY), Math.abs(y - maxY))];
69
+ }
70
+
71
+ /** Whether the follow point crossed the entry's `placementReach` range since its batch was built. */
72
+ function reachCrossed(
73
+ slab: Float64Array,
74
+ at: number,
75
+ cell: number,
76
+ followY: number,
77
+ brackets: readonly [number, number, number, number],
78
+ ): boolean {
79
+ const minY = slab[at + 10] as number;
80
+ const maxY = slab[at + 11] as number;
81
+ const filterY = slab[at + 2] as number;
82
+ const [reachBuiltNear, reachBuiltFar] = span(
83
+ slab[cell] as number,
84
+ slab[cell + 1] as number,
85
+ slab[cell + 2] as number,
86
+ slab[at + 1] as number,
87
+ slab[at + 3] as number,
88
+ );
89
+ const current = vertical(followY, minY, maxY);
90
+ const previous = vertical(filterY, minY, maxY);
91
+ const reachLow = Math.min(length(brackets[2], current[0]), length(reachBuiltNear, previous[0]));
92
+ const reachHigh = Math.max(length(brackets[3], current[1]), length(reachBuiltFar, previous[1]));
93
+ return (slab[at + 8] as number) <= reachHigh && (slab[at + 9] as number) >= reachLow;
94
+ }
95
+
96
+ /** The scan of one entry at `at`; true when its asset is stale. */
97
+ function entryStale(
98
+ slab: Float64Array,
99
+ at: number,
100
+ cell: number,
101
+ gates: Float64Array,
102
+ query: Float64Array,
103
+ brackets: readonly [number, number, number, number],
104
+ ): boolean {
105
+ const x = query[0] as number;
106
+ const followY = query[1] as number;
107
+ const z = query[2] as number;
108
+ const eyeX = query[3] as number;
109
+ const eyeY = query[4] as number;
110
+ const eyeZ = query[5] as number;
111
+ const gpuOn = query[6] as number;
112
+ const left = slab[cell] as number;
113
+ const nearZ = slab[cell + 1] as number;
114
+ const size = slab[cell + 2] as number;
115
+ const [eyeNear, eyeFar] = brackets;
116
+ const threshold = slab[at + 7] as number;
117
+ const reachMin = slab[at + 8] as number;
118
+ const reach = !Number.isNaN(reachMin);
119
+ if (!reach && (gpuOn === 1 || Number.isNaN(threshold))) return false;
120
+ const step = (Number.isNaN(threshold) ? 6 : threshold) / 8;
121
+ const filterX = slab[at + 1] as number;
122
+ const filterY = slab[at + 2] as number;
123
+ const filterZ = slab[at + 3] as number;
124
+ const lodX = slab[at + 4] as number;
125
+ const lodY = slab[at + 5] as number;
126
+ const lodZ = slab[at + 6] as number;
127
+ if (
128
+ length(x - filterX, followY - filterY, z - filterZ) <= step &&
129
+ length(eyeX - lodX, eyeY - lodY, eyeZ - lodZ) <= step
130
+ )
131
+ return false;
132
+ const asset = slab[at] as number;
133
+ const gateAt = gates[1 + asset * 2] as number;
134
+ if (gateAt < 0) return false;
135
+ const gateCount = gpuOn === 1 ? 0 : (gates[2 + asset * 2] as number);
136
+ const [builtNear, builtFar] = span(left, nearZ, size, lodX, lodZ);
137
+ let low = Math.min(eyeNear, builtNear);
138
+ let high = Math.max(eyeFar, builtFar);
139
+ if (reach) {
140
+ const minY = slab[at + 10] as number;
141
+ const maxY = slab[at + 11] as number;
142
+ const eyeNow = vertical(eyeY, minY, maxY);
143
+ const eyeBefore = vertical(lodY, minY, maxY);
144
+ low = Math.min(length(eyeNear, eyeNow[0]), length(builtNear, eyeBefore[0]));
145
+ high = Math.max(length(eyeFar, eyeNow[1]), length(builtFar, eyeBefore[1]));
146
+ if (reachCrossed(slab, at, cell, followY, brackets)) return true;
147
+ }
148
+ for (let gate = 0; gate < gateCount; gate += 1) {
149
+ const value = gates[gateAt + gate] as number;
150
+ if (value >= low && value <= high) return true;
151
+ }
152
+ return false;
153
+ }
154
+
155
+ /**
156
+ * The upstream-three twin of the engine's `__tnStaleEntries`: every cell-asset whose follow point or
157
+ * LOD eye crossed a gate or a `placementReach` boundary since its batch was built.
158
+ */
159
+ export function staleRows(slab: Float64Array, gates: Float64Array, query: Float64Array): number[] {
160
+ const out: number[] = [];
161
+ const seen = new Set<number>();
162
+ const x = query[0] as number;
163
+ const z = query[2] as number;
164
+ const eyeX = query[3] as number;
165
+ const eyeZ = query[5] as number;
166
+ const gpuOn = query[6] as number;
167
+ let ordinal = 0;
168
+ for (let cell = 0; cell < slab.length; ordinal += 1) {
169
+ const entries = slab[cell + 6] as number;
170
+ const next = cell + STALE_HEADER + entries * STALE_ENTRY;
171
+ const left = slab[cell] as number;
172
+ const nearZ = slab[cell + 1] as number;
173
+ const size = slab[cell + 2] as number;
174
+ const hasReach = slab[cell + 5] === 1;
175
+ const [eyeNear, eyeFar] = span(left, nearZ, size, eyeX, eyeZ);
176
+ const low = Math.min(eyeNear, slab[cell + 3] as number);
177
+ const high = Math.max(eyeFar, slab[cell + 4] as number);
178
+ if ((gpuOn === 1 && !hasReach) || (!hasReach && !crossesWorldGate(query, low, high))) {
179
+ cell = next;
180
+ continue;
181
+ }
182
+ const [near, far] = span(left, nearZ, size, x, z);
183
+ seen.clear();
184
+ for (let at = cell + STALE_HEADER; at < next; at += STALE_ENTRY) {
185
+ const asset = slab[at] as number;
186
+ if (seen.has(asset)) continue;
187
+ if (!entryStale(slab, at, cell, gates, query, [eyeNear, eyeFar, near, far])) continue;
188
+ seen.add(asset);
189
+ out.push(ordinal, asset, eyeNear);
190
+ }
191
+ cell = next;
192
+ }
193
+ return out;
194
+ }
195
+
196
+ /**
197
+ * The upstream-three twin of the engine's `__tnStaleRows(blocks, plan)`: the next slab, built from the
198
+ * one held and the blocks that changed. A refilter rebuilds one cell's block, so re-sending the whole
199
+ * slab cost 0.30 ms a swap frame on the forest walk for numbers the engine already held.
200
+ *
201
+ * `plan` is `[source, count]` pairs in slab order: `source` 0 or more keeps `count` numbers of the
202
+ * held slab from `source`, and -1 takes the next `count` numbers of `blocks`.
203
+ */
204
+ export function patchRows(
205
+ held: Float64Array,
206
+ blocks: Float64Array,
207
+ plan: ArrayLike<number>,
208
+ ): Float64Array<ArrayBuffer> {
209
+ let length = 0;
210
+ for (let at = 1; at < plan.length; at += 2) length += plan[at] as number;
211
+ const next = new Float64Array(length);
212
+ let written = 0;
213
+ let taken = 0;
214
+ for (let at = 0; at + 1 < plan.length; at += 2) {
215
+ const source = plan[at] as number;
216
+ const count = plan[at + 1] as number;
217
+ const from = source === -1 ? blocks : held;
218
+ const start = source === -1 ? taken : source;
219
+ if (
220
+ !(
221
+ Number.isInteger(start) &&
222
+ Number.isInteger(count) &&
223
+ start >= 0 &&
224
+ count >= 0 &&
225
+ start + count <= from.length
226
+ )
227
+ )
228
+ throw new RangeError(
229
+ `TN_WORLD_STALE: a plan run [${String(source)}, ${String(count)}] is outside its rows`,
230
+ );
231
+ next.set(from.subarray(start, start + count), written);
232
+ written += count;
233
+ if (source === -1) taken += count;
234
+ }
235
+ if (taken !== blocks.length)
236
+ throw new RangeError("TN_WORLD_STALE: the plan leaves changed blocks unread");
237
+ return next;
238
+ }
@@ -61,7 +61,7 @@ import { InstancedBatch } from "./instanced-batch.js";
61
61
  import { biasedLodDistance, setLodBias, worldSphere } from "./model-lod.js";
62
62
  import { type OcclusionMode, occlusionMode } from "./render/depth-pyramid.js";
63
63
 
64
- import { advanceWriteEpoch, drainMeshPool } from "./render/mesh-pool.js";
64
+ import { drainMeshPool } from "./render/mesh-pool.js";
65
65
  import type { IRendererLike } from "./renderer.js";
66
66
 
67
67
  import { addInSlices } from "./streaming.js";
@@ -81,6 +81,7 @@ import { CellPrewarm } from "./world-cell-prewarm.js";
81
81
  import { CellLodBias } from "./world-cell-lod-bias.js";
82
82
  import { CellPlacements, newBatches, newBoxes, publishCount } from "./world-cell-placements.js";
83
83
  import { CellReadiness } from "./world-cell-readiness.js";
84
+ import { batchRecords } from "./world-cell-records.js";
84
85
  import { CellResidency } from "./world-cell-residency.js";
85
86
  import {
86
87
  type IShadowLevel,
@@ -321,6 +322,8 @@ export class WorldCells extends Group implements IComputeDriven {
321
322
 
322
323
  readonly #render: CellRender;
323
324
  readonly #onPublication: IWorldCellsInit["onPublication"];
325
+ /** Publications told after the frame's records reach the engine, so a told batch is drawable. */
326
+ readonly #publications: Box3[] = [];
324
327
  /** The spawn and view gates, and the waiters they settle. */
325
328
  readonly #readiness: CellReadiness;
326
329
  readonly #prewarm: CellPrewarm;
@@ -366,6 +369,8 @@ export class WorldCells extends Group implements IComputeDriven {
366
369
  followCluster: () => this.#render.followCluster(),
367
370
  wideShape: (asset, level, part, fallback) =>
368
371
  this.#render.wideShape(asset, level, part, fallback),
372
+ lodSurface: (asset, level, part, source) =>
373
+ this.#render.lodSurface(asset, level, part, source),
369
374
  });
370
375
  this.#init = { ...init };
371
376
  this.#budgets = {
@@ -589,11 +594,16 @@ export class WorldCells extends Group implements IComputeDriven {
589
594
  canonical: (id) => this.#canonical(id),
590
595
  renderer: () => this.#chunks.renderer,
591
596
  camera: () => this.#chunks.camera,
597
+ // Live, not a snapshot: three refreshes `matrixWorld` before it renders, so a game that moves
598
+ // the root reads its own frame from the next update on — the same answer `stepCellProxies`
599
+ // is handed below.
600
+ root: () => this.matrixWorld,
592
601
  now: () => this.#now(),
593
602
  stats: () => this.stats(),
594
603
  residentCells: () => this.#residency.resident.values(),
595
604
  runMax: (asset) => this.#runMax.get(asset),
596
605
  widenFilterRange: (cell, x, z) => this.#placementBuild.widenFilterRange(cell, x, z),
606
+ cellBatchesChanged: (cell) => this.#placementBuild.cellBatchesChanged(cell),
597
607
  addUnchanged: () => {
598
608
  this.#unchanged += 1;
599
609
  },
@@ -797,10 +807,11 @@ export class WorldCells extends Group implements IComputeDriven {
797
807
  parts: () => parts,
798
808
  prefetchSeconds: () => this.#prefetchSeconds,
799
809
  published: (bounds) => {
800
- this.#onPublication?.(bounds);
810
+ if (this.#onPublication !== undefined) this.#publications.push(bounds.clone());
801
811
  },
802
812
  released: () => this.#released,
803
813
  ring: () => this.#ring,
814
+ root: () => this.matrixWorld,
804
815
  });
805
816
  this.#readiness = new CellReadiness({
806
817
  asset: (id) => this.#models.asset(id),
@@ -1153,9 +1164,6 @@ export class WorldCells extends Group implements IComputeDriven {
1153
1164
  // earlier, which is the state the run that found this was in.
1154
1165
  this.#render.announceGpu();
1155
1166
  }
1156
- // A new upload epoch, so no batch's pending span outlives the render that consumed it. See
1157
- // `SharedBatch#touched`.
1158
- advanceWriteEpoch();
1159
1167
  const x = this.#follow.position.x;
1160
1168
  const z = this.#follow.position.z;
1161
1169
  // Terrain admits first, and a tile is one unit of several milliseconds, so after a jump (a
@@ -1237,6 +1245,10 @@ export class WorldCells extends Group implements IComputeDriven {
1237
1245
  camera,
1238
1246
  );
1239
1247
  this.#render.reportMainCull();
1248
+ // Last, after every write, clear, compact, grow and cull repack above: the frame's instance
1249
+ // records reach the engine in one call (see `world-cell-records.ts`).
1250
+ batchRecords.flush();
1251
+ this.#tellPublications();
1240
1252
  this.#admission = {
1241
1253
  backlog: this.#residency.backlog(),
1242
1254
  deferred: this.#residency.queuedBuilds,
@@ -1246,6 +1258,11 @@ export class WorldCells extends Group implements IComputeDriven {
1246
1258
  this.#readiness.settleWaiters();
1247
1259
  }
1248
1260
 
1261
+ /** The frame's publications, told once their records are in the engine's buffers. */
1262
+ #tellPublications(): void {
1263
+ for (const bounds of this.#publications.splice(0)) this.#onPublication?.(bounds);
1264
+ }
1265
+
1249
1266
  process(renderer?: IRendererLike, camera?: Camera, covered = false): void {
1250
1267
  this.#covered = covered;
1251
1268
  try {
@@ -6,53 +6,26 @@
6
6
  * what a run would use without building a scene, and a test can pin the order the sources are read
7
7
  * in without a device.
8
8
  */
9
+ import { readLaunchFlag, readLaunchValues } from "./debug.js";
9
10
 
10
11
  /** The launch flag. */
11
12
  export const GPU_SCENE_FLAG = "TN_GPU_SCENE";
12
13
 
13
14
  /**
14
15
  * Did this launch ask for `flag` to be **off**? The environment variable, the query string and the
15
- * global a test sets are the three ways one is asked, and `0` and `false` are the only answers that
16
- * count: an unset or empty variable is the same as no variable, and a saved URL that used to enable
17
- * a switch still says "off".
16
+ * global a test sets are the three ways one is asked, and `debug.ts` owns the rule that reads them
17
+ * — see {@link readLaunchFlag}.
18
18
  */
19
19
  function askedOff(flag: string, parameter: string, globalName: string): boolean {
20
- const host = globalThis as { process?: { env?: Record<string, unknown> } } & Record<
21
- string,
22
- unknown
23
- >;
24
- const fromEnv = host.process?.env?.[flag];
25
- if (fromEnv === "0" || fromEnv === "false") return true;
26
- const query = globalThis.location?.search;
27
- if (
28
- typeof query === "string" &&
29
- new RegExp(`[?&]${parameter}=(?:0|false)(?:&|$)`, "u").test(query)
30
- )
31
- return true;
32
- const set = host[globalName];
33
- return set === false || set === 0 || set === "0" || set === "false";
20
+ return readLaunchFlag({ environment: flag, global: globalName, query: parameter }, "off");
34
21
  }
35
22
 
36
23
  /**
37
- * Did this launch ask for `flag` to be **on**? The mirror of {@link askedOff}, for the switches that
38
- * are opt-in: the environment variable, the query string and the global a test sets, and only
39
- * `1` and `true` count. An unset or empty variable is the same as no variable, so an old URL that
40
- * never mentioned the switch stays off.
24
+ * Did this launch ask for `flag` to be **on**? The mirror of {@link askedOff}, for the switches
25
+ * that are opt-in.
41
26
  */
42
27
  function askedOn(flag: string, parameter: string, globalName: string): boolean {
43
- const host = globalThis as { process?: { env?: Record<string, unknown> } } & Record<
44
- string,
45
- unknown
46
- >;
47
- const fromEnv = host.process?.env?.[flag];
48
- if (fromEnv === "1" || fromEnv === "true") return true;
49
- const query = globalThis.location?.search;
50
- if (
51
- typeof query === "string" &&
52
- new RegExp(`[?&]${parameter}=(?:1|true)(?:&|$)`, "u").test(query)
53
- )
54
- return true;
55
- return host[globalName] === true || host[globalName] === 1 || host[globalName] === "1";
28
+ return readLaunchFlag({ environment: flag, global: globalName, query: parameter });
56
29
  }
57
30
 
58
31
  /**
@@ -91,8 +64,16 @@ export const BUNDLE_FLAG = "TN_BUNDLES";
91
64
  * variable, a browser asks with the query string, and a test sets the global.
92
65
  */
93
66
  export function bundlesAsked(): "default" | "off" | "on" {
94
- if (askedOn(BUNDLE_FLAG, "tnBundles", "__tnBundles")) return "on";
95
- return askedOff(BUNDLE_FLAG, "tnBundles", "__tnBundles") ? "off" : "default";
67
+ // Its own vocabulary over the one reader: a launch can answer yes, answer no, or say nothing, and
68
+ // "said nothing" is what a caller has to tell apart from a measurement's default. Every seam is
69
+ // heard, as it is for every other switch, so an explicit yes anywhere beats a no anywhere.
70
+ const values = readLaunchValues({
71
+ environment: BUNDLE_FLAG,
72
+ global: "__tnBundles",
73
+ query: "tnBundles",
74
+ });
75
+ if (values.some((value) => value === "1" || value === "true" || value === "")) return "on";
76
+ return values.some((value) => value === "0" || value === "false") ? "off" : "default";
96
77
  }
97
78
 
98
79
  /**
@@ -127,20 +108,7 @@ export const GPU_SCENE_VALIDATE_FLAG = "TN_GPU_SCENE_VALIDATE";
127
108
  * browser asks with `?tnGpuSceneValidate=1`, and a test sets the global.
128
109
  */
129
110
  export function gpuSceneValidationRequested(): boolean {
130
- const host = globalThis as {
131
- process?: { env?: Record<string, unknown> };
132
- __tnGpuSceneValidate?: unknown;
133
- };
134
- const fromEnv = host.process?.env?.[GPU_SCENE_VALIDATE_FLAG];
135
- if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
136
- return true;
137
- const query = globalThis.location?.search;
138
- if (
139
- typeof query === "string" &&
140
- /[?&]tnGpuSceneValidate=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query)
141
- )
142
- return true;
143
- return host.__tnGpuSceneValidate === true || host.__tnGpuSceneValidate === "1";
111
+ return askedOn(GPU_SCENE_VALIDATE_FLAG, "tnGpuSceneValidate", "__tnGpuSceneValidate");
144
112
  }
145
113
 
146
114
  /** The launch flag. */
@@ -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 };