@threenative/three-native 0.3.10 → 0.3.12

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.
@@ -32,7 +32,12 @@ import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
32
32
  import type { CatalogEntry, ICatalog } from "./catalog.js";
33
33
  import { CPU_STAGE_FIELDS } from "./gpu-stages.js";
34
34
  import { withMathUtilsExtras } from "./math-utils.js";
35
- import { Material, defineObjectSurface, defineTypeFlags } from "./object-surface.js";
35
+ import {
36
+ Material,
37
+ defineObjectSurface,
38
+ defineReleaseNoops,
39
+ defineTypeFlags,
40
+ } from "./object-surface.js";
36
41
  import { type PassDraw, definePass } from "./pass-node.js";
37
42
  import { definePropertyBinding } from "./property-binding.js";
38
43
  import { defineQuadMesh } from "./quad-mesh.js";
@@ -52,7 +57,8 @@ const UPSTREAM_SOURCES = new Set(["three", "three/webgpu", "three/tsl"]);
52
57
  /**
53
58
  * A value that throws `diagnostic` on any call, construction or property access. Its `prototype`
54
59
  * alone reads, so a module may declare a subclass (core's `VirtualShadowNode extends ShadowBaseNode`)
55
- * and fail only when it constructs one.
60
+ * and fail only when it constructs one. `Symbol.hasInstance` reads as absent, so `x instanceof Sub`
61
+ * is the ordinary prototype check (always false here) instead of a throw on every caller.
56
62
  */
