@threenative/core 0.3.12 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -1,7 +1,7 @@
1
- import { isEngineRenderHook, TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin, TN_DISCRETE_LOD, DiscreteLodPlugin, GEOMETRY_ASSET_KEY, DISCRETE_LOD_DEFAULT_HYSTERESIS, lodChainOf, registerModelLodController, conservativeViewDepth, biasedLodDistance, selectLodLevel } from './chunk-5O73CDMR.js';
2
- import { isNative } from './chunk-6KLNISRJ.js';
3
- import { debugRequested, countDebug, measureDebug } from './chunk-N5LRP4BR.js';
4
- import { AnimationAction, AnimationMixer, Matrix4, NumberKeyframeTrack, Skeleton, Vector3, BufferGeometry, Color, BufferAttribute, Matrix3, Mesh, InstancedBufferGeometry, InstancedMesh, Object3D, Quaternion, NoColorSpace, SRGBColorSpace, Sphere, RGBA_ASTC_4x4_Format, Frustum, Box3, InstancedBufferAttribute, Texture } from 'three';
1
+ import { isEngineRenderHook, markStreamedGeometry, upgradeStreamedGeometry, GEOMETRY_ASSET_KEY, TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin, TN_DISCRETE_LOD, DiscreteLodPlugin, isStreamedGeometry, DISCRETE_LOD_DEFAULT_HYSTERESIS, lodChainOf, registerModelLodController, selectLodFor, biasedLodDistance, selectLodLevel } from './chunk-QAMSM3Z5.js';
2
+ import { debugRequested, countDebug, readLaunchFlag, measureDebug } from './chunk-VQRPEOKY.js';
3
+ import { isNative } from './chunk-XDTZ4QMO.js';
4
+ import { AnimationAction, AnimationMixer, Matrix4, NumberKeyframeTrack, Skeleton, Vector3, BufferGeometry, Color, BufferAttribute, Matrix3, Mesh, InstancedBufferGeometry, Object3D, Texture, InstancedMesh, Quaternion, NoColorSpace, SRGBColorSpace, Sphere, RGBA_ASTC_4x4_Format, Frustum, Box3, InstancedBufferAttribute } from 'three';
5
5
  import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
6
6
  import { storage, attribute, instanceIndex, uint, Fn, mat4, If, normalLocal, vec4, normalGeometry, tangentLocal, tangentGeometry, positionPrevious, positionGeometry, pmremTexture, cos, sin, float } from 'three/tsl';
7
7
  import { StorageBufferAttribute, MeshBasicNodeMaterial, MeshLambertNodeMaterial, MeshMatcapNodeMaterial, MeshNormalNodeMaterial, MeshPhongNodeMaterial, MeshPhysicalNodeMaterial, MeshStandardNodeMaterial, MeshToonNodeMaterial } from 'three/webgpu';
@@ -55,7 +55,7 @@ function indexOf(part, deindex) {
55
55
  if (array instanceof Uint32Array) return array;
56
56
  return null;
57
57
  }
