@threenative/three-native 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.
@@ -5,25 +5,46 @@
5
5
  * engine did. What it does not implement throws its diagnostic rather than doing nothing.
6
6
  */
7
7
  import { TSL_NODE, type TnAbiModule, engineRef } from "./browser-backend.js";
8
- import { type ITslRuntime, isTslNode } from "./browser-tsl.js";
8
+ import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
9
+ import { debugTelemetry } from "./debug-telemetry.js";
10
+ import {
11
+ CPU_STAGE_ENTRIES,
12
+ type CpuStageName,
13
+ GPU_STAGES,
14
+ SHADOW_SEGMENT_FIELD,
15
+ SHADOW_STAGE,
16
+ WORK_COUNT_NAMES,
17
+ type WorkCountName,
18
+ } from "./gpu-stages.js";
9
19
  import type { PassDraw } from "./pass-node.js";
10
- import { defineRenderTargets } from "./render-target.js";
20
+ import { defineRenderTargets, targetTexelBytes } from "./render-target.js";
11
21
  import { ShadowMap } from "./shadow-map.js";
22
+ import { syncVirtualShadowLods } from "./shadow-node.js";
23
+ import { defineSphereReflectionCapture } from "./sphere-reflection-capture.js";
12
24
  import { readStorageBytes } from "./storage.js";
25
+ import type { INodeFrame } from "./temp-node.js";
26
+ import { defineToneMappingLibrary } from "./tone-mapping.js";
13
27
 
14
28
  /** The product host's exports beside the catalog ABI (all numbers: pointers, sizes, status). */
15
29
  type HostCall =
16
30
  | "_tnw_web_init"
31
+ | "_tnw_web_host_abi"
17
32
  | "_tnw_web_poll"
18
33
  | "_tnw_web_error"
19
34
  | "_tnw_web_adapter"
20
35
  | "_tnw_web_resize"
21
36
  | "_tnw_web_render"
37
+ | "_tnw_web_prepare_environment"
38
+ | "_tnw_web_set_presentation_hold"
39
+ | "_tnw_web_compile_async"
40
+ | "_tnw_web_compile_status"
22
41
  | "_tnw_web_renderer_state"
23
42
  | "_tnw_web_frame"
24
43
  | "_tnw_web_render_target"
25
44
  | "_tnw_web_read_target"
26
- | "_tnw_web_read_target_take";
45
+ | "_tnw_web_read_target_take"
46
+ | "_tnw_web_capture_face"
47
+ | "_tnw_web_threads";
27
48
 
28
49
  export type WebHostModule = Record<HostCall, (...args: number[]) => number> & {
29
50
  readonly specialHTMLTargets: Record<string, unknown>;
@@ -35,13 +56,26 @@ export function isWebHostModule(module: TnAbiModule): module is WebEngineModule
35
56
  return typeof (module as Partial<WebHostModule>)._tnw_web_init === "function";
36
57
  }
37
58
 
59
+ /**
60
+ * The tnw_* contract this facade speaks (web_host.cpp `kWebHostAbi`). Bump both on every tnw_*
61
+ * signature change: web-host-abi.spec.ts pins the signatures per number, and a mismatch fails init.
62
+ */
63
+ export const WEB_HOST_ABI = 8;
64
+
38
65
  /** The canvas key the host's surface looks up; Emscripten resolves it before any DOM query. */
39
66
  const CANVAS_TARGET = "!threenative-canvas";
40
67
  const READY = 1;
41
68
  /** The facade's own redraw, for RenderPipeline (browser-entry.ts). */
42
69
  export const RENDER_AGAIN = Symbol("tn.renderAgain");
70
+ /** The last RenderPipeline's post graph install, which the warm-up entry points run first (browser-entry.ts). */
71
+ export const PIPELINE_POST = Symbol("tn.pipelinePost");
43
72
  const DRAW_TARGET = Symbol("tn.drawTarget");
44
73
  const FAILED = 2;
74
+ /**
75
+ * `tnw_web_frame` field of the first named stage's segment (web_host.cpp): 19 + 4 shadow, scene, other and output
76
+ * passes. `GPU_STAGES` counts on from there, one segment per stage.
77
+ */
78
+ const GPU_STAGE_FIELD = 23;
45
79
 
