@threenative/runtime-native 0.3.6 → 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.
@@ -1,14 +1,36 @@
1
1
  export * from "./core-three.mjs";
2
- import { BufferAttribute, Color, Material, NormalBlending } from "./core-three.mjs";
2
+ export { ShadowBaseNode } from "../../../../three-native/src/shadow-node.ts";
3
+ import { detachVirtualShadow, shadowFilterOptions, virtualShadowOptions, syncVirtualShadowLods } from "../../../../three-native/src/shadow-node.ts";
4
+ // Native VSM configuration crosses the same LightShadow registry setter as the Wasm facade.
5
+ for (const name of ["DirectionalLightShadow", "PointLightShadow", "SpotLightShadow"]) {
6
+ const prototype = globalThis[name]?.prototype;
7
+ for (const [property, translate] of [["shadowNode", virtualShadowOptions], ["filterNode", shadowFilterOptions]]) {
8
+ const set = prototype && Object.getOwnPropertyDescriptor(prototype, property)?.set;
9
+ if (!set) continue;
10
+ const nodes = new WeakMap();
11
+ Object.defineProperty(prototype, property, {
12
+ configurable: true,
13
+ get() { return nodes.get(this) ?? null; },
14
+ set(value) { if (property === "shadowNode" && nodes.get(this) === value) return; set.call(this, translate(value, (command) => set.call(this, command))); if (nodes.get(this) !== value) detachVirtualShadow(nodes.get(this)); nodes.set(this, value); },
15
+ });
16
+ }
17
+ }
18
+ import { BufferAttribute, Color, DataTexture, Material, NormalBlending } from "./core-three.mjs";
3
19
  import { unsupportedExport } from "../../../../three-native/src/refused.ts";
4
20
  import { PassNode, StorageBufferAttribute, StorageInstancedBufferAttribute, syncUniforms, updateSecondaryPasses } from "./core-tsl.mjs";
5
21
  import { readStorageBytes } from "../../../../three-native/src/storage.ts";
6
22
  import { GAME_SPANS } from "../../../../core/src/profiling/Spans.ts";
23
+ import { defineToneMappingLibrary } from "../../../../three-native/src/tone-mapping.ts";
7
24
  import { ShadowMap } from "../../../../three-native/src/shadow-map.ts";
25
+ import { defineSphereReflectionCapture } from "../../../../three-native/src/sphere-reflection-capture.ts";
8
26
  import { defineRenderTargets } from "../../../../three-native/src/render-target.ts";
9
27
  import { defineQuadMesh } from "../../../../three-native/src/quad-mesh.ts";
28
+ import { defineTempNode } from "../../../../three-native/src/temp-node.ts";
29
+ import { defineRendererUtils } from "../../../../three-native/src/renderer-utils.ts";
30
+ import { GPU_STAGES, SHADOW_STAGE } from "../../../../three-native/src/gpu-stages.ts";
10
31
 
11
- export const { MeshBasicNodeMaterial, MeshStandardNodeMaterial, SpriteNodeMaterial } = globalThis;
32
+ export const { StorageTexture, MeshBasicNodeMaterial, MeshStandardNodeMaterial, SpriteNodeMaterial } = globalThis;
33
+ Object.setPrototypeOf(StorageTexture.prototype, globalThis.Texture.prototype);
12
34
  Object.setPrototypeOf(MeshBasicNodeMaterial.prototype, globalThis.MeshBasicMaterial.prototype);
13
35
  Object.setPrototypeOf(MeshStandardNodeMaterial.prototype, globalThis.MeshStandardMaterial.prototype);
14
36
  Object.setPrototypeOf(SpriteNodeMaterial.prototype, globalThis.SpriteMaterial.prototype);
