@threenative/three-native 0.3.6 → 0.3.9

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.
@@ -20,15 +20,25 @@ import {
20
20
  createWasmRuntime,
21
21
  defineBrowserClasses,
22
22
  } from "./browser-backend.js";
23
- import { RENDER_AGAIN, defineWebRenderer, isWebHostModule } from "./browser-renderer.js";
23
+ import { ColorManagement } from "./browser-math.js";
24
+ import {
25
+ PIPELINE_POST,
26
+ RENDER_AGAIN,
27
+ type WebHostModule,
28
+ defineWebRenderer,
29
+ isWebHostModule,
30
+ } from "./browser-renderer.js";
24
31
  import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
25
32
  import type { CatalogEntry, ICatalog } from "./catalog.js";
33
+ import { CPU_STAGE_FIELDS } from "./gpu-stages.js";
26
34
  import { withMathUtilsExtras } from "./math-utils.js";
27
35
  import { Material, defineObjectSurface, defineTypeFlags } from "./object-surface.js";
28
36
  import { type PassDraw, definePass } from "./pass-node.js";
29
37
  import { definePropertyBinding } from "./property-binding.js";
30
38
  import { defineQuadMesh } from "./quad-mesh.js";
31
39
  import { defineReflector } from "./reflector.js";
40
+ import { defineRendererUtils } from "./renderer-utils.js";
41
+ import { ShadowBaseNode } from "./shadow-node.js";
32
42
  import { ReadbackBuffer } from "./storage.js";
33
43
  import { defineTextureSources } from "./texture-sources.js";
34
44
 
@@ -103,24 +113,62 @@ export function bindUpstreamExports(
103
113
  }
104
114
 
105
115
  /** Boots the Wasm module and returns every upstream export name bound over it. */
