@threenative/core 0.3.12 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
package/dist/world.js CHANGED
@@ -1,13 +1,14 @@
1
- import { SPANS, createAssetLoader, addInSlices, yieldToHost, advanceWriteEpoch, drainMeshPool, spanRecorder, spanNow, addSpan, InstancedBatch, INSTANCED_LOD_MAX_PIXEL_ERROR, dropPooledFor, parkMesh, warmUpSceneWithCompletion, loadAll, warmUpScene, markStatic, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, pooledCapacity, pooledMesh, currentWriteEpoch, displacesVertices, DEFAULT_TARGET_FPS, isStatic, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, mergeByMaterial } from './chunk-GMHATRPW.js';
1
+ import { SPANS, createAssetLoader, addInSlices, yieldToHost, batchRecords, drainMeshPool, spanRecorder, spanNow, addSpan, fetchAsset, placedBox, InstancedBatch, INSTANCED_LOD_MAX_PIXEL_ERROR, dropPooledFor, DRAW_ARGS_BYTES, parkMesh, warmUpSceneWithCompletion, loadAll, warmUpScene, markStatic, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, pooledCapacity, pooledMesh, displacesVertices, DEFAULT_TARGET_FPS, STORAGE_PLAIN, argsWords, NO_LOCAL, SLOT_NONE, LOCAL_WORDS, storageAttribute, SOURCE_FLOOR, PLACEMENT_ROWS, DRAW_ARGS_WORDS, growBuffer, addRange, PLACEMENT_WORDS, VEC4_WORDS, composeSilencedByFreeze, worldSilencedByFreeze, isStatic, markEngineStatic, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, frustumPlanes, rendererFacts, mergeByMaterial, VALIDATE_EVERY, TALLY_EVERY, nodes } from './chunk-GEMQJBY4.js';
2
2
  import { GPUReadback } from './chunk-QWJEMUUT.js';
3
- import { worldSphere, conservativeViewDepth, projectedLodError, selectLodLevel, setLodBias, markEngineRenderHook, biasedLodDistance, isLodJoinProxy, setModelLodLayers, isEngineRenderHook, lodChainOf, DISCRETE_LOD_DEFAULT_HYSTERESIS, baseGeometryOf } from './chunk-5O73CDMR.js';
4
- import './chunk-6KLNISRJ.js';
3
+ import { baseGeometryOf, worldSphere, selectLodFor, projectedLodError, selectLodLevel, setLodBias, markEngineRenderHook, biasedLodDistance, isLodJoinProxy, setModelLodLayers, LOD_NEAR_PLANE, GEOMETRY_ASSET_KEY, isEngineRenderHook, lodChainOf, DISCRETE_LOD_DEFAULT_HYSTERESIS } from './chunk-QAMSM3Z5.js';
4
+ import { readLaunchFlag, readLaunchValues, readLaunchValue } from './chunk-VQRPEOKY.js';
5
+ import './chunk-XDTZ4QMO.js';
6
+ import './chunk-VP43GIWW.js';
5
7
  import { createTerrainJobRunner, edgeWorldPoint } from './chunk-KIRUKTBQ.js';
6
- import './chunk-N5LRP4BR.js';
7
- import { Matrix4, Vector3, Frustum, Group, BufferAttribute, Sphere, BufferGeometry, Object3D, Box3, LOD, Mesh, Data3DTexture, RGBAFormat, UnsignedByteType, LinearFilter, RepeatWrapping, NoColorSpace, DataArrayTexture, LinearMipmapLinearFilter, CompressedArrayTexture, InstancedMesh, Quaternion, InstancedBufferAttribute, DynamicDrawUsage, InstancedInterleavedBuffer, SkinnedMesh, Vector4, Texture, Material, Scene, OrthographicCamera, Color, DoubleSide, Float32BufferAttribute, Vector2, PerspectiveCamera, TextureUtils, SRGBColorSpace, NoBlending } from 'three';
8
+ import { Matrix4, Vector3, Frustum, Box3, Group, BufferAttribute, Sphere, BufferGeometry, Quaternion, Object3D, LOD, Mesh, Data3DTexture, RGBAFormat, UnsignedByteType, LinearFilter, RepeatWrapping, NoColorSpace, DataArrayTexture, LinearMipmapLinearFilter, CompressedArrayTexture, InstancedMesh, InstancedBufferAttribute, DynamicDrawUsage, InstancedInterleavedBuffer, SkinnedMesh, Vector4, Texture, Material, Scene, OrthographicCamera, Color, DoubleSide, Float32BufferAttribute, Vector2, PerspectiveCamera, TextureUtils, SRGBColorSpace, NoBlending } from 'three';
8
9
  import * as threeTsl from 'three/tsl';
9
- import { struct, vec2, positionWorld, float, texture, int, mx_noise_float, vec3, normalWorld, smoothstep as smoothstep$1, cameraPosition, mix, dot, clamp, cameraViewMatrix, vec4, texture3D, Fn, floor, fract, sin, instancedArray, uniform, renderGroup, mat4, storage, instanceIndex, instancedDynamicBufferAttribute, instancedBufferAttribute, varyingProperty, modelWorldMatrix, length, select, normalize, positionGeometry, attribute, transformNormal, If, Return, min, max, abs, Loop, atomicAdd, varying, screenCoordinate, diffuseColor, positionView, mrt, element, cameraProjectionMatrix, mat3, cross, log2, dFdx, dFdy, Break, textureLoad, ivec2, ceil, pow, uv, uint, atomicLoad, log } from 'three/tsl';
10
- import { MeshStandardNodeMaterial, BundleGroup, EventNode, ReadbackBuffer, IndirectStorageBufferAttribute, StorageInstancedBufferAttribute, StorageBufferAttribute, RenderTarget, LinearMipmapLinearFilter as LinearMipmapLinearFilter$1, LinearFilter as LinearFilter$1, UnsignedByteType as UnsignedByteType$1, RGBAFormat as RGBAFormat$1, MeshBasicNodeMaterial, MeshPhysicalNodeMaterial } from 'three/webgpu';
10
+ import { vec2, positionWorld, float, texture, int, mx_noise_float, vec3, normalWorld, smoothstep as smoothstep$1, cameraPosition, mix, dot, clamp, cameraViewMatrix, vec4, texture3D, Fn, floor, fract, sin, instancedArray, uniform, renderGroup, mat4, storage, instanceIndex, instancedDynamicBufferAttribute, instancedBufferAttribute, varyingProperty, modelWorldMatrix, length, select, normalize, positionGeometry, min, abs, attribute, transformNormal, If, Return, max, uint, Loop, atomicAdd, varying, screenCoordinate, diffuseColor, positionView, mrt, element, cameraProjectionMatrix, mat3, cross, log2, dFdx, dFdy, Break, textureLoad, ivec2, ceil, pow, uv, atomicLoad, log } from 'three/tsl';
11
+ import { MeshStandardNodeMaterial, StorageBufferAttribute, StorageInstancedBufferAttribute, IndirectStorageBufferAttribute, BundleGroup, EventNode, ReadbackBuffer, RenderTarget, LinearMipmapLinearFilter as LinearMipmapLinearFilter$1, LinearFilter as LinearFilter$1, UnsignedByteType as UnsignedByteType$1, RGBAFormat as RGBAFormat$1, MeshBasicNodeMaterial, MeshPhysicalNodeMaterial } from 'three/webgpu';
11
12
 
