@threenative/core 0.3.12 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +746 -32
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-4SRAQFTU.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-DIPIJICH.js} +1590 -375
  7. package/dist/{chunk-OKXUCASC.js → chunk-EEABDLUC.js} +3 -4
  8. package/dist/{chunk-5O73CDMR.js → chunk-EFWZWLPY.js} +62 -16
  9. package/dist/{chunk-N5LRP4BR.js → chunk-GYUZJQ7U.js} +63 -3
  10. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  11. package/dist/{chunk-2Z44XSI2.js → chunk-SV4QVUTQ.js} +3 -7
  12. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  13. package/dist/chunk-VP43GIWW.js +18 -0
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +289 -1034
  20. package/dist/index.js +3096 -1305
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BYqKGAwo.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +269 -15
  33. package/dist/world.js +1372 -628
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +105 -7
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/src/animation-batch.ts +193 -0
  39. package/src/animation-layers.ts +7 -3
  40. package/src/animation.ts +209 -29
  41. package/src/asset-cache.ts +3 -3
  42. package/src/asset-memo.ts +202 -0
  43. package/src/assets.ts +436 -131
  44. package/src/auto-batch.ts +190 -44
  45. package/src/compute-driven.ts +1 -1
  46. package/src/config.ts +8 -0
  47. package/src/debug.ts +103 -22
  48. package/src/dev-global.ts +54 -0
  49. package/src/engine-hooks.ts +37 -0
  50. package/src/frame-budget.ts +19 -3
  51. package/src/game-boot-phase.ts +269 -0
  52. package/src/game-dev-tools.ts +7 -14
  53. package/src/game-frame-loop.ts +45 -82
  54. package/src/game-startup.ts +145 -70
  55. package/src/game-ui.ts +84 -0
  56. package/src/game.ts +168 -552
  57. package/src/gamepad-mappings.ts +269 -0
  58. package/src/generated/console-markers.ts +13 -0
  59. package/src/geometry-capture.ts +28 -4
  60. package/src/gpu-readings.ts +98 -0
  61. package/src/gpu-scene-bvh.ts +149 -36
  62. package/src/hot.ts +4 -7
  63. package/src/index.ts +115 -8
  64. package/src/input.ts +237 -25
  65. package/src/instanced-batch-lod.ts +3 -8
  66. package/src/interpolation.ts +171 -40
  67. package/src/look/ao-admission.ts +4 -3
  68. package/src/look/auto-exposure.ts +5 -16
  69. package/src/look/default-tone-mapping.ts +41 -5
  70. package/src/look/local-exposure.ts +2 -7
  71. package/src/look/quad-pass.ts +21 -0
  72. package/src/look/quality.ts +4 -0
  73. package/src/look/unreal-bloom.ts +4 -13
  74. package/src/look/world-environment.ts +58 -115
  75. package/src/merge-parts.ts +20 -24
  76. package/src/model-lod.ts +97 -14
  77. package/src/particle-significance.ts +12 -0
  78. package/src/particles.ts +19 -10
  79. package/src/platform.ts +23 -4
  80. package/src/profiling/FrameStages.ts +5 -6
  81. package/src/profiling/Spans.ts +3 -17
  82. package/src/profiling/debug-telemetry.ts +2 -6
  83. package/src/profiling/render-list-validate.ts +6 -15
  84. package/src/projection-marker.ts +2 -1
  85. package/src/quiet-markers.ts +3 -10
  86. package/src/render/cpu-bvh.ts +100 -0
  87. package/src/render/depth-pyramid.ts +6 -14
  88. package/src/render/environment/environmentContribution.ts +202 -0
  89. package/src/render/environment/environmentRadiance.ts +44 -0
  90. package/src/render/environment/environmentSampleCache.ts +56 -0
  91. package/src/render/environment/environmentSampling.ts +201 -0
  92. package/src/render/environment/environmentSnapshot.ts +71 -0
  93. package/src/render/environment/gate.ts +57 -0
  94. package/src/render/mesh-pool.ts +3 -19
  95. package/src/render/probe-trace.ts +872 -0
  96. package/src/render/probe-volume.ts +780 -34
  97. package/src/render/radiance-cache.ts +17 -0
  98. package/src/render/virtual-shadow-partial.ts +13 -0
  99. package/src/render/virtual-shadow.ts +18 -16
  100. package/src/render/world-impostor-surface.ts +109 -6
  101. package/src/render/world-impostor.ts +5 -2
  102. package/src/render-camera-cull.ts +98 -3
  103. package/src/render-environment.ts +41 -0
  104. package/src/renderer-config.ts +36 -0
  105. package/src/renderer-facts.ts +37 -0
  106. package/src/renderer.ts +52 -28
  107. package/src/resolution-scaler.ts +3 -2
  108. package/src/scene-entry-inspectors.ts +61 -0
  109. package/src/snow-field.ts +1 -0
  110. package/src/startup-offscreen-bytes.ts +78 -0
  111. package/src/static-transform.ts +25 -19
  112. package/src/streamed-textures.ts +112 -0
  113. package/src/streaming.ts +68 -4
  114. package/src/texture-streaming.ts +331 -0
  115. package/src/version.ts +1 -1
  116. package/src/worker.ts +12 -2
  117. package/src/world-bundle-safety.ts +55 -10
  118. package/src/world-cell-batches.ts +162 -200
  119. package/src/world-cell-chunks.ts +3 -7
  120. package/src/world-cell-impostors.ts +20 -8
  121. package/src/world-cell-options.ts +2 -14
  122. package/src/world-cell-placements.ts +194 -90
  123. package/src/world-cell-prewarm.ts +39 -4
  124. package/src/world-cell-records.ts +401 -0
  125. package/src/world-cell-render-bundles.ts +2 -2
  126. package/src/world-cell-render-gpu-dress.ts +13 -17
  127. package/src/world-cell-render-main-cull.ts +73 -17
  128. package/src/world-cell-render-util.ts +17 -4
  129. package/src/world-cell-render.ts +13 -5
  130. package/src/world-cell-residency.ts +15 -6
  131. package/src/world-cell-stale.ts +238 -0
  132. package/src/world-cells.ts +22 -5
  133. package/src/world-gpu-flags.ts +18 -50
  134. package/src/world-gpu-reference.ts +22 -8
  135. package/src/world-gpu-scene.ts +44 -24
  136. package/src/world-gpu-shadow.ts +21 -8
  137. package/src/world-gpu-types.ts +41 -13
  138. package/src/world-load-limiter.ts +5 -0
  139. package/src/world-model-sections.ts +80 -0
  140. package/src/world-river-ribbon.ts +282 -0
  141. package/src/world-root-frame.ts +39 -0
  142. package/src/world-shore-field.ts +91 -0
  143. package/src/world-static-pose.ts +163 -0
  144. package/src/world-surface-sampler.ts +48 -0
  145. package/src/world-terrain-splat.ts +10 -18
  146. package/src/world-tile-budget.ts +4 -11
  147. package/src/world-tiles.ts +79 -12
  148. package/src/world-validate.ts +6 -14
  149. package/src/world-warm.ts +51 -0
  150. package/src/world.ts +13 -0
