@threenative/core 0.3.6 → 0.3.8

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 (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
package/dist/world.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Vector3, Sphere, Matrix4, Frustum, Object3D, LOD, BufferGeometry, Mesh, Group, Quaternion, Box3, InstancedMesh, InstancedBufferAttribute, BufferAttribute, RepeatWrapping, DataArrayTexture, RGBAFormat, UnsignedByteType, NoColorSpace, LinearFilter, LinearMipmapLinearFilter, PerspectiveCamera, Vector4, Scene, OrthographicCamera, Color, SkinnedMesh, DoubleSide, Float32BufferAttribute, Texture, Material, CompressedArrayTexture, Vector2, SRGBColorSpace, NoBlending, TextureUtils, InstancedInterleavedBuffer, DynamicDrawUsage, Matrix3, RGBA_ASTC_4x4_Format } from 'three';
1
+ import { Vector3, Sphere, Matrix4, Frustum, Object3D, LOD, BufferGeometry, Mesh, Group, Quaternion, Box3, InstancedMesh, InstancedBufferAttribute, BufferAttribute, RepeatWrapping, DataArrayTexture, RGBAFormat, UnsignedByteType, NoColorSpace, LinearFilter, LinearMipmapLinearFilter, PerspectiveCamera, Vector4, Scene, OrthographicCamera, Color, SkinnedMesh, DoubleSide, Float32BufferAttribute, Texture, Material, CompressedArrayTexture, Vector2, SRGBColorSpace, NoBlending, TextureUtils, RGBA_ASTC_4x4_Format, InstancedInterleavedBuffer, DynamicDrawUsage, Matrix3 } from 'three';
2
2
  import { struct, vec2, positionWorld, float, texture, int, mx_noise_float, vec3, clamp, mix, normalWorld, cameraViewMatrix, vec4, smoothstep as smoothstep$1, cameraPosition, dot, uniform, storage, Fn, If, instanceIndex, Return, length, abs, Loop, max, atomicAdd, min, varyingProperty, modelWorldMatrix, select, normalize, positionGeometry, attribute, transformNormal, instancedArray, textureLoad, ivec2, ceil, log2, pow, diffuseColor, positionView, mrt, element, cameraProjectionMatrix, mat3, cross, floor, Break, mat4, instancedDynamicBufferAttribute, instancedBufferAttribute, dFdx, dFdy, pmremTexture, uv, uint, atomicLoad, log } from 'three/tsl';
3
3
  import { MeshStandardNodeMaterial, BundleGroup, ReadbackBuffer, StorageBufferAttribute, IndirectStorageBufferAttribute, StorageInstancedBufferAttribute, RenderTarget, LinearMipmapLinearFilter as LinearMipmapLinearFilter$1, LinearFilter as LinearFilter$1, UnsignedByteType as UnsignedByteType$1, RGBAFormat as RGBAFormat$1, MeshBasicNodeMaterial, MeshPhysicalNodeMaterial, EventNode } from 'three/webgpu';
4
4
  import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
@@ -1291,6 +1291,10 @@ var chainsHost = globalThis;
1291
1291
  var carriedChains = chainsHost[CHAINS_KEY];
1292
1292
  var chains = carriedChains ?? /* @__PURE__ */ new WeakMap();
1293
1293
  chainsHost[CHAINS_KEY] = chains;
1294
+ var CHAINS_VERSION_KEY = /* @__PURE__ */ Symbol.for("threenative.discreteLodChainsVersion");
1295
+ var bumpChains = () => {
1296
+ chainsHost[CHAINS_VERSION_KEY] = (chainsHost[CHAINS_VERSION_KEY] ?? 0) + 1;
1297
+ };
1294
1298
  var cloneHooks = /* @__PURE__ */ new WeakSet();