116
+ /**
117
+ * PRD-752 phase 4: `on (N)` names the job pool's workers; `off (<reason>)` says why it has none. The
118
+ * threaded engine runs on shared memory, which only a cross-origin-isolated page has.
119
+ */
120
+ export function webThreadsReport(module: object, isolated: boolean): string {
121
+ const memory = (module as { wasmMemory?: WebAssembly.Memory }).wasmMemory;
122
+ if (typeof SharedArrayBuffer === "undefined" || !(memory?.buffer instanceof SharedArrayBuffer))
123
+ return `off (${isolated ? "single-thread engine build" : "not cross-origin isolated"})`;
124
+ const workers = (module as Partial<WebHostModule>)._tnw_web_threads?.() ?? 0;
125
+ return workers > 0 ? `on (${workers})` : "off (no spare hardware thread)";
126
+ }
127
+
106
128
  export async function bindWebEngine(
107
- createModule: () => Promise<TnAbiModule>,
129
+ createModule: (options?: {
130
+ print: (line: string) => void;
131
+ printErr: (line: string) => void;
132
+ }) => Promise<TnAbiModule>,
108
133
  names: readonly string[],
109
134
  ): Promise<Record<string, unknown>> {
110
- const module = await createModule();
135
+ // Emscripten binds `console.log` once, at load; these read the console per line, so the quiet-marker
136
+ // routing core installs at `start()` also reaches the engine's own TN_RENDERER notes.
137
+ const module = await createModule({
138
+ print: (line) => console.log(line),
139
+ printErr: (line) => console.error(line),
140
+ });
111
141
  // The engine's linear memory, for a bench page's memory report (`memory.buffer` survives growth).
112
142
  const memory = (module as { wasmMemory?: WebAssembly.Memory }).wasmMemory;
113
143
  if (memory !== undefined)
114
144
  (globalThis as { __tnWasmMemoryBytes?: () => number }).__tnWasmMemoryBytes = () =>
115
145
  memory.buffer.byteLength;
146
+ // Core's TN_FRAME_BUDGET carries the verdict.
147
+ (globalThis as { __tnWebThreads?: string }).__tnWebThreads = webThreadsReport(
148
+ module,
149
+ globalThis.crossOriginIsolated === true,
150
+ );
116
151
  const runtime = createWasmRuntime(module);
117
- const { classes, wrap, collect, crossings } = defineBrowserClasses(
152
+ const { classes, wrap, collect, crossings, counters } = defineBrowserClasses(
118
153
  registry as IRegistryDump,
119
154
  runtime,
120
155
  engineCatalog,
121
156
  );
122
157
  // Engine crossings so far, for a bench page's per-frame bridgeCalls (the pair's crossing budget).
123
158
  (globalThis as { __tnCrossingCount?: () => number }).__tnCrossingCount = crossings;
159
+ // The engine's running work totals by name, which core puts per frame into TN_FRAME_BUDGET.counters.engine.
160
+ // The renderer's CPU stage totals ride beside them, so a slow frame names its costly stage.
161
+ (globalThis as { __tnEngineCounters?: () => Record<string, number> }).__tnEngineCounters =
162
+ isWebHostModule(module)
163
+ ? () => {
164
+ const totals = { ...counters() };
165
+ // Off, the engine reads no clock and the totals stand at their last value: listing them would report a stale cost.
166
+ if (module._tnw_web_frame(84) !== 0)
167
+ for (const [name, field] of Object.entries(CPU_STAGE_FIELDS))
168
+ totals[name] = module._tnw_web_frame(field);
169
+ return totals;
170
+ }
171
+ : counters;
124
172
  defineTypeFlags(classes);
125
173
  // three's BatchedMesh/InstancedMesh.dispose frees the instance textures; the engine frees its instance
126
174
  // buffers with the object, so the call has nothing to release (core's projection mirror makes it).
@@ -156,7 +204,9 @@ export async function bindWebEngine(
156
204
  ...withTextureSources(classes, runtime),
157
205
  ...tsl?.exports,
158
206
  };
207
+ bound.RendererUtils = defineRendererUtils(classes.Color as never);
159
208
  bound.Material = Material;
209
+ bound.ShadowBaseNode = ShadowBaseNode;
160
210
  bound.ReadbackBuffer = ReadbackBuffer;
161
211
  // three's PropertyBinding statics and console function over the engine class (shared with V8).
162
212
  if (classes.PropertyBinding !== undefined)
@@ -185,17 +235,34 @@ export async function bindWebEngine(
185
235
  // The product host draws; a module without it (the ABI-only test module) keeps the refusal.
186
236
  // Before each frame: edited Color/VectorN uniform values reach the engine, world poses WebAudio,
187
237
  // and the wrapper safe point runs (collect: held while the engine references them).
238
+ // The safe point and the audio pose run once per renderer frame: collect asks a sixty-fourth of the
239
+ // settled wrappers per call, sized for one call a frame, and a post chain renders about ten passes.
240
+ let updating = false;
241
+ let collectedFrame: number | undefined;
188
242
  if (isWebHostModule(module))
189
243
  bound.WebGPURenderer = defineWebRenderer(
190
244
  module,
191
245
  classes.Color as never,
192
246
  (frame) => {
193
- collect();
194
- tsl?.sync(frame);
195
- audio.updateAudio();
247
+ // A compute dispatch passes no frame: it belongs to the frame already collected.
248
+ const frameId = frame?.frameId ?? collectedFrame;
249
+ if (updating || (frameId !== undefined && frameId === collectedFrame)) {
250
+ tsl?.sync(frame);
251
+ return;
252
+ }
253
+ collectedFrame = frameId;
254
+ updating = true;
255
+ try {
256
+ collect();
257
+ tsl?.sync(frame);
258
+ audio.updateAudio();
259
+ } finally {
260
+ updating = false;
261
+ }
196
262
  },
197
263
  runtime.tsl,
198
264
  (surface, draw) => drawSecondaryPasses(surface, draw),
265
+ bound.DataTexture as never,
199
266
  );
200
267
  // A GLB through the engine's own glTF loader, for the web GLTFLoader (addons/gltf-loader-web.ts).
201
268
  const { loadGltf } = runtime;
@@ -234,17 +301,18 @@ export async function bindWebEngine(
234
301
 
235
302
  /**
236
303
  * The engine classes plus what plain JS adds over them: three's texture sources (typed array,
237
- * canvas, image, ImageBitmapLoader) and `DataUtils`, which touches no engine object at all.
304
+ * canvas, image, ImageBitmapLoader), `DataUtils`, and the `ColorManagement` singleton.
238
305
  */
239
306
  export function withTextureSources(
240
307
  classes: Readonly<Record<string, unknown>>,
241
308
  runtime: IBrowserRuntime,
242
309
  ): Record<string, unknown> {
243
- return { ...classes, ...defineTextureSources(classes, runtime), DataUtils };
310
+ return { ...classes, ...defineTextureSources(classes, runtime), DataUtils, ColorManagement };
244
311
  }
245
312
 
246
313
  interface IPipelineRenderer {
247
314
  [RENDER_AGAIN]?: () => void;
315
+ [PIPELINE_POST]?: () => void;
248
316
  render?(scene: unknown, camera: unknown): void;
249
317
  }
250
318
 
@@ -253,7 +321,10 @@ interface IPipelineRenderer {
253
321
  * the web host, which draws it between the scene and the output, over the scene and camera the
254
322
  * graph's `pass(scene, camera)` points at (`target`), else the renderer's last scene.
255
323
  */
256
- function defineRenderPipeline(tsl: ITslRuntime, target: { scene?: unknown; camera?: unknown }) {
324
+ export function defineRenderPipeline(
325
+ tsl: ITslRuntime,
326
+ target: { scene?: unknown; camera?: unknown },
327
+ ) {
257
328
  return class RenderPipeline {
258
329
  outputNode: unknown;
259
330
  outputColorTransform = true;
@@ -266,14 +337,21 @@ function defineRenderPipeline(tsl: ITslRuntime, target: { scene?: unknown; camer
266
337
  constructor(renderer: IPipelineRenderer, outputNode?: unknown) {
267
338
  this.renderer = renderer;
268
339
  this.outputNode = outputNode;
340
+ // The engine's post graph sets the main pass's sample count (TRAA draws it at 1x), so a warm-up
341
+ // that compiles before the first render() installs it too, or it builds a pass the game never draws.
342
+ renderer[PIPELINE_POST] = this.install;
269
343
  }
270
344
 
345
+ private readonly install = (): void => {
346
+ if (isTslNode(this.outputNode)) tsl.setPost(this.graph(this.outputNode[TSL_NODE]));
347
+ };
348
+
271
349
  render(): void {
272
350
  if (!isTslNode(this.outputNode))
273
351
  throw new TypeError("TN_WASM_POST: RenderPipeline.outputNode is not a TSL node");
274
352
  this.context.onBeforeRenderPipeline?.();
275
353
  try {
276
- tsl.setPost(this.graph(this.outputNode[TSL_NODE]));
354
+ this.install();
277
355
  if (target.scene !== undefined && target.camera !== undefined && this.renderer.render)
278
356
  this.renderer.render(target.scene, target.camera);
279
357
  else this.renderer[RENDER_AGAIN]?.();
@@ -297,6 +375,7 @@ function defineRenderPipeline(tsl: ITslRuntime, target: { scene?: unknown; camer
297
375
  }
298
376
 
299
377
  dispose(): void {
378
+ if (this.renderer[PIPELINE_POST] === this.install) delete this.renderer[PIPELINE_POST];
300
379
  tsl.setPost(null);
301
380
  if (this.outputGraph !== undefined) tsl.release(this.outputGraph);
302
381
  this.outputGraph = undefined;
@@ -1,11 +1,27 @@
1
1
  /**
2
- * three's math value classes in JavaScript (three r185's Vector3, MIT), for the browser back end.
2
+ * three's math value classes in JavaScript (three r185's, MIT), for the browser back end.
3
3
  *
4
- * A `new Vector3()` is a plain JS value: its arithmetic never calls the engine, which cost Midway
5
- * hundreds of thousands of engine calls at load. A vector the engine owns (`mesh.position`) is the
6
- * same class over the engine's memory (see `defineBrowserClasses`), so `copy`, `add` and the rest run
4
+ * A `new Color()` is a plain JS value: its arithmetic never calls the engine, which cost Hop Garden
5
+ * 7.7 s in `Color.lerp` at load. A value the engine owns (`material.color`, `mesh.position`) is the
6
+ * same class over the engine's memory (see `defineBrowserClasses`), so `copy`, `lerp` and the rest run
7
7
  * the same code on both. A value crosses to the engine by value only when an engine call takes it.
8
+ *
9
+ * The nine classes the V8 player already runs as JS (PRD-573 step 4a) are three's own modules, as
10
+ * that player bundles them; Vector3 stays the hand-ported subset this file shipped first.
8
11
  */
12
+ import { Box3 } from "three/src/math/Box3.js";
13
+ import { Color } from "three/src/math/Color.js";
14
+ import { ColorManagement } from "three/src/math/ColorManagement.js";
15
+ import { Euler } from "three/src/math/Euler.js";
16
+ import { Matrix3 } from "three/src/math/Matrix3.js";
17
+ import { Matrix4 } from "three/src/math/Matrix4.js";
18
+ import { Quaternion } from "three/src/math/Quaternion.js";
19
+ import { Sphere } from "three/src/math/Sphere.js";
20
+ import { Vector2 } from "three/src/math/Vector2.js";
21
+ import { Vector3 as UpstreamVector3 } from "three/src/math/Vector3.js";
22
+ import { Vector4 } from "three/src/math/Vector4.js";
23
+
24
+ export { ColorManagement, UpstreamVector3 };
9
25
 
10
26
  interface IVec3 {
11
27
  x: number;
@@ -45,15 +61,17 @@ interface IQuaternionScratch extends IQuat {
45
61
  const clamp = (value: number, min: number, max: number): number =>
46
62
  Math.max(min, Math.min(max, value));
47
63
 
48
- /** The JS classes; `quaternion` makes the engine Quaternion `applyEuler` and `applyAxisAngle` use. */
49
- export function defineMath(quaternion: () => IQuaternionScratch) {
64
+ /** The JS classes, with three's MathUtils subset the engine binds. */
65
+ export function defineMath() {
50
66
  let rotation: IQuaternionScratch | undefined;
51
67
  const scratchQuaternion = (): IQuaternionScratch => {
52
- rotation ??= quaternion();
68
+ rotation ??= new Quaternion() as IQuaternionScratch;
53
69
  return rotation;
54
70
  };
55
71
 
56
72
  class Vector3 implements IVec3 {
73
+ // three's type flag: upstream math (`Matrix4.setPosition`) branches on it.
74
+ readonly isVector3 = true;
57
75
  declare x: number;
58
76
  declare y: number;
59
77
  declare z: number;
@@ -444,5 +462,20 @@ export function defineMath(quaternion: () => IQuaternionScratch) {
444
462
  }
445
463
  }
446
464
 
447
- return { Vector3, MathUtils };
465
+ return {
466
+ Vector2,
467
+ Vector3,
468
+ Vector4,
469
+ Quaternion,
470
+ Euler,
471
+ Matrix3,
472
+ Matrix4,
473
+ Color,
474
+ Box3,
475
+ Sphere,
476
+ MathUtils,
477
+ // three's own Vector3, whose prototype Box3 and Sphere use for their default members; the
478
+ // back end registers it beside the hand-written Vector3 so those members can cross too.
479
+ UpstreamVector3,
480
+ };
448
481
  }