@threenative/core 0.3.12 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +746 -32
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-4SRAQFTU.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-DIPIJICH.js} +1590 -375
  7. package/dist/{chunk-OKXUCASC.js → chunk-EEABDLUC.js} +3 -4
  8. package/dist/{chunk-5O73CDMR.js → chunk-EFWZWLPY.js} +62 -16
  9. package/dist/{chunk-N5LRP4BR.js → chunk-GYUZJQ7U.js} +63 -3
  10. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  11. package/dist/{chunk-2Z44XSI2.js → chunk-SV4QVUTQ.js} +3 -7
  12. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  13. package/dist/chunk-VP43GIWW.js +18 -0
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +289 -1034
  20. package/dist/index.js +3096 -1305
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BYqKGAwo.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +269 -15
  33. package/dist/world.js +1372 -628
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +105 -7
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/src/animation-batch.ts +193 -0
  39. package/src/animation-layers.ts +7 -3
  40. package/src/animation.ts +209 -29
  41. package/src/asset-cache.ts +3 -3
  42. package/src/asset-memo.ts +202 -0
  43. package/src/assets.ts +436 -131
  44. package/src/auto-batch.ts +190 -44
  45. package/src/compute-driven.ts +1 -1
  46. package/src/config.ts +8 -0
  47. package/src/debug.ts +103 -22
  48. package/src/dev-global.ts +54 -0
  49. package/src/engine-hooks.ts +37 -0
  50. package/src/frame-budget.ts +19 -3
  51. package/src/game-boot-phase.ts +269 -0
  52. package/src/game-dev-tools.ts +7 -14
  53. package/src/game-frame-loop.ts +45 -82
  54. package/src/game-startup.ts +145 -70
  55. package/src/game-ui.ts +84 -0
  56. package/src/game.ts +168 -552
  57. package/src/gamepad-mappings.ts +269 -0
  58. package/src/generated/console-markers.ts +13 -0
  59. package/src/geometry-capture.ts +28 -4
  60. package/src/gpu-readings.ts +98 -0
  61. package/src/gpu-scene-bvh.ts +149 -36
  62. package/src/hot.ts +4 -7
  63. package/src/index.ts +115 -8
  64. package/src/input.ts +237 -25
  65. package/src/instanced-batch-lod.ts +3 -8
  66. package/src/interpolation.ts +171 -40
  67. package/src/look/ao-admission.ts +4 -3
  68. package/src/look/auto-exposure.ts +5 -16
  69. package/src/look/default-tone-mapping.ts +41 -5
  70. package/src/look/local-exposure.ts +2 -7
  71. package/src/look/quad-pass.ts +21 -0
  72. package/src/look/quality.ts +4 -0
  73. package/src/look/unreal-bloom.ts +4 -13
  74. package/src/look/world-environment.ts +58 -115
  75. package/src/merge-parts.ts +20 -24
  76. package/src/model-lod.ts +97 -14
  77. package/src/particle-significance.ts +12 -0
  78. package/src/particles.ts +19 -10
  79. package/src/platform.ts +23 -4
  80. package/src/profiling/FrameStages.ts +5 -6
  81. package/src/profiling/Spans.ts +3 -17
  82. package/src/profiling/debug-telemetry.ts +2 -6
  83. package/src/profiling/render-list-validate.ts +6 -15
  84. package/src/projection-marker.ts +2 -1
  85. package/src/quiet-markers.ts +3 -10
  86. package/src/render/cpu-bvh.ts +100 -0
  87. package/src/render/depth-pyramid.ts +6 -14
  88. package/src/render/environment/environmentContribution.ts +202 -0
  89. package/src/render/environment/environmentRadiance.ts +44 -0
  90. package/src/render/environment/environmentSampleCache.ts +56 -0
  91. package/src/render/environment/environmentSampling.ts +201 -0
  92. package/src/render/environment/environmentSnapshot.ts +71 -0
  93. package/src/render/environment/gate.ts +57 -0
  94. package/src/render/mesh-pool.ts +3 -19
  95. package/src/render/probe-trace.ts +872 -0
  96. package/src/render/probe-volume.ts +780 -34
  97. package/src/render/radiance-cache.ts +17 -0
  98. package/src/render/virtual-shadow-partial.ts +13 -0
  99. package/src/render/virtual-shadow.ts +18 -16
  100. package/src/render/world-impostor-surface.ts +109 -6
  101. package/src/render/world-impostor.ts +5 -2
  102. package/src/render-camera-cull.ts +98 -3
  103. package/src/render-environment.ts +41 -0
  104. package/src/renderer-config.ts +36 -0
  105. package/src/renderer-facts.ts +37 -0
  106. package/src/renderer.ts +52 -28
  107. package/src/resolution-scaler.ts +3 -2
  108. package/src/scene-entry-inspectors.ts +61 -0
  109. package/src/snow-field.ts +1 -0
  110. package/src/startup-offscreen-bytes.ts +78 -0
  111. package/src/static-transform.ts +25 -19
  112. package/src/streamed-textures.ts +112 -0
  113. package/src/streaming.ts +68 -4
  114. package/src/texture-streaming.ts +331 -0
  115. package/src/version.ts +1 -1
  116. package/src/worker.ts +12 -2
  117. package/src/world-bundle-safety.ts +55 -10
  118. package/src/world-cell-batches.ts +162 -200
  119. package/src/world-cell-chunks.ts +3 -7
  120. package/src/world-cell-impostors.ts +20 -8
  121. package/src/world-cell-options.ts +2 -14
  122. package/src/world-cell-placements.ts +194 -90
  123. package/src/world-cell-prewarm.ts +39 -4
  124. package/src/world-cell-records.ts +401 -0
  125. package/src/world-cell-render-bundles.ts +2 -2
  126. package/src/world-cell-render-gpu-dress.ts +13 -17
  127. package/src/world-cell-render-main-cull.ts +73 -17
  128. package/src/world-cell-render-util.ts +17 -4
  129. package/src/world-cell-render.ts +13 -5
  130. package/src/world-cell-residency.ts +15 -6
  131. package/src/world-cell-stale.ts +238 -0
  132. package/src/world-cells.ts +22 -5
  133. package/src/world-gpu-flags.ts +18 -50
  134. package/src/world-gpu-reference.ts +22 -8
  135. package/src/world-gpu-scene.ts +44 -24
  136. package/src/world-gpu-shadow.ts +21 -8
  137. package/src/world-gpu-types.ts +41 -13
  138. package/src/world-load-limiter.ts +5 -0
  139. package/src/world-model-sections.ts +80 -0
  140. package/src/world-river-ribbon.ts +282 -0
  141. package/src/world-root-frame.ts +39 -0
  142. package/src/world-shore-field.ts +91 -0
  143. package/src/world-static-pose.ts +163 -0
  144. package/src/world-surface-sampler.ts +48 -0
  145. package/src/world-terrain-splat.ts +10 -18
  146. package/src/world-tile-budget.ts +4 -11
  147. package/src/world-tiles.ts +79 -12
  148. package/src/world-validate.ts +6 -14
  149. package/src/world-warm.ts +51 -0
  150. package/src/world.ts +13 -0
@@ -1,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-EFWZWLPY.js';
2
+ import { debugRequested, countDebug, readLaunchFlag, measureDebug } from './chunk-GYUZJQ7U.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,42 @@ 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.";
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]) => ({ bytes: asset.bytes ?? 0, path })).sort((a, b) => b.bytes - a.bytes);
872
+ if (files.length === 0) return void 0;
873
+ return {
874
+ bytes: files.reduce((sum, file) => sum + file.bytes, 0),
875
+ files,
876
+ fix: ASSET_UNUSED_FIX,
877
+ sinceRevealMs
878
+ };
879
+ }
880
+ function reportUnusedModelsLater(awaited, root, gone) {
881
+ const timer = setTimeout(() => {
882
+ if (gone()) return;
883
+ try {
884
+ const unused = measureUnusedModels(awaited, root, ASSET_UNUSED_AFTER_MS);
885
+ if (unused !== void 0) console.warn(`${ASSET_UNUSED_MARKER}:${JSON.stringify(unused)}`);
886
+ } catch (error) {
887
+ console.warn(
888
+ `${ASSET_UNUSED_MARKER}_FAILED: ${error instanceof Error ? error.message : String(error)}`
889
+ );
890
+ }
891
+ }, ASSET_UNUSED_AFTER_MS);
892
+ return () => clearTimeout(timer);
893
+ }
870
894
 
871
895
  // src/auto-batch.ts
872
896
  var AUTO_BATCH_MARKER = "TN_AUTO_BATCH";
@@ -945,6 +969,41 @@ function stampMatches(object2, stamp) {
945
969
  for (let at = 0; at < SNAPSHOT_LENGTH; at += 1) if (scratch[at] !== stamp[at]) return false;
946
970
  return true;
947
971
  }
972
+ var ownLayers = /* @__PURE__ */ new WeakMap();
973
+ var drawingWorld = 0;
974
+ function drawWorld(draw) {
975
+ drawingWorld += 1;
976
+ try {
977
+ return draw();
978
+ } finally {
979
+ drawingWorld -= 1;
980
+ }
981
+ }
982
+ function setBatchHidden(mesh, hidden) {
983
+ const engine = mesh;
984
+ if ("__tnBatchHidden" in engine) {
985
+ engine.__tnBatchHidden = hidden;
986
+ return;
987
+ }
988
+ if (!hidden) {
989
+ const own2 = ownLayers.get(mesh);
990
+ if (own2 !== void 0) mesh.layers = own2;
991
+ ownLayers.delete(mesh);
992
+ return;
993
+ }
994
+ if (ownLayers.has(mesh)) return;
995
+ const own = mesh.layers;
996
+ ownLayers.set(mesh, own);
997
+ mesh.layers = Object.create(Object.getPrototypeOf(own), {
998
+ mask: {
999
+ get: () => own.mask,
1000
+ set: (mask) => {
1001
+ own.mask = mask;
1002
+ }
1003
+ },
1004
+ test: { value: (layers) => drawingWorld === 0 && own.test(layers) }
1005
+ });
1006
+ }
948
1007
  function isMesh(object2) {
949
1008
  return object2.isMesh === true;
950
1009
  }
@@ -968,7 +1027,7 @@ function bakeable(geometry) {
968
1027
  return true;
969
1028
  }
970
1029
  function mergeable(mesh) {
971
- return plainDraw(mesh) && bakeable(mesh.geometry) && mesh.matrixWorld.determinant() > 0;
1030
+ return plainDraw(mesh) && bakeable(mesh.geometry) && !isStreamedGeometry(mesh.geometry) && mesh.matrixWorld.determinant() > 0;
972
1031
  }
