@threenative/core 0.3.4 → 0.3.5

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,253 @@
1
+ import { type RenderTarget, type Texture, Vector2 } from "three";
2
+
3
+ export interface IResolutionTextureView {
4
+ readonly viewFraction: Vector2;
5
+ readonly halfTexel: Vector2;
6
+ }
7
+ export interface IResolutionSubrectNode {
8
+ setSize(width: number, height: number): void;
9
+ }
10
+ interface IRetainedTarget {
11
+ readonly target: RenderTarget;
12
+ readonly view: IResolutionTextureView;
13
+ readonly original: RenderTarget["setSize"];
14
+ readonly wrapped: RenderTarget["setSize"];
15
+ width: number;
16
+ height: number;
17
+ viewWidth: number;
18
+ viewHeight: number;
19
+ }
20
+ interface IRetainedNode {
21
+ readonly node: IResolutionSubrectNode;
22
+ readonly original: IResolutionSubrectNode["setSize"];
23
+ readonly wrapped: IResolutionSubrectNode["setSize"];
24
+ readonly targets: readonly IRetainedTarget[];
25
+ width: number;
26
+ height: number;
27
+ }
28
+
29
+ const quantize = (size: number): number => Math.max(8, Math.ceil(size / 8) * 8);
30
+ const validateSize = (width: number, height: number): void => {
31
+ if (![width, height].every((value) => Number.isFinite(value) && value > 0))
32
+ throw new Error("TN_RESOLUTION_SUBRECT: invalid target extent");
33
+ };
34
+
35
+ const validateScale = (scale: number): void => {
36
+ if (!Number.isFinite(scale) || scale <= 0 || scale > 1)
37
+ throw new Error("TN_RESOLUTION_SUBRECT: invalid scale");
38
+ };
39
+
40
+ /** Owns capacity and viewport lifetime; generated render source owns sampling. */
41
+ export interface IResolutionSubrect {
42
+ readonly active?: boolean;
43
+ readonly view?: IResolutionTextureView;
44
+ textureView(texture: Texture): IResolutionTextureView | undefined;
45
+ activate?(scale: number): void;
46
+ deactivate?(): void;
47
+ setScale?(scale: number): void;
48
+ setSize?(width: number, height: number): void;
49
+ retain(node: IResolutionSubrectNode, targets: readonly RenderTarget[]): void;
50
+ release(node: IResolutionSubrectNode): void;
51
+ dispose(): void;
52
+ }
53
+
54
+ export class ResolutionSubrect implements IResolutionSubrect {
55
+ readonly viewSize = new Vector2();
56
+ readonly #fullSize = new Vector2();
57
+ readonly #nodes = new Map<IResolutionSubrectNode, IRetainedNode>();
58
+ readonly #targets = new Map<RenderTarget, IRetainedTarget>();
59
+ #active = false;
60
+ #disposed = false;
61
+ #reserving = false;
62
+ #scale = 1;
63
+
64
+ get active(): boolean {
65
+ return this.#active;
66
+ }
67
+ get scale(): number {
68
+ return this.#scale;
69
+ }
70
+
71
+ get view(): IResolutionTextureView | undefined {
72
+ for (const binding of this.#targets.values()) return binding.view;
73
+ return undefined;
74
+ }
75
+
76
+ activate(scale: number): void {
77
+ if (this.#disposed) throw new Error("TN_RESOLUTION_SUBRECT: disposed controller");
78
+ validateScale(scale);
79
+ this.#active = true;
80
+ this.setScale(scale);
81
+ }
82
+
83
+ deactivate(): void {
84
+ if (!this.#active) return;
85
+ this.#active = false;
86
+ for (const binding of this.#nodes.values()) {
87
+ if (binding.width <= 0 || binding.height <= 0) continue;
88
+ binding.original.call(
89
+ binding.node,
90
+ Math.max(1, Math.round(binding.width * this.#scale)),
91
+ Math.max(1, Math.round(binding.height * this.#scale)),
92
+ );
93
+ }
94
+ for (const binding of this.#targets.values()) {
95
+ const width = Math.max(1, binding.target.width);
96
+ const height = Math.max(1, binding.target.height);
97
+ binding.target.viewport.set(0, 0, width, height);
98
+ binding.target.scissor.copy(binding.target.viewport);
99
+ binding.target.scissorTest = false;
100
+ binding.view.viewFraction.set(1, 1);
101
+ binding.view.halfTexel.set(0.5 / width, 0.5 / height);
102
+ }
103
+ }
104
+
105
+ setScale(scale: number): void {
106
+ if (this.#disposed) throw new Error("TN_RESOLUTION_SUBRECT: disposed controller");
107
+ validateScale(scale);
108
+ this.#scale = scale;
109
+ if (this.#fullSize.x > 0)
110
+ this.viewSize.set(quantize(this.#fullSize.x * scale), quantize(this.#fullSize.y * scale));
111
+ for (const binding of this.#nodes.values()) {
112
+ if (binding.width > 0) binding.node.setSize(binding.width, binding.height);
113
+ }
114
+ }
115
+
116
+ setSize(width: number, height: number): void {
117
+ if (this.#disposed) throw new Error("TN_RESOLUTION_SUBRECT: disposed controller");
118
+ validateSize(width, height);
119
+ if (this.#active && this.#fullSize.x === width && this.#fullSize.y === height) return;
120
+ this.#fullSize.set(width, height);
121
+ this.viewSize.set(quantize(width * this.#scale), quantize(height * this.#scale));
122
+ for (const binding of this.#nodes.values()) binding.node.setSize(width, height);
123
+ }
124
+
125
+ retain(node: IResolutionSubrectNode, targets: readonly RenderTarget[]): void {
126
+ if (this.#disposed) throw new Error("TN_RESOLUTION_SUBRECT: disposed controller");
127
+ if (this.#nodes.has(node)) return;
128
+ if (
129
+ targets.length === 0 ||
130
+ new Set(targets).size !== targets.length ||
131
+ targets.some((target) => this.#targets.has(target))
132
+ )
133
+ throw new Error("TN_RESOLUTION_SUBRECT: missing or multiply owned target");
134
+ const retained = targets.map((target) => {
135
+ const view = { viewFraction: new Vector2(1, 1), halfTexel: new Vector2() };
136
+ const original = target.setSize;
137
+ const binding: IRetainedTarget = {
138
+ target,
139
+ view,
140
+ original,
141
+ width: 0,
142
+ height: 0,
143
+ viewWidth: 0,
144
+ viewHeight: 0,
145
+ wrapped: (width, height, depth = target.depth) => {
146
+ validateSize(width, height);
147
+ if (!this.#active) {
148
+ original.call(target, width, height, depth);
149
+ view.viewFraction.set(1, 1);
150
+ view.halfTexel.set(0.5 / width, 0.5 / height);
151
+ return;
152
+ }
153
+ let capacityChanged = false;
154
+ if (this.#reserving) {
155
+ const widthCapacity = Math.max(binding.width, quantize(width));
156
+ const heightCapacity = Math.max(binding.height, quantize(height));
157
+ capacityChanged = widthCapacity !== binding.width || heightCapacity !== binding.height;
158
+ binding.width = widthCapacity;
159
+ binding.height = heightCapacity;
160
+ } else {
161
+ if (binding.width === 0 || binding.height === 0)
162
+ throw new Error("TN_RESOLUTION_SUBRECT: target capacity not reserved");
163
+ if (Math.round(width) > binding.width || Math.round(height) > binding.height)
164
+ throw new Error("TN_RESOLUTION_SUBRECT: viewport exceeds retained capacity");
165
+ binding.viewWidth = Math.max(1, Math.round(width));
166
+ binding.viewHeight = Math.max(1, Math.round(height));
167
+ }
168
+ if (capacityChanged || target.width !== binding.width || target.height !== binding.height)
169
+ original.call(target, binding.width, binding.height, depth);
170
+ if (!this.#reserving) this.#applyViewport(binding);
171
+ },
172
+ };
173
+ target.setSize = binding.wrapped;
174
+ this.#targets.set(target, binding);
175
+ return binding;
176
+ });
177
+ const original = node.setSize;
178
+ const binding: IRetainedNode = {
179
+ node,
180
+ original,
181
+ targets: retained,
182
+ width: 0,
183
+ height: 0,
184
+ wrapped: (width, height) => {
185
+ validateSize(width, height);
186
+ binding.width = width;
187
+ binding.height = height;
188
+ if (!this.#active) {
189
+ original.call(node, width, height);
190
+ return;
191
+ }
192
+ this.#reserving = true;
193
+ try {
194
+ // Reserve for the quantized size the viewport can reach at scale 1. A node that floors
195
+ // each mip of a halving chain can otherwise leave a capacity one texel short of it.
196
+ original.call(node, quantize(width), quantize(height));
197
+ } finally {
198
+ this.#reserving = false;
199
+ }
200
+ original.call(node, quantize(width * this.#scale), quantize(height * this.#scale));
201
+ // PassNode copies its own viewport/scissor after target.setSize().
202
+ for (const target of retained) this.#applyViewport(target);
203
+ },
204
+ };
205
+ node.setSize = binding.wrapped;
206
+ this.#nodes.set(node, binding);
207
+ if (this.#active && this.#fullSize.x > 0) node.setSize(this.#fullSize.x, this.#fullSize.y);
208
+ }
209
+
210
+ textureView(texture: Texture): IResolutionTextureView | undefined {
211
+ for (const { target, view } of this.#targets.values()) {
212
+ if (target.textures.includes(texture) || target.depthTexture === texture) {
213
+ return view;
214
+ }
215
+ }
216
+ return undefined;
217
+ }
218
+
219
+ release(node: IResolutionSubrectNode): void {
220
+ const binding = this.#nodes.get(node);
221
+ if (!binding) return;
222
+ if (node.setSize === binding.wrapped) node.setSize = binding.original;
223
+ for (const { target, original, wrapped } of binding.targets) {
224
+ if (target.setSize === wrapped) target.setSize = original;
225
+ this.#targets.delete(target);
226
+ }
227
+ this.#nodes.delete(node);
228
+ }
229
+
230
+ dispose(): void {
231
+ if (this.#disposed) return;
232
+ this.deactivate();
233
+ this.#disposed = true;
234
+ for (const { node, original, wrapped } of this.#nodes.values()) {
235
+ if (node.setSize === wrapped) node.setSize = original;
236
+ }
237
+ for (const { target, original, wrapped } of this.#targets.values()) {
238
+ if (target.setSize === wrapped) target.setSize = original;
239
+ }
240
+ this.#nodes.clear();
241
+ this.#targets.clear();
242
+ }
243
+
244
+ #applyViewport({ target, view, width, height, viewWidth, viewHeight }: IRetainedTarget): void {
245
+ if (viewWidth > width || viewHeight > height || viewWidth <= 0 || viewHeight <= 0)
246
+ throw new Error("TN_RESOLUTION_SUBRECT: viewport exceeds retained capacity");
247
+ target.viewport.set(0, 0, viewWidth, viewHeight);
248
+ target.scissor.copy(target.viewport);
249
+ target.scissorTest = true;
250
+ view.viewFraction.set(viewWidth / width, viewHeight / height);
251
+ view.halfTexel.set(0.5 / width, 0.5 / height);
252
+ }
253
+ }
@@ -0,0 +1,442 @@
1
+ import type { BatchedMesh, Matrix4, Object3D, RenderTarget, SkinnedMesh } from "three";
2
+ import { context, mrt, output, velocity } from "three/tsl";
3
+ import type { MRTNode, Node, TextureNode } from "three/webgpu";
4
+
5
+ import {
6
+ disposeBatchedMeshVelocity,
7
+ ensureBatchedMeshVelocity,
8
+ setBatchedMeshPreviousMatrices,
9
+ } from "./batched-velocity.js";
10
+
11
+ /** The output name shared by the scene pass and temporal consumers. */
12
+ export const VELOCITY_OUTPUT_NAME = "velocity";
13
+
14
+ /**
15
+ * The pass surface needed to add and read the shared screen-space output.
16
+ *
17
+ * Keeping this structural lets the same seam work with Three's `PassNode` and a native adapter
18
+ * without making the game depend on either implementation.
19
+ */
20
+ export interface IVelocityRenderPass {
21
+ /** Physical attachments on Three passes; structural adapters may own them elsewhere. */
22
+ readonly renderTarget?: Pick<RenderTarget, "textures" | "dispose">;
23
+ getMRT(): MRTNode | null;
24
+ getTextureNode(name?: string): Node;
25
+ setMRT(value: MRTNode | null): unknown;
26
+ }
27
+
28
+ /** The symbol read by the patched Three.js instance accessor. */
29
+ export const VELOCITY_PREVIOUS_INSTANCE_MATRICES = Symbol.for(
30
+ "threenative.velocity.previousInstanceMatrices",
31
+ );
32
+ /** The symbol read by the patched Three.js velocity accessor for rigid history. */
33
+ export const VELOCITY_PREVIOUS_WORLD_MATRIX = Symbol.for(
34
+ "threenative.velocity.previousWorldMatrix",
35
+ );
36
+ /** The symbol read by the patched Three.js skinning accessor for bone history. */
37
+ export const VELOCITY_PREVIOUS_BONE_MATRICES = Symbol.for(
38
+ "threenative.velocity.previousBoneMatrices",
39
+ );
40
+
41
+ const VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE = Symbol.for(
42
+ "threenative.velocity.previousBindMatrixInverse",
43
+ );
44
+
45
+ interface IInstanceMatrixSource {
46
+ instanceMatrix?: { array: ArrayLike<number>; version?: number };
47
+ }
48
+
49
+ interface IBatchedMatrixSource {
50
+ isBatchedMesh?: boolean;
51
+ _matricesTexture?: { image?: { data?: ArrayLike<number> } } | null;
52
+ _previousMatricesTexture?: unknown;
53
+ }
54
+
55
+ interface IVelocityObject {
56
+ userData: Record<string, unknown>;
57
+ [VELOCITY_PREVIOUS_INSTANCE_MATRICES]?: Float32Array;
58
+ [VELOCITY_PREVIOUS_WORLD_MATRIX]?: Matrix4;
59
+ [VELOCITY_PREVIOUS_BONE_MATRICES]?: Float32Array;
60
+ [VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE]?: Matrix4;
61
+ }
62
+
63
+ interface ITrackedSkeleton {
64
+ boneMatrices: ArrayLike<number>;
65
+ update(): unknown;
66
+ }
67
+
68
+ interface IOriginalVelocityFlag {
69
+ readonly present: boolean;
70
+ readonly value: unknown;
71
+ }
72
+
73
+ /**
74
+ * Adds the velocity output to a scene pass without creating its texture until it is read.
75
+ *
76
+ * The existing outputs remain intact. A pass with no prior MRT receives the normal colour output
77
+ * as well, so adding history does not remove the frame's visible colour.
78
+ * @situation add a velocity target before a temporal stage consumes a scene pass
79
+ * @constraint call only when a temporal stage is active
80
+ */
81
+ export function ensureVelocityOutput(pass: IVelocityRenderPass): MRTNode {
82
+ const current = pass.getMRT();
83
+ if (current?.has(VELOCITY_OUTPUT_NAME)) return current;
84
+ const added = mrt({ [VELOCITY_OUTPUT_NAME]: velocity });
85
+ const next =
86
+ current === null ? mrt({ output, [VELOCITY_OUTPUT_NAME]: velocity }) : current.merge(added);
87
+ pass.setMRT(next);
88
+ return next;
89
+ }
90
+
91
+ /**
92
+ * Returns the velocity texture node after ensuring the pass writes it.
93
+ * @situation read screen-space motion for a temporal stage
94
+ */
95
+ export function velocityTexture(pass: IVelocityRenderPass): Node {
96
+ ensureVelocityOutput(pass);
97
+ const node = pass.getTextureNode(VELOCITY_OUTPUT_NAME);
98
+ const target = pass.renderTarget;
99
+ const texture = (node as TextureNode).value;
100
+ // PassNode caches texture nodes after a chain detaches their physical attachment.
101
+ if (target !== undefined && texture?.isTexture === true && !target.textures.includes(texture))
102
+ target.textures.push(texture);
103
+ return node;
104
+ }
105
+
106
+ /**
107
+ * Gives a composed TSL graph the velocity source used by temporal nodes.
108
+ * Plain game values are returned unchanged, which keeps the chain's diagnostic seam lightweight.
109
+ * @situation hand the provisioned velocity source through a composed temporal graph
110
+ */
111
+ export function withVelocityContext<T>(node: T, source: Node): T {
112
+ if (!isNode(node)) return node;
113
+ return context(node, { velocity: source }) as T;
114
+ }
115
+
116
+ /**
117
+ * How the render chain provisions the MRT velocity a temporal stage reads. The chain defaults to
118
+ * {@link mrtVelocity}; a host that provisions velocity another way (an engine whose scene pass owns
119
+ * the output) passes its own as `request.velocity.provision`.
120
+ */
121
+ export interface IVelocityProvision {
122
+ /** Ensures `pass` writes velocity and returns its texture node. */
123
+ texture(pass: IVelocityRenderPass): Node;
124
+ /** Hands the velocity source through the composed graph; `source` is the node `texture` returned. */
125
+ attach<T>(node: T, source: Node): T;
126
+ }
127
+
128
+ /**
129
+ * Core's own provision: the scene pass's MRT output, with the TSL `velocity` accessor as the context
130
+ * source temporal nodes jitter.
131
+ */
132
+ export function mrtVelocity(): IVelocityProvision {
133
+ return { texture: velocityTexture, attach: (node) => withVelocityContext(node, velocity) };
134
+ }
135
+
136
+ /**
137
+ * Captures instance matrices at the framework's pre-render boundary and enables previous data on
138
+ * every renderable in the graph. The previous snapshot is never the array the game writes next.
139
+ * @situation retain previous transforms for animated and instanced renderables
140
+ * @constraint call `update()` after gameplay writes and `commit()` after the render
141
+ */
142
+ export class VelocityTracker {
143
+ readonly #originalFlags = new Map<Object3D, IOriginalVelocityFlag>();
144
+ readonly #instanceSnapshots = new Map<Object3D, Float32Array>();
145
+ readonly #worldSnapshots = new Map<Object3D, Matrix4>();
146
+ readonly #bindInverseSnapshots = new Map<Object3D, Matrix4>();
147
+ readonly #boneSnapshots = new Map<ITrackedSkeleton, Float32Array>();
148
+ // The previous frame's buffers, written at the next commit. The snapshot scheduled for the frame
149
+ // that just rendered stays untouched until `update` replaces it, and steady state allocates nothing.
150
+ readonly #spareInstances = new Map<Object3D, Float32Array>();
151
+ readonly #spareWorlds = new Map<Object3D, Matrix4>();
152
+ readonly #spareBones = new Map<ITrackedSkeleton, Float32Array>();
153
+ /** `instanceMatrix.version` at the last commit: an unchanged mesh's history already equals it. */
154
+ readonly #instanceVersions = new Map<Object3D, number>();
155
+ readonly #ownedBatchedMeshes = new Set<BatchedMesh>();
156
+ readonly #active = new Set<Object3D>();
157
+ #updatedRoot: Object3D | undefined;
158
+
159
+ /** Schedule the committed snapshot that the current colour and velocity frame must read. */
160
+ update(root: Object3D): void {
161
+ this.#updatedRoot = root;
162
+ root.updateMatrixWorld(true);
163
+ const seen = new Set<Object3D>();
164
+ const seenSkeletons = new Set<ITrackedSkeleton>();
165
+ root.traverse((object) => {
166
+ if (!isVelocityRenderable(object)) return;
167
+ seen.add(object);
168
+ this.enable(object);
169
+ this.captureWorld(object);
170
+ const skeleton = getSkeleton(object);
171
+ if (skeleton !== undefined) {
172
+ if (!seenSkeletons.has(skeleton)) {
173
+ skeleton.update();
174
+ seenSkeletons.add(skeleton);
175
+ }
176
+ this.captureBones(object, skeleton);
177
+ (object as IVelocityObject)[VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE] =
178
+ this.#bindInverseSnapshots.get(object) ??
179
+ (object as SkinnedMesh).bindMatrixInverse.clone();
180
+ } else {
181
+ Reflect.deleteProperty(object, VELOCITY_PREVIOUS_BONE_MATRICES);
182
+ Reflect.deleteProperty(object, VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE);
183
+ this.#bindInverseSnapshots.delete(object);
184
+ }
185
+ this.captureInstance(object);
186
+ });
187
+
188
+ for (const object of this.#active) {
189
+ if (seen.has(object)) continue;
190
+ this.restore(object);
191
+ this.#active.delete(object);
192
+ }
193
+ for (const skeleton of this.#boneSnapshots.keys()) {
194
+ if (!seenSkeletons.has(skeleton)) {
195
+ this.#boneSnapshots.delete(skeleton);
196
+ this.#spareBones.delete(skeleton);
197
+ }
198
+ }
199
+ for (const object of seen) this.#active.add(object);
200
+ }
201
+
202
+ /** Commit transforms after the renderer has consumed the scheduled velocity frame. */
203
+ commit(root: Object3D): void {
204
+ if (this.#updatedRoot !== root) return;
205
+ root.updateMatrixWorld(true);
206
+ const seen = new Set<Object3D>();
207
+ const seenSkeletons = new Set<ITrackedSkeleton>();
208
+ root.traverse((object) => {
209
+ if (!this.#active.has(object) || !isVelocityRenderable(object)) return;
210
+ seen.add(object);
211
+ const spare = this.#spareWorlds.get(object);
212
+ const scheduled = this.#worldSnapshots.get(object);
213
+ if (scheduled) this.#spareWorlds.set(object, scheduled);
214
+ this.#worldSnapshots.set(
215
+ object,
216
+ spare ? spare.copy(object.matrixWorld) : object.matrixWorld.clone(),
217
+ );
218
+ const skeleton = getSkeleton(object);
219
+ if (skeleton !== undefined) {
220
+ this.#bindInverseSnapshots.set(object, (object as SkinnedMesh).bindMatrixInverse.clone());
221
+ if (!seenSkeletons.has(skeleton)) {
222
+ skeleton.update();
223
+ seenSkeletons.add(skeleton);
224
+ rotate(this.#boneSnapshots, this.#spareBones, skeleton, skeleton.boneMatrices);
225
+ }
226
+ }
227
+ this.commitInstance(object);
228
+ });
229
+ for (const object of this.#active) {
230
+ if (seen.has(object)) continue;
231
+ this.restore(object);
232
+ this.#active.delete(object);
233
+ }
234
+ }
235
+
236
+ /** Restore caller-owned flags and release all retained frame snapshots. */
237
+ clear(): void {
238
+ for (const object of this.#active) this.restore(object);
239
+ this.#active.clear();
240
+ this.#originalFlags.clear();
241
+ this.#instanceSnapshots.clear();
242
+ this.#worldSnapshots.clear();
243
+ this.#bindInverseSnapshots.clear();
244
+ this.#boneSnapshots.clear();
245
+ this.#spareInstances.clear();
246
+ this.#instanceVersions.clear();
247
+ this.#spareWorlds.clear();
248
+ this.#spareBones.clear();
249
+ this.#updatedRoot = undefined;
250
+ }
251
+
252
+ private enable(object: Object3D): void {
253
+ if (!this.#originalFlags.has(object)) {
254
+ this.#originalFlags.set(object, {
255
+ present: Object.hasOwn(object.userData, "useVelocity"),
256
+ value: object.userData.useVelocity,
257
+ });
258
+ }
259
+ object.userData.useVelocity = true;
260
+ }
261
+
262
+ private captureWorld(object: Object3D): void {
263
+ const previous = this.#worldSnapshots.get(object);
264
+ const scheduledPrevious = previous ?? object.matrixWorld.clone();
265
+ (object as IVelocityObject)[VELOCITY_PREVIOUS_WORLD_MATRIX] = scheduledPrevious;
266
+ }
267
+
268
+ private captureBones(object: Object3D, skeleton: ITrackedSkeleton): void {
269
+ const current = skeleton.boneMatrices;
270
+ const previous = this.#boneSnapshots.get(skeleton);
271
+ const scheduledPrevious = previous?.length === current.length ? previous : copyArray(current);
272
+ (object as IVelocityObject)[VELOCITY_PREVIOUS_BONE_MATRICES] = scheduledPrevious;
273
+ }
274
+
275
+ private captureInstance(object: Object3D): void {
276
+ const batch = getBatchedMesh(object);
277
+ if (batch !== undefined) {
278
+ this.captureBatch(object, batch);
279
+ return;
280
+ }
281
+ if ((object as Object3D & { isInstancedMesh?: boolean }).isInstancedMesh !== true) return;
282
+ const source = object as Object3D & IInstanceMatrixSource;
283
+ const current = source.instanceMatrix?.array;
284
+ if (current === undefined) return;
285
+
286
+ const previous = this.#instanceSnapshots.get(object);
287
+ const scheduledPrevious = previous?.length === current.length ? previous : copyArray(current);
288
+ (object as IVelocityObject)[VELOCITY_PREVIOUS_INSTANCE_MATRICES] = scheduledPrevious;
289
+ }
290
+
291
+ private captureBatch(object: Object3D, batch: BatchedMesh): void {
292
+ const current = batchedMatrixData(batch);
293
+ if (current === undefined) return;
294
+ if (!hasBatchedPreviousMatrices(batch)) {
295
+ ensureBatchedMeshVelocity(batch);
296
+ this.#ownedBatchedMeshes.add(batch);
297
+ }
298
+
299
+ const previous = this.#instanceSnapshots.get(object);
300
+ const scheduledPrevious = previous?.length === current.length ? previous : copyArray(current);
301
+ (object as IVelocityObject)[VELOCITY_PREVIOUS_INSTANCE_MATRICES] = scheduledPrevious;
302
+ // A material-batching projection already owns and advances this texture per sub-draw. Direct
303
+ // tracker users reach the branch above that creates it, so only those textures are written
304
+ // here; two owners would race and erase the projection's source-to-slot history.
305
+ if (this.#ownedBatchedMeshes.has(batch))
306
+ setBatchedMeshPreviousMatrices(batch, scheduledPrevious);
307
+ }
308
+
309
+ private commitInstance(object: Object3D): void {
310
+ const batch = getBatchedMesh(object);
311
+ const matrices =
312
+ batch === undefined ? (object as Object3D & IInstanceMatrixSource).instanceMatrix : undefined;
313
+ const current = batch === undefined ? matrices?.array : batchedMatrixData(batch);
314
+ if (current === undefined) return;
315
+ // A static forest is nearly every instance: copying 218,809 unchanged matrices each frame was
316
+ // the remaining per-frame cost. Same version means the scheduled history is already current.
317
+ const version = matrices?.version;
318
+ if (
319
+ version !== undefined &&
320
+ this.#instanceVersions.get(object) === version &&
321
+ this.#instanceSnapshots.get(object)?.length === current.length
322
+ )
323
+ return;
324
+ rotate(this.#instanceSnapshots, this.#spareInstances, object, current);
325
+ if (version !== undefined) this.#instanceVersions.set(object, version);
326
+ else this.#instanceVersions.delete(object);
327
+ }
328
+
329
+ private restore(object: Object3D): void {
330
+ const typed = object as IVelocityObject;
331
+ const original = this.#originalFlags.get(object);
332
+ if (original === undefined || !original.present)
333
+ Reflect.deleteProperty(typed.userData, "useVelocity");
334
+ else typed.userData.useVelocity = original.value;
335
+ const batch = getBatchedMesh(object);
336
+ if (batch !== undefined && this.#ownedBatchedMeshes.delete(batch))
337
+ disposeBatchedMeshVelocity(batch);
338
+ Reflect.deleteProperty(typed, VELOCITY_PREVIOUS_INSTANCE_MATRICES);
339
+ Reflect.deleteProperty(typed, VELOCITY_PREVIOUS_WORLD_MATRIX);
340
+ Reflect.deleteProperty(typed, VELOCITY_PREVIOUS_BONE_MATRICES);
341
+ Reflect.deleteProperty(typed, VELOCITY_PREVIOUS_BIND_MATRIX_INVERSE);
342
+ this.#originalFlags.delete(object);
343
+ this.#instanceSnapshots.delete(object);
344
+ this.#worldSnapshots.delete(object);
345
+ this.#spareInstances.delete(object);
346
+ this.#instanceVersions.delete(object);
347
+ this.#spareWorlds.delete(object);
348
+ this.#bindInverseSnapshots.delete(object);
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Reads the scheduled previous instance/sub-draw array for conformance tests and renderer adapters.
354
+ * @situation inspect the previous instance frame at a renderer adapter boundary
355
+ */
356
+ export function readVelocityPreviousMatrices(object: Object3D): Float32Array | undefined {
357
+ return (object as IVelocityObject)[VELOCITY_PREVIOUS_INSTANCE_MATRICES];
358
+ }
359
+
360
+ /**
361
+ * Reads the scheduled previous world matrix for conformance tests and renderer adapters.
362
+ * @situation inspect the previous rigid transform at a renderer adapter boundary
363
+ */
364
+ export function readVelocityPreviousWorldMatrix(object: Object3D): Matrix4 | undefined {
365
+ return (object as IVelocityObject)[VELOCITY_PREVIOUS_WORLD_MATRIX];
366
+ }
367
+
368
+ /**
369
+ * Reads the scheduled previous bone array for conformance tests and renderer adapters.
370
+ * @situation inspect the previous skinned pose at a renderer adapter boundary
371
+ */
372
+ export function readVelocityPreviousBoneMatrices(object: Object3D): Float32Array | undefined {
373
+ return (object as IVelocityObject)[VELOCITY_PREVIOUS_BONE_MATRICES];
374
+ }
375
+
376
+ function isVelocityRenderable(object: Object3D): boolean {
377
+ return (
378
+ (object as { isMesh?: boolean }).isMesh === true ||
379
+ (object as { isLine?: boolean }).isLine === true ||
380
+ (object as { isPoints?: boolean }).isPoints === true ||
381
+ (object as { isSprite?: boolean }).isSprite === true
382
+ );
383
+ }
384
+
385
+ function getSkeleton(object: Object3D): ITrackedSkeleton | undefined {
386
+ const candidate = object as Object3D & {
387
+ isSkinnedMesh?: boolean;
388
+ skeleton?: ITrackedSkeleton;
389
+ };
390
+ return candidate.isSkinnedMesh === true ? candidate.skeleton : undefined;
391
+ }
392
+
393
+ function getBatchedMesh(object: Object3D): BatchedMesh | undefined {
394
+ return (object as IBatchedMatrixSource).isBatchedMesh === true
395
+ ? (object as BatchedMesh)
396
+ : undefined;
397
+ }
398
+
399
+ function batchedMatrixData(mesh: BatchedMesh): ArrayLike<number> | undefined {
400
+ return (mesh as BatchedMesh & IBatchedMatrixSource)._matricesTexture?.image?.data;
401
+ }
402
+
403
+ function hasBatchedPreviousMatrices(mesh: BatchedMesh): boolean {
404
+ return (mesh as BatchedMesh & IBatchedMatrixSource)._previousMatricesTexture !== undefined;
405
+ }
406
+
407
+ function isNode(value: unknown): value is Node {
408
+ return (
409
+ typeof value === "object" && value !== null && (value as { isNode?: boolean }).isNode === true
410
+ );
411
+ }
412
+
413
+ function copyArray(source: ArrayLike<number>): Float32Array {
414
+ const copy = new Float32Array(source.length);
415
+ copy.set(source);
416
+ return copy;
417
+ }
418
+
419
+ /**
420
+ * The committed history, written into last frame's buffer when the length still matches. Three
421
+ * copies the scheduled history into its own attribute at draw time, so reuse is safe; a fresh array
422
+ * per instanced mesh per frame was ~14 MB of garbage a frame for 218,809 instances and produced
423
+ * multi-second collector stalls.
424
+ */
425
+ /** Commit into last frame's spare buffer and keep the scheduled one as the next spare. */
426
+ function rotate<K>(
427
+ snapshots: Map<K, Float32Array>,
428
+ spares: Map<K, Float32Array>,
429
+ key: K,
430
+ source: ArrayLike<number>,
431
+ ): void {
432
+ const scheduled = snapshots.get(key);
433
+ const next = copyInto(spares.get(key), source);
434
+ if (scheduled) spares.set(key, scheduled);
435
+ snapshots.set(key, next);
436
+ }
437
+
438
+ function copyInto(target: Float32Array | undefined, source: ArrayLike<number>): Float32Array {
439
+ if (target === undefined || target.length !== source.length) return copyArray(source);
440
+ target.set(source);
441
+ return target;
442
+ }