@threenative/core 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
package/src/animation.ts CHANGED
@@ -2,6 +2,10 @@ import {
2
2
  type AnimationAction,
3
3
  type AnimationClip,
4
4
  AnimationMixer,
5
+ type AnimationMixerEventMap,
6
+ type Box3,
7
+ type BufferGeometry,
8
+ type EventListener,
5
9
  LoopOnce,
6
10
  LoopRepeat,
7
11
  Matrix4,
@@ -9,7 +13,20 @@ import {
9
13
  Vector3,
10
14
  type VectorKeyframeTrack,
11
15
  } from "three";
16
+ import {
17
+ type IAnimationPacketState,
18
+ animationPacketField,
19
+ animationPacketMethodsPristine,
20
+ animationPacketReaders,
21
+ animationPacketTime,
22
+ animationPacketTimeReaders,
23
+ } from "./animation-packet-state.js";
12
24
  import { clipTrackBindings } from "./clip-audit.js";
25
+ import {
26
+ type IAnimationRateState,
27
+ animationRateStates,
28
+ trackAnimationRate,
29
+ } from "./render-camera-cull.js";
13
30
  import { type ISharedStride, type RigPreparation, uniformYawScale } from "./rig-preparation.js";
14
31
 
15
32
  export interface IAnimationPlayerOptions {
@@ -29,6 +46,10 @@ export interface IAnimationPlayerOptions {
29
46
  * way. Set `false` to keep the authored rate; the measurement below stays live either way and
30
47
  * says that it was overridden. The convention re-times locomotion only: a `"once"` clip — a
31
48
  * death, a flinch — always plays at its authored rate.
49
+ *
50
+ * Left unset, a rig carried by a camera (first-person hands, a held weapon) keeps its authored
51
+ * rate: the camera moves it, and a mouse turn sweeps its root metres a second, which read as
52
+ * stride played the hands at the 3x ceiling. `stride.cameraCarried` reports it; `true` syncs anyway.
32
53
  */
33
54
  readonly strideSync?: boolean;
34
55
  /**
@@ -39,6 +60,27 @@ export interface IAnimationPlayerOptions {
39
60
  * the clip's motion back as if it were the body's.
40
61
  */
41
62
  readonly strideRoot?: Object3D;
63
+ /**
64
+ * Evaluate by measured screen size by default; a positive integer names a frame interval.
65
+ * A stride-synced walk at 32 px or more evaluates every frame.
66
+ * Public mixer listeners/speed overrides stay full-rate; action speed interpolations do until settled.
67
+ */
68
+ readonly updateRate?: "auto" | number;
69
+ /**
70
+ * Let the skinned batch evaluate a held, distant rig's pose on the GPU from keyframes and time.
71
+ * Off by default: each vertex re-evaluates the pose in the main and shadow passes, which cost
72
+ * 2.7 / 10.3 / 13.8 ms of GPU time at 32 / 128 / 256 rigs on Intel gen-12lp (PRD-570). Held rigs
73
+ * otherwise keep their last CPU pose until their next evaluation.
74
+ */
75
+ readonly gpuPose?: boolean;
76
+ }
77
+
78
+ export interface IAnimationUpdateRateReport {
79
+ readonly rate: number;
80
+ readonly overridden: boolean;
81
+ readonly evaluated: boolean;
82
+ /** Frames between CPU bone refreshes: `rate`, or longer while the GPU evaluates the pose. */
83
+ readonly boneRate: number;
42
84
  }
43
85
 
44
86
  /**
@@ -58,6 +100,8 @@ export interface IStrideReport {
58
100
  readonly synced: boolean;
59
101
  /** True when a rate was measured and deliberately not applied. */
60
102
  readonly overridden: boolean;
103
+ /** True when a camera carries the rig, so an unset `strideSync` keeps the authored rate. */
104
+ readonly cameraCarried: boolean;
61
105
  /**
62
106
  * True when the clip carries no root motion and its stride was read off the feet instead.
63
107
  *
@@ -76,12 +120,27 @@ export interface IStrideReport {
76
120
  * clip reads as a cartoon; at zero it freezes mid-stride while the body drifts, which is worse
77
121
  * than a slow cycle. Both ends are a property of the clip set, so both are the game's to move.
78
122
  */
123
+ /** Packet-state reads that reuse the last full validation of the action and mixer internals. */
124
+ const PACKET_REVALIDATE_READS = 256;
125
+ /**
126
+ * While the GPU evaluates a rig's pose, the CPU bones refresh every this many scheduled
127
+ * evaluations. The drawn pose stays exact every frame; only bone readers see the longer interval.
128
+ */
129
+ const GPU_POSE_BONE_REFRESH = 4;
79
130
  const STRIDE_RATE_MIN = 0.15;
80
131
  const STRIDE_RATE_MAX = 3;
81
132
  /** Below this the body is standing, and a measured rate would be noise. */
82
133
  const STRIDE_SPEED_FLOOR = 1e-4;
83
134
  /** A clip carrying less ground than this per second is not locomotion. */
84
135
  const CLIP_GROUND_FLOOR = 1e-3;
136
+
137
+ /** True when `object` is a camera or sits under one: the camera moves it, not its own clip. */
138
+ function cameraCarried(object: Object3D): boolean {
139
+ for (let node: Object3D | null = object; node !== null; node = node.parent) {
140
+ if ((node as { isCamera?: boolean }).isCamera === true) return true;
141
+ }
142
+ return false;
143
+ }
85
144
  /** Poses taken across one cycle when reading an in-place clip's stride off its feet. */
86
145
  const PLANT_SAMPLES = 64;
87
146
  /** A contact bone is one that reaches this near the lowest point the rig visits. */
@@ -119,6 +178,189 @@ function clipRootMotionSpeed(clip: AnimationClip): number {
119
178
  return best;
120
179
  }
121
180
 
181
+ /**
182
+ * The box a mesh's contact point is read from, or undefined for the object's own origin.
183
+ *
184
+ * A procedural boot or sole has its origin wherever the author put the geometry, usually the
185
+ * middle. On a leg that swings from the hip the origin sweeps a smaller circle than the sole does,
186
+ * so reading it reports a stride shorter than the ground the sole covers, and the clip plays too
187
+ * fast. A skinned mesh keeps its bind-pose box under a static matrix, so its bones carry the
188
+ * motion and it stays on the origin path.
189
+ */
190
+ function contactBox(object: Object3D): Box3 | undefined {
191
+ const mesh = object as Object3D & { geometry?: BufferGeometry; isSkinnedMesh?: boolean };
192
+ if (mesh.geometry === undefined || mesh.isSkinnedMesh === true) return undefined;
193
+ if (mesh.geometry.boundingBox === null) mesh.geometry.computeBoundingBox();
194
+ const box = mesh.geometry.boundingBox;
195
+ if (box === null || box.isEmpty()) return undefined;
196
+ const finite = [box.min.x, box.min.y, box.min.z, box.max.x, box.max.y, box.max.z];
197
+ return finite.every(Number.isFinite) ? box : undefined;
198
+ }
199
+
200
+ /**
201
+ * Where an object meets the floor: its lowest world-space geometry point, with the horizontal
202
+ * position taken at the middle of the four lowest corners of its box (the sole, however it tilts).
203
+ * An object without geometry is its origin.
204
+ */
205
+ function contactPoint(elements: Float64Array, box: Box3 | undefined, target: Vector3): Vector3 {
206
+ if (box === undefined)
207
+ return target.set(elements[12] as number, elements[13] as number, elements[14] as number);
208
+ // Plain arithmetic over one read of the matrix and the box, Vector3.applyMatrix4's own formula:
209
+ // on the owned engine each vector call crosses into the engine, and 8 corners per mesh per sample
210
+ // held Lantern Vale's first walk and first run for 43 ms each.
211
+ const e0 = elements[0] as number;
212
+ const e1 = elements[1] as number;
213
+ const e2 = elements[2] as number;
214
+ const e3 = elements[3] as number;
215
+ const e4 = elements[4] as number;
216
+ const e5 = elements[5] as number;
217
+ const e6 = elements[6] as number;
218
+ const e7 = elements[7] as number;
219
+ const e8 = elements[8] as number;
220
+ const e9 = elements[9] as number;
221
+ const e10 = elements[10] as number;
222
+ const e11 = elements[11] as number;
223
+ const e12 = elements[12] as number;
224
+ const e13 = elements[13] as number;
225
+ const e14 = elements[14] as number;
226
+ const e15 = elements[15] as number;
227
+ const { x: minX, y: minY, z: minZ } = box.min;
228
+ const { x: maxX, y: maxY, z: maxZ } = box.max;
229
+ for (let index = 0; index < 8; index += 1) {
230
+ const x = index & 1 ? maxX : minX;
231
+ const y = index & 2 ? maxY : minY;
232
+ const z = index & 4 ? maxZ : minZ;
233
+ const w = 1 / (e3 * x + e7 * y + e11 * z + e15);
234
+ cornerX[index] = (e0 * x + e4 * y + e8 * z + e12) * w;
235
+ cornerY[index] = (e1 * x + e5 * y + e9 * z + e13) * w;
236
+ cornerZ[index] = (e2 * x + e6 * y + e10 * z + e14) * w;
237
+ // Insert by height as each corner lands: a stable sort of 8 without Array.sort's comparator calls,
238
+ // which cost three quarters of this function on Lantern Vale's first walk.
239
+ const height = cornerY[index] as number;
240
+ let slot = index;
241
+ while (slot > 0 && (cornerY[cornerOrder[slot - 1] as number] as number) > height) {
242
+ cornerOrder[slot] = cornerOrder[slot - 1] as number;
243
+ slot -= 1;
244
+ }
245
+ cornerOrder[slot] = index;
246
+ }
247
+ let x = 0;
248
+ let z = 0;
249
+ for (let index = 0; index < 4; index += 1) {
250
+ const corner = cornerOrder[index] as number;
251
+ x += cornerX[corner] as number;
252
+ z += cornerZ[corner] as number;
253
+ }
254
+ return target.set(x / 4, cornerY[cornerOrder[0] as number] as number, z / 4);
255
+ }
256
+
257
+ /** An object's current world matrix into `target`, identity for none; the engine copies it out. */
258
+ function worldOf(object: Object3D | null, target: Float64Array): void {
259
+ if (object === null) {
260
+ target.set(IDENTITY);
261
+ return;
262
+ }
263
+ const source = object as Object3D & { __tnCopyMatrixWorld?: (target: Matrix4) => void };
264
+ // 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
+ }
270
+ }
271
+
272
+ const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
273
+
274
+ /** Matrix4.compose from the object's position, quaternion and scale, three's own formula. */
275
+ function composeLocal(object: Object3D, te: Float64Array): void {
276
+ const { x, y, z, w } = object.quaternion;
277
+ const x2 = x + x;
278
+ const y2 = y + y;
279
+ const z2 = z + z;
280
+ const xx = x * x2;
281
+ const xy = x * y2;
282
+ const xz = x * z2;
283
+ const yy = y * y2;
284
+ const yz = y * z2;
285
+ const zz = z * z2;
286
+ const wx = w * x2;
287
+ const wy = w * y2;
288
+ const wz = w * z2;
289
+ const { x: sx, y: sy, z: sz } = object.scale;
290
+ te[0] = (1 - (yy + zz)) * sx;
291
+ te[1] = (xy + wz) * sx;
292
+ te[2] = (xz - wy) * sx;
293
+ te[3] = 0;
294
+ te[4] = (xy - wz) * sy;
295
+ te[5] = (1 - (xx + zz)) * sy;
296
+ te[6] = (yz + wx) * sy;
297
+ te[7] = 0;
298
+ te[8] = (xz + wy) * sz;
299
+ te[9] = (yz - wx) * sz;
300
+ te[10] = (1 - (xx + yy)) * sz;
301
+ te[11] = 0;
302
+ te[12] = object.position.x;
303
+ te[13] = object.position.y;
304
+ te[14] = object.position.z;
305
+ te[15] = 1;
306
+ }
307
+
308
+ /**
309
+ * Matrix4.multiplyMatrices(a, b) into `te`, three's own formula. Indexed reads on purpose: this runs
310
+ * on a clip's first play, before the JIT warms, where destructuring a Float64Array runs its
311
+ * iterator at twice the cost.
312
+ */
313
+ function multiplyInto(ae: Float64Array, be: Float64Array, te: Float64Array): void {
314
+ const a11 = ae[0] as number;
315
+ const a21 = ae[1] as number;
316
+ const a31 = ae[2] as number;
317
+ const a41 = ae[3] as number;
318
+ const a12 = ae[4] as number;
319
+ const a22 = ae[5] as number;
320
+ const a32 = ae[6] as number;
321
+ const a42 = ae[7] as number;
322
+ const a13 = ae[8] as number;
323
+ const a23 = ae[9] as number;
324
+ const a33 = ae[10] as number;
325
+ const a43 = ae[11] as number;
326
+ const a14 = ae[12] as number;
327
+ const a24 = ae[13] as number;
328
+ const a34 = ae[14] as number;
329
+ const a44 = ae[15] as number;
330
+ const b11 = be[0] as number;
331
+ const b21 = be[1] as number;
332
+ const b31 = be[2] as number;
333
+ const b41 = be[3] as number;
334
+ const b12 = be[4] as number;
335
+ const b22 = be[5] as number;
336
+ const b32 = be[6] as number;
337
+ const b42 = be[7] as number;
338
+ const b13 = be[8] as number;
339
+ const b23 = be[9] as number;
340
+ const b33 = be[10] as number;
341
+ const b43 = be[11] as number;
342
+ const b14 = be[12] as number;
343
+ const b24 = be[13] as number;
344
+ const b34 = be[14] as number;
345
+ const b44 = be[15] as number;
346
+ te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
347
+ te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
348
+ te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
349
+ te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
350
+ te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
351
+ te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
352
+ te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
353
+ te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
354
+ te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
355
+ te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
356
+ te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
357
+ te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
358
+ te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
359
+ te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
360
+ te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
361
+ te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
362
+ }
363
+
122
364
  /**
123
365
  * The ground an in-place clip was authored for, read off the feet, in world metres per clip-second.
124
366
  *
@@ -126,7 +368,7 @@ function clipRootMotionSpeed(clip: AnimationClip): number {
126
368
  * travelling — that is what "planted" means — so the stance phase of a cycle states the clip's
127
369
  * speed even though nothing in it translates. Contact bones are found by where they go rather than
128
370
  * by what they are called: whatever reaches the bottom of the rig's arc is a foot, in any rig and
129
- * any language. The median over stance frames rejects the toe-off and heel-strike ends of the
371
+ * any language. A mesh counts at its lowest geometry point, not its origin (`contactPoint`). The median over stance frames rejects the toe-off and heel-strike ends of the
130
372
  * sweep, and the median over feet rejects a limb that never plants.
131
373
  *
132
374
  * The rig is driven and then restored to the transforms it arrived with, once per clip.
@@ -134,6 +376,7 @@ function clipRootMotionSpeed(clip: AnimationClip): number {
134
376
  function footPlantSpeed(root: Object3D, clip: AnimationClip): number {
135
377
  const objects: Object3D[] = [];
136
378
  root.traverse((object) => objects.push(object));
379
+ const boxes = objects.map(contactBox);
137
380
 
138
381
  // The root belongs to the game, which turns it with `rotation.y +=`. A quaternion restore
139
382
  // rewrites `rotation` as the equivalent Euler, so a yaw of PI comes back as (PI, 0, PI) and the
@@ -148,19 +391,38 @@ function footPlantSpeed(root: Object3D, clip: AnimationClip): number {
148
391
  const step = clip.duration / PLANT_SAMPLES;
149
392
  // The mixer animates only the rig, so its ancestors need one refresh, not one per sample.
150
393
  root.parent?.updateWorldMatrix(true, false);
394
+ // A rig that updates its own matrices gets its world matrices here, with three's own compose and
395
+ // multiply over plain arrays: on the owned engine a world read is one crossing and a matrix read
396
+ // sixteen proxied ones, per node per sample, and those held Lantern Vale's first walk 13 ms on a
397
+ // desktop. A node with a hand-set matrix keeps the engine's world read.
398
+ const composed = objects.every(
399
+ (object) => object.matrixAutoUpdate !== false && object.matrixWorldAutoUpdate !== false,
400
+ );
401
+ const worlds = objects.map(() => new Float64Array(16));
402
+ const local = new Float64Array(16);
403
+ const rootParentWorld = new Float64Array(16);
404
+ const parentOf = new Map(objects.map((object, index) => [object, index]));
405
+ const parents = objects.map((object) =>
406
+ object === root ? -1 : (parentOf.get(object.parent as Object3D) ?? -1),
407
+ );
408
+ if (composed) worldOf(root.parent, rootParentWorld);
151
409
  try {
152
410
  for (let frame = 0; frame <= PLANT_SAMPLES; frame += 1) {
153
411
  mixer.setTime(frame * step);
154
- root.updateMatrixWorld(true);
412
+ if (!composed) root.updateMatrixWorld(true);
155
413
  for (let index = 0; index < objects.length; index += 1) {
156
- // The frame's updateMatrixWorld already holds every bone; getWorldPosition re-walks ancestors.
157
- const object = objects[index] as Object3D & {
158
- __tnCopyMatrixWorld?: (target: Matrix4) => void;
159
- };
160
- if (object.__tnCopyMatrixWorld !== undefined) {
161
- object.__tnCopyMatrixWorld(scratchMatrixWorld);
162
- scratchWorld.setFromMatrixPosition(scratchMatrixWorld);
163
- } else scratchWorld.setFromMatrixPosition(object.matrixWorld);
414
+ const object = objects[index] as Object3D;
415
+ const world = worlds[index] as Float64Array;
416
+ if (composed) {
417
+ composeLocal(object, local);
418
+ const parent = parents[index] as number;
419
+ multiplyInto(
420
+ parent < 0 ? rootParentWorld : (worlds[parent] as Float64Array),
421
+ local,
422
+ world,
423
+ );
424
+ } else worldOf(object, world);
425
+ contactPoint(world, boxes[index], scratchWorld);
164
426
  (paths[index] as { x: number; y: number; z: number }[]).push({
165
427
  x: scratchWorld.x,
166
428
  y: scratchWorld.y,
@@ -229,13 +491,127 @@ export interface IAnimationPlayOptions {
229
491
  * also keeps its authored rate — stride sync re-times locomotion, not events.
230
492
  */
231
493
  readonly mode?: "loop" | "once";
494
+ /**
495
+ * The playback rate of this play of a `"once"` clip, like Godot's `play(name, blend, speed)`.
496
+ * `1` (the default) is the authored rate; the next play without it returns to `1`. A looping clip
497
+ * keeps its stride-synced rate and ignores it.
498
+ */
499
+ readonly speed?: number;
232
500
  }
