@threenative/three-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,11 +1,19 @@
1
1
  import { type IEngineRef, TSL_NODE, engineRef } from "./browser-backend.js";
2
+ import { withFnBuilder } from "./fn-builder.js";
2
3
  import { markNormalTarget } from "./pass-node.js";
3
4
  import { defineQuadMesh } from "./quad-mesh.js";
4
5
  import { type IRttClasses, defineRtt } from "./rtt.js";
5
- import { defineStorage } from "./storage.js";
6
+ import { defineStorage, defineStorageTextures } from "./storage.js";
7
+ import { type INodeFrame, NodeUpdateType, defineTempNode } from "./temp-node.js";
6
8
  import { defineTslExtras } from "./tsl-extras.js";
7
9
  import { defineStruct } from "./tsl-struct.js";
8
- import { type ConstClasses, liveUniforms, uniformLanes, withConstValues } from "./tsl-uniforms.js";
10
+ import {
11
+ type ConstClasses,
12
+ booleanUniforms,
13
+ liveUniforms,
14
+ uniformLanes,
15
+ withConstValues,
16
+ } from "./tsl-uniforms.js";
9
17
  import { defineWgslFn } from "./wgsl-fn.js";
10
18
  /**
11
19
  * TSL on the Wasm engine (PRD-540): three's `three/tsl` authoring functions and node methods as JS
@@ -37,6 +45,7 @@ export interface ITslRuntime {
37
45
  effectParameter(node: number, name: string, value?: number): number;
38
46
  /** three's RenderPipeline: the post graph the web host draws between scene and output, or none. */
39
47
  setPost(node: number | null): void;
48
+ setToneMapping?(node: number | null): void;
40
49
  /** three's `renderer.compute(node)`: queues the kernel; it runs ahead of the next draw or read. */
41
50
  compute(node: number): void;
42
51
  /** `renderer.getArrayBufferAsync(attribute)`: the storage buffer's bytes after every queued kernel. */