12
13
  function finite(name, value, minimum = 0) {
13
14
  if (!Number.isFinite(value) || value < minimum)
@@ -1026,10 +1027,10 @@ var Heightfield = class _Heightfield extends Group {
1026
1027
  const far = Math.min(this.rows - 1, row + 1);
1027
1028
  const slopeX = (this.#height(row * this.columns + right) - this.#height(row * this.columns + left)) / ((right - left) * this.#cellWidth);
1028
1029
  const slopeZ = (this.#height(far * this.columns + column) - this.#height(near * this.columns + column)) / ((far - near) * this.#cellDepth);
1029
- const length6 = Math.hypot(slopeX, 1, slopeZ);
1030
- const x = -slopeX / length6;
1031
- const y = 1 / length6;
1032
- const z = -slopeZ / length6;
1030
+ const length7 = Math.hypot(slopeX, 1, slopeZ);
1031
+ const x = -slopeX / length7;
1032
+ const y = 1 / length7;
1033
+ const z = -slopeZ / length7;
1033
1034
  if (target instanceof Float32Array) {
1034
1035
  target[vertex * 3] = x;
1035
1036
  target[vertex * 3 + 1] = y;
@@ -1296,6 +1297,63 @@ function waterlineRadius(field, centre, level) {
1296
1297
  }
1297
1298
  return furthest;
1298
1299
  }
1300
+ function lakeDisc(field, lake, rings = 44, spokes = 88, packing = 1.7) {
1301
+ const reach = lakeReach(field, lake);
1302
+ if (!(reach > 0)) return void 0;
1303
+ const [cx = 0, cz = 0] = lake.at;
1304
+ const minX = field.origin.x - field.width / 2;
1305
+ const minZ = field.origin.z - field.depth / 2;
1306
+ const count3 = (rings - 1) * spokes + 1;
1307
+ const positions = new Float32Array(count3 * 2);
1308
+ const raw = new Float32Array(count3);
1309
+ for (let index = 0; index < count3; index += 1) {
1310
+ const ring = index === 0 ? 0 : Math.floor((index - 1) / spokes) + 1;
1311
+ const angle = (index - 1) % spokes / spokes * Math.PI * 2;
1312
+ const radius = index === 0 ? 0 : reach * (ring / (rings - 1)) ** packing;
1313
+ const x = Math.max(minX, Math.min(minX + field.width, cx + Math.cos(angle) * radius));
1314
+ const z = Math.max(minZ, Math.min(minZ + field.depth, cz + Math.sin(angle) * radius));
1315
+ positions[index * 2] = x;
1316
+ positions[index * 2 + 1] = z;
1317
+ raw[index] = Math.max(0, lake.level - field.heightAt(x, z));
1318
+ }
1319
+ const depths = new Float32Array(count3);
1320
+ const stack = [0];
1321
+ depths[0] = raw[0];
1322
+ const visit = (index) => {
1323
+ if (raw[index] > 0 && depths[index] === 0) {
1324
+ depths[index] = raw[index];
1325
+ stack.push(index);
1326
+ }
1327
+ };
1328
+ while (stack.length > 0) {
1329
+ const index = stack.pop();
1330
+ if (index === 0) {
1331
+ for (let spoke2 = 0; spoke2 < spokes; spoke2 += 1) visit(1 + spoke2);
1332
+ continue;
1333
+ }
1334
+ const ring = Math.floor((index - 1) / spokes) + 1;
1335
+ const spoke = (index - 1) % spokes;
1336
+ const at = (r, s) => r === 0 ? 0 : 1 + (r - 1) * spokes + s;
1337
+ visit(at(ring, (spoke + 1) % spokes));
1338
+ visit(at(ring, (spoke + spokes - 1) % spokes));
1339
+ visit(at(ring - 1, spoke));
1340
+ if (ring + 1 < rings) visit(at(ring + 1, spoke));
1341
+ }
1342
+ return { x: cx, z: cz, reach, rings, spokes, packing, positions, depths };
1343
+ }
1344
+ function discReaches(disc, x, z) {
1345
+ const dx = x - disc.x;
1346
+ const dz = z - disc.z;
1347
+ const t = (Math.hypot(dx, dz) / disc.reach) ** (1 / disc.packing) * (disc.rings - 1);
1348
+ const ring = Math.min(disc.rings - 2, Math.floor(t));
1349
+ const turn = (Math.atan2(dz, dx) / (Math.PI * 2) + 1) % 1;
1350
+ const spoke = Math.floor(turn * disc.spokes) % disc.spokes;
1351
+ const at = (r, s) => r === 0 ? 0 : 1 + (r - 1) * disc.spokes + s;
1352
+ const next = (spoke + 1) % disc.spokes;
1353
+ return [at(ring, spoke), at(ring, next), at(ring + 1, spoke), at(ring + 1, next)].some(
1354
+ (index) => disc.depths[index] > 0
1355
+ );
1356
+ }
1299
1357
  function lakeReach(field, lake) {
1300
1358
  return Math.min(waterlineRadius(field, lake.at, lake.level) * lake.margin, lake.radius);
1301
1359
  }
@@ -1307,7 +1365,7 @@ var WaterBodies = class {
1307
1365
  constructor(options) {
1308
1366
  const field = options.field;
1309
1367
  const reaches = [];
1310
- for (const ribbon of options.ribbons ?? []) buildReaches(ribbon, reaches);
1368
+ for (const ribbon2 of options.ribbons ?? []) buildReaches(ribbon2, reaches);
1311
1369
  this.#cellSize = Math.max(1, ...reaches.map((piece) => piece.reach));
1312
1370
  this.#cells = indexReaches(reaches, this.#cellSize);
1313
1371
  this.#pools = (options.lakes ?? NO_LAKES).map((lake) => poolOf(field, lake));
@@ -1337,9 +1395,9 @@ var WaterBodies = class {
1337
1395
  out.z = 0;
1338
1396
  return out;
1339
1397
  }
1340
- const length6 = Math.sqrt(piece.length2);
1341
- out.x = piece.dx / length6 * piece.flow;
1342
- out.z = piece.dz / length6 * piece.flow;
1398
+ const length7 = Math.sqrt(piece.length2);
1399
+ out.x = piece.dx / length7 * piece.flow;
1400
+ out.z = piece.dz / length7 * piece.flow;
1343
1401
  return out;
1344
1402
  }
1345
1403
  /** Which water body covers (x, z) and how high its surface is, or `undefined` where none is. */
@@ -1374,7 +1432,7 @@ var WaterBodies = class {
1374
1432
  let level = river === void 0 ? Number.NEGATIVE_INFINITY : river.ha + (river.hb - river.ha) * along;
1375
1433
  let kind = river === void 0 ? void 0 : "river";
1376
1434
  for (const pool of this.#pools)
1377
- if ((x - pool.x) ** 2 + (z - pool.z) ** 2 <= pool.radius2 && pool.level > level) {
1435
+ if ((x - pool.x) ** 2 + (z - pool.z) ** 2 <= pool.radius2 && pool.level > level && !isolated(pool, x, z)) {
1378
1436
  level = pool.level;
1379
1437
  river = void 0;
1380
1438
  kind = "lake";
@@ -1388,10 +1446,22 @@ var WaterBodies = class {
1388
1446
  return kind === void 0 ? void 0 : { kind, level, river };
1389
1447
  }
1390
1448
  };
1391
- function buildReaches(ribbon, into) {
1392
- const width = positive2(ribbon.width, "ribbon width");
1393
- const flow = finite3(ribbon.flow, "ribbon flow");
1394
- const points = ribbon.points;
1449
+ function isolated(pool, x, z) {
1450
+ const disc = pool.disc;
1451
+ if (disc === void 0 || discReaches(disc, x, z)) return false;
1452
+ const field = pool.field;
1453
+ const minX = field.origin.x - field.width / 2;
1454
+ const minZ = field.origin.z - field.depth / 2;
1455
+ const ground = field.heightAt(
1456
+ Math.max(minX, Math.min(minX + field.width, x)),
1457
+ Math.max(minZ, Math.min(minZ + field.depth, z))
1458
+ );
1459
+ return ground < pool.level;
1460
+ }
1461
+ function buildReaches(ribbon2, into) {
1462
+ const width = positive2(ribbon2.width, "ribbon width");
1463
+ const flow = finite3(ribbon2.flow, "ribbon flow");
1464
+ const points = ribbon2.points;
1395
1465
  if (!Array.isArray(points) || points.length < 2)
1396
1466
  throw new Error(
1397
1467
  `TN_WATER_BODIES_INVALID: a ribbon needs at least two stations, received ${String(points?.length)}.`
@@ -1422,8 +1492,9 @@ function poolOf(field, lake) {
1422
1492
  const [x = 0, z = 0] = lake.at;
1423
1493
  finite3(x, "lake x");
1424
1494
  finite3(z, "lake z");
1425
- const radius = lakeReach(field, lake);
1426
- return { level: lake.level, radius2: radius * radius, x, z };
1495
+ const disc = lakeDisc(field, lake);
1496
+ const radius = disc?.reach ?? 0;
1497
+ return { level: lake.level, radius2: radius * radius, x, z, disc, field };
1427
1498
  }
1428
1499
  function indexReaches(reaches, cellSize) {
1429
1500
  const cells = /* @__PURE__ */ new Map();
@@ -1444,6 +1515,481 @@ function indexReaches(reaches, cellSize) {
1444
1515
  }
1445
1516
  return cells;
1446
1517
  }
1518
+ function riverRibbonGeometry(rivers, field, options = {}) {
1519
+ const columns = options.columns ?? 25;
1520
+ if (!Number.isInteger(columns) || columns < 2)
1521
+ throw new Error(
1522
+ `TN_RIVER_RIBBON_INVALID: columns must be an integer of at least 2, received ${columns}.`
1523
+ );
1524
+ const perWidth = options.reach ?? WATER_RIBBON_REACH;
1525
+ const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
1526
+ const edgeSlope = options.edgeSlope ?? 0.2;
1527
+ if (!(perWidth > 0) || !(maxDepth > 0) || !(edgeSlope >= 0))
1528
+ throw new Error(
1529
+ "TN_RIVER_RIBBON_INVALID: reach and maxDepth must be positive, edgeSlope not negative."
1530
+ );
1531
+ const positions = [];
1532
+ const flows = [];
1533
+ const uvs = [];
1534
+ const depths = [];
1535
+ const indices = [];
1536
+ const geometry = new BufferGeometry();
1537
+ for (const river of rivers) {
1538
+ if (!(river.width > 0) || river.points.length < 2)
1539
+ throw new Error(
1540
+ `TN_RIVER_RIBBON_INVALID: a river needs a positive width and two stations, received width ${river.width} and ${river.points.length} stations.`
1541
+ );
1542
+ const start = indices.length;
1543
+ ribbon(field, river.points, river.width * perWidth, columns, maxDepth, edgeSlope, {
1544
+ depths,
1545
+ flows,
1546
+ indices,
1547
+ positions,
1548
+ uvs
1549
+ });
1550
+ geometry.addGroup(start, indices.length - start, 0);
1551
+ }
1552
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
1553
+ geometry.setAttribute("flow", new BufferAttribute(new Float32Array(flows), 2));
1554
+ geometry.setAttribute("flowUv", new BufferAttribute(new Float32Array(uvs), 2));
1555
+ geometry.setAttribute("metres", new BufferAttribute(new Float32Array(depths), 1));
1556
+ geometry.setIndex(indices);
1557
+ geometry.computeVertexNormals();
1558
+ geometry.computeBoundingBox();
1559
+ geometry.computeBoundingSphere();
1560
+ return geometry;
1561
+ }
1562
+ var DRAIN_TOLERANCE = 0.05;
1563
+ function beyond(end, inner, reach) {
1564
+ const dx = (end[0] ?? 0) - (inner[0] ?? 0);
1565
+ const dz = (end[2] ?? 0) - (inner[2] ?? 0);
1566
+ const length7 = Math.hypot(dx, dz) || 1;
1567
+ return [
1568
+ (end[0] ?? 0) + dx / length7 * reach,
1569
+ end[1] ?? 0,
1570
+ (end[2] ?? 0) + dz / length7 * reach
1571
+ ];
1572
+ }
1573
+ function ribbon(field, stations, reach, columns, maxDepth, edgeSlope, out) {
1574
+ const points = [
1575
+ beyond(stations[0], stations[1], reach),
1576
+ ...stations,
1577
+ beyond(stations.at(-1), stations.at(-2), reach)
1578
+ ];
1579
+ const base = out.positions.length / 3;
1580
+ const minX = field.origin.x - field.width / 2;
1581
+ const minZ = field.origin.z - field.depth / 2;
1582
+ const ground = (x, z) => field.heightAt(
1583
+ Math.min(minX + field.width, Math.max(minX, x)),
1584
+ Math.min(minZ + field.depth, Math.max(minZ, z))
1585
+ );
1586
+ const wet = [];
1587
+ const last = points.length - 1;
1588
+ const bedAt = (station) => ground(station[0] ?? 0, station[2] ?? 0);
1589
+ const capBed = [
1590
+ bedAt(stations[0]),
1591
+ bedAt(stations.at(-1))
1592
+ ];
1593
+ const drained = [];
1594
+ let downstream = 0;
1595
+ for (let k = 0; k < points.length; k += 1) {
1596
+ const [x = 0, y = 0, z = 0] = points[k];
1597
+ if (k > 0) {
1598
+ const [px = 0, , pz = 0] = points[k - 1];
1599
+ downstream += Math.hypot(x - px, z - pz);
1600
+ }
1601
+ const before = points[Math.max(0, k - 1)];
1602
+ const after = points[Math.min(points.length - 1, k + 1)];
1603
+ let dx = (after[0] ?? 0) - (before[0] ?? 0);
1604
+ let dz = (after[2] ?? 0) - (before[2] ?? 0);
1605
+ const length7 = Math.hypot(dx, dz) || 1;
1606
+ dx /= length7;
1607
+ dz /= length7;
1608
+ for (let c = 0; c < columns; c += 1) {
1609
+ const across = (c / (columns - 1) - 0.5) * 2 * reach;
1610
+ const vx = x - dz * across;
1611
+ const vz = z + dx * across;
1612
+ out.positions.push(vx, y, vz);
1613
+ out.flows.push(dx, dz);
1614
+ out.uvs.push(downstream, across);
1615
+ const below = ground(vx, vz);
1616
+ const bed = k === 0 ? capBed[0] : k === last ? capBed[1] : void 0;
1617
+ const dry = bed !== void 0 && below < bed - DRAIN_TOLERANCE;
1618
+ const depth = dry ? 0 : Math.min(
1619
+ maxDepth,
1620
+ Math.max(0, y - below),
1621
+ Math.max(0, (reach - Math.abs(across)) * edgeSlope)
1622
+ );
1623
+ out.depths.push(depth);
1624
+ wet.push(depth > 0 ? 1 : 0);
1625
+ drained.push(dry);
1626
+ }
1627
+ }
1628
+ for (let k = 1; k < points.length; k += 1) {
1629
+ for (let c = 1; c < columns; c += 1) {
1630
+ const a = (k - 1) * columns + c - 1;
1631
+ const d = k * columns + c - 1;
1632
+ const rowA = (wet[a - 1] ?? 0) + (wet[a + 1] ?? 0) + (wet[d - 1] ?? 0) + (wet[d + 1] ?? 0);
1633
+ const rowB = (wet[a] ?? 0) + (wet[a + 1] ?? 0) + (wet[d] ?? 0) + (wet[d + 1] ?? 0);
1634
+ if (rowA === 0 && rowB === 0) continue;
1635
+ if (drained[a] || drained[a + 1] || drained[d] || drained[d + 1]) continue;
1636
+ out.indices.push(base + a, base + a + 1, base + d, base + a + 1, base + d + 1, base + d);
1637
+ }
1638
+ }
1639
+ }
1640
+ function lakeSurfaceGeometry(lake, field, options = {}) {
1641
+ const rings = options.rings ?? 44;
1642
+ const spokes = options.spokes ?? 88;
1643
+ const packing = options.packing ?? 1.7;
1644
+ const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
1645
+ if (!Number.isInteger(rings) || rings < 2 || !Number.isInteger(spokes) || spokes < 3)
1646
+ throw new Error(
1647
+ `TN_LAKE_SURFACE_INVALID: rings must be an integer of at least 2 and spokes of at least 3, received ${rings} and ${spokes}.`
1648
+ );
1649
+ if (!(packing > 0) || !(maxDepth > 0))
1650
+ throw new Error("TN_LAKE_SURFACE_INVALID: packing and maxDepth must be positive.");
1651
+ const disc = lakeDisc(field, lake, rings, spokes, packing);
1652
+ if (disc === void 0) return void 0;
1653
+ const count3 = disc.depths.length;
1654
+ const positions = new Float32Array(count3 * 3);
1655
+ const depths = new Float32Array(count3);
1656
+ for (let index = 0; index < count3; index += 1) {
1657
+ positions[index * 3] = disc.positions[index * 2];
1658
+ positions[index * 3 + 1] = lake.level;
1659
+ positions[index * 3 + 2] = disc.positions[index * 2 + 1];
1660
+ depths[index] = Math.min(maxDepth, disc.depths[index]);
1661
+ }
1662
+ const depth = (index) => depths[index] ?? 0;
1663
+ const indices = [];
1664
+ for (let spoke = 0; spoke < spokes; spoke += 1) {
1665
+ const first = 1 + spoke;
1666
+ const next = 1 + (spoke + 1) % spokes;
1667
+ if (depth(0) + depth(first) + depth(next) > 0) indices.push(0, first, next);
1668
+ }
1669
+ for (let ring = 2; ring < rings; ring += 1)
1670
+ for (let spoke = 0; spoke < spokes; spoke += 1) {
1671
+ const next = (spoke + 1) % spokes;
1672
+ const inner = 1 + (ring - 2) * spokes + spoke;
1673
+ const innerNext = 1 + (ring - 2) * spokes + next;
1674
+ const outer = 1 + (ring - 1) * spokes + spoke;
1675
+ const outerNext = 1 + (ring - 1) * spokes + next;
1676
+ if (depth(inner) + depth(innerNext) + depth(outer) + depth(outerNext) <= 0) continue;
1677
+ indices.push(inner, outer, innerNext, innerNext, outer, outerNext);
1678
+ }
1679
+ const geometry = new BufferGeometry();
1680
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
1681
+ geometry.setAttribute("metres", new BufferAttribute(depths, 1));
1682
+ geometry.setIndex(indices);
1683
+ geometry.computeVertexNormals();
1684
+ geometry.computeBoundingSphere();
1685
+ return geometry;
1686
+ }
1687
+
1688
+ // src/world-load-limiter.ts
1689
+ var ModelLoadLimiter = class {
1690
+ #concurrency;
1691
+ #queue = [];
1692
+ #inFlight = 0;
1693
+ constructor(concurrency) {
1694
+ this.#concurrency = concurrency;
1695
+ }
1696
+ get inFlight() {
1697
+ return this.#inFlight;
1698
+ }
1699
+ get queued() {
1700
+ return this.#queue.length;
1701
+ }
1702
+ load(run, wanted) {
1703
+ return new Promise((resolve, reject) => {
1704
+ this.#queue.push({ reject, resolve, run, wanted });
1705
+ this.#pump();
1706
+ });
1707
+ }
1708
+ #pump() {
1709
+ while (this.#inFlight < this.#concurrency && this.#queue.length > 0) {
1710
+ const job = this.#queue.shift();
1711
+ if (!job.wanted()) {
1712
+ job.resolve(void 0);
1713
+ continue;
1714
+ }
1715
+ this.#inFlight += 1;
1716
+ try {
1717
+ job.run().then(
1718
+ (model) => {
1719
+ this.#inFlight -= 1;
1720
+ job.resolve(model);
1721
+ this.#pump();
1722
+ },
1723
+ (error) => {
1724
+ this.#inFlight -= 1;
1725
+ job.reject(error);
1726
+ this.#pump();
1727
+ }
1728
+ );
1729
+ } catch (error) {
1730
+ this.#inFlight -= 1;
1731
+ job.reject(error);
1732
+ this.#pump();
1733
+ }
1734
+ }
1735
+ }
1736
+ };
1737
+ var AdmissionBudget = class {
1738
+ #limitMs;
1739
+ #now;
1740
+ #spentMs = 0;
1741
+ constructor(limitMs, now) {
1742
+ this.#limitMs = limitMs;
1743
+ this.#now = now;
1744
+ }
1745
+ get spentMs() {
1746
+ return this.#spentMs;
1747
+ }
1748
+ admit(work) {
1749
+ if (this.#spentMs >= this.#limitMs) return false;
1750
+ const startedAt = this.#now();
1751
+ work();
1752
+ this.#spentMs += this.#now() - startedAt;
1753
+ return true;
1754
+ }
1755
+ };
1756
+
1757
+ // src/world-shore-field.ts
1758
+ function shoreField(heights, resolution, size, level, options = {}) {
1759
+ const n = resolution;
1760
+ const openDepth = options.openDepth ?? 2;
1761
+ const carry = options.carry ?? 18;
1762
+ if (!Number.isInteger(n) || n < 2 || heights.length !== n * n)
1763
+ throw new Error(
1764
+ `TN_SHORE_FIELD_INVALID: heights must hold resolution\xB2 values, received ${heights.length} for ${n}.`
1765
+ );
1766
+ if (!(size > 0) || !Number.isFinite(level) || !(openDepth >= 0) || !(carry >= 0))
1767
+ throw new Error(
1768
+ "TN_SHORE_FIELD_INVALID: size must be positive, level finite, openDepth and carry not negative."
1769
+ );
1770
+ const cell = size / (n - 1);
1771
+ const height2 = (i) => heights[i] ?? 0;
1772
+ const distance = new Float32Array(n * n);
1773
+ for (let i = 0; i < n * n; i++) distance[i] = height2(i) >= level ? 0 : 1e4;
1774
+ const exposed = new Uint8Array(n * n);
1775
+ const queue = [];
1776
+ for (let i = 0; i < n * n; i++) {
1777
+ const row = Math.floor(i / n);
1778
+ const col = i % n;
1779
+ if ((row === 0 || col === 0 || row === n - 1 || col === n - 1) && height2(i) < level - openDepth) {
1780
+ exposed[i] = 1;
1781
+ queue.push(i);
1782
+ }
1783
+ if (col > 0) distance[i] = Math.min(distance[i] ?? 0, (distance[i - 1] ?? 0) + cell);
1784
+ if (row > 0) distance[i] = Math.min(distance[i] ?? 0, (distance[i - n] ?? 0) + cell);
1785
+ }
1786
+ for (let i = n * n - 1; i >= 0; i--) {
1787
+ if (i % n < n - 1) distance[i] = Math.min(distance[i] ?? 0, (distance[i + 1] ?? 0) + cell);
1788
+ if (i < n * (n - 1)) distance[i] = Math.min(distance[i] ?? 0, (distance[i + n] ?? 0) + cell);
1789
+ }
1790
+ for (let head = 0; head < queue.length; head++) {
1791
+ const i = queue[head] ?? 0;
1792
+ for (const next of [i % n > 0 ? i - 1 : -1, i % n < n - 1 ? i + 1 : -1, i - n, i + n]) {
1793
+ if (next < 0 || next >= exposed.length || exposed[next] || height2(next) >= level - openDepth)
1794
+ continue;
1795
+ exposed[next] = 1;
1796
+ queue.push(next);
1797
+ }
1798
+ }
1799
+ for (let pass = 0; pass < Math.ceil(carry / cell); pass++) {
1800
+ const previous = exposed.slice();
1801
+ for (let i = 0; i < exposed.length; i++) {
1802
+ if (height2(i) >= level) continue;
1803
+ if (i % n > 0 && previous[i - 1] || i % n < n - 1 && previous[i + 1] || previous[i - n] || previous[i + n])
1804
+ exposed[i] = 1;
1805
+ }
1806
+ }
1807
+ return { distance, exposed };
1808
+ }
1809
+ function surfaceSampler(field, matrixWorld) {
1810
+ const translation = new Vector3();
1811
+ const rotation = new Quaternion();
1812
+ const scale = new Vector3();
1813
+ matrixWorld.decompose(translation, rotation, scale);
1814
+ const upright = Math.abs(rotation.x) < 1e-6 && Math.abs(rotation.y) < 1e-6 && Math.abs(rotation.z) < 1e-6 && Math.abs(rotation.w - 1) < 1e-6 && scale.x > 0 && scale.x === scale.y && scale.y === scale.z;
1815
+ if (!upright) return () => null;
1816
+ const { origin, width, depth } = field;
1817
+ const slack = 1e-5;
1818
+ const minX = origin.x - width / 2;
1819
+ const maxX = origin.x + width / 2;
1820
+ const minZ = origin.z - depth / 2;
1821
+ const maxZ = origin.z + depth / 2;
1822
+ return (worldX, worldZ) => {
1823
+ const x = (worldX - translation.x) / scale.x;
1824
+ const z = (worldZ - translation.z) / scale.z;
1825
+ if (x < minX - slack || x > maxX + slack || z < minZ - slack || z > maxZ + slack) return null;
1826
+ const clampedX = Math.min(maxX, Math.max(minX, x));
1827
+ const clampedZ = Math.min(maxZ, Math.max(minZ, z));
1828
+ return field.surfaceAt(clampedX, clampedZ) * scale.y + translation.y;
1829
+ };
1830
+ }
1831
+ var bottomFirst = /* @__PURE__ */ new WeakMap();
1832
+ function verticesBottomFirst(geometry) {
1833
+ const cached = bottomFirst.get(geometry);
1834
+ if (cached) return cached;
1835
+ const position = geometry.getAttribute("position");
1836
+ const order = Array.from({ length: position.count }, (_, i) => i).sort(
1837
+ (a, b) => position.getY(a) - position.getY(b)
1838
+ );
1839
+ const xyz3 = new Float32Array(position.count * 3);
1840
+ let reach = 0;
1841
+ order.forEach((i, k) => {
1842
+ xyz3[k * 3] = position.getX(i);
1843
+ xyz3[k * 3 + 1] = position.getY(i);
1844
+ xyz3[k * 3 + 2] = position.getZ(i);
1845
+ reach = Math.max(reach, Math.hypot(position.getX(i), position.getZ(i)));
1846
+ });
1847
+ const entry = { xyz: xyz3, reach };
1848
+ bottomFirst.set(geometry, entry);
1849
+ return entry;
1850
+ }
1851
+ function staticLowestY(geometry, matrix) {
1852
+ const e = matrix.elements;
1853
+ if (e[1] === 0 && e[9] === 0) {
1854
+ if (geometry.boundingBox === null) geometry.computeBoundingBox();
1855
+ const box = geometry.boundingBox;
1856
+ if (box) return (e[5] < 0 ? box.max.y : box.min.y) * e[5] + e[13];
1857
+ }
1858
+ const { xyz: xyz3, reach } = verticesBottomFirst(geometry);
1859
+ const tilt = reach * Math.hypot(e[1], e[9]);
1860
+ const upright = e[5] > 0;
1861
+ let lowest = Number.POSITIVE_INFINITY;
1862
+ for (let k = 0; k < xyz3.length; k += 3) {
1863
+ const y = xyz3[k + 1];
1864
+ if (upright && y * e[5] + e[13] - tilt >= lowest) break;
1865
+ lowest = Math.min(
1866
+ lowest,
1867
+ xyz3[k] * e[1] + y * e[5] + xyz3[k + 2] * e[9] + e[13]
1868
+ );
1869
+ }
1870
+ return lowest;
1871
+ }
1872
+ function footprintGap(geometry, matrix, ground, margin = 0) {
1873
+ if (geometry.boundingBox === null) geometry.computeBoundingBox();
1874
+ const base = geometry.boundingBox?.min.y ?? Number.POSITIVE_INFINITY;
1875
+ const positions = geometry.getAttribute("position");
1876
+ const point = new Vector3();
1877
+ let gap = 0;
1878
+ for (let i = 0; i < positions.count; i++) {
1879
+ if (Math.abs(positions.getY(i) - base) > 1e-5) continue;
1880
+ point.fromBufferAttribute(positions, i).applyMatrix4(matrix);
1881
+ const height2 = ground(point.x, point.z);
1882
+ if (height2 === null)
1883
+ throw new Error(
1884
+ `TN_STATIC_POSE_GROUND: no ground under the footprint at ${point.x}, ${point.z}.`
1885
+ );
1886
+ gap = Math.max(gap, point.y - height2 + margin);
1887
+ }
1888
+ return gap;
1889
+ }
1890
+ function baseRingGap(geometry, matrix, ground, options = {}) {
1891
+ const count3 = options.sectors ?? 16;
1892
+ const rim = options.rim ?? 0.75;
1893
+ if (!Number.isInteger(count3) || count3 < 1 || !(rim >= 0 && rim <= 1))
1894
+ throw new Error(
1895
+ "TN_STATIC_POSE_INVALID: sectors must be a positive integer and rim within 0..1."
1896
+ );
1897
+ if (geometry.boundingBox === null) geometry.computeBoundingBox();
1898
+ const box = geometry.boundingBox;
1899
+ if (!box) throw new Error("TN_STATIC_POSE_INVALID: the geometry has no bounds.");
1900
+ const centre = box.getCenter(new Vector3()).applyMatrix4(matrix);
1901
+ const sectors = Array.from({ length: count3 }, () => ({ reach: 0, vertices: [] }));
1902
+ const vertices = geometry.getAttribute("position");
1903
+ for (let i = 0; i < vertices.count; i++) {
1904
+ const point = new Vector3().fromBufferAttribute(vertices, i).applyMatrix4(matrix);
1905
+ const dx = point.x - centre.x;
1906
+ const dz = point.z - centre.z;
1907
+ const bin = Math.min(
1908
+ count3 - 1,
1909
+ Math.floor((Math.atan2(dz, dx) + Math.PI) / (2 * Math.PI) * count3)
1910
+ );
1911
+ const sector = sectors[bin];
1912
+ if (!sector) continue;
1913
+ sector.reach = Math.max(sector.reach, Math.hypot(dx, dz));
1914
+ sector.vertices.push(point);
1915
+ }
1916
+ let gap = Number.NEGATIVE_INFINITY;
1917
+ let samples = 0;
1918
+ for (const sector of sectors) {
1919
+ let lowest;
1920
+ for (const point of sector.vertices)
1921
+ if (Math.hypot(point.x - centre.x, point.z - centre.z) >= sector.reach * rim && (!lowest || point.y < lowest.y))
1922
+ lowest = point;
1923
+ if (!lowest) continue;
1924
+ const contact = ground(lowest.x, lowest.z);
1925
+ if (contact === null)
1926
+ throw new Error(
1927
+ `TN_STATIC_POSE_GROUND: no ground under the base ring at ${lowest.x}, ${lowest.z}.`
1928
+ );
1929
+ gap = Math.max(gap, lowest.y - contact);
1930
+ samples++;
1931
+ }
1932
+ return { gap, samples };
1933
+ }
1934
+ function meshSections(mesh) {
1935
+ const materials = mesh.material;
1936
+ return Array.isArray(materials) ? mesh.geometry.groups.map((group) => ({
1937
+ material: materials[group.materialIndex ?? 0],
1938
+ group
1939
+ })) : [{ material: materials }];
1940
+ }
1941
+ function sectionGeometry(mesh, box, section, options = {}) {
1942
+ const geometry = baseGeometryOf(mesh).clone().applyMatrix4(mesh.matrixWorld);
1943
+ const { group } = section;
1944
+ if (group) {
1945
+ const start = Math.max(group.start, geometry.drawRange.start);
1946
+ const end = Math.min(
1947
+ group.start + group.count,
1948
+ geometry.drawRange.start + geometry.drawRange.count
1949
+ );
1950
+ geometry.clearGroups();
1951
+ geometry.setDrawRange(start, Math.max(0, end - start));
1952
+ }
1953
+ const centre = box.getCenter(new Vector3());
1954
+ const centred = options.centreXZ === true;
1955
+ geometry.translate(centred ? -centre.x : 0, -box.min.y, centred ? -centre.z : 0);
1956
+ return geometry;
1957
+ }
1958
+ function repairZeroNormals(geometry) {
1959
+ const normals = geometry.getAttribute("normal");
1960
+ let valid = normals !== void 0;
1961
+ for (let i = 0; valid && normals && i < normals.count; i++) {
1962
+ const length7 = Math.hypot(normals.getX(i), normals.getY(i), normals.getZ(i));
1963
+ valid = Number.isFinite(length7) && length7 >= 0.01;
1964
+ }
1965
+ if (!valid) geometry.computeVertexNormals();
1966
+ return !valid;
1967
+ }
1968
+
1969
+ // src/world-warm.ts
1970
+ function warmUnculled(ctx, root, options = {}) {
1971
+ const draws = options.draws ?? 2;
1972
+ if (!Number.isInteger(draws) || draws < 1)
1973
+ throw new Error(
1974
+ `TN_WARM_UNCULLED_INVALID: draws must be a positive integer, received ${draws}.`
1975
+ );
1976
+ const when = options.when ?? (() => true);
1977
+ const cull = (culled) => root.traverse((object) => {
1978
+ object.frustumCulled = culled;
1979
+ });
1980
+ return new Promise((resolve) => {
1981
+ let counted = 0;
1982
+ ctx.beforeRender(() => {
1983
+ if (counted < 0) return;
1984
+ cull(false);
1985
+ if (when()) counted += 1;
1986
+ if (counted <= draws) return;
1987
+ counted = -1;
1988
+ cull(true);
1989
+ resolve();
1990
+ });
1991
+ });
1992
+ }
1447
1993
  var BRIDGE_COORDINATE_EPSILON = 1e-4;
1448
1994
  var BRIDGE_COORDINATE_RELATIVE_EPSILON = 2 ** -22;
1449
1995
  var BRIDGE_STRIP_INDEX_PATTERN = [0, 1, 2, 2, 1, 3, 2, 1, 0, 3, 1, 2];
@@ -1779,13 +2325,10 @@ var TERRAIN_MERGE_BLOCK = 4;
1779
2325
  var TERRAIN_MERGE_FLAG = "TN_TERRAIN_MERGE";
1780
2326
  var TERRAIN_TILE_MARKER_MS = 5e3;
1781
2327
  function terrainMergeOptedOut() {
1782
- const host = globalThis;
1783
- const fromEnv = host.process?.env?.[TERRAIN_MERGE_FLAG];
1784
- if (fromEnv === "0" || fromEnv === "false") return true;
1785
- const query = globalThis.location?.search;
1786
- if (typeof query === "string" && /[?&]tnTerrainMerge=(?:0|false)(?:&|$)/u.test(query))
1787
- return true;
1788
- return host.__tnTerrainMerge === false || host.__tnTerrainMerge === 0 || host.__tnTerrainMerge === "0";
2328
+ return readLaunchFlag(
2329
+ { environment: TERRAIN_MERGE_FLAG, global: "__tnTerrainMerge", query: "tnTerrainMerge" },
2330
+ "off"
2331
+ );
1789
2332
  }
1790
2333
  function blockKeyFor(lod, tileX, tileZ) {
1791
2334
  return `${String(lod)}:${String(Math.floor(tileX / TERRAIN_MERGE_BLOCK))},${String(
@@ -2025,14 +2568,14 @@ function reliefFieldEdge(field) {
2025
2568
  const center = height(field, Math.floor(field.rows / 2), Math.floor(field.columns / 2));
2026
2569
  return Math.abs(center - edgeMean) / relief;
2027
2570
  }
2028
- function slidingExtrema(read, length6, radius, write) {
2571
+ function slidingExtrema(read, length7, radius, write) {
2029
2572
  const minimumDeque = [];
2030
2573
  const maximumDeque = [];
2031
2574
  let minimumHead = 0;
2032
2575
  let maximumHead = 0;
2033
2576
  let right = -1;
2034
- for (let index = 0; index < length6; index += 1) {
2035
- const desiredRight = Math.min(length6 - 1, index + radius);
2577
+ for (let index = 0; index < length7; index += 1) {
2578
+ const desiredRight = Math.min(length7 - 1, index + radius);
2036
2579
  while (right < desiredRight) {
2037
2580
  right += 1;
2038
2581
  const value = read(right);
@@ -2243,14 +2786,11 @@ function summarizeWorldTopology(field) {
2243
2786
  var TERRAIN_VALIDATE_MARKER = "TN_TERRAIN_VALIDATE";
2244
2787
  var TERRAIN_VALIDATE_FLAG = "TN_TERRAIN_VALIDATE";
2245
2788
  function terrainValidationRequested() {
2246
- const host = globalThis;
2247
- const fromEnv = host.process?.env?.[TERRAIN_VALIDATE_FLAG];
2248
- if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
2249
- return true;
2250
- const query = globalThis.location?.search;
2251
- if (typeof query === "string" && /[?&]tnTerrainValidate=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query))
2252
- return true;
2253
- return host.__tnTerrainValidate === true || host.__tnTerrainValidate === "1";
2789
+ return readLaunchFlag({
2790
+ environment: TERRAIN_VALIDATE_FLAG,
2791
+ global: "__tnTerrainValidate",
2792
+ query: "tnTerrainValidate"
2793
+ });
2254
2794
  }
2255
2795
  function appendQuad(indices, topLeft, bottomLeft, topRight, bottomRight) {
2256
2796
  indices.push(topLeft, bottomLeft, topRight, topRight, bottomLeft, bottomRight);
@@ -2972,6 +3512,7 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
2972
3512
  #sampleHeight;
2973
3513
  #streamRadius;
2974
3514
  #extent;
3515
+ #hole;
2975
3516
  /** Diagnostics outlive construction; their canonical field is never used by resident tiles. */
2976
3517
  #topology;
2977
3518
  #topologyBytes = 0;
@@ -3068,6 +3609,7 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3068
3609
  this.skirtDepth = positive3(options.skirtDepth ?? this.tileSize, "skirtDepth");
3069
3610
  this.#streamRadius = integerAtLeast(options.streamRadius ?? 1, 0, "streamRadius");
3070
3611
  this.#extent = options.extent;
3612
+ this.#hole = options.hole;
3071
3613
  this.#receiveShadow = options.receiveShadow === true;
3072
3614
  this.#colliderRadius = integerAtLeast(
3073
3615
  options.colliderRadius ?? this.#streamRadius,
@@ -3288,6 +3830,35 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3288
3830
  getTile(key) {
3289
3831
  return this.#resident.get(key);
3290
3832
  }
3833
+ /**
3834
+ * Half-width, in metres, of the largest square of tiles around `position`'s tile that is fully
3835
+ * settled: each tile in it is resident, or is one the stream never draws (wholly inside `hole` or
3836
+ * past `extent`). Zero while the tile under `position` is still building. A game that draws other
3837
+ * ground where the tiles have not arrived (a collar, a far mesh) clips it to this square, so a tile
3838
+ * still building shows that ground, never a hole.
3839
+ *
3840
+ * @situation a hole or a flicker where streamed terrain tiles are still building
3841
+ * @situation split the ground between streamed tiles and a far mesh around the player
3842
+ * @constraint reads residency only; call it after `follow` in the same frame
3843
+ * @example split.half.value = tiles.settledHalf(player.position);
3844
+ */
3845
+ settledHalf(position) {
3846
+ const centerX = Math.floor(
3847
+ (finite4(position.x, "settled x") + this.tileSize / 2) / this.tileSize
3848
+ );
3849
+ const centerZ = Math.floor(
3850
+ (finite4(position.z, "settled z") + this.tileSize / 2) / this.tileSize
3851
+ );
3852
+ const settled = (tileX, tileZ) => this.#resident.has(keyFor(tileX, tileZ)) || !this.#touchesExtent(tileX, tileZ);
3853
+ let ring = -1;
3854
+ for (let k = 0; k <= this.#streamRadius; k += 1) {
3855
+ for (let d = -k; d <= k; d += 1)
3856
+ if (!settled(centerX + d, centerZ - k) || !settled(centerX + d, centerZ + k) || !settled(centerX - k, centerZ + d) || !settled(centerX + k, centerZ + d))
3857
+ return ring < 0 ? 0 : (ring + 0.5) * this.tileSize;
3858
+ ring = k;
3859
+ }
3860
+ return (ring + 0.5) * this.tileSize;
3861
+ }
3291
3862
  /**
3292
3863
  * Move residency to the followed point: admit, evict and re-level every tile.
3293
3864
  *
@@ -3503,19 +4074,22 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3503
4074
  if (view !== void 0 && next !== void 0 && finest !== void 0 && bounds != null) {
3504
4075
  finest.mesh.updateWorldMatrix(true, false);
3505
4076
  const sphere = worldSphere(bounds, finest.mesh);
3506
- const depth = conservativeViewDepth(
4077
+ const { degenerate, depth } = selectLodFor(
3507
4078
  view.camera,
3508
- sphere.center,
3509
- sphere.radius,
4079
+ sphere,
3510
4080
  view.camera.near ?? 0
3511
4081
  );
3512
4082
  const errorPixels = projectedLodError(
3513
4083
  next.surfaceError * finest.mesh.matrixWorld.getMaxScaleOnAxis(),
3514
4084
  view.camera,
3515
4085
  view.viewportHeight,
3516
- depth.depth
4086
+ depth
3517
4087
  );
3518
- projection = { ...depth, ...Number.isFinite(errorPixels) ? { errorPixels } : {} };
4088
+ projection = {
4089
+ degenerate,
4090
+ depth,
4091
+ ...Number.isFinite(errorPixels) ? { errorPixels } : {}
4092
+ };
3519
4093
  }
3520
4094
  return {
3521
4095
  key: tile.key,
@@ -3829,11 +4403,17 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3829
4403
  #selectLod(tile, distance, countTransition = true) {
3830
4404
  this.#setLodLevel(tile, this.#targetLod(tile, distance), countTransition);
3831
4405
  }
3832
- /** Whether the tile's square overlaps the ground at all; always true when no extent was given. */
4406
+ /**
4407
+ * Whether the tile's square overlaps the ground at all and is not wholly inside the hole; always
4408
+ * true when neither was given.
4409
+ */
3833
4410
  #touchesExtent(tileX, tileZ) {
4411
+ const half = this.tileSize / 2;
4412
+ const hole = this.#hole;
4413
+ if (hole !== void 0 && tileX * this.tileSize - half >= hole.minX && tileX * this.tileSize + half <= hole.maxX && tileZ * this.tileSize - half >= hole.minZ && tileZ * this.tileSize + half <= hole.maxZ)
4414
+ return false;
3834
4415
  const extent = this.#extent;
3835
4416
  if (extent === void 0) return true;
3836
- const half = this.tileSize / 2;
3837
4417
  return tileX * this.tileSize + half > extent.minX && tileX * this.tileSize - half < extent.maxX && tileZ * this.tileSize + half > extent.minZ && tileZ * this.tileSize - half < extent.maxZ;
3838
4418
  }
3839
4419
  #setLodView(view) {
@@ -3853,10 +4433,9 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3853
4433
  if (finest === void 0 || bounds == null) return 0;
3854
4434
  finest.mesh.updateWorldMatrix(true, false);
3855
4435
  const sphere = worldSphere(bounds, finest.mesh);
3856
- const depth = conservativeViewDepth(
4436
+ const { depth, degenerate } = selectLodFor(
3857
4437
  view.camera,
3858
- sphere.center,
3859
- sphere.radius,
4438
+ sphere,
3860
4439
  view.camera.near ?? 0
3861
4440
  );
3862
4441
  const scale = finest.mesh.matrixWorld.getMaxScaleOnAxis();
@@ -3864,7 +4443,7 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3864
4443
  this.#lodErrors[index] = tile.levels[index].surfaceError * scale;
3865
4444
  this.#lodErrors.length = floor2 + 1;
3866
4445
  return selectLodLevel(this.#lodErrors, tile.lodLevel, view.maxPixelError, view.hysteresis, [
3867
- { ...view, ...depth }
4446
+ { ...view, degenerate, depth }
3868
4447
  ]);
3869
4448
  }
3870
4449
  #syncMorphEdges() {
@@ -4940,8 +5519,8 @@ function cellPlacements(placements, run) {
4940
5519
  if (!Number.isInteger(run.offset) || !Number.isInteger(run.count) || run.offset < 0 || run.count < 0)
4941
5520
  throw new RangeError("Placement run offset and count must be non-negative integers.");
4942
5521
  const start = run.offset * PLACEMENT_RECORD_BYTES;
4943
- const length6 = run.count * PLACEMENT_RECORD_BYTES;
4944
- if (start + length6 > placements.byteLength)
5522
+ const length7 = run.count * PLACEMENT_RECORD_BYTES;
5523
+ if (start + length7 > placements.byteLength)
4945
5524
  throw new RangeError(
4946
5525
  `Placement run [${String(run.offset)}, ${String(run.offset + run.count)}) reaches past the ${String(placements.byteLength)}-byte buffer.`
4947
5526
  );
@@ -5563,24 +6142,15 @@ function packageAssetPath(directory, path) {
5563
6142
  return `${prefix}${segments.join("/")}`;
5564
6143
  }
5565
6144
  async function fetchResolved(assets, path) {
5566
- let attempted = false;
5567
- let everyFetchRejected = true;
5568
- let lastFetchError;
5569
- for (const candidate of await assets.resolve(path)) {
5570
- attempted = true;
5571
- let response;
5572
- try {
5573
- response = await fetch(candidate);
5574
- } catch (error) {
5575
- lastFetchError = error;
5576
- continue;
5577
- }
5578
- everyFetchRejected = false;
5579
- if (response.ok) return response;
6145
+ try {
6146
+ return await fetchAsset(assets, path);
6147
+ } catch (error) {
6148
+ const cause = error instanceof Error ? error.cause : void 0;
6149
+ throw new Error(
6150
+ `loadTerrainSplat: '${path}' is not served.`,
6151
+ cause === void 0 ? void 0 : { cause }
6152
+ );
5580
6153
  }
5581
- if (attempted && everyFetchRejected)
5582
- throw new Error(`loadTerrainSplat: '${path}' is not served.`, { cause: lastFetchError });
5583
- throw new Error(`loadTerrainSplat: '${path}' is not served.`);
5584
6154
  }
5585
6155
  function splatArray(bytes, size, planes) {
5586
6156
  if (bytes.byteLength < planes * size * size * 4)
@@ -6115,11 +6685,24 @@ var TEXTURE_SLOTS = [
6115
6685
  "emissiveMap",
6116
6686
  "alphaMap"
6117
6687
  ];
6688
+ var unnamedIds = /* @__PURE__ */ new WeakMap();
6689
+ var nextUnnamedId = 0;
6690
+ function sourceId(texture3) {
6691
+ const uuid = texture3.source?.uuid;
6692
+ if (uuid !== void 0) return uuid;
6693
+ let id = unnamedIds.get(texture3);
6694
+ if (id === void 0) {
6695
+ id = nextUnnamedId++;
6696
+ unnamedIds.set(texture3, id);
6697
+ }
6698
+ return `#${String(id)}`;
6699
+ }
6118
6700
  function textureKey(texture3) {
6119
6701
  if (texture3 === null || texture3 === void 0) return "-";
6120
6702
  const image = texture3.image;
6121
6703
  const mips = texture3.mipmaps;
6122
- return `${texture3.name}:${String(image?.width ?? 0)}x${String(image?.height ?? 0)}:${String(mips?.[0]?.data?.byteLength ?? 0)}:${texture3.flipY ? 1 : 0}`;
6704
+ const id = texture3.name !== "" ? texture3.name : `source:${sourceId(texture3)}`;
6705
+ return `${id}:${String(image?.width ?? 0)}x${String(image?.height ?? 0)}:${String(mips?.[0]?.data?.byteLength ?? 0)}:${texture3.flipY ? 1 : 0}`;
6123
6706
  }
6124
6707
  function materialKey(material) {
6125
6708
  const fields = material;
@@ -7027,12 +7610,7 @@ var CellChunks = class {
7027
7610
  const scale = cellProxyWorldScale(matrixWorld);
7028
7611
  const sphere = this.#host.worldSphere(state.prepared.bounds);
7029
7612
  sphere.radius = state.prepared.bounds.radius * scale;
7030
- const view = camera === void 0 ? void 0 : conservativeViewDepth(
7031
- camera,
7032
- sphere.center,
7033
- sphere.radius,
7034
- Reflect.get(camera, "near") ?? 0.1
7035
- );
7613
+ const view = camera === void 0 ? void 0 : selectLodFor(camera, sphere, Reflect.get(camera, "near") ?? LOD_NEAR_PLANE);
7036
7614
  const height2 = renderer?.domElement.height;
7037
7615
  const selected = state.selector.select({
7038
7616
  sourceReady: cellLoaded(cell),
@@ -7315,16 +7893,6 @@ function cellLoaded(cell) {
7315
7893
  function clusterOf(cellX, cellZ, cellsPerCluster) {
7316
7894
  return `${String(Math.floor(cellX / cellsPerCluster))},${String(Math.floor(cellZ / cellsPerCluster))}`;
7317
7895
  }
7318
- function crossesGate(gates, low, high) {
7319
- let start = 0;
7320
- let end = gates.length;
7321
- while (start < end) {
7322
- const middle = start + end >> 1;
7323
- if (gates[middle] < low) start = middle + 1;
7324
- else end = middle;
7325
- }
7326
- return start < gates.length && gates[start] <= high;
7327
- }
7328
7896
  var PLACED_STRIDE = 7;
7329
7897
  function positiveInteger(value, name) {
7330
7898
  if (!Number.isInteger(value) || value < 1)
@@ -7395,10 +7963,11 @@ function impostorBounds(parts) {
7395
7963
  whole.union(localBox);
7396
7964
  any = true;
7397
7965
  }
7398
- if (!any) return { center: new Vector3(), radius: 0.5 };
7966
+ if (!any) return { center: new Vector3(), radius: 0.5, halfExtents: new Vector3(0.5, 0.5, 0.5) };
7399
7967
  const center = whole.getCenter(new Vector3());
7400
7968
  const radius = whole.getBoundingSphere(new Sphere()).radius;
7401
- return { center, radius: radius > 0 ? radius : 0.5 };
7969
+ const halfExtents = whole.getSize(new Vector3()).multiplyScalar(0.5);
7970
+ return { center, radius: radius > 0 ? radius : 0.5, halfExtents };
7402
7971
  }
7403
7972
  function mipChainBytes(pixels, depth, levels) {
7404
7973
  let bytes = 0;
@@ -7681,6 +8250,13 @@ var GEOMETRY_MAPS = [
7681
8250
  "thicknessMap",
7682
8251
  "transmissionMap"
7683
8252
  ];
8253
+ var SURFACE_NODES = [
8254
+ "aoNode",
8255
+ "emissiveNode",
8256
+ "roughnessNode",
8257
+ "metalnessNode",
8258
+ "maskNode"
8259
+ ];
7684
8260
  var INSTANCE_COLUMNS = /* @__PURE__ */ new WeakMap();
7685
8261
  function signNotZeroNode(value) {
7686
8262
  return select(value.greaterThanEqual(0), float(1), float(-1));
@@ -7827,6 +8403,7 @@ var WorldImpostorSurface = class {
7827
8403
  throw new Error("WorldImpostorSurface requires a baked atlas.");
7828
8404
  const material = cloneLitMaterial(options.source);
7829
8405
  for (const key of GEOMETRY_MAPS) Reflect.set(material, key, null);
8406
+ for (const key of SURFACE_NODES) Reflect.set(material, key, null);
7830
8407
  material.vertexColors = false;
7831
8408
  material.opacity = 1;
7832
8409
  material.opacityNode = null;
@@ -7839,6 +8416,7 @@ var WorldImpostorSurface = class {
7839
8416
  material.needsUpdate = true;
7840
8417
  const centerUniform = uniform(center);
7841
8418
  const radiusUniform = uniform(radius);
8419
+ const halfUniform = options.halfExtents === void 0 ? void 0 : uniform(options.halfExtents.clone());
7842
8420
  const cull = options.cull === true;
7843
8421
  const name = `WorldImpostorSurface${surfaceId}`;
7844
8422
  surfaceId += 1;
@@ -7856,7 +8434,14 @@ var WorldImpostorSurface = class {
7856
8434
  const dAsset = normalize(asMat3(view).inverse().mul(eyeView));
7857
8435
  const basis = frameBasisNode(dAsset);
7858
8436
  const corner = positionGeometry.xy;
7859
- const rel = basis.right.mul(corner.x).add(basis.up.mul(corner.y)).mul(radiusUniform);
8437
+ const extent = halfUniform ? vec2(
8438
+ min(radiusUniform, length(halfUniform.xz).mul(QUAD_ACROSS_SLACK)),
8439
+ min(
8440
+ radiusUniform,
8441
+ abs(basis.up.x).mul(halfUniform.x).add(abs(basis.up.y).mul(halfUniform.y)).add(abs(basis.up.z).mul(halfUniform.z)).mul(QUAD_UP_SLACK)
8442
+ )
8443
+ ) : vec2(radiusUniform, radiusUniform);
8444
+ const rel = basis.right.mul(corner.x.mul(extent.x)).add(basis.up.mul(corner.y.mul(extent.y)));
7860
8445
  const gated = cull ? rel.mul(
7861
8446
  select(
7862
8447
  orthographicNode(),
@@ -7892,6 +8477,7 @@ var WorldImpostorSurface = class {
7892
8477
  (_inputs, builder) => transformNormal(fragment.normalAsset, instanceViewMatrixNode(builder))
7893
8478
  )();
7894
8479
  material.positionNode = positionNode;
8480
+ material.castShadowPositionNode = null;
7895
8481
  const geometry = new BufferGeometry();
7896
8482
  geometry.setAttribute(
7897
8483
  "position",
@@ -7964,7 +8550,15 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
7964
8550
  const uvs = [];
7965
8551
  const colors = [];
7966
8552
  const normals = [];
7967
- for (let index = 0; index < 3; index += 1) {
8553
+ const [wa, wb, wc] = weights;
8554
+ const pickA = wa.greaterThanEqual(wb).and(wa.greaterThanEqual(wc));
8555
+ const pickB = wb.greaterThanEqual(wc);
8556
+ const [xa, xb, xc] = cellX;
8557
+ const [ya, yb, yc] = cellY;
8558
+ cellX.push(select(pickA, xa, select(pickB, xb, xc)));
8559
+ cellY.push(select(pickA, ya, select(pickB, yb, yc)));
8560
+ let marched;
8561
+ for (let index = 3; index < 4; index += 1) {
7968
8562
  const direction = octahedralViewNode(
7969
8563
  cellX[index],
7970
8564
  cellY[index],
@@ -7981,6 +8575,7 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
7981
8575
  const hit = Fn(() => {
7982
8576
  const found = float(0).toVar();
7983
8577
  const hitUv = vec2(2).toVar();
8578
+ const hitT = float(0).toVar();
7984
8579
  const previousGap = float(0).toVar();
7985
8580
  const previousAlpha = float(0).toVar();
7986
8581
  const previousT = radiusUniform.toVar();
@@ -8034,6 +8629,7 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
8034
8629
  ),
8035
8630
  () => {
8036
8631
  hitUv.assign(u);
8632
+ hitT.assign(front.add(back).mul(0.5));
8037
8633
  found.assign(1);
8038
8634
  }
8039
8635
  );
@@ -8046,11 +8642,22 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
8046
8642
  Break();
8047
8643
  });
8048
8644
  });
8049
- return vec3(hitUv, found);
8645
+ return vec4(hitUv, found, hitT);
8050
8646
  })();
8051
- uvs.push(hit.xy);
8052
- colors.push(colorMap.depth(layer).sample(hit.xy).mul(hit.z).toVar());
8053
- normals.push(normalMap.depth(layer).sample(hit.xy).mul(hit.z).toVar());
8647
+ marched = hit;
8648
+ }
8649
+ const surface = marched;
8650
+ const rayOut = normalize(select(orthographicNode(), dirVarying, dirVarying.sub(relVarying)));
8651
+ const hitPoint = relVarying.add(rayOut.mul(surface.w));
8652
+ for (let index = 0; index < 3; index += 1) {
8653
+ const basis = frameBasisNode(
8654
+ octahedralViewNode(cellX[index], cellY[index], grid)
8655
+ );
8656
+ const layer = cellY[index].mul(grid).add(cellX[index]).toInt();
8657
+ const uv2 = vec2(dot(hitPoint, basis.right), dot(hitPoint, basis.up).negate()).div(radiusUniform).mul(0.5).add(0.5);
8658
+ uvs.push(uv2);
8659
+ colors.push(colorMap.depth(layer).sample(uv2).mul(surface.z).toVar());
8660
+ normals.push(normalMap.depth(layer).sample(uv2).mul(surface.z).toVar());
8054
8661
  }
8055
8662
  const [w0, w1, w2] = weights;
8056
8663
  const [c0, c1, c2] = colors;
@@ -8067,6 +8674,8 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
8067
8674
  threshold: mipThresholdNode(uvs, atlas.pixels, cutoff, mipScale)
8068
8675
  };
8069
8676
  }
8677
+ var QUAD_ACROSS_SLACK = 1.25;
8678
+ var QUAD_UP_SLACK = 1.1;
8070
8679
  var LOD_TEMPORAL_LAG = 0.5;
8071
8680
  function advanceTemporalLod(state, eye, now, lag = LOD_TEMPORAL_LAG) {
8072
8681
  if (!Number.isFinite(state.toTime) || now < state.toTime) {
@@ -8085,14 +8694,57 @@ function advanceTemporalLod(state, eye, now, lag = LOD_TEMPORAL_LAG) {
8085
8694
  const window = state.toTime - state.fromTime;
8086
8695
  state.alpha = window > 0 ? Math.min(1, Math.max(0, (now - lag - state.fromTime) / window)) : 1;
8087
8696
  }
8697
+ function lodFadedPast(distances, level, width) {
8698
+ const gate = level + 1;
8699
+ const at = distances[gate];
8700
+ if (at === void 0) return void 0;
8701
+ let span2 = Math.min(at * width, (at - distances[gate - 1]) * width);
8702
+ const next = distances[gate + 1];
8703
+ if (next !== void 0) span2 = Math.min(span2, (next - at) * width);
8704
+ return at + 0.75 * span2;
8705
+ }
8706
+ var lodCollapseArmed;
8707
+ var makeLodCollapseSwitch = () => uniform(1).setGroup(renderGroup);
8708
+ var lodCollapseSwitch;
8709
+ function lodCollapseNode() {
8710
+ lodCollapseArmed ??= readLaunchFlag({
8711
+ environment: "TN_LOD_COLLAPSE",
8712
+ query: "lodCollapse",
8713
+ global: "__tnLodCollapse"
8714
+ });
8715
+ if (!lodCollapseArmed) return void 0;
8716
+ lodCollapseSwitch ??= makeLodCollapseSwitch();
8717
+ return lodCollapseSwitch;
8718
+ }
8719
+ function syncLodCollapse() {
8720
+ if (lodCollapseSwitch === void 0) return;
8721
+ const live = Reflect.get(globalThis, "__tnLodCollapse");
8722
+ if (typeof live === "boolean") lodCollapseSwitch.value = live ? 1 : 0;
8723
+ }
8724
+ function collapseFadedVertices(material, on, gate) {
8725
+ let faded = on.greaterThan(0.5);
8726
+ for (const distance of gate.distances) faded = faded.and(distance.greaterThanEqual(gate.past));
8727
+ if (gate.publishedRanges) {
8728
+ const range = attribute("tnPublishedLodRange", "vec4");
8729
+ faded = faded.and(range.y.greaterThan(gate.lod));
8730
+ if (gate.clock !== void 0)
8731
+ faded = faded.and(
8732
+ range.z.lessThan(0).or(gate.clock.sub(range.w).div(LOD_TEMPORAL_LAG).greaterThanEqual(1)).or(range.z.sub(gate.lod).abs().greaterThanEqual(0.5))
8733
+ );
8734
+ }
8735
+ const position = material.positionNode ?? positionGeometry;
8736
+ material.positionNode = select(faded, vec3(0, 0, 0), position);
8737
+ }
8088
8738
  function worldLodMaterial(source, local, distances, level, width, eye, distanceBias, spatial, publishedRanges = false, clock, temporal, shadowFloor = 0) {
8089
8739
  const material = cloneLitMaterial(source);
8090
8740
  const inverse = uniform(local.clone().invert());
8091
8741
  const root = Fn(
8092
8742
  (_inputs, builder) => userInstanceMatrix(builder).mul(inverse).mul(vec4(0, 0, 0, 1)).xyz
8093
8743
  )();
8094
- const origin = varying(floor(root.mul(16).add(0.5)).div(16));
8095
- const distanceTo = (at) => (spatial ? length(origin.sub(at)) : length(origin.xz.sub(at.xz))).mul(distanceBias);
8744
+ const quantised = floor(root.mul(16).add(0.5)).div(16);
8745
+ const origin = varying(quantised);
8746
+ const distanceFrom = (point, at) => (spatial ? length(point.sub(at)) : length(point.xz.sub(at.xz))).mul(distanceBias);
8747
+ const distanceTo = (at) => distanceFrom(origin, at);
8096
8748
  const distance = distanceTo(eye);
8097
8749
  const random = fract(sin(dot(origin.xz, vec2(12.9898, 78.233))).mul(43758.5453));
8098
8750
  const noise = fract(sin(dot(floor(screenCoordinate.xy), vec2(12.9898, 78.233))).mul(43758.5453));
@@ -8104,17 +8756,17 @@ function worldLodMaterial(source, local, distances, level, width, eye, distanceB
8104
8756
  let mask2 = always;
8105
8757
  for (let gate = first; gate < distances.length; gate++) {
8106
8758
  const at = gates[gate];
8107
- let span = at.mul(width).min(at.sub(gates[gate - 1]).mul(width));
8759
+ let span2 = at.mul(width).min(at.sub(gates[gate - 1]).mul(width));
8108
8760
  if (gate + 1 < distances.length)
8109
- span = span.min(gates[gate + 1].sub(at).mul(width));
8110
- const mix2 = mixAt(at, span);
8761
+ span2 = span2.min(gates[gate + 1].sub(at).mul(width));
8762
+ const mix2 = mixAt(at, span2);
8111
8763
  const fadeIn = published === void 0 ? noise.lessThan(mix2) : select(published.x.lessThan(lod), noise.lessThan(mix2), always);
8112
8764
  const fadeOut = published === void 0 ? noise.greaterThanEqual(mix2) : select(published.y.greaterThan(lod), noise.greaterThanEqual(mix2), always);
8113
8765
  mask2 = mask2.and(lod.notEqual(gate).or(fadeIn)).and(lod.notEqual(gate - 1).or(fadeOut));
8114
8766
  }
8115
8767
  return mask2;
8116
8768
  };
8117
- const rampAt = (at, span) => distance.sub(at).div(span).add(0.5).add(random.sub(0.5).mul(0.5)).clamp(0, 1);
8769
+ const rampAt = (at, span2) => distance.sub(at).div(span2).add(0.5).add(random.sub(0.5).mul(0.5)).clamp(0, 1);
8118
8770
  const mask = levelMask(rampAt);
8119
8771
  const shadow = shadowFloor > 0 ? lod.greaterThanEqual(shadowFloor).and(levelMask(rampAt, shadowFloor + 1)) : mask;
8120
8772
  const past = (eyeAt, at) => select(distanceTo(eyeAt).greaterThan(at), float(1), float(0));
@@ -8132,6 +8784,17 @@ function worldLodMaterial(source, local, distances, level, width, eye, distanceB
8132
8784
  }
8133
8785
  material.maskNode = material.maskNode ? material.maskNode.and(colour) : colour;
8134
8786
  material.maskShadowNode = material.maskShadowNode ? material.maskShadowNode.and(shadow) : shadow;
8787
+ const collapseOn = lodCollapseNode();
8788
+ if (collapseOn !== void 0)
8789
+ collapseFadedVertices(material, collapseOn, {
8790
+ past: uniform((lodFadedPast(distances, level, width) ?? 1e30) * 1.001),
8791
+ distances: (temporal === void 0 ? [eye] : [eye, temporal.from, temporal.to]).map(
8792
+ (at) => distanceFrom(quantised, at)
8793
+ ),
8794
+ lod,
8795
+ publishedRanges,
8796
+ clock
8797
+ });
8135
8798
  if (publishedRanges) material.userData.tnPublishedLodRange = true;
8136
8799
  return material;
8137
8800
  }
@@ -8421,9 +9084,9 @@ var CellImpostors = class {
8421
9084
  const staged = impostorParts(parts);
8422
9085
  try {
8423
9086
  this.#baker.begin(asset.id, staged, { pixels: IMPOSTOR_FRAME_PIXELS });
8424
- } catch {
9087
+ } catch (error) {
8425
9088
  this.#host.addFailure();
8426
- this.#reportImpostor(asset, "begin-failed");
9089
+ this.#reportImpostor(asset, "begin-failed", error);
8427
9090
  continue;
8428
9091
  }
8429
9092
  this.#impostorReservedBytes = IMPOSTOR_ATLAS_BYTES;
@@ -8443,11 +9106,11 @@ var CellImpostors = class {
8443
9106
  atlas = this.#baker.step(raw);
8444
9107
  if (atlas !== void 0 || this.#baker.pending?.view === view) break;
8445
9108
  }
8446
- } catch {
9109
+ } catch (error) {
8447
9110
  this.#host.addFailure();
8448
9111
  this.#impostorBaking = void 0;
8449
9112
  this.#impostorReservedBytes = 0;
8450
- this.#reportImpostor(baking, "bake-failed");
9113
+ this.#reportImpostor(baking, "bake-failed", error);
8451
9114
  return;
8452
9115
  }
8453
9116
  if (atlas === void 0) return;
@@ -8500,6 +9163,7 @@ var CellImpostors = class {
8500
9163
  atlas,
8501
9164
  bytes: atlas.bytes,
8502
9165
  center: bounds.center,
9166
+ halfExtents: bounds.halfExtents,
8503
9167
  key,
8504
9168
  radius: bounds.radius,
8505
9169
  users: 0
@@ -8532,12 +9196,13 @@ var CellImpostors = class {
8532
9196
  alphaTest: source.alphaTest,
8533
9197
  atlas: record.atlas,
8534
9198
  center: record.center,
9199
+ halfExtents: record.halfExtents,
8535
9200
  radius: record.radius,
8536
9201
  source: source.source
8537
9202
  });
8538
- } catch {
9203
+ } catch (error) {
8539
9204
  this.#host.addFailure();
8540
- this.#reportImpostor(asset, "surface-failed");
9205
+ this.#reportImpostor(asset, "surface-failed", error);
8541
9206
  return;
8542
9207
  }
8543
9208
  const switchAt = asset.definition.impostorDistance ?? 2 * record.radius * this.#autoLodPixelsPerUnit / IMPOSTOR_FRAME_PIXELS;
@@ -8720,6 +9385,7 @@ var CellImpostors = class {
8720
9385
  atlas: cohort.record.atlas,
8721
9386
  center: cohort.record.center,
8722
9387
  cull: true,
9388
+ halfExtents: cohort.record.halfExtents,
8723
9389
  radius: cohort.record.radius,
8724
9390
  source: cohort.source
8725
9391
  });
@@ -8834,6 +9500,7 @@ var CellImpostors = class {
8834
9500
  const mesh = new InstancedMesh(surface.geometry, surface.material, capacity);
8835
9501
  mesh.count = capacity;
8836
9502
  mesh.frustumCulled = false;
9503
+ mesh.renderOrder = 1;
8837
9504
  mesh.name = `tn-far:${assetId}`;
8838
9505
  mesh.userData.tnDrawSource = "proxies";
8839
9506
  if (surface.cull) this.#attachFarCull(surface.geometry, capacity);
@@ -9107,13 +9774,14 @@ var CellImpostors = class {
9107
9774
  * `TN_WORLD_IMPOSTOR`, one bounded line per asset: its terminal level, the metres it takes over at,
9108
9775
  * the views the atlas holds, its GPU bytes, and — when the world can name it — why it did not land.
9109
9776
  */
9110
- #reportImpostor(asset, reason) {
9777
+ /** One line per asset; a failure carries its error, so the cause is on the line and not swallowed. */
9778
+ #reportImpostor(asset, reason, error) {
9111
9779
  if (this.#impostorReported.has(asset.id)) return;
9112
9780
  this.#impostorReported.add(asset.id);
9113
9781
  const impostor = asset.impostor;
9114
9782
  const atlas = impostor?.record.atlas ?? this.#baker.pending?.atlas;
9115
9783
  console.info(
9116
- `${WORLD_IMPOSTOR_MARKER} asset=${asset.id} level=${String(asset.levels.length - 1)} switch=${(asset.distances.at(-1) ?? 0).toFixed(1)} views=${String(atlas === void 0 ? 0 : IMPOSTOR_VIEWS)} bytes=${String(atlas?.bytes ?? 0)} reason=${reason}`
9784
+ `${WORLD_IMPOSTOR_MARKER} asset=${asset.id} level=${String(asset.levels.length - 1)} switch=${(asset.distances.at(-1) ?? 0).toFixed(1)} views=${String(atlas === void 0 ? 0 : IMPOSTOR_VIEWS)} bytes=${String(atlas?.bytes ?? 0)} reason=${reason}${error === void 0 ? "" : ` error=${error instanceof Error ? error.message : String(error)}`}`
9117
9785
  );
9118
9786
  }
9119
9787
  };
@@ -9123,75 +9791,6 @@ function cullDistance(maxDistance) {
9123
9791
  return maxDistance === void 0 ? void 0 : maxDistance - maxDistance / 8;
9124
9792
  }
9125
9793
 
9126
- // src/world-load-limiter.ts
9127
- var ModelLoadLimiter = class {
9128
- #concurrency;
9129
- #queue = [];
9130
- #inFlight = 0;
9131
- constructor(concurrency) {
9132
- this.#concurrency = concurrency;
9133
- }
9134
- get inFlight() {
9135
- return this.#inFlight;
9136
- }
9137
- get queued() {
9138
- return this.#queue.length;
9139
- }
9140
- load(run, wanted) {
9141
- return new Promise((resolve, reject) => {
9142
- this.#queue.push({ reject, resolve, run, wanted });
9143
- this.#pump();
9144
- });
9145
- }
9146
- #pump() {
9147
- while (this.#inFlight < this.#concurrency && this.#queue.length > 0) {
9148
- const job = this.#queue.shift();
9149
- if (!job.wanted()) {
9150
- job.resolve(void 0);
9151
- continue;
9152
- }
9153
- this.#inFlight += 1;
9154
- try {
9155
- job.run().then(
9156
- (model) => {
9157
- this.#inFlight -= 1;
9158
- job.resolve(model);
9159
- this.#pump();
9160
- },
9161
- (error) => {
9162
- this.#inFlight -= 1;
9163
- job.reject(error);
9164
- this.#pump();
9165
- }
9166
- );
9167
- } catch (error) {
9168
- this.#inFlight -= 1;
9169
- job.reject(error);
9170
- this.#pump();
9171
- }
9172
- }
9173
- }
9174
- };
9175
- var AdmissionBudget = class {
9176
- #limitMs;
9177
- #now;
9178
- #spentMs = 0;
9179
- constructor(limitMs, now) {
9180
- this.#limitMs = limitMs;
9181
- this.#now = now;
9182
- }
9183
- get spentMs() {
9184
- return this.#spentMs;
9185
- }
9186
- admit(work) {
9187
- if (this.#spentMs >= this.#limitMs) return false;
9188
- const startedAt = this.#now();
9189
- work();
9190
- this.#spentMs += this.#now() - startedAt;
9191
- return true;
9192
- }
9193
- };
9194
-
9195
9794
  // src/world-cell-models.ts
9196
9795
  async function loadModelWith(assets, path, sceneName) {
9197
9796
  const gltf = await assets.model(path, {
@@ -9225,7 +9824,7 @@ function renderableParts(model, surfaceFor) {
9225
9824
  if (object instanceof SkinnedMesh || !(object instanceof Mesh)) return;
9226
9825
  const material = Array.isArray(object.material) ? object.material[0] : object.material;
9227
9826
  if (object.geometry === void 0 || material === void 0) return;
9228
- const surface = surfaceFor(material);
9827
+ const surface = surfaceFor(material, object.geometry);
9229
9828
  parts.push({
9230
9829
  geometry: object.geometry,
9231
9830
  local: local.multiplyMatrices(rootInverse, object.matrixWorld).clone(),
@@ -9419,6 +10018,7 @@ var CellModels = class _CellModels {
9419
10018
  /** The screen-space error budget a synthesized level is switched at; see `autoLod`. */
9420
10019
  #autoLodMaxPixelError;
9421
10020
  #transparentScatter;
10021
+ #partMaterial;
9422
10022
  constructor(init, settings, host) {
9423
10023
  this.#host = host;
9424
10024
  this.#lodHysteresis = settings.lodHysteresis;
@@ -9432,6 +10032,7 @@ var CellModels = class _CellModels {
9432
10032
  this.#loader = init.assets ?? createAssetLoader();
9433
10033
  this.#ownsLoader = init.ownsAssets ?? init.assets === void 0;
9434
10034
  this.#loadModel = init.loadModel;
10035
+ this.#partMaterial = init.partMaterial;
9435
10036
  this.#limiter = new ModelLoadLimiter(
9436
10037
  positiveInteger(init.concurrency ?? WORLD_LOAD_CONCURRENCY, "concurrency")
9437
10038
  );
@@ -9555,7 +10156,15 @@ var CellModels = class _CellModels {
9555
10156
  /** One loaded model's drawable parts, or `undefined` when it carries nothing to draw. */
9556
10157
  #partsOf(model) {
9557
10158
  if (model === void 0) return void 0;
9558
- const parts = renderableParts(model, (material) => this.#surfaceFor(material));
10159
+ let parts;
10160
+ try {
10161
+ parts = renderableParts(model, (material, geometry) => this.#surfaceFor(material, geometry));
10162
+ } catch (error) {
10163
+ this.#host.setFailures(this.#host.failures() + 1);
10164
+ this.#host.reportCellFailure("asset", model.name || "model", [], error);
10165
+ this.#host.setFailures(this.#host.failures() + this.disposeLoaded(model));
10166
+ return void 0;
10167
+ }
9559
10168
  if (parts.length === 0) {
9560
10169
  this.#host.setFailures(this.#host.failures() + 1);
9561
10170
  this.#host.setFailures(this.#host.failures() + this.disposeLoaded(model));
@@ -9732,8 +10341,12 @@ var CellModels = class _CellModels {
9732
10341
  * canonical one (converted to a cutout when it is transparent scatter), and every later material
9733
10342
  * with the same content is released on arrival and draws with it instead.
9734
10343
  */
9735
- #surfaceFor(source) {
9736
- const key = this.#preserveAuthoredParts ? source.uuid : materialKey(source);
10344
+ #surfaceFor(source, geometry) {
10345
+ const game = this.#partMaterial?.(source, geometry);
10346
+ if (game !== void 0 && game?.isMaterial !== true)
10347
+ throw new Error("WorldCells partMaterial must return a Material.");
10348
+ const hooked = game !== void 0 && game !== source;
10349
+ const key = hooked ? `part:${game.uuid}` : this.#preserveAuthoredParts ? source.uuid : materialKey(source);
9737
10350
  const shared2 = this.#surfaces.get(key);
9738
10351
  if (shared2 !== void 0) {
9739
10352
  shared2.users += 1;
@@ -9741,8 +10354,9 @@ var CellModels = class _CellModels {
9741
10354
  this.#host.setFailures(this.#host.failures() + 1);
9742
10355
  return { key, material: shared2.material };
9743
10356
  }
9744
- const drawn = scatterMaterial(source, this.#transparentScatter);
9745
- this.#surfaces.set(key, { material: drawn.material, owned: drawn.owned, users: 1 });
10357
+ const drawn = scatterMaterial(hooked ? game : source, this.#transparentScatter);
10358
+ const owned = hooked ? [source, ...drawn.owned] : drawn.owned;
10359
+ this.#surfaces.set(key, { material: drawn.material, owned, users: 1 });
9746
10360
  return { key, material: drawn.material };
9747
10361
  }
9748
10362
  /** One user gone; the last one tears the shared surface down. Returns teardowns that threw. */
@@ -9815,13 +10429,21 @@ var CellModels = class _CellModels {
9815
10429
  paths.length = 0;
9816
10430
  }
9817
10431
  };
9818
-
9819
- // src/world-bundle-safety.ts
9820
10432
  var PER_RENDER_UPDATE = "render";
9821
10433
  var BUNDLE_PROOF_ROWS_PER_FRAME = 256;
9822
10434
  var BUNDLE_PROOF_MAX_PERIOD = 600;
9823
10435
  var BundleSurfaceSafety = class {
9824
10436
  #checks = /* @__PURE__ */ new WeakMap();
10437
+ /**
10438
+ * The owned engine holds every cached verdict's `transparent`, `visible` and `transmission` and
10439
+ * answers which moved in one call a frame, so a settled `deep: false` test reads none of them.
10440
+ * Upstream three has no such host method and reads them per test, as before.
10441
+ *
10442
+ * ponytail: the list keeps every proved material until `clear`, which a world bounds by its assets.
10443
+ */
10444
+ #witness = new Object3D();
10445
+ #witnessed = [];
10446
+ #moved = /* @__PURE__ */ new Set();
9825
10447
  #revision = 0;
9826
10448
  #frame = 0;
9827
10449
  #frameRows = 0;
@@ -9835,6 +10457,9 @@ var BundleSurfaceSafety = class {
9835
10457
  };
9836
10458
  clear() {
9837
10459
  this.#checks = /* @__PURE__ */ new WeakMap();
10460
+ this.#witnessed = [];
10461
+ this.#moved.clear();
10462
+ this.#witness.__tnMaterialWatch?.(this.#witnessed);
9838
10463
  }
9839
10464
  /** Opens a frame: the period every deep proof is spread over follows the last frame's rows. */
9840
10465
  beginFrame() {
@@ -9844,6 +10469,10 @@ var BundleSurfaceSafety = class {
9844
10469
  Math.max(1, Math.ceil(this.#frameRows / BUNDLE_PROOF_ROWS_PER_FRAME))
9845
10470
  );
9846
10471
  this.#frameRows = 0;
10472
+ const moved = this.#witness.__tnMaterialCheck?.();
10473
+ if (moved !== void 0)
10474
+ for (let at = 0; at < moved.length; at++)
10475
+ this.#moved.add(this.#witnessed[moved[at]]);
9847
10476
  }
9848
10477
  /**
9849
10478
  * `deep: false` is for a renderer that records its own bundles from each frame's draws (the owned
@@ -9854,7 +10483,7 @@ var BundleSurfaceSafety = class {
9854
10483
  test(material, deep = true) {
9855
10484
  this.stats.checks++;
9856
10485
  const previous = this.#checks.get(material);
9857
- if (previous !== void 0 && previous.version === material.version && previous.transparent === material.transparent && previous.visible === material.visible && previous.transmission === Reflect.get(material, "transmission")) {
10486
+ if (previous !== void 0 && this.#shallowHolds(material, previous, deep)) {
9858
10487
  if (!deep) return previous;
9859
10488
  if (previous.testedFrame !== this.#frame) {
9860
10489
  previous.testedFrame = this.#frame;
@@ -9889,9 +10518,28 @@ var BundleSurfaceSafety = class {
9889
10518
  if (capture.overflow) {
9890
10519
  this.stats.uncached++;
9891
10520
  this.#checks.delete(material);
9892
- } else this.#checks.set(material, checked);
10521
+ } else {
10522
+ this.#checks.set(material, checked);
10523
+ this.#rewatch(material);
10524
+ }
9893
10525
  return checked;
9894
10526
  }
10527
+ /**
10528
+ * Whether the material still holds the cached verdict's shallow witness. `version` is JS-side;
10529
+ * the flags are the engine's answer when it witnesses them and a `deep: false` test asks.
10530
+ */
10531
+ #shallowHolds(material, previous, deep) {
10532
+ if (previous.version !== material.version) return false;
10533
+ if (!deep && this.#witness.__tnMaterialCheck !== void 0) return !this.#moved.has(material);
10534
+ return previous.transparent === material.transparent && previous.visible === material.visible && previous.transmission === Reflect.get(material, "transmission");
10535
+ }
10536
+ /** Re-stamp the engine's witness after a verdict was (re)taken, so it answers from this state. */
10537
+ #rewatch(material) {
10538
+ if (this.#witness.__tnMaterialWatch === void 0) return;
10539
+ if (!this.#witnessed.includes(material)) this.#witnessed.push(material);
10540
+ this.#moved.delete(material);
10541
+ this.#witness.__tnMaterialWatch(this.#witnessed);
10542
+ }
9895
10543
  };
9896
10544
  function graphSnapshotCurrent(row) {
9897
10545
  const node = row.node;
@@ -10094,11 +10742,14 @@ function freshMeshFor(old, geometry, count3) {
10094
10742
  next.receiveShadow = old.receiveShadow;
10095
10743
  next.renderOrder = old.renderOrder;
10096
10744
  next.userData = old.userData;
10745
+ next.position.copy(old.position);
10746
+ next.quaternion.copy(old.quaternion);
10747
+ next.scale.copy(old.scale);
10097
10748
  next.matrix.copy(old.matrix);
10098
- next.matrixAutoUpdate = old.matrixAutoUpdate;
10099
10749
  next.matrixWorld.copy(old.matrixWorld);
10100
- next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate;
10101
- if (isStatic(old)) markStatic(next);
10750
+ next.matrixAutoUpdate = old.matrixAutoUpdate || composeSilencedByFreeze(old);
10751
+ next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate || worldSilencedByFreeze(old);
10752
+ if (isStatic(old)) markEngineStatic(next);
10102
10753
  return next;
10103
10754
  }
10104
10755
  function followCluster(follow, minX, minZ, cellSize, cellsPerCluster) {
@@ -10109,7 +10760,7 @@ function followCluster(follow, minX, minZ, cellSize, cellsPerCluster) {
10109
10760
  );
10110
10761
  }
10111
10762
  function heldBytes(shared2) {
10112
- return shared2.mesh.instanceMatrix.array.byteLength;
10763
+ return shared2.mesh.instanceMatrix.count * 16 * Float32Array.BYTES_PER_ELEMENT;
10113
10764
  }
10114
10765
  function redressMaterial(mesh) {
10115
10766
  for (const material of redressed.get(mesh) ?? []) material.dispose();
@@ -10253,8 +10904,7 @@ var CellBundles = class {
10253
10904
  if (this.#ownsBundles !== void 0) return this.#ownsBundles;
10254
10905
  const renderer = this.#host.renderer();
10255
10906
  if (renderer === void 0) return false;
10256
- const info = renderer.raw?.info;
10257
- this.#ownsBundles = info !== void 0 && "engine" in info;
10907
+ this.#ownsBundles = rendererFacts(renderer).ownedEngine;
10258
10908
  return this.#ownsBundles;
10259
10909
  }
10260
10910
  /** One re-record, counted: `BundleGroup.needsUpdate` is a version bump, and nothing else. */
@@ -10462,68 +11112,6 @@ var CellBundles = class {
10462
11112
  this.#bundleSafety.clear();
10463
11113
  }
10464
11114
  };
10465
- var DRAW_ARGS_WORDS = 5;
10466
- var LOCAL_WORDS = 16;
10467
- var PLACEMENT_WORDS = 24;
10468
- var DRAW_ARGS_BYTES = DRAW_ARGS_WORDS * 4;
10469
- function argsWords(keys) {
10470
- return keys * DRAW_ARGS_WORDS + keys;
10471
- }
10472
- var VEC4_WORDS = 4;
10473
- var SLOT_NONE = -1;
10474
- var STORAGE_WORDS = {
10475
- /** `mat4` + `centre` (vec4) + `info` (vec4), so one placement is 96 bytes and one stride. */
10476
- // quality-allow: the object key is the WGSL type name the kernel reads, so it keeps that spelling.
10477
- // biome-ignore lint/style/useNamingConvention: the key is the WGSL type, spelled as the kernel declares it.
10478
- GpuPlacement: PLACEMENT_WORDS,
10479
- /** `mat4`, one per key: the part's own offset inside the model, the same one the CPU composes. */
10480
- mat4: LOCAL_WORDS,
10481
- /** `DrawIndexedIndirect`'s five words; `uint` is one word, so the element count is the word count. */
10482
- uint: 1,
10483
- /** One `vec4` per key, per asset slot and per level gate. */
10484
- vec4: VEC4_WORDS
10485
- };
10486
- function storageAttribute(ctor, type, count3, array = Float32Array) {
10487
- const words = STORAGE_WORDS[type];
10488
- return new ctor(new array(Math.max(1, count3) * words), words);
10489
- }
10490
- var VALIDATE_EVERY = 30;
10491
- var TALLY_EVERY = 30;
10492
- var PlacementStruct = struct(
10493
- { matrix: "mat4", centre: "vec4", info: "vec4" },
10494
- "GpuPlacement"
10495
- );
10496
- function growBuffer(current, needed, make) {
10497
- if (current.count >= needed) return current;
10498
- let capacity = Math.max(1, current.count);
10499
- while (capacity < needed) capacity *= 2;
10500
- const grown = make(capacity);
10501
- grown.array.set(current.array);
10502
- grown.addUpdateRange(0, current.array.length);
10503
- return grown;
10504
- }
10505
- function addRange(attribute2, start, count3) {
10506
- const last = attribute2.updateRanges[attribute2.updateRanges.length - 1];
10507
- if (last === void 0 || start > last.start + last.count || start + count3 < last.start) {
10508
- attribute2.addUpdateRange(start, count3);
10509
- return;
10510
- }
10511
- const newStart = Math.min(last.start, start);
10512
- last.count = Math.max(last.start + last.count, start + count3) - newStart;
10513
- last.start = newStart;
10514
- }
10515
- var NO_LOCAL = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
10516
- function nodes(value) {
10517
- return value;
10518
- }
10519
- var STORAGE_PLAIN = {
10520
- gates: "vec4",
10521
- keys: "vec4",
10522
- levels: "vec4",
10523
- locals: "mat4",
10524
- source: "GpuPlacement"
10525
- };
10526
- var SOURCE_FLOOR = 16;
10527
11115
 
10528
11116
  // src/world-gpu-validation.ts
10529
11117
  var VALIDATE_REPORTED_KEYS = 10;
@@ -10737,10 +11325,11 @@ function validationReport(input) {
10737
11325
  }
10738
11326
  var OCCLUSION_FLAG = "TN_OCCLUSION";
10739
11327
  function occlusionMode() {
10740
- const host = globalThis;
10741
- const fromEnv = host.process?.env?.[OCCLUSION_FLAG];
10742
- const query = host.location?.search;
10743
- const asked = typeof fromEnv === "string" && fromEnv !== "" ? fromEnv : typeof query === "string" ? /[?&]tnOcclusion=([^&]*)/u.exec(query)?.[1] ?? "" : typeof host.__tnOcclusion === "string" ? host.__tnOcclusion : "";
11328
+ const asked = readLaunchValue({
11329
+ environment: OCCLUSION_FLAG,
11330
+ global: "__tnOcclusion",
11331
+ query: "tnOcclusion"
11332
+ }) ?? "";
10744
11333
  const value = asked.trim().toLowerCase();
10745
11334
  if (value === "" || value === "0" || value === "off" || value === "false") return "off";
10746
11335
  if (value === "measure" || value === "1" || value === "true") return "measure";
@@ -10841,12 +11430,12 @@ var DepthPyramid = class {
10841
11430
  */
10842
11431
  resize(depthWidth, depthHeight) {
10843
11432
  const levels = [];
10844
- let span = 0;
11433
+ let span2 = 0;
10845
11434
  let width = Math.max(1, Math.ceil(depthWidth / 2));
10846
11435
  let height2 = Math.max(1, Math.ceil(depthHeight / 2));
10847
11436
  while (true) {
10848
- levels.push({ width, height: height2, offset: span });
10849
- span += width * height2;
11437
+ levels.push({ width, height: height2, offset: span2 });
11438
+ span2 += width * height2;
10850
11439
  if (width === 1 && height2 === 1) break;
10851
11440
  width = Math.max(1, Math.ceil(width / 2));
10852
11441
  height2 = Math.max(1, Math.ceil(height2 / 2));
@@ -10859,7 +11448,7 @@ var DepthPyramid = class {
10859
11448
  }))
10860
11449
  return false;
10861
11450
  this.#words = new StorageBufferAttribute(
10862
- new Float32Array(levels.length * TABLE_WORDS + span),
11451
+ new Float32Array(levels.length * TABLE_WORDS + span2),
10863
11452
  1
10864
11453
  );
10865
11454
  const table = this.#words.array;
@@ -11138,7 +11727,7 @@ function liveKeyInstances(placements, asset, camera) {
11138
11727
  }
11139
11728
  function buildCullKernel(input) {
11140
11729
  const { buffers } = input;
11141
- const source = nodes(storage(buffers.source, PlacementStruct, buffers.source.count));
11730
+ const source = nodes(storage(buffers.source, "vec4", buffers.source.count));
11142
11731
  const drawn = nodes(storage(buffers.drawn, "mat4", buffers.drawn.count));
11143
11732
  const argsPlain = nodes(storage(buffers.args, "uint", buffers.args.count));
11144
11733
  const argsAtomic = nodes(storage(buffers.args, "uint", buffers.args.count).toAtomic());
@@ -11167,10 +11756,16 @@ function buildCullKernel(input) {
11167
11756
  })().compute(Math.max(1, buffers.keys.count * clearWidth));
11168
11757
  const cull = Fn(() => {
11169
11758
  If(instanceIndex.greaterThanEqual(counts.x), () => Return());
11170
- const placement = source.element(instanceIndex);
11171
- const centre = placement.get("centre");
11172
- const matrix = placement.get("matrix");
11173
- const slot = placement.get("info").x;
11759
+ const base = instanceIndex.mul(uint(PLACEMENT_ROWS));
11760
+ const matrix = mat4(
11761
+ source.element(base),
11762
+ source.element(base.add(uint(1))),
11763
+ source.element(base.add(uint(2))),
11764
+ source.element(base.add(uint(3)))
11765
+ );
11766
+ const centre = source.element(base.add(uint(4)));
11767
+ const info = source.element(base.add(uint(5)));
11768
+ const slot = info.x;
11174
11769
  If(slot.lessThan(0), () => Return());
11175
11770
  If(slot.greaterThanEqual(counts.y), () => Return());
11176
11771
  const radius = centre.w;
@@ -11180,7 +11775,7 @@ function buildCullKernel(input) {
11180
11775
  If(gate.w.mod(2).greaterThan(0.5).and(distance.greaterThan(gate.z)), () => Return());
11181
11776
  const lodDistance = nodes(distance).mul(bias);
11182
11777
  const level = int(0).toVar();
11183
- const scale = abs(placement.get("info").y);
11778
+ const scale = abs(info.y);
11184
11779
  Loop({ start: int(1), end: gate.y, type: "int", condition: "<" }, ({ i }) => {
11185
11780
  const candidate = levels.element(gate.x.add(i));
11186
11781
  const threshold = nodes(candidate.x).toVar();
@@ -11212,7 +11807,10 @@ function buildCullKernel(input) {
11212
11807
  drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
11213
11808
  });
11214
11809
  });
11215
- })().compute(Math.max(1, buffers.source.count));
11810
+ })().compute(
11811
+ // One thread per placement record, not per `vec4` row of the source buffer.
11812
+ Math.max(1, Math.ceil(buffers.source.count / PLACEMENT_ROWS))
11813
+ );
11216
11814
  clear.setName("worldGpuSceneClear");
11217
11815
  cull.setName("worldGpuSceneCull");
11218
11816
  return { clear, cull };
@@ -11221,23 +11819,10 @@ function buildCullKernel(input) {
11221
11819
  // src/world-gpu-flags.ts
11222
11820
  var GPU_SCENE_FLAG = "TN_GPU_SCENE";
11223
11821
  function askedOff(flag, parameter, globalName) {
11224
- const host = globalThis;
11225
- const fromEnv = host.process?.env?.[flag];
11226
- if (fromEnv === "0" || fromEnv === "false") return true;
11227
- const query = globalThis.location?.search;
11228
- if (typeof query === "string" && new RegExp(`[?&]${parameter}=(?:0|false)(?:&|$)`, "u").test(query))
11229
- return true;
11230
- const set = host[globalName];
11231
- return set === false || set === 0 || set === "0" || set === "false";
11822
+ return readLaunchFlag({ environment: flag, global: globalName, query: parameter }, "off");
11232
11823
  }
11233
11824
  function askedOn(flag, parameter, globalName) {
11234
- const host = globalThis;
11235
- const fromEnv = host.process?.env?.[flag];
11236
- if (fromEnv === "1" || fromEnv === "true") return true;
11237
- const query = globalThis.location?.search;
11238
- if (typeof query === "string" && new RegExp(`[?&]${parameter}=(?:1|true)(?:&|$)`, "u").test(query))
11239
- return true;
11240
- return host[globalName] === true || host[globalName] === 1 || host[globalName] === "1";
11825
+ return readLaunchFlag({ environment: flag, global: globalName, query: parameter });
11241
11826
  }
11242
11827
  function gpuSceneRequested() {
11243
11828
  return askedOff(GPU_SCENE_FLAG, "tnGpuScene", "__tnGpuScene") === false;
@@ -11247,19 +11832,17 @@ function lodFromFollowRequested() {
11247
11832
  }
11248
11833
  var BUNDLE_FLAG = "TN_BUNDLES";
11249
11834
  function bundlesAsked() {
11250
- if (askedOn(BUNDLE_FLAG, "tnBundles", "__tnBundles")) return "on";
11251
- return askedOff(BUNDLE_FLAG, "tnBundles", "__tnBundles") ? "off" : "default";
11835
+ const values = readLaunchValues({
11836
+ environment: BUNDLE_FLAG,
11837
+ global: "__tnBundles",
11838
+ query: "tnBundles"
11839
+ });
11840
+ if (values.some((value) => value === "1" || value === "true" || value === "")) return "on";
11841
+ return values.some((value) => value === "0" || value === "false") ? "off" : "default";
11252
11842
  }
11253
11843
  var GPU_SCENE_VALIDATE_FLAG = "TN_GPU_SCENE_VALIDATE";
11254
11844
  function gpuSceneValidationRequested() {
11255
- const host = globalThis;
11256
- const fromEnv = host.process?.env?.[GPU_SCENE_VALIDATE_FLAG];
11257
- if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
11258
- return true;
11259
- const query = globalThis.location?.search;
11260
- if (typeof query === "string" && /[?&]tnGpuSceneValidate=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query))
11261
- return true;
11262
- return host.__tnGpuSceneValidate === true || host.__tnGpuSceneValidate === "1";
11845
+ return askedOn(GPU_SCENE_VALIDATE_FLAG, "tnGpuSceneValidate", "__tnGpuSceneValidate");
11263
11846
  }
11264
11847
  var SHADOW_GPU_KEYS_FLAG = "TN_SHADOW_GPU_KEYS";
11265
11848
  function shadowGpuKeysRequested() {
@@ -11869,7 +12452,7 @@ function uncapturedMessage(event) {
11869
12452
  }
11870
12453
  function buildShadowKernel(input) {
11871
12454
  const { buffers, shadow } = input;
11872
- const source = nodes(storage(buffers.source, PlacementStruct, buffers.source.count));
12455
+ const source = nodes(storage(buffers.source, "vec4", buffers.source.count));
11873
12456
  const drawn = nodes(storage(shadow.drawn, "mat4", shadow.drawn.count));
11874
12457
  const argsPlain = nodes(storage(shadow.args, "uint", shadow.args.count));
11875
12458
  const argsAtomic = nodes(storage(shadow.args, "uint", shadow.args.count).toAtomic());
@@ -11881,7 +12464,7 @@ function buildShadowKernel(input) {
11881
12464
  const eye = nodes(input.eye);
11882
12465
  const bias = nodes(input.bias);
11883
12466
  const gate = nodes(input.gate);
11884
- const base = nodes(input.base);
12467
+ nodes(input.base);
11885
12468
  const planes = input.planes.map((plane) => nodes(plane));
11886
12469
  const clearWidth = input.measureOcclusion ? 2 : 1;
11887
12470
  const clear = Fn(() => {
@@ -11900,10 +12483,16 @@ function buildShadowKernel(input) {
11900
12483
  })().compute(Math.max(1, buffers.keys.count * clearWidth));
11901
12484
  const cull = Fn(() => {
11902
12485
  If(instanceIndex.greaterThanEqual(counts.x), () => Return());
11903
- const placement = source.element(instanceIndex);
11904
- const centre = placement.get("centre");
11905
- const matrix = placement.get("matrix");
11906
- const slot = placement.get("info").x;
12486
+ const base2 = instanceIndex.mul(uint(PLACEMENT_ROWS));
12487
+ const matrix = mat4(
12488
+ source.element(base2),
12489
+ source.element(base2.add(uint(1))),
12490
+ source.element(base2.add(uint(2))),
12491
+ source.element(base2.add(uint(3)))
12492
+ );
12493
+ const centre = source.element(base2.add(uint(4)));
12494
+ const info = source.element(base2.add(uint(5)));
12495
+ const slot = info.x;
11907
12496
  If(slot.lessThan(0), () => Return());
11908
12497
  If(slot.greaterThanEqual(counts.y), () => Return());
11909
12498
  const radius = centre.w;
@@ -11914,7 +12503,7 @@ function buildShadowKernel(input) {
11914
12503
  If(asset.w.mod(2).greaterThan(0.5).and(distance.greaterThan(asset.z)), () => Return());
11915
12504
  const lodDistance = nodes(distance).mul(bias);
11916
12505
  const level = int(0).toVar();
11917
- const scale = abs(placement.get("info").y);
12506
+ const scale = abs(info.y);
11918
12507
  Loop({ start: int(1), end: asset.y, type: "int", condition: "<" }, ({ i }) => {
11919
12508
  const candidate = levels.element(asset.x.add(i));
11920
12509
  const threshold = nodes(candidate.x).toVar();
@@ -11939,7 +12528,7 @@ function buildShadowKernel(input) {
11939
12528
  {
11940
12529
  start: int(0),
11941
12530
  end: nodes(
11942
- max(level, int(min(base, asset.y.sub(1))))
12531
+ max(level, int(min(base2, asset.y.sub(1))))
11943
12532
  ).add(1),
11944
12533
  type: "int",
11945
12534
  condition: "<"
@@ -11960,11 +12549,29 @@ function buildShadowKernel(input) {
11960
12549
  drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
11961
12550
  });
11962
12551
  });
11963
- })().compute(Math.max(1, buffers.source.count));
12552
+ })().compute(
12553
+ // One thread per placement record, not per `vec4` row of the source buffer.
12554
+ Math.max(1, Math.ceil(buffers.source.count / PLACEMENT_ROWS))
12555
+ );
11964
12556
  clear.setName("worldGpuSceneShadowClear");
11965
12557
  cull.setName("worldGpuSceneShadowCull");
11966
12558
  return { clear, cull };
11967
12559
  }
12560
+ var _inverse = new Matrix4();
12561
+ function isIdentity(matrix) {
12562
+ const elements = matrix.elements;
12563
+ for (let at = 0; at < 16; at += 1) if (elements[at] !== (at % 5 === 0 ? 1 : 0)) return false;
12564
+ return true;
12565
+ }
12566
+ function localClip(out, camera, root) {
12567
+ out.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
12568
+ if (root === void 0 || isIdentity(root)) return out;
12569
+ return out.multiply(root);
12570
+ }
12571
+ function localPoint(point, root) {
12572
+ if (root === void 0 || isIdentity(root)) return point;
12573
+ return point.applyMatrix4(_inverse.copy(root).invert());
12574
+ }
11968
12575
 
11969
12576
  // src/world-gpu-scene.ts
11970
12577
  function gpuSceneUnsupported(renderer) {
@@ -11978,21 +12585,10 @@ function gpuSceneUnsupported(renderer) {
11978
12585
  return "feature=indirect-first-instance";
11979
12586
  return "";
11980
12587
  }
11981
- function cameraPlanes(camera, out) {
11982
- _cullFrustum.setFromProjectionMatrix(
11983
- _proj.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
11984
- );
11985
- for (const [index, plane] of _cullFrustum.planes.entries()) {
11986
- const at = index * 4;
11987
- out[at] = plane.normal.x;
11988
- out[at + 1] = plane.normal.y;
11989
- out[at + 2] = plane.normal.z;
11990
- out[at + 3] = plane.constant;
11991
- }
12588
+ function cameraPlanes(camera, out, root) {
12589
+ frustumPlanes(localClip(_proj, camera, root), out);
11992
12590
  }
11993
12591
  var _proj = new Matrix4();
11994
- var _cullFrustum = new Frustum();
11995
- var _eye2 = new Vector3();
11996
12592
  var WorldGpuScene = class {
11997
12593
  /** Resident placements, in the source buffer's own order; index 0 is the buffer's first record. */
11998
12594
  placements = [];
@@ -12477,10 +13073,26 @@ var WorldGpuScene = class {
12477
13073
  * One frame of the main pass: zero every key's instance count, then cull and LOD-select every
12478
13074
  * resident placement into the shared drawn buffer. Nothing else is written.
12479
13075
  */
12480
- dispatch(renderer, camera) {
13076
+ /**
13077
+ * The LOD eye `WorldCells` grades its CPU path from (`updateLodEye`): the camera, pulled to within
13078
+ * the first gate of `follow`. Levels and `maxDistance` then read one eye on both paths (PRD-857).
13079
+ * Unset, the dispatch measures from the camera.
13080
+ */
13081
+ lodEye(x, y, z) {
13082
+ this.#lodEye.set(x, y, z);
13083
+ this.#lodEyeSet = true;
13084
+ }
13085
+ #lodEye = new Vector3();
13086
+ #lodEyeSet = false;
13087
+ /**
13088
+ * `root` is the world's own `matrixWorld`: the frame its placements are recorded in, which is the
13089
+ * frame the planes and the eye have to be taken in. A harness driving the scene on its own leaves
13090
+ * it out, and then the records are read in world space, as they were before the root could move.
13091
+ */
13092
+ dispatch(renderer, camera, root) {
12481
13093
  if (this.#on === false) return;
12482
13094
  if (this.#buffers === void 0) return;
12483
- cameraPlanes(camera, this.#planes);
13095
+ cameraPlanes(camera, this.#planes, root);
12484
13096
  for (const [index, plane] of this.#planeVectors.entries()) {
12485
13097
  const at = index * 4;
12486
13098
  plane.set(
@@ -12490,8 +13102,8 @@ var WorldGpuScene = class {
12490
13102
  this.#planes[at + 3]
12491
13103
  );
12492
13104
  }
12493
- _eye2.setFromMatrixPosition(camera.matrixWorld);
12494
- this.#eye.value.copy(_eye2);
13105
+ if (this.#lodEyeSet) this.#eye.value.copy(this.#lodEye);
13106
+ else localPoint(this.#eye.value.setFromMatrixPosition(camera.matrixWorld), root);
12495
13107
  if (this.#readback.measuring) this.#readback.measure(renderer, camera);
12496
13108
  const kernel = this.#kernel ?? this.#buildKernel();
12497
13109
  if (kernel === void 0) return;
@@ -12610,7 +13222,10 @@ var WorldGpuScene = class {
12610
13222
  keys: storageAttribute(StorageBufferAttribute, "vec4", 1),
12611
13223
  levels: storageAttribute(StorageBufferAttribute, "vec4", 1),
12612
13224
  locals: storageAttribute(StorageBufferAttribute, "mat4", 1),
12613
- source: storageAttribute(StorageBufferAttribute, "GpuPlacement", SOURCE_FLOOR)
13225
+ // Six `vec4` rows per placement, so the count is the rows the kernels index by rather than
13226
+ // the placements: one placement record is 24 words either way, and the CPU's `Float32Array`
13227
+ // stays the GPU's buffer with no repacking.
13228
+ source: storageAttribute(StorageBufferAttribute, "vec4", SOURCE_FLOOR * PLACEMENT_ROWS)
12614
13229
  };
12615
13230
  this.#version += 1;
12616
13231
  return this.#buffers;
@@ -12645,7 +13260,7 @@ var WorldGpuScene = class {
12645
13260
  this.#growOf("drawn", this.#drawnCapacity);
12646
13261
  }
12647
13262
  #reserve(count3) {
12648
- return this.#growOf("source", Math.max(SOURCE_FLOOR, count3));
13263
+ return this.#growOf("source", Math.max(SOURCE_FLOOR, count3) * PLACEMENT_ROWS);
12649
13264
  }
12650
13265
  #writePlacement(index) {
12651
13266
  const buffers = this.#buffers;
@@ -12857,7 +13472,6 @@ var WorldGpuScene = class {
12857
13472
 
12858
13473
  // src/world-cell-render-gpu-dress.ts
12859
13474
  var _gpuEye = new Vector3();
12860
- var _cullFrustum2 = new Frustum();
12861
13475
  var _cullProjScreen = new Matrix4();
12862
13476
  var CellGpuDress = class {
12863
13477
  #host;
@@ -12909,10 +13523,11 @@ var CellGpuDress = class {
12909
13523
  }) : { geometry: own.geometry, material: own.material };
12910
13524
  return {
12911
13525
  ...shape,
12912
- material: this.#lodSurface(entry.asset, level, entry.part, shape.material)
13526
+ material: this.lodSurface(entry.asset, level, entry.part, shape.material)
12913
13527
  };
12914
13528
  }
12915
- #lodSurface(assetId, level, partIndex, source) {
13529
+ /** The material a batch of this level and part draws: `source` with the LOD gate's mask, when the asset has one. */
13530
+ lodSurface(assetId, level, partIndex, source) {
12916
13531
  assertSlotFree(source, assetId);
12917
13532
  const asset = this.#host.asset(assetId);
12918
13533
  const part = asset?.levels[level]?.[partIndex];
@@ -12952,6 +13567,7 @@ var CellGpuDress = class {
12952
13567
  updateLodEye(x, y, z) {
12953
13568
  this.#lodEye.value.set(x, y, z);
12954
13569
  this.#lodClock.value = (performance.now() - this.#lodClockOrigin) / 1e3;
13570
+ syncLodCollapse();
12955
13571
  if (this.#host.lodTransition() !== "temporal") return;
12956
13572
  advanceTemporalLod(this.#temporalLod, this.#lodEye.value, this.#lodClock.value);
12957
13573
  this.#lodAlpha.value = this.#temporalLod.alpha;
@@ -12964,7 +13580,7 @@ var CellGpuDress = class {
12964
13580
  const partIndex = Number(partText?.split("@")[0]);
12965
13581
  const part = asset.levels[level]?.[partIndex];
12966
13582
  if (part !== void 0) {
12967
- const material = this.#lodSurface(asset.id, level, partIndex, part.material);
13583
+ const material = this.lodSurface(asset.id, level, partIndex, part.material);
12968
13584
  if (material.userData.tnPublishedLodRange === true && shared2.mesh.geometry.getAttribute("tnPublishedLodRange") === void 0 && shared2.mesh.count === 0)
12969
13585
  shared2.rebind(part.geometry, material);
12970
13586
  else shared2.surface(material);
@@ -12994,7 +13610,7 @@ var CellGpuDress = class {
12994
13610
  dressMesh(shared2, receiveShadow) {
12995
13611
  const mesh = shared2.mesh;
12996
13612
  const role = shared2.role;
12997
- markStatic(mesh);
13613
+ markEngineStatic(mesh);
12998
13614
  if (role !== "main") {
12999
13615
  mesh.layers.set(
13000
13616
  role === "cluster" ? VIRTUAL_SHADOW_CASTER_LAYER : role === "key" ? VIRTUAL_SHADOW_KEY_LAYER : shared2.smallCaster ? VIRTUAL_SHADOW_SMALL_CASTER_LAYER : VIRTUAL_SHADOW_WIDE_CASTER_LAYER
@@ -13243,18 +13859,10 @@ var CellGpuDress = class {
13243
13859
  if (camera === void 0) return [];
13244
13860
  const lives = this.liveGates();
13245
13861
  if (lives.size === 0) return [];
13862
+ const root = this.#host.root();
13246
13863
  const planes = this.#gpuPlanes;
13247
- _cullFrustum2.setFromProjectionMatrix(
13248
- _cullProjScreen.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
13249
- );
13250
- for (const [index, plane] of _cullFrustum2.planes.entries()) {
13251
- const at = index * 4;
13252
- planes[at] = plane.normal.x;
13253
- planes[at + 1] = plane.normal.y;
13254
- planes[at + 2] = plane.normal.z;
13255
- planes[at + 3] = plane.constant;
13256
- }
13257
- _gpuEye.setFromMatrixPosition(camera.matrixWorld);
13864
+ frustumPlanes(localClip(_cullProjScreen, camera, root), planes);
13865
+ localPoint(_gpuEye.setFromMatrixPosition(camera.matrixWorld), root);
13258
13866
  const expected = liveKeyInstances(
13259
13867
  this.#host.gpuScene().placements,
13260
13868
  (slot) => {
@@ -13318,18 +13926,9 @@ var CellGpuDress = class {
13318
13926
  }
13319
13927
  };
13320
13928
  var PARKED_SHARED_CAPACITY = 1;
13321
- var regroupScratch = new Float32Array(0);
13322
- var lodRangeScratch = new Float32Array(0);
13323
13929
  var LOD_RANGE_ATTRIBUTE = "tnPublishedLodRange";
13930
+ var ZERO = new Vector3();
13324
13931
  var LOD_RANGE_STRIDE = 4;
13325
- function lodScratchFor(floats) {
13326
- if (lodRangeScratch.length < floats) lodRangeScratch = new Float32Array(floats * 2);
13327
- return lodRangeScratch;
13328
- }
13329
- function scratchFor(floats) {
13330
- if (regroupScratch.length < floats) regroupScratch = new Float32Array(floats * 2);
13331
- return regroupScratch;
13332
- }
13333
13932
  function sizeOf(square) {
13334
13933
  let size = 0;
13335
13934
  for (const block of square.blocks) size += block[2];
@@ -13450,17 +14049,19 @@ var SharedBatch = class {
13450
14049
  #boxes = /* @__PURE__ */ new Map();
13451
14050
  /** Block handle -> the largest instance scale in it; the union is published on the mesh. */
13452
14051
  #scales = /* @__PURE__ */ new Map();
13453
- /** Carried out of the last `#boxOf` pass, which already reads every record's basis. */
13454
- #maxScale = 0;
13455
14052
  #localGeometry;
13456
14053
  #localCenter = new Vector3();
13457
14054
  #localHalf = new Vector3();
13458
14055
  #union = new Box3();
13459
14056
  #point = new Vector3();
13460
- /** This batch's own pending upload span, and the `update` it was opened in. See `#touched`. */
14057
+ /** This batch's pending upload span, in floats of the instance buffer, until the next flush. See `#touched`. */
13461
14058
  #pendingLow = 0;
13462
14059
  #pendingHigh = 0;
13463
- #pendingEpoch = -1;
14060
+ /** The buffers that span belongs to: the ones this batch wrote last, whatever a later dress swaps in. */
14061
+ #pendingMatrix;
14062
+ #pendingRanges;
14063
+ /** Block handle -> where its box starts in the flush's answer; see {@link settleRecords}. */
14064
+ #pendingBoxes = /* @__PURE__ */ new Map();
13464
14065
  constructor(geometry, material, segmentSize, segments, name, bounds, role, rangeLevel = 0) {
13465
14066
  this.role = role;
13466
14067
  this.#sourceGeometry = geometry;
@@ -13493,6 +14094,8 @@ var SharedBatch = class {
13493
14094
  view.boundingSphere = source.boundingSphere;
13494
14095
  view.setDrawRange(source.drawRange.start, source.drawRange.count);
13495
14096
  view.userData.tnPublishedLodRangeView = true;
14097
+ const stamp = source.userData[GEOMETRY_ASSET_KEY];
14098
+ if (stamp !== void 0) view.userData[GEOMETRY_ASSET_KEY] = stamp;
13496
14099
  const ranges = new InstancedBufferAttribute(
13497
14100
  new Float32Array(capacity * LOD_RANGE_STRIDE),
13498
14101
  LOD_RANGE_STRIDE
@@ -13550,8 +14153,8 @@ var SharedBatch = class {
13550
14153
  mesh.frustumCulled = true;
13551
14154
  mesh.castShadow = false;
13552
14155
  mesh.receiveShadow = false;
13553
- mesh.instanceMatrix.array.fill(0);
13554
- mesh.instanceMatrix.needsUpdate = true;
14156
+ batchRecords.fill(mesh.instanceMatrix, 0, records * 16);
14157
+ batchRecords.upload(mesh.instanceMatrix, 0, 0);
13555
14158
  mesh.casterInstanceScale = 0;
13556
14159
  mesh.userData.tnBundled = false;
13557
14160
  mesh.mainAdmitted = true;
@@ -13583,13 +14186,8 @@ var SharedBatch = class {
13583
14186
  this.#setGeometry(this.#geometryFor(this.mesh.instanceMatrix.count));
13584
14187
  const ranges = this.#lodRangeAttribute();
13585
14188
  if (ranges === void 0) return;
13586
- const values = ranges.array;
13587
- for (let at = 0; at < values.length; at += LOD_RANGE_STRIDE) {
13588
- values[at] = this.#rangeLevel;
13589
- values[at + 1] = this.#rangeLevel;
13590
- values[at + 2] = -1;
13591
- }
13592
- ranges.needsUpdate = true;
14189
+ batchRecords.lanes(ranges, LOD_RANGE_STRIDE, [this.#rangeLevel, this.#rangeLevel, -1]);
14190
+ batchRecords.upload(ranges, 0, 0);
13593
14191
  }
13594
14192
  /** The capacity this batch had when it was parked; see {@link park}. */
13595
14193
  #parked = 0;
@@ -13644,72 +14242,26 @@ var SharedBatch = class {
13644
14242
  this.mesh.casterInstanceScale = live === false ? 0 : Math.max(...this.#scales.values());
13645
14243
  }
13646
14244
  /**
13647
- * The AABB of records `[from, from + count)` of the instance buffer, read from the bytes just
13648
- * written rather than from the batch that wrote them, so it is the same numbers the GPU gets. The
13649
- * half-extents are `|basis| * half`, which is the box a rotated or stretched instance of the part
13650
- * actually covers — a translate-only box would let a scaled trunk through the shadow cull.
14245
+ * The part's local box centre and half size, read once per geometry: the input of the record box
14246
+ * the engine measures from the bytes as written (see {@link write}). False when the geometry has
14247
+ * no readable box, and the package extent stands in for the block's records.
13651
14248
  */
13652
- #boxOf(from, count3) {
13653
- const array = this.mesh.instanceMatrix.array;
14249
+ #localBox() {
13654
14250
  const geometry = this.mesh.geometry;
13655
14251
  if (this.#localGeometry !== geometry) {
13656
14252
  this.#localGeometry = geometry;
13657
14253
  if (geometry?.boundingBox === null || geometry?.boundingBox === void 0)
13658
14254
  geometry?.computeBoundingBox?.();
13659
14255
  const local = geometry?.boundingBox;
13660
- if (local === void 0 || local === null || local.isEmpty()) return this.#bounds;
13661
- this.#localCenter.copy(local.getCenter(this.#point));
13662
- this.#localHalf.copy(local.getSize(this.#point)).multiplyScalar(0.5);
13663
- }
13664
- const cx = this.#localCenter.x;
13665
- const cy = this.#localCenter.y;
13666
- const cz = this.#localCenter.z;
13667
- const hx = this.#localHalf.x;
13668
- const hy = this.#localHalf.y;
13669
- const hz = this.#localHalf.z;
13670
- const out = new Box3();
13671
- let minX = Number.POSITIVE_INFINITY;
13672
- let minY = Number.POSITIVE_INFINITY;
13673
- let minZ = Number.POSITIVE_INFINITY;
13674
- let maxX = Number.NEGATIVE_INFINITY;
13675
- let maxY = Number.NEGATIVE_INFINITY;
13676
- let maxZ = Number.NEGATIVE_INFINITY;
13677
- let scale = 0;
13678
- for (let index = from; index < from + count3; index += 1) {
13679
- const at = index * 16;
13680
- const m0 = array[at];
13681
- const m1 = array[at + 1];
13682
- const m2 = array[at + 2];
13683
- const m4 = array[at + 4];
13684
- const m5 = array[at + 5];
13685
- const m6 = array[at + 6];
13686
- const m8 = array[at + 8];
13687
- const m9 = array[at + 9];
13688
- const m10 = array[at + 10];
13689
- const px = m0 * cx + m4 * cy + m8 * cz + array[at + 12];
13690
- const py = m1 * cx + m5 * cy + m9 * cz + array[at + 13];
13691
- const pz = m2 * cx + m6 * cy + m10 * cz + array[at + 14];
13692
- const ex = Math.abs(m0) * hx + Math.abs(m4) * hy + Math.abs(m8) * hz;
13693
- const ey = Math.abs(m1) * hx + Math.abs(m5) * hy + Math.abs(m9) * hz;
13694
- const ez = Math.abs(m2) * hx + Math.abs(m6) * hy + Math.abs(m10) * hz;
13695
- if (px - ex < minX) minX = px - ex;
13696
- if (py - ey < minY) minY = py - ey;
13697
- if (pz - ez < minZ) minZ = pz - ez;
13698
- if (px + ex > maxX) maxX = px + ex;
13699
- if (py + ey > maxY) maxY = py + ey;
13700
- if (pz + ez > maxZ) maxZ = pz + ez;
13701
- const basis = Math.max(
13702
- Math.hypot(m0, m1, m2),
13703
- Math.hypot(m4, m5, m6),
13704
- Math.hypot(m8, m9, m10)
13705
- );
13706
- if (basis > scale) scale = basis;
14256
+ this.#localReadable = !(local === void 0 || local === null || local.isEmpty());
14257
+ if (local !== void 0 && local !== null && this.#localReadable) {
14258
+ this.#localCenter.copy(local.getCenter(this.#point));
14259
+ this.#localHalf.copy(local.getSize(this.#point)).multiplyScalar(0.5);
14260
+ }
13707
14261
  }
13708
- this.#maxScale = scale;
13709
- out.min.set(minX, minY, minZ);
13710
- out.max.set(maxX, maxY, maxZ);
13711
- return out;
14262
+ return this.#localReadable;
13712
14263
  }
14264
+ #localReadable = false;
13713
14265
  /** A handle for `count` free records, or `undefined` when the buffer has none and must grow. */
13714
14266
  allocate(count3, cluster) {
13715
14267
  const at = this.#take(count3);
@@ -13742,13 +14294,12 @@ var SharedBatch = class {
13742
14294
  old.name,
13743
14295
  this.#bounds
13744
14296
  );
13745
- mesh.instanceMatrix.array.set(old.instanceMatrix.array);
14297
+ const records = old.instanceMatrix.count;
14298
+ batchRecords.copy(mesh.instanceMatrix, old.instanceMatrix, records * 16);
13746
14299
  const oldRanges = old.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
13747
14300
  const nextRanges = mesh.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
13748
- if (oldRanges instanceof InstancedBufferAttribute && nextRanges instanceof InstancedBufferAttribute) {
13749
- nextRanges.array.set(oldRanges.array);
13750
- nextRanges.needsUpdate = true;
13751
- }
14301
+ if (oldRanges instanceof InstancedBufferAttribute && nextRanges instanceof InstancedBufferAttribute)
14302
+ batchRecords.copy(nextRanges, oldRanges, records * LOD_RANGE_STRIDE);
13752
14303
  mesh.castShadow = old.castShadow;
13753
14304
  mesh.receiveShadow = old.receiveShadow;
13754
14305
  this.mesh = mesh;
@@ -13756,7 +14307,6 @@ var SharedBatch = class {
13756
14307
  this.#ceiling = mesh.instanceMatrix.count;
13757
14308
  this.#settle();
13758
14309
  this.#touched(0, this.#drawn);
13759
- this.#rebound();
13760
14310
  return old;
13761
14311
  }
13762
14312
  /**
@@ -13792,37 +14342,53 @@ var SharedBatch = class {
13792
14342
  this.#publish(this.#drawn);
13793
14343
  return;
13794
14344
  }
13795
- const array = this.mesh.instanceMatrix.array;
13796
- const written = batch.writeMatrices(array, start);
13797
- const ranges = this.#lodRangeAttribute();
13798
- if (ranges !== void 0) {
13799
- const values = ranges.array;
13800
- if (lodRanges !== void 0)
13801
- values.set(lodRanges.subarray(0, written * LOD_RANGE_STRIDE), start * LOD_RANGE_STRIDE);
13802
- else
13803
- for (let index = 0; index < written; index += 1) {
13804
- const at = (start + index) * LOD_RANGE_STRIDE;
13805
- values[at] = this.#rangeLevel;
13806
- values[at + 1] = this.#rangeLevel;
13807
- values[at + 2] = -1;
13808
- values[at + 3] = 0;
13809
- }
13810
- values.fill(0, (start + written) * LOD_RANGE_STRIDE, (start + reserved) * LOD_RANGE_STRIDE);
13811
- ranges.needsUpdate = true;
13812
- }
13813
- array.fill(0, (start + written) * 16, (start + reserved) * 16);
14345
+ const matrix = this.mesh.instanceMatrix;
14346
+ const payloadAt = batchRecords.reserve(batch.count * 16);
14347
+ const written = batch.writeMatrices(batchRecords.payload, payloadAt / 16);
14348
+ batchRecords.write(matrix, start * 16, written * 16, payloadAt);
14349
+ this.#writeRanges(start, written, reserved, lodRanges);
14350
+ batchRecords.fill(matrix, (start + written) * 16, (reserved - written) * 16);
13814
14351
  if (written < reserved) this.#hole(start + written, start + reserved);
13815
14352
  this.#size.set(segment, written);
13816
14353
  if (written > 0) {
13817
- this.#boxes.set(segment, this.#boxOf(start, written));
13818
- this.#scales.set(segment, this.#maxScale);
14354
+ const readable = this.#localBox();
14355
+ const index = batchRecords.box(
14356
+ matrix,
14357
+ start,
14358
+ written,
14359
+ readable ? this.#localCenter : ZERO,
14360
+ readable ? this.#localHalf : ZERO
14361
+ );
14362
+ this.#pendingBoxes.set(segment, readable ? index : -1 - index);
13819
14363
  } else {
13820
14364
  this.#boxes.delete(segment);
13821
14365
  this.#scales.delete(segment);
14366
+ this.#pendingBoxes.delete(segment);
13822
14367
  }
13823
14368
  this.#settle();
13824
14369
  this.#touched(start, written);
13825
- this.#rebound();
14370
+ }
14371
+ /** The block's LOD-range column: the published ranges, or each record whole at this batch's level. */
14372
+ #writeRanges(start, written, reserved, lodRanges) {
14373
+ const ranges = this.#lodRangeAttribute();
14374
+ if (ranges === void 0) return;
14375
+ const at = batchRecords.reserve(written * LOD_RANGE_STRIDE);
14376
+ const values = batchRecords.payload;
14377
+ if (lodRanges !== void 0) values.set(lodRanges.subarray(0, written * LOD_RANGE_STRIDE), at);
14378
+ else
14379
+ for (let index = 0; index < written; index += 1) {
14380
+ const record = at + index * LOD_RANGE_STRIDE;
14381
+ values[record] = this.#rangeLevel;
14382
+ values[record + 1] = this.#rangeLevel;
14383
+ values[record + 2] = -1;
14384
+ values[record + 3] = 0;
14385
+ }
14386
+ batchRecords.write(ranges, start * LOD_RANGE_STRIDE, written * LOD_RANGE_STRIDE, at);
14387
+ batchRecords.fill(
14388
+ ranges,
14389
+ (start + written) * LOD_RANGE_STRIDE,
14390
+ (reserved - written) * LOD_RANGE_STRIDE
14391
+ );
13826
14392
  }
13827
14393
  clear(segment) {
13828
14394
  const start = this.#start.get(segment);
@@ -13841,22 +14407,16 @@ var SharedBatch = class {
13841
14407
  this.#publish(this.#drawn);
13842
14408
  return;
13843
14409
  }
13844
- this.mesh.instanceMatrix.array.fill(0, start * 16, (start + size) * 16);
14410
+ batchRecords.fill(this.mesh.instanceMatrix, start * 16, size * 16);
13845
14411
  const ranges = this.#lodRangeAttribute();
13846
- if (ranges !== void 0) {
13847
- ranges.array.fill(
13848
- 0,
13849
- start * LOD_RANGE_STRIDE,
13850
- (start + size) * LOD_RANGE_STRIDE
13851
- );
13852
- ranges.needsUpdate = true;
13853
- }
14412
+ if (ranges !== void 0)
14413
+ batchRecords.fill(ranges, start * LOD_RANGE_STRIDE, size * LOD_RANGE_STRIDE);
13854
14414
  this.#hole(start, start + size);
13855
14415
  this.#settle();
13856
14416
  this.#touched(0, this.#drawn);
13857
14417
  this.#boxes.delete(segment);
13858
14418
  this.#scales.delete(segment);
13859
- this.#rebound();
14419
+ this.#pendingBoxes.delete(segment);
13860
14420
  }
13861
14421
  /** The first free range with room for `count` records, taken out of the list; -1 when there is none. */
13862
14422
  #take(count3) {
@@ -13894,7 +14454,8 @@ var SharedBatch = class {
13894
14454
  * instead of a `grow`, and the free list is left as the single tail range `[drawn, capacity)`.
13895
14455
  */
13896
14456
  #compact() {
13897
- const array = this.mesh.instanceMatrix.array;
14457
+ const matrix = this.mesh.instanceMatrix;
14458
+ const ranges = this.#lodRangeAttribute();
13898
14459
  for (; ; ) {
13899
14460
  let drawn = 0;
13900
14461
  let top = -1;
@@ -13912,12 +14473,14 @@ var SharedBatch = class {
13912
14473
  const [holeStart, holeEnd] = lowest;
13913
14474
  const size = this.#size.get(top) ?? 0;
13914
14475
  if (size <= holeEnd - holeStart) {
13915
- array.copyWithin(holeStart * 16, topFrom * 16, drawn * 16);
13916
- this.#lodRangeAttribute()?.array.copyWithin(
13917
- holeStart * LOD_RANGE_STRIDE,
13918
- topFrom * LOD_RANGE_STRIDE,
13919
- drawn * LOD_RANGE_STRIDE
13920
- );
14476
+ batchRecords.move(matrix, topFrom * 16, holeStart * 16, (drawn - topFrom) * 16);
14477
+ if (ranges !== void 0)
14478
+ batchRecords.move(
14479
+ ranges,
14480
+ topFrom * LOD_RANGE_STRIDE,
14481
+ holeStart * LOD_RANGE_STRIDE,
14482
+ (drawn - topFrom) * LOD_RANGE_STRIDE
14483
+ );
13921
14484
  this.#start.set(top, holeStart);
13922
14485
  if (holeEnd - holeStart > size) this.#free[0] = [holeStart + size, holeEnd];
13923
14486
  else this.#free.shift();
@@ -13926,12 +14489,14 @@ var SharedBatch = class {
13926
14489
  this.#touched(holeStart, size);
13927
14490
  } else {
13928
14491
  const shift = holeEnd - holeStart;
13929
- array.copyWithin(holeStart * 16, holeEnd * 16, drawn * 16);
13930
- this.#lodRangeAttribute()?.array.copyWithin(
13931
- holeStart * LOD_RANGE_STRIDE,
13932
- holeEnd * LOD_RANGE_STRIDE,
13933
- drawn * LOD_RANGE_STRIDE
13934
- );
14492
+ batchRecords.move(matrix, holeEnd * 16, holeStart * 16, (drawn - holeEnd) * 16);
14493
+ if (ranges !== void 0)
14494
+ batchRecords.move(
14495
+ ranges,
14496
+ holeEnd * LOD_RANGE_STRIDE,
14497
+ holeStart * LOD_RANGE_STRIDE,
14498
+ (drawn - holeEnd) * LOD_RANGE_STRIDE
14499
+ );
13935
14500
  this.#free.shift();
13936
14501
  for (const [handle, start] of this.#start) {
13937
14502
  if (start >= holeEnd) this.#start.set(handle, start - shift);
@@ -13973,8 +14538,8 @@ var SharedBatch = class {
13973
14538
  *
13974
14539
  * A regroup is a permutation of `[0, drawn)` and there is no in-place order for one: writing the
13975
14540
  * visible squares to the front necessarily lands on squares whose records have not been read out
13976
- * yet, in either direction. So every block is copied into {@link regroupScratch} and the new order
13977
- * is copied back — two passes over the drawn range, and only when a square entered or left the
14541
+ * yet, in either direction. So the engine's gather op reads every block out before it writes the
14542
+ * new order back — two passes over the drawn range, and only when a square entered or left the
13978
14543
  * window, which on a settled camera is not once a frame.
13979
14544
  *
13980
14545
  * Squares keep their relative order within each half, so a residency change regroups in place and
@@ -13993,44 +14558,30 @@ var SharedBatch = class {
13993
14558
  * stay few and large rather than many and small.
13994
14559
  */
13995
14560
  #regroup(visible = this.#visible) {
13996
- const array = this.mesh.instanceMatrix.array;
13997
- const rangeAttribute = this.#lodRangeAttribute();
13998
- const rangeArray = rangeAttribute?.array;
13999
14561
  const squares = this.#squares();
14000
- let total = 0;
14001
- for (const square of squares) total += sizeOf(square);
14002
- const scratch = scratchFor(total * 16);
14003
- const rangeScratch = rangeArray === void 0 ? void 0 : lodScratchFor(total * LOD_RANGE_STRIDE);
14004
14562
  const front = squares.filter((one) => visible?.has(one.cluster) ?? true);
14005
14563
  const back = squares.filter((one) => !(visible?.has(one.cluster) ?? true));
14006
14564
  let written = 0;
14007
14565
  let movedFrom = -1;
14008
14566
  let movedTo = 0;
14567
+ const blocks = [];
14009
14568
  this.#squareSizes.clear();
14010
14569
  for (const square of [...front, ...back]) {
14011
- const union = new Box3();
14012
14570
  for (const [handle, start, count3] of square.blocks) {
14013
- scratch.set(array.subarray(start * 16, (start + count3) * 16), written * 16);
14014
- if (rangeScratch !== void 0 && rangeArray !== void 0)
14015
- rangeScratch.set(
14016
- rangeArray.subarray(start * LOD_RANGE_STRIDE, (start + count3) * LOD_RANGE_STRIDE),
14017
- written * LOD_RANGE_STRIDE
14018
- );
14571
+ blocks.push(start, count3);
14019
14572
  if (this.#start.get(handle) !== written) {
14020
14573
  if (movedFrom < 0) movedFrom = written;
14021
14574
  movedTo = written + count3;
14022
14575
  }
14023
14576
  this.#start.set(handle, written);
14024
- const box = this.#boxes.get(handle);
14025
- if (box !== void 0) union.union(box);
14026
14577
  written += count3;
14027
14578
  }
14028
14579
  this.#squareSizes.set(square.cluster, sizeOf(square));
14029
14580
  }
14030
- array.set(scratch.subarray(0, written * 16));
14031
- if (rangeArray !== void 0 && rangeScratch !== void 0 && rangeAttribute !== void 0) {
14032
- rangeArray.set(rangeScratch.subarray(0, written * LOD_RANGE_STRIDE));
14033
- rangeAttribute.needsUpdate = true;
14581
+ if (movedFrom >= 0) {
14582
+ batchRecords.gather(this.mesh.instanceMatrix, 16, blocks);
14583
+ const ranges = this.#lodRangeAttribute();
14584
+ if (ranges !== void 0) batchRecords.gather(ranges, LOD_RANGE_STRIDE, blocks);
14034
14585
  }
14035
14586
  this.#drawn = written;
14036
14587
  const capacity = this.mesh.instanceMatrix.count;
@@ -14156,14 +14707,10 @@ var SharedBatch = class {
14156
14707
  */
14157
14708
  #touched(from, count3) {
14158
14709
  if (this.gpu !== void 0) return;
14159
- const matrix = this.mesh.instanceMatrix;
14160
14710
  const drawn = this.#drawn * 16;
14161
- const low0 = from * 16;
14162
- const high0 = (from + count3) * 16;
14163
- let low = low0;
14164
- let high = high0;
14165
- const epoch = currentWriteEpoch();
14166
- if (this.#pendingEpoch === epoch) {
14711
+ let low = from * 16;
14712
+ let high = (from + count3) * 16;
14713
+ if (this.#pendingMatrix !== void 0) {
14167
14714
  if (this.#pendingLow < low) low = this.#pendingLow;
14168
14715
  if (this.#pendingHigh > high) high = this.#pendingHigh;
14169
14716
  }
@@ -14173,23 +14720,50 @@ var SharedBatch = class {
14173
14720
  }
14174
14721
  this.#pendingLow = low;
14175
14722
  this.#pendingHigh = high;
14176
- this.#pendingEpoch = epoch;
14177
- matrix.clearUpdateRanges();
14178
- if (high > low) matrix.addUpdateRange(low, high - low);
14179
- matrix.needsUpdate = true;
14180
- const ranges = this.#lodRangeAttribute();
14181
- if (ranges !== void 0) {
14182
- ranges.clearUpdateRanges();
14183
- if (high > low)
14184
- ranges.addUpdateRange(
14185
- low / 16 * LOD_RANGE_STRIDE,
14186
- (high - low) / 16 * LOD_RANGE_STRIDE
14187
- );
14188
- ranges.needsUpdate = true;
14189
- }
14723
+ this.#pendingMatrix = this.mesh.instanceMatrix;
14724
+ this.#pendingRanges = this.#lodRangeAttribute();
14725
+ batchRecords.touch(this);
14190
14726
  this.#publish(this.#drawn);
14191
14727
  this.mesh.frustumCulled = true;
14192
14728
  }
14729
+ /** The flush asks for this frame's upload span, one range per buffer; see {@link #touched}. */
14730
+ uploadRecords() {
14731
+ const matrix = this.#pendingMatrix;
14732
+ if (matrix === void 0) return;
14733
+ const low = this.#pendingLow;
14734
+ const high = this.#pendingHigh;
14735
+ batchRecords.upload(matrix, low, high - low);
14736
+ if (this.#pendingRanges !== void 0)
14737
+ batchRecords.upload(
14738
+ this.#pendingRanges,
14739
+ low / 16 * LOD_RANGE_STRIDE,
14740
+ (high - low) / 16 * LOD_RANGE_STRIDE
14741
+ );
14742
+ this.#pendingMatrix = void 0;
14743
+ this.#pendingRanges = void 0;
14744
+ }
14745
+ /**
14746
+ * The flush answered: each block written this frame gets the box the engine measured, and the
14747
+ * mesh's bounds are published once from all of them.
14748
+ */
14749
+ settleRecords(boxes) {
14750
+ for (const [segment, encoded] of this.#pendingBoxes) {
14751
+ if (!this.#start.has(segment)) continue;
14752
+ const at = encoded < 0 ? -1 - encoded : encoded;
14753
+ const box = encoded < 0 ? this.#bounds : new Box3(
14754
+ new Vector3(boxes[at], boxes[at + 1], boxes[at + 2]),
14755
+ new Vector3(
14756
+ boxes[at + 3],
14757
+ boxes[at + 4],
14758
+ boxes[at + 5]
14759
+ )
14760
+ );
14761
+ this.#boxes.set(segment, box);
14762
+ this.#scales.set(segment, boxes[at + 6]);
14763
+ }
14764
+ this.#pendingBoxes.clear();
14765
+ this.#rebound();
14766
+ }
14193
14767
  /**
14194
14768
  * The one place `mesh.count` is written, so a batch that would draw nothing is not submitted.
14195
14769
  *
@@ -14282,8 +14856,20 @@ var SharedBatch = class {
14282
14856
  };
14283
14857
 
14284
14858
  // src/world-cell-render-main-cull.ts
14285
- var _cullFrustum3 = new Frustum();
14859
+ var _cullFrustum = new Frustum();
14286
14860
  var _cullProjScreen2 = new Matrix4();
14861
+ var _cullBox = new Box3();
14862
+ function boxesInFrustum(frustum, boxes) {
14863
+ const engine = frustum.__tnIntersectsBoxes;
14864
+ if (typeof engine === "function") return engine.call(frustum, boxes);
14865
+ const hits = [];
14866
+ for (let at = 0; at < boxes.length; at += 6) {
14867
+ _cullBox.min.fromArray(boxes, at);
14868
+ _cullBox.max.fromArray(boxes, at + 3);
14869
+ if (frustum.intersectsBox(_cullBox)) hits.push(at / 6);
14870
+ }
14871
+ return hits;
14872
+ }
14287
14873
  var CellMainCull = class {
14288
14874
  #host;
14289
14875
  #cellSize;
@@ -14318,6 +14904,13 @@ var CellMainCull = class {
14318
14904
  * {@link #cullMainPass}.
14319
14905
  */
14320
14906
  #cullCells = /* @__PURE__ */ new Map();
14907
+ /**
14908
+ * The non-empty volumes of `#cullCells` packed for the frame's one frustum test, and their names
14909
+ * by index. Repacked only after a volume was admitted, widened or dropped, so a frame reads no box.
14910
+ */
14911
+ #cullBoxes = new Float64Array(0);
14912
+ #cullNames = [];
14913
+ #cullPacked = false;
14321
14914
  /** The visibility cells the last cull kept and the frame's set, trading places; see `#cullMainPass`. */
14322
14915
  #visibleSquares = /* @__PURE__ */ new Set();
14323
14916
  #cullScratch = /* @__PURE__ */ new Set();
@@ -14361,14 +14954,14 @@ var CellMainCull = class {
14361
14954
  if (camera === void 0 || camera.isOrthographicCamera === true) return;
14362
14955
  this.#host.beginBundleFrame();
14363
14956
  this.#mainCullFrustums += 1;
14364
- const frustum = _cullFrustum3.setFromProjectionMatrix(
14365
- _cullProjScreen2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
14366
- );
14957
+ const root = this.#host.render().root();
14958
+ const frustum = _cullFrustum.setFromProjectionMatrix(localClip(_cullProjScreen2, camera, root));
14367
14959
  const next = this.#cullScratch;
14368
14960
  next.clear();
14369
- for (const [cell, entry] of this.#cullCells) {
14370
- if (entry.box.isEmpty() === false && frustum.intersectsBox(entry.box)) next.add(cell);
14371
- }
14961
+ if (!this.#cullPacked) this.#packCullBoxes();
14962
+ const hits = boxesInFrustum(frustum, this.#cullBoxes);
14963
+ for (let at = 0; at < hits.length; at += 1)
14964
+ next.add(this.#cullNames[hits[at]]);
14372
14965
  if (!sameSquares(next, this.#visibleSquares)) {
14373
14966
  this.#visibleEpoch += 1;
14374
14967
  const was = this.#visibleSquares;
@@ -14408,13 +15001,29 @@ var CellMainCull = class {
14408
15001
  this.#host.dressShadowKey(shared2, shared2.mesh.name.slice(0, -GPU_KEY_SUFFIX.length));
14409
15002
  }
14410
15003
  this.#host.applyGpuMain(dressed);
14411
- if (gpu.on) gpu.dispatch(this.#host.render().renderer(), camera);
15004
+ if (gpu.on) gpu.dispatch(this.#host.render().renderer(), camera, root);
15005
+ }
15006
+ /**
15007
+ * An occupied cell whose placements have not been decoded yet holds nothing to draw, and its Y
15008
+ * range is still empty — a volume that cannot be tested against ±Infinity is not one a frame's
15009
+ * answer may rest on, so it is not packed.
15010
+ */
15011
+ #packCullBoxes() {
15012
+ this.#cullNames.length = 0;
15013
+ this.#cullBoxes = new Float64Array(this.#cullCells.size * 6);
15014
+ for (const [cell, { box }] of this.#cullCells) {
15015
+ if (box.isEmpty()) continue;
15016
+ const at = this.#cullNames.length * 6;
15017
+ box.min.toArray(this.#cullBoxes, at);
15018
+ box.max.toArray(this.#cullBoxes, at + 3);
15019
+ this.#cullNames.push(cell);
15020
+ }
15021
+ this.#cullBoxes = this.#cullBoxes.subarray(0, this.#cullNames.length * 6);
15022
+ this.#cullPacked = true;
14412
15023
  }
14413
15024
  /** Borrowed scratch box: consume its transformed volume before the next bounds query. */
14414
15025
  #boundsAt(bounds, matrix) {
14415
- this.#recordBounds.min.fromArray(bounds.min);
14416
- this.#recordBounds.max.fromArray(bounds.max);
14417
- return this.#recordBounds.applyMatrix4(matrix);
15026
+ return placedBox(this.#recordBounds, bounds.min, bounds.max, matrix);
14418
15027
  }
14419
15028
  /**
14420
15029
  * The one volume per resident visibility cell, shared by every key: its own XZ footprint, and in Y
@@ -14458,6 +15067,7 @@ var CellMainCull = class {
14458
15067
  this.#cullCells.set(name, entry);
14459
15068
  }
14460
15069
  entry.cells += 1;
15070
+ this.#cullPacked = false;
14461
15071
  const box = entry.box;
14462
15072
  for (const run of cell.runs) {
14463
15073
  const bounds = this.#manifest.assets[this.#host.render().canonical(run.asset)]?.bounds;
@@ -14491,7 +15101,10 @@ var CellMainCull = class {
14491
15101
  const entry = this.#cullCells.get(name);
14492
15102
  if (entry === void 0) return;
14493
15103
  entry.cells -= 1;
14494
- if (entry.cells <= 0) this.#cullCells.delete(name);
15104
+ if (entry.cells <= 0) {
15105
+ this.#cullCells.delete(name);
15106
+ this.#cullPacked = false;
15107
+ }
14495
15108
  }
14496
15109
  /**
14497
15110
  * `TN_WORLD_MAIN_CULL`, every `MAIN_CULL_MARKER_MS`: what the main pass holds, what it is drawing,
@@ -14593,11 +15206,14 @@ var CellMainCull = class {
14593
15206
  * is why it lives here: a caller that answered from a copy no frame wrote would hold everything.
14594
15207
  */
14595
15208
  intersectsObject(mesh) {
14596
- return _cullFrustum3.intersectsObject(mesh);
15209
+ return _cullFrustum.intersectsObject(mesh);
14597
15210
  }
14598
- /** The volume each resident visibility cell covers, which the chunk bounds widen on admission. */
14599
- cells() {
14600
- return this.#cullCells;
15211
+ /** Widen a resident visibility cell's volume by a chunk's bounds; an unknown cell is left alone. */
15212
+ widenCell(name, box) {
15213
+ const entry = this.#cullCells.get(name);
15214
+ if (entry === void 0) return;
15215
+ entry.box.union(box);
15216
+ this.#cullPacked = false;
14601
15217
  }
14602
15218
  /** The visibility cells the last cull kept, which the GPU dress's coarse gate reads. */
14603
15219
  get visible() {
@@ -14717,6 +15333,7 @@ var CellPrewarm = class {
14717
15333
  const batch = this.#drawBatches.get(object);
14718
15334
  if (!batch || batch.gpu !== void 0 || batch.role !== "main" || object.count <= 0 || !camera.layers.test(object.layers) || !frustum.intersectsObject(object))
14719
15335
  return;
15336
+ this.#drawBorrows.get(object)?.settle();
14720
15337
  if (this.#submitted.has(object)) return;
14721
15338
  pending++;
14722
15339
  active.add(object);
@@ -14728,6 +15345,11 @@ var CellPrewarm = class {
14728
15345
  const hadBefore = Object.hasOwn(object, "onBeforeRender");
14729
15346
  const hadAfter = Object.hasOwn(object, "onAfterRender");
14730
15347
  let before;
15348
+ let hookedAt;
15349
+ const renders = () => {
15350
+ const value = renderer.info.render?.calls;
15351
+ return Number.isSafeInteger(value) ? value : void 0;
15352
+ };
14731
15353
  const calls = () => {
14732
15354
  const value = renderer.info.render;
14733
15355
  const count3 = value?.drawCalls ?? value?.calls;
@@ -14746,6 +15368,7 @@ var CellPrewarm = class {
14746
15368
  before = void 0;
14747
15369
  ownBefore.apply(this, args);
14748
15370
  before = args[2] === camera && renderer.compiling !== true ? calls() : void 0;
15371
+ hookedAt = before === void 0 ? void 0 : renders();
14749
15372
  };
14750
15373
  const afterHook = function(...args) {
14751
15374
  const after = calls();
@@ -14754,13 +15377,21 @@ var CellPrewarm = class {
14754
15377
  release3();
14755
15378
  }
14756
15379
  before = void 0;
15380
+ hookedAt = void 0;
14757
15381
  ownAfter.apply(this, args);
14758
15382
  };
14759
15383
  markEngineRenderHook(beforeHook);
14760
15384
  markEngineRenderHook(afterHook);
14761
15385
  object.onBeforeRender = beforeHook;
14762
15386
  object.onAfterRender = afterHook;
14763
- this.#drawBorrows.set(object, { before: beforeHook, release: release3 });
15387
+ const settle = () => {
15388
+ const now = hookedAt === void 0 ? void 0 : renders();
15389
+ if (object.count > 0 && now !== void 0 && hookedAt !== void 0 && now > hookedAt) {
15390
+ submitted.add(object);
15391
+ release3();
15392
+ }
15393
+ };
15394
+ this.#drawBorrows.set(object, { before: beforeHook, release: release3, settle });
14764
15395
  });
14765
15396
  for (const [mesh, borrow] of this.#drawBorrows) if (!active.has(mesh)) borrow.release();
14766
15397
  return pending;
@@ -14860,7 +15491,7 @@ var CellPrewarm = class {
14860
15491
  return;
14861
15492
  const shared2 = new SharedBatch(
14862
15493
  entry.geometry,
14863
- entry.material,
15494
+ this.#host.lodSurface(entry.asset, entry.level, entry.part, entry.material),
14864
15495
  this.#host.runMax(entry.asset) ?? 1,
14865
15496
  this.#host.residentCells() + 1,
14866
15497
  entry.key,
@@ -15200,6 +15831,7 @@ var CellRender = class {
15200
15831
  if (entry.wide !== void 0)
15201
15832
  entry.wide.write(entry.wideSegment, entry.wideRoot ?? entry.batch, entry.lodRanges);
15202
15833
  }
15834
+ this.#host.cellBatchesChanged(cell);
15203
15835
  this.publishGpuGates(job.asset);
15204
15836
  const before = job.cell.placed?.get(job.run);
15205
15837
  const after = job.placed ?? [];
@@ -15771,6 +16403,7 @@ var CellRender = class {
15771
16403
  renderer: () => this.#host.renderer(),
15772
16404
  resident: () => this.#gpuResident,
15773
16405
  retired: () => this.#retired,
16406
+ root: () => this.#host.root(),
15774
16407
  shadowFloorOf: (assetId) => this.shadowFloorOf(assetId),
15775
16408
  shadowKeyFor: (key, part) => this.shadowKeyFor(key, part),
15776
16409
  shared: () => this.#shared,
@@ -15932,10 +16565,14 @@ var CellRender = class {
15932
16565
  }
15933
16566
  updateLodEye(x, y, z) {
15934
16567
  this.#dress.updateLodEye(x, y, z);
16568
+ this.#gpuScene.lodEye(x, y, z);
15935
16569
  }
15936
16570
  refreshLodMaterials(asset) {
15937
16571
  this.#dress.refreshLodMaterials(asset);
15938
16572
  }
16573
+ lodSurface(asset, level, part, source) {
16574
+ return this.#dress.lodSurface(asset, level, part, source);
16575
+ }
15939
16576
  impostorDrawn() {
15940
16577
  return this.#dress.impostorDrawn();
15941
16578
  }
@@ -16049,7 +16686,7 @@ var CellRender = class {
16049
16686
  if (box !== void 0) {
16050
16687
  if (proxies > 0) this.shadowRecordsMoved(box, true);
16051
16688
  if (this.#bundles.wanted)
16052
- this.#cull.cells().get(clusterOf(cell.x, cell.z, this.#cellsPerCullCell))?.box.union(box);
16689
+ this.#cull.widenCell(clusterOf(cell.x, cell.z, this.#cellsPerCullCell), box);
16053
16690
  }
16054
16691
  }
16055
16692
  enableGpu(renderer, wanted, validate, tally, occlusion) {
@@ -16197,17 +16834,7 @@ function autoLodPixelError(autoLod) {
16197
16834
  }
16198
16835
  var DEFAULT_MAIN_GPU_SHARE = 0.5;
16199
16836
  function launchValue(parameter, flag, globalName) {
16200
- const host = globalThis;
16201
- const env = host.process?.env?.[flag];
16202
- if (typeof env === "string" && env !== "") return env;
16203
- const query = globalThis.location?.search;
16204
- if (typeof query === "string") {
16205
- const value = new URLSearchParams(query).get(parameter);
16206
- if (value !== null) return value;
16207
- }
16208
- const global = host[globalName];
16209
- if (typeof global === "number") return String(global);
16210
- return typeof global === "string" ? global : void 0;
16837
+ return readLaunchValue({ environment: flag, global: globalName, query: parameter });
16211
16838
  }
16212
16839
  function impostorsRequested() {
16213
16840
  const raw = launchValue("tnImpostors", "TN_IMPOSTORS", "__tnImpostors");
@@ -16231,6 +16858,162 @@ function impostorFarOption(value) {
16231
16858
  throw new Error('WorldCells impostorFar must be "ring" or "always".');
16232
16859
  }
16233
16860
 
16861
+ // src/world-cell-stale.ts
16862
+ var STALE_HEADER = 8;
16863
+ var STALE_ENTRY = 12;
16864
+ var STALE_QUERY = 8;
16865
+ function length6(x, y, z = 0) {
16866
+ return Math.sqrt(x * x + y * y + z * z);
16867
+ }
16868
+ function span(left, near, size, x, z) {
16869
+ const right = left + size;
16870
+ const far = near + size;
16871
+ return [
16872
+ length6(Math.max(left - x, x - right, 0), Math.max(near - z, z - far, 0)),
16873
+ length6(
16874
+ Math.max(Math.abs(x - left), Math.abs(x - right)),
16875
+ Math.max(Math.abs(z - near), Math.abs(z - far))
16876
+ )
16877
+ ];
16878
+ }
16879
+ function crossesWorldGate(query, low, high) {
16880
+ const count3 = query[7];
16881
+ let start = 0;
16882
+ let end = count3;
16883
+ while (start < end) {
16884
+ const middle = start + end >> 1;
16885
+ if (query[STALE_QUERY + middle] < low) start = middle + 1;
16886
+ else end = middle;
16887
+ }
16888
+ return start < count3 && query[STALE_QUERY + start] <= high;
16889
+ }
16890
+ function vertical(y, minY, maxY) {
16891
+ return [Math.max(minY - y, y - maxY, 0), Math.max(Math.abs(y - minY), Math.abs(y - maxY))];
16892
+ }
16893
+ function reachCrossed(slab, at, cell, followY, brackets) {
16894
+ const minY = slab[at + 10];
16895
+ const maxY = slab[at + 11];
16896
+ const filterY = slab[at + 2];
16897
+ const [reachBuiltNear, reachBuiltFar] = span(
16898
+ slab[cell],
16899
+ slab[cell + 1],
16900
+ slab[cell + 2],
16901
+ slab[at + 1],
16902
+ slab[at + 3]
16903
+ );
16904
+ const current = vertical(followY, minY, maxY);
16905
+ const previous = vertical(filterY, minY, maxY);
16906
+ const reachLow = Math.min(length6(brackets[2], current[0]), length6(reachBuiltNear, previous[0]));
16907
+ const reachHigh = Math.max(length6(brackets[3], current[1]), length6(reachBuiltFar, previous[1]));
16908
+ return slab[at + 8] <= reachHigh && slab[at + 9] >= reachLow;
16909
+ }
16910
+ function entryStale(slab, at, cell, gates, query, brackets) {
16911
+ const x = query[0];
16912
+ const followY = query[1];
16913
+ const z = query[2];
16914
+ const eyeX = query[3];
16915
+ const eyeY = query[4];
16916
+ const eyeZ = query[5];
16917
+ const gpuOn = query[6];
16918
+ const left = slab[cell];
16919
+ const nearZ = slab[cell + 1];
16920
+ const size = slab[cell + 2];
16921
+ const [eyeNear, eyeFar] = brackets;
16922
+ const threshold = slab[at + 7];
16923
+ const reachMin = slab[at + 8];
16924
+ const reach = !Number.isNaN(reachMin);
16925
+ if (!reach && (gpuOn === 1 || Number.isNaN(threshold))) return false;
16926
+ const step = (Number.isNaN(threshold) ? 6 : threshold) / 8;
16927
+ const filterX = slab[at + 1];
16928
+ const filterY = slab[at + 2];
16929
+ const filterZ = slab[at + 3];
16930
+ const lodX = slab[at + 4];
16931
+ const lodY = slab[at + 5];
16932
+ const lodZ = slab[at + 6];
16933
+ if (length6(x - filterX, followY - filterY, z - filterZ) <= step && length6(eyeX - lodX, eyeY - lodY, eyeZ - lodZ) <= step)
16934
+ return false;
16935
+ const asset = slab[at];
16936
+ const gateAt = gates[1 + asset * 2];
16937
+ if (gateAt < 0) return false;
16938
+ const gateCount = gpuOn === 1 ? 0 : gates[2 + asset * 2];
16939
+ const [builtNear, builtFar] = span(left, nearZ, size, lodX, lodZ);
16940
+ let low = Math.min(eyeNear, builtNear);
16941
+ let high = Math.max(eyeFar, builtFar);
16942
+ if (reach) {
16943
+ const minY = slab[at + 10];
16944
+ const maxY = slab[at + 11];
16945
+ const eyeNow = vertical(eyeY, minY, maxY);
16946
+ const eyeBefore = vertical(lodY, minY, maxY);
16947
+ low = Math.min(length6(eyeNear, eyeNow[0]), length6(builtNear, eyeBefore[0]));
16948
+ high = Math.max(length6(eyeFar, eyeNow[1]), length6(builtFar, eyeBefore[1]));
16949
+ if (reachCrossed(slab, at, cell, followY, brackets)) return true;
16950
+ }
16951
+ for (let gate = 0; gate < gateCount; gate += 1) {
16952
+ const value = gates[gateAt + gate];
16953
+ if (value >= low && value <= high) return true;
16954
+ }
16955
+ return false;
16956
+ }
16957
+ function staleRows(slab, gates, query) {
16958
+ const out = [];
16959
+ const seen = /* @__PURE__ */ new Set();
16960
+ const x = query[0];
16961
+ const z = query[2];
16962
+ const eyeX = query[3];
16963
+ const eyeZ = query[5];
16964
+ const gpuOn = query[6];
16965
+ let ordinal = 0;
16966
+ for (let cell = 0; cell < slab.length; ordinal += 1) {
16967
+ const entries = slab[cell + 6];
16968
+ const next = cell + STALE_HEADER + entries * STALE_ENTRY;
16969
+ const left = slab[cell];
16970
+ const nearZ = slab[cell + 1];
16971
+ const size = slab[cell + 2];
16972
+ const hasReach = slab[cell + 5] === 1;
16973
+ const [eyeNear, eyeFar] = span(left, nearZ, size, eyeX, eyeZ);
16974
+ const low = Math.min(eyeNear, slab[cell + 3]);
16975
+ const high = Math.max(eyeFar, slab[cell + 4]);
16976
+ if (gpuOn === 1 && !hasReach || !hasReach && !crossesWorldGate(query, low, high)) {
16977
+ cell = next;
16978
+ continue;
16979
+ }
16980
+ const [near, far] = span(left, nearZ, size, x, z);
16981
+ seen.clear();
16982
+ for (let at = cell + STALE_HEADER; at < next; at += STALE_ENTRY) {
16983
+ const asset = slab[at];
16984
+ if (seen.has(asset)) continue;
16985
+ if (!entryStale(slab, at, cell, gates, query, [eyeNear, eyeFar, near, far])) continue;
16986
+ seen.add(asset);
16987
+ out.push(ordinal, asset, eyeNear);
16988
+ }
16989
+ cell = next;
16990
+ }
16991
+ return out;
16992
+ }
16993
+ function patchRows(held, blocks, plan) {
16994
+ let length7 = 0;
16995
+ for (let at = 1; at < plan.length; at += 2) length7 += plan[at];
16996
+ const next = new Float64Array(length7);
16997
+ let written = 0;
16998
+ let taken = 0;
16999
+ for (let at = 0; at + 1 < plan.length; at += 2) {
17000
+ const source = plan[at];
17001
+ const count3 = plan[at + 1];
17002
+ const from = source === -1 ? blocks : held;
17003
+ const start = source === -1 ? taken : source;
17004
+ if (!(Number.isInteger(start) && Number.isInteger(count3) && start >= 0 && count3 >= 0 && start + count3 <= from.length))
17005
+ throw new RangeError(
17006
+ `TN_WORLD_STALE: a plan run [${String(source)}, ${String(count3)}] is outside its rows`
17007
+ );
17008
+ next.set(from.subarray(start, start + count3), written);
17009
+ written += count3;
17010
+ if (source === -1) taken += count3;
17011
+ }
17012
+ if (taken !== blocks.length)
17013
+ throw new RangeError("TN_WORLD_STALE: the plan leaves changed blocks unread");
17014
+ return next;
17015
+ }
17016
+
16234
17017
  // src/world-cell-placements.ts
16235
17018
  function newBatches(asset) {
16236
17019
  const batches = [];
@@ -16256,6 +17039,14 @@ function newBoxes(batches) {
16256
17039
  }
16257
17040
  return boxes;
16258
17041
  }
17042
+ function extendPlan(plan, source, count3) {
17043
+ const last = plan.length - 2;
17044
+ const runSource = plan[last];
17045
+ const runCount = plan[last + 1];
17046
+ const joins = runSource !== void 0 && (source === -1 ? runSource === -1 : runSource >= 0 && runSource + runCount === source);
17047
+ if (joins) plan[last + 1] = runCount + count3;
17048
+ else plan.push(source, count3);
17049
+ }
16259
17050
  var CellPlacements = class {
16260
17051
  #host;
16261
17052
  /** The authored placement records, immutable for the world's life. */
@@ -16271,9 +17062,22 @@ var CellPlacements = class {
16271
17062
  #placementRanges;
16272
17063
  /** Every distinct gate distance the world's assets have, ascending; see `noteGate`. */
16273
17064
  #gates = [];
16274
- /** The reused hit list and the reused per-cell seen set; see `#staleIn`. */
17065
+ /** The reused hit list; see `#collectStale`. */
16275
17066
  #stale = [];
16276
- #staleSeen = /* @__PURE__ */ new Set();
17067
+ /** Per cell, its block of the stale scan's slab, dropped when the cell's batches change. */
17068
+ #rows = /* @__PURE__ */ new WeakMap();
17069
+ /** The resident cells' blocks laid end to end, and the cells in block order; see `#collectStale`. */
17070
+ #slab = new Float64Array(0);
17071
+ #slabCells = [];
17072
+ /** Where each cell's block sits in the slab the last pack sent; an unchanged block is not sent again. */
17073
+ #slabAt = /* @__PURE__ */ new Map();
17074
+ #slabEpoch = -1;
17075
+ #slabStale = true;
17076
+ /** Asset ids by the index the slab names them with; the index only ever grows. */
17077
+ #assetIds = [];
17078
+ #assetIndex = /* @__PURE__ */ new Map();
17079
+ /** The owned engine's `__tnStaleEntries` host; on upstream three it has no such method. */
17080
+ #engine = new Object3D();
16277
17081
  /** Stale cell-assets the passes found, cumulative; see `IWorldCellsStats.refilterEntries`. */
16278
17082
  #staleEntries = 0;
16279
17083
  /** Refilter passes run, whether or not they queued anything; see `IWorldCellsStats.refilters`. */
@@ -16342,9 +17146,7 @@ var CellPlacements = class {
16342
17146
  }
16343
17147
  /** Borrowed scratch box: consume its transformed volume before the next bounds query. */
16344
17148
  #boundsAt(bounds, matrix) {
16345
- this.#recordBounds.min.fromArray(bounds.min);
16346
- this.#recordBounds.max.fromArray(bounds.max);
16347
- return this.#recordBounds.applyMatrix4(matrix);
17149
+ return placedBox(this.#recordBounds, bounds.min, bounds.max, matrix);
16348
17150
  }
16349
17151
  /**
16350
17152
  * Does this update have to run the `maxDistance`/`lods` refilter pass?
@@ -16453,16 +17255,16 @@ var CellPlacements = class {
16453
17255
  this.#placementRanges[record] = minPublished + 1 | maxPublished + 1 << 4;
16454
17256
  }
16455
17257
  const bounds = asset.definition.bounds;
16456
- const placedBox = this.#boundsAt(bounds, this.#matrix);
17258
+ const placedBox2 = this.#boundsAt(bounds, this.#matrix);
16457
17259
  job.placed ??= [];
16458
17260
  job.placed.push(
16459
17261
  index,
16460
- placedBox.min.x,
16461
- placedBox.min.y,
16462
- placedBox.min.z,
16463
- placedBox.max.x,
16464
- placedBox.max.y,
16465
- placedBox.max.z
17262
+ placedBox2.min.x,
17263
+ placedBox2.min.y,
17264
+ placedBox2.min.z,
17265
+ placedBox2.max.x,
17266
+ placedBox2.max.y,
17267
+ placedBox2.max.z
16466
17268
  );
16467
17269
  for (level of selected) {
16468
17270
  if (wantRoots) {
@@ -16501,7 +17303,6 @@ var CellPlacements = class {
16501
17303
  z: centre.z
16502
17304
  });
16503
17305
  }
16504
- this.#boundsAt(bounds, this.#matrix);
16505
17306
  const parts = asset.levels[level];
16506
17307
  const levelBatches = job.batches?.[level];
16507
17308
  const levelBoxes = job.boxes?.[level];
@@ -16535,6 +17336,12 @@ var CellPlacements = class {
16535
17336
  const [near, far] = this.#span(cell, filterX, filterZ);
16536
17337
  if (near < cell.filterNear) cell.filterNear = near;
16537
17338
  if (far > cell.filterFar) cell.filterFar = far;
17339
+ this.cellBatchesChanged(cell);
17340
+ }
17341
+ /** The cell's batches or bracket changed, so its block of the stale scan is rebuilt. */
17342
+ cellBatchesChanged(cell) {
17343
+ this.#rows.delete(cell);
17344
+ this.#slabStale = true;
16538
17345
  }
16539
17346
  buildOne(job, batches) {
16540
17347
  const { asset } = job;
@@ -16599,71 +17406,6 @@ var CellPlacements = class {
16599
17406
  )
16600
17407
  ];
16601
17408
  }
16602
- /**
16603
- * One entry per asset of `cell` the follow point has moved a gate of, nearest placement first.
16604
- *
16605
- * The cell's own bracket is the caller's: it was derived once for the cell, and every batch of a
16606
- * cell is measured against the same rectangle, so deriving it per batch was the same four
16607
- * `Math.max` and two `Math.hypot` calls as many times as the cell had batches. What is left here is
16608
- * per batch: one moved-point test and, for a batch that moved, its own bracket.
16609
- *
16610
- * Nothing is allocated to find them: the entries go into one reused array, the per-cell "already
16611
- * seen" set into another, and a pass that crossed no gate anywhere pushes nothing at all.
16612
- */
16613
- #staleIn(cell, x, z, near, far) {
16614
- const seen = this.#staleSeen;
16615
- seen.clear();
16616
- const eye = this.#host.eye();
16617
- const [eyeNear, eyeFar] = this.#span(cell, eye.x, eye.z);
16618
- for (const entry of cell.batches) {
16619
- const reach = this.#reachRanges.get(cell.cell)?.get(entry.asset);
16620
- if (entry.threshold === void 0 && reach === void 0 || seen.has(entry.asset)) continue;
16621
- const step = (entry.threshold ?? 6) / 8;
16622
- if (Math.hypot(
16623
- x - entry.lastFilterX,
16624
- this.followY() - entry.lastFilterY,
16625
- z - entry.lastFilterZ
16626
- ) <= step && Math.hypot(eye.x - entry.lastLodX, eye.y - entry.lastLodY, eye.z - entry.lastLodZ) <= step)
16627
- continue;
16628
- const asset = this.#host.asset(entry.asset);
16629
- if (asset === void 0) continue;
16630
- const gates = this.#host.gpuOn() ? [] : asset.gates;
16631
- const [builtNear, builtFar] = this.#span(cell, entry.lastLodX, entry.lastLodZ);
16632
- let low = Math.min(eyeNear, builtNear);
16633
- let high = Math.max(eyeFar, builtFar);
16634
- let reachCrossed = false;
16635
- if (reach !== void 0) {
16636
- const vertical = (y) => [
16637
- Math.max(reach.minY - y, y - reach.maxY, 0),
16638
- Math.max(Math.abs(y - reach.minY), Math.abs(y - reach.maxY))
16639
- ];
16640
- const eyeNow = vertical(eye.y);
16641
- const eyeBefore = vertical(entry.lastLodY);
16642
- low = Math.min(Math.hypot(eyeNear, eyeNow[0]), Math.hypot(builtNear, eyeBefore[0]));
16643
- high = Math.max(Math.hypot(eyeFar, eyeNow[1]), Math.hypot(builtFar, eyeBefore[1]));
16644
- const [reachBuiltNear, reachBuiltFar] = this.#span(
16645
- cell,
16646
- entry.lastFilterX,
16647
- entry.lastFilterZ
16648
- );
16649
- const current = vertical(this.followY());
16650
- const previous = vertical(entry.lastFilterY);
16651
- const reachLow = Math.min(
16652
- Math.hypot(near, current[0]),
16653
- Math.hypot(reachBuiltNear, previous[0])
16654
- );
16655
- const reachHigh = Math.max(
16656
- Math.hypot(far, current[1]),
16657
- Math.hypot(reachBuiltFar, previous[1])
16658
- );
16659
- reachCrossed = reach.min <= reachHigh && reach.max >= reachLow;
16660
- }
16661
- if (!reachCrossed && !gates.some((gate) => gate >= low && gate <= high)) continue;
16662
- seen.add(entry.asset);
16663
- this.#stale.push({ cell, distance: eyeNear, id: entry.asset });
16664
- this.#staleEntries += 1;
16665
- }
16666
- }
16667
17409
  /**
16668
17410
  * Record that one more gate distance exists, keeping the world's list ascending so
16669
17411
  * {@link crossesGate} can binary search it. A gate is never withdrawn: an asset whose ring left
@@ -16722,14 +17464,141 @@ var CellPlacements = class {
16722
17464
  * which the follow point has not yet reached anything that switches.
16723
17465
  */
16724
17466
  #collectStale(x, z) {
17467
+ const epoch = this.#host.residencyEpoch();
17468
+ if (this.#slabStale || this.#slabEpoch !== epoch) this.#packSlab(epoch);
17469
+ const eye = this.#host.eye();
17470
+ const query = new Float64Array(STALE_QUERY + this.#gates.length);
17471
+ query.set([
17472
+ x,
17473
+ this.followY(),
17474
+ z,
17475
+ eye.x,
17476
+ eye.y,
17477
+ eye.z,
17478
+ this.#host.gpuOn() ? 1 : 0,
17479
+ this.#gates.length
17480
+ ]);
17481
+ query.set(this.#gates, STALE_QUERY);
17482
+ const gates = this.#gateTable();
17483
+ const found = typeof this.#engine.__tnStaleEntries === "function" ? this.#engine.__tnStaleEntries(gates, query) : staleRows(this.#slab, gates, query);
17484
+ for (let at = 0; at < found.length; at += 3) {
17485
+ this.#stale.push({
17486
+ cell: this.#slabCells[found[at]],
17487
+ distance: found[at + 2],
17488
+ id: this.#assetIds[found[at + 1]]
17489
+ });
17490
+ this.#staleEntries += 1;
17491
+ }
17492
+ }
17493
+ /**
17494
+ * The resident cells' blocks end to end; only a changed cell builds its block again, and only the
17495
+ * changed blocks are sent: an unchanged one is a `[source, count]` run of the slab already held
17496
+ * (see `patchRows`).
17497
+ */
17498
+ #packSlab(epoch) {
17499
+ const plan = [];
17500
+ const changed = [];
17501
+ const cells = [];
17502
+ const placed = /* @__PURE__ */ new Map();
17503
+ let length7 = 0;
17504
+ let sent = 0;
16725
17505
  for (const cell of this.#host.resident()) {
16726
- const [eyeNear, eyeFar] = this.#span(cell, this.#host.eye().x, this.#host.eye().z);
16727
- const low = eyeNear < cell.filterNear ? eyeNear : cell.filterNear;
16728
- const high = eyeFar > cell.filterFar ? eyeFar : cell.filterFar;
16729
- if (!this.#reachRanges.has(cell.cell) && !crossesGate(this.#gates, low, high)) continue;
16730
- const [near, far] = this.#span(cell, x, z);
16731
- this.#staleIn(cell, x, z, near, far);
17506
+ const rows = this.#rowsOf(cell);
17507
+ const held = this.#slabAt.get(cell);
17508
+ const source = held !== void 0 && held.rows === rows ? held.at : -1;
17509
+ extendPlan(plan, source, rows.length);
17510
+ if (source === -1) {
17511
+ changed.push(rows);
17512
+ sent += rows.length;
17513
+ }
17514
+ placed.set(cell, { at: length7, rows });
17515
+ cells.push(cell);
17516
+ length7 += rows.length;
16732
17517
  }
17518
+ const blocks = new Float64Array(sent);
17519
+ let at = 0;
17520
+ for (const block of changed) {
17521
+ blocks.set(block, at);
17522
+ at += block.length;
17523
+ }
17524
+ if (typeof this.#engine.__tnStaleEntries === "function") {
17525
+ if (typeof this.#engine.__tnStaleRows !== "function")
17526
+ throw new Error("TN_WORLD_STALE: the engine has __tnStaleEntries but no __tnStaleRows");
17527
+ this.#engine.__tnStaleRows(blocks, Float64Array.from(plan));
17528
+ } else this.#slab = patchRows(this.#slab, blocks, plan);
17529
+ this.#slabAt = placed;
17530
+ this.#slabCells = cells;
17531
+ this.#slabEpoch = epoch;
17532
+ this.#slabStale = false;
17533
+ }
17534
+ /** One cell's block: its rectangle and bracket, then each batch entry's filter state. */
17535
+ #rowsOf(cell) {
17536
+ const cached = this.#rows.get(cell);
17537
+ if (cached !== void 0 && cached.batches === cell.batches.length) return cached.rows;
17538
+ this.#grid ??= this.#host.extent();
17539
+ const { cellSize, minX, minZ } = this.#grid;
17540
+ const reach = this.#reachRanges.get(cell.cell);
17541
+ const rows = new Float64Array(STALE_HEADER + cell.batches.length * STALE_ENTRY);
17542
+ rows.set([
17543
+ minX + cell.x * cellSize,
17544
+ minZ + cell.z * cellSize,
17545
+ cellSize,
17546
+ cell.filterNear,
17547
+ cell.filterFar,
17548
+ reach === void 0 ? 0 : 1,
17549
+ cell.batches.length,
17550
+ 0
17551
+ ]);
17552
+ let at = STALE_HEADER;
17553
+ for (const entry of cell.batches) {
17554
+ const range = reach?.get(entry.asset);
17555
+ rows.set(
17556
+ [
17557
+ this.#assetSlot(entry.asset),
17558
+ entry.lastFilterX,
17559
+ entry.lastFilterY,
17560
+ entry.lastFilterZ,
17561
+ entry.lastLodX,
17562
+ entry.lastLodY,
17563
+ entry.lastLodZ,
17564
+ entry.threshold ?? Number.NaN,
17565
+ range?.min ?? Number.NaN,
17566
+ range?.max ?? Number.NaN,
17567
+ range?.minY ?? Number.NaN,
17568
+ range?.maxY ?? Number.NaN
17569
+ ],
17570
+ at
17571
+ );
17572
+ at += STALE_ENTRY;
17573
+ }
17574
+ this.#rows.set(cell, { rows, batches: cell.batches.length });
17575
+ return rows;
17576
+ }
17577
+ #assetSlot(id) {
17578
+ let slot = this.#assetIndex.get(id);
17579
+ if (slot === void 0) {
17580
+ slot = this.#assetIds.length;
17581
+ this.#assetIds.push(id);
17582
+ this.#assetIndex.set(id, slot);
17583
+ }
17584
+ return slot;
17585
+ }
17586
+ /** Each slab asset's gates, read live: `[count, [at, count]..., values]`, `at` -1 for a gone asset. */
17587
+ #gateTable() {
17588
+ const ids = this.#assetIds;
17589
+ let values = 0;
17590
+ for (const id of ids) values += this.#host.asset(id)?.gates.length ?? 0;
17591
+ const table = new Float64Array(1 + ids.length * 2 + values);
17592
+ table[0] = ids.length;
17593
+ let at = 1 + ids.length * 2;
17594
+ for (const [slot, id] of ids.entries()) {
17595
+ const gates = this.#host.asset(id)?.gates;
17596
+ table[1 + slot * 2] = gates === void 0 ? -1 : at;
17597
+ table[2 + slot * 2] = gates?.length ?? 0;
17598
+ if (gates !== void 0) table.set(gates, at);
17599
+ at += gates?.length ?? 0;
17600
+ }
17601
+ return table;
16733
17602
  }
16734
17603
  };
16735
17604
  var _readinessPosition = new Vector3();
@@ -17111,17 +17980,21 @@ var CellResidency = class {
17111
17980
  * resting near the gate does not flip the eye between the two.
17112
17981
  */
17113
17982
  updateEye() {
17114
- const follow = this.#eyeFollow.set(
17115
- this.#host.follow().position.x,
17116
- this.#host.parts().placements.followY(),
17117
- this.#host.follow().position.z
17983
+ const root = this.#host.root();
17984
+ const follow = localPoint(
17985
+ this.#eyeFollow.set(
17986
+ this.#host.follow().position.x,
17987
+ this.#host.parts().placements.followY(),
17988
+ this.#host.follow().position.z
17989
+ ),
17990
+ root
17118
17991
  );
17119
17992
  const camera = this.#host.lodFrom() === "camera" ? this.#host.parts().chunks.camera : void 0;
17120
17993
  if (camera === void 0) {
17121
17994
  this.#eye.copy(follow);
17122
17995
  return;
17123
17996
  }
17124
- this.#eye.setFromMatrixPosition(camera.matrixWorld);
17997
+ localPoint(this.#eye.setFromMatrixPosition(camera.matrixWorld), root);
17125
17998
  if (this.#host.parts().placements.placementReach === void 0) this.#eye.y = 0;
17126
17999
  const inside = this.#host.parts().placements.firstGate;
17127
18000
  const offset = this.#eye.distanceTo(follow);
@@ -17159,10 +18032,10 @@ var CellResidency = class {
17159
18032
  let leadX = this.#velocityX * this.#host.prefetchSeconds();
17160
18033
  let leadZ = this.#velocityZ * this.#host.prefetchSeconds();
17161
18034
  const limit = cellSize * this.#host.ring() * 0.75;
17162
- const length6 = Math.hypot(leadX, leadZ);
17163
- if (length6 > limit) {
17164
- leadX *= limit / length6;
17165
- leadZ *= limit / length6;
18035
+ const length7 = Math.hypot(leadX, leadZ);
18036
+ if (length7 > limit) {
18037
+ leadX *= limit / length7;
18038
+ leadZ *= limit / length7;
17166
18039
  }
17167
18040
  return { x: x + leadX, z: z + leadZ };
17168
18041
  }
@@ -17617,6 +18490,8 @@ var WorldCells = class _WorldCells extends Group {
17617
18490
  #adaptiveBias;
17618
18491
  #render;
17619
18492
  #onPublication;
18493
+ /** Publications told after the frame's records reach the engine, so a told batch is drawable. */
18494
+ #publications = [];
17620
18495
  /** The spawn and view gates, and the waiters they settle. */
17621
18496
  #readiness;
17622
18497
  #prewarm;
@@ -17654,7 +18529,8 @@ var WorldCells = class _WorldCells extends Group {
17654
18529
  casts: (level) => this.#render.casts(level),
17655
18530
  wideOwed: (asset, part) => this.#render.wideOwed(asset, part),
17656
18531
  followCluster: () => this.#render.followCluster(),
17657
- wideShape: (asset, level, part, fallback) => this.#render.wideShape(asset, level, part, fallback)
18532
+ wideShape: (asset, level, part, fallback) => this.#render.wideShape(asset, level, part, fallback),
18533
+ lodSurface: (asset, level, part, source) => this.#render.lodSurface(asset, level, part, source)
17658
18534
  });
17659
18535
  this.#init = { ...init };
17660
18536
  this.#budgets = {
@@ -17840,11 +18716,16 @@ var WorldCells = class _WorldCells extends Group {
17840
18716
  canonical: (id) => this.#canonical(id),
17841
18717
  renderer: () => this.#chunks.renderer,
17842
18718
  camera: () => this.#chunks.camera,
18719
+ // Live, not a snapshot: three refreshes `matrixWorld` before it renders, so a game that moves
18720
+ // the root reads its own frame from the next update on — the same answer `stepCellProxies`
18721
+ // is handed below.
18722
+ root: () => this.matrixWorld,
17843
18723
  now: () => this.#now(),
17844
18724
  stats: () => this.stats(),
17845
18725
  residentCells: () => this.#residency.resident.values(),
17846
18726
  runMax: (asset) => this.#runMax.get(asset),
17847
18727
  widenFilterRange: (cell, x, z) => this.#placementBuild.widenFilterRange(cell, x, z),
18728
+ cellBatchesChanged: (cell) => this.#placementBuild.cellBatchesChanged(cell),
17848
18729
  addUnchanged: () => {
17849
18730
  this.#unchanged += 1;
17850
18731
  },
@@ -18027,10 +18908,11 @@ var WorldCells = class _WorldCells extends Group {
18027
18908
  parts: () => parts,
18028
18909
  prefetchSeconds: () => this.#prefetchSeconds,
18029
18910
  published: (bounds) => {
18030
- this.#onPublication?.(bounds);
18911
+ if (this.#onPublication !== void 0) this.#publications.push(bounds.clone());
18031
18912
  },
18032
18913
  released: () => this.#released,
18033
- ring: () => this.#ring
18914
+ ring: () => this.#ring,
18915
+ root: () => this.matrixWorld
18034
18916
  });
18035
18917
  this.#readiness = new CellReadiness({
18036
18918
  asset: (id) => this.#models.asset(id),
@@ -18322,7 +19204,6 @@ var WorldCells = class _WorldCells extends Group {
18322
19204
  this.#render.seedGpuKeys();
18323
19205
  this.#render.announceGpu();
18324
19206
  }
18325
- advanceWriteEpoch();
18326
19207
  const x = this.#follow.position.x;
18327
19208
  const z = this.#follow.position.z;
18328
19209
  const budgetMs = this.#covered ? this.#coveredBudgetMs : this.#budgetMs;
@@ -18365,6 +19246,8 @@ var WorldCells = class _WorldCells extends Group {
18365
19246
  camera
18366
19247
  );
18367
19248
  this.#render.reportMainCull();
19249
+ batchRecords.flush();
19250
+ this.#tellPublications();
18368
19251
  this.#admission = {
18369
19252
  backlog: this.#residency.backlog(),
18370
19253
  deferred: this.#residency.queuedBuilds,
@@ -18372,6 +19255,10 @@ var WorldCells = class _WorldCells extends Group {
18372
19255
  };
18373
19256
  this.#readiness.settleWaiters();
18374
19257
  }
19258
+ /** The frame's publications, told once their records are in the engine's buffers. */
19259
+ #tellPublications() {
19260
+ for (const bounds of this.#publications.splice(0)) this.#onPublication?.(bounds);
19261
+ }
18375
19262
  process(renderer, camera, covered = false) {
18376
19263
  this.#covered = covered;
18377
19264
  try {
@@ -18554,4 +19441,4 @@ var WorldCells = class _WorldCells extends Group {
18554
19441
  }
18555
19442
  };
18556
19443
 
18557
- export { Heightfield, HeightfieldCollar, NOISE_PERIOD, NOISE_TEXELS, SnowField, TERRAIN_VALIDATE_FLAG, TERRAIN_VALIDATE_MARKER, TerrainTiles, WATER_RIBBON_REACH, WaterBodies, WorldCells, applyTerrainSurface, bakedFractalNoise, bakedNoise, cellPlacements, getWorldCapabilities, heightSamplerFromHeightmap, instanceRandom, lakeReach, loadTerrainSplat, loadWorldHeightmap, noiseVolume, snowDiscFootprint, terrainValidationRequested, validateWorldPackage, waterlineRadius };
19444
+ export { AdmissionBudget, Heightfield, HeightfieldCollar, NOISE_PERIOD, NOISE_TEXELS, SnowField, TERRAIN_VALIDATE_FLAG, TERRAIN_VALIDATE_MARKER, TerrainTiles, WATER_RIBBON_REACH, WaterBodies, WorldCells, applyTerrainSurface, bakedFractalNoise, bakedNoise, baseRingGap, cellPlacements, footprintGap, getWorldCapabilities, heightSamplerFromHeightmap, instanceRandom, lakeReach, lakeSurfaceGeometry, loadTerrainSplat, loadWorldHeightmap, meshSections, noiseVolume, repairZeroNormals, riverRibbonGeometry, sectionGeometry, shoreField, snowDiscFootprint, staticLowestY, surfaceSampler, terrainValidationRequested, validateWorldPackage, warmUnculled, waterlineRadius };