@threenative/core 0.3.12 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +746 -32
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-4SRAQFTU.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-DIPIJICH.js} +1590 -375
  7. package/dist/{chunk-OKXUCASC.js → chunk-EEABDLUC.js} +3 -4
  8. package/dist/{chunk-5O73CDMR.js → chunk-EFWZWLPY.js} +62 -16
  9. package/dist/{chunk-N5LRP4BR.js → chunk-GYUZJQ7U.js} +63 -3
  10. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  11. package/dist/{chunk-2Z44XSI2.js → chunk-SV4QVUTQ.js} +3 -7
  12. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  13. package/dist/chunk-VP43GIWW.js +18 -0
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +289 -1034
  20. package/dist/index.js +3096 -1305
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BYqKGAwo.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +269 -15
  33. package/dist/world.js +1372 -628
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +105 -7
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/src/animation-batch.ts +193 -0
  39. package/src/animation-layers.ts +7 -3
  40. package/src/animation.ts +209 -29
  41. package/src/asset-cache.ts +3 -3
  42. package/src/asset-memo.ts +202 -0
  43. package/src/assets.ts +436 -131
  44. package/src/auto-batch.ts +190 -44
  45. package/src/compute-driven.ts +1 -1
  46. package/src/config.ts +8 -0
  47. package/src/debug.ts +103 -22
  48. package/src/dev-global.ts +54 -0
  49. package/src/engine-hooks.ts +37 -0
  50. package/src/frame-budget.ts +19 -3
  51. package/src/game-boot-phase.ts +269 -0
  52. package/src/game-dev-tools.ts +7 -14
  53. package/src/game-frame-loop.ts +45 -82
  54. package/src/game-startup.ts +145 -70
  55. package/src/game-ui.ts +84 -0
  56. package/src/game.ts +168 -552
  57. package/src/gamepad-mappings.ts +269 -0
  58. package/src/generated/console-markers.ts +13 -0
  59. package/src/geometry-capture.ts +28 -4
  60. package/src/gpu-readings.ts +98 -0
  61. package/src/gpu-scene-bvh.ts +149 -36
  62. package/src/hot.ts +4 -7
  63. package/src/index.ts +115 -8
  64. package/src/input.ts +237 -25
  65. package/src/instanced-batch-lod.ts +3 -8
  66. package/src/interpolation.ts +171 -40
  67. package/src/look/ao-admission.ts +4 -3
  68. package/src/look/auto-exposure.ts +5 -16
  69. package/src/look/default-tone-mapping.ts +41 -5
  70. package/src/look/local-exposure.ts +2 -7
  71. package/src/look/quad-pass.ts +21 -0
  72. package/src/look/quality.ts +4 -0
  73. package/src/look/unreal-bloom.ts +4 -13
  74. package/src/look/world-environment.ts +58 -115
  75. package/src/merge-parts.ts +20 -24
  76. package/src/model-lod.ts +97 -14
  77. package/src/particle-significance.ts +12 -0
  78. package/src/particles.ts +19 -10
  79. package/src/platform.ts +23 -4
  80. package/src/profiling/FrameStages.ts +5 -6
  81. package/src/profiling/Spans.ts +3 -17
  82. package/src/profiling/debug-telemetry.ts +2 -6
  83. package/src/profiling/render-list-validate.ts +6 -15
  84. package/src/projection-marker.ts +2 -1
  85. package/src/quiet-markers.ts +3 -10
  86. package/src/render/cpu-bvh.ts +100 -0
  87. package/src/render/depth-pyramid.ts +6 -14
  88. package/src/render/environment/environmentContribution.ts +202 -0
  89. package/src/render/environment/environmentRadiance.ts +44 -0
  90. package/src/render/environment/environmentSampleCache.ts +56 -0
  91. package/src/render/environment/environmentSampling.ts +201 -0
  92. package/src/render/environment/environmentSnapshot.ts +71 -0
  93. package/src/render/environment/gate.ts +57 -0
  94. package/src/render/mesh-pool.ts +3 -19
  95. package/src/render/probe-trace.ts +872 -0
  96. package/src/render/probe-volume.ts +780 -34
  97. package/src/render/radiance-cache.ts +17 -0
  98. package/src/render/virtual-shadow-partial.ts +13 -0
  99. package/src/render/virtual-shadow.ts +18 -16
  100. package/src/render/world-impostor-surface.ts +109 -6
  101. package/src/render/world-impostor.ts +5 -2
  102. package/src/render-camera-cull.ts +98 -3
  103. package/src/render-environment.ts +41 -0
  104. package/src/renderer-config.ts +36 -0
  105. package/src/renderer-facts.ts +37 -0
  106. package/src/renderer.ts +52 -28
  107. package/src/resolution-scaler.ts +3 -2
  108. package/src/scene-entry-inspectors.ts +61 -0
  109. package/src/snow-field.ts +1 -0
  110. package/src/startup-offscreen-bytes.ts +78 -0
  111. package/src/static-transform.ts +25 -19
  112. package/src/streamed-textures.ts +112 -0
  113. package/src/streaming.ts +68 -4
  114. package/src/texture-streaming.ts +331 -0
  115. package/src/version.ts +1 -1
  116. package/src/worker.ts +12 -2
  117. package/src/world-bundle-safety.ts +55 -10
  118. package/src/world-cell-batches.ts +162 -200
  119. package/src/world-cell-chunks.ts +3 -7
  120. package/src/world-cell-impostors.ts +20 -8
  121. package/src/world-cell-options.ts +2 -14
  122. package/src/world-cell-placements.ts +194 -90
  123. package/src/world-cell-prewarm.ts +39 -4
  124. package/src/world-cell-records.ts +401 -0
  125. package/src/world-cell-render-bundles.ts +2 -2
  126. package/src/world-cell-render-gpu-dress.ts +13 -17
  127. package/src/world-cell-render-main-cull.ts +73 -17
  128. package/src/world-cell-render-util.ts +17 -4
  129. package/src/world-cell-render.ts +13 -5
  130. package/src/world-cell-residency.ts +15 -6
  131. package/src/world-cell-stale.ts +238 -0
  132. package/src/world-cells.ts +22 -5
  133. package/src/world-gpu-flags.ts +18 -50
  134. package/src/world-gpu-reference.ts +22 -8
  135. package/src/world-gpu-scene.ts +44 -24
  136. package/src/world-gpu-shadow.ts +21 -8
  137. package/src/world-gpu-types.ts +41 -13
  138. package/src/world-load-limiter.ts +5 -0
  139. package/src/world-model-sections.ts +80 -0
  140. package/src/world-river-ribbon.ts +282 -0
  141. package/src/world-root-frame.ts +39 -0
  142. package/src/world-shore-field.ts +91 -0
  143. package/src/world-static-pose.ts +163 -0
  144. package/src/world-surface-sampler.ts +48 -0
  145. package/src/world-terrain-splat.ts +10 -18
  146. package/src/world-tile-budget.ts +4 -11
  147. package/src/world-tiles.ts +79 -12
  148. package/src/world-validate.ts +6 -14
  149. package/src/world-warm.ts +51 -0
  150. package/src/world.ts +13 -0
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, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, frustumPlanes, rendererFacts, mergeByMaterial, VALIDATE_EVERY, TALLY_EVERY, nodes } from './chunk-DIPIJICH.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, isEngineRenderHook, lodChainOf, DISCRETE_LOD_DEFAULT_HYSTERESIS } from './chunk-EFWZWLPY.js';
4
+ import { readLaunchFlag, readLaunchValues, readLaunchValue } from './chunk-GYUZJQ7U.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;
@@ -1307,7 +1308,7 @@ var WaterBodies = class {
1307
1308
  constructor(options) {
1308
1309
  const field = options.field;
1309
1310
  const reaches = [];
1310
- for (const ribbon of options.ribbons ?? []) buildReaches(ribbon, reaches);
1311
+ for (const ribbon2 of options.ribbons ?? []) buildReaches(ribbon2, reaches);
1311
1312
  this.#cellSize = Math.max(1, ...reaches.map((piece) => piece.reach));
1312
1313
  this.#cells = indexReaches(reaches, this.#cellSize);
1313
1314
  this.#pools = (options.lakes ?? NO_LAKES).map((lake) => poolOf(field, lake));
@@ -1337,9 +1338,9 @@ var WaterBodies = class {
1337
1338
  out.z = 0;
1338
1339
  return out;
1339
1340
  }
1340
- const length6 = Math.sqrt(piece.length2);
1341
- out.x = piece.dx / length6 * piece.flow;
1342
- out.z = piece.dz / length6 * piece.flow;
1341
+ const length7 = Math.sqrt(piece.length2);
1342
+ out.x = piece.dx / length7 * piece.flow;
1343
+ out.z = piece.dz / length7 * piece.flow;
1343
1344
  return out;
1344
1345
  }
1345
1346
  /** Which water body covers (x, z) and how high its surface is, or `undefined` where none is. */
@@ -1388,10 +1389,10 @@ var WaterBodies = class {
1388
1389
  return kind === void 0 ? void 0 : { kind, level, river };
1389
1390
  }
1390
1391
  };
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;
1392
+ function buildReaches(ribbon2, into) {
1393
+ const width = positive2(ribbon2.width, "ribbon width");
1394
+ const flow = finite3(ribbon2.flow, "ribbon flow");
1395
+ const points = ribbon2.points;
1395
1396
  if (!Array.isArray(points) || points.length < 2)
1396
1397
  throw new Error(
1397
1398
  `TN_WATER_BODIES_INVALID: a ribbon needs at least two stations, received ${String(points?.length)}.`
@@ -1444,6 +1445,493 @@ function indexReaches(reaches, cellSize) {
1444
1445
  }
1445
1446
  return cells;
1446
1447
  }
1448
+ function riverRibbonGeometry(rivers, field, options = {}) {
1449
+ const columns = options.columns ?? 25;
1450
+ if (!Number.isInteger(columns) || columns < 2)
1451
+ throw new Error(
1452
+ `TN_RIVER_RIBBON_INVALID: columns must be an integer of at least 2, received ${columns}.`
1453
+ );
1454
+ const perWidth = options.reach ?? WATER_RIBBON_REACH;
1455
+ const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
1456
+ const edgeSlope = options.edgeSlope ?? 0.2;
1457
+ if (!(perWidth > 0) || !(maxDepth > 0) || !(edgeSlope >= 0))
1458
+ throw new Error(
1459
+ "TN_RIVER_RIBBON_INVALID: reach and maxDepth must be positive, edgeSlope not negative."
1460
+ );
1461
+ const positions = [];
1462
+ const flows = [];
1463
+ const uvs = [];
1464
+ const depths = [];
1465
+ const indices = [];
1466
+ const geometry = new BufferGeometry();
1467
+ for (const river of rivers) {
1468
+ if (!(river.width > 0) || river.points.length < 2)
1469
+ throw new Error(
1470
+ `TN_RIVER_RIBBON_INVALID: a river needs a positive width and two stations, received width ${river.width} and ${river.points.length} stations.`
1471
+ );
1472
+ const start = indices.length;
1473
+ ribbon(field, river.points, river.width * perWidth, columns, maxDepth, edgeSlope, {
1474
+ depths,
1475
+ flows,
1476
+ indices,
1477
+ positions,
1478
+ uvs
1479
+ });
1480
+ geometry.addGroup(start, indices.length - start, 0);
1481
+ }
1482
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
1483
+ geometry.setAttribute("flow", new BufferAttribute(new Float32Array(flows), 2));
1484
+ geometry.setAttribute("flowUv", new BufferAttribute(new Float32Array(uvs), 2));
1485
+ geometry.setAttribute("metres", new BufferAttribute(new Float32Array(depths), 1));
1486
+ geometry.setIndex(indices);
1487
+ geometry.computeVertexNormals();
1488
+ geometry.computeBoundingBox();
1489
+ geometry.computeBoundingSphere();
1490
+ return geometry;
1491
+ }
1492
+ var DRAIN_TOLERANCE = 0.05;
1493
+ function beyond(end, inner, reach) {
1494
+ const dx = (end[0] ?? 0) - (inner[0] ?? 0);
1495
+ const dz = (end[2] ?? 0) - (inner[2] ?? 0);
1496
+ const length7 = Math.hypot(dx, dz) || 1;
1497
+ return [
1498
+ (end[0] ?? 0) + dx / length7 * reach,
1499
+ end[1] ?? 0,
1500
+ (end[2] ?? 0) + dz / length7 * reach
1501
+ ];
1502
+ }
1503
+ function ribbon(field, stations, reach, columns, maxDepth, edgeSlope, out) {
1504
+ const points = [
1505
+ beyond(stations[0], stations[1], reach),
1506
+ ...stations,
1507
+ beyond(stations.at(-1), stations.at(-2), reach)
1508
+ ];
1509
+ const base = out.positions.length / 3;
1510
+ const minX = field.origin.x - field.width / 2;
1511
+ const minZ = field.origin.z - field.depth / 2;
1512
+ const ground = (x, z) => field.heightAt(
1513
+ Math.min(minX + field.width, Math.max(minX, x)),
1514
+ Math.min(minZ + field.depth, Math.max(minZ, z))
1515
+ );
1516
+ const wet = [];
1517
+ const last = points.length - 1;
1518
+ const bedAt = (station) => ground(station[0] ?? 0, station[2] ?? 0);
1519
+ const capBed = [
1520
+ bedAt(stations[0]),
1521
+ bedAt(stations.at(-1))
1522
+ ];
1523
+ const drained = [];
1524
+ let downstream = 0;
1525
+ for (let k = 0; k < points.length; k += 1) {
1526
+ const [x = 0, y = 0, z = 0] = points[k];
1527
+ if (k > 0) {
1528
+ const [px = 0, , pz = 0] = points[k - 1];
1529
+ downstream += Math.hypot(x - px, z - pz);
1530
+ }
1531
+ const before = points[Math.max(0, k - 1)];
1532
+ const after = points[Math.min(points.length - 1, k + 1)];
1533
+ let dx = (after[0] ?? 0) - (before[0] ?? 0);
1534
+ let dz = (after[2] ?? 0) - (before[2] ?? 0);
1535
+ const length7 = Math.hypot(dx, dz) || 1;
1536
+ dx /= length7;
1537
+ dz /= length7;
1538
+ for (let c = 0; c < columns; c += 1) {
1539
+ const across = (c / (columns - 1) - 0.5) * 2 * reach;
1540
+ const vx = x - dz * across;
1541
+ const vz = z + dx * across;
1542
+ out.positions.push(vx, y, vz);
1543
+ out.flows.push(dx, dz);
1544
+ out.uvs.push(downstream, across);
1545
+ const below = ground(vx, vz);
1546
+ const bed = k === 0 ? capBed[0] : k === last ? capBed[1] : void 0;
1547
+ const dry = bed !== void 0 && below < bed - DRAIN_TOLERANCE;
1548
+ const depth = dry ? 0 : Math.min(
1549
+ maxDepth,
1550
+ Math.max(0, y - below),
1551
+ Math.max(0, (reach - Math.abs(across)) * edgeSlope)
1552
+ );
1553
+ out.depths.push(depth);
1554
+ wet.push(depth > 0 ? 1 : 0);
1555
+ drained.push(dry);
1556
+ }
1557
+ }
1558
+ for (let k = 1; k < points.length; k += 1) {
1559
+ for (let c = 1; c < columns; c += 1) {
1560
+ const a = (k - 1) * columns + c - 1;
1561
+ const d = k * columns + c - 1;
1562
+ const rowA = (wet[a - 1] ?? 0) + (wet[a + 1] ?? 0) + (wet[d - 1] ?? 0) + (wet[d + 1] ?? 0);
1563
+ const rowB = (wet[a] ?? 0) + (wet[a + 1] ?? 0) + (wet[d] ?? 0) + (wet[d + 1] ?? 0);
1564
+ if (rowA === 0 && rowB === 0) continue;
1565
+ if (drained[a] || drained[a + 1] || drained[d] || drained[d + 1]) continue;
1566
+ out.indices.push(base + a, base + a + 1, base + d, base + a + 1, base + d + 1, base + d);
1567
+ }
1568
+ }
1569
+ }
1570
+ function lakeSurfaceGeometry(lake, field, options = {}) {
1571
+ const rings = options.rings ?? 44;
1572
+ const spokes = options.spokes ?? 88;
1573
+ const packing = options.packing ?? 1.7;
1574
+ const maxDepth = options.maxDepth ?? Number.POSITIVE_INFINITY;
1575
+ if (!Number.isInteger(rings) || rings < 2 || !Number.isInteger(spokes) || spokes < 3)
1576
+ throw new Error(
1577
+ `TN_LAKE_SURFACE_INVALID: rings must be an integer of at least 2 and spokes of at least 3, received ${rings} and ${spokes}.`
1578
+ );
1579
+ if (!(packing > 0) || !(maxDepth > 0))
1580
+ throw new Error("TN_LAKE_SURFACE_INVALID: packing and maxDepth must be positive.");
1581
+ const reach = lakeReach(field, lake);
1582
+ if (!(reach > 0)) return void 0;
1583
+ const [cx = 0, cz = 0] = lake.at;
1584
+ const minX = field.origin.x - field.width / 2;
1585
+ const minZ = field.origin.z - field.depth / 2;
1586
+ const count3 = (rings - 1) * spokes + 1;
1587
+ const positions = new Float32Array(count3 * 3);
1588
+ const depths = new Float32Array(count3);
1589
+ const place = (index, radius, spoke) => {
1590
+ const angle = spoke / spokes * Math.PI * 2;
1591
+ const x = Math.max(minX, Math.min(minX + field.width, cx + Math.cos(angle) * radius));
1592
+ const z = Math.max(minZ, Math.min(minZ + field.depth, cz + Math.sin(angle) * radius));
1593
+ positions[index * 3] = x;
1594
+ positions[index * 3 + 1] = lake.level;
1595
+ positions[index * 3 + 2] = z;
1596
+ depths[index] = Math.min(maxDepth, Math.max(0, lake.level - field.heightAt(x, z)));
1597
+ };
1598
+ place(0, 0, 0);
1599
+ for (let ring = 1; ring < rings; ring += 1) {
1600
+ const radius = reach * (ring / (rings - 1)) ** packing;
1601
+ for (let spoke = 0; spoke < spokes; spoke += 1)
1602
+ place(1 + (ring - 1) * spokes + spoke, radius, spoke);
1603
+ }
1604
+ const depth = (index) => depths[index] ?? 0;
1605
+ const indices = [];
1606
+ for (let spoke = 0; spoke < spokes; spoke += 1) {
1607
+ const first = 1 + spoke;
1608
+ const next = 1 + (spoke + 1) % spokes;
1609
+ if (depth(0) + depth(first) + depth(next) > 0) indices.push(0, first, next);
1610
+ }
1611
+ for (let ring = 2; ring < rings; ring += 1)
1612
+ for (let spoke = 0; spoke < spokes; spoke += 1) {
1613
+ const next = (spoke + 1) % spokes;
1614
+ const inner = 1 + (ring - 2) * spokes + spoke;
1615
+ const innerNext = 1 + (ring - 2) * spokes + next;
1616
+ const outer = 1 + (ring - 1) * spokes + spoke;
1617
+ const outerNext = 1 + (ring - 1) * spokes + next;
1618
+ if (depth(inner) + depth(innerNext) + depth(outer) + depth(outerNext) <= 0) continue;
1619
+ indices.push(inner, outer, innerNext, innerNext, outer, outerNext);
1620
+ }
1621
+ const geometry = new BufferGeometry();
1622
+ geometry.setAttribute("position", new BufferAttribute(positions, 3));
1623
+ geometry.setAttribute("metres", new BufferAttribute(depths, 1));
1624
+ geometry.setIndex(indices);
1625
+ geometry.computeVertexNormals();
1626
+ geometry.computeBoundingSphere();
1627
+ return geometry;
1628
+ }
1629
+
1630
+ // src/world-load-limiter.ts
1631
+ var ModelLoadLimiter = class {
1632
+ #concurrency;
1633
+ #queue = [];
1634
+ #inFlight = 0;
1635
+ constructor(concurrency) {
1636
+ this.#concurrency = concurrency;
1637
+ }
1638
+ get inFlight() {
1639
+ return this.#inFlight;
1640
+ }
1641
+ get queued() {
1642
+ return this.#queue.length;
1643
+ }
1644
+ load(run, wanted) {
1645
+ return new Promise((resolve, reject) => {
1646
+ this.#queue.push({ reject, resolve, run, wanted });
1647
+ this.#pump();
1648
+ });
1649
+ }
1650
+ #pump() {
1651
+ while (this.#inFlight < this.#concurrency && this.#queue.length > 0) {
1652
+ const job = this.#queue.shift();
1653
+ if (!job.wanted()) {
1654
+ job.resolve(void 0);
1655
+ continue;
1656
+ }
1657
+ this.#inFlight += 1;
1658
+ try {
1659
+ job.run().then(
1660
+ (model) => {
1661
+ this.#inFlight -= 1;
1662
+ job.resolve(model);
1663
+ this.#pump();
1664
+ },
1665
+ (error) => {
1666
+ this.#inFlight -= 1;
1667
+ job.reject(error);
1668
+ this.#pump();
1669
+ }
1670
+ );
1671
+ } catch (error) {
1672
+ this.#inFlight -= 1;
1673
+ job.reject(error);
1674
+ this.#pump();
1675
+ }
1676
+ }
1677
+ }
1678
+ };
1679
+ var AdmissionBudget = class {
1680
+ #limitMs;
1681
+ #now;
1682
+ #spentMs = 0;
1683
+ constructor(limitMs, now) {
1684
+ this.#limitMs = limitMs;
1685
+ this.#now = now;
1686
+ }
1687
+ get spentMs() {
1688
+ return this.#spentMs;
1689
+ }
1690
+ admit(work) {
1691
+ if (this.#spentMs >= this.#limitMs) return false;
1692
+ const startedAt = this.#now();
1693
+ work();
1694
+ this.#spentMs += this.#now() - startedAt;
1695
+ return true;
1696
+ }
1697
+ };
1698
+
1699
+ // src/world-shore-field.ts
1700
+ function shoreField(heights, resolution, size, level, options = {}) {
1701
+ const n = resolution;
1702
+ const openDepth = options.openDepth ?? 2;
1703
+ const carry = options.carry ?? 18;
1704
+ if (!Number.isInteger(n) || n < 2 || heights.length !== n * n)
1705
+ throw new Error(
1706
+ `TN_SHORE_FIELD_INVALID: heights must hold resolution\xB2 values, received ${heights.length} for ${n}.`
1707
+ );
1708
+ if (!(size > 0) || !Number.isFinite(level) || !(openDepth >= 0) || !(carry >= 0))
1709
+ throw new Error(
1710
+ "TN_SHORE_FIELD_INVALID: size must be positive, level finite, openDepth and carry not negative."
1711
+ );
1712
+ const cell = size / (n - 1);
1713
+ const height2 = (i) => heights[i] ?? 0;
1714
+ const distance = new Float32Array(n * n);
1715
+ for (let i = 0; i < n * n; i++) distance[i] = height2(i) >= level ? 0 : 1e4;
1716
+ const exposed = new Uint8Array(n * n);
1717
+ const queue = [];
1718
+ for (let i = 0; i < n * n; i++) {
1719
+ const row = Math.floor(i / n);
1720
+ const col = i % n;
1721
+ if ((row === 0 || col === 0 || row === n - 1 || col === n - 1) && height2(i) < level - openDepth) {
1722
+ exposed[i] = 1;
1723
+ queue.push(i);
1724
+ }
1725
+ if (col > 0) distance[i] = Math.min(distance[i] ?? 0, (distance[i - 1] ?? 0) + cell);
1726
+ if (row > 0) distance[i] = Math.min(distance[i] ?? 0, (distance[i - n] ?? 0) + cell);
1727
+ }
1728
+ for (let i = n * n - 1; i >= 0; i--) {
1729
+ if (i % n < n - 1) distance[i] = Math.min(distance[i] ?? 0, (distance[i + 1] ?? 0) + cell);
1730
+ if (i < n * (n - 1)) distance[i] = Math.min(distance[i] ?? 0, (distance[i + n] ?? 0) + cell);
1731
+ }
1732
+ for (let head = 0; head < queue.length; head++) {
1733
+ const i = queue[head] ?? 0;
1734
+ for (const next of [i % n > 0 ? i - 1 : -1, i % n < n - 1 ? i + 1 : -1, i - n, i + n]) {
1735
+ if (next < 0 || next >= exposed.length || exposed[next] || height2(next) >= level - openDepth)
1736
+ continue;
1737
+ exposed[next] = 1;
1738
+ queue.push(next);
1739
+ }
1740
+ }
1741
+ for (let pass = 0; pass < Math.ceil(carry / cell); pass++) {
1742
+ const previous = exposed.slice();
1743
+ for (let i = 0; i < exposed.length; i++) {
1744
+ if (height2(i) >= level) continue;
1745
+ if (i % n > 0 && previous[i - 1] || i % n < n - 1 && previous[i + 1] || previous[i - n] || previous[i + n])
1746
+ exposed[i] = 1;
1747
+ }
1748
+ }
1749
+ return { distance, exposed };
1750
+ }
1751
+ function surfaceSampler(field, matrixWorld) {
1752
+ const translation = new Vector3();
1753
+ const rotation = new Quaternion();
1754
+ const scale = new Vector3();
1755
+ matrixWorld.decompose(translation, rotation, scale);
1756
+ 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;
1757
+ if (!upright) return () => null;
1758
+ const { origin, width, depth } = field;
1759
+ const slack = 1e-5;
1760
+ const minX = origin.x - width / 2;
1761
+ const maxX = origin.x + width / 2;
1762
+ const minZ = origin.z - depth / 2;
1763
+ const maxZ = origin.z + depth / 2;
1764
+ return (worldX, worldZ) => {
1765
+ const x = (worldX - translation.x) / scale.x;
1766
+ const z = (worldZ - translation.z) / scale.z;
1767
+ if (x < minX - slack || x > maxX + slack || z < minZ - slack || z > maxZ + slack) return null;
1768
+ const clampedX = Math.min(maxX, Math.max(minX, x));
1769
+ const clampedZ = Math.min(maxZ, Math.max(minZ, z));
1770
+ return field.surfaceAt(clampedX, clampedZ) * scale.y + translation.y;
1771
+ };
1772
+ }
1773
+ var bottomFirst = /* @__PURE__ */ new WeakMap();
1774
+ function verticesBottomFirst(geometry) {
1775
+ const cached = bottomFirst.get(geometry);
1776
+ if (cached) return cached;
1777
+ const position = geometry.getAttribute("position");
1778
+ const order = Array.from({ length: position.count }, (_, i) => i).sort(
1779
+ (a, b) => position.getY(a) - position.getY(b)
1780
+ );
1781
+ const xyz3 = new Float32Array(position.count * 3);
1782
+ let reach = 0;
1783
+ order.forEach((i, k) => {
1784
+ xyz3[k * 3] = position.getX(i);
1785
+ xyz3[k * 3 + 1] = position.getY(i);
1786
+ xyz3[k * 3 + 2] = position.getZ(i);
1787
+ reach = Math.max(reach, Math.hypot(position.getX(i), position.getZ(i)));
1788
+ });
1789
+ const entry = { xyz: xyz3, reach };
1790
+ bottomFirst.set(geometry, entry);
1791
+ return entry;
1792
+ }
1793
+ function staticLowestY(geometry, matrix) {
1794
+ const e = matrix.elements;
1795
+ if (e[1] === 0 && e[9] === 0) {
1796
+ if (geometry.boundingBox === null) geometry.computeBoundingBox();
1797
+ const box = geometry.boundingBox;
1798
+ if (box) return (e[5] < 0 ? box.max.y : box.min.y) * e[5] + e[13];
1799
+ }
1800
+ const { xyz: xyz3, reach } = verticesBottomFirst(geometry);
1801
+ const tilt = reach * Math.hypot(e[1], e[9]);
1802
+ const upright = e[5] > 0;
1803
+ let lowest = Number.POSITIVE_INFINITY;
1804
+ for (let k = 0; k < xyz3.length; k += 3) {
1805
+ const y = xyz3[k + 1];
1806
+ if (upright && y * e[5] + e[13] - tilt >= lowest) break;
1807
+ lowest = Math.min(
1808
+ lowest,
1809
+ xyz3[k] * e[1] + y * e[5] + xyz3[k + 2] * e[9] + e[13]
1810
+ );
1811
+ }
1812
+ return lowest;
1813
+ }
1814
+ function footprintGap(geometry, matrix, ground, margin = 0) {
1815
+ if (geometry.boundingBox === null) geometry.computeBoundingBox();
1816
+ const base = geometry.boundingBox?.min.y ?? Number.POSITIVE_INFINITY;
1817
+ const positions = geometry.getAttribute("position");
1818
+ const point = new Vector3();
1819
+ let gap = 0;
1820
+ for (let i = 0; i < positions.count; i++) {
1821
+ if (Math.abs(positions.getY(i) - base) > 1e-5) continue;
1822
+ point.fromBufferAttribute(positions, i).applyMatrix4(matrix);
1823
+ const height2 = ground(point.x, point.z);
1824
+ if (height2 === null)
1825
+ throw new Error(
1826
+ `TN_STATIC_POSE_GROUND: no ground under the footprint at ${point.x}, ${point.z}.`
1827
+ );
1828
+ gap = Math.max(gap, point.y - height2 + margin);
1829
+ }
1830
+ return gap;
1831
+ }
1832
+ function baseRingGap(geometry, matrix, ground, options = {}) {
1833
+ const count3 = options.sectors ?? 16;
1834
+ const rim = options.rim ?? 0.75;
1835
+ if (!Number.isInteger(count3) || count3 < 1 || !(rim >= 0 && rim <= 1))
1836
+ throw new Error(
1837
+ "TN_STATIC_POSE_INVALID: sectors must be a positive integer and rim within 0..1."
1838
+ );
1839
+ if (geometry.boundingBox === null) geometry.computeBoundingBox();
1840
+ const box = geometry.boundingBox;
1841
+ if (!box) throw new Error("TN_STATIC_POSE_INVALID: the geometry has no bounds.");
1842
+ const centre = box.getCenter(new Vector3()).applyMatrix4(matrix);
1843
+ const sectors = Array.from({ length: count3 }, () => ({ reach: 0, vertices: [] }));
1844
+ const vertices = geometry.getAttribute("position");
1845
+ for (let i = 0; i < vertices.count; i++) {
1846
+ const point = new Vector3().fromBufferAttribute(vertices, i).applyMatrix4(matrix);
1847
+ const dx = point.x - centre.x;
1848
+ const dz = point.z - centre.z;
1849
+ const bin = Math.min(
1850
+ count3 - 1,
1851
+ Math.floor((Math.atan2(dz, dx) + Math.PI) / (2 * Math.PI) * count3)
1852
+ );
1853
+ const sector = sectors[bin];
1854
+ if (!sector) continue;
1855
+ sector.reach = Math.max(sector.reach, Math.hypot(dx, dz));
1856
+ sector.vertices.push(point);
1857
+ }
1858
+ let gap = Number.NEGATIVE_INFINITY;
1859
+ let samples = 0;
1860
+ for (const sector of sectors) {
1861
+ let lowest;
1862
+ for (const point of sector.vertices)
1863
+ if (Math.hypot(point.x - centre.x, point.z - centre.z) >= sector.reach * rim && (!lowest || point.y < lowest.y))
1864
+ lowest = point;
1865
+ if (!lowest) continue;
1866
+ const contact = ground(lowest.x, lowest.z);
1867
+ if (contact === null)
1868
+ throw new Error(
1869
+ `TN_STATIC_POSE_GROUND: no ground under the base ring at ${lowest.x}, ${lowest.z}.`
1870
+ );
1871
+ gap = Math.max(gap, lowest.y - contact);
1872
+ samples++;
1873
+ }
1874
+ return { gap, samples };
1875
+ }
1876
+ function meshSections(mesh) {
1877
+ const materials = mesh.material;
1878
+ return Array.isArray(materials) ? mesh.geometry.groups.map((group) => ({
1879
+ material: materials[group.materialIndex ?? 0],
1880
+ group
1881
+ })) : [{ material: materials }];
1882
+ }
1883
+ function sectionGeometry(mesh, box, section, options = {}) {
1884
+ const geometry = baseGeometryOf(mesh).clone().applyMatrix4(mesh.matrixWorld);
1885
+ const { group } = section;
1886
+ if (group) {
1887
+ const start = Math.max(group.start, geometry.drawRange.start);
1888
+ const end = Math.min(
1889
+ group.start + group.count,
1890
+ geometry.drawRange.start + geometry.drawRange.count
1891
+ );
1892
+ geometry.clearGroups();
1893
+ geometry.setDrawRange(start, Math.max(0, end - start));
1894
+ }
1895
+ const centre = box.getCenter(new Vector3());
1896
+ const centred = options.centreXZ === true;
1897
+ geometry.translate(centred ? -centre.x : 0, -box.min.y, centred ? -centre.z : 0);
1898
+ return geometry;
1899
+ }
1900
+ function repairZeroNormals(geometry) {
1901
+ const normals = geometry.getAttribute("normal");
1902
+ let valid = normals !== void 0;
1903
+ for (let i = 0; valid && normals && i < normals.count; i++) {
1904
+ const length7 = Math.hypot(normals.getX(i), normals.getY(i), normals.getZ(i));
1905
+ valid = Number.isFinite(length7) && length7 >= 0.01;
1906
+ }
1907
+ if (!valid) geometry.computeVertexNormals();
1908
+ return !valid;
1909
+ }
1910
+
1911
+ // src/world-warm.ts
1912
+ function warmUnculled(ctx, root, options = {}) {
1913
+ const draws = options.draws ?? 2;
1914
+ if (!Number.isInteger(draws) || draws < 1)
1915
+ throw new Error(
1916
+ `TN_WARM_UNCULLED_INVALID: draws must be a positive integer, received ${draws}.`
1917
+ );
1918
+ const when = options.when ?? (() => true);
1919
+ const cull = (culled) => root.traverse((object) => {
1920
+ object.frustumCulled = culled;
1921
+ });
1922
+ return new Promise((resolve) => {
1923
+ let counted = 0;
1924
+ ctx.beforeRender(() => {
1925
+ if (counted < 0) return;
1926
+ cull(false);
1927
+ if (when()) counted += 1;
1928
+ if (counted <= draws) return;
1929
+ counted = -1;
1930
+ cull(true);
1931
+ resolve();
1932
+ });
1933
+ });
1934
+ }
1447
1935
  var BRIDGE_COORDINATE_EPSILON = 1e-4;
1448
1936
  var BRIDGE_COORDINATE_RELATIVE_EPSILON = 2 ** -22;
1449
1937
  var BRIDGE_STRIP_INDEX_PATTERN = [0, 1, 2, 2, 1, 3, 2, 1, 0, 3, 1, 2];
@@ -1779,13 +2267,10 @@ var TERRAIN_MERGE_BLOCK = 4;
1779
2267
  var TERRAIN_MERGE_FLAG = "TN_TERRAIN_MERGE";
1780
2268
  var TERRAIN_TILE_MARKER_MS = 5e3;
1781
2269
  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";
2270
+ return readLaunchFlag(
2271
+ { environment: TERRAIN_MERGE_FLAG, global: "__tnTerrainMerge", query: "tnTerrainMerge" },
2272
+ "off"
2273
+ );
1789
2274
  }
