@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,1021 @@
1
+ import type { Texture } from "three";
2
+ import type { MRTNode, Node } from "three/webgpu";
3
+
4
+ import type { IFrameBudgetWindow } from "../frame-budget.js";
5
+ import type {
6
+ IRenderOutputInstallation,
7
+ IRenderOutputOptions,
8
+ RenderOutputSetter,
9
+ RendererKind,
10
+ } from "../renderer.js";
11
+ import type { IResolutionSubrect, IResolutionTextureView } from "./resolution-subrect.js";
12
+ import { VELOCITY_OUTPUT_NAME, mrtVelocity } from "./velocity.js";
13
+ import type { IVelocityProvision, IVelocityRenderPass } from "./velocity.js";
14
+
15
+ /** The marker shared by render-chain logs, playtests, and native diagnostics. */
16
+ export const RENDER_CHAIN_MARKER = "TN_RENDER_CHAIN";
17
+
18
+ /** Canonical order for the stages a game may request. */
19
+ export const RENDER_CHAIN_STAGE_ORDER = [
20
+ "probeVolume",
21
+ "ambientOcclusion",
22
+ "ssgi",
23
+ "godRays",
24
+ "ssr",
25
+ "denoise",
26
+ "temporalReproject",
27
+ "taa",
28
+ "traa",
29
+ "motionBlur",
30
+ "sharpen",
31
+ "bloom",
32
+ "vignette",
33
+ "lensDistortion",
34
+ "sparkle",
35
+ "gradualBackground",
36
+ ] as const;
37
+
38
+ export type RenderChainStageName = (typeof RENDER_CHAIN_STAGE_ORDER)[number];
39
+ /** Built-in stage names plus an opaque id owned by the game that supplied the stage. */
40
+ export type RenderChainStageId = RenderChainStageName | (string & {});
41
+ export type RenderChainTier = "high" | "medium" | "low" | "off";
42
+ export type RenderChainTierRequest = RenderChainTier | "auto";
43
+ export type RenderChainSource = "pinned" | "auto";
44
+ export type RenderChainVelocitySource = "mrt" | "per-object" | null;
45
+
46
+ export interface IRenderChainVelocityMeasurement {
47
+ /** Monotonic frame number derived from the stage's completed velocity result. */
48
+ readonly frame: number;
49
+ /** Share of result pixels whose temporal history was rejected in that frame. */
50
+ readonly rejectionFraction: number;
51
+ }
52
+
53
+ export interface IRenderChainVelocityResult {
54
+ /** Monotonic frame number from the active temporal stage's completed result. */
55
+ readonly frame: number;
56
+ /** One binary value per result pixel: one means the temporal history was rejected. */
57
+ readonly rejectionMask: ArrayLike<number>;
58
+ }
59
+
60
+ export interface IRenderChainRenderer {
61
+ readonly kind: RendererKind;
62
+ readonly raw: unknown;
63
+ clearOutputNode?(expectedNode?: unknown): void;
64
+ /** Internal renderer seam used to turn on core-owned previous-frame bookkeeping for active temporal stages. */
65
+ setRenderChainVelocityEnabled?(enabled: boolean): void;
66
+ /** Install a graph and identify the authored world pass that follows the rendered scene root. */
67
+ setOutputNode: RenderOutputSetter;
68
+ }
69
+
70
+ const TIER_LEVEL: Record<RenderChainTier, number> = {
71
+ high: 3,
72
+ low: 1,
73
+ medium: 2,
74
+ off: 0,
75
+ };
76
+
77
+ /** Quality values are algorithm parameters, not appearance values. Templates own the latter. */
78
+ export const RENDER_CHAIN_TIERS = {
79
+ high: { denoiseIterations: 3, sliceCount: 3, stepCount: 16 },
80
+ low: { denoiseIterations: 1, sliceCount: 1, stepCount: 12 },
81
+ medium: { denoiseIterations: 2, sliceCount: 2, stepCount: 8 },
82
+ off: { denoiseIterations: 0, sliceCount: 0, stepCount: 0 },
83
+ } as const satisfies Record<
84
+ RenderChainTier,
85
+ {
86
+ denoiseIterations: number;
87
+ sliceCount: number;
88
+ stepCount: number;
89
+ }
90
+ >;
91
+
92
+ const VELOCITY_STAGES = new Set<RenderChainStageName>([
93
+ "motionBlur",
94
+ "taa",
95
+ "temporalReproject",
96
+ "traa",
97
+ ]);
98
+
99
+ export interface IRenderChainVelocityRequest {
100
+ /** The scene pass that owns the shared velocity output. */
101
+ pass?: IVelocityRenderPass;
102
+ /**
103
+ * Optional: how the chain builds the velocity output on `pass` and hands it through the composed
104
+ * graph. Defaults to core's own {@link mrtVelocity}, so a web game never names it; a host whose
105
+ * scene pass owns the output differently passes its own.
106
+ */
107
+ provision?: IVelocityProvision;
108
+ /** Treat the renderer's MRT velocity output as provisioned. */
109
+ mrt?: boolean;
110
+ /** Treat objects carrying `userData.useVelocity === true` as provisioned. */
111
+ objectFlags?: boolean;
112
+ /** Alias accepted by integrations that call this route per-object velocity. */
113
+ perObject?: boolean;
114
+ /**
115
+ * Compatibility source for completed temporal measurements. The stage reader wins when it
116
+ * returns a result; this callback is consulted when an integration cannot expose that reader.
117
+ */
118
+ rejectionMeasurement?: () => IRenderChainVelocityMeasurement | undefined;
119
+ /** Explicit route, useful for a native host whose MRT is not introspectable from JavaScript. */
120
+ source?: Exclude<RenderChainVelocitySource, null>;
121
+ }
122
+
123
+ export interface IRenderChainRequest {
124
+ /** Built-ins use canonical order; authored stages use their supplied anchor order. */
125
+ stages?: readonly RenderChainStageId[];
126
+ /** A fixed tier pins quality; `auto` enables the measured frame-budget ladder. */
127
+ tier?: RenderChainTierRequest;
128
+ velocity?: IRenderChainVelocityRequest;
129
+ }
130
+
131
+ export interface IRenderChainStageContext {
132
+ readonly tier: RenderChainTier;
133
+ readonly velocity: IRenderChainVelocityReport;
134
+ /** Mutable target fractions supplied to generated stages for sub-rectangle sampling. */
135
+ readonly resolutionSubrect?: IResolutionTextureView;
136
+ /** TSL source handed to temporal stages when the request owns a scene pass. */
137
+ readonly velocityNode?: Node;
138
+ readonly quality: (typeof RENDER_CHAIN_TIERS)[RenderChainTier];
139
+ }
140
+
141
+ export interface IRenderChainStage {
142
+ readonly supportsResolutionSubrect?: boolean;
143
+ readonly name: RenderChainStageId;
144
+ /** Place an authored stage immediately before this built-in or supplied stage. */
145
+ readonly before?: RenderChainStageId;
146
+ /** Place an authored stage immediately after this built-in or supplied stage. */
147
+ readonly after?: RenderChainStageId;
148
+ /**
149
+ * This stage reads display-referred colour, so the chain installs the graph with the renderer's
150
+ * automatic output transform switched off and the stage applies that transform itself.
151
+ *
152
+ * Mechanism, not look. Some effects are defined against the sRGB picture — a `.cube` table, a
153
+ * sharpening or edge filter — and bending scene-referred light into that domain costs precision
154
+ * instead of buying anything: measured on an 8-bit table, a bijective log shaper costs 2–4
155
+ * 8-bit steps per channel against under 1 for the transform this names (PRD-492).
156
+ *
157
+ * The stage therefore runs last, and may not declare an anchor: a stage placed after it would
158
+ * receive display-referred colour it was not written for.
159
+ */
160
+ readonly afterOutputTransform?: boolean;
161
+ readonly build: (input: unknown, context: IRenderChainStageContext) => unknown;
162
+ /** Stages below this tier are named as dropped instead of silently changing the graph. */
163
+ readonly minimumTier?: RenderChainTier;
164
+ /** Return a reason to drop the stage on this target, or true when it is available. */
165
+ readonly available?: (context: IRenderChainStageContext) => boolean | string;
166
+ /** Read the completed velocity result after rendering; the chain derives its rejection fraction. */
167
+ readonly readVelocityResult?: (node: unknown) => IRenderChainVelocityResult | undefined;
168
+ /** Defaults from the canonical stage name for the temporal stages. */
169
+ readonly requiresVelocity?: boolean;
170
+ /** Release resources allocated while building this stage's graph. */
171
+ readonly dispose?: () => void;
172
+ }
173
+
174
+ export interface IRenderChainDroppedStage {
175
+ readonly name: RenderChainStageId;
176
+ readonly reason: string;
177
+ }
178
+
179
+ export interface IRenderChainVelocityReport {
180
+ readonly provisioned: boolean;
181
+ readonly required: boolean;
182
+ readonly source: RenderChainVelocitySource;
183
+ readonly rejectionFraction?: number;
184
+ readonly measurementFrame?: number;
185
+ }
186
+
187
+ export interface IRenderChainApplied {
188
+ readonly contributions: readonly {
189
+ readonly graphOutputChanged: boolean;
190
+ readonly name: RenderChainStageId;
191
+ }[];
192
+ readonly dropped: readonly IRenderChainDroppedStage[];
193
+ readonly requested: readonly RenderChainStageId[];
194
+ readonly source: RenderChainSource;
195
+ readonly stages: readonly RenderChainStageId[];
196
+ readonly tier: RenderChainTier;
197
+ readonly velocity: IRenderChainVelocityReport;
198
+ }
199
+
200
+ export interface IRenderChainMarker {
201
+ readonly applied: IRenderChainApplied;
202
+ readonly marker: typeof RENDER_CHAIN_MARKER;
203
+ }
204
+
205
+ export interface IRenderChainBudgetWindow {
206
+ /** Compilation-contaminated windows remain observable but cannot drive quality changes. */
207
+ readonly surface?: Pick<NonNullable<IFrameBudgetWindow["surface"]>, "compiling">;
208
+ readonly phases: {
209
+ readonly render: Pick<IFrameBudgetWindow["phases"]["render"], "p95">;
210
+ };
211
+ }
212
+
213
+ export interface IRenderChainOptions {
214
+ readonly resolutionSubrect?: IResolutionSubrect;
215
+ readonly renderer: IRenderChainRenderer;
216
+ readonly input?: unknown;
217
+ /** Explicit scene pass for output retargeting; avoids traversing a composed graph to find it. */
218
+ readonly worldPass?: unknown;
219
+ readonly report?: (line: string) => void;
220
+ readonly request?: IRenderChainRequest;
221
+ readonly stages?: readonly IRenderChainStage[];
222
+ readonly targetFps?: number;
223
+ /** Number of consecutive over-budget windows before the automatic ladder steps down. */
224
+ readonly dwellWindows?: number;
225
+ /** Optional scene-like traversal for detecting `userData.useVelocity` flags. */
226
+ readonly scene?: {
227
+ traverse(callback: (object: { userData?: Record<string, unknown> }) => void): void;
228
+ };
229
+ }
230
+
231
+ /**
232
+ * Where a chain publishes its last report: a registered symbol on the renderer, not a
233
+ * module-scoped map.
234
+ *
235
+ * `tsup` emits `dist/playtest.js` as its own entry with its own copy of this module, so the
236
+ * browser bridge that reads the report is never the copy that wrote it. A `WeakMap` in module
237
+ * scope is therefore written by one copy and read by another, and `readRenderChainObservation`
238
+ * returned `undefined` for every installed chain — every `renderChain` assertion failed closed
239
+ * as UNOBSERVABLE while the chain was running and printing its marker. `Symbol.for` is one key
240
+ * across every copy of this module, and the report lives on the thing it is about.
241
+ */
242
+ const REPORT_KEY = Symbol.for("threenative.renderChain.report");
243
+
244
+ function storedReport(target: object): IRenderChainMarker | undefined {
245
+ return (target as Record<symbol, IRenderChainMarker | undefined>)[REPORT_KEY];
246
+ }
247
+
248
+ function storeReport(target: object, marker: IRenderChainMarker | undefined): void {
249
+ Object.defineProperty(target, REPORT_KEY, {
250
+ configurable: true,
251
+ enumerable: false,
252
+ value: marker,
253
+ writable: true,
254
+ });
255
+ }
256
+
257
+ /**
258
+ * Read the last chain marker associated with a renderer or its raw renderer.
259
+ * @situation expose the render tier and dropped-stage reasons to a playtest
260
+ * @situation inspect whether a temporal pass received velocity
261
+ * @constraint an absent value means no chain was installed and must fail a chain assertion
262
+ * @example const chain = readRenderChainReport(ctx.renderer);
263
+ */
264
+ export function readRenderChainReport(renderer: unknown): IRenderChainMarker | undefined {
265
+ if (!isObject(renderer)) return undefined;
266
+ const raw = readRawRenderer(renderer);
267
+ return storedReport(renderer) ?? (isObject(raw) ? storedReport(raw) : undefined);
268
+ }
269
+
270
+ /** JSON-safe observation used by the browser and native playtest bridges. */
271
+ export function readRenderChainObservation(
272
+ renderer: unknown,
273
+ ): IRenderChainMarker["applied"] | undefined {
274
+ return readRenderChainReport(renderer)?.applied;
275
+ }
276
+
277
+ /**
278
+ * Compose game-provided nodes through one ordered, measured, honest render seam.
279
+ *
280
+ * The chain owns only stage ordering, availability, velocity provisioning and quality selection.
281
+ * Every stage factory is supplied by the game/template, so this module never chooses a material,
282
+ * colour, light, shader or post-processing look.
283
+ */
284
+ export class RenderChain {
285
+ readonly #renderer: IRenderChainRenderer;
286
+ readonly #input: unknown;
287
+ readonly #worldPass: unknown;
288
+ readonly #resolutionSubrect: IResolutionSubrect | undefined;
289
+ readonly #report: (line: string) => void;
290
+ readonly #stageDefinitions: ReadonlyMap<RenderChainStageId, IRenderChainStage>;
291
+ readonly #requested: readonly RenderChainStageId[];
292
+ readonly #requestVelocity: IRenderChainVelocityRequest;
293
+ readonly #automatic: boolean;
294
+ readonly #targetFps: number;
295
+ readonly #dwellWindows: number;
296
+ readonly #scene: IRenderChainOptions["scene"];
297
+ #activeStageDefinitions: IRenderChainStage[] = [];
298
+ #tier: RenderChainTier;
299
+ #source: RenderChainSource;
300
+ #overBudgetWindows = 0;
301
+ #lastMeasurementFrame: number | undefined;
302
+ #reportedMeasurement = false;
303
+ #velocityResultNode: unknown = undefined;
304
+ #velocityResultReader: ((node: unknown) => IRenderChainVelocityResult | undefined) | undefined =
305
+ undefined;
306
+ #ownedVelocityPass: IVelocityRenderPass | undefined = undefined;
307
+ #ownedVelocityMrt: MRTNode | null | undefined = undefined;
308
+ #ownedVelocityTexture: Texture | undefined = undefined;
309
+ #disposed = false;
310
+ #installedNode: unknown;
311
+ #installation: IRenderOutputInstallation | undefined;
312
+ #applied: IRenderChainApplied;
313
+
314
+ constructor(renderer: IRenderChainRenderer, options?: Omit<IRenderChainOptions, "renderer">);
315
+ constructor(options: IRenderChainOptions);
316
+ constructor(
317
+ rendererOrOptions: IRenderChainRenderer | IRenderChainOptions,
318
+ suppliedOptions: Omit<IRenderChainOptions, "renderer"> = {},
319
+ ) {
320
+ const options = isRenderer(rendererOrOptions)
321
+ ? { ...suppliedOptions, renderer: rendererOrOptions }
322
+ : rendererOrOptions;
323
+ this.#renderer = options.renderer;
324
+ this.#input = options.input;
325
+ this.#worldPass = options.worldPass;
326
+ this.#resolutionSubrect = options.resolutionSubrect;
327
+ this.#report = options.report ?? ((line) => console.log(line));
328
+ this.#stageDefinitions = createStageDefinitions(options.stages ?? []);
329
+ this.#requested = normalizeRequestedStages(
330
+ options.request?.stages ?? [],
331
+ this.#stageDefinitions,
332
+ );
333
+ this.#requestVelocity = options.request?.velocity ?? {};
334
+ this.#automatic = (options.request?.tier ?? "high") === "auto";
335
+ this.#tier = this.#automatic ? "high" : validateTier(options.request?.tier ?? "high");
336
+ this.#source = this.#automatic ? "auto" : "pinned";
337
+ this.#targetFps = requirePositiveNumber(options.targetFps ?? 60, "targetFps");
338
+ this.#dwellWindows = requirePositiveInteger(options.dwellWindows ?? 2, "dwellWindows");
339
+ this.#scene = options.scene;
340
+ this.#applied = emptyApplied(this.#requested, this.#tier, this.#source, false);
341
+ this.apply();
342
+ }
343
+
344
+ get applied(): IRenderChainApplied {
345
+ return this.#applied;
346
+ }
347
+
348
+ get disposed(): boolean {
349
+ return this.#disposed;
350
+ }
351
+
352
+ /** Rebuild and install the current tier. */
353
+ apply(): IRenderChainApplied {
354
+ if (this.#disposed) throw new Error("RenderChain.apply called after dispose().");
355
+ this.#disposeActiveStages();
356
+ this.#restoreOwnedVelocityOutput();
357
+ this.#velocityResultNode = undefined;
358
+ this.#velocityResultReader = undefined;
359
+ if (this.#requested.length === 0) {
360
+ this.#applied = emptyApplied([], this.#tier, this.#source, false);
361
+ this.#lastMeasurementFrame = undefined;
362
+ this.#reportedMeasurement = false;
363
+ this.#renderer.setRenderChainVelocityEnabled?.(false);
364
+ forgetReport(this.#renderer);
365
+ return this.#applied;
366
+ }
367
+
368
+ const requiredVelocity = this.#requested.some((name) =>
369
+ requiresVelocityFor(this.#stageDefinitions.get(name), name),
370
+ );
371
+ const velocity = resolveVelocity(
372
+ this.#renderer,
373
+ this.#requestVelocity,
374
+ this.#scene,
375
+ requiredVelocity,
376
+ );
377
+ let velocityNode: Node | undefined;
378
+ let attachVelocity: IVelocityProvision["attach"] | undefined;
379
+ const originalMrt = this.#requestVelocity.pass?.getMRT();
380
+ this.#lastMeasurementFrame = undefined;
381
+ this.#reportedMeasurement = false;
382
+ const dropped: IRenderChainDroppedStage[] = [];
383
+ const contributions: Array<IRenderChainApplied["contributions"][number]> = [];
384
+ const stages: RenderChainStageId[] = [];
385
+ const builtStageDefinitions: IRenderChainStage[] = [];
386
+ let node = this.#input;
387
+
388
+ for (const name of this.#requested) {
389
+ if (this.#tier === "off") {
390
+ dropped.push({ name, reason: "tier:off" });
391
+ continue;
392
+ }
393
+ const definition = this.#stageDefinitions.get(name);
394
+ if (definition === undefined) {
395
+ dropped.push({ name, reason: "provider:missing" });
396
+ continue;
397
+ }
398
+ if (this.#renderer.kind !== "webgpu") {
399
+ dropped.push({ name, reason: `renderer:${this.#renderer.kind}` });
400
+ continue;
401
+ }
402
+ if (
403
+ definition.minimumTier !== undefined &&
404
+ TIER_LEVEL[this.#tier] < TIER_LEVEL[definition.minimumTier]
405
+ ) {
406
+ dropped.push({ name, reason: `tier:${this.#tier}` });
407
+ continue;
408
+ }
409
+ const requiresVelocity = requiresVelocityFor(definition, name);
410
+ if (requiresVelocity && !velocity.provisioned) {
411
+ dropped.push({ name, reason: "velocity:missing" });
412
+ continue;
413
+ }
414
+ const context = stageContext(
415
+ this.#tier,
416
+ velocity,
417
+ velocityNode,
418
+ this.#resolutionSubrect?.view,
419
+ );
420
+ const availability = definition.available?.(context);
421
+ if (availability === false) {
422
+ dropped.push({ name, reason: `unavailable:${this.#renderer.kind}` });
423
+ continue;
424
+ }
425
+ if (typeof availability === "string") {
426
+ dropped.push({ name, reason: availability });
427
+ continue;
428
+ }
429
+ try {
430
+ if (
431
+ requiresVelocity &&
432
+ velocityNode === undefined &&
433
+ velocity.source === "mrt" &&
434
+ this.#requestVelocity.pass !== undefined
435
+ ) {
436
+ const pass = this.#requestVelocity.pass;
437
+ const priorTextures = [...(pass.renderTarget?.textures ?? [])];
438
+ const provision = this.#requestVelocity.provision ?? mrtVelocity();
439
+ velocityNode = provision.texture(pass);
440
+ attachVelocity = provision.attach;
441
+ this.#ownedVelocityPass = pass;
442
+ this.#ownedVelocityMrt = originalMrt;
443
+ if (originalMrt?.has(VELOCITY_OUTPUT_NAME) !== true)
444
+ this.#ownedVelocityTexture = pass.renderTarget?.textures.find(
445
+ (texture) =>
446
+ texture.name === VELOCITY_OUTPUT_NAME && !priorTextures.includes(texture),
447
+ );
448
+ }
449
+ const buildContext = stageContext(
450
+ this.#tier,
451
+ velocity,
452
+ velocityNode,
453
+ this.#resolutionSubrect?.view,
454
+ );
455
+ const next = definition.build(node, buildContext);
456
+ if (next === undefined || next === null) throw new Error("stage returned no node");
457
+ contributions.push({ graphOutputChanged: next !== node, name });
458
+ node = next;
459
+ stages.push(name);
460
+ builtStageDefinitions.push(definition);
461
+ if (requiresVelocity && definition.readVelocityResult !== undefined) {
462
+ this.#velocityResultNode = next;
463
+ this.#velocityResultReader = definition.readVelocityResult;
464
+ }
465
+ } catch (error) {
466
+ definition.dispose?.();
467
+ dropped.push({ name, reason: `build:${errorMessage(error)}` });
468
+ }
469
+ }
470
+
471
+ const hasActiveVelocityStage = stages.some((name) =>
472
+ requiresVelocityFor(this.#stageDefinitions.get(name), name),
473
+ );
474
+ // Temporal nodes jitter the scene-side velocity node (TRAANode calls setProjectionMatrix on
475
+ // it); the pass texture is what a stage samples, so it stays on the build context only.
476
+ if (velocityNode !== undefined && attachVelocity !== undefined && hasActiveVelocityStage)
477
+ // TRAANode uses context.velocity to set the unjittered projection, not to sample MRT.
478
+ // The sampled texture already travels to the factory via context.velocityNode.
479
+ node = attachVelocity(node, velocityNode);
480
+
481
+ if (stages.length > 0) {
482
+ try {
483
+ // Only a stage that actually ran may take the transform away from the renderer; a
484
+ // dropped one would leave the frame untone-mapped with nothing to have applied it.
485
+ const outputOptions: IRenderOutputOptions[] = builtStageDefinitions.some(
486
+ (definition) => definition.afterOutputTransform === true,
487
+ )
488
+ ? [{ outputColorTransform: false }]
489
+ : [];
490
+ if (this.#resolutionSubrect !== undefined) {
491
+ const refused = builtStageDefinitions
492
+ .filter((stage) => stage.supportsResolutionSubrect !== true)
493
+ .map((stage) => stage.name);
494
+ this.#report(
495
+ `TN_RESOLUTION_SUBRECT ${JSON.stringify({ applied: refused.length === 0 ? stages : [], refused: refused.map((name) => ({ name, reason: "sampling support not declared" })) })}`,
496
+ );
497
+ if (refused.length === 0) {
498
+ if (outputOptions.length === 0)
499
+ outputOptions.push({ resolutionSubrect: this.#resolutionSubrect });
500
+ else
501
+ outputOptions[0] = {
502
+ ...outputOptions[0],
503
+ resolutionSubrect: this.#resolutionSubrect,
504
+ };
505
+ }
506
+ }
507
+ const installation = this.#renderer.setOutputNode(
508
+ node,
509
+ this.#worldPass ?? this.#requestVelocity.pass,
510
+ ...outputOptions,
511
+ );
512
+ // Historical void-style callbacks can return an ignored value (for example Array.push).
513
+ // Only an explicit receipt upgrades that adapter to installation ownership.
514
+ this.#installation =
515
+ installation &&
516
+ typeof installation.isCurrent === "function" &&
517
+ typeof installation.dispose === "function"
518
+ ? installation
519
+ : undefined;
520
+ this.#installedNode = node;
521
+ } catch (error) {
522
+ const reason = `install:${errorMessage(error)}`;
523
+ dropped.push(...stages.map((name) => ({ name, reason })));
524
+ stages.length = 0;
525
+ contributions.length = 0;
526
+ for (const definition of builtStageDefinitions) definition.dispose?.();
527
+ builtStageDefinitions.length = 0;
528
+ // A renderer may throw after partially installing this attempt. Clear that identity,
529
+ // then the prior owned graph, without touching an unrelated replacement.
530
+ this.#renderer.clearOutputNode?.(node);
531
+ this.#clearOwnedOutput();
532
+ }
533
+ } else {
534
+ this.#clearOwnedOutput();
535
+ }
536
+
537
+ const activeVelocity = stages.some((name) =>
538
+ requiresVelocityFor(this.#stageDefinitions.get(name), name),
539
+ );
540
+ if (!activeVelocity) {
541
+ this.#restoreOwnedVelocityOutput();
542
+ this.#velocityResultNode = undefined;
543
+ this.#velocityResultReader = undefined;
544
+ }
545
+ const appliedVelocity = activeVelocity
546
+ ? velocity
547
+ : { provisioned: false, required: velocity.required, source: null };
548
+
549
+ this.#applied = {
550
+ contributions,
551
+ dropped,
552
+ requested: this.#requested,
553
+ source: this.#source,
554
+ stages,
555
+ tier: this.#tier,
556
+ velocity: appliedVelocity,
557
+ };
558
+ this.#activeStageDefinitions = builtStageDefinitions;
559
+ this.#renderer.setRenderChainVelocityEnabled?.(
560
+ stages.some((name) => requiresVelocityFor(this.#stageDefinitions.get(name), name)),
561
+ );
562
+ this.#publish(true);
563
+ return this.#applied;
564
+ }
565
+
566
+ /** Samples the active temporal stage's completed velocity result after rendering. */
567
+ observeFrame(): IRenderChainApplied {
568
+ if (this.#disposed) throw new Error("RenderChain.observeFrame called after dispose().");
569
+ if (this.#installation?.isCurrent() === false) return this.#applied;
570
+ const requiresMeasurement = this.#applied.stages.some((name) =>
571
+ requiresVelocityFor(this.#stageDefinitions.get(name), name),
572
+ );
573
+ if (!requiresMeasurement) return this.#applied;
574
+
575
+ const result = this.#velocityResultReader?.(this.#velocityResultNode);
576
+ const measurement =
577
+ result === undefined
578
+ ? validateCompatibilityMeasurement(
579
+ this.#requestVelocity.rejectionMeasurement?.(),
580
+ this.#lastMeasurementFrame,
581
+ )
582
+ : deriveVelocityMeasurement(result, this.#lastMeasurementFrame);
583
+ if (measurement === undefined) {
584
+ this.#setMeasurement(undefined, false);
585
+ return this.#applied;
586
+ }
587
+ this.#lastMeasurementFrame = measurement.frame;
588
+ this.#setMeasurement(measurement, !this.#reportedMeasurement || measurement.frame % 60 === 0);
589
+ return this.#applied;
590
+ }
591
+
592
+ /** Feed the chain the same render-window evidence used by the frame budget. */
593
+ observeFrameBudget(window: IRenderChainBudgetWindow): RenderChainTier {
594
+ if (this.#disposed) throw new Error("RenderChain.observeFrameBudget called after dispose().");
595
+ if (!this.#automatic || this.#installation?.isCurrent() === false) return this.#tier;
596
+ const renderP95 = window.phases.render?.p95;
597
+ if (typeof renderP95 !== "number" || !Number.isFinite(renderP95) || renderP95 < 0) {
598
+ throw new Error("RenderChain frame budget render.p95 must be a finite non-negative number.");
599
+ }
600
+ const compiling = window.surface?.compiling;
601
+ if (compiling !== undefined && typeof compiling !== "boolean") {
602
+ throw new Error(
603
+ "RenderChain frame budget surface.compiling must be a boolean when observed.",
604
+ );
605
+ }
606
+ if (compiling === true) {
607
+ // Compilation is not steady-state render cost. It also retains resources that a tier
608
+ // rebuild disposes, so only consecutive clean windows may replace the active stages.
609
+ this.#overBudgetWindows = 0;
610
+ return this.#tier;
611
+ }
612
+ const budgetMs = 1_000 / this.#targetFps;
613
+ if (renderP95 > budgetMs) this.#overBudgetWindows += 1;
614
+ else this.#overBudgetWindows = 0;
615
+ if (this.#overBudgetWindows >= this.#dwellWindows) {
616
+ this.#overBudgetWindows = 0;
617
+ const next = nextLowerTier(this.#tier);
618
+ if (next !== this.#tier) {
619
+ this.#tier = next;
620
+ this.#source = "auto";
621
+ this.apply();
622
+ }
623
+ }
624
+ return this.#tier;
625
+ }
626
+
627
+ dispose(): void {
628
+ if (this.#disposed) return;
629
+ this.#disposed = true;
630
+ this.#disposeActiveStages();
631
+ this.#restoreOwnedVelocityOutput();
632
+ this.#renderer.setRenderChainVelocityEnabled?.(false);
633
+ this.#clearOwnedOutput();
634
+ forgetReport(this.#renderer);
635
+ }
636
+
637
+ #clearOwnedOutput(): void {
638
+ if (this.#installation !== undefined) this.#installation.dispose();
639
+ // Compatibility only: a void-returning adapter cannot distinguish same-node reinstalls.
640
+ else if (this.#installedNode !== undefined)
641
+ this.#renderer.clearOutputNode?.(this.#installedNode);
642
+ this.#installation = undefined;
643
+ this.#installedNode = undefined;
644
+ }
645
+
646
+ #setMeasurement(measurement: IRenderChainVelocityMeasurement | undefined, emit: boolean): void {
647
+ const { provisioned, required, source } = this.#applied.velocity;
648
+ this.#applied = {
649
+ ...this.#applied,
650
+ velocity: {
651
+ provisioned,
652
+ required,
653
+ source,
654
+ ...(measurement === undefined
655
+ ? {}
656
+ : {
657
+ measurementFrame: measurement.frame,
658
+ rejectionFraction: measurement.rejectionFraction,
659
+ }),
660
+ },
661
+ };
662
+ if (measurement !== undefined) this.#reportedMeasurement = true;
663
+ this.#publish(emit);
664
+ }
665
+
666
+ #publish(emit: boolean): void {
667
+ const marker: IRenderChainMarker = { applied: this.#applied, marker: RENDER_CHAIN_MARKER };
668
+ rememberReport(this.#renderer, marker);
669
+ if (emit) this.#report(`${RENDER_CHAIN_MARKER}:${JSON.stringify(marker)}`);
670
+ }
671
+
672
+ #restoreOwnedVelocityOutput(): void {
673
+ if (this.#ownedVelocityPass !== undefined && this.#ownedVelocityMrt !== undefined) {
674
+ this.#ownedVelocityPass.setMRT(this.#ownedVelocityMrt);
675
+ const target = this.#ownedVelocityPass.renderTarget;
676
+ const texture = this.#ownedVelocityTexture;
677
+ if (target !== undefined && texture !== undefined) {
678
+ const index = target.textures.indexOf(texture);
679
+ if (index !== -1) {
680
+ // Three must destroy the old GPU attachment set before the cached texture is detached.
681
+ target.dispose();
682
+ target.textures.splice(index, 1);
683
+ }
684
+ }
685
+ }
686
+ this.#ownedVelocityPass = undefined;
687
+ this.#ownedVelocityMrt = undefined;
688
+ this.#ownedVelocityTexture = undefined;
689
+ }
690
+
691
+ #disposeActiveStages(): void {
692
+ for (const definition of this.#activeStageDefinitions) definition.dispose?.();
693
+ this.#activeStageDefinitions = [];
694
+ }
695
+ }
696
+
697
+ function createStageDefinitions(
698
+ stages: readonly IRenderChainStage[],
699
+ ): ReadonlyMap<RenderChainStageId, IRenderChainStage> {
700
+ const definitions = new Map<RenderChainStageId, IRenderChainStage>();
701
+ for (const stage of stages) {
702
+ const name = requireStageId(stage.name, "render-chain stage");
703
+ if (definitions.has(name)) throw new Error(`duplicate render-chain stage '${stage.name}'`);
704
+ if (typeof stage.build !== "function")
705
+ throw new Error(`render-chain stage '${name}' needs a build function`);
706
+ const hasBefore = stage.before !== undefined;
707
+ const hasAfter = stage.after !== undefined;
708
+ if (stage.afterOutputTransform === true && (hasBefore || hasAfter)) {
709
+ throw new Error(
710
+ `render-chain stage '${name}' declares afterOutputTransform and an anchor; a stage that reads display-referred colour is last by construction, so an anchor is either ignored or wrong`,
711
+ );
712
+ }
713
+ if (isBuiltInStageId(name)) {
714
+ if (hasBefore || hasAfter) {
715
+ throw new Error(
716
+ `built-in render-chain stage '${name}' cannot declare before or after; its canonical order is fixed`,
717
+ );
718
+ }
719
+ } else if (hasBefore === hasAfter && stage.afterOutputTransform !== true) {
720
+ throw new Error(
721
+ `authored render-chain stage '${name}' must declare exactly one of before or after`,
722
+ );
723
+ }
724
+ if (hasBefore) requireStageId(stage.before, `render-chain stage '${name}' before anchor`);
725
+ if (hasAfter) requireStageId(stage.after, `render-chain stage '${name}' after anchor`);
726
+ definitions.set(name, stage);
727
+ }
728
+ for (const [name, stage] of definitions) {
729
+ const anchor = stage.before ?? stage.after;
730
+ if (anchor !== undefined && !isBuiltInStageId(anchor) && !definitions.has(anchor)) {
731
+ throw new Error(`render-chain stage '${name}' anchor '${anchor}' is missing`);
732
+ }
733
+ }
734
+ resolveStageOrder(definitions);
735
+ return definitions;
736
+ }
737
+
738
+ function normalizeRequestedStages(
739
+ stages: readonly RenderChainStageId[],
740
+ definitions: ReadonlyMap<RenderChainStageId, IRenderChainStage>,
741
+ ): readonly RenderChainStageId[] {
742
+ const requested = new Set<RenderChainStageId>();
743
+ for (const name of stages) {
744
+ const id = requireStageId(name, "requested render-chain stage");
745
+ if (requested.has(id)) throw new Error(`duplicate requested render-chain stage '${id}'`);
746
+ // A built-in needs no supplied definition, the same allowance the anchor check above makes.
747
+ // Requesting one the tier or the provider then drops is ordinary — `traa` at `tier: "off"`
748
+ // is a dropped stage with a reason, not an unknown name — and refusing it here turned that
749
+ // into a throw on the shipped path.
750
+ if (!isBuiltInStageId(id) && !definitions.has(id)) {
751
+ throw new Error(`unknown render-chain stage '${id}': no supplied definition`);
752
+ }
753
+ requested.add(id);
754
+ }
755
+ return resolveStageOrder(definitions, requested).filter((name) => requested.has(name));
756
+ }
757
+
758
+ function resolveStageOrder(
759
+ definitions: ReadonlyMap<RenderChainStageId, IRenderChainStage>,
760
+ additionalIds: Iterable<RenderChainStageId> = [],
761
+ ): readonly RenderChainStageId[] {
762
+ const ranks = new Map<RenderChainStageId, number>();
763
+ const visiting: RenderChainStageId[] = [];
764
+ const step = 1 / (definitions.size + 1);
765
+ const rank = (id: RenderChainStageId): number => {
766
+ const builtInIndex = RENDER_CHAIN_STAGE_ORDER.indexOf(id as RenderChainStageName);
767
+ if (builtInIndex >= 0) return builtInIndex;
768
+ const known = ranks.get(id);
769
+ if (known !== undefined) return known;
770
+ const cycleStart = visiting.indexOf(id);
771
+ if (cycleStart >= 0) {
772
+ const cycle = [...visiting.slice(cycleStart), id].join(" -> ");
773
+ throw new Error(`render-chain stage anchor cycle: ${cycle}`);
774
+ }
775
+ const definition = definitions.get(id);
776
+ if (definition === undefined) {
777
+ throw new Error(`render-chain stage '${id}' has no supplied definition`);
778
+ }
779
+ // The output transform's own seat. No stage may follow it, so it outranks every anchor
780
+ // without needing one, and it needs no anchor to be ordered.
781
+ if (definition.afterOutputTransform === true) {
782
+ ranks.set(id, RENDER_CHAIN_STAGE_ORDER.length + 1);
783
+ return ranks.get(id) as number;
784
+ }
785
+ const anchor = definition.before ?? definition.after;
786
+ if (anchor === undefined) {
787
+ throw new Error(`authored render-chain stage '${id}' has no anchor`);
788
+ }
789
+ visiting.push(id);
790
+ const anchorRank = rank(anchor);
791
+ visiting.pop();
792
+ const resolved = anchorRank + (definition.before === undefined ? step : -step);
793
+ ranks.set(id, resolved);
794
+ return resolved;
795
+ };
796
+
797
+ const ordered = [...new Set([...definitions.keys(), ...additionalIds])].map((id, index) => ({
798
+ id,
799
+ index,
800
+ rank: rank(id),
801
+ }));
802
+ ordered.sort((left, right) => left.rank - right.rank || left.index - right.index);
803
+ return ordered.map(({ id }) => id);
804
+ }
805
+
806
+ function requireStageId(value: unknown, label: string): RenderChainStageId {
807
+ if (typeof value !== "string" || value.trim().length === 0) {
808
+ throw new Error(`${label} id must be a non-blank string; received ${String(value)}`);
809
+ }
810
+ return value as RenderChainStageId;
811
+ }
812
+
813
+ function isBuiltInStageId(value: RenderChainStageId): value is RenderChainStageName {
814
+ return (RENDER_CHAIN_STAGE_ORDER as readonly string[]).includes(value);
815
+ }
816
+
817
+ function requiresVelocityFor(
818
+ definition: IRenderChainStage | undefined,
819
+ id: RenderChainStageId,
820
+ ): boolean {
821
+ return definition?.requiresVelocity ?? (isBuiltInStageId(id) && VELOCITY_STAGES.has(id));
822
+ }
823
+
824
+ function validateTier(value: unknown): RenderChainTier {
825
+ if (value === "high" || value === "medium" || value === "low" || value === "off") return value;
826
+ throw new Error(
827
+ `RenderChain tier must be high, medium, low, off, or auto; received ${String(value)}.`,
828
+ );
829
+ }
830
+
831
+ function resolveVelocity(
832
+ renderer: IRenderChainRenderer,
833
+ request: IRenderChainVelocityRequest,
834
+ scene: IRenderChainOptions["scene"],
835
+ required: boolean,
836
+ ): IRenderChainVelocityReport {
837
+ if (!required) return { provisioned: false, required: false, source: null };
838
+ const source =
839
+ request.source ??
840
+ (request.pass !== undefined || request.mrt === true || hasMrtVelocity(renderer.raw)
841
+ ? "mrt"
842
+ : undefined) ??
843
+ (request.objectFlags === true || request.perObject === true || hasObjectVelocityFlag(scene)
844
+ ? "per-object"
845
+ : null);
846
+ return { provisioned: source !== null, required: true, source };
847
+ }
848
+
849
+ function hasMrtVelocity(raw: unknown): boolean {
850
+ if (!isObject(raw)) return false;
851
+ const getMrt = raw.getMRT;
852
+ if (typeof getMrt === "function") {
853
+ try {
854
+ if (containsVelocity(getMrt.call(raw))) return true;
855
+ } catch {
856
+ return false;
857
+ }
858
+ }
859
+ return containsVelocity(raw.mrt) || containsVelocity(raw.mrtOutputs);
860
+ }
861
+
862
+ function containsVelocity(value: unknown): boolean {
863
+ if (value instanceof Set || value instanceof Map) return value.has("velocity");
864
+ if (Array.isArray(value)) return value.includes("velocity");
865
+ return isObject(value) && value.velocity === true;
866
+ }
867
+
868
+ function hasObjectVelocityFlag(scene: IRenderChainOptions["scene"]): boolean {
869
+ if (scene === undefined) return false;
870
+ let found = false;
871
+ scene.traverse((object) => {
872
+ if (object.userData?.useVelocity === true) found = true;
873
+ });
874
+ return found;
875
+ }
876
+
877
+ function stageContext(
878
+ tier: RenderChainTier,
879
+ velocity: IRenderChainVelocityReport,
880
+ velocityNode: Node | undefined,
881
+ resolutionSubrect: IResolutionTextureView | undefined,
882
+ ): IRenderChainStageContext {
883
+ return {
884
+ quality: RENDER_CHAIN_TIERS[tier],
885
+ tier,
886
+ velocity,
887
+ ...(velocityNode === undefined ? {} : { velocityNode }),
888
+ ...(resolutionSubrect === undefined ? {} : { resolutionSubrect }),
889
+ };
890
+ }
891
+
892
+ function deriveVelocityMeasurement(
893
+ result: IRenderChainVelocityResult,
894
+ previousFrame: number | undefined,
895
+ ): IRenderChainVelocityMeasurement {
896
+ if (!Number.isInteger(result.frame) || result.frame < 0) {
897
+ throw new Error(
898
+ `RenderChain velocity result frame must be a non-negative integer, received ${String(result.frame)}.`,
899
+ );
900
+ }
901
+ if (previousFrame !== undefined && result.frame <= previousFrame) {
902
+ throw new Error(
903
+ `RenderChain velocity result frame must advance beyond ${String(previousFrame)}, received ${String(result.frame)}.`,
904
+ );
905
+ }
906
+ if (!Number.isInteger(result.rejectionMask.length) || result.rejectionMask.length <= 0) {
907
+ throw new Error("RenderChain velocity result rejectionMask must contain at least one pixel.");
908
+ }
909
+ let rejected = 0;
910
+ for (let index = 0; index < result.rejectionMask.length; index += 1) {
911
+ const value = result.rejectionMask[index];
912
+ if (value !== 0 && value !== 1) {
913
+ throw new Error(
914
+ `RenderChain velocity result rejectionMask[${String(index)}] must be 0 or 1, received ${String(value)}.`,
915
+ );
916
+ }
917
+ rejected += value;
918
+ }
919
+ return {
920
+ frame: result.frame,
921
+ rejectionFraction: rejected / result.rejectionMask.length,
922
+ };
923
+ }
924
+
925
+ function validateCompatibilityMeasurement(
926
+ value: unknown,
927
+ previousFrame: number | undefined,
928
+ ): IRenderChainVelocityMeasurement | undefined {
929
+ if (value === undefined) return undefined;
930
+ if (!isObject(value))
931
+ throw new Error("RenderChain rejectionMeasurement must return an object or undefined.");
932
+ const frame = value.frame;
933
+ const rejectionFraction = value.rejectionFraction;
934
+ if (typeof frame !== "number" || !Number.isInteger(frame) || frame < 0) {
935
+ throw new Error(
936
+ `RenderChain rejectionMeasurement frame must be a non-negative integer, received ${String(frame)}.`,
937
+ );
938
+ }
939
+ if (previousFrame !== undefined && frame <= previousFrame) {
940
+ throw new Error(
941
+ `RenderChain rejectionMeasurement frame must advance beyond ${String(previousFrame)}, received ${String(frame)}.`,
942
+ );
943
+ }
944
+ if (
945
+ typeof rejectionFraction !== "number" ||
946
+ !Number.isFinite(rejectionFraction) ||
947
+ rejectionFraction < 0 ||
948
+ rejectionFraction > 1
949
+ ) {
950
+ throw new Error(
951
+ `RenderChain rejectionMeasurement rejectionFraction must be between 0 and 1, received ${String(rejectionFraction)}.`,
952
+ );
953
+ }
954
+ return { frame, rejectionFraction };
955
+ }
956
+
957
+ function emptyApplied(
958
+ requested: readonly RenderChainStageId[],
959
+ tier: RenderChainTier,
960
+ source: RenderChainSource,
961
+ required: boolean,
962
+ ): IRenderChainApplied {
963
+ return {
964
+ contributions: [],
965
+ dropped: [],
966
+ requested,
967
+ source,
968
+ stages: [],
969
+ tier,
970
+ velocity: { provisioned: false, required, source: null },
971
+ };
972
+ }
973
+
974
+ function nextLowerTier(tier: RenderChainTier): RenderChainTier {
975
+ if (tier === "high") return "medium";
976
+ if (tier === "medium") return "low";
977
+ if (tier === "low") return "off";
978
+ return "off";
979
+ }
980
+
981
+ function rememberReport(renderer: IRenderChainRenderer, marker: IRenderChainMarker): void {
982
+ if (isObject(renderer)) storeReport(renderer, marker);
983
+ if (isObject(renderer.raw)) storeReport(renderer.raw, marker);
984
+ }
985
+
986
+ function forgetReport(renderer: IRenderChainRenderer): void {
987
+ if (isObject(renderer)) storeReport(renderer, undefined);
988
+ if (isObject(renderer.raw)) storeReport(renderer.raw, undefined);
989
+ }
990
+
991
+ function readRawRenderer(renderer: object): unknown {
992
+ return "raw" in renderer ? renderer.raw : renderer;
993
+ }
994
+
995
+ function isRenderer(
996
+ value: IRenderChainRenderer | IRenderChainOptions,
997
+ ): value is IRenderChainRenderer {
998
+ return isObject(value) && "kind" in value && "setOutputNode" in value;
999
+ }
1000
+
1001
+ function isObject(value: unknown): value is Record<string, unknown> {
1002
+ return typeof value === "object" && value !== null;
1003
+ }
1004
+
1005
+ function errorMessage(error: unknown): string {
1006
+ return error instanceof Error ? error.message : String(error);
1007
+ }
1008
+
1009
+ function requirePositiveInteger(value: number, name: string): number {
1010
+ if (!Number.isInteger(value) || value <= 0)
1011
+ throw new Error(`RenderChain ${name} must be a positive integer.`);
1012
+ return value;
1013
+ }
1014
+
1015
+ function requirePositiveNumber(value: number, name: string): number {
1016
+ if (!Number.isFinite(value) || value <= 0)
1017
+ throw new Error(`RenderChain ${name} must be a finite positive number.`);
1018
+ return value;
1019
+ }
1020
+
1021
+ export type { RendererKind };