@threenative/core 0.3.11 → 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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
package/src/assets.ts CHANGED
@@ -20,10 +20,20 @@ import {
20
20
  canonicalUrl,
21
21
  createAssetCache,
22
22
  } from "./asset-cache.js";
23
+ import { type AssetMemo, createAssetMemo } from "./asset-memo.js";
23
24
  import { TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin } from "./clustered-mesh.js";
24
25
  import { GEOMETRY_ASSET_KEY } from "./geometry-capture.js";
25
- import { DiscreteLodPlugin, type IModelLodPolicy, TN_DISCRETE_LOD } from "./model-lod.js";
26
+ import { attachInstancedLod } from "./instanced-batch-lod.js";
27
+ import {
28
+ DiscreteLodPlugin,
29
+ type IModelLodPolicy,
30
+ TN_DISCRETE_LOD,
31
+ markStreamedGeometry,
32
+ upgradeStreamedGeometry,
33
+ } from "./model-lod.js";
26
34
  import { countDebug, debugRequested, measureDebug } from "./profiling/debug-telemetry.js";
35
+ import { streamedTextureUpgrade } from "./streamed-textures.js";
36
+ import { openKtx2Stream } from "./texture-streaming.js";
27
37
 
28
38
  export interface IAssetLoaderOptions {
29
39
  readonly basePath?: string;
@@ -66,15 +76,58 @@ export interface IAssetLoaderOptions {
66
76
  * `navigator.connection.saveData`.
67
77
  */
68
78
  readonly backgroundFill?: boolean;
79
+ /**
80
+ * Draw a model's coarse companion first, where the cook wrote one, and the full model when it
81
+ * lands (PRD-860). On by default; `false` is the named override, reported once as
82
+ * `TN_ASSETS_STREAM_MESHES_OFF`.
83
+ */
84
+ readonly streamMeshes?: boolean;
85
+ /**
86
+ * Draw a streamed model's KTX2 textures with their resident mips first, and the whole files when
87
+ * they land (PRD-860). On by default; `false` is the named override, reported once as
88
+ * `TN_ASSETS_STREAM_TEXTURES_OFF`. It rides on `streamMeshes`: the coarse parse is where the
89
+ * resident mips draw.
90
+ */
91
+ readonly streamTextures?: boolean;
92
+ }
93
+
94
+ /**
95
+ * A streamed model's images for one parse: whether any drew from its resident mips only (`used`),
96
+ * and the KTX2 files a host with no `Range` sent whole, handed on to the full parse (`keptOnly`).
97
+ */
98
+ interface IResidentImages {
99
+ used: boolean;
100
+ readonly whole: Map<string, Uint8Array>;
101
+ readonly keptOnly?: boolean;
69
102
  }
70
103
 
71
104
  /** What one request is worth relative to the rest of the loader's queue. */
105
+ /**
106
+ * Report marker for a file a scene asks for after the reveal that the game had not prefetched.
107
+ *
108
+ * The reveal is the first moment the player is playing, so the download such a request starts is
109
+ * time spent looking at a world without that file in it — the pop-in a streaming game exists to
110
+ * avoid. One line per file, carrying the bytes and how far into play the request landed, so a
111
+ * playtest can count the pop-ins instead of a person having to watch for them.
112
+ *
113
+ * A file the game asked `prefetch` for first is not late: that is a deliberate stream, and the
114
+ * engine's own background fill is no promise either — it lags the link by design.
115
+ */
116
+ export const ASSET_LATE_MARKER = "TN_ASSET_LATE";
117
+
72
118
  export interface IAssetRequestOptions {
73
119
  /**
74
120
  * `now` for a file the running scene awaits, `soon` for a prefetch. The loader's own direct
75
121
  * calls default to `now`.
76
122
  */
77
123
  readonly priority?: AssetPriority;
124
+ /**
125
+ * PRD-860: `true` resolves a model only once its full file has replaced the coarse companion the
126
+ * first scene draws (the same object, upgraded in place). For a caller that copies the vertices:
127
+ * a trimesh or convex-hull collider, a navmesh bake, a geometry merge. Default: the coarse model,
128
+ * so the scene plays before the download ends.
129
+ */
130
+ readonly whole?: boolean;
78
131
  }
79
132
 
80
133
  /** What a `prefetch` asked for and what the download produced. */
@@ -215,8 +268,22 @@ export interface IAssetLoader {
215
268
  /**
216
269
  * Start the post-reveal idle fill. The engine calls this when `ctx.startup.whenReady()` settles;
217
270
  * a game that drives a loader outside `defineGame` may call it after its own reveal.
271
+ *
272
+ * It is also where the reveal is marked for {@link ASSET_LATE_MARKER}: a whole-file load a scene
273
+ * asks for after this call, and that the game did not `prefetch`, is reported as the pop-in it is.
274
+ * A game that never calls it never gets the report.
218
275
  */
219
276
  startBackgroundFill(): Promise<void>;
277
+ /**
278
+ * Generated content kept between runs (PRD-860): returns what `build` returned the last time this
279
+ * build of the game ran, read from disk, and calls `build` only when nothing is stored. Use it for
280
+ * seeded work that is the same every run, such as placement lists, painted sky pixels or terrain
281
+ * heights. The value is named typed arrays. A new build regenerates. On the dev server and on a
282
+ * native host `build` runs every time, and `TN_ASSET_MEMO` says why.
283
+ *
284
+ * @example const { pixels } = await ctx.assets.memo("sky", () => ({ pixels: paintSky() }));
285
+ */
286
+ memo: AssetMemo;
220
287
  /**
221
288
  * How many loads this loader has been asked for and how many have settled (resolved or
222
289
  * rejected). A loading view reads the ratio; the runtime folds it into `ctx.startup.progress`
@@ -790,6 +857,15 @@ function widenNormalizedScalars(root: Object3D): void {
790
857
  }
791
858
 
792
859
  /** The `{ scene }` a GLTF result carries, when it carries one. */
860
+ /** A loaded model's meshes in traversal order: the coarse companion and the full model list them alike. */
861
+ function meshesOf(value: unknown): Mesh[] {
862
+ const meshes: Mesh[] = [];
863
+ modelRoot(value)?.traverse((object) => {
864
+ if ((object as Mesh).isMesh === true) meshes.push(object as Mesh);
865
+ });
866
+ return meshes;
867
+ }
868
+
793
869
  function modelRoot(value: unknown): Object3D | undefined {
794
870
  if (typeof value !== "object" || value === null) return undefined;
795
871
  const scene = (value as { scene?: unknown }).scene;
@@ -886,6 +962,56 @@ export function reconcileMirroredClips(root: Object3D, clips: readonly Animation
886
962
  export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoader {
887
963
  const debug = debugRequested();
888
964
  const basePath = options.basePath ?? "";
965
+ const streamMeshes = options.streamMeshes !== false;
966
+ if (!streamMeshes)
967
+ console.info(
968
+ "TN_ASSETS_STREAM_MESHES_OFF: assets.streamMeshes is false; every model loads whole.",
969
+ );
970
+ const streamTextures = options.streamTextures !== false;
971
+ if (!streamTextures)
972
+ console.info(
973
+ "TN_ASSETS_STREAM_TEXTURES_OFF: assets.streamTextures is false; every model texture loads whole.",
974
+ );
975
+ // What the texture streaming kept off the first-play path, read from the console as TN_STREAMING_POOL.
976
+ const pool = { files: 0, fullBytes: 0, ranged: 0, residentBytes: 0, upgraded: 0 };
977
+ let poolTimer: ReturnType<typeof setTimeout> | undefined;
978
+ const reportPool = (): void => {
979
+ clearTimeout(poolTimer);
980
+ poolTimer = setTimeout(() => {
981
+ poolTimer = undefined;
982
+ console.info(
983
+ `TN_STREAMING_POOL ${JSON.stringify({ ...pool, deferredBytes: pool.fullBytes - pool.residentBytes })}`,
984
+ );
985
+ }, 2000);
986
+ };
987
+ /** One KTX2 image as its resident mips only; any other image, or a host with no `Range`, loads whole. */
988
+ const residentImage = async (
989
+ url: string,
990
+ ): Promise<{ readonly file: Uint8Array; readonly partial: boolean } | undefined> => {
991
+ if (!/\.ktx2(?:$|\?)/iu.test(url)) return undefined;
992
+ const stream = await openKtx2Stream(url);
993
+ // A host with no Range support sent the whole file already: hand it on, not fetched again.
994
+ if (!stream.ranged) return { file: stream.file(), partial: false };
995
+ const file = stream.file();
996
+ pool.files += 1;
997
+ pool.ranged += 1;
998
+ pool.residentBytes += file.byteLength;
999
+ pool.fullBytes += stream.index.levels.reduce((sum, level) => sum + level.byteLength, 0);
1000
+ reportPool();
1001
+ return { file, partial: true };
1002
+ };
1003
+ /** The engine loader's `imageSource` for one parse of a streamed model. */
1004
+ const imageSourceFor =
1005
+ (resident: IResidentImages) =>
1006
+ async (imageUrl: string): Promise<Uint8Array | undefined> => {
1007
+ // A host with no Range already sent this file whole to the coarse parse.
1008
+ const kept = resident.whole.get(imageUrl);
1009
+ if (kept !== undefined || resident.keptOnly === true) return kept;
1010
+ const served = await residentImage(imageUrl);
1011
+ if (served?.partial === true) resident.used = true;
1012
+ else if (served !== undefined) resident.whole.set(imageUrl, served.file);
1013
+ return served?.file;
1014
+ };
889
1015
  // `assets` is what `@threenative/assets` compiles from unless a project says otherwise, so it is
890
1016
  // where an unbaked game's files are. A project that moved its sources passes `sourcePath`.
891
1017
  const sourcePath = (options.sourcePath ?? "assets").replace(/^\/+|\/+$/gu, "");
@@ -1124,6 +1250,19 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1124
1250
  let settledBytes = 0;
1125
1251
  /** Logical paths asked for and not yet settled, in request order — what a loading view names. */
1126
1252
  const pending = new Set<string>();
1253
+ /** A streamed model's full-file upgrade, settled when it landed or failed (`whole: true` waits on it). */
1254
+ const wholeOf = new WeakMap<object, Promise<void>>();
1255
+ const wholeWhen = <T>(wait: boolean, loading: Promise<T>): Promise<T> =>
1256
+ wait
1257
+ ? loading.then(async (value) => {
1258
+ if (typeof value === "object" && value !== null) await wholeOf.get(value);
1259
+ return value;
1260
+ })
1261
+ : loading;
1262
+ /** Logical paths the game warmed ahead of time; a load of one is a stream, not a pop-in. */
1263
+ const warmed = new Set<string>();
1264
+ /** When the reveal made the player play; `undefined` until then. */
1265
+ let revealedAtMs: number | undefined;
1127
1266
 
1128
1267
  /**
1129
1268
  * The compiled size of a logical path, or 0 when it is not knowable — no manifest, an external
@@ -1138,6 +1277,22 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1138
1277
  return typeof bytes === "number" && Number.isFinite(bytes) && bytes > 0 ? bytes : 0;
1139
1278
  };
1140
1279
 
1280
+ /** A model's coarse companion (PRD-860 Phase 3), when the cook wrote one and streaming is on. */
1281
+ const coarseOf = async (path: string): Promise<{ bytes: number; url: string } | undefined> => {
1282
+ if (!streamMeshes || isExternalAssetPath(path)) return undefined;
1283
+ const entry = (await manifestOnce())?.entries[path];
1284
+ const coarse =
1285
+ isRecord(entry) && Array.isArray(entry.streamedLods) ? entry.streamedLods[0] : undefined;
1286
+ if (!isRecord(coarse) || typeof coarse.output !== "string" || typeof coarse.bytes !== "number")
1287
+ return undefined;
1288
+ return { bytes: coarse.bytes, url: resolvePath(basePath, coarse.output) };
1289
+ };
1290
+
1291
+ /** What a request waits for: a streamed model's coarse companion, else the file itself. */
1292
+ const weightOf = async (kind: string, path: string): Promise<number> =>
1293
+ (kind === "model" && !warmed.has(path) ? (await coarseOf(path))?.bytes : undefined) ??
1294
+ bytesOf(path);
1295
+
1141
1296
  /** The shared images and lightmaps a path's load downloads beside its own file, with sizes. */
1142
1297
  const auxiliaryOf = async (path: string): Promise<IResolvedFile[]> => {
1143
1298
  if (isExternalAssetPath(path)) return [];
@@ -1162,6 +1317,7 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1162
1317
  path: string,
1163
1318
  load: (url: string, priority: AssetPriority) => Promise<T>,
1164
1319
  priority: AssetPriority = "now",
1320
+ whole = false,
1165
1321
  ): Promise<T> => {
1166
1322
  const key = `${kind}:${path}`;
1167
1323
  const existing = cache.get(key);
@@ -1172,7 +1328,7 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1172
1328
  existing.priority = priority;
1173
1329
  if (existing.url !== undefined) assetCache.promote(existing.url, priority);
1174
1330
  }
1175
- return existing.promise as Promise<T>;
1331
+ return wholeWhen(whole, existing.promise as Promise<T>);
1176
1332
  }
1177
1333
  requested += 1;
1178
1334
  // The size is only knowable once the manifest lands, so this load's weight joins the
@@ -1180,7 +1336,7 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1180
1336
  // so a load that fails still contributes the same weight to both sides of the ratio.
1181
1337
  let weight = 0;
1182
1338
  let auxiliary: readonly IResolvedFile[] = [];
1183
- const weighed = Promise.all([bytesOf(path), auxiliaryOf(path)]).then(
1339
+ const weighed = Promise.all([weightOf(kind, path), auxiliaryOf(path)]).then(
1184
1340
  ([bytes, files]) => {
1185
1341
  weight = bytes;
1186
1342
  auxiliary = files;
@@ -1188,6 +1344,22 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1188
1344
  },
1189
1345
  () => undefined,
1190
1346
  );
1347
+ // A whole-file request after the reveal is the pop-in a streaming game exists to avoid: the
1348
+ // scene has no bytes and starts a download while the player is already looking at the world.
1349
+ // Measured, never configured — and quiet for a file the game warmed with `prefetch`.
1350
+ if (revealedAtMs !== undefined && !warmed.has(path)) {
1351
+ const lateAt = revealedAtMs;
1352
+ void weighed.then(() =>
1353
+ console.log(
1354
+ `${ASSET_LATE_MARKER}:${JSON.stringify({
1355
+ bytes: weight,
1356
+ kind,
1357
+ ms: Math.round(performanceNow() - lateAt),
1358
+ path,
1359
+ })}`,
1360
+ ),
1361
+ );
1362
+ }
1191
1363
  // Opt-in per-asset timing, off by default and free when off: a launch that is slow because of
1192
1364
  // *which* asset is slow cannot be told from the group totals a game logs, and the engine is the
1193
1365
  // only place that sees every settle. Set `globalThis.__TN_ASSET_TRACE__ = true` before boot.
@@ -1246,7 +1418,7 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1246
1418
  };
1247
1419
  entry.promise.then(note, note);
1248
1420
  cache.set(key, entry);
1249
- return entry.promise as Promise<T>;
1421
+ return wholeWhen(whole, entry.promise as Promise<T>);
1250
1422
  };
1251
1423
 
1252
1424
  const releaseEntry = (entry: IAssetEntry): void => {
@@ -1264,6 +1436,9 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1264
1436
  * settles; a path the manifest does not list is skipped rather than failing the whole prefetch.
1265
1437
  */
1266
1438
  const prefetchPaths = async (paths: readonly string[]): Promise<IAssetPrefetchProgress> => {
1439
+ // Marked before the early returns: a native host has the files installed, and a game asked for
1440
+ // these either way, so a later load of one is not a surprise download.
1441
+ for (const path of paths) warmed.add(path);
1267
1442
  if (!assetCache.enabled) {
1268
1443
  return {
1269
1444
  requested: paths.length,
@@ -1367,139 +1542,233 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1367
1542
  await attachCompiledLightmaps(path, value);
1368
1543
  return value;
1369
1544
  }
1370
- // Fetched here rather than through the loader so the declared extensions decide which
1371
- // decoders load: a game never pays for a codec its assets do not use, and no WASM is
1372
- // instantiated on platforms that never load a compressed model. Both the compiled and
1373
- // the uncompiled path take this one code path.
1374
- const expected = await bytesOf(path);
1375
- const data = await fetchModelBytes(
1376
- url,
1377
- assetCache,
1378
- expected > 0 ? expected : undefined,
1379
- priority,
1380
- );
1381
- const extensions = declaredExtensions(data);
1382
- const { GLTFLoader } = await import("three/addons/loaders/GLTFLoader.js");
1383
- const loader = new GLTFLoader();
1384
- // Both glTF texture extensions use the same support-detected instance as texture().
1385
- const astcExtension = "EXT_texture_astc";
1386
- const hasBasis = extensions.has("KHR_texture_basisu");
1387
- const hasAstc = extensions.has(astcExtension);
1388
- let shared: IKTX2LoaderLike | undefined;
1389
- if (compressedTextures !== undefined && (hasBasis || hasAstc)) {
1545
+ const parse = async (
1546
+ fileUrl: string,
1547
+ expected: number,
1548
+ at: AssetPriority,
1549
+ resident?: IResidentImages,
1550
+ ): Promise<T> => {
1551
+ // Fetched here rather than through the loader so the declared extensions decide which
1552
+ // decoders load: a game never pays for a codec its assets do not use, and no WASM is
1553
+ // instantiated on platforms that never load a compressed model. Both the compiled and
1554
+ // the uncompiled path take this one code path.
1555
+ const data = await fetchModelBytes(
1556
+ fileUrl,
1557
+ assetCache,
1558
+ expected > 0 ? expected : undefined,
1559
+ at,
1560
+ );
1561
+ const extensions = declaredExtensions(data);
1562
+ const { GLTFLoader } = await import("three/addons/loaders/GLTFLoader.js");
1563
+ const loader = new GLTFLoader();
1564
+ if (resident !== undefined && "imageSource" in loader)
1565
+ (loader as { imageSource?: unknown }).imageSource = imageSourceFor(resident);
1566
+ // Both glTF texture extensions use the same support-detected instance as texture().
1567
+ const astcExtension = "EXT_texture_astc";
1568
+ // The owned engine's loader (`failClosed`) transcodes KHR_texture_basisu itself, to BC7,
1569
+ // ETC2 or RGBA8, so three's KTX2Loader and its format check do not gate it (PRD-867).
1570
+ const hasBasis =
1571
+ extensions.has("KHR_texture_basisu") &&
1572
+ (loader as { failClosed?: boolean }).failClosed !== true;
1573
+ const hasAstc = extensions.has(astcExtension);
1574
+ let shared: IKTX2LoaderLike | undefined;
1575
+ if (compressedTextures !== undefined && (hasBasis || hasAstc)) {
1576
+ try {
1577
+ shared = await compressedTextures.loader;
1578
+ } catch (error) {
1579
+ // Only ASTC-only models may select their ordinary fallback on capability refusal.
1580
+ // Import/setup failures and the existing Basis contract still reject unchanged.
1581
+ if (
1582
+ hasBasis ||
1583
+ !(error instanceof Error) ||
1584
+ !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:")
1585
+ )
1586
+ throw error;
1587
+ }
1588
+ if (shared !== undefined) {
1589
+ loader.setKTX2Loader(
1590
+ shared as unknown as Parameters<typeof loader.setKTX2Loader>[0],
1591
+ );
1592
+ }
1593
+ }
1594
+ if (hasAstc) {
1595
+ const astcLoader = shared;
1596
+ const astcSupported = hasAstcSupport(astcLoader);
1597
+ // EXT_texture_astc is an official vendor draft. Borrow Three's Basis plugin handoff,
1598
+ // but raw ASTC cannot use Basis's format fallback and needs this explicit GPU guard.
1599
+ loader.register((parser) => {
1600
+ if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
1601
+ throw new Error(
1602
+ "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support.",
1603
+ );
1604
+ }
1605
+ return {
1606
+ name: astcExtension,
1607
+ loadTexture(textureIndex) {
1608
+ const extension =
1609
+ parser.json.textures[textureIndex].extensions?.[astcExtension];
1610
+ if (extension === undefined || !astcSupported || astcLoader === undefined)
1611
+ return null;
1612
+ return parser.loadTextureImage(
1613
+ textureIndex,
1614
+ extension.source,
1615
+ astcLoader as NonNullable<Parameters<typeof loader.setKTX2Loader>[0]>,
1616
+ );
1617
+ },
1618
+ };
1619
+ });
1620
+ }
1621
+ // three's own decoder embeds its WASM; it compiles only once a compressed model is
1622
+ // actually loaded. The native bundle inlines this branch (no runtime import remains),
1623
+ // and the host shims WebAssembly.
1624
+ if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
1625
+ const { MeshoptDecoder } = await import(
1626
+ "three/addons/libs/meshopt_decoder.module.js"
1627
+ );
1628
+ loader.setMeshoptDecoder(MeshoptDecoder);
1629
+ }
1630
+ // Draco is an input format only: the compile step re-emits Draco assets as Meshopt,
1631
+ // so this serves uncompiled Draco files dropped into a web root. The decoder wasm is
1632
+ // served from `<basePath>draco/` by convention, like `basis/`.
1633
+ // The cluster DAG the asset pipeline baked in. Registered only when the file declares it,
1634
+ // so a game whose models are ordinary meshes never pays for the plugin — and a game whose
1635
+ // models are not gets a plain `Mesh`, with no runtime switch either way.
1636
+ // The Wasm engine's loader hosts no cluster plugin and refuses any it does not host. The
1637
+ // pipeline never marks the bake required, so there the file's source triangles draw.
1638
+ if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
1639
+ if ((loader as { failClosed?: boolean }).failClosed === true)
1640
+ console.info(
1641
+ `TN_VIRTUAL_GEOMETRY_SKIPPED ${path}: this engine's glTF loader hosts no cluster plugin; the source mesh draws`,
1642
+ );
1643
+ else loader.register((parser) => new VirtualGeometryPlugin(parser as never) as never);
1644
+ }
1645
+ // The discrete chain the asset pipeline baked in. Registered only when the file declares it,
1646
+ // so a game with no auto LOD never pays for the plugin. Levels are built after the quantized
1647
+ // positions are widened, so the derived geometries share the widened attributes.
1648
+ // The Wasm engine's loader hosts this plugin too, and sets `failClosed`: a chain it cannot
1649
+ // deliver rejects the load there instead of being logged.
1650
+ const discreteLod = extensions.has(TN_DISCRETE_LOD)
1651
+ ? new DiscreteLodPlugin({
1652
+ failClosed: (loader as { failClosed?: boolean }).failClosed === true,
1653
+ })
1654
+ : undefined;
1655
+ if (discreteLod !== undefined) {
1656
+ const plugin = discreteLod;
1657
+ loader.register((parser) => {
1658
+ plugin.setParser(parser as never);
1659
+ return plugin as never;
1660
+ });
1661
+ }
1662
+ if (extensions.has(DRACO_EXTENSION)) {
1663
+ const { DRACOLoader } = await import("three/addons/loaders/DRACOLoader.js");
1664
+ const dracoLoader = new DRACOLoader();
1665
+ dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
1666
+ loader.setDRACOLoader(dracoLoader);
1667
+ }
1668
+ const value = await new Promise<T>((resolve, reject) =>
1669
+ loader.parse(data, resourcePathOf(fileUrl), resolve as never, reject),
1670
+ );
1671
+ // Before the game ever sees it: a quantized POSITION is a trap for every ordinary
1672
+ // three.js geometry call. See `widenQuantizedPositions`.
1673
+ const root = modelRoot(value);
1674
+ if (root !== undefined) widenQuantizedPositions(root);
1675
+ // And a normalized scalar is a trap for the WebGPU pipeline. See `widenNormalizedScalars`.
1676
+ if (root !== undefined) widenNormalizedScalars(root);
1677
+ // Built here, after both widenings, so the derived levels share the widened base
1678
+ // attributes instead of pinning the quantized ones.
1679
+ if (root !== undefined && discreteLod !== undefined)
1680
+ discreteLod.attach(root, await discretePolicy(path), attachInstancedLod);
1681
+ // Before the game ever sees it: clips z-mirrored against their own bind pose play every
1682
+ // animal backwards, silently. See `reconcileMirroredClips`.
1683
+ const clips = modelClips(value);
1684
+ if (root !== undefined && clips.length > 0 && reconcileMirroredClips(root, clips)) {
1685
+ // A warning, not an info line: every file this fires on is a defect in whatever wrote
1686
+ // it, and a repair that reads as routine is a repair nobody ever removes the cause of.
1687
+ // The Unreal importer's own reader of ActorX PSA keys once produced exactly this on
1688
+ // every skeletal mesh it converted, unnoticed for as long as the line said `info`.
1689
+ const cause =
1690
+ "its clips are mirrored against its own bind pose, and the loader un-mirrored them " +
1691
+ "so the game plays forwards. The file is wrong, not the game: re-import it with a " +
1692
+ "current converter and this stops.";
1693
+ console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} — ${cause}`);
1694
+ }
1695
+ return value;
1696
+ };
1697
+ // PRD-860 Phase 3: a model the cook gave a coarse companion draws it first, and every
1698
+ // coarse geometry takes the full model in place when that lands, the game's clones
1699
+ // included. A model the game prefetched is already on its way whole.
1700
+ const coarse = warmed.has(path) ? undefined : await coarseOf(path);
1701
+ let value: T | undefined;
1702
+ const residentState: IResidentImages | undefined = streamTextures
1703
+ ? { used: false, whole: new Map() }
1704
+ : undefined;
1705
+ if (coarse !== undefined) {
1390
1706
  try {
1391
- shared = await compressedTextures.loader;
1707
+ value = await parse(coarse.url, coarse.bytes, priority, residentState);
1392
1708
  } catch (error) {
1393
- // Only ASTC-only models may select their ordinary fallback on capability refusal.
1394
- // Import/setup failures and the existing Basis contract still reject unchanged.
1395
- if (
1396
- hasBasis ||
1397
- !(error instanceof Error) ||
1398
- !error.message.startsWith("TN_ASSETS_KTX2_UNSUPPORTED:")
1399
- )
1400
- throw error;
1401
- }
1402
- if (shared !== undefined) {
1403
- loader.setKTX2Loader(shared as unknown as Parameters<typeof loader.setKTX2Loader>[0]);
1709
+ console.warn(
1710
+ `TN_ASSETS_STREAM_FAILED ${path}: the coarse model did not load, so the whole file does; ${error instanceof Error ? error.message : String(error)}`,
1711
+ );
1404
1712
  }
1405
1713
  }
1406
- if (hasAstc) {
1407
- const astcLoader = shared;
1408
- const astcSupported = hasAstcSupport(astcLoader);
1409
- // EXT_texture_astc is an official vendor draft. Borrow Three's Basis plugin handoff,
1410
- // but raw ASTC cannot use Basis's format fallback and needs this explicit GPU guard.
1411
- loader.register((parser) => {
1412
- if (!astcSupported && parser.json.extensionsRequired?.includes(astcExtension)) {
1413
- throw new Error(
1414
- "TN_ASSETS_ASTC_UNSUPPORTED: required EXT_texture_astc needs a renderer with ASTC texture-compression support.",
1415
- );
1416
- }
1417
- return {
1418
- name: astcExtension,
1419
- loadTexture(textureIndex) {
1420
- const extension = parser.json.textures[textureIndex].extensions?.[astcExtension];
1421
- if (extension === undefined || !astcSupported || astcLoader === undefined)
1422
- return null;
1423
- return parser.loadTextureImage(
1424
- textureIndex,
1425
- extension.source,
1426
- astcLoader as NonNullable<Parameters<typeof loader.setKTX2Loader>[0]>,
1714
+ if (value === undefined) value = await parse(url, await bytesOf(path), priority);
1715
+ else {
1716
+ const coarseMeshes = meshesOf(value);
1717
+ // What the coarse model brought, recorded now: the game may set a geometry, material
1718
+ // or texture of its own before the full model lands, and the upgrade leaves that alone.
1719
+ const coarseGeometries = coarseMeshes.map((mesh) => mesh.geometry);
1720
+ const upgradeTextures = streamedTextureUpgrade(coarseMeshes);
1721
+ for (const geometry of coarseGeometries) markStreamedGeometry(geometry);
1722
+ // Released, cleared or the loader disposed while the full file was on its way: the
1723
+ // coarse model is gone, so the full one is not parsed, or is released unused.
1724
+ const gone = (): boolean =>
1725
+ loaderDisposed ||
1726
+ coarseGeometries.some((geometry) => disposed.geometries.has(geometry));
1727
+ const landed = bytesOf(path)
1728
+ .then((bytes) =>
1729
+ gone()
1730
+ ? undefined
1731
+ : parse(
1732
+ url,
1733
+ bytes,
1734
+ "soon",
1735
+ residentState && { keptOnly: true, used: false, whole: residentState.whole },
1736
+ ),
1737
+ )
1738
+ .then((full) => {
1739
+ residentState?.whole.clear();
1740
+ if (full === undefined) return;
1741
+ if (gone()) {
1742
+ disposeModel(full, disposed);
1743
+ return;
1744
+ }
1745
+ const fullMeshes = meshesOf(full);
1746
+ if (fullMeshes.length !== coarseMeshes.length)
1747
+ throw new Error(
1748
+ `the full model has ${String(fullMeshes.length)} mesh(es), the coarse ${String(coarseMeshes.length)}`,
1427
1749
  );
1428
- },
1429
- };
1430
- });
1431
- }
1432
- // three's own decoder embeds its WASM; it compiles only once a compressed model is
1433
- // actually loaded. The native bundle inlines this branch (no runtime import remains),
1434
- // and the host shims WebAssembly.
1435
- if (MESHOPT_EXTENSIONS.some((extension) => extensions.has(extension))) {
1436
- const { MeshoptDecoder } = await import("three/addons/libs/meshopt_decoder.module.js");
1437
- loader.setMeshoptDecoder(MeshoptDecoder);
1438
- }
1439
- // Draco is an input format only: the compile step re-emits Draco assets as Meshopt,
1440
- // so this serves uncompiled Draco files dropped into a web root. The decoder wasm is
1441
- // served from `<basePath>draco/` by convention, like `basis/`.
1442
- // The cluster DAG the asset pipeline baked in. Registered only when the file declares it,
1443
- // so a game whose models are ordinary meshes never pays for the plugin — and a game whose
1444
- // models are not gets a plain `Mesh`, with no runtime switch either way.
1445
- if (extensions.has(TN_VIRTUAL_GEOMETRY)) {
1446
- loader.register((parser) => new VirtualGeometryPlugin(parser as never) as never);
1447
- }
1448
- // The discrete chain the asset pipeline baked in. Registered only when the file declares it,
1449
- // so a game with no auto LOD never pays for the plugin. Levels are built after the quantized
1450
- // positions are widened, so the derived geometries share the widened attributes.
1451
- // The Wasm engine's loader hosts this plugin too, and sets `failClosed`: a chain it cannot
1452
- // deliver rejects the load there instead of being logged.
1453
- const discreteLod = extensions.has(TN_DISCRETE_LOD)
1454
- ? new DiscreteLodPlugin({
1455
- failClosed: (loader as { failClosed?: boolean }).failClosed === true,
1750
+ coarseGeometries.forEach((geometry, index) =>
1751
+ upgradeStreamedGeometry(geometry, (fullMeshes[index] as Mesh).geometry),
1752
+ );
1753
+ const swapped = upgradeTextures(fullMeshes, residentState?.used === true);
1754
+ if (residentState?.used === true) {
1755
+ pool.upgraded += swapped;
1756
+ reportPool();
1757
+ }
1456
1758
  })
1457
- : undefined;
1458
- if (discreteLod !== undefined) {
1459
- const plugin = discreteLod;
1460
- loader.register((parser) => {
1461
- plugin.setParser(parser as never);
1462
- return plugin as never;
1463
- });
1464
- }
1465
- if (extensions.has(DRACO_EXTENSION)) {
1466
- const { DRACOLoader } = await import("three/addons/loaders/DRACOLoader.js");
1467
- const dracoLoader = new DRACOLoader();
1468
- dracoLoader.setDecoderPath(resolvePath(basePath, "draco/"));
1469
- loader.setDRACOLoader(dracoLoader);
1470
- }
1471
- const value = await new Promise<T>((resolve, reject) =>
1472
- loader.parse(data, resourcePathOf(url), resolve as never, reject),
1473
- );
1474
- // Before the game ever sees it: a quantized POSITION is a trap for every ordinary
1475
- // three.js geometry call. See `widenQuantizedPositions`.
1476
- const root = modelRoot(value);
1477
- if (root !== undefined) widenQuantizedPositions(root);
1478
- // And a normalized scalar is a trap for the WebGPU pipeline. See `widenNormalizedScalars`.
1479
- if (root !== undefined) widenNormalizedScalars(root);
1480
- // Built here, after both widenings, so the derived levels share the widened base
1481
- // attributes instead of pinning the quantized ones.
1482
- if (root !== undefined && discreteLod !== undefined)
1483
- discreteLod.attach(root, await discretePolicy(path));
1484
- // Before the game ever sees it: clips z-mirrored against their own bind pose play every
1485
- // animal backwards, silently. See `reconcileMirroredClips`.
1486
- const clips = modelClips(value);
1487
- if (root !== undefined && clips.length > 0 && reconcileMirroredClips(root, clips)) {
1488
- // A warning, not an info line: every file this fires on is a defect in whatever wrote
1489
- // it, and a repair that reads as routine is a repair nobody ever removes the cause of.
1490
- // The Unreal importer's own reader of ActorX PSA keys once produced exactly this on
1491
- // every skeletal mesh it converted, unnoticed for as long as the line said `info`.
1492
- const cause =
1493
- "its clips are mirrored against its own bind pose, and the loader un-mirrored them " +
1494
- "so the game plays forwards. The file is wrong, not the game: re-import it with a " +
1495
- "current converter and this stops.";
1496
- console.warn(`TN_ASSETS_MIRRORED_CLIPS_REPAIRED ${path} — ${cause}`);
1759
+ .catch((error: unknown) =>
1760
+ console.warn(
1761
+ `TN_ASSETS_STREAM_FAILED ${path}: the coarse model stays; ${error instanceof Error ? error.message : String(error)}`,
1762
+ ),
1763
+ );
1764
+ if (typeof value === "object" && value !== null) wholeOf.set(value, landed);
1497
1765
  }
1498
1766
  stampAssetProvenance(value, path);
1499
1767
  await attachCompiledLightmaps(path, value);
1500
1768
  return value;
1501
1769
  },
1502
1770
  request?.priority ?? "now",
1771
+ request?.whole === true,
1503
1772
  ),
1504
1773
  get cache() {
1505
1774
  return { ...assetCache.report, clear: () => assetCache.clear() };
@@ -1507,9 +1776,13 @@ export function createAssetLoader(options: IAssetLoaderOptions = {}): IAssetLoad
1507
1776
  get progress() {
1508
1777
  return { pending: [...pending], requested, requestedBytes, settled, settledBytes };
1509
1778
  },
1779
+ memo: createAssetMemo(canonicalUrl(manifestUrl)),
1510
1780
  prefetch: prefetchPaths,
1511
1781
  resolve: async (path) => (await resolveCandidates(path)).urls,
1512
1782
  startBackgroundFill: () => {
1783
+ // The reveal is the first moment the network is free and the player is playing, so it is also
1784
+ // where a request stops being a load and starts being a pop-in. See `ASSET_LATE_MARKER`.
1785
+ revealedAtMs ??= performanceNow();
1513
1786
  // The fill needs the manifest even when the scene loaded nothing through this loader yet;
1514
1787
  // a failed read is the documented no-manifest case and simply leaves the fill empty.
1515
1788
  void manifestOnce().catch(() => undefined);
@@ -1670,3 +1943,42 @@ function isSize(bytes: unknown): bytes is number {
1670
1943
  function isRecord(value: unknown): value is Record<string, unknown> {
1671
1944
  return typeof value === "object" && value !== null;
1672
1945
  }
1946
+
1947
+ /**
1948
+ * Fetch a data file the asset loader serves: each url `assets.resolve(path)` names, in order, until
1949
+ * one answers ok. A built game serves the hashed output and a dev server the source path, so taking
1950
+ * only the first url 404s on one of them. When none answers it throws `TN_ASSET_NOT_SERVED` naming
1951
+ * every url tried and why, so a missing file is never a half-drawn world.
1952
+ *
1953
+ * @situation load a baked JSON or binary file (a heightmap, a placement buffer, a data table) that the loader has no typed method for
1954
+ * @situation a data file loads in dev but 404s in the built game
1955
+ * @constraint reads the response once; call `.json()` or `.arrayBuffer()` on the result
1956
+ * @example const heights = new Float32Array(await (await fetchAsset(ctx.assets, "world/forest.bin")).arrayBuffer());
1957
+ */
1958
+ export async function fetchAsset(
1959
+ assets: Pick<IAssetLoader, "resolve">,
1960
+ path: string,
1961
+ ): Promise<Response> {
1962
+ const candidates = await assets.resolve(path);
1963
+ const failures: string[] = [];
1964
+ let answered = false;
1965
+ let lastError: unknown;
1966
+ for (const url of candidates) {
1967
+ let response: Response;
1968
+ try {
1969
+ response = await fetch(url);
1970
+ } catch (error) {
1971
+ lastError = error;
1972
+ failures.push(`${url} (${error instanceof Error ? error.message : String(error)})`);
1973
+ continue;
1974
+ }
1975
+ answered = true;
1976
+ if (response.ok) return response;
1977
+ failures.push(`${url} (status ${String(response.status)})`);
1978
+ }
1979
+ // When every fetch rejected, the last rejection is the cause: a native host's file error says why.
1980
+ throw new Error(
1981
+ `TN_ASSET_NOT_SERVED: '${path}' is not served by any of ${String(candidates.length)} candidate url(s): ${failures.join("; ") || "none"}.`,
1982
+ answered || candidates.length === 0 ? undefined : { cause: lastError },
1983
+ );
1984
+ }