@threenative/core 0.3.12 → 0.3.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -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.
@@ -36,6 +36,13 @@ interface IFrozenRoot {
36
36
  readonly snapshot: Float64Array;
37
37
  /** Bumped every time the subtree is re-armed; the contract a consumer checks, not the flag. */
38
38
  version: number;
39
+ /**
40
+ * Set by {@link markEngineStatic}: the parent the root was frozen under. The engine owns the root's
41
+ * local transform, so the per-frame check reads only this parent's world matrix, once per parent.
42
+ */
43
+ parent?: Object3D | null;
44
+ /** An engine-owned root not yet checked in full since it froze. */
45
+ fresh?: boolean;
39
46
  }
40
47
 
41
48
  /**
@@ -47,13 +54,17 @@ interface IFrozenRoot {
47
54
  */
48
55
  const frozen = new Map<Object3D, IFrozenRoot>();
49
56
 
50
- const SNAPSHOT_LENGTH = 3 + 4 + 3 + 16;
57
+ /** Position, quaternion, scale, local matrix, then the parent's world matrix (identity with none). */
58
+ const SNAPSHOT_LENGTH = 3 + 4 + 3 + 16 + 16;
59
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
51
60
 
52
61
  function writeSnapshot(root: Object3D, into: Float64Array): void {
53
62
  const position: Vector3 = root.position;
54
63
  const quaternion: Quaternion = root.quaternion;
55
64
  const scale: Vector3 = root.scale;
56
- const matrix: Matrix4 = root.matrix;
65
+ // One read of each `elements`: on the owned engine it is an accessor that resolves a Wasm heap
66
+ // view per read, and this runs for every frozen root every frame (PRD-887 AC-3).
67
+ const matrix: Matrix4["elements"] = root.matrix.elements;
57
68
  into[0] = position.x;
58
69
  into[1] = position.y;
59
70
  into[2] = position.z;
@@ -64,8 +75,13 @@ function writeSnapshot(root: Object3D, into: Float64Array): void {
64
75
  into[7] = scale.x;
65
76
  into[8] = scale.y;
66
77
  into[9] = scale.z;
67
- for (let element = 0; element < 16; element += 1)
68
- into[10 + element] = matrix.elements[element] ?? 0;
78
+ for (let element = 0; element < 16; element += 1) into[10 + element] = matrix[element] ?? 0;
79
+ // The frozen world matrix is the parent's times the root's own, so a root attached after it froze,
80
+ // or one whose ancestor moved, is as stale as one the author moved. A streamed world freezes each
81
+ // draw before it joins the world root, and a seated world (`world.position.y = -ground`) drew
82
+ // every tree at the package's absolute height.
83
+ const parent = root.parent?.matrixWorld.elements ?? IDENTITY;
84
+ for (let element = 0; element < 16; element += 1) into[26 + element] = parent[element] ?? 0;
69
85
  }
70
86
 
71
87
  function snapshotMatches(root: Object3D, snapshot: Float64Array, scratch: Float64Array): boolean {
@@ -122,6 +138,15 @@ export function worldSilencedByFreeze(object: Object3D): boolean {
122
138
  return worldSilenced.has(object);
123
139
  }
124
140
 
141
+ /** Gives a frozen subtree its compose flags back, so the next update recomposes it. */
142
+ function thaw(root: Object3D): void {
143
+ if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
144
+ root.traverse((child) => {
145
+ if (composeSilenced.delete(child)) child.matrixAutoUpdate = true;
146
+ child.matrixWorldNeedsUpdate = true;
147
+ });
148
+ }
149
+
125
150
  /** Freezes the subtree in place and answers how many objects stopped recomposing. */
126
151
  function freeze(root: Object3D): number {
127
152
  root.updateMatrixWorld(true);
@@ -150,12 +175,35 @@ function freeze(root: Object3D): number {
150
175
  * `invalidateStatic` does and the reason a generator can emit the call unconditionally.
151
176
  */
152
177
  export function markStatic(root: Object3D): number {
153
- const objects = freeze(root);
178
+ return freezeRoot(root, false);
179
+ }
180
+
181
+ /**
182
+ * `markStatic` for a draw the engine creates and owns, such as a streamed world's instanced batches:
183
+ * nothing but the engine writes its local transform, and the engine re-arms it when it does. The
184
+ * per-frame check then reads its parent's world matrix once for every draw under that parent, rather
185
+ * than every draw's own transform: a cooked region froze 2,077 batches at its overview and paid the
186
+ * per-root check for each (PRD-887 AC-3). A draw moved under another parent still re-arms.
187
+ */
188
+ export function markEngineStatic(root: Object3D): number {
189
+ return freezeRoot(root, true);
190
+ }
191
+
192
+ function freezeRoot(root: Object3D, engine: boolean): number {
154
193
  const existing = frozen.get(root);
194
+ // A second mark re-arms: thaw first, or `freeze`'s update skips the root's own world compose (the
195
+ // first freeze turned it off) and the subtree keeps the world matrix of its first parent.
196
+ if (existing !== undefined) thaw(root);
197
+ const objects = freeze(root);
155
198
  const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH);
156
199
  writeSnapshot(root, snapshot);
157
200
  const version = (existing?.version ?? 0) + 1;
158
- frozen.set(root, { objects, root, snapshot, version });
201
+ frozen.set(
202
+ root,
203
+ engine
204
+ ? { objects, root, snapshot, version, parent: root.parent, fresh: true }
205
+ : { objects, root, snapshot, version },
206
+ );
159
207
  return version;
160
208
  }
161
209
 
@@ -186,17 +234,8 @@ export function unmarkStatic(root: Object3D): void {
186
234
  export function invalidateStatic(object: Object3D): number | undefined {
187
235
  let node: Object3D | null = object;
188
236
  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
- }
237
+ // `markStatic` thaws a frozen root before it freezes it again.
238
+ if (frozen.has(node)) return markStatic(node);
200
239
  node = node.parent;
201
240
  }
202
241
  return undefined;
@@ -242,18 +281,53 @@ let rearmedSinceCensus = 0;
242
281
  */
243
282
  export function refreshStaticTransforms(): void {
244
283
  if (frozen.size === 0) return;
284
+ parentMovedThisFrame.clear();
245
285
  for (const entry of frozen.values()) {
246
- 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
- markStatic(entry.root);
286
+ const engine = entry.parent !== undefined;
287
+ if (engine) {
288
+ const parent = entry.root.parent;
289
+ // Read even for a fresh root, so the parent's matrix is on record before the next frame.
290
+ const moved = parentMoved(parent);
291
+ if (parent === entry.parent && entry.fresh !== true && !moved) continue;
292
+ entry.fresh = false;
293
+ // A draw frozen before it joined its parent, at the pose that parent still has, stays frozen
294
+ // and is watched under the parent it has now.
295
+ if (snapshotMatches(entry.root, entry.snapshot, scratch)) {
296
+ entry.parent = parent;
297
+ continue;
298
+ }
299
+ } else if (snapshotMatches(entry.root, entry.snapshot, scratch)) continue;
300
+ freezeRoot(entry.root, engine);
253
301
  rearmedSinceCensus += 1;
254
302
  }
255
303
  }
256
304
 
305
+ /** Each watched parent's world matrix as the previous refresh read it. */
306
+ const parentSeen = new WeakMap<Object3D, Float64Array>();
307
+ /** This refresh's answer per parent, so a parent shared by a thousand draws is read once. */
308
+ const parentMovedThisFrame = new Map<Object3D, boolean>();
309
+
310
+ /** Whether `parent`'s world matrix changed since the previous refresh read it; null never moves. */
311
+ function parentMoved(parent: Object3D | null): boolean {
312
+ if (parent === null) return false;
313
+ const answered = parentMovedThisFrame.get(parent);
314
+ if (answered !== undefined) return answered;
315
+ const elements = parent.matrixWorld.elements;
316
+ let seen = parentSeen.get(parent);
317
+ let moved = seen === undefined;
318
+ if (seen === undefined) {
319
+ seen = new Float64Array(16);
320
+ parentSeen.set(parent, seen);
321
+ }
322
+ for (let element = 0; element < 16; element += 1) {
323
+ const value = elements[element] ?? 0;
324
+ if (seen[element] !== value) moved = true;
325
+ seen[element] = value;
326
+ }
327
+ parentMovedThisFrame.set(parent, moved);
328
+ return moved;
329
+ }
330
+
257
331
  /** The census, and the re-arm counter it resets. */
258
332
  export function staticTransformCensus(): IStaticTransformCensus {
259
333
  let objects = 0;
@@ -270,5 +344,6 @@ export function staticTransformCensus(): IStaticTransformCensus {
270
344
  /** Drops every registration. A game that tore down its scene must not keep its roots alive. */
271
345
  export function resetStaticTransforms(): void {
272
346
  frozen.clear();
347
+ parentMovedThisFrame.clear();
273
348
  rearmedSinceCensus = 0;
274
349
  }
@@ -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()) {