1790
2275
  function blockKeyFor(lod, tileX, tileZ) {
1791
2276
  return `${String(lod)}:${String(Math.floor(tileX / TERRAIN_MERGE_BLOCK))},${String(
@@ -2025,14 +2510,14 @@ function reliefFieldEdge(field) {
2025
2510
  const center = height(field, Math.floor(field.rows / 2), Math.floor(field.columns / 2));
2026
2511
  return Math.abs(center - edgeMean) / relief;
2027
2512
  }
2028
- function slidingExtrema(read, length6, radius, write) {
2513
+ function slidingExtrema(read, length7, radius, write) {
2029
2514
  const minimumDeque = [];
2030
2515
  const maximumDeque = [];
2031
2516
  let minimumHead = 0;
2032
2517
  let maximumHead = 0;
2033
2518
  let right = -1;
2034
- for (let index = 0; index < length6; index += 1) {
2035
- const desiredRight = Math.min(length6 - 1, index + radius);
2519
+ for (let index = 0; index < length7; index += 1) {
2520
+ const desiredRight = Math.min(length7 - 1, index + radius);
2036
2521
  while (right < desiredRight) {
2037
2522
  right += 1;
2038
2523
  const value = read(right);
@@ -2243,14 +2728,11 @@ function summarizeWorldTopology(field) {
2243
2728
  var TERRAIN_VALIDATE_MARKER = "TN_TERRAIN_VALIDATE";
2244
2729
  var TERRAIN_VALIDATE_FLAG = "TN_TERRAIN_VALIDATE";
2245
2730
  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";
2731
+ return readLaunchFlag({
2732
+ environment: TERRAIN_VALIDATE_FLAG,
2733
+ global: "__tnTerrainValidate",
2734
+ query: "tnTerrainValidate"
2735
+ });
2254
2736
  }
2255
2737
  function appendQuad(indices, topLeft, bottomLeft, topRight, bottomRight) {
2256
2738
  indices.push(topLeft, bottomLeft, topRight, topRight, bottomLeft, bottomRight);
@@ -2972,6 +3454,7 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
2972
3454
  #sampleHeight;
2973
3455
  #streamRadius;
2974
3456
  #extent;
3457
+ #hole;
2975
3458
  /** Diagnostics outlive construction; their canonical field is never used by resident tiles. */
2976
3459
  #topology;
2977
3460
  #topologyBytes = 0;
@@ -3068,6 +3551,7 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3068
3551
  this.skirtDepth = positive3(options.skirtDepth ?? this.tileSize, "skirtDepth");
3069
3552
  this.#streamRadius = integerAtLeast(options.streamRadius ?? 1, 0, "streamRadius");
3070
3553
  this.#extent = options.extent;
3554
+ this.#hole = options.hole;
3071
3555
  this.#receiveShadow = options.receiveShadow === true;
3072
3556
  this.#colliderRadius = integerAtLeast(
3073
3557
  options.colliderRadius ?? this.#streamRadius,
@@ -3288,6 +3772,35 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3288
3772
  getTile(key) {
3289
3773
  return this.#resident.get(key);
3290
3774
  }
3775
+ /**
3776
+ * Half-width, in metres, of the largest square of tiles around `position`'s tile that is fully
3777
+ * settled: each tile in it is resident, or is one the stream never draws (wholly inside `hole` or
3778
+ * past `extent`). Zero while the tile under `position` is still building. A game that draws other
3779
+ * ground where the tiles have not arrived (a collar, a far mesh) clips it to this square, so a tile
3780
+ * still building shows that ground, never a hole.
3781
+ *
3782
+ * @situation a hole or a flicker where streamed terrain tiles are still building
3783
+ * @situation split the ground between streamed tiles and a far mesh around the player
3784
+ * @constraint reads residency only; call it after `follow` in the same frame
3785
+ * @example split.half.value = tiles.settledHalf(player.position);
3786
+ */
3787
+ settledHalf(position) {
3788
+ const centerX = Math.floor(
3789
+ (finite4(position.x, "settled x") + this.tileSize / 2) / this.tileSize
3790
+ );
3791
+ const centerZ = Math.floor(
3792
+ (finite4(position.z, "settled z") + this.tileSize / 2) / this.tileSize
3793
+ );
3794
+ const settled = (tileX, tileZ) => this.#resident.has(keyFor(tileX, tileZ)) || !this.#touchesExtent(tileX, tileZ);
3795
+ let ring = -1;
3796
+ for (let k = 0; k <= this.#streamRadius; k += 1) {
3797
+ for (let d = -k; d <= k; d += 1)
3798
+ if (!settled(centerX + d, centerZ - k) || !settled(centerX + d, centerZ + k) || !settled(centerX - k, centerZ + d) || !settled(centerX + k, centerZ + d))
3799
+ return ring < 0 ? 0 : (ring + 0.5) * this.tileSize;
3800
+ ring = k;
3801
+ }
3802
+ return (ring + 0.5) * this.tileSize;
3803
+ }
3291
3804
  /**
3292
3805
  * Move residency to the followed point: admit, evict and re-level every tile.
3293
3806
  *
@@ -3503,19 +4016,22 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3503
4016
  if (view !== void 0 && next !== void 0 && finest !== void 0 && bounds != null) {
3504
4017
  finest.mesh.updateWorldMatrix(true, false);
3505
4018
  const sphere = worldSphere(bounds, finest.mesh);
3506
- const depth = conservativeViewDepth(
4019
+ const { degenerate, depth } = selectLodFor(
3507
4020
  view.camera,
3508
- sphere.center,
3509
- sphere.radius,
4021
+ sphere,
3510
4022
  view.camera.near ?? 0
3511
4023
  );
3512
4024
  const errorPixels = projectedLodError(
3513
4025
  next.surfaceError * finest.mesh.matrixWorld.getMaxScaleOnAxis(),
3514
4026
  view.camera,
3515
4027
  view.viewportHeight,
3516
- depth.depth
4028
+ depth
3517
4029
  );
3518
- projection = { ...depth, ...Number.isFinite(errorPixels) ? { errorPixels } : {} };
4030
+ projection = {
4031
+ degenerate,
4032
+ depth,
4033
+ ...Number.isFinite(errorPixels) ? { errorPixels } : {}
4034
+ };
3519
4035
  }
3520
4036
  return {
3521
4037
  key: tile.key,
@@ -3829,11 +4345,17 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3829
4345
  #selectLod(tile, distance, countTransition = true) {
3830
4346
  this.#setLodLevel(tile, this.#targetLod(tile, distance), countTransition);
3831
4347
  }
3832
- /** Whether the tile's square overlaps the ground at all; always true when no extent was given. */
4348
+ /**
4349
+ * Whether the tile's square overlaps the ground at all and is not wholly inside the hole; always
4350
+ * true when neither was given.
4351
+ */
3833
4352
  #touchesExtent(tileX, tileZ) {
4353
+ const half = this.tileSize / 2;
4354
+ const hole = this.#hole;
4355
+ 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)
4356
+ return false;
3834
4357
  const extent = this.#extent;
3835
4358
  if (extent === void 0) return true;
3836
- const half = this.tileSize / 2;
3837
4359
  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
4360
  }
3839
4361
  #setLodView(view) {
@@ -3853,10 +4375,9 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3853
4375
  if (finest === void 0 || bounds == null) return 0;
3854
4376
  finest.mesh.updateWorldMatrix(true, false);
3855
4377
  const sphere = worldSphere(bounds, finest.mesh);
3856
- const depth = conservativeViewDepth(
4378
+ const { depth, degenerate } = selectLodFor(
3857
4379
  view.camera,
3858
- sphere.center,
3859
- sphere.radius,
4380
+ sphere,
3860
4381
  view.camera.near ?? 0
3861
4382
  );
3862
4383
  const scale = finest.mesh.matrixWorld.getMaxScaleOnAxis();
@@ -3864,7 +4385,7 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
3864
4385
  this.#lodErrors[index] = tile.levels[index].surfaceError * scale;
3865
4386
  this.#lodErrors.length = floor2 + 1;
3866
4387
  return selectLodLevel(this.#lodErrors, tile.lodLevel, view.maxPixelError, view.hysteresis, [
3867
- { ...view, ...depth }
4388
+ { ...view, degenerate, depth }
3868
4389
  ]);
3869
4390
  }
3870
4391
  #syncMorphEdges() {
@@ -4940,8 +5461,8 @@ function cellPlacements(placements, run) {
4940
5461
  if (!Number.isInteger(run.offset) || !Number.isInteger(run.count) || run.offset < 0 || run.count < 0)
4941
5462
  throw new RangeError("Placement run offset and count must be non-negative integers.");
4942
5463
  const start = run.offset * PLACEMENT_RECORD_BYTES;
4943
- const length6 = run.count * PLACEMENT_RECORD_BYTES;
4944
- if (start + length6 > placements.byteLength)
5464
+ const length7 = run.count * PLACEMENT_RECORD_BYTES;
5465
+ if (start + length7 > placements.byteLength)
4945
5466
  throw new RangeError(
4946
5467
  `Placement run [${String(run.offset)}, ${String(run.offset + run.count)}) reaches past the ${String(placements.byteLength)}-byte buffer.`
4947
5468
  );
@@ -5563,24 +6084,15 @@ function packageAssetPath(directory, path) {
5563
6084
  return `${prefix}${segments.join("/")}`;
5564
6085
  }
5565
6086
  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;
6087
+ try {
6088
+ return await fetchAsset(assets, path);
6089
+ } catch (error) {
6090
+ const cause = error instanceof Error ? error.cause : void 0;
6091
+ throw new Error(
6092
+ `loadTerrainSplat: '${path}' is not served.`,
6093
+ cause === void 0 ? void 0 : { cause }
6094
+ );
5580
6095
  }
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
6096
  }
5585
6097
  function splatArray(bytes, size, planes) {
5586
6098
  if (bytes.byteLength < planes * size * size * 4)
@@ -7027,12 +7539,7 @@ var CellChunks = class {
7027
7539
  const scale = cellProxyWorldScale(matrixWorld);
7028
7540
  const sphere = this.#host.worldSphere(state.prepared.bounds);
7029
7541
  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
- );
7542
+ const view = camera === void 0 ? void 0 : selectLodFor(camera, sphere, Reflect.get(camera, "near") ?? LOD_NEAR_PLANE);
7036
7543
  const height2 = renderer?.domElement.height;
7037
7544
  const selected = state.selector.select({
7038
7545
  sourceReady: cellLoaded(cell),
@@ -7315,16 +7822,6 @@ function cellLoaded(cell) {
7315
7822
  function clusterOf(cellX, cellZ, cellsPerCluster) {
7316
7823
  return `${String(Math.floor(cellX / cellsPerCluster))},${String(Math.floor(cellZ / cellsPerCluster))}`;
7317
7824
  }
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
7825
  var PLACED_STRIDE = 7;
7329
7826
  function positiveInteger(value, name) {
7330
7827
  if (!Number.isInteger(value) || value < 1)
@@ -7395,10 +7892,11 @@ function impostorBounds(parts) {
7395
7892
  whole.union(localBox);
7396
7893
  any = true;
7397
7894
  }
7398
- if (!any) return { center: new Vector3(), radius: 0.5 };
7895
+ if (!any) return { center: new Vector3(), radius: 0.5, halfExtents: new Vector3(0.5, 0.5, 0.5) };
7399
7896
  const center = whole.getCenter(new Vector3());
7400
7897
  const radius = whole.getBoundingSphere(new Sphere()).radius;
7401
- return { center, radius: radius > 0 ? radius : 0.5 };
7898
+ const halfExtents = whole.getSize(new Vector3()).multiplyScalar(0.5);
7899
+ return { center, radius: radius > 0 ? radius : 0.5, halfExtents };
7402
7900
  }
7403
7901
  function mipChainBytes(pixels, depth, levels) {
7404
7902
  let bytes = 0;
@@ -7681,6 +8179,13 @@ var GEOMETRY_MAPS = [
7681
8179
  "thicknessMap",
7682
8180
  "transmissionMap"
7683
8181
  ];
8182
+ var SURFACE_NODES = [
8183
+ "aoNode",
8184
+ "emissiveNode",
8185
+ "roughnessNode",
8186
+ "metalnessNode",
8187
+ "maskNode"
8188
+ ];
7684
8189
  var INSTANCE_COLUMNS = /* @__PURE__ */ new WeakMap();
7685
8190
  function signNotZeroNode(value) {
7686
8191
  return select(value.greaterThanEqual(0), float(1), float(-1));
@@ -7827,6 +8332,7 @@ var WorldImpostorSurface = class {
7827
8332
  throw new Error("WorldImpostorSurface requires a baked atlas.");
7828
8333
  const material = cloneLitMaterial(options.source);
7829
8334
  for (const key of GEOMETRY_MAPS) Reflect.set(material, key, null);
8335
+ for (const key of SURFACE_NODES) Reflect.set(material, key, null);
7830
8336
  material.vertexColors = false;
7831
8337
  material.opacity = 1;
7832
8338
  material.opacityNode = null;
@@ -7839,6 +8345,7 @@ var WorldImpostorSurface = class {
7839
8345
  material.needsUpdate = true;
7840
8346
  const centerUniform = uniform(center);
7841
8347
  const radiusUniform = uniform(radius);
8348
+ const halfUniform = options.halfExtents === void 0 ? void 0 : uniform(options.halfExtents.clone());
7842
8349
  const cull = options.cull === true;
7843
8350
  const name = `WorldImpostorSurface${surfaceId}`;
7844
8351
  surfaceId += 1;
@@ -7856,7 +8363,14 @@ var WorldImpostorSurface = class {
7856
8363
  const dAsset = normalize(asMat3(view).inverse().mul(eyeView));
7857
8364
  const basis = frameBasisNode(dAsset);
7858
8365
  const corner = positionGeometry.xy;
7859
- const rel = basis.right.mul(corner.x).add(basis.up.mul(corner.y)).mul(radiusUniform);
8366
+ const extent = halfUniform ? vec2(
8367
+ min(radiusUniform, length(halfUniform.xz).mul(QUAD_ACROSS_SLACK)),
8368
+ min(
8369
+ radiusUniform,
8370
+ 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)
8371
+ )
8372
+ ) : vec2(radiusUniform, radiusUniform);
8373
+ const rel = basis.right.mul(corner.x.mul(extent.x)).add(basis.up.mul(corner.y.mul(extent.y)));
7860
8374
  const gated = cull ? rel.mul(
7861
8375
  select(
7862
8376
  orthographicNode(),
@@ -7892,6 +8406,7 @@ var WorldImpostorSurface = class {
7892
8406
  (_inputs, builder) => transformNormal(fragment.normalAsset, instanceViewMatrixNode(builder))
7893
8407
  )();
7894
8408
  material.positionNode = positionNode;
8409
+ material.castShadowPositionNode = null;
7895
8410
  const geometry = new BufferGeometry();
7896
8411
  geometry.setAttribute(
7897
8412
  "position",
@@ -7964,7 +8479,15 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
7964
8479
  const uvs = [];
7965
8480
  const colors = [];
7966
8481
  const normals = [];
7967
- for (let index = 0; index < 3; index += 1) {
8482
+ const [wa, wb, wc] = weights;
8483
+ const pickA = wa.greaterThanEqual(wb).and(wa.greaterThanEqual(wc));
8484
+ const pickB = wb.greaterThanEqual(wc);
8485
+ const [xa, xb, xc] = cellX;
8486
+ const [ya, yb, yc] = cellY;
8487
+ cellX.push(select(pickA, xa, select(pickB, xb, xc)));
8488
+ cellY.push(select(pickA, ya, select(pickB, yb, yc)));
8489
+ let marched;
8490
+ for (let index = 3; index < 4; index += 1) {
7968
8491
  const direction = octahedralViewNode(
7969
8492
  cellX[index],
7970
8493
  cellY[index],
@@ -7981,6 +8504,7 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
7981
8504
  const hit = Fn(() => {
7982
8505
  const found = float(0).toVar();
7983
8506
  const hitUv = vec2(2).toVar();
8507
+ const hitT = float(0).toVar();
7984
8508
  const previousGap = float(0).toVar();
7985
8509
  const previousAlpha = float(0).toVar();
7986
8510
  const previousT = radiusUniform.toVar();
@@ -8034,6 +8558,7 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
8034
8558
  ),
8035
8559
  () => {
8036
8560
  hitUv.assign(u);
8561
+ hitT.assign(front.add(back).mul(0.5));
8037
8562
  found.assign(1);
8038
8563
  }
8039
8564
  );
@@ -8046,11 +8571,22 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
8046
8571
  Break();
8047
8572
  });
8048
8573
  });
8049
- return vec3(hitUv, found);
8574
+ return vec4(hitUv, found, hitT);
8050
8575
  })();
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());
8576
+ marched = hit;
8577
+ }
8578
+ const surface = marched;
8579
+ const rayOut = normalize(select(orthographicNode(), dirVarying, dirVarying.sub(relVarying)));
8580
+ const hitPoint = relVarying.add(rayOut.mul(surface.w));
8581
+ for (let index = 0; index < 3; index += 1) {
8582
+ const basis = frameBasisNode(
8583
+ octahedralViewNode(cellX[index], cellY[index], grid)
8584
+ );
8585
+ const layer = cellY[index].mul(grid).add(cellX[index]).toInt();
8586
+ const uv2 = vec2(dot(hitPoint, basis.right), dot(hitPoint, basis.up).negate()).div(radiusUniform).mul(0.5).add(0.5);
8587
+ uvs.push(uv2);
8588
+ colors.push(colorMap.depth(layer).sample(uv2).mul(surface.z).toVar());
8589
+ normals.push(normalMap.depth(layer).sample(uv2).mul(surface.z).toVar());
8054
8590
  }
8055
8591
  const [w0, w1, w2] = weights;
8056
8592
  const [c0, c1, c2] = colors;
@@ -8067,6 +8603,8 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
8067
8603
  threshold: mipThresholdNode(uvs, atlas.pixels, cutoff, mipScale)
8068
8604
  };
8069
8605
  }
8606
+ var QUAD_ACROSS_SLACK = 1.25;
8607
+ var QUAD_UP_SLACK = 1.1;
8070
8608
  var LOD_TEMPORAL_LAG = 0.5;
8071
8609
  function advanceTemporalLod(state, eye, now, lag = LOD_TEMPORAL_LAG) {
8072
8610
  if (!Number.isFinite(state.toTime) || now < state.toTime) {
@@ -8104,17 +8642,17 @@ function worldLodMaterial(source, local, distances, level, width, eye, distanceB
8104
8642
  let mask2 = always;
8105
8643
  for (let gate = first; gate < distances.length; gate++) {
8106
8644
  const at = gates[gate];
8107
- let span = at.mul(width).min(at.sub(gates[gate - 1]).mul(width));
8645
+ let span2 = at.mul(width).min(at.sub(gates[gate - 1]).mul(width));
8108
8646
  if (gate + 1 < distances.length)
8109
- span = span.min(gates[gate + 1].sub(at).mul(width));
8110
- const mix2 = mixAt(at, span);
8647
+ span2 = span2.min(gates[gate + 1].sub(at).mul(width));
8648
+ const mix2 = mixAt(at, span2);
8111
8649
  const fadeIn = published === void 0 ? noise.lessThan(mix2) : select(published.x.lessThan(lod), noise.lessThan(mix2), always);
8112
8650
  const fadeOut = published === void 0 ? noise.greaterThanEqual(mix2) : select(published.y.greaterThan(lod), noise.greaterThanEqual(mix2), always);
8113
8651
  mask2 = mask2.and(lod.notEqual(gate).or(fadeIn)).and(lod.notEqual(gate - 1).or(fadeOut));
8114
8652
  }
8115
8653
  return mask2;
8116
8654
  };
8117
- const rampAt = (at, span) => distance.sub(at).div(span).add(0.5).add(random.sub(0.5).mul(0.5)).clamp(0, 1);
8655
+ const rampAt = (at, span2) => distance.sub(at).div(span2).add(0.5).add(random.sub(0.5).mul(0.5)).clamp(0, 1);
8118
8656
  const mask = levelMask(rampAt);
8119
8657
  const shadow = shadowFloor > 0 ? lod.greaterThanEqual(shadowFloor).and(levelMask(rampAt, shadowFloor + 1)) : mask;
8120
8658
  const past = (eyeAt, at) => select(distanceTo(eyeAt).greaterThan(at), float(1), float(0));
@@ -8421,9 +8959,9 @@ var CellImpostors = class {
8421
8959
  const staged = impostorParts(parts);
8422
8960
  try {
8423
8961
  this.#baker.begin(asset.id, staged, { pixels: IMPOSTOR_FRAME_PIXELS });
8424
- } catch {
8962
+ } catch (error) {
8425
8963
  this.#host.addFailure();
8426
- this.#reportImpostor(asset, "begin-failed");
8964
+ this.#reportImpostor(asset, "begin-failed", error);
8427
8965
  continue;
8428
8966
  }
8429
8967
  this.#impostorReservedBytes = IMPOSTOR_ATLAS_BYTES;
@@ -8443,11 +8981,11 @@ var CellImpostors = class {
8443
8981
  atlas = this.#baker.step(raw);
8444
8982
  if (atlas !== void 0 || this.#baker.pending?.view === view) break;
8445
8983
  }
8446
- } catch {
8984
+ } catch (error) {
8447
8985
  this.#host.addFailure();
8448
8986
  this.#impostorBaking = void 0;
8449
8987
  this.#impostorReservedBytes = 0;
8450
- this.#reportImpostor(baking, "bake-failed");
8988
+ this.#reportImpostor(baking, "bake-failed", error);
8451
8989
  return;
8452
8990
  }
8453
8991
  if (atlas === void 0) return;
@@ -8500,6 +9038,7 @@ var CellImpostors = class {
8500
9038
  atlas,
8501
9039
  bytes: atlas.bytes,
8502
9040
  center: bounds.center,
9041
+ halfExtents: bounds.halfExtents,
8503
9042
  key,
8504
9043
  radius: bounds.radius,
8505
9044
  users: 0
@@ -8532,12 +9071,13 @@ var CellImpostors = class {
8532
9071
  alphaTest: source.alphaTest,
8533
9072
  atlas: record.atlas,
8534
9073
  center: record.center,
9074
+ halfExtents: record.halfExtents,
8535
9075
  radius: record.radius,
8536
9076
  source: source.source
8537
9077
  });
8538
- } catch {
9078
+ } catch (error) {
8539
9079
  this.#host.addFailure();
8540
- this.#reportImpostor(asset, "surface-failed");
9080
+ this.#reportImpostor(asset, "surface-failed", error);
8541
9081
  return;
8542
9082
  }
8543
9083
  const switchAt = asset.definition.impostorDistance ?? 2 * record.radius * this.#autoLodPixelsPerUnit / IMPOSTOR_FRAME_PIXELS;
@@ -8720,6 +9260,7 @@ var CellImpostors = class {
8720
9260
  atlas: cohort.record.atlas,
8721
9261
  center: cohort.record.center,
8722
9262
  cull: true,
9263
+ halfExtents: cohort.record.halfExtents,
8723
9264
  radius: cohort.record.radius,
8724
9265
  source: cohort.source
8725
9266
  });
@@ -8834,6 +9375,7 @@ var CellImpostors = class {
8834
9375
  const mesh = new InstancedMesh(surface.geometry, surface.material, capacity);
8835
9376
  mesh.count = capacity;
8836
9377
  mesh.frustumCulled = false;
9378
+ mesh.renderOrder = 1;
8837
9379
  mesh.name = `tn-far:${assetId}`;
8838
9380
  mesh.userData.tnDrawSource = "proxies";
8839
9381
  if (surface.cull) this.#attachFarCull(surface.geometry, capacity);
@@ -9107,13 +9649,14 @@ var CellImpostors = class {
9107
9649
  * `TN_WORLD_IMPOSTOR`, one bounded line per asset: its terminal level, the metres it takes over at,
9108
9650
  * the views the atlas holds, its GPU bytes, and — when the world can name it — why it did not land.
9109
9651
  */
9110
- #reportImpostor(asset, reason) {
9652
+ /** One line per asset; a failure carries its error, so the cause is on the line and not swallowed. */
9653
+ #reportImpostor(asset, reason, error) {
9111
9654
  if (this.#impostorReported.has(asset.id)) return;
9112
9655
  this.#impostorReported.add(asset.id);
9113
9656
  const impostor = asset.impostor;
9114
9657
  const atlas = impostor?.record.atlas ?? this.#baker.pending?.atlas;
9115
9658
  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}`
9659
+ `${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
9660
  );
9118
9661
  }
9119
9662
  };
@@ -9123,75 +9666,6 @@ function cullDistance(maxDistance) {
9123
9666
  return maxDistance === void 0 ? void 0 : maxDistance - maxDistance / 8;
9124
9667
  }
9125
9668
 
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
9669
  // src/world-cell-models.ts
9196
9670
  async function loadModelWith(assets, path, sceneName) {
9197
9671
  const gltf = await assets.model(path, {
@@ -9815,13 +10289,21 @@ var CellModels = class _CellModels {
9815
10289
  paths.length = 0;
9816
10290
  }
9817
10291
  };
9818
-
9819
- // src/world-bundle-safety.ts
9820
10292
  var PER_RENDER_UPDATE = "render";
9821
10293
  var BUNDLE_PROOF_ROWS_PER_FRAME = 256;
9822
10294
  var BUNDLE_PROOF_MAX_PERIOD = 600;
9823
10295
  var BundleSurfaceSafety = class {
9824
10296
  #checks = /* @__PURE__ */ new WeakMap();
10297
+ /**
10298
+ * The owned engine holds every cached verdict's `transparent`, `visible` and `transmission` and
10299
+ * answers which moved in one call a frame, so a settled `deep: false` test reads none of them.
10300
+ * Upstream three has no such host method and reads them per test, as before.
10301
+ *
10302
+ * ponytail: the list keeps every proved material until `clear`, which a world bounds by its assets.
10303
+ */
10304
+ #witness = new Object3D();
10305
+ #witnessed = [];
10306
+ #moved = /* @__PURE__ */ new Set();
9825
10307
  #revision = 0;
9826
10308
  #frame = 0;
9827
10309
  #frameRows = 0;
@@ -9835,6 +10317,9 @@ var BundleSurfaceSafety = class {
9835
10317
  };
9836
10318
  clear() {
9837
10319
  this.#checks = /* @__PURE__ */ new WeakMap();
10320
+ this.#witnessed = [];
10321
+ this.#moved.clear();
10322
+ this.#witness.__tnMaterialWatch?.(this.#witnessed);
9838
10323
  }
9839
10324
  /** Opens a frame: the period every deep proof is spread over follows the last frame's rows. */
9840
10325
  beginFrame() {
@@ -9844,6 +10329,10 @@ var BundleSurfaceSafety = class {
9844
10329
  Math.max(1, Math.ceil(this.#frameRows / BUNDLE_PROOF_ROWS_PER_FRAME))
9845
10330
  );
9846
10331
  this.#frameRows = 0;
10332
+ const moved = this.#witness.__tnMaterialCheck?.();
10333
+ if (moved !== void 0)
10334
+ for (let at = 0; at < moved.length; at++)
10335
+ this.#moved.add(this.#witnessed[moved[at]]);
9847
10336
  }
9848
10337
  /**
9849
10338
  * `deep: false` is for a renderer that records its own bundles from each frame's draws (the owned
@@ -9854,7 +10343,7 @@ var BundleSurfaceSafety = class {
9854
10343
  test(material, deep = true) {
9855
10344
  this.stats.checks++;
9856
10345
  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")) {
10346
+ if (previous !== void 0 && this.#shallowHolds(material, previous, deep)) {
9858
10347
  if (!deep) return previous;
9859
10348
  if (previous.testedFrame !== this.#frame) {
9860
10349
  previous.testedFrame = this.#frame;
@@ -9889,9 +10378,28 @@ var BundleSurfaceSafety = class {
9889
10378
  if (capture.overflow) {
9890
10379
  this.stats.uncached++;
9891
10380
  this.#checks.delete(material);
9892
- } else this.#checks.set(material, checked);
10381
+ } else {
10382
+ this.#checks.set(material, checked);
10383
+ this.#rewatch(material);
10384
+ }
9893
10385
  return checked;
9894
10386
  }
10387
+ /**
10388
+ * Whether the material still holds the cached verdict's shallow witness. `version` is JS-side;
10389
+ * the flags are the engine's answer when it witnesses them and a `deep: false` test asks.
10390
+ */
10391
+ #shallowHolds(material, previous, deep) {
10392
+ if (previous.version !== material.version) return false;
10393
+ if (!deep && this.#witness.__tnMaterialCheck !== void 0) return !this.#moved.has(material);
10394
+ return previous.transparent === material.transparent && previous.visible === material.visible && previous.transmission === Reflect.get(material, "transmission");
10395
+ }
10396
+ /** Re-stamp the engine's witness after a verdict was (re)taken, so it answers from this state. */
10397
+ #rewatch(material) {
10398
+ if (this.#witness.__tnMaterialWatch === void 0) return;
10399
+ if (!this.#witnessed.includes(material)) this.#witnessed.push(material);
10400
+ this.#moved.delete(material);
10401
+ this.#witness.__tnMaterialWatch(this.#witnessed);
10402
+ }
9895
10403
  };
9896
10404
  function graphSnapshotCurrent(row) {
9897
10405
  const node = row.node;
@@ -10094,10 +10602,13 @@ function freshMeshFor(old, geometry, count3) {
10094
10602
  next.receiveShadow = old.receiveShadow;
10095
10603
  next.renderOrder = old.renderOrder;
10096
10604
  next.userData = old.userData;
10605
+ next.position.copy(old.position);
10606
+ next.quaternion.copy(old.quaternion);
10607
+ next.scale.copy(old.scale);
10097
10608
  next.matrix.copy(old.matrix);
10098
- next.matrixAutoUpdate = old.matrixAutoUpdate;
10099
10609
  next.matrixWorld.copy(old.matrixWorld);
10100
- next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate;
10610
+ next.matrixAutoUpdate = old.matrixAutoUpdate || composeSilencedByFreeze(old);
10611
+ next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate || worldSilencedByFreeze(old);
10101
10612
  if (isStatic(old)) markStatic(next);
10102
10613
  return next;
10103
10614
  }
@@ -10109,7 +10620,7 @@ function followCluster(follow, minX, minZ, cellSize, cellsPerCluster) {
10109
10620
  );
10110
10621
  }
10111
10622
  function heldBytes(shared2) {
10112
- return shared2.mesh.instanceMatrix.array.byteLength;
10623
+ return shared2.mesh.instanceMatrix.count * 16 * Float32Array.BYTES_PER_ELEMENT;
10113
10624
  }
10114
10625
  function redressMaterial(mesh) {
10115
10626
  for (const material of redressed.get(mesh) ?? []) material.dispose();
@@ -10253,8 +10764,7 @@ var CellBundles = class {
10253
10764
  if (this.#ownsBundles !== void 0) return this.#ownsBundles;
10254
10765
  const renderer = this.#host.renderer();
10255
10766
  if (renderer === void 0) return false;
10256
- const info = renderer.raw?.info;
10257
- this.#ownsBundles = info !== void 0 && "engine" in info;
10767
+ this.#ownsBundles = rendererFacts(renderer).ownedEngine;
10258
10768
  return this.#ownsBundles;
10259
10769
  }
10260
10770
  /** One re-record, counted: `BundleGroup.needsUpdate` is a version bump, and nothing else. */
@@ -10462,68 +10972,6 @@ var CellBundles = class {
10462
10972
  this.#bundleSafety.clear();
10463
10973
  }
10464
10974
  };
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
10975
 
10528
10976
  // src/world-gpu-validation.ts
10529
10977
  var VALIDATE_REPORTED_KEYS = 10;
@@ -10737,10 +11185,11 @@ function validationReport(input) {
10737
11185
  }
10738
11186
  var OCCLUSION_FLAG = "TN_OCCLUSION";
10739
11187
  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 : "";
11188
+ const asked = readLaunchValue({
11189
+ environment: OCCLUSION_FLAG,
11190
+ global: "__tnOcclusion",
11191
+ query: "tnOcclusion"
11192
+ }) ?? "";
10744
11193
  const value = asked.trim().toLowerCase();
10745
11194
  if (value === "" || value === "0" || value === "off" || value === "false") return "off";
10746
11195
  if (value === "measure" || value === "1" || value === "true") return "measure";
@@ -10841,12 +11290,12 @@ var DepthPyramid = class {
10841
11290
  */
10842
11291
  resize(depthWidth, depthHeight) {
10843
11292
  const levels = [];
10844
- let span = 0;
11293
+ let span2 = 0;
10845
11294
  let width = Math.max(1, Math.ceil(depthWidth / 2));
10846
11295
  let height2 = Math.max(1, Math.ceil(depthHeight / 2));
10847
11296
  while (true) {
10848
- levels.push({ width, height: height2, offset: span });
10849
- span += width * height2;
11297
+ levels.push({ width, height: height2, offset: span2 });
11298
+ span2 += width * height2;
10850
11299
  if (width === 1 && height2 === 1) break;
10851
11300
  width = Math.max(1, Math.ceil(width / 2));
10852
11301
  height2 = Math.max(1, Math.ceil(height2 / 2));
@@ -10859,7 +11308,7 @@ var DepthPyramid = class {
10859
11308
  }))
10860
11309
  return false;
10861
11310
  this.#words = new StorageBufferAttribute(
10862
- new Float32Array(levels.length * TABLE_WORDS + span),
11311
+ new Float32Array(levels.length * TABLE_WORDS + span2),
10863
11312
  1
10864
11313
  );
10865
11314
  const table = this.#words.array;
@@ -11138,7 +11587,7 @@ function liveKeyInstances(placements, asset, camera) {
11138
11587
  }
11139
11588
  function buildCullKernel(input) {
11140
11589
  const { buffers } = input;
11141
- const source = nodes(storage(buffers.source, PlacementStruct, buffers.source.count));
11590
+ const source = nodes(storage(buffers.source, "vec4", buffers.source.count));
11142
11591
  const drawn = nodes(storage(buffers.drawn, "mat4", buffers.drawn.count));
11143
11592
  const argsPlain = nodes(storage(buffers.args, "uint", buffers.args.count));
11144
11593
  const argsAtomic = nodes(storage(buffers.args, "uint", buffers.args.count).toAtomic());
@@ -11167,10 +11616,16 @@ function buildCullKernel(input) {
11167
11616
  })().compute(Math.max(1, buffers.keys.count * clearWidth));
11168
11617
  const cull = Fn(() => {
11169
11618
  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;
11619
+ const base = instanceIndex.mul(uint(PLACEMENT_ROWS));
11620
+ const matrix = mat4(
11621
+ source.element(base),
11622
+ source.element(base.add(uint(1))),
11623
+ source.element(base.add(uint(2))),
11624
+ source.element(base.add(uint(3)))
11625
+ );
11626
+ const centre = source.element(base.add(uint(4)));
11627
+ const info = source.element(base.add(uint(5)));
11628
+ const slot = info.x;
11174
11629
  If(slot.lessThan(0), () => Return());
11175
11630
  If(slot.greaterThanEqual(counts.y), () => Return());
11176
11631
  const radius = centre.w;
@@ -11180,7 +11635,7 @@ function buildCullKernel(input) {
11180
11635
  If(gate.w.mod(2).greaterThan(0.5).and(distance.greaterThan(gate.z)), () => Return());
11181
11636
  const lodDistance = nodes(distance).mul(bias);
11182
11637
  const level = int(0).toVar();
11183
- const scale = abs(placement.get("info").y);
11638
+ const scale = abs(info.y);
11184
11639
  Loop({ start: int(1), end: gate.y, type: "int", condition: "<" }, ({ i }) => {
11185
11640
  const candidate = levels.element(gate.x.add(i));
11186
11641
  const threshold = nodes(candidate.x).toVar();
@@ -11212,7 +11667,10 @@ function buildCullKernel(input) {
11212
11667
  drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
11213
11668
  });
11214
11669
  });
11215
- })().compute(Math.max(1, buffers.source.count));
11670
+ })().compute(
11671
+ // One thread per placement record, not per `vec4` row of the source buffer.
11672
+ Math.max(1, Math.ceil(buffers.source.count / PLACEMENT_ROWS))
11673
+ );
11216
11674
  clear.setName("worldGpuSceneClear");
11217
11675
  cull.setName("worldGpuSceneCull");
11218
11676
  return { clear, cull };
@@ -11221,23 +11679,10 @@ function buildCullKernel(input) {
11221
11679
  // src/world-gpu-flags.ts
11222
11680
  var GPU_SCENE_FLAG = "TN_GPU_SCENE";
11223
11681
  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";
11682
+ return readLaunchFlag({ environment: flag, global: globalName, query: parameter }, "off");
11232
11683
  }
11233
11684
  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";
11685
+ return readLaunchFlag({ environment: flag, global: globalName, query: parameter });
11241
11686
  }
11242
11687
  function gpuSceneRequested() {
11243
11688
  return askedOff(GPU_SCENE_FLAG, "tnGpuScene", "__tnGpuScene") === false;
@@ -11247,19 +11692,17 @@ function lodFromFollowRequested() {
11247
11692
  }
11248
11693
  var BUNDLE_FLAG = "TN_BUNDLES";
11249
11694
  function bundlesAsked() {
11250
- if (askedOn(BUNDLE_FLAG, "tnBundles", "__tnBundles")) return "on";
11251
- return askedOff(BUNDLE_FLAG, "tnBundles", "__tnBundles") ? "off" : "default";
11695
+ const values = readLaunchValues({
11696
+ environment: BUNDLE_FLAG,
11697
+ global: "__tnBundles",
11698
+ query: "tnBundles"
11699
+ });
11700
+ if (values.some((value) => value === "1" || value === "true" || value === "")) return "on";
11701
+ return values.some((value) => value === "0" || value === "false") ? "off" : "default";
11252
11702
  }
11253
11703
  var GPU_SCENE_VALIDATE_FLAG = "TN_GPU_SCENE_VALIDATE";
11254
11704
  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";
11705
+ return askedOn(GPU_SCENE_VALIDATE_FLAG, "tnGpuSceneValidate", "__tnGpuSceneValidate");
11263
11706
  }
11264
11707
  var SHADOW_GPU_KEYS_FLAG = "TN_SHADOW_GPU_KEYS";
11265
11708
  function shadowGpuKeysRequested() {
@@ -11869,7 +12312,7 @@ function uncapturedMessage(event) {
11869
12312
  }
11870
12313
  function buildShadowKernel(input) {
11871
12314
  const { buffers, shadow } = input;
11872
- const source = nodes(storage(buffers.source, PlacementStruct, buffers.source.count));
12315
+ const source = nodes(storage(buffers.source, "vec4", buffers.source.count));
11873
12316
  const drawn = nodes(storage(shadow.drawn, "mat4", shadow.drawn.count));
11874
12317
  const argsPlain = nodes(storage(shadow.args, "uint", shadow.args.count));
11875
12318
  const argsAtomic = nodes(storage(shadow.args, "uint", shadow.args.count).toAtomic());
@@ -11881,7 +12324,7 @@ function buildShadowKernel(input) {
11881
12324
  const eye = nodes(input.eye);
11882
12325
  const bias = nodes(input.bias);
11883
12326
  const gate = nodes(input.gate);
11884
- const base = nodes(input.base);
12327
+ nodes(input.base);
11885
12328
  const planes = input.planes.map((plane) => nodes(plane));
11886
12329
  const clearWidth = input.measureOcclusion ? 2 : 1;
11887
12330
  const clear = Fn(() => {
@@ -11900,10 +12343,16 @@ function buildShadowKernel(input) {
11900
12343
  })().compute(Math.max(1, buffers.keys.count * clearWidth));
11901
12344
  const cull = Fn(() => {
11902
12345
  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;
12346
+ const base2 = instanceIndex.mul(uint(PLACEMENT_ROWS));
12347
+ const matrix = mat4(
12348
+ source.element(base2),
12349
+ source.element(base2.add(uint(1))),
12350
+ source.element(base2.add(uint(2))),
12351
+ source.element(base2.add(uint(3)))
12352
+ );
12353
+ const centre = source.element(base2.add(uint(4)));
12354
+ const info = source.element(base2.add(uint(5)));
12355
+ const slot = info.x;
11907
12356
  If(slot.lessThan(0), () => Return());
11908
12357
  If(slot.greaterThanEqual(counts.y), () => Return());
11909
12358
  const radius = centre.w;
@@ -11914,7 +12363,7 @@ function buildShadowKernel(input) {
11914
12363
  If(asset.w.mod(2).greaterThan(0.5).and(distance.greaterThan(asset.z)), () => Return());
11915
12364
  const lodDistance = nodes(distance).mul(bias);
11916
12365
  const level = int(0).toVar();
11917
- const scale = abs(placement.get("info").y);
12366
+ const scale = abs(info.y);
11918
12367
  Loop({ start: int(1), end: asset.y, type: "int", condition: "<" }, ({ i }) => {
11919
12368
  const candidate = levels.element(asset.x.add(i));
11920
12369
  const threshold = nodes(candidate.x).toVar();
@@ -11939,7 +12388,7 @@ function buildShadowKernel(input) {
11939
12388
  {
11940
12389
  start: int(0),
11941
12390
  end: nodes(
11942
- max(level, int(min(base, asset.y.sub(1))))
12391
+ max(level, int(min(base2, asset.y.sub(1))))
11943
12392
  ).add(1),
11944
12393
  type: "int",
11945
12394
  condition: "<"
@@ -11960,11 +12409,29 @@ function buildShadowKernel(input) {
11960
12409
  drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
11961
12410
  });
11962
12411
  });
11963
- })().compute(Math.max(1, buffers.source.count));
12412
+ })().compute(
12413
+ // One thread per placement record, not per `vec4` row of the source buffer.
12414
+ Math.max(1, Math.ceil(buffers.source.count / PLACEMENT_ROWS))
12415
+ );
11964
12416
  clear.setName("worldGpuSceneShadowClear");
11965
12417
  cull.setName("worldGpuSceneShadowCull");
11966
12418
  return { clear, cull };
11967
12419
  }
12420
+ var _inverse = new Matrix4();
12421
+ function isIdentity(matrix) {
12422
+ const elements = matrix.elements;
12423
+ for (let at = 0; at < 16; at += 1) if (elements[at] !== (at % 5 === 0 ? 1 : 0)) return false;
12424
+ return true;
12425
+ }
12426
+ function localClip(out, camera, root) {
12427
+ out.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
12428
+ if (root === void 0 || isIdentity(root)) return out;
12429
+ return out.multiply(root);
12430
+ }
12431
+ function localPoint(point, root) {
12432
+ if (root === void 0 || isIdentity(root)) return point;
12433
+ return point.applyMatrix4(_inverse.copy(root).invert());
12434
+ }
11968
12435
 
11969
12436
  // src/world-gpu-scene.ts
11970
12437
  function gpuSceneUnsupported(renderer) {
@@ -11978,21 +12445,10 @@ function gpuSceneUnsupported(renderer) {
11978
12445
  return "feature=indirect-first-instance";
11979
12446
  return "";
11980
12447
  }
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
- }
12448
+ function cameraPlanes(camera, out, root) {
12449
+ frustumPlanes(localClip(_proj, camera, root), out);
11992
12450
  }
11993
12451
  var _proj = new Matrix4();
11994
- var _cullFrustum = new Frustum();
11995
- var _eye2 = new Vector3();
11996
12452
  var WorldGpuScene = class {
11997
12453
  /** Resident placements, in the source buffer's own order; index 0 is the buffer's first record. */
11998
12454
  placements = [];
@@ -12477,10 +12933,26 @@ var WorldGpuScene = class {
12477
12933
  * One frame of the main pass: zero every key's instance count, then cull and LOD-select every
12478
12934
  * resident placement into the shared drawn buffer. Nothing else is written.
12479
12935
  */
12480
- dispatch(renderer, camera) {
12936
+ /**
12937
+ * The LOD eye `WorldCells` grades its CPU path from (`updateLodEye`): the camera, pulled to within
12938
+ * the first gate of `follow`. Levels and `maxDistance` then read one eye on both paths (PRD-857).
12939
+ * Unset, the dispatch measures from the camera.
12940
+ */
12941
+ lodEye(x, y, z) {
12942
+ this.#lodEye.set(x, y, z);
12943
+ this.#lodEyeSet = true;
12944
+ }
12945
+ #lodEye = new Vector3();
12946
+ #lodEyeSet = false;
12947
+ /**
12948
+ * `root` is the world's own `matrixWorld`: the frame its placements are recorded in, which is the
12949
+ * frame the planes and the eye have to be taken in. A harness driving the scene on its own leaves
12950
+ * it out, and then the records are read in world space, as they were before the root could move.
12951
+ */
12952
+ dispatch(renderer, camera, root) {
12481
12953
  if (this.#on === false) return;
12482
12954
  if (this.#buffers === void 0) return;
12483
- cameraPlanes(camera, this.#planes);
12955
+ cameraPlanes(camera, this.#planes, root);
12484
12956
  for (const [index, plane] of this.#planeVectors.entries()) {
12485
12957
  const at = index * 4;
12486
12958
  plane.set(
@@ -12490,8 +12962,8 @@ var WorldGpuScene = class {
12490
12962
  this.#planes[at + 3]
12491
12963
  );
12492
12964
  }
12493
- _eye2.setFromMatrixPosition(camera.matrixWorld);
12494
- this.#eye.value.copy(_eye2);
12965
+ if (this.#lodEyeSet) this.#eye.value.copy(this.#lodEye);
12966
+ else localPoint(this.#eye.value.setFromMatrixPosition(camera.matrixWorld), root);
12495
12967
  if (this.#readback.measuring) this.#readback.measure(renderer, camera);
12496
12968
  const kernel = this.#kernel ?? this.#buildKernel();
12497
12969
  if (kernel === void 0) return;
@@ -12610,7 +13082,10 @@ var WorldGpuScene = class {
12610
13082
  keys: storageAttribute(StorageBufferAttribute, "vec4", 1),
12611
13083
  levels: storageAttribute(StorageBufferAttribute, "vec4", 1),
12612
13084
  locals: storageAttribute(StorageBufferAttribute, "mat4", 1),
12613
- source: storageAttribute(StorageBufferAttribute, "GpuPlacement", SOURCE_FLOOR)
13085
+ // Six `vec4` rows per placement, so the count is the rows the kernels index by rather than
13086
+ // the placements: one placement record is 24 words either way, and the CPU's `Float32Array`
13087
+ // stays the GPU's buffer with no repacking.
13088
+ source: storageAttribute(StorageBufferAttribute, "vec4", SOURCE_FLOOR * PLACEMENT_ROWS)
12614
13089
  };
12615
13090
  this.#version += 1;
12616
13091
  return this.#buffers;
@@ -12645,7 +13120,7 @@ var WorldGpuScene = class {
12645
13120
  this.#growOf("drawn", this.#drawnCapacity);
12646
13121
  }
12647
13122
  #reserve(count3) {
12648
- return this.#growOf("source", Math.max(SOURCE_FLOOR, count3));
13123
+ return this.#growOf("source", Math.max(SOURCE_FLOOR, count3) * PLACEMENT_ROWS);
12649
13124
  }
12650
13125
  #writePlacement(index) {
12651
13126
  const buffers = this.#buffers;
@@ -12857,7 +13332,6 @@ var WorldGpuScene = class {
12857
13332
 
12858
13333
  // src/world-cell-render-gpu-dress.ts
12859
13334
  var _gpuEye = new Vector3();
12860
- var _cullFrustum2 = new Frustum();
12861
13335
  var _cullProjScreen = new Matrix4();
12862
13336
  var CellGpuDress = class {
12863
13337
  #host;
@@ -12909,10 +13383,11 @@ var CellGpuDress = class {
12909
13383
  }) : { geometry: own.geometry, material: own.material };
12910
13384
  return {
12911
13385
  ...shape,
12912
- material: this.#lodSurface(entry.asset, level, entry.part, shape.material)
13386
+ material: this.lodSurface(entry.asset, level, entry.part, shape.material)
12913
13387
  };
12914
13388
  }
12915
- #lodSurface(assetId, level, partIndex, source) {
13389
+ /** The material a batch of this level and part draws: `source` with the LOD gate's mask, when the asset has one. */
13390
+ lodSurface(assetId, level, partIndex, source) {
12916
13391
  assertSlotFree(source, assetId);
12917
13392
  const asset = this.#host.asset(assetId);
12918
13393
  const part = asset?.levels[level]?.[partIndex];
@@ -12964,7 +13439,7 @@ var CellGpuDress = class {
12964
13439
  const partIndex = Number(partText?.split("@")[0]);
12965
13440
  const part = asset.levels[level]?.[partIndex];
12966
13441
  if (part !== void 0) {
12967
- const material = this.#lodSurface(asset.id, level, partIndex, part.material);
13442
+ const material = this.lodSurface(asset.id, level, partIndex, part.material);
12968
13443
  if (material.userData.tnPublishedLodRange === true && shared2.mesh.geometry.getAttribute("tnPublishedLodRange") === void 0 && shared2.mesh.count === 0)
12969
13444
  shared2.rebind(part.geometry, material);
12970
13445
  else shared2.surface(material);
@@ -13243,18 +13718,10 @@ var CellGpuDress = class {
13243
13718
  if (camera === void 0) return [];
13244
13719
  const lives = this.liveGates();
13245
13720
  if (lives.size === 0) return [];
13721
+ const root = this.#host.root();
13246
13722
  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);
13723
+ frustumPlanes(localClip(_cullProjScreen, camera, root), planes);
13724
+ localPoint(_gpuEye.setFromMatrixPosition(camera.matrixWorld), root);
13258
13725
  const expected = liveKeyInstances(
13259
13726
  this.#host.gpuScene().placements,
13260
13727
  (slot) => {
@@ -13318,18 +13785,9 @@ var CellGpuDress = class {
13318
13785
  }
13319
13786
  };
13320
13787
  var PARKED_SHARED_CAPACITY = 1;
13321
- var regroupScratch = new Float32Array(0);
13322
- var lodRangeScratch = new Float32Array(0);
13323
13788
  var LOD_RANGE_ATTRIBUTE = "tnPublishedLodRange";
13789
+ var ZERO = new Vector3();
13324
13790
  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
13791
  function sizeOf(square) {
13334
13792
  let size = 0;
13335
13793
  for (const block of square.blocks) size += block[2];
@@ -13450,17 +13908,19 @@ var SharedBatch = class {
13450
13908
  #boxes = /* @__PURE__ */ new Map();
13451
13909
  /** Block handle -> the largest instance scale in it; the union is published on the mesh. */
13452
13910
  #scales = /* @__PURE__ */ new Map();
13453
- /** Carried out of the last `#boxOf` pass, which already reads every record's basis. */
13454
- #maxScale = 0;
13455
13911
  #localGeometry;
13456
13912
  #localCenter = new Vector3();
13457
13913
  #localHalf = new Vector3();
13458
13914
  #union = new Box3();
13459
13915
  #point = new Vector3();
13460
- /** This batch's own pending upload span, and the `update` it was opened in. See `#touched`. */
13916
+ /** This batch's pending upload span, in floats of the instance buffer, until the next flush. See `#touched`. */
13461
13917
  #pendingLow = 0;
13462
13918
  #pendingHigh = 0;
13463
- #pendingEpoch = -1;
13919
+ /** The buffers that span belongs to: the ones this batch wrote last, whatever a later dress swaps in. */
13920
+ #pendingMatrix;
13921
+ #pendingRanges;
13922
+ /** Block handle -> where its box starts in the flush's answer; see {@link settleRecords}. */
13923
+ #pendingBoxes = /* @__PURE__ */ new Map();
13464
13924
  constructor(geometry, material, segmentSize, segments, name, bounds, role, rangeLevel = 0) {
13465
13925
  this.role = role;
13466
13926
  this.#sourceGeometry = geometry;
@@ -13550,8 +14010,8 @@ var SharedBatch = class {
13550
14010
  mesh.frustumCulled = true;
13551
14011
  mesh.castShadow = false;
13552
14012
  mesh.receiveShadow = false;
13553
- mesh.instanceMatrix.array.fill(0);
13554
- mesh.instanceMatrix.needsUpdate = true;
14013
+ batchRecords.fill(mesh.instanceMatrix, 0, records * 16);
14014
+ batchRecords.upload(mesh.instanceMatrix, 0, 0);
13555
14015
  mesh.casterInstanceScale = 0;
13556
14016
  mesh.userData.tnBundled = false;
13557
14017
  mesh.mainAdmitted = true;
@@ -13583,13 +14043,8 @@ var SharedBatch = class {
13583
14043
  this.#setGeometry(this.#geometryFor(this.mesh.instanceMatrix.count));
13584
14044
  const ranges = this.#lodRangeAttribute();
13585
14045
  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;
14046
+ batchRecords.lanes(ranges, LOD_RANGE_STRIDE, [this.#rangeLevel, this.#rangeLevel, -1]);
14047
+ batchRecords.upload(ranges, 0, 0);
13593
14048
  }
13594
14049
  /** The capacity this batch had when it was parked; see {@link park}. */
13595
14050
  #parked = 0;
@@ -13644,72 +14099,26 @@ var SharedBatch = class {
13644
14099
  this.mesh.casterInstanceScale = live === false ? 0 : Math.max(...this.#scales.values());
13645
14100
  }
13646
14101
  /**
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.
14102
+ * The part's local box centre and half size, read once per geometry: the input of the record box
14103
+ * the engine measures from the bytes as written (see {@link write}). False when the geometry has
14104
+ * no readable box, and the package extent stands in for the block's records.
13651
14105
  */
13652
- #boxOf(from, count3) {
13653
- const array = this.mesh.instanceMatrix.array;
14106
+ #localBox() {
13654
14107
  const geometry = this.mesh.geometry;
13655
14108
  if (this.#localGeometry !== geometry) {
13656
14109
  this.#localGeometry = geometry;
13657
14110
  if (geometry?.boundingBox === null || geometry?.boundingBox === void 0)
13658
14111
  geometry?.computeBoundingBox?.();
13659
14112
  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;
14113
+ this.#localReadable = !(local === void 0 || local === null || local.isEmpty());
14114
+ if (local !== void 0 && local !== null && this.#localReadable) {
14115
+ this.#localCenter.copy(local.getCenter(this.#point));
14116
+ this.#localHalf.copy(local.getSize(this.#point)).multiplyScalar(0.5);
14117
+ }
13707
14118
  }
13708
- this.#maxScale = scale;
13709
- out.min.set(minX, minY, minZ);
13710
- out.max.set(maxX, maxY, maxZ);
13711
- return out;
14119
+ return this.#localReadable;
13712
14120
  }
14121
+ #localReadable = false;
13713
14122
  /** A handle for `count` free records, or `undefined` when the buffer has none and must grow. */
13714
14123
  allocate(count3, cluster) {
13715
14124
  const at = this.#take(count3);
@@ -13742,13 +14151,12 @@ var SharedBatch = class {
13742
14151
  old.name,
13743
14152
  this.#bounds
13744
14153
  );
13745
- mesh.instanceMatrix.array.set(old.instanceMatrix.array);
14154
+ const records = old.instanceMatrix.count;
14155
+ batchRecords.copy(mesh.instanceMatrix, old.instanceMatrix, records * 16);
13746
14156
  const oldRanges = old.geometry.getAttribute(LOD_RANGE_ATTRIBUTE);
13747
14157
  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
- }
14158
+ if (oldRanges instanceof InstancedBufferAttribute && nextRanges instanceof InstancedBufferAttribute)
14159
+ batchRecords.copy(nextRanges, oldRanges, records * LOD_RANGE_STRIDE);
13752
14160
  mesh.castShadow = old.castShadow;
13753
14161
  mesh.receiveShadow = old.receiveShadow;
13754
14162
  this.mesh = mesh;
@@ -13756,7 +14164,6 @@ var SharedBatch = class {
13756
14164
  this.#ceiling = mesh.instanceMatrix.count;
13757
14165
  this.#settle();
13758
14166
  this.#touched(0, this.#drawn);
13759
- this.#rebound();
13760
14167
  return old;
13761
14168
  }
13762
14169
  /**
@@ -13792,37 +14199,53 @@ var SharedBatch = class {
13792
14199
  this.#publish(this.#drawn);
13793
14200
  return;
13794
14201
  }
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);
14202
+ const matrix = this.mesh.instanceMatrix;
14203
+ const payloadAt = batchRecords.reserve(batch.count * 16);
14204
+ const written = batch.writeMatrices(batchRecords.payload, payloadAt / 16);
14205
+ batchRecords.write(matrix, start * 16, written * 16, payloadAt);
14206
+ this.#writeRanges(start, written, reserved, lodRanges);
14207
+ batchRecords.fill(matrix, (start + written) * 16, (reserved - written) * 16);
13814
14208
  if (written < reserved) this.#hole(start + written, start + reserved);
13815
14209
  this.#size.set(segment, written);
13816
14210
  if (written > 0) {
13817
- this.#boxes.set(segment, this.#boxOf(start, written));
13818
- this.#scales.set(segment, this.#maxScale);
14211
+ const readable = this.#localBox();
14212
+ const index = batchRecords.box(
14213
+ matrix,
14214
+ start,
14215
+ written,
14216
+ readable ? this.#localCenter : ZERO,
14217
+ readable ? this.#localHalf : ZERO
14218
+ );
14219
+ this.#pendingBoxes.set(segment, readable ? index : -1 - index);
13819
14220
  } else {
13820
14221
  this.#boxes.delete(segment);
13821
14222
  this.#scales.delete(segment);
14223
+ this.#pendingBoxes.delete(segment);
13822
14224
  }
13823
14225
  this.#settle();
13824
14226
  this.#touched(start, written);
13825
- this.#rebound();
14227
+ }
14228
+ /** The block's LOD-range column: the published ranges, or each record whole at this batch's level. */
14229
+ #writeRanges(start, written, reserved, lodRanges) {
14230
+ const ranges = this.#lodRangeAttribute();
14231
+ if (ranges === void 0) return;
14232
+ const at = batchRecords.reserve(written * LOD_RANGE_STRIDE);
14233
+ const values = batchRecords.payload;
14234
+ if (lodRanges !== void 0) values.set(lodRanges.subarray(0, written * LOD_RANGE_STRIDE), at);
14235
+ else
14236
+ for (let index = 0; index < written; index += 1) {
14237
+ const record = at + index * LOD_RANGE_STRIDE;
14238
+ values[record] = this.#rangeLevel;
14239
+ values[record + 1] = this.#rangeLevel;
14240
+ values[record + 2] = -1;
14241
+ values[record + 3] = 0;
14242
+ }
14243
+ batchRecords.write(ranges, start * LOD_RANGE_STRIDE, written * LOD_RANGE_STRIDE, at);
14244
+ batchRecords.fill(
14245
+ ranges,
14246
+ (start + written) * LOD_RANGE_STRIDE,
14247
+ (reserved - written) * LOD_RANGE_STRIDE
14248
+ );
13826
14249
  }
13827
14250
  clear(segment) {
13828
14251
  const start = this.#start.get(segment);
@@ -13841,22 +14264,16 @@ var SharedBatch = class {
13841
14264
  this.#publish(this.#drawn);
13842
14265
  return;
13843
14266
  }
13844
- this.mesh.instanceMatrix.array.fill(0, start * 16, (start + size) * 16);
14267
+ batchRecords.fill(this.mesh.instanceMatrix, start * 16, size * 16);
13845
14268
  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
- }
14269
+ if (ranges !== void 0)
14270
+ batchRecords.fill(ranges, start * LOD_RANGE_STRIDE, size * LOD_RANGE_STRIDE);
13854
14271
  this.#hole(start, start + size);
13855
14272
  this.#settle();
13856
14273
  this.#touched(0, this.#drawn);
13857
14274
  this.#boxes.delete(segment);
13858
14275
  this.#scales.delete(segment);
13859
- this.#rebound();
14276
+ this.#pendingBoxes.delete(segment);
13860
14277
  }
13861
14278
  /** The first free range with room for `count` records, taken out of the list; -1 when there is none. */
13862
14279
  #take(count3) {
@@ -13894,7 +14311,8 @@ var SharedBatch = class {
13894
14311
  * instead of a `grow`, and the free list is left as the single tail range `[drawn, capacity)`.
13895
14312
  */
13896
14313
  #compact() {
13897
- const array = this.mesh.instanceMatrix.array;
14314
+ const matrix = this.mesh.instanceMatrix;
14315
+ const ranges = this.#lodRangeAttribute();
13898
14316
  for (; ; ) {
13899
14317
  let drawn = 0;
13900
14318
  let top = -1;
@@ -13912,12 +14330,14 @@ var SharedBatch = class {
13912
14330
  const [holeStart, holeEnd] = lowest;
13913
14331
  const size = this.#size.get(top) ?? 0;
13914
14332
  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
- );
14333
+ batchRecords.move(matrix, topFrom * 16, holeStart * 16, (drawn - topFrom) * 16);
14334
+ if (ranges !== void 0)
14335
+ batchRecords.move(
14336
+ ranges,
14337
+ topFrom * LOD_RANGE_STRIDE,
14338
+ holeStart * LOD_RANGE_STRIDE,
14339
+ (drawn - topFrom) * LOD_RANGE_STRIDE
14340
+ );
13921
14341
  this.#start.set(top, holeStart);
13922
14342
  if (holeEnd - holeStart > size) this.#free[0] = [holeStart + size, holeEnd];
13923
14343
  else this.#free.shift();
@@ -13926,12 +14346,14 @@ var SharedBatch = class {
13926
14346
  this.#touched(holeStart, size);
13927
14347
  } else {
13928
14348
  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
- );
14349
+ batchRecords.move(matrix, holeEnd * 16, holeStart * 16, (drawn - holeEnd) * 16);
14350
+ if (ranges !== void 0)
14351
+ batchRecords.move(
14352
+ ranges,
14353
+ holeEnd * LOD_RANGE_STRIDE,
14354
+ holeStart * LOD_RANGE_STRIDE,
14355
+ (drawn - holeEnd) * LOD_RANGE_STRIDE
14356
+ );
13935
14357
  this.#free.shift();
13936
14358
  for (const [handle, start] of this.#start) {
13937
14359
  if (start >= holeEnd) this.#start.set(handle, start - shift);
@@ -13973,8 +14395,8 @@ var SharedBatch = class {
13973
14395
  *
13974
14396
  * A regroup is a permutation of `[0, drawn)` and there is no in-place order for one: writing the
13975
14397
  * 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
14398
+ * yet, in either direction. So the engine's gather op reads every block out before it writes the
14399
+ * new order back — two passes over the drawn range, and only when a square entered or left the
13978
14400
  * window, which on a settled camera is not once a frame.
13979
14401
  *
13980
14402
  * Squares keep their relative order within each half, so a residency change regroups in place and
@@ -13993,44 +14415,30 @@ var SharedBatch = class {
13993
14415
  * stay few and large rather than many and small.
13994
14416
  */
13995
14417
  #regroup(visible = this.#visible) {
13996
- const array = this.mesh.instanceMatrix.array;
13997
- const rangeAttribute = this.#lodRangeAttribute();
13998
- const rangeArray = rangeAttribute?.array;
13999
14418
  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
14419
  const front = squares.filter((one) => visible?.has(one.cluster) ?? true);
14005
14420
  const back = squares.filter((one) => !(visible?.has(one.cluster) ?? true));
14006
14421
  let written = 0;
14007
14422
  let movedFrom = -1;
14008
14423
  let movedTo = 0;
14424
+ const blocks = [];
14009
14425
  this.#squareSizes.clear();
14010
14426
  for (const square of [...front, ...back]) {
14011
- const union = new Box3();
14012
14427
  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
- );
14428
+ blocks.push(start, count3);
14019
14429
  if (this.#start.get(handle) !== written) {
14020
14430
  if (movedFrom < 0) movedFrom = written;
14021
14431
  movedTo = written + count3;
14022
14432
  }
14023
14433
  this.#start.set(handle, written);
14024
- const box = this.#boxes.get(handle);
14025
- if (box !== void 0) union.union(box);
14026
14434
  written += count3;
14027
14435
  }
14028
14436
  this.#squareSizes.set(square.cluster, sizeOf(square));
14029
14437
  }
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;
14438
+ if (movedFrom >= 0) {
14439
+ batchRecords.gather(this.mesh.instanceMatrix, 16, blocks);
14440
+ const ranges = this.#lodRangeAttribute();
14441
+ if (ranges !== void 0) batchRecords.gather(ranges, LOD_RANGE_STRIDE, blocks);
14034
14442
  }
14035
14443
  this.#drawn = written;
14036
14444
  const capacity = this.mesh.instanceMatrix.count;
@@ -14156,14 +14564,10 @@ var SharedBatch = class {
14156
14564
  */
14157
14565
  #touched(from, count3) {
14158
14566
  if (this.gpu !== void 0) return;
14159
- const matrix = this.mesh.instanceMatrix;
14160
14567
  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) {
14568
+ let low = from * 16;
14569
+ let high = (from + count3) * 16;
14570
+ if (this.#pendingMatrix !== void 0) {
14167
14571
  if (this.#pendingLow < low) low = this.#pendingLow;
14168
14572
  if (this.#pendingHigh > high) high = this.#pendingHigh;
14169
14573
  }
@@ -14173,23 +14577,50 @@ var SharedBatch = class {
14173
14577
  }
14174
14578
  this.#pendingLow = low;
14175
14579
  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
- }
14580
+ this.#pendingMatrix = this.mesh.instanceMatrix;
14581
+ this.#pendingRanges = this.#lodRangeAttribute();
14582
+ batchRecords.touch(this);
14190
14583
  this.#publish(this.#drawn);
14191
14584
  this.mesh.frustumCulled = true;
14192
14585
  }
14586
+ /** The flush asks for this frame's upload span, one range per buffer; see {@link #touched}. */
14587
+ uploadRecords() {
14588
+ const matrix = this.#pendingMatrix;
14589
+ if (matrix === void 0) return;
14590
+ const low = this.#pendingLow;
14591
+ const high = this.#pendingHigh;
14592
+ batchRecords.upload(matrix, low, high - low);
14593
+ if (this.#pendingRanges !== void 0)
14594
+ batchRecords.upload(
14595
+ this.#pendingRanges,
14596
+ low / 16 * LOD_RANGE_STRIDE,
14597
+ (high - low) / 16 * LOD_RANGE_STRIDE
14598
+ );
14599
+ this.#pendingMatrix = void 0;
14600
+ this.#pendingRanges = void 0;
14601
+ }
14602
+ /**
14603
+ * The flush answered: each block written this frame gets the box the engine measured, and the
14604
+ * mesh's bounds are published once from all of them.
14605
+ */
14606
+ settleRecords(boxes) {
14607
+ for (const [segment, encoded] of this.#pendingBoxes) {
14608
+ if (!this.#start.has(segment)) continue;
14609
+ const at = encoded < 0 ? -1 - encoded : encoded;
14610
+ const box = encoded < 0 ? this.#bounds : new Box3(
14611
+ new Vector3(boxes[at], boxes[at + 1], boxes[at + 2]),
14612
+ new Vector3(
14613
+ boxes[at + 3],
14614
+ boxes[at + 4],
14615
+ boxes[at + 5]
14616
+ )
14617
+ );
14618
+ this.#boxes.set(segment, box);
14619
+ this.#scales.set(segment, boxes[at + 6]);
14620
+ }
14621
+ this.#pendingBoxes.clear();
14622
+ this.#rebound();
14623
+ }
14193
14624
  /**
14194
14625
  * The one place `mesh.count` is written, so a batch that would draw nothing is not submitted.
14195
14626
  *
@@ -14282,8 +14713,20 @@ var SharedBatch = class {
14282
14713
  };
14283
14714
 
14284
14715
  // src/world-cell-render-main-cull.ts
14285
- var _cullFrustum3 = new Frustum();
14716
+ var _cullFrustum = new Frustum();
14286
14717
  var _cullProjScreen2 = new Matrix4();
14718
+ var _cullBox = new Box3();
14719
+ function boxesInFrustum(frustum, boxes) {
14720
+ const engine = frustum.__tnIntersectsBoxes;
14721
+ if (typeof engine === "function") return engine.call(frustum, boxes);
14722
+ const hits = [];
14723
+ for (let at = 0; at < boxes.length; at += 6) {
14724
+ _cullBox.min.fromArray(boxes, at);
14725
+ _cullBox.max.fromArray(boxes, at + 3);
14726
+ if (frustum.intersectsBox(_cullBox)) hits.push(at / 6);
14727
+ }
14728
+ return hits;
14729
+ }
14287
14730
  var CellMainCull = class {
14288
14731
  #host;
14289
14732
  #cellSize;
@@ -14318,6 +14761,13 @@ var CellMainCull = class {
14318
14761
  * {@link #cullMainPass}.
14319
14762
  */
14320
14763
  #cullCells = /* @__PURE__ */ new Map();
14764
+ /**
14765
+ * The non-empty volumes of `#cullCells` packed for the frame's one frustum test, and their names
14766
+ * by index. Repacked only after a volume was admitted, widened or dropped, so a frame reads no box.
14767
+ */
14768
+ #cullBoxes = new Float64Array(0);
14769
+ #cullNames = [];
14770
+ #cullPacked = false;
14321
14771
  /** The visibility cells the last cull kept and the frame's set, trading places; see `#cullMainPass`. */
14322
14772
  #visibleSquares = /* @__PURE__ */ new Set();
14323
14773
  #cullScratch = /* @__PURE__ */ new Set();
@@ -14361,14 +14811,14 @@ var CellMainCull = class {
14361
14811
  if (camera === void 0 || camera.isOrthographicCamera === true) return;
14362
14812
  this.#host.beginBundleFrame();
14363
14813
  this.#mainCullFrustums += 1;
14364
- const frustum = _cullFrustum3.setFromProjectionMatrix(
14365
- _cullProjScreen2.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
14366
- );
14814
+ const root = this.#host.render().root();
14815
+ const frustum = _cullFrustum.setFromProjectionMatrix(localClip(_cullProjScreen2, camera, root));
14367
14816
  const next = this.#cullScratch;
14368
14817
  next.clear();
14369
- for (const [cell, entry] of this.#cullCells) {
14370
- if (entry.box.isEmpty() === false && frustum.intersectsBox(entry.box)) next.add(cell);
14371
- }
14818
+ if (!this.#cullPacked) this.#packCullBoxes();
14819
+ const hits = boxesInFrustum(frustum, this.#cullBoxes);
14820
+ for (let at = 0; at < hits.length; at += 1)
14821
+ next.add(this.#cullNames[hits[at]]);
14372
14822
  if (!sameSquares(next, this.#visibleSquares)) {
14373
14823
  this.#visibleEpoch += 1;
14374
14824
  const was = this.#visibleSquares;
@@ -14408,13 +14858,29 @@ var CellMainCull = class {
14408
14858
  this.#host.dressShadowKey(shared2, shared2.mesh.name.slice(0, -GPU_KEY_SUFFIX.length));
14409
14859
  }
14410
14860
  this.#host.applyGpuMain(dressed);
14411
- if (gpu.on) gpu.dispatch(this.#host.render().renderer(), camera);
14861
+ if (gpu.on) gpu.dispatch(this.#host.render().renderer(), camera, root);
14862
+ }
14863
+ /**
14864
+ * An occupied cell whose placements have not been decoded yet holds nothing to draw, and its Y
14865
+ * range is still empty — a volume that cannot be tested against ±Infinity is not one a frame's
14866
+ * answer may rest on, so it is not packed.
14867
+ */
14868
+ #packCullBoxes() {
14869
+ this.#cullNames.length = 0;
14870
+ this.#cullBoxes = new Float64Array(this.#cullCells.size * 6);
14871
+ for (const [cell, { box }] of this.#cullCells) {
14872
+ if (box.isEmpty()) continue;
14873
+ const at = this.#cullNames.length * 6;
14874
+ box.min.toArray(this.#cullBoxes, at);
14875
+ box.max.toArray(this.#cullBoxes, at + 3);
14876
+ this.#cullNames.push(cell);
14877
+ }
14878
+ this.#cullBoxes = this.#cullBoxes.subarray(0, this.#cullNames.length * 6);
14879
+ this.#cullPacked = true;
14412
14880
  }
14413
14881
  /** Borrowed scratch box: consume its transformed volume before the next bounds query. */
14414
14882
  #boundsAt(bounds, matrix) {
14415
- this.#recordBounds.min.fromArray(bounds.min);
14416
- this.#recordBounds.max.fromArray(bounds.max);
14417
- return this.#recordBounds.applyMatrix4(matrix);
14883
+ return placedBox(this.#recordBounds, bounds.min, bounds.max, matrix);
14418
14884
  }
14419
14885
  /**
14420
14886
  * The one volume per resident visibility cell, shared by every key: its own XZ footprint, and in Y
@@ -14458,6 +14924,7 @@ var CellMainCull = class {
14458
14924
  this.#cullCells.set(name, entry);
14459
14925
  }
14460
14926
  entry.cells += 1;
14927
+ this.#cullPacked = false;
14461
14928
  const box = entry.box;
14462
14929
  for (const run of cell.runs) {
14463
14930
  const bounds = this.#manifest.assets[this.#host.render().canonical(run.asset)]?.bounds;
@@ -14491,7 +14958,10 @@ var CellMainCull = class {
14491
14958
  const entry = this.#cullCells.get(name);
14492
14959
  if (entry === void 0) return;
14493
14960
  entry.cells -= 1;
14494
- if (entry.cells <= 0) this.#cullCells.delete(name);
14961
+ if (entry.cells <= 0) {
14962
+ this.#cullCells.delete(name);
14963
+ this.#cullPacked = false;
14964
+ }
14495
14965
  }
14496
14966
  /**
14497
14967
  * `TN_WORLD_MAIN_CULL`, every `MAIN_CULL_MARKER_MS`: what the main pass holds, what it is drawing,
@@ -14593,11 +15063,14 @@ var CellMainCull = class {
14593
15063
  * is why it lives here: a caller that answered from a copy no frame wrote would hold everything.
14594
15064
  */
14595
15065
  intersectsObject(mesh) {
14596
- return _cullFrustum3.intersectsObject(mesh);
15066
+ return _cullFrustum.intersectsObject(mesh);
14597
15067
  }
14598
- /** The volume each resident visibility cell covers, which the chunk bounds widen on admission. */
14599
- cells() {
14600
- return this.#cullCells;
15068
+ /** Widen a resident visibility cell's volume by a chunk's bounds; an unknown cell is left alone. */
15069
+ widenCell(name, box) {
15070
+ const entry = this.#cullCells.get(name);
15071
+ if (entry === void 0) return;
15072
+ entry.box.union(box);
15073
+ this.#cullPacked = false;
14601
15074
  }
14602
15075
  /** The visibility cells the last cull kept, which the GPU dress's coarse gate reads. */
14603
15076
  get visible() {
@@ -14717,6 +15190,7 @@ var CellPrewarm = class {
14717
15190
  const batch = this.#drawBatches.get(object);
14718
15191
  if (!batch || batch.gpu !== void 0 || batch.role !== "main" || object.count <= 0 || !camera.layers.test(object.layers) || !frustum.intersectsObject(object))
14719
15192
  return;
15193
+ this.#drawBorrows.get(object)?.settle();
14720
15194
  if (this.#submitted.has(object)) return;
14721
15195
  pending++;
14722
15196
  active.add(object);
@@ -14728,6 +15202,11 @@ var CellPrewarm = class {
14728
15202
  const hadBefore = Object.hasOwn(object, "onBeforeRender");
14729
15203
  const hadAfter = Object.hasOwn(object, "onAfterRender");
14730
15204
  let before;
15205
+ let hookedAt;
15206
+ const renders = () => {
15207
+ const value = renderer.info.render?.calls;
15208
+ return Number.isSafeInteger(value) ? value : void 0;
15209
+ };
14731
15210
  const calls = () => {
14732
15211
  const value = renderer.info.render;
14733
15212
  const count3 = value?.drawCalls ?? value?.calls;
@@ -14746,6 +15225,7 @@ var CellPrewarm = class {
14746
15225
  before = void 0;
14747
15226
  ownBefore.apply(this, args);
14748
15227
  before = args[2] === camera && renderer.compiling !== true ? calls() : void 0;
15228
+ hookedAt = before === void 0 ? void 0 : renders();
14749
15229
  };
14750
15230
  const afterHook = function(...args) {
14751
15231
  const after = calls();
@@ -14754,13 +15234,21 @@ var CellPrewarm = class {
14754
15234
  release3();
14755
15235
  }
14756
15236
  before = void 0;
15237
+ hookedAt = void 0;
14757
15238
  ownAfter.apply(this, args);
14758
15239
  };
14759
15240
  markEngineRenderHook(beforeHook);
14760
15241
  markEngineRenderHook(afterHook);
14761
15242
  object.onBeforeRender = beforeHook;
14762
15243
  object.onAfterRender = afterHook;
14763
- this.#drawBorrows.set(object, { before: beforeHook, release: release3 });
15244
+ const settle = () => {
15245
+ const now = hookedAt === void 0 ? void 0 : renders();
15246
+ if (object.count > 0 && now !== void 0 && hookedAt !== void 0 && now > hookedAt) {
15247
+ submitted.add(object);
15248
+ release3();
15249
+ }
15250
+ };
15251
+ this.#drawBorrows.set(object, { before: beforeHook, release: release3, settle });
14764
15252
  });
14765
15253
  for (const [mesh, borrow] of this.#drawBorrows) if (!active.has(mesh)) borrow.release();
14766
15254
  return pending;
@@ -14860,7 +15348,7 @@ var CellPrewarm = class {
14860
15348
  return;
14861
15349
  const shared2 = new SharedBatch(
14862
15350
  entry.geometry,
14863
- entry.material,
15351
+ this.#host.lodSurface(entry.asset, entry.level, entry.part, entry.material),
14864
15352
  this.#host.runMax(entry.asset) ?? 1,
14865
15353
  this.#host.residentCells() + 1,
14866
15354
  entry.key,
@@ -15200,6 +15688,7 @@ var CellRender = class {
15200
15688
  if (entry.wide !== void 0)
15201
15689
  entry.wide.write(entry.wideSegment, entry.wideRoot ?? entry.batch, entry.lodRanges);
15202
15690
  }
15691
+ this.#host.cellBatchesChanged(cell);
15203
15692
  this.publishGpuGates(job.asset);
15204
15693
  const before = job.cell.placed?.get(job.run);
15205
15694
  const after = job.placed ?? [];
@@ -15771,6 +16260,7 @@ var CellRender = class {
15771
16260
  renderer: () => this.#host.renderer(),
15772
16261
  resident: () => this.#gpuResident,
15773
16262
  retired: () => this.#retired,
16263
+ root: () => this.#host.root(),
15774
16264
  shadowFloorOf: (assetId) => this.shadowFloorOf(assetId),
15775
16265
  shadowKeyFor: (key, part) => this.shadowKeyFor(key, part),
15776
16266
  shared: () => this.#shared,
@@ -15932,10 +16422,14 @@ var CellRender = class {
15932
16422
  }
15933
16423
  updateLodEye(x, y, z) {
15934
16424
  this.#dress.updateLodEye(x, y, z);
16425
+ this.#gpuScene.lodEye(x, y, z);
15935
16426
  }
15936
16427
  refreshLodMaterials(asset) {
15937
16428
  this.#dress.refreshLodMaterials(asset);
15938
16429
  }
16430
+ lodSurface(asset, level, part, source) {
16431
+ return this.#dress.lodSurface(asset, level, part, source);
16432
+ }
15939
16433
  impostorDrawn() {
15940
16434
  return this.#dress.impostorDrawn();
15941
16435
  }
@@ -16049,7 +16543,7 @@ var CellRender = class {
16049
16543
  if (box !== void 0) {
16050
16544
  if (proxies > 0) this.shadowRecordsMoved(box, true);
16051
16545
  if (this.#bundles.wanted)
16052
- this.#cull.cells().get(clusterOf(cell.x, cell.z, this.#cellsPerCullCell))?.box.union(box);
16546
+ this.#cull.widenCell(clusterOf(cell.x, cell.z, this.#cellsPerCullCell), box);
16053
16547
  }
16054
16548
  }
16055
16549
  enableGpu(renderer, wanted, validate, tally, occlusion) {
@@ -16197,17 +16691,7 @@ function autoLodPixelError(autoLod) {
16197
16691
  }
16198
16692
  var DEFAULT_MAIN_GPU_SHARE = 0.5;
16199
16693
  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;
16694
+ return readLaunchValue({ environment: flag, global: globalName, query: parameter });
16211
16695
  }
16212
16696
  function impostorsRequested() {
16213
16697
  const raw = launchValue("tnImpostors", "TN_IMPOSTORS", "__tnImpostors");
@@ -16231,6 +16715,162 @@ function impostorFarOption(value) {
16231
16715
  throw new Error('WorldCells impostorFar must be "ring" or "always".');
16232
16716
  }
16233
16717
 
16718
+ // src/world-cell-stale.ts
16719
+ var STALE_HEADER = 8;
16720
+ var STALE_ENTRY = 12;
16721
+ var STALE_QUERY = 8;
16722
+ function length6(x, y, z = 0) {
16723
+ return Math.sqrt(x * x + y * y + z * z);
16724
+ }
16725
+ function span(left, near, size, x, z) {
16726
+ const right = left + size;
16727
+ const far = near + size;
16728
+ return [
16729
+ length6(Math.max(left - x, x - right, 0), Math.max(near - z, z - far, 0)),
16730
+ length6(
16731
+ Math.max(Math.abs(x - left), Math.abs(x - right)),
16732
+ Math.max(Math.abs(z - near), Math.abs(z - far))
16733
+ )
16734
+ ];
16735
+ }
16736
+ function crossesWorldGate(query, low, high) {
16737
+ const count3 = query[7];
16738
+ let start = 0;
16739
+ let end = count3;
16740
+ while (start < end) {
16741
+ const middle = start + end >> 1;
16742
+ if (query[STALE_QUERY + middle] < low) start = middle + 1;
16743
+ else end = middle;
16744
+ }
16745
+ return start < count3 && query[STALE_QUERY + start] <= high;
16746
+ }
16747
+ function vertical(y, minY, maxY) {
16748
+ return [Math.max(minY - y, y - maxY, 0), Math.max(Math.abs(y - minY), Math.abs(y - maxY))];
16749
+ }
16750
+ function reachCrossed(slab, at, cell, followY, brackets) {
16751
+ const minY = slab[at + 10];
16752
+ const maxY = slab[at + 11];
16753
+ const filterY = slab[at + 2];
16754
+ const [reachBuiltNear, reachBuiltFar] = span(
16755
+ slab[cell],
16756
+ slab[cell + 1],
16757
+ slab[cell + 2],
16758
+ slab[at + 1],
16759
+ slab[at + 3]
16760
+ );
16761
+ const current = vertical(followY, minY, maxY);
16762
+ const previous = vertical(filterY, minY, maxY);
16763
+ const reachLow = Math.min(length6(brackets[2], current[0]), length6(reachBuiltNear, previous[0]));
16764
+ const reachHigh = Math.max(length6(brackets[3], current[1]), length6(reachBuiltFar, previous[1]));
16765
+ return slab[at + 8] <= reachHigh && slab[at + 9] >= reachLow;
16766
+ }
16767
+ function entryStale(slab, at, cell, gates, query, brackets) {
16768
+ const x = query[0];
16769
+ const followY = query[1];
16770
+ const z = query[2];
16771
+ const eyeX = query[3];
16772
+ const eyeY = query[4];
16773
+ const eyeZ = query[5];
16774
+ const gpuOn = query[6];
16775
+ const left = slab[cell];
16776
+ const nearZ = slab[cell + 1];
16777
+ const size = slab[cell + 2];
16778
+ const [eyeNear, eyeFar] = brackets;
16779
+ const threshold = slab[at + 7];
16780
+ const reachMin = slab[at + 8];
16781
+ const reach = !Number.isNaN(reachMin);
16782
+ if (!reach && (gpuOn === 1 || Number.isNaN(threshold))) return false;
16783
+ const step = (Number.isNaN(threshold) ? 6 : threshold) / 8;
16784
+ const filterX = slab[at + 1];
16785
+ const filterY = slab[at + 2];
16786
+ const filterZ = slab[at + 3];
16787
+ const lodX = slab[at + 4];
16788
+ const lodY = slab[at + 5];
16789
+ const lodZ = slab[at + 6];
16790
+ if (length6(x - filterX, followY - filterY, z - filterZ) <= step && length6(eyeX - lodX, eyeY - lodY, eyeZ - lodZ) <= step)
16791
+ return false;
16792
+ const asset = slab[at];
16793
+ const gateAt = gates[1 + asset * 2];
16794
+ if (gateAt < 0) return false;
16795
+ const gateCount = gpuOn === 1 ? 0 : gates[2 + asset * 2];
16796
+ const [builtNear, builtFar] = span(left, nearZ, size, lodX, lodZ);
16797
+ let low = Math.min(eyeNear, builtNear);
16798
+ let high = Math.max(eyeFar, builtFar);
16799
+ if (reach) {
16800
+ const minY = slab[at + 10];
16801
+ const maxY = slab[at + 11];
16802
+ const eyeNow = vertical(eyeY, minY, maxY);
16803
+ const eyeBefore = vertical(lodY, minY, maxY);
16804
+ low = Math.min(length6(eyeNear, eyeNow[0]), length6(builtNear, eyeBefore[0]));
16805
+ high = Math.max(length6(eyeFar, eyeNow[1]), length6(builtFar, eyeBefore[1]));
16806
+ if (reachCrossed(slab, at, cell, followY, brackets)) return true;
16807
+ }
16808
+ for (let gate = 0; gate < gateCount; gate += 1) {
16809
+ const value = gates[gateAt + gate];
16810
+ if (value >= low && value <= high) return true;
16811
+ }
16812
+ return false;
16813
+ }
16814
+ function staleRows(slab, gates, query) {
16815
+ const out = [];
16816
+ const seen = /* @__PURE__ */ new Set();
16817
+ const x = query[0];
16818
+ const z = query[2];
16819
+ const eyeX = query[3];
16820
+ const eyeZ = query[5];
16821
+ const gpuOn = query[6];
16822
+ let ordinal = 0;
16823
+ for (let cell = 0; cell < slab.length; ordinal += 1) {
16824
+ const entries = slab[cell + 6];
16825
+ const next = cell + STALE_HEADER + entries * STALE_ENTRY;
16826
+ const left = slab[cell];
16827
+ const nearZ = slab[cell + 1];
16828
+ const size = slab[cell + 2];
16829
+ const hasReach = slab[cell + 5] === 1;
16830
+ const [eyeNear, eyeFar] = span(left, nearZ, size, eyeX, eyeZ);
16831
+ const low = Math.min(eyeNear, slab[cell + 3]);
16832
+ const high = Math.max(eyeFar, slab[cell + 4]);
16833
+ if (gpuOn === 1 && !hasReach || !hasReach && !crossesWorldGate(query, low, high)) {
16834
+ cell = next;
16835
+ continue;
16836
+ }
16837
+ const [near, far] = span(left, nearZ, size, x, z);
16838
+ seen.clear();
16839
+ for (let at = cell + STALE_HEADER; at < next; at += STALE_ENTRY) {
16840
+ const asset = slab[at];
16841
+ if (seen.has(asset)) continue;
16842
+ if (!entryStale(slab, at, cell, gates, query, [eyeNear, eyeFar, near, far])) continue;
16843
+ seen.add(asset);
16844
+ out.push(ordinal, asset, eyeNear);
16845
+ }
16846
+ cell = next;
16847
+ }
16848
+ return out;
16849
+ }
16850
+ function patchRows(held, blocks, plan) {
16851
+ let length7 = 0;
16852
+ for (let at = 1; at < plan.length; at += 2) length7 += plan[at];
16853
+ const next = new Float64Array(length7);
16854
+ let written = 0;
16855
+ let taken = 0;
16856
+ for (let at = 0; at + 1 < plan.length; at += 2) {
16857
+ const source = plan[at];
16858
+ const count3 = plan[at + 1];
16859
+ const from = source === -1 ? blocks : held;
16860
+ const start = source === -1 ? taken : source;
16861
+ if (!(Number.isInteger(start) && Number.isInteger(count3) && start >= 0 && count3 >= 0 && start + count3 <= from.length))
16862
+ throw new RangeError(
16863
+ `TN_WORLD_STALE: a plan run [${String(source)}, ${String(count3)}] is outside its rows`
16864
+ );
16865
+ next.set(from.subarray(start, start + count3), written);
16866
+ written += count3;
16867
+ if (source === -1) taken += count3;
16868
+ }
16869
+ if (taken !== blocks.length)
16870
+ throw new RangeError("TN_WORLD_STALE: the plan leaves changed blocks unread");
16871
+ return next;
16872
+ }
16873
+
16234
16874
  // src/world-cell-placements.ts
16235
16875
  function newBatches(asset) {
16236
16876
  const batches = [];
@@ -16256,6 +16896,14 @@ function newBoxes(batches) {
16256
16896
  }
16257
16897
  return boxes;
16258
16898
  }
16899
+ function extendPlan(plan, source, count3) {
16900
+ const last = plan.length - 2;
16901
+ const runSource = plan[last];
16902
+ const runCount = plan[last + 1];
16903
+ const joins = runSource !== void 0 && (source === -1 ? runSource === -1 : runSource >= 0 && runSource + runCount === source);
16904
+ if (joins) plan[last + 1] = runCount + count3;
16905
+ else plan.push(source, count3);
16906
+ }
16259
16907
  var CellPlacements = class {
16260
16908
  #host;
16261
16909
  /** The authored placement records, immutable for the world's life. */
@@ -16271,9 +16919,22 @@ var CellPlacements = class {
16271
16919
  #placementRanges;
16272
16920
  /** Every distinct gate distance the world's assets have, ascending; see `noteGate`. */
16273
16921
  #gates = [];
16274
- /** The reused hit list and the reused per-cell seen set; see `#staleIn`. */
16922
+ /** The reused hit list; see `#collectStale`. */
16275
16923
  #stale = [];
16276
- #staleSeen = /* @__PURE__ */ new Set();
16924
+ /** Per cell, its block of the stale scan's slab, dropped when the cell's batches change. */
16925
+ #rows = /* @__PURE__ */ new WeakMap();
16926
+ /** The resident cells' blocks laid end to end, and the cells in block order; see `#collectStale`. */
16927
+ #slab = new Float64Array(0);
16928
+ #slabCells = [];
16929
+ /** Where each cell's block sits in the slab the last pack sent; an unchanged block is not sent again. */
16930
+ #slabAt = /* @__PURE__ */ new Map();
16931
+ #slabEpoch = -1;
16932
+ #slabStale = true;
16933
+ /** Asset ids by the index the slab names them with; the index only ever grows. */
16934
+ #assetIds = [];
16935
+ #assetIndex = /* @__PURE__ */ new Map();
16936
+ /** The owned engine's `__tnStaleEntries` host; on upstream three it has no such method. */
16937
+ #engine = new Object3D();
16277
16938
  /** Stale cell-assets the passes found, cumulative; see `IWorldCellsStats.refilterEntries`. */
16278
16939
  #staleEntries = 0;
16279
16940
  /** Refilter passes run, whether or not they queued anything; see `IWorldCellsStats.refilters`. */
@@ -16342,9 +17003,7 @@ var CellPlacements = class {
16342
17003
  }
16343
17004
  /** Borrowed scratch box: consume its transformed volume before the next bounds query. */
16344
17005
  #boundsAt(bounds, matrix) {
16345
- this.#recordBounds.min.fromArray(bounds.min);
16346
- this.#recordBounds.max.fromArray(bounds.max);
16347
- return this.#recordBounds.applyMatrix4(matrix);
17006
+ return placedBox(this.#recordBounds, bounds.min, bounds.max, matrix);
16348
17007
  }
16349
17008
  /**
16350
17009
  * Does this update have to run the `maxDistance`/`lods` refilter pass?
@@ -16453,16 +17112,16 @@ var CellPlacements = class {
16453
17112
  this.#placementRanges[record] = minPublished + 1 | maxPublished + 1 << 4;
16454
17113
  }
16455
17114
  const bounds = asset.definition.bounds;
16456
- const placedBox = this.#boundsAt(bounds, this.#matrix);
17115
+ const placedBox2 = this.#boundsAt(bounds, this.#matrix);
16457
17116
  job.placed ??= [];
16458
17117
  job.placed.push(
16459
17118
  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
17119
+ placedBox2.min.x,
17120
+ placedBox2.min.y,
17121
+ placedBox2.min.z,
17122
+ placedBox2.max.x,
17123
+ placedBox2.max.y,
17124
+ placedBox2.max.z
16466
17125
  );
16467
17126
  for (level of selected) {
16468
17127
  if (wantRoots) {
@@ -16501,7 +17160,6 @@ var CellPlacements = class {
16501
17160
  z: centre.z
16502
17161
  });
16503
17162
  }
16504
- this.#boundsAt(bounds, this.#matrix);
16505
17163
  const parts = asset.levels[level];
16506
17164
  const levelBatches = job.batches?.[level];
16507
17165
  const levelBoxes = job.boxes?.[level];
@@ -16535,6 +17193,12 @@ var CellPlacements = class {
16535
17193
  const [near, far] = this.#span(cell, filterX, filterZ);
16536
17194
  if (near < cell.filterNear) cell.filterNear = near;
16537
17195
  if (far > cell.filterFar) cell.filterFar = far;
17196
+ this.cellBatchesChanged(cell);
17197
+ }
17198
+ /** The cell's batches or bracket changed, so its block of the stale scan is rebuilt. */
17199
+ cellBatchesChanged(cell) {
17200
+ this.#rows.delete(cell);
17201
+ this.#slabStale = true;
16538
17202
  }
16539
17203
  buildOne(job, batches) {
16540
17204
  const { asset } = job;
@@ -16599,71 +17263,6 @@ var CellPlacements = class {
16599
17263
  )
16600
17264
  ];
16601
17265
  }
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
17266
  /**
16668
17267
  * Record that one more gate distance exists, keeping the world's list ascending so
16669
17268
  * {@link crossesGate} can binary search it. A gate is never withdrawn: an asset whose ring left
@@ -16722,14 +17321,141 @@ var CellPlacements = class {
16722
17321
  * which the follow point has not yet reached anything that switches.
16723
17322
  */
16724
17323
  #collectStale(x, z) {
17324
+ const epoch = this.#host.residencyEpoch();
17325
+ if (this.#slabStale || this.#slabEpoch !== epoch) this.#packSlab(epoch);
17326
+ const eye = this.#host.eye();
17327
+ const query = new Float64Array(STALE_QUERY + this.#gates.length);
17328
+ query.set([
17329
+ x,
17330
+ this.followY(),
17331
+ z,
17332
+ eye.x,
17333
+ eye.y,
17334
+ eye.z,
17335
+ this.#host.gpuOn() ? 1 : 0,
17336
+ this.#gates.length
17337
+ ]);
17338
+ query.set(this.#gates, STALE_QUERY);
17339
+ const gates = this.#gateTable();
17340
+ const found = typeof this.#engine.__tnStaleEntries === "function" ? this.#engine.__tnStaleEntries(gates, query) : staleRows(this.#slab, gates, query);
17341
+ for (let at = 0; at < found.length; at += 3) {
17342
+ this.#stale.push({
17343
+ cell: this.#slabCells[found[at]],
17344
+ distance: found[at + 2],
17345
+ id: this.#assetIds[found[at + 1]]
17346
+ });
17347
+ this.#staleEntries += 1;
17348
+ }
17349
+ }
17350
+ /**
17351
+ * The resident cells' blocks end to end; only a changed cell builds its block again, and only the
17352
+ * changed blocks are sent: an unchanged one is a `[source, count]` run of the slab already held
17353
+ * (see `patchRows`).
17354
+ */
17355
+ #packSlab(epoch) {
17356
+ const plan = [];
17357
+ const changed = [];
17358
+ const cells = [];
17359
+ const placed = /* @__PURE__ */ new Map();
17360
+ let length7 = 0;
17361
+ let sent = 0;
16725
17362
  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);
17363
+ const rows = this.#rowsOf(cell);
17364
+ const held = this.#slabAt.get(cell);
17365
+ const source = held !== void 0 && held.rows === rows ? held.at : -1;
17366
+ extendPlan(plan, source, rows.length);
17367
+ if (source === -1) {
17368
+ changed.push(rows);
17369
+ sent += rows.length;
17370
+ }
17371
+ placed.set(cell, { at: length7, rows });
17372
+ cells.push(cell);
17373
+ length7 += rows.length;
16732
17374
  }
17375
+ const blocks = new Float64Array(sent);
17376
+ let at = 0;
17377
+ for (const block of changed) {
17378
+ blocks.set(block, at);
17379
+ at += block.length;
17380
+ }
17381
+ if (typeof this.#engine.__tnStaleEntries === "function") {
17382
+ if (typeof this.#engine.__tnStaleRows !== "function")
17383
+ throw new Error("TN_WORLD_STALE: the engine has __tnStaleEntries but no __tnStaleRows");
17384
+ this.#engine.__tnStaleRows(blocks, Float64Array.from(plan));
17385
+ } else this.#slab = patchRows(this.#slab, blocks, plan);
17386
+ this.#slabAt = placed;
17387
+ this.#slabCells = cells;
17388
+ this.#slabEpoch = epoch;
17389
+ this.#slabStale = false;
17390
+ }
17391
+ /** One cell's block: its rectangle and bracket, then each batch entry's filter state. */
17392
+ #rowsOf(cell) {
17393
+ const cached = this.#rows.get(cell);
17394
+ if (cached !== void 0 && cached.batches === cell.batches.length) return cached.rows;
17395
+ this.#grid ??= this.#host.extent();
17396
+ const { cellSize, minX, minZ } = this.#grid;
17397
+ const reach = this.#reachRanges.get(cell.cell);
17398
+ const rows = new Float64Array(STALE_HEADER + cell.batches.length * STALE_ENTRY);
17399
+ rows.set([
17400
+ minX + cell.x * cellSize,
17401
+ minZ + cell.z * cellSize,
17402
+ cellSize,
17403
+ cell.filterNear,
17404
+ cell.filterFar,
17405
+ reach === void 0 ? 0 : 1,
17406
+ cell.batches.length,
17407
+ 0
17408
+ ]);
17409
+ let at = STALE_HEADER;
17410
+ for (const entry of cell.batches) {
17411
+ const range = reach?.get(entry.asset);
17412
+ rows.set(
17413
+ [
17414
+ this.#assetSlot(entry.asset),
17415
+ entry.lastFilterX,
17416
+ entry.lastFilterY,
17417
+ entry.lastFilterZ,
17418
+ entry.lastLodX,
17419
+ entry.lastLodY,
17420
+ entry.lastLodZ,
17421
+ entry.threshold ?? Number.NaN,
17422
+ range?.min ?? Number.NaN,
17423
+ range?.max ?? Number.NaN,
17424
+ range?.minY ?? Number.NaN,
17425
+ range?.maxY ?? Number.NaN
17426
+ ],
17427
+ at
17428
+ );
17429
+ at += STALE_ENTRY;
17430
+ }
17431
+ this.#rows.set(cell, { rows, batches: cell.batches.length });
17432
+ return rows;
17433
+ }
17434
+ #assetSlot(id) {
17435
+ let slot = this.#assetIndex.get(id);
17436
+ if (slot === void 0) {
17437
+ slot = this.#assetIds.length;
17438
+ this.#assetIds.push(id);
17439
+ this.#assetIndex.set(id, slot);
17440
+ }
17441
+ return slot;
17442
+ }
17443
+ /** Each slab asset's gates, read live: `[count, [at, count]..., values]`, `at` -1 for a gone asset. */
17444
+ #gateTable() {
17445
+ const ids = this.#assetIds;
17446
+ let values = 0;
17447
+ for (const id of ids) values += this.#host.asset(id)?.gates.length ?? 0;
17448
+ const table = new Float64Array(1 + ids.length * 2 + values);
17449
+ table[0] = ids.length;
17450
+ let at = 1 + ids.length * 2;
17451
+ for (const [slot, id] of ids.entries()) {
17452
+ const gates = this.#host.asset(id)?.gates;
17453
+ table[1 + slot * 2] = gates === void 0 ? -1 : at;
17454
+ table[2 + slot * 2] = gates?.length ?? 0;
17455
+ if (gates !== void 0) table.set(gates, at);
17456
+ at += gates?.length ?? 0;
17457
+ }
17458
+ return table;
16733
17459
  }
16734
17460
  };
16735
17461
  var _readinessPosition = new Vector3();
@@ -17111,17 +17837,21 @@ var CellResidency = class {
17111
17837
  * resting near the gate does not flip the eye between the two.
17112
17838
  */
17113
17839
  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
17840
+ const root = this.#host.root();
17841
+ const follow = localPoint(
17842
+ this.#eyeFollow.set(
17843
+ this.#host.follow().position.x,
17844
+ this.#host.parts().placements.followY(),
17845
+ this.#host.follow().position.z
17846
+ ),
17847
+ root
17118
17848
  );
17119
17849
  const camera = this.#host.lodFrom() === "camera" ? this.#host.parts().chunks.camera : void 0;
17120
17850
  if (camera === void 0) {
17121
17851
  this.#eye.copy(follow);
17122
17852
  return;
17123
17853
  }
17124
- this.#eye.setFromMatrixPosition(camera.matrixWorld);
17854
+ localPoint(this.#eye.setFromMatrixPosition(camera.matrixWorld), root);
17125
17855
  if (this.#host.parts().placements.placementReach === void 0) this.#eye.y = 0;
17126
17856
  const inside = this.#host.parts().placements.firstGate;
17127
17857
  const offset = this.#eye.distanceTo(follow);
@@ -17159,10 +17889,10 @@ var CellResidency = class {
17159
17889
  let leadX = this.#velocityX * this.#host.prefetchSeconds();
17160
17890
  let leadZ = this.#velocityZ * this.#host.prefetchSeconds();
17161
17891
  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;
17892
+ const length7 = Math.hypot(leadX, leadZ);
17893
+ if (length7 > limit) {
17894
+ leadX *= limit / length7;
17895
+ leadZ *= limit / length7;
17166
17896
  }
17167
17897
  return { x: x + leadX, z: z + leadZ };
17168
17898
  }
@@ -17617,6 +18347,8 @@ var WorldCells = class _WorldCells extends Group {
17617
18347
  #adaptiveBias;
17618
18348
  #render;
17619
18349
  #onPublication;
18350
+ /** Publications told after the frame's records reach the engine, so a told batch is drawable. */
18351
+ #publications = [];
17620
18352
  /** The spawn and view gates, and the waiters they settle. */
17621
18353
  #readiness;
17622
18354
  #prewarm;
@@ -17654,7 +18386,8 @@ var WorldCells = class _WorldCells extends Group {
17654
18386
  casts: (level) => this.#render.casts(level),
17655
18387
  wideOwed: (asset, part) => this.#render.wideOwed(asset, part),
17656
18388
  followCluster: () => this.#render.followCluster(),
17657
- wideShape: (asset, level, part, fallback) => this.#render.wideShape(asset, level, part, fallback)
18389
+ wideShape: (asset, level, part, fallback) => this.#render.wideShape(asset, level, part, fallback),
18390
+ lodSurface: (asset, level, part, source) => this.#render.lodSurface(asset, level, part, source)
17658
18391
  });
17659
18392
  this.#init = { ...init };
17660
18393
  this.#budgets = {
@@ -17840,11 +18573,16 @@ var WorldCells = class _WorldCells extends Group {
17840
18573
  canonical: (id) => this.#canonical(id),
17841
18574
  renderer: () => this.#chunks.renderer,
17842
18575
  camera: () => this.#chunks.camera,
18576
+ // Live, not a snapshot: three refreshes `matrixWorld` before it renders, so a game that moves
18577
+ // the root reads its own frame from the next update on — the same answer `stepCellProxies`
18578
+ // is handed below.
18579
+ root: () => this.matrixWorld,
17843
18580
  now: () => this.#now(),
17844
18581
  stats: () => this.stats(),
17845
18582
  residentCells: () => this.#residency.resident.values(),
17846
18583
  runMax: (asset) => this.#runMax.get(asset),
17847
18584
  widenFilterRange: (cell, x, z) => this.#placementBuild.widenFilterRange(cell, x, z),
18585
+ cellBatchesChanged: (cell) => this.#placementBuild.cellBatchesChanged(cell),
17848
18586
  addUnchanged: () => {
17849
18587
  this.#unchanged += 1;
17850
18588
  },
@@ -18027,10 +18765,11 @@ var WorldCells = class _WorldCells extends Group {
18027
18765
  parts: () => parts,
18028
18766
  prefetchSeconds: () => this.#prefetchSeconds,
18029
18767
  published: (bounds) => {
18030
- this.#onPublication?.(bounds);
18768
+ if (this.#onPublication !== void 0) this.#publications.push(bounds.clone());
18031
18769
  },
18032
18770
  released: () => this.#released,
18033
- ring: () => this.#ring
18771
+ ring: () => this.#ring,
18772
+ root: () => this.matrixWorld
18034
18773
  });
18035
18774
  this.#readiness = new CellReadiness({
18036
18775
  asset: (id) => this.#models.asset(id),
@@ -18322,7 +19061,6 @@ var WorldCells = class _WorldCells extends Group {
18322
19061
  this.#render.seedGpuKeys();
18323
19062
  this.#render.announceGpu();
18324
19063
  }
18325
- advanceWriteEpoch();
18326
19064
  const x = this.#follow.position.x;
18327
19065
  const z = this.#follow.position.z;
18328
19066
  const budgetMs = this.#covered ? this.#coveredBudgetMs : this.#budgetMs;
@@ -18365,6 +19103,8 @@ var WorldCells = class _WorldCells extends Group {
18365
19103
  camera
18366
19104
  );
18367
19105
  this.#render.reportMainCull();
19106
+ batchRecords.flush();
19107
+ this.#tellPublications();
18368
19108
  this.#admission = {
18369
19109
  backlog: this.#residency.backlog(),
18370
19110
  deferred: this.#residency.queuedBuilds,
@@ -18372,6 +19112,10 @@ var WorldCells = class _WorldCells extends Group {
18372
19112
  };
18373
19113
  this.#readiness.settleWaiters();
18374
19114
  }
19115
+ /** The frame's publications, told once their records are in the engine's buffers. */
19116
+ #tellPublications() {
19117
+ for (const bounds of this.#publications.splice(0)) this.#onPublication?.(bounds);
19118
+ }
18375
19119
  process(renderer, camera, covered = false) {
18376
19120
  this.#covered = covered;
18377
19121
  try {
@@ -18554,4 +19298,4 @@ var WorldCells = class _WorldCells extends Group {
18554
19298
  }
18555
19299
  };
18556
19300
 
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 };
19301
+ 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 };