package/src/animation.ts CHANGED
@@ -13,6 +13,13 @@ import {
13
13
  Vector3,
14
14
  type VectorKeyframeTrack,
15
15
  } from "three";
16
+ import {
17
+ type IAnimationTickResult,
18
+ type IAnimationTickRig,
19
+ animationTickExecutor,
20
+ flushAnimationTicks,
21
+ queueAnimationTick,
22
+ } from "./animation-batch.js";
16
23
  import {
17
24
  type IAnimationPacketState,
18
25
  animationPacketField,
@@ -22,10 +29,11 @@ import {
22
29
  animationPacketTimeReaders,
23
30
  } from "./animation-packet-state.js";
24
31
  import { clipTrackBindings } from "./clip-audit.js";
32
+ import { copyMatrixWorld } from "./engine-hooks.js";
25
33
  import {
26
34
  type IAnimationRateState,
27
- animationRateStates,
28
35
  trackAnimationRate,
36
+ untrackAnimationRate,
29
37
  } from "./render-camera-cull.js";
30
38
  import { type ISharedStride, type RigPreparation, uniformYawScale } from "./rig-preparation.js";
31
39
 
@@ -260,13 +268,9 @@ function worldOf(object: Object3D | null, target: Float64Array): void {
260
268
  target.set(IDENTITY);
261
269
  return;
262
270
  }
263
- const source = object as Object3D & { __tnCopyMatrixWorld?: (target: Matrix4) => void };
264
271
  // The frame's updateMatrixWorld already holds every bone; getWorldPosition re-walks ancestors.
265
- if (source.__tnCopyMatrixWorld === undefined) target.set(object.matrixWorld.elements);
266
- else {
267
- source.__tnCopyMatrixWorld(scratchMatrixWorld);
268
- target.set(scratchMatrixWorld.elements);
269
- }
272
+ if (copyMatrixWorld(object, scratchMatrixWorld)) target.set(scratchMatrixWorld.elements);
273
+ else target.set(object.matrixWorld.elements);
270
274
  }
271
275
 
272
276
  const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