@@ -47,6 +56,7 @@ export interface ITslRuntime {
47
56
 
48
57
  /** Module functions the shared table answers (engine/abi/tsl_call.cpp). */
49
58
  const FUNCTIONS = [
59
+ "toneMappingColor",
50
60
  "float",
51
61
  "int",
52
62
  "uint",
@@ -107,7 +117,10 @@ const FUNCTIONS = [
107
117
  "nodeObject",
108
118
  "color",
109
119
  "ivec2",
120
+ "uvec2",
121
+ "storageTexture",
110
122
  "textureLoad",
123
+ "textureSize",
111
124
  "reflect",
112
125
  "dFdx",
113
126
  "dFdy",
@@ -120,6 +133,7 @@ const FUNCTIONS = [
120
133
  "varying",
121
134
  // The live post effects (lane-531's table entries); post-effects.ts publishes them as three's addons.
122
135
  "ao",
136
+ "ssr",
123
137
  "denoise",
124
138
  "smaa",
125
139
  "bloom",
@@ -136,12 +150,62 @@ const FUNCTIONS = [
136
150
  "logarithmicDepthToViewZ",
137
151
  "oneMinus",
138
152
  "mx_noise_float",
153
+ "mx_worley_noise_float",
139
154
  "mx_worley_noise_vec2",
140
155
  "pmremTexture",
141
156
  "reflector",
142
157
  "transformDirection",
143
158
  "transformNormalToView",
144
159
  "property",
160
+ "radians",
161
+ "degrees",
162
+ "inverseSqrt",
163
+ "ceil",
164
+ "sinh",
165
+ "cosh",
166
+ "tan",
167
+ "tanh",
168
+ "asin",
169
+ "asinh",
170
+ "acos",
171
+ "acosh",
172
+ "atanh",
173
+ "sign",
174
+ "round",
175
+ "reciprocal",
176
+ "trunc",
177
+ "transpose",
178
+ "determinant",
179
+ "inverse",
180
+ "difference",
181
+ "pow2",
182
+ "pow3",
183
+ "pow4",
184
+ "transformNormalByViewMatrix",
185
+ "transformNormalByInverseViewMatrix",
186
+ "cbrt",
187
+ "saturate",
188
+ "refract",
189
+ "faceForward",
190
+ "rand",
191
+ "mixElement",
192
+ "smoothstepElement",
193
+ "stepElement",
194
+ "faceforward",
195
+ "inversesqrt",
196
+ "xor",
197
+ "bitAnd",
198
+ "bitNot",
199
+ "bitOr",
200
+ "bitXor",
201
+ "shiftLeft",
202
+ "shiftRight",
203
+ "incrementBefore",
204
+ "decrementBefore",
205
+ "increment",
206
+ "decrement",
207
+ "mat3",
208
+ "mat4",
145
209
  ] as const;
146
210
  /** The inputs TSL exports as values (tn::abi::tslConstants), each built once, when first read. */
147
211
  const CONSTANTS = [
@@ -160,8 +224,10 @@ const CONSTANTS = [
160
224
  "normalWorld",
161
225
  "positionLocal",
162
226
  "positionWorld",
227
+ "positionWorldDirection",
163
228
  "normalViewGeometry",
164
229
  "cameraViewMatrix",
230
+ "modelWorldMatrix",
165
231
  "instanceIndex",
166
232
  "vertexIndex",
167
233
  "screenUV",
@@ -177,9 +243,16 @@ const CONSTANTS = [
177
243
  "normalGeometry",
178
244
  "tangentGeometry",
179
245
  "normalWorldGeometry",
246
+ "EPSILON",
247
+ "INFINITY",
248
+ "PI",
249
+ "PI2",
250
+ "TWO_PI",
251
+ "HALF_PI",
180
252
  ] as const;
181
253
  /** Node methods the shared table answers, with the receiver passed apart. */
182
254
  const METHODS = [
255
+ "element",
183
256
  "compute",
184
257
  "add",
185
258
  "sub",
@@ -245,7 +318,48 @@ const METHODS = [
245
318
  "flipZ",
246
319
  "flipW",
247
320
  "level",
321
+ "bias",
248
322
  "transformDirection",
323
+ "radians",
324
+ "degrees",
325
+ "inverseSqrt",
326
+ "ceil",
327
+ "sinh",
328
+ "cosh",
329
+ "tan",
330
+ "tanh",
331
+ "asin",
332
+ "asinh",
333
+ "acos",
334
+ "acosh",
335
+ "atanh",
336
+ "round",
337
+ "reciprocal",
338
+ "trunc",
339
+ "pow2",
340
+ "pow3",
341
+ "pow4",
342
+ "transformNormalByViewMatrix",
343
+ "transformNormalByInverseViewMatrix",
344
+ "refract",
345
+ "faceForward",
346
+ "difference",
347
+ "saturate",
348
+ "transpose",
349
+ "determinant",
350
+ "inverse",
351
+ "rand",
352
+ "xor",
353
+ "bitAnd",
354
+ "bitNot",
355
+ "bitOr",
356
+ "bitXor",
357
+ "shiftLeft",
358
+ "shiftRight",
359
+ "incrementBefore",
360
+ "decrementBefore",
361
+ "increment",
362
+ "decrement",
249
363
  ] as const;
250
364
  /** three's swizzles: every 1-4 lane combination of xyzw, rgba or stpq, as xyzw lanes. */
251
365
  const SWIZZLES: Readonly<Record<string, string>> = (() => {
@@ -274,7 +388,11 @@ export function isTslNode(value: unknown): value is ITslNode {
274
388
  function takesEngineObject(name: string, index: number): boolean {
275
389
  return (
276
390
  (index === 0 &&
277
- (name === "pmremTexture" || name === "texture3D" || name === "lightShadowMatrix")) ||
391
+ (name === "pmremTexture" ||
392
+ name === "texture3D" ||
393
+ name === "storageTexture" ||
394
+ name === "textureStore" ||
395
+ name === "lightShadowMatrix")) ||
278
396
  (index < 2 && (name === "reflector" || name === "__rtt"))
279
397
  );
280
398
  }
@@ -295,10 +413,11 @@ export function defineTsl(
295
413
  classes?: ConstClasses,
296
414
  ): {
297
415
  exports: Record<string, unknown>;
298
- sync(frame?: { camera?: unknown; scene?: unknown }): void;
416
+ sync(frame?: INodeFrame): void;
299
417
  } {
300
418
  const released = new FinalizationRegistry<number>((node) => runtime.release(node));
301
- const prototype: Record<string, unknown> = {};
419
+ // three marks every node with `isNode`; framework code (Atmosphere.radiance) branches on it.
420
+ const prototype: Record<string, unknown> = { isNode: true };
302
421
  const wrap = (node: number): ITslNode => {
303
422
  const object = Object.create(prototype) as ITslNode;
304
423
  Object.defineProperty(object, TSL_NODE, { value: node, configurable: true });
@@ -322,12 +441,19 @@ export function defineTsl(
322
441
  // and textureLoad also takes a texture node.
323
442
  if (
324
443
  index === 0 &&
325
- name === "texture" &&
444
+ (name === "texture" || name === "textureValue") &&
326
445
  typeof value === "object" &&
327
446
  engineRef(value) !== undefined
328
447
  )
329
448
  return { kind: "handle", ref: engineRef(value) as IEngineRef };
330
- if (index === 0 && (name === "texture" || name === "textureLoad") && typeof value === "object")
449
+ if (
450
+ index === 0 &&
451
+ (name === "texture" ||
452
+ name === "textureLoad" ||
453
+ name === "textureSize" ||
454
+ name === "textureValue") &&
455
+ typeof value === "object"
456
+ )
331
457
  return { kind: "named", text: String((value as { name?: unknown } | null)?.name ?? "") };
332
458
  // A three value is the engine's (`mesh.position`) or JS's own (`new Vector3()`).
333
459
  if (typeof value === "object" && value !== null) {
@@ -438,9 +564,26 @@ export function defineTsl(
438
564
  runtime.release(previous);
439
565
  return this;
440
566
  };
567
+ const custom = defineTempNode(prototype);
441
568
  const exports: Record<string, unknown> = {};
569
+ exports.TempNode = custom.TempNode;
570
+ exports.NodeUpdateType = NodeUpdateType;
442
571
  for (const name of FUNCTIONS)
443
572
  exports[name] = (...args: unknown[]) => wrap(call(name, null, args));
573
+ exports.nodeObject = (value: unknown) =>
574
+ isTslNode(value) ? value : wrap(call("nodeObject", null, [value]));
575
+ exports.texture = (initial: unknown, ...args: unknown[]) => {
576
+ let value = initial;
577
+ const node = wrap(call("texture", null, [value, ...args]));
578
+ return Object.defineProperty(node, "value", {
579
+ get: () => value,
580
+ set: (next: unknown) => {
581
+ if (next === value) return;
582
+ runtime.release(call("textureValue", node[TSL_NODE], [next]));
583
+ value = next;
584
+ },
585
+ });
586
+ };
444
587
  exports.rtt = defineRtt(
445
588
  exports.rtt as Parameters<typeof defineRtt>[0],
446
589
  classes && "Mesh" in classes
@@ -478,11 +621,17 @@ export function defineTsl(
478
621
  };
479
622
  return Object.assign(inline, { setLayout: () => inline });
480
623
  };
481
- for (const name of ["atomicAdd", "atomicStore"])
624
+ exports.Fn = withFnBuilder(exports.Fn as Parameters<typeof withFnBuilder>[0]);
625
+ for (const name of ["atomicAdd", "atomicStore", "textureStore"])
482
626
  exports[name] = (...args: unknown[]) => {
483
627
  statement(name);
484
628
  return wrap(call(name, null, args));
485
629
  };
630
+ Object.assign(
631
+ exports,
632
+ // quality-allow: the export table is untyped; defineStorageTextures narrows it to the builders it reads.
633
+ defineStorageTextures(exports as unknown as Parameters<typeof defineStorageTextures>[0]),
634
+ );
486
635
  // r185's Break(), Continue() and Return(): a loop or kernel ends early (statements, like atomicAdd).
487
636
  for (const name of ["Break", "Continue", "Return"])
488
637
  exports[name] = (...args: unknown[]) => {
@@ -634,7 +783,9 @@ export function defineTsl(
634
783
  exports.uniform as (value: unknown, type?: unknown) => ITslNode,
635
784
  (node, lanes) => runtime.setUniform(node[TSL_NODE], lanes),
636
785
  );
637
- exports.uniform = live.uniform;
786
+ exports.uniform = booleanUniforms(live.uniform, (scalar) =>
787
+ wrap(call("notEqual", scalar[TSL_NODE], [0])),
788
+ );
638
789
  exports.uniformArray = live.uniformArray;
639
790
  exports.reference = live.reference;
640
791
  if (classes !== undefined) withConstValues(exports, classes);
@@ -646,5 +797,11 @@ export function defineTsl(
646
797
  args.length === 2 && args[1] === 0
647
798
  ? (markNormalTarget(vec4, exports.normalView) as typeof vec4)(...args)
648
799
  : vec4(...args);
649
- return { exports, sync: live.sync };
800
+ return {
801
+ exports,
802
+ sync(frame) {
803
+ custom.update(frame);
804
+ live.sync(frame);
805
+ },
806
+ };
650
807
  }
@@ -0,0 +1,115 @@
1
+ import { PLAYTEST_OBSERVING_GLOBAL, callerOf } from "./bridge-meter.js";
2
+
3
+ /** Kept local to the bridge so three-native does not depend on core. */
4
+ export function debugRequested(): boolean {
5
+ const host = globalThis as {
6
+ process?: { env?: Record<string, unknown> };
7
+ [name: string]: unknown;
8
+ };
9
+ return (
10
+ host.process?.env?.TN_DEBUG === "1" ||
11
+ /[?&]tnDebug=1(?:&|$)/u.test(globalThis.location?.search ?? "") ||
12
+ host.__THREENATIVE_DEBUG__ === true
13
+ );
14
+ }
15
+
16
+ type DebugSource = { area: string; caller: string; lever?: string; unit?: string };
17
+
18
+ /** Debug-only cumulative totals; the existing engine counter reader owns windows and reports. */
19
+ export class DebugTelemetry {
20
+ readonly totals: Record<string, number> = {};
21
+ #names = new Map<string, string>();
22
+ #reads = new Map<string, Set<string>>();
23
+ #readCount = 0;
24
+
25
+ add(
26
+ name: string,
27
+ amount = 1,
28
+ area = "bridge",
29
+ caller = "browser-backend.ts",
30
+ unit?: string,
31
+ ): void {
32
+ if (!Number.isFinite(amount) || amount < 0)
33
+ throw new Error(`TN_DEBUG: invalid ${name} observation.`);
34
+ this.totals[name] = (this.totals[name] ?? 0) + amount;
35
+ const host = globalThis as { __tnDebugSources?: Record<string, DebugSource> };
36
+ host.__tnDebugSources ??= {};
37
+ host.__tnDebugSources[name] ??= {
38
+ area,
39
+ caller,
40
+ ...(area === "bridge"
41
+ ? {
42
+ lever:
43
+ "PERFORMANCE-LEARNINGS.md#2026-10-27--web-engine-bridge-keep-what-game-code-reads-again-three-native-back-end--keep",
44
+ }
45
+ : {}),
46
+ ...(unit === undefined ? {} : { unit }),
47
+ };
48
+ }
49
+
50
+ crossing(kind: string, self: { key: string; type: number }, name: string, type: string): void {
51
+ if (((globalThis as Record<string, unknown>)[PLAYTEST_OBSERVING_GLOBAL] as number) > 0) return;
52
+ this.add("bridgeCrossings");
53
+ this.add(`bridge${kind[0]?.toUpperCase()}${kind.slice(1)}Crossings`);
54
+ const label = `${kind} ${type}.${name}`;
55
+ let counter = this.#names.get(label);
56
+ if (counter === undefined && this.#names.size < 4096) {
57
+ counter = `bridge:${label}`;
58
+ this.#names.set(label, counter);
59
+ this.add(counter, 0, "bridge", callerOf(captureStack()));
60
+ }
61
+ if (counter !== undefined) this.add(counter);
62
+ else this.add("bridgeOtherNameCrossings");
63
+ if (kind === "call" || kind === "attributeWrite") {
64
+ this.#readCount -= this.#reads.get(self.key)?.size ?? 0;
65
+ this.#reads.delete(self.key);
66
+ } else if (kind === "set" && this.#reads.get(self.key)?.delete(name)) this.#readCount--;
67
+ if (kind !== "get") return;
68
+ const reads = this.#reads.get(self.key);
69
+ if (reads?.has(name)) {
70
+ this.add("bridgeRedundantReads");
71
+ return;
72
+ }
73
+ // Bound retained identities during a pathological frame; crossing totals remain complete.
74
+ if (this.#readCount >= 65536) return;
75
+ if (reads === undefined) this.#reads.set(self.key, new Set([name]));
76
+ else reads.add(name);
77
+ this.#readCount++;
78
+ }
79
+
80
+ frame(): void {
81
+ this.#reads.clear();
82
+ this.#readCount = 0;
83
+ }
84
+
85
+ widen(value: { readonly byteLength: number }, property: string, encodedBytes: number): void {
86
+ this.add("bridgeTypedSourceBytes", value.byteLength);
87
+ this.add("bridgeTypedEncodedBytes", encodedBytes);
88
+ if (encodedBytes <= value.byteLength) return;
89
+ this.add("bridgeWidenings");
90
+ this.add("bridgeWidenedBytes", encodedBytes);
91
+ const label = `widen ${property}`;
92
+ if (!this.#names.has(label) && this.#names.size < 4096) {
93
+ const counter = `bridge:${label}`;
94
+ this.#names.set(label, counter);
95
+ this.add(counter, 0, "bridge", callerOf(captureStack()), "encoded bytes");
96
+ }
97
+ const counter = this.#names.get(label);
98
+ if (counter !== undefined) this.add(counter, encodedBytes);
99
+ }
100
+ }
101
+
102
+ const meters = new WeakMap<object, DebugTelemetry>();
103
+ export function debugTelemetry(owner: object): DebugTelemetry | undefined {
104
+ if (!debugRequested()) return undefined;
105
+ let meter = meters.get(owner);
106
+ if (meter === undefined) {
107
+ meter = new DebugTelemetry();
108
+ meters.set(owner, meter);
109
+ }
110
+ return meter;
111
+ }
112
+
113
+ function captureStack(): string | undefined {
114
+ return new Error().stack;
115
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * three hands a `Fn` callback its NodeBuilder as the second argument and builds the body once per object,
3
+ * so `builder.object` is the mesh being compiled. The engine builds a body once, at the call, for every
4
+ * object that uses it: a body that reads the builder is refused by name rather than handed `undefined`.
5
+ */
6
+ const refuse = (name: string) => () => {
7
+ throw new Error(
8
+ `TN_NATIVE_FN_BUILDER_UNSUPPORTED: Fn's builder.${name} needs a per-object shader build, which the native engine does not do`,
9
+ );
10
+ };
11
+ const builder = Object.freeze(
12
+ Object.defineProperties(
13
+ {},
14
+ Object.fromEntries(
15
+ ["object", "geometry", "material"].map((name) => [name, { get: refuse(name) }]),
16
+ ),
17
+ ),
18
+ );
19
+
20
+ type Fn = (callback: unknown) => unknown;
21
+
22
+ /** The back end's `Fn`, with three's builder argument as the refusing stand-in. */
23
+ export function withFnBuilder(fn: Fn): Fn {
24
+ return (callback) => {
25
+ if (typeof callback !== "function") throw new TypeError("TN_TSL Fn: expected a callback");
26
+ return fn((inputs: unknown) =>
27
+ (callback as (inputs: unknown, b: unknown) => unknown)(inputs, builder),
28
+ );
29
+ };
30
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The GPU stages the owned engine times by name. A post pass the author labels with one reports its
3
+ * time under that name in `info.engine.gpuStages`, beside the frame's whole time in `info.render.timestamp`;
4
+ * a stage that drew no pass is absent. The order is the native stage id counting from 1
5
+ * (`kStageScreenSpaceGi` in post_effects.h), so a new name goes last.
6
+ */
7
+ export const GPU_STAGES = ["SSGI"] as const;
8
+
9
+ export type GpuStage = (typeof GPU_STAGES)[number];
10
+
11
+ /** The native id of a stage name; fails closed on a name the engine does not time. */
12
+ export function gpuStageId(name: unknown): number {
13
+ const index = GPU_STAGES.indexOf(name as GpuStage);
14
+ if (index < 0)
15
+ throw new TypeError(
16
+ `TN_GPU_STAGE: unknown stage ${String(name)}; the engine times ${GPU_STAGES.join(", ")}`,
17
+ );
18
+ return index + 1;
19
+ }
20
+
21
+ /**
22
+ * The stage the shadow passes' summed time reports under. The engine times them without a label
23
+ * (segment 0 of the frame's timing), so the name is fixed here and is the one `@threenative/core`
24
+ * reads as `SHADOW_STAGE`.
25
+ */
26
+ export const SHADOW_STAGE = "Shadow";
27
+
28
+ /** `tnw_web_frame` field of the shadow passes' segment (web_host.cpp). */
29
+ export const SHADOW_SEGMENT_FIELD = 19;
30
+
31
+ /**
32
+ * The renderer's CPU stages by `tnw_web_frame` field (web_host.cpp 66 to 77): running ms of every render, which
33
+ * core turns into per-frame time in `TN_FRAME_BUDGET.stages` (and, with debug on, `counters.engine`).
34
+ *
35
+ * The renderer's own stages come first: the virtual shadow pages and caster bounds, the draw plan and the shadow
36
+ * passes' draw lists (all three nested in the prepare half), the whole prepare half, and the encode half, of which
37
+ * `cpuPostMs` is the post effects' and output pass's share. Then the scene half of the render database (joints, scene
38
+ * walk, shadow sync) and the web host's own: the whole main-view `tnw_web_render`, the queued kernels' flush inside it
39
+ * and the batched queue submit that ends it (PRD-771), then the `tnw_web_poll` that opens it and its tail (surface texture release, frame gate, diagnostics) and the wall time of `Renderer::render` itself (`rendererMs`, which holds the prepare and encode halves) inside the whole `RenderDatabase::render` call (`hostDatabaseMs`), then the render targets' draws (`hostTargetMs`). The order of the names is the order the page reads them.
40
+ */
41
+ export const CPU_STAGE_FIELDS = {
42
+ cpuVirtualPagesMs: 66,
43
+ cpuPlanMs: 67,
44
+ cpuShadowBuildMs: 68,
45
+ cpuPrepareMs: 69,
46
+ cpuEncodeMs: 70,
47
+ cpuPostMs: 73,
48
+ cpuSceneMs: 74,
49
+ hostRenderMs: 75,
50
+ hostComputeMs: 76,
51
+ hostSubmitMs: 77,
52
+ hostPollMs: 79,
53
+ hostTailMs: 80,
54
+ rendererMs: 81,
55
+ hostDatabaseMs: 82,
56
+ hostTargetMs: 83,
57
+ } as const;
58
+
59
+ export type CpuStageName = keyof typeof CPU_STAGE_FIELDS;
60
+
61
+ /** `[name, field]` pairs of {@link CPU_STAGE_FIELDS}, built once so a per-frame read allocates nothing. */
62
+ export const CPU_STAGE_ENTRIES: readonly (readonly [CpuStageName, number])[] = Object.entries(
63
+ CPU_STAGE_FIELDS,
64
+ ) as [CpuStageName, number][];
65
+
66
+ /**
67
+ * The work counts the host publishes after the stage totals (same array, `tnw_web_frame` 78): transforms moved,
68
+ * shadow casters the virtual atlas judged moving, and bytes the GPU queue took in buffer writes. Running totals.
69
+ */
70
+ export const WORK_COUNT_NAMES = ["dirtyTransforms", "castersMoving", "queueWriteBytes"] as const;
71
+
72
+ export type WorkCountName = (typeof WORK_COUNT_NAMES)[number];