58
- function writePosition(channel, indices, elements, scratch3, values, at) {
58
+ function writePosition(channel, indices, elements, values, at) {
59
59
  const { array, count, offset, scale, stride } = channel;
60
60
  for (let vertex = 0; vertex < count; vertex += 1) {
61
61
  const base = (indices === null ? vertex : indices[vertex]) * stride + offset;
@@ -78,14 +78,6 @@ function writePosition(channel, indices, elements, scratch3, values, at) {
78
78
  pz = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
79
79
  }
80
80
  const out = at + vertex * 3;
81
- if (scratch3 !== null) {
82
- scratch3[0] = Math.round(px * scale);
83
- scratch3[1] = Math.round(py * scale);
84
- scratch3[2] = Math.round(pz * scale);
85
- px = Math.max(scratch3[0] / scale, -1);
86
- py = Math.max(scratch3[1] / scale, -1);
87
- pz = Math.max(scratch3[2] / scale, -1);
88
- }
89
81
  values[out] = px;
90
82
  values[out + 1] = py;
91
83
  values[out + 2] = pz;
@@ -165,8 +157,18 @@ function scratchOf(array) {
165
157
  if (array instanceof Uint32Array) return new Uint32Array(3);
166
158
  return null;
167
159
  }
160
+ function floatCopy(attribute2) {
161
+ const values = new Float32Array(attribute2.count * attribute2.itemSize);
162
+ for (let index = 0; index < attribute2.count; index += 1)
163
+ for (let component = 0; component < attribute2.itemSize; component += 1)
164
+ values[index * attribute2.itemSize + component] = attribute2.getComponent(index, component);
165
+ return new BufferAttribute(values, attribute2.itemSize);
166
+ }
168
167
  function flatten(part, paint, preserve, deindex) {
169
168
  const placed = part.geometry.clone();
169
+ const position = placed.getAttribute("position");
170
+ if (position !== void 0 && (!(position.array instanceof Float32Array) || position.normalized))
171
+ placed.setAttribute("position", floatCopy(position));
170
172
  const matrix2 = placementMatrix(part);
171
173
  if (matrix2 !== void 0) placed.applyMatrix4(matrix2);
172
174
  const flat = deindex && placed.index !== null ? placed.toNonIndexed() : placed;
@@ -181,17 +183,13 @@ function flatten(part, paint, preserve, deindex) {
181
183
  const attribute2 = flat.getAttribute(name);
182
184
  if (attribute2.array instanceof Float32Array && !attribute2.normalized && !("isInterleavedBufferAttribute" in attribute2))
183
185
  continue;
184
- const values = new Float32Array(attribute2.count * attribute2.itemSize);
185
- for (let index = 0; index < attribute2.count; index += 1)
186
- for (let component = 0; component < attribute2.itemSize; component += 1)
187
- values[index * attribute2.itemSize + component] = attribute2.getComponent(index, component);
188
- flat.setAttribute(name, new BufferAttribute(values, attribute2.itemSize));
189
- }
190
- const position = flat.getAttribute("position");
191
- if (!paint || position === void 0) return flat;
186
+ flat.setAttribute(name, floatCopy(attribute2));
187
+ }
188
+ const flatPosition = flat.getAttribute("position");
189
+ if (!paint || flatPosition === void 0) return flat;
192
190
  const tone = new Color(part.color);
193
- const painted = new Float32Array(position.count * 3);
194
- for (let vertex = 0; vertex < position.count; vertex += 1) {
191
+ const painted = new Float32Array(flatPosition.count * 3);
192
+ for (let vertex = 0; vertex < flatPosition.count; vertex += 1) {
195
193
  painted[vertex * 3] = tone.r;
196
194
  painted[vertex * 3 + 1] = tone.g;
197
195
  painted[vertex * 3 + 2] = tone.b;
@@ -284,7 +282,6 @@ function writeChannel(name, part, count, deindex, label, values, at) {
284
282
  indices,
285
283
  // quality-allow: Matrix4.elements is number[] in three's types and always 16 long.
286
284
  matrix2 === void 0 ? null : matrix2.elements,
287
- scratchOf(channel.array),
288
285
  values,
289
286
  at
290
287
  );
@@ -573,19 +570,19 @@ var SpanRecorder = class {
573
570
  this.#topLevelSeries = new Ring(capacity);
574
571
  }
575
572
  /** Opens a span. Returns false when the tree is already at `MAX_DEPTH` and the span is dropped. */
576
- begin(id, now2) {
573
+ begin(id, now3) {
577
574
  if (this.#depth >= MAX_DEPTH) {
578
575
  this.#overflowed += 1;
579
576
  return false;
580
577
  }
581
578
  this.#stackId[this.#depth] = id;
582
- this.#stackStart[this.#depth] = now2;
579
+ this.#stackStart[this.#depth] = now3;
583
580
  this.#depth += 1;
584
581
  this.#entries[id] = (this.#entries[id] ?? 0) + 1;
585
582
  return true;
586
583
  }
587
584
  /** Closes the span `begin` opened. Throws when it names a different span. */
588
- end(id, now2) {
585
+ end(id, now3) {
589
586
  if (this.#depth === 0)
590
587
  throw new Error(`Span ${SPAN_NAMES[id] ?? String(id)} ended with no span open.`);
591
588
  const depth = this.#depth - 1;
@@ -595,7 +592,7 @@ var SpanRecorder = class {
595
592
  `Span ${SPAN_NAMES[id] ?? String(id)} ended while ${SPAN_NAMES[open] ?? String(open)} was open.`
596
593
  );
597
594
  this.#depth = depth;
598
- const ms = now2 - (this.#stackStart[depth] ?? now2);
595
+ const ms = now3 - (this.#stackStart[depth] ?? now3);
599
596
  if (this.#debug)
600
597
  countDebug(`span.${SPAN_NAMES[id]}Ms`, ms, "renderer", `Spans.${SPAN_NAMES[id]}`, "ms");
601
598
  this.#own[id] = (this.#own[id] ?? 0) + ms;
@@ -760,16 +757,7 @@ function addSpan(id, ms) {
760
757
  active.add(id, ms);
761
758
  }
762
759
  function spansRequested() {
763
- if (debugRequested()) return true;
764
- const host = globalThis;
765
- const fromEnv = host.process?.env?.[SPANS_FLAG];
766
- if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
767
- return true;
768
- const query = globalThis.location?.search;
769
- if (typeof query === "string" && /[?&]tnFrameSpans=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query))
770
- return true;
771
- const fromGlobal = host.__tnFrameSpans;
772
- return fromGlobal === true || typeof fromGlobal === "string" && fromGlobal !== "" && fromGlobal !== "0" && fromGlobal !== "false";
760
+ return debugRequested() || readLaunchFlag({ environment: SPANS_FLAG, global: "__tnFrameSpans", query: "tnFrameSpans" });
773
761
  }
774
762
  function formatSpansWindow(window) {
775
763
  return `${SPANS_MARKER}:${JSON.stringify(window)}`;
@@ -867,6 +855,43 @@ function measureStartupOffscreenBytes(resolved, root, camera) {
867
855
  warn: offscreenBytes > visibleBytes
868
856
  };
869
857
  }
858
+ var ASSET_UNUSED_MARKER = "TN_ASSET_UNUSED";
859
+ var ASSET_UNUSED_AFTER_MS = 6e4;
860
+ var ASSET_UNUSED_FIX = "Nothing in the scene came from these models, which the reveal waited for. If nothing ever builds one, delete its load; if the game builds it later, ctx.assets.prefetch it after the reveal and load it then. A listed file may also be geometry the game merged into a new buffer, which drops its provenance: check that before deleting it.";
861
+ function measureUnusedModels(resolved, root, sinceRevealMs) {
862
+ const present = unbilled(() => {
863
+ const paths = /* @__PURE__ */ new Set();
864
+ root.traverse((object2) => {
865
+ const geometry = object2.geometry;
866
+ for (const path of [stampOf(object2.userData), stampOf(geometry?.userData)])
867
+ if (path !== void 0) paths.add(path);
868
+ });
869
+ return paths;
870
+ });
871
+ const files = [...resolved].filter(([path, asset]) => asset.kind === "model" && !present.has(path)).map(([path, asset]) => asset.bytes === void 0 ? { path } : { bytes: asset.bytes, path }).sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1));
872
+ if (files.length === 0) return void 0;
873
+ return {
874
+ bytes: files.reduce((sum, file) => sum + (file.bytes ?? 0), 0),
875
+ files,
876
+ fix: ASSET_UNUSED_FIX,
877
+ sinceRevealMs,
878
+ unsizedFiles: files.filter((file) => file.bytes === void 0).length
879
+ };
880
+ }
881
+ function reportUnusedModelsLater(awaited, root, gone) {
882
+ const timer = setTimeout(() => {
883
+ if (gone()) return;
884
+ try {
885
+ const unused = measureUnusedModels(awaited, root, ASSET_UNUSED_AFTER_MS);
886
+ if (unused !== void 0) console.warn(`${ASSET_UNUSED_MARKER}:${JSON.stringify(unused)}`);
887
+ } catch (error) {
888
+ console.warn(
889
+ `${ASSET_UNUSED_MARKER}_FAILED: ${error instanceof Error ? error.message : String(error)}`
890
+ );
891
+ }
892
+ }, ASSET_UNUSED_AFTER_MS);
893
+ return () => clearTimeout(timer);
894
+ }
870
895
 
871
896
  // src/auto-batch.ts
872
897
  var AUTO_BATCH_MARKER = "TN_AUTO_BATCH";
@@ -945,6 +970,41 @@ function stampMatches(object2, stamp) {
945
970
  for (let at = 0; at < SNAPSHOT_LENGTH; at += 1) if (scratch[at] !== stamp[at]) return false;
946
971
  return true;
947
972
  }
973
+ var ownLayers = /* @__PURE__ */ new WeakMap();
974
+ var drawingWorld = 0;
975
+ function drawWorld(draw) {
976
+ drawingWorld += 1;
977
+ try {
978
+ return draw();
979
+ } finally {
980
+ drawingWorld -= 1;
981
+ }
982
+ }
983
+ function setBatchHidden(mesh, hidden) {
984
+ const engine = mesh;
985
+ if ("__tnBatchHidden" in engine) {
986
+ engine.__tnBatchHidden = hidden;
987
+ return;
988
+ }
989
+ if (!hidden) {
990
+ const own2 = ownLayers.get(mesh);
991
+ if (own2 !== void 0) mesh.layers = own2;
992
+ ownLayers.delete(mesh);
993
+ return;
994
+ }
995
+ if (ownLayers.has(mesh)) return;
996
+ const own = mesh.layers;
997
+ ownLayers.set(mesh, own);
998
+ mesh.layers = Object.create(Object.getPrototypeOf(own), {
999
+ mask: {
1000
+ get: () => own.mask,
1001
+ set: (mask) => {
1002
+ own.mask = mask;
1003
+ }
1004
+ },
1005
+ test: { value: (layers) => drawingWorld === 0 && own.test(layers) }
1006
+ });
1007
+ }
948
1008
  function isMesh(object2) {
949
1009
  return object2.isMesh === true;
950
1010
  }
@@ -968,7 +1028,7 @@ function bakeable(geometry) {
968
1028
  return true;
969
1029
  }
970
1030
  function mergeable(mesh) {
971
- return plainDraw(mesh) && bakeable(mesh.geometry) && mesh.matrixWorld.determinant() > 0;
1031
+ return plainDraw(mesh) && bakeable(mesh.geometry) && !isStreamedGeometry(mesh.geometry) && mesh.matrixWorld.determinant() > 0;
972
1032
  }
973
1033
  function flagKey(mesh) {
974
1034
  const { geometry } = mesh;
@@ -1010,6 +1070,8 @@ var AutoBatch = class {
1010
1070
  #excluded = /* @__PURE__ */ new WeakSet();
1011
1071
  #records = [];
1012
1072
  #ancestors = /* @__PURE__ */ new Map();
1073
+ /** The ancestors in the order the engine's guard watches them, so its indices name them. */
1074
+ #watchedAncestors = [];
1013
1075
  #watched = /* @__PURE__ */ new Map();
1014
1076
  #state = "idle";
1015
1077
  #known = Number.NaN;
@@ -1036,12 +1098,24 @@ var AutoBatch = class {
1036
1098
  #levelOne = /* @__PURE__ */ new Set();
1037
1099
  /** Children added to or removed from the scene since the last frame, to start or stop counting. */
1038
1100
  #arrived = [];
1101
+ /**
1102
+ * The subtrees a scan walks: what was added at the top two levels since the last finished scan, plus what an
1103
+ * earlier scan could not merge yet (a hidden subtree, a mesh that moved while watched, a mesh with no partner).
1104
+ * A scan costs what arrived and what still waits, never the scene: ten thrown objects a second re-walked the
1105
+ * stress lab's 5,000 nodes after every add and every remove, 4.1 ms of a 9.8 ms frame.
1106
+ * ponytail: a mesh with no partner is walked by every scan; index those by material when a scene holds thousands.
1107
+ */
1108
+ #pending = /* @__PURE__ */ new Set();
1109
+ /** What the scan in progress met and left for the next one: hidden subtrees. */
1110
+ #later = /* @__PURE__ */ new Set();
1039
1111
  #onTopChild = (event) => {
1040
1112
  this.#shapeChanges += 1;
1041
1113
  this.#arrived.push(event.child);
1114
+ if (event.type === "childadded") this.#pending.add(event.child);
1042
1115
  };
1043
- #onChild = () => {
1116
+ #onChild = (event) => {
1044
1117
  this.#shapeChanges += 1;
1118
+ if (event.type === "childadded") this.#pending.add(event.child);
1045
1119
  };
1046
1120
  constructor(scene, options = {}) {
1047
1121
  this.#scene = scene;
@@ -1055,6 +1129,7 @@ var AutoBatch = class {
1055
1129
  scene.addEventListener("childadded", this.#onTopChild);
1056
1130
  scene.addEventListener("childremoved", this.#onTopChild);
1057
1131
  this.#arrived = [...scene.children];
1132
+ this.#pending = new Set(this.#arrived);
1058
1133
  }
1059
1134
  get census() {
1060
1135
  return {
@@ -1101,6 +1176,7 @@ var AutoBatch = class {
1101
1176
  this.#state = "watching";
1102
1177
  this.#frames = 0;
1103
1178
  if (this.#watched.size < 2) {
1179
+ this.#finish(this.#watched);
1104
1180
  this.#known = shape;
1105
1181
  this.#state = "idle";
1106
1182
  }
@@ -1117,6 +1193,7 @@ var AutoBatch = class {
1117
1193
  if (!this.#enabled) return;
1118
1194
  const meshes = this.#snapshot();
1119
1195
  if (meshes.size >= 2) this.#merge([...meshes.keys()]);
1196
+ this.#finish(meshes);
1120
1197
  this.#watchEngine();
1121
1198
  this.#known = this.#shape();
1122
1199
  this.#state = "idle";
@@ -1125,11 +1202,12 @@ var AutoBatch = class {
1125
1202
  reset() {
1126
1203
  for (const record of this.#records) if (!record.out) this.#giveBack(record);
1127
1204
  this.#records = [];
1128
- this.#watchEngine();
1129
1205
  this.#ancestors.clear();
1206
+ this.#watchEngine();
1130
1207
  this.#watched.clear();
1131
1208
  this.#state = "idle";
1132
1209
  this.#known = Number.NaN;
1210
+ this.#pending = new Set(this.#scene.children);
1133
1211
  }
1134
1212
  /**
1135
1213
  * Changes when something is added to or removed from the scene's top two levels. three's own graph
@@ -1153,47 +1231,80 @@ var AutoBatch = class {
1153
1231
  return this.#shapeChanges;
1154
1232
  }
1155
1233
  /**
1156
- * Eligible meshes with the world matrix they were drawn at. Runs only while the scene settles, so
1157
- * its reads are no game's steady cost and the bridge census leaves them out.
1234
+ * Eligible meshes under the pending subtrees, with the world matrix they were drawn at. Runs only while
1235
+ * the scene settles, so its reads are no game's steady cost and the bridge census leaves them out.
1158
1236
  */
1159
1237
  #snapshot() {
1160
1238
  return unbilled(() => {
1161
- this.#scene.updateMatrixWorld(true);
1162
1239
  const found = /* @__PURE__ */ new Map();
1163
1240
  this.#optedOut = 0;
1164
1241
  this.#held = 0;
1242
+ this.#later = /* @__PURE__ */ new Set();
1165
1243
  const held = heldObjects(this.#entities);
1166
- this.#walk(this.#scene, false, held, (mesh) => {
1244
+ const visit = (mesh) => {
1167
1245
  found.set(mesh, Float64Array.from(mesh.matrixWorld.elements));
1168
- });
1246
+ };
1247
+ for (const root of [...this.#pending]) {
1248
+ const off = this.#hangs(root, held);
1249
+ if (off === "gone") this.#pending.delete(root);
1250
+ else if (off === "wait") this.#later.add(root);
1251
+ else {
1252
+ root.updateWorldMatrix(true, true);
1253
+ this.#visit(root, off, held, visit);
1254
+ }
1255
+ }
1169
1256
  return found;
1170
1257
  });
1171
1258
  }
1172
- #walk(object2, off, held, visit) {
1173
- for (const child of object2.children) {
1174
- if (!child.visible || this.#excluded.has(child) || child.isLOD === true)
1175
- continue;
1176
- if (held.has(child)) {
1177
- const parts = countMeshes(child);
1178
- if (parts <= HELD_SUBTREE_MAX_MESHES) {
1179
- this.#held += parts;
1180
- continue;
1181
- }
1182
- }
1183
- const skip = off || child.userData.batch === "off";
1184
- if (isMesh(child) && mergeable(child)) {
1185
- if (skip) this.#optedOut += 1;
1186
- else visit(child);
1259
+ /**
1260
+ * How a pending subtree hangs under the scene. `gone`: it left the scene, or a pending ancestor walks it.
1261
+ * `wait`: an ancestor is hidden, held or an LOD, which the game can change. Else whether an ancestor opted it out.
1262
+ */
1263
+ #hangs(root, held) {
1264
+ let off = false;
1265
+ let wait = false;
1266
+ for (let node = root.parent; node !== this.#scene; node = node.parent) {
1267
+ if (node === null || this.#excluded.has(node) || this.#pending.has(node)) return "gone";
1268
+ wait ||= !node.visible || node.isLOD === true || held.has(node);
1269
+ off ||= node.userData.batch === "off";
1270
+ }
1271
+ return wait ? "wait" : off;
1272
+ }
1273
+ /**
1274
+ * Ends a scan: the next one walks what this one left (`#later`) and each mesh it found that no merge took.
1275
+ * A mesh that moved can come to rest, and a mesh with no partner can get one.
1276
+ */
1277
+ #finish(found) {
1278
+ this.#pending = this.#later;
1279
+ this.#later = /* @__PURE__ */ new Set();
1280
+ for (const mesh of found.keys()) if (!sourceGroups.has(mesh)) this.#pending.add(mesh);
1281
+ }
1282
+ #visit(child, off, held, visit) {
1283
+ if (!child.visible) {
1284
+ this.#later.add(child);
1285
+ return;
1286
+ }
1287
+ if (this.#excluded.has(child) || child.isLOD === true) return;
1288
+ if (held.has(child)) {
1289
+ const parts = countMeshes(child);
1290
+ if (parts <= HELD_SUBTREE_MAX_MESHES) {
1291
+ this.#held += parts;
1292
+ return;
1187
1293
  }
1188
- this.#walk(child, skip, held, visit);
1189
1294
  }
1295
+ const skip = off || child.userData.batch === "off";
1296
+ if (isMesh(child) && !sourceGroups.has(child) && mergeable(child)) {
1297
+ if (skip) this.#optedOut += 1;
1298
+ else visit(child);
1299
+ }
1300
+ for (const part of child.children) this.#visit(part, skip, held, visit);
1190
1301
  }
1191
1302
  #settle() {
1192
1303
  const before = this.#watched;
1193
1304
  const stable = /* @__PURE__ */ new Map();
1194
- const now2 = this.#snapshot();
1305
+ const now3 = this.#snapshot();
1195
1306
  let moved = 0;
1196
- for (const [mesh, matrix2] of now2) {
1307
+ for (const [mesh, matrix2] of now3) {
1197
1308
  const earlier = before.get(mesh);
1198
1309
  if (earlier !== void 0 && matrix2.every((value, at) => value === earlier[at]))
1199
1310
  stable.set(mesh, matrix2);
@@ -1202,6 +1313,7 @@ var AutoBatch = class {
1202
1313
  this.#unsettled = moved;
1203
1314
  this.#watched = /* @__PURE__ */ new Map();
1204
1315
  this.#merge([...stable.keys()]);
1316
+ this.#finish(now3);
1205
1317
  this.#watchEngine();
1206
1318
  this.#known = this.#shape();
1207
1319
  this.#state = "idle";
@@ -1275,7 +1387,7 @@ var AutoBatch = class {
1275
1387
  out: false
1276
1388
  };
1277
1389
  vertexStart += vertexCount;
1278
- mesh.visible = false;
1390
+ setBatchHidden(mesh, true);
1279
1391
  writeStamp(mesh, record.stamp);
1280
1392
  group.sources.push(record);
1281
1393
  sourceGroups.set(mesh, group);
@@ -1317,15 +1429,32 @@ var AutoBatch = class {
1317
1429
  /** Every frame, because there are few ancestors and one moved parent changes thousands of sources. */
1318
1430
  #checkAncestors() {
1319
1431
  let given = 0;
1432
+ const engine = this.#engine;
1433
+ if (engine?.__tnGuardCheckAncestors !== void 0) {
1434
+ const changed = engine.__tnGuardCheckAncestors();
1435
+ for (let at = 0; at < changed.length; at += 1) {
1436
+ const node = this.#watchedAncestors[changed[at]];
1437
+ if (node !== void 0) given += this.#giveBackUnder(node);
1438
+ }
1439
+ return given;
1440
+ }
1320
1441
  for (const [node, entry] of this.#ancestors) {
1321
1442
  if (node.parent === entry.parent && stampMatches(node, entry.stamp)) continue;
1322
- this.#excluded.add(node);
1323
- this.#ancestors.delete(node);
1324
- for (const record of entry.records) {
1325
- if (record.out) continue;
1326
- this.#giveBack(record);
1327
- given += 1;
1328
- }
1443
+ given += this.#giveBackUnder(node);
1444
+ }
1445
+ return given;
1446
+ }
1447
+ /** An ancestor moved: it never merges again, and every source under it goes back to the game. */
1448
+ #giveBackUnder(node) {
1449
+ const entry = this.#ancestors.get(node);
1450
+ if (entry === void 0) return 0;
1451
+ let given = 0;
1452
+ this.#excluded.add(node);
1453
+ this.#ancestors.delete(node);
1454
+ for (const record of entry.records) {
1455
+ if (record.out) continue;
1456
+ this.#giveBack(record);
1457
+ given += 1;
1329
1458
  }
1330
1459
  return given;
1331
1460
  }
@@ -1334,7 +1463,12 @@ var AutoBatch = class {
1334
1463
  * and each give-back, so no game code runs between the state merged and the state watched.
1335
1464
  */
1336
1465
  #watchEngine() {
1337
- this.#engine?.__tnGuardWatch(this.#records.map((record) => record.mesh));
1466
+ if (this.#engine === void 0) return;
1467
+ this.#watchedAncestors = [...this.#ancestors.keys()];
1468
+ this.#engine.__tnGuardWatch(
1469
+ this.#records.map((record) => record.mesh),
1470
+ this.#watchedAncestors
1471
+ );
1338
1472
  }
1339
1473
  /** A slice of the sources bounded by {@link GUARD_BUDGET_MS}, or all of them under `everyFrame`. */
1340
1474
  #checkSources(started) {
@@ -1392,7 +1526,7 @@ var AutoBatch = class {
1392
1526
  this.#excluded.add(record.mesh);
1393
1527
  this.#restored += 1;
1394
1528
  this.#meshes -= 1;
1395
- record.mesh.visible = true;
1529
+ setBatchHidden(record.mesh, false);
1396
1530
  const { group } = record;
1397
1531
  group.live -= 1;
1398
1532
  if (group.live > 0) this.#collapse(record);
@@ -3724,12 +3858,38 @@ var RATE_HOLD_RIGS = 32;
3724
3858
  var RATE_MEASURE_FRAMES = 4;
3725
3859
  var animationRateRootRefs = /* @__PURE__ */ new WeakMap();
3726
3860
  var animationRateCarriers = /* @__PURE__ */ new Set();
3861
+ function untrackAnimationRate(root, state) {
3862
+ if (animationRateStates.get(root) !== state) return;
3863
+ animationRateStates.delete(root);
3864
+ const id = engineRateIds.get(root);
3865
+ if (id === void 0) return;
3866
+ setEngineRateState(id, void 0);
3867
+ const engineRig = root;
3868
+ if (typeof engineRig.__trackAnimationRate === "function") engineRig.__trackAnimationRate(-1);
3869
+ }
3727
3870
  function observeAnimationRates(carrier, sources) {
3728
3871
  if (!animationRateSources.has(carrier)) animationRateCarriers.add(new WeakRef(carrier));
3729
3872
  animationRateSources.set(carrier, sources);
3730
3873
  }
3874
+ var engineRateIds = /* @__PURE__ */ new WeakMap();
3875
+ var engineRateStates = [];
3876
+ var engineRateRigs = 0;
3877
+ function setEngineRateState(id, state) {
3878
+ engineRateRigs += (state === void 0 ? 0 : 1) - (engineRateStates[id] === void 0 ? 0 : 1);
3879
+ engineRateStates[id] = state;
3880
+ }
3731
3881
  function trackAnimationRate(root, state) {
3732
3882
  animationRateStates.set(root, state);
3883
+ const engineRig = root;
3884
+ if (typeof engineRig.__trackAnimationRate === "function") {
3885
+ let id = engineRateIds.get(root);
3886
+ if (id === void 0) {
3887
+ id = engineRateStates.length;
3888
+ engineRateIds.set(root, id);
3889
+ }
3890
+ setEngineRateState(id, state);
3891
+ engineRig.__trackAnimationRate(id);
3892
+ }
3733
3893
  let ref = animationRateRootRefs.get(root);
3734
3894
  if (ref === void 0) {
3735
3895
  ref = new WeakRef(root);
@@ -3747,10 +3907,14 @@ function hierarchyRevision(object2) {
3747
3907
  const revision = object2.__hierarchyRevision;
3748
3908
  return typeof revision === "number" ? revision : void 0;
3749
3909
  }
3750
- function countEngineCost2(name) {
3910
+ function countEngineCost2(name, count = 1) {
3751
3911
  const host = globalThis;
3752
3912
  host.__tnEngineCost ??= {};
3753
- host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + 1;
3913
+ host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + count;
3914
+ }
3915
+ function engineBandRoot(root) {
3916
+ const candidate = root;
3917
+ return typeof candidate?.__bandAnimation === "function" ? candidate : void 0;
3754
3918
  }
3755
3919
  function engineCullRoot(root) {
3756
3920
  const candidate = root;
@@ -3904,6 +4068,10 @@ var RenderCameraCull = class {
3904
4068
  this.#animationFrame += 1;
3905
4069
  this.#animationPrepared = true;
3906
4070
  this.#prepareCamera(camera, viewportHeight);
4071
+ if (this.#bandOnEngine(root, camera)) {
4072
+ countEngineCost2("cullRigRebuilds", 0);
4073
+ return;
4074
+ }
3907
4075
  if (!this.#prepareAnimated()) return;
3908
4076
  const rootShown = this.#isVisibleInWorld(root);
3909
4077
  const holds = rootShown && !this.#nestedRigs && animationRateCarriers.size === 0 && animationRateRoots.size >= RATE_HOLD_RIGS;
@@ -3912,8 +4080,8 @@ var RenderCameraCull = class {
3912
4080
  const rig = ref.deref();
3913
4081
  if (rig === void 0 || !this.#reaches(rig, root)) continue;
3914
4082
  turn += 1;
3915
- if (!holds || turn % RATE_MEASURE_FRAMES === 0 || !this.#holdRate(rig))
3916
- this.#visitRig(rig, rootShown);
4083
+ if (holds && turn % RATE_MEASURE_FRAMES !== 0 && this.#holdRate(rig)) continue;
4084
+ this.#visitRig(rig, rootShown);
3917
4085
  }
3918
4086
  for (const ref of animationRateCarriers) {
3919
4087
  const carrier = ref.deref();
@@ -3928,6 +4096,40 @@ var RenderCameraCull = class {
3928
4096
  if (observes && this.#reaches(carrier, root)) carrier.traverseVisible(this.#animationVisitor);
3929
4097
  }
3930
4098
  }
4099
+ /**
4100
+ * On the engine, with no stand-in observing a rig, the whole pass is one call (PRD-878): the engine keeps the
4101
+ * rigs, checks which reach the root, holds a crowd's rates and bands the rest. False sends the frame to the
4102
+ * walk below: plain three, a stand-in, or a rig inside a rig.
4103
+ */
4104
+ #bandOnEngine(root, camera) {
4105
+ const engine = animationRateCarriers.size === 0 ? engineBandRoot(root) : void 0;
4106
+ if (engine !== void 0 && engineRateRigs === 0) return true;
4107
+ const pairs = engine?.__bandAnimation(
4108
+ camera,
4109
+ this.#cameraResolved,
4110
+ this.#scale,
4111
+ this.#animationFrame
4112
+ );
4113
+ if (pairs === void 0) return false;
4114
+ this.#takeBands(pairs);
4115
+ return true;
4116
+ }
4117
+ /** The engine's [handle, rate] pairs, written to each state as the JS walk writes it; -1 drops a freed rig. */
4118
+ #takeBands(pairs) {
4119
+ for (let index = 0; index + 1 < pairs.length; index += 2) {
4120
+ const id = pairs[index];
4121
+ const rate = pairs[index + 1];
4122
+ if (rate < 0) {
4123
+ setEngineRateState(id, void 0);
4124
+ continue;
4125
+ }
4126
+ const state = engineRateStates[id];
4127
+ if (state === void 0) continue;
4128
+ state.rate = rate;
4129
+ state.source = this;
4130
+ state.frame = this.#animationFrame;
4131
+ }
4132
+ }
3931
4133
  /** Carries a rig's rate into this frame; false when last frame did not measure or hold it, as for a rig just shown. */
3932
4134
  #holdRate(rig) {
3933
4135
  const state = animationRateStates.get(rig);
@@ -4185,12 +4387,12 @@ var RenderCameraCull = class {
4185
4387
  union[3] = z;
4186
4388
  union[4] = radius;
4187
4389
  } else {
4188
- const grown = (distance + ur + radius) / 2;
4189
- const shift = (grown - ur) / distance;
4390
+ const grown2 = (distance + ur + radius) / 2;
4391
+ const shift = (grown2 - ur) / distance;
4190
4392
  union[1] = ux + (x - ux) * shift;
4191
4393
  union[2] = uy + (y - uy) * shift;
4192
4394
  union[3] = uz + (z - uz) * shift;
4193
- union[4] = grown;
4395
+ union[4] = grown2;
4194
4396
  }
4195
4397
  }
4196
4398
  }
@@ -4788,6 +4990,150 @@ function createAssetCache(options = {}) {
4788
4990
  }
4789
4991
  };
4790
4992
  }
4993
+
4994
+ // src/asset-memo.ts
4995
+ var KINDS = {
4996
+ Float32Array,
4997
+ Float64Array,
4998
+ Int16Array,
4999
+ Int32Array,
5000
+ Int8Array,
5001
+ Uint16Array,
5002
+ Uint32Array,
5003
+ Uint8Array,
5004
+ Uint8ClampedArray
5005
+ };
5006
+ var BUILD_ID_GLOBAL = "__TN_BUILD_ID__";
5007
+ var MEMO_CACHE = "threenative-memo";
5008
+ var MEMO_ORIGIN = "https://memo.threenative.invalid/";
5009
+ var MAGIC = 1330466388;
5010
+ function invalid(detail) {
5011
+ return new Error(`TN_ASSET_MEMO_INVALID: ${detail}`);
5012
+ }
5013
+ function kindOf(value) {
5014
+ for (const kind of Object.keys(KINDS)) if (value instanceof KINDS[kind]) return kind;
5015
+ return void 0;
5016
+ }
5017
+ function encodeMemo(value) {
5018
+ const entries = Object.entries(value).map(([name, array]) => {
5019
+ const kind = kindOf(array);
5020
+ if (kind === void 0) throw invalid(`"${name}" is not a typed array.`);
5021
+ return { array, kind, name };
5022
+ });
5023
+ const align = (n) => Math.ceil(n / 8) * 8;
5024
+ const header = new TextEncoder().encode(
5025
+ JSON.stringify(entries.map(({ array, kind, name }) => ({ kind, length: array.length, name })))
5026
+ );
5027
+ let offset = align(8 + header.byteLength);
5028
+ const placed = entries.map((entry) => {
5029
+ const at = offset;
5030
+ offset = align(at + entry.array.byteLength);
5031
+ return { ...entry, at };
5032
+ });
5033
+ const buffer = new ArrayBuffer(offset);
5034
+ const view = new DataView(buffer);
5035
+ view.setUint32(0, MAGIC, true);
5036
+ view.setUint32(4, header.byteLength, true);
5037
+ new Uint8Array(buffer, 8, header.byteLength).set(header);
5038
+ for (const { array, at } of placed)
5039
+ new Uint8Array(buffer, at, array.byteLength).set(
5040
+ new Uint8Array(array.buffer, array.byteOffset, array.byteLength)
5041
+ );
5042
+ return buffer;
5043
+ }
5044
+ function decodeMemo(buffer) {
5045
+ const view = new DataView(buffer);
5046
+ if (buffer.byteLength < 8 || view.getUint32(0, true) !== MAGIC)
5047
+ throw invalid("stored entry is not a memo.");
5048
+ const headerBytes = view.getUint32(4, true);
5049
+ if (8 + headerBytes > buffer.byteLength) throw invalid("stored entry is truncated.");
5050
+ const header = JSON.parse(
5051
+ new TextDecoder().decode(new Uint8Array(buffer, 8, headerBytes))
5052
+ );
5053
+ if (!Array.isArray(header)) throw invalid("stored entry has no array list.");
5054
+ const result = {};
5055
+ let offset = Math.ceil((8 + headerBytes) / 8) * 8;
5056
+ for (const entry of header) {
5057
+ const kind = entry.kind;
5058
+ const Ctor = KINDS[kind];
5059
+ if (Ctor === void 0 || typeof entry.name !== "string" || !Number.isInteger(entry.length))
5060
+ throw invalid("stored entry has a malformed array.");
5061
+ const length = entry.length;
5062
+ const bytes = length * Ctor.BYTES_PER_ELEMENT;
5063
+ if (offset + bytes > buffer.byteLength) throw invalid("stored entry is truncated.");
5064
+ result[entry.name] = new Ctor(buffer, offset, length);
5065
+ offset = Math.ceil((offset + bytes) / 8) * 8;
5066
+ }
5067
+ return result;
5068
+ }
5069
+ function report(fields) {
5070
+ console.info(`TN_ASSET_MEMO:${JSON.stringify(fields)}`);
5071
+ }
5072
+ function now() {
5073
+ return globalThis.performance?.now() ?? Date.now();
5074
+ }
5075
+ function createAssetMemo(namespace) {
5076
+ const storage2 = cacheStorage();
5077
+ const id = globalThis[BUILD_ID_GLOBAL];
5078
+ const buildId = typeof id === "string" && id !== "" ? id : void 0;
5079
+ const reason = storage2 === void 0 ? isNative() ? "native host has no Cache API: generated content rebuilds each run" : "cache API unavailable: generated content rebuilds each run" : buildId === void 0 ? "no build id (dev server or a page the web build did not write): generated content rebuilds each run" : void 0;
5080
+ const prefix = buildId === void 0 ? "" : `${MEMO_ORIGIN}${encodeURIComponent(buildId)}/`;
5081
+ const name = `${MEMO_CACHE}-${manifestFingerprint([{ url: namespace }]).slice(0, 8)}`;
5082
+ let opened;
5083
+ const open = () => {
5084
+ opened ??= (async () => {
5085
+ const cache2 = await storage2?.open(name);
5086
+ if (cache2 === void 0) return void 0;
5087
+ for (const request of await cache2.keys())
5088
+ if (!request.url.startsWith(prefix)) await cache2.delete(request.url);
5089
+ return cache2;
5090
+ })().catch(() => void 0);
5091
+ return opened;
5092
+ };
5093
+ const checked = (key, value) => {
5094
+ if (typeof value !== "object" || value === null)
5095
+ throw invalid(`build for "${key}" returned no object.`);
5096
+ for (const [field, array] of Object.entries(value))
5097
+ if (kindOf(array) === void 0)
5098
+ throw invalid(`build for "${key}" returned "${field}", not a typed array.`);
5099
+ return value;
5100
+ };
5101
+ return async (key, build) => {
5102
+ if (typeof key !== "string" || key === "") throw invalid("key must be a non-empty string.");
5103
+ const started = now();
5104
+ if (reason !== void 0) {
5105
+ const value2 = checked(key, await build());
5106
+ report({ key, hit: false, ms: Math.round(now() - started), reason });
5107
+ return value2;
5108
+ }
5109
+ const url = `${prefix}${encodeURIComponent(key)}`;
5110
+ const cache2 = await open();
5111
+ if (cache2 !== void 0) {
5112
+ try {
5113
+ const stored = await cache2.match(url);
5114
+ if (stored !== void 0) {
5115
+ const buffer = await stored.arrayBuffer();
5116
+ const value2 = decodeMemo(buffer);
5117
+ report({ bytes: buffer.byteLength, hit: true, key, ms: Math.round(now() - started) });
5118
+ return value2;
5119
+ }
5120
+ } catch {
5121
+ await cache2.delete(url).catch(() => void 0);
5122
+ }
5123
+ }
5124
+ const value = checked(key, await build());
5125
+ const encoded = encodeMemo(value);
5126
+ const builtMs = Math.round(now() - started);
5127
+ if (cache2 === void 0) {
5128
+ report({ hit: false, key, ms: builtMs, reason: "cache storage refused to open" });
5129
+ return value;
5130
+ }
5131
+ void cache2.put(url, new Response(encoded)).then(() => report({ bytes: encoded.byteLength, hit: false, key, ms: builtMs, stored: true })).catch(
5132
+ (error) => report({ hit: false, key, ms: builtMs, stored: false, reason: String(error) })
5133
+ );
5134
+ return value;
5135
+ };
5136
+ }
4791
5137
  var INSTANCED_LOD_MAX_PIXEL_ERROR = 4;
4792
5138
  function spatialPartitions(mesh) {
4793
5139
  const limit = Math.ceil(Math.sqrt(mesh.count));
@@ -4940,12 +5286,7 @@ function attachInstancedLod(mesh, options) {
4940
5286
  mesh.getMatrixAt(index, matrix2);
4941
5287
  world.multiplyMatrices(mesh.matrixWorld, matrix2);
4942
5288
  sphere.copy(local).applyMatrix4(world);
4943
- const view = conservativeViewDepth(
4944
- camera,
4945
- sphere.center,
4946
- sphere.radius,
4947
- camera.near ?? 0
4948
- );
5289
+ const view = selectLodFor(camera, sphere, camera.near ?? 0);
4949
5290
  let level = 0;
4950
5291
  if (options.lods !== void 0) {
4951
5292
  const distance = biasedLodDistance(cameraPosition.distanceTo(sphere.center));
@@ -4962,7 +5303,7 @@ function attachInstancedLod(mesh, options) {
4962
5303
  {
4963
5304
  camera,
4964
5305
  viewportHeight,
4965
- depth: biasedLodDistance(view.depth),
5306
+ depth: view.biased,
4966
5307
  degenerate: view.degenerate
4967
5308
  }
4968
5309
  ]
@@ -5011,7 +5352,334 @@ function attachInstancedLod(mesh, options) {
5011
5352
  mesh.addEventListener("dispose", () => controller.release());
5012
5353
  }
5013
5354
 
5355
+ // src/streamed-textures.ts
5356
+ var TEXTURE_SLOTS = [
5357
+ "map",
5358
+ "normalMap",
5359
+ "roughnessMap",
5360
+ "metalnessMap",
5361
+ "aoMap",
5362
+ "emissiveMap",
5363
+ "alphaMap",
5364
+ "bumpMap",
5365
+ "lightMap",
5366
+ "displacementMap",
5367
+ "clearcoatMap",
5368
+ "clearcoatNormalMap",
5369
+ "clearcoatRoughnessMap",
5370
+ "sheenColorMap",
5371
+ "sheenRoughnessMap",
5372
+ "transmissionMap",
5373
+ "thicknessMap",
5374
+ "iridescenceMap",
5375
+ "specularColorMap",
5376
+ "specularIntensityMap"
5377
+ ];
5378
+ var CARRIED = [
5379
+ "anisotropy",
5380
+ "wrapS",
5381
+ "wrapT",
5382
+ "magFilter",
5383
+ "minFilter",
5384
+ "colorSpace",
5385
+ "channel",
5386
+ "rotation",
5387
+ "matrixAutoUpdate",
5388
+ "userData"
5389
+ ];
5390
+ var CARRIED_VECTORS = ["offset", "repeat", "center", "matrix"];
5391
+ function carry(from, next) {
5392
+ for (const name of CARRIED) if (name in from) next[name] = from[name];
5393
+ for (const name of CARRIED_VECTORS)
5394
+ next[name]?.copy?.(from[name]);
5395
+ }
5396
+ var materialsOf = (mesh) => [].concat(mesh?.material).filter(Boolean);
5397
+ function streamedTextureUpgrade(coarse) {
5398
+ const loaded = coarse.map(
5399
+ (mesh) => materialsOf(mesh).map((material) => TEXTURE_SLOTS.map((name) => material[name]))
5400
+ );
5401
+ return (full, swap) => {
5402
+ const whole = /* @__PURE__ */ new Map();
5403
+ const unused = /* @__PURE__ */ new Set();
5404
+ full.forEach(
5405
+ (mesh, index) => materialsOf(mesh).forEach(
5406
+ (material, slot) => TEXTURE_SLOTS.forEach((name, at) => {
5407
+ const next = material[name];
5408
+ const resident = loaded[index]?.[slot]?.[at];
5409
+ if (!next || next === resident) return;
5410
+ if (swap && resident) whole.set(resident, next);
5411
+ else unused.add(next);
5412
+ })
5413
+ )
5414
+ );
5415
+ const replaced = /* @__PURE__ */ new Set();
5416
+ const taken = /* @__PURE__ */ new Set();
5417
+ let swapped = 0;
5418
+ for (const mesh of whole.size > 0 ? coarse : [])
5419
+ for (const material of materialsOf(mesh)) {
5420
+ let changed = false;
5421
+ for (const name of TEXTURE_SLOTS) {
5422
+ const resident = material[name];
5423
+ const next = resident ? whole.get(resident) : void 0;
5424
+ if (resident === null || resident === void 0 || next === void 0) continue;
5425
+ if (!taken.has(next))
5426
+ carry(resident, next);
5427
+ material[name] = next;
5428
+ replaced.add(resident);
5429
+ taken.add(next);
5430
+ swapped += 1;
5431
+ changed = true;
5432
+ }
5433
+ if (changed) material.needsUpdate = true;
5434
+ }
5435
+ for (const next of whole.values()) unused.add(next);
5436
+ for (const texture of replaced) texture.dispose?.();
5437
+ for (const texture of unused) if (!taken.has(texture)) texture.dispose?.();
5438
+ return swapped;
5439
+ };
5440
+ }
5441
+
5442
+ // src/texture-streaming.ts
5443
+ var KTX2_IDENTIFIER = [
5444
+ 171,
5445
+ 75,
5446
+ 84,
5447
+ 88,
5448
+ 32,
5449
+ 50,
5450
+ 48,
5451
+ 187,
5452
+ 13,
5453
+ 10,
5454
+ 26,
5455
+ 10
5456
+ ];
5457
+ var KTX2_INDEX_BYTES = 80;
5458
+ var KTX2_LEVEL_ENTRY_BYTES = 24;
5459
+ var MAX_SAFE_U64 = BigInt(Number.MAX_SAFE_INTEGER);
5460
+ function headerFailure(reason) {
5461
+ return new Error(`TN_KTX2_HEADER: ${reason}`);
5462
+ }
5463
+ function levelEntryCount(levelCount) {
5464
+ return Number.isFinite(levelCount) ? Math.max(1, Math.trunc(levelCount)) : 1;
5465
+ }
5466
+ function ktx2HeaderBytes(levelCount) {
5467
+ return KTX2_INDEX_BYTES + KTX2_LEVEL_ENTRY_BYTES * levelEntryCount(levelCount);
5468
+ }
5469
+ function readU64(view, offset, field) {
5470
+ const value = view.getBigUint64(offset, true);
5471
+ if (value > MAX_SAFE_U64) {
5472
+ throw headerFailure(`${field} is ${value.toString()}, above Number.MAX_SAFE_INTEGER`);
5473
+ }
5474
+ return Number(value);
5475
+ }
5476
+ function parseKtx2LevelIndex(bytes) {
5477
+ if (bytes.byteLength < KTX2_IDENTIFIER.length) {
5478
+ throw headerFailure(
5479
+ `buffer is ${String(bytes.byteLength)} bytes, too short for the identifier: ${String(KTX2_IDENTIFIER.length)}`
5480
+ );
5481
+ }
5482
+ for (let i = 0; i < KTX2_IDENTIFIER.length; i += 1) {
5483
+ if (bytes[i] !== KTX2_IDENTIFIER[i]) {
5484
+ throw headerFailure(`byte ${String(i)} is not the KTX 2.0 identifier`);
5485
+ }
5486
+ }
5487
+ if (bytes.byteLength < KTX2_INDEX_BYTES) {
5488
+ throw headerFailure(
5489
+ `buffer is ${String(bytes.byteLength)} bytes, too short for the 80-byte header and index`
5490
+ );
5491
+ }
5492
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
5493
+ const levelCount = levelEntryCount(view.getUint32(40, true));
5494
+ const required = ktx2HeaderBytes(levelCount);
5495
+ if (bytes.byteLength < required) {
5496
+ throw headerFailure(
5497
+ `buffer is ${String(bytes.byteLength)} bytes, ${String(levelCount)} level(s) need ${String(required)}`
5498
+ );
5499
+ }
5500
+ const levels = [];
5501
+ for (let level = 0; level < levelCount; level += 1) {
5502
+ const at = KTX2_INDEX_BYTES + level * KTX2_LEVEL_ENTRY_BYTES;
5503
+ levels.push({
5504
+ byteOffset: readU64(view, at, `level ${String(level)} byteOffset`),
5505
+ byteLength: readU64(view, at + 8, `level ${String(level)} byteLength`),
5506
+ uncompressedByteLength: readU64(
5507
+ view,
5508
+ at + 16,
5509
+ `level ${String(level)} uncompressedByteLength`
5510
+ )
5511
+ });
5512
+ }
5513
+ return {
5514
+ vkFormat: view.getUint32(12, true),
5515
+ typeSize: view.getUint32(16, true),
5516
+ pixelWidth: view.getUint32(20, true),
5517
+ pixelHeight: view.getUint32(24, true),
5518
+ pixelDepth: view.getUint32(28, true),
5519
+ layerCount: view.getUint32(32, true),
5520
+ faceCount: view.getUint32(36, true),
5521
+ levelCount,
5522
+ supercompressionScheme: view.getUint32(44, true),
5523
+ sgdByteOffset: readU64(view, 64, "sgdByteOffset"),
5524
+ sgdByteLength: readU64(view, 72, "sgdByteLength"),
5525
+ levels
5526
+ };
5527
+ }
5528
+ var KTX2_PROBE_BYTES = 64 * 1024;
5529
+ var KTX2_TAIL_MAX_PX = 64;
5530
+ var KTX2_LEVEL_ALIGN = 48;
5531
+ var BASISLZ = 1;
5532
+ var BASISLZ_SGD_HEADER_BYTES = 20;
5533
+ var BASISLZ_IMAGE_DESC_BYTES = 20;
5534
+ function alignUp(value, alignment) {
5535
+ return Math.ceil(value / alignment) * alignment;
5536
+ }
5537
+ function trimBasisLzGlobalData(sgd, index, first) {
5538
+ const images = (level) => Math.max(1, index.layerCount) * index.faceCount * Math.max(1, index.pixelDepth >> level);
5539
+ let dropped = 0;
5540
+ for (let level = 0; level < first; level += 1) dropped += images(level);
5541
+ let total = dropped;
5542
+ for (let level = first; level < index.levelCount; level += 1) total += images(level);
5543
+ const descs = BASISLZ_SGD_HEADER_BYTES;
5544
+ const rest = descs + total * BASISLZ_IMAGE_DESC_BYTES;
5545
+ if (sgd.byteLength < rest)
5546
+ throw headerFailure(
5547
+ `BasisLZ global data is ${String(sgd.byteLength)} bytes, ${String(rest)} needed`
5548
+ );
5549
+ const out = new Uint8Array(sgd.byteLength - dropped * BASISLZ_IMAGE_DESC_BYTES);
5550
+ out.set(sgd.subarray(0, descs));
5551
+ out.set(sgd.subarray(descs + dropped * BASISLZ_IMAGE_DESC_BYTES), descs);
5552
+ return out;
5553
+ }
5554
+ function trimmedKtx2(src, index, first) {
5555
+ const view = new DataView(src.buffer, src.byteOffset, src.byteLength);
5556
+ const slice = (offset, length) => {
5557
+ if (offset + length > src.byteLength)
5558
+ throw new Error(
5559
+ `TN_KTX2_HEADER: a section at ${String(offset)}+${String(length)} lies past the ${String(src.byteLength)} bytes read`
5560
+ );
5561
+ return src.subarray(offset, offset + length);
5562
+ };
5563
+ const dfd = slice(view.getUint32(48, true), view.getUint32(52, true));
5564
+ const kvd = slice(view.getUint32(56, true), view.getUint32(60, true));
5565
+ let sgd = slice(index.sgdByteOffset, index.sgdByteLength);
5566
+ if (index.supercompressionScheme === BASISLZ && sgd.byteLength > 0)
5567
+ sgd = trimBasisLzGlobalData(sgd, index, first);
5568
+ const kept = index.levels.slice(first);
5569
+ const dfdAt = ktx2HeaderBytes(kept.length);
5570
+ const kvdAt = dfdAt + dfd.byteLength;
5571
+ const sgdAt = alignUp(kvdAt + kvd.byteLength, 8);
5572
+ const placed = [];
5573
+ let end = sgdAt + sgd.byteLength;
5574
+ for (let i = kept.length - 1; i >= 0; i -= 1) {
5575
+ const at = alignUp(end, KTX2_LEVEL_ALIGN);
5576
+ placed[i] = at;
5577
+ end = at + (kept[i]?.byteLength ?? 0);
5578
+ }
5579
+ const out = new Uint8Array(end);
5580
+ const write = new DataView(out.buffer);
5581
+ out.set(src.subarray(0, 48));
5582
+ write.setUint32(20, Math.max(1, index.pixelWidth >> first), true);
5583
+ if (index.pixelHeight > 0) write.setUint32(24, Math.max(1, index.pixelHeight >> first), true);
5584
+ if (index.pixelDepth > 0) write.setUint32(28, Math.max(1, index.pixelDepth >> first), true);
5585
+ write.setUint32(40, kept.length, true);
5586
+ write.setUint32(48, dfd.byteLength > 0 ? dfdAt : 0, true);
5587
+ write.setUint32(52, dfd.byteLength, true);
5588
+ write.setUint32(56, kvd.byteLength > 0 ? kvdAt : 0, true);
5589
+ write.setUint32(60, kvd.byteLength, true);
5590
+ write.setBigUint64(64, BigInt(sgd.byteLength > 0 ? sgdAt : 0), true);
5591
+ write.setBigUint64(72, BigInt(sgd.byteLength), true);
5592
+ out.set(dfd, dfdAt);
5593
+ out.set(kvd, kvdAt);
5594
+ out.set(sgd, sgdAt);
5595
+ kept.forEach((level, i) => {
5596
+ const at = KTX2_INDEX_BYTES + i * KTX2_LEVEL_ENTRY_BYTES;
5597
+ write.setBigUint64(at, BigInt(placed[i] ?? 0), true);
5598
+ write.setBigUint64(at + 8, BigInt(level.byteLength), true);
5599
+ write.setBigUint64(at + 16, BigInt(level.uncompressedByteLength), true);
5600
+ out.set(slice(level.byteOffset, level.byteLength), placed[i]);
5601
+ });
5602
+ return out;
5603
+ }
5604
+ async function openKtx2Stream(url, fetchRange = (target, init) => fetch(target, init)) {
5605
+ let have = new Uint8Array(0);
5606
+ let ranged = true;
5607
+ let bytesRead = 0;
5608
+ const readTo = async (end) => {
5609
+ if (!ranged || end <= have.byteLength) return;
5610
+ const start = have.byteLength;
5611
+ const response = await fetchRange(url, {
5612
+ headers: { range: `bytes=${String(start)}-${String(end - 1)}` }
5613
+ });
5614
+ if (!response.ok)
5615
+ throw new Error(`TN_KTX2_FETCH: '${url}' answered ${String(response.status)}`);
5616
+ const body = new Uint8Array(await response.arrayBuffer());
5617
+ bytesRead += body.byteLength;
5618
+ if (response.status !== 206) {
5619
+ have = body;
5620
+ ranged = false;
5621
+ return;
5622
+ }
5623
+ const from = /^bytes (\d+)-/u.exec(response.headers.get("content-range") ?? "")?.[1];
5624
+ if (from !== void 0 && Number(from) !== start)
5625
+ throw new Error(
5626
+ `TN_KTX2_FETCH: '${url}' answered bytes from ${from}, ${String(start)} asked`
5627
+ );
5628
+ const next = new Uint8Array(start + body.byteLength);
5629
+ next.set(have);
5630
+ next.set(body, start);
5631
+ have = next;
5632
+ };
5633
+ await readTo(KTX2_PROBE_BYTES);
5634
+ const index = parseKtx2LevelIndex(have);
5635
+ const { levels } = index;
5636
+ const last = levels.length - 1;
5637
+ const levelEnd = (level) => (levels[level]?.byteOffset ?? 0) + (levels[level]?.byteLength ?? 0);
5638
+ const ordered = levels.every(
5639
+ (level, i) => i === last || level.byteOffset > (levels[i + 1]?.byteOffset ?? 0)
5640
+ );
5641
+ if (!ordered) await readTo(Math.max(...levels.map((_, i) => levelEnd(i))));
5642
+ let tail = 1;
5643
+ while (tail < levels.length && Math.max(index.pixelWidth, index.pixelHeight) >> levels.length - 1 - tail <= KTX2_TAIL_MAX_PX)
5644
+ tail += 1;
5645
+ await readTo(levelEnd(levels.length - tail));
5646
+ const resident = () => {
5647
+ if (!ranged) return levels.length;
5648
+ let count = 0;
5649
+ while (count < levels.length && levelEnd(last - count) <= have.byteLength) count += 1;
5650
+ return count;
5651
+ };
5652
+ const file = () => {
5653
+ const count = resident();
5654
+ if (count === 0)
5655
+ throw new Error(
5656
+ `TN_KTX2_FETCH: '${url}' sent ${String(have.byteLength)} bytes, short of its smallest mip level`
5657
+ );
5658
+ return count === levels.length && !ranged ? have : trimmedKtx2(have, index, levels.length - count);
5659
+ };
5660
+ return {
5661
+ index,
5662
+ get residentLevels() {
5663
+ return resident();
5664
+ },
5665
+ get ranged() {
5666
+ return ranged;
5667
+ },
5668
+ get bytesRead() {
5669
+ return bytesRead;
5670
+ },
5671
+ file,
5672
+ want: async (count) => {
5673
+ const target = Math.min(levels.length, Math.max(1, Math.trunc(count)));
5674
+ if (target <= resident()) return void 0;
5675
+ await readTo(levelEnd(levels.length - target));
5676
+ return file();
5677
+ }
5678
+ };
5679
+ }
5680
+
5014
5681
  // src/assets.ts
5682
+ var ASSET_LATE_MARKER = "TN_ASSET_LATE";
5015
5683
  function configuredTexture(texture, options) {
5016
5684
  const copy = texture.clone();
5017
5685
  copy.colorSpace = options.data === true ? NoColorSpace : SRGBColorSpace;
@@ -5316,6 +5984,13 @@ function widenNormalizedScalars(root) {
5316
5984
  }
5317
5985
  });
5318
5986
  }
5987
+ function meshesOf(value) {
5988
+ const meshes = [];
5989
+ modelRoot(value)?.traverse((object2) => {
5990
+ if (object2.isMesh === true) meshes.push(object2);
5991
+ });
5992
+ return meshes;
5993
+ }
5319
5994
  function modelRoot(value) {
5320
5995
  if (typeof value !== "object" || value === null) return void 0;
5321
5996
  const scene = value.scene;
@@ -5384,6 +6059,47 @@ function reconcileMirroredClips(root, clips) {
5384
6059
  function createAssetLoader(options = {}) {
5385
6060
  const debug = debugRequested();
5386
6061
  const basePath = options.basePath ?? "";
6062
+ const streamMeshes = options.streamMeshes !== false;
6063
+ if (!streamMeshes)
6064
+ console.info(
6065
+ "TN_ASSETS_STREAM_MESHES_OFF: assets.streamMeshes is false; every model loads whole."
6066
+ );
6067
+ const streamTextures = options.streamTextures !== false;
6068
+ if (!streamTextures)
6069
+ console.info(
6070
+ "TN_ASSETS_STREAM_TEXTURES_OFF: assets.streamTextures is false; every model texture loads whole."
6071
+ );
6072
+ const pool = { files: 0, fullBytes: 0, ranged: 0, residentBytes: 0, upgraded: 0 };
6073
+ let poolTimer;
6074
+ const reportPool = () => {
6075
+ clearTimeout(poolTimer);
6076
+ poolTimer = setTimeout(() => {
6077
+ poolTimer = void 0;
6078
+ console.info(
6079
+ `TN_STREAMING_POOL ${JSON.stringify({ ...pool, deferredBytes: pool.fullBytes - pool.residentBytes })}`
6080
+ );
6081
+ }, 2e3);
6082
+ };
6083
+ const residentImage = async (url) => {
6084
+ if (!/\.ktx2(?:$|\?)/iu.test(url)) return void 0;
6085
+ const stream = await openKtx2Stream(url);
6086
+ if (!stream.ranged) return { file: stream.file(), partial: false };
6087
+ const file = stream.file();
6088
+ pool.files += 1;
6089
+ pool.ranged += 1;
6090
+ pool.residentBytes += file.byteLength;
6091
+ pool.fullBytes += stream.index.levels.reduce((sum, level) => sum + level.byteLength, 0);
6092
+ reportPool();
6093
+ return { file, partial: true };
6094
+ };
6095
+ const imageSourceFor = (resident) => async (imageUrl) => {
6096
+ const kept = resident.whole.get(imageUrl);
6097
+ if (kept !== void 0 || resident.keptOnly === true) return kept;
6098
+ const served = await residentImage(imageUrl);
6099
+ if (served?.partial === true) resident.used = true;
6100
+ else if (served !== void 0) resident.whole.set(imageUrl, served.file);
6101
+ return served?.file;
6102
+ };
5387
6103
  const sourcePath = (options.sourcePath ?? "assets").replace(/^\/+|\/+$/gu, "");
5388
6104
  const manifestUrl = resolvePath(basePath, options.manifest ?? "assets.manifest.json");
5389
6105
  const assetCache = createAssetCache({
@@ -5553,6 +6269,13 @@ function createAssetLoader(options = {}) {
5553
6269
  let settled = 0;
5554
6270
  let settledBytes = 0;
5555
6271
  const pending = /* @__PURE__ */ new Set();
6272
+ const wholeOf = /* @__PURE__ */ new WeakMap();
6273
+ const wholeWhen = (wait, loading) => wait ? loading.then(async (value) => {
6274
+ if (typeof value === "object" && value !== null) await wholeOf.get(value);
6275
+ return value;
6276
+ }) : loading;
6277
+ const warmed = /* @__PURE__ */ new Set();
6278
+ let revealedAtMs;
5556
6279
  const bytesOf = async (path) => {
5557
6280
  if (isExternalAssetPath(path)) return 0;
5558
6281
  const manifest = await manifestOnce();
@@ -5560,6 +6283,15 @@ function createAssetLoader(options = {}) {
5560
6283
  const bytes = isRecord(entry) ? entry.bytes : void 0;
5561
6284
  return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
5562
6285
  };
6286
+ const coarseOf = async (path) => {
6287
+ if (!streamMeshes || isExternalAssetPath(path)) return void 0;
6288
+ const entry = (await manifestOnce())?.entries[path];
6289
+ const coarse = isRecord(entry) && Array.isArray(entry.streamedLods) ? entry.streamedLods[0] : void 0;
6290
+ if (!isRecord(coarse) || typeof coarse.output !== "string" || typeof coarse.bytes !== "number")
6291
+ return void 0;
6292
+ return { bytes: coarse.bytes, url: resolvePath(basePath, coarse.output) };
6293
+ };
6294
+ const weightOf = async (kind, path) => (kind === "model" && !warmed.has(path) ? (await coarseOf(path))?.bytes : void 0) ?? bytesOf(path);
5563
6295
  const auxiliaryOf = async (path) => {
5564
6296
  if (isExternalAssetPath(path)) return [];
5565
6297
  const entry = (await manifestOnce())?.entries[path];
@@ -5577,7 +6309,7 @@ function createAssetLoader(options = {}) {
5577
6309
  }
5578
6310
  return files;
5579
6311
  };
5580
- const cached = (kind, path, load, priority = "now") => {
6312
+ const cached = (kind, path, load, priority = "now", whole = false) => {
5581
6313
  const key = `${kind}:${path}`;
5582
6314
  const existing = cache2.get(key);
5583
6315
  if (existing !== void 0) {
@@ -5585,12 +6317,12 @@ function createAssetLoader(options = {}) {
5585
6317
  existing.priority = priority;
5586
6318
  if (existing.url !== void 0) assetCache.promote(existing.url, priority);
5587
6319
  }
5588
- return existing.promise;
6320
+ return wholeWhen(whole, existing.promise);
5589
6321
  }
5590
6322
  requested += 1;
5591
6323
  let weight = 0;
5592
6324
  let auxiliary = [];
5593
- const weighed = Promise.all([bytesOf(path), auxiliaryOf(path)]).then(
6325
+ const weighed = Promise.all([weightOf(kind, path), auxiliaryOf(path)]).then(
5594
6326
  ([bytes, files]) => {
5595
6327
  weight = bytes;
5596
6328
  auxiliary = files;
@@ -5598,6 +6330,19 @@ function createAssetLoader(options = {}) {
5598
6330
  },
5599
6331
  () => void 0
5600
6332
  );
6333
+ if (revealedAtMs !== void 0 && !warmed.has(path)) {
6334
+ const lateAt = revealedAtMs;
6335
+ void weighed.then(
6336
+ () => console.log(
6337
+ `${ASSET_LATE_MARKER}:${JSON.stringify({
6338
+ bytes: weight,
6339
+ kind,
6340
+ ms: Math.round(performanceNow() - lateAt),
6341
+ path
6342
+ })}`
6343
+ )
6344
+ );
6345
+ }
5601
6346
  const traceStart = assetTraceEnabled() ? performanceNow() : 0;
5602
6347
  const entry = {
5603
6348
  disposed: false,
@@ -5650,7 +6395,7 @@ function createAssetLoader(options = {}) {
5650
6395
  };
5651
6396
  entry.promise.then(note, note);
5652
6397
  cache2.set(key, entry);
5653
- return entry.promise;
6398
+ return wholeWhen(whole, entry.promise);
5654
6399
  };
5655
6400
  const releaseEntry = (entry) => {
5656
6401
  entry.released = true;
@@ -5662,6 +6407,7 @@ function createAssetLoader(options = {}) {
5662
6407
  );
5663
6408
  };
5664
6409
  const prefetchPaths = async (paths) => {
6410
+ for (const path of paths) warmed.add(path);
5665
6411
  if (!assetCache.enabled) {
5666
6412
  return {
5667
6413
  requested: paths.length,
@@ -5752,100 +6498,160 @@ function createAssetLoader(options = {}) {
5752
6498
  await attachCompiledLightmaps(path, value2);
5753
6499
  return value2;
5754
6500
  }
5755
- const expected = await bytesOf(path);
5756
- const data = await fetchModelBytes(
5757
- url,
5758
- assetCache,
5759
- expected > 0 ? expected : void 0,
5760
- priority
5761
- );
5762
- const extensions = declaredExtensions(data);
5763
- const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
5764
- const loader = new GLTFLoader();
5765
- const astcExtension = "EXT_texture_astc";
5766
- const hasBasis = extensions.has("KHR_texture_basisu");
5767
- const hasAstc = extensions.has(astcExtension);
5768
- let shared;
5769
- if (compressedTextures !== void 0 && (hasBasis || hasAstc)) {
6501
+ const parse = async (fileUrl, expected, at, resident) => {
6502
+ const data = await fetchModelBytes(
6503
+ fileUrl,
6504
+ assetCache,
6505
+ expected > 0 ? expected : void 0,
6506
+ at
6507
+ );
6508
+ const extensions = declaredExtensions(data);
6509
+ const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
6510
+ const loader = new GLTFLoader();
6511
+ if (resident !== void 0 && "imageSource" in loader)
6512
+ loader.imageSource = imageSourceFor(resident);
6513
+ const astcExtension = "EXT_texture_astc";
6514
+ const hasBasis = extensions.has("KHR_texture_basisu") && loader.failClosed !== true;
6515
+ const hasAstc = extensions.has(astcExtension);
6516
+ let shared;
6517
+ if (compressedTextures !== void 0 && (hasBasis || hasAstc)) {
6518
+ try {
6519
+ shared = await compressedTextures.loader;
6520
+ } catch (error) {
6521
+ if (hasBasis || !(error instanceof Error) || !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:"))
6522
+ throw error;
6523
+ }
6524
+ if (shared !== void 0) {
6525
+ loader.setKTX2Loader(
6526
+ shared
6527
+ );
6528
+ }
6529
+ }
6530
+ if (hasAstc) {
6531
+ const astcLoader = shared;
6532
+ const astcSupported = hasAstcSupport(astcLoader);
6533
+ loader.register((parser) => {
6534
+ if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
6535
+ throw new Error(
6536
+ "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support."
6537
+ );
6538
+ }
6539
+ return {
6540
+ name: astcExtension,
6541
+ loadTexture(textureIndex) {
6542
+ const extension = parser.json.textures[textureIndex].extensions?.[astcExtension];
6543
+ if (extension === void 0 || !astcSupported || astcLoader === void 0)
6544
+ return null;
6545
+ return parser.loadTextureImage(
6546
+ textureIndex,
6547
+ extension.source,
6548
+ astcLoader
6549
+ );
6550
+ }
6551
+ };
6552
+ });
6553
+ }
6554
+ if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
6555
+ const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');
6556
+ loader.setMeshoptDecoder(MeshoptDecoder);
6557
+ }
6558
+ if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
6559
+ if (loader.failClosed === true)
6560
+ console.info(
6561
+ `TN_VIRTUAL_GEOMETRY_SKIPPED ${path}: this engine's glTF loader hosts no cluster plugin; the source mesh draws`
6562
+ );
6563
+ else loader.register((parser) => new VirtualGeometryPlugin(parser));
6564
+ }
6565
+ const discreteLod = extensions.has(TN_DISCRETE_LOD) ? new DiscreteLodPlugin({
6566
+ failClosed: loader.failClosed === true
6567
+ }) : void 0;
6568
+ if (discreteLod !== void 0) {
6569
+ const plugin = discreteLod;
6570
+ loader.register((parser) => {
6571
+ plugin.setParser(parser);
6572
+ return plugin;
6573
+ });
6574
+ }
6575
+ if (extensions.has(DRACO_EXTENSION)) {
6576
+ const { DRACOLoader } = await import('three/addons/loaders/DRACOLoader.js');
6577
+ const dracoLoader = new DRACOLoader();
6578
+ dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
6579
+ loader.setDRACOLoader(dracoLoader);
6580
+ }
6581
+ const value2 = await new Promise(
6582
+ (resolve, reject) => loader.parse(data, resourcePathOf(fileUrl), resolve, reject)
6583
+ );
6584
+ const root = modelRoot(value2);
6585
+ if (root !== void 0) widenQuantizedPositions(root);
6586
+ if (root !== void 0) widenNormalizedScalars(root);
6587
+ if (root !== void 0 && discreteLod !== void 0)
6588
+ discreteLod.attach(root, await discretePolicy(path), attachInstancedLod);
6589
+ const clips = modelClips(value2);
6590
+ if (root !== void 0 && clips.length > 0 && reconcileMirroredClips(root, clips)) {
6591
+ const cause = "its clips are mirrored against its own bind pose, and the loader un-mirrored them so the game plays forwards. The file is wrong, not the game: re-import it with a current converter and this stops.";
6592
+ console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} \u2014 ${cause}`);
6593
+ }
6594
+ return value2;
6595
+ };
6596
+ const coarse = warmed.has(path) ? void 0 : await coarseOf(path);
6597
+ let value;
6598
+ const residentState = streamTextures ? { used: false, whole: /* @__PURE__ */ new Map() } : void 0;
6599
+ if (coarse !== void 0) {
5770
6600
  try {
5771
- shared = await compressedTextures.loader;
6601
+ value = await parse(coarse.url, coarse.bytes, priority, residentState);
5772
6602
  } catch (error) {
5773
- if (hasBasis || !(error instanceof Error) || !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:"))
5774
- throw error;
5775
- }
5776
- if (shared !== void 0) {
5777
- loader.setKTX2Loader(shared);
6603
+ console.warn(
6604
+ `TN_ASSETS_STREAM_FAILED ${path}: the coarse model did not load, so the whole file does; ${error instanceof Error ? error.message : String(error)}`
6605
+ );
5778
6606
  }
5779
6607
  }
5780
- if (hasAstc) {
5781
- const astcLoader = shared;
5782
- const astcSupported = hasAstcSupport(astcLoader);
5783
- loader.register((parser) => {
5784
- if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
6608
+ if (value === void 0) value = await parse(url, await bytesOf(path), priority);
6609
+ else {
6610
+ const coarseMeshes = meshesOf(value);
6611
+ const coarseGeometries = coarseMeshes.map((mesh) => mesh.geometry);
6612
+ const upgradeTextures = streamedTextureUpgrade(coarseMeshes);
6613
+ for (const geometry of coarseGeometries) markStreamedGeometry(geometry);
6614
+ const gone = () => loaderDisposed || coarseGeometries.some((geometry) => disposed.geometries.has(geometry));
6615
+ const landed = bytesOf(path).then(
6616
+ (bytes) => gone() ? void 0 : parse(
6617
+ url,
6618
+ bytes,
6619
+ "soon",
6620
+ residentState && { keptOnly: true, used: false, whole: residentState.whole }
6621
+ )
6622
+ ).then((full) => {
6623
+ residentState?.whole.clear();
6624
+ if (full === void 0) return;
6625
+ if (gone()) {
6626
+ disposeModel(full, disposed);
6627
+ return;
6628
+ }
6629
+ const fullMeshes = meshesOf(full);
6630
+ if (fullMeshes.length !== coarseMeshes.length)
5785
6631
  throw new Error(
5786
- "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support."
6632
+ `the full model has ${String(fullMeshes.length)} mesh(es), the coarse ${String(coarseMeshes.length)}`
5787
6633
  );
5788
- }
5789
- return {
5790
- name: astcExtension,
5791
- loadTexture(textureIndex) {
5792
- const extension = parser.json.textures[textureIndex].extensions?.[astcExtension];
5793
- if (extension === void 0 || !astcSupported || astcLoader === void 0)
5794
- return null;
5795
- return parser.loadTextureImage(
5796
- textureIndex,
5797
- extension.source,
5798
- astcLoader
5799
- );
5800
- }
5801
- };
5802
- });
5803
- }
5804
- if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
5805
- const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');
5806
- loader.setMeshoptDecoder(MeshoptDecoder);
5807
- }
5808
- if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
5809
- if (loader.failClosed === true)
5810
- console.info(
5811
- `TN_VIRTUAL_GEOMETRY_SKIPPED ${path}: this engine's glTF loader hosts no cluster plugin; the source mesh draws`
6634
+ coarseGeometries.forEach(
6635
+ (geometry, index) => upgradeStreamedGeometry(geometry, fullMeshes[index].geometry)
5812
6636
  );
5813
- else loader.register((parser) => new VirtualGeometryPlugin(parser));
5814
- }
5815
- const discreteLod = extensions.has(TN_DISCRETE_LOD) ? new DiscreteLodPlugin({
5816
- failClosed: loader.failClosed === true
5817
- }) : void 0;
5818
- if (discreteLod !== void 0) {
5819
- const plugin = discreteLod;
5820
- loader.register((parser) => {
5821
- plugin.setParser(parser);
5822
- return plugin;
5823
- });
5824
- }
5825
- if (extensions.has(DRACO_EXTENSION)) {
5826
- const { DRACOLoader } = await import('three/addons/loaders/DRACOLoader.js');
5827
- const dracoLoader = new DRACOLoader();
5828
- dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
5829
- loader.setDRACOLoader(dracoLoader);
5830
- }
5831
- const value = await new Promise(
5832
- (resolve, reject) => loader.parse(data, resourcePathOf(url), resolve, reject)
5833
- );
5834
- const root = modelRoot(value);
5835
- if (root !== void 0) widenQuantizedPositions(root);
5836
- if (root !== void 0) widenNormalizedScalars(root);
5837
- if (root !== void 0 && discreteLod !== void 0)
5838
- discreteLod.attach(root, await discretePolicy(path), attachInstancedLod);
5839
- const clips = modelClips(value);
5840
- if (root !== void 0 && clips.length > 0 && reconcileMirroredClips(root, clips)) {
5841
- const cause = "its clips are mirrored against its own bind pose, and the loader un-mirrored them so the game plays forwards. The file is wrong, not the game: re-import it with a current converter and this stops.";
5842
- console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} \u2014 ${cause}`);
6637
+ const swapped = upgradeTextures(fullMeshes, residentState?.used === true);
6638
+ if (residentState?.used === true) {
6639
+ pool.upgraded += swapped;
6640
+ reportPool();
6641
+ }
6642
+ }).catch(
6643
+ (error) => console.warn(
6644
+ `TN_ASSETS_STREAM_FAILED ${path}: the coarse model stays; ${error instanceof Error ? error.message : String(error)}`
6645
+ )
6646
+ );
6647
+ if (typeof value === "object" && value !== null) wholeOf.set(value, landed);
5843
6648
  }
5844
6649
  stampAssetProvenance(value, path);
5845
6650
  await attachCompiledLightmaps(path, value);
5846
6651
  return value;
5847
6652
  },
5848
- request?.priority ?? "now"
6653
+ request?.priority ?? "now",
6654
+ request?.whole === true
5849
6655
  ),
5850
6656
  get cache() {
5851
6657
  return { ...assetCache.report, clear: () => assetCache.clear() };
@@ -5853,9 +6659,11 @@ function createAssetLoader(options = {}) {
5853
6659
  get progress() {
5854
6660
  return { pending: [...pending], requested, requestedBytes, settled, settledBytes };
5855
6661
  },
6662
+ memo: createAssetMemo(canonicalUrl(manifestUrl)),
5856
6663
  prefetch: prefetchPaths,
5857
6664
  resolve: async (path) => (await resolveCandidates(path)).urls,
5858
6665
  startBackgroundFill: () => {
6666
+ revealedAtMs ??= performanceNow();
5859
6667
  void manifestOnce().catch(() => void 0);
5860
6668
  return assetCache.startFill();
5861
6669
  },
@@ -5976,16 +6784,40 @@ function isSize(bytes) {
5976
6784
  function isRecord(value) {
5977
6785
  return typeof value === "object" && value !== null;
5978
6786
  }
6787
+ async function fetchAsset(assets, path) {
6788
+ const candidates = await assets.resolve(path);
6789
+ const failures = [];
6790
+ let answered = false;
6791
+ let lastError;
6792
+ for (const url of candidates) {
6793
+ let response;
6794
+ try {
6795
+ response = await fetch(url);
6796
+ } catch (error) {
6797
+ lastError = error;
6798
+ failures.push(`${url} (${error instanceof Error ? error.message : String(error)})`);
6799
+ continue;
6800
+ }
6801
+ answered = true;
6802
+ if (response.ok) return response;
6803
+ failures.push(`${url} (status ${String(response.status)})`);
6804
+ }
6805
+ throw new Error(
6806
+ `TN_ASSET_NOT_SERVED: '${path}' is not served by any of ${String(candidates.length)} candidate url(s): ${failures.join("; ") || "none"}.`,
6807
+ answered || candidates.length === 0 ? void 0 : { cause: lastError }
6808
+ );
6809
+ }
5979
6810
 
5980
6811
  // src/static-transform.ts
5981
6812
  var STATIC_TRANSFORM_MARKER = "TN_STATIC_TRANSFORMS";
5982
6813
  var frozen = /* @__PURE__ */ new Map();
5983
- var SNAPSHOT_LENGTH2 = 3 + 4 + 3 + 16;
6814
+ var SNAPSHOT_LENGTH2 = 3 + 4 + 3 + 16 + 16;
6815
+ var IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
5984
6816
  function writeSnapshot(root, into) {
5985
6817
  const position = root.position;
5986
6818
  const quaternion = root.quaternion;
5987
6819
  const scale = root.scale;
5988
- const matrix2 = root.matrix;
6820
+ const matrix2 = root.matrix.elements;
5989
6821
  into[0] = position.x;
5990
6822
  into[1] = position.y;
5991
6823
  into[2] = position.z;
@@ -5996,8 +6828,9 @@ function writeSnapshot(root, into) {
5996
6828
  into[7] = scale.x;
5997
6829
  into[8] = scale.y;
5998
6830
  into[9] = scale.z;
5999
- for (let element = 0; element < 16; element += 1)
6000
- into[10 + element] = matrix2.elements[element] ?? 0;
6831
+ for (let element = 0; element < 16; element += 1) into[10 + element] = matrix2[element] ?? 0;
6832
+ const parent = root.parent?.matrixWorld.elements ?? IDENTITY;
6833
+ for (let element = 0; element < 16; element += 1) into[26 + element] = parent[element] ?? 0;
6001
6834
  }
6002
6835
  function snapshotMatches(root, snapshot, scratch3) {
6003
6836
  writeSnapshot(root, scratch3);
@@ -6018,6 +6851,13 @@ var worldSilenced = /* @__PURE__ */ new WeakSet();
6018
6851
  function worldSilencedByFreeze(object2) {
6019
6852
  return worldSilenced.has(object2);
6020
6853
  }
6854
+ function thaw(root) {
6855
+ if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
6856
+ root.traverse((child) => {
6857
+ if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
6858
+ child.matrixWorldNeedsUpdate = true;
6859
+ });
6860
+ }
6021
6861
  function freeze(root) {
6022
6862
  root.updateMatrixWorld(true);
6023
6863
  let objects = 0;
@@ -6033,12 +6873,22 @@ function freeze(root) {
6033
6873
  return objects;
6034
6874
  }
6035
6875
  function markStatic(root) {
6036
- const objects = freeze(root);
6876
+ return freezeRoot(root, false);
6877
+ }
6878
+ function markEngineStatic(root) {
6879
+ return freezeRoot(root, true);
6880
+ }
6881
+ function freezeRoot(root, engine) {
6037
6882
  const existing = frozen.get(root);
6883
+ if (existing !== void 0) thaw(root);
6884
+ const objects = freeze(root);
6038
6885
  const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH2);
6039
6886
  writeSnapshot(root, snapshot);
6040
6887
  const version = (existing?.version ?? 0) + 1;
6041
- frozen.set(root, { objects, root, snapshot, version });
6888
+ frozen.set(
6889
+ root,
6890
+ engine ? { objects, root, snapshot, version, parent: root.parent, fresh: true } : { objects, root, snapshot, version }
6891
+ );
6042
6892
  return version;
6043
6893
  }
6044
6894
  function unmarkStatic(root) {
@@ -6053,15 +6903,7 @@ function unmarkStatic(root) {
6053
6903
  function invalidateStatic(object2) {
6054
6904
  let node = object2;
6055
6905
  while (node !== null) {
6056
- if (frozen.has(node)) {
6057
- const root = node;
6058
- root.traverse((child) => {
6059
- if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
6060
- child.matrixWorldNeedsUpdate = true;
6061
- });
6062
- if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
6063
- return markStatic(root);
6064
- }
6906
+ if (frozen.has(node)) return markStatic(node);
6065
6907
  node = node.parent;
6066
6908
  }
6067
6909
  return void 0;
@@ -6075,17 +6917,44 @@ function staticRoots() {
6075
6917
  var rearmedSinceCensus = 0;
6076
6918
  function refreshStaticTransforms() {
6077
6919
  if (frozen.size === 0) return;
6920
+ parentMovedThisFrame.clear();
6078
6921
  for (const entry of frozen.values()) {
6079
- if (snapshotMatches(entry.root, entry.snapshot, scratch2)) continue;
6080
- if (worldSilenced.delete(entry.root)) entry.root.matrixWorldAutoUpdate = true;
6081
- entry.root.traverse((child) => {
6082
- if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
6083
- child.matrixWorldNeedsUpdate = true;
6084
- });
6085
- markStatic(entry.root);
6922
+ const engine = entry.parent !== void 0;
6923
+ if (engine) {
6924
+ const parent = entry.root.parent;
6925
+ const moved = parentMoved(parent);
6926
+ if (parent === entry.parent && entry.fresh !== true && !moved) continue;
6927
+ entry.fresh = false;
6928
+ if (snapshotMatches(entry.root, entry.snapshot, scratch2)) {
6929
+ entry.parent = parent;
6930
+ continue;
6931
+ }
6932
+ } else if (snapshotMatches(entry.root, entry.snapshot, scratch2)) continue;
6933
+ freezeRoot(entry.root, engine);
6086
6934
  rearmedSinceCensus += 1;
6087
6935
  }
6088
6936
  }
6937
+ var parentSeen = /* @__PURE__ */ new WeakMap();
6938
+ var parentMovedThisFrame = /* @__PURE__ */ new Map();
6939
+ function parentMoved(parent) {
6940
+ if (parent === null) return false;
6941
+ const answered = parentMovedThisFrame.get(parent);
6942
+ if (answered !== void 0) return answered;
6943
+ const elements = parent.matrixWorld.elements;
6944
+ let seen = parentSeen.get(parent);
6945
+ let moved = seen === void 0;
6946
+ if (seen === void 0) {
6947
+ seen = new Float64Array(16);
6948
+ parentSeen.set(parent, seen);
6949
+ }
6950
+ for (let element = 0; element < 16; element += 1) {
6951
+ const value = elements[element] ?? 0;
6952
+ if (seen[element] !== value) moved = true;
6953
+ seen[element] = value;
6954
+ }
6955
+ parentMovedThisFrame.set(parent, moved);
6956
+ return moved;
6957
+ }
6089
6958
  function staticTransformCensus() {
6090
6959
  let objects = 0;
6091
6960
  for (const entry of frozen.values()) objects += entry.objects;
@@ -6099,6 +6968,7 @@ function staticTransformCensus() {
6099
6968
  }
6100
6969
  function resetStaticTransforms() {
6101
6970
  frozen.clear();
6971
+ parentMovedThisFrame.clear();
6102
6972
  rearmedSinceCensus = 0;
6103
6973
  }
6104
6974
 
@@ -6534,8 +7404,11 @@ function positiveInteger(value, name) {
6534
7404
  // src/warmup.ts
6535
7405
  var warmUpCompletions = /* @__PURE__ */ new WeakMap();
6536
7406
  async function warmUpSceneWithCompletion(renderer, scene, camera, options = {}) {
6537
- const report = await warmUpScene(renderer, scene, camera, options);
6538
- return { report, completion: warmUpCompletions.get(report) ?? Promise.resolve() };
7407
+ const report2 = await warmUpScene(renderer, scene, camera, options);
7408
+ return { report: report2, completion: warmUpCompletions.get(report2) ?? Promise.resolve() };
7409
+ }
7410
+ function isFrameGateTimeout(error) {
7411
+ return error instanceof Error && error.message.startsWith("TN_WARMUP_FRAME_GATE");
6539
7412
  }
6540
7413
  function nativeEnvironmentPreparer(raw) {
6541
7414
  return typeof raw?.prepareEnvironmentAsync === "function" ? raw : void 0;
@@ -6661,7 +7534,7 @@ async function yieldThroughHost(yieldFrame) {
6661
7534
  new Promise((resolve) => setTimeout(resolve, 0))
6662
7535
  ]);
6663
7536
  }
6664
- async function withinDeadline(deadline, work, yieldFrame, now2) {
7537
+ async function withinDeadline(deadline, work, yieldFrame, now3) {
6665
7538
  let settled;
6666
7539
  const completion = work.then(
6667
7540
  () => {
@@ -6674,12 +7547,12 @@ async function withinDeadline(deadline, work, yieldFrame, now2) {
6674
7547
  }
6675
7548
  );
6676
7549
  await Promise.resolve();
6677
- if (now2() >= deadline) return false;
7550
+ if (now3() >= deadline) return false;
6678
7551
  if (settled !== void 0) return settled;
6679
- while (now2() < deadline) {
7552
+ while (now3() < deadline) {
6680
7553
  if (settled !== void 0) return settled;
6681
7554
  let timer;
6682
- const remaining = Math.max(0, deadline - now2());
7555
+ const remaining = Math.max(0, deadline - now3());
6683
7556
  const expiry = new Promise((resolve) => {
6684
7557
  timer = setTimeout(() => resolve("timeout"), remaining);
6685
7558
  });
@@ -6690,11 +7563,11 @@ async function withinDeadline(deadline, work, yieldFrame, now2) {
6690
7563
  ]);
6691
7564
  if (timer !== void 0) clearTimeout(timer);
6692
7565
  if (result === "timeout") return false;
6693
- if (result.kind === "complete") return now2() < deadline && result.value;
7566
+ if (result.kind === "complete") return now3() < deadline && result.value;
6694
7567
  }
6695
7568
  return false;
6696
7569
  }
6697
- async function runComputeWarmUp(renderer, nodes, compileTimeoutMs, deadline, now2, yieldFrame) {
7570
+ async function runComputeWarmUp(renderer, nodes2, compileTimeoutMs, deadline, now3, yieldFrame) {
6698
7571
  const seam = computeAsyncOf(renderer);
6699
7572
  if (seam === void 0) {
6700
7573
  return { compiled: 0, abandoned: 0, unsupported: true, timedOut: false };
@@ -6702,30 +7575,30 @@ async function runComputeWarmUp(renderer, nodes, compileTimeoutMs, deadline, now
6702
7575
  let compiled = 0;
6703
7576
  let abandoned = 0;
6704
7577
  let timedOut = false;
6705
- for (let index = 0; index < nodes.length; index += 1) {
6706
- const remaining = deadline - now2();
7578
+ for (let index = 0; index < nodes2.length; index += 1) {
7579
+ const remaining = deadline - now3();
6707
7580
  if (remaining <= 0) {
6708
7581
  timedOut = true;
6709
- abandoned += nodes.length - index;
7582
+ abandoned += nodes2.length - index;
6710
7583
  break;
6711
7584
  }
6712
7585
  const finished = await withinDeadline(
6713
- Math.min(deadline, now2() + compileTimeoutMs),
6714
- Promise.resolve().then(() => seam.warm(nodes[index])),
7586
+ Math.min(deadline, now3() + compileTimeoutMs),
7587
+ Promise.resolve().then(() => seam.warm(nodes2[index])),
6715
7588
  yieldFrame,
6716
- now2
7589
+ now3
6717
7590
  );
6718
7591
  if (finished) compiled += 1;
6719
7592
  else abandoned += 1;
6720
- if (now2() >= deadline && (!finished || index + 1 < nodes.length)) {
7593
+ if (now3() >= deadline && (!finished || index + 1 < nodes2.length)) {
6721
7594
  timedOut = true;
6722
- abandoned += nodes.length - index - 1;
7595
+ abandoned += nodes2.length - index - 1;
6723
7596
  break;
6724
7597
  }
6725
7598
  }
6726
7599
  return { compiled, abandoned, unsupported: false, timedOut };
6727
7600
  }
6728
- async function warmUpComputeNodes(renderer, nodes, options = {}) {
7601
+ async function warmUpComputeNodes(renderer, nodes2, options = {}) {
6729
7602
  const compileTimeoutMs = options.compileTimeoutMs ?? DEFAULT_COMPILE_TIMEOUT_MS;
6730
7603
  const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;
6731
7604
  for (const [name, value] of [
@@ -6738,19 +7611,19 @@ async function warmUpComputeNodes(renderer, nodes, options = {}) {
6738
7611
  );
6739
7612
  }
6740
7613
  }
6741
- const now2 = () => globalThis.performance?.now() ?? Date.now();
7614
+ const now3 = () => globalThis.performance?.now() ?? Date.now();
6742
7615
  return runComputeWarmUp(
6743
7616
  renderer,
6744
- nodes,
7617
+ nodes2,
6745
7618
  compileTimeoutMs,
6746
- now2() + budgetMs,
6747
- now2,
7619
+ now3() + budgetMs,
7620
+ now3,
6748
7621
  options.yieldFrame ?? yieldToHost
6749
7622
  );
6750
7623
  }
6751
- function withComputeReport(report, compute) {
7624
+ function withComputeReport(report2, compute) {
6752
7625
  return {
6753
- ...report,
7626
+ ...report2,
6754
7627
  computeCompiled: compute.compiled,
6755
7628
  computeAbandoned: compute.abandoned,
6756
7629
  computeUnsupported: compute.unsupported,
@@ -6801,11 +7674,11 @@ function observePipelineCensus(before, after) {
6801
7674
  status
6802
7675
  };
6803
7676
  }
6804
- function reconcileWarmUpObservation(report) {
6805
- const unavailable = report.unsupported || report.computeUnsupported === true;
6806
- const incomplete = report.abandoned > 0 || report.timedOut || report.computeTimedOut === true || (report.computeAbandoned ?? 0) > 0;
6807
- const status = unavailable ? "unavailable" : incomplete && report.observed.status === "complete" ? "incomplete" : report.observed.status;
6808
- return status === report.observed.status ? report : { ...report, observed: { ...report.observed, status } };
7677
+ function reconcileWarmUpObservation(report2) {
7678
+ const unavailable = report2.unsupported || report2.computeUnsupported === true;
7679
+ const incomplete = report2.abandoned > 0 || report2.timedOut || report2.computeTimedOut === true || (report2.computeAbandoned ?? 0) > 0;
7680
+ const status = unavailable ? "unavailable" : incomplete && report2.observed.status === "complete" ? "incomplete" : report2.observed.status;
7681
+ return status === report2.observed.status ? report2 : { ...report2, observed: { ...report2.observed, status } };
6809
7682
  }
6810
7683
  function hasShadowCaster(scene) {
6811
7684
  const stack = [scene];
@@ -6954,10 +7827,10 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
6954
7827
  );
6955
7828
  }
6956
7829
  }
6957
- const now2 = () => globalThis.performance?.now() ?? Date.now();
7830
+ const now3 = () => globalThis.performance?.now() ?? Date.now();
6958
7831
  const yieldFrame = options.yieldFrame ?? yieldToHost;
6959
- const environmentDeadline = now2() + environmentBudgetMs;
6960
- let startedAt = now2();
7832
+ const environmentDeadline = now3() + environmentBudgetMs;
7833
+ let startedAt = now3();
6961
7834
  let environmentPreparationStarted = false;
6962
7835
  let environmentPrepared = false;
6963
7836
  let environmentPreparation;
@@ -6990,7 +7863,7 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
6990
7863
  let cacheStatus = readWarmUpCache(cacheIdentity, candidates, computeNodes.length);
6991
7864
  const upfront = ensureEnvironmentPreparation();
6992
7865
  if (upfront !== void 0) {
6993
- if (!await withinDeadline(environmentDeadline, upfront, yieldFrame, now2)) {
7866
+ if (!await withinDeadline(environmentDeadline, upfront, yieldFrame, now3)) {
6994
7867
  return reconcileWarmUpObservation({
6995
7868
  compiled: 0,
6996
7869
  pipelines: candidates,
@@ -6998,20 +7871,20 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
6998
7871
  attempted: 0,
6999
7872
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7000
7873
  slices: 0,
7001
- elapsedMs: now2() - startedAt,
7874
+ elapsedMs: now3() - startedAt,
7002
7875
  unsupported: false,
7003
7876
  abandoned: 1,
7004
- timedOut: now2() >= environmentDeadline,
7877
+ timedOut: now3() >= environmentDeadline,
7005
7878
  cache: cacheStatus
7006
7879
  });
7007
7880
  }
7008
- startedAt = now2();
7881
+ startedAt = now3();
7009
7882
  }
7010
7883
  if (cacheStatus === "hit" && typeof renderer.compileAsync === "function") {
7011
7884
  const computeSupported = computeNodes.length === 0 || computeAsyncOf(renderer) !== void 0;
7012
7885
  if (computeSupported) {
7013
7886
  const preparation = ensureEnvironmentPreparation();
7014
- if (preparation !== void 0 && !await withinDeadline(startedAt + budgetMs, preparation, yieldFrame, now2)) {
7887
+ if (preparation !== void 0 && !await withinDeadline(startedAt + budgetMs, preparation, yieldFrame, now3)) {
7015
7888
  return reconcileWarmUpObservation({
7016
7889
  compiled: 0,
7017
7890
  pipelines: candidates,
@@ -7019,21 +7892,21 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7019
7892
  attempted: 0,
7020
7893
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7021
7894
  slices: 0,
7022
- elapsedMs: now2() - startedAt,
7895
+ elapsedMs: now3() - startedAt,
7023
7896
  unsupported: false,
7024
7897
  abandoned: 1,
7025
- timedOut: now2() >= startedAt + budgetMs,
7898
+ timedOut: now3() >= startedAt + budgetMs,
7026
7899
  cache: "hit"
7027
7900
  });
7028
7901
  }
7029
- const report2 = {
7902
+ const report3 = {
7030
7903
  compiled: 0,
7031
7904
  pipelines: candidates,
7032
7905
  candidates,
7033
7906
  attempted: 0,
7034
7907
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7035
7908
  slices: 0,
7036
- elapsedMs: now2() - startedAt,
7909
+ elapsedMs: now3() - startedAt,
7037
7910
  unsupported: false,
7038
7911
  abandoned: 0,
7039
7912
  timedOut: false,
@@ -7045,7 +7918,7 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7045
7918
  computeTimedOut: false
7046
7919
  }
7047
7920
  };
7048
- return report2;
7921
+ return report3;
7049
7922
  }
7050
7923
  cacheStatus = "miss";
7051
7924
  }
@@ -7054,33 +7927,33 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7054
7927
  computeNodes,
7055
7928
  compileTimeoutMs,
7056
7929
  startedAt + budgetMs,
7057
- now2,
7930
+ now3,
7058
7931
  yieldFrame
7059
7932
  );
7060
7933
  if (typeof renderer.compileAsync !== "function") {
7061
- const report2 = reconcileWarmUpObservation({
7934
+ const report3 = reconcileWarmUpObservation({
7062
7935
  compiled: 0,
7063
7936
  pipelines: candidates,
7064
7937
  candidates,
7065
7938
  attempted: 0,
7066
7939
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7067
7940
  slices: 0,
7068
- elapsedMs: now2() - startedAt,
7941
+ elapsedMs: now3() - startedAt,
7069
7942
  unsupported: true,
7070
7943
  abandoned: 0,
7071
7944
  timedOut: false,
7072
7945
  cache: cacheStatus
7073
7946
  });
7074
- return compute === void 0 ? report2 : reconcileWarmUpObservation(withComputeReport(report2, compute));
7947
+ return compute === void 0 ? report3 : reconcileWarmUpObservation(withComputeReport(report3, compute));
7075
7948
  }
7076
7949
  const compileAsync = renderer.compileAsync.bind(renderer);
7077
7950
  let attempted = 0;
7078
7951
  const pendingCompiles = [];
7079
7952
  const invokeCompile = (object2, targetScene) => {
7080
- const compileDeadline = (options.granularity ?? "scene") === "scene" ? startedAt + budgetMs : Math.min(startedAt + budgetMs, now2() + compileTimeoutMs);
7953
+ const compileDeadline = (options.granularity ?? "scene") === "scene" ? startedAt + budgetMs : Math.min(startedAt + budgetMs, now3() + compileTimeoutMs);
7081
7954
  const preparation = ensureEnvironmentPreparation(targetScene ?? scene);
7082
7955
  const compile = () => {
7083
- if (now2() >= compileDeadline) {
7956
+ if (now3() >= compileDeadline) {
7084
7957
  return Promise.reject(
7085
7958
  new Error("TN_WARMUP_COMPILE_DEADLINE: PMREM preparation consumed this compile slice.")
7086
7959
  );
@@ -7100,32 +7973,35 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7100
7973
  return compile.catch(() => void 0).then(async () => {
7101
7974
  const pass = await renderWarmPassesOnce();
7102
7975
  if (pass === void 0) {
7103
- if (passError === void 0 && now2() >= startedAt + budgetMs) return;
7976
+ if (passError === void 0 && now3() >= startedAt + budgetMs) return;
7977
+ if (isFrameGateTimeout(passError)) return;
7104
7978
  throw passError ?? new Error("covered world warm render did not settle");
7105
7979
  }
7106
7980
  });
7107
7981
  };
7108
7982
  let gpuDrainSettled = true;
7109
- const compileWithinDeadline = async (deadline2, work, yieldFrame2, now3) => {
7983
+ let compileOutran = false;
7984
+ const compileWithinDeadline = async (deadline2, work, yieldFrame2, now4) => {
7110
7985
  let settled = false;
7111
7986
  const track = () => {
7112
7987
  settled = true;
7113
7988
  };
7114
7989
  void work.then(track, track);
7115
- const finished = await withinDeadline(deadline2, work, yieldFrame2, now3);
7116
- if (!finished && !settled) pendingCompiles.push(work);
7990
+ const finished = await withinDeadline(deadline2, work, yieldFrame2, now4);
7991
+ compileOutran = !finished && !settled;
7992
+ if (compileOutran) pendingCompiles.push(work);
7117
7993
  return finished;
7118
7994
  };
7119
- const finish = (report2) => {
7995
+ const finish = (report3) => {
7120
7996
  const coveredPassIncomplete = renderer.warmUpWorldPass !== void 0 && passResult === void 0;
7121
- const drainNormalized = gpuDrainSettled ? report2 : {
7122
- ...report2,
7997
+ const drainNormalized = gpuDrainSettled ? report3 : {
7998
+ ...report3,
7123
7999
  timedOut: true
7124
8000
  };
7125
8001
  const normalized = coveredPassIncomplete ? {
7126
8002
  ...drainNormalized,
7127
8003
  abandoned: Math.max(1, drainNormalized.abandoned),
7128
- timedOut: drainNormalized.timedOut || now2() >= startedAt + budgetMs
8004
+ timedOut: drainNormalized.timedOut || now3() >= startedAt + budgetMs
7129
8005
  } : drainNormalized;
7130
8006
  const complete = gpuDrainSettled && !normalized.unsupported && !normalized.timedOut && normalized.abandoned === 0 && normalized.computeUnsupported !== true && normalized.computeTimedOut !== true && (normalized.computeAbandoned ?? 0) === 0;
7131
8007
  const finalCache = complete && cacheIdentity !== void 0 ? storeWarmUpCache(cacheIdentity, candidates, computeNodes.length) : cacheStatus;
@@ -7144,7 +8020,7 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7144
8020
  if (passRendered) return passResult;
7145
8021
  passRendered = true;
7146
8022
  if (environmentPreparationStarted && !environmentPrepared) return void 0;
7147
- if (now2() >= startedAt + budgetMs) return void 0;
8023
+ if (now3() >= startedAt + budgetMs) return void 0;
7148
8024
  try {
7149
8025
  passResult = await renderWarmPasses(
7150
8026
  renderer,
@@ -7166,20 +8042,20 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7166
8042
  const queue = renderer.raw?.backend?.device?.queue;
7167
8043
  if (typeof queue?.onSubmittedWorkDone !== "function") return;
7168
8044
  const drained = Promise.resolve().then(() => queue.onSubmittedWorkDone?.());
7169
- gpuDrainSettled = await withinDeadline(startedAt + budgetMs, drained, yieldFrame, now2);
8045
+ gpuDrainSettled = await withinDeadline(startedAt + budgetMs, drained, yieldFrame, now3);
7170
8046
  };
7171
- const withPasses = (report2) => passResult === void 0 ? report2 : {
7172
- ...report2,
8047
+ const withPasses = (report3) => passResult === void 0 ? report3 : {
8048
+ ...report3,
7173
8049
  passes: passResult.passes,
7174
8050
  passPipelines: passResult.created,
7175
8051
  cullingForced: passResult.cullingForced,
7176
8052
  visibilityForced: passResult.visibilityForced,
7177
- elapsedMs: report2.elapsedMs + passResult.elapsedMs
8053
+ elapsedMs: report3.elapsedMs + passResult.elapsedMs
7178
8054
  };
7179
8055
  if ((options.granularity ?? "scene") === "scene") {
7180
8056
  if (compute === void 0) {
7181
8057
  const deadline2 = startedAt + budgetMs;
7182
- const finished2 = now2() < deadline2 ? await compileWithinDeadline(deadline2, invokeSceneCompile(), yieldFrame, now2) : false;
8058
+ const finished2 = now3() < deadline2 ? await compileWithinDeadline(deadline2, invokeSceneCompile(), yieldFrame, now3) : false;
7183
8059
  options.onProgress?.({ done: finished2 ? 1 : 0, total: 1 });
7184
8060
  await renderWarmPassesOnce();
7185
8061
  await settleGpu();
@@ -7191,15 +8067,15 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7191
8067
  attempted,
7192
8068
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7193
8069
  slices: 1,
7194
- elapsedMs: now2() - startedAt,
8070
+ elapsedMs: now3() - startedAt,
7195
8071
  unsupported: false,
7196
8072
  abandoned: finished2 ? 0 : 1,
7197
- timedOut: !finished2 && (passError === void 0 || now2() >= deadline2)
8073
+ timedOut: !finished2 && (passError === void 0 || compileOutran || now3() >= deadline2)
7198
8074
  })
7199
8075
  );
7200
8076
  }
7201
- const remaining = Math.max(0, startedAt + budgetMs - now2());
7202
- const finished = remaining > 0 ? await compileWithinDeadline(startedAt + budgetMs, invokeSceneCompile(), yieldFrame, now2) : false;
8077
+ const remaining = Math.max(0, startedAt + budgetMs - now3());
8078
+ const finished = remaining > 0 ? await compileWithinDeadline(startedAt + budgetMs, invokeSceneCompile(), yieldFrame, now3) : false;
7203
8079
  options.onProgress?.({ done: finished ? 1 : 0, total: 1 });
7204
8080
  await renderWarmPassesOnce();
7205
8081
  await settleGpu();
@@ -7213,10 +8089,10 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7213
8089
  attempted,
7214
8090
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7215
8091
  slices: 1,
7216
- elapsedMs: now2() - startedAt,
8092
+ elapsedMs: now3() - startedAt,
7217
8093
  unsupported: false,
7218
8094
  abandoned: finished ? 0 : 1,
7219
- timedOut: compute.timedOut || !finished && now2() >= startedAt + budgetMs
8095
+ timedOut: compute.timedOut || !finished && now3() >= startedAt + budgetMs
7220
8096
  },
7221
8097
  compute
7222
8098
  )
@@ -7226,19 +8102,19 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7226
8102
  const total = renderables.length;
7227
8103
  if (total === 0) {
7228
8104
  options.onProgress?.({ done: 0, total: 0 });
7229
- const report2 = reconcileWarmUpObservation({
8105
+ const report3 = reconcileWarmUpObservation({
7230
8106
  compiled: 0,
7231
8107
  pipelines: candidates,
7232
8108
  candidates,
7233
8109
  attempted,
7234
8110
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7235
8111
  slices: 0,
7236
- elapsedMs: now2() - startedAt,
8112
+ elapsedMs: now3() - startedAt,
7237
8113
  unsupported: false,
7238
8114
  abandoned: 0,
7239
8115
  timedOut: false
7240
8116
  });
7241
- return compute === void 0 ? finish(report2) : finish(withComputeReport(report2, compute));
8117
+ return compute === void 0 ? finish(report3) : finish(withComputeReport(report3, compute));
7242
8118
  }
7243
8119
  let slices = 0;
7244
8120
  let compiled = 0;
@@ -7246,21 +8122,21 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7246
8122
  let timedOut = false;
7247
8123
  const deadline = startedAt + budgetMs;
7248
8124
  for (let index = 0; index < total; index += 1) {
7249
- if (now2() >= deadline) {
8125
+ if (now3() >= deadline) {
7250
8126
  timedOut = true;
7251
8127
  abandoned += total - index;
7252
8128
  break;
7253
8129
  }
7254
8130
  const finished = await compileWithinDeadline(
7255
- Math.min(deadline, now2() + compileTimeoutMs),
8131
+ Math.min(deadline, now3() + compileTimeoutMs),
7256
8132
  invokeCompile(renderables[index], options.targetScene ?? scene),
7257
8133
  yieldFrame,
7258
- now2
8134
+ now3
7259
8135
  );
7260
8136
  if (finished) compiled += 1;
7261
8137
  else {
7262
8138
  abandoned += 1;
7263
- if (now2() >= deadline) timedOut = true;
8139
+ if (now3() >= deadline) timedOut = true;
7264
8140
  }
7265
8141
  const done = index + 1;
7266
8142
  if (done % sliceSize === 0 || done === total) {
@@ -7270,27 +8146,162 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7270
8146
  }
7271
8147
  }
7272
8148
  if (renderer.warmUpWorldPass === void 0) await renderWarmPassesOnce();
7273
- else await withinDeadline(startedAt + budgetMs, renderWarmPassesOnce(), yieldFrame, now2);
8149
+ else await withinDeadline(startedAt + budgetMs, renderWarmPassesOnce(), yieldFrame, now3);
7274
8150
  await settleGpu();
7275
- const report = {
8151
+ const report2 = {
7276
8152
  compiled,
7277
8153
  pipelines: candidates,
7278
8154
  candidates,
7279
8155
  attempted,
7280
8156
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7281
8157
  slices,
7282
- elapsedMs: now2() - startedAt,
8158
+ elapsedMs: now3() - startedAt,
7283
8159
  unsupported: false,
7284
8160
  abandoned,
7285
8161
  timedOut
7286
8162
  };
7287
- return compute === void 0 ? finish(withPasses(report)) : finish(
8163
+ return compute === void 0 ? finish(withPasses(report2)) : finish(
7288
8164
  withPasses(
7289
- withComputeReport({ ...report, timedOut: compute.timedOut || timedOut }, compute)
8165
+ withComputeReport({ ...report2, timedOut: compute.timedOut || timedOut }, compute)
7290
8166
  )
7291
8167
  );
7292
8168
  }
7293
8169
 
8170
+ // src/streaming.ts
8171
+ var DEFAULT_SLICE_BUDGET_MS = 8;
8172
+ var DEFAULT_CONCURRENCY2 = 6;
8173
+ var now2 = () => globalThis.performance?.now() ?? Date.now();
8174
+ var SLICE_FRAME_MARGIN_MS = 2;
8175
+ var MIN_SLICE_BUDGET_MS = 1;
8176
+ var LOOP_FRAME_WAIT_MS = 250;
8177
+ var loopFrames = {
8178
+ visible: false,
8179
+ budgetMs: DEFAULT_SLICE_BUDGET_MS,
8180
+ waiters: []
8181
+ };
8182
+ function noteSliceFrame(frameMs, targetFps, visible) {
8183
+ loopFrames.visible = visible;
8184
+ loopFrames.budgetMs = targetFps > 0 ? Math.min(
8185
+ DEFAULT_SLICE_BUDGET_MS,
8186
+ Math.max(MIN_SLICE_BUDGET_MS, 1e3 / targetFps - frameMs - SLICE_FRAME_MARGIN_MS)
8187
+ ) : DEFAULT_SLICE_BUDGET_MS;
8188
+ for (const resolve of loopFrames.waiters.splice(0)) resolve();
8189
+ }
8190
+ function endSliceFrames() {
8191
+ noteSliceFrame(0, 0, false);
8192
+ }
8193
+ var nextLoopFrame = () => new Promise((resolve) => {
8194
+ const timer = setTimeout(resolve, LOOP_FRAME_WAIT_MS);
8195
+ loopFrames.waiters.push(() => {
8196
+ clearTimeout(timer);
8197
+ resolve();
8198
+ });
8199
+ }).then(yieldToHost);
8200
+ var yieldSlice = () => loopFrames.visible ? nextLoopFrame() : yieldToHost();
8201
+ var sliceBudget = () => loopFrames.visible ? loopFrames.budgetMs : DEFAULT_SLICE_BUDGET_MS;
8202
+ function assertWholeAtLeastOne(value, name, code) {
8203
+ if (!Number.isInteger(value) || value < 1) {
8204
+ throw new Error(
8205
+ `${code}: ${name} must be a whole number of at least one, received ${String(value)}.`
8206
+ );
8207
+ }
8208
+ }
8209
+ async function addInSlices(objects, add, options = {}) {
8210
+ const sliceSize = options.sliceSize;
8211
+ if (sliceSize !== void 0) {
8212
+ assertWholeAtLeastOne(sliceSize, "sliceSize", "TN_ADD_SLICES_SLICE_INVALID");
8213
+ }
8214
+ const countSlices = sliceSize !== void 0;
8215
+ const nextBudget = options.yieldFrame === void 0 ? sliceBudget : () => DEFAULT_SLICE_BUDGET_MS;
8216
+ let sliceBudgetMs = countSlices ? void 0 : nextBudget();
8217
+ const yieldFrame = options.yieldFrame ?? yieldSlice;
8218
+ const shouldContinue = options.while;
8219
+ const startedAt = now2();
8220
+ const list = [...objects];
8221
+ const total = list.length;
8222
+ let added = 0;
8223
+ let reported = 0;
8224
+ let slices = 0;
8225
+ let stopped = false;
8226
+ let sliceStartedAt = now2();
8227
+ const flush = async (yieldAfter) => {
8228
+ slices += 1;
8229
+ reported = added;
8230
+ options.onProgress?.({ added, total });
8231
+ if (yieldAfter) {
8232
+ await yieldFrame();
8233
+ if (sliceBudgetMs !== void 0) {
8234
+ sliceBudgetMs = nextBudget();
8235
+ sliceStartedAt = now2();
8236
+ }
8237
+ }
8238
+ };
8239
+ const sliceSpent = () => sliceSize !== void 0 ? added % sliceSize === 0 : now2() - sliceStartedAt >= Number(sliceBudgetMs);
8240
+ for (let index = 0; index < total; index += 1) {
8241
+ if (shouldContinue !== void 0 && !shouldContinue()) {
8242
+ stopped = true;
8243
+ break;
8244
+ }
8245
+ add(list[index], index);
8246
+ added += 1;
8247
+ if (added < total && sliceSpent()) await flush(true);
8248
+ }
8249
+ if (added > reported) await flush(false);
8250
+ const report2 = {
8251
+ added,
8252
+ total,
8253
+ slices,
8254
+ elapsedMs: now2() - startedAt,
8255
+ // Measured rather than assumed: with no count to divide by, the average is what the run did.
8256
+ sliceSize: sliceSize ?? Math.round(added / Math.max(slices, 1)),
8257
+ sliceSizeOverridden: countSlices,
8258
+ sliceBudgetMs,
8259
+ stopped
8260
+ };
8261
+ if (options.marker !== false) {
8262
+ console.info(
8263
+ `TN_ADD_SLICES added=${String(added)} total=${String(total)} slices=${String(slices)} sliceSize=${String(report2.sliceSize)} overridden=${String(countSlices)} budgetMs=${String(sliceBudgetMs ?? "none")} stopped=${String(stopped)} ms=${report2.elapsedMs.toFixed(1)}`
8264
+ );
8265
+ }
8266
+ return report2;
8267
+ }
8268
+ async function loadAll(items, load, options = {}) {
8269
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY2;
8270
+ assertWholeAtLeastOne(concurrency, "concurrency", "TN_LOAD_ALL_CONCURRENCY_INVALID");
8271
+ const concurrencyOverridden = options.concurrency !== void 0;
8272
+ const yieldFrame = options.yieldFrame ?? yieldToHost;
8273
+ const startedAt = now2();
8274
+ const total = items.length;
8275
+ const results = new Array(total);
8276
+ let next = 0;
8277
+ let settled = 0;
8278
+ let failed = false;
8279
+ const lane = async () => {
8280
+ for (; ; ) {
8281
+ if (failed) return;
8282
+ const index = next;
8283
+ next += 1;
8284
+ if (index >= total) return;
8285
+ try {
8286
+ results[index] = await load(items[index], index);
8287
+ } catch (error) {
8288
+ failed = true;
8289
+ throw error;
8290
+ }
8291
+ settled += 1;
8292
+ options.onProgress?.({ settled, total });
8293
+ await yieldFrame();
8294
+ }
8295
+ };
8296
+ await Promise.all(Array.from({ length: Math.min(concurrency, total) }, () => lane()));
8297
+ if (options.marker !== false) {
8298
+ console.info(
8299
+ `TN_LOAD_ALL items=${String(total)} concurrency=${String(concurrency)} overridden=${String(concurrencyOverridden)} ms=${(now2() - startedAt).toFixed(1)}`
8300
+ );
8301
+ }
8302
+ return results;
8303
+ }
8304
+
7294
8305
  // src/target-fps.ts
7295
8306
  var DEFAULT_TARGET_FPS = 60;
7296
8307
  var MAX_TARGET_FPS = 120;
@@ -7316,16 +8327,282 @@ function resolveTargetFps(config, platform, measuredRefreshHz) {
7316
8327
  if (measuredRefreshHz === void 0) return { source: "fallback", targetFps: DEFAULT_TARGET_FPS };
7317
8328
  return { source: "display", targetFps: snapRefreshRate(measuredRefreshHz) };
7318
8329
  }
8330
+
8331
+ // src/world-cell-records.ts
8332
+ var RECORD_OP = {
8333
+ write: 1,
8334
+ fill: 2,
8335
+ move: 3,
8336
+ copy: 4,
8337
+ gather: 5,
8338
+ upload: 6,
8339
+ box: 7,
8340
+ lanes: 8
8341
+ };
8342
+ var RECORD_BOX_SIZE = 7;
8343
+ function grown(array, needed) {
8344
+ if (needed <= array.length) return array;
8345
+ const next = new array.constructor(
8346
+ Math.max(needed, array.length * 2)
8347
+ );
8348
+ next.set(array);
8349
+ return next;
8350
+ }
8351
+ var RecordQueue = class {
8352
+ #attributes = [];
8353
+ #slots = /* @__PURE__ */ new Map();
8354
+ #ops = new Float64Array(1024);
8355
+ #opAt = 0;
8356
+ #payload = new Float32Array(16384);
8357
+ #payloadAt = 0;
8358
+ #boxes = 0;
8359
+ #writers = /* @__PURE__ */ new Set();
8360
+ /** The payload buffer; read it after {@link reserve}, which may replace it. */
8361
+ get payload() {
8362
+ return this.#payload;
8363
+ }
8364
+ /** Room for `floats` payload floats at a record-aligned offset, which is returned. */
8365
+ reserve(floats) {
8366
+ const at = Math.ceil(this.#payloadAt / 16) * 16;
8367
+ this.#payload = grown(this.#payload, at + floats);
8368
+ this.#payloadAt = at + floats;
8369
+ return at;
8370
+ }
8371
+ write(attribute2, at, count, payloadAt) {
8372
+ if (count > 0) this.#op(RECORD_OP.write, attribute2, at, count, payloadAt);
8373
+ }
8374
+ fill(attribute2, at, count) {
8375
+ if (count > 0) this.#op(RECORD_OP.fill, attribute2, at, count);
8376
+ }
8377
+ move(attribute2, from, to, count) {
8378
+ if (count > 0 && from !== to) this.#op(RECORD_OP.move, attribute2, from, to, count);
8379
+ }
8380
+ copy(target, source, count) {
8381
+ if (count > 0) this.#op(RECORD_OP.copy, target, this.#slot(source), count);
8382
+ }
8383
+ /** `blocks` holds `[fromRecord, records]` pairs, laid out from record 0 in order. */
8384
+ gather(attribute2, stride, blocks) {
8385
+ if (blocks.length === 0) return;
8386
+ this.#op(RECORD_OP.gather, attribute2, stride, blocks.length / 2, ...blocks);
8387
+ }
8388
+ upload(attribute2, from, count) {
8389
+ this.#op(RECORD_OP.upload, attribute2, from, count);
8390
+ }
8391
+ /** Queues a box; the returned index is where its seven numbers start in the flush's answer. */
8392
+ box(attribute2, from, count, center, half) {
8393
+ const at = this.reserve(6);
8394
+ this.#payload.set([center.x, center.y, center.z, half.x, half.y, half.z], at);
8395
+ this.#op(RECORD_OP.box, attribute2, from, count, at);
8396
+ const index = this.#boxes;
8397
+ this.#boxes += RECORD_BOX_SIZE;
8398
+ return index;
8399
+ }
8400
+ lanes(attribute2, stride, values) {
8401
+ this.#op(RECORD_OP.lanes, attribute2, stride, values.length, ...values);
8402
+ }
8403
+ /** `writer` names its upload ranges at the next flush and reads its boxes back after it. */
8404
+ touch(writer) {
8405
+ this.#writers.add(writer);
8406
+ }
8407
+ /**
8408
+ * Hands the frame's ops to the engine in one call (or to {@link applyRecords} on upstream three),
8409
+ * then tells each writer what its boxes measured. A frame that queued nothing calls nothing.
8410
+ */
8411
+ flush() {
8412
+ if (this.#writers.size === 0 && this.#opAt === 0) return;
8413
+ const writers = [...this.#writers];
8414
+ this.#writers.clear();
8415
+ for (const writer of writers) writer.uploadRecords();
8416
+ const attributes = this.#attributes;
8417
+ const ops = this.#ops.subarray(0, this.#opAt);
8418
+ const payload = this.#payload.subarray(0, this.#payloadAt);
8419
+ this.#attributes = [];
8420
+ this.#slots.clear();
8421
+ this.#opAt = 0;
8422
+ this.#payloadAt = 0;
8423
+ this.#boxes = 0;
8424
+ const first = attributes[0];
8425
+ let boxes = [];
8426
+ if (first !== void 0) {
8427
+ const engine = first.__tnRecords;
8428
+ boxes = typeof engine === "function" ? engine.call(first, attributes, ops, payload) : applyRecords(attributes, ops, payload);
8429
+ }
8430
+ for (const writer of writers) writer.settleRecords(boxes);
8431
+ }
8432
+ #slot(attribute2) {
8433
+ let slot = this.#slots.get(attribute2);
8434
+ if (slot === void 0) {
8435
+ slot = this.#attributes.length;
8436
+ this.#attributes.push(attribute2);
8437
+ this.#slots.set(attribute2, slot);
8438
+ }
8439
+ return slot;
8440
+ }
8441
+ #op(code, attribute2, ...args) {
8442
+ const slot = this.#slot(attribute2);
8443
+ this.#ops = grown(this.#ops, this.#opAt + 2 + args.length);
8444
+ this.#ops[this.#opAt] = code;
8445
+ this.#ops[this.#opAt + 1] = slot;
8446
+ this.#ops.set(args, this.#opAt + 2);
8447
+ this.#opAt += 2 + args.length;
8448
+ }
8449
+ };
8450
+ var batchRecords = new RecordQueue();
8451
+ function span(array, at, count, what) {
8452
+ if (!(Number.isInteger(at) && Number.isInteger(count) && at >= 0 && count >= 0 && at + count <= array.length))
8453
+ throw new RangeError(
8454
+ `TN_WORLD_RECORDS: ${what} [${String(at)}, ${String(at + count)}) is outside ${String(array.length)} floats`
8455
+ );
8456
+ }
8457
+ function gather(array, ops, at) {
8458
+ const stride = ops[at + 2];
8459
+ const blocks = ops[at + 3];
8460
+ let total = 0;
8461
+ for (let block = 0; block < blocks; block += 1) total += ops[at + 5 + block * 2];
8462
+ const scratch3 = new Float32Array(total * stride);
8463
+ let written = 0;
8464
+ for (let block = 0; block < blocks; block += 1) {
8465
+ const from = ops[at + 4 + block * 2] * stride;
8466
+ const count = ops[at + 5 + block * 2] * stride;
8467
+ span(array, from, count, "gather");
8468
+ scratch3.set(array.subarray(from, from + count), written);
8469
+ written += count;
8470
+ }
8471
+ span(array, 0, written, "gather target");
8472
+ array.set(scratch3);
8473
+ }
8474
+ function lanes(array, ops, at) {
8475
+ const stride = ops[at + 2];
8476
+ const count = ops[at + 3];
8477
+ if (!(count <= stride)) throw new RangeError("TN_WORLD_RECORDS: lanes wider than the record");
8478
+ for (let record = 0; record + stride <= array.length; record += stride)
8479
+ for (let lane = 0; lane < count; lane += 1) array[record + lane] = ops[at + 4 + lane];
8480
+ }
8481
+ function applyRecords(attributes, ops, payload) {
8482
+ const boxes = [];
8483
+ for (let at = 0; at < ops.length; ) at = applyOp(attributes, ops, at, payload, boxes);
8484
+ return boxes;
8485
+ }
8486
+ function applyOp(attributes, ops, at, payload, boxes) {
8487
+ const attribute2 = attributes[ops[at + 1]];
8488
+ if (attribute2 === void 0) throw new RangeError("TN_WORLD_RECORDS: an op names no attribute");
8489
+ const array = attribute2.array;
8490
+ const a = ops[at + 2];
8491
+ const b = ops[at + 3];
8492
+ const c = ops[at + 4];
8493
+ switch (ops[at]) {
8494
+ case RECORD_OP.write:
8495
+ span(array, a, b, "write");
8496
+ span(payload, c, b, "payload");
8497
+ array.set(payload.subarray(c, c + b), a);
8498
+ return at + 5;
8499
+ case RECORD_OP.fill:
8500
+ span(array, a, b, "fill");
8501
+ array.fill(0, a, a + b);
8502
+ return at + 4;
8503
+ case RECORD_OP.move:
8504
+ span(array, a, c, "move source");
8505
+ span(array, b, c, "move target");
8506
+ array.copyWithin(b, a, a + c);
8507
+ return at + 5;
8508
+ case RECORD_OP.copy: {
8509
+ const source = attributes[a]?.array;
8510
+ if (source === void 0) throw new RangeError("TN_WORLD_RECORDS: copy names no source");
8511
+ span(array, 0, b, "copy target");
8512
+ span(source, 0, b, "copy source");
8513
+ array.set(source.subarray(0, b));
8514
+ return at + 4;
8515
+ }
8516
+ case RECORD_OP.gather:
8517
+ gather(array, ops, at);
8518
+ return at + 4 + b * 2;
8519
+ case RECORD_OP.upload:
8520
+ span(array, a, b, "upload");
8521
+ attribute2.clearUpdateRanges();
8522
+ if (b > 0) attribute2.addUpdateRange(a, b);
8523
+ attribute2.needsUpdate = true;
8524
+ return at + 4;
8525
+ case RECORD_OP.box:
8526
+ span(array, a * 16, b * 16, "box");
8527
+ span(payload, c, 6, "box payload");
8528
+ boxes.push(...boxOf(array, a, b, payload, c));
8529
+ return at + 5;
8530
+ case RECORD_OP.lanes:
8531
+ lanes(array, ops, at);
8532
+ return at + 4 + b;
8533
+ default:
8534
+ throw new RangeError(`TN_WORLD_RECORDS: unknown op ${String(ops[at])}`);
8535
+ }
8536
+ }
8537
+ function boxOf(array, from, count, local, at) {
8538
+ const cx = local[at];
8539
+ const cy = local[at + 1];
8540
+ const cz = local[at + 2];
8541
+ const hx = local[at + 3];
8542
+ const hy = local[at + 4];
8543
+ const hz = local[at + 5];
8544
+ let minX = Number.POSITIVE_INFINITY;
8545
+ let minY = Number.POSITIVE_INFINITY;
8546
+ let minZ = Number.POSITIVE_INFINITY;
8547
+ let maxX = Number.NEGATIVE_INFINITY;
8548
+ let maxY = Number.NEGATIVE_INFINITY;
8549
+ let maxZ = Number.NEGATIVE_INFINITY;
8550
+ let scale = 0;
8551
+ for (let index = from; index < from + count; index += 1) {
8552
+ const m = index * 16;
8553
+ const m0 = array[m];
8554
+ const m1 = array[m + 1];
8555
+ const m2 = array[m + 2];
8556
+ const m4 = array[m + 4];
8557
+ const m5 = array[m + 5];
8558
+ const m6 = array[m + 6];
8559
+ const m8 = array[m + 8];
8560
+ const m9 = array[m + 9];
8561
+ const m10 = array[m + 10];
8562
+ const px = m0 * cx + m4 * cy + m8 * cz + array[m + 12];
8563
+ const py = m1 * cx + m5 * cy + m9 * cz + array[m + 13];
8564
+ const pz = m2 * cx + m6 * cy + m10 * cz + array[m + 14];
8565
+ const ex = Math.abs(m0) * hx + Math.abs(m4) * hy + Math.abs(m8) * hz;
8566
+ const ey = Math.abs(m1) * hx + Math.abs(m5) * hy + Math.abs(m9) * hz;
8567
+ const ez = Math.abs(m2) * hx + Math.abs(m6) * hy + Math.abs(m10) * hz;
8568
+ if (px - ex < minX) minX = px - ex;
8569
+ if (py - ey < minY) minY = py - ey;
8570
+ if (pz - ez < minZ) minZ = pz - ez;
8571
+ if (px + ex > maxX) maxX = px + ex;
8572
+ if (py + ey > maxY) maxY = py + ey;
8573
+ if (pz + ez > maxZ) maxZ = pz + ez;
8574
+ const basis = Math.max(Math.hypot(m0, m1, m2), Math.hypot(m4, m5, m6), Math.hypot(m8, m9, m10));
8575
+ if (basis > scale) scale = basis;
8576
+ }
8577
+ return [minX, minY, minZ, maxX, maxY, maxZ, scale];
8578
+ }
8579
+ function placedBox(target, min, max, matrix2) {
8580
+ target.min.fromArray(min);
8581
+ target.max.fromArray(max);
8582
+ if (target.isEmpty()) return target;
8583
+ const e = matrix2.elements;
8584
+ const cx = (min[0] + max[0]) / 2;
8585
+ const cy = (min[1] + max[1]) / 2;
8586
+ const cz = (min[2] + max[2]) / 2;
8587
+ const hx = (max[0] - min[0]) / 2;
8588
+ const hy = (max[1] - min[1]) / 2;
8589
+ const hz = (max[2] - min[2]) / 2;
8590
+ for (let axis = 0; axis < 3; axis += 1) {
8591
+ const a = e[axis];
8592
+ const b = e[axis + 4];
8593
+ const c = e[axis + 8];
8594
+ const centre = a * cx + b * cy + c * cz + e[axis + 12];
8595
+ const half = Math.abs(a) * hx + Math.abs(b) * hy + Math.abs(c) * hz;
8596
+ target.min.setComponent(axis, centre - half);
8597
+ target.max.setComponent(axis, centre + half);
8598
+ }
8599
+ return target;
8600
+ }
8601
+
8602
+ // src/render/mesh-pool.ts
7319
8603
  var MESH_POOL_MIN_CAPACITY = 64;
7320
8604
  var MESH_POOL_MAX_PER_PAIR = 8;
7321
8605
  var MESH_POOL_MAX_HELD = 512;
7322
- var writeEpoch = 0;
7323
- function currentWriteEpoch() {
7324
- return writeEpoch;
7325
- }
7326
- function advanceWriteEpoch() {
7327
- writeEpoch += 1;
7328
- }
7329
8606
  var meshPool = /* @__PURE__ */ new Map();
7330
8607
  var meshPoolHeld = 0;
7331
8608
  function pooledCapacity(capacity) {
@@ -7360,8 +8637,8 @@ function parkMesh(mesh) {
7360
8637
  mesh.frustumCulled = false;
7361
8638
  mesh.castShadow = false;
7362
8639
  mesh.receiveShadow = false;
7363
- mesh.instanceMatrix.array.fill(0);
7364
- mesh.instanceMatrix.needsUpdate = true;
8640
+ batchRecords.fill(mesh.instanceMatrix, 0, mesh.instanceMatrix.count * 16);
8641
+ batchRecords.upload(mesh.instanceMatrix, 0, 0);
7365
8642
  let forGeometry = meshPool.get(mesh.geometry);
7366
8643
  if (forGeometry === void 0) {
7367
8644
  forGeometry = /* @__PURE__ */ new Map();
@@ -7595,107 +8872,97 @@ function clipLadder(authored, maxRatio) {
7595
8872
  return { extents, source };
7596
8873
  }
7597
8874
 
7598
- // src/streaming.ts
7599
- var DEFAULT_SLICE_BUDGET_MS = 8;
7600
- var DEFAULT_CONCURRENCY2 = 6;
7601
- var now = () => globalThis.performance?.now() ?? Date.now();
7602
- function assertWholeAtLeastOne(value, name, code) {
7603
- if (!Number.isInteger(value) || value < 1) {
7604
- throw new Error(
7605
- `${code}: ${name} must be a whole number of at least one, received ${String(value)}.`
7606
- );
7607
- }
7608
- }
7609
- async function addInSlices(objects, add, options = {}) {
7610
- const sliceSize = options.sliceSize;
7611
- if (sliceSize !== void 0) {
7612
- assertWholeAtLeastOne(sliceSize, "sliceSize", "TN_ADD_SLICES_SLICE_INVALID");
7613
- }
7614
- const countSlices = sliceSize !== void 0;
7615
- const sliceBudgetMs = countSlices ? void 0 : DEFAULT_SLICE_BUDGET_MS;
7616
- const yieldFrame = options.yieldFrame ?? yieldToHost;
7617
- const shouldContinue = options.while;
7618
- const startedAt = now();
7619
- const list = [...objects];
7620
- const total = list.length;
7621
- let added = 0;
7622
- let reported = 0;
7623
- let slices = 0;
7624
- let stopped = false;
7625
- let sliceStartedAt = now();
7626
- const flush = async (yieldAfter) => {
7627
- slices += 1;
7628
- reported = added;
7629
- options.onProgress?.({ added, total });
7630
- if (yieldAfter) {
7631
- await yieldFrame();
7632
- if (sliceBudgetMs !== void 0) sliceStartedAt = now();
7633
- }
7634
- };
7635
- const sliceSpent = () => sliceSize !== void 0 ? added % sliceSize === 0 : now() - sliceStartedAt >= DEFAULT_SLICE_BUDGET_MS;
7636
- for (let index = 0; index < total; index += 1) {
7637
- if (shouldContinue !== void 0 && !shouldContinue()) {
7638
- stopped = true;
7639
- break;
7640
- }
7641
- add(list[index], index);
7642
- added += 1;
7643
- if (added < total && sliceSpent()) await flush(true);
7644
- }
7645
- if (added > reported) await flush(false);
7646
- const report = {
7647
- added,
7648
- total,
7649
- slices,
7650
- elapsedMs: now() - startedAt,
7651
- // Measured rather than assumed: with no count to divide by, the average is what the run did.
7652
- sliceSize: sliceSize ?? Math.round(added / Math.max(slices, 1)),
7653
- sliceSizeOverridden: countSlices,
7654
- sliceBudgetMs,
7655
- stopped
8875
+ // src/renderer-facts.ts
8876
+ function rendererFacts(renderer) {
8877
+ const info = renderer?.raw?.info;
8878
+ return {
8879
+ kind: renderer?.kind ?? "unknown",
8880
+ ownedEngine: info !== void 0 && info.engine !== void 0
7656
8881
  };
7657
- if (options.marker !== false) {
7658
- console.info(
7659
- `TN_ADD_SLICES added=${String(added)} total=${String(total)} slices=${String(slices)} sliceSize=${String(report.sliceSize)} overridden=${String(countSlices)} budgetMs=${String(sliceBudgetMs ?? "none")} stopped=${String(stopped)} ms=${report.elapsedMs.toFixed(1)}`
7660
- );
7661
- }
7662
- return report;
7663
8882
  }
7664
- async function loadAll(items, load, options = {}) {
7665
- const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY2;
7666
- assertWholeAtLeastOne(concurrency, "concurrency", "TN_LOAD_ALL_CONCURRENCY_INVALID");
7667
- const concurrencyOverridden = options.concurrency !== void 0;
7668
- const yieldFrame = options.yieldFrame ?? yieldToHost;
7669
- const startedAt = now();
7670
- const total = items.length;
7671
- const results = new Array(total);
7672
- let next = 0;
7673
- let settled = 0;
7674
- let failed = false;
7675
- const lane = async () => {
7676
- for (; ; ) {
7677
- if (failed) return;
7678
- const index = next;
7679
- next += 1;
7680
- if (index >= total) return;
7681
- try {
7682
- results[index] = await load(items[index], index);
7683
- } catch (error) {
7684
- failed = true;
7685
- throw error;
7686
- }
7687
- settled += 1;
7688
- options.onProgress?.({ settled, total });
7689
- await yieldFrame();
7690
- }
7691
- };
7692
- await Promise.all(Array.from({ length: Math.min(concurrency, total) }, () => lane()));
7693
- if (options.marker !== false) {
7694
- console.info(
7695
- `TN_LOAD_ALL items=${String(total)} concurrency=${String(concurrency)} overridden=${String(concurrencyOverridden)} ms=${(now() - startedAt).toFixed(1)}`
7696
- );
8883
+
8884
+ // src/world-gpu-types.ts
8885
+ function frustumPlanes(matrix2, out) {
8886
+ const m = matrix2.elements;
8887
+ const rows = [0, -1, 0, 1, 1, 1, 1, -1, 2, -1, 2, 1];
8888
+ for (let plane = 0; plane < 6; plane += 1) {
8889
+ const k = rows[plane * 2];
8890
+ const sign = rows[plane * 2 + 1];
8891
+ const x = m[3] + sign * m[k];
8892
+ const y = m[7] + sign * m[4 + k];
8893
+ const z = m[11] + sign * m[8 + k];
8894
+ const w = m[15] + sign * m[12 + k];
8895
+ const inverse = 1 / Math.hypot(x, y, z);
8896
+ const at = plane * 4;
8897
+ out[at] = x * inverse;
8898
+ out[at + 1] = y * inverse;
8899
+ out[at + 2] = z * inverse;
8900
+ out[at + 3] = w * inverse;
8901
+ }
8902
+ }
8903
+ var DRAW_ARGS_WORDS = 5;
8904
+ var LOCAL_WORDS = 16;
8905
+ var PLACEMENT_WORDS = 24;
8906
+ var DRAW_ARGS_BYTES = DRAW_ARGS_WORDS * 4;
8907
+ function argsWords(keys) {
8908
+ return keys * DRAW_ARGS_WORDS + keys;
8909
+ }
8910
+ var VEC4_WORDS = 4;
8911
+ var SLOT_NONE = -1;
8912
+ var STORAGE_WORDS = {
8913
+ /**
8914
+ * `mat4` + `centre` (vec4) + `info` (vec4), so one placement is 96 bytes and one stride. Nothing
8915
+ * is allocated from this key any more: the kernels read one placement as {@link PLACEMENT_ROWS}
8916
+ * consecutive `vec4` rows, and the source buffer is allocated in those rows. The key stays as the
8917
+ * name of the record's whole stride.
8918
+ */
8919
+ // quality-allow: the object key names one placement's whole stride, so it keeps that spelling.
8920
+ // biome-ignore lint/style/useNamingConvention: the key names one placement's whole stride, spelled as its record.
8921
+ GpuPlacement: PLACEMENT_WORDS,
8922
+ /** `mat4`, one per key: the part's own offset inside the model, the same one the CPU composes. */
8923
+ mat4: LOCAL_WORDS,
8924
+ /** `DrawIndexedIndirect`'s five words; `uint` is one word, so the element count is the word count. */
8925
+ uint: 1,
8926
+ /** One `vec4` per key, per asset slot and per level gate. */
8927
+ vec4: VEC4_WORDS
8928
+ };
8929
+ function storageAttribute(ctor, type, count, array = Float32Array) {
8930
+ const words2 = STORAGE_WORDS[type];
8931
+ return new ctor(new array(Math.max(1, count) * words2), words2);
8932
+ }
8933
+ var VALIDATE_EVERY = 30;
8934
+ var TALLY_EVERY = 30;
8935
+ var PLACEMENT_ROWS = PLACEMENT_WORDS / VEC4_WORDS;
8936
+ function growBuffer(current, needed, make) {
8937
+ if (current.count >= needed) return current;
8938
+ let capacity = Math.max(1, current.count);
8939
+ while (capacity < needed) capacity *= 2;
8940
+ const grown2 = make(capacity);
8941
+ grown2.array.set(current.array);
8942
+ grown2.addUpdateRange(0, current.array.length);
8943
+ return grown2;
8944
+ }
8945
+ function addRange(attribute2, start, count) {
8946
+ const last = attribute2.updateRanges[attribute2.updateRanges.length - 1];
8947
+ if (last === void 0 || start > last.start + last.count || start + count < last.start) {
8948
+ attribute2.addUpdateRange(start, count);
8949
+ return;
7697
8950
  }
7698
- return results;
8951
+ const newStart = Math.min(last.start, start);
8952
+ last.count = Math.max(last.start + last.count, start + count) - newStart;
8953
+ last.start = newStart;
7699
8954
  }
8955
+ var NO_LOCAL = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
8956
+ function nodes(value) {
8957
+ return value;
8958
+ }
8959
+ var STORAGE_PLAIN = {
8960
+ gates: "vec4",
8961
+ keys: "vec4",
8962
+ levels: "vec4",
8963
+ locals: "mat4",
8964
+ source: "vec4"
8965
+ };
8966
+ var SOURCE_FLOOR = 16;
7700
8967
 
7701
- export { AutoBatch, DEFAULT_CLIP_EXTENTS, DEFAULT_MAX_LEVEL_RATIO, DEFAULT_TARGET_FPS, INSTANCED_LOD_MAX_PIXEL_ERROR, InstancedBatch, MAX_TARGET_FPS, MIN_BATCH_MEMBERS, RenderCameraCull, SPANS, SPANS_FLAG, SPANS_MARKER, SPAN_COUNT, SPAN_NAMES, STARTUP_COMPILE_BUDGET_MS, STARTUP_OFFSCREEN_BYTES_MARKER, STARTUP_STABLE_WINDOW_MS, STARTUP_STALL_MS, STATIC_TRANSFORM_MARKER, SkinnedBatch, SpanRecorder, StartupReadiness, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_MOVER_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, addInSlices, addSpan, advanceWriteEpoch, alwaysRender, animationPacketField, animationPacketMethodsPristine, animationPacketReaders, animationPacketTime, animationPacketTimeReaders, animationRateStates, autoBatchOf, baseColorOf, beginSpan, clipLadder, composeSilencedByFreeze, createAssetLoader, createProjectionScanWorkspace, currentWriteEpoch, displacesVertices, drainMeshPool, dropPooledFor, endSpan, formatSpansWindow, geometryVersionSum, hasMorphAttributes, hasRenderHook, invalidateStatic, isAutoBatchMerged, isLight, isRenderable, isSimilarityTransform, isStatic, loadAll, markStatic, measureStartupOffscreenBytes, mergeByMaterial, mergeParts, observeAnimationRates, parkMesh, pooledCapacity, pooledMesh, prepareSceneEnvironment, reconcileMirroredClips, refreshStaticTransforms, releaseProjectionScanWorkspace, resetStaticTransforms, resolveTargetFps, scanProjection, sceneNeedsEnvironmentPreparation, setSpanRecorder, snapRefreshRate, spanNow, spanRecorder, spansRequested, staticRoots, staticTransformCensus, trackAnimationRate, uniformUnchanged, unmarkStatic, warmUpComputeNodes, warmUpScene, warmUpSceneWithCompletion, worldSilencedByFreeze, yieldToHost };
8968
+ export { ASSET_LATE_MARKER, AutoBatch, DEFAULT_CLIP_EXTENTS, DEFAULT_MAX_LEVEL_RATIO, DEFAULT_TARGET_FPS, DRAW_ARGS_BYTES, DRAW_ARGS_WORDS, INSTANCED_LOD_MAX_PIXEL_ERROR, InstancedBatch, LOCAL_WORDS, MAX_TARGET_FPS, MIN_BATCH_MEMBERS, NO_LOCAL, PLACEMENT_ROWS, PLACEMENT_WORDS, RenderCameraCull, SLOT_NONE, SOURCE_FLOOR, SPANS, SPANS_FLAG, SPANS_MARKER, SPAN_COUNT, SPAN_NAMES, STARTUP_COMPILE_BUDGET_MS, STARTUP_OFFSCREEN_BYTES_MARKER, STARTUP_STABLE_WINDOW_MS, STARTUP_STALL_MS, STATIC_TRANSFORM_MARKER, STORAGE_PLAIN, SkinnedBatch, SpanRecorder, StartupReadiness, TALLY_EVERY, VALIDATE_EVERY, VEC4_WORDS, VIRTUAL_SHADOW_CASTER_LAYER, VIRTUAL_SHADOW_KEY_LAYER, VIRTUAL_SHADOW_MOVER_LAYER, VIRTUAL_SHADOW_SMALL_CASTER_LAYER, VIRTUAL_SHADOW_WIDE_CASTER_LAYER, addInSlices, addRange, addSpan, alwaysRender, animationPacketField, animationPacketMethodsPristine, animationPacketReaders, animationPacketTime, animationPacketTimeReaders, argsWords, autoBatchOf, baseColorOf, batchRecords, beginSpan, clipLadder, composeSilencedByFreeze, createAssetLoader, createProjectionScanWorkspace, displacesVertices, drainMeshPool, drawWorld, dropPooledFor, endSliceFrames, endSpan, fetchAsset, formatSpansWindow, frustumPlanes, geometryVersionSum, growBuffer, hasMorphAttributes, hasRenderHook, invalidateStatic, isAutoBatchMerged, isLight, isRenderable, isSimilarityTransform, isStatic, loadAll, markEngineStatic, markStatic, measureStartupOffscreenBytes, mergeByMaterial, mergeParts, nodes, noteSliceFrame, observeAnimationRates, parkMesh, placedBox, pooledCapacity, pooledMesh, prepareSceneEnvironment, reconcileMirroredClips, refreshStaticTransforms, releaseProjectionScanWorkspace, rendererFacts, reportUnusedModelsLater, resetStaticTransforms, resolveTargetFps, scanProjection, sceneNeedsEnvironmentPreparation, setSpanRecorder, snapRefreshRate, spanNow, spanRecorder, spansRequested, staticRoots, staticTransformCensus, storageAttribute, trackAnimationRate, uniformUnchanged, unmarkStatic, untrackAnimationRate, warmUpComputeNodes, warmUpScene, warmUpSceneWithCompletion, worldSilencedByFreeze, yieldToHost };