233
501
 
234
502
  type AnimationMode = "loop" | "once";
503
+ let nextAnimationOffset = 0;
504
+ const ANIMATION_RATE_STATE_KEY = "threenative.animationRateState";
505
+
506
+ type LoopListener = EventListener<AnimationMixerEventMap["loop"], "loop", LoopAwareAnimationMixer>;
507
+ type FinishedListener = EventListener<
508
+ AnimationMixerEventMap["finished"],
509
+ "finished",
510
+ LoopAwareAnimationMixer
511
+ >;
512
+ type BeforeFirstLoopListener = (duringUpdate: boolean) => void;
513
+
514
+ class LoopAwareAnimationMixer extends AnimationMixer<AnimationMixerEventMap> {
515
+ readonly #loopListeners = new Set<LoopListener>();
516
+ readonly #finishedListeners = new Set<FinishedListener>();
517
+ readonly #beforeFirstLoopListener: BeforeFirstLoopListener;
518
+ #updateDepth = 0;
519
+
520
+ constructor(
521
+ root: Object3D,
522
+ beforeFirstLoopListener: BeforeFirstLoopListener,
523
+ internalFinishedListener: FinishedListener,
524
+ ) {
525
+ super(root);
526
+ this.#beforeFirstLoopListener = beforeFirstLoopListener;
527
+ super.addEventListener("finished", internalFinishedListener);
528
+ }
529
+
530
+ get hasPublicListeners(): boolean {
531
+ return this.#loopListeners.size > 0 || this.#finishedListeners.size > 0;
532
+ }
533
+
534
+ override addEventListener(type: "loop", listener: LoopListener): void;
535
+ override addEventListener(type: "finished", listener: FinishedListener): void;
536
+ override addEventListener(
537
+ type: "loop" | "finished",
538
+ listener: LoopListener | FinishedListener,
539
+ ): void {
540
+ if (type === "loop") {
541
+ const loopListener = listener as LoopListener;
542
+ if (!this.hasEventListener(type, loopListener)) {
543
+ if (!this.hasPublicListeners) {
544
+ const duringUpdate = this.#updateDepth > 0;
545
+ this.#beforeFirstLoopListener(duringUpdate);
546
+ }
547
+ this.#loopListeners.add(loopListener);
548
+ }
549
+ super.addEventListener(type, loopListener);
550
+ return;
551
+ }
552
+ const finishedListener = listener as FinishedListener;
553
+ if (!this.hasEventListener(type, finishedListener)) {
554
+ if (!this.hasPublicListeners) this.#beforeFirstLoopListener(this.#updateDepth > 0);
555
+ this.#finishedListeners.add(finishedListener);
556
+ }
557
+ super.addEventListener(type, finishedListener);
558
+ }
559
+
560
+ override removeEventListener(type: "loop", listener: LoopListener): void;
561
+ override removeEventListener(type: "finished", listener: FinishedListener): void;
562
+ override removeEventListener(
563
+ type: "loop" | "finished",
564
+ listener: LoopListener | FinishedListener,
565
+ ): void {
566
+ if (type === "loop") {
567
+ const loopListener = listener as LoopListener;
568
+ const wasRegistered = this.hasEventListener(type, loopListener);
569
+ super.removeEventListener(type, loopListener);
570
+ if (wasRegistered) this.#loopListeners.delete(loopListener);
571
+ return;
572
+ }
573
+ const finishedListener = listener as FinishedListener;
574
+ super.removeEventListener(type, finishedListener);
575
+ this.#finishedListeners.delete(finishedListener);
576
+ }
577
+
578
+ override update(deltaTime: number): AnimationMixer {
579
+ this.#updateDepth += 1;
580
+ try {
581
+ return super.update(deltaTime);
582
+ } finally {
583
+ this.#updateDepth -= 1;
584
+ }
585
+ }
586
+ }
235
587
 
