@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,160 @@
1
+ /**
2
+ * Which family of GPU the adapter is: the start point of the look and of the pixel count.
3
+ *
4
+ * A fact about the machine, read from the four `adapter.info` fields and nothing else. What a
5
+ * class *looks like* is the game's own decision (`src/render/quality.ts`); this file only names the
6
+ * class, so a Mali-G52 phone and a Mali-G715 phone stop sharing one `mobile` flag.
7
+ *
8
+ * Measurement outranks this table. The first eligible frame-budget window moves the tier and the
9
+ * scale whichever class started them, so a wrong row costs windows, never a stuck look.
10
+ */
11
+
12
+ export type GpuClass =
13
+ | "software"
14
+ | "mobile-low"
15
+ | "mobile-mid"
16
+ | "mobile-high"
17
+ | "integrated"
18
+ | "discrete"
19
+ | "unknown";
20
+
21
+ /** The four fields WebGPU's `adapter.info` carries. A field the platform omits is the empty string. */
22
+ export interface IGpuAdapterFields {
23
+ readonly architecture: string;
24
+ readonly description: string;
25
+ readonly device: string;
26
+ readonly vendor: string;
27
+ }
28
+
29
+ export interface IGpuClassification {
30
+ readonly class: GpuClass;
31
+ /** The first rule that matched, or `none` when no rule did. */
32
+ readonly rule: string;
33
+ readonly fields: IGpuAdapterFields;
34
+ }
35
+
36
+ /** The marker printed once per launch, beside the class, the rule and the raw fields. */
37
+ export const GPU_CLASS_MARKER = "TN_GPU_CLASS";
38
+
39
+ /**
40
+ * Which `adapter.info` field value names a CPU rasteriser.
41
+ *
42
+ * Every field is searched because which one carries the giveaway depends on the platform: Linux
43
+ * Dawn puts `swiftshader` in `architecture`, Mesa reports `llvmpipe` in `description`, and a
44
+ * headless Windows run says `Microsoft Basic Render Driver` in `device`.
45
+ */
46
+ export const SOFTWARE_ADAPTER =
47
+ /swiftshader|llvmpipe|lavapipe|softwarerasterizer|software adapter|basic render/i;
48
+
49
+ /**
50
+ * One row: the class it names, or `undefined` when the row does not match.
51
+ *
52
+ * Each row reads only the fields it names. A field the platform did not report is empty and no
53
+ * pattern matches it, so a coarse adapter falls through to `unknown`, never to a wrong class.
54
+ */
55
+ type Rule = (fields: IGpuAdapterFields) => GpuClass | undefined;
56
+
57
+ const MALI_MODEL = /\bmali[\s_-]*g?[\s-]*(\d{2,3})/i;
58
+ const ADRENO_MODEL = /\badreno\W*(?:tm\W*)?(\d)(\d\d|xx)/i;
59
+ // A Ryzen iGPU names itself `Radeon Graphics` or `Radeon <n>M`; a card carries `RX`/`Pro`/`Vega <n>`.
60
+ const AMD_INTEGRATED = /radeon(?:\(tm\))?\s+(?:graphics|\d{3}m)\b/i;
61
+ const INTEL_DISCRETE = /\barc\b|xe2?-hpg|battlemage|alchemist/i;
62
+
63
+ const RULES: readonly (readonly [name: string, rule: Rule])[] = [
64
+ [
65
+ "software",
66
+ ({ architecture, description, device, vendor }) =>
67
+ [architecture, description, device, vendor].some((value) => SOFTWARE_ADAPTER.test(value))
68
+ ? "software"
69
+ : undefined,
70
+ ],
71
+ [
72
+ // Reads `description`, `device` or `architecture`: Chrome on Android often leaves the first two
73
+ // empty and names only the microarchitecture, which the next row handles.
74
+ "mali-model",
75
+ ({ architecture, description, device }) => {
76
+ const number = [description, device, architecture]
77
+ .map((value) => MALI_MODEL.exec(value)?.[1])
78
+ .find((value) => value !== undefined);
79
+ if (number === undefined) return undefined;
80
+ const model = Number(number);
81
+ // G31, G51, G52, G71 and G72 are the budget Bifrost parts; G57 to G78 and the G3xx, G5xx and
82
+ // G6xx Valhall parts are the middle; G710 and newer (G715, G720, G925) are the flagship line.
83
+ if (model >= 710) return "mobile-high";
84
+ return model < 57 || model === 71 || model === 72 ? "mobile-low" : "mobile-mid";
85
+ },
86
+ ],
87
+ [
88
+ "arm-architecture",
89
+ ({ architecture, vendor }) => {
90
+ if (!/\barm\b/i.test(vendor)) return undefined;
91
+ if (/midgard|bifrost/i.test(architecture)) return "mobile-low";
92
+ if (/valhall/i.test(architecture)) return "mobile-mid";
93
+ return /5th-?gen|immortalis/i.test(architecture) ? "mobile-high" : undefined;
94
+ },
95
+ ],
96
+ [
97
+ "adreno-model",
98
+ ({ architecture, description, device }) => {
99
+ const match = [description, device, architecture]
100
+ .map((value) => ADRENO_MODEL.exec(value))
101
+ .find((value) => value !== null && value !== undefined);
102
+ if (match === null || match === undefined) return undefined;
103
+ const generation = Number(match[1]);
104
+ if (generation <= 4) return "mobile-low";
105
+ if (generation === 5) return "mobile-mid";
106
+ // 6xx spans the 610 budget part to the 660 flagship; a generation-only name is the safe middle.
107
+ if (generation === 6)
108
+ return match[2] !== "xx" && Number(match[2]) >= 30 ? "mobile-high" : "mobile-mid";
109
+ return "mobile-high";
110
+ },
111
+ ],
112
+ [
113
+ "nvidia",
114
+ ({ architecture, description, device, vendor }) =>
115
+ /nvidia/i.test(vendor) && ![architecture, description, device].some((v) => /tegra/i.test(v))
116
+ ? "discrete"
117
+ : undefined,
118
+ ],
119
+ [
120
+ "intel",
121
+ ({ architecture, description, device, vendor }) => {
122
+ if (!/intel/i.test(vendor)) return undefined;
123
+ return [architecture, description, device].some((value) => INTEL_DISCRETE.test(value))
124
+ ? "discrete"
125
+ : "integrated";
126
+ },
127
+ ],
128
+ [
129
+ // An APU and a card share an architecture name, so an unnamed iGPU is classed `discrete`: the
130
+ // wrong answer there is today's start, where the other wrong answer would cap a strong GPU.
131
+ "amd",
132
+ ({ description, vendor }) =>
133
+ /\b(?:amd|ati)\b/i.test(vendor)
134
+ ? AMD_INTEGRATED.test(description)
135
+ ? "integrated"
136
+ : "discrete"
137
+ : undefined,
138
+ ],
139
+ ];
140
+
141
+ /**
142
+ * Classifies one adapter. Ordered rules, first match wins; no match is `unknown`, which every
143
+ * consumer treats as "the behaviour before this table existed".
144
+ *
145
+ * Apple Silicon, Qualcomm desktop parts and anything unrecognised are `unknown` on purpose: an
146
+ * unmatched strong GPU keeps today's start, while a row guessed wrong would cap it.
147
+ */
148
+ export function classifyGpu(fields: Partial<IGpuAdapterFields>): IGpuClassification {
149
+ const normalised: IGpuAdapterFields = {
150
+ architecture: fields.architecture ?? "",
151
+ description: fields.description ?? "",
152
+ device: fields.device ?? "",
153
+ vendor: fields.vendor ?? "",
154
+ };
155
+ for (const [name, rule] of RULES) {
156
+ const matched = rule(normalised);
157
+ if (matched !== undefined) return { class: matched, fields: normalised, rule: name };
158
+ }
159
+ return { class: "unknown", fields: normalised, rule: "none" };
160
+ }
@@ -0,0 +1,424 @@
1
+ export interface IGpuFrameObservationOptions {
2
+ readonly maxFrames: number;
3
+ /** Timestamp slots, two per allocated pass; bounds pending plus queued observations. */
4
+ readonly maxQueries: number;
5
+ }
6
+ export interface IGpuObservedQuery {
7
+ readonly uid: string;
8
+ readonly begin: number;
9
+ readonly end: number;
10
+ readonly ms: number;
11
+ }
12
+ export interface IGpuObservedFrame {
13
+ readonly generation: number;
14
+ readonly batch: number;
15
+ /** Three render-query frame, which may belong to an overlay; not a world callback ID. */
16
+ readonly frame: number;
17
+ readonly ms: number;
18
+ readonly queries: readonly IGpuObservedQuery[];
19
+ }
20
+ export interface IGpuFrameObservationStatus {
21
+ readonly generation: number;
22
+ readonly state: "active" | "stopped" | "failed" | "disposed";
23
+ readonly stopFrame: number | undefined;
24
+ readonly maxFrames: number;
25
+ readonly maxQueries: number;
26
+ readonly expectedFrames: number;
27
+ readonly expectedQueries: number;
28
+ readonly resolvedFrames: number;
29
+ readonly resolvedQueries: number;
30
+ readonly deliveredFrames: number;
31
+ readonly deliveredQueries: number;
32
+ readonly pendingFrames: number;
33
+ readonly pendingQueries: number;
34
+ /** Eligible allocated membership waiting behind an older resolve; included in capacity. */
35
+ readonly undrainedFrames: number;
36
+ readonly undrainedQueries: number;
37
+ readonly queuedFrames: number;
38
+ readonly queuedQueries: number;
39
+ readonly droppedFrames: number;
40
+ readonly droppedQueries: number;
41
+ /** Allocation attempts are not instrumented. Saturation cannot prove zero lost queries. */
42
+ readonly allocationLoss: "not-observed" | "unknown-after-saturation";
43
+ readonly ignoredCompletions: number;
44
+ readonly failure: string | undefined;
45
+ }
46
+ export interface IGpuFrameObservation {
47
+ take(): readonly IGpuObservedFrame[];
48
+ status(): IGpuFrameObservationStatus;
49
+ /** Fence selection now; existing renderer resolves continue draining eligible older frames. */
50
+ stop(): void;
51
+ dispose(): void;
52
+ }
53
+ interface IPool {
54
+ readonly trackTimestamp: boolean;
55
+ readonly isDisposed: boolean;
56
+ readonly maxQueries: number;
57
+ readonly currentQueryIndex: number;
58
+ readonly queryOffsets: Map<string, number>;
59
+ readonly timestamps: Map<string, number>;
60
+ readonly frames: number[];
61
+ readonly pendingResolve: Promise<unknown> | false | null;
62
+ }
63
+ interface IMember {
64
+ readonly uid: string;
65
+ readonly begin: number;
66
+ readonly frame: number;
67
+ }
68
+ interface IBatch {
69
+ readonly pool: IPool;
70
+ readonly previousFrames: number[];
71
+ readonly timestamps: Map<string, number>;
72
+ readonly members: readonly IMember[];
73
+ readonly frames: readonly number[];
74
+ readonly selected: ReadonlyMap<number, readonly IMember[]>;
75
+ readonly slots: number;
76
+ }
77
+ const PREFIX = "TN_GPU_FRAME_OBSERVATION_";
78
+ const integer = (value: unknown): value is number =>
79
+ typeof value === "number" && Number.isSafeInteger(value);
80
+ function readPool(value: unknown): IPool {
81
+ if (typeof value !== "object" || value === null) throw new Error(`${PREFIX}UNSUPPORTED_POOL`);
82
+ const p = value as Partial<IPool>;
83
+ if (
84
+ p.trackTimestamp !== true ||
85
+ p.isDisposed !== false ||
86
+ !integer(p.maxQueries) ||
87
+ p.maxQueries < 2 ||
88
+ p.maxQueries > 131072 ||
89
+ p.maxQueries % 2 !== 0 ||
90
+ !integer(p.currentQueryIndex) ||
91
+ p.currentQueryIndex < 0 ||
92
+ p.currentQueryIndex > p.maxQueries ||
93
+ p.currentQueryIndex % 2 !== 0 ||
94
+ !(p.queryOffsets instanceof Map) ||
95
+ !(p.timestamps instanceof Map) ||
96
+ !Array.isArray(p.frames) ||
97
+ (p.pendingResolve !== false &&
98
+ p.pendingResolve !== null &&
99
+ !(p.pendingResolve instanceof Promise))
100
+ )
101
+ throw new Error(`${PREFIX}UNSUPPORTED_POOL`);
102
+ return p as IPool;
103
+ }
104
+
105
+ /** Opt-in, read-only observer of the pinned Three render pool. It submits no GPU work. */
106
+ export class GpuFrameObservation implements IGpuFrameObservation {
107
+ #state: IGpuFrameObservationStatus["state"] = "active";
108
+ #stopFrame: number | undefined;
109
+ #failure: string | undefined;
110
+ #pool: IPool | undefined;
111
+ #batches = new Map<number, IBatch>();
112
+ #queue: IGpuObservedFrame[] = [];
113
+ #nextBatch = 0;
114
+ #highestFrame = -1;
115
+ #expectedFrames = 0;
116
+ #expectedQueries = 0;
117
+ #resolvedFrames = 0;
118
+ #resolvedQueries = 0;
119
+ #deliveredFrames = 0;
120
+ #deliveredQueries = 0;
121
+ #pendingFrames = 0;
122
+ #pendingQueries = 0;
123
+ #queuedQueries = 0;
124
+ #undrainedFrames = 0;
125
+ #undrainedQueries = 0;
126
+ #droppedFrames = 0;
127
+ #droppedQueries = 0;
128
+ #allocationLoss: IGpuFrameObservationStatus["allocationLoss"] = "not-observed";
129
+ #ignoredCompletions = 0;
130
+ readonly #maxFrames: number;
131
+ readonly #maxQueries: number;
132
+ constructor(
133
+ readonly generation: number,
134
+ readonly firstFrame: number,
135
+ private readonly getPool: () => unknown,
136
+ private readonly getFrame: () => number,
137
+ options: IGpuFrameObservationOptions,
138
+ ) {
139
+ if (
140
+ !integer(generation) ||
141
+ generation < 1 ||
142
+ !integer(firstFrame) ||
143
+ firstFrame < 0 ||
144
+ !integer(options?.maxFrames) ||
145
+ options.maxFrames < 1 ||
146
+ options.maxFrames > 16384 ||
147
+ !integer(options?.maxQueries) ||
148
+ options.maxQueries < 2 ||
149
+ options.maxQueries > 131072 ||
150
+ options.maxQueries % 2 !== 0
151
+ )
152
+ throw new Error(`${PREFIX}LIMITS`);
153
+ this.#maxFrames = options.maxFrames;
154
+ this.#maxQueries = options.maxQueries;
155
+ }
156
+ #fail(reason: string) {
157
+ if (this.#state === "failed" || this.#state === "disposed") return;
158
+ this.#failure = reason.startsWith(PREFIX) ? reason : `${PREFIX}${reason}`;
159
+ this.#state = "failed";
160
+ this.#expectedFrames += this.#undrainedFrames;
161
+ this.#expectedQueries += this.#undrainedQueries;
162
+ this.#droppedFrames += this.#pendingFrames + this.#queue.length + this.#undrainedFrames;
163
+ this.#droppedQueries += this.#pendingQueries + this.#queuedQueries + this.#undrainedQueries;
164
+ this.#clear();
165
+ }
166
+ #clear() {
167
+ this.#batches.clear();
168
+ this.#queue = [];
169
+ this.#pendingFrames =
170
+ this.#pendingQueries =
171
+ this.#queuedQueries =
172
+ this.#undrainedFrames =
173
+ this.#undrainedQueries =
174
+ 0;
175
+ }
176
+ #refreshUndrained(): IBatch | undefined {
177
+ const value = this.getPool();
178
+ if (value === undefined && this.#pool === undefined) return;
179
+ const pool = readPool(value);
180
+ if (this.#pool !== undefined && this.#pool !== pool) throw new Error(`${PREFIX}POOL_RESET`);
181
+ this.#pool = pool;
182
+ if (pool.queryOffsets.size * 2 !== pool.currentQueryIndex)
183
+ throw new Error(`${PREFIX}PAIR_CONSERVATION`);
184
+ const used = new Set<number>();
185
+ const members: IMember[] = [];
186
+ const groups = new Map<number, IMember[]>();
187
+ const currentFrame = this.getFrame();
188
+ for (const [uid, begin] of pool.queryOffsets) {
189
+ const match = typeof uid === "string" ? /^r:[^\s]+:f(\d+)$/.exec(uid) : null;
190
+ const frame = Number(match?.[1]);
191
+ if (
192
+ match === null ||
193
+ !integer(frame) ||
194
+ frame < 0 ||
195
+ !integer(begin) ||
196
+ begin < 0 ||
197
+ begin % 2 !== 0 ||
198
+ begin + 1 >= pool.currentQueryIndex ||
199
+ used.has(begin) ||
200
+ !integer(currentFrame) ||
201
+ frame > currentFrame
202
+ )
203
+ throw new Error(`${PREFIX}MEMBERSHIP`);
204
+ if (pool.timestamps.has(uid)) throw new Error(`${PREFIX}REUSED_QUERY`);
205
+ used.add(begin);
206
+ const member = { uid, begin, frame };
207
+ members.push(member);
208
+ const group = groups.get(frame) ?? [];
209
+ group.push(member);
210
+ groups.set(frame, group);
211
+ }
212
+ const frames = [...groups.keys()];
213
+ const selected = new Map(
214
+ [...groups].filter(
215
+ ([frame]) =>
216
+ frame >= this.firstFrame && (this.#stopFrame === undefined || frame <= this.#stopFrame),
217
+ ),
218
+ );
219
+ const slots = [...selected.values()].reduce((sum, group) => sum + group.length * 2, 0);
220
+ this.#undrainedFrames = selected.size;
221
+ this.#undrainedQueries = slots;
222
+ if (pool.currentQueryIndex >= pool.maxQueries) {
223
+ this.#allocationLoss = "unknown-after-saturation";
224
+ throw new Error(`${PREFIX}SATURATED_POOL`);
225
+ }
226
+ if (
227
+ this.#pendingFrames + this.#queue.length + selected.size > this.#maxFrames ||
228
+ this.#pendingQueries + this.#queuedQueries + slots > this.#maxQueries
229
+ )
230
+ throw new Error(`${PREFIX}OVERFLOW`);
231
+ return {
232
+ pool,
233
+ previousFrames: pool.frames,
234
+ timestamps: pool.timestamps,
235
+ members,
236
+ frames,
237
+ selected,
238
+ slots,
239
+ };
240
+ }
241
+ /** Capture before the existing resolve; failure stays on the receipt, never on rendering. */
242
+ capture(): number | undefined {
243
+ if (this.#state === "failed" || this.#state === "disposed") return;
244
+ try {
245
+ const batch = this.#refreshUndrained();
246
+ // Pending older work cannot own the newly queued offsets, which remain counted separately.
247
+ if (batch === undefined || batch.pool.pendingResolve || batch.pool.currentQueryIndex === 0)
248
+ return;
249
+ const selectedFrames = [...batch.selected.keys()];
250
+ if (selectedFrames.some((frame) => frame <= this.#highestFrame))
251
+ throw new Error(`${PREFIX}REPEATED_FRAME`);
252
+ if (selectedFrames.length) this.#highestFrame = Math.max(...selectedFrames);
253
+ this.#expectedFrames += batch.selected.size;
254
+ this.#expectedQueries += batch.slots;
255
+ const id = ++this.#nextBatch;
256
+ this.#batches.set(id, batch);
257
+ this.#pendingFrames += batch.selected.size;
258
+ this.#pendingQueries += batch.slots;
259
+ this.#undrainedFrames = this.#undrainedQueries = 0;
260
+ return id;
261
+ } catch (error) {
262
+ this.#fail(error instanceof Error ? error.message : "CAPTURE_FAILED");
263
+ }
264
+ }
265
+ /** Called immediately after the raw resolve has synchronously drained its allocation map. */
266
+ submitted(id: number | undefined): void {
267
+ if (id === undefined) return;
268
+ const batch = this.#batches.get(id);
269
+ if (batch === undefined) return;
270
+ try {
271
+ const pending = batch.pool.pendingResolve;
272
+ if (
273
+ this.getPool() !== batch.pool ||
274
+ !(pending instanceof Promise) ||
275
+ batch.pool.currentQueryIndex !== 0 ||
276
+ batch.pool.queryOffsets.size !== 0
277
+ ) {
278
+ this.#fail("NOT_SUBMITTED");
279
+ return;
280
+ }
281
+ // Observe the actual pool promise, not a wrapper that may merely return an older lastValue.
282
+ void pending.then(
283
+ () => this.#complete(id),
284
+ () => this.#fail("RESOLVE_REJECTED"),
285
+ );
286
+ } catch (error) {
287
+ this.#fail(error instanceof Error ? error.message : "SUBMISSION_FAILED");
288
+ }
289
+ }
290
+ #complete(id: number) {
291
+ const batch = this.#batches.get(id);
292
+ if (batch === undefined) {
293
+ this.#ignoredCompletions += 1;
294
+ return;
295
+ }
296
+ try {
297
+ const pool = batch.pool;
298
+ if (this.getPool() !== pool || pool.isDisposed || pool.timestamps !== batch.timestamps)
299
+ throw new Error(`${PREFIX}POOL_RESET`);
300
+ if (
301
+ pool.frames === batch.previousFrames ||
302
+ pool.frames.length !== batch.frames.length ||
303
+ pool.frames.some((f, i) => f !== batch.frames[i])
304
+ )
305
+ throw new Error(`${PREFIX}STALE_RESOLUTION`);
306
+ // Fresh publication is atomic in Three. Missing members now cannot be repaired by later maps.
307
+ const values = new Map<string, number>();
308
+ for (const member of batch.members) {
309
+ const ms = pool.timestamps.get(member.uid);
310
+ if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)
311
+ throw new Error(`${PREFIX}INCOMPLETE_RESOLUTION`);
312
+ values.set(member.uid, ms);
313
+ }
314
+ const samples: IGpuObservedFrame[] = [];
315
+ for (const [frame, group] of batch.selected) {
316
+ const queries = group.map((member) => {
317
+ const ms = values.get(member.uid);
318
+ if (ms === undefined) throw new Error(`${PREFIX}INCOMPLETE_RESOLUTION`);
319
+ return Object.freeze({
320
+ uid: member.uid,
321
+ begin: member.begin,
322
+ end: member.begin + 1,
323
+ ms,
324
+ });
325
+ });
326
+ const ms = queries.reduce((sum, query) => sum + query.ms, 0);
327
+ if (!Number.isFinite(ms)) throw new Error(`${PREFIX}INVALID_DURATION`);
328
+ samples.push(
329
+ Object.freeze({
330
+ generation: this.generation,
331
+ batch: id,
332
+ frame,
333
+ ms,
334
+ queries: Object.freeze(queries),
335
+ }),
336
+ );
337
+ }
338
+ this.#batches.delete(id);
339
+ this.#pendingFrames -= batch.selected.size;
340
+ this.#pendingQueries -= batch.slots;
341
+ this.#resolvedFrames += samples.length;
342
+ this.#resolvedQueries += batch.slots;
343
+ this.#queuedQueries += batch.slots;
344
+ this.#queue.push(...samples);
345
+ } catch (error) {
346
+ this.#fail(error instanceof Error ? error.message : "COMPLETION_FAILED");
347
+ }
348
+ }
349
+ take(): readonly IGpuObservedFrame[] {
350
+ if (this.#state === "failed") throw new Error(this.#failure);
351
+ if (this.#state === "disposed") throw new Error(`${PREFIX}DISPOSED`);
352
+ const samples = this.#queue;
353
+ this.#queue = [];
354
+ this.#deliveredFrames += samples.length;
355
+ this.#deliveredQueries += this.#queuedQueries;
356
+ this.#queuedQueries = 0;
357
+ return Object.freeze(samples);
358
+ }
359
+ status(): IGpuFrameObservationStatus {
360
+ if (this.#state === "active" || this.#state === "stopped") {
361
+ try {
362
+ this.#refreshUndrained();
363
+ } catch (error) {
364
+ this.#fail(error instanceof Error ? error.message : "BACKLOG_FAILED");
365
+ }
366
+ }
367
+ return Object.freeze({
368
+ generation: this.generation,
369
+ state: this.#state,
370
+ stopFrame: this.#stopFrame,
371
+ maxFrames: this.#maxFrames,
372
+ maxQueries: this.#maxQueries,
373
+ expectedFrames: this.#expectedFrames + this.#undrainedFrames,
374
+ expectedQueries: this.#expectedQueries + this.#undrainedQueries,
375
+ resolvedFrames: this.#resolvedFrames,
376
+ resolvedQueries: this.#resolvedQueries,
377
+ deliveredFrames: this.#deliveredFrames,
378
+ deliveredQueries: this.#deliveredQueries,
379
+ pendingFrames: this.#pendingFrames,
380
+ pendingQueries: this.#pendingQueries,
381
+ undrainedFrames: this.#undrainedFrames,
382
+ undrainedQueries: this.#undrainedQueries,
383
+ queuedFrames: this.#queue.length,
384
+ queuedQueries: this.#queuedQueries,
385
+ droppedFrames: this.#droppedFrames,
386
+ droppedQueries: this.#droppedQueries,
387
+ allocationLoss: this.#allocationLoss,
388
+ ignoredCompletions: this.#ignoredCompletions,
389
+ failure: this.#failure,
390
+ });
391
+ }
392
+ stop(): void {
393
+ if (this.#state !== "active") return;
394
+ const frame = this.getFrame();
395
+ if (!integer(frame) || frame < -1) {
396
+ this.#fail("FRAME_RESET");
397
+ return;
398
+ }
399
+ this.#stopFrame = frame;
400
+ this.#state = "stopped";
401
+ try {
402
+ this.#refreshUndrained();
403
+ } catch (error) {
404
+ this.#fail(error instanceof Error ? error.message : "BACKLOG_FAILED");
405
+ }
406
+ }
407
+ dispose(): void {
408
+ if (this.#state === "disposed") return;
409
+ if (this.#state === "active" || this.#state === "stopped") {
410
+ try {
411
+ this.#refreshUndrained();
412
+ } catch (error) {
413
+ this.#fail(error instanceof Error ? error.message : "BACKLOG_FAILED");
414
+ }
415
+ }
416
+ this.#expectedFrames += this.#undrainedFrames;
417
+ this.#expectedQueries += this.#undrainedQueries;
418
+ this.#droppedFrames += this.#pendingFrames + this.#queue.length + this.#undrainedFrames;
419
+ this.#droppedQueries += this.#pendingQueries + this.#queuedQueries + this.#undrainedQueries;
420
+ this.#clear();
421
+ this.#pool = undefined;
422
+ this.#state = "disposed";
423
+ }
424
+ }