57
63
  function refused(name: string, diagnostic: string): unknown {
58
64
  const fail = (): never => {
@@ -61,7 +67,8 @@ function refused(name: string, diagnostic: string): unknown {
61
67
  return new Proxy(function refusedExport() {}, {
62
68
  apply: fail,
63
69
  construct: fail,
64
- get: (target, key) => (key === "prototype" ? target.prototype : fail()),
70
+ get: (target, key) =>
71
+ key === "prototype" ? target.prototype : key === Symbol.hasInstance ? undefined : fail(),
65
72
  set: fail,
66
73
  has: fail,
67
74
  ownKeys: fail,
@@ -170,13 +177,7 @@ export async function bindWebEngine(
170
177
  }
171
178
  : counters;
172
179
  defineTypeFlags(classes);
173
- // three's BatchedMesh/InstancedMesh.dispose frees the instance textures; the engine frees its instance
174
- // buffers with the object, so the call has nothing to release (core's projection mirror makes it).
175
- for (const name of ["BatchedMesh", "InstancedMesh"]) {
176
- const prototype = (classes[name] as { prototype: { dispose?: () => void } } | undefined)
177
- ?.prototype;
178
- if (prototype !== undefined) prototype.dispose ??= () => {};
179
- }
180
+ defineReleaseNoops(classes);
180
181
  // attributes/groups, shape.holes and the abstract Material, as on the V8 player (object-surface.ts).
181
182
  const entries = engineCatalog.entries;
182
183
  const extending = (base: string) =>
@@ -232,6 +233,8 @@ export async function bindWebEngine(
232
233
  bound.MathUtils = withMathUtilsExtras(bound.MathUtils as new () => object);
233
234
  // Offscreen PassNodes (pass-node.ts) draw into their targets at the top of each frame; the TSL block below binds it.
234
235
  let drawSecondaryPasses: PassUpdate = () => {};
236
+ // A frame PassNode's updateBefore runs once a frame, as three's node update system runs it.
237
+ let updatePasses: (frame?: { frameId?: number }) => void = () => {};
235
238
  // The product host draws; a module without it (the ABI-only test module) keeps the refusal.
236
239
  // Before each frame: edited Color/VectorN uniform values reach the engine, world poses WebAudio,
237
240
  // and the wrapper safe point runs (collect: held while the engine references them).
@@ -244,6 +247,9 @@ export async function bindWebEngine(
244
247
  module,
245
248
  classes.Color as never,
246
249
  (frame) => {
250
+ // Each renderer render runs the live frame passes' updateBefore, as three's node update does;
251
+ // a render that advances no frame (a standing frame the runner asks for) still hears them.
252
+ updatePasses(frame);
247
253
  // A compute dispatch passes no frame: it belongs to the frame already collected.
248
254
  const frameId = frame?.frameId ?? collectedFrame;
249
255
  if (updating || (frameId !== undefined && frameId === collectedFrame)) {
@@ -281,6 +287,8 @@ export async function bindWebEngine(
281
287
  // draws the scene and camera the pass points at.
282
288
  const target: { scene?: unknown; camera?: unknown } = {};
283
289
  bound.RenderPipeline = defineRenderPipeline(runtime.tsl, target);
290
+ // The frame counters a host module answers (0 from a module without one, before it draws).
291
+ const hostFrame = (module as Partial<WebHostModule>)._tnw_web_frame;
284
292
  const passes = definePass(
285
293
  tsl.exports as never,
286
294
  (scene, camera) => {
@@ -289,11 +297,21 @@ export async function bindWebEngine(
289
297
  },
290
298
  classes.RenderTarget === undefined
291
299
  ? undefined
292
- : // quality-allow: three's class name, so a back end passes its class map.
293
- // biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
294
- { RenderTarget: classes.RenderTarget as never },
300
+ : {
301
+ // quality-allow: three's class name, so a back end passes its class map.
302
+ // biome-ignore lint/style/useNamingConvention: three's class name, so a back end passes its class map.
303
+ RenderTarget: classes.RenderTarget as never,
304
+ // The frame pass draws at the engine's input size, at the frame's sample count (tnw_web_frame's
305
+ // 35, 36 and 18), so a game reads the size and MSAA the engine actually drew.
306
+ surface: () => ({
307
+ width: hostFrame?.call(module, 35) ?? 0,
308
+ height: hostFrame?.call(module, 36) ?? 0,
309
+ }),
310
+ samples: () => hostFrame?.call(module, 18) ?? 0,
311
+ },
295
312
  );
296
313
  drawSecondaryPasses = passes.updateSecondaryPasses;
314
+ updatePasses = passes.updateFramePasses;
297
315
  Object.assign(bound, passes);
298
316
  }
299
317
  return bindUpstreamExports(names, engineCatalog, bound);
@@ -0,0 +1,79 @@
1
+ /**
2
+ * What a JS value becomes on its way to the engine (PRD-532, PRD-803): three's typed arrays with the
3
+ * engine's scalar order they name, the symbol that keeps a value's storage type, the ref slot every
4
+ * engine wrapper carries, and the parameter rules three's own `Color.set` and `Material.setValues`
5
+ * apply to a constructor's parameters object.
6
+ */
7
+
8
+ export type TypedArray =
9
+ | Float32Array
10
+ | Float64Array
11
+ | Int8Array
12
+ | Uint8Array
13
+ | Int16Array
14
+ | Uint16Array
15
+ | Int32Array
16
+ | Uint32Array;
17
+
18
+ export const REF = Symbol("tn.engineRef");
19
+
20
+ /** A number list that came from a typed array names it, so the engine keeps three's storage type. */
21
+ export const TYPED = Symbol("tn.typedArray");
22
+ // The engine's Scalar order: F32, F64, I8, U8, I16, U16, I32, U32.
23
+ export const SCALARS = [
24
+ Float32Array,
25
+ Float64Array,
26
+ Int8Array,
27
+ Uint8Array,
28
+ Int16Array,
29
+ Uint16Array,
30
+ Int32Array,
31
+ Uint32Array,
32
+ ];
33
+
34
+ export function isPlainObject(value: unknown): boolean {
35
+ return (
36
+ typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype
37
+ );
38
+ }
39
+
40
+ export function isWrapperOf(
41
+ value: unknown,
42
+ className: string,
43
+ ): value is Record<string, (...args: unknown[]) => unknown> {
44
+ return (
45
+ typeof value === "object" &&
46
+ value !== null &&
47
+ REF in value &&
48
+ value.constructor.name === className
49
+ );
50
+ }
51
+
52
+ /** three's `Color.set`: a hex number, a CSS string, or another Color. */
53
+ export function setColor(
54
+ color: Record<string, (...args: unknown[]) => unknown>,
55
+ value: unknown,
56
+ ): void {
57
+ if (typeof value === "number") color.setHex?.(value);
58
+ else if (typeof value === "string") color.setStyle?.(value);
59
+ else color.copy?.(value);
60
+ }
61
+
62
+ /**
63
+ * three's `Material.setValues`: an undefined value is skipped, a Color member is set from a hex,
64
+ * a CSS string or another Color, a Vector3 member copies a Vector3, everything else is assigned.
65
+ * three warns and drops a key the object does not have; here that key fails.
66
+ */
67
+ export function setValues(target: object, className: string, values: object): void {
68
+ const self = target as Record<string, unknown>;
69
+ for (const [key, value] of Object.entries(values)) {
70
+ if (value === undefined) continue;
71
+ const current = self[key];
72
+ if (current === undefined)
73
+ throw new TypeError(`TN_BROWSER_PARAMETER_UNSUPPORTED: ${className} has no '${key}'`);
74
+ if (isWrapperOf(current, "Color")) setColor(current, value);
75
+ else if (isWrapperOf(current, "Vector3") && (value as { isVector3?: boolean }).isVector3)
76
+ current.copy?.(value);
77
+ else self[key] = value;
78
+ }
79
+ }
@@ -17,6 +17,7 @@ import {
17
17
  type WorkCountName,
18
18
  } from "./gpu-stages.js";
19
19
  import type { PassDraw } from "./pass-node.js";
20
+ import { frameAttachmentName } from "./pass-node.js";
20
21
  import { defineRenderTargets, targetTexelBytes } from "./render-target.js";
21
22
  import { ShadowMap } from "./shadow-map.js";
22
23
  import { syncVirtualShadowLods } from "./shadow-node.js";
@@ -41,9 +42,14 @@ type HostCall =
41
42
  | "_tnw_web_renderer_state"
42
43
  | "_tnw_web_frame"
43
44
  | "_tnw_web_render_target"
45
+ | "_tnw_web_clear_target"
44
46
  | "_tnw_web_read_target"
45
47
  | "_tnw_web_read_target_take"
46
48
  | "_tnw_web_capture_face"
49
+ | "_tnw_web_init_texture"
50
+ | "_tnw_web_copy_texture"
51
+ | "_tnw_web_read_mrt"
52
+ | "_tnw_web_device_limit"
47
53
  | "_tnw_web_threads";
48
54
 
49
55
  export type WebHostModule = Record<HostCall, (...args: number[]) => number> & {
@@ -60,7 +66,7 @@ export function isWebHostModule(module: TnAbiModule): module is WebEngineModule
60
66
  * The tnw_* contract this facade speaks (web_host.cpp `kWebHostAbi`). Bump both on every tnw_*
61
67
  * signature change: web-host-abi.spec.ts pins the signatures per number, and a mismatch fails init.
62
68
  */
63
- export const WEB_HOST_ABI = 8;
69
+ export const WEB_HOST_ABI = 11;
64
70
 
65
71
  /** The canvas key the host's surface looks up; Emscripten resolves it before any DOM query. */
66
72
  const CANVAS_TARGET = "!threenative-canvas";
@@ -70,6 +76,7 @@ export const RENDER_AGAIN = Symbol("tn.renderAgain");
70
76
  /** The last RenderPipeline's post graph install, which the warm-up entry points run first (browser-entry.ts). */
71
77
  export const PIPELINE_POST = Symbol("tn.pipelinePost");
72
78
  const DRAW_TARGET = Symbol("tn.drawTarget");
79
+ const CLEAR_TARGET = Symbol("tn.clearTarget");
73
80
  const FAILED = 2;
74
81
  /**
75
82
  * `tnw_web_frame` field of the first named stage's segment (web_host.cpp): 19 + 4 shadow, scene, other and output
@@ -84,6 +91,20 @@ interface IAdapterInfo {
84
91
  readonly device: string;
85
92
  }
86
93
 
94
+ /** three's Box2 and Box3 as a texture copy reads them: a region by its corners. */
95
+ interface IRegionLike {
96
+ readonly isBox3?: boolean;
97
+ readonly min: { readonly x: number; readonly y: number; readonly z?: number };
98
+ readonly max: { readonly x: number; readonly y: number; readonly z?: number };
99
+ }
100
+
101
+ /** A Vector2 or Vector3: the destination origin of a texture copy, z the array layer. */
102
+ interface IPositionLike {
103
+ readonly x: number;
104
+ readonly y: number;
105
+ readonly z?: number;
106
+ }
107
+
87
108
  interface IColorLike {
88
109
  readonly r: number;
89
110
  readonly g: number;
@@ -332,7 +353,14 @@ export function defineWebRenderer(
332
353
  getTimestampFrames(type: string): number[];
333
354
  pipelineCompiles(): number;
334
355
  /** 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 }> };
356
+ readonly device: {
357
+ readonly lost: Promise<{ reason: string; message: string }>;
358
+ /** three's GPUDevice.limits: the pair the colour-attachment proofs check, read from the device once. */
359
+ readonly limits: {
360
+ readonly maxColorAttachments: number;
361
+ readonly maxColorAttachmentBytesPerSample: number;
362
+ };
363
+ };
336
364
  };
337
365
  #deviceLost: (info: { reason: string; message: string }) => void = () => undefined;
338
366
  /** The environment a preparation gave up on at its deadline, until a drawn frame finds it baked. */
@@ -395,6 +423,14 @@ export function defineWebRenderer(
395
423
  lost: new Promise((resolve) => {
396
424
  this.#deviceLost = resolve;
397
425
  }),
426
+ limits: {
427
+ get maxColorAttachments() {
428
+ return module._tnw_web_device_limit(0);
429
+ },
430
+ get maxColorAttachmentBytesPerSample() {
431
+ return module._tnw_web_device_limit(1);
432
+ },
433
+ },
398
434
  },
399
435
  };
400
436
  }
@@ -655,6 +691,12 @@ export function defineWebRenderer(
655
691
  this.info.engine.gpuStages = stages;
656
692
  this.info.engine.shadows.sunGpuMs = module._tnw_web_frame(19);
657
693
  this.info.engine.shadows.lampGpuMs = module._tnw_web_frame(24);
694
+ // Opt-in, as `__tnPassLog`: a probe that sets `__tnGpuSegments` to an array gets each resolved sample's
695
+ // split (frame_gpu_timer.h segments: sun shadow, scene, other passes, output, gather, lamp shadow).
696
+ (globalThis as { __tnGpuSegments?: number[][] }).__tnGpuSegments?.push([
697
+ gpuMs,
698
+ ...[19, 20, 21, 22, 23, 24].map((field) => module._tnw_web_frame(field)),
699
+ ]);
658
700
  }
659
701
  }
660
702
  const engine = this.info.engine;
@@ -772,7 +814,22 @@ export function defineWebRenderer(
772
814
  handles,
773
815
  handles + 12,
774
816
  ...this.#clear,
775
- deferred ? 1 : 0,
817
+ (deferred ? 1 : 0) | (this.autoClear ? 0 : 2),
818
+ ),
819
+ );
820
+ }
821
+
822
+ /** three's clear(color, depth) while a render target is set (render-target.ts): clears it to the clear colour. */
823
+ [CLEAR_TARGET](target: unknown, color: boolean, depth: boolean): void {
824
+ if (this.#adapter === undefined)
825
+ throw new Error("TN_WASM_RENDERER: clear() before init() finished.");
826
+ if (this.#lost) return;
827
+ writeHandle(24, target, "render target");
828
+ this.#drawStatus(
829
+ module._tnw_web_clear_target(
830
+ handles + 24,
831
+ ...this.#clear,
832
+ (color ? 1 : 0) | (depth ? 2 : 0),
776
833
  ),
777
834
  );
778
835
  }
@@ -990,6 +1047,57 @@ export function defineWebRenderer(
990
1047
  return this;
991
1048
  }
992
1049
 
1050
+ /**
1051
+ * three's initTexture: the engine builds the texture's GPU copy now. `source.dataReady = false` (set by a caller
1052
+ * that fills the texture with copyTextureToTexture) uploads nothing and drops the CPU texels.
1053
+ */
1054
+ initTexture(texture: unknown): void {
1055
+ if (this.#adapter === undefined)
1056
+ throw new Error("TN_WASM_RENDERER: initTexture() before init() finished.");
1057
+ writeHandle(0, texture, "texture");
1058
+ const dataReady = (texture as { source?: { dataReady?: boolean } }).source?.dataReady;
1059
+ check(module._tnw_web_init_texture(handles, dataReady === false ? 1 : 0));
1060
+ }
1061
+
1062
+ /**
1063
+ * three's copyTextureToTexture: `srcRegion` is a Box2 or Box3 (the source's image size when null), `dstPosition`
1064
+ * a Vector2 or Vector3 whose z is the destination's array layer. Both textures are initialised first.
1065
+ */
1066
+ copyTextureToTexture(
1067
+ source: unknown,
1068
+ destination: unknown,
1069
+ srcRegion: IRegionLike | null = null,
1070
+ dstPosition: IPositionLike | null = null,
1071
+ srcLevel = 0,
1072
+ dstLevel = 0,
1073
+ ): void {
1074
+ if (this.#adapter === undefined)
1075
+ throw new Error("TN_WASM_RENDERER: copyTextureToTexture() before init() finished.");
1076
+ writeHandle(0, source, "source texture");
1077
+ writeHandle(12, destination, "destination texture");
1078
+ const { min, max } = srcRegion ?? {};
1079
+ // A Box2 has no z: its depth is one layer, a Box3's its own.
1080
+ const size =
1081
+ min && max ? [max.x - min.x, max.y - min.y, (max.z ?? 1) - (min.z ?? 0)] : [-1, -1, 1];
1082
+ check(
1083
+ module._tnw_web_copy_texture(
1084
+ handles,
1085
+ handles + 12,
1086
+ min?.x ?? 0,
1087
+ min?.y ?? 0,
1088
+ min?.z ?? 0,
1089
+ size[0] as number,
1090
+ size[1] as number,
1091
+ srcRegion?.isBox3 ? (size[2] as number) : 1,
1092
+ dstPosition?.x ?? 0,
1093
+ dstPosition?.y ?? 0,
1094
+ dstPosition?.z ?? 0,
1095
+ srcLevel,
1096
+ dstLevel,
1097
+ ),
1098
+ );
1099
+ }
1100
+
993
1101
  getRenderTarget(): null {
994
1102
  return null;
995
1103
  }
@@ -1011,12 +1119,8 @@ export function defineWebRenderer(
1011
1119
  this.setPresentationHeld(false);
1012
1120
  }
1013
1121
  };
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);
1122
+ /** Polls a read id until it delivers, then returns the region's bytes. */
1123
+ const take = async (id: number, size: number) => {
1020
1124
  const out = module._malloc(size) >>> 0;
1021
1125
  try {
1022
1126
  for (;;) {
@@ -1036,6 +1140,39 @@ export function defineWebRenderer(
1036
1140
  module._free(out);
1037
1141
  }
1038
1142
  };
1143
+ const read = async (
1144
+ target: unknown,
1145
+ x: number,
1146
+ y: number,
1147
+ width: number,
1148
+ height: number,
1149
+ textureIndex = 0,
1150
+ ) => {
1151
+ // An RG attachment's texel is two channels, so the region's bytes follow its format as well as its type.
1152
+ const { type, format } = (target as { texture: { type: number; format?: number } }).texture;
1153
+ const size = width * height * targetTexelBytes(type, format);
1154
+ // three's textureIndex selects an attachment of the target. The frame pass's attachments are the
1155
+ // engine's own colour targets, so the index names one and the host reads that slot.
1156
+ const attachment = frameAttachmentName(target, textureIndex);
1157
+ if (attachment !== undefined) {
1158
+ const name = string(attachment);
1159
+ try {
1160
+ const id = module._tnw_web_read_mrt(name, x, y, width, height);
1161
+ if (id === 0) check(1);
1162
+ return await take(id, size);
1163
+ } finally {
1164
+ module._free(name);
1165
+ }
1166
+ }
1167
+ if (textureIndex !== 0)
1168
+ throw new Error(
1169
+ `TN_WASM_READ_TARGET: the target has no colour attachment ${String(textureIndex)}`,
1170
+ );
1171
+ writeHandle(24, target, "render target");
1172
+ const id = module._tnw_web_read_target(handles + 24, x, y, width, height);
1173
+ if (id === 0) check(1);
1174
+ return take(id, size);
1175
+ };
1039
1176
  if (DataTexture !== undefined)
1040
1177
  Object.assign(Renderer.prototype, {
1041
1178
  // quality-allow: the capture API takes the requested Unreal actor name
@@ -1077,6 +1214,12 @@ export function defineWebRenderer(
1077
1214
  root,
1078
1215
  camera,
1079
1216
  ),
1217
+ clear: (target, color, depth) =>
1218
+ (renderer as { [CLEAR_TARGET](t: unknown, c: boolean, d: boolean): void })[CLEAR_TARGET](
1219
+ target,
1220
+ color,
1221
+ depth,
1222
+ ),
1080
1223
  read,
1081
1224
  }));
1082
1225
  return Renderer;
@@ -11,6 +11,7 @@ import {
11
11
  type ConstClasses,
12
12
  booleanUniforms,
13
13
  liveUniforms,
14
+ matrixElements,
14
15
  uniformLanes,
15
16
  withConstValues,
16
17
  } from "./tsl-uniforms.js";
@@ -117,10 +118,14 @@ const FUNCTIONS = [
117
118
  "nodeObject",
118
119
  "color",
119
120
  "ivec2",
121
+ "ivec3",
122
+ "ivec4",
120
123
  "uvec2",
124
+ "bool",
121
125
  "storageTexture",
122
126
  "textureLoad",
123
127
  "textureSize",
128
+ "mrt",
124
129
  "reflect",
125
130
  "dFdx",
126
131
  "dFdy",
@@ -144,6 +149,7 @@ const FUNCTIONS = [
144
149
  "struct",
145
150
  "wgslFunction",
146
151
  "lightShadowMatrix",
152
+ "lights",
147
153
  "luminance",
148
154
  "viewZToOrthographicDepth",
149
155
  "viewZToPerspectiveDepth",
@@ -156,7 +162,12 @@ const FUNCTIONS = [
156
162
  "reflector",
157
163
  "transformDirection",
158
164
  "transformNormalToView",
165
+ "getViewPosition",
166
+ "bumpMap",
167
+ "normalMap",
159
168
  "property",
169
+ "varyingProperty",
170
+ "instanceMatrix",
160
171
  "radians",
161
172
  "degrees",
162
173
  "inverseSqrt",
@@ -209,6 +220,7 @@ const FUNCTIONS = [
209
220
  ] as const;
210
221
  /** The inputs TSL exports as values (tn::abi::tslConstants), each built once, when first read. */
211
222
  const CONSTANTS = [
223
+ "modelViewProjection",
212
224
  "viewportLinearDepth",
213
225
  "frameGroup",
214
226
  "renderGroup",
@@ -224,6 +236,9 @@ const CONSTANTS = [
224
236
  "normalWorld",
225
237
  "positionLocal",
226
238
  "positionWorld",
239
+ "positionView",
240
+ "frontFacing",
241
+ "faceDirection",
227
242
  "positionWorldDirection",
228
243
  "normalViewGeometry",
229
244
  "cameraViewMatrix",
@@ -242,6 +257,9 @@ const CONSTANTS = [
242
257
  "screenCoordinate",
243
258
  "normalGeometry",
244
259
  "tangentGeometry",
260
+ "normalLocal",
261
+ "tangentLocal",
262
+ "positionPrevious",
245
263
  "normalWorldGeometry",
246
264
  "EPSILON",
247
265
  "INFINITY",
@@ -306,6 +324,7 @@ const METHODS = [
306
324
  "smoothstep",
307
325
  "select",
308
326
  "sample",
327
+ "setInterpolation",
309
328
  "__rtt",
310
329
  "oneMinus",
311
330
  "dispose",
@@ -319,6 +338,7 @@ const METHODS = [
319
338
  "flipW",
320
339
  "level",
321
340
  "bias",
341
+ "depth",
322
342
  "transformDirection",
323
343
  "radians",
324
344
  "degrees",
@@ -393,6 +413,7 @@ function takesEngineObject(name: string, index: number): boolean {
393
413
  name === "storageTexture" ||
394
414
  name === "textureStore" ||
395
415
  name === "lightShadowMatrix")) ||
416
+ name === "lights" ||
396
417
  (index < 2 && (name === "reflector" || name === "__rtt"))
397
418
  );
398
419
  }
@@ -441,7 +462,10 @@ export function defineTsl(
441
462
  // and textureLoad also takes a texture node.
442
463
  if (
443
464
  index === 0 &&
444
- (name === "texture" || name === "textureValue") &&
465
+ (name === "texture" ||
466
+ name === "textureValue" ||
467
+ name === "textureLoad" ||
468
+ name === "textureSize") &&
445
469
  typeof value === "object" &&
446
470
  engineRef(value) !== undefined
447
471
  )
@@ -495,7 +519,9 @@ export function defineTsl(
495
519
  const node = (id: number): TslArgValue => ({ kind: "node", node: id });
496
520
  const capture = (form: string, callback: unknown, input?: unknown): number => {
497
521
  if (typeof callback !== "function") throw new TypeError(`TN_TSL ${form}: expected a callback`);
498
- runtime.release(runtime.call("scope:open", null, []));
522
+ runtime.release(
523
+ runtime.call("scope:open", null, form === "Fn" ? [{ kind: "string", text: "Fn" }] : []),
524
+ );
499
525
  depth++;
500
526
  let returned: TslArgValue[] = [];
501
527
  try {
@@ -518,9 +544,8 @@ export function defineTsl(
518
544
  if (depth === 0) throw new TypeError(`TN_TSL ${form}: statement outside Fn`);
519
545
  };
520
546
  prototype.toVar = function (this: ITslNode) {
521
- // Outside a function body there is no stack to declare a variable in (rain's fragment node names its
522
- // terms this way); the expression itself is the value, read where it is used.
523
- if (depth === 0) return this;
547
+ // Outside a function body the engine declares the variable at the top of the program (rain's fragment node
548
+ // names its terms this way; a Fn assigns one handed to it as an `out` argument).
524
549
  return wrap(runtime.call("toVar", this[TSL_NODE], []));
525
550
  };
526
551
  prototype.assign = function (this: ITslNode, value: unknown) {
@@ -572,6 +597,8 @@ export function defineTsl(
572
597
  exports.NodeUpdateType = NodeUpdateType;
573
598
  for (const name of FUNCTIONS)
574
599
  exports[name] = (...args: unknown[]) => wrap(call(name, null, args));
600
+ // three's lights([...]) takes one array; each light crosses as its own engine object.
601
+ exports.lights = (list: readonly unknown[] = []) => wrap(call("lights", null, [...list]));
575
602
  exports.nodeObject = (value: unknown) =>
576
603
  isTslNode(value) ? value : wrap(call("nodeObject", null, [value]));
577
604
  exports.texture = (initial: unknown, ...args: unknown[]) => {
@@ -614,8 +641,13 @@ export function defineTsl(
614
641
  (Array.isArray(first) || first.constructor === Object)
615
642
  ? first
616
643
  : args;
644
+ // As three's nodeObject: a plain object or array (a struct of nodes, a list) passes through unchanged.
617
645
  const asNode = (value: unknown) =>
618
- isTslNode(value) ? value : wrap(call("nodeObject", null, [value]));
646
+ isTslNode(value) ||
647
+ Array.isArray(value) ||
648
+ (typeof value === "object" && value !== null && value.constructor === Object)
649
+ ? value
650
+ : wrap(call("nodeObject", null, [value]));
619
651
  const parameters = Array.isArray(inputs)
620
652
  ? inputs.map(asNode)
621
653
  : Object.fromEntries(Object.entries(inputs).map(([key, value]) => [key, asNode(value)]));
@@ -634,8 +666,9 @@ export function defineTsl(
634
666
  // quality-allow: the export table is untyped; defineStorageTextures narrows it to the builders it reads.
635
667
  defineStorageTextures(exports as unknown as Parameters<typeof defineStorageTextures>[0]),
636
668
  );
637
- // r185's Break(), Continue() and Return(): a loop or kernel ends early (statements, like atomicAdd).
638
- for (const name of ["Break", "Continue", "Return"])
669
+ // r185's Break(), Continue() and Return(): a loop or kernel ends early (statements, like atomicAdd);
670
+ // Discard(conditional) ends the fragment, under If(conditional) when one is given.
671
+ for (const name of ["Break", "Continue", "Return", "Discard"])
639
672
  exports[name] = (...args: unknown[]) => {
640
673
  statement(name);
641
674
  return wrap(call(name, null, args));
@@ -781,9 +814,22 @@ export function defineTsl(
781
814
  },
782
815
  });
783
816
  }
784
- const live = liveUniforms(
785
- exports.uniform as (value: unknown, type?: unknown) => ITslNode,
786
- (node, lanes) => runtime.setUniform(node[TSL_NODE], lanes),
817
+ // uniform(matrix): the engine takes a matN uniform's first value as a constant matN, built here
818
+ // from the matrix's columns; later edits sync through uniformLanes (the 9 or 16 elements).
819
+ const valueUniform = exports.uniform as (value: unknown, type?: unknown) => ITslNode;
820
+ const vec = (n: number) => exports[`vec${n}`] as (...lanes: number[]) => ITslNode;
821
+ const matrixUniform = (value: unknown, type?: unknown): ITslNode => {
822
+ const elements = matrixElements(value);
823
+ if (elements === undefined)
824
+ return type === undefined ? valueUniform(value) : valueUniform(value, type);
825
+ const n = elements.length === 16 ? 4 : 3;
826
+ const columns = Array.from({ length: n }, (_, c) =>
827
+ vec(n)(...Array.from({ length: n }, (_, r) => elements[c * n + r] as number)),
828
+ );
829
+ return valueUniform((exports[`mat${n}`] as (...columns: ITslNode[]) => ITslNode)(...columns));
830
+ };
831
+ const live = liveUniforms(matrixUniform, (node, lanes) =>
832
+ runtime.setUniform(node[TSL_NODE], lanes),
787
833
  );
788
834
  exports.uniform = booleanUniforms(live.uniform, (scalar) =>
789
835
  wrap(call("notEqual", scalar[TSL_NODE], [0])),