1295
1299
  function preserveChainClones(registered) {
1296
1300
  for (const source of registered.chain.levels) {
@@ -1323,6 +1327,7 @@ function preserveChainClones(registered) {
1323
1327
  policy: current.policy
1324
1328
  };
1325
1329
  for (const geometry of levels) chains.set(geometry, copied);
1330
+ bumpChains();
1326
1331
  preserveChainClones(copied);
1327
1332
  const apply = copy.applyMatrix4.bind(copy);
1328
1333
  copy.applyMatrix4 = (matrix) => {
@@ -1468,6 +1473,7 @@ var DiscreteLodPlugin = class {
1468
1473
  policy: applied
1469
1474
  };
1470
1475
  for (const geometry of levels) chains.set(geometry, registered);
1476
+ bumpChains();
1471
1477
  preserveChainClones(registered);
1472
1478
  controllers.set(mesh, new ModelLod(mesh, registered.chain, applied));
1473
1479
  appliedCount += 1;
@@ -1539,6 +1545,7 @@ var DiscreteLodPlugin = class {
1539
1545
  policy: applied
1540
1546
  };
1541
1547
  chains.set(member.geometry, registered);
1548
+ bumpChains();
1542
1549
  }
1543
1550
  for (const geometry of registered.chain.levels) geometries.add(geometry);
1544
1551
  }
@@ -1564,6 +1571,7 @@ var DiscreteLodPlugin = class {
1564
1571
  policy: registered.policy
1565
1572
  };
1566
1573
  for (const geometry of registered.chain.levels) chains.set(geometry, withJoined);
1574
+ bumpChains();
1567
1575
  controllers.set(
1568
1576
  member,
1569
1577
  new ModelLod(member, registered.chain, applied, rung, member === authority)
@@ -1581,13 +1589,37 @@ function lodChainOf(geometry) {
1581
1589
  return chains.get(geometry)?.chain;
1582
1590
  }
1583
1591
 
1592
+ // src/profiling/debug-telemetry.ts
1593
+ var DEBUG_GLOBAL = "__THREENATIVE_DEBUG__";
1594
+ function debugRequested() {
1595
+ const host = globalThis;
1596
+ return host.process?.env?.TN_DEBUG === "1" || globalThis[DEBUG_GLOBAL] === true || /[?&]tnDebug=1(?:&|$)/u.test(globalThis.location?.search ?? "");
1597
+ }
1598
+ function countDebug(name, value, area, caller, unit2 = "count") {
1599
+ if (!Number.isFinite(value) || value < 0)
1600
+ throw new Error(`TN_DEBUG: invalid ${name} observation.`);
1601
+ const host = globalThis;
1602
+ host.__tnEngineCost ??= {};
1603
+ host.__tnDebugSources ??= {};
1604
+ host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + value;
1605
+ host.__tnDebugSources[name] ??= { area, caller, unit: unit2 };
1606
+ }
1607
+ function measureDebug(name, area, caller, run) {
1608
+ const start = performance.now();
1609
+ try {
1610
+ return run();
1611
+ } finally {
1612
+ countDebug(`${name}Ms`, performance.now() - start, area, caller, "ms");
1613
+ countDebug(`${name}Calls`, 1, area, caller);
1614
+ }
1615
+ }
1616
+
1584
1617
  // src/profiling/Spans.ts
1585
1618
  var SPANS = {
1586
1619
  /** Terrain block rebuild and merged-attribute swap on the calling thread. */
1587
1620
  terrainBlock: 14,
1588
1621
  /** Terrain seam reconciliation and bridge-attribute swap on the calling thread. */
1589
- terrainSeam: 15
1590
- };
1622
+ terrainSeam: 15};
1591
1623
  var RECORDER_SLOT = /* @__PURE__ */ Symbol.for("threenative.frameSpans.recorder");
1592
1624
  function recorderHost() {
1593
1625
  return globalThis;
@@ -4417,9 +4449,9 @@ var TerrainTiles = class _TerrainTiles extends Object3D {
4417
4449
  "TerrainTiles residentByteBudget cannot fit stitched neighbor geometry."
4418
4450
  );
4419
4451
  if (this.#validate) {
4420
- const scratch2 = this.#ringScratch;
4452
+ const scratch3 = this.#ringScratch;
4421
4453
  this.#ringScratch = this.#settledRing ?? [];
4422
- this.#settledRing = scratch2;
4454
+ this.#settledRing = scratch3;
4423
4455
  this.#ringStateInto(this.#settledRing);
4424
4456
  }
4425
4457
  this.#seamEpoch = this.#ringEpoch;
@@ -4937,7 +4969,7 @@ function validateWorldPackage(manifest, options) {
4937
4969
  }
4938
4970
  return value;
4939
4971
  };
4940
- const text = (value, path) => {
4972
+ const text2 = (value, path) => {
4941
4973
  if (typeof value !== "string" || value.length === 0) {
4942
4974
  malformed(path, `${path} must be a non-empty string.`);
4943
4975
  return void 0;
@@ -4974,7 +5006,7 @@ function validateWorldPackage(manifest, options) {
4974
5006
  malformed("terrain", "World package terrain is required and must be an object.");
4975
5007
  } else {
4976
5008
  const raw = manifest.terrain;
4977
- const heightmap = text(raw.heightmap, "terrain.heightmap");
5009
+ const heightmap = text2(raw.heightmap, "terrain.heightmap");
4978
5010
  const columns = positiveInteger2(raw.columns, "terrain.columns");
4979
5011
  const rows = positiveInteger2(raw.rows, "terrain.rows");
4980
5012
  const spacing = positive4(raw.spacing, "terrain.spacing");
@@ -4987,7 +5019,7 @@ function validateWorldPackage(manifest, options) {
4987
5019
  } else {
4988
5020
  layers = {};
4989
5021
  for (const [name, value] of Object.entries(raw.layers)) {
4990
- const path = text(value, `terrain.layers.${name}`);
5022
+ const path = text2(value, `terrain.layers.${name}`);
4991
5023
  if (path !== void 0) layers[name] = path;
4992
5024
  }
4993
5025
  }
@@ -5038,7 +5070,7 @@ function validateWorldPackage(manifest, options) {
5038
5070
  malformed(path, `${path} must be an object.`);
5039
5071
  continue;
5040
5072
  }
5041
- text(value.glb, `${path}.glb`);
5073
+ text2(value.glb, `${path}.glb`);
5042
5074
  if (!isRecord(value.bounds)) {
5043
5075
  malformed(`${path}.bounds`, `${path}.bounds is required and must be an object.`);
5044
5076
  } else {
@@ -5061,7 +5093,7 @@ function validateWorldPackage(manifest, options) {
5061
5093
  malformed(lodPath, `${lodPath} must be an object.`);
5062
5094
  return;
5063
5095
  }
5064
- text(lod.glb, `${lodPath}.glb`);
5096
+ text2(lod.glb, `${lodPath}.glb`);
5065
5097
  finite6(lod.distance, `${lodPath}.distance`);
5066
5098
  });
5067
5099
  }
@@ -5069,7 +5101,7 @@ function validateWorldPackage(manifest, options) {
5069
5101
  if (value.maxDistance !== void 0) finite6(value.maxDistance, `${path}.maxDistance`);
5070
5102
  }
5071
5103
  }
5072
- text(manifest.placements, "placements");
5104
+ text2(manifest.placements, "placements");
5073
5105
  const maximumCellX = extent !== void 0 && cellSize !== void 0 ? Math.ceil(extent.sizeX / cellSize) : void 0;
5074
5106
  const maximumCellZ = extent !== void 0 && cellSize !== void 0 ? Math.ceil(extent.sizeZ / cellSize) : void 0;
5075
5107
  if (!Array.isArray(manifest.cells)) {
@@ -5104,7 +5136,7 @@ function validateWorldPackage(manifest, options) {
5104
5136
  if (!isRecord(cell.proxy)) malformed(proxyPath, `${proxyPath} must be an object.`);
5105
5137
  else {
5106
5138
  const proxy = cell.proxy;
5107
- text(proxy.glb, `${proxyPath}.glb`);
5139
+ text2(proxy.glb, `${proxyPath}.glb`);
5108
5140
  const error = finite6(proxy.error, `${proxyPath}.error`);
5109
5141
  if (error !== void 0 && error < 0)
5110
5142
  malformed(`${proxyPath}.error`, "Proxy error must be non-negative.");
@@ -5199,6 +5231,7 @@ var RECOVERED_INDENT = 4e-4;
5199
5231
  var RECOVERED_COMPACTION = 8e-3;
5200
5232
  var WIND_EROSION = 65e-5;
5201
5233
  var DEPOSITION_BURIAL = 26;
5234
+ var MAX_UNTAKEN_WINDOWS = 32;
5202
5235
  var MAX_CONTACT_CELLS = 1 << 20;
5203
5236
  var EMPTY_SAMPLE = Object.freeze({
5204
5237
  bank: 0,
@@ -5303,6 +5336,7 @@ var SnowField = class {
5303
5336
  #version = 0;
5304
5337
  #dirty;
5305
5338
  #untaken;
5339
+ #untakenWindows = [];
5306
5340
  #scratch = new Float32Array(0);
5307
5341
  constructor(options) {
5308
5342
  const field = options.field;
@@ -5362,8 +5396,21 @@ var SnowField = class {
5362
5396
  takeDirtyRegion() {
5363
5397
  const region = this.#untaken;
5364
5398
  this.#untaken = void 0;
5399
+ this.#untakenWindows = [];
5365
5400
  return region;
5366
5401
  }
5402
+ /**
5403
+ * The windows written since the previous call, then forgotten. Windows that overlap or touch
5404
+ * are one window, so two bodies a long way apart are two small windows, where
5405
+ * `takeDirtyRegion` returns the large box around both. A renderer that uploads only what moved
5406
+ * takes this. Like `takeDirtyRegion` it has one owner, and taking either one empties both.
5407
+ */
5408
+ takeDirtyRegions() {
5409
+ const windows = this.#untakenWindows;
5410
+ this.#untaken = void 0;
5411
+ this.#untakenWindows = [];
5412
+ return windows;
5413
+ }
5367
5414
  /** Bytes retained by the four snow channels and the base terrain copy. */
5368
5415
  get memoryBytes() {
5369
5416
  return (4 * this.#indent.length + this.#base.length) * Float32Array.BYTES_PER_ELEMENT;
@@ -5462,15 +5509,15 @@ var SnowField = class {
5462
5509
  const fraction = this.#fraction(contact.duration ?? this.responseTime);
5463
5510
  if (fraction <= 0) return 0;
5464
5511
  if (!this.#overlaps(resolved)) return 0;
5465
- const window = this.#contactWindow(resolved.x, resolved.z, resolved.extent);
5466
- if (!this.#pressWindow(window, resolved, penetration, fraction)) return 0;
5512
+ const window2 = this.#contactWindow(resolved.x, resolved.z, resolved.extent);
5513
+ if (!this.#pressWindow(window2, resolved, penetration, fraction)) return 0;
5467
5514
  this.#steps += 1;
5468
5515
  this.#lastSink = penetration;
5469
5516
  this.#flush({
5470
- column: window.firstColumn,
5471
- columns: window.lastColumn - window.firstColumn + 1,
5472
- row: window.firstRow,
5473
- rows: window.lastRow - window.firstRow + 1
5517
+ column: window2.firstColumn,
5518
+ columns: window2.lastColumn - window2.firstColumn + 1,
5519
+ row: window2.firstRow,
5520
+ rows: window2.lastRow - window2.firstRow + 1
5474
5521
  });
5475
5522
  return penetration;
5476
5523
  }
@@ -5490,11 +5537,11 @@ var SnowField = class {
5490
5537
  return !(contact.z + contact.extent < this.minimumZ || contact.z - contact.extent > this.minimumZ + this.field.depth);
5491
5538
  }
5492
5539
  /** Sample the footprint across its window, returning whether any cell changed. */
5493
- #pressWindow(window, contact, penetration, fraction) {
5540
+ #pressWindow(window2, contact, penetration, fraction) {
5494
5541
  let touched = false;
5495
- for (let row = window.firstRow; row <= window.lastRow; row += 1) {
5542
+ for (let row = window2.firstRow; row <= window2.lastRow; row += 1) {
5496
5543
  const localZ = this.minimumZ + row * this.cellDepth - contact.z;
5497
- for (let column = window.firstColumn; column <= window.lastColumn; column += 1) {
5544
+ for (let column = window2.firstColumn; column <= window2.lastColumn; column += 1) {
5498
5545
  const localX = this.minimumX + column * this.cellWidth - contact.x;
5499
5546
  const sample = unit(
5500
5547
  contact.footprint.sample(
@@ -5675,9 +5722,29 @@ var SnowField = class {
5675
5722
  this.field.updateHeights({ ...bounds, heights });
5676
5723
  this.#dirty = { ...bounds };
5677
5724
  this.#untaken = unionBounds(this.#untaken, bounds);
5725
+ this.#untakenWindows = addWindow(this.#untakenWindows, bounds);
5678
5726
  this.#version += 1;
5679
5727
  }
5680
5728
  };
5729
+ function addWindow(windows, next) {
5730
+ let merged = next;
5731
+ let rest = [...windows];
5732
+ for (let again = true; again; ) {
5733
+ again = false;
5734
+ const keep = [];
5735
+ for (const window2 of rest) {
5736
+ const apart = window2.column > merged.column + merged.columns || merged.column > window2.column + window2.columns || window2.row > merged.row + merged.rows || merged.row > window2.row + window2.rows;
5737
+ if (apart) keep.push(window2);
5738
+ else {
5739
+ merged = unionBounds(merged, window2);
5740
+ again = true;
5741
+ }
5742
+ }
5743
+ rest = keep;
5744
+ }
5745
+ const all = [...rest, merged];
5746
+ return all.length > MAX_UNTAKEN_WINDOWS ? [all.reduce((a, b) => unionBounds(a, b))] : all;
5747
+ }
5681
5748
 
5682
5749
  // src/world-heightmap.ts
5683
5750
  var HEIGHTMAP_MAX = 65535;
@@ -6014,6 +6081,604 @@ async function loadTerrainSplat(options) {
6014
6081
  return material;
6015
6082
  }
6016
6083
 
6084
+ // src/platform.ts
6085
+ var DESKTOP_OS = /* @__PURE__ */ new Set(["linux", "macos", "windows"]);
6086
+ var MOBILE_OS = /* @__PURE__ */ new Set(["android", "ios"]);
6087
+ function isRecord2(value) {
6088
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6089
+ }
6090
+ function freezePlatform(value) {
6091
+ return Object.freeze(value);
6092
+ }
6093
+ function invalidNativePlatform(reason) {
6094
+ throw new Error(`TN_NATIVE_PLATFORM_INVALID: ${reason}`);
6095
+ }
6096
+ function nativePlatform(source) {
6097
+ if (!isRecord2(source)) invalidNativePlatform("the native marker is not an object");
6098
+ const descriptor = source.platform;
6099
+ if (!isRecord2(descriptor)) invalidNativePlatform("platform descriptor is missing");
6100
+ const runtime = descriptor.runtime;
6101
+ const os = descriptor.os;
6102
+ const formFactor = descriptor.formFactor;
6103
+ const maxTouchPoints = descriptor.maxTouchPoints;
6104
+ if (runtime !== "native") invalidNativePlatform("runtime must be native");
6105
+ if (os !== "android" && os !== "ios" && os !== "linux" && os !== "macos" && os !== "windows" && os !== "unknown") {
6106
+ invalidNativePlatform("os is unknown");
6107
+ }
6108
+ if (formFactor !== "mobile" && formFactor !== "desktop" && formFactor !== "unknown") {
6109
+ invalidNativePlatform("formFactor is unknown");
6110
+ }
6111
+ if (!Number.isInteger(maxTouchPoints) || maxTouchPoints < 0) {
6112
+ invalidNativePlatform("maxTouchPoints must be a non-negative integer");
6113
+ }
6114
+ const expectedFormFactor = MOBILE_OS.has(os) ? "mobile" : DESKTOP_OS.has(os) ? "desktop" : "unknown";
6115
+ if (formFactor !== expectedFormFactor) {
6116
+ invalidNativePlatform("os and formFactor disagree");
6117
+ }
6118
+ return freezePlatform({
6119
+ formFactor,
6120
+ maxTouchPoints,
6121
+ os,
6122
+ runtime
6123
+ });
6124
+ }
6125
+ function text(value) {
6126
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
6127
+ }
6128
+ function parseOS(value) {
6129
+ if (value === void 0) return void 0;
6130
+ const normalized = value.toLowerCase();
6131
+ if (normalized.includes("android")) return "android";
6132
+ if (/(iphone|ipad|ipod|ios)/u.test(normalized)) return "ios";
6133
+ if (/(windows|win32|win64|winnt|wince)/u.test(normalized)) return "windows";
6134
+ if (/(macintosh|mac os|macos|macintel|macppc|mac68k)/u.test(normalized)) return "macos";
6135
+ if (/(linux|x11)/u.test(normalized)) return "linux";
6136
+ return void 0;
6137
+ }
6138
+ function compatibleBrowserOS(left, right, iosUserAgent) {
6139
+ if (left === right) return true;
6140
+ if (left === "android" && right === "linux" || left === "linux" && right === "android")
6141
+ return true;
6142
+ if (iosUserAgent && (left === "ios" && right === "macos" || left === "macos" && right === "ios"))
6143
+ return true;
6144
+ return false;
6145
+ }
6146
+ function resolveBrowserOS(userAgentDataOS, navigatorOS, userAgentOS, iosUserAgent) {
6147
+ let resolved;
6148
+ for (const candidate of [userAgentDataOS, navigatorOS, userAgentOS]) {
6149
+ if (candidate === void 0) continue;
6150
+ if (resolved === void 0) {
6151
+ resolved = candidate;
6152
+ continue;
6153
+ }
6154
+ if (!compatibleBrowserOS(resolved, candidate, iosUserAgent)) return "unknown";
6155
+ if (resolved === "linux" && candidate === "android" || resolved === "macos" && candidate === "ios") {
6156
+ resolved = candidate;
6157
+ }
6158
+ }
6159
+ return resolved ?? "unknown";
6160
+ }
6161
+ function readTouchPoints(value) {
6162
+ return Number.isInteger(value) && value >= 0 ? value : 0;
6163
+ }
6164
+ function browserPlatform(source) {
6165
+ if (!isRecord2(source)) {
6166
+ return freezePlatform({
6167
+ formFactor: "unknown",
6168
+ maxTouchPoints: 0,
6169
+ os: "unknown",
6170
+ runtime: "web"
6171
+ });
6172
+ }
6173
+ const userAgentData = isRecord2(source.userAgentData) ? source.userAgentData : void 0;
6174
+ const userAgentDataOS = parseOS(text(userAgentData?.platform));
6175
+ const navigatorOS = parseOS(text(source.platform));
6176
+ const userAgent = text(source.userAgent);
6177
+ const userAgentOS = parseOS(userAgent);
6178
+ const iosUserAgent = userAgentOS === "ios";
6179
+ const os = resolveBrowserOS(userAgentDataOS, navigatorOS, userAgentOS, iosUserAgent);
6180
+ let formFactor = "unknown";
6181
+ if (typeof userAgentData?.mobile === "boolean") {
6182
+ formFactor = userAgentData.mobile ? "mobile" : "desktop";
6183
+ } else if (MOBILE_OS.has(os)) {
6184
+ formFactor = "mobile";
6185
+ } else if (DESKTOP_OS.has(os)) {
6186
+ formFactor = "desktop";
6187
+ }
6188
+ if (os === "unknown") formFactor = "unknown";
6189
+ return freezePlatform({
6190
+ formFactor,
6191
+ maxTouchPoints: readTouchPoints(source.maxTouchPoints),
6192
+ os,
6193
+ runtime: "web"
6194
+ });
6195
+ }
6196
+ function globalPlatformSource() {
6197
+ const globals = globalThis;
6198
+ return {
6199
+ native: globals.__THREENATIVE_NATIVE__,
6200
+ navigator: globals.__tnPageNavigator ?? globals.navigator
6201
+ };
6202
+ }
6203
+ function detectPlatform(source = globalPlatformSource()) {
6204
+ return source.native === void 0 ? browserPlatform(source.navigator) : nativePlatform(source.native);
6205
+ }
6206
+ var platformSnapshot;
6207
+ function getPlatform() {
6208
+ platformSnapshot ??= detectPlatform();
6209
+ return platformSnapshot;
6210
+ }
6211
+ function isNative() {
6212
+ return getPlatform().runtime === "native";
6213
+ }
6214
+
6215
+ // src/asset-cache.ts
6216
+ var CACHE_NAME = "threenative-assets";
6217
+ var DEFAULT_CONCURRENCY = 6;
6218
+ var DEFAULT_RETRY_DELAYS_MS = [500, 1e3, 2e3];
6219
+ var BYTES_HEADER = "x-tn-bytes";
6220
+ var ACCESS_HEADER = "x-tn-access";
6221
+ var ACCESS_REFRESH_MS = 36e5;
6222
+ var PRIORITY_ORDER = { now: 0, soon: 1, idle: 2 };
6223
+ function cacheStorage() {
6224
+ return globalThis.caches;
6225
+ }
6226
+ function storageManager() {
6227
+ return globalThis.navigator?.storage;
6228
+ }
6229
+ function saveDataEnabled() {
6230
+ return globalThis.navigator?.connection?.saveData === true;
6231
+ }
6232
+ function delay(ms) {
6233
+ return new Promise((resolve) => setTimeout(resolve, ms));
6234
+ }
6235
+ function canonicalUrl(url) {
6236
+ try {
6237
+ const base = globalThis.location?.href;
6238
+ return new URL(url, base ?? "http://localhost/").href;
6239
+ } catch {
6240
+ return url;
6241
+ }
6242
+ }
6243
+ function errorMessage(error) {
6244
+ if (error instanceof Error) return error.message;
6245
+ return String(error);
6246
+ }
6247
+ function manifestFingerprint(entries) {
6248
+ let hash = 2166136261;
6249
+ for (const entry of entries) {
6250
+ const text2 = `${entry.url}:${entry.bytes ?? 0};`;
6251
+ for (let index = 0; index < text2.length; index += 1) {
6252
+ hash ^= text2.charCodeAt(index);
6253
+ hash = Math.imul(hash, 16777619) >>> 0;
6254
+ }
6255
+ }
6256
+ return hash.toString(16).padStart(8, "0");
6257
+ }
6258
+ function createAssetCache(options = {}) {
6259
+ const storage4 = cacheStorage();
6260
+ const reason = options.enabled === false ? "assets.cache is false" : storage4 === void 0 ? isNative() ? "native host reads installed files" : "cache API unavailable" : void 0;
6261
+ const enabled = reason === void 0;
6262
+ const backgroundFill = options.backgroundFill !== false;
6263
+ const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
6264
+ const retryDelays = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
6265
+ let cacheName;
6266
+ const gameCacheName = options.namespace === void 0 || options.namespace === "" ? CACHE_NAME : `${CACHE_NAME}-${manifestFingerprint([{ url: options.namespace }]).slice(0, 8)}`;
6267
+ let entries = [];
6268
+ const known = /* @__PURE__ */ new Map();
6269
+ let resolveManifest;
6270
+ const manifestReady = new Promise((resolve) => {
6271
+ resolveManifest = resolve;
6272
+ });
6273
+ let persisted = false;
6274
+ let persistAsked = false;
6275
+ let hits = 0;
6276
+ let misses = 0;
6277
+ let bytesOnDisk = 0;
6278
+ let measured = false;
6279
+ let bytesTotal = 0;
6280
+ let filling = false;
6281
+ let fillStarted = false;
6282
+ let cleared = false;
6283
+ let storageFull = false;
6284
+ let cacheGeneration = 0;
6285
+ let restoreFetch;
6286
+ let nativeFetch = globalThis.fetch.bind(globalThis);
6287
+ const touched = /* @__PURE__ */ new Set();
6288
+ const requests = /* @__PURE__ */ new Map();
6289
+ const writes = /* @__PURE__ */ new Map();
6290
+ const queues = { now: [], soon: [], idle: [] };
6291
+ let active = 0;
6292
+ let activeNow = 0;
6293
+ const openCache = async () => {
6294
+ if (!enabled || cacheName === void 0 || storage4 === void 0) return void 0;
6295
+ return storage4.open(cacheName);
6296
+ };
6297
+ const pruneAndMeasure = async (cache) => {
6298
+ let total = 0;
6299
+ for (const request of await cache.keys()) {
6300
+ if (!known.has(canonicalUrl(request.url))) {
6301
+ await cache.delete(request.url);
6302
+ continue;
6303
+ }
6304
+ const response = await cache.match(request.url);
6305
+ const size = Number(response?.headers.get(BYTES_HEADER) ?? "0");
6306
+ if (Number.isFinite(size) && size > 0) total += size;
6307
+ }
6308
+ bytesOnDisk = total;
6309
+ measured = true;
6310
+ };
6311
+ const askToPersist = async () => {
6312
+ if (persistAsked) return;
6313
+ persistAsked = true;
6314
+ try {
6315
+ persisted = await storageManager()?.persist?.() === true;
6316
+ } catch {
6317
+ persisted = false;
6318
+ }
6319
+ };
6320
+ const readCandidates = async (cache) => {
6321
+ const candidates = [];
6322
+ for (const request of await cache.keys()) {
6323
+ const response = await cache.match(request.url);
6324
+ candidates.push({
6325
+ access: Number(response?.headers.get(ACCESS_HEADER) ?? "0"),
6326
+ size: Number(response?.headers.get(BYTES_HEADER) ?? "0"),
6327
+ url: request.url
6328
+ });
6329
+ }
6330
+ return candidates;
6331
+ };
6332
+ const isQuotaError = (error) => error instanceof Error && (error.name === "QuotaExceededError" || /quota/iu.test(error.message));
6333
+ const store = async (cache, url, buffer, generation) => {
6334
+ if (generation !== cacheGeneration) return;
6335
+ const put = () => cache.put(
6336
+ url,
6337
+ new Response(buffer, {
6338
+ headers: {
6339
+ [ACCESS_HEADER]: String(Date.now()),
6340
+ [BYTES_HEADER]: String(buffer.byteLength)
6341
+ }
6342
+ })
6343
+ );
6344
+ try {
6345
+ await put();
6346
+ if (measured) bytesOnDisk += buffer.byteLength;
6347
+ return;
6348
+ } catch (error) {
6349
+ if (!isQuotaError(error)) return;
6350
+ }
6351
+ try {
6352
+ const candidates = await readCandidates(cache);
6353
+ candidates.sort((left, right) => left.access - right.access);
6354
+ for (const candidate of candidates) {
6355
+ if (touched.has(canonicalUrl(candidate.url))) continue;
6356
+ if (!await cache.delete(candidate.url)) continue;
6357
+ bytesOnDisk = Math.max(0, bytesOnDisk - candidate.size);
6358
+ try {
6359
+ await put();
6360
+ if (measured) bytesOnDisk += buffer.byteLength;
6361
+ return;
6362
+ } catch (error) {
6363
+ if (!isQuotaError(error)) return;
6364
+ }
6365
+ }
6366
+ } catch {
6367
+ }
6368
+ storageFull = true;
6369
+ };
6370
+ const download = async (url, priority, expectedBytes) => {
6371
+ let last;
6372
+ for (let attempt = 0; attempt <= retryDelays.length; attempt += 1) {
6373
+ try {
6374
+ const init = priority === "idle" ? { priority: "low" } : void 0;
6375
+ const response = await (init === void 0 ? nativeFetch(url) : nativeFetch(url, init));
6376
+ if (!response.ok) {
6377
+ const status = response.status;
6378
+ const error = new Error(`status ${String(status)}`);
6379
+ const retryable = status === 408 || status === 425 || status === 429 || status >= 500;
6380
+ if (!retryable) throw Object.assign(error, { retryable: false });
6381
+ throw error;
6382
+ }
6383
+ const buffer = await response.arrayBuffer();
6384
+ if (expectedBytes !== void 0 && buffer.byteLength !== expectedBytes) {
6385
+ throw new Error(
6386
+ `incomplete download (${String(buffer.byteLength)} of ${String(expectedBytes)} bytes)`
6387
+ );
6388
+ }
6389
+ return buffer;
6390
+ } catch (error) {
6391
+ last = error;
6392
+ if (error.retryable === false) break;
6393
+ const wait = retryDelays[attempt];
6394
+ if (wait === void 0) break;
6395
+ await delay(wait);
6396
+ }
6397
+ }
6398
+ throw new Error(errorMessage(last));
6399
+ };
6400
+ const load = async (url, request, expectedBytes) => {
6401
+ if (!enabled) {
6402
+ const response = await nativeFetch(url);
6403
+ if (!response.ok) throw new Error(`status ${String(response.status)}`);
6404
+ return response.arrayBuffer();
6405
+ }
6406
+ const generation = cacheGeneration;
6407
+ const key = canonicalUrl(url);
6408
+ const pendingWrite = writes.get(key);
6409
+ if (pendingWrite !== void 0) await pendingWrite;
6410
+ let cache = expectedBytes === void 0 ? void 0 : await openCache().catch(() => void 0);
6411
+ if (cache !== void 0) {
6412
+ try {
6413
+ const hit = await cache.match(url);
6414
+ if (hit !== void 0) {
6415
+ const access = Number(hit.headers.get(ACCESS_HEADER) ?? "0");
6416
+ const cached = await hit.arrayBuffer();
6417
+ if (expectedBytes === void 0 || cached.byteLength === expectedBytes) {
6418
+ hits += 1;
6419
+ touched.add(canonicalUrl(url));
6420
+ if (Date.now() - access > ACCESS_REFRESH_MS) {
6421
+ void cache.put(
6422
+ url,
6423
+ new Response(cached, {
6424
+ headers: {
6425
+ [ACCESS_HEADER]: String(Date.now()),
6426
+ [BYTES_HEADER]: String(cached.byteLength)
6427
+ }
6428
+ })
6429
+ ).catch(() => void 0);
6430
+ }
6431
+ return cached;
6432
+ }
6433
+ console.warn(
6434
+ `TN_ASSETS_CACHE_TRUNCATED '${url}': stored ${String(cached.byteLength)} of ${String(expectedBytes)} bytes; fetching again.`
6435
+ );
6436
+ bytesOnDisk = Math.max(0, bytesOnDisk - cached.byteLength);
6437
+ await cache.delete(url);
6438
+ }
6439
+ } catch {
6440
+ cache = void 0;
6441
+ }
6442
+ }
6443
+ misses += 1;
6444
+ const buffer = await enqueue(url, request.priority, expectedBytes);
6445
+ if (cache !== void 0) {
6446
+ touched.add(key);
6447
+ void askToPersist();
6448
+ const write = store(cache, url, buffer, generation);
6449
+ if (request.priority === "idle") {
6450
+ await write;
6451
+ } else {
6452
+ writes.set(key, write);
6453
+ void write.then(() => {
6454
+ if (writes.get(key) === write) writes.delete(key);
6455
+ });
6456
+ }
6457
+ }
6458
+ return buffer;
6459
+ };
6460
+ const take = () => {
6461
+ if (queues.now.length > 0) return queues.now.shift();
6462
+ if (activeNow > 0) return void 0;
6463
+ if (queues.soon.length > 0) return queues.soon.shift();
6464
+ return queues.idle.shift();
6465
+ };
6466
+ const pump = () => {
6467
+ while (queues.now.length > 0 || active < concurrency) {
6468
+ const job = take();
6469
+ if (job === void 0) return;
6470
+ active += 1;
6471
+ if (job.priority === "now") activeNow += 1;
6472
+ void download(job.url, job.priority, job.expectedBytes).then(
6473
+ (buffer) => {
6474
+ job.resolve(buffer);
6475
+ },
6476
+ (error) => {
6477
+ job.reject(error);
6478
+ }
6479
+ ).then(() => {
6480
+ active -= 1;
6481
+ if (job.priority === "now") activeNow -= 1;
6482
+ pump();
6483
+ });
6484
+ }
6485
+ };
6486
+ const enqueue = (url, priority, expectedBytes) => new Promise((resolve, reject) => {
6487
+ queues[priority].push({ expectedBytes, priority, reject, resolve, url });
6488
+ pump();
6489
+ });
6490
+ const fetchBytes = (url, priority = "now", expectedBytes) => {
6491
+ const key = canonicalUrl(url);
6492
+ const existing = requests.get(key);
6493
+ if (existing !== void 0) {
6494
+ if (PRIORITY_ORDER[priority] < PRIORITY_ORDER[existing.priority]) {
6495
+ existing.priority = priority;
6496
+ for (const queue of Object.values(queues)) {
6497
+ const job = queue.find((candidate) => canonicalUrl(candidate.url) === key);
6498
+ if (job === void 0) continue;
6499
+ queue.splice(queue.indexOf(job), 1);
6500
+ job.priority = priority;
6501
+ queues[priority].push(job);
6502
+ break;
6503
+ }
6504
+ }
6505
+ pump();
6506
+ return existing.promise;
6507
+ }
6508
+ const request = { priority };
6509
+ request.promise = load(url, request, expectedBytes);
6510
+ requests.set(key, request);
6511
+ const promise = request.promise;
6512
+ void promise.then(
6513
+ () => requests.delete(key),
6514
+ () => requests.delete(key)
6515
+ );
6516
+ return promise;
6517
+ };
6518
+ const prefetch = async (targets, priority) => {
6519
+ if (!enabled) return;
6520
+ await Promise.allSettled(targets.map((entry) => fetchBytes(entry.url, priority, entry.bytes)));
6521
+ };
6522
+ const installFetchBridge = (name) => {
6523
+ if (typeof globalThis.fetch !== "function" || storage4 === void 0) return;
6524
+ const original = globalThis.fetch;
6525
+ nativeFetch = original.bind(globalThis);
6526
+ const wrapped = async (input, init) => {
6527
+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");
6528
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
6529
+ const key = canonicalUrl(url);
6530
+ const expected = known.get(key);
6531
+ if (method.toUpperCase() !== "GET" || expected === void 0) return original(input, init);
6532
+ if (requests.has(key)) {
6533
+ const buffer = await fetchBytes(url, "now", expected);
6534
+ return new Response(buffer, {
6535
+ headers: { [BYTES_HEADER]: String(buffer.byteLength) }
6536
+ });
6537
+ }
6538
+ const pendingWrite = writes.get(key);
6539
+ if (pendingWrite !== void 0) await pendingWrite;
6540
+ try {
6541
+ const cache = await storage4.open(name);
6542
+ const hit = await cache.match(url);
6543
+ if (hit !== void 0) {
6544
+ const access = Number(hit.headers.get(ACCESS_HEADER) ?? "0");
6545
+ const cached = await hit.arrayBuffer();
6546
+ if (cached.byteLength === expected) {
6547
+ touched.add(key);
6548
+ if (Date.now() - access > ACCESS_REFRESH_MS) {
6549
+ void cache.put(
6550
+ url,
6551
+ new Response(cached, {
6552
+ headers: {
6553
+ [ACCESS_HEADER]: String(Date.now()),
6554
+ [BYTES_HEADER]: String(cached.byteLength)
6555
+ }
6556
+ })
6557
+ ).catch(() => void 0);
6558
+ }
6559
+ return new Response(cached, {
6560
+ headers: {
6561
+ [ACCESS_HEADER]: String(Date.now()),
6562
+ [BYTES_HEADER]: String(cached.byteLength)
6563
+ }
6564
+ });
6565
+ }
6566
+ console.warn(
6567
+ `TN_ASSETS_CACHE_TRUNCATED '${url}': stored ${String(cached.byteLength)} of ${String(expected)} bytes; fetching again.`
6568
+ );
6569
+ await cache.delete(url).catch(() => void 0);
6570
+ }
6571
+ } catch {
6572
+ }
6573
+ const response = await original(input, init);
6574
+ if (response.ok && !requests.has(key)) {
6575
+ try {
6576
+ const cache = await storage4.open(name);
6577
+ const copy = response.clone();
6578
+ void copy.arrayBuffer().then((buffer) => {
6579
+ if (buffer.byteLength !== expected) return void 0;
6580
+ touched.add(key);
6581
+ return store(cache, url, buffer, cacheGeneration);
6582
+ }).catch(() => void 0);
6583
+ } catch {
6584
+ }
6585
+ }
6586
+ return response;
6587
+ };
6588
+ globalThis.fetch = wrapped;
6589
+ restoreFetch = () => {
6590
+ if (globalThis.fetch === wrapped) globalThis.fetch = original;
6591
+ };
6592
+ };
6593
+ const runFill = async () => {
6594
+ await manifestReady;
6595
+ if (!enabled || !backgroundFill || entries.length === 0) return;
6596
+ filling = true;
6597
+ try {
6598
+ const chunk = Math.max(1, concurrency);
6599
+ for (let index = 0; index < entries.length; index += chunk) {
6600
+ if (cleared || storageFull || saveDataEnabled()) break;
6601
+ await prefetch(entries.slice(index, index + chunk), "idle");
6602
+ }
6603
+ } finally {
6604
+ filling = false;
6605
+ }
6606
+ };
6607
+ return {
6608
+ get enabled() {
6609
+ return enabled;
6610
+ },
6611
+ get report() {
6612
+ return {
6613
+ enabled,
6614
+ persisted,
6615
+ hits,
6616
+ misses,
6617
+ bytesOnDisk,
6618
+ bytesTotal,
6619
+ filling,
6620
+ backgroundFill: enabled && backgroundFill && !saveDataEnabled(),
6621
+ ...reason === void 0 ? {} : { reason }
6622
+ };
6623
+ },
6624
+ fetchBytes,
6625
+ promote: (url, priority) => {
6626
+ if (requests.has(canonicalUrl(url))) void fetchBytes(url, priority).catch(() => void 0);
6627
+ },
6628
+ prefetch: async (targets) => prefetch(targets, "soon"),
6629
+ setManifest: (manifestEntries) => {
6630
+ if (cacheName !== void 0) return;
6631
+ if (manifestEntries.length === 0) {
6632
+ resolveManifest?.();
6633
+ return;
6634
+ }
6635
+ entries = manifestEntries;
6636
+ known.clear();
6637
+ for (const entry of manifestEntries) known.set(canonicalUrl(entry.url), entry.bytes);
6638
+ bytesTotal = manifestEntries.reduce((sum, entry) => sum + (entry.bytes ?? 0), 0);
6639
+ void storageManager()?.persisted?.().then((granted) => {
6640
+ persisted = granted === true;
6641
+ }).catch(() => void 0);
6642
+ if (!enabled) {
6643
+ resolveManifest?.();
6644
+ return;
6645
+ }
6646
+ cacheName = gameCacheName;
6647
+ installFetchBridge(gameCacheName);
6648
+ void (async () => {
6649
+ try {
6650
+ const cache = await openCache();
6651
+ if (cache !== void 0) await pruneAndMeasure(cache);
6652
+ } catch {
6653
+ }
6654
+ resolveManifest?.();
6655
+ })();
6656
+ },
6657
+ startFill: () => {
6658
+ if (fillStarted || cleared) return Promise.resolve();
6659
+ fillStarted = true;
6660
+ return runFill().catch(() => void 0);
6661
+ },
6662
+ clear: async () => {
6663
+ cleared = true;
6664
+ fillStarted = true;
6665
+ cacheGeneration += 1;
6666
+ storageFull = false;
6667
+ if (cacheName === void 0 || storage4 === void 0) {
6668
+ bytesOnDisk = 0;
6669
+ return;
6670
+ }
6671
+ await storage4.delete(cacheName);
6672
+ bytesOnDisk = 0;
6673
+ touched.clear();
6674
+ },
6675
+ dispose: () => {
6676
+ restoreFetch?.();
6677
+ restoreFetch = void 0;
6678
+ }
6679
+ };
6680
+ }
6681
+
6017
6682
  // src/engine-render-hook.ts
6018
6683
  var engineRenderHooks = /* @__PURE__ */ new WeakSet();
6019
6684
  function markEngineRenderHook(hook) {
@@ -6043,20 +6708,20 @@ function configuredTexture(texture3, options) {
6043
6708
  var MANIFEST_VERSION = 1;
6044
6709
  var ASTC_FORMAT = "astc4x4";
6045
6710
  function entryUsesKtx2(entry) {
6046
- if (!isRecord2(entry)) return false;
6711
+ if (!isRecord3(entry)) return false;
6047
6712
  if (typeof entry.output === "string" && /\.ktx2$/iu.test(entry.output)) return true;
6048
6713
  if (Array.isArray(entry.extensions) && entry.extensions.some(
6049
6714
  (extension) => extension === "KHR_texture_basisu" || extension === "EXT_texture_astc"
6050
6715
  ))
6051
6716
  return true;
6052
6717
  const embeddedTextures = entry.embeddedTextures;
6053
- if (isRecord2(embeddedTextures) && isRecord2(embeddedTextures.formats) && Object.values(embeddedTextures.formats).some(
6718
+ if (isRecord3(embeddedTextures) && isRecord3(embeddedTextures.formats) && Object.values(embeddedTextures.formats).some(
6054
6719
  (format) => typeof format === "string" && format !== "none"
6055
6720
  ))
6056
6721
  return true;
6057
6722
  return [entry.lightmaps, entry.sharedImages].some(
6058
6723
  (outputs) => Array.isArray(outputs) && outputs.some(
6059
- (item) => isRecord2(item) && typeof item.output === "string" && /\.ktx2$/iu.test(item.output)
6724
+ (item) => isRecord3(item) && typeof item.output === "string" && /\.ktx2$/iu.test(item.output)
6060
6725
  )
6061
6726
  );
6062
6727
  }
@@ -6064,21 +6729,21 @@ function manifestOutput(entry, fallback) {
6064
6729
  return typeof entry.output === "string" ? entry.output : fallback;
6065
6730
  }
6066
6731
  function firstRawAstcAsset(logicalPath, entry) {
6067
- if (!isRecord2(entry)) return void 0;
6732
+ if (!isRecord3(entry)) return void 0;
6068
6733
  const output = manifestOutput(entry, logicalPath);
6069
6734
  if (entry.format === ASTC_FORMAT) return { logicalPath, output };
6070
6735
  if (Array.isArray(entry.lightmaps)) {
6071
- const lightmap = entry.lightmaps.find((item) => isRecord2(item) && item.format === ASTC_FORMAT);
6072
- if (isRecord2(lightmap)) return { logicalPath, output: manifestOutput(lightmap, output) };
6736
+ const lightmap = entry.lightmaps.find((item) => isRecord3(item) && item.format === ASTC_FORMAT);
6737
+ if (isRecord3(lightmap)) return { logicalPath, output: manifestOutput(lightmap, output) };
6073
6738
  }
6074
6739
  if (Array.isArray(entry.sharedImages)) {
6075
6740
  const sharedImage = entry.sharedImages.find(
6076
- (item) => isRecord2(item) && item.codec === ASTC_FORMAT
6741
+ (item) => isRecord3(item) && item.codec === ASTC_FORMAT
6077
6742
  );
6078
- if (isRecord2(sharedImage)) return { logicalPath, output: manifestOutput(sharedImage, output) };
6743
+ if (isRecord3(sharedImage)) return { logicalPath, output: manifestOutput(sharedImage, output) };
6079
6744
  }
6080
6745
  const embeddedTextures = entry.embeddedTextures;
6081
- if (isRecord2(embeddedTextures) && isRecord2(embeddedTextures.formats) && Object.values(embeddedTextures.formats).some((format) => format === ASTC_FORMAT))
6746
+ if (isRecord3(embeddedTextures) && isRecord3(embeddedTextures.formats) && Object.values(embeddedTextures.formats).some((format) => format === ASTC_FORMAT))
6082
6747
  return { logicalPath, output };
6083
6748
  return void 0;
6084
6749
  }
@@ -6090,14 +6755,14 @@ function firstRawAstcManifestAsset(manifest) {
6090
6755
  return void 0;
6091
6756
  }
6092
6757
  function compiledLightmaps(entry, logicalPath) {
6093
- if (!isRecord2(entry) || entry.lightmaps === void 0) return [];
6758
+ if (!isRecord3(entry) || entry.lightmaps === void 0) return [];
6094
6759
  if (!Array.isArray(entry.lightmaps)) {
6095
6760
  throw new Error(
6096
6761
  `TN_ASSETS_LIGHTMAP_MANIFEST_INVALID: '${logicalPath}' lightmaps must be an array.`
6097
6762
  );
6098
6763
  }
6099
6764
  return entry.lightmaps.map((lightmap, index) => {
6100
- if (!isRecord2(lightmap) || typeof lightmap.output !== "string" || lightmap.texCoord !== 1 || !Array.isArray(lightmap.materialTargets) || !lightmap.materialTargets.every((target) => typeof target === "string")) {
6765
+ if (!isRecord3(lightmap) || typeof lightmap.output !== "string" || lightmap.texCoord !== 1 || !Array.isArray(lightmap.materialTargets) || !lightmap.materialTargets.every((target) => typeof target === "string")) {
6101
6766
  throw new Error(
6102
6767
  `TN_ASSETS_LIGHTMAP_MANIFEST_INVALID: '${logicalPath}' lightmaps[${String(index)}] must name output, texCoord 1, and string materialTargets.`
6103
6768
  );
@@ -6134,7 +6799,7 @@ async function readManifest(url) {
6134
6799
  } catch {
6135
6800
  throw new Error(`Asset manifest '${url}' does not contain valid JSON.`);
6136
6801
  }
6137
- if (!isRecord2(parsed) || parsed.version !== MANIFEST_VERSION || !isRecord2(parsed.entries)) {
6802
+ if (!isRecord3(parsed) || parsed.version !== MANIFEST_VERSION || !isRecord3(parsed.entries)) {
6138
6803
  throw new Error(
6139
6804
  `Asset manifest '${url}' must be version ${MANIFEST_VERSION} with an 'entries' object.`
6140
6805
  );
@@ -6167,24 +6832,43 @@ function declaredExtensions(data) {
6167
6832
  return /* @__PURE__ */ new Set();
6168
6833
  }
6169
6834
  }
6170
- async function fetchModelBytes(url) {
6171
- let response;
6835
+ async function fetchModelBytes(url, cache, expectedBytes, priority) {
6172
6836
  try {
6173
- response = await fetch(url);
6837
+ return await cache.fetchBytes(url, priority, expectedBytes);
6174
6838
  } catch (error) {
6175
6839
  throw new Error(
6176
6840
  `Failed to load model '${url}': ${error instanceof Error ? error.message : String(error)}.`
6177
6841
  );
6178
6842
  }
6179
- if (!response.ok) throw new Error(`Failed to load model '${url}': ${response.status}.`);
6180
- return response.arrayBuffer();
6181
6843
  }
6182
- async function loadBitmapTexture(url, renderer) {
6183
- const response = await fetch(url);
6184
- if (!response.ok) throw new Error(`Failed to load texture '${url}': ${response.status}.`);
6185
- const blob = new Blob([await response.arrayBuffer()]);
6844
+ async function loadBitmapTexture(url, renderer, cache, expectedBytes, priority) {
6845
+ let data;
6846
+ try {
6847
+ data = await cache.fetchBytes(url, priority, expectedBytes);
6848
+ } catch (error) {
6849
+ throw new Error(
6850
+ `Failed to load texture '${url}': ${error instanceof Error ? error.message : String(error)}.`
6851
+ );
6852
+ }
6853
+ const blob = new Blob([data]);
6186
6854
  const flipsAtUpload = renderer === void 0 || renderer.isWebGPURenderer === true;
6187
- const bitmap = await (flipsAtUpload ? createImageBitmap(blob) : createImageBitmap(blob, { imageOrientation: "flipY" }));
6855
+ const debug = debugRequested();
6856
+ const start = debug ? performanceNow() : 0;
6857
+ const pending = flipsAtUpload ? createImageBitmap(blob) : createImageBitmap(blob, { imageOrientation: "flipY" });
6858
+ if (debug) {
6859
+ const elapsed = performanceNow() - start;
6860
+ countDebug("textureDecodeDispatchMs", elapsed, "loading", "loadBitmapTexture (all URLs)", "ms");
6861
+ countDebug(`textureDecode.${url}DispatchMs`, elapsed, "loading", url, "ms");
6862
+ }
6863
+ const bitmap = await pending;
6864
+ if (debug) {
6865
+ const caller = "loadBitmapTexture (all URLs)";
6866
+ const elapsed = performanceNow() - start;
6867
+ countDebug("textureDecodes", 1, "loading", caller);
6868
+ countDebug("textureDecodeBytes", data.byteLength, "loading", caller, "bytes");
6869
+ countDebug("textureDecodeWallMs", elapsed, "loading", caller, "async-ms");
6870
+ countDebug(`textureDecode.${url}WallMs`, elapsed, "loading", url, "async-ms");
6871
+ }
6188
6872
  const texture3 = new Texture(bitmap);
6189
6873
  texture3.flipY = flipsAtUpload;
6190
6874
  texture3.needsUpdate = true;
@@ -6212,7 +6896,7 @@ function attachLightmap(value, specification, texture3) {
6212
6896
  const renderable = object;
6213
6897
  const materials = Array.isArray(renderable.material) ? renderable.material : [renderable.material];
6214
6898
  for (const material of materials) {
6215
- if (!isRecord2(material) || !targets.has(String(material.name ?? ""))) continue;
6899
+ if (!isRecord3(material) || !targets.has(String(material.name ?? ""))) continue;
6216
6900
  if (renderable.geometry?.getAttribute(`uv${String(specification.texCoord)}`) === void 0) {
6217
6901
  throw new Error(
6218
6902
  `TN_ASSETS_LIGHTMAP_UV2_MISSING: material '${String(material.name ?? "")}' has no TEXCOORD_1 geometry.`
@@ -6381,12 +7065,57 @@ function reconcileMirroredClips(root, clips) {
6381
7065
  return true;
6382
7066
  }
6383
7067
  function createAssetLoader(options = {}) {
7068
+ const debug = debugRequested();
6384
7069
  const basePath = options.basePath ?? "";
6385
7070
  const sourcePath = (options.sourcePath ?? "assets").replace(/^\/+|\/+$/gu, "");
6386
7071
  const manifestUrl = resolvePath(basePath, options.manifest ?? "assets.manifest.json");
7072
+ const assetCache = createAssetCache({
7073
+ enabled: options.cache,
7074
+ backgroundFill: options.backgroundFill,
7075
+ // A different manifest url is a different game on the same origin, and must not delete this
7076
+ // one's cache at startup. Two urls of the same page (`/` and `/index.html`) read the same one.
7077
+ namespace: canonicalUrl(manifestUrl)
7078
+ });
7079
+ const fillEntries = (manifest) => {
7080
+ const byUrl = /* @__PURE__ */ new Map();
7081
+ const add = (output, bytes) => {
7082
+ if (typeof output !== "string" || !isSize(bytes)) return;
7083
+ const url = resolvePath(basePath, output);
7084
+ if (byUrl.has(url)) return;
7085
+ byUrl.set(url, { bytes, url });
7086
+ };
7087
+ for (const entry of Object.values(manifest.entries)) {
7088
+ if (!isRecord3(entry)) continue;
7089
+ add(entry.output, entry.bytes);
7090
+ if (Array.isArray(entry.lightmaps)) {
7091
+ for (const lightmap of entry.lightmaps) {
7092
+ if (isRecord3(lightmap)) add(lightmap.output, lightmap.bytes);
7093
+ }
7094
+ }
7095
+ if (Array.isArray(entry.sharedImages)) {
7096
+ for (const image of entry.sharedImages) {
7097
+ if (isRecord3(image)) add(image.output, image.bytes);
7098
+ }
7099
+ }
7100
+ }
7101
+ return [...byUrl.values()];
7102
+ };
6387
7103
  let manifestRequest;
6388
7104
  const manifestOnce = () => {
6389
- if (manifestRequest === void 0) manifestRequest = readManifest(manifestUrl);
7105
+ if (manifestRequest === void 0) {
7106
+ manifestRequest = readManifest(manifestUrl).catch((error) => {
7107
+ assetCache.setManifest([]);
7108
+ throw error;
7109
+ }).then((manifest) => {
7110
+ if (manifest !== void 0) {
7111
+ const entries = fillEntries(manifest);
7112
+ assetCache.setManifest(entries);
7113
+ } else {
7114
+ assetCache.setManifest([]);
7115
+ }
7116
+ return manifest;
7117
+ });
7118
+ }
6390
7119
  return manifestRequest;
6391
7120
  };
6392
7121
  const compressedTextures = options.renderer === void 0 ? void 0 : (() => {
@@ -6405,6 +7134,7 @@ function createAssetLoader(options = {}) {
6405
7134
  surfaces: /* @__PURE__ */ new WeakSet(),
6406
7135
  textures: /* @__PURE__ */ new WeakSet()
6407
7136
  };
7137
+ let loaderDisposed = false;
6408
7138
  const loadCompiledKtx2 = async (url) => {
6409
7139
  if (compressedTextures === void 0) {
6410
7140
  throw new Error(
@@ -6453,9 +7183,9 @@ function createAssetLoader(options = {}) {
6453
7183
  if (isExternalAssetPath(logicalPath)) return void 0;
6454
7184
  const manifest = await manifestOnce();
6455
7185
  const entry = manifest?.entries[logicalPath];
6456
- const lod = isRecord2(entry) ? entry.lod : void 0;
6457
- const runtime = isRecord2(lod) ? lod.runtime : void 0;
6458
- if (!isRecord2(runtime) || typeof runtime.maxPixelError !== "number" || typeof runtime.hysteresis !== "number") {
7186
+ const lod = isRecord3(entry) ? entry.lod : void 0;
7187
+ const runtime = isRecord3(lod) ? lod.runtime : void 0;
7188
+ if (!isRecord3(runtime) || typeof runtime.maxPixelError !== "number" || typeof runtime.hysteresis !== "number") {
6459
7189
  return void 0;
6460
7190
  }
6461
7191
  return { hysteresis: runtime.hysteresis, maxPixelError: runtime.maxPixelError };
@@ -6465,7 +7195,7 @@ function createAssetLoader(options = {}) {
6465
7195
  const manifest = await manifestOnce();
6466
7196
  if (manifest !== void 0) {
6467
7197
  const listed = manifest.entries[path];
6468
- const output = isRecord2(listed) ? listed.output : void 0;
7198
+ const output = isRecord3(listed) ? listed.output : void 0;
6469
7199
  if (typeof output !== "string") {
6470
7200
  throw new Error(`Asset '${path}' is not listed in the asset manifest '${manifestUrl}'.`);
6471
7201
  }
@@ -6479,12 +7209,22 @@ function createAssetLoader(options = {}) {
6479
7209
  const loadFirst = async (path, { urls, via }, load) => {
6480
7210
  const failures = [];
6481
7211
  for (const url of urls) {
7212
+ const start = debug ? performanceNow() : 0;
6482
7213
  try {
6483
- const value = await load(url);
7214
+ const value = await (debug ? measureDebug(`assetDispatch.${url}`, "loading", url, () => load(url)) : load(url));
6484
7215
  resolvedAssets.set(path, { url, via });
6485
7216
  return value;
6486
7217
  } catch (error) {
6487
7218
  failures.push(`${url} (${error instanceof Error ? error.message : String(error)})`);
7219
+ } finally {
7220
+ if (debug)
7221
+ countDebug(
7222
+ `assetLoad.${url}WallMs`,
7223
+ performanceNow() - start,
7224
+ "loading",
7225
+ url,
7226
+ "async-ms"
7227
+ );
6488
7228
  }
6489
7229
  }
6490
7230
  throw new Error(
@@ -6500,18 +7240,43 @@ function createAssetLoader(options = {}) {
6500
7240
  if (isExternalAssetPath(path)) return 0;
6501
7241
  const manifest = await manifestOnce();
6502
7242
  const entry = manifest?.entries[path];
6503
- const bytes = isRecord2(entry) ? entry.bytes : void 0;
7243
+ const bytes = isRecord3(entry) ? entry.bytes : void 0;
6504
7244
  return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
6505
7245
  };
6506
- const cached = (kind, path, load) => {
7246
+ const auxiliaryOf = async (path) => {
7247
+ if (isExternalAssetPath(path)) return [];
7248
+ const entry = (await manifestOnce())?.entries[path];
7249
+ if (!isRecord3(entry)) return [];
7250
+ const files = [];
7251
+ for (const key of ["sharedImages", "lightmaps"]) {
7252
+ const outputs = entry[key];
7253
+ if (!Array.isArray(outputs)) continue;
7254
+ for (const output of outputs) {
7255
+ if (!isRecord3(output) || typeof output.output !== "string") continue;
7256
+ const bytes = output.bytes;
7257
+ if (typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0)
7258
+ files.push({ bytes, url: resolvePath(basePath, output.output) });
7259
+ }
7260
+ }
7261
+ return files;
7262
+ };
7263
+ const cached = (kind, path, load, priority = "now") => {
6507
7264
  const key = `${kind}:${path}`;
6508
7265
  const existing = cache.get(key);
6509
- if (existing !== void 0) return existing.promise;
7266
+ if (existing !== void 0) {
7267
+ if (!existing.loaded && PRIORITY_ORDER[priority] < PRIORITY_ORDER[existing.priority]) {
7268
+ existing.priority = priority;
7269
+ if (existing.url !== void 0) assetCache.promote(existing.url, priority);
7270
+ }
7271
+ return existing.promise;
7272
+ }
6510
7273
  requested += 1;
6511
7274
  let weight = 0;
6512
- const weighed = bytesOf(path).then(
6513
- (bytes) => {
7275
+ let auxiliary = [];
7276
+ const weighed = Promise.all([bytesOf(path), auxiliaryOf(path)]).then(
7277
+ ([bytes, files]) => {
6514
7278
  weight = bytes;
7279
+ auxiliary = files;
6515
7280
  requestedBytes += bytes;
6516
7281
  },
6517
7282
  () => void 0
@@ -6521,12 +7286,20 @@ function createAssetLoader(options = {}) {
6521
7286
  disposed: false,
6522
7287
  kind,
6523
7288
  loaded: false,
6524
- promise: Promise.resolve().then(() => resolveCandidates(path)).then((candidates) => loadFirst(path, candidates, load)),
7289
+ priority,
7290
+ promise: Promise.resolve().then(() => resolveCandidates(path)).then(
7291
+ (candidates) => loadFirst(path, candidates, (url) => {
7292
+ entry.url = url;
7293
+ return load(url, entry.priority);
7294
+ })
7295
+ ),
6525
7296
  released: false
6526
7297
  };
6527
7298
  entry.promise = entry.promise.then((value) => {
6528
7299
  entry.loaded = true;
6529
7300
  entry.value = value;
7301
+ const record = resolvedAssets.get(path);
7302
+ if (record !== void 0) resolvedAssets.set(path, { ...record, kind });
6530
7303
  if (entry.released) disposeEntry(entry, disposed);
6531
7304
  return value;
6532
7305
  });
@@ -6539,6 +7312,13 @@ function createAssetLoader(options = {}) {
6539
7312
  pending.delete(path);
6540
7313
  void weighed.then(() => {
6541
7314
  settledBytes += weight;
7315
+ const record = resolvedAssets.get(path);
7316
+ if (record !== void 0 && weight > 0)
7317
+ resolvedAssets.set(path, {
7318
+ ...record,
7319
+ bytes: weight,
7320
+ files: [{ bytes: weight, url: record.url }, ...auxiliary]
7321
+ });
6542
7322
  });
6543
7323
  if (traceStart !== 0) {
6544
7324
  console.log(
@@ -6564,6 +7344,67 @@ function createAssetLoader(options = {}) {
6564
7344
  () => void 0
6565
7345
  );
6566
7346
  };
7347
+ const prefetchPaths = async (paths) => {
7348
+ if (!assetCache.enabled) {
7349
+ return {
7350
+ requested: paths.length,
7351
+ requestedBytes: 0,
7352
+ settled: paths.length,
7353
+ settledBytes: 0
7354
+ };
7355
+ }
7356
+ const manifest = await manifestOnce().catch(() => void 0);
7357
+ if (manifest === void 0) {
7358
+ return {
7359
+ requested: paths.length,
7360
+ requestedBytes: 0,
7361
+ settled: paths.length,
7362
+ settledBytes: 0
7363
+ };
7364
+ }
7365
+ const targets = [];
7366
+ const addOutput = (output, bytes) => {
7367
+ if (typeof output !== "string" || !isSize(bytes)) return;
7368
+ targets.push({ bytes, url: resolvePath(basePath, output) });
7369
+ };
7370
+ for (const path of paths) {
7371
+ let urls;
7372
+ try {
7373
+ urls = (await resolveCandidates(path)).urls;
7374
+ } catch {
7375
+ continue;
7376
+ }
7377
+ const size = await bytesOf(path);
7378
+ for (const url of urls) targets.push({ url, ...size > 0 ? { bytes: size } : {} });
7379
+ const entry = manifest.entries[path];
7380
+ if (!isRecord3(entry)) continue;
7381
+ for (const key of ["lightmaps", "sharedImages"]) {
7382
+ const outputs = entry[key];
7383
+ if (!Array.isArray(outputs)) continue;
7384
+ for (const output of outputs) {
7385
+ if (!isRecord3(output)) continue;
7386
+ addOutput(output.output, output.bytes);
7387
+ }
7388
+ }
7389
+ }
7390
+ const unique = [...new Map(targets.map((target) => [target.url, target])).values()];
7391
+ const results = await Promise.allSettled(
7392
+ unique.map((target) => assetCache.fetchBytes(target.url, "soon", target.bytes))
7393
+ );
7394
+ let settled2 = 0;
7395
+ let settledBytes2 = 0;
7396
+ results.forEach((result, index) => {
7397
+ if (result.status !== "fulfilled") return;
7398
+ settled2 += 1;
7399
+ settledBytes2 += unique[index]?.bytes ?? result.value.byteLength;
7400
+ });
7401
+ return {
7402
+ requested: unique.length,
7403
+ requestedBytes: unique.reduce((sum, target) => sum + (target.bytes ?? 0), 0),
7404
+ settled: settled2,
7405
+ settledBytes: settledBytes2
7406
+ };
7407
+ };
6567
7408
  return {
6568
7409
  audio: (path) => cached("audio", path, async (url) => {
6569
7410
  if (options.audio !== void 0) return options.audio(url);
@@ -6575,101 +7416,128 @@ function createAssetLoader(options = {}) {
6575
7416
  cache.clear();
6576
7417
  entries.forEach(releaseEntry);
6577
7418
  },
7419
+ dispose: () => {
7420
+ if (loaderDisposed) return;
7421
+ loaderDisposed = true;
7422
+ assetCache.dispose();
7423
+ void compressedTextures?.loader.then((shared) => {
7424
+ shared?.dispose?.();
7425
+ }).catch(() => void 0);
7426
+ },
6578
7427
  ...compressedTextures === void 0 ? {} : { compressedTextures },
6579
- model: (path) => cached("model", path, async (url) => {
6580
- if (options.model !== void 0) {
6581
- const value2 = await options.model(url);
6582
- stampAssetProvenance(value2, path);
6583
- await attachCompiledLightmaps(path, value2);
6584
- return value2;
6585
- }
6586
- const data = await fetchModelBytes(url);
6587
- const extensions = declaredExtensions(data);
6588
- const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
6589
- const loader = new GLTFLoader();
6590
- const astcExtension = "EXT_texture_astc";
6591
- const hasBasis = extensions.has("KHR_texture_basisu");
6592
- const hasAstc = extensions.has(astcExtension);
6593
- let shared;
6594
- if (compressedTextures !== void 0 && (hasBasis || hasAstc)) {
6595
- try {
6596
- shared = await compressedTextures.loader;
6597
- } catch (error) {
6598
- if (hasBasis || !(error instanceof Error) || !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:"))
6599
- throw error;
7428
+ model: (path, request) => cached(
7429
+ "model",
7430
+ path,
7431
+ async (url, priority) => {
7432
+ if (options.model !== void 0) {
7433
+ const value2 = await options.model(url);
7434
+ stampAssetProvenance(value2, path);
7435
+ await attachCompiledLightmaps(path, value2);
7436
+ return value2;
6600
7437
  }
6601
- if (shared !== void 0) {
6602
- loader.setKTX2Loader(shared);
6603
- }
6604
- }
6605
- if (hasAstc) {
6606
- const astcLoader = shared;
6607
- const astcSupported = hasAstcSupport(astcLoader);
6608
- loader.register((parser) => {
6609
- if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
6610
- throw new Error(
6611
- "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support."
6612
- );
7438
+ const expected = await bytesOf(path);
7439
+ const data = await fetchModelBytes(
7440
+ url,
7441
+ assetCache,
7442
+ expected > 0 ? expected : void 0,
7443
+ priority
7444
+ );
7445
+ const extensions = declaredExtensions(data);
7446
+ const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
7447
+ const loader = new GLTFLoader();
7448
+ const astcExtension = "EXT_texture_astc";
7449
+ const hasBasis = extensions.has("KHR_texture_basisu");
7450
+ const hasAstc = extensions.has(astcExtension);
7451
+ let shared;
7452
+ if (compressedTextures !== void 0 && (hasBasis || hasAstc)) {
7453
+ try {
7454
+ shared = await compressedTextures.loader;
7455
+ } catch (error) {
7456
+ if (hasBasis || !(error instanceof Error) || !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:"))
7457
+ throw error;
6613
7458
  }
6614
- return {
6615
- name: astcExtension,
6616
- loadTexture(textureIndex) {
6617
- const extension = parser.json.textures[textureIndex].extensions?.[astcExtension];
6618
- if (extension === void 0 || !astcSupported || astcLoader === void 0)
6619
- return null;
6620
- return parser.loadTextureImage(
6621
- textureIndex,
6622
- extension.source,
6623
- astcLoader
7459
+ if (shared !== void 0) {
7460
+ loader.setKTX2Loader(shared);
7461
+ }
7462
+ }
7463
+ if (hasAstc) {
7464
+ const astcLoader = shared;
7465
+ const astcSupported = hasAstcSupport(astcLoader);
7466
+ loader.register((parser) => {
7467
+ if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
7468
+ throw new Error(
7469
+ "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support."
6624
7470
  );
6625
7471
  }
6626
- };
6627
- });
6628
- }
6629
- if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
6630
- const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');
6631
- loader.setMeshoptDecoder(MeshoptDecoder);
6632
- }
6633
- if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
6634
- loader.register((parser) => new VirtualGeometryPlugin(parser));
6635
- }
6636
- const discreteLod = extensions.has(TN_DISCRETE_LOD) ? new DiscreteLodPlugin({
6637
- failClosed: loader.failClosed === true
6638
- }) : void 0;
6639
- if (discreteLod !== void 0) {
6640
- const plugin = discreteLod;
6641
- loader.register((parser) => {
6642
- plugin.setParser(parser);
6643
- return plugin;
6644
- });
6645
- }
6646
- if (extensions.has(DRACO_EXTENSION)) {
6647
- const { DRACOLoader } = await import('three/addons/loaders/DRACOLoader.js');
6648
- const dracoLoader = new DRACOLoader();
6649
- dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
6650
- loader.setDRACOLoader(dracoLoader);
6651
- }
6652
- const value = await new Promise(
6653
- (resolve, reject) => loader.parse(data, resourcePathOf(url), resolve, reject)
6654
- );
6655
- const root = modelRoot(value);
6656
- if (root !== void 0) widenQuantizedPositions(root);
6657
- if (root !== void 0) widenNormalizedScalars(root);
6658
- if (root !== void 0 && discreteLod !== void 0)
6659
- discreteLod.attach(root, await discretePolicy(path));
6660
- const clips = modelClips(value);
6661
- if (root !== void 0 && clips.length > 0 && reconcileMirroredClips(root, clips)) {
6662
- 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.";
6663
- console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} \u2014 ${cause}`);
6664
- }
6665
- stampAssetProvenance(value, path);
6666
- await attachCompiledLightmaps(path, value);
6667
- return value;
6668
- }),
7472
+ return {
7473
+ name: astcExtension,
7474
+ loadTexture(textureIndex) {
7475
+ const extension = parser.json.textures[textureIndex].extensions?.[astcExtension];
7476
+ if (extension === void 0 || !astcSupported || astcLoader === void 0)
7477
+ return null;
7478
+ return parser.loadTextureImage(
7479
+ textureIndex,
7480
+ extension.source,
7481
+ astcLoader
7482
+ );
7483
+ }
7484
+ };
7485
+ });
7486
+ }
7487
+ if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
7488
+ const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');
7489
+ loader.setMeshoptDecoder(MeshoptDecoder);
7490
+ }
7491
+ if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
7492
+ loader.register((parser) => new VirtualGeometryPlugin(parser));
7493
+ }
7494
+ const discreteLod = extensions.has(TN_DISCRETE_LOD) ? new DiscreteLodPlugin({
7495
+ failClosed: loader.failClosed === true
7496
+ }) : void 0;
7497
+ if (discreteLod !== void 0) {
7498
+ const plugin = discreteLod;
7499
+ loader.register((parser) => {
7500
+ plugin.setParser(parser);
7501
+ return plugin;
7502
+ });
7503
+ }
7504
+ if (extensions.has(DRACO_EXTENSION)) {
7505
+ const { DRACOLoader } = await import('three/addons/loaders/DRACOLoader.js');
7506
+ const dracoLoader = new DRACOLoader();
7507
+ dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
7508
+ loader.setDRACOLoader(dracoLoader);
7509
+ }
7510
+ const value = await new Promise(
7511
+ (resolve, reject) => loader.parse(data, resourcePathOf(url), resolve, reject)
7512
+ );
7513
+ const root = modelRoot(value);
7514
+ if (root !== void 0) widenQuantizedPositions(root);
7515
+ if (root !== void 0) widenNormalizedScalars(root);
7516
+ if (root !== void 0 && discreteLod !== void 0)
7517
+ discreteLod.attach(root, await discretePolicy(path));
7518
+ const clips = modelClips(value);
7519
+ if (root !== void 0 && clips.length > 0 && reconcileMirroredClips(root, clips)) {
7520
+ 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.";
7521
+ console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} \u2014 ${cause}`);
7522
+ }
7523
+ stampAssetProvenance(value, path);
7524
+ await attachCompiledLightmaps(path, value);
7525
+ return value;
7526
+ },
7527
+ request?.priority ?? "now"
7528
+ ),
7529
+ get cache() {
7530
+ return { ...assetCache.report, clear: () => assetCache.clear() };
7531
+ },
6669
7532
  get progress() {
6670
7533
  return { pending: [...pending], requested, requestedBytes, settled, settledBytes };
6671
7534
  },
7535
+ prefetch: prefetchPaths,
6672
7536
  resolve: async (path) => (await resolveCandidates(path)).urls,
7537
+ startBackgroundFill: () => {
7538
+ void manifestOnce().catch(() => void 0);
7539
+ return assetCache.startFill();
7540
+ },
6673
7541
  // A copy per read, like `progress`: a caller inspecting the record must not be able to
6674
7542
  // rewrite what the loader reports for the next asset that settles.
6675
7543
  get resolved() {
@@ -6684,15 +7552,23 @@ function createAssetLoader(options = {}) {
6684
7552
  return true;
6685
7553
  },
6686
7554
  texture: async (path, textureOptions) => {
6687
- const texture3 = await cached("texture", path, async (url) => {
7555
+ const texture3 = await cached("texture", path, async (url, priority) => {
6688
7556
  if (options.texture !== void 0) return options.texture(url);
6689
7557
  if (/\.ktx2$/iu.test(url)) {
6690
7558
  return loadCompiledKtx2(url);
6691
7559
  }
6692
7560
  if (typeof createImageBitmap === "function") {
6693
- return loadBitmapTexture(url, options.renderer);
7561
+ const expected = await bytesOf(path);
7562
+ return loadBitmapTexture(
7563
+ url,
7564
+ options.renderer,
7565
+ assetCache,
7566
+ expected > 0 ? expected : void 0,
7567
+ priority
7568
+ );
6694
7569
  }
6695
7570
  const { TextureLoader: Loader } = await import('three');
7571
+ if (debug) countDebug("textureMainThreadDecodeFallbacks", 1, "loading", url);
6696
7572
  return loadWith(new Loader(), url);
6697
7573
  });
6698
7574
  return textureOptions === void 0 ? texture3 : configuredTexture(texture3, textureOptions);
@@ -6710,13 +7586,15 @@ function disposeModel(value, disposed) {
6710
7586
  root.traverse((object) => {
6711
7587
  const renderable = object;
6712
7588
  disposeResource(renderable.geometry, disposed.geometries);
7589
+ const skeleton = renderable.skeleton;
7590
+ disposeTexture(skeleton?.boneTexture, disposed);
6713
7591
  disposeSurface(renderable["material"], disposed);
6714
7592
  });
6715
7593
  }
6716
7594
  }
6717
7595
  function modelRoots(value) {
6718
7596
  if (value instanceof Object3D) return [value];
6719
- if (!isRecord2(value)) return [];
7597
+ if (!isRecord3(value)) return [];
6720
7598
  const roots = [value.scene, ...Array.isArray(value.scenes) ? value.scenes : []];
6721
7599
  return roots.filter((root) => root instanceof Object3D);
6722
7600
  }
@@ -6726,6 +7604,10 @@ function stampAssetProvenance(value, logicalPath) {
6726
7604
  const existing = userData[GEOMETRY_ASSET_KEY];
6727
7605
  if (typeof existing === "string" && existing !== "") continue;
6728
7606
  userData[GEOMETRY_ASSET_KEY] = logicalPath;
7607
+ root.traverse((object) => {
7608
+ const geometry = object.geometry;
7609
+ if (geometry?.userData !== void 0) geometry.userData[GEOMETRY_ASSET_KEY] ??= logicalPath;
7610
+ });
6729
7611
  }
6730
7612
  }
6731
7613
  function disposeSurface(value, disposed) {
@@ -6733,7 +7615,7 @@ function disposeSurface(value, disposed) {
6733
7615
  for (const surface of value) disposeSurface(surface, disposed);
6734
7616
  return;
6735
7617
  }
6736
- if (!isRecord2(value)) return;
7618
+ if (!isRecord3(value)) return;
6737
7619
  if (disposed.surfaces.has(value)) return;
6738
7620
  disposeSurfaceTextures(value, disposed, /* @__PURE__ */ new WeakSet());
6739
7621
  disposeResource(value, disposed.surfaces);
@@ -6765,9 +7647,12 @@ function isDisposable(value) {
6765
7647
  return typeof value === "object" && value !== null && typeof value.dispose === "function";
6766
7648
  }
6767
7649
  function isTexture(value) {
6768
- return value instanceof Texture || isRecord2(value) && value.isTexture === true;
7650
+ return value instanceof Texture || isRecord3(value) && value.isTexture === true;
6769
7651
  }
6770
- function isRecord2(value) {
7652
+ function isSize(bytes) {
7653
+ return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0;
7654
+ }
7655
+ function isRecord3(value) {
6771
7656
  return typeof value === "object" && value !== null;
6772
7657
  }
6773
7658
  var INSTANCED_LOD_MAX_PIXEL_ERROR = 4;
@@ -7292,7 +8177,7 @@ function indexOf(part, deindex) {
7292
8177
  if (array instanceof Uint32Array) return array;
7293
8178
  return null;
7294
8179
  }
7295
- function writePosition(channel, indices, elements, scratch2, values, at) {
8180
+ function writePosition(channel, indices, elements, scratch3, values, at) {
7296
8181
  const { array, count: count3, offset, scale, stride } = channel;
7297
8182
  for (let vertex = 0; vertex < count3; vertex += 1) {
7298
8183
  const base = (indices === null ? vertex : indices[vertex]) * stride + offset;
@@ -7315,20 +8200,20 @@ function writePosition(channel, indices, elements, scratch2, values, at) {
7315
8200
  pz = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
7316
8201
  }
7317
8202
  const out = at + vertex * 3;
7318
- if (scratch2 !== null) {
7319
- scratch2[0] = Math.round(px * scale);
7320
- scratch2[1] = Math.round(py * scale);
7321
- scratch2[2] = Math.round(pz * scale);
7322
- px = Math.max(scratch2[0] / scale, -1);
7323
- py = Math.max(scratch2[1] / scale, -1);
7324
- pz = Math.max(scratch2[2] / scale, -1);
8203
+ if (scratch3 !== null) {
8204
+ scratch3[0] = Math.round(px * scale);
8205
+ scratch3[1] = Math.round(py * scale);
8206
+ scratch3[2] = Math.round(pz * scale);
8207
+ px = Math.max(scratch3[0] / scale, -1);
8208
+ py = Math.max(scratch3[1] / scale, -1);
8209
+ pz = Math.max(scratch3[2] / scale, -1);
7325
8210
  }
7326
8211
  values[out] = px;
7327
8212
  values[out + 1] = py;
7328
8213
  values[out + 2] = pz;
7329
8214
  }
7330
8215
  }
7331
- function writeNormal(channel, indices, elements, scratch2, values, at) {
8216
+ function writeNormal(channel, indices, elements, scratch3, values, at) {
7332
8217
  const { array, count: count3, offset, scale, stride } = channel;
7333
8218
  const e = elements;
7334
8219
  for (let vertex = 0; vertex < count3; vertex += 1) {
@@ -7354,13 +8239,13 @@ function writeNormal(channel, indices, elements, scratch2, values, at) {
7354
8239
  pz *= by;
7355
8240
  }
7356
8241
  const out = at + vertex * 3;
7357
- if (scratch2 !== null) {
7358
- scratch2[0] = Math.round(px * scale);
7359
- scratch2[1] = Math.round(py * scale);
7360
- scratch2[2] = Math.round(pz * scale);
7361
- px = Math.max(scratch2[0] / scale, -1);
7362
- py = Math.max(scratch2[1] / scale, -1);
7363
- pz = Math.max(scratch2[2] / scale, -1);
8242
+ if (scratch3 !== null) {
8243
+ scratch3[0] = Math.round(px * scale);
8244
+ scratch3[1] = Math.round(py * scale);
8245
+ scratch3[2] = Math.round(pz * scale);
8246
+ px = Math.max(scratch3[0] / scale, -1);
8247
+ py = Math.max(scratch3[1] / scale, -1);
8248
+ pz = Math.max(scratch3[2] / scale, -1);
7364
8249
  }
7365
8250
  values[out] = px;
7366
8251
  values[out + 1] = py;
@@ -7599,15 +8484,16 @@ function mergeByMaterial(root, options) {
7599
8484
  const open = groups[groups.length - 1];
7600
8485
  const vertices = verticesOf(part.geometry);
7601
8486
  if (open === void 0 || open.vertices + vertices > (options.maxGroupVertices ?? Number.POSITIVE_INFINITY)) {
7602
- const started = { parts: [], triangles: 0, vertices: 0 };
8487
+ const started = { parts: [], sources: [], triangles: 0, vertices: 0 };
7603
8488
  groups.push(started);
7604
8489
  return started;
7605
8490
  }
7606
8491
  return open;
7607
8492
  };
7608
- const add = (material, part, triangles) => {
8493
+ const add = (material, part, triangles, source) => {
7609
8494
  const group = groupFor(material, part);
7610
8495
  group.parts.push(part);
8496
+ group.sources.push(source);
7611
8497
  group.triangles += triangles;
7612
8498
  group.vertices += verticesOf(part.geometry);
7613
8499
  return group;
@@ -7621,7 +8507,8 @@ function mergeByMaterial(root, options) {
7621
8507
  add(
7622
8508
  renderable.material,
7623
8509
  { geometry: renderable.geometry, matrix: place },
7624
- trianglesOf(renderable.geometry)
8510
+ trianglesOf(renderable.geometry),
8511
+ renderable
7625
8512
  );
7626
8513
  return;
7627
8514
  }
@@ -7641,7 +8528,8 @@ function mergeByMaterial(root, options) {
7641
8528
  add(
7642
8529
  renderable.material,
7643
8530
  { geometry: instanced.geometry, matrix: place.clone().multiply(instance) },
7644
- shape
8531
+ shape,
8532
+ instanced
7645
8533
  );
7646
8534
  }
7647
8535
  });
@@ -7653,19 +8541,23 @@ function mergeByMaterial(root, options) {
7653
8541
  const preserve = MERGEABLE_CHANNELS.filter(
7654
8542
  (channel) => channel === "uv" ? group.parts.some((piece) => has(piece, channel)) : group.parts.every((piece) => has(piece, channel))
7655
8543
  );
7656
- merged.push(
7657
- new Mesh(
7658
- mergeParts(group.parts, {
7659
- label: `${options.label}:${material.name || index}${part === 0 ? "" : `#${part}`}`,
7660
- preserve
7661
- }),
7662
- material
7663
- )
8544
+ const mesh = new Mesh(
8545
+ mergeParts(group.parts, {
8546
+ label: `${options.label}:${material.name || index}${part === 0 ? "" : `#${part}`}`,
8547
+ preserve
8548
+ }),
8549
+ material
7664
8550
  );
8551
+ options.onGroup?.(mesh, group.sources);
8552
+ merged.push(mesh);
7665
8553
  });
7666
8554
  });
7667
8555
  return [...merged, ...kept];
7668
8556
  }
8557
+ var sourceGroups = /* @__PURE__ */ new WeakMap();
8558
+ function isAutoBatchSource(object) {
8559
+ return sourceGroups.has(object);
8560
+ }
7669
8561
 
7670
8562
  // src/projection-plan.ts
7671
8563
  function displacesVertices(material) {
@@ -8023,6 +8915,7 @@ function materialKey(material) {
8023
8915
  material.type,
8024
8916
  material.transparent ? 1 : 0,
8025
8917
  num(material.alphaTest),
8918
+ material.alphaHash ? 1 : 0,
8026
8919
  material.side,
8027
8920
  material.vertexColors ? 1 : 0,
8028
8921
  num(material.opacity),
@@ -8716,7 +9609,7 @@ function buildFragmentNodes(atlas, centerUniform, radiusUniform, cutoff, mipScal
8716
9609
 
8717
9610
  // src/static-transform.ts
8718
9611
  var frozen = /* @__PURE__ */ new Map();
8719
- var SNAPSHOT_LENGTH = 3 + 4 + 3 + 16;
9612
+ var SNAPSHOT_LENGTH2 = 3 + 4 + 3 + 16;
8720
9613
  function writeSnapshot(root, into) {
8721
9614
  const position = root.position;
8722
9615
  const quaternion = root.quaternion;
@@ -8757,7 +9650,7 @@ function freeze(root) {
8757
9650
  function markStatic(root) {
8758
9651
  const objects = freeze(root);
8759
9652
  const existing = frozen.get(root);
8760
- const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH);
9653
+ const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH2);
8761
9654
  writeSnapshot(root, snapshot);
8762
9655
  const version = (existing?.version ?? 0) + 1;
8763
9656
  frozen.set(root, { objects, root, snapshot, version });
@@ -8783,13 +9676,14 @@ function sceneNeedsEnvironmentPreparation(renderer, scene) {
8783
9676
  const backend = raw.backend;
8784
9677
  return backend?.isWebGPUBackend === true;
8785
9678
  }
8786
- async function prepareSceneEnvironment(renderer, scene, camera, deadlineMs) {
9679
+ async function prepareSceneEnvironment(renderer, scene, camera, deadlineMs, afterDraw) {
8787
9680
  const environment = scene.environment;
8788
9681
  if (environment?.isTexture !== true) return true;
8789
9682
  const raw = renderer.raw;
8790
9683
  if (typeof raw !== "object" || raw === null) return true;
8791
9684
  const native = nativeEnvironmentPreparer(raw);
8792
- if (native !== void 0) return native.prepareEnvironmentAsync(scene, camera, deadlineMs);
9685
+ if (native !== void 0)
9686
+ return native.prepareEnvironmentAsync(scene, camera, deadlineMs, afterDraw);
8793
9687
  const backend = raw.backend;
8794
9688
  if (backend?.isWebGPUBackend !== true) return true;
8795
9689
  const PMREMNode = pmremTexture(environment).constructor;
@@ -8799,7 +9693,25 @@ async function prepareSceneEnvironment(renderer, scene, camera, deadlineMs) {
8799
9693
  "TN_PMREM_ASYNC_PREPARER_UNAVAILABLE: patched Three.js has no PMREM cache preparer."
8800
9694
  );
8801
9695
  }
8802
- return prepare.call(PMREMNode, raw, environment);
9696
+ const prepared = prepare.call(PMREMNode, raw, environment);
9697
+ console.info("TN_ENVIRONMENT_BAKE:started");
9698
+ void prepared.then(
9699
+ (ready) => console.info(`TN_ENVIRONMENT_BAKE:finished ready=${ready}`),
9700
+ () => console.info("TN_ENVIRONMENT_BAKE:finished ready=false")
9701
+ );
9702
+ const remaining = deadlineMs - (globalThis.performance?.now() ?? Date.now());
9703
+ if (!Number.isFinite(remaining)) return prepared;
9704
+ let timer;
9705
+ try {
9706
+ return await Promise.race([
9707
+ prepared,
9708
+ new Promise((resolve) => {
9709
+ timer = setTimeout(() => resolve(false), Math.max(0, remaining));
9710
+ })
9711
+ ]);
9712
+ } finally {
9713
+ clearTimeout(timer);
9714
+ }
8803
9715
  }
8804
9716
  var DEFAULT_SLICE_SIZE = 24;
8805
9717
  var DEFAULT_COMPILE_TIMEOUT_MS = 2e3;
@@ -8956,7 +9868,8 @@ function collectRenderables(root) {
8956
9868
  const stack = [root];
8957
9869
  while (stack.length > 0) {
8958
9870
  const object = stack.pop();
8959
- if (object.material !== void 0) found.push(object);
9871
+ if (object.material !== void 0 && !isAutoBatchSource(object))
9872
+ found.push(object);
8960
9873
  const children = object.children ?? [];
8961
9874
  for (let index = children.length - 1; index >= 0; index -= 1) {
8962
9875
  stack.push(children[index]);
@@ -9019,10 +9932,12 @@ function nodeHasReflector(root, depth) {
9019
9932
  }
9020
9933
  function hasReflector(scene) {
9021
9934
  const stack = [scene];
9935
+ const read = /* @__PURE__ */ new Set();
9022
9936
  while (stack.length > 0) {
9023
9937
  const object = stack.pop();
9024
9938
  const material = object.material;
9025
- if (typeof material === "object" && material !== null && material.isNodeMaterial === true) {
9939
+ if (typeof material === "object" && material !== null && material.isNodeMaterial === true && !read.has(material)) {
9940
+ read.add(material);
9026
9941
  for (const value of Object.values(material)) {
9027
9942
  if (nodeHasReflector(value, 0)) return true;
9028
9943
  }
@@ -9032,9 +9947,12 @@ function hasReflector(scene) {
9032
9947
  }
9033
9948
  return false;
9034
9949
  }
9035
- async function renderWarmPasses(renderer, scene, camera, enabled, includeHidden, targetScene) {
9950
+ async function renderWarmPasses(renderer, scene, camera, enabled, includeHidden, targetScene, afterCoveredDraw) {
9036
9951
  const coveredWorldPass = renderer.warmUpWorldPass;
9037
- const render = coveredWorldPass === void 0 ? renderer.render === void 0 ? void 0 : () => renderer.render?.(scene, camera) : () => coveredWorldPass(scene, camera, targetScene);
9952
+ const render = coveredWorldPass === void 0 ? renderer.render === void 0 ? void 0 : () => {
9953
+ renderer.render?.(scene, camera);
9954
+ afterCoveredDraw?.();
9955
+ } : () => coveredWorldPass(scene, camera, targetScene, afterCoveredDraw);
9038
9956
  if (render === void 0) return void 0;
9039
9957
  const skipped = {
9040
9958
  passes: [],
@@ -9072,7 +9990,7 @@ async function renderWarmPasses(renderer, scene, camera, enabled, includeHidden,
9072
9990
  object.frustumCulled = false;
9073
9991
  cullingForced += 1;
9074
9992
  }
9075
- if (includeHidden && object !== scene && object.visible === false) {
9993
+ if (includeHidden && object !== scene && object.visible === false && !isAutoBatchSource(object)) {
9076
9994
  entry.visible = false;
9077
9995
  object.visible = true;
9078
9996
  visibilityForced += 1;
@@ -9145,7 +10063,8 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
9145
10063
  renderer,
9146
10064
  targetScene,
9147
10065
  camera,
9148
- environmentDeadline
10066
+ environmentDeadline,
10067
+ options.afterCoveredDraw
9149
10068
  ).then((prepared) => {
9150
10069
  environmentPrepared = prepared;
9151
10070
  if (!prepared) {
@@ -9309,7 +10228,8 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
9309
10228
  camera,
9310
10229
  options.renderPasses !== false,
9311
10230
  options.includeHidden === true,
9312
- options.targetScene
10231
+ options.targetScene,
10232
+ options.afterCoveredDraw
9313
10233
  );
9314
10234
  } catch (error) {
9315
10235
  passError = error;
@@ -9449,7 +10369,7 @@ async function warmUpScene(renderer, scene, camera, options = {}) {
9449
10369
 
9450
10370
  // src/streaming.ts
9451
10371
  var DEFAULT_SLICE_BUDGET_MS = 8;
9452
- var DEFAULT_CONCURRENCY = 6;
10372
+ var DEFAULT_CONCURRENCY2 = 6;
9453
10373
  var now = () => globalThis.performance?.now() ?? Date.now();
9454
10374
  function assertWholeAtLeastOne(value, name, code) {
9455
10375
  if (!Number.isInteger(value) || value < 1) {
@@ -9514,7 +10434,7 @@ async function addInSlices(objects, add, options = {}) {
9514
10434
  return report;
9515
10435
  }
9516
10436
  async function loadAll(items, load, options = {}) {
9517
- const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY;
10437
+ const concurrency = options.concurrency ?? DEFAULT_CONCURRENCY2;
9518
10438
  assertWholeAtLeastOne(concurrency, "concurrency", "TN_LOAD_ALL_CONCURRENCY_INVALID");
9519
10439
  const concurrencyOverridden = options.concurrency !== void 0;
9520
10440
  const yieldFrame = options.yieldFrame ?? yieldToHost;
@@ -12380,7 +13300,7 @@ var SharedBatch = class _SharedBatch {
12380
13300
  const squares = this.#squares();
12381
13301
  let total = 0;
12382
13302
  for (const square of squares) total += sizeOf(square);
12383
- const scratch2 = scratchFor(total * 16);
13303
+ const scratch3 = scratchFor(total * 16);
12384
13304
  const front = squares.filter((one) => visible?.has(one.cluster) ?? true);
12385
13305
  const back = squares.filter((one) => !(visible?.has(one.cluster) ?? true));
12386
13306
  let written = 0;
@@ -12390,7 +13310,7 @@ var SharedBatch = class _SharedBatch {
12390
13310
  for (const square of [...front, ...back]) {
12391
13311
  const union = new Box3();
12392
13312
  for (const [handle, start, count3] of square.blocks) {
12393
- scratch2.set(array.subarray(start * 16, (start + count3) * 16), written * 16);
13313
+ scratch3.set(array.subarray(start * 16, (start + count3) * 16), written * 16);
12394
13314
  if (this.#start.get(handle) !== written) {
12395
13315
  if (movedFrom < 0) movedFrom = written;
12396
13316
  movedTo = written + count3;
@@ -12402,7 +13322,7 @@ var SharedBatch = class _SharedBatch {
12402
13322
  }
12403
13323
  this.#squareSizes.set(square.cluster, sizeOf(square));
12404
13324
  }
12405
- array.set(scratch2.subarray(0, written * 16));
13325
+ array.set(scratch3.subarray(0, written * 16));
12406
13326
  this.#drawn = written;
12407
13327
  const capacity = this.mesh.instanceMatrix.count;
12408
13328
  this.#free = written < capacity ? [[written, capacity]] : [];
@@ -12442,9 +13362,9 @@ var SharedBatch = class _SharedBatch {
12442
13362
  /** Records of the squares in `visible`, the count a clustered batch's `mesh.count` draws. */
12443
13363
  #windowOf(visible) {
12444
13364
  if (visible === void 0) return this.#drawn;
12445
- let window = 0;
12446
- for (const [cluster, size] of this.#squareSizes) if (visible.has(cluster)) window += size;
12447
- return window;
13365
+ let window2 = 0;
13366
+ for (const [cluster, size] of this.#squareSizes) if (visible.has(cluster)) window2 += size;
13367
+ return window2;
12448
13368
  }
12449
13369
  /**
12450
13370
  * Narrow the draw window to the visibility cells `visible` names, rewriting the instance buffer
@@ -12667,7 +13587,7 @@ function release(target) {
12667
13587
  return false;
12668
13588
  }
12669
13589
  async function loadModelWith(assets, path) {
12670
- const gltf = await assets.model(path);
13590
+ const gltf = await assets.model(path, { priority: "soon" });
12671
13591
  const scene = gltf?.scene;
12672
13592
  if (!(scene instanceof Object3D))
12673
13593
  throw new Error(`World asset '${path}' loaded without an Object3D scene.`);