236
588
  export class AnimationPlayer {
589
+ readonly #packetReader = () => this.#readPacketState();
590
+ readonly #packetTimeReader = () => this.#trustedPacketTime();
591
+ /** The action and clip the last full packet validation accepted, reused for a bounded number of reads. */
592
+ #packetTrust: { action: AnimationAction; clip: AnimationClip; left: number } | undefined;
237
593
  readonly mixer: AnimationMixer;
238
594
  readonly root: Object3D;
595
+ readonly #rateState: IAnimationRateState = {
596
+ rate: 1,
597
+ effectiveRate: 1,
598
+ frame: 0,
599
+ source: undefined,
600
+ evaluated: true,
601
+ evaluation: 0,
602
+ syncBones: () => this.#flushPending(),
603
+ };
604
+ readonly #staggerOffset = nextAnimationOffset++;
605
+ #updateRate: "auto" | number = "auto";
606
+ #updateFrame = 0;
607
+ #skippedFrames = 0;
608
+ #pendingDt = 0;
609
+ readonly #pendingActionTimes = new Map<AnimationAction, number>();
610
+ readonly #evaluationScales = new Map<AnimationAction, number>();
611
+ readonly #evaluationPaused = new Set<AnimationAction>();
612
+ readonly #timeScaleInterpolations = new Set<AnimationAction>();
613
+ #evaluating = false;
614
+ #evaluated = false;
239
615
  #actions = new Map<string, AnimationAction>();
