@threenative/core 0.3.4 → 0.3.6

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-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -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 +57 -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 +2408 -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 +574 -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 +850 -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,176 @@
1
+ import type { Camera, Object3D } from "three";
2
+ import type { IFrameBudgetSimulation, IFrameBudgetWindow } from "./frame-budget.js";
3
+ import { type IBudgetCandidate, ParticleSignificance } from "./particle-significance.js";
4
+ import type { IRendererLike } from "./renderer.js";
5
+
6
+ /**
7
+ * The lifecycle contract for a game-owned GPU simulation.
8
+ *
9
+ * A compute-driven object owns its kernels, buffers, and appearance. The framework only attaches
10
+ * the active renderer, warms the kernels before the world is shown, dispatches process calls at
11
+ * the object's declared cadence, and releases the object when its scene ends.
12
+ */
13
+ export interface IComputeDriven {
14
+ /** Kernels to compile before the world is shown. Read once, at attach. */
15
+ readonly warmupNodes: readonly unknown[];
16
+ attachRenderer(renderer: IRendererLike): void;
17
+ /**
18
+ * The loop phase that dispatches `process`. Defaults to fixed-step; render cadence preserves the
19
+ * existing behavior of consumers whose simulation is intentionally tied to presentation.
20
+ */
21
+ readonly processCadence?: "fixed" | "render";
22
+ /** Render admission needed to settle a startup hold, after initial compilation. */
23
+ readonly processDuringStartup?: boolean;
24
+ /**
25
+ * Yield simulation work in order of projected size when measured GPU compute exceeds budget.
26
+ * @situation Let the render loop pause low-significance particle emitters under GPU pressure.
27
+ * @constraint Only live render-cadence objects participate; missing measurements never shed.
28
+ */
29
+ readonly budget?: IBudgetCandidate;
30
+ /**
31
+ * Dispatched once per fixed step, in scene-add order unless render cadence is declared.
32
+ *
33
+ * `camera` is the frame's render camera, handed over at render cadence so a consumer that culls by
34
+ * the view — a streamed world narrowing its instanced windows to what the frustum covers — can do
35
+ * it from the driver that runs every frame rather than from a draw three will not submit. An
36
+ * implementation that does not need it simply declares one parameter.
37
+ *
38
+ * `covered` is true while the startup cover hides the world and readiness is still pending, so
39
+ * a streamed world may spend more of the frame admitting the spawn it is waiting on.
40
+ */
41
+ process(
42
+ renderer: IRendererLike,
43
+ camera?: Camera,
44
+ covered?: boolean,
45
+ view?: undefined,
46
+ simulatedSeconds?: number,
47
+ ): void;
48
+ detach(): void;
49
+ readonly released: boolean;
50
+ }
51
+
52
+ interface IComputeDrivenEntry {
53
+ readonly object: Object3D;
54
+ readonly driven: IComputeDriven;
55
+ readonly warmupNodes: readonly unknown[];
56
+ }
57
+
58
+ /** The ordered registry used by the game loop for all compute-driven scene objects. */
59
+ export class ComputeDrivenRegistry {
60
+ #entries = new Map<IComputeDriven, IComputeDrivenEntry>();
61
+ readonly #significance = new ParticleSignificance();
62
+
63
+ get size(): number {
64
+ return this.#entries.size;
65
+ }
66
+
67
+ /** Attach and remember one object. Re-adding the same object is idempotent. */
68
+ add(object: Object3D & IComputeDriven, renderer: IRendererLike): void {
69
+ const driven = object;
70
+ if (this.#entries.has(driven)) return;
71
+ const warmupNodes = [...driven.warmupNodes];
72
+ driven.attachRenderer(renderer);
73
+ this.#entries.set(driven, { object, driven, warmupNodes });
74
+ }
75
+
76
+ /** Release one object without disturbing the order of the remaining objects. */
77
+ remove(driven: IComputeDriven): void {
78
+ const entry = this.#entries.get(driven);
79
+ if (entry === undefined) return;
80
+ this.#entries.delete(driven);
81
+ if (!entry.driven.released) entry.driven.detach();
82
+ }
83
+
84
+ /** Kernels in the same order as their objects were added to the scene. */
85
+ get warmupNodes(): readonly unknown[] {
86
+ return [...this.#entries.values()].flatMap((entry) => entry.warmupNodes);
87
+ }
88
+
89
+ /** Dispatch fixed-step objects once; detached scene children are released before dispatch. */
90
+ process(renderer: IRendererLike): void {
91
+ this.#process(renderer, "fixed");
92
+ }
93
+
94
+ /** Forward a measured frame window to the particle budget coordinator. */
95
+ observeBudget(
96
+ window: Pick<
97
+ IFrameBudgetWindow,
98
+ "frames" | "presented" | "gpuMs" | "gpuCompute" | "targetFps" | "simulatedSeconds"
99
+ >,
100
+ ): void {
101
+ this.#significance.observe(window);
102
+ }
103
+
104
+ /**
105
+ * Dispatch render-cadence objects once with the frame's render camera; detached scene children are
106
+ * released before dispatch.
107
+ */
108
+ processRender(
109
+ renderer: IRendererLike,
110
+ camera?: Camera,
111
+ startupOnly = false,
112
+ simulation?: IFrameBudgetSimulation,
113
+ ): void {
114
+ const simulatedSeconds =
115
+ simulation === undefined ? undefined : simulation.tick() * simulation.step;
116
+ if (camera !== undefined) {
117
+ const candidates: IBudgetCandidate[] = [];
118
+ for (const { object, driven } of this.#entries.values()) {
119
+ if (
120
+ !driven.released &&
121
+ object.parent !== null &&
122
+ driven.processCadence === "render" &&
123
+ driven.budget !== undefined
124
+ )
125
+ candidates.push(driven.budget);
126
+ }
127
+ // Wall time is only for callers without a loop clock.
128
+ this.#significance.apply(candidates, camera, simulatedSeconds ?? performance.now() / 1000);
129
+ }
130
+ this.#process(renderer, "render", camera, startupOnly, simulatedSeconds);
131
+ }
132
+
133
+ #process(
134
+ renderer: IRendererLike,
135
+ cadence: "fixed" | "render",
136
+ camera?: Camera,
137
+ startupOnly = false,
138
+ simulatedSeconds?: number,
139
+ ): void {
140
+ for (const entry of [...this.#entries.values()]) {
141
+ if (entry.driven.released || entry.object.parent === null) {
142
+ this.remove(entry.driven);
143
+ continue;
144
+ }
145
+ if ((entry.driven.processCadence ?? "fixed") !== cadence) continue;
146
+ if (startupOnly && entry.driven.processDuringStartup !== true) continue;
147
+ // TerrainTiles owns the fourth argument for its LOD view.
148
+ entry.driven.process(renderer, camera, startupOnly, undefined, simulatedSeconds);
149
+ }
150
+ }
151
+
152
+ /** Release every registered object, continuing after a failure so no resource is stranded. */
153
+ clear(): void {
154
+ const failures: unknown[] = [];
155
+ for (const driven of [...this.#entries.keys()]) {
156
+ try {
157
+ this.remove(driven);
158
+ } catch (error) {
159
+ failures.push(error);
160
+ }
161
+ }
162
+ if (failures.length > 0) throw failures[0];
163
+ }
164
+ }
165
+
166
+ export function isComputeDriven(value: unknown): value is IComputeDriven {
167
+ if (typeof value !== "object" || value === null) return false;
168
+ const candidate = value as Partial<IComputeDriven>;
169
+ return (
170
+ Array.isArray(candidate.warmupNodes) &&
171
+ typeof candidate.attachRenderer === "function" &&
172
+ typeof candidate.process === "function" &&
173
+ typeof candidate.detach === "function" &&
174
+ typeof candidate.released === "boolean"
175
+ );
176
+ }
@@ -0,0 +1,318 @@
1
+ /** Exact per-call timings from Three 0.185.1's compute pool; Three owns all GPU resources. */
2
+ export interface IComputeTimingSample {
3
+ readonly call: number;
4
+ readonly uid: string;
5
+ readonly gpuMs: number;
6
+ }
7
+ export interface IComputeTimingReceipt {
8
+ readonly generation: object;
9
+ readonly calls: readonly number[];
10
+ /** Incomplete membership is absent; a completed receipt can be consumed only once. */
11
+ read(): readonly IComputeTimingSample[] | undefined;
12
+ }
13
+ interface IQueryPool {
14
+ readonly queryOffsets: Map<string, number>;
15
+ readonly timestamps: Map<string, number>;
16
+ readonly maxQueries: number;
17
+ readonly currentQueryIndex: number;
18
+ readonly isDisposed: boolean;
19
+ readonly trackTimestamp: boolean;
20
+ }
21
+ interface IComputeSource {
22
+ readonly info: { frame: number };
23
+ readonly backend: {
24
+ readonly isWebGPUBackend: true;
25
+ readonly device: object;
26
+ trackTimestamp: boolean;
27
+ readonly timestampQueryPool?: { readonly compute?: IQueryPool | null };
28
+ };
29
+ compute(node: unknown): unknown;
30
+ }
31
+ function object(value: unknown): value is Record<string, unknown> {
32
+ return typeof value === "object" && value !== null;
33
+ }
34
+ function thenable(value: unknown): boolean {
35
+ return (object(value) || typeof value === "function") && "then" in value;
36
+ }
37
+ function source(value: unknown): IComputeSource {
38
+ if (!object(value) || !object(value.backend) || !object(value.info))
39
+ throw new Error("TN_COMPUTE_TIMING_UNSUPPORTED: initialized renderer fields are absent.");
40
+ const backend = value.backend;
41
+ const device = backend.device;
42
+ if (
43
+ backend.isWebGPUBackend !== true ||
44
+ typeof backend.trackTimestamp !== "boolean" ||
45
+ !object(device) ||
46
+ !object(device.features) ||
47
+ typeof device.features.has !== "function" ||
48
+ device.features.has("timestamp-query") !== true ||
49
+ typeof value.compute !== "function" ||
50
+ !Number.isSafeInteger(value.info.frame) ||
51
+ Number(value.info.frame) < 0
52
+ )
53
+ throw new Error(
54
+ "TN_COMPUTE_TIMING_UNSUPPORTED: initialized WebGPU timestamp queries are required.",
55
+ );
56
+ // quality-allow: the guard above proved every field of IComputeSource that the renderer needs.
57
+ return value as unknown as IComputeSource;
58
+ }
59
+ function poolOf(raw: IComputeSource): IQueryPool | undefined {
60
+ const pool = raw.backend.timestampQueryPool?.compute;
61
+ if (pool === undefined || pool === null) return undefined;
62
+ if (
63
+ !(pool.queryOffsets instanceof Map) ||
64
+ !(pool.timestamps instanceof Map) ||
65
+ typeof pool.isDisposed !== "boolean" ||
66
+ typeof pool.trackTimestamp !== "boolean" ||
67
+ !Number.isSafeInteger(pool.maxQueries) ||
68
+ pool.maxQueries < 2 ||
69
+ pool.maxQueries % 2 !== 0 ||
70
+ !Number.isSafeInteger(pool.currentQueryIndex) ||
71
+ pool.currentQueryIndex < 0 ||
72
+ pool.currentQueryIndex > pool.maxQueries ||
73
+ pool.currentQueryIndex % 2 !== 0
74
+ )
75
+ throw new Error(
76
+ "TN_COMPUTE_TIMING_UNSUPPORTED: compute query maps and capacity are unavailable.",
77
+ );
78
+ return pool;
79
+ }
80
+ function checkQueryCapacity(pool: IQueryPool | undefined): void {
81
+ if (pool === undefined) return; // Three allocates its first pool lazily.
82
+ if (pool.isDisposed) throw new Error("TN_COMPUTE_TIMING_STALE: compute pool retired.");
83
+ if (!pool.trackTimestamp)
84
+ throw new Error("TN_COMPUTE_TIMING_UNSUPPORTED: compute pool tracking disabled.");
85
+ if (pool.currentQueryIndex + 2 > pool.maxQueries)
86
+ throw new Error(`TN_COMPUTE_TIMING_CAPACITY: query pair exceeds ${pool.maxQueries}.`);
87
+ }
88
+ function allocated(
89
+ raw: IComputeSource,
90
+ before: ReadonlySet<string>,
91
+ call: number,
92
+ ): { pool: IQueryPool; uid: string } {
93
+ const pool = poolOf(raw);
94
+ if (pool === undefined) throw new Error("TN_COMPUTE_TIMING_MISSING: no compute pool allocated.");
95
+ const added = [...pool.queryOffsets.keys()].filter((uid) => !before.has(uid));
96
+ const uid = added[0];
97
+ const offset = uid === undefined ? undefined : pool.queryOffsets.get(uid);
98
+ if (
99
+ added.length !== 1 ||
100
+ typeof uid !== "string" ||
101
+ !uid.endsWith(`:f${call}`) ||
102
+ !Number.isSafeInteger(offset) ||
103
+ Number(offset) < 0 ||
104
+ Number(offset) % 2 !== 0 ||
105
+ Number(offset) + 2 > pool.maxQueries ||
106
+ raw.info.frame !== call
107
+ )
108
+ throw new Error(
109
+ `TN_COMPUTE_TIMING_MISSING: call ${call} allocated ${added.length} valid query UIDs.`,
110
+ );
111
+ if (pool.timestamps.has(uid))
112
+ throw new Error("TN_COMPUTE_TIMING_DUPLICATE: query UID already resolved.");
113
+ return { pool, uid };
114
+ }
115
+ function maximumCalls(operation: unknown, options: unknown): number {
116
+ if (
117
+ typeof operation !== "function" ||
118
+ !object(options) ||
119
+ Array.isArray(options) ||
120
+ Object.keys(options).some((key) => key !== "maxCalls")
121
+ )
122
+ throw new Error(
123
+ "TN_COMPUTE_TIMING_CAPACITY: operation and named maxCalls options are required.",
124
+ );
125
+ const maximum = options.maxCalls === undefined ? 64 : options.maxCalls;
126
+ if (typeof maximum !== "number" || !Number.isSafeInteger(maximum) || maximum < 1 || maximum > 64)
127
+ throw new Error(`TN_COMPUTE_TIMING_CAPACITY: maxCalls ${String(maximum)}; expected 1..64.`);
128
+ return maximum;
129
+ }
130
+ function restore(
131
+ raw: IComputeSource,
132
+ descriptor: PropertyDescriptor | undefined,
133
+ tracking: boolean,
134
+ ): unknown[] {
135
+ const errors: unknown[] = [];
136
+ try {
137
+ const restored =
138
+ descriptor === undefined
139
+ ? Reflect.deleteProperty(raw, "compute")
140
+ : Reflect.defineProperty(raw, "compute", descriptor);
141
+ if (!restored) throw new Error("Original compute descriptor was not restored.");
142
+ } catch (error) {
143
+ errors.push(error);
144
+ }
145
+ try {
146
+ raw.backend.trackTimestamp = tracking;
147
+ } catch (error) {
148
+ errors.push(error);
149
+ }
150
+ return errors;
151
+ }
152
+
153
+ /** Lazy and opt-in: ordinary compute calls receive no wrapper, allocation or extra branch. */
154
+ export class ComputeTimingScopes {
155
+ readonly #readSource: () => unknown;
156
+ readonly #generation = Object.freeze({});
157
+ #disposed = false;
158
+ #active = false;
159
+ #failed = false;
160
+ #failure: unknown;
161
+ #raw: IComputeSource | undefined;
162
+ #device: object | undefined;
163
+ #pool: IQueryPool | undefined;
164
+ #offsets: Map<string, number> | undefined;
165
+ #timestamps: Map<string, number> | undefined;
166
+ #lastCall = -1;
167
+
168
+ constructor(readSource: () => unknown) {
169
+ this.#readSource = readSource;
170
+ }
171
+
172
+ #bindPool(pool: IQueryPool | undefined): void {
173
+ if (this.#pool !== undefined || pool === undefined) return;
174
+ this.#pool = pool;
175
+ this.#offsets = pool.queryOffsets;
176
+ this.#timestamps = pool.timestamps;
177
+ }
178
+ #current(raw: IComputeSource): void {
179
+ if (
180
+ this.#disposed ||
181
+ this.#readSource() !== raw ||
182
+ raw !== this.#raw ||
183
+ raw.backend.device !== this.#device ||
184
+ // Three's own animation loop rewrites info.frame lower every rAF; per-call order is checked in #compute.
185
+ !Number.isSafeInteger(raw.info.frame)
186
+ )
187
+ throw new Error("TN_COMPUTE_TIMING_STALE: renderer, device or compute frame changed.");
188
+ const pool = poolOf(raw);
189
+ if (
190
+ this.#pool !== undefined &&
191
+ (pool !== this.#pool ||
192
+ pool.isDisposed ||
193
+ pool.queryOffsets !== this.#offsets ||
194
+ pool.timestamps !== this.#timestamps)
195
+ )
196
+ throw new Error("TN_COMPUTE_TIMING_STALE: compute pool or query maps changed.");
197
+ }
198
+ #compute(
199
+ raw: IComputeSource,
200
+ original: IComputeSource["compute"],
201
+ node: unknown,
202
+ captured: { call: number; uid: string }[],
203
+ maxCalls: number,
204
+ ): unknown {
205
+ this.#current(raw);
206
+ if (captured.length >= maxCalls)
207
+ throw new Error(`TN_COMPUTE_TIMING_CAPACITY: compute calls exceed ${maxCalls}.`);
208
+ const pool = poolOf(raw);
209
+ checkQueryCapacity(pool); // Three's exhausted allocator otherwise passes null into timestampWrites.
210
+ const call = raw.info.frame;
211
+ if (call <= this.#lastCall)
212
+ throw new Error("TN_COMPUTE_TIMING_STALE: compute call frame was reused.");
213
+ const before = new Set(pool?.queryOffsets.keys());
214
+ this.#lastCall = call; // Reserve it even if the dispatch throws and its caller catches the failure.
215
+ raw.backend.trackTimestamp = true; // Core's sampler has already run for this call.
216
+ const result = original.call(raw, node);
217
+ if (thenable(result))
218
+ throw new Error("TN_COMPUTE_TIMING_ASYNC: compute must already be warmed.");
219
+ const query = allocated(raw, before, call);
220
+ this.#bindPool(query.pool);
221
+ this.#current(raw);
222
+ captured.push({ call, uid: query.uid });
223
+ return result;
224
+ }
225
+
226
+ capture(
227
+ operation: () => unknown,
228
+ options: { readonly maxCalls?: number } = {},
229
+ ): IComputeTimingReceipt {
230
+ if (this.#disposed)
231
+ throw new Error("TN_COMPUTE_TIMING_STALE: renderer timing generation retired.");
232
+ if (this.#active) {
233
+ this.#failed = true;
234
+ this.#failure = new Error("TN_COMPUTE_TIMING_NESTED: synchronous scopes cannot nest.");
235
+ throw this.#failure;
236
+ }
237
+ const maxCalls = maximumCalls(operation, options);
238
+ const raw = source(this.#readSource());
239
+ this.#raw ??= raw;
240
+ this.#device ??= raw.backend.device;
241
+ this.#bindPool(poolOf(raw));
242
+ this.#current(raw);
243
+ const original = raw.compute;
244
+ const descriptor = Object.getOwnPropertyDescriptor(raw, "compute");
245
+ const tracking = raw.backend.trackTimestamp;
246
+ const captured: { call: number; uid: string }[] = [];
247
+ const token = { active: true };
248
+ let installed = false;
249
+ let failed = false;
250
+ let failure: unknown;
251
+ let cleanup: unknown[] = [];
252
+ this.#active = true;
253
+ this.#failed = false;
254
+ this.#failure = undefined;
255
+ try {
256
+ installed = Reflect.set(raw, "compute", (node: unknown) => {
257
+ if (!token.active) throw new Error("TN_COMPUTE_TIMING_STALE: capture scope has ended.");
258
+ try {
259
+ return this.#compute(raw, original, node, captured, maxCalls);
260
+ } catch (error) {
261
+ this.#failed = true;
262
+ this.#failure = error;
263
+ throw error;
264
+ }
265
+ });
266
+ if (!installed || raw.compute === original)
267
+ throw new Error("TN_COMPUTE_TIMING_UNSUPPORTED: compute method cannot be scoped.");
268
+ const result = operation();
269
+ if (thenable(result))
270
+ throw new Error("TN_COMPUTE_TIMING_ASYNC: operation must complete synchronously.");
271
+ if (this.#failed) throw this.#failure;
272
+ this.#current(raw);
273
+ if (captured.length === 0)
274
+ throw new Error("TN_COMPUTE_TIMING_MISSING: scope dispatched no compute calls.");
275
+ } catch (error) {
276
+ failed = true;
277
+ failure = error;
278
+ } finally {
279
+ token.active = false;
280
+ if (installed) cleanup = restore(raw, descriptor, tracking);
281
+ this.#active = false;
282
+ if (cleanup.length > 0) this.#disposed = true; // Any retained wrapper now rejects before dispatch.
283
+ }
284
+ if (cleanup.length > 0)
285
+ throw new AggregateError(
286
+ failed ? [failure, ...cleanup] : cleanup,
287
+ "TN_COMPUTE_TIMING_RESTORE: timing generation retired after restoration failed.",
288
+ );
289
+ if (failed) throw failure;
290
+ let consumed = false;
291
+ const queries = Object.freeze(captured.map((sample) => Object.freeze(sample)));
292
+ return Object.freeze({
293
+ generation: this.#generation,
294
+ calls: Object.freeze(queries.map((sample) => sample.call)),
295
+ read: (): readonly IComputeTimingSample[] | undefined => {
296
+ this.#current(raw);
297
+ if (consumed) throw new Error("TN_COMPUTE_TIMING_DUPLICATE: receipt already consumed.");
298
+ const pool = this.#pool;
299
+ if (pool === undefined)
300
+ throw new Error("TN_COMPUTE_TIMING_MISSING: compute query pool is absent.");
301
+ const samples: IComputeTimingSample[] = [];
302
+ for (const sample of queries) {
303
+ if (!pool.timestamps.has(sample.uid)) return undefined;
304
+ const gpuMs = pool.timestamps.get(sample.uid);
305
+ if (typeof gpuMs !== "number" || !Number.isFinite(gpuMs) || gpuMs <= 0)
306
+ throw new Error(`TN_COMPUTE_TIMING_INVALID: query ${sample.uid} duration ${gpuMs}.`);
307
+ samples.push(Object.freeze({ ...sample, gpuMs }));
308
+ }
309
+ consumed = true;
310
+ return Object.freeze(samples);
311
+ },
312
+ });
313
+ }
314
+
315
+ dispose(): void {
316
+ this.#disposed = true;
317
+ }
318
+ }