@@ -25,10 +47,23 @@ class NativeBackend {
25
47
  // Pipelines the player's renderer has compiled so far (three counts createRenderPipeline calls on its
26
48
  // backend; the engine counts its own pipeline cache). A window's compiles are the difference of two reads.
27
49
  pipelineCompiles = () => globalThis.tn.renderInfo().pipelineCompiles;
50
+ // The frame the newest resolved GPU time belongs to, as the Wasm backend reports it (core's `stageGpuReading` reads it).
51
+ // The first reader turns the player's frame timing on: an unread timer costs a query resolve and readback per frame.
52
+ #timing = false;
53
+ getTimestampFrames(type) {
54
+ if (type !== "render") return [];
55
+ if (!this.#timing) {
56
+ this.#timing = true;
57
+ globalThis.tn.setGpuTimer(true);
58
+ }
59
+ const { samples, source } = globalThis.tn.renderInfo().gpuTiming;
60
+ return samples > 0 ? [source] : [];
61
+ }
28
62
  }
29
63
 
30
64
  function drawTarget(renderer, target, root, camera, deferred) {
31
65
  syncUniforms();
66
+ renderer.library.apply(renderer.toneMapping);
32
67
  globalThis.tn.setRendererState(renderer); // the target clears to the renderer's current clear colour
33
68
  if (deferred) globalThis.tn.renderTarget(target, root, camera, true);
34
69
  else globalThis.tn.renderTarget(target, root, camera);
@@ -37,12 +72,20 @@ function drawTarget(renderer, target, root, camera, deferred) {
37
72
  // Every offscreen PassNode plans its draw into its own target; the player records it in this frame, after the post
38
73
  // render-to-texture passes when the post graph samples the target, else ahead of the scene pass.
39
74
  function drawSecondaryPasses(renderer) {
75
+ syncVirtualShadowLods();
40
76
  updateSecondaryPasses(() => globalThis.tn.surfaceSize(), (target, root, camera) => drawTarget(renderer, target, root, camera, true));
41
77
  }
42
78
 
43
79
  export class WebGPURenderer {
44
80
  // The native scene pass draws to the player-owned surface, not a retained frame target.
45
81
  supportsRetainedTargetSubrect = false;
82
+ renderScale = 1;
83
+ get temporalUpscale() { return globalThis.tn.renderInfo().temporalUpscale === true; }
84
+ setRenderScale(scale) {
85
+ if (!Number.isFinite(scale) || scale < 0.25 || scale > 1)
86
+ throw new Error("renderScale must be finite and between 0.25 and 1.");
87
+ this.renderScale = scale;
88
+ }
46
89
  constructor({ canvas, antialias = false } = {}) {
47
90
  this.domElement = canvas;
48
91
  this.samples = antialias ? 4 : 0;
@@ -54,14 +97,36 @@ export class WebGPURenderer {
54
97
  render: {
55
98
  get drawCalls() { return globalThis.tn.renderInfo().drawCalls; },
56
99
  get calls() { return globalThis.tn.renderInfo().drawCalls; },
100
+ // The newest resolved GPU time of the whole frame in ms, 0 before one has (the timer starts at the first `getTimestampFrames`).
101
+ get timestamp() { return Math.max(0, globalThis.tn.renderInfo().gpuTiming.ms); },
57
102
  get triangles() { return globalThis.tn.renderInfo().triangles; },
58
103
  },
59
104
  compute: {},
105
+ // What the owned engine adds to three's info, as the Wasm engine does: the samples the scene draws with (1 while the
106
+ // temporal pass replaces multisampling) and that pass's live frame, history and jitter.
107
+ engine: {
108
+ get samples() { return globalThis.tn.renderInfo().samples; },
109
+ get temporal() { return globalThis.tn.renderInfo().temporal; },
110
+ // The GPU ms by named stage (gpu-stages.ts) of that sample; a stage that drew no pass is absent. Segments 0..3 are
111
+ // the shadow, scene, other and output passes, so the named stages follow them in `GPU_STAGES` order.
112
+ get gpuStages() {
113
+ const { segments } = globalThis.tn.renderInfo().gpuTiming;
114
+ const stages = {};
115
+ GPU_STAGES.forEach((name, index) => { if (segments[4 + index] > 0) stages[name] = segments[4 + index]; });
116
+ if (segments[0] > 0) stages[SHADOW_STAGE] = segments[0];
117
+ return stages;
118
+ },
119
+ },
60
120
  frame: 0,
61
121
  reset() {},
62
122
  };
63
123
  // WebGPURenderer's defaults; the player applies them before each frame it draws.
64
124
  shadowMap = new ShadowMap();
125
+ __customToneMapping = null;
126
+ library = defineToneMappingLibrary(
127
+ () => [globalThis.tsl.toneMappingColor(), globalThis.tsl.uniform(1).setName("toneMappingExposure")],
128
+ (node) => { this.__customToneMapping = node; },
129
+ );
65
130
  toneMapping = 0;
66
131
  toneMappingExposure = 1;
67
132
  outputColorSpace = "srgb";
@@ -76,6 +141,8 @@ export class WebGPURenderer {
76
141
  getClearAlpha() { return this.__clearColor[3]; }
77
142
  setClearAlpha(alpha) { this.__clearColor[3] = alpha; }
78
143
  setPixelRatio() {}
144
+ // The player draws at the surface it opened, so the drawing buffer is the CSS size.
145
+ getPixelRatio() { return 1; }
79
146
  // three's `await renderer.init()`: the player owns the GPU and has opened it before any script runs.
80
147
  async init() { return this; }
81
148
  // WebGPUCapabilities.getMaxAnisotropy: WebGPU samplers clamp maxAnisotropy to 16.
@@ -90,6 +157,7 @@ export class WebGPURenderer {
90
157
  return target.set(width, height);
91
158
  }
92
159
  render(scene, camera) {
160
+ updateTempNodes(this, scene, camera);
93
161
  drawSecondaryPasses(this);
94
162
  globalThis.__tnGameSpan?.(GAME_SPANS.transport, 0);
95
163
  try { syncUniforms(); } finally { globalThis.__tnGameSpan?.(GAME_SPANS.transport, 1); }
@@ -97,14 +165,39 @@ export class WebGPURenderer {
97
165
  try {
98
166
  globalThis.tn.scene = scene;
99
167
  globalThis.tn.camera = camera;
168
+ this.library.apply(this.toneMapping);
100
169
  globalThis.tn.setRendererState(this);
101
170
  } finally { globalThis.__tnGameSpan?.(GAME_SPANS.publish, 1); }
171
+ this.__worldFrame = this.info.frame;
172
+ }
173
+ // core's canvas layer (a loading screen, a canvas HUD), drawn over this frame's world with no post and no temporal
174
+ // step (Renderer::overlayRenderer), and never published as tn.scene: as the world, it moved the world's temporal
175
+ // history and metered exposure. A frame core draws no world in (a held loader frame) draws the overlay alone;
176
+ // core advances info.frame once per frame.
177
+ renderOverlay(scene, camera) {
178
+ syncUniforms();
179
+ globalThis.tn.renderOverlay(scene, camera, this.__worldFrame === this.info.frame);
102
180
  }
103
181
  compileAsync(root, camera, scene) {
104
182
  syncUniforms();
183
+ this.library.apply(this.toneMapping);
105
184
  globalThis.tn.setRendererState(this);
106
185
  return globalThis.tn.compileAsync(root, camera, scene);
107
186
  }
187
+ // Core warm-up's PMREM preparer (warmup.ts nativeEnvironmentPreparer): the player skips every frame
188
+ // whose environment is not baked yet, so startup waits for the bake instead of counting empty frames.
189
+ // True once baked; false at `deadlineMs` (a performance.now() time).
190
+ async prepareEnvironmentAsync(scene, camera, deadlineMs = Number.POSITIVE_INFINITY) {
191
+ syncUniforms();
192
+ this.library.apply(this.toneMapping);
193
+ globalThis.tn.setRendererState(this);
194
+ while (performance.now() < deadlineMs) {
195
+ if (globalThis.tn.prepareEnvironment(scene, camera)) return true;
196
+ // A macrotask: the GPU completion that advances the bake lands between tasks.
197
+ await new Promise((resolve) => setTimeout(resolve, 0));
198
+ }
199
+ return false;
200
+ }
108
201
  // PRD-620: three's compute(node | node[]) queues kernels in call order; the player runs them before the
109
202
  // frame's passes (and before a render target or a read of one). A dispatch size override has no native form.
110
203
  compute(computeNodes, dispatchSize = null) {
@@ -131,6 +224,20 @@ defineRenderTargets(WebGPURenderer.prototype, (renderer) => ({
131
224
  // three's QuadMesh over the engine Mesh (shared with the Wasm back end).
132
225
  export const QuadMesh = defineQuadMesh(globalThis);
133
226
 
227
+ // three's TempNode (shared with the Wasm back end): the V8 TSL adapter reads a game node's engine node
228
+ // under `threenative.tslNode`, and each top-level render runs the FRAME nodes' updateBefore first. An
229
+ // engine node carries its methods itself; the adapter calls them on the receiver's engine node.
230
+ const tslNode = Symbol.for("threenative.tslNode");
231
+ const nodeMethods = Object.defineProperties({}, Object.getOwnPropertyDescriptors(globalThis.tsl.float(0)));
232
+ const tempNodes = defineTempNode(nodeMethods, tslNode, (output) => (tslNode in output ? output[tslNode] : output));
233
+ export const { TempNode } = tempNodes;
234
+ // The game's startup render() runs before the player opens its renderer and draws no frame, so its nodes
235
+ // update on the first render() of a drawn frame.
236
+ let tempFrame = 0;
237
+ const updateTempNodes = (renderer, scene, camera) => {
238
+ if (globalThis.tn.hasRenderer()) tempNodes.update({ renderer, scene, camera, frameId: ++tempFrame });
239
+ };
240
+
134
241
  // three's RenderPipeline(renderer, outputNode): the player installs the node graph as its post pass
135
242
  // (once per graph) and draws it with the renderer's settings.
136
243
  export class RenderPipeline {
@@ -145,8 +252,10 @@ export class RenderPipeline {
145
252
  render() {
146
253
  this.context.onBeforeRenderPipeline?.();
147
254
  try {
255
+ updateTempNodes(this.renderer, globalThis.tn.scene, globalThis.tn.camera);
148
256
  drawSecondaryPasses(this.renderer);
149
257
  syncUniforms();
258
+ this.renderer.library.apply(this.renderer.toneMapping);
150
259
  globalThis.tn.setRendererState(this.renderer);
151
260
  if (this._source !== this.outputNode) {
152
261
  this._source = this.outputNode;
@@ -193,15 +302,21 @@ export class BlendMode {
193
302
  // three's ReadbackBuffer (shared with the Wasm back end).
194
303
  export { ReadbackBuffer } from "../../../../three-native/src/storage.ts";
195
304
 
196
- // Game-authored node lifecycles and fullscreen node materials have no V8 renderer binding. They stay
197
- // importable, so a game that defines a node class or imports them runs; one that constructs or calls
198
- // them fails at that use, by name. TempNode is a real constructor so `class X extends TempNode` loads.
199
- export class TempNode {
200
- constructor() {
201
- throw new Error("TN_NATIVE_UNSUPPORTED_TEMPNODE: TempNode is not available on the native engine.");
202
- }
203
- }
204
305
  export const NodeMaterial = globalThis.NodeMaterial;
205
306
  Object.setPrototypeOf(NodeMaterial.prototype, Material.prototype);
206
307
  NodeMaterial.prototype.isNodeMaterial = true;
207
- export const RendererUtils = unsupportedExport("RendererUtils");
308
+ // three's RendererUtils state save/restore (shared with the Wasm back end).
309
+ export const RendererUtils = defineRendererUtils(Color);
310
+ // Refused at use: only VirtualShadowNode.setup builds one, and the engine draws that map in C++.
311
+ export const AssignNode = unsupportedExport("AssignNode");
312
+
313
+ WebGPURenderer.prototype.SphereReflectionCapture = defineSphereReflectionCapture(
314
+ async (scene, x, y, z, size, face, renderer) => {
315
+ // A face is a render of `scene` (three's CubeCamera.update): its FRAME nodes update first, once per frame, so a
316
+ // sky node's look-up tables are drawn before a face reads them (the Wasm back end does the same).
317
+ if (globalThis.tn.hasRenderer()) tempNodes.update({ renderer, scene, frameId: tempFrame });
318
+ syncUniforms();
319
+ const bytes = await globalThis.tn.captureFace(scene, x, y, z, size, face);
320
+ return bytes === null ? null : new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
321
+ }, DataTexture,
322
+ );