@threenative/three-native 0.3.11 → 0.3.13

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.
@@ -4,9 +4,11 @@
4
4
  * surface and every draw; this class turns three's calls into host calls and reports what the
5
5
  * engine did. What it does not implement throws its diagnostic rather than doing nothing.
6
6
  */
7
+ import { packedRef } from "./browser-abi-types.js";
7
8
  import { TSL_NODE, type TnAbiModule, engineRef } from "./browser-backend.js";
8
9
  import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
9
10
  import { debugTelemetry } from "./debug-telemetry.js";
11
+ import { WEB_FRAME_FIELD } from "./generated/web-frame-fields.js";
10
12
  import {
11
13
  CPU_STAGE_ENTRIES,
12
14
  type CpuStageName,
@@ -17,9 +19,16 @@ import {
17
19
  type WorkCountName,
18
20
  } from "./gpu-stages.js";
19
21
  import type { PassDraw } from "./pass-node.js";
20
- import { defineRenderTargets, targetTexelBytes } from "./render-target.js";
22
+ import { frameAttachmentName } from "./pass-node.js";
23
+ import {
24
+ type IPositionLike,
25
+ type IRegionLike,
26
+ defineRenderTargets,
27
+ targetTexelBytes,
28
+ textureCopyArguments,
29
+ } from "./render-target.js";
21
30
  import { ShadowMap } from "./shadow-map.js";
22
- import { syncVirtualShadowLods } from "./shadow-node.js";
31
+ import { reportVirtualShadowFrame, syncVirtualShadowLods } from "./shadow-node.js";
23
32
  import { defineSphereReflectionCapture } from "./sphere-reflection-capture.js";
24
33
  import { readStorageBytes } from "./storage.js";
25
34
  import type { INodeFrame } from "./temp-node.js";
@@ -41,9 +50,15 @@ type HostCall =
41
50
  | "_tnw_web_renderer_state"
42
51
  | "_tnw_web_frame"
43
52
  | "_tnw_web_render_target"
53
+ | "_tnw_web_clear_target"
44
54
  | "_tnw_web_read_target"
45
55
  | "_tnw_web_read_target_take"
46
56
  | "_tnw_web_capture_face"
57
+ | "_tnw_web_init_texture"
58
+ | "_tnw_web_copy_texture"
59
+ | "_tnw_web_read_mrt"
60
+ | "_tnw_web_device_limit"
61
+ | "_tnw_web_device_feature"
47
62
  | "_tnw_web_threads";
48
63
 
49
64
  export type WebHostModule = Record<HostCall, (...args: number[]) => number> & {
@@ -60,7 +75,16 @@ export function isWebHostModule(module: TnAbiModule): module is WebEngineModule
60
75
  * The tnw_* contract this facade speaks (web_host.cpp `kWebHostAbi`). Bump both on every tnw_*
61
76
  * signature change: web-host-abi.spec.ts pins the signatures per number, and a mismatch fails init.
62
77
  */
63
- export const WEB_HOST_ABI = 8;
78
+ export const WEB_HOST_ABI = 13;
79
+
80
+ /**
81
+ * The device features three reads by name, as `tnw_web_device_feature`'s argument (web_host.cpp): every
82
+ * other name answers false, as a WebGPU GPUSupportedFeatures without it does.
83
+ */
84
+ const WEB_DEVICE_FEATURES: Readonly<Record<string, number>> = {
85
+ "core-features-and-limits": 0,
86
+ "indirect-first-instance": 1,
87
+ };
64
88
 
65
89
  /** The canvas key the host's surface looks up; Emscripten resolves it before any DOM query. */
66
90
  const CANVAS_TARGET = "!threenative-canvas";
@@ -70,12 +94,18 @@ export const RENDER_AGAIN = Symbol("tn.renderAgain");
70
94
  /** The last RenderPipeline's post graph install, which the warm-up entry points run first (browser-entry.ts). */
71
95
  export const PIPELINE_POST = Symbol("tn.pipelinePost");
72
96
  const DRAW_TARGET = Symbol("tn.drawTarget");
97
+ const CLEAR_TARGET = Symbol("tn.clearTarget");
73
98
  const FAILED = 2;
74
99
  /**
75
100
  * `tnw_web_frame` field of the first named stage's segment (web_host.cpp): 19 + 4 shadow, scene, other and output
76
101
  * passes. `GPU_STAGES` counts on from there, one segment per stage.
77
102
  */
78
- const GPU_STAGE_FIELD = 23;
103
+ const GPU_STAGE_FIELD: number = WEB_FRAME_FIELD.gpuSegmentGather;
104
+
105
+ /** One number of the frame snapshot (`tnw_web_frame` 89), read in place at the block's index plus the field id. */
106
+ function frameField(heap: Float64Array, block: number, field: number): number {
107
+ return heap[block + field] ?? Number.NaN;
108
+ }
79
109
 
80
110
  interface IAdapterInfo {
81
111
  readonly vendor: string;
@@ -126,7 +156,8 @@ function markBaked(environment: IBakedEnvironment): void {
126
156
  export function defineWebRenderer(
127
157
  module: WebEngineModule,
128
158
  Color: new (...args: unknown[]) => IColorLike,
129
- beforeRender: (frame?: INodeFrame) => void = () => {},
159
+ /** The frame hook: a draw passes its frame; a dispatch passes none, with its kernels' engine node ids. */
160
+ beforeRender: (frame?: INodeFrame, kernels?: readonly number[]) => void = () => {},
130
161
  tsl?: ITslRuntime,
131
162
  /** Draws the offscreen PassNodes into their targets (pass-node.ts); given the drawing buffer and the target draw. */
132
163
  drawSecondaryPasses: (
@@ -157,17 +188,11 @@ export function defineWebRenderer(
157
188
  const ref = typeof object === "object" && object !== null ? engineRef(object) : undefined;
158
189
  if (ref === undefined)
159
190
  throw new TypeError(`TN_WASM_RENDER: the ${what} is not an engine object.`);
160
- const [type, context, slot, generation] = ref.key.split(":").map(Number) as [
161
- number,
162
- number,
163
- number,
164
- number,
165
- ];
191
+ const { w0, w1, w2 } = packedRef(ref);
166
192
  const view = new DataView(module.HEAPU8.buffer);
167
- view.setUint16(handles + offset, type, true);
168
- view.setUint16(handles + offset + 2, context, true);
169
- view.setUint32(handles + offset + 4, slot, true);
170
- view.setUint32(handles + offset + 8, generation, true);
193
+ view.setUint32(handles + offset, w0, true);
194
+ view.setUint32(handles + offset + 4, w1, true);
195
+ view.setUint32(handles + offset + 8, w2, true);
171
196
  };
172
197
 
173
198
  const Renderer = class WebGPURenderer {
@@ -176,7 +201,7 @@ export function defineWebRenderer(
176
201
  readonly supportsRetainedTargetSubrect = false;
177
202
  renderScale = 1;
178
203
  get temporalUpscale(): boolean {
179
- return module._tnw_web_frame(34) === 1;
204
+ return module._tnw_web_frame(WEB_FRAME_FIELD.temporalUpscale) === 1;
180
205
  }
181
206
  #stageMeters = true;
182
207
  /** Address of the host's stage-total array (`tnw_web_frame` 78), 0 until `init` asks. */
@@ -187,7 +212,7 @@ export function defineWebRenderer(
187
212
  */
188
213
  setStageMeters(enabled: boolean): void {
189
214
  this.#stageMeters = enabled;
190
- module._tnw_web_frame(enabled ? -3 : -4);
215
+ module._tnw_web_frame(enabled ? WEB_FRAME_FIELD.cpuMetersOn : WEB_FRAME_FIELD.cpuMetersOff);
191
216
  }
192
217
  setRenderScale(scale: number): void {
193
218
  if (!Number.isFinite(scale) || scale < 0.25 || scale > 1)
@@ -254,6 +279,10 @@ export function defineWebRenderer(
254
279
  // The GPU milliseconds of the sample `render.timestamp` reports, by named stage (gpu-stages.ts). A stage that
255
280
  // drew no pass is absent; core's `stageGpuReading` hands it to the GI and shadow budgets.
256
281
  gpuStages: {} as Record<string, number>,
282
+ // The same sample split by pass (frame_gpu_timer.h segments): the scene pass, every shadow map, and the rest
283
+ // (other passes, output, gather). `frame` is the sample's source frame, -1 until one resolves; core's
284
+ // `gpuFrameSample` hands the split to the frame budget's `gpuMain`, `gpuShadow` and `gpuOther`.
285
+ gpuSplit: { frame: -1, main: 0, shadow: 0, other: 0 },
257
286
  // The last frame's shadow passes, the spot and point light maps apart from the sun's (PRD-650):
258
287
  // lamp maps redrawn and their draws, every shadow draw (the sun's are the rest), and the GPU
259
288
  // milliseconds of each part in the sample `render.timestamp` reports, -1 until one resolves.
@@ -331,8 +360,20 @@ export function defineWebRenderer(
331
360
  trackTimestamp: boolean;
332
361
  getTimestampFrames(type: string): number[];
333
362
  pipelineCompiles(): number;
363
+ /**
364
+ * three's GPUSupportedFeatures.has, which core reads to gate its GPU world scene
365
+ * (world-gpu-scene.ts `gpuSceneUnsupported`): the device's own answer, asked of the host.
366
+ */
367
+ hasFeature(name: string): boolean;
334
368
  /** 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 }> };
369
+ readonly device: {
370
+ readonly lost: Promise<{ reason: string; message: string }>;
371
+ /** three's GPUDevice.limits: the pair the colour-attachment proofs check, read from the device once. */
372
+ readonly limits: {
373
+ readonly maxColorAttachments: number;
374
+ readonly maxColorAttachmentBytesPerSample: number;
375
+ };
376
+ };
336
377
  };
337
378
  #deviceLost: (info: { reason: string; message: string }) => void = () => undefined;
338
379
  /** The environment a preparation gave up on at its deadline, until a drawn frame finds it baked. */
@@ -390,11 +431,23 @@ export function defineWebRenderer(
390
431
  },
391
432
  trackTimestamp: Boolean(parameters.trackTimestamp ?? true),
392
433
  getTimestampFrames: timestampFrames,
393
- pipelineCompiles: () => module._tnw_web_frame(2),
434
+ pipelineCompiles: () => module._tnw_web_frame(WEB_FRAME_FIELD.pipelineCompiles),
435
+ hasFeature(name: string): boolean {
436
+ const feature = WEB_DEVICE_FEATURES[name];
437
+ return feature !== undefined && module._tnw_web_device_feature(feature) === 1;
438
+ },
394
439
  device: {
395
440
  lost: new Promise((resolve) => {
396
441
  this.#deviceLost = resolve;
397
442
  }),
443
+ limits: {
444
+ get maxColorAttachments() {
445
+ return module._tnw_web_device_limit(0);
446
+ },
447
+ get maxColorAttachmentBytesPerSample() {
448
+ return module._tnw_web_device_limit(1);
449
+ },
450
+ },
398
451
  },
399
452
  };
400
453
  }
@@ -440,8 +493,9 @@ export function defineWebRenderer(
440
493
  };
441
494
  // Honest, like the engine: a device without timestamp-query times no frame, so no caller
442
495
  // may be told timestamps are enabled. An explicit opt-out stays off.
443
- if (module._tnw_web_frame(10) === 0) this.backend.trackTimestamp = false;
444
- this.#stageBase = module._tnw_web_frame(78);
496
+ if (module._tnw_web_frame(WEB_FRAME_FIELD.gpuTimerAvailable) === 0)
497
+ this.backend.trackTimestamp = false;
498
+ this.#stageBase = module._tnw_web_frame(WEB_FRAME_FIELD.stageTotalsAddress);
445
499
  if (this.#stageBase > 0) {
446
500
  this.info.engine.cpuMs = Object.fromEntries(
447
501
  CPU_STAGE_ENTRIES.map(([name]) => [name, 0]),
@@ -545,6 +599,20 @@ export function defineWebRenderer(
545
599
  }
546
600
  }
547
601
 
602
+ /**
603
+ * three's `hasFeature`, which KTX2Loader.detectSupport reads (PRD-867): the block formats the engine
604
+ * uploads on this device. BC7 answers from the device; ETC2 answers false until the engine uploads
605
+ * three's opaque `RGB_ETC2_Format`, which KTX2Loader picks there, so a KTX2 falls back to RGBA instead.
606
+ */
607
+ hasFeature(name: string): boolean {
608
+ if (this.#adapter === undefined)
609
+ throw new Error("TN_WASM_RENDERER: hasFeature() before init() finished.");
610
+ return (
611
+ name === "texture-compression-bc" &&
612
+ module._tnw_web_frame(WEB_FRAME_FIELD.textureCompressionBc) === 1
613
+ );
614
+ }
615
+
548
616
  render(scene: unknown, camera: unknown): void {
549
617
  if (this.#adapter === undefined)
550
618
  throw new Error("TN_WASM_RENDERER: render() before init() finished.");
@@ -557,7 +625,7 @@ export function defineWebRenderer(
557
625
  // texture already taken, so refusing it saves no frame and presents the world without it.
558
626
  // Measured on Lantern Vale: every cover over a drawn frame was refused, so the loading screen
559
627
  // flickered black for the whole environment bake and then showed the unfinished world.
560
- if (!this.#frameOpen && module._tnw_web_frame(11) === 1) {
628
+ if (!this.#frameOpen && module._tnw_web_frame(WEB_FRAME_FIELD.gpuBusy) === 1) {
561
629
  // A lost device leaves its frames on the GPU for good, so the gate declines every later frame
562
630
  // and no draw ever returns a status: name the loss here, where the frame poll just ran.
563
631
  if (this.#noticeLost()) return;
@@ -587,7 +655,11 @@ export function defineWebRenderer(
587
655
  const renderFrame = this.info.frame;
588
656
  if (debug !== undefined) {
589
657
  // Observation only: native captures this request with each submitted sample.
590
- module._tnw_web_frame(this.backend.trackTimestamp ? -1 : -2);
658
+ module._tnw_web_frame(
659
+ this.backend.trackTimestamp
660
+ ? WEB_FRAME_FIELD.debugTimestampOn
661
+ : WEB_FRAME_FIELD.debugTimestampOff,
662
+ );
591
663
  debug?.add(
592
664
  "gpuTimestampRequests",
593
665
  this.backend.trackTimestamp ? 1 : 0,
@@ -605,32 +677,42 @@ export function defineWebRenderer(
605
677
  ),
606
678
  );
607
679
  this.info.frame += 1;
608
- if (this.#bakingEnvironment !== undefined && module._tnw_web_frame(12) === 0) {
680
+ // PRD-878: one host call copies every number of the frame into a block, read in place below.
681
+ const block = module._tnw_web_frame(WEB_FRAME_FIELD.frameSnapshot) / 8;
682
+ const heap = module.HEAPF64; // after the call: a grown memory replaces the view
683
+ if (!this.#overlay)
684
+ reportVirtualShadowFrame(
685
+ frameField(heap, block, WEB_FRAME_FIELD.virtualShadowPendingLevels),
686
+ );
687
+ if (
688
+ this.#bakingEnvironment !== undefined &&
689
+ frameField(heap, block, WEB_FRAME_FIELD.environmentPending) === 0
690
+ ) {
609
691
  // An overlay draw has no environment and says nothing; another sky ends the watch.
610
692
  const drawnEnvironment = (scene as { environment?: unknown }).environment;
611
693
  if (drawnEnvironment === this.#bakingEnvironment) markBaked(this.#bakingEnvironment);
612
694
  if (drawnEnvironment != null) this.#bakingEnvironment = undefined;
613
695
  }
614
- this.info.render.frameCalls = module._tnw_web_frame(0);
696
+ this.info.render.frameCalls = frameField(heap, block, WEB_FRAME_FIELD.draws);
615
697
  this.info.render.calls += this.info.render.frameCalls;
616
698
  this.info.render.drawCalls += this.info.render.frameCalls;
617
- const lastTriangles = module._tnw_web_frame(1);
699
+ const lastTriangles = frameField(heap, block, WEB_FRAME_FIELD.triangles);
618
700
  this.info.render.triangles += lastTriangles;
619
701
  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);
702
+ shadows.lampRedraws = frameField(heap, block, WEB_FRAME_FIELD.lampRedraws);
703
+ shadows.lampDraws = frameField(heap, block, WEB_FRAME_FIELD.lampShadowDraws);
704
+ shadows.shadowDraws = frameField(heap, block, WEB_FRAME_FIELD.shadowDraws);
705
+ shadows.lampMapMin = frameField(heap, block, WEB_FRAME_FIELD.lampMapMin);
706
+ shadows.lampMapMax = frameField(heap, block, WEB_FRAME_FIELD.lampMapMax);
707
+ shadows.keptMaps = frameField(heap, block, WEB_FRAME_FIELD.keptShadowMaps);
708
+ this.info.engine.uniformBytes = frameField(heap, block, WEB_FRAME_FIELD.uniformBytes);
627
709
  const split = this.info.engine.frameSplit;
628
710
  // 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
711
  split.shadowDraws = this.#overlay ? 0 : shadows.shadowDraws;
630
- split.shadowTriangles = module._tnw_web_frame(85);
712
+ split.shadowTriangles = frameField(heap, block, WEB_FRAME_FIELD.shadowTriangles);
631
713
  split.mainDraws = this.info.render.frameCalls - split.shadowDraws;
632
714
  split.mainTriangles = lastTriangles - split.shadowTriangles;
633
- const gpuSamples = module._tnw_web_frame(8);
715
+ const gpuSamples = frameField(heap, block, WEB_FRAME_FIELD.gpuSamples);
634
716
  if (gpuSamples > this.#gpuSamples) {
635
717
  debug?.add(
636
718
  "gpuTimestampSamples",
@@ -639,45 +721,77 @@ export function defineWebRenderer(
639
721
  "native timestamp readback",
640
722
  );
641
723
  this.#gpuSamples = gpuSamples;
642
- const gpuMs = module._tnw_web_frame(7);
724
+ const gpuMs = frameField(heap, block, WEB_FRAME_FIELD.gpuMs);
643
725
  // The engine reports which submitted frame this sample belongs to; the readback can land
644
726
  // many frames later, so the arrival frame is never the sample's age.
645
727
  if (Number.isFinite(gpuMs) && gpuMs > 0) {
646
728
  this.info.render.timestamp = gpuMs;
647
- this.#timestampFrames = [module._tnw_web_frame(9)];
729
+ this.#timestampFrames = [frameField(heap, block, WEB_FRAME_FIELD.gpuSourceFrame)];
648
730
  const stages: Record<string, number> = {};
649
731
  GPU_STAGES.forEach((name, index) => {
650
- const stageMs = module._tnw_web_frame(GPU_STAGE_FIELD + index);
732
+ const stageMs = frameField(heap, block, GPU_STAGE_FIELD + index);
651
733
  if (stageMs > 0) stages[name] = stageMs;
652
734
  });
653
- const shadowMs = module._tnw_web_frame(SHADOW_SEGMENT_FIELD);
735
+ const shadowMs = frameField(heap, block, SHADOW_SEGMENT_FIELD);
654
736
  if (shadowMs > 0) stages[SHADOW_STAGE] = shadowMs;
655
737
  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);
738
+ this.info.engine.shadows.sunGpuMs = frameField(
739
+ heap,
740
+ block,
741
+ WEB_FRAME_FIELD.gpuSegmentShadow,
742
+ );
743
+ this.info.engine.shadows.lampGpuMs = frameField(
744
+ heap,
745
+ block,
746
+ WEB_FRAME_FIELD.gpuSegmentLampShadow,
747
+ );
748
+ const segment = (field: number): number => Math.max(0, frameField(heap, block, field));
749
+ const split = this.info.engine.gpuSplit;
750
+ split.frame = this.#timestampFrames[0] ?? -1;
751
+ split.main = segment(WEB_FRAME_FIELD.gpuSegmentScene);
752
+ split.shadow =
753
+ segment(WEB_FRAME_FIELD.gpuSegmentShadow) +
754
+ segment(WEB_FRAME_FIELD.gpuSegmentLampShadow);
755
+ split.other =
756
+ segment(WEB_FRAME_FIELD.gpuSegmentOther) +
757
+ segment(WEB_FRAME_FIELD.gpuSegmentOutput) +
758
+ segment(WEB_FRAME_FIELD.gpuSegmentGather);
759
+ // Opt-in, as `__tnPassLog`: a probe that sets `__tnGpuSegments` to an array gets each resolved sample's
760
+ // split (frame_gpu_timer.h segments: sun shadow, scene, other passes, output, gather, lamp shadow).
761
+ (globalThis as { __tnGpuSegments?: number[][] }).__tnGpuSegments?.push([
762
+ gpuMs,
763
+ ...[
764
+ WEB_FRAME_FIELD.gpuSegmentShadow,
765
+ WEB_FRAME_FIELD.gpuSegmentScene,
766
+ WEB_FRAME_FIELD.gpuSegmentOther,
767
+ WEB_FRAME_FIELD.gpuSegmentOutput,
768
+ WEB_FRAME_FIELD.gpuSegmentGather,
769
+ WEB_FRAME_FIELD.gpuSegmentLampShadow,
770
+ ].map((field) => frameField(heap, block, field)),
771
+ ]);
658
772
  }
659
773
  }
660
774
  const engine = this.info.engine;
661
- engine.compiles = module._tnw_web_frame(2);
662
- engine.textLookups = module._tnw_web_frame(3);
663
- engine.bindGroups = module._tnw_web_frame(4);
664
- engine.graphKeys = module._tnw_web_frame(5);
665
- engine.programs = module._tnw_web_frame(6);
775
+ engine.compiles = frameField(heap, block, WEB_FRAME_FIELD.pipelineCompiles);
776
+ engine.textLookups = frameField(heap, block, WEB_FRAME_FIELD.pipelineLookups);
777
+ engine.bindGroups = frameField(heap, block, WEB_FRAME_FIELD.bindGroupsCreated);
778
+ engine.graphKeys = frameField(heap, block, WEB_FRAME_FIELD.graphKeyBuilds);
779
+ engine.programs = frameField(heap, block, WEB_FRAME_FIELD.programs);
666
780
  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);
781
+ temporal.active = frameField(heap, block, WEB_FRAME_FIELD.temporalActive) === 1;
782
+ temporal.frame = frameField(heap, block, WEB_FRAME_FIELD.temporalFrame);
783
+ temporal.historyValid = frameField(heap, block, WEB_FRAME_FIELD.temporalHistoryValid) === 1;
784
+ temporal.jitter[0] = frameField(heap, block, WEB_FRAME_FIELD.temporalJitterX);
785
+ temporal.jitter[1] = frameField(heap, block, WEB_FRAME_FIELD.temporalJitterY);
786
+ temporal.rejected = frameField(heap, block, WEB_FRAME_FIELD.temporalRejected);
787
+ temporal.clamped = frameField(heap, block, WEB_FRAME_FIELD.temporalClamped);
788
+ temporal.pixels = frameField(heap, block, WEB_FRAME_FIELD.temporalPixels);
789
+ temporal.countedFrame = frameField(heap, block, WEB_FRAME_FIELD.temporalCountedFrame);
790
+ temporal.inputWidth = frameField(heap, block, WEB_FRAME_FIELD.inputWidth);
791
+ temporal.inputHeight = frameField(heap, block, WEB_FRAME_FIELD.inputHeight);
792
+ temporal.jitterLength = frameField(heap, block, WEB_FRAME_FIELD.temporalJitterLength);
793
+ temporal.outputWidth = frameField(heap, block, WEB_FRAME_FIELD.width);
794
+ temporal.outputHeight = frameField(heap, block, WEB_FRAME_FIELD.height);
681
795
  if (debug !== undefined && temporal.active) {
682
796
  // The native renderer counts the active/history/rejected/clamped pixel totals under these
683
797
  // exact names (foundation/waste_counters.h, renderer.cpp); a JS series beside them would be
@@ -686,12 +800,11 @@ export function defineWebRenderer(
686
800
  debug.add("temporalInputPixels", temporal.inputWidth * temporal.inputHeight, "temporal");
687
801
  debug.add("temporalOutputPixels", temporal.outputWidth * temporal.outputHeight, "temporal");
688
802
  }
689
- engine.samples = module._tnw_web_frame(18);
803
+ engine.samples = frameField(heap, block, WEB_FRAME_FIELD.sampleCount);
690
804
  const cpu = engine.cpuMs;
691
805
  const work = engine.work;
692
806
  if (this.#stageMeters && cpu !== undefined && work !== undefined) {
693
807
  // 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
808
  const first = this.#stageBase / 8;
696
809
  for (let index = 0; index < CPU_STAGE_ENTRIES.length; index += 1)
697
810
  cpu[(CPU_STAGE_ENTRIES[index] as readonly [CpuStageName, number])[0]] =
@@ -701,19 +814,21 @@ export function defineWebRenderer(
701
814
  heap[first + CPU_STAGE_ENTRIES.length + index] ?? 0;
702
815
  }
703
816
  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);
817
+ passes.mainRecorded = frameField(heap, block, WEB_FRAME_FIELD.mainRecorded);
818
+ passes.recordCause = frameField(heap, block, WEB_FRAME_FIELD.recordCause);
819
+ passes.auxRecorded = frameField(heap, block, WEB_FRAME_FIELD.auxRecorded);
820
+ passes.recordMs = frameField(heap, block, WEB_FRAME_FIELD.recordMs);
821
+ passes.shadowEncodeMs = frameField(heap, block, WEB_FRAME_FIELD.shadowEncodeMs);
822
+ passes.shadowRecorded = frameField(heap, block, WEB_FRAME_FIELD.shadowRecorded);
710
823
  // The startup's own report, read only while the cover is up so a held frame sees the one it just made. After
711
824
  // the release nothing reads it, so a steady frame pays no host call for it and the last values stand.
712
825
  if (this.#presentationHeld) {
713
- engine.startup.worldSubmissions = module._tnw_web_frame(71);
714
- engine.startup.shadowInputsReady = module._tnw_web_frame(72) === 1;
826
+ engine.startup.worldSubmissions = frameField(heap, block, WEB_FRAME_FIELD.worldSubmissions);
827
+ engine.startup.shadowInputsReady =
828
+ frameField(heap, block, WEB_FRAME_FIELD.shadowInputsReady) === 1;
715
829
  } else if (!engine.startup.worldPresented) {
716
- engine.startup.worldPresented = module._tnw_web_frame(86) === 1;
830
+ engine.startup.worldPresented =
831
+ module._tnw_web_frame(WEB_FRAME_FIELD.firstWorldFrameDrawn) === 1;
717
832
  }
718
833
  // Opt-in, as `__tnCallCounts`: a probe that sets `__tnPassLog` to an array gets every frame's counters.
719
834
  (globalThis as { __tnPassLog?: unknown[] }).__tnPassLog?.push({ ...passes });
@@ -756,7 +871,13 @@ export function defineWebRenderer(
756
871
  * render() while a render target is set (render-target.ts): draws into the target. `deferred` (an offscreen PassNode)
757
872
  * plans the draw and has the engine record it in the frame that samples the target.
758
873
  */
759
- [DRAW_TARGET](target: unknown, root: unknown, camera: unknown, deferred = false): void {
874
+ [DRAW_TARGET](
875
+ target: unknown,
876
+ root: unknown,
877
+ camera: unknown,
878
+ deferred = false,
879
+ layer = 0,
880
+ ): void {
760
881
  if (this.#adapter === undefined)
761
882
  throw new Error("TN_WASM_RENDERER: render() before init() finished.");
762
883
  if (this.#lost) return;
@@ -772,7 +893,23 @@ export function defineWebRenderer(
772
893
  handles,
773
894
  handles + 12,
774
895
  ...this.#clear,
775
- deferred ? 1 : 0,
896
+ // Bits 8 and up: the layer of an array target (tnw_web_render_target).
897
+ (deferred ? 1 : 0) | (this.autoClear ? 0 : 2) | (layer << 8),
898
+ ),
899
+ );
900
+ }
901
+
902
+ /** three's clear(color, depth) while a render target is set (render-target.ts): clears it to the clear colour. */
903
+ [CLEAR_TARGET](target: unknown, color: boolean, depth: boolean): void {
904
+ if (this.#adapter === undefined)
905
+ throw new Error("TN_WASM_RENDERER: clear() before init() finished.");
906
+ if (this.#lost) return;
907
+ writeHandle(24, target, "render target");
908
+ this.#drawStatus(
909
+ module._tnw_web_clear_target(
910
+ handles + 24,
911
+ ...this.#clear,
912
+ (color ? 1 : 0) | (depth ? 2 : 0),
776
913
  ),
777
914
  );
778
915
  }
@@ -944,14 +1081,15 @@ export function defineWebRenderer(
944
1081
  throw new Error(
945
1082
  "TN_COMPUTE_DISPATCH_SIZE: renderer.compute(nodes, dispatchSize) is not available on the Wasm engine; give the node its count.",
946
1083
  );
947
- beforeRender();
948
- for (const node of Array.isArray(computeNodes) ? computeNodes : [computeNodes]) {
1084
+ const kernels = (Array.isArray(computeNodes) ? computeNodes : [computeNodes]).map((node) => {
949
1085
  if (!isTslNode(node))
950
1086
  throw new TypeError(
951
1087
  "TN_COMPUTE_NODE: renderer.compute takes the node Fn(() => { ... })().compute(count) makes",
952
1088
  );
953
- tsl.compute(node[TSL_NODE]);
954
- }
1089
+ return node[TSL_NODE];
1090
+ });
1091
+ beforeRender(undefined, kernels);
1092
+ for (const kernel of kernels) tsl.compute(kernel);
955
1093
  }
956
1094
 
957
1095
  async computeAsync(computeNodes: unknown, dispatchSize: unknown = null): Promise<void> {
@@ -990,6 +1128,43 @@ export function defineWebRenderer(
990
1128
  return this;
991
1129
  }
992
1130
 
1131
+ /**
1132
+ * three's initTexture: the engine builds the texture's GPU copy now. `source.dataReady = false` (set by a caller
1133
+ * that fills the texture with copyTextureToTexture) uploads nothing and drops the CPU texels.
1134
+ */
1135
+ initTexture(texture: unknown): void {
1136
+ if (this.#adapter === undefined)
1137
+ throw new Error("TN_WASM_RENDERER: initTexture() before init() finished.");
1138
+ writeHandle(0, texture, "texture");
1139
+ const dataReady = (texture as { source?: { dataReady?: boolean } }).source?.dataReady;
1140
+ check(module._tnw_web_init_texture(handles, dataReady === false ? 1 : 0));
1141
+ }
1142
+
1143
+ /**
1144
+ * three's copyTextureToTexture: `srcRegion` is a Box2 or Box3 (the source's image size when null), `dstPosition`
1145
+ * a Vector2 or Vector3 whose z is the destination's array layer. Both textures are initialised first.
1146
+ */
1147
+ copyTextureToTexture(
1148
+ source: unknown,
1149
+ destination: unknown,
1150
+ srcRegion: IRegionLike | null = null,
1151
+ dstPosition: IPositionLike | null = null,
1152
+ srcLevel = 0,
1153
+ dstLevel = 0,
1154
+ ): void {
1155
+ if (this.#adapter === undefined)
1156
+ throw new Error("TN_WASM_RENDERER: copyTextureToTexture() before init() finished.");
1157
+ writeHandle(0, source, "source texture");
1158
+ writeHandle(12, destination, "destination texture");
1159
+ check(
1160
+ module._tnw_web_copy_texture(
1161
+ handles,
1162
+ handles + 12,
1163
+ ...textureCopyArguments(srcRegion, dstPosition, srcLevel, dstLevel),
1164
+ ),
1165
+ );
1166
+ }
1167
+
993
1168
  getRenderTarget(): null {
994
1169
  return null;
995
1170
  }
@@ -1011,12 +1186,8 @@ export function defineWebRenderer(
1011
1186
  this.setPresentationHeld(false);
1012
1187
  }
1013
1188
  };
1014
- const read = async (target: unknown, x: number, y: number, width: number, height: number) => {
1015
- writeHandle(24, target, "render target");
1016
- const id = module._tnw_web_read_target(handles + 24, x, y, width, height);
1017
- if (id === 0) check(1);
1018
- const size =
1019
- width * height * targetTexelBytes((target as { texture: { type: number } }).texture.type);
1189
+ /** Polls a read id until it delivers, then returns the region's bytes. */
1190
+ const take = async (id: number, size: number) => {
1020
1191
  const out = module._malloc(size) >>> 0;
1021
1192
  try {
1022
1193
  for (;;) {
@@ -1036,6 +1207,39 @@ export function defineWebRenderer(
1036
1207
  module._free(out);
1037
1208
  }
1038
1209
  };
1210
+ const read = async (
1211
+ target: unknown,
1212
+ x: number,
1213
+ y: number,
1214
+ width: number,
1215
+ height: number,
1216
+ textureIndex = 0,
1217
+ ) => {
1218
+ // An RG attachment's texel is two channels, so the region's bytes follow its format as well as its type.
1219
+ const { type, format } = (target as { texture: { type: number; format?: number } }).texture;
1220
+ const size = width * height * targetTexelBytes(type, format);
1221
+ // three's textureIndex selects an attachment of the target. The frame pass's attachments are the
1222
+ // engine's own colour targets, so the index names one and the host reads that slot.
1223
+ const attachment = frameAttachmentName(target, textureIndex);
1224
+ if (attachment !== undefined) {
1225
+ const name = string(attachment);
1226
+ try {
1227
+ const id = module._tnw_web_read_mrt(name, x, y, width, height);
1228
+ if (id === 0) check(1);
1229
+ return await take(id, size);
1230
+ } finally {
1231
+ module._free(name);
1232
+ }
1233
+ }
1234
+ if (textureIndex !== 0)
1235
+ throw new Error(
1236
+ `TN_WASM_READ_TARGET: the target has no colour attachment ${String(textureIndex)}`,
1237
+ );
1238
+ writeHandle(24, target, "render target");
1239
+ const id = module._tnw_web_read_target(handles + 24, x, y, width, height);
1240
+ if (id === 0) check(1);
1241
+ return take(id, size);
1242
+ };
1039
1243
  if (DataTexture !== undefined)
1040
1244
  Object.assign(Renderer.prototype, {
1041
1245
  // quality-allow: the capture API takes the requested Unreal actor name
@@ -1071,11 +1275,17 @@ export function defineWebRenderer(
1071
1275
  ),
1072
1276
  });
1073
1277
  defineRenderTargets(Renderer.prototype, (renderer) => ({
1074
- draw: (target, root, camera) =>
1075
- (renderer as { [DRAW_TARGET](t: unknown, r: unknown, c: unknown): void })[DRAW_TARGET](
1278
+ draw: (target, root, camera, layer) =>
1279
+ (
1280
+ renderer as {
1281
+ [DRAW_TARGET](t: unknown, r: unknown, c: unknown, d: boolean, l: number): void;
1282
+ }
1283
+ )[DRAW_TARGET](target, root, camera, false, layer),
1284
+ clear: (target, color, depth) =>
1285
+ (renderer as { [CLEAR_TARGET](t: unknown, c: boolean, d: boolean): void })[CLEAR_TARGET](
1076
1286
  target,
1077
- root,
1078
- camera,
1287
+ color,
1288
+ depth,
1079
1289
  ),
1080
1290
  read,
1081
1291
  }));