@threenative/core 0.3.5 → 0.3.8

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 (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Bj8G1wmD.d.ts → game-cb99J-YE.d.ts} +112 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22445 -12411
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +59 -10
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +544 -106
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +40 -6
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +69 -12
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
@@ -177,6 +177,17 @@ export class ProjectionStability {
177
177
  return this.#watchedCount;
178
178
  }
179
179
 
180
+ /** Distinct materials the last scan read — the list `holds` walks. It must describe the scene,
181
+ * never the number of scans run, so a spec pins it. */
182
+ get watchedMaterialCount(): number {
183
+ return this.#materials.length;
184
+ }
185
+
186
+ /** Distinct geometries the last scan read. Same contract as {@link watchedMaterialCount}. */
187
+ get watchedGeometryCount(): number {
188
+ return this.#geometries.length;
189
+ }
190
+
180
191
  /**
181
192
  * The exact lane the last scan classified, repooled for this frame's apply.
182
193
  *
@@ -201,6 +212,11 @@ export class ProjectionStability {
201
212
  record(source: Scene, scan: IProjectionScanResult): void {
202
213
  this.#materialSet.clear();
203
214
  this.#geometrySet.clear();
215
+ // The lists hold what *this* scan read, exactly like `#nodes` and `#watched`: without this every
216
+ // re-record appends another copy of the scene's materials and geometries and `holds()` pays for
217
+ // the log, not the scene.
218
+ this.#materials.length = 0;
219
+ this.#geometries.length = 0;
204
220
  const nodes = this.#nodes;
205
221
  const stack = this.#stack;
206
222
  const stackVisible = this.#stackVisible;
@@ -76,7 +76,11 @@ const opaqueIds = new WeakMap<object, number>();
76
76
  let nextOpaqueId = 1;
77
77
 
78
78
  function isTextureValue(value: unknown): boolean {
79
- return value !== null && (value as { isTexture?: boolean }).isTexture === true;
79
+ return (
80
+ typeof value === "object" &&
81
+ value !== null &&
82
+ (value as { isTexture?: boolean }).isTexture === true
83
+ );
80
84
  }
81
85
 
82
86
  /**
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Keeps the browser console quiet: a `console.log` / `console.info` line whose first argument
3
+ * starts with `TN_` goes to `console.debug` instead, which DevTools hides at its default level and
4
+ * Playwright still receives. `warn`, `error` and every other line are untouched.
5
+ *
6
+ * The flag that prints markers at their own level has the same three seams as `spansRequested()`:
7
+ * `TN_LOG` through `process.env`, `?tnLog=1` in the page URL, and `globalThis.__THREENATIVE_LOG__`
8
+ * (the worker host forwards `__THREENATIVE_` page globals, so a worker game follows the page).
9
+ * Only a real browser page installs it: the native host stubs `document.location` but sets no
10
+ * `globalThis.location`, so a native game keeps its console as the host prints it.
11
+ */
12
+ const LOG_FLAG = "TN_LOG";
13
+ const BROWSER_PROTOCOLS = new Set(["http:", "https:", "file:"]);
14
+
15
+ type ConsoleMethod = (...args: unknown[]) => void;
16
+ let restore: { log: ConsoleMethod; info: ConsoleMethod } | undefined;
17
+
18
+ const isOn = (value: unknown): boolean =>
19
+ value === true ||
20
+ (typeof value === "string" && value !== "" && value !== "0" && value !== "false");
21
+
22
+ /** Whether `TN_LOG` asks for markers at their own console level on this launch. */
23
+ export function markerLogRequested(): boolean {
24
+ const host = globalThis as { process?: { env?: Record<string, unknown> } };
25
+ if (isOn(host.process?.env?.[LOG_FLAG])) return true;
26
+ const query = globalThis.location?.search;
27
+ if (typeof query === "string" && /[?&]tnLog=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query))
28
+ return true;
29
+ return isOn((globalThis as Record<string, unknown>).__THREENATIVE_LOG__);
30
+ }
31
+
32
+ /** Re-routes `TN_` log/info lines to `console.debug`; a second call is a no-op. */
33
+ export function installQuietMarkers(): void {
34
+ const protocol = globalThis.location?.protocol;
35
+ if (restore !== undefined || typeof protocol !== "string" || !BROWSER_PROTOCOLS.has(protocol))
36
+ return;
37
+ if (markerLogRequested()) return;
38
+ const original = { log: console.log, info: console.info };
39
+ const quiet =
40
+ (method: ConsoleMethod): ConsoleMethod =>
41
+ (...args) => {
42
+ if (typeof args[0] === "string" && args[0].startsWith("TN_")) console.debug(...args);
43
+ else method.apply(console, args);
44
+ };
45
+ console.log = quiet(original.log);
46
+ console.info = quiet(original.info);
47
+ restore = original;
48
+ }
49
+
50
+ /** Puts back the exact console methods `installQuietMarkers` replaced. */
51
+ export function uninstallQuietMarkers(): void {
52
+ if (restore === undefined) return;
53
+ console.log = restore.log;
54
+ console.info = restore.info;
55
+ restore = undefined;
56
+ }
@@ -0,0 +1,256 @@
1
+ import {
2
+ FrameTimeBudget,
3
+ type FrameTimeModel,
4
+ type IFrameTimeBudgetOptions,
5
+ } from "./frame-time-budget.js";
6
+
7
+ /**
8
+ * A cost ladder for one stage: the stage runs at one level, and the whole GPU frame moves it. The
9
+ * frame-period rule of `FrameTimeBudget` (Unreal's DynamicRenderScaling heuristic) says when the
10
+ * frame is too dear or has room. A stage steps down only when it could absorb the overage even at
11
+ * zero cost, so a frame that another stage made slow keeps its level. A level that failed waits a
12
+ * growing number of frames before the next try, because the cheaper level's own reading cannot say
13
+ * what the dearer one would cost.
14
+ *
15
+ * Measurement and decision only. What a level draws belongs to the game, which applies the step.
16
+ * The same ladder serves the shadow filter samples (`ShadowFilterBudget`) and, with one level, the
17
+ * GI report (`GIBudget`).
18
+ */
19
+
20
+ export interface IBudgetLadderOptions<L extends string> {
21
+ /** Levels from the cheapest to the dearest. */
22
+ readonly levels: readonly L[];
23
+ /** The level the stage starts at. */
24
+ readonly start: L;
25
+ /** The author fixed the level: an over-budget frame is reported and the level never changes. */
26
+ readonly explicit?: boolean;
27
+ /** The frame period in milliseconds, such as 1000 / 60. The rule compares the whole GPU frame with it. */
28
+ readonly framePeriodMs: number;
29
+ /** The Unreal settings of the rule. Defaults are the primary dynamic resolution ones. */
30
+ readonly rule?: Omit<IFrameTimeBudgetOptions, "periodMs">;
31
+ /** Frames per report when nothing moves. Default 120. */
32
+ readonly windowFrames?: number;
33
+ /** Frames to wait before retrying a level that failed once; each further failure doubles it. Default 600. */
34
+ readonly retryFrames?: number;
35
+ }
36
+
37
+ export type BudgetVerdict = "over" | "within" | "under" | "unobserved";
38
+
39
+ /** One closed window: a report every `windowFrames` frames, or earlier when the level moves. */
40
+ export interface IBudgetWindow<L extends string> {
41
+ /** 1 for the first window the ladder closes. */
42
+ readonly number: number;
43
+ readonly level: L;
44
+ /** Mean of the stage's resolved readings, or `undefined` when none resolved. */
45
+ readonly windowMs: number | undefined;
46
+ /** The frame period the rule compares the GPU frame with. */
47
+ readonly periodMs: number;
48
+ /** The period less its headroom: the frame the rule steers to. */
49
+ readonly targetMs: number;
50
+ /** Frames in the window. */
51
+ readonly frames: number;
52
+ /** Frames in the window with a resolved whole-frame reading. */
53
+ readonly samples: number;
54
+ /** Mean of the whole frame's readings in the window, or `undefined` when none resolved. */
55
+ readonly frameMs: number | undefined;
56
+ readonly verdict: BudgetVerdict;
57
+ /** The level the ladder moved to when this window moved it. */
58
+ readonly stepped: L | undefined;
59
+ /** Two consecutive frames over the period moved the level without the change-period gate. */
60
+ readonly panic: boolean;
61
+ /** The frame was over the target but the stage could not absorb the overage even at zero cost. */
62
+ readonly notBlamed: boolean;
63
+ readonly explicit: boolean;
64
+ }
65
+
66
+ const DEFAULT_WINDOW_FRAMES = 120;
67
+ const DEFAULT_RETRY_FRAMES = 600;
68
+ /** A level that keeps failing is retried at most this many frames apart. */
69
+ const MAX_RETRY_FRAMES = 160 * DEFAULT_WINDOW_FRAMES;
70
+
71
+ function positiveInteger(value: number, name: string): number {
72
+ if (!Number.isInteger(value) || value < 1)
73
+ throw new RangeError(`BudgetLadder ${name} must be an integer of at least one, got ${value}.`);
74
+ return value;
75
+ }
76
+
77
+ export type { FrameTimeModel };
78
+
79
+ export class BudgetLadder<L extends string> {
80
+ readonly #levels: readonly L[];
81
+ readonly #explicit: boolean;
82
+ readonly #windowFrames: number;
83
+ readonly #retryFrames: number;
84
+ readonly #rule: FrameTimeBudget;
85
+ readonly #historyFrames: number;
86
+ #index: number;
87
+ #frames = 0;
88
+ #frameSamples = 0;
89
+ #frameSum = 0;
90
+ #stageSamples = 0;
91
+ #stageSum = 0;
92
+ #windowNumber = 0;
93
+ #loopFrame = 0;
94
+ #panic = false;
95
+ #notBlamed = false;
96
+ /** The newest readings the rule reads, to size the stage against the overage. */
97
+ #recent: { frame: number; stage: number | undefined }[] = [];
98
+ /** Failure count, the loop frame before which a level may not be tried again, and what the level cost in its failed window. */
99
+ readonly #failures = new Map<L, { count: number; retryAt: number; ms: number }>();
100
+
101
+ constructor(options: IBudgetLadderOptions<L>) {
102
+ if (options.levels.length === 0) throw new RangeError("BudgetLadder levels must not be empty.");
103
+ const start = options.levels.indexOf(options.start);
104
+ if (start === -1)
105
+ throw new RangeError(`BudgetLadder start ${String(options.start)} is not one of its levels.`);
106
+ this.#levels = options.levels;
107
+ this.#index = start;
108
+ this.#explicit = options.explicit === true;
109
+ this.#windowFrames = positiveInteger(
110
+ options.windowFrames ?? DEFAULT_WINDOW_FRAMES,
111
+ "windowFrames",
112
+ );
113
+ this.#retryFrames = positiveInteger(options.retryFrames ?? DEFAULT_RETRY_FRAMES, "retryFrames");
114
+ this.#rule = new FrameTimeBudget({ ...options.rule, periodMs: options.framePeriodMs });
115
+ this.#historyFrames = Math.floor(options.rule?.historyFrames ?? 16);
116
+ }
117
+
118
+ get level(): L {
119
+ return this.#levels[this.#index] as L;
120
+ }
121
+
122
+ get explicit(): boolean {
123
+ return this.#explicit;
124
+ }
125
+
126
+ get periodMs(): number {
127
+ return this.#rule.periodMs;
128
+ }
129
+
130
+ get targetMs(): number {
131
+ return this.#rule.targetMs;
132
+ }
133
+
134
+ /**
135
+ * Feeds one loop frame. `ms` is the stage's GPU time and `frameMs` the whole frame's; `undefined`
136
+ * is a frame whose GPU time has not resolved. Returns the closed window on the frame that ends
137
+ * one or moves the level, `undefined` while a window is open.
138
+ */
139
+ observe(ms: number | undefined, frameMs?: number): IBudgetWindow<L> | undefined {
140
+ for (const value of [ms, frameMs]) {
141
+ if (value !== undefined && (!Number.isFinite(value) || value < 0))
142
+ throw new RangeError(
143
+ `BudgetLadder readings must be finite and at least zero, got ${value}.`,
144
+ );
145
+ }
146
+ this.#loopFrame += 1;
147
+ this.#frames += 1;
148
+ if (ms !== undefined) {
149
+ this.#stageSamples += 1;
150
+ this.#stageSum += ms;
151
+ }
152
+ if (frameMs !== undefined) {
153
+ this.#frameSamples += 1;
154
+ this.#frameSum += frameMs;
155
+ this.#recent.push({ frame: frameMs, stage: ms });
156
+ if (this.#recent.length > this.#historyFrames) this.#recent.shift();
157
+ }
158
+ const decision = this.#rule.observe(frameMs);
159
+ const from = this.level;
160
+ let stepped: L | undefined;
161
+ if (decision.direction === "down")
162
+ stepped = this.#down(decision.panic, decision.frames, decision.meanMs);
163
+ else if (decision.direction === "up") stepped = this.#up();
164
+ if (stepped !== undefined) {
165
+ this.#rule.reset();
166
+ this.#recent = [];
167
+ return this.#close(from, stepped);
168
+ }
169
+ return this.#frames < this.#windowFrames ? undefined : this.#close(from, undefined);
170
+ }
171
+
172
+ #down(panic: boolean, frames: number, meanMs: number | undefined): L | undefined {
173
+ const lower = this.#index - 1;
174
+ if (this.#explicit || lower < 0 || meanMs === undefined) return undefined;
175
+ // The stage steps only when zero cost would fit the frame: the overage of the frames the rule read
176
+ // (the newest `frames` of them, which are 2 on a panic) must not exceed the stage time of the same frames.
177
+ const read = this.#recent.slice(-frames);
178
+ const stages = read.flatMap((r) => (r.stage === undefined ? [] : [r.stage]));
179
+ if (stages.length === 0) return undefined;
180
+ const stage = mean(stages) as number;
181
+ const overage = meanMs - this.#rule.targetMs;
182
+ if (!(stage >= overage && overage > 0)) {
183
+ this.#notBlamed = true;
184
+ return undefined;
185
+ }
186
+ this.#panic = panic;
187
+ this.#fail(this.level, stage);
188
+ this.#index = lower;
189
+ return this.level;
190
+ }
191
+
192
+ #up(): L | undefined {
193
+ const upper = this.#index + 1;
194
+ const upperLevel = this.#levels[upper];
195
+ if (this.#explicit || upperLevel === undefined) return undefined;
196
+ if (this.#loopFrame < (this.#failures.get(upperLevel)?.retryAt ?? 0)) return undefined;
197
+ const frame = mean(this.#recent.map((r) => r.frame));
198
+ if (frame === undefined) return undefined;
199
+ const stages = this.#recent.flatMap((r) => (r.stage === undefined ? [] : [r.stage]));
200
+ const stage = mean(stages) ?? 0;
201
+ // The dearer level may cost what it cost when it last failed, over what the stage costs now.
202
+ const extra = Math.max(0, (this.#failures.get(upperLevel)?.ms ?? 0) - stage);
203
+ if (frame + extra > this.#rule.targetMs) return undefined;
204
+ this.#index = upper;
205
+ return upperLevel;
206
+ }
207
+
208
+ #close(ranAt: L, stepped: L | undefined): IBudgetWindow<L> {
209
+ this.#windowNumber += 1;
210
+ const frameMs = this.#frameSamples > 0 ? this.#frameSum / this.#frameSamples : undefined;
211
+ const stageMs = this.#stageSamples > 0 ? this.#stageSum / this.#stageSamples : undefined;
212
+ const down =
213
+ stepped !== undefined && this.#levels.indexOf(stepped) < this.#levels.indexOf(ranAt);
214
+ let verdict: BudgetVerdict;
215
+ if (stepped !== undefined) verdict = down ? "over" : "under";
216
+ else if (frameMs === undefined) verdict = "unobserved";
217
+ else verdict = frameMs > this.#rule.targetMs ? "over" : "within";
218
+ const window: IBudgetWindow<L> = {
219
+ explicit: this.#explicit,
220
+ frameMs,
221
+ frames: this.#frames,
222
+ level: ranAt,
223
+ notBlamed: this.#notBlamed,
224
+ number: this.#windowNumber,
225
+ panic: this.#panic,
226
+ periodMs: this.#rule.periodMs,
227
+ samples: this.#frameSamples,
228
+ stepped,
229
+ targetMs: this.#rule.targetMs,
230
+ verdict,
231
+ windowMs: stageMs,
232
+ };
233
+ this.#frames = 0;
234
+ this.#frameSamples = 0;
235
+ this.#frameSum = 0;
236
+ this.#stageSamples = 0;
237
+ this.#stageSum = 0;
238
+ this.#panic = false;
239
+ this.#notBlamed = false;
240
+ return window;
241
+ }
242
+
243
+ /** The level failed at `ms`: wait longer each time before trying it again. */
244
+ #fail(level: L, ms: number): void {
245
+ const count = (this.#failures.get(level)?.count ?? 0) + 1;
246
+ const wait = Math.min(MAX_RETRY_FRAMES, this.#retryFrames * 2 ** (count - 1));
247
+ this.#failures.set(level, { count, retryAt: this.#loopFrame + wait, ms });
248
+ }
249
+ }
250
+
251
+ function mean(values: readonly number[]): number | undefined {
252
+ if (values.length === 0) return undefined;
253
+ let sum = 0;
254
+ for (const v of values) sum += v;
255
+ return sum / values.length;
256
+ }
@@ -74,17 +74,26 @@ const TIER_LEVEL: Record<RenderChainTier, number> = {
74
74
  off: 0,
75
75
  };
76
76
 
77
- /** Quality values are algorithm parameters, not appearance values. Templates own the latter. */
77
+ /**
78
+ * Quality values are algorithm parameters, not appearance values. Templates own the latter.
79
+ *
80
+ * `ssrMaxSteps` caps the mirror reflection march as Unreal caps it per tier (UE 5.8.3:
81
+ * Engine/Shaders/Private/SSRT/SSRTReflections.usf:198-216, Engine/Config/BaseScalability.ini
82
+ * `[ReflectionQuality@N]`). `high` is Epic, `r.SSR.Quality` 3: 8 steps on each of 4 rays, so the
83
+ * one mirror ray gets the 32 steps. `medium` is Medium, quality 2: 16 steps on 1 ray. `low` takes
84
+ * quality 1, 8 steps on 1 ray.
85
+ */
78
86
  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 },
87
+ high: { denoiseIterations: 3, sliceCount: 3, ssrMaxSteps: 32, stepCount: 16 },
88
+ low: { denoiseIterations: 1, sliceCount: 1, ssrMaxSteps: 8, stepCount: 12 },
89
+ medium: { denoiseIterations: 2, sliceCount: 2, ssrMaxSteps: 16, stepCount: 8 },
90
+ off: { denoiseIterations: 0, sliceCount: 0, ssrMaxSteps: 0, stepCount: 0 },
83
91
  } as const satisfies Record<
84
92
  RenderChainTier,
85
93
  {
86
94
  denoiseIterations: number;
87
95
  sliceCount: number;
96
+ ssrMaxSteps: number;
88
97
  stepCount: number;
89
98
  }
90
99
  >;
@@ -185,6 +194,13 @@ export interface IRenderChainVelocityReport {
185
194
  }
186
195
 
187
196
  export interface IRenderChainApplied {
197
+ /** Actual GPU allocation sizes, absent until the owned temporal pass has rendered. */
198
+ readonly stageSizes?: {
199
+ readonly traa: {
200
+ readonly input: readonly [number, number];
201
+ readonly output: readonly [number, number];
202
+ };
203
+ };
188
204
  readonly contributions: readonly {
189
205
  readonly graphOutputChanged: boolean;
190
206
  readonly name: RenderChainStageId;
@@ -274,6 +290,26 @@ export function readRenderChainObservation(
274
290
  return readRenderChainReport(renderer)?.applied;
275
291
  }
276
292
 
293
+ /**
294
+ * Print `TN_RENDER_CHAIN` and remember the report for a frame that installs no chain because no stage
295
+ * is requested, so a game that turns every post stage off still reports its tier. Returns the forget call.
296
+ * @situation a `renderChain` playtest assertion on a game whose look runs no post stage
297
+ */
298
+ export function publishDirectRenderChainReport(
299
+ renderer: Pick<IRenderChainRenderer, "raw">,
300
+ tier: RenderChainTier,
301
+ dropped: readonly IRenderChainDroppedStage[],
302
+ report: (line: string) => void = (line) => console.log(line),
303
+ ): () => void {
304
+ const marker: IRenderChainMarker = {
305
+ applied: { ...emptyApplied([], tier, "pinned", false), dropped },
306
+ marker: RENDER_CHAIN_MARKER,
307
+ };
308
+ rememberReport(renderer, marker);
309
+ report(`${RENDER_CHAIN_MARKER}:${JSON.stringify(marker)}`);
310
+ return () => forgetReport(renderer);
311
+ }
312
+
277
313
  /**
278
314
  * Compose game-provided nodes through one ordered, measured, honest render seam.
279
315
  *
@@ -567,6 +603,7 @@ export class RenderChain {
567
603
  observeFrame(): IRenderChainApplied {
568
604
  if (this.#disposed) throw new Error("RenderChain.observeFrame called after dispose().");
569
605
  if (this.#installation?.isCurrent() === false) return this.#applied;
606
+ this.#observeStageSizes();
570
607
  const requiresMeasurement = this.#applied.stages.some((name) =>
571
608
  requiresVelocityFor(this.#stageDefinitions.get(name), name),
572
609
  );
@@ -643,6 +680,48 @@ export class RenderChain {
643
680
  this.#installedNode = undefined;
644
681
  }
645
682
 
683
+ #observeStageSizes(): void {
684
+ const raw = this.#renderer.raw;
685
+ const engine = isObject(raw) && isObject(raw.info) ? raw.info.engine : undefined;
686
+ const temporal = isObject(engine) ? engine.temporal : undefined;
687
+ const dimensions = isObject(temporal)
688
+ ? [temporal.inputWidth, temporal.inputHeight, temporal.outputWidth, temporal.outputHeight]
689
+ : [];
690
+ const sizes =
691
+ this.#applied.stages.includes("traa") &&
692
+ isObject(temporal) &&
693
+ temporal.active === true &&
694
+ dimensions.length === 4 &&
695
+ dimensions.every(
696
+ (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0,
697
+ )
698
+ ? (dimensions as [number, number, number, number])
699
+ : undefined;
700
+ const old = this.#applied.stageSizes?.traa;
701
+ if (sizes === undefined && old === undefined) return;
702
+ if (
703
+ sizes !== undefined &&
704
+ old !== undefined &&
705
+ old.input[0] === sizes[0] &&
706
+ old.input[1] === sizes[1] &&
707
+ old.output[0] === sizes[2] &&
708
+ old.output[1] === sizes[3]
709
+ )
710
+ return;
711
+ const { stageSizes: _previousSizes, ...applied } = this.#applied;
712
+ this.#applied = {
713
+ ...applied,
714
+ ...(sizes === undefined
715
+ ? {}
716
+ : {
717
+ stageSizes: {
718
+ traa: { input: [sizes[0], sizes[1]] as const, output: [sizes[2], sizes[3]] as const },
719
+ },
720
+ }),
721
+ };
722
+ this.#publish(true);
723
+ }
724
+
646
725
  #setMeasurement(measurement: IRenderChainVelocityMeasurement | undefined, emit: boolean): void {
647
726
  const { provisioned, required, source } = this.#applied.velocity;
648
727
  this.#applied = {
@@ -978,12 +1057,15 @@ function nextLowerTier(tier: RenderChainTier): RenderChainTier {
978
1057
  return "off";
979
1058
  }
980
1059
 
981
- function rememberReport(renderer: IRenderChainRenderer, marker: IRenderChainMarker): void {
1060
+ function rememberReport(
1061
+ renderer: Pick<IRenderChainRenderer, "raw">,
1062
+ marker: IRenderChainMarker,
1063
+ ): void {
982
1064
  if (isObject(renderer)) storeReport(renderer, marker);
983
1065
  if (isObject(renderer.raw)) storeReport(renderer.raw, marker);
984
1066
  }
985
1067
 
986
- function forgetReport(renderer: IRenderChainRenderer): void {
1068
+ function forgetReport(renderer: Pick<IRenderChainRenderer, "raw">): void {
987
1069
  if (isObject(renderer)) storeReport(renderer, undefined);
988
1070
  if (isObject(renderer.raw)) storeReport(renderer.raw, undefined);
989
1071
  }
@@ -0,0 +1,59 @@
1
+ // Photometric exposure plumbing (PRD-632). The values — which EV100, which sun lux — are the
2
+ // game's and live in its `src/render/`; this file only converts between the units.
3
+ //
4
+ // Saturation-based exposure for a sensor at ISO 100 (ISO 2720, as used by Lagarde and de
5
+ // Rousiers, "Moving Frostbite to PBR", 2014): the luminance that saturates the sensor is
6
+ // 1.2 * 2^EV100 cd/m², so scaling scene luminance by its reciprocal maps that luminance to 1.
7
+ // Reflected-light metering uses the calibration constant K = 12.5.
8
+
9
+ const SATURATION = 1.2;
10
+ const METER_CALIBRATION = 12.5;
11
+
12
+ /** The renderer multiplier for an exposure value at ISO 100.
13
+ * @situation expose a frame lit in lux and nits with a physical camera exposure value
14
+ * @constraint ev100 must be finite; a unitless scene keeps its own multiplier instead
15
+ * @example renderer.toneMappingExposure = exposureFromEv100(14.5);
16
+ */
17
+ export function exposureFromEv100(ev100: number): number {
18
+ if (!Number.isFinite(ev100))
19
+ throw new RangeError(`exposureFromEv100: ev100 ${ev100} is not finite`);
20
+ return 1 / (SATURATION * 2 ** ev100);
21
+ }
22
+
23
+ /** The exposure value at ISO 100 that a renderer multiplier stands for.
24
+ * @situation report a hand-set exposure multiplier as an EV100
25
+ * @constraint multiplier must be finite and greater than zero
26
+ * @example const ev = ev100FromExposure(renderer.toneMappingExposure);
27
+ */
28
+ export function ev100FromExposure(multiplier: number): number {
29
+ if (!(multiplier > 0) || !Number.isFinite(multiplier))
30
+ throw new RangeError(`ev100FromExposure: multiplier ${multiplier} must be finite and > 0`);
31
+ return -Math.log2(SATURATION * multiplier);
32
+ }
33
+
34
+ /** The exposure value at ISO 100 of a physical camera: aperture f-number, shutter seconds, ISO.
35
+ * @situation expose like a camera with an aperture, a shutter time and an ISO
36
+ * @constraint every argument must be finite and greater than zero
37
+ * @example const ev = ev100FromCamera(4, 1 / 60, 100); // 9.91
38
+ */
39
+ export function ev100FromCamera(aperture: number, shutterSeconds: number, iso: number): number {
40
+ for (const [name, value] of [
41
+ ["aperture", aperture],
42
+ ["shutterSeconds", shutterSeconds],
43
+ ["iso", iso],
44
+ ] as const)
45
+ if (!(value > 0) || !Number.isFinite(value))
46
+ throw new RangeError(`ev100FromCamera: ${name} ${value} must be finite and > 0`);
47
+ return Math.log2(((aperture * aperture) / shutterSeconds) * (100 / iso));
48
+ }
49
+
50
+ /** The exposure value at ISO 100 that a reflected-light meter reads for an average luminance.
51
+ * @situation meter a frame's average luminance in cd/m² into an exposure value
52
+ * @constraint luminance must be finite and greater than zero
53
+ * @example const ev = ev100FromLuminance(averageNits);
54
+ */
55
+ export function ev100FromLuminance(luminance: number): number {
56
+ if (!(luminance > 0) || !Number.isFinite(luminance))
57
+ throw new RangeError(`ev100FromLuminance: luminance ${luminance} must be finite and > 0`);
58
+ return Math.log2((luminance * 100) / METER_CALIBRATION);
59
+ }