240
616
  #current: string | undefined;
241
617
  #mode: AnimationMode = "loop";
@@ -254,10 +630,18 @@ export class AnimationPlayer {
254
630
  #blendElapsed = 0;
255
631
  #blendStarts = new Map<string, number>();
256
632
  #preparation: RigPreparation | undefined;
257
- #strideSync: boolean;
633
+ #strideSync: boolean | undefined;
258
634
  #strideRoot: Object3D;
635
+ #cameraCarried = false;
259
636
  #lastRootPosition = new Vector3();
260
637
  #hasLastRootPosition = false;
638
+ /**
639
+ * The clip whose last stride measurement could not change any time scale: it is not locomotion,
640
+ * or the game declined stride sync. While it is still playing, a held tick only banks its `dt`
641
+ * and the next evaluation measures the whole interval, so a held rig pays no world-matrix walk.
642
+ */
643
+ #strideReportOnlyFor: string | undefined;
644
+ #strideDtDebt = 0;
261
645
  // The last update's numbers, kept as scalars so a frame that never reads `.stride` builds no
262
646
  // report. A read materializes a fresh snapshot, so a retained report never changes under it.
263
647
  #strideGroundSpeed = 0;
@@ -272,9 +656,17 @@ export class AnimationPlayer {
272
656
  constructor(options: IAnimationPlayerOptions) {
273
657
  const owner = new.target.name || "AnimationPlayer";
274
658
  this.root = options.root;
275
- this.mixer = new AnimationMixer(options.root);
659
+ this.updateRate = options.updateRate ?? "auto";
660
+ this.#rateState.gpuPoseEnabled = options.gpuPose === true;
661
+ this.mixer = new LoopAwareAnimationMixer(
662
+ options.root,
663
+ (duringUpdate) => {
664
+ if (!duringUpdate) this.#flushPending();
665
+ },
666
+ this.#onFinished,
667
+ );
276
668
  this.#preparation = options.preparation;
277
- this.#strideSync = options.strideSync ?? true;
669
+ this.#strideSync = options.strideSync;
278
670
  this.#strideRoot = options.strideRoot ?? options.root;
279
671
  for (const clip of options.clips) {
280
672
  if (this.#actions.has(clip.name))
@@ -288,6 +680,7 @@ export class AnimationPlayer {
288
680
  const action = this.mixer.clipAction(clip);
289
681
  if (action === null)
290
682
  throw new Error(`Animation clip '${clip.name}' could not create an action.`);
683
+ this.#observeTimeScaleInterpolation(action);
291
684
  this.#actions.set(clip.name, action);
292
685
  this.#clips.set(clip.name, clip);
293
686
  }
@@ -307,7 +700,81 @@ export class AnimationPlayer {
307
700
  `${owner}: clip '${name}' binds 0 tracks to '${options.root.name || options.root.type}'.`,
308
701
  );
309
702
  }
310
- this.mixer.addEventListener("finished", this.#onFinished);
703
+ animationPacketReaders.set(this.root, this.#packetReader);
704
+ animationPacketTimeReaders.set(this.root, this.#packetTimeReader);
705
+ trackAnimationRate(this.root, this.#rateState);
706
+ this.root.userData[ANIMATION_RATE_STATE_KEY] = this.#rateState;
707
+ }
708
+
709
+ get updateRate(): "auto" | number {
710
+ return this.#updateRate;
711
+ }
712
+
713
+ set updateRate(value: "auto" | number) {
714
+ if (value !== "auto" && (!Number.isSafeInteger(value) || value < 1))
715
+ throw new Error("AnimationPlayer.updateRate requires 'auto' or a positive safe integer.");
716
+ this.#updateRate = value;
717
+ }
718
+
719
+ get updateRateReport(): IAnimationUpdateRateReport {
720
+ const rate = this.#effectiveUpdateRate();
721
+ return {
722
+ rate,
723
+ overridden: this.#updateRate !== "auto",
724
+ evaluated: this.#evaluated,
725
+ boneRate: this.#boneRate(rate),
726
+ };
727
+ }
728
+
729
+ /** An explicit `updateRate` keeps the CPU pose on that interval; auto lets the GPU pose stretch it. */
730
+ #boneRate(rate: number): number {
731
+ return this.#updateRate === "auto" && rate > 1 && this.#rateState.gpuPose === true
732
+ ? rate * GPU_POSE_BONE_REFRESH
733
+ : rate;
734
+ }
735
+
736
+ #effectiveUpdateRate(mixerScale = this.mixer.timeScale): number {
737
+ // Public mixer speed overrides and observed events retain ordinary Three.js tick semantics.
738
+ if (mixerScale !== 1) return 1;
739
+ // Event deadlines and changing blend weights remain exactly on the gameplay tick.
740
+ if (
741
+ this.#mode === "once" ||
742
+ this.#fadeOut.length > 0 ||
743
+ this.#blendElapsed < this.#blendDuration
744
+ )
745
+ return 1;
746
+ if (this.mixer instanceof LoopAwareAnimationMixer && this.mixer.hasPublicListeners) return 1;
747
+ if (this.#timeScaleInterpolations.size > 0) return 1;
748
+ if (this.#updateRate !== "auto") return this.#updateRate;
749
+ const state = this.#rateState;
750
+ if (state.source === undefined) return 1;
751
+ // A held pose rides on a moving body, so a stride-synced walk in the 32-128 px band evaluates
752
+ // every frame, or its planted foot slides by the body's travel; smaller rigs keep the band rate.
753
+ return state.frame === state.source.animationFrame
754
+ ? state.rate === 2 && this.#strideSynced && this.#strideGroundSpeed >= STRIDE_SPEED_FLOOR
755
+ ? 1
756
+ : state.rate
757
+ : 8;
758
+ }
759
+
760
+ #observeTimeScaleInterpolation(action: AnimationAction): void {
761
+ const warp = action.warp.bind(action);
762
+ const stopWarping = action.stopWarping.bind(action);
763
+ const crossFadeFrom = action.crossFadeFrom.bind(action);
764
+ action.warp = (startTimeScale, endTimeScale, duration) => {
765
+ if (!this.#evaluating) this.#flushPending();
766
+ this.#timeScaleInterpolations.add(action);
767
+ return warp(startTimeScale, endTimeScale, duration);
768
+ };
769
+ action.crossFadeFrom = (fadeOutAction, duration, warp) => {
770
+ if (!this.#evaluating) this.#flushPending();
771
+ return crossFadeFrom(fadeOutAction, duration, warp);
772
+ };
773
+ action.stopWarping = () => {
774
+ const result = stopWarping();
775
+ this.#timeScaleInterpolations.delete(action);
776
+ return result;
777
+ };
311
778
  }
312
779
 
313
780
  get current(): string | undefined {
@@ -339,6 +806,7 @@ export class AnimationPlayer {
339
806
  clipGroundSpeed: measured?.groundSpeed ?? 0,
340
807
  groundSpeed: this.#strideGroundSpeed,
341
808
  inPlace: measured?.inPlace ?? this.#strideInPlace,
809
+ cameraCarried: this.#cameraCarried,
342
810
  overridden: this.#strideOverridden,
343
811
  rate: this.#strideRate,
344
812
  synced: this.#strideSynced,
@@ -459,22 +927,30 @@ export class AnimationPlayer {
459
927
  : 0;
460
928
  this.#lastRootPosition.copy(scratchWorld);
461
929
  this.#hasLastRootPosition = true;
930
+ this.#cameraCarried = cameraCarried(this.#strideRoot);
462
931
  if (name === undefined || action === undefined || dt <= 0) return;
932
+ const strideSync = this.#strideSync ?? !this.#cameraCarried;
463
933
  const measured = this.#measureOf(name);
464
934
  const clipGroundSpeed = measured.groundSpeed;
465
935
  const groundSpeed = moved / dt;
466
936
  // A dominant idle must not leave a contributing walk at its authored speed.
467
- if (this.#blendTargets !== undefined && this.#strideSync && this.#mode === "loop")
937
+ if (this.#blendTargets !== undefined && strideSync && this.#mode === "loop")
468
938
  this.#syncBlendParticipants(groundSpeed);
469
939
  if (clipGroundSpeed < CLIP_GROUND_FLOOR) {
470
940
  // Not locomotion. An idle, a reload or a death is authored at the rate it is authored at,
471
941
  // and warping it by how fast the body happens to be sliding is a bug, not a convention.
472
- if (action.getEffectiveTimeScale() !== 1) action.setEffectiveTimeScale(1);
942
+ if (
943
+ this.#strideSynced &&
944
+ !this.#timeScaleInterpolations.has(action) &&
945
+ action.getEffectiveTimeScale() === this.#strideRate
946
+ )
947
+ action.setEffectiveTimeScale(1);
473
948
  this.#strideGroundSpeed = groundSpeed;
474
949
  this.#strideRate = 1;
475
950
  this.#strideSynced = false;
476
951
  this.#strideOverridden = false;
477
952
  this.#strideInPlace = measured.inPlace;
953
+ this.#strideReportOnlyFor = this.#blendTargets === undefined ? name : undefined;
478
954
  return;
479
955
  }
480
956
  const wanted =
@@ -484,13 +960,15 @@ export class AnimationPlayer {
484
960
  // event happens at, however still the body stands: its own root motion is the movement, so
485
961
  // re-timing it against a stationary body only slows the event down. A travelling death clip
486
962
  // clamped to the rate floor held a corpse upright through its whole death in the sandbox.
487
- const applies = this.#strideSync && this.#mode === "loop";
488
- if (applies) action.setEffectiveTimeScale(rate);
963
+ const applies =
964
+ strideSync && this.#mode === "loop" && !this.#timeScaleInterpolations.has(action);
965
+ if (applies && action.timeScale !== rate) action.setEffectiveTimeScale(rate);
489
966
  this.#strideGroundSpeed = groundSpeed;
490
967
  this.#strideRate = rate;
491
968
  this.#strideSynced = applies;
492
- this.#strideOverridden = !this.#strideSync;
969
+ this.#strideOverridden = !strideSync;
493
970
  this.#strideInPlace = measured.inPlace;
971
+ this.#strideReportOnlyFor = !applies && this.#blendTargets === undefined ? name : undefined;
494
972
  }
495
973
 
496
974
  /**
@@ -504,13 +982,14 @@ export class AnimationPlayer {
504
982
  for (const [name, action] of this.#actions) {
505
983
  if (!action.isScheduled() || action.getEffectiveWeight() <= 0) continue;
506
984
  const ground = this.#measureOf(name).groundSpeed;
507
- if (ground < CLIP_GROUND_FLOOR) continue;
985
+ if (ground < CLIP_GROUND_FLOOR || this.#timeScaleInterpolations.has(action)) continue;
508
986
  const wanted = groundSpeed < STRIDE_SPEED_FLOOR ? STRIDE_RATE_MIN : groundSpeed / ground;
509
- action.setEffectiveTimeScale(Math.min(STRIDE_RATE_MAX, Math.max(STRIDE_RATE_MIN, wanted)));
987
+ const rate = Math.min(STRIDE_RATE_MAX, Math.max(STRIDE_RATE_MIN, wanted));
988
+ if (action.timeScale !== rate) action.setEffectiveTimeScale(rate);
510
989
  }
511
990
  }
512
991
 
513
- #playAction(action: AnimationAction, mode: AnimationMode, weight: number): void {
992
+ #playAction(action: AnimationAction, mode: AnimationMode, weight: number, speed: number): void {
514
993
  const once = mode === "once";
515
994
  action
516
995
  .reset()
@@ -518,29 +997,35 @@ export class AnimationPlayer {
518
997
  .setEffectiveWeight(weight)
519
998
  .play();
520
999
  action.clampWhenFinished = once;
1000
+ if (once) action.setEffectiveTimeScale(speed);
521
1001
  }
522
1002
 
523
- #replayCurrent(action: AnimationAction, mode: AnimationMode): void {
1003
+ #replayCurrent(action: AnimationAction, mode: AnimationMode, speed: number): void {
524
1004
  for (const entry of this.#fadeOut) entry.action.stop();
525
1005
  this.#fadeOut = [];
526
1006
  for (const other of this.#actions.values()) {
527
1007
  if (other !== action) other.setEffectiveWeight(0).stop();
528
1008
  }
529
- this.#playAction(action, mode, 1);
1009
+ this.#playAction(action, mode, 1, speed);
530
1010
  this.#mode = mode;
531
1011
  this.#finished = false;
532
1012
  this.#advancedFrames = 0;
533
1013
  }
534
1014
 
535
- #playCurrent(action: AnimationAction, requestedMode: AnimationMode | undefined): void {
1015
+ #playCurrent(
1016
+ action: AnimationAction,
1017
+ requestedMode: AnimationMode | undefined,
1018
+ speed: number,
1019
+ ): void {
536
1020
  const mode = requestedMode ?? "loop";
537
1021
  if (!this.#finished && mode === this.#mode) return;
538
- this.#replayCurrent(action, mode);
1022
+ this.#replayCurrent(action, mode, speed);
539
1023
  }
540
1024
 
541
1025
  #playNext(name: string, next: AnimationAction, options: IAnimationPlayOptions): void {
542
1026
  const fade = Math.max(0, options.fade ?? 0);
543
1027
  const once = options.mode === "once";
1028
+ const speed = options.speed ?? 1;
544
1029
  const from = fade > 0 && next.isScheduled() ? next.getEffectiveWeight() : 0;
545
1030
  // A loop that is still visible keeps its gait; explicit one-shots and mode changes replay.
546
1031
  const time = from > 0 && !once && next.loop === LoopRepeat ? next.time : 0;
@@ -559,7 +1044,12 @@ export class AnimationPlayer {
559
1044
  else action.setEffectiveWeight(0).stop();
560
1045
  }
561
1046
 
562
- this.#playAction(next, once ? "once" : "loop", fade > 0 && outgoing.length > 0 ? from : 1);
1047
+ this.#playAction(
1048
+ next,
1049
+ once ? "once" : "loop",
1050
+ fade > 0 && outgoing.length > 0 ? from : 1,
1051
+ speed,
1052
+ );
563
1053
  next.time = time;
564
1054
  if (outgoing.length === 0 || fade === 0) {
565
1055
  for (const entry of outgoing) entry.action.setEffectiveWeight(0).stop();
@@ -603,8 +1093,13 @@ export class AnimationPlayer {
603
1093
  }
604
1094
 
605
1095
  #start(name: string, options: IAnimationPlayOptions): void {
1096
+ const speed = options.speed ?? 1;
1097
+ if (!(Number.isFinite(speed) && speed > 0))
1098
+ throw new Error(`Animation play speed must be a positive finite number, got ${speed}.`);
606
1099
  const next = this.#actions.get(name);
607
1100
  if (next === undefined) throw new Error(`Unknown animation clip '${name}'.`);
1101
+ if (this.#current !== name || this.#finished || (options.mode ?? "loop") !== this.#mode)
1102
+ this.#flushPending();
608
1103
  // One owner at a time. A single-clip request takes the rig back from a weighted blend, exactly
609
1104
  // as it took it back from a crossfade.
610
1105
  const weighted = this.#blendTargets !== undefined;
@@ -617,7 +1112,7 @@ export class AnimationPlayer {
617
1112
  const keepPhase = this.#mode === "loop" && options.mode !== "once";
618
1113
  this.#playNext(name, next, options);
619
1114
  if (keepPhase) next.time = time;
620
- } else this.#playCurrent(next, options.mode);
1115
+ } else this.#playCurrent(next, options.mode, speed);
621
1116
  return;
622
1117
  }
623
1118
  this.#playNext(name, next, options);
@@ -663,6 +1158,7 @@ export class AnimationPlayer {
663
1158
  [...targets].every(([name, weight]) => this.#blendTargets?.get(name) === weight)
664
1159
  )
665
1160
  return;
1161
+ this.#flushPending();
666
1162
  // Any crossfade in flight stops owning the rig; its outgoing actions join the blend ramp below
667
1163
  // as participants with a target of zero, so they leave the same bounded way they arrived.
668
1164
  this.#fadeOut = [];
@@ -772,14 +1268,245 @@ export class AnimationPlayer {
772
1268
  }
773
1269
  }
774
1270
 
775
- update(dt: number): void {
1271
+ /** `force` evaluates accumulated time now, even outside this player's stagger slot. */
1272
+ update(dt: number, force = false): void {
776
1273
  if (!Number.isFinite(dt) || dt < 0)
777
1274
  throw new Error("AnimationPlayer.update requires a finite non-negative dt.");
1275
+ const mixerScale = this.mixer.timeScale;
1276
+ if (mixerScale !== 1) this.#flushPending();
1277
+ const elapsed = dt * mixerScale;
1278
+ const rate = this.#effectiveUpdateRate(mixerScale);
1279
+ this.#rateState.effectiveRate = force ? 1 : rate;
1280
+ this.#updateFrame += 1;
1281
+ this.#skippedFrames += 1;
1282
+ this.#rateState.evaluated = false;
1283
+ const boneRate = this.#boneRate(rate);
1284
+ this.#evaluated =
1285
+ force ||
1286
+ (this.#updateFrame + this.#staggerOffset) % boneRate === 0 ||
1287
+ this.#skippedFrames >= boneRate;
1288
+ // A full-rate tick with no held time advances through the mixer's own actions; only deferred
1289
+ // integration needs per-action elapsed time. Scanning the whole clip library to bank that time
1290
+ // 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
+ ) {
1297
+ for (const action of this.#actions.values()) {
1298
+ if (!action.isScheduled()) continue;
1299
+ const time = action.paused ? 0 : action.timeScale * elapsed;
1300
+ this.#pendingActionTimes.set(action, (this.#pendingActionTimes.get(action) ?? 0) + time);
1301
+ }
1302
+ }
1303
+ this.#pendingDt += elapsed;
1304
+ if (this.#evaluated) this.#evaluate(dt, mixerScale);
1305
+ // Measure the body's movement on every tick, including skipped pose evaluations. A held tick of
1306
+ // a clip whose measurement only reports banks its dt: the average speed over the interval is
1307
+ // the same number, measured once.
1308
+ if (
1309
+ !this.#evaluated &&
1310
+ this.#strideReportOnlyFor !== undefined &&
1311
+ this.#strideReportOnlyFor === this.#current &&
1312
+ this.#blendTargets === undefined &&
1313
+ dt > 0
1314
+ ) {
1315
+ this.#strideDtDebt += dt;
1316
+ return;
1317
+ }
1318
+ if (dt > 0) {
1319
+ const interval = dt + this.#strideDtDebt;
1320
+ this.#strideDtDebt = 0;
1321
+ this.#syncStride(interval);
1322
+ } else this.#syncStride(dt);
1323
+ }
1324
+
1325
+ /**
1326
+ * The playhead a trusted packet reads, as a bare number: the same checks as the trusted branch
1327
+ * of `#readPacketState` without building a state object. Undefined sends the caller to the full
1328
+ * read, which also renews the trust.
1329
+ */
1330
+ #trustedPacketTime(): number | undefined {
1331
+ const trust = this.#packetTrust;
1332
+ if (
1333
+ trust === undefined ||
1334
+ trust.left <= 0 ||
1335
+ this.#evaluating ||
1336
+ this.#actions.size !== 1 ||
1337
+ this.#mode !== "loop" ||
1338
+ this.#finished ||
1339
+ this.#fadeOut.length !== 0 ||
1340
+ this.#blendTargets !== undefined ||
1341
+ this.#timeScaleInterpolations.size !== 0
1342
+ )
1343
+ return undefined;
1344
+ const name = this.#current ?? "";
1345
+ const action = this.#actions.get(name);
1346
+ if (action !== trust.action || this.#clips.get(name) !== trust.clip) return undefined;
1347
+ trust.left -= 1;
1348
+ return animationPacketTime(
1349
+ action.time,
1350
+ this.#pendingActionTimes.get(action) ?? 0,
1351
+ trust.clip.duration,
1352
+ );
1353
+ }
1354
+
1355
+ #readPacketState(): IAnimationPacketState | undefined {
1356
+ if (
1357
+ this.#evaluating ||
1358
+ this.#actions.size !== 1 ||
1359
+ this.#mode !== "loop" ||
1360
+ this.#finished ||
1361
+ this.#fadeOut.length !== 0 ||
1362
+ this.#blendTargets !== undefined ||
1363
+ this.#timeScaleInterpolations.size !== 0
1364
+ )
1365
+ return undefined;
1366
+ const action = this.#actions.get(this.#current ?? "");
1367
+ const clip = this.#clips.get(this.#current ?? "");
1368
+ const trust = this.#packetTrust;
1369
+ if (trust !== undefined && trust.left > 0 && action === trust.action && clip === trust.clip) {
1370
+ trust.left -= 1;
1371
+ // Between full validations only the playhead is read: plain data fields, no author code.
1372
+ const time = animationPacketTime(
1373
+ action.time,
1374
+ this.#pendingActionTimes.get(action) ?? 0,
1375
+ clip.duration,
1376
+ );
1377
+ if (time === undefined) return undefined;
1378
+ return Object.freeze({
1379
+ root: this.root,
1380
+ mixer: this.mixer,
1381
+ action,
1382
+ clip,
1383
+ time,
1384
+ evaluated: this.#rateState.evaluated,
1385
+ evaluation: this.#rateState.evaluation,
1386
+ });
1387
+ }
1388
+ this.#packetTrust = undefined;
1389
+ if (
1390
+ action === undefined ||
1391
+ clip === undefined ||
1392
+ !animationPacketMethodsPristine(action, this.mixer)
1393
+ )
1394
+ return undefined;
1395
+ const field = animationPacketField;
1396
+ const duration = field(clip, "duration");
1397
+ const held = field(action, "time");
1398
+ const index = field(action, "_cacheIndex");
1399
+ const active = field(this.mixer, "_nActiveActions");
1400
+ const actions = field(this.mixer, "_actions");
1401
+ if (
1402
+ field(action, "_mixer") !== this.mixer ||
1403
+ field(action, "_clip") !== clip ||
1404
+ field(this.mixer, "_root") !== this.root ||
1405
+ field(this.mixer, "timeScale") !== 1 ||
1406
+ field(action, "loop") !== LoopRepeat ||
1407
+ field(action, "repetitions") !== Number.POSITIVE_INFINITY ||
1408
+ field(action, "clampWhenFinished") !== false ||
1409
+ field(action, "paused") !== false ||
1410
+ field(action, "enabled") !== true ||
1411
+ field(action, "weight") !== 1 ||
1412
+ field(action, "_effectiveWeight") !== 1 ||
1413
+ field(action, "timeScale") !== 1 ||
1414
+ field(action, "_effectiveTimeScale") !== 1 ||
1415
+ field(action, "_startTime") !== null ||
1416
+ field(action, "_weightInterpolant") !== null ||
1417
+ field(action, "_timeScaleInterpolant") !== null ||
1418
+ active !== 1 ||
1419
+ typeof index !== "number" ||
1420
+ index !== 0 ||
1421
+ !Array.isArray(actions) ||
1422
+ field(actions, String(index)) !== action ||
1423
+ typeof duration !== "number" ||
1424
+ !Number.isFinite(duration) ||
1425
+ duration <= 0 ||
1426
+ typeof held !== "number" ||
1427
+ !Number.isFinite(held) ||
1428
+ held < 0 ||
1429
+ held > duration
1430
+ )
1431
+ return undefined;
1432
+ const time = animationPacketTime(held, this.#pendingActionTimes.get(action) ?? 0, duration);
1433
+ if (time === undefined) return undefined;
1434
+ this.#packetTrust = { action, clip, left: PACKET_REVALIDATE_READS };
1435
+ return Object.freeze({
1436
+ root: this.root,
1437
+ mixer: this.mixer,
1438
+ action,
1439
+ clip,
1440
+ time,
1441
+ evaluated: this.#rateState.evaluated,
1442
+ evaluation: this.#rateState.evaluation,
1443
+ });
1444
+ }
1445
+
1446
+ #flushPending(): void {
1447
+ if (this.#pendingDt !== 0) this.#evaluate(this.#pendingDt);
1448
+ }
1449
+
1450
+ #evaluate(dt: number, mixerScale = this.mixer.timeScale): void {
778
1451
  // Read before mixer.update(): the "finished" listener fires inside it for a completing
779
1452
  // once-clip, and that final frame still counts as advancement.
780
1453
  const wasFinished = this.#finished;
781
1454
  const before = this.mixer.time;
782
- this.mixer.update(dt);
1455
+ const elapsed = this.#pendingDt;
1456
+ const direct =
1457
+ this.#skippedFrames === 1 &&
1458
+ elapsed === dt * mixerScale &&
1459
+ (this.#pendingActionTimes.size === 0 ||
1460
+ mixerScale !== 1 ||
1461
+ (this.mixer instanceof LoopAwareAnimationMixer && this.mixer.hasPublicListeners));
1462
+ if (!direct) {
1463
+ this.mixer.timeScale = 1;
1464
+ for (const [action, pending] of this.#pendingActionTimes) {
1465
+ const wasPaused = action.paused;
1466
+ if (wasPaused && pending !== 0) {
1467
+ this.#evaluationPaused.add(action);
1468
+ action.paused = false;
1469
+ }
1470
+ let time = pending;
1471
+ let seamAdjusted = false;
1472
+ const duration = action.getClip().duration;
1473
+ if (action.loop === LoopRepeat && duration > 0) {
1474
+ const end = action.time + time;
1475
+ const seam = Math.round(end / duration) * duration;
1476
+ // Grouped addition must not hold the last pose when rate 1 already crossed a loop seam.
1477
+ if (Math.abs(end - seam) <= Number.EPSILON * 16 * Math.max(duration, Math.abs(end))) {
1478
+ time = seam - action.time;
1479
+ seamAdjusted = true;
1480
+ }
1481
+ }
1482
+ // Integrate changing stride rates; the last tick's rate must not own earlier skipped time.
1483
+ if (elapsed !== 0) {
1484
+ const scale = time / elapsed;
1485
+ const equalToActionScale =
1486
+ Math.abs(scale - action.timeScale) <=
1487
+ Number.EPSILON * 16 * Math.max(1, Math.abs(scale), Math.abs(action.timeScale));
1488
+ const warpActive = !wasPaused && action.getEffectiveTimeScale() !== action.timeScale;
1489
+ if (!warpActive && (seamAdjusted || !equalToActionScale)) {
1490
+ this.#evaluationScales.set(action, action.timeScale);
1491
+ action.setEffectiveTimeScale(scale);
1492
+ }
1493
+ }
1494
+ }
1495
+ }
1496
+ this.#evaluating = true;
1497
+ try {
1498
+ this.mixer.update(direct ? dt : elapsed);
1499
+ } finally {
1500
+ this.#evaluating = false;
1501
+ if (!direct) this.mixer.timeScale = mixerScale;
1502
+ for (const action of this.#evaluationPaused) action.paused = true;
1503
+ this.#evaluationPaused.clear();
1504
+ for (const [action, scale] of this.#evaluationScales) action.setEffectiveTimeScale(scale);
1505
+ this.#evaluationScales.clear();
1506
+ this.#pendingDt = 0;
1507
+ this.#pendingActionTimes.clear();
1508
+ this.#skippedFrames = 0;
1509
+ }
783
1510
  if (this.#fadeOut.length > 0) {
784
1511
  this.#fadeElapsed = Math.min(this.#fadeDuration, this.#fadeElapsed + dt);
785
1512
  const linear = this.#fadeDuration === 0 ? 1 : this.#fadeElapsed / this.#fadeDuration;
@@ -803,11 +1530,17 @@ export class AnimationPlayer {
803
1530
  if (this.#current !== undefined && !wasFinished && this.mixer.time !== before)
804
1531
  this.#advancedFrames += 1;
805
1532
  this.#advanceBlend(dt);
806
- this.#syncStride(dt);
1533
+ this.#rateState.evaluation += 1;
1534
+ this.#rateState.evaluated = true;
807
1535
  }
808
1536
 
809
1537
  stop(): void {
1538
+ this.#pendingDt = 0;
1539
+ this.#pendingActionTimes.clear();
1540
+ this.#skippedFrames = 0;
1541
+ this.#evaluated = false;
810
1542
  this.mixer.stopAllAction();
1543
+ this.#rateState.evaluation += 1;
811
1544
  this.#current = undefined;
812
1545
  this.#mode = "loop";
813
1546
  this.#finished = false;
@@ -817,11 +1550,14 @@ export class AnimationPlayer {
817
1550
  this.#blendDuration = 0;
818
1551
  this.#blendElapsed = 0;
819
1552
  this.#blendStarts.clear();
1553
+ this.#timeScaleInterpolations.clear();
820
1554
  this.#resetStride();
821
1555
  }
822
1556
 
823
1557
  #resetStride(): void {
824
1558
  this.#hasLastRootPosition = false;
1559
+ this.#strideReportOnlyFor = undefined;
1560
+ this.#strideDtDebt = 0;
825
1561
  this.#strideGroundSpeed = 0;
826
1562
  this.#strideRate = 1;
827
1563
  this.#strideSynced = false;
@@ -837,6 +1573,14 @@ export class AnimationPlayer {
837
1573
  this.#clips.clear();
838
1574
  this.#clipGroundSpeed.clear();
839
1575
  this.#preparation = undefined;
1576
+ if (animationPacketReaders.get(this.root) === this.#packetReader)
1577
+ animationPacketReaders.delete(this.root);
1578
+ if (animationPacketTimeReaders.get(this.root) === this.#packetTimeReader)
1579
+ animationPacketTimeReaders.delete(this.root);
1580
+ if (animationRateStates.get(this.root) === this.#rateState)
1581
+ animationRateStates.delete(this.root);
1582
+ if (this.root.userData[ANIMATION_RATE_STATE_KEY] === this.#rateState)
1583
+ delete this.root.userData[ANIMATION_RATE_STATE_KEY];
840
1584
  }
841
1585
  }
842
1586
 
@@ -844,6 +1588,10 @@ export class AnimationPlayer {
844
1588
  const scratchWorld = new Vector3();
845
1589
  const scratchScale = new Vector3();
846
1590
  const scratchMatrixWorld = new Matrix4();
1591
+ const cornerX = new Float64Array(8);
1592
+ const cornerY = new Float64Array(8);
1593
+ const cornerZ = new Float64Array(8);
1594
+ const cornerOrder = new Uint8Array(8);
847
1595
 
848
1596
  /**
849
1597
  * Validate one weighted request into normalized, non-zero target weights.