973
1032
  function flagKey(mesh) {
974
1033
  const { geometry } = mesh;
@@ -1010,6 +1069,8 @@ var AutoBatch = class {
1010
1069
  #excluded = /* @__PURE__ */ new WeakSet();
1011
1070
  #records = [];
1012
1071
  #ancestors = /* @__PURE__ */ new Map();
1072
+ /** The ancestors in the order the engine's guard watches them, so its indices name them. */
1073
+ #watchedAncestors = [];
1013
1074
  #watched = /* @__PURE__ */ new Map();
1014
1075
  #state = "idle";
1015
1076
  #known = Number.NaN;
@@ -1036,12 +1097,24 @@ var AutoBatch = class {
1036
1097
  #levelOne = /* @__PURE__ */ new Set();
1037
1098
  /** Children added to or removed from the scene since the last frame, to start or stop counting. */
1038
1099
  #arrived = [];
1100
+ /**
1101
+ * The subtrees a scan walks: what was added at the top two levels since the last finished scan, plus what an
1102
+ * earlier scan could not merge yet (a hidden subtree, a mesh that moved while watched, a mesh with no partner).
1103
+ * A scan costs what arrived and what still waits, never the scene: ten thrown objects a second re-walked the
1104
+ * stress lab's 5,000 nodes after every add and every remove, 4.1 ms of a 9.8 ms frame.
1105
+ * ponytail: a mesh with no partner is walked by every scan; index those by material when a scene holds thousands.
1106
+ */
1107
+ #pending = /* @__PURE__ */ new Set();
1108
+ /** What the scan in progress met and left for the next one: hidden subtrees. */
1109
+ #later = /* @__PURE__ */ new Set();
1039
1110
  #onTopChild = (event) => {
1040
1111
  this.#shapeChanges += 1;
1041
1112
  this.#arrived.push(event.child);
1113
+ if (event.type === "childadded") this.#pending.add(event.child);
1042
1114
  };
1043
- #onChild = () => {
1115
+ #onChild = (event) => {
1044
1116
  this.#shapeChanges += 1;
1117
+ if (event.type === "childadded") this.#pending.add(event.child);
1045
1118
  };
1046
1119
  constructor(scene, options = {}) {
1047
1120
  this.#scene = scene;
@@ -1055,6 +1128,7 @@ var AutoBatch = class {
1055
1128
  scene.addEventListener("childadded", this.#onTopChild);
1056
1129
  scene.addEventListener("childremoved", this.#onTopChild);
1057
1130
  this.#arrived = [...scene.children];
1131
+ this.#pending = new Set(this.#arrived);
1058
1132
  }
1059
1133
  get census() {
1060
1134
  return {
@@ -1101,6 +1175,7 @@ var AutoBatch = class {
1101
1175
  this.#state = "watching";
1102
1176
  this.#frames = 0;
1103
1177
  if (this.#watched.size < 2) {
1178
+ this.#finish(this.#watched);
1104
1179
  this.#known = shape;
1105
1180
  this.#state = "idle";
1106
1181
  }
@@ -1117,6 +1192,7 @@ var AutoBatch = class {
1117
1192
  if (!this.#enabled) return;
1118
1193
  const meshes = this.#snapshot();
1119
1194
  if (meshes.size >= 2) this.#merge([...meshes.keys()]);
1195
+ this.#finish(meshes);
1120
1196
  this.#watchEngine();
1121
1197
  this.#known = this.#shape();
1122
1198
  this.#state = "idle";
@@ -1125,11 +1201,12 @@ var AutoBatch = class {
1125
1201
  reset() {
1126
1202
  for (const record of this.#records) if (!record.out) this.#giveBack(record);
1127
1203
  this.#records = [];
1128
- this.#watchEngine();
1129
1204
  this.#ancestors.clear();
1205
+ this.#watchEngine();
1130
1206
  this.#watched.clear();
1131
1207
  this.#state = "idle";
1132
1208
  this.#known = Number.NaN;
1209
+ this.#pending = new Set(this.#scene.children);
1133
1210
  }
1134
1211
  /**
1135
1212
  * Changes when something is added to or removed from the scene's top two levels. three's own graph
@@ -1153,47 +1230,80 @@ var AutoBatch = class {
1153
1230
  return this.#shapeChanges;
1154
1231
  }
1155
1232
  /**
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.
1233
+ * Eligible meshes under the pending subtrees, with the world matrix they were drawn at. Runs only while
1234
+ * the scene settles, so its reads are no game's steady cost and the bridge census leaves them out.
1158
1235
  */
1159
1236
  #snapshot() {
1160
1237
  return unbilled(() => {
1161
- this.#scene.updateMatrixWorld(true);
1162
1238
  const found = /* @__PURE__ */ new Map();
1163
1239
  this.#optedOut = 0;
1164
1240
  this.#held = 0;
1241
+ this.#later = /* @__PURE__ */ new Set();
1165
1242
  const held = heldObjects(this.#entities);
1166
- this.#walk(this.#scene, false, held, (mesh) => {
1243
+ const visit = (mesh) => {
1167
1244
  found.set(mesh, Float64Array.from(mesh.matrixWorld.elements));
1168
- });
1245
+ };
1246
+ for (const root of [...this.#pending]) {
1247
+ const off = this.#hangs(root, held);
1248
+ if (off === "gone") this.#pending.delete(root);
1249
+ else if (off === "wait") this.#later.add(root);
1250
+ else {
1251
+ root.updateWorldMatrix(true, true);
1252
+ this.#visit(root, off, held, visit);
1253
+ }
1254
+ }
1169
1255
  return found;
1170
1256
  });
1171
1257
  }
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);
1258
+ /**
1259
+ * How a pending subtree hangs under the scene. `gone`: it left the scene, or a pending ancestor walks it.
1260
+ * `wait`: an ancestor is hidden, held or an LOD, which the game can change. Else whether an ancestor opted it out.
1261
+ */
1262
+ #hangs(root, held) {
1263
+ let off = false;
1264
+ let wait = false;
1265
+ for (let node = root.parent; node !== this.#scene; node = node.parent) {
1266
+ if (node === null || this.#excluded.has(node) || this.#pending.has(node)) return "gone";
1267
+ wait ||= !node.visible || node.isLOD === true || held.has(node);
1268
+ off ||= node.userData.batch === "off";
1269
+ }
1270
+ return wait ? "wait" : off;
1271
+ }
1272
+ /**
1273
+ * Ends a scan: the next one walks what this one left (`#later`) and each mesh it found that no merge took.
1274
+ * A mesh that moved can come to rest, and a mesh with no partner can get one.
1275
+ */
1276
+ #finish(found) {
1277
+ this.#pending = this.#later;
1278
+ this.#later = /* @__PURE__ */ new Set();
1279
+ for (const mesh of found.keys()) if (!sourceGroups.has(mesh)) this.#pending.add(mesh);
1280
+ }
1281
+ #visit(child, off, held, visit) {
1282
+ if (!child.visible) {
1283
+ this.#later.add(child);
1284
+ return;
1285
+ }
1286
+ if (this.#excluded.has(child) || child.isLOD === true) return;
1287
+ if (held.has(child)) {
1288
+ const parts = countMeshes(child);
1289
+ if (parts <= HELD_SUBTREE_MAX_MESHES) {
1290
+ this.#held += parts;
1291
+ return;
1187
1292
  }
1188
- this.#walk(child, skip, held, visit);
1189
1293
  }
1294
+ const skip = off || child.userData.batch === "off";
1295
+ if (isMesh(child) && !sourceGroups.has(child) && mergeable(child)) {
1296
+ if (skip) this.#optedOut += 1;
1297
+ else visit(child);
1298
+ }
1299
+ for (const part of child.children) this.#visit(part, skip, held, visit);
1190
1300
  }
1191
1301
  #settle() {
1192
1302
  const before = this.#watched;
1193
1303
  const stable = /* @__PURE__ */ new Map();
1194
- const now2 = this.#snapshot();
1304
+ const now3 = this.#snapshot();
1195
1305
  let moved = 0;
1196
- for (const [mesh, matrix2] of now2) {
1306
+ for (const [mesh, matrix2] of now3) {
1197
1307
  const earlier = before.get(mesh);
1198
1308
  if (earlier !== void 0 && matrix2.every((value, at) => value === earlier[at]))
1199
1309
  stable.set(mesh, matrix2);
@@ -1202,6 +1312,7 @@ var AutoBatch = class {
1202
1312
  this.#unsettled = moved;
1203
1313
  this.#watched = /* @__PURE__ */ new Map();
1204
1314
  this.#merge([...stable.keys()]);
1315
+ this.#finish(now3);
1205
1316
  this.#watchEngine();
1206
1317
  this.#known = this.#shape();
1207
1318
  this.#state = "idle";
@@ -1275,7 +1386,7 @@ var AutoBatch = class {
1275
1386
  out: false
1276
1387
  };
1277
1388
  vertexStart += vertexCount;
1278
- mesh.visible = false;
1389
+ setBatchHidden(mesh, true);
1279
1390
  writeStamp(mesh, record.stamp);
1280
1391
  group.sources.push(record);
1281
1392
  sourceGroups.set(mesh, group);
@@ -1317,15 +1428,32 @@ var AutoBatch = class {
1317
1428
  /** Every frame, because there are few ancestors and one moved parent changes thousands of sources. */
1318
1429
  #checkAncestors() {
1319
1430
  let given = 0;
1431
+ const engine = this.#engine;
1432
+ if (engine?.__tnGuardCheckAncestors !== void 0) {
1433
+ const changed = engine.__tnGuardCheckAncestors();
1434
+ for (let at = 0; at < changed.length; at += 1) {
1435
+ const node = this.#watchedAncestors[changed[at]];
1436
+ if (node !== void 0) given += this.#giveBackUnder(node);
1437
+ }
1438
+ return given;
1439
+ }
1320
1440
  for (const [node, entry] of this.#ancestors) {
1321
1441
  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
- }
1442
+ given += this.#giveBackUnder(node);
1443
+ }
1444
+ return given;
1445
+ }
1446
+ /** An ancestor moved: it never merges again, and every source under it goes back to the game. */
1447
+ #giveBackUnder(node) {
1448
+ const entry = this.#ancestors.get(node);
1449
+ if (entry === void 0) return 0;
1450
+ let given = 0;
1451
+ this.#excluded.add(node);
1452
+ this.#ancestors.delete(node);
1453
+ for (const record of entry.records) {
1454
+ if (record.out) continue;
1455
+ this.#giveBack(record);
1456
+ given += 1;
1329
1457
  }
1330
1458
  return given;
1331
1459
  }
@@ -1334,7 +1462,12 @@ var AutoBatch = class {
1334
1462
  * and each give-back, so no game code runs between the state merged and the state watched.
1335
1463
  */
1336
1464
  #watchEngine() {
1337
- this.#engine?.__tnGuardWatch(this.#records.map((record) => record.mesh));
1465
+ if (this.#engine === void 0) return;
1466
+ this.#watchedAncestors = [...this.#ancestors.keys()];
1467
+ this.#engine.__tnGuardWatch(
1468
+ this.#records.map((record) => record.mesh),
1469
+ this.#watchedAncestors
1470
+ );
1338
1471
  }
1339
1472
  /** A slice of the sources bounded by {@link GUARD_BUDGET_MS}, or all of them under `everyFrame`. */
1340
1473
  #checkSources(started) {
@@ -1392,7 +1525,7 @@ var AutoBatch = class {
1392
1525
  this.#excluded.add(record.mesh);
1393
1526
  this.#restored += 1;
1394
1527
  this.#meshes -= 1;
1395
- record.mesh.visible = true;
1528
+ setBatchHidden(record.mesh, false);
1396
1529
  const { group } = record;
1397
1530
  group.live -= 1;
1398
1531
  if (group.live > 0) this.#collapse(record);
@@ -3724,12 +3857,38 @@ var RATE_HOLD_RIGS = 32;
3724
3857
  var RATE_MEASURE_FRAMES = 4;
3725
3858
  var animationRateRootRefs = /* @__PURE__ */ new WeakMap();
3726
3859
  var animationRateCarriers = /* @__PURE__ */ new Set();
3860
+ function untrackAnimationRate(root, state) {
3861
+ if (animationRateStates.get(root) !== state) return;
3862
+ animationRateStates.delete(root);
3863
+ const id = engineRateIds.get(root);
3864
+ if (id === void 0) return;
3865
+ setEngineRateState(id, void 0);
3866
+ const engineRig = root;
3867
+ if (typeof engineRig.__trackAnimationRate === "function") engineRig.__trackAnimationRate(-1);
3868
+ }
3727
3869
  function observeAnimationRates(carrier, sources) {
3728
3870
  if (!animationRateSources.has(carrier)) animationRateCarriers.add(new WeakRef(carrier));
3729
3871
  animationRateSources.set(carrier, sources);
3730
3872
  }
3873
+ var engineRateIds = /* @__PURE__ */ new WeakMap();
3874
+ var engineRateStates = [];
3875
+ var engineRateRigs = 0;
3876
+ function setEngineRateState(id, state) {
3877
+ engineRateRigs += (state === void 0 ? 0 : 1) - (engineRateStates[id] === void 0 ? 0 : 1);
3878
+ engineRateStates[id] = state;
3879
+ }
3731
3880
  function trackAnimationRate(root, state) {
3732
3881
  animationRateStates.set(root, state);
3882
+ const engineRig = root;
3883
+ if (typeof engineRig.__trackAnimationRate === "function") {
3884
+ let id = engineRateIds.get(root);
3885
+ if (id === void 0) {
3886
+ id = engineRateStates.length;
3887
+ engineRateIds.set(root, id);
3888
+ }
3889
+ setEngineRateState(id, state);
3890
+ engineRig.__trackAnimationRate(id);
3891
+ }
3733
3892
  let ref = animationRateRootRefs.get(root);
3734
3893
  if (ref === void 0) {
3735
3894
  ref = new WeakRef(root);
@@ -3752,6 +3911,10 @@ function countEngineCost2(name) {
3752
3911
  host.__tnEngineCost ??= {};
3753
3912
  host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + 1;
3754
3913
  }
3914
+ function engineBandRoot(root) {
3915
+ const candidate = root;
3916
+ return typeof candidate?.__bandAnimation === "function" ? candidate : void 0;
3917
+ }
3755
3918
  function engineCullRoot(root) {
3756
3919
  const candidate = root;
3757
3920
  return typeof candidate?.__cullProjected === "function" && typeof candidate.__restoreCull === "function" ? candidate : void 0;
@@ -3904,7 +4067,7 @@ var RenderCameraCull = class {
3904
4067
  this.#animationFrame += 1;
3905
4068
  this.#animationPrepared = true;
3906
4069
  this.#prepareCamera(camera, viewportHeight);
3907
- if (!this.#prepareAnimated()) return;
4070
+ if (this.#bandOnEngine(root, camera) || !this.#prepareAnimated()) return;
3908
4071
  const rootShown = this.#isVisibleInWorld(root);
3909
4072
  const holds = rootShown && !this.#nestedRigs && animationRateCarriers.size === 0 && animationRateRoots.size >= RATE_HOLD_RIGS;
3910
4073
  let turn = this.#animationFrame;
@@ -3912,8 +4075,8 @@ var RenderCameraCull = class {
3912
4075
  const rig = ref.deref();
3913
4076
  if (rig === void 0 || !this.#reaches(rig, root)) continue;
3914
4077
  turn += 1;
3915
- if (!holds || turn % RATE_MEASURE_FRAMES === 0 || !this.#holdRate(rig))
3916
- this.#visitRig(rig, rootShown);
4078
+ if (holds && turn % RATE_MEASURE_FRAMES !== 0 && this.#holdRate(rig)) continue;
4079
+ this.#visitRig(rig, rootShown);
3917
4080
  }
3918
4081
  for (const ref of animationRateCarriers) {
3919
4082
  const carrier = ref.deref();
@@ -3928,6 +4091,40 @@ var RenderCameraCull = class {
3928
4091
  if (observes && this.#reaches(carrier, root)) carrier.traverseVisible(this.#animationVisitor);
3929
4092
  }
3930
4093
  }
4094
+ /**
4095
+ * On the engine, with no stand-in observing a rig, the whole pass is one call (PRD-878): the engine keeps the
4096
+ * rigs, checks which reach the root, holds a crowd's rates and bands the rest. False sends the frame to the
4097
+ * walk below: plain three, a stand-in, or a rig inside a rig.
4098
+ */
4099
+ #bandOnEngine(root, camera) {
4100
+ const engine = animationRateCarriers.size === 0 ? engineBandRoot(root) : void 0;
4101
+ if (engine !== void 0 && engineRateRigs === 0) return true;
4102
+ const pairs = engine?.__bandAnimation(
4103
+ camera,
4104
+ this.#cameraResolved,
4105
+ this.#scale,
4106
+ this.#animationFrame
4107
+ );
4108
+ if (pairs === void 0) return false;
4109
+ this.#takeBands(pairs);
4110
+ return true;
4111
+ }
4112
+ /** The engine's [handle, rate] pairs, written to each state as the JS walk writes it; -1 drops a freed rig. */
4113
+ #takeBands(pairs) {
4114
+ for (let index = 0; index + 1 < pairs.length; index += 2) {
4115
+ const id = pairs[index];
4116
+ const rate = pairs[index + 1];
4117
+ if (rate < 0) {
4118
+ setEngineRateState(id, void 0);
4119
+ continue;
4120
+ }
4121
+ const state = engineRateStates[id];
4122
+ if (state === void 0) continue;
4123
+ state.rate = rate;
4124
+ state.source = this;
4125
+ state.frame = this.#animationFrame;
4126
+ }
4127
+ }
3931
4128
  /** 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
4129
  #holdRate(rig) {
3933
4130
  const state = animationRateStates.get(rig);
@@ -4185,12 +4382,12 @@ var RenderCameraCull = class {
4185
4382
  union[3] = z;
4186
4383
  union[4] = radius;
4187
4384
  } else {
4188
- const grown = (distance + ur + radius) / 2;
4189
- const shift = (grown - ur) / distance;
4385
+ const grown2 = (distance + ur + radius) / 2;
4386
+ const shift = (grown2 - ur) / distance;
4190
4387
  union[1] = ux + (x - ux) * shift;
4191
4388
  union[2] = uy + (y - uy) * shift;
4192
4389
  union[3] = uz + (z - uz) * shift;
4193
- union[4] = grown;
4390
+ union[4] = grown2;
4194
4391
  }
4195
4392
  }
4196
4393
  }
@@ -4788,6 +4985,150 @@ function createAssetCache(options = {}) {
4788
4985
  }
4789
4986
  };
4790
4987
  }
4988
+
4989
+ // src/asset-memo.ts
4990
+ var KINDS = {
4991
+ Float32Array,
4992
+ Float64Array,
4993
+ Int16Array,
4994
+ Int32Array,
4995
+ Int8Array,
4996
+ Uint16Array,
4997
+ Uint32Array,
4998
+ Uint8Array,
4999
+ Uint8ClampedArray
5000
+ };
5001
+ var BUILD_ID_GLOBAL = "__TN_BUILD_ID__";
5002
+ var MEMO_CACHE = "threenative-memo";
5003
+ var MEMO_ORIGIN = "https://memo.threenative.invalid/";
5004
+ var MAGIC = 1330466388;
5005
+ function invalid(detail) {
5006
+ return new Error(`TN_ASSET_MEMO_INVALID: ${detail}`);
5007
+ }
5008
+ function kindOf(value) {
5009
+ for (const kind of Object.keys(KINDS)) if (value instanceof KINDS[kind]) return kind;
5010
+ return void 0;
5011
+ }
5012
+ function encodeMemo(value) {
5013
+ const entries = Object.entries(value).map(([name, array]) => {
5014
+ const kind = kindOf(array);
5015
+ if (kind === void 0) throw invalid(`"${name}" is not a typed array.`);
5016
+ return { array, kind, name };
5017
+ });
5018
+ const align = (n) => Math.ceil(n / 8) * 8;
5019
+ const header = new TextEncoder().encode(
5020
+ JSON.stringify(entries.map(({ array, kind, name }) => ({ kind, length: array.length, name })))
5021
+ );
5022
+ let offset = align(8 + header.byteLength);
5023
+ const placed = entries.map((entry) => {
5024
+ const at = offset;
5025
+ offset = align(at + entry.array.byteLength);
5026
+ return { ...entry, at };
5027
+ });
5028
+ const buffer = new ArrayBuffer(offset);
5029
+ const view = new DataView(buffer);
5030
+ view.setUint32(0, MAGIC, true);
5031
+ view.setUint32(4, header.byteLength, true);
5032
+ new Uint8Array(buffer, 8, header.byteLength).set(header);
5033
+ for (const { array, at } of placed)
5034
+ new Uint8Array(buffer, at, array.byteLength).set(
5035
+ new Uint8Array(array.buffer, array.byteOffset, array.byteLength)
5036
+ );
5037
+ return buffer;
5038
+ }
5039
+ function decodeMemo(buffer) {
5040
+ const view = new DataView(buffer);
5041
+ if (buffer.byteLength < 8 || view.getUint32(0, true) !== MAGIC)
5042
+ throw invalid("stored entry is not a memo.");
5043
+ const headerBytes = view.getUint32(4, true);
5044
+ if (8 + headerBytes > buffer.byteLength) throw invalid("stored entry is truncated.");
5045
+ const header = JSON.parse(
5046
+ new TextDecoder().decode(new Uint8Array(buffer, 8, headerBytes))
5047
+ );
5048
+ if (!Array.isArray(header)) throw invalid("stored entry has no array list.");
5049
+ const result = {};
5050
+ let offset = Math.ceil((8 + headerBytes) / 8) * 8;
5051
+ for (const entry of header) {
5052
+ const kind = entry.kind;
5053
+ const Ctor = KINDS[kind];
5054
+ if (Ctor === void 0 || typeof entry.name !== "string" || !Number.isInteger(entry.length))
5055
+ throw invalid("stored entry has a malformed array.");
5056
+ const length = entry.length;
5057
+ const bytes = length * Ctor.BYTES_PER_ELEMENT;
5058
+ if (offset + bytes > buffer.byteLength) throw invalid("stored entry is truncated.");
5059
+ result[entry.name] = new Ctor(buffer, offset, length);
5060
+ offset = Math.ceil((offset + bytes) / 8) * 8;
5061
+ }
5062
+ return result;
5063
+ }
5064
+ function report(fields) {
5065
+ console.info(`TN_ASSET_MEMO:${JSON.stringify(fields)}`);
5066
+ }
5067
+ function now() {
5068
+ return globalThis.performance?.now() ?? Date.now();
5069
+ }
5070
+ function createAssetMemo(namespace) {
5071
+ const storage2 = cacheStorage();
5072
+ const id = globalThis[BUILD_ID_GLOBAL];
5073
+ const buildId = typeof id === "string" && id !== "" ? id : void 0;
5074
+ 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;
5075
+ const prefix = buildId === void 0 ? "" : `${MEMO_ORIGIN}${encodeURIComponent(buildId)}/`;
5076
+ const name = `${MEMO_CACHE}-${manifestFingerprint([{ url: namespace }]).slice(0, 8)}`;
5077
+ let opened;
5078
+ const open = () => {
5079
+ opened ??= (async () => {
5080
+ const cache2 = await storage2?.open(name);
5081
+ if (cache2 === void 0) return void 0;
5082
+ for (const request of await cache2.keys())
5083
+ if (!request.url.startsWith(prefix)) await cache2.delete(request.url);
5084
+ return cache2;
5085
+ })().catch(() => void 0);
5086
+ return opened;
5087
+ };
5088
+ const checked = (key, value) => {
5089
+ if (typeof value !== "object" || value === null)
5090
+ throw invalid(`build for "${key}" returned no object.`);
5091
+ for (const [field, array] of Object.entries(value))
5092
+ if (kindOf(array) === void 0)
5093
+ throw invalid(`build for "${key}" returned "${field}", not a typed array.`);
5094
+ return value;
5095
+ };
5096
+ return async (key, build) => {
5097
+ if (typeof key !== "string" || key === "") throw invalid("key must be a non-empty string.");
5098
+ const started = now();
5099
+ if (reason !== void 0) {
5100
+ const value2 = checked(key, await build());
5101
+ report({ key, hit: false, ms: Math.round(now() - started), reason });
5102
+ return value2;
5103
+ }
5104
+ const url = `${prefix}${encodeURIComponent(key)}`;
5105
+ const cache2 = await open();
5106
+ if (cache2 !== void 0) {
5107
+ try {
5108
+ const stored = await cache2.match(url);
5109
+ if (stored !== void 0) {
5110
+ const buffer = await stored.arrayBuffer();
5111
+ const value2 = decodeMemo(buffer);
5112
+ report({ bytes: buffer.byteLength, hit: true, key, ms: Math.round(now() - started) });
5113
+ return value2;
5114
+ }
5115
+ } catch {
5116
+ await cache2.delete(url).catch(() => void 0);
5117
+ }
5118
+ }
5119
+ const value = checked(key, await build());
5120
+ const encoded = encodeMemo(value);
5121
+ const builtMs = Math.round(now() - started);
5122
+ if (cache2 === void 0) {
5123
+ report({ hit: false, key, ms: builtMs, reason: "cache storage refused to open" });
5124
+ return value;
5125
+ }
5126
+ void cache2.put(url, new Response(encoded)).then(() => report({ bytes: encoded.byteLength, hit: false, key, ms: builtMs, stored: true })).catch(
5127
+ (error) => report({ hit: false, key, ms: builtMs, stored: false, reason: String(error) })
5128
+ );
5129
+ return value;
5130
+ };
5131
+ }
4791
5132
  var INSTANCED_LOD_MAX_PIXEL_ERROR = 4;
4792
5133
  function spatialPartitions(mesh) {
4793
5134
  const limit = Math.ceil(Math.sqrt(mesh.count));
@@ -4940,12 +5281,7 @@ function attachInstancedLod(mesh, options) {
4940
5281
  mesh.getMatrixAt(index, matrix2);
4941
5282
  world.multiplyMatrices(mesh.matrixWorld, matrix2);
4942
5283
  sphere.copy(local).applyMatrix4(world);
4943
- const view = conservativeViewDepth(
4944
- camera,
4945
- sphere.center,
4946
- sphere.radius,
4947
- camera.near ?? 0
4948
- );
5284
+ const view = selectLodFor(camera, sphere, camera.near ?? 0);
4949
5285
  let level = 0;
4950
5286
  if (options.lods !== void 0) {
4951
5287
  const distance = biasedLodDistance(cameraPosition.distanceTo(sphere.center));
@@ -4962,7 +5298,7 @@ function attachInstancedLod(mesh, options) {
4962
5298
  {
4963
5299
  camera,
4964
5300
  viewportHeight,
4965
- depth: biasedLodDistance(view.depth),
5301
+ depth: view.biased,
4966
5302
  degenerate: view.degenerate
4967
5303
  }
4968
5304
  ]
@@ -5011,7 +5347,334 @@ function attachInstancedLod(mesh, options) {
5011
5347
  mesh.addEventListener("dispose", () => controller.release());
5012
5348
  }
5013
5349
 
5350
+ // src/streamed-textures.ts
5351
+ var TEXTURE_SLOTS = [
5352
+ "map",
5353
+ "normalMap",
5354
+ "roughnessMap",
5355
+ "metalnessMap",
5356
+ "aoMap",
5357
+ "emissiveMap",
5358
+ "alphaMap",
5359
+ "bumpMap",
5360
+ "lightMap",
5361
+ "displacementMap",
5362
+ "clearcoatMap",
5363
+ "clearcoatNormalMap",
5364
+ "clearcoatRoughnessMap",
5365
+ "sheenColorMap",
5366
+ "sheenRoughnessMap",
5367
+ "transmissionMap",
5368
+ "thicknessMap",
5369
+ "iridescenceMap",
5370
+ "specularColorMap",
5371
+ "specularIntensityMap"
5372
+ ];
5373
+ var CARRIED = [
5374
+ "anisotropy",
5375
+ "wrapS",
5376
+ "wrapT",
5377
+ "magFilter",
5378
+ "minFilter",
5379
+ "colorSpace",
5380
+ "channel",
5381
+ "rotation",
5382
+ "matrixAutoUpdate",
5383
+ "userData"
5384
+ ];
5385
+ var CARRIED_VECTORS = ["offset", "repeat", "center", "matrix"];
5386
+ function carry(from, next) {
5387
+ for (const name of CARRIED) if (name in from) next[name] = from[name];
5388
+ for (const name of CARRIED_VECTORS)
5389
+ next[name]?.copy?.(from[name]);
5390
+ }
5391
+ var materialsOf = (mesh) => [].concat(mesh?.material).filter(Boolean);
5392
+ function streamedTextureUpgrade(coarse) {
5393
+ const loaded = coarse.map(
5394
+ (mesh) => materialsOf(mesh).map((material) => TEXTURE_SLOTS.map((name) => material[name]))
5395
+ );
5396
+ return (full, swap) => {
5397
+ const whole = /* @__PURE__ */ new Map();
5398
+ const unused = /* @__PURE__ */ new Set();
5399
+ full.forEach(
5400
+ (mesh, index) => materialsOf(mesh).forEach(
5401
+ (material, slot) => TEXTURE_SLOTS.forEach((name, at) => {
5402
+ const next = material[name];
5403
+ const resident = loaded[index]?.[slot]?.[at];
5404
+ if (!next || next === resident) return;
5405
+ if (swap && resident) whole.set(resident, next);
5406
+ else unused.add(next);
5407
+ })
5408
+ )
5409
+ );
5410
+ const replaced = /* @__PURE__ */ new Set();
5411
+ const taken = /* @__PURE__ */ new Set();
5412
+ let swapped = 0;
5413
+ for (const mesh of whole.size > 0 ? coarse : [])
5414
+ for (const material of materialsOf(mesh)) {
5415
+ let changed = false;
5416
+ for (const name of TEXTURE_SLOTS) {
5417
+ const resident = material[name];
5418
+ const next = resident ? whole.get(resident) : void 0;
5419
+ if (resident === null || resident === void 0 || next === void 0) continue;
5420
+ if (!taken.has(next))
5421
+ carry(resident, next);
5422
+ material[name] = next;
5423
+ replaced.add(resident);
5424
+ taken.add(next);
5425
+ swapped += 1;
5426
+ changed = true;
5427
+ }
5428
+ if (changed) material.needsUpdate = true;
5429
+ }
5430
+ for (const next of whole.values()) unused.add(next);
5431
+ for (const texture of replaced) texture.dispose?.();
5432
+ for (const texture of unused) if (!taken.has(texture)) texture.dispose?.();
5433
+ return swapped;
5434
+ };
5435
+ }
5436
+
5437
+ // src/texture-streaming.ts
5438
+ var KTX2_IDENTIFIER = [
5439
+ 171,
5440
+ 75,
5441
+ 84,
5442
+ 88,
5443
+ 32,
5444
+ 50,
5445
+ 48,
5446
+ 187,
5447
+ 13,
5448
+ 10,
5449
+ 26,
5450
+ 10
5451
+ ];
5452
+ var KTX2_INDEX_BYTES = 80;
5453
+ var KTX2_LEVEL_ENTRY_BYTES = 24;
5454
+ var MAX_SAFE_U64 = BigInt(Number.MAX_SAFE_INTEGER);
5455
+ function headerFailure(reason) {
5456
+ return new Error(`TN_KTX2_HEADER: ${reason}`);
5457
+ }
5458
+ function levelEntryCount(levelCount) {
5459
+ return Number.isFinite(levelCount) ? Math.max(1, Math.trunc(levelCount)) : 1;
5460
+ }
5461
+ function ktx2HeaderBytes(levelCount) {
5462
+ return KTX2_INDEX_BYTES + KTX2_LEVEL_ENTRY_BYTES * levelEntryCount(levelCount);
5463
+ }
5464
+ function readU64(view, offset, field) {
5465
+ const value = view.getBigUint64(offset, true);
5466
+ if (value > MAX_SAFE_U64) {
5467
+ throw headerFailure(`${field} is ${value.toString()}, above Number.MAX_SAFE_INTEGER`);
5468
+ }
5469
+ return Number(value);
5470
+ }
5471
+ function parseKtx2LevelIndex(bytes) {
5472
+ if (bytes.byteLength < KTX2_IDENTIFIER.length) {
5473
+ throw headerFailure(
5474
+ `buffer is ${String(bytes.byteLength)} bytes, too short for the identifier: ${String(KTX2_IDENTIFIER.length)}`
5475
+ );
5476
+ }
5477
+ for (let i = 0; i < KTX2_IDENTIFIER.length; i += 1) {
5478
+ if (bytes[i] !== KTX2_IDENTIFIER[i]) {
5479
+ throw headerFailure(`byte ${String(i)} is not the KTX 2.0 identifier`);
5480
+ }
5481
+ }
5482
+ if (bytes.byteLength < KTX2_INDEX_BYTES) {
5483
+ throw headerFailure(
5484
+ `buffer is ${String(bytes.byteLength)} bytes, too short for the 80-byte header and index`
5485
+ );
5486
+ }
5487
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
5488
+ const levelCount = levelEntryCount(view.getUint32(40, true));
5489
+ const required = ktx2HeaderBytes(levelCount);
5490
+ if (bytes.byteLength < required) {
5491
+ throw headerFailure(
5492
+ `buffer is ${String(bytes.byteLength)} bytes, ${String(levelCount)} level(s) need ${String(required)}`
5493
+ );
5494
+ }
5495
+ const levels = [];
5496
+ for (let level = 0; level < levelCount; level += 1) {
5497
+ const at = KTX2_INDEX_BYTES + level * KTX2_LEVEL_ENTRY_BYTES;
5498
+ levels.push({
5499
+ byteOffset: readU64(view, at, `level ${String(level)} byteOffset`),
5500
+ byteLength: readU64(view, at + 8, `level ${String(level)} byteLength`),
5501
+ uncompressedByteLength: readU64(
5502
+ view,
5503
+ at + 16,
5504
+ `level ${String(level)} uncompressedByteLength`
5505
+ )
5506
+ });
5507
+ }
5508
+ return {
5509
+ vkFormat: view.getUint32(12, true),
5510
+ typeSize: view.getUint32(16, true),
5511
+ pixelWidth: view.getUint32(20, true),
5512
+ pixelHeight: view.getUint32(24, true),
5513
+ pixelDepth: view.getUint32(28, true),
5514
+ layerCount: view.getUint32(32, true),
5515
+ faceCount: view.getUint32(36, true),
5516
+ levelCount,
5517
+ supercompressionScheme: view.getUint32(44, true),
5518
+ sgdByteOffset: readU64(view, 64, "sgdByteOffset"),
5519
+ sgdByteLength: readU64(view, 72, "sgdByteLength"),
5520
+ levels
5521
+ };
5522
+ }
5523
+ var KTX2_PROBE_BYTES = 64 * 1024;
5524
+ var KTX2_TAIL_MAX_PX = 64;
5525
+ var KTX2_LEVEL_ALIGN = 48;
5526
+ var BASISLZ = 1;
5527
+ var BASISLZ_SGD_HEADER_BYTES = 20;
5528
+ var BASISLZ_IMAGE_DESC_BYTES = 20;
5529
+ function alignUp(value, alignment) {
5530
+ return Math.ceil(value / alignment) * alignment;
5531
+ }
5532
+ function trimBasisLzGlobalData(sgd, index, first) {
5533
+ const images = (level) => Math.max(1, index.layerCount) * index.faceCount * Math.max(1, index.pixelDepth >> level);
5534
+ let dropped = 0;
5535
+ for (let level = 0; level < first; level += 1) dropped += images(level);
5536
+ let total = dropped;
5537
+ for (let level = first; level < index.levelCount; level += 1) total += images(level);
5538
+ const descs = BASISLZ_SGD_HEADER_BYTES;
5539
+ const rest = descs + total * BASISLZ_IMAGE_DESC_BYTES;
5540
+ if (sgd.byteLength < rest)
5541
+ throw headerFailure(
5542
+ `BasisLZ global data is ${String(sgd.byteLength)} bytes, ${String(rest)} needed`
5543
+ );
5544
+ const out = new Uint8Array(sgd.byteLength - dropped * BASISLZ_IMAGE_DESC_BYTES);
5545
+ out.set(sgd.subarray(0, descs));
5546
+ out.set(sgd.subarray(descs + dropped * BASISLZ_IMAGE_DESC_BYTES), descs);
5547
+ return out;
5548
+ }
5549
+ function trimmedKtx2(src, index, first) {
5550
+ const view = new DataView(src.buffer, src.byteOffset, src.byteLength);
5551
+ const slice = (offset, length) => {
5552
+ if (offset + length > src.byteLength)
5553
+ throw new Error(
5554
+ `TN_KTX2_HEADER: a section at ${String(offset)}+${String(length)} lies past the ${String(src.byteLength)} bytes read`
5555
+ );
5556
+ return src.subarray(offset, offset + length);
5557
+ };
5558
+ const dfd = slice(view.getUint32(48, true), view.getUint32(52, true));
5559
+ const kvd = slice(view.getUint32(56, true), view.getUint32(60, true));
5560
+ let sgd = slice(index.sgdByteOffset, index.sgdByteLength);
5561
+ if (index.supercompressionScheme === BASISLZ && sgd.byteLength > 0)
5562
+ sgd = trimBasisLzGlobalData(sgd, index, first);
5563
+ const kept = index.levels.slice(first);
5564
+ const dfdAt = ktx2HeaderBytes(kept.length);
5565
+ const kvdAt = dfdAt + dfd.byteLength;
5566
+ const sgdAt = alignUp(kvdAt + kvd.byteLength, 8);
5567
+ const placed = [];
5568
+ let end = sgdAt + sgd.byteLength;
5569
+ for (let i = kept.length - 1; i >= 0; i -= 1) {
5570
+ const at = alignUp(end, KTX2_LEVEL_ALIGN);
5571
+ placed[i] = at;
5572
+ end = at + (kept[i]?.byteLength ?? 0);
5573
+ }
5574
+ const out = new Uint8Array(end);
5575
+ const write = new DataView(out.buffer);
5576
+ out.set(src.subarray(0, 48));
5577
+ write.setUint32(20, Math.max(1, index.pixelWidth >> first), true);
5578
+ if (index.pixelHeight > 0) write.setUint32(24, Math.max(1, index.pixelHeight >> first), true);
5579
+ if (index.pixelDepth > 0) write.setUint32(28, Math.max(1, index.pixelDepth >> first), true);
5580
+ write.setUint32(40, kept.length, true);
5581
+ write.setUint32(48, dfd.byteLength > 0 ? dfdAt : 0, true);
5582
+ write.setUint32(52, dfd.byteLength, true);
5583
+ write.setUint32(56, kvd.byteLength > 0 ? kvdAt : 0, true);
5584
+ write.setUint32(60, kvd.byteLength, true);
5585
+ write.setBigUint64(64, BigInt(sgd.byteLength > 0 ? sgdAt : 0), true);
5586
+ write.setBigUint64(72, BigInt(sgd.byteLength), true);
5587
+ out.set(dfd, dfdAt);
5588
+ out.set(kvd, kvdAt);
5589
+ out.set(sgd, sgdAt);
5590
+ kept.forEach((level, i) => {
5591
+ const at = KTX2_INDEX_BYTES + i * KTX2_LEVEL_ENTRY_BYTES;
5592
+ write.setBigUint64(at, BigInt(placed[i] ?? 0), true);
5593
+ write.setBigUint64(at + 8, BigInt(level.byteLength), true);
5594
+ write.setBigUint64(at + 16, BigInt(level.uncompressedByteLength), true);
5595
+ out.set(slice(level.byteOffset, level.byteLength), placed[i]);
5596
+ });
5597
+ return out;
5598
+ }
5599
+ async function openKtx2Stream(url, fetchRange = (target, init) => fetch(target, init)) {
5600
+ let have = new Uint8Array(0);
5601
+ let ranged = true;
5602
+ let bytesRead = 0;
5603
+ const readTo = async (end) => {
5604
+ if (!ranged || end <= have.byteLength) return;
5605
+ const start = have.byteLength;
5606
+ const response = await fetchRange(url, {
5607
+ headers: { range: `bytes=${String(start)}-${String(end - 1)}` }
5608
+ });
5609
+ if (!response.ok)
5610
+ throw new Error(`TN_KTX2_FETCH: '${url}' answered ${String(response.status)}`);
5611
+ const body = new Uint8Array(await response.arrayBuffer());
5612
+ bytesRead += body.byteLength;
5613
+ if (response.status !== 206) {
5614
+ have = body;
5615
+ ranged = false;
5616
+ return;
5617
+ }
5618
+ const from = /^bytes (\d+)-/u.exec(response.headers.get("content-range") ?? "")?.[1];
5619
+ if (from !== void 0 && Number(from) !== start)
5620
+ throw new Error(
5621
+ `TN_KTX2_FETCH: '${url}' answered bytes from ${from}, ${String(start)} asked`
5622
+ );
5623
+ const next = new Uint8Array(start + body.byteLength);
5624
+ next.set(have);
5625
+ next.set(body, start);
5626
+ have = next;
5627
+ };
5628
+ await readTo(KTX2_PROBE_BYTES);
5629
+ const index = parseKtx2LevelIndex(have);
5630
+ const { levels } = index;
5631
+ const last = levels.length - 1;
5632
+ const levelEnd = (level) => (levels[level]?.byteOffset ?? 0) + (levels[level]?.byteLength ?? 0);
5633
+ const ordered = levels.every(
5634
+ (level, i) => i === last || level.byteOffset > (levels[i + 1]?.byteOffset ?? 0)
5635
+ );
5636
+ if (!ordered) await readTo(Math.max(...levels.map((_, i) => levelEnd(i))));
5637
+ let tail = 1;
5638
+ while (tail < levels.length && Math.max(index.pixelWidth, index.pixelHeight) >> levels.length - 1 - tail <= KTX2_TAIL_MAX_PX)
5639
+ tail += 1;
5640
+ await readTo(levelEnd(levels.length - tail));
5641
+ const resident = () => {
5642
+ if (!ranged) return levels.length;
5643
+ let count = 0;
5644
+ while (count < levels.length && levelEnd(last - count) <= have.byteLength) count += 1;
5645
+ return count;
5646
+ };
5647
+ const file = () => {
5648
+ const count = resident();
5649
+ if (count === 0)
5650
+ throw new Error(
5651
+ `TN_KTX2_FETCH: '${url}' sent ${String(have.byteLength)} bytes, short of its smallest mip level`
5652
+ );
5653
+ return count === levels.length && !ranged ? have : trimmedKtx2(have, index, levels.length - count);
5654
+ };
5655
+ return {
5656
+ index,
5657
+ get residentLevels() {
5658
+ return resident();
5659
+ },
5660
+ get ranged() {
5661
+ return ranged;
5662
+ },
5663
+ get bytesRead() {
5664
+ return bytesRead;
5665
+ },
5666
+ file,
5667
+ want: async (count) => {
5668
+ const target = Math.min(levels.length, Math.max(1, Math.trunc(count)));
5669
+ if (target <= resident()) return void 0;
5670
+ await readTo(levelEnd(levels.length - target));
5671
+ return file();
5672
+ }
5673
+ };
5674
+ }
5675
+
5014
5676
  // src/assets.ts
5677
+ var ASSET_LATE_MARKER = "TN_ASSET_LATE";
5015
5678
  function configuredTexture(texture, options) {
5016
5679
  const copy = texture.clone();
5017
5680
  copy.colorSpace = options.data === true ? NoColorSpace : SRGBColorSpace;
@@ -5316,6 +5979,13 @@ function widenNormalizedScalars(root) {
5316
5979
  }
5317
5980
  });
5318
5981
  }
5982
+ function meshesOf(value) {
5983
+ const meshes = [];
5984
+ modelRoot(value)?.traverse((object2) => {
5985
+ if (object2.isMesh === true) meshes.push(object2);
5986
+ });
5987
+ return meshes;
5988
+ }
5319
5989
  function modelRoot(value) {
5320
5990
  if (typeof value !== "object" || value === null) return void 0;
5321
5991
  const scene = value.scene;
@@ -5384,6 +6054,47 @@ function reconcileMirroredClips(root, clips) {
5384
6054
  function createAssetLoader(options = {}) {
5385
6055
  const debug = debugRequested();
5386
6056
  const basePath = options.basePath ?? "";
6057
+ const streamMeshes = options.streamMeshes !== false;
6058
+ if (!streamMeshes)
6059
+ console.info(
6060
+ "TN_ASSETS_STREAM_MESHES_OFF: assets.streamMeshes is false; every model loads whole."
6061
+ );
6062
+ const streamTextures = options.streamTextures !== false;
6063
+ if (!streamTextures)
6064
+ console.info(
6065
+ "TN_ASSETS_STREAM_TEXTURES_OFF: assets.streamTextures is false; every model texture loads whole."
6066
+ );
6067
+ const pool = { files: 0, fullBytes: 0, ranged: 0, residentBytes: 0, upgraded: 0 };
6068
+ let poolTimer;
6069
+ const reportPool = () => {
6070
+ clearTimeout(poolTimer);
6071
+ poolTimer = setTimeout(() => {
6072
+ poolTimer = void 0;
6073
+ console.info(
6074
+ `TN_STREAMING_POOL ${JSON.stringify({ ...pool, deferredBytes: pool.fullBytes - pool.residentBytes })}`
6075
+ );
6076
+ }, 2e3);
6077
+ };
6078
+ const residentImage = async (url) => {
6079
+ if (!/\.ktx2(?:$|\?)/iu.test(url)) return void 0;
6080
+ const stream = await openKtx2Stream(url);
6081
+ if (!stream.ranged) return { file: stream.file(), partial: false };
6082
+ const file = stream.file();
6083
+ pool.files += 1;
6084
+ pool.ranged += 1;
6085
+ pool.residentBytes += file.byteLength;
6086
+ pool.fullBytes += stream.index.levels.reduce((sum, level) => sum + level.byteLength, 0);
6087
+ reportPool();
6088
+ return { file, partial: true };
6089
+ };
6090
+ const imageSourceFor = (resident) => async (imageUrl) => {
6091
+ const kept = resident.whole.get(imageUrl);
6092
+ if (kept !== void 0 || resident.keptOnly === true) return kept;
6093
+ const served = await residentImage(imageUrl);
6094
+ if (served?.partial === true) resident.used = true;
6095
+ else if (served !== void 0) resident.whole.set(imageUrl, served.file);
6096
+ return served?.file;
6097
+ };
5387
6098
  const sourcePath = (options.sourcePath ?? "assets").replace(/^\/+|\/+$/gu, "");
5388
6099
  const manifestUrl = resolvePath(basePath, options.manifest ?? "assets.manifest.json");
5389
6100
  const assetCache = createAssetCache({
@@ -5553,6 +6264,13 @@ function createAssetLoader(options = {}) {
5553
6264
  let settled = 0;
5554
6265
  let settledBytes = 0;
5555
6266
  const pending = /* @__PURE__ */ new Set();
6267
+ const wholeOf = /* @__PURE__ */ new WeakMap();
6268
+ const wholeWhen = (wait, loading) => wait ? loading.then(async (value) => {
6269
+ if (typeof value === "object" && value !== null) await wholeOf.get(value);
6270
+ return value;
6271
+ }) : loading;
6272
+ const warmed = /* @__PURE__ */ new Set();
6273
+ let revealedAtMs;
5556
6274
  const bytesOf = async (path) => {
5557
6275
  if (isExternalAssetPath(path)) return 0;
5558
6276
  const manifest = await manifestOnce();
@@ -5560,6 +6278,15 @@ function createAssetLoader(options = {}) {
5560
6278
  const bytes = isRecord(entry) ? entry.bytes : void 0;
5561
6279
  return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
5562
6280
  };
6281
+ const coarseOf = async (path) => {
6282
+ if (!streamMeshes || isExternalAssetPath(path)) return void 0;
6283
+ const entry = (await manifestOnce())?.entries[path];
6284
+ const coarse = isRecord(entry) && Array.isArray(entry.streamedLods) ? entry.streamedLods[0] : void 0;
6285
+ if (!isRecord(coarse) || typeof coarse.output !== "string" || typeof coarse.bytes !== "number")
6286
+ return void 0;
6287
+ return { bytes: coarse.bytes, url: resolvePath(basePath, coarse.output) };
6288
+ };
6289
+ const weightOf = async (kind, path) => (kind === "model" && !warmed.has(path) ? (await coarseOf(path))?.bytes : void 0) ?? bytesOf(path);
5563
6290
  const auxiliaryOf = async (path) => {
5564
6291
  if (isExternalAssetPath(path)) return [];
5565
6292
  const entry = (await manifestOnce())?.entries[path];
@@ -5577,7 +6304,7 @@ function createAssetLoader(options = {}) {
5577
6304
  }
5578
6305
  return files;
5579
6306
  };
5580
- const cached = (kind, path, load, priority = "now") => {
6307
+ const cached = (kind, path, load, priority = "now", whole = false) => {
5581
6308
  const key = `${kind}:${path}`;
5582
6309
  const existing = cache2.get(key);
5583
6310
  if (existing !== void 0) {
@@ -5585,12 +6312,12 @@ function createAssetLoader(options = {}) {
5585
6312
  existing.priority = priority;
5586
6313
  if (existing.url !== void 0) assetCache.promote(existing.url, priority);
5587
6314
  }
5588
- return existing.promise;
6315
+ return wholeWhen(whole, existing.promise);
5589
6316
  }
5590
6317
  requested += 1;
5591
6318
  let weight = 0;
5592
6319
  let auxiliary = [];
5593
- const weighed = Promise.all([bytesOf(path), auxiliaryOf(path)]).then(
6320
+ const weighed = Promise.all([weightOf(kind, path), auxiliaryOf(path)]).then(
5594
6321
  ([bytes, files]) => {
5595
6322
  weight = bytes;
5596
6323
  auxiliary = files;
@@ -5598,6 +6325,19 @@ function createAssetLoader(options = {}) {
5598
6325
  },
5599
6326
  () => void 0
5600
6327
  );
6328
+ if (revealedAtMs !== void 0 && !warmed.has(path)) {
6329
+ const lateAt = revealedAtMs;
6330
+ void weighed.then(
6331
+ () => console.log(
6332
+ `${ASSET_LATE_MARKER}:${JSON.stringify({
6333
+ bytes: weight,
6334
+ kind,
6335
+ ms: Math.round(performanceNow() - lateAt),
6336
+ path
6337
+ })}`
6338
+ )
6339
+ );
6340
+ }
5601
6341
  const traceStart = assetTraceEnabled() ? performanceNow() : 0;
5602
6342
  const entry = {
5603
6343
  disposed: false,
@@ -5650,7 +6390,7 @@ function createAssetLoader(options = {}) {
5650
6390
  };
5651
6391
  entry.promise.then(note, note);
5652
6392
  cache2.set(key, entry);
5653
- return entry.promise;
6393
+ return wholeWhen(whole, entry.promise);
5654
6394
  };
5655
6395
  const releaseEntry = (entry) => {
5656
6396
  entry.released = true;
@@ -5662,6 +6402,7 @@ function createAssetLoader(options = {}) {
5662
6402
  );
5663
6403
  };
5664
6404
  const prefetchPaths = async (paths) => {
6405
+ for (const path of paths) warmed.add(path);
5665
6406
  if (!assetCache.enabled) {
5666
6407
  return {
5667
6408
  requested: paths.length,
@@ -5752,100 +6493,160 @@ function createAssetLoader(options = {}) {
5752
6493
  await attachCompiledLightmaps(path, value2);
5753
6494
  return value2;
5754
6495
  }
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)) {
6496
+ const parse = async (fileUrl, expected, at, resident) => {
6497
+ const data = await fetchModelBytes(
6498
+ fileUrl,
6499
+ assetCache,
6500
+ expected > 0 ? expected : void 0,
6501
+ at
6502
+ );
6503
+ const extensions = declaredExtensions(data);
6504
+ const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
6505
+ const loader = new GLTFLoader();
6506
+ if (resident !== void 0 && "imageSource" in loader)
6507
+ loader.imageSource = imageSourceFor(resident);
6508
+ const astcExtension = "EXT_texture_astc";
6509
+ const hasBasis = extensions.has("KHR_texture_basisu") && loader.failClosed !== true;
6510
+ const hasAstc = extensions.has(astcExtension);
6511
+ let shared;
6512
+ if (compressedTextures !== void 0 && (hasBasis || hasAstc)) {
6513
+ try {
6514
+ shared = await compressedTextures.loader;
6515
+ } catch (error) {
6516
+ if (hasBasis || !(error instanceof Error) || !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:"))
6517
+ throw error;
6518
+ }
6519
+ if (shared !== void 0) {
6520
+ loader.setKTX2Loader(
6521
+ shared
6522
+ );
6523
+ }
6524
+ }
6525
+ if (hasAstc) {
6526
+ const astcLoader = shared;
6527
+ const astcSupported = hasAstcSupport(astcLoader);
6528
+ loader.register((parser) => {
6529
+ if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
6530
+ throw new Error(
6531
+ "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support."
6532
+ );
6533
+ }
6534
+ return {
6535
+ name: astcExtension,
6536
+ loadTexture(textureIndex) {
6537
+ const extension = parser.json.textures[textureIndex].extensions?.[astcExtension];
6538
+ if (extension === void 0 || !astcSupported || astcLoader === void 0)
6539
+ return null;
6540
+ return parser.loadTextureImage(
6541
+ textureIndex,
6542
+ extension.source,
6543
+ astcLoader
6544
+ );
6545
+ }
6546
+ };
6547
+ });
6548
+ }
6549
+ if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
6550
+ const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');
6551
+ loader.setMeshoptDecoder(MeshoptDecoder);
6552
+ }
6553
+ if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
6554
+ if (loader.failClosed === true)
6555
+ console.info(
6556
+ `TN_VIRTUAL_GEOMETRY_SKIPPED ${path}: this engine's glTF loader hosts no cluster plugin; the source mesh draws`
6557
+ );
6558
+ else loader.register((parser) => new VirtualGeometryPlugin(parser));
6559
+ }
6560
+ const discreteLod = extensions.has(TN_DISCRETE_LOD) ? new DiscreteLodPlugin({
6561
+ failClosed: loader.failClosed === true
6562
+ }) : void 0;
6563
+ if (discreteLod !== void 0) {
6564
+ const plugin = discreteLod;
6565
+ loader.register((parser) => {
6566
+ plugin.setParser(parser);
6567
+ return plugin;
6568
+ });
6569
+ }
6570
+ if (extensions.has(DRACO_EXTENSION)) {
6571
+ const { DRACOLoader } = await import('three/addons/loaders/DRACOLoader.js');
6572
+ const dracoLoader = new DRACOLoader();
6573
+ dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
6574
+ loader.setDRACOLoader(dracoLoader);
6575
+ }
6576
+ const value2 = await new Promise(
6577
+ (resolve, reject) => loader.parse(data, resourcePathOf(fileUrl), resolve, reject)
6578
+ );
6579
+ const root = modelRoot(value2);
6580
+ if (root !== void 0) widenQuantizedPositions(root);
6581
+ if (root !== void 0) widenNormalizedScalars(root);
6582
+ if (root !== void 0 && discreteLod !== void 0)
6583
+ discreteLod.attach(root, await discretePolicy(path), attachInstancedLod);
6584
+ const clips = modelClips(value2);
6585
+ if (root !== void 0 && clips.length > 0 && reconcileMirroredClips(root, clips)) {
6586
+ 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.";
6587
+ console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} \u2014 ${cause}`);
6588
+ }
6589
+ return value2;
6590
+ };
6591
+ const coarse = warmed.has(path) ? void 0 : await coarseOf(path);
6592
+ let value;
6593
+ const residentState = streamTextures ? { used: false, whole: /* @__PURE__ */ new Map() } : void 0;
6594
+ if (coarse !== void 0) {
5770
6595
  try {
5771
- shared = await compressedTextures.loader;
6596
+ value = await parse(coarse.url, coarse.bytes, priority, residentState);
5772
6597
  } 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);
6598
+ console.warn(
6599
+ `TN_ASSETS_STREAM_FAILED ${path}: the coarse model did not load, so the whole file does; ${error instanceof Error ? error.message : String(error)}`
6600
+ );
5778
6601
  }
5779
6602
  }
5780
- if (hasAstc) {
5781
- const astcLoader = shared;
5782
- const astcSupported = hasAstcSupport(astcLoader);
5783
- loader.register((parser) => {
5784
- if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
6603
+ if (value === void 0) value = await parse(url, await bytesOf(path), priority);
6604
+ else {
6605
+ const coarseMeshes = meshesOf(value);
6606
+ const coarseGeometries = coarseMeshes.map((mesh) => mesh.geometry);
6607
+ const upgradeTextures = streamedTextureUpgrade(coarseMeshes);
6608
+ for (const geometry of coarseGeometries) markStreamedGeometry(geometry);
6609
+ const gone = () => loaderDisposed || coarseGeometries.some((geometry) => disposed.geometries.has(geometry));
6610
+ const landed = bytesOf(path).then(
6611
+ (bytes) => gone() ? void 0 : parse(
6612
+ url,
6613
+ bytes,
6614
+ "soon",
6615
+ residentState && { keptOnly: true, used: false, whole: residentState.whole }
6616
+ )
6617
+ ).then((full) => {
6618
+ residentState?.whole.clear();
6619
+ if (full === void 0) return;
6620
+ if (gone()) {
6621
+ disposeModel(full, disposed);
6622
+ return;
6623
+ }
6624
+ const fullMeshes = meshesOf(full);
6625
+ if (fullMeshes.length !== coarseMeshes.length)
5785
6626
  throw new Error(
5786
- "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support."
6627
+ `the full model has ${String(fullMeshes.length)} mesh(es), the coarse ${String(coarseMeshes.length)}`
5787
6628
  );
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`
6629
+ coarseGeometries.forEach(
6630
+ (geometry, index) => upgradeStreamedGeometry(geometry, fullMeshes[index].geometry)
5812
6631
  );
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}`);
6632
+ const swapped = upgradeTextures(fullMeshes, residentState?.used === true);
6633
+ if (residentState?.used === true) {
6634
+ pool.upgraded += swapped;
6635
+ reportPool();
6636
+ }
6637
+ }).catch(
6638
+ (error) => console.warn(
6639
+ `TN_ASSETS_STREAM_FAILED ${path}: the coarse model stays; ${error instanceof Error ? error.message : String(error)}`
6640
+ )
6641
+ );
6642
+ if (typeof value === "object" && value !== null) wholeOf.set(value, landed);
5843
6643
  }
5844
6644
  stampAssetProvenance(value, path);
5845
6645
  await attachCompiledLightmaps(path, value);
5846
6646
  return value;
5847
6647
  },
5848
- request?.priority ?? "now"
6648
+ request?.priority ?? "now",
6649
+ request?.whole === true
5849
6650
  ),
5850
6651
  get cache() {
5851
6652
  return { ...assetCache.report, clear: () => assetCache.clear() };
@@ -5853,9 +6654,11 @@ function createAssetLoader(options = {}) {
5853
6654
  get progress() {
5854
6655
  return { pending: [...pending], requested, requestedBytes, settled, settledBytes };
5855
6656
  },
6657
+ memo: createAssetMemo(canonicalUrl(manifestUrl)),
5856
6658
  prefetch: prefetchPaths,
5857
6659
  resolve: async (path) => (await resolveCandidates(path)).urls,
5858
6660
  startBackgroundFill: () => {
6661
+ revealedAtMs ??= performanceNow();
5859
6662
  void manifestOnce().catch(() => void 0);
5860
6663
  return assetCache.startFill();
5861
6664
  },
@@ -5976,11 +6779,35 @@ function isSize(bytes) {
5976
6779
  function isRecord(value) {
5977
6780
  return typeof value === "object" && value !== null;
5978
6781
  }
6782
+ async function fetchAsset(assets, path) {
6783
+ const candidates = await assets.resolve(path);
6784
+ const failures = [];
6785
+ let answered = false;
6786
+ let lastError;
6787
+ for (const url of candidates) {
6788
+ let response;
6789
+ try {
6790
+ response = await fetch(url);
6791
+ } catch (error) {
6792
+ lastError = error;
6793
+ failures.push(`${url} (${error instanceof Error ? error.message : String(error)})`);
6794
+ continue;
6795
+ }
6796
+ answered = true;
6797
+ if (response.ok) return response;
6798
+ failures.push(`${url} (status ${String(response.status)})`);
6799
+ }
6800
+ throw new Error(
6801
+ `TN_ASSET_NOT_SERVED: '${path}' is not served by any of ${String(candidates.length)} candidate url(s): ${failures.join("; ") || "none"}.`,
6802
+ answered || candidates.length === 0 ? void 0 : { cause: lastError }
6803
+ );
6804
+ }
5979
6805
 
5980
6806
  // src/static-transform.ts
5981
6807
  var STATIC_TRANSFORM_MARKER = "TN_STATIC_TRANSFORMS";
5982
6808
  var frozen = /* @__PURE__ */ new Map();
5983
- var SNAPSHOT_LENGTH2 = 3 + 4 + 3 + 16;
6809
+ var SNAPSHOT_LENGTH2 = 3 + 4 + 3 + 16 + 16;
6810
+ var IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
5984
6811
  function writeSnapshot(root, into) {
5985
6812
  const position = root.position;
5986
6813
  const quaternion = root.quaternion;
@@ -5998,6 +6825,8 @@ function writeSnapshot(root, into) {
5998
6825
  into[9] = scale.z;
5999
6826
  for (let element = 0; element < 16; element += 1)
6000
6827
  into[10 + element] = matrix2.elements[element] ?? 0;
6828
+ const parent = root.parent?.matrixWorld.elements ?? IDENTITY;
6829
+ for (let element = 0; element < 16; element += 1) into[26 + element] = parent[element] ?? 0;
6001
6830
  }
6002
6831
  function snapshotMatches(root, snapshot, scratch3) {
6003
6832
  writeSnapshot(root, scratch3);
@@ -6018,6 +6847,13 @@ var worldSilenced = /* @__PURE__ */ new WeakSet();
6018
6847
  function worldSilencedByFreeze(object2) {
6019
6848
  return worldSilenced.has(object2);
6020
6849
  }
6850
+ function thaw(root) {
6851
+ if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
6852
+ root.traverse((child) => {
6853
+ if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
6854
+ child.matrixWorldNeedsUpdate = true;
6855
+ });
6856
+ }
6021
6857
  function freeze(root) {
6022
6858
  root.updateMatrixWorld(true);
6023
6859
  let objects = 0;
@@ -6033,8 +6869,9 @@ function freeze(root) {
6033
6869
  return objects;
6034
6870
  }
6035
6871
  function markStatic(root) {
6036
- const objects = freeze(root);
6037
6872
  const existing = frozen.get(root);
6873
+ if (existing !== void 0) thaw(root);
6874
+ const objects = freeze(root);
6038
6875
  const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH2);
6039
6876
  writeSnapshot(root, snapshot);
6040
6877
  const version = (existing?.version ?? 0) + 1;
@@ -6053,15 +6890,7 @@ function unmarkStatic(root) {
6053
6890
  function invalidateStatic(object2) {
6054
6891
  let node = object2;
6055
6892
  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
- }
6893
+ if (frozen.has(node)) return markStatic(node);
6065
6894
  node = node.parent;
6066
6895
  }
6067
6896
  return void 0;
@@ -6077,11 +6906,6 @@ function refreshStaticTransforms() {
6077
6906
  if (frozen.size === 0) return;
6078
6907
  for (const entry of frozen.values()) {
6079
6908
  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
6909
  markStatic(entry.root);
6086
6910
  rearmedSinceCensus += 1;
6087
6911
  }
@@ -6534,8 +7358,8 @@ function positiveInteger(value, name) {
6534
7358
  // src/warmup.ts
6535
7359
  var warmUpCompletions = /* @__PURE__ */ new WeakMap();
6536
7360
  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() };
7361
+ const report2 = await warmUpScene(renderer, scene, camera, options);
7362
+ return { report: report2, completion: warmUpCompletions.get(report2) ?? Promise.resolve() };
6539
7363
  }
6540
7364
  function nativeEnvironmentPreparer(raw) {
6541
7365
  return typeof raw?.prepareEnvironmentAsync === "function" ? raw : void 0;
@@ -6661,7 +7485,7 @@ async function yieldThroughHost(yieldFrame) {
6661
7485
  new Promise((resolve) => setTimeout(resolve, 0))
6662
7486
  ]);
6663
7487
  }
6664
- async function withinDeadline(deadline, work, yieldFrame, now2) {
7488
+ async function withinDeadline(deadline, work, yieldFrame, now3) {
6665
7489
  let settled;
6666
7490
  const completion = work.then(
6667
7491
  () => {
@@ -6674,12 +7498,12 @@ async function withinDeadline(deadline, work, yieldFrame, now2) {
6674
7498
  }
6675
7499
  );
6676
7500
  await Promise.resolve();
6677
- if (now2() >= deadline) return false;
7501
+ if (now3() >= deadline) return false;
6678
7502
  if (settled !== void 0) return settled;
6679
- while (now2() < deadline) {
7503
+ while (now3() < deadline) {
6680
7504
  if (settled !== void 0) return settled;
6681
7505
  let timer;
6682
- const remaining = Math.max(0, deadline - now2());
7506
+ const remaining = Math.max(0, deadline - now3());
6683
7507
  const expiry = new Promise((resolve) => {
6684
7508
  timer = setTimeout(() => resolve("timeout"), remaining);
6685
7509
  });
@@ -6690,11 +7514,11 @@ async function withinDeadline(deadline, work, yieldFrame, now2) {
6690
7514
  ]);
6691
7515
  if (timer !== void 0) clearTimeout(timer);
6692
7516
  if (result === "timeout") return false;
6693
- if (result.kind === "complete") return now2() < deadline && result.value;
7517
+ if (result.kind === "complete") return now3() < deadline && result.value;
6694
7518
  }
6695
7519
  return false;
6696
7520
  }
6697
- async function runComputeWarmUp(renderer, nodes, compileTimeoutMs, deadline, now2, yieldFrame) {
7521
+ async function runComputeWarmUp(renderer, nodes2, compileTimeoutMs, deadline, now3, yieldFrame) {
6698
7522
  const seam = computeAsyncOf(renderer);
6699
7523
  if (seam === void 0) {
6700
7524
  return { compiled: 0, abandoned: 0, unsupported: true, timedOut: false };
@@ -6702,30 +7526,30 @@ async function runComputeWarmUp(renderer, nodes, compileTimeoutMs, deadline, now
6702
7526
  let compiled = 0;
6703
7527
  let abandoned = 0;
6704
7528
  let timedOut = false;
6705
- for (let index = 0; index < nodes.length; index += 1) {
6706
- const remaining = deadline - now2();
7529
+ for (let index = 0; index < nodes2.length; index += 1) {
7530
+ const remaining = deadline - now3();
6707
7531
  if (remaining <= 0) {
6708
7532
  timedOut = true;
6709
- abandoned += nodes.length - index;
7533
+ abandoned += nodes2.length - index;
6710
7534
  break;
6711
7535
  }
6712
7536
  const finished = await withinDeadline(
6713
- Math.min(deadline, now2() + compileTimeoutMs),
6714
- Promise.resolve().then(() => seam.warm(nodes[index])),
7537
+ Math.min(deadline, now3() + compileTimeoutMs),
7538
+ Promise.resolve().then(() => seam.warm(nodes2[index])),
6715
7539
  yieldFrame,
6716
- now2
7540
+ now3
6717
7541
  );
6718
7542
  if (finished) compiled += 1;
6719
7543
  else abandoned += 1;
6720
- if (now2() >= deadline && (!finished || index + 1 < nodes.length)) {
7544
+ if (now3() >= deadline && (!finished || index + 1 < nodes2.length)) {
6721
7545
  timedOut = true;
6722
- abandoned += nodes.length - index - 1;
7546
+ abandoned += nodes2.length - index - 1;
6723
7547
  break;
6724
7548
  }
6725
7549
  }
6726
7550
  return { compiled, abandoned, unsupported: false, timedOut };
6727
7551
  }
6728
- async function warmUpComputeNodes(renderer, nodes, options = {}) {
7552
+ async function warmUpComputeNodes(renderer, nodes2, options = {}) {
6729
7553
  const compileTimeoutMs = options.compileTimeoutMs ?? DEFAULT_COMPILE_TIMEOUT_MS;
6730
7554
  const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;
6731
7555
  for (const [name, value] of [
@@ -6738,19 +7562,19 @@ async function warmUpComputeNodes(renderer, nodes, options = {}) {
6738
7562
  );
6739
7563
  }
6740
7564
  }
6741
- const now2 = () => globalThis.performance?.now() ?? Date.now();
7565
+ const now3 = () => globalThis.performance?.now() ?? Date.now();
6742
7566
  return runComputeWarmUp(
6743
7567
  renderer,
6744
- nodes,
7568
+ nodes2,
6745
7569
  compileTimeoutMs,
6746
- now2() + budgetMs,
6747
- now2,
7570
+ now3() + budgetMs,
7571
+ now3,
6748
7572
  options.yieldFrame ?? yieldToHost
6749
7573
  );
6750
7574
  }
6751
- function withComputeReport(report, compute) {
7575
+ function withComputeReport(report2, compute) {
6752
7576
  return {
6753
- ...report,
7577
+ ...report2,
6754
7578
  computeCompiled: compute.compiled,
6755
7579
  computeAbandoned: compute.abandoned,
6756
7580
  computeUnsupported: compute.unsupported,
@@ -6801,11 +7625,11 @@ function observePipelineCensus(before, after) {
6801
7625
  status
6802
7626
  };
6803
7627
  }
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 } };
7628
+ function reconcileWarmUpObservation(report2) {
7629
+ const unavailable = report2.unsupported || report2.computeUnsupported === true;
7630
+ const incomplete = report2.abandoned > 0 || report2.timedOut || report2.computeTimedOut === true || (report2.computeAbandoned ?? 0) > 0;
7631
+ const status = unavailable ? "unavailable" : incomplete && report2.observed.status === "complete" ? "incomplete" : report2.observed.status;
7632
+ return status === report2.observed.status ? report2 : { ...report2, observed: { ...report2.observed, status } };
6809
7633
  }
6810
7634
  function hasShadowCaster(scene) {
6811
7635
  const stack = [scene];
@@ -6954,10 +7778,10 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
6954
7778
  );
6955
7779
  }
6956
7780
  }
6957
- const now2 = () => globalThis.performance?.now() ?? Date.now();
7781
+ const now3 = () => globalThis.performance?.now() ?? Date.now();
6958
7782
  const yieldFrame = options.yieldFrame ?? yieldToHost;
6959
- const environmentDeadline = now2() + environmentBudgetMs;
6960
- let startedAt = now2();
7783
+ const environmentDeadline = now3() + environmentBudgetMs;
7784
+ let startedAt = now3();
6961
7785
  let environmentPreparationStarted = false;
6962
7786
  let environmentPrepared = false;
6963
7787
  let environmentPreparation;
@@ -6990,7 +7814,7 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
6990
7814
  let cacheStatus = readWarmUpCache(cacheIdentity, candidates, computeNodes.length);
6991
7815
  const upfront = ensureEnvironmentPreparation();
6992
7816
  if (upfront !== void 0) {
6993
- if (!await withinDeadline(environmentDeadline, upfront, yieldFrame, now2)) {
7817
+ if (!await withinDeadline(environmentDeadline, upfront, yieldFrame, now3)) {
6994
7818
  return reconcileWarmUpObservation({
6995
7819
  compiled: 0,
6996
7820
  pipelines: candidates,
@@ -6998,20 +7822,20 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
6998
7822
  attempted: 0,
6999
7823
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7000
7824
  slices: 0,
7001
- elapsedMs: now2() - startedAt,
7825
+ elapsedMs: now3() - startedAt,
7002
7826
  unsupported: false,
7003
7827
  abandoned: 1,
7004
- timedOut: now2() >= environmentDeadline,
7828
+ timedOut: now3() >= environmentDeadline,
7005
7829
  cache: cacheStatus
7006
7830
  });
7007
7831
  }
7008
- startedAt = now2();
7832
+ startedAt = now3();
7009
7833
  }
7010
7834
  if (cacheStatus === "hit" && typeof renderer.compileAsync === "function") {
7011
7835
  const computeSupported = computeNodes.length === 0 || computeAsyncOf(renderer) !== void 0;
7012
7836
  if (computeSupported) {
7013
7837
  const preparation = ensureEnvironmentPreparation();
7014
- if (preparation !== void 0 && !await withinDeadline(startedAt + budgetMs, preparation, yieldFrame, now2)) {
7838
+ if (preparation !== void 0 && !await withinDeadline(startedAt + budgetMs, preparation, yieldFrame, now3)) {
7015
7839
  return reconcileWarmUpObservation({
7016
7840
  compiled: 0,
7017
7841
  pipelines: candidates,
@@ -7019,21 +7843,21 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7019
7843
  attempted: 0,
7020
7844
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7021
7845
  slices: 0,
7022
- elapsedMs: now2() - startedAt,
7846
+ elapsedMs: now3() - startedAt,
7023
7847
  unsupported: false,
7024
7848
  abandoned: 1,
7025
- timedOut: now2() >= startedAt + budgetMs,
7849
+ timedOut: now3() >= startedAt + budgetMs,
7026
7850
  cache: "hit"
7027
7851
  });
7028
7852
  }
7029
- const report2 = {
7853
+ const report3 = {
7030
7854
  compiled: 0,
7031
7855
  pipelines: candidates,
7032
7856
  candidates,
7033
7857
  attempted: 0,
7034
7858
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7035
7859
  slices: 0,
7036
- elapsedMs: now2() - startedAt,
7860
+ elapsedMs: now3() - startedAt,
7037
7861
  unsupported: false,
7038
7862
  abandoned: 0,
7039
7863
  timedOut: false,
@@ -7045,7 +7869,7 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7045
7869
  computeTimedOut: false
7046
7870
  }
7047
7871
  };
7048
- return report2;
7872
+ return report3;
7049
7873
  }
7050
7874
  cacheStatus = "miss";
7051
7875
  }
@@ -7054,33 +7878,33 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7054
7878
  computeNodes,
7055
7879
  compileTimeoutMs,
7056
7880
  startedAt + budgetMs,
7057
- now2,
7881
+ now3,
7058
7882
  yieldFrame
7059
7883
  );
7060
7884
  if (typeof renderer.compileAsync !== "function") {
7061
- const report2 = reconcileWarmUpObservation({
7885
+ const report3 = reconcileWarmUpObservation({
7062
7886
  compiled: 0,
7063
7887
  pipelines: candidates,
7064
7888
  candidates,
7065
7889
  attempted: 0,
7066
7890
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7067
7891
  slices: 0,
7068
- elapsedMs: now2() - startedAt,
7892
+ elapsedMs: now3() - startedAt,
7069
7893
  unsupported: true,
7070
7894
  abandoned: 0,
7071
7895
  timedOut: false,
7072
7896
  cache: cacheStatus
7073
7897
  });
7074
- return compute === void 0 ? report2 : reconcileWarmUpObservation(withComputeReport(report2, compute));
7898
+ return compute === void 0 ? report3 : reconcileWarmUpObservation(withComputeReport(report3, compute));
7075
7899
  }
7076
7900
  const compileAsync = renderer.compileAsync.bind(renderer);
7077
7901
  let attempted = 0;
7078
7902
  const pendingCompiles = [];
7079
7903
  const invokeCompile = (object2, targetScene) => {
7080
- const compileDeadline = (options.granularity ?? "scene") === "scene" ? startedAt + budgetMs : Math.min(startedAt + budgetMs, now2() + compileTimeoutMs);
7904
+ const compileDeadline = (options.granularity ?? "scene") === "scene" ? startedAt + budgetMs : Math.min(startedAt + budgetMs, now3() + compileTimeoutMs);
7081
7905
  const preparation = ensureEnvironmentPreparation(targetScene ?? scene);
7082
7906
  const compile = () => {
7083
- if (now2() >= compileDeadline) {
7907
+ if (now3() >= compileDeadline) {
7084
7908
  return Promise.reject(
7085
7909
  new Error("TN_WARMUP_COMPILE_DEADLINE: PMREM preparation consumed this compile slice.")
7086
7910
  );
@@ -7100,32 +7924,32 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7100
7924
  return compile.catch(() => void 0).then(async () => {
7101
7925
  const pass = await renderWarmPassesOnce();
7102
7926
  if (pass === void 0) {
7103
- if (passError === void 0 && now2() >= startedAt + budgetMs) return;
7927
+ if (passError === void 0 && now3() >= startedAt + budgetMs) return;
7104
7928
  throw passError ?? new Error("covered world warm render did not settle");
7105
7929
  }
7106
7930
  });
7107
7931
  };
7108
7932
  let gpuDrainSettled = true;
7109
- const compileWithinDeadline = async (deadline2, work, yieldFrame2, now3) => {
7933
+ const compileWithinDeadline = async (deadline2, work, yieldFrame2, now4) => {
7110
7934
  let settled = false;
7111
7935
  const track = () => {
7112
7936
  settled = true;
7113
7937
  };
7114
7938
  void work.then(track, track);
7115
- const finished = await withinDeadline(deadline2, work, yieldFrame2, now3);
7939
+ const finished = await withinDeadline(deadline2, work, yieldFrame2, now4);
7116
7940
  if (!finished && !settled) pendingCompiles.push(work);
7117
7941
  return finished;
7118
7942
  };
7119
- const finish = (report2) => {
7943
+ const finish = (report3) => {
7120
7944
  const coveredPassIncomplete = renderer.warmUpWorldPass !== void 0 && passResult === void 0;
7121
- const drainNormalized = gpuDrainSettled ? report2 : {
7122
- ...report2,
7945
+ const drainNormalized = gpuDrainSettled ? report3 : {
7946
+ ...report3,
7123
7947
  timedOut: true
7124
7948
  };
7125
7949
  const normalized = coveredPassIncomplete ? {
7126
7950
  ...drainNormalized,
7127
7951
  abandoned: Math.max(1, drainNormalized.abandoned),
7128
- timedOut: drainNormalized.timedOut || now2() >= startedAt + budgetMs
7952
+ timedOut: drainNormalized.timedOut || now3() >= startedAt + budgetMs
7129
7953
  } : drainNormalized;
7130
7954
  const complete = gpuDrainSettled && !normalized.unsupported && !normalized.timedOut && normalized.abandoned === 0 && normalized.computeUnsupported !== true && normalized.computeTimedOut !== true && (normalized.computeAbandoned ?? 0) === 0;
7131
7955
  const finalCache = complete && cacheIdentity !== void 0 ? storeWarmUpCache(cacheIdentity, candidates, computeNodes.length) : cacheStatus;
@@ -7144,7 +7968,7 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7144
7968
  if (passRendered) return passResult;
7145
7969
  passRendered = true;
7146
7970
  if (environmentPreparationStarted && !environmentPrepared) return void 0;
7147
- if (now2() >= startedAt + budgetMs) return void 0;
7971
+ if (now3() >= startedAt + budgetMs) return void 0;
7148
7972
  try {
7149
7973
  passResult = await renderWarmPasses(
7150
7974
  renderer,
@@ -7166,20 +7990,20 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7166
7990
  const queue = renderer.raw?.backend?.device?.queue;
7167
7991
  if (typeof queue?.onSubmittedWorkDone !== "function") return;
7168
7992
  const drained = Promise.resolve().then(() => queue.onSubmittedWorkDone?.());
7169
- gpuDrainSettled = await withinDeadline(startedAt + budgetMs, drained, yieldFrame, now2);
7993
+ gpuDrainSettled = await withinDeadline(startedAt + budgetMs, drained, yieldFrame, now3);
7170
7994
  };
7171
- const withPasses = (report2) => passResult === void 0 ? report2 : {
7172
- ...report2,
7995
+ const withPasses = (report3) => passResult === void 0 ? report3 : {
7996
+ ...report3,
7173
7997
  passes: passResult.passes,
7174
7998
  passPipelines: passResult.created,
7175
7999
  cullingForced: passResult.cullingForced,
7176
8000
  visibilityForced: passResult.visibilityForced,
7177
- elapsedMs: report2.elapsedMs + passResult.elapsedMs
8001
+ elapsedMs: report3.elapsedMs + passResult.elapsedMs
7178
8002
  };
7179
8003
  if ((options.granularity ?? "scene") === "scene") {
7180
8004
  if (compute === void 0) {
7181
8005
  const deadline2 = startedAt + budgetMs;
7182
- const finished2 = now2() < deadline2 ? await compileWithinDeadline(deadline2, invokeSceneCompile(), yieldFrame, now2) : false;
8006
+ const finished2 = now3() < deadline2 ? await compileWithinDeadline(deadline2, invokeSceneCompile(), yieldFrame, now3) : false;
7183
8007
  options.onProgress?.({ done: finished2 ? 1 : 0, total: 1 });
7184
8008
  await renderWarmPassesOnce();
7185
8009
  await settleGpu();
@@ -7191,15 +8015,15 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7191
8015
  attempted,
7192
8016
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7193
8017
  slices: 1,
7194
- elapsedMs: now2() - startedAt,
8018
+ elapsedMs: now3() - startedAt,
7195
8019
  unsupported: false,
7196
8020
  abandoned: finished2 ? 0 : 1,
7197
- timedOut: !finished2 && (passError === void 0 || now2() >= deadline2)
8021
+ timedOut: !finished2 && (passError === void 0 || now3() >= deadline2)
7198
8022
  })
7199
8023
  );
7200
8024
  }
7201
- const remaining = Math.max(0, startedAt + budgetMs - now2());
7202
- const finished = remaining > 0 ? await compileWithinDeadline(startedAt + budgetMs, invokeSceneCompile(), yieldFrame, now2) : false;
8025
+ const remaining = Math.max(0, startedAt + budgetMs - now3());
8026
+ const finished = remaining > 0 ? await compileWithinDeadline(startedAt + budgetMs, invokeSceneCompile(), yieldFrame, now3) : false;
7203
8027
  options.onProgress?.({ done: finished ? 1 : 0, total: 1 });
7204
8028
  await renderWarmPassesOnce();
7205
8029
  await settleGpu();
@@ -7213,10 +8037,10 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7213
8037
  attempted,
7214
8038
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7215
8039
  slices: 1,
7216
- elapsedMs: now2() - startedAt,
8040
+ elapsedMs: now3() - startedAt,
7217
8041
  unsupported: false,
7218
8042
  abandoned: finished ? 0 : 1,
7219
- timedOut: compute.timedOut || !finished && now2() >= startedAt + budgetMs
8043
+ timedOut: compute.timedOut || !finished && now3() >= startedAt + budgetMs
7220
8044
  },
7221
8045
  compute
7222
8046
  )
@@ -7226,19 +8050,19 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7226
8050
  const total = renderables.length;
7227
8051
  if (total === 0) {
7228
8052
  options.onProgress?.({ done: 0, total: 0 });
7229
- const report2 = reconcileWarmUpObservation({
8053
+ const report3 = reconcileWarmUpObservation({
7230
8054
  compiled: 0,
7231
8055
  pipelines: candidates,
7232
8056
  candidates,
7233
8057
  attempted,
7234
8058
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7235
8059
  slices: 0,
7236
- elapsedMs: now2() - startedAt,
8060
+ elapsedMs: now3() - startedAt,
7237
8061
  unsupported: false,
7238
8062
  abandoned: 0,
7239
8063
  timedOut: false
7240
8064
  });
7241
- return compute === void 0 ? finish(report2) : finish(withComputeReport(report2, compute));
8065
+ return compute === void 0 ? finish(report3) : finish(withComputeReport(report3, compute));
7242
8066
  }
7243
8067
  let slices = 0;
7244
8068
  let compiled = 0;
@@ -7246,21 +8070,21 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7246
8070
  let timedOut = false;
7247
8071
  const deadline = startedAt + budgetMs;
7248
8072
  for (let index = 0; index < total; index += 1) {
7249
- if (now2() >= deadline) {
8073
+ if (now3() >= deadline) {
7250
8074
  timedOut = true;
7251
8075
  abandoned += total - index;
7252
8076
  break;
7253
8077
  }
7254
8078
  const finished = await compileWithinDeadline(
7255
- Math.min(deadline, now2() + compileTimeoutMs),
8079
+ Math.min(deadline, now3() + compileTimeoutMs),
7256
8080
  invokeCompile(renderables[index], options.targetScene ?? scene),
7257
8081
  yieldFrame,
7258
- now2
8082
+ now3
7259
8083
  );
7260
8084
  if (finished) compiled += 1;
7261
8085
  else {
7262
8086
  abandoned += 1;
7263
- if (now2() >= deadline) timedOut = true;
8087
+ if (now3() >= deadline) timedOut = true;
7264
8088
  }
7265
8089
  const done = index + 1;
7266
8090
  if (done % sliceSize === 0 || done === total) {
@@ -7270,27 +8094,162 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
7270
8094
  }
7271
8095
  }
7272
8096
  if (renderer.warmUpWorldPass === void 0) await renderWarmPassesOnce();
7273
- else await withinDeadline(startedAt + budgetMs, renderWarmPassesOnce(), yieldFrame, now2);
8097
+ else await withinDeadline(startedAt + budgetMs, renderWarmPassesOnce(), yieldFrame, now3);
7274
8098
  await settleGpu();
7275
- const report = {
8099
+ const report2 = {
7276
8100
  compiled,
7277
8101
  pipelines: candidates,
7278
8102
  candidates,
7279
8103
  attempted,
7280
8104
  observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
7281
8105
  slices,
7282
- elapsedMs: now2() - startedAt,
8106
+ elapsedMs: now3() - startedAt,
7283
8107
  unsupported: false,
7284
8108
  abandoned,
7285
8109
  timedOut
7286
8110
  };
7287
- return compute === void 0 ? finish(withPasses(report)) : finish(
8111
+ return compute === void 0 ? finish(withPasses(report2)) : finish(
7288
8112
  withPasses(
7289
- withComputeReport({ ...report, timedOut: compute.timedOut || timedOut }, compute)
8113
+ withComputeReport({ ...report2, timedOut: compute.timedOut || timedOut }, compute)
7290
8114
  )
7291
8115
  );
7292
8116
  }
7293
8117
 
8118
+ // src/streaming.ts
8119
+ var DEFAULT_SLICE_BUDGET_MS = 8;
8120
+ var DEFAULT_CONCURRENCY2 = 6;
8121
+ var now2 = () => globalThis.performance?.now() ?? Date.now();
8122
+ var SLICE_FRAME_MARGIN_MS = 2;
8123
+ var MIN_SLICE_BUDGET_MS = 1;
8124
+ var LOOP_FRAME_WAIT_MS = 250;
8125
+ var loopFrames = {
8126
+ visible: false,
8127
+ budgetMs: DEFAULT_SLICE_BUDGET_MS,
8128
+ waiters: []
8129
+ };
8130
+ function noteSliceFrame(frameMs, targetFps, visible) {
8131
+ loopFrames.visible = visible;
8132
+ loopFrames.budgetMs = targetFps > 0 ? Math.min(
8133
+ DEFAULT_SLICE_BUDGET_MS,
8134
+ Math.max(MIN_SLICE_BUDGET_MS, 1e3 / targetFps - frameMs - SLICE_FRAME_MARGIN_MS)
8135
+ ) : DEFAULT_SLICE_BUDGET_MS;
8136
+ for (const resolve of loopFrames.waiters.splice(0)) resolve();
8137
+ }
8138
+ function endSliceFrames() {
8139
+ noteSliceFrame(0, 0, false);
8140
+ }
8141
+ var nextLoopFrame = () => new Promise((resolve) => {
8142
+ const timer = setTimeout(resolve, LOOP_FRAME_WAIT_MS);
8143
+ loopFrames.waiters.push(() => {
8144
+ clearTimeout(timer);
8145
+ resolve();
8146
+ });
8147
+ }).then(yieldToHost);
8148
+ var yieldSlice = () => loopFrames.visible ? nextLoopFrame() : yieldToHost();
8149
+ var sliceBudget = () => loopFrames.visible ? loopFrames.budgetMs : DEFAULT_SLICE_BUDGET_MS;
8150
+ function assertWholeAtLeastOne(value, name, code) {
8151
+ if (!Number.isInteger(value) || value < 1) {
8152
+ throw new Error(
8153
+ `${code}: ${name} must be a whole number of at least one, received ${String(value)}.`
8154
+ );
8155
+ }
8156
+ }
8157
+ async function addInSlices(objects, add, options = {}) {
8158
+ const sliceSize = options.sliceSize;
8159
+ if (sliceSize !== void 0) {
8160
+ assertWholeAtLeastOne(sliceSize, "sliceSize", "TN_ADD_SLICES_SLICE_INVALID");
8161
+ }
8162
+ const countSlices = sliceSize !== void 0;
8163
+ const nextBudget = options.yieldFrame === void 0 ? sliceBudget : () => DEFAULT_SLICE_BUDGET_MS;
8164
+ let sliceBudgetMs = countSlices ? void 0 : nextBudget();
8165
+ const yieldFrame = options.yieldFrame ?? yieldSlice;
8166
+ const shouldContinue = options.while;
8167
+ const startedAt = now2();
8168
+ const list = [...objects];
8169
+ const total = list.length;
8170
+ let added = 0;
8171
+ let reported = 0;
8172
+ let slices = 0;
8173
+ let stopped = false;
8174
+ let sliceStartedAt = now2();
8175
+ const flush = async (yieldAfter) => {
8176
+ slices += 1;
8177
+ reported = added;
8178
+ options.onProgress?.({ added, total });
8179
+ if (yieldAfter) {
8180
+ await yieldFrame();
8181
+ if (sliceBudgetMs !== void 0) {
8182
+ sliceBudgetMs = nextBudget();
8183
+ sliceStartedAt = now2();
8184
+ }
8185
+ }
8186
+ };
8187
+ const sliceSpent = () => sliceSize !== void 0 ? added % sliceSize === 0 : now2() - sliceStartedAt >= Number(sliceBudgetMs);
8188
+ for (let index = 0; index < total; index += 1) {
8189
+ if (shouldContinue !== void 0 && !shouldContinue()) {
8190
+ stopped = true;
8191
+ break;
8192
+ }
8193
+ add(list[index], index);
8194
+ added += 1;
8195
+ if (added < total && sliceSpent()) await flush(true);
8196
+ }
8197
+ if (added > reported) await flush(false);
8198
+ const report2 = {
8199
+ added,
8200
+ total,
8201
+ slices,
8202
+ elapsedMs: now2() - startedAt,
8203
+ // Measured rather than assumed: with no count to divide by, the average is what the run did.
8204
+ sliceSize: sliceSize ?? Math.round(added / Math.max(slices, 1)),
8205
+ sliceSizeOverridden: countSlices,
8206
+ sliceBudgetMs,
8207
+ stopped
8208
+ };
8209
+ if (options.marker !== false) {
8210
+ console.info(
8211
+ `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)}`
8212
+ );
8213
+ }
8214
+ return report2;
8215
+ }
8216
+ async function loadAll(items, load, options = {}) {
8217
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY2;
8218
+ assertWholeAtLeastOne(concurrency, "concurrency", "TN_LOAD_ALL_CONCURRENCY_INVALID");
8219
+ const concurrencyOverridden = options.concurrency !== void 0;
8220
+ const yieldFrame = options.yieldFrame ?? yieldToHost;
8221
+ const startedAt = now2();
8222
+ const total = items.length;
8223
+ const results = new Array(total);
8224
+ let next = 0;
8225
+ let settled = 0;
8226
+ let failed = false;
8227
+ const lane = async () => {
8228
+ for (; ; ) {
8229
+ if (failed) return;
8230
+ const index = next;
8231
+ next += 1;
8232
+ if (index >= total) return;
8233
+ try {
8234
+ results[index] = await load(items[index], index);
8235
+ } catch (error) {
8236
+ failed = true;
8237
+ throw error;
8238
+ }
8239
+ settled += 1;
8240
+ options.onProgress?.({ settled, total });
8241
+ await yieldFrame();
8242
+ }
8243
+ };
8244
+ await Promise.all(Array.from({ length: Math.min(concurrency, total) }, () => lane()));
8245
+ if (options.marker !== false) {
8246
+ console.info(
8247
+ `TN_LOAD_ALL items=${String(total)} concurrency=${String(concurrency)} overridden=${String(concurrencyOverridden)} ms=${(now2() - startedAt).toFixed(1)}`
8248
+ );
8249
+ }
8250
+ return results;
8251
+ }
8252
+
7294
8253
  // src/target-fps.ts
7295
8254
  var DEFAULT_TARGET_FPS = 60;
7296
8255
  var MAX_TARGET_FPS = 120;
@@ -7316,16 +8275,282 @@ function resolveTargetFps(config, platform, measuredRefreshHz) {
7316
8275
  if (measuredRefreshHz === void 0) return { source: "fallback", targetFps: DEFAULT_TARGET_FPS };
7317
8276
  return { source: "display", targetFps: snapRefreshRate(measuredRefreshHz) };
7318
8277
  }
8278
+
8279
+ // src/world-cell-records.ts
8280
+ var RECORD_OP = {
8281
+ write: 1,
8282
+ fill: 2,
8283
+ move: 3,
8284
+ copy: 4,
8285
+ gather: 5,
8286
+ upload: 6,
8287
+ box: 7,
8288
+ lanes: 8
8289
+ };
8290
+ var RECORD_BOX_SIZE = 7;
8291
+ function grown(array, needed) {
8292
+ if (needed <= array.length) return array;
8293
+ const next = new array.constructor(
8294
+ Math.max(needed, array.length * 2)
8295
+ );
8296
+ next.set(array);
8297
+ return next;
8298
+ }
8299
+ var RecordQueue = class {
8300
+ #attributes = [];
8301
+ #slots = /* @__PURE__ */ new Map();
8302
+ #ops = new Float64Array(1024);
8303
+ #opAt = 0;
8304
+ #payload = new Float32Array(16384);
8305
+ #payloadAt = 0;
8306
+ #boxes = 0;
8307
+ #writers = /* @__PURE__ */ new Set();
8308
+ /** The payload buffer; read it after {@link reserve}, which may replace it. */
8309
+ get payload() {
8310
+ return this.#payload;
8311
+ }
8312
+ /** Room for `floats` payload floats at a record-aligned offset, which is returned. */
8313
+ reserve(floats) {
8314
+ const at = Math.ceil(this.#payloadAt / 16) * 16;
8315
+ this.#payload = grown(this.#payload, at + floats);
8316
+ this.#payloadAt = at + floats;
8317
+ return at;
8318
+ }
8319
+ write(attribute2, at, count, payloadAt) {
8320
+ if (count > 0) this.#op(RECORD_OP.write, attribute2, at, count, payloadAt);
8321
+ }
8322
+ fill(attribute2, at, count) {
8323
+ if (count > 0) this.#op(RECORD_OP.fill, attribute2, at, count);
8324
+ }
8325
+ move(attribute2, from, to, count) {
8326
+ if (count > 0 && from !== to) this.#op(RECORD_OP.move, attribute2, from, to, count);
8327
+ }
8328
+ copy(target, source, count) {
8329
+ if (count > 0) this.#op(RECORD_OP.copy, target, this.#slot(source), count);
8330
+ }
8331
+ /** `blocks` holds `[fromRecord, records]` pairs, laid out from record 0 in order. */
8332
+ gather(attribute2, stride, blocks) {
8333
+ if (blocks.length === 0) return;
8334
+ this.#op(RECORD_OP.gather, attribute2, stride, blocks.length / 2, ...blocks);
8335
+ }
8336
+ upload(attribute2, from, count) {
8337
+ this.#op(RECORD_OP.upload, attribute2, from, count);
8338
+ }
8339
+ /** Queues a box; the returned index is where its seven numbers start in the flush's answer. */
8340
+ box(attribute2, from, count, center, half) {
8341
+ const at = this.reserve(6);
8342
+ this.#payload.set([center.x, center.y, center.z, half.x, half.y, half.z], at);
8343
+ this.#op(RECORD_OP.box, attribute2, from, count, at);
8344
+ const index = this.#boxes;
8345
+ this.#boxes += RECORD_BOX_SIZE;
8346
+ return index;
8347
+ }
8348
+ lanes(attribute2, stride, values) {
8349
+ this.#op(RECORD_OP.lanes, attribute2, stride, values.length, ...values);
8350
+ }
8351
+ /** `writer` names its upload ranges at the next flush and reads its boxes back after it. */
8352
+ touch(writer) {
8353
+ this.#writers.add(writer);
8354
+ }
8355
+ /**
8356
+ * Hands the frame's ops to the engine in one call (or to {@link applyRecords} on upstream three),
8357
+ * then tells each writer what its boxes measured. A frame that queued nothing calls nothing.
8358
+ */
8359
+ flush() {
8360
+ if (this.#writers.size === 0 && this.#opAt === 0) return;
8361
+ const writers = [...this.#writers];
8362
+ this.#writers.clear();
8363
+ for (const writer of writers) writer.uploadRecords();
8364
+ const attributes = this.#attributes;
8365
+ const ops = this.#ops.subarray(0, this.#opAt);
8366
+ const payload = this.#payload.subarray(0, this.#payloadAt);
8367
+ this.#attributes = [];
8368
+ this.#slots.clear();
8369
+ this.#opAt = 0;
8370
+ this.#payloadAt = 0;
8371
+ this.#boxes = 0;
8372
+ const first = attributes[0];
8373
+ let boxes = [];
8374
+ if (first !== void 0) {
8375
+ const engine = first.__tnRecords;
8376
+ boxes = typeof engine === "function" ? engine.call(first, attributes, ops, payload) : applyRecords(attributes, ops, payload);
8377
+ }
8378
+ for (const writer of writers) writer.settleRecords(boxes);
8379
+ }
8380
+ #slot(attribute2) {
8381
+ let slot = this.#slots.get(attribute2);
8382
+ if (slot === void 0) {
8383
+ slot = this.#attributes.length;
8384
+ this.#attributes.push(attribute2);
8385
+ this.#slots.set(attribute2, slot);
8386
+ }
8387
+ return slot;
8388
+ }
8389
+ #op(code, attribute2, ...args) {
8390
+ const slot = this.#slot(attribute2);
8391
+ this.#ops = grown(this.#ops, this.#opAt + 2 + args.length);
8392
+ this.#ops[this.#opAt] = code;
8393
+ this.#ops[this.#opAt + 1] = slot;
8394
+ this.#ops.set(args, this.#opAt + 2);
8395
+ this.#opAt += 2 + args.length;
8396
+ }
8397
+ };
8398
+ var batchRecords = new RecordQueue();
8399
+ function span(array, at, count, what) {
8400
+ if (!(Number.isInteger(at) && Number.isInteger(count) && at >= 0 && count >= 0 && at + count <= array.length))
8401
+ throw new RangeError(
8402
+ `TN_WORLD_RECORDS: ${what} [${String(at)}, ${String(at + count)}) is outside ${String(array.length)} floats`
8403
+ );
8404
+ }
8405
+ function gather(array, ops, at) {
8406
+ const stride = ops[at + 2];
8407
+ const blocks = ops[at + 3];
8408
+ let total = 0;
8409
+ for (let block = 0; block < blocks; block += 1) total += ops[at + 5 + block * 2];
8410
+ const scratch3 = new Float32Array(total * stride);
8411
+ let written = 0;
8412
+ for (let block = 0; block < blocks; block += 1) {
8413
+ const from = ops[at + 4 + block * 2] * stride;
8414
+ const count = ops[at + 5 + block * 2] * stride;
8415
+ span(array, from, count, "gather");
8416
+ scratch3.set(array.subarray(from, from + count), written);
8417
+ written += count;
8418
+ }
8419
+ span(array, 0, written, "gather target");
8420
+ array.set(scratch3);
8421
+ }
8422
+ function lanes(array, ops, at) {
8423
+ const stride = ops[at + 2];
8424
+ const count = ops[at + 3];
8425
+ if (!(count <= stride)) throw new RangeError("TN_WORLD_RECORDS: lanes wider than the record");
8426
+ for (let record = 0; record + stride <= array.length; record += stride)
8427
+ for (let lane = 0; lane < count; lane += 1) array[record + lane] = ops[at + 4 + lane];
8428
+ }
8429
+ function applyRecords(attributes, ops, payload) {
8430
+ const boxes = [];
8431
+ for (let at = 0; at < ops.length; ) at = applyOp(attributes, ops, at, payload, boxes);
8432
+ return boxes;
8433
+ }
8434
+ function applyOp(attributes, ops, at, payload, boxes) {
8435
+ const attribute2 = attributes[ops[at + 1]];
8436
+ if (attribute2 === void 0) throw new RangeError("TN_WORLD_RECORDS: an op names no attribute");
8437
+ const array = attribute2.array;
8438
+ const a = ops[at + 2];
8439
+ const b = ops[at + 3];
8440
+ const c = ops[at + 4];
8441
+ switch (ops[at]) {
8442
+ case RECORD_OP.write:
8443
+ span(array, a, b, "write");
8444
+ span(payload, c, b, "payload");
8445
+ array.set(payload.subarray(c, c + b), a);
8446
+ return at + 5;
8447
+ case RECORD_OP.fill:
8448
+ span(array, a, b, "fill");
8449
+ array.fill(0, a, a + b);
8450
+ return at + 4;
8451
+ case RECORD_OP.move:
8452
+ span(array, a, c, "move source");
8453
+ span(array, b, c, "move target");
8454
+ array.copyWithin(b, a, a + c);
8455
+ return at + 5;
8456
+ case RECORD_OP.copy: {
8457
+ const source = attributes[a]?.array;
8458
+ if (source === void 0) throw new RangeError("TN_WORLD_RECORDS: copy names no source");
8459
+ span(array, 0, b, "copy target");
8460
+ span(source, 0, b, "copy source");
8461
+ array.set(source.subarray(0, b));
8462
+ return at + 4;
8463
+ }
8464
+ case RECORD_OP.gather:
8465
+ gather(array, ops, at);
8466
+ return at + 4 + b * 2;
8467
+ case RECORD_OP.upload:
8468
+ span(array, a, b, "upload");
8469
+ attribute2.clearUpdateRanges();
8470
+ if (b > 0) attribute2.addUpdateRange(a, b);
8471
+ attribute2.needsUpdate = true;
8472
+ return at + 4;
8473
+ case RECORD_OP.box:
8474
+ span(array, a * 16, b * 16, "box");
8475
+ span(payload, c, 6, "box payload");
8476
+ boxes.push(...boxOf(array, a, b, payload, c));
8477
+ return at + 5;
8478
+ case RECORD_OP.lanes:
8479
+ lanes(array, ops, at);
8480
+ return at + 4 + b;
8481
+ default:
8482
+ throw new RangeError(`TN_WORLD_RECORDS: unknown op ${String(ops[at])}`);
8483
+ }
8484
+ }
8485
+ function boxOf(array, from, count, local, at) {
8486
+ const cx = local[at];
8487
+ const cy = local[at + 1];
8488
+ const cz = local[at + 2];
8489
+ const hx = local[at + 3];
8490
+ const hy = local[at + 4];
8491
+ const hz = local[at + 5];
8492
+ let minX = Number.POSITIVE_INFINITY;
8493
+ let minY = Number.POSITIVE_INFINITY;
8494
+ let minZ = Number.POSITIVE_INFINITY;
8495
+ let maxX = Number.NEGATIVE_INFINITY;
8496
+ let maxY = Number.NEGATIVE_INFINITY;
8497
+ let maxZ = Number.NEGATIVE_INFINITY;
8498
+ let scale = 0;
8499
+ for (let index = from; index < from + count; index += 1) {
8500
+ const m = index * 16;
8501
+ const m0 = array[m];
8502
+ const m1 = array[m + 1];
8503
+ const m2 = array[m + 2];
8504
+ const m4 = array[m + 4];
8505
+ const m5 = array[m + 5];
8506
+ const m6 = array[m + 6];
8507
+ const m8 = array[m + 8];
8508
+ const m9 = array[m + 9];
8509
+ const m10 = array[m + 10];
8510
+ const px = m0 * cx + m4 * cy + m8 * cz + array[m + 12];
8511
+ const py = m1 * cx + m5 * cy + m9 * cz + array[m + 13];
8512
+ const pz = m2 * cx + m6 * cy + m10 * cz + array[m + 14];
8513
+ const ex = Math.abs(m0) * hx + Math.abs(m4) * hy + Math.abs(m8) * hz;
8514
+ const ey = Math.abs(m1) * hx + Math.abs(m5) * hy + Math.abs(m9) * hz;
8515
+ const ez = Math.abs(m2) * hx + Math.abs(m6) * hy + Math.abs(m10) * hz;
8516
+ if (px - ex < minX) minX = px - ex;
8517
+ if (py - ey < minY) minY = py - ey;
8518
+ if (pz - ez < minZ) minZ = pz - ez;
8519
+ if (px + ex > maxX) maxX = px + ex;
8520
+ if (py + ey > maxY) maxY = py + ey;
8521
+ if (pz + ez > maxZ) maxZ = pz + ez;
8522
+ const basis = Math.max(Math.hypot(m0, m1, m2), Math.hypot(m4, m5, m6), Math.hypot(m8, m9, m10));
8523
+ if (basis > scale) scale = basis;
8524
+ }
8525
+ return [minX, minY, minZ, maxX, maxY, maxZ, scale];
8526
+ }
8527
+ function placedBox(target, min, max, matrix2) {
8528
+ target.min.fromArray(min);
8529
+ target.max.fromArray(max);
8530
+ if (target.isEmpty()) return target;
8531
+ const e = matrix2.elements;
8532
+ const cx = (min[0] + max[0]) / 2;
8533
+ const cy = (min[1] + max[1]) / 2;
8534
+ const cz = (min[2] + max[2]) / 2;
8535
+ const hx = (max[0] - min[0]) / 2;
8536
+ const hy = (max[1] - min[1]) / 2;
8537
+ const hz = (max[2] - min[2]) / 2;
8538
+ for (let axis = 0; axis < 3; axis += 1) {
8539
+ const a = e[axis];
8540
+ const b = e[axis + 4];
8541
+ const c = e[axis + 8];
8542
+ const centre = a * cx + b * cy + c * cz + e[axis + 12];
8543
+ const half = Math.abs(a) * hx + Math.abs(b) * hy + Math.abs(c) * hz;
8544
+ target.min.setComponent(axis, centre - half);
8545
+ target.max.setComponent(axis, centre + half);
8546
+ }
8547
+ return target;
8548
+ }
8549
+
8550
+ // src/render/mesh-pool.ts
7319
8551
  var MESH_POOL_MIN_CAPACITY = 64;
7320
8552
  var MESH_POOL_MAX_PER_PAIR = 8;
7321
8553
  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
8554
  var meshPool = /* @__PURE__ */ new Map();
7330
8555
  var meshPoolHeld = 0;
7331
8556
  function pooledCapacity(capacity) {
@@ -7360,8 +8585,8 @@ function parkMesh(mesh) {
7360
8585
  mesh.frustumCulled = false;
7361
8586
  mesh.castShadow = false;
7362
8587
  mesh.receiveShadow = false;
7363
- mesh.instanceMatrix.array.fill(0);
7364
- mesh.instanceMatrix.needsUpdate = true;
8588
+ batchRecords.fill(mesh.instanceMatrix, 0, mesh.instanceMatrix.count * 16);
8589
+ batchRecords.upload(mesh.instanceMatrix, 0, 0);
7365
8590
  let forGeometry = meshPool.get(mesh.geometry);
7366
8591
  if (forGeometry === void 0) {
7367
8592
  forGeometry = /* @__PURE__ */ new Map();
@@ -7595,107 +8820,97 @@ function clipLadder(authored, maxRatio) {
7595
8820
  return { extents, source };
7596
8821
  }
7597
8822
 
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
8823
+ // src/renderer-facts.ts
8824
+ function rendererFacts(renderer) {
8825
+ const info = renderer?.raw?.info;
8826
+ return {
8827
+ kind: renderer?.kind ?? "unknown",
8828
+ ownedEngine: info !== void 0 && info.engine !== void 0
7656
8829
  };
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
8830
  }
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
- );
8831
+
8832
+ // src/world-gpu-types.ts
8833
+ function frustumPlanes(matrix2, out) {
8834
+ const m = matrix2.elements;
8835
+ const rows = [0, -1, 0, 1, 1, 1, 1, -1, 2, -1, 2, 1];
8836
+ for (let plane = 0; plane < 6; plane += 1) {
8837
+ const k = rows[plane * 2];
8838
+ const sign = rows[plane * 2 + 1];
8839
+ const x = m[3] + sign * m[k];
8840
+ const y = m[7] + sign * m[4 + k];
8841
+ const z = m[11] + sign * m[8 + k];
8842
+ const w = m[15] + sign * m[12 + k];
8843
+ const inverse = 1 / Math.hypot(x, y, z);
8844
+ const at = plane * 4;
8845
+ out[at] = x * inverse;
8846
+ out[at + 1] = y * inverse;
8847
+ out[at + 2] = z * inverse;
8848
+ out[at + 3] = w * inverse;
8849
+ }
8850
+ }
8851
+ var DRAW_ARGS_WORDS = 5;
8852
+ var LOCAL_WORDS = 16;
8853
+ var PLACEMENT_WORDS = 24;
8854
+ var DRAW_ARGS_BYTES = DRAW_ARGS_WORDS * 4;
8855
+ function argsWords(keys) {
8856
+ return keys * DRAW_ARGS_WORDS + keys;
8857
+ }
8858
+ var VEC4_WORDS = 4;
8859
+ var SLOT_NONE = -1;
8860
+ var STORAGE_WORDS = {
8861
+ /**
8862
+ * `mat4` + `centre` (vec4) + `info` (vec4), so one placement is 96 bytes and one stride. Nothing
8863
+ * is allocated from this key any more: the kernels read one placement as {@link PLACEMENT_ROWS}
8864
+ * consecutive `vec4` rows, and the source buffer is allocated in those rows. The key stays as the
8865
+ * name of the record's whole stride.
8866
+ */
8867
+ // quality-allow: the object key names one placement's whole stride, so it keeps that spelling.
8868
+ // biome-ignore lint/style/useNamingConvention: the key names one placement's whole stride, spelled as its record.
8869
+ GpuPlacement: PLACEMENT_WORDS,
8870
+ /** `mat4`, one per key: the part's own offset inside the model, the same one the CPU composes. */
8871
+ mat4: LOCAL_WORDS,
8872
+ /** `DrawIndexedIndirect`'s five words; `uint` is one word, so the element count is the word count. */
8873
+ uint: 1,
8874
+ /** One `vec4` per key, per asset slot and per level gate. */
8875
+ vec4: VEC4_WORDS
8876
+ };
8877
+ function storageAttribute(ctor, type, count, array = Float32Array) {
8878
+ const words2 = STORAGE_WORDS[type];
8879
+ return new ctor(new array(Math.max(1, count) * words2), words2);
8880
+ }
8881
+ var VALIDATE_EVERY = 30;
8882
+ var TALLY_EVERY = 30;
8883
+ var PLACEMENT_ROWS = PLACEMENT_WORDS / VEC4_WORDS;
8884
+ function growBuffer(current, needed, make) {
8885
+ if (current.count >= needed) return current;
8886
+ let capacity = Math.max(1, current.count);
8887
+ while (capacity < needed) capacity *= 2;
8888
+ const grown2 = make(capacity);
8889
+ grown2.array.set(current.array);
8890
+ grown2.addUpdateRange(0, current.array.length);
8891
+ return grown2;
8892
+ }
8893
+ function addRange(attribute2, start, count) {
8894
+ const last = attribute2.updateRanges[attribute2.updateRanges.length - 1];
8895
+ if (last === void 0 || start > last.start + last.count || start + count < last.start) {
8896
+ attribute2.addUpdateRange(start, count);
8897
+ return;
7697
8898
  }
7698
- return results;
8899
+ const newStart = Math.min(last.start, start);
8900
+ last.count = Math.max(last.start + last.count, start + count) - newStart;
8901
+ last.start = newStart;
7699
8902
  }
8903
+ var NO_LOCAL = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
8904
+ function nodes(value) {
8905
+ return value;
8906
+ }
8907
+ var STORAGE_PLAIN = {
8908
+ gates: "vec4",
8909
+ keys: "vec4",
8910
+ levels: "vec4",
8911
+ locals: "mat4",
8912
+ source: "vec4"
8913
+ };
8914
+ var SOURCE_FLOOR = 16;
7700
8915
 
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 };
8916
+ 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, 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 };