@@ -641,7 +645,29 @@ export class AnimationPlayer {
641
645
  * and the next evaluation measures the whole interval, so a held rig pays no world-matrix walk.
642
646
  */
643
647
  #strideReportOnlyFor: string | undefined;
644
- #strideDtDebt = 0;
648
+ /**
649
+ * PRD-828: the tick this player handed to the engine's batch, and what the JS loop was in the middle
650
+ * of when it did. The batch is a whole frame's rigs in one crossing, so each field is one rig's worth.
651
+ */
652
+ #batchQueued = false;
653
+ #batchName: string | undefined;
654
+ #batchStep = false;
655
+ #batchStrideSync = true;
656
+ #batchLocomotion = false;
657
+ /** The player ran ticks the engine did not since its last batched one: its banked advance is spent. */
658
+ #batchReset = true;
659
+ /** The queued tick measured the ground: a hand-back tick never does, and its status is not a reading. */
660
+ #batchMeasured = false;
661
+ /**
662
+ * The engine holds held-tick time for this rig that JS has not handed back or spent. It cannot be
663
+ * spent twice — `#evaluate` sets `#batchReset`, so the engine drops any bank a JS advance has already
664
+ * covered — but dropping it loses the interval, so it is handed back instead.
665
+ */
666
+ #engineBank = false;
667
+ /** Seconds the engine has not measured the body over: its last position is that much out of date. */
668
+ #batchGapDt = 0;
669
+ /** Seconds the JS loop has not measured the body over: its last position is that much out of date. */
670
+ #jsGapDt = 0;
645
671
  // The last update's numbers, kept as scalars so a frame that never reads `.stride` builds no
646
672
  // report. A read materializes a fresh snapshot, so a retained report never changes under it.
647
673
  #strideGroundSpeed = 0;
@@ -782,14 +808,24 @@ export class AnimationPlayer {
782
808
  }
783
809
 
784
810
  get advancedFrames(): number {
811
+ this.#settle();
785
812
  return this.#advancedFrames;
786
813
  }
787
814
 
788
815
  /** True when a `"once"` clip has reached its end and is holding. */
789
816
  get finished(): boolean {
817
+ this.#settle();
790
818
  return this.#finished;
791
819
  }
792
820
 
821
+ /**
822
+ * Runs a tick this player queued and the frame loop has not reached yet, so a reader never sees the
823
+ * pose, the stride or the counters from before the last `update`.
824
+ */
825
+ #settle(): void {
826
+ if (this.#batchQueued) flushAnimationTicks();
827
+ }
828
+
793
829
  /**
794
830
  * What the feet are doing against what the body is doing, as of the last `update`.
795
831
  *
@@ -798,6 +834,7 @@ export class AnimationPlayer {
798
834
  * be honest about what it turned off.
799
835
  */
800
836
  get stride(): IStrideReport {
837
+ this.#settle();
801
838
  const name = this.#current;
802
839
  const measured = name === undefined ? undefined : this.#measureOf(name);
803
840
  // A fresh snapshot each read: what the last update stored, with the clip's own ground speed
@@ -882,15 +919,10 @@ export class AnimationPlayer {
882
919
 
883
920
  #uniformWorldScale(): number | undefined {
884
921
  const root = this.mixer.getRoot() as Object3D;
885
- const owner = (root.parent ?? root) as Object3D & {
886
- __tnCopyMatrixWorld?: (target: Matrix4) => void;
887
- };
922
+ const owner = (root.parent ?? root) as Object3D;
888
923
  owner.updateWorldMatrix(true, false);
889
- if (owner.__tnCopyMatrixWorld !== undefined) {
890
- // Native copies into owned storage so this read cannot escape the live transform alias.
891
- owner.__tnCopyMatrixWorld(scratchMatrixWorld);
892
- return uniformYawScale(scratchMatrixWorld);
893
- }
924
+ // Native copies into owned storage so this read cannot escape the live transform alias.
925
+ if (copyMatrixWorld(owner, scratchMatrixWorld)) return uniformYawScale(scratchMatrixWorld);
894
926
  return uniformYawScale(owner.matrixWorld);
895
927
  }
896
928
 
@@ -1093,6 +1125,7 @@ export class AnimationPlayer {
1093
1125
  }
1094
1126
 
1095
1127
  #start(name: string, options: IAnimationPlayOptions): void {
1128
+ this.#settle();
1096
1129
  const speed = options.speed ?? 1;
1097
1130
  if (!(Number.isFinite(speed) && speed > 0))
1098
1131
  throw new Error(`Animation play speed must be a positive finite number, got ${speed}.`);
@@ -1145,6 +1178,7 @@ export class AnimationPlayer {
1145
1178
  entries: readonly { readonly clip: string; readonly weight: number }[],
1146
1179
  options: { readonly transition?: number; readonly phaseSync?: boolean } = {},
1147
1180
  ): void {
1181
+ this.#settle();
1148
1182
  const transition = options.transition ?? 0;
1149
1183
  if (!Number.isFinite(transition) || transition < 0)
1150
1184
  throw new Error("AnimationPlayer.playWeighted requires a finite non-negative transition.");
@@ -1272,6 +1306,7 @@ export class AnimationPlayer {
1272
1306
  update(dt: number, force = false): void {
1273
1307
  if (!Number.isFinite(dt) || dt < 0)
1274
1308
  throw new Error("AnimationPlayer.update requires a finite non-negative dt.");
1309
+ if (this.#batchQueued) flushAnimationTicks();
1275
1310
  const mixerScale = this.mixer.timeScale;
1276
1311
  if (mixerScale !== 1) this.#flushPending();
1277
1312
  const elapsed = dt * mixerScale;
@@ -1285,22 +1320,28 @@ export class AnimationPlayer {
1285
1320
  force ||
1286
1321
  (this.#updateFrame + this.#staggerOffset) % boneRate === 0 ||
1287
1322
  this.#skippedFrames >= boneRate;
1323
+ // The batch decides before the JS bank does: a tick it takes must not also be banked per action,
1324
+ // or the two paths would each other's time.
1325
+ const heldBefore = this.#pendingDt;
1326
+ if (this.#queueTick(dt, elapsed, mixerScale)) {
1327
+ // The engine banked this tick; JS holds none of it, and measured nothing, so its last position
1328
+ // goes stale by one interval.
1329
+ if (!this.#batchStep) this.#engineBank = true;
1330
+ this.#jsGapDt += dt;
1331
+ return;
1332
+ }
1333
+ this.#pendingDt += elapsed;
1288
1334
  // A full-rate tick with no held time advances through the mixer's own actions; only deferred
1289
1335
  // integration needs per-action elapsed time. Scanning the whole clip library to bank that time
1290
1336
  // costs every full-rate rig every frame.
1291
- if (
1292
- !this.#evaluated ||
1293
- this.#pendingDt !== 0 ||
1294
- this.#pendingActionTimes.size !== 0 ||
1295
- rate !== 1
1296
- ) {
1337
+ if (!this.#evaluated || heldBefore !== 0 || this.#pendingActionTimes.size !== 0 || rate !== 1) {
1297
1338
  for (const action of this.#actions.values()) {
1298
1339
  if (!action.isScheduled()) continue;
1299
1340
  const time = action.paused ? 0 : action.timeScale * elapsed;
1300
1341
  this.#pendingActionTimes.set(action, (this.#pendingActionTimes.get(action) ?? 0) + time);
1301
1342
  }
1302
1343
  }
1303
- this.#pendingDt += elapsed;
1344
+ this.#batchGapDt += dt;
1304
1345
  if (this.#evaluated) this.#evaluate(dt, mixerScale);
1305
1346
  // Measure the body's movement on every tick, including skipped pose evaluations. A held tick of
1306
1347
  // a clip whose measurement only reports banks its dt: the average speed over the interval is
@@ -1312,22 +1353,150 @@ export class AnimationPlayer {
1312
1353
  this.#blendTargets === undefined &&
1313
1354
  dt > 0
1314
1355
  ) {
1315
- this.#strideDtDebt += dt;
1356
+ this.#jsGapDt += dt;
1316
1357
  return;
1317
1358
  }
1318
1359
  if (dt > 0) {
1319
- const interval = dt + this.#strideDtDebt;
1320
- this.#strideDtDebt = 0;
1360
+ const interval = dt + this.#jsGapDt;
1361
+ this.#jsGapDt = 0;
1321
1362
  this.#syncStride(interval);
1322
1363
  } else this.#syncStride(dt);
1323
1364
  }
1324
1365
 
1366
+ /**
1367
+ * Hand this tick to the engine's batch, or answer false and let the JS loop run it.
1368
+ *
1369
+ * The batch runs the same three rules over a span of rigs — the weight ramp, the stride rate and the
1370
+ * mixer step — so it takes only a tick whose shape it can express exactly: one contributing clip, no
1371
+ * fade, no blend, no warp, no held pause. Everything else keeps the JS loop, which is not a fallback
1372
+ * mode but the general path; this is the one shape the stress lab's crowd is made of.
1373
+ */
1374
+ #queueTick(dt: number, elapsed: number, mixerScale: number): boolean {
1375
+ if (mixerScale !== 1 || dt <= 0) return false;
1376
+ const name = this.#current;
1377
+ const action = name === undefined ? undefined : this.#actions.get(name);
1378
+ if (name === undefined || action === undefined) return false;
1379
+ if (this.#mode !== "loop" || this.#finished) return false;
1380
+ if (this.#fadeOut.length !== 0 || this.#blendTargets !== undefined) return false;
1381
+ if (this.#timeScaleInterpolations.size !== 0) return false;
1382
+ if (this.#evaluationScales.size !== 0 || this.#evaluationPaused.size !== 0) return false;
1383
+ if (action.paused) return false;
1384
+ // Deferred per-action time is integrated below in JS; the batch takes the frame's own interval.
1385
+ if (this.#pendingActionTimes.size !== 0) return false;
1386
+ if (this.mixer instanceof LoopAwareAnimationMixer && this.mixer.hasPublicListeners)
1387
+ return false;
1388
+ if (animationTickExecutor() === undefined) return false;
1389
+ this.#queueRig(name, action, dt, elapsed, this.#evaluated);
1390
+ return true;
1391
+ }
1392
+
1393
+ /**
1394
+ * One rig's descriptor, in the shape `tn_anim_tick` takes. The held bank is the engine's, not ours.
1395
+ *
1396
+ * `strideRoot` is null for a tick that only has to spend the engine's bank: handing the body over would
1397
+ * move the engine's last measured position without measuring the interval it belongs to.
1398
+ */
1399
+ #queueRig(
1400
+ name: string,
1401
+ action: AnimationAction,
1402
+ dt: number,
1403
+ elapsed: number,
1404
+ step: boolean,
1405
+ strideRoot: object | null = this.#strideRoot,
1406
+ ): void {
1407
+ const measured = this.#measureOf(name);
1408
+ this.#cameraCarried = cameraCarried(this.#strideRoot);
1409
+ this.#batchName = name;
1410
+ this.#batchStep = step;
1411
+ this.#batchMeasured = dt > 0;
1412
+ this.#batchStrideSync = this.#strideSync ?? !this.#cameraCarried;
1413
+ this.#batchLocomotion = measured.groundSpeed >= CLIP_GROUND_FLOOR;
1414
+ const rig: IAnimationTickRig = {
1415
+ mixer: this.mixer,
1416
+ action,
1417
+ strideRoot,
1418
+ // The interval the ground is measured over: this tick, plus the time the engine stopped measuring
1419
+ // while the JS loop had the rig, so a switch never divides a stale displacement by one frame's dt.
1420
+ dt: dt + this.#batchGapDt,
1421
+ elapsed,
1422
+ step,
1423
+ reset: this.#batchReset,
1424
+ // The engine must not take back a scale the game chose: 0 says the action's scale is not ours.
1425
+ lastRate: this.#strideSynced ? this.#strideRate : 0,
1426
+ clipGroundSpeed: measured.groundSpeed,
1427
+ strideSync: this.#batchStrideSync,
1428
+ };
1429
+ queueAnimationTick(rig, this.#applyTick);
1430
+ this.#batchQueued = true;
1431
+ }
1432
+
1433
+ /**
1434
+ * The engine holds time this rig banked on held ticks it posed nothing for. Before the JS loop spends
1435
+ * any time of its own, hand that bank back as one step: the engine integrates it at the exact rates it
1436
+ * ran under, and JS then advances only the time it banked itself. Without this, a `warp()`, a slow-mo
1437
+ * frame, a `syncBones` or a clip change would advance the held interval twice.
1438
+ */
1439
+ #handBackToEngine(): void {
1440
+ if (!this.#engineBank) return;
1441
+ this.#engineBank = false;
1442
+ const name = this.#current;
1443
+ const action = name === undefined ? undefined : this.#actions.get(name);
1444
+ if (name === undefined || action === undefined) return;
1445
+ if (animationTickExecutor() === undefined) return;
1446
+ this.#queueRig(name, action, 0, 0, true, null);
1447
+ flushAnimationTicks();
1448
+ }
1449
+
1450
+ /** The stride scalars `#syncStride` would have written for this clip, from the tick's own answer. */
1451
+ #batchStrideReport(name: string | undefined): void {
1452
+ if (this.#batchLocomotion) {
1453
+ this.#strideSynced = this.#batchStrideSync;
1454
+ this.#strideOverridden = !this.#batchStrideSync;
1455
+ this.#strideReportOnlyFor = this.#batchStrideSync ? undefined : name;
1456
+ return;
1457
+ }
1458
+ // Not locomotion: authored at its own rate. The report says so, and reports the ground it covered.
1459
+ this.#strideSynced = false;
1460
+ this.#strideOverridden = false;
1461
+ this.#strideReportOnlyFor = name;
1462
+ }
1463
+
1464
+ /**
1465
+ * A batched tick came back. Writes the same numbers the JS loop would have, from the same rules:
1466
+ * the stride scalars the report and `#effectiveUpdateRate` read, the advance counters, and `finished`.
1467
+ */
1468
+ readonly #applyTick = (result: IAnimationTickResult): void => {
1469
+ const name = this.#batchName;
1470
+ this.#batchQueued = false;
1471
+ this.#batchName = undefined;
1472
+ this.#batchReset = false;
1473
+ this.#batchGapDt = 0;
1474
+ // A tick that only spent the engine's bank measured nothing: its status is not a stride reading.
1475
+ if (this.#batchMeasured) {
1476
+ this.#strideGroundSpeed = result.groundSpeed;
1477
+ this.#strideRate = result.strideRate;
1478
+ this.#strideInPlace = name === undefined ? false : this.#measureOf(name).inPlace;
1479
+ this.#batchStrideReport(name);
1480
+ }
1481
+ if (this.#batchStep) {
1482
+ this.#batchStep = false;
1483
+ this.#engineBank = false;
1484
+ if (result.changed) this.#advancedFrames += 1;
1485
+ this.#pendingDt = 0;
1486
+ this.#skippedFrames = 0;
1487
+ this.#rateState.evaluation += 1;
1488
+ this.#rateState.evaluated = true;
1489
+ }
1490
+ if (result.finished) this.#finished = true;
1491
+ };
1492
+
1325
1493
  /**
1326
1494
  * The playhead a trusted packet reads, as a bare number: the same checks as the trusted branch
1327
1495
  * of `#readPacketState` without building a state object. Undefined sends the caller to the full
1328
1496
  * read, which also renews the trust.
1329
1497
  */
1330
1498
  #trustedPacketTime(): number | undefined {
1499
+ this.#settle();
1331
1500
  const trust = this.#packetTrust;
1332
1501
  if (
1333
1502
  trust === undefined ||
@@ -1353,6 +1522,7 @@ export class AnimationPlayer {
1353
1522
  }
1354
1523
 
1355
1524
  #readPacketState(): IAnimationPacketState | undefined {
1525
+ this.#settle();
1356
1526
  if (
1357
1527
  this.#evaluating ||
1358
1528
  this.#actions.size !== 1 ||
@@ -1444,10 +1614,14 @@ export class AnimationPlayer {
1444
1614
  }
1445
1615
 
1446
1616
  #flushPending(): void {
1617
+ // A tick may be queued with time this would spend a second time: settle it first, always.
1618
+ this.#settle();
1447
1619
  if (this.#pendingDt !== 0) this.#evaluate(this.#pendingDt);
1448
1620
  }
1449
1621
 
1450
1622
  #evaluate(dt: number, mixerScale = this.mixer.timeScale): void {
1623
+ this.#handBackToEngine();
1624
+ this.#batchReset = true;
1451
1625
  // Read before mixer.update(): the "finished" listener fires inside it for a completing
1452
1626
  // once-clip, and that final frame still counts as advancement.
1453
1627
  const wasFinished = this.#finished;
@@ -1535,6 +1709,8 @@ export class AnimationPlayer {
1535
1709
  }
1536
1710
 
1537
1711
  stop(): void {
1712
+ this.#settle();
1713
+ this.#engineBank = false;
1538
1714
  this.#pendingDt = 0;
1539
1715
  this.#pendingActionTimes.clear();
1540
1716
  this.#skippedFrames = 0;
@@ -1557,7 +1733,10 @@ export class AnimationPlayer {
1557
1733
  #resetStride(): void {
1558
1734
  this.#hasLastRootPosition = false;
1559
1735
  this.#strideReportOnlyFor = undefined;
1560
- this.#strideDtDebt = 0;
1736
+ this.#batchGapDt = 0;
1737
+ this.#jsGapDt = 0;
1738
+ this.#batchReset = true;
1739
+ this.#engineBank = false;
1561
1740
  this.#strideGroundSpeed = 0;
1562
1741
  this.#strideRate = 1;
1563
1742
  this.#strideSynced = false;
@@ -1567,6 +1746,8 @@ export class AnimationPlayer {
1567
1746
 
1568
1747
  dispose(): void {
1569
1748
  this.stop();
1749
+ this.#batchQueued = false;
1750
+ this.#batchName = undefined;
1570
1751
  this.mixer.uncacheRoot(this.mixer.getRoot());
1571
1752
  this.mixer.removeEventListener("finished", this.#onFinished);
1572
1753
  this.#actions.clear();
@@ -1577,8 +1758,7 @@ export class AnimationPlayer {
1577
1758
  animationPacketReaders.delete(this.root);
1578
1759
  if (animationPacketTimeReaders.get(this.root) === this.#packetTimeReader)
1579
1760
  animationPacketTimeReaders.delete(this.root);
1580
- if (animationRateStates.get(this.root) === this.#rateState)
1581
- animationRateStates.delete(this.root);
1761
+ untrackAnimationRate(this.root, this.#rateState);
1582
1762
  if (this.root.userData[ANIMATION_RATE_STATE_KEY] === this.#rateState)
1583
1763
  delete this.root.userData[ANIMATION_RATE_STATE_KEY];
1584
1764
  }
@@ -73,13 +73,13 @@ const ACCESS_REFRESH_MS = 3_600_000;
73
73
  /** Lower is more urgent. */
74
74
  export const PRIORITY_ORDER: Record<AssetPriority, number> = { now: 0, soon: 1, idle: 2 };
75
75
 
76
- type CacheStorageLike = {
76
+ export type CacheStorageLike = {
77
77
  delete(name: string): Promise<boolean>;
78
78
  keys(): Promise<readonly string[]>;
79
79
  open(name: string): Promise<CacheLike>;
80
80
  };
81
81
 
82
- type CacheLike = {
82
+ export type CacheLike = {
83
83
  delete(request: string): Promise<boolean>;
84
84
  keys(): Promise<readonly Request[]>;
85
85
  match(request: string): Promise<Response | undefined>;
@@ -94,7 +94,7 @@ interface IJob {
94
94
  priority: AssetPriority;
95
95
  }
96
96
 
97
- function cacheStorage(): CacheStorageLike | undefined {
97
+ export function cacheStorage(): CacheStorageLike | undefined {
98
98
  return (globalThis as { caches?: CacheStorageLike }).caches;
99
99
  }
100
100
 
@@ -0,0 +1,202 @@
1
+ import { type CacheLike, cacheStorage, manifestFingerprint } from "./asset-cache.js";
2
+ import { isNative } from "./platform.js";
3
+
4
+ /**
5
+ * Generated content kept between runs (PRD-860): `ctx.assets.memo(key, build)` returns what `build`
6
+ * returned the last time this exact build of the game ran, read back from disk, and calls `build`
7
+ * only when nothing is stored. A seeded world, a painted sky or a baked placement list is the same
8
+ * every run of one build, so a repeat visit stops paying for it.
9
+ *
10
+ * The value is named typed arrays, the shape a generator hands to geometry, instancing and
11
+ * textures. The build identity is the hashed entry script the web build writes into the page
12
+ * (`__TN_BUILD_ID__`), so any code change regenerates and the old build's entries are deleted. With
13
+ * no build identity (the dev server) or no Cache API (a native host), `build` runs every time and
14
+ * `TN_ASSET_MEMO` says why.
15
+ */
16
+ export type MemoArray =
17
+ | Float32Array
18
+ | Float64Array
19
+ | Int8Array
20
+ | Int16Array
21
+ | Int32Array
22
+ | Uint8Array
23
+ | Uint8ClampedArray
24
+ | Uint16Array
25
+ | Uint32Array;
26
+
27
+ export type MemoArrays = Readonly<Record<string, MemoArray>>;
28
+ /** Every field a typed array: a record or an interface, which has no index signature. */
29
+ export type MemoShape<T> = { readonly [K in keyof T]: MemoArray };
30
+
31
+ export type AssetMemo = <T extends MemoShape<T>>(
32
+ key: string,
33
+ build: () => T | Promise<T>,
34
+ ) => Promise<T>;
35
+
36
+ const KINDS = {
37
+ Float32Array,
38
+ Float64Array,
39
+ Int16Array,
40
+ Int32Array,
41
+ Int8Array,
42
+ Uint16Array,
43
+ Uint32Array,
44
+ Uint8Array,
45
+ Uint8ClampedArray,
46
+ } as const;
47
+ type Kind = keyof typeof KINDS;
48
+
49
+ const BUILD_ID_GLOBAL = "__TN_BUILD_ID__";
50
+ const MEMO_CACHE = "threenative-memo";
51
+ /** A host no request ever reaches: the Cache API only needs an absolute url to key on. */
52
+ const MEMO_ORIGIN = "https://memo.threenative.invalid/";
53
+ const MAGIC = 0x4f4d4e54; // "TNMO"
54
+
55
+ function invalid(detail: string): Error {
56
+ return new Error(`TN_ASSET_MEMO_INVALID: ${detail}`);
57
+ }
58
+
59
+ function kindOf(value: unknown): Kind | undefined {
60
+ for (const kind of Object.keys(KINDS) as Kind[]) if (value instanceof KINDS[kind]) return kind;
61
+ return undefined;
62
+ }
63
+
64
+ /** Header (magic, JSON length, JSON) then each array's bytes at an 8-byte boundary. */
65
+ export function encodeMemo(value: MemoArrays): ArrayBuffer {
66
+ const entries = Object.entries(value).map(([name, array]) => {
67
+ const kind = kindOf(array);
68
+ if (kind === undefined) throw invalid(`"${name}" is not a typed array.`);
69
+ return { array, kind, name };
70
+ });
71
+ const align = (n: number): number => Math.ceil(n / 8) * 8;
72
+ const header = new TextEncoder().encode(
73
+ JSON.stringify(entries.map(({ array, kind, name }) => ({ kind, length: array.length, name }))),
74
+ );
75
+ let offset = align(8 + header.byteLength);
76
+ const placed = entries.map((entry) => {
77
+ const at = offset;
78
+ offset = align(at + entry.array.byteLength);
79
+ return { ...entry, at };
80
+ });
81
+ const buffer = new ArrayBuffer(offset);
82
+ const view = new DataView(buffer);
83
+ view.setUint32(0, MAGIC, true);
84
+ view.setUint32(4, header.byteLength, true);
85
+ new Uint8Array(buffer, 8, header.byteLength).set(header);
86
+ for (const { array, at } of placed)
87
+ new Uint8Array(buffer, at, array.byteLength).set(
88
+ new Uint8Array(array.buffer, array.byteOffset, array.byteLength),
89
+ );
90
+ return buffer;
91
+ }
92
+
93
+ /** The inverse of `encodeMemo`; throws on anything it did not write. */
94
+ export function decodeMemo(buffer: ArrayBuffer): Record<string, MemoArray> {
95
+ const view = new DataView(buffer);
96
+ if (buffer.byteLength < 8 || view.getUint32(0, true) !== MAGIC)
97
+ throw invalid("stored entry is not a memo.");
98
+ const headerBytes = view.getUint32(4, true);
99
+ if (8 + headerBytes > buffer.byteLength) throw invalid("stored entry is truncated.");
100
+ const header: unknown = JSON.parse(
101
+ new TextDecoder().decode(new Uint8Array(buffer, 8, headerBytes)),
102
+ );
103
+ if (!Array.isArray(header)) throw invalid("stored entry has no array list.");
104
+ const result: Record<string, MemoArray> = {};
105
+ let offset = Math.ceil((8 + headerBytes) / 8) * 8;
106
+ for (const entry of header as Array<{ kind?: unknown; length?: unknown; name?: unknown }>) {
107
+ const kind = entry.kind as Kind;
108
+ const Ctor = KINDS[kind];
109
+ if (Ctor === undefined || typeof entry.name !== "string" || !Number.isInteger(entry.length))
110
+ throw invalid("stored entry has a malformed array.");
111
+ const length = entry.length as number;
112
+ const bytes = length * Ctor.BYTES_PER_ELEMENT;
113
+ if (offset + bytes > buffer.byteLength) throw invalid("stored entry is truncated.");
114
+ result[entry.name] = new Ctor(buffer, offset, length);
115
+ offset = Math.ceil((offset + bytes) / 8) * 8;
116
+ }
117
+ return result;
118
+ }
119
+
120
+ function report(fields: Record<string, unknown>): void {
121
+ console.info(`TN_ASSET_MEMO:${JSON.stringify(fields)}`);
122
+ }
123
+
124
+ function now(): number {
125
+ return globalThis.performance?.now() ?? Date.now();
126
+ }
127
+
128
+ export function createAssetMemo(namespace: string): AssetMemo {
129
+ const storage = cacheStorage();
130
+ const id = (globalThis as Record<string, unknown>)[BUILD_ID_GLOBAL];
131
+ const buildId = typeof id === "string" && id !== "" ? id : undefined;
132
+ const reason =
133
+ storage === undefined
134
+ ? isNative()
135
+ ? "native host has no Cache API: generated content rebuilds each run"
136
+ : "cache API unavailable: generated content rebuilds each run"
137
+ : buildId === undefined
138
+ ? "no build id (dev server or a page the web build did not write): generated content rebuilds each run"
139
+ : undefined;
140
+ const prefix = buildId === undefined ? "" : `${MEMO_ORIGIN}${encodeURIComponent(buildId)}/`;
141
+ const name = `${MEMO_CACHE}-${manifestFingerprint([{ url: namespace }]).slice(0, 8)}`;
142
+ let opened: Promise<CacheLike | undefined> | undefined;
143
+ /** Opens once, deleting what another build stored, so a cache holds one build's content. */
144
+ const open = (): Promise<CacheLike | undefined> => {
145
+ opened ??= (async () => {
146
+ const cache = await storage?.open(name);
147
+ if (cache === undefined) return undefined;
148
+ for (const request of await cache.keys())
149
+ if (!request.url.startsWith(prefix)) await cache.delete(request.url);
150
+ return cache;
151
+ })().catch(() => undefined);
152
+ return opened;
153
+ };
154
+ const checked = <T extends MemoShape<T>>(key: string, value: T): T => {
155
+ if (typeof value !== "object" || value === null)
156
+ throw invalid(`build for "${key}" returned no object.`);
157
+ for (const [field, array] of Object.entries(value))
158
+ if (kindOf(array) === undefined)
159
+ throw invalid(`build for "${key}" returned "${field}", not a typed array.`);
160
+ return value;
161
+ };
162
+
163
+ return async <T extends MemoShape<T>>(key: string, build: () => T | Promise<T>): Promise<T> => {
164
+ if (typeof key !== "string" || key === "") throw invalid("key must be a non-empty string.");
165
+ const started = now();
166
+ if (reason !== undefined) {
167
+ const value = checked(key, await build());
168
+ report({ key, hit: false, ms: Math.round(now() - started), reason });
169
+ return value;
170
+ }
171
+ const url = `${prefix}${encodeURIComponent(key)}`;
172
+ const cache = await open();
173
+ if (cache !== undefined) {
174
+ try {
175
+ const stored = await cache.match(url);
176
+ if (stored !== undefined) {
177
+ const buffer = await stored.arrayBuffer();
178
+ const value = decodeMemo(buffer) as T;
179
+ report({ bytes: buffer.byteLength, hit: true, key, ms: Math.round(now() - started) });
180
+ return value;
181
+ }
182
+ } catch {
183
+ // A damaged entry is a miss: delete it and build, never fail the load over a cache.
184
+ await cache.delete(url).catch(() => undefined);
185
+ }
186
+ }
187
+ const value = checked(key, await build());
188
+ const encoded = encodeMemo(value as MemoArrays);
189
+ const builtMs = Math.round(now() - started);
190
+ if (cache === undefined) {
191
+ report({ hit: false, key, ms: builtMs, reason: "cache storage refused to open" });
192
+ return value;
193
+ }
194
+ void cache
195
+ .put(url, new Response(encoded))
196
+ .then(() => report({ bytes: encoded.byteLength, hit: false, key, ms: builtMs, stored: true }))
197
+ .catch((error: unknown) =>
198
+ report({ hit: false, key, ms: builtMs, stored: false, reason: String(error) }),
199
+ );
200
+ return value;
201
+ };
202
+ }