@threenative/core 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,193 @@
1
+ /**
2
+ * PRD-828: the frame's animation work, queued and then run in one crossing.
3
+ *
4
+ * A rig's per-frame loop reads and writes engine state per action — the stress lab measured 1,323
5
+ * crossings a frame, eight of the ten busiest classes inside `AnimationPlayer.update`, `#syncStride`
6
+ * and `#evaluate`. The backend can run that whole loop in C++ (`tn_anim_tick`), so a player that can
7
+ * be described by data queues a descriptor here instead of crossing per property, and the frame calls
8
+ * one flush.
9
+ *
10
+ * The fallback is not a mode: when the backend installs no executor (a surface-only runtime, or a
11
+ * build without the entry point), nothing is ever queued and every player keeps its own loop.
12
+ */
13
+
14
+ /** One rig, in the terms the batch entry takes. Numbers only: the backend resolves the objects. */
15
+ export interface IAnimationTickRig {
16
+ readonly mixer: object;
17
+ /** The rig's current action, or null for a rig with nothing playing (its mixer still steps). */
18
+ readonly action: object | null;
19
+ /** The body the stride is measured from, or null to measure none. */
20
+ readonly strideRoot: object | null;
21
+ /** The interval the body's movement is divided by: a held tick banks its own `dt` into this. */
22
+ readonly dt: number;
23
+ /** This tick's own time. The engine banks it at the rate in force; the caller never reads a scale back. */
24
+ readonly elapsed: number;
25
+ /** True on the tick that poses the rig; a held tick measures the stride and advances nothing. */
26
+ readonly step: boolean;
27
+ /** The player spent ticks this batch did not, so the banked advance the engine holds is already spent. */
28
+ readonly reset: boolean;
29
+ /**
30
+ * The rate this rule last applied to the action, or 0 when its scale is the game's own. The engine is
31
+ * the only writer of a rate, but the player is the side that knows whether it wrote one.
32
+ */
33
+ readonly lastRate: number;
34
+ /** Metres of ground the clip covers per clip-second, measured when the clip was analysed. */
35
+ readonly clipGroundSpeed: number;
36
+ readonly strideSync: boolean;
37
+ }
38
+
39
+ /** What the batch did with one rig, read back in the order the rigs were queued. */
40
+ export interface IAnimationTickResult {
41
+ readonly strideRate: number;
42
+ readonly groundSpeed: number;
43
+ readonly finished: boolean;
44
+ readonly changed: boolean;
45
+ }
46
+
47
+ /** The backend's entry point, installed on `globalThis` by `@threenative/three-native`'s web backend. */
48
+ export type AnimationTickExecutor = (
49
+ rigs: readonly IAnimationTickRig[],
50
+ status: Float64Array,
51
+ ) => void;
52
+
53
+ const EXECUTOR_KEY = "__tnAnimationTick";
54
+ /** 3 doubles per rig: stride rate, ground speed, flags (bit 0 finished, bit 1 changed). */
55
+ const STATUS_STRIDE = 3;
56
+
57
+ /** The executor this realm's backend installed, or undefined when it batches nothing. */
58
+ export function animationTickExecutor(): AnimationTickExecutor | undefined {
59
+ const host = globalThis as { [EXECUTOR_KEY]?: unknown };
60
+ const candidate = host[EXECUTOR_KEY];
61
+ return typeof candidate === "function" ? (candidate as AnimationTickExecutor) : undefined;
62
+ }
63
+
64
+ interface IQueuedRig {
65
+ readonly rig: IAnimationTickRig;
66
+ apply(result: IAnimationTickResult): void;
67
+ }
68
+
69
+ const queue: IQueuedRig[] = [];
70
+ const pending: IAnimationTickRig[] = [];
71
+ let status = new Float64Array(STATUS_STRIDE * 256);
72
+
73
+ /** Queues one rig for this frame's batch. Called from `AnimationPlayer.update`. */
74
+ export function queueAnimationTick(
75
+ rig: IAnimationTickRig,
76
+ apply: (result: IAnimationTickResult) => void,
77
+ ): void {
78
+ queue.push({ rig, apply });
79
+ }
80
+
81
+ /** How many rigs are waiting for the flush (a player that wants to know whether it queued). */
82
+ export function queuedAnimationTicks(): number {
83
+ return queue.length;
84
+ }
85
+
86
+ /**
87
+ * Runs every queued rig in one call and hands each its result. Returns the number of batches run (0 or
88
+ * 1), which is the frame's crossing count for animation.
89
+ *
90
+ * Fail closed on the shape: a backend that answers a different number of rigs than it was given would
91
+ * silently leave a rig unadvanced, so that throws instead.
92
+ */
93
+ export function flushAnimationTicks(): number {
94
+ const count = queue.length;
95
+ if (count === 0) return 0;
96
+ const executor = animationTickExecutor();
97
+ if (executor === undefined) {
98
+ // Nothing to run it: the players that queued took the data path only because availability was
99
+ // checked at queue time, so this is a backend that uninstalled mid-frame.
100
+ queue.length = 0;
101
+ pending.length = 0;
102
+ throw new Error("TN_ANIM_TICK_EXECUTOR_GONE: a rig was queued and no executor is installed.");
103
+ }
104
+ if (status.length < count * STATUS_STRIDE) status = new Float64Array(count * STATUS_STRIDE);
105
+ pending.length = count;
106
+ for (let i = 0; i < count; i += 1) {
107
+ const entry = queue[i];
108
+ if (entry !== undefined) pending[i] = entry.rig;
109
+ }
110
+ countEngineBatch(1);
111
+ try {
112
+ executor(pending, status);
113
+ } catch (error) {
114
+ // A failed call leaves the rigs unadvanced and their descriptors stale: dropping them is the only
115
+ // state that cannot advance a rig twice, and the throw still reaches the caller.
116
+ queue.length = 0;
117
+ pending.length = 0;
118
+ throw error;
119
+ }
120
+ for (let i = 0; i < count; i += 1) {
121
+ const at = i * STATUS_STRIDE;
122
+ const flags = status[at + 2] as number;
123
+ queue[i]?.apply({
124
+ strideRate: status[at] as number,
125
+ groundSpeed: status[at + 1] as number,
126
+ finished: (flags & 1) !== 0,
127
+ changed: (flags & 2) !== 0,
128
+ });
129
+ }
130
+ queue.length = 0;
131
+ pending.length = 0;
132
+ return 1;
133
+ }
134
+
135
+ /**
136
+ * One batch is one crossing for a whole frame's rigs; a reader that settles the queue mid-frame turns
137
+ * that into one batch per rig, which is a bug that looks like a slow engine. Counted where the playtest
138
+ * bounds read it (`TN_FRAME_BUDGET.counters.engine`), so a regression names itself.
139
+ */
140
+ function countEngineBatch(batches: number): void {
141
+ const host = globalThis as { __tnEngineCost?: Record<string, number> };
142
+ if (host.__tnEngineCost === undefined) host.__tnEngineCost = {};
143
+ const bag = host.__tnEngineCost;
144
+ bag.animationTickBatches = (bag.animationTickBatches ?? 0) + batches;
145
+ }
146
+
147
+ /** Drops the queue without running it: a scene teardown must not advance rigs it is destroying. */
148
+ export function clearAnimationTicks(): void {
149
+ queue.length = 0;
150
+ pending.length = 0;
151
+ }
152
+
153
+ /**
154
+ * The queue is what turns N per-rig loops into one call: the smallest check that fails if the
155
+ * read-back stops lining up with the rigs that were queued.
156
+ */
157
+ export function demo(): string {
158
+ const seen: number[] = [];
159
+ const saved = (globalThis as { [EXECUTOR_KEY]?: unknown })[EXECUTOR_KEY];
160
+ (globalThis as { [EXECUTOR_KEY]?: unknown })[EXECUTOR_KEY] = (
161
+ rigs: readonly IAnimationTickRig[],
162
+ out: Float64Array,
163
+ ) => {
164
+ for (let i = 0; i < rigs.length; i += 1) {
165
+ out[i * STATUS_STRIDE] = (rigs[i] as IAnimationTickRig).dt * 10;
166
+ out[i * STATUS_STRIDE + 1] = 2;
167
+ out[i * STATUS_STRIDE + 2] = 3;
168
+ }
169
+ };
170
+ try {
171
+ const rig = (dt: number): IAnimationTickRig => ({
172
+ mixer: {},
173
+ action: null,
174
+ strideRoot: null,
175
+ dt,
176
+ elapsed: dt,
177
+ step: true,
178
+ reset: false,
179
+ lastRate: 0,
180
+ clipGroundSpeed: 1,
181
+ strideSync: true,
182
+ });
183
+ queueAnimationTick(rig(0.1), (result) => seen.push(result.strideRate));
184
+ queueAnimationTick(rig(0.2), (result) => seen.push(result.strideRate));
185
+ if (queuedAnimationTicks() !== 2) throw new Error("queue length");
186
+ if (flushAnimationTicks() !== 1) throw new Error("one batch");
187
+ if (seen.join(",") !== "1,2") throw new Error(`read-back order: ${seen.join(",")}`);
188
+ if (queuedAnimationTicks() !== 0) throw new Error("queue drained");
189
+ return "demo: ok";
190
+ } finally {
191
+ (globalThis as { [EXECUTOR_KEY]?: unknown })[EXECUTOR_KEY] = saved;
192
+ }
193
+ }
@@ -205,7 +205,8 @@ export function prepareAnimationLayers(
205
205
  )
206
206
  throw new Error(`AnimationComposer: reference pose lacks compatible '${track.name}'.`);
207
207
  }
208
- AnimationUtils.makeClipAdditive(clip, time * 30, reference, 30);
208
+ // three edits `clip` and returns it; the owned engine's port returns a new clip.
209
+ return { options, clip: AnimationUtils.makeClipAdditive(clip, time * 30, reference, 30) };
209
210
  }
210
211
  return { options, clip };
211
212
  });
@@ -222,8 +223,11 @@ export function prepareAnimationLayers(
222
223
  property === "position"
223
224
  ? consumedRoot.position.toArray()
224
225
  : consumedRoot.quaternion.toArray();
225
- for (let offset = 0; offset < track.values.length; offset += reference.length)
226
- track.values.set(reference, offset);
226
+ // Written back whole: the owned engine's `values` reads as a copy (three's is the array itself).
227
+ const values = Float32Array.from(track.values);
228
+ for (let offset = 0; offset < values.length; offset += reference.length)
229
+ values.set(reference, offset);
230
+ track.values = values;
227
231
  }
228
232
  }
229
233
  const groups: AnimationClip[] = [];
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