@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
@@ -27,6 +27,12 @@ const IMAGE_COLD: IStartupImageState = {
27
27
  };
28
28
 
29
29
  export interface IStartupReadinessOptions {
30
+ /**
31
+ * Final render-owned work (such as shadow maps), checked after warm-up for two quiet frames.
32
+ * Settlement still missing after stableWindowMs resolves readiness anyway and sets `timedOut`:
33
+ * a late shadow costs a pop, never a game that does not start.
34
+ */
35
+ readonly settled?: () => boolean;
30
36
  /** Maximum wall-clock time spent waiting for first-use compilation. */
31
37
  readonly compileBudgetMs?: number;
32
38
  /** Maximum measured callback duration for a stable startup frame. */
@@ -70,8 +76,9 @@ export interface IStartupReadinessOptions {
70
76
  * then hit 28 main-thread tasks over 40 ms, the worst 267 ms, dominated by TSL graph `build` and
71
77
  * by the main thread idling on GPU pipeline creation.
72
78
  *
73
- * Rejections are swallowed: a warm-up that fails must cost hitches, never a game that will not
74
- * start.
79
+ * A rejection fails `whenReady()` so the loading layer can report a first-use failure instead
80
+ * of revealing a world whose pipeline creation failed. A warm-up still running after
81
+ * `stableWindowMs` is slow, not failed: the gate moves on to settlement and sets `timedOut`.
75
82
  */
76
83
  readonly afterHolds?: () => Promise<void> | void;
77
84
  }
@@ -126,8 +133,8 @@ export const STARTUP_IMAGE_TIMEOUT_MS = 3_000;
126
133
  /** One registered hold: the game's own launch work, and the bounded wait for it. */
127
134
  interface IHold {
128
135
  readonly label: string;
129
- /** Polled once per rendered frame for a predicate hold; absent for a promise hold. */
130
- readonly ready?: () => boolean;
136
+ /** Polled for a predicate hold; absent for a promise hold or a failed-open predicate. */
137
+ ready?: () => boolean;
131
138
  release?: (expired: boolean) => void;
132
139
  settled: boolean;
133
140
  timer: ReturnType<typeof setTimeout> | undefined;
@@ -145,6 +152,13 @@ export class StartupReadiness {
145
152
  #stableFrameCount = 0;
146
153
  #started = false;
147
154
  #ready = false;
155
+ #failed = false;
156
+ #cancelled = false;
157
+ readonly #settled: (() => boolean) | undefined;
158
+ #quietFrames = 0;
159
+ #finishing = false;
160
+ #afterHoldsDone = false;
161
+ #timedOut: "warmup" | "settlement" | undefined;
148
162
  #frameWindowDone = false;
149
163
  readonly #holds = new Map<string, IHold>();
150
164
  #holdBudgetMs: number;
@@ -156,6 +170,7 @@ export class StartupReadiness {
156
170
  #compileTimer: ReturnType<typeof setTimeout> | undefined;
157
171
  #windowTimer: ReturnType<typeof setTimeout> | undefined;
158
172
  #resolveReady: () => void = () => undefined;
173
+ #rejectReady: (error: Error) => void = () => undefined;
159
174
  #resolveFrameworkReady: () => void = () => undefined;
160
175
  readonly #readyPromise: Promise<void>;
161
176
  readonly #frameworkReadyPromise: Promise<void>;
@@ -182,15 +197,30 @@ export class StartupReadiness {
182
197
  "holdBudgetMs",
183
198
  );
184
199
  this.#afterHolds = options.afterHolds;
200
+ this.#settled = options.settled;
185
201
  this.#imageReady = options.imageReady;
186
- this.#readyPromise = new Promise<void>((resolve) => {
202
+ this.#readyPromise = new Promise<void>((resolve, reject) => {
187
203
  this.#resolveReady = resolve;
204
+ this.#rejectReady = reject;
188
205
  });
189
206
  this.#frameworkReadyPromise = new Promise<void>((resolve) => {
190
207
  this.#resolveFrameworkReady = resolve;
191
208
  });
192
209
  }
193
210
 
211
+ /** Stop observing a discarded launch without publishing readiness or failure. */
212
+ cancel(): void {
213
+ this.#cancelled = true;
214
+ if (this.#compileTimer !== undefined) clearTimeout(this.#compileTimer);
215
+ if (this.#windowTimer !== undefined) clearTimeout(this.#windowTimer);
216
+ this.#compileTimer = undefined;
217
+ this.#windowTimer = undefined;
218
+ for (const hold of this.#holds.values()) {
219
+ if (hold.timer !== undefined) clearTimeout(hold.timer);
220
+ hold.timer = undefined;
221
+ }
222
+ }
223
+
194
224
  whenReady(): Promise<void> {
195
225
  return this.#readyPromise;
196
226
  }
@@ -227,6 +257,11 @@ export class StartupReadiness {
227
257
  return this.#frameWindowDone;
228
258
  }
229
259
 
260
+ /** Which bounded post-hold wait ran out, if any; readiness resolved anyway. */
261
+ get timedOut(): "warmup" | "settlement" | undefined {
262
+ return this.#timedOut;
263
+ }
264
+
230
265
  /** Labels of holds that have not settled yet, in registration order. */
231
266
  get pendingHolds(): readonly string[] {
232
267
  return [...this.#holds.values()].filter((hold) => !hold.settled).map((hold) => hold.label);
@@ -283,6 +318,7 @@ export class StartupReadiness {
283
318
  budgetMs: number = this.#holdBudgetMs,
284
319
  progress?: () => number,
285
320
  ): void {
321
+ if (this.#cancelled) return;
286
322
  if (typeof label !== "string" || label.trim() === "")
287
323
  throw new Error("TN_STARTUP_HOLD_LABEL_INVALID: a hold needs a non-empty label.");
288
324
  if (this.#holds.has(label))
@@ -303,7 +339,7 @@ export class StartupReadiness {
303
339
  };
304
340
  this.#holds.set(label, hold);
305
341
  const release = (expired: boolean): void => {
306
- if (hold.settled) return;
342
+ if (this.#cancelled || hold.settled) return;
307
343
  this.#sampleHold(hold);
308
344
  hold.progress = undefined;
309
345
  hold.settled = true;
@@ -332,6 +368,17 @@ export class StartupReadiness {
332
368
  }
333
369
  }
334
370
 
371
+ #holdReady(hold: IHold): boolean {
372
+ if (hold.expired || hold.ready === undefined) return true;
373
+ try {
374
+ return hold.ready();
375
+ } catch {
376
+ // Like a rejected promise, a failed predicate remains settled on later quiet polls.
377
+ hold.ready = undefined;
378
+ return true;
379
+ }
380
+ }
381
+
335
382
  /**
336
383
  * Predicate holds settle on rendered frames, not simulation steps: a deterministic playtest clock
337
384
  * advances no fixed step while startup is held, so a gate read only in `afterPhysics` waited on
@@ -340,13 +387,7 @@ export class StartupReadiness {
340
387
  #pollHolds(): void {
341
388
  for (const hold of this.#holds.values()) {
342
389
  if (hold.settled || hold.ready === undefined) continue;
343
- let done: boolean;
344
- try {
345
- done = hold.ready();
346
- } catch {
347
- done = true;
348
- }
349
- if (done) hold.release?.(false);
390
+ if (this.#holdReady(hold)) hold.release?.(false);
350
391
  }
351
392
  }
352
393
 
@@ -408,7 +449,7 @@ export class StartupReadiness {
408
449
 
409
450
  /** Begin the one-time first-use gate after the entered scene has been built. */
410
451
  start(compile?: StartupCompile): void {
411
- if (this.#started) return;
452
+ if (this.#cancelled || this.#started) return;
412
453
  this.#started = true;
413
454
  if (compile === undefined) {
414
455
  this.#finishCompile();
@@ -419,7 +460,9 @@ export class StartupReadiness {
419
460
  // Defer the call one microtask so the already-visible loading layer gets a present before a
420
461
  // renderer that performs synchronous first-use work starts compiling.
421
462
  void Promise.resolve()
422
- .then(() => compile())
463
+ .then(() => {
464
+ if (!this.#cancelled) return compile();
465
+ })
423
466
  .then(
424
467
  () => this.#finishCompile(),
425
468
  () => this.#finishCompile(),
@@ -428,11 +471,24 @@ export class StartupReadiness {
428
471
 
429
472
  /** Feed actual callback wall time, not requestAnimationFrame timestamp spacing. */
430
473
  observe(frameMs: number): void {
474
+ if (this.#cancelled || this.#failed) return;
431
475
  if (!this.#ready) {
432
476
  this.#pollHolds();
433
477
  this.#pollImage();
434
478
  }
435
479
  if (!this.#started || this.#ready) return;
480
+ if (this.#afterHoldsDone && this.#settled !== undefined) {
481
+ const quiet =
482
+ this.#settled() &&
483
+ [...this.#holds.values()].every((hold) => hold.settled && this.#holdReady(hold));
484
+ this.#quietFrames = quiet ? this.#quietFrames + 1 : 0;
485
+ if (this.#quietFrames >= 2) {
486
+ if (this.#windowTimer !== undefined) clearTimeout(this.#windowTimer);
487
+ this.#windowTimer = undefined;
488
+ this.#ready = true;
489
+ this.#resolveReady();
490
+ }
491
+ }
436
492
  if (
437
493
  this.#compileSettled &&
438
494
  Number.isFinite(frameMs) &&
@@ -449,7 +505,7 @@ export class StartupReadiness {
449
505
  }
450
506
 
451
507
  #finishCompile(): void {
452
- if (this.#compileSettled) return;
508
+ if (this.#cancelled || this.#compileSettled) return;
453
509
  this.#compileSettled = true;
454
510
  if (this.#compileTimer !== undefined) clearTimeout(this.#compileTimer);
455
511
  this.#compileTimer = undefined;
@@ -463,7 +519,7 @@ export class StartupReadiness {
463
519
 
464
520
  /** The framework's own work is done. Whether the *world* is ready also depends on the holds and the picture. */
465
521
  #finishFrameWindow(): void {
466
- if (this.#frameWindowDone) return;
522
+ if (this.#cancelled || this.#frameWindowDone) return;
467
523
  this.#frameWindowDone = true;
468
524
  if (this.#windowTimer !== undefined) clearTimeout(this.#windowTimer);
469
525
  this.#windowTimer = undefined;
@@ -473,7 +529,7 @@ export class StartupReadiness {
473
529
  }
474
530
 
475
531
  #resolveIfComplete(): void {
476
- if (this.#ready || !this.#frameWindowDone) return;
532
+ if (this.#cancelled || this.#ready || this.#finishing || !this.#frameWindowDone) return;
477
533
  for (const hold of this.#holds.values()) if (!hold.settled) return;
478
534
  // Last, because it is the only wait that is not the caller's: a renderer that has not drawn a world a
479
535
  // player may see yet keeps the cover, whatever the timers say — and no longer than its own deadline.
@@ -483,26 +539,64 @@ export class StartupReadiness {
483
539
  this.#armImageDeadline();
484
540
  return;
485
541
  }
486
- // Claim readiness before awaiting, so a hold that settles during `afterHolds` cannot re-enter
487
- // and run it twice.
488
- this.#ready = true;
489
- if (this.#imageTimer !== undefined) clearTimeout(this.#imageTimer);
490
- this.#imageTimer = undefined;
542
+ this.#finishing = true;
543
+ const finish = (): void => {
544
+ if (this.#cancelled || this.#failed || this.#afterHoldsDone) return;
545
+ this.#afterHoldsDone = true;
546
+ // `#finishing` claims the reveal before awaiting, so a hold that settles during `afterHolds`
547
+ // cannot re-enter; the image deadline is spent the moment the reveal is decided.
548
+ if (this.#imageTimer !== undefined) clearTimeout(this.#imageTimer);
549
+ this.#imageTimer = undefined;
550
+ if (this.#settled === undefined) {
551
+ this.#ready = true;
552
+ this.#resolveReady();
553
+ } else {
554
+ // Bounded by the frame-window budget. A slow machine gets the world with a late shadow,
555
+ // and `timedOut` says so, instead of a loading screen that never lifts.
556
+ this.#windowTimer = setTimeout(() => {
557
+ this.#windowTimer = undefined;
558
+ if (this.#cancelled || this.#failed || this.#ready) return;
559
+ this.#timedOut ??= "settlement";
560
+ this.#ready = true;
561
+ this.#resolveReady();
562
+ }, this.#stableWindowMs);
563
+ }
564
+ };
491
565
  const afterHolds = this.#afterHolds;
492
- // No holds means no second tier, which means the framework's own pass already saw the whole
493
- // scene. Resolving synchronously there keeps every game that does not stream exactly as it was.
494
566
  if (afterHolds === undefined || this.#holds.size === 0) {
495
- this.#resolveReady();
567
+ finish();
496
568
  return;
497
569
  }
498
- void (async () => {
499
- try {
500
- await afterHolds();
501
- } catch {
502
- // Swallowed on purpose: a warm-up that fails costs hitches, not a game that never starts.
503
- }
504
- this.#resolveReady();
505
- })();
570
+ this.#windowTimer = setTimeout(() => {
571
+ this.#windowTimer = undefined;
572
+ if (this.#cancelled || this.#failed || this.#ready) return;
573
+ // A slow warm-up costs first-use hitches, never a game that does not start.
574
+ this.#timedOut = "warmup";
575
+ finish();
576
+ }, this.#stableWindowMs);
577
+ let afterHoldsWork: Promise<void> | void;
578
+ try {
579
+ afterHoldsWork = afterHolds();
580
+ } catch (error) {
581
+ afterHoldsWork = Promise.reject(error);
582
+ }
583
+ void Promise.resolve(afterHoldsWork).then(
584
+ () => {
585
+ if (this.#afterHoldsDone) return;
586
+ if (this.#windowTimer !== undefined) clearTimeout(this.#windowTimer);
587
+ this.#windowTimer = undefined;
588
+ finish();
589
+ },
590
+ (error: unknown) => {
591
+ // A failure after the warm-up already timed out arrives too late to hold the reveal.
592
+ if (this.#afterHoldsDone) return;
593
+ if (this.#windowTimer !== undefined) clearTimeout(this.#windowTimer);
594
+ this.#windowTimer = undefined;
595
+ if (this.#cancelled || this.#failed || this.#ready) return;
596
+ this.#failed = true;
597
+ this.#rejectReady(error instanceof Error ? error : new Error(String(error)));
598
+ },
599
+ );
506
600
  }
507
601
  }
508
602
 
@@ -16,7 +16,7 @@
16
16
  * **Staticness is authored, never guessed.** A heuristic that decides an object has "not moved in
17
17
  * 60 frames" is a correctness bug with no reproduction, so nothing here watches gameplay. What the
18
18
  * engine does do is check the promise where it is cheap to check it: the root's own local transform
19
- * is compared against what was frozen, once per frame, and a root the author moved thaws and
19
+ * and its parent's world matrix are compared against what was frozen, once per frame, and a root the author moved thaws and
20
20
  * refreezes itself. That is O(static roots), not O(objects), and it turns the most common way to
21
21
  * get this wrong into a non-event. Writes deeper inside a frozen subtree are the author's to
22
22
  * announce with `invalidateStatic`, and `TN_RENDERLIST_VALIDATE=1` is what proves they did.
@@ -47,7 +47,9 @@ interface IFrozenRoot {
47
47
  */
48
48
  const frozen = new Map<Object3D, IFrozenRoot>();
49
49
 
50
- const SNAPSHOT_LENGTH = 3 + 4 + 3 + 16;
50
+ /** Position, quaternion, scale, local matrix, then the parent's world matrix (identity with none). */
51
+ const SNAPSHOT_LENGTH = 3 + 4 + 3 + 16 + 16;
52
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
51
53
 
52
54
  function writeSnapshot(root: Object3D, into: Float64Array): void {
53
55
  const position: Vector3 = root.position;
@@ -66,6 +68,12 @@ function writeSnapshot(root: Object3D, into: Float64Array): void {
66
68
  into[9] = scale.z;
67
69
  for (let element = 0; element < 16; element += 1)
68
70
  into[10 + element] = matrix.elements[element] ?? 0;
71
+ // The frozen world matrix is the parent's times the root's own, so a root attached after it froze,
72
+ // or one whose ancestor moved, is as stale as one the author moved. A streamed world freezes each
73
+ // draw before it joins the world root, and a seated world (`world.position.y = -ground`) drew
74
+ // every tree at the package's absolute height.
75
+ const parent = root.parent?.matrixWorld.elements ?? IDENTITY;
76
+ for (let element = 0; element < 16; element += 1) into[26 + element] = parent[element] ?? 0;
69
77
  }
70
78
 
71
79
  function snapshotMatches(root: Object3D, snapshot: Float64Array, scratch: Float64Array): boolean {
@@ -122,6 +130,15 @@ export function worldSilencedByFreeze(object: Object3D): boolean {
122
130
  return worldSilenced.has(object);
123
131
  }
124
132
 
133
+ /** Gives a frozen subtree its compose flags back, so the next update recomposes it. */
134
+ function thaw(root: Object3D): void {
135
+ if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
136
+ root.traverse((child) => {
137
+ if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
138
+ child.matrixWorldNeedsUpdate = true;
139
+ });
140
+ }
141
+
125
142
  /** Freezes the subtree in place and answers how many objects stopped recomposing. */
126
143
  function freeze(root: Object3D): number {
127
144
  root.updateMatrixWorld(true);
@@ -150,8 +167,11 @@ function freeze(root: Object3D): number {
150
167
  * `invalidateStatic` does and the reason a generator can emit the call unconditionally.
151
168
  */
152
169
  export function markStatic(root: Object3D): number {
153
- const objects = freeze(root);
154
170
  const existing = frozen.get(root);
171
+ // A second mark re-arms: thaw first, or `freeze`'s update skips the root's own world compose (the
172
+ // first freeze turned it off) and the subtree keeps the world matrix of its first parent.
173
+ if (existing !== undefined) thaw(root);
174
+ const objects = freeze(root);
155
175
  const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH);
156
176
  writeSnapshot(root, snapshot);
157
177
  const version = (existing?.version ?? 0) + 1;
@@ -186,17 +206,8 @@ export function unmarkStatic(root: Object3D): void {
186
206
  export function invalidateStatic(object: Object3D): number | undefined {
187
207
  let node: Object3D | null = object;
188
208
  while (node !== null) {
189
- if (frozen.has(node)) {
190
- // Thaw the flags first: `freeze` starts with a forced update, and an object left with
191
- // `matrixAutoUpdate` off would recompose its world matrix from a stale local one.
192
- const root = node;
193
- root.traverse((child) => {
194
- if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
195
- child.matrixWorldNeedsUpdate = true;
196
- });
197
- if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
198
- return markStatic(root);
199
- }
209
+ // `markStatic` thaws a frozen root before it freezes it again.
210
+ if (frozen.has(node)) return markStatic(node);
200
211
  node = node.parent;
201
212
  }
202
213
  return undefined;
@@ -244,11 +255,6 @@ export function refreshStaticTransforms(): void {
244
255
  if (frozen.size === 0) return;
245
256
  for (const entry of frozen.values()) {
246
257
  if (snapshotMatches(entry.root, entry.snapshot, scratch)) continue;
247
- if (worldSilenced.delete(entry.root)) entry.root.matrixWorldAutoUpdate = true;
248
- entry.root.traverse((child) => {
249
- if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
250
- child.matrixWorldNeedsUpdate = true;
251
- });
252
258
  markStatic(entry.root);
253
259
  rearmedSinceCensus += 1;
254
260
  }
@@ -0,0 +1,112 @@
1
+ import type { Mesh } from "three";
2
+
3
+ /** The material texture slots a model's images reach (glTF's own, plus the physical extensions). */
4
+ const TEXTURE_SLOTS = [
5
+ "map",
6
+ "normalMap",
7
+ "roughnessMap",
8
+ "metalnessMap",
9
+ "aoMap",
10
+ "emissiveMap",
11
+ "alphaMap",
12
+ "bumpMap",
13
+ "lightMap",
14
+ "displacementMap",
15
+ "clearcoatMap",
16
+ "clearcoatNormalMap",
17
+ "clearcoatRoughnessMap",
18
+ "sheenColorMap",
19
+ "sheenRoughnessMap",
20
+ "transmissionMap",
21
+ "thicknessMap",
22
+ "iridescenceMap",
23
+ "specularColorMap",
24
+ "specularIntensityMap",
25
+ ] as const;
26
+
27
+ type SlottedMaterial = Record<string, unknown> & { needsUpdate?: boolean };
28
+
29
+ type Releasable = { dispose?: () => void };
30
+
31
+ /** Texture state a game sets after load (sampler, transform, tags); the whole file keeps it. */
32
+ const CARRIED = [
33
+ "anisotropy",
34
+ "wrapS",
35
+ "wrapT",
36
+ "magFilter",
37
+ "minFilter",
38
+ "colorSpace",
39
+ "channel",
40
+ "rotation",
41
+ "matrixAutoUpdate",
42
+ "userData",
43
+ ] as const;
44
+ const CARRIED_VECTORS = ["offset", "repeat", "center", "matrix"] as const;
45
+
46
+ /** Gives `next` what the game set on `from`, so the swap changes the mips and nothing else. */
47
+ function carry(from: Record<string, unknown>, next: Record<string, unknown>): void {
48
+ for (const name of CARRIED) if (name in from) next[name] = from[name];
49
+ for (const name of CARRIED_VECTORS)
50
+ (next[name] as { copy?: (value: unknown) => void } | undefined)?.copy?.(from[name]);
51
+ }
52
+
53
+ const materialsOf = (mesh: Mesh | undefined): SlottedMaterial[] =>
54
+ ([] as unknown[]).concat(mesh?.material).filter(Boolean) as SlottedMaterial[];
55
+
56
+ /**
57
+ * PRD-860 Phase 2: the coarse model drew with each texture's resident mips; the full model parses
58
+ * with the whole files. Call this at the coarse load: it records the textures the coarse model
59
+ * brought. The returned function takes the full model's meshes when they land and puts the whole
60
+ * texture in every slot that still holds a recorded one, on whatever material the mesh has now, so a
61
+ * clone of the material takes it too while a texture or material the game set meanwhile stays. The
62
+ * whole texture takes what the game set on the resident one (anisotropy, wrap, transform). It
63
+ * releases the replaced resident textures and every full-model texture nothing took. With
64
+ * `swap: false` (no resident mips were served, so the coarse textures are already whole) it only
65
+ * releases the full model's copies. Returns how many slots swapped.
66
+ */
67
+ export function streamedTextureUpgrade(
68
+ coarse: readonly Mesh[],
69
+ ): (full: readonly Mesh[], swap: boolean) => number {
70
+ const loaded = coarse.map((mesh) =>
71
+ materialsOf(mesh).map((material) => TEXTURE_SLOTS.map((name) => material[name])),
72
+ );
73
+ return (full, swap) => {
74
+ const whole = new Map<Releasable, Releasable>();
75
+ const unused = new Set<Releasable>();
76
+ full.forEach((mesh, index) =>
77
+ materialsOf(mesh).forEach((material, slot) =>
78
+ TEXTURE_SLOTS.forEach((name, at) => {
79
+ const next = material[name] as Releasable | null | undefined;
80
+ const resident = loaded[index]?.[slot]?.[at] as Releasable | null | undefined;
81
+ if (!next || next === resident) return;
82
+ if (swap && resident) whole.set(resident, next);
83
+ else unused.add(next);
84
+ }),
85
+ ),
86
+ );
87
+ const replaced = new Set<Releasable>();
88
+ const taken = new Set<Releasable>();
89
+ let swapped = 0;
90
+ for (const mesh of whole.size > 0 ? coarse : [])
91
+ for (const material of materialsOf(mesh)) {
92
+ let changed = false;
93
+ for (const name of TEXTURE_SLOTS) {
94
+ const resident = material[name] as Releasable | null | undefined;
95
+ const next = resident ? whole.get(resident) : undefined;
96
+ if (resident === null || resident === undefined || next === undefined) continue;
97
+ if (!taken.has(next))
98
+ carry(resident as Record<string, unknown>, next as Record<string, unknown>);
99
+ material[name] = next;
100
+ replaced.add(resident);
101
+ taken.add(next);
102
+ swapped += 1;
103
+ changed = true;
104
+ }
105
+ if (changed) material.needsUpdate = true;
106
+ }
107
+ for (const next of whole.values()) unused.add(next);
108
+ for (const texture of replaced) texture.dispose?.();
109
+ for (const texture of unused) if (!taken.has(texture)) texture.dispose?.();
110
+ return swapped;
111
+ };
112
+ }
package/src/streaming.ts CHANGED
@@ -133,6 +133,65 @@ export const DEFAULT_CONCURRENCY = 6;
133
133
 
134
134
  const now = (): number => globalThis.performance?.now() ?? Date.now();
135
135
 
136
+ /** Kept back from a frame's headroom for the browser's own commit and the GPU process. */
137
+ const SLICE_FRAME_MARGIN_MS = 2;
138
+ /** A slice always gets this much, so a frame with no headroom still moves the list. */
139
+ const MIN_SLICE_BUDGET_MS = 1;
140
+ /** A loop that stops presenting (a hidden tab) must not stall a run: fall back to the host. */
141
+ const LOOP_FRAME_WAIT_MS = 250;
142
+
143
+ /**
144
+ * The game loop's frame pulse, for slices that run once the world is on screen.
145
+ *
146
+ * In Chrome a `scheduler.yield` continuation runs ahead of rendering, so a chain of 8 ms slices
147
+ * presents no frame until the scheduler's ~100 ms starvation guard fires. That is harmless behind
148
+ * a loading curtain and a 10 fps stutter in front of the player: Midway streaming its cockpit
149
+ * after the reveal read a 102 ms host gap at p95, against 9 ms with nothing streaming. So once
150
+ * the loop says the world is visible, a slice waits for the loop's next frame, then for one host
151
+ * yield so it runs after that frame commits, and spends only the headroom the frame left.
152
+ */
153
+ const loopFrames = {
154
+ visible: false,
155
+ budgetMs: DEFAULT_SLICE_BUDGET_MS,
156
+ waiters: [] as Array<() => void>,
157
+ };
158
+
159
+ /**
160
+ * Called by the frame loop after every frame callback: its wall time, the target rate and
161
+ * whether the world is on screen.
162
+ *
163
+ * @internal Shared with `game-frame-loop.ts`; not part of the public surface.
164
+ */
165
+ export function noteSliceFrame(frameMs: number, targetFps: number, visible: boolean): void {
166
+ loopFrames.visible = visible;
167
+ loopFrames.budgetMs =
168
+ targetFps > 0
169
+ ? Math.min(
170
+ DEFAULT_SLICE_BUDGET_MS,
171
+ Math.max(MIN_SLICE_BUDGET_MS, 1_000 / targetFps - frameMs - SLICE_FRAME_MARGIN_MS),
172
+ )
173
+ : DEFAULT_SLICE_BUDGET_MS;
174
+ for (const resolve of loopFrames.waiters.splice(0)) resolve();
175
+ }
176
+
177
+ /** The loop stopped: release every waiting slice and go back to the host yield. @internal */
178
+ export function endSliceFrames(): void {
179
+ noteSliceFrame(0, 0, false);
180
+ }
181
+
182
+ const nextLoopFrame = (): Promise<void> =>
183
+ new Promise<void>((resolve) => {
184
+ const timer = setTimeout(resolve, LOOP_FRAME_WAIT_MS);
185
+ loopFrames.waiters.push(() => {
186
+ clearTimeout(timer);
187
+ resolve();
188
+ });
189
+ }).then(yieldToHost);
190
+
191
+ const yieldSlice = (): Promise<void> => (loopFrames.visible ? nextLoopFrame() : yieldToHost());
192
+ const sliceBudget = (): number =>
193
+ loopFrames.visible ? loopFrames.budgetMs : DEFAULT_SLICE_BUDGET_MS;
194
+
136
195
  function assertWholeAtLeastOne(value: number, name: string, code: string): void {
137
196
  if (!Number.isInteger(value) || value < 1) {
138
197
  throw new Error(
@@ -166,8 +225,10 @@ export async function addInSlices<T>(
166
225
  assertWholeAtLeastOne(sliceSize, "sliceSize", "TN_ADD_SLICES_SLICE_INVALID");
167
226
  }
168
227
  const countSlices = sliceSize !== undefined;
169
- const sliceBudgetMs = countSlices ? undefined : DEFAULT_SLICE_BUDGET_MS;
170
- const yieldFrame = options.yieldFrame ?? yieldToHost;
228
+ // A game's own yield keeps the fixed budget: the frame pulse paces only the engine's yield.
229
+ const nextBudget = options.yieldFrame === undefined ? sliceBudget : () => DEFAULT_SLICE_BUDGET_MS;
230
+ let sliceBudgetMs = countSlices ? undefined : nextBudget();
231
+ const yieldFrame = options.yieldFrame ?? yieldSlice;
171
232
  const shouldContinue = options.while;
172
233
  const startedAt = now();
173
234
 
@@ -189,7 +250,10 @@ export async function addInSlices<T>(
189
250
  if (yieldAfter) {
190
251
  await yieldFrame();
191
252
  // The presented frame is not part of the next slice's work.
192
- if (sliceBudgetMs !== undefined) sliceStartedAt = now();
253
+ if (sliceBudgetMs !== undefined) {
254
+ sliceBudgetMs = nextBudget();
255
+ sliceStartedAt = now();
256
+ }
193
257
  }
194
258
  };
195
259
 
@@ -197,7 +261,7 @@ export async function addInSlices<T>(
197
261
  const sliceSpent = (): boolean =>
198
262
  sliceSize !== undefined
199
263
  ? added % sliceSize === 0
200
- : now() - sliceStartedAt >= DEFAULT_SLICE_BUDGET_MS;
264
+ : now() - sliceStartedAt >= Number(sliceBudgetMs);
201
265
 
202
266
  for (let index = 0; index < total; index += 1) {
203
267
  if (shouldContinue !== undefined && !shouldContinue()) {