46
80
  interface IAdapterInfo {
47
81
  readonly vendor: string;
@@ -56,24 +90,54 @@ interface IColorLike {
56
90
  readonly b: number;
57
91
  }
58
92
 
93
+ /** Resolves once compilation `id` (0: it never started) has built every pipeline; rejects naming the refusal. */
94
+ async function compiled(module: WebEngineModule, id: number): Promise<void> {
95
+ const refused = (): Error => new Error(module.UTF8ToString(module._tnw_web_error()));
96
+ if (id === 0) throw refused();
97
+ for (;;) {
98
+ const status = module._tnw_web_compile_status(id);
99
+ if (status === 1) return;
100
+ if (status < 0) throw refused();
101
+ // A macrotask: the browser delivers the pipelines' completions between tasks.
102
+ await new Promise((resolve) => setTimeout(resolve, 0));
103
+ }
104
+ }
105
+
59
106
  function unsupported(name: string): never {
60
107
  throw new Error(`TN_NATIVE_UNSUPPORTED_${name.toUpperCase()}: not available on the Wasm engine.`);
61
108
  }
62
109
 
63
110
  /** Defines the renderer class over one loaded module; the module owns one device and one canvas. */
111
+ /** A scene environment as the bake record reads it: the engine keys its bake by texture and version. */
112
+ interface IBakedEnvironment {
113
+ readonly version: number;
114
+ addEventListener?(type: "dispose", listener: () => void): void;
115
+ }
116
+
117
+ /** Environments a draw saw baked, at the version it saw; a disposal retires the engine's bake too. */
118
+ const bakedEnvironments = new WeakMap<IBakedEnvironment, number>();
119
+
120
+ function markBaked(environment: IBakedEnvironment): void {
121
+ if (!bakedEnvironments.has(environment))
122
+ environment.addEventListener?.("dispose", () => bakedEnvironments.delete(environment));
123
+ bakedEnvironments.set(environment, environment.version);
124
+ }
125
+
64
126
  export function defineWebRenderer(
65
127
  module: WebEngineModule,
66
128
  Color: new (...args: unknown[]) => IColorLike,
67
- beforeRender: (frame?: { camera?: unknown; scene?: unknown }) => void = () => {},
129
+ beforeRender: (frame?: INodeFrame) => void = () => {},
68
130
  tsl?: ITslRuntime,
69
131
  /** Draws the offscreen PassNodes into their targets (pass-node.ts); given the drawing buffer and the target draw. */
70
132
  drawSecondaryPasses: (
71
133
  surface: () => { width: number; height: number },
72
134
  draw: PassDraw,
73
135
  ) => void = () => {},
136
+ DataTexture?: Parameters<typeof defineSphereReflectionCapture>[1],
74
137
  ): new (
75
138
  parameters?: Record<string, unknown>,
76
139
  ) => object {
140
+ const debug = debugTelemetry(module);
77
141
  let claimed = false;
78
142
  // The engine starts once per page: one device, and one surface bound to the first renderer's canvas.
79
143
  // A renderer built after that one was disposed (a hot update re-runs the game) adopts both.
@@ -110,6 +174,26 @@ export function defineWebRenderer(
110
174
  readonly isWebGPURenderer = true;
111
175
  /** The native scene pass draws to the surface; there is no frame RenderTarget to retain. */
112
176
  readonly supportsRetainedTargetSubrect = false;
177
+ renderScale = 1;
178
+ get temporalUpscale(): boolean {
179
+ return module._tnw_web_frame(34) === 1;
180
+ }
181
+ #stageMeters = true;
182
+ /** Address of the host's stage-total array (`tnw_web_frame` 78), 0 until `init` asks. */
183
+ #stageBase = 0;
184
+ /**
185
+ * The engine's CPU stage meters on (the default) or off. Off, the engine reads no clock around its stages and this
186
+ * facade reads no totals, so the paired A/B of the meters' own cost can run on one build (PRD-771).
187
+ */
188
+ setStageMeters(enabled: boolean): void {
189
+ this.#stageMeters = enabled;
190
+ module._tnw_web_frame(enabled ? -3 : -4);
191
+ }
192
+ setRenderScale(scale: number): void {
193
+ if (!Number.isFinite(scale) || scale < 0.25 || scale > 1)
194
+ throw new Error("renderScale must be finite and between 0.25 and 1.");
195
+ this.renderScale = scale;
196
+ }
113
197
  readonly domElement: HTMLCanvasElement;
114
198
  readonly info = {
115
199
  autoReset: true,
@@ -128,12 +212,112 @@ export function defineWebRenderer(
128
212
  graphKeys: 0,
129
213
  programs: 0,
130
214
  frameGateSkips: 0,
215
+ // The last frame's draws and triangles with the shadow passes apart from the main pass (web_host.cpp fields 0, 1, 27
216
+ // and 85). `info.render` adds them, as three's does; core's pass recorder reads this to report `main` and `shadow`.
217
+ frameSplit: { mainDraws: 0, mainTriangles: 0, shadowDraws: 0, shadowTriangles: 0 },
218
+ // The startup's first real frame (web_host.cpp fields 71 and 72): the ordinary world submissions that encoded,
219
+ // and whether the shadow inputs such a frame samples exist. Core holds presentation until both, and the
220
+ // eye adaptation, say the world is ready; a bake step, an overlay, a declined draw or a failed one adds to
221
+ // neither. A shadow draw count is not the same answer.
222
+ startup: {
223
+ worldSubmissions: 0,
224
+ shadowInputsReady: false,
225
+ // web_host.cpp field 86: the first world frame drawn after the hold came off has finished on the GPU. True
226
+ // until a hold comes off, so a page that never held presentation has nothing to wait for.
227
+ worldPresented: true,
228
+ },
229
+ // True while prepareEnvironmentAsync draws the held scene under the loading cover. The world
230
+ // is still unlit, so these pixels are not the view's first frame: core's eye adaptation holds
231
+ // its history rather than adopting this bake's black target.
232
+ environmentBake: false,
233
+ // The temporal pass, read from the engine each frame. `active` is false until a traa() effect is in the post
234
+ // graph, so a graph that never reached the engine shows here as a pass that never ran.
235
+ temporal: {
236
+ active: false,
237
+ frame: 0,
238
+ historyValid: false,
239
+ jitter: [0, 0] as [number, number],
240
+ // The newest counted frame (one in 16 is counted): the pixels whose history the resolve discarded and the pixels
241
+ // whose history it pulled into the colour neighbourhood, of `pixels`, and which frame it was. 0 until the first.
242
+ rejected: 0,
243
+ clamped: 0,
244
+ pixels: 0,
245
+ countedFrame: 0,
246
+ inputWidth: 0,
247
+ inputHeight: 0,
248
+ outputWidth: 0,
249
+ outputHeight: 0,
250
+ jitterLength: 0,
251
+ },
252
+ // The samples the scene draws with. `samples` above is what was asked for; 1 here while the temporal pass runs.
253
+ samples: 1,
254
+ // The GPU milliseconds of the sample `render.timestamp` reports, by named stage (gpu-stages.ts). A stage that
255
+ // drew no pass is absent; core's `stageGpuReading` hands it to the GI and shadow budgets.
256
+ gpuStages: {} as Record<string, number>,
257
+ // The last frame's shadow passes, the spot and point light maps apart from the sun's (PRD-650):
258
+ // lamp maps redrawn and their draws, every shadow draw (the sun's are the rest), and the GPU
259
+ // milliseconds of each part in the sample `render.timestamp` reports, -1 until one resolves.
260
+ // `lampMapMin` and `lampMapMax` are the edges of the lamp maps the engine sized from their footprint.
261
+ // `keptMaps` counts the maps (sun or lamp) kept from the last frame because nothing they draw changed.
262
+ shadows: {
263
+ lampRedraws: 0,
264
+ lampDraws: 0,
265
+ shadowDraws: 0,
266
+ sunGpuMs: -1,
267
+ lampGpuMs: -1,
268
+ lampMapMin: 0,
269
+ lampMapMax: 0,
270
+ keptMaps: 0,
271
+ },
272
+ // The last frame's recorded passes (PRD-754): the draws the main pass recorded into its bundle, why its key
273
+ // moved (0 held, 1 draw order, 2 uniform offsets, 3 visible count, 4 other; the web engine reads 1 and 2 as
274
+ // 4), the aux and velocity draws recorded, and the ms spent recording bundles and encoding the shadow passes.
275
+ passes: {
276
+ mainRecorded: 0,
277
+ recordCause: 0,
278
+ auxRecorded: 0,
279
+ shadowRecorded: 0,
280
+ recordMs: 0,
281
+ shadowEncodeMs: 0,
282
+ },
283
+ // The bytes of per-draw uniforms the last frame uploaded.
284
+ uniformBytes: 0,
285
+ // The engine's CPU stages as running totals in ms (gpu-stages.ts `CPU_STAGE_FIELDS`) and the work counts beside
286
+ // them (`WORK_COUNT_NAMES`), re-read after every render while the stage meters are on: core differences two
287
+ // reads into `TN_FRAME_BUDGET.stages`. Made by `init` when the module publishes them: a module that does not
288
+ // has none, and core reads that as unmeasured, never as zero.
289
+ cpuMs: undefined as Record<CpuStageName, number> | undefined,
290
+ work: undefined as Record<WorkCountName, number> | undefined,
291
+ },
292
+ // three's Info: render() adds to drawCalls and triangles, and the caller resets once per frame, so a
293
+ // frame that draws its world and then its overlay reports both (core does this in onBeginFrame).
294
+ reset(): void {
295
+ this.render.drawCalls = 0;
296
+ this.render.frameCalls = 0;
297
+ this.render.triangles = 0;
131
298
  },
132
- reset(): void {},
133
299
  };
134
300
  /** three's WebGPURenderer: `antialias` is 4x MSAA, `samples` 0 or 1 is none; the engine draws 1 or 4. */
135
301
  readonly samples: number;
136
302
  autoClear = true;
303
+ readonly library = defineToneMappingLibrary(
304
+ () => {
305
+ if (!tsl) throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_MISSING: no TSL runtime");
306
+ const { exports } = defineTsl(tsl);
307
+ const color = (exports.toneMappingColor as () => unknown)();
308
+ const exposure = (exports.uniform as (value: number) => { setName(name: string): unknown })(
309
+ 1,
310
+ ).setName("toneMappingExposure");
311
+ return [color, exposure];
312
+ },
313
+ (node) => {
314
+ if (!isTslNode(node))
315
+ throw new TypeError("TN_NATIVE_CUSTOM_TONEMAPPING_TYPE: expected a TSL vec3 node");
316
+ if (!tsl?.setToneMapping)
317
+ throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_MISSING: no output binding");
318
+ tsl.setToneMapping(node[TSL_NODE]);
319
+ },
320
+ );
137
321
  toneMapping = 0;
138
322
  toneMappingExposure = 1;
139
323
  outputColorSpace = "srgb";
@@ -147,18 +331,35 @@ export function defineWebRenderer(
147
331
  trackTimestamp: boolean;
148
332
  getTimestampFrames(type: string): number[];
149
333
  pipelineCompiles(): number;
334
+ /** Resolves as three's GPUDevice.lost does once the host loses its device; core reports it (TN_DEVICE_LOST). */
335
+ readonly device: { readonly lost: Promise<{ reason: string; message: string }> };
150
336
  };
337
+ #deviceLost: (info: { reason: string; message: string }) => void = () => undefined;
338
+ /** The environment a preparation gave up on at its deadline, until a drawn frame finds it baked. */
339
+ #bakingEnvironment: IBakedEnvironment | undefined;
151
340
  #pixelRatio = 1;
152
341
  #width: number;
153
342
  #height: number;
154
343
  #clear: [number, number, number, number] = [0, 0, 0, 1];
344
+ /** The last number or string clear colour and its lanes: each is converted once. */
345
+ #clearKey: unknown = Symbol("unset");
346
+ #clearLanes: [number, number, number] = [0, 0, 0];
155
347
  #initialized: Promise<this> | undefined;
156
348
  #adapter: IAdapterInfo | undefined;
157
349
  #last: [unknown, unknown] | undefined;
350
+ [PIPELINE_POST]?: () => void;
351
+ /** The host is Failed for good (the GPU process destroyed the device, an uncaptured error): see #drawStatus. */
352
+ #lost = false;
353
+ /** A draw got through in this task, so later draws land on its surface texture: see render(). */
354
+ #frameOpen = false;
355
+ /** The draw in flight is renderOverlay's. */
356
+ #overlay = false;
158
357
  #state: string | undefined;
159
358
  #gpuSamples = 0;
160
359
  #holdsSlot = true;
161
360
  #timestampFrames: number[] = [];
361
+ /** The host's presentation hold is engaged, so this renderer has one of its own to release. */
362
+ #presentationHeld = false;
162
363
 
163
364
  constructor(parameters: Record<string, unknown> = {}) {
164
365
  if (claimed)
@@ -171,7 +372,8 @@ export function defineWebRenderer(
171
372
  (parameters.canvas as HTMLCanvasElement | undefined) ??
172
373
  document.createElement("canvas");
173
374
  // three's WebGPURenderer marks its canvas `three.js r<rev> webgpu`; tools read the backend there.
174
- this.domElement.setAttribute("data-engine", "threenative wasm webgpu");
375
+ // A worker's OffscreenCanvas has no attributes (PRD-752).
376
+ this.domElement.setAttribute?.("data-engine", "threenative wasm webgpu");
175
377
  const samples = parameters.samples ?? (parameters.antialias ? 4 : 1);
176
378
  this.samples = Math.max(1, Number(samples));
177
379
  this.#width = this.domElement.width || 300;
@@ -189,24 +391,39 @@ export function defineWebRenderer(
189
391
  trackTimestamp: Boolean(parameters.trackTimestamp ?? true),
190
392
  getTimestampFrames: timestampFrames,
191
393
  pipelineCompiles: () => module._tnw_web_frame(2),
394
+ device: {
395
+ lost: new Promise((resolve) => {
396
+ this.#deviceLost = resolve;
397
+ }),
398
+ },
192
399
  };
193
400
  }
194
401
 
195
402
  init(): Promise<this> {
196
403
  this.#initialized ??= (async () => {
197
404
  if (started === undefined) {
405
+ // A module of another ABI reads every later call's arguments as something else: the
406
+ // overlay flag as the frame number drew the world without post (39295d1f3).
407
+ const engine = (module as Partial<WebHostModule>)._tnw_web_host_abi?.();
408
+ if (engine !== WEB_HOST_ABI)
409
+ throw new Error(
410
+ `TN_WASM_ABI_MISMATCH: this facade speaks web host ABI ${WEB_HOST_ABI}, the engine ${engine ?? "none (older than ABI 2)"}: install create-threenative and @threenative/runtime-native from one build`,
411
+ );
198
412
  started = this.domElement;
199
413
  module.specialHTMLTargets[CANVAS_TARGET] = this.domElement;
200
414
  handles = module._malloc(36) >>> 0;
201
415
  const selector = string(CANVAS_TARGET);
202
416
  try {
203
- check(module._tnw_web_init(selector, this.#drawWidth(), this.#drawHeight()));
417
+ check(
418
+ module._tnw_web_init(selector, this.#drawWidth(), this.#drawHeight(), WEB_HOST_ABI),
419
+ );
204
420
  } finally {
205
421
  module._free(selector);
206
422
  }
207
423
  } else {
208
424
  // The disposed renderer's post graph must not outlive its game.
209
425
  tsl?.setPost(null);
426
+ tsl?.setToneMapping?.(null);
210
427
  }
211
428
  for (;;) {
212
429
  const state = module._tnw_web_poll();
@@ -224,6 +441,15 @@ export function defineWebRenderer(
224
441
  // Honest, like the engine: a device without timestamp-query times no frame, so no caller
225
442
  // may be told timestamps are enabled. An explicit opt-out stays off.
226
443
  if (module._tnw_web_frame(10) === 0) this.backend.trackTimestamp = false;
444
+ this.#stageBase = module._tnw_web_frame(78);
445
+ if (this.#stageBase > 0) {
446
+ this.info.engine.cpuMs = Object.fromEntries(
447
+ CPU_STAGE_ENTRIES.map(([name]) => [name, 0]),
448
+ ) as Record<CpuStageName, number>;
449
+ this.info.engine.work = Object.fromEntries(
450
+ WORK_COUNT_NAMES.map((name) => [name, 0]),
451
+ ) as Record<WorkCountName, number>;
452
+ }
227
453
  return this;
228
454
  })();
229
455
  return this.#initialized;
@@ -271,10 +497,30 @@ export function defineWebRenderer(
271
497
  }
272
498
 
273
499
  setClearColor(color: unknown, alpha = 1): void {
274
- const value = (
275
- typeof color === "object" && color !== null ? color : new Color(color)
276
- ) as IColorLike;
277
- this.#clear = [value.r, value.g, value.b, alpha];
500
+ if (typeof color === "object" && color !== null) {
501
+ const value = color as IColorLike;
502
+ this.#clear = [value.r, value.g, value.b, alpha];
503
+ return;
504
+ }
505
+ // Every post pass resets the clear colour to 0 (RendererUtils), and an engine Color per call
506
+ // was a construction across the boundary each time.
507
+ if (!Object.is(color, this.#clearKey)) {
508
+ const value = new Color(color) as IColorLike;
509
+ this.#clearLanes = [value.r, value.g, value.b];
510
+ this.#clearKey = color;
511
+ const host = globalThis as { __tnEngineCost?: Record<string, number> };
512
+ host.__tnEngineCost ??= {};
513
+ host.__tnEngineCost.clearColorConversions =
514
+ (host.__tnEngineCost.clearColorConversions ?? 0) + 1;
515
+ }
516
+ const lanes = this.#clearLanes;
517
+ this.#clear = [lanes[0], lanes[1], lanes[2], alpha];
518
+ }
519
+
520
+ getClearColor<T extends IColorLike & { setRGB(r: number, g: number, b: number): T }>(
521
+ target: T,
522
+ ): T {
523
+ return target.setRGB(this.#clear[0], this.#clear[1], this.#clear[2]);
278
524
  }
279
525
 
280
526
  getClearAlpha(): number {
@@ -285,19 +531,51 @@ export function defineWebRenderer(
285
531
  this.#clear[3] = alpha;
286
532
  }
287
533
 
534
+ /**
535
+ * core's canvas-layer overlay (a loading screen, a canvas HUD): drawn over the frame already on the canvas, with
536
+ * no post and no temporal step. Through render() it replaced the world frame and moved the temporal history and
537
+ * the metered exposure, so the world came back ghosted and blurred after the loading screen.
538
+ */
539
+ renderOverlay(scene: unknown, camera: unknown): void {
540
+ this.#overlay = true;
541
+ try {
542
+ this.render(scene, camera);
543
+ } finally {
544
+ this.#overlay = false;
545
+ }
546
+ }
547
+
288
548
  render(scene: unknown, camera: unknown): void {
289
549
  if (this.#adapter === undefined)
290
550
  throw new Error("TN_WASM_RENDERER: render() before init() finished.");
551
+ if (this.#lost) return;
291
552
  // Chromium queues a submitted frame without bound. When rAF outruns the GPU (an unthrottled
292
553
  // loop, a heavy scene) the page blocks until the GPU drains and the GPU process is killed.
293
554
  // The host says 1 while two drawn frames are still on the GPU: draw nothing this call.
294
- if (module._tnw_web_frame(11) === 1) {
555
+ // The gate holds back a frame, not a draw: a draw after one that got through in the same task
556
+ // (the overlay over the world, a loading cover over a covered bake) lands on the surface
557
+ // texture already taken, so refusing it saves no frame and presents the world without it.
558
+ // Measured on Lantern Vale: every cover over a drawn frame was refused, so the loading screen
559
+ // flickered black for the whole environment bake and then showed the unfinished world.
560
+ if (!this.#frameOpen && module._tnw_web_frame(11) === 1) {
561
+ // A lost device leaves its frames on the GPU for good, so the gate declines every later frame
562
+ // and no draw ever returns a status: name the loss here, where the frame poll just ran.
563
+ if (this.#noticeLost()) return;
295
564
  // Counted, never hidden: the loop's render phase for this frame is near zero, and a meter that
296
565
  // averages it with drawn frames reads cheaper than the work that was done (core's `renderSkips`).
297
566
  this.info.engine.frameGateSkips += 1;
298
567
  return;
299
568
  }
300
- beforeRender({ camera, scene });
569
+ if (!this.#frameOpen) {
570
+ this.#frameOpen = true;
571
+ // Every draw of a frame is synchronous in one task (the frame loop's callback, a warm-up timer
572
+ // task), so the frame closes when the task's synchronous work is done.
573
+ queueMicrotask(() => {
574
+ this.#frameOpen = false;
575
+ });
576
+ }
577
+ syncVirtualShadowLods();
578
+ beforeRender({ camera, scene, renderer: this, frameId: this.info.frame });
301
579
  drawSecondaryPasses(
302
580
  () => ({ width: this.#drawWidth(), height: this.#drawHeight() }),
303
581
  (target, root, view) => this[DRAW_TARGET](target, root, view, true),
@@ -307,14 +585,59 @@ export function defineWebRenderer(
307
585
  writeHandle(0, scene, "scene");
308
586
  writeHandle(12, camera, "camera");
309
587
  const renderFrame = this.info.frame;
310
- check(module._tnw_web_render(handles, handles + 12, ...this.#clear, renderFrame));
588
+ if (debug !== undefined) {
589
+ // Observation only: native captures this request with each submitted sample.
590
+ module._tnw_web_frame(this.backend.trackTimestamp ? -1 : -2);
591
+ debug?.add(
592
+ "gpuTimestampRequests",
593
+ this.backend.trackTimestamp ? 1 : 0,
594
+ "gpu",
595
+ "WebGPURenderer.render",
596
+ );
597
+ }
598
+ this.#drawStatus(
599
+ module._tnw_web_render(
600
+ handles,
601
+ handles + 12,
602
+ ...this.#clear,
603
+ this.#overlay ? 1 : 0,
604
+ renderFrame,
605
+ ),
606
+ );
311
607
  this.info.frame += 1;
608
+ if (this.#bakingEnvironment !== undefined && module._tnw_web_frame(12) === 0) {
609
+ // An overlay draw has no environment and says nothing; another sky ends the watch.
610
+ const drawnEnvironment = (scene as { environment?: unknown }).environment;
611
+ if (drawnEnvironment === this.#bakingEnvironment) markBaked(this.#bakingEnvironment);
612
+ if (drawnEnvironment != null) this.#bakingEnvironment = undefined;
613
+ }
312
614
  this.info.render.frameCalls = module._tnw_web_frame(0);
313
615
  this.info.render.calls += this.info.render.frameCalls;
314
- this.info.render.drawCalls = this.info.render.frameCalls;
315
- this.info.render.triangles = module._tnw_web_frame(1);
616
+ this.info.render.drawCalls += this.info.render.frameCalls;
617
+ const lastTriangles = module._tnw_web_frame(1);
618
+ this.info.render.triangles += lastTriangles;
619
+ const shadows = this.info.engine.shadows;
620
+ shadows.lampRedraws = module._tnw_web_frame(25);
621
+ shadows.lampDraws = module._tnw_web_frame(26);
622
+ shadows.shadowDraws = module._tnw_web_frame(27);
623
+ shadows.lampMapMin = module._tnw_web_frame(28);
624
+ shadows.lampMapMax = module._tnw_web_frame(29);
625
+ shadows.keptMaps = module._tnw_web_frame(40);
626
+ this.info.engine.uniformBytes = module._tnw_web_frame(41);
627
+ const split = this.info.engine.frameSplit;
628
+ // Field 0 answers for the renderer that drew last and field 27 for the world's: an overlay has no shadow pass of its own.
629
+ split.shadowDraws = this.#overlay ? 0 : shadows.shadowDraws;
630
+ split.shadowTriangles = module._tnw_web_frame(85);
631
+ split.mainDraws = this.info.render.frameCalls - split.shadowDraws;
632
+ split.mainTriangles = lastTriangles - split.shadowTriangles;
316
633
  const gpuSamples = module._tnw_web_frame(8);
317
634
  if (gpuSamples > this.#gpuSamples) {
635
+ debug?.add(
636
+ "gpuTimestampSamples",
637
+ gpuSamples - this.#gpuSamples,
638
+ "gpu",
639
+ "native timestamp readback",
640
+ );
318
641
  this.#gpuSamples = gpuSamples;
319
642
  const gpuMs = module._tnw_web_frame(7);
320
643
  // The engine reports which submitted frame this sample belongs to; the readback can land
@@ -322,6 +645,16 @@ export function defineWebRenderer(
322
645
  if (Number.isFinite(gpuMs) && gpuMs > 0) {
323
646
  this.info.render.timestamp = gpuMs;
324
647
  this.#timestampFrames = [module._tnw_web_frame(9)];
648
+ const stages: Record<string, number> = {};
649
+ GPU_STAGES.forEach((name, index) => {
650
+ const stageMs = module._tnw_web_frame(GPU_STAGE_FIELD + index);
651
+ if (stageMs > 0) stages[name] = stageMs;
652
+ });
653
+ const shadowMs = module._tnw_web_frame(SHADOW_SEGMENT_FIELD);
654
+ if (shadowMs > 0) stages[SHADOW_STAGE] = shadowMs;
655
+ this.info.engine.gpuStages = stages;
656
+ this.info.engine.shadows.sunGpuMs = module._tnw_web_frame(19);
657
+ this.info.engine.shadows.lampGpuMs = module._tnw_web_frame(24);
325
658
  }
326
659
  }
327
660
  const engine = this.info.engine;
@@ -330,12 +663,74 @@ export function defineWebRenderer(
330
663
  engine.bindGroups = module._tnw_web_frame(4);
331
664
  engine.graphKeys = module._tnw_web_frame(5);
332
665
  engine.programs = module._tnw_web_frame(6);
666
+ const temporal = engine.temporal;
667
+ temporal.active = module._tnw_web_frame(13) === 1;
668
+ temporal.frame = module._tnw_web_frame(14);
669
+ temporal.historyValid = module._tnw_web_frame(15) === 1;
670
+ temporal.jitter[0] = module._tnw_web_frame(16);
671
+ temporal.jitter[1] = module._tnw_web_frame(17);
672
+ temporal.rejected = module._tnw_web_frame(30);
673
+ temporal.clamped = module._tnw_web_frame(31);
674
+ temporal.pixels = module._tnw_web_frame(32);
675
+ temporal.countedFrame = module._tnw_web_frame(33);
676
+ temporal.inputWidth = module._tnw_web_frame(35);
677
+ temporal.inputHeight = module._tnw_web_frame(36);
678
+ temporal.jitterLength = module._tnw_web_frame(37);
679
+ temporal.outputWidth = module._tnw_web_frame(38);
680
+ temporal.outputHeight = module._tnw_web_frame(39);
681
+ if (debug !== undefined && temporal.active) {
682
+ // The native renderer counts the active/history/rejected/clamped pixel totals under these
683
+ // exact names (foundation/waste_counters.h, renderer.cpp); a JS series beside them would be
684
+ // overwritten by `counters()` where the names collide and silently stale where they do not.
685
+ // Only the input and output sizes have no native producer.
686
+ debug.add("temporalInputPixels", temporal.inputWidth * temporal.inputHeight, "temporal");
687
+ debug.add("temporalOutputPixels", temporal.outputWidth * temporal.outputHeight, "temporal");
688
+ }
689
+ engine.samples = module._tnw_web_frame(18);
690
+ const cpu = engine.cpuMs;
691
+ const work = engine.work;
692
+ if (this.#stageMeters && cpu !== undefined && work !== undefined) {
693
+ // In place, from the array the host fills at the end of every render: the ABI census above stays as it was.
694
+ const heap = module.HEAPF64;
695
+ const first = this.#stageBase / 8;
696
+ for (let index = 0; index < CPU_STAGE_ENTRIES.length; index += 1)
697
+ cpu[(CPU_STAGE_ENTRIES[index] as readonly [CpuStageName, number])[0]] =
698
+ heap[first + index] ?? 0;
699
+ for (let index = 0; index < WORK_COUNT_NAMES.length; index += 1)
700
+ work[WORK_COUNT_NAMES[index] as WorkCountName] =
701
+ heap[first + CPU_STAGE_ENTRIES.length + index] ?? 0;
702
+ }
703
+ const passes = engine.passes;
704
+ passes.mainRecorded = module._tnw_web_frame(60);
705
+ passes.recordCause = module._tnw_web_frame(61);
706
+ passes.auxRecorded = module._tnw_web_frame(62);
707
+ passes.recordMs = module._tnw_web_frame(63);
708
+ passes.shadowEncodeMs = module._tnw_web_frame(64);
709
+ passes.shadowRecorded = module._tnw_web_frame(65);
710
+ // The startup's own report, read only while the cover is up so a held frame sees the one it just made. After
711
+ // the release nothing reads it, so a steady frame pays no host call for it and the last values stand.
712
+ if (this.#presentationHeld) {
713
+ engine.startup.worldSubmissions = module._tnw_web_frame(71);
714
+ engine.startup.shadowInputsReady = module._tnw_web_frame(72) === 1;
715
+ } else if (!engine.startup.worldPresented) {
716
+ engine.startup.worldPresented = module._tnw_web_frame(86) === 1;
717
+ }
718
+ // Opt-in, as `__tnCallCounts`: a probe that sets `__tnPassLog` to an array gets every frame's counters.
719
+ (globalThis as { __tnPassLog?: unknown[] }).__tnPassLog?.push({ ...passes });
333
720
  }
334
721
 
335
722
  /** three's output and shadow settings, handed to the engine when they change. */
336
723
  #applyState(): void {
337
- const { toneMapping, toneMappingExposure, outputColorSpace, shadowMap, samples } = this;
338
- const key = `${toneMapping}|${toneMappingExposure}|${outputColorSpace}|${shadowMap.enabled}|${shadowMap.type}|${samples}`;
724
+ const {
725
+ toneMapping,
726
+ toneMappingExposure,
727
+ outputColorSpace,
728
+ shadowMap,
729
+ samples,
730
+ renderScale,
731
+ } = this;
732
+ this.library.apply(toneMapping);
733
+ const key = `${toneMapping}|${toneMappingExposure}|${outputColorSpace}|${shadowMap.enabled}|${shadowMap.type}|${samples}|${renderScale}|${this.backend.trackTimestamp}`;
339
734
  if (key === this.#state) return;
340
735
  const space = string(String(outputColorSpace));
341
736
  try {
@@ -347,6 +742,8 @@ export function defineWebRenderer(
347
742
  shadowMap.enabled ? 1 : 0,
348
743
  shadowMap.type,
349
744
  samples,
745
+ renderScale,
746
+ this.backend.trackTimestamp ? 1 : 0,
350
747
  ),
351
748
  );
352
749
  } finally {
@@ -362,12 +759,14 @@ export function defineWebRenderer(
362
759
  [DRAW_TARGET](target: unknown, root: unknown, camera: unknown, deferred = false): void {
363
760
  if (this.#adapter === undefined)
364
761
  throw new Error("TN_WASM_RENDERER: render() before init() finished.");
365
- beforeRender({ camera, scene: root });
762
+ if (this.#lost) return;
763
+ syncVirtualShadowLods();
764
+ beforeRender({ camera, scene: root, renderer: this, frameId: this.info.frame });
366
765
  this.#applyState();
367
766
  writeHandle(0, root, "scene");
368
767
  writeHandle(12, camera, "camera");
369
768
  writeHandle(24, target, "render target");
370
- check(
769
+ this.#drawStatus(
371
770
  module._tnw_web_render_target(
372
771
  handles + 24,
373
772
  handles,
@@ -378,6 +777,33 @@ export function defineWebRenderer(
378
777
  );
379
778
  }
380
779
 
780
+ /**
781
+ * A draw's status. The host stays Failed once it lost its device and answers every later draw with the
782
+ * same message, so the first one throws and the renderer draws nothing after it: one diagnostic, not one
783
+ * page error per frame. A refusal that leaves the host running (a render target's) still throws each time.
784
+ */
785
+ #drawStatus(status: number): void {
786
+ if (status !== 0) this.#noticeLost();
787
+ check(status);
788
+ }
789
+
790
+ /**
791
+ * True once the host is Failed for good. The first time, the console names it: the throw from a draw
792
+ * is the only other report, and a warm-up or a frame hook may swallow it. A lost device also resolves
793
+ * `backend.device.lost`; another host failure (an uncaptured error) is not a lost device.
794
+ */
795
+ #noticeLost(): boolean {
796
+ if (this.#lost || module._tnw_web_poll() !== FAILED) return this.#lost;
797
+ this.#lost = true;
798
+ const message = module.UTF8ToString(module._tnw_web_error());
799
+ console.error(
800
+ `TN_WASM_RENDERER_LOST: this renderer draws nothing after this call. ${message}`,
801
+ );
802
+ if (message.startsWith("TN_WASM_DEVICE_LOST"))
803
+ this.#deviceLost({ reason: "unknown", message });
804
+ return true;
805
+ }
806
+
381
807
  /** The last scene and camera again: RenderPipeline.render() draws through its post graph. */
382
808
  [RENDER_AGAIN](): void {
383
809
  if (this.#last !== undefined) this.render(...this.#last);
@@ -388,31 +814,118 @@ export function defineWebRenderer(
388
814
  return 16;
389
815
  }
390
816
 
391
- compileAsync(): Promise<void> {
392
- return Promise.resolve();
817
+ /**
818
+ * three's compileAsync: the engine builds the pipelines the first draw of `scene` takes through
819
+ * createRenderPipelineAsync (tnw_web_compile_async), and this resolves once every one is built. A no-op
820
+ * here left them to that draw, which compiled each one synchronously: all 205 of Lantern Vale's, behind
821
+ * its loading screen. A refusal rejects; the first draw then compiles instead.
822
+ */
823
+ async compileAsync(scene: unknown, camera: unknown, targetScene?: unknown): Promise<void> {
824
+ if (this.#adapter === undefined)
825
+ throw new Error("TN_WASM_RENDERER: compileAsync() before init() finished.");
826
+ if (this.#lost) return;
827
+ // The game's first draw runs through its RenderPipeline: compile with that graph's settings.
828
+ this[PIPELINE_POST]?.();
829
+ this.#applyState();
830
+ writeHandle(0, scene, "scene");
831
+ writeHandle(12, camera, "camera");
832
+ if (targetScene != null) writeHandle(24, targetScene, "target scene");
833
+ const id = module._tnw_web_compile_async(
834
+ handles,
835
+ handles + 12,
836
+ targetScene == null ? 0 : handles + 24,
837
+ );
838
+ await compiled(module, id);
839
+ }
840
+
841
+ /**
842
+ * Holds the canvas while a startup's first world frame is still cold (web_host.cpp
843
+ * `tnw_web_set_presentation_hold`). A held render still draws its scene, shadow, post and temporal
844
+ * passes, but takes no canvas texture, so nothing the engine's inputs are not ready for is presented.
845
+ * Overlays still present. Core releases it on the first frame its own readiness accepts.
846
+ */
847
+ setPresentationHeld(held: boolean): void {
848
+ const next = held === true;
849
+ if (next === this.#presentationHeld) return;
850
+ this.#presentationHeld = next;
851
+ // The release is the moment the next world frame is the one the player sees: watch it leave the GPU.
852
+ if (!next) this.info.engine.startup.worldPresented = false;
853
+ module._tnw_web_set_presentation_hold(next ? 1 : 0);
393
854
  }
394
855
 
395
856
  /**
396
857
  * Startup warm-up's native counterpart of three's PMREM preparer: the engine bakes an environment
397
- * a retained packet per render and skips every frame until it is done, so draw the held scene
398
- * (behind the loading cover) until a render is no longer skipped for it. True when it drew;
399
- * false at `deadlineMs` (a `performance.now()` time), so a bake that never finishes cannot
400
- * hold the caller or keep drawing after it gave up.
858
+ * a retained packet per call and skips every frame until it is done, so advance the bake one step
859
+ * per task until it reports baked. True when it baked; false at `deadlineMs` (a `performance.now()`
860
+ * time), so a bake that never finishes cannot hold the caller or keep preparing after it gave up.
861
+ *
862
+ * A step presents nothing. The bake used to reach the canvas through render(), so its last draw
863
+ * was the page's first picture: bright, without the cast shadows the next frame had, on screen for
864
+ * as long as the bake ran. `afterDraw` still runs after every step, in the same task, so the caller
865
+ * keeps its loading cover over the frame last presented while the world is unfinished.
401
866
  */
402
867
  async prepareEnvironmentAsync(
403
868
  scene: unknown,
404
869
  camera: unknown,
405
870
  deadlineMs = Number.POSITIVE_INFINITY,
871
+ afterDraw?: () => void,
406
872
  ): Promise<boolean> {
407
- while (performance.now() < deadlineMs) {
408
- const gated = this.info.engine.frameGateSkips;
409
- this.render(scene, camera);
410
- if (this.info.engine.frameGateSkips === gated && module._tnw_web_frame(12) === 0)
411
- return true;
412
- // A macrotask, not a frame: the work-done callbacks that advance the bake arrive between tasks.
413
- await new Promise((resolve) => setTimeout(resolve, 0));
873
+ // The engine keeps a bake per texture and version, so a restart into the same sky has nothing
874
+ // to wait for: answer before a step, which would otherwise cost the caller a task per packet.
875
+ const environment = (scene as { environment?: IBakedEnvironment | null }).environment;
876
+ if (environment != null && bakedEnvironments.get(environment) === environment.version)
877
+ return true;
878
+ // A bake an earlier preparation is waiting on, or already waited its budget for, is still
879
+ // running: the engine finishes it whether or not anyone waits, so a restart into it does not
880
+ // wait a second budget.
881
+ if (environment != null && environment === this.#bakingEnvironment) return false;
882
+ if (environment != null) this.#bakingEnvironment = environment;
883
+ // Lantern Vale's bake drew the main pass at 4x MSAA before its TRAA graph was installed: 39
884
+ // pipelines the game never drew, compiled synchronously behind the cover.
885
+ this[PIPELINE_POST]?.();
886
+ // The scene's first drawn frame follows this bake, so build its pipelines off the queue first: on
887
+ // Lantern Vale that draw compiled 84 synchronously and held the GPU queue for over a second
888
+ // (ready 6.3 s -> 4.5 s). A refusal is the draw's to report, where it compiles that pipeline again.
889
+ // It waits at most half the time left, so a slow compile still leaves the bake its steps.
890
+ const compiling = this.compileAsync(scene, camera).catch(() => undefined);
891
+ const left = (deadlineMs - performance.now()) / 2;
892
+ if (Number.isFinite(left)) {
893
+ let timer: ReturnType<typeof setTimeout> | undefined;
894
+ await Promise.race([
895
+ compiling,
896
+ new Promise((resolve) => {
897
+ timer = setTimeout(resolve, Math.max(0, left));
898
+ }),
899
+ ]);
900
+ clearTimeout(timer);
901
+ } else await compiling;
902
+ this.info.engine.environmentBake = true;
903
+ try {
904
+ while (performance.now() < deadlineMs) {
905
+ // Every step: `afterDraw` may paint the cover through render(), which rewrites these slots.
906
+ writeHandle(0, scene, "scene");
907
+ writeHandle(12, camera, "camera");
908
+ // The host's own preparer, not a draw: no surface frame is taken, no shadow or post pass encoded,
909
+ // no temporal step advanced, and nothing is counted as a frame.
910
+ const status = module._tnw_web_prepare_environment(handles, handles + 12);
911
+ afterDraw?.();
912
+ if (status < 0) this.#drawStatus(status);
913
+ if (status > 0) {
914
+ if (environment != null) {
915
+ markBaked(environment);
916
+ if (this.#bakingEnvironment === environment) this.#bakingEnvironment = undefined;
917
+ }
918
+ return true;
919
+ }
920
+ // A macrotask, not a frame: the work-done callbacks that advance the bake arrive between tasks.
921
+ await new Promise((resolve) => setTimeout(resolve, 0));
922
+ }
923
+ // The bake keeps running after the caller gave up on it: the first drawn frame that finds it
924
+ // done records it (`#bakingEnvironment` stays set), so the next restart does not wait again.
925
+ return false;
926
+ } finally {
927
+ this.info.engine.environmentBake = false;
414
928
  }
415
- return false;
416
929
  }
417
930
 
418
931
  async resolveTimestampsAsync(type = "render"): Promise<number | undefined> {
@@ -494,26 +1007,69 @@ export function defineWebRenderer(
494
1007
  if (!this.#holdsSlot) return;
495
1008
  this.#holdsSlot = false;
496
1009
  claimed = false;
1010
+ // A renderer disposed mid-startup must not leave its hold behind for the next one.
1011
+ this.setPresentationHeld(false);
497
1012
  }
498
1013
  };
499
1014
  const read = async (target: unknown, x: number, y: number, width: number, height: number) => {
500
1015
  writeHandle(24, target, "render target");
501
1016
  const id = module._tnw_web_read_target(handles + 24, x, y, width, height);
502
1017
  if (id === 0) check(1);
503
- const size = width * height * 8;
1018
+ const size =
1019
+ width * height * targetTexelBytes((target as { texture: { type: number } }).texture.type);
504
1020
  const out = module._malloc(size) >>> 0;
505
1021
  try {
506
1022
  for (;;) {
507
1023
  module._tnw_web_poll();
508
1024
  const status = module._tnw_web_read_target_take(id, out, size);
509
1025
  if (status === 1) return module.HEAPU8.slice(out, out + size);
510
- if (status < 0) throw new Error("TN_WASM_READ_TARGET: the read failed");
1026
+ // A read the lost device dropped says so, so the caller's report is read as that one loss.
1027
+ if (status < 0)
1028
+ throw new Error(
1029
+ module._tnw_web_poll() === FAILED
1030
+ ? `TN_WASM_READ_TARGET: the read failed: ${module.UTF8ToString(module._tnw_web_error())}`
1031
+ : "TN_WASM_READ_TARGET: the read failed",
1032
+ );
511
1033
  await new Promise((resolve) => setTimeout(resolve, 0));
512
1034
  }
513
1035
  } finally {
514
1036
  module._free(out);
515
1037
  }
516
1038
  };
1039
+ if (DataTexture !== undefined)
1040
+ Object.assign(Renderer.prototype, {
1041
+ // quality-allow: the capture API takes the requested Unreal actor name
1042
+ // biome-ignore lint/style/useNamingConvention: capture API uses the requested Unreal actor name.
1043
+ SphereReflectionCapture: defineSphereReflectionCapture(
1044
+ async (scene, x, y, z, size, face, renderer) => {
1045
+ // A face is a render of `scene`, as three's CubeCamera.update is: the scene's frame nodes run updateBefore first,
1046
+ // once per frame. Unreal captures the sky after the frame drew its look-up tables (UE 5.8.3:
1047
+ // Engine/Source/Runtime/Renderer/Private/DeferredShadingRenderer.cpp:2850, :2868); a capture taken before the
1048
+ // first frame read a sky node's never-drawn targets, and a chrome sphere reflected a black sky.
1049
+ const { frame } = (renderer as { info: { frame: number } }).info;
1050
+ beforeRender({ scene, renderer: renderer as object, frameId: frame });
1051
+ writeHandle(0, scene, "scene");
1052
+ const id = module._tnw_web_capture_face(handles, x, y, z, size, face);
1053
+ if (id === -2) return null;
1054
+ if (id < 0) check(1);
1055
+ const bytes = size * size * 3 * 4;
1056
+ const out = module._malloc(bytes) >>> 0;
1057
+ try {
1058
+ for (;;) {
1059
+ module._tnw_web_poll();
1060
+ const status = module._tnw_web_read_target_take(id, out, bytes);
1061
+ if (status === 1)
1062
+ return new Float32Array(module.HEAPU8.slice(out, out + bytes).buffer);
1063
+ if (status < 0) throw new Error("TN_REFLECTION_CAPTURE_READ");
1064
+ await new Promise((resolve) => setTimeout(resolve, 0));
1065
+ }
1066
+ } finally {
1067
+ module._free(out);
1068
+ }
1069
+ },
1070
+ DataTexture,
1071
+ ),
1072
+ });
517
1073
  defineRenderTargets(Renderer.prototype, (renderer) => ({
518
1074
  draw: (target, root, camera) =>
519
1075
  (renderer as { [DRAW_TARGET](t: unknown, r: unknown, c: unknown): void })[DRAW_TARGET](