@threenative/three-native 0.0.0-stage → 0.3.5

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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -2
  3. package/package.json +42 -3
  4. package/src/addons/buffer-geometry-utils.ts +14 -0
  5. package/src/addons/data-utils.ts +63 -0
  6. package/src/addons/decal-geometry.ts +25 -0
  7. package/src/addons/decal.ts +218 -0
  8. package/src/addons/gltf-loader-web.ts +323 -0
  9. package/src/addons/hdr-loader.ts +71 -0
  10. package/src/addons/hdr.ts +139 -0
  11. package/src/addons/lut-cube-loader-web.ts +17 -0
  12. package/src/addons/lut-cube-loader.ts +149 -0
  13. package/src/addons/merge-geometries.ts +374 -0
  14. package/src/addons/mesh-bvh-webgpu.ts +13 -0
  15. package/src/addons/mesh-bvh.ts +50 -0
  16. package/src/addons/post-effects-web.ts +22 -0
  17. package/src/addons/post-effects.ts +173 -0
  18. package/src/audio.ts +564 -0
  19. package/src/blend-mode.ts +33 -0
  20. package/src/browser-backend.ts +2156 -0
  21. package/src/browser-entry.ts +305 -0
  22. package/src/browser-math.ts +448 -0
  23. package/src/browser-renderer.ts +527 -0
  24. package/src/browser-tsl.ts +650 -0
  25. package/src/catalog.ts +497 -0
  26. package/src/fixture-format.ts +721 -0
  27. package/src/fixture-native.ts +426 -0
  28. package/src/fixture-protocol.ts +315 -0
  29. package/src/math-utils.ts +65 -0
  30. package/src/object-surface.ts +250 -0
  31. package/src/pass-node.ts +286 -0
  32. package/src/property-binding.ts +93 -0
  33. package/src/quad-mesh.ts +54 -0
  34. package/src/reflector.ts +89 -0
  35. package/src/refused.ts +27 -0
  36. package/src/render-target.ts +107 -0
  37. package/src/rtt.ts +158 -0
  38. package/src/shadow-map.ts +21 -0
  39. package/src/storage.ts +206 -0
  40. package/src/texture-sources.ts +252 -0
  41. package/src/tsl-extras.ts +51 -0
  42. package/src/tsl-struct.ts +20 -0
  43. package/src/tsl-uniforms.ts +234 -0
  44. package/src/update-ranges.ts +109 -0
  45. package/src/wgsl-fn.ts +55 -0
@@ -0,0 +1,2156 @@
1
+ /**
2
+ * The browser-JS back end (PRD-532): three's class names as JS classes over the engine's C ABI
3
+ * compiled to Wasm.
4
+ *
5
+ * The classes are built from the binding registry snapshot (`api/native-registry.json`): every class
6
+ * the registry binds becomes a constructor whose prototype carries exactly that class's methods,
7
+ * top-level getters and setters, and member objects. That is the surface the catalog marks supported
8
+ * (`catalog-registry.spec.ts`), and nothing else. Dotted registry paths (`position.x`) are protocol
9
+ * paths and stay off the prototype: `mesh.position.x` goes through the member object.
10
+ *
11
+ * One wrapper per engine handle, so identity survives (`mesh.position === mesh.position`); a
12
+ * collected wrapper releases its object.
13
+ */
14
+
15
+ import { defineMath } from "./browser-math.js";
16
+ import type { ITslRuntime, TslArgValue } from "./browser-tsl.js";
17
+ import { withUpdateRanges } from "./update-ranges.js";
18
+
19
+ export interface IRegistryClass {
20
+ readonly constructor: boolean;
21
+ readonly methods: readonly string[];
22
+ readonly getters: readonly string[];
23
+ readonly setters: readonly string[];
24
+ readonly members: readonly string[];
25
+ /** Language callbacks the engine calls back (`onBeforeRender`). */
26
+ readonly callbacks: readonly string[];
27
+ /** Event types the engine dispatches (AnimationMixer's `finished`, `loop`). */
28
+ readonly events?: readonly string[];
29
+ /** Members the owner keeps for life (`position`, `matrixWorld`): the first answer may be kept. */
30
+ readonly fixedMembers?: readonly string[];
31
+ /** Doubles held in place: [byte offset from the object's `__address`, count] (JSON arrays). */
32
+ readonly fields?: Readonly<Record<string, readonly number[]>>;
33
+ }
34
+
35
+ export interface IRegistryDump {
36
+ readonly classes: Readonly<Record<string, IRegistryClass>>;
37
+ }
38
+
39
+ /** A ref with its handle words kept (see `createWasmRuntime`): type | context << 16, index, generation. */
40
+ interface IPackedRef extends IEngineRef {
41
+ w0: number;
42
+ w1: number;
43
+ w2: number;
44
+ }
45
+
46
+ /** An engine object as the back end sees it: an opaque key and its catalog type id. */
47
+ export interface IEngineRef {
48
+ readonly key: string;
49
+ readonly type: number;
50
+ }
51
+
52
+ export type EngineValue =
53
+ | null
54
+ | undefined
55
+ | number
56
+ | boolean
57
+ | string
58
+ | readonly EngineValue[]
59
+ | IEngineRef
60
+ | { readonly [key: string]: EngineValue };
61
+
62
+ /** What the classes call; the Wasm ABI implements it, and a surface-only runtime refuses every call. */
63
+ export interface IBrowserRuntime {
64
+ typeId(className: string): number;
65
+ construct(className: string, args: readonly EngineValue[]): IEngineRef;
66
+ invoke(self: IEngineRef, method: string, args: readonly EngineValue[]): EngineValue;
67
+ get(self: IEngineRef, path: string): EngineValue;
68
+ set(self: IEngineRef, path: string, value: EngineValue): void;
69
+ release(self: IEngineRef): void;
70
+ /** For each ref, how many references other engine objects hold to its object; one call a batch. */
71
+ engineReferences?(refs: readonly IEngineRef[]): ArrayLike<number>;
72
+ /** Doubles at `address` in the engine's memory (one as a number, more as an array); Wasm only. */
73
+ readDoubles?(address: number, count: number): number | number[];
74
+ /**
75
+ * The engine's memory as doubles, current: Emscripten replaces the view when the memory grows, so a caller
76
+ * reads it per operation and never keeps it. Wasm only.
77
+ */
78
+ heapF64?(): Float64Array;
79
+ /** The byte at `address` in the engine's memory; Wasm only. A registry field `[offset, 0]` is a byte flag. */
80
+ readByte?(address: number): number;
81
+ /** Writes one double at `address` in the engine's memory; Wasm only. */
82
+ writeDouble?(address: number, value: number): void;
83
+ /**
84
+ * A copy of the attribute's data, of its scalar type; three's `attribute.array` is built on it.
85
+ * With `offset`/`count`, a copy of that scalar subrange only (a per-vertex setter syncs one item).
86
+ */
87
+ attributeArray?(self: IEngineRef, offset?: number, count?: number): TypedArray;
88
+ /**
89
+ * Writes `array` into the attribute's data; present with attributeArray. With `offset`, writes that
90
+ * subrange; without it, `array` must be the attribute's whole data.
91
+ */
92
+ attributeWrite?(self: IEngineRef, array: TypedArray, offset?: number): void;
93
+ /** Sets (or, with null, clears) a callback the engine runs; `handler` gets the engine's arguments. */
94
+ setCallback(
95
+ self: IEngineRef,
96
+ name: string,
97
+ handler: ((args: readonly EngineValue[]) => void) | null,
98
+ ): void;
99
+ /** TSL by name (PRD-540), when the module carries `tn_tsl_call`. */
100
+ readonly tsl?: ITslRuntime;
101
+ /** A GLB through the engine's own glTF loader (PRD-540), when the module carries the web host. */
102
+ loadGltf?(
103
+ bytes: Uint8Array,
104
+ files?: ReadonlyMap<string, Uint8Array>,
105
+ ): { readonly scene: IEngineRef; readonly animations: IEngineRef[] };
106
+ }
107
+
108
+ /** The engine node id a TSL wrapper (`browser-tsl.ts`) carries. */
109
+ export const TSL_NODE = Symbol("tn.tslNode");
110
+
111
+ /** The defined classes and the callback safe point the host runs between frames. */
112
+ export interface IBrowserEngine {
113
+ readonly classes: Record<string, new (...args: unknown[]) => object>;
114
+ /**
115
+ * The safe point (the renderer runs one before every frame). A wrapper the engine references (a
116
+ * parent, a material slot) is held, so its JS state (userData, expandos, a subclass, callbacks)
117
+ * survives while JS keeps no reference; once nothing in the engine references it, it is let go,
118
+ * so a detached subtree, its closures and its wrappers are collected.
119
+ */
120
+ collect(): void;
121
+ /** Engine crossings so far (construct, get, set, invoke, engineReferences): a bench rung's bridgeCalls. */
122
+ crossings(): number;
123
+ /** The wrapper for an engine object the engine handed over (a loaded model's scene). */
124
+ wrap(ref: IEngineRef): object;
125
+ }
126
+
127
+ /** Safe points a pass over the settled wrappers spans. */
128
+ const SETTLED_PASS = 64;
129
+
130
+ const REF = Symbol("tn.engineRef");
131
+
132
+ type TypedArray =
133
+ | Float32Array
134
+ | Float64Array
135
+ | Int8Array
136
+ | Uint8Array
137
+ | Int16Array
138
+ | Uint16Array
139
+ | Int32Array
140
+ | Uint32Array;
141
+ /** A number list that came from a typed array names it, so the engine keeps three's storage type. */
142
+ const TYPED = Symbol("tn.typedArray");
143
+ // The engine's Scalar order: F32, F64, I8, U8, I16, U16, I32, U32.
144
+ const SCALARS = [
145
+ Float32Array,
146
+ Float64Array,
147
+ Int8Array,
148
+ Uint8Array,
149
+ Int16Array,
150
+ Uint16Array,
151
+ Int32Array,
152
+ Uint32Array,
153
+ ];
154
+ const ATTRIBUTE_CLASSES = new Set([
155
+ "BufferAttribute",
156
+ "Float32BufferAttribute",
157
+ "Uint16BufferAttribute",
158
+ "Uint32BufferAttribute",
159
+ "InstancedBufferAttribute",
160
+ ]);
161
+
162
+ interface IWrapped {
163
+ [REF]: IEngineRef;
164
+ }
165
+
166
+ /** The engine object behind a back-end wrapper, for a host that talks to the ABI directly. */
167
+ export function engineRef(object: object): IEngineRef | undefined {
168
+ return (object as Partial<IWrapped>)[REF];
169
+ }
170
+
171
+ function isRef(value: unknown): value is IEngineRef {
172
+ return typeof value === "object" && value !== null && "key" in value && "type" in value;
173
+ }
174
+
175
+ function isPlainObject(value: unknown): boolean {
176
+ return (
177
+ typeof value === "object" && value !== null && Object.getPrototypeOf(value) === Object.prototype
178
+ );
179
+ }
180
+
181
+ function isWrapperOf(
182
+ value: unknown,
183
+ className: string,
184
+ ): value is Record<string, (...args: unknown[]) => unknown> {
185
+ return (
186
+ typeof value === "object" &&
187
+ value !== null &&
188
+ REF in value &&
189
+ value.constructor.name === className
190
+ );
191
+ }
192
+
193
+ /** three's `Color.set`: a hex number, a CSS string, or another Color. */
194
+ function setColor(color: Record<string, (...args: unknown[]) => unknown>, value: unknown): void {
195
+ if (typeof value === "number") color.setHex?.(value);
196
+ else if (typeof value === "string") color.setStyle?.(value);
197
+ else color.copy?.(value);
198
+ }
199
+
200
+ /**
201
+ * three's `Material.setValues`: an undefined value is skipped, a Color member is set from a hex,
202
+ * a CSS string or another Color, a Vector3 member copies a Vector3, everything else is assigned.
203
+ * three warns and drops a key the object does not have; here that key fails.
204
+ */
205
+ function setValues(target: object, className: string, values: object): void {
206
+ const self = target as Record<string, unknown>;
207
+ for (const [key, value] of Object.entries(values)) {
208
+ if (value === undefined) continue;
209
+ const current = self[key];
210
+ if (current === undefined)
211
+ throw new TypeError(`TN_BROWSER_PARAMETER_UNSUPPORTED: ${className} has no '${key}'`);
212
+ if (isWrapperOf(current, "Color")) setColor(current, value);
213
+ else if (isWrapperOf(current, "Vector3") && (value as { isVector3?: boolean }).isVector3)
214
+ current.copy?.(value);
215
+ else self[key] = value;
216
+ }
217
+ }
218
+
219
+ /** What the back end reads from the catalog: each class's parent and three's `is*` flags. */
220
+ export interface ICatalogShape {
221
+ readonly entries: readonly {
222
+ readonly name: string;
223
+ readonly kind: string;
224
+ readonly extends?: string | null;
225
+ readonly fields?: readonly {
226
+ readonly name: string;
227
+ readonly type: string;
228
+ readonly mutable?: boolean;
229
+ }[];
230
+ }[];
231
+ }
232
+
233
+ /** Members every scene-graph class gets in JavaScript: game state, walks over `children` and `raycast`. */
234
+ export const LANGUAGE_MEMBERS = [
235
+ "userData",
236
+ "traverse",
237
+ "traverseVisible",
238
+ "traverseAncestors",
239
+ "raycast",
240
+ ] as const;
241
+
242
+ type TraverseCallback = (object: object) => void;
243
+
244
+ /**
245
+ * The `traverse` family, written over `children`, as three writes it. A class whose engine binding
246
+ * has no `children` refuses by name instead of visiting only the root.
247
+ */
248
+ function defineTraversal(
249
+ prototype: Record<string, unknown>,
250
+ className: string,
251
+ hasChildren: boolean,
252
+ walks: boolean,
253
+ ) {
254
+ const childrenOf = (object: object): object[] => {
255
+ if (!hasChildren) throw new TypeError(`TN_BROWSER_UNBOUND: ${className}.children`);
256
+ return (object as { children: object[] }).children;
257
+ };
258
+ // The engine's walk: one crossing for the whole subtree, in three's order (`__walk`).
259
+ const walk = (object: object, visibleOnly: boolean): object[] =>
260
+ (object as { __walk(visibleOnly: boolean): object[] }).__walk(visibleOnly);
261
+ const methods: Record<string, (this: object, callback: TraverseCallback) => void> = {
262
+ traverse(callback) {
263
+ if (walks) {
264
+ for (const object of walk(this, false)) callback(object);
265
+ return;
266
+ }
267
+ callback(this);
268
+ for (const child of childrenOf(this))
269
+ (child as { traverse(c: TraverseCallback): void }).traverse(callback);
270
+ },
271
+ traverseVisible(callback) {
272
+ if (walks) {
273
+ for (const object of walk(this, true)) callback(object);
274
+ return;
275
+ }
276
+ if ((this as { visible: boolean }).visible === false) return;
277
+ callback(this);
278
+ for (const child of childrenOf(this))
279
+ (child as { traverseVisible(c: TraverseCallback): void }).traverseVisible(callback);
280
+ },
281
+ traverseAncestors(callback) {
282
+ const parent = (this as { parent: object | null }).parent;
283
+ if (parent === null) return;
284
+ callback(parent);
285
+ (parent as { traverseAncestors(c: TraverseCallback): void }).traverseAncestors(callback);
286
+ },
287
+ };
288
+ for (const [name, value] of Object.entries(methods))
289
+ Object.defineProperty(prototype, name, { configurable: true, writable: true, value });
290
+ // three's Object3D.raycast(raycaster, intersects): push this object's own hits, no recursion. The engine
291
+ // answers them through Raycaster.intersectObject (the object's native raycast; a Group answers none).
292
+ Object.defineProperty(prototype, "raycast", {
293
+ configurable: true,
294
+ writable: true,
295
+ value(
296
+ this: object,
297
+ raycaster: { intersectObject(object: object, recursive: boolean): unknown[] },
298
+ intersects: unknown[],
299
+ ) {
300
+ intersects.push(...raycaster.intersectObject(this, false));
301
+ },
302
+ });
303
+ }
304
+
305
+ /**
306
+ * Defines every registry class over `runtime`. With `catalog`, classes chain as three's do
307
+ * (`mesh instanceof Object3D`) and carry three's `is*` flags.
308
+ */
309
+ export function defineBrowserClasses(
310
+ registry: IRegistryDump,
311
+ source: IBrowserRuntime,
312
+ catalog?: ICatalogShape,
313
+ ): IBrowserEngine {
314
+ // Every call into the engine counts, one increment each: the bench's crossing budget reads it per frame.
315
+ let crossings = 0;
316
+ const counted =
317
+ <A extends unknown[], R>(call: (...args: A) => R) =>
318
+ (...args: A): R => {
319
+ crossings++;
320
+ return call(...args);
321
+ };
322
+ const runtime: IBrowserRuntime = {
323
+ ...source,
324
+ construct: counted(source.construct),
325
+ get: counted(source.get),
326
+ set: counted(source.set),
327
+ invoke: counted(source.invoke),
328
+ ...(source.engineReferences === undefined
329
+ ? {}
330
+ : { engineReferences: counted(source.engineReferences) }),
331
+ };
332
+ const classes: Record<string, new (...args: unknown[]) => object> = {};
333
+ const byType = new Map<number, { prototype: object }>();
334
+ const typeNames = new Map<number, string>();
335
+ (globalThis as { __tnEngineTypes?: Map<number, string> }).__tnEngineTypes = typeNames;
336
+ // Reads that need no engine call: a field the engine holds in place is read from its memory (Wasm,
337
+ // `readDoubles`), and a fixed member (`position`, `matrixWorld`) is kept after its first answer.
338
+ // Writes still go through the engine's setters, which it reacts to.
339
+ const addresses = new WeakMap<object, number>();
340
+ // Each object's kept `rotation` Euler -> the object, whose quaternion a rotation write syncs.
341
+ const rotations = new WeakMap<object, object>();
342
+ // Properties only the object's own setter or methods change: `name` and `type` (read per track and
343
+ // per bone while a game binds animations), an attribute's shape (read per merge), a mesh's
344
+ // geometry and material. The answer is kept until JS sets it or calls a method on that object.
345
+ // ponytail: an engine call on another object that changes one of these is missed; none does today.
346
+ const labelled = new Set([
347
+ "name",
348
+ "type",
349
+ "itemSize",
350
+ "normalized",
351
+ "gpuType",
352
+ "geometry",
353
+ "material",
354
+ ]);
355
+ const labels = new WeakMap<object, Map<string, unknown>>();
356
+ const mixerStats = new WeakMap<object, object>();
357
+ const fastGetter = (binding: IRegistryClass, property: string) => {
358
+ const field = binding.fields?.[property];
359
+ const read = runtime.readDoubles;
360
+ const readByte = runtime.readByte;
361
+ if (field !== undefined && read !== undefined) {
362
+ const [offset = 0, count = 1] = field;
363
+ // `[offset, 0]` is a byte flag (visible, castShadow, receiveShadow), `[offset, n]` n doubles.
364
+ if (count === 0)
365
+ return readByte === undefined
366
+ ? undefined
367
+ : function (this: object) {
368
+ return readByte(addressOf(this) + offset) !== 0;
369
+ };
370
+ return function (this: object) {
371
+ return read(addressOf(this) + offset, count);
372
+ };
373
+ }
374
+ if (binding.fixedMembers?.includes(property) && !binding.setters.includes(property))
375
+ // The first read defines the member as the object's own read-only property, as three's
376
+ // Object3D has it: every later read is a plain property load, never this getter (R5 reads
377
+ // position and rotation three times per cube per frame).
378
+ return function (this: object) {
379
+ const member = fromEngine(runtime.get(refOf(this), property));
380
+ Object.defineProperty(this, property, { value: member, writable: false });
381
+ if (property === "rotation") rotations.set(member as object, this);
382
+ return member;
383
+ };
384
+ return undefined;
385
+ };
386
+ const addressOf = (self: object): number => {
387
+ let address = addresses.get(self);
388
+ if (address === undefined) {
389
+ address = runtime.get(refOf(self), "__address") as number;
390
+ addresses.set(self, address);
391
+ }
392
+ return address;
393
+ };
394
+ // three's math values are JS (browser-math.ts): `new Vector3()` holds its own lanes. The engine's
395
+ // vectors (`mesh.position`) share that prototype through `engine`, whose lanes are its memory.
396
+ // An engine call takes a JS value by value: a method borrows a pooled engine object and copies
397
+ // the lanes back after the call (an output argument); a constructor or setter, which may keep the
398
+ // object, gets the value itself turned into an engine object in place, so identity survives.
399
+ interface IValueClass {
400
+ name: string;
401
+ lanes: string[];
402
+ engine: object;
403
+ pool: object[];
404
+ top: number;
405
+ }
406
+ const math = defineMath(
407
+ () =>
408
+ new (classes.Quaternion as new () => object)() as ReturnType<
409
+ Parameters<typeof defineMath>[0]
410
+ >,
411
+ ) as Record<string, new (...args: unknown[]) => object>;
412
+ const valueClasses = new Map<object, IValueClass>(); // JS prototype -> its engine side
413
+ const loans: [Record<string, number>, Record<string, number>, IValueClass][] = [];
414
+ let borrowing = false;
415
+ const toEngineArgs = (args: readonly unknown[]): EngineValue[] => {
416
+ borrowing = true;
417
+ try {
418
+ return args.map(toEngine);
419
+ } finally {
420
+ borrowing = false;
421
+ }
422
+ };
423
+ const lend = (value: Record<string, number>, info: IValueClass): IEngineRef => {
424
+ let scratch = info.pool[info.top];
425
+ if (scratch === undefined) {
426
+ scratch = wrap(runtime.construct(info.name, []));
427
+ info.pool.push(scratch);
428
+ }
429
+ info.top++;
430
+ const lanes = scratch as Record<string, number>;
431
+ for (const lane of info.lanes) lanes[lane] = value[lane] as number;
432
+ loans.push([value, lanes, info]);
433
+ return refOf(scratch);
434
+ };
435
+ // Copies each borrowed object's lanes back to its JS value; the result answers the value itself.
436
+ const repay = (mark: number, returned: unknown): unknown => {
437
+ let result = returned;
438
+ for (let i = loans.length - 1; i >= mark; i--) {
439
+ const [value, scratch, info] = loans[i] as (typeof loans)[number];
440
+ for (const lane of info.lanes) value[lane] = scratch[lane] as number;
441
+ info.top--;
442
+ if (result === scratch) result = value;
443
+ }
444
+ loans.length = mark;
445
+ return result;
446
+ };
447
+ const promote = (value: Record<string, number>, info: IValueClass): void => {
448
+ const lanes = info.lanes.map((lane) => value[lane] as number);
449
+ for (const lane of info.lanes) delete value[lane];
450
+ Object.setPrototypeOf(value, info.engine);
451
+ adopt(value, runtime.construct(info.name, lanes));
452
+ };
453
+ const wrappers = new Map<string, WeakRef<object>>();
454
+ // Callbacks: the function lives on its wrapper (a WeakMap entry), so wrapper -> closure is an edge
455
+ // the collector sees; `held` roots a wrapper while the engine may still call it.
456
+ const callbackFunctions = new WeakMap<object, Map<string, (...args: unknown[]) => unknown>>();
457
+ const callbackNames = new Map<string, Set<string>>(); // by handle key, to clear on collection
458
+ const held = new Set<object>(); // handed out since the last safe point: asked at the next one
459
+ const settled = new Set<object>(); // the engine referenced it when asked: asked again a pass at a time
460
+ const hold = (wrapper: object): void => {
461
+ if (!settled.has(wrapper)) held.add(wrapper);
462
+ };
463
+ let cursor = settled.values(); // collect()'s place in `settled`
464
+ let peak = 0; // the most wrappers settled since this pass of `cursor` began
465
+ // userData is the game's: it lives with the wrapper, which `held` keeps while the engine references it.
466
+ const userData = new WeakMap<object, unknown>();
467
+ const shaderNodes = new Map<string, Map<string, unknown>>(); // material key -> slot -> TSL node
468
+ // three's `attribute.array` is the attribute's own JS typed array (PRD-540): the array the
469
+ // constructor was handed, or a copy of the engine's data on first read. A view of Wasm memory
470
+ // would detach when the memory grows, so the shadow is a JS array. The shadow and the engine's
471
+ // store are kept in step (PRD-617): an engine mutator copies back ONLY the range it wrote, so a
472
+ // later game edit to the array wins, and `needsUpdate` sends the array to the engine. A read hands
473
+ // the game the array, so the attribute is `pending` until its array is written back before the next
474
+ // engine call (a per-vertex setter reads no kept array and flushes nothing).
475
+ const { attributeArray, attributeWrite } = runtime;
476
+ const arrays = new WeakMap<object, { array: TypedArray }>();
477
+ const itemSizes = new WeakMap<object, number>();
478
+ const pending = new Set<object>();
479
+ const writeBack = (): void => {
480
+ for (const attribute of pending) {
481
+ const entry = arrays.get(attribute);
482
+ if (entry !== undefined) attributeWrite?.call(runtime, refOf(attribute), entry.array);
483
+ }
484
+ pending.clear();
485
+ };
486
+ const itemSizeOf = (attribute: object): number => {
487
+ let size = itemSizes.get(attribute);
488
+ if (size === undefined) {
489
+ size = Number(runtime.get(refOf(attribute), "itemSize"));
490
+ itemSizes.set(attribute, size);
491
+ }
492
+ return size;
493
+ };
494
+ // The scalar range an attribute mutator wrote: derived from the method and its arguments, so the
495
+ // engine syncs back only those elements. A component setter writes one, setXY/XYZ/XYZW an item's
496
+ // lanes, copyAt a whole destination item.
497
+ const lanes: Record<string, number> = { setX: 0, setY: 1, setZ: 2, setW: 3 };
498
+ const rangeOf = (
499
+ method: string,
500
+ args: readonly unknown[],
501
+ itemSize: number,
502
+ ): readonly [number, number] => {
503
+ const at = Number(args[0]) * itemSize;
504
+ if (method === "copyAt") return [at, itemSize];
505
+ const component = lanes[method];
506
+ if (component !== undefined) return [at + component, 1];
507
+ if (method === "setComponent") return [at + Number(args[1]), 1];
508
+ return [at, method === "setXY" ? 2 : method === "setXYZ" ? 3 : 4];
509
+ };
510
+ const syncRange = (
511
+ attribute: object,
512
+ entry: { array: TypedArray },
513
+ offset: number,
514
+ count: number,
515
+ ): void => {
516
+ // A malformed range (a fraction, NaN, Infinity, a negative offset or a non-positive count) names
517
+ // no element: it must fail, not slip to element 0 through subarray's own coercion. A range that
518
+ // only runs past the end is the engine's documented bounds no-op (`setComponent`/`setRaw`
519
+ // ignore it, as JS does), so there is nothing to read back. A required range read that comes
520
+ // back missing or short is a provider fault, never a silently stale shadow.
521
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(count) || offset < 0 || count <= 0)
522
+ throw new RangeError(
523
+ `TN_NATIVE_ATTRIBUTE_RANGE: [${String(offset)}, ${String(count)}) is not a valid element range`,
524
+ );
525
+ if (offset + count > entry.array.length) return;
526
+ const fresh = attributeArray?.call(runtime, refOf(attribute), offset, count);
527
+ if (fresh === undefined || fresh.length !== count)
528
+ throw new TypeError(
529
+ `TN_NATIVE_ATTRIBUTE_SYNC: attributeArray gave ${fresh === undefined ? "no array" : `${String(fresh.length)} elements`} for [${String(offset)}, ${String(count)})`,
530
+ );
531
+ entry.array.set(fresh, offset);
532
+ };
533
+ const syncFull = (attribute: object, entry: { array: TypedArray }): void => {
534
+ const fresh = attributeArray?.call(runtime, refOf(attribute));
535
+ if (fresh === undefined) return;
536
+ if (fresh.length === entry.array.length) entry.array.set(fresh);
537
+ else entry.array = fresh;
538
+ };
539
+ const released = new FinalizationRegistry<IEngineRef>((ref) => {
540
+ if (wrappers.get(ref.key)?.deref() === undefined) {
541
+ wrappers.delete(ref.key);
542
+ shaderNodes.delete(ref.key); // the engine material keeps its graph; the JS nodes may go
543
+ for (const name of callbackNames.get(ref.key) ?? []) runtime.setCallback(ref, name, null);
544
+ callbackNames.delete(ref.key);
545
+ runtime.release(ref);
546
+ }
547
+ });
548
+
549
+ const adopt = (target: object, ref: IEngineRef): object => {
550
+ (target as IWrapped)[REF] = ref;
551
+ wrappers.set(ref.key, new WeakRef(target));
552
+ released.register(target, ref);
553
+ return target;
554
+ };
555
+ const wrap = (ref: IEngineRef): object => {
556
+ const live = wrappers.get(ref.key)?.deref();
557
+ if (live !== undefined) return live;
558
+ const cls = byType.get(ref.type);
559
+ if (cls === undefined)
560
+ throw new TypeError(`TN_BROWSER_TYPE_UNKNOWN: no class for engine type ${ref.type}`);
561
+ // Held until the next safe point decides: the engine may reference what it just handed out.
562
+ const wrapper = adopt(Object.create(cls.prototype) as object, ref);
563
+ hold(wrapper);
564
+ return wrapper;
565
+ };
566
+ const refOf = (self: unknown): IEngineRef => {
567
+ const ref = (self as Partial<IWrapped> | null)?.[REF];
568
+ if (ref === undefined)
569
+ throw new TypeError(
570
+ "TN_BROWSER_NOT_ENGINE_OBJECT: called on an object the engine does not own",
571
+ );
572
+ return ref;
573
+ };
574
+ const toEngine = (value: unknown): EngineValue => {
575
+ if (value === null || value === undefined) return null;
576
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "string")
577
+ return value;
578
+ if (ArrayBuffer.isView(value) && !(value instanceof DataView)) {
579
+ // quality-allow: a typed-array view read as its numeric index signature, which ArrayBufferView does not declare.
580
+ const list = Array.from(value as unknown as ArrayLike<number>);
581
+ Object.defineProperty(list, TYPED, { value: value.constructor.name });
582
+ return list;
583
+ }
584
+ if (Array.isArray(value)) return Array.from(value as ArrayLike<unknown>, toEngine);
585
+ const info = valueClasses.get(Object.getPrototypeOf(value) as object);
586
+ if (info !== undefined) {
587
+ if (borrowing) return lend(value as Record<string, number>, info);
588
+ promote(value as Record<string, number>, info);
589
+ }
590
+ if (typeof value === "object" && REF in value) {
591
+ // A wrapper passed into the engine is held until the next safe point decides (collect()).
592
+ hold(value);
593
+ return (value as IWrapped)[REF];
594
+ }
595
+ // An options object (`new ExtrudeGeometry(shape, { depth })`) crosses as a record of scalars and
596
+ // engine objects, as the V8 adapter passes it; an undefined value is left out, as three reads it.
597
+ if (isPlainObject(value)) {
598
+ const fields: Record<string, EngineValue> = {};
599
+ for (const [key, item] of Object.entries(value as object)) {
600
+ if (item === undefined) continue;
601
+ if (
602
+ item !== null &&
603
+ typeof item === "object" &&
604
+ !(REF in item) &&
605
+ !valueClasses.has(Object.getPrototypeOf(item) as object)
606
+ )
607
+ throw new TypeError(
608
+ `TN_BROWSER_ARGUMENT_UNSUPPORTED: option ${key} cannot cross to the engine`,
609
+ );
610
+ fields[key] = toEngine(item);
611
+ }
612
+ return fields;
613
+ }
614
+ throw new TypeError(
615
+ `TN_BROWSER_ARGUMENT_UNSUPPORTED: ${typeof value} cannot cross to the engine`,
616
+ );
617
+ };
618
+ const fromEngine = (value: EngineValue): unknown => {
619
+ if (isRef(value)) return wrap(value);
620
+ if (Array.isArray(value)) return value.map(fromEngine);
621
+ if (typeof value === "object" && value !== null)
622
+ return Object.fromEntries(
623
+ Object.entries(value).map(([key, item]) => [key, fromEngine(item)]),
624
+ );
625
+ return value;
626
+ };
627
+ // A geometry bulk mutator (`translate`, `applyMatrix4`, `computeVertexNormals`, ...) writes the
628
+ // bytes of its attributes. The engine already keeps the geometry's current attribute list, so the
629
+ // wrapper enumerates it (one `__attributeNames` read, then a `getAttribute` each) rather than track
630
+ // links that an engine-side attribute replacement would leave stale. A game's edit reaches the
631
+ // engine before the call, and a kept array follows the transform after it.
632
+ const geometryAttributes = (geometry: object): object[] => {
633
+ const listed = runtime.get(refOf(geometry), "__attributeNames");
634
+ if (typeof listed !== "string" || listed === "") return [];
635
+ const found: object[] = [];
636
+ for (const name of listed.split("\n")) {
637
+ const attribute = fromEngine(runtime.invoke(refOf(geometry), "getAttribute", [name]));
638
+ if (typeof attribute === "object" && attribute !== null) found.push(attribute);
639
+ }
640
+ return found;
641
+ };
642
+ const uploadGeometry = (geometry: object): void => {
643
+ for (const attribute of geometryAttributes(geometry)) {
644
+ const entry = arrays.get(attribute);
645
+ if (entry !== undefined) attributeWrite?.call(runtime, refOf(attribute), entry.array);
646
+ }
647
+ };
648
+ const refreshGeometry = (geometry: object): void => {
649
+ for (const attribute of geometryAttributes(geometry)) {
650
+ const entry = arrays.get(attribute);
651
+ if (entry !== undefined) syncFull(attribute, entry);
652
+ }
653
+ };
654
+ // Attribute methods that write only their own range, and the full-array transforms that read their
655
+ // own data. A per-vertex setter must not flush a whole shadow (O(N) per call); a full transform
656
+ // uploads its own shadow once before the call (O(N), bulk, as three reads its array).
657
+ const rangeMethods = new Set([
658
+ "setX",
659
+ "setY",
660
+ "setZ",
661
+ "setW",
662
+ "setXY",
663
+ "setXYZ",
664
+ "setXYZW",
665
+ "setComponent",
666
+ "copyAt",
667
+ ]);
668
+ const transformMethods = new Set([
669
+ "applyMatrix3",
670
+ "applyMatrix4",
671
+ "applyNormalMatrix",
672
+ "transformDirection",
673
+ ]);
674
+ // Geometry methods that write attribute bytes, so a kept shadow must be refreshed after them.
675
+ const geometryWrites = new Set([
676
+ "applyMatrix4",
677
+ "translate",
678
+ "rotateX",
679
+ "rotateY",
680
+ "rotateZ",
681
+ "scale",
682
+ "center",
683
+ "computeVertexNormals",
684
+ "normalizeNormals",
685
+ "setFromPoints",
686
+ "setIndex",
687
+ ]);
688
+
689
+ for (const [name, binding] of Object.entries(registry.classes)) {
690
+ const adopts =
691
+ attributeWrite !== undefined &&
692
+ (name === "BufferAttribute" || name === "InstancedBufferAttribute");
693
+ const attributeClass = ATTRIBUTE_CLASSES.has(name);
694
+ const geometryClass = name.endsWith("Geometry");
695
+ const engineClass = class {
696
+ constructor(...args: unknown[]) {
697
+ if (!binding.constructor) throw new TypeError(`TN_BROWSER_NOT_CONSTRUCTIBLE: ${name}`);
698
+ // three's parameters object (`new MeshStandardMaterial({ color })`) is construct, then
699
+ // setValues, which the wrapper applies key by key. Other classes take an options object as
700
+ // a record argument (ExtrudeGeometry).
701
+ const parameters =
702
+ name.endsWith("Material") && isPlainObject(args.at(-1))
703
+ ? (args.at(-1) as object)
704
+ : undefined;
705
+ const engineArgs = parameters === undefined ? args : args.slice(0, -1);
706
+ adopt(this, runtime.construct(name, engineArgs.map(toEngine)));
707
+ if (parameters !== undefined) setValues(this, name, parameters);
708
+ // three's BufferAttribute keeps the typed array it is handed; the typed subclasses copy.
709
+ const handed = args[0];
710
+ if (adopts && ArrayBuffer.isView(handed) && !(handed instanceof DataView)) {
711
+ arrays.set(this, { array: handed as TypedArray });
712
+ itemSizes.set(this, Number(args[1]));
713
+ pending.add(this);
714
+ }
715
+ }
716
+ };
717
+ const valueClass = math[name];
718
+ const cls = (valueClass ?? engineClass) as typeof engineClass;
719
+ Object.defineProperty(cls, "name", { value: name });
720
+ const prototype = cls.prototype as Record<string, unknown>;
721
+ // A value class's engine accessors (its lanes, `__address`) live on the engine side only.
722
+ const accessors = (valueClass === undefined ? prototype : Object.create(prototype)) as Record<
723
+ string,
724
+ unknown
725
+ >;
726
+ if (valueClass !== undefined && binding.fields !== undefined)
727
+ valueClasses.set(prototype, {
728
+ name,
729
+ lanes: Object.keys(binding.fields ?? {}),
730
+ engine: accessors,
731
+ pool: [],
732
+ top: 0,
733
+ });
734
+ for (const method of binding.methods) {
735
+ if (valueClass !== undefined && Object.hasOwn(prototype, method)) continue;
736
+ // A geometry's attribute lookups are kept with its labels, until anything else runs on it.
737
+ const query = method === "getAttribute" || method === "hasAttribute";
738
+ // A read-only method keeps them too: core's projection asks each mesh __tnVisibleInWorld a frame,
739
+ // and dropping the labels there re-crossed and re-kept every mesh's geometry and material each frame.
740
+ const keeps = query || /^(get|has|clone|equals|toJSON|__tnVisibleInWorld$)/u.test(method);
741
+ // PRD-617 shadows. Apart from an attribute's own range, an engine mutator touches the game's
742
+ // kept arrays: a geometry transform sends and refreshes its attributes' shadows. The three
743
+ // kinds are exclusive, so an attribute setter never enumerates a geometry and vice versa.
744
+ const rangeMethod = attributeClass && rangeMethods.has(method);
745
+ const transformMethod = attributeClass && transformMethods.has(method);
746
+ const geometryWrite = geometryClass && geometryWrites.has(method);
747
+ Object.defineProperty(prototype, method, {
748
+ configurable: true,
749
+ writable: true,
750
+ value(this: object, ...args: unknown[]) {
751
+ const intersections = method === "intersectObject" || method === "intersectObjects";
752
+ const key = query ? `${method} ${String(args[0])}` : "";
753
+ if (query && labels.get(this)?.has(key)) return labels.get(this)?.get(key);
754
+ // A per-vertex setter writes its own range and reads no kept array, so a whole-shadow flush
755
+ // would cost O(N) a call; it syncs just its range back below. Anything else flushes edits.
756
+ if (pending.size > 0 && !rangeMethod) writeBack();
757
+ // A full-array attribute transform reads its own array: send the game's shadow first.
758
+ if (transformMethod) {
759
+ const entry = arrays.get(this);
760
+ if (entry !== undefined) attributeWrite?.call(runtime, refOf(this), entry.array);
761
+ }
762
+ if (geometryWrite) uploadGeometry(this);
763
+ // copyAt reads the source attribute's item: send that item first, then the engine copies it.
764
+ if (
765
+ rangeMethod &&
766
+ method === "copyAt" &&
767
+ typeof args[1] === "object" &&
768
+ args[1] !== null
769
+ ) {
770
+ const source = args[1] as object;
771
+ const entry = arrays.get(source);
772
+ if (entry !== undefined) {
773
+ const item = itemSizeOf(source) * Number(args[2]);
774
+ attributeWrite?.call(
775
+ runtime,
776
+ refOf(source),
777
+ entry.array.subarray(item, item + itemSizeOf(source)),
778
+ item,
779
+ );
780
+ }
781
+ }
782
+ if (!keeps) labels.delete(this);
783
+ const mark = loans.length;
784
+ let result: unknown;
785
+ try {
786
+ result = fromEngine(
787
+ runtime.invoke(
788
+ refOf(this),
789
+ method,
790
+ toEngineArgs(intersections ? args.slice(0, 2) : args),
791
+ ),
792
+ );
793
+ } finally {
794
+ if (loans.length > mark) result = repay(mark, result);
795
+ }
796
+ // The engine wrote only this range: copy it back, so a later game edit to the shadow wins.
797
+ if (rangeMethod) {
798
+ const entry = arrays.get(this);
799
+ if (entry !== undefined) {
800
+ const [offset, count] = rangeOf(method, args, itemSizeOf(this));
801
+ syncRange(this, entry, offset, count);
802
+ }
803
+ } else if (transformMethod) {
804
+ const entry = arrays.get(this);
805
+ if (entry !== undefined) syncFull(this, entry);
806
+ } else if (geometryWrite) refreshGeometry(this);
807
+ if (intersections && args[2] !== undefined) {
808
+ if (!Array.isArray(args[2]) || !Array.isArray(result))
809
+ throw new TypeError("intersection target must be an array");
810
+ args[2].push(...result);
811
+ args[2].sort((a, b) => a.distance - b.distance);
812
+ return args[2];
813
+ }
814
+ if (query)
815
+ labels.get(this)?.set(key, result) ?? labels.set(this, new Map([[key, result]]));
816
+ return result;
817
+ },
818
+ });
819
+ }
820
+ // A transform matrix (`mesh.matrixWorld`, a projection's kept copy) is 16 doubles at an engine address:
821
+ // copy and equals between two engine matrices run over that memory, not as engine calls (PRD-573 web
822
+ // cut 2, the web side of the desktop's TransformPage views). Anything else takes the engine method.
823
+ const elements = binding.fields?.elements;
824
+ const heapF64 = runtime.heapF64;
825
+ if (elements !== undefined && heapF64 !== undefined && binding.methods.includes("copy")) {
826
+ const [offset = 0, count = 0] = elements;
827
+ const engineCopy = prototype.copy as (this: object, other: unknown) => object;
828
+ const engineEquals = prototype.equals as (this: object, other: unknown) => boolean;
829
+ Object.defineProperties(prototype, {
830
+ copy: {
831
+ configurable: true,
832
+ writable: true,
833
+ value(this: object, other: unknown) {
834
+ if (
835
+ other === null ||
836
+ typeof other !== "object" ||
837
+ Object.getPrototypeOf(other) !== prototype
838
+ )
839
+ return engineCopy.call(this, other);
840
+ const from = (addressOf(other) + offset) / 8;
841
+ heapF64().copyWithin((addressOf(this) + offset) / 8, from, from + count);
842
+ return this;
843
+ },
844
+ },
845
+ equals: {
846
+ configurable: true,
847
+ writable: true,
848
+ value(this: object, other: unknown) {
849
+ if (
850
+ other === null ||
851
+ typeof other !== "object" ||
852
+ Object.getPrototypeOf(other) !== prototype
853
+ )
854
+ return engineEquals.call(this, other);
855
+ const heap = heapF64();
856
+ const a = (addressOf(this) + offset) / 8;
857
+ const b = (addressOf(other) + offset) / 8;
858
+ for (let i = 0; i < count; i++) if (heap[a + i] !== heap[b + i]) return false;
859
+ return true;
860
+ },
861
+ },
862
+ });
863
+ }
864
+ const setters = new Set(binding.setters);
865
+ // A node material's TSL slots (`colorNode`) take an engine graph node, which no ABI value
866
+ // carries: the graph goes in through the TSL runtime, and reading the slot answers the node set.
867
+ for (const property of binding.setters.filter((key) => /^[a-z]+Node$/u.test(key))) {
868
+ Object.defineProperty(prototype, property, {
869
+ configurable: true,
870
+ get(this: object) {
871
+ return shaderNodes.get(refOf(this).key)?.get(property) ?? null;
872
+ },
873
+ set(this: object, value: unknown) {
874
+ const ref = refOf(this);
875
+ if (value === null) {
876
+ runtime.set(ref, property, null);
877
+ shaderNodes.get(ref.key)?.delete(property);
878
+ return;
879
+ }
880
+ if (typeof value !== "object" || !(TSL_NODE in value) || !runtime.tsl)
881
+ throw new TypeError(`TN_BROWSER_SHADER_NODE: ${name}.${property} takes a TSL node`);
882
+ runtime.tsl.set(ref, property, (value as Record<symbol, number>)[TSL_NODE] as number);
883
+ const slots = shaderNodes.get(ref.key) ?? new Map<string, unknown>();
884
+ shaderNodes.set(ref.key, slots.set(property, value));
885
+ },
886
+ });
887
+ }
888
+ // A list getter with indexed setters (`morphTargetInfluences.0`) is a live array, as on the V8 adapter:
889
+ // an index write and a whole-array assignment (core's projection shares the source's) reach the engine.
890
+ const indexed = (head: string) =>
891
+ binding.setters.some(
892
+ (path) => path.startsWith(`${head}.`) && /^\d+$/u.test(path.slice(head.length + 1)),
893
+ );
894
+ for (const property of binding.getters) {
895
+ if (property.includes(".") || setters.has(property) || !indexed(property)) continue;
896
+ Object.defineProperty(prototype, property, {
897
+ configurable: true,
898
+ get(this: object) {
899
+ const ref = refOf(this);
900
+ const list = fromEngine(runtime.get(ref, property));
901
+ if (!Array.isArray(list)) return list;
902
+ return new Proxy(list, {
903
+ set(target, key, value) {
904
+ target[key as never] = value as never;
905
+ if (typeof key === "string" && /^\d+$/u.test(key))
906
+ runtime.set(ref, `${property}.${key}`, toEngine(value));
907
+ return true;
908
+ },
909
+ });
910
+ },
911
+ set(this: object, value: ArrayLike<number>) {
912
+ const ref = refOf(this);
913
+ for (let index = 0; index < value.length; index++)
914
+ runtime.set(ref, `${property}.${index}`, value[index] as number);
915
+ },
916
+ });
917
+ }
918
+ const write = runtime.writeDouble;
919
+ for (const property of [...binding.getters, ...binding.members]) {
920
+ if (
921
+ property.includes(".") ||
922
+ binding.methods.includes(property) ||
923
+ Object.hasOwn(accessors, property)
924
+ )
925
+ continue;
926
+ // A value class's lane is written in place: its engine setter is a plain store.
927
+ const lane = valueClass !== undefined ? binding.fields?.[property] : undefined;
928
+ const flagField = binding.fields?.[property];
929
+ const peek = runtime.readByte;
930
+ const flag =
931
+ flagField !== undefined && flagField[1] === 0 && peek !== undefined
932
+ ? (self: object): boolean => peek(addressOf(self) + (flagField[0] ?? 0)) !== 0
933
+ : undefined;
934
+ Object.defineProperty(accessors, property, {
935
+ configurable: true,
936
+ get:
937
+ fastGetter(binding, property) ??
938
+ (name === "AnimationMixer" && property === "stats"
939
+ ? function (this: object) {
940
+ let stats = mixerStats.get(this);
941
+ if (stats !== undefined) return stats;
942
+ const count = (name: string) => {
943
+ const read = (field: "total" | "inUse") => {
944
+ const counts = (
945
+ runtime.get(refOf(this), "stats") as Record<
946
+ string,
947
+ Record<string, number> | undefined
948
+ >
949
+ )[name];
950
+ if (counts === undefined)
951
+ throw new TypeError(`TN_BROWSER_STATS_MISSING: ${name}`);
952
+ return counts[field];
953
+ };
954
+ return Object.defineProperties(
955
+ {},
956
+ {
957
+ total: { get: () => read("total"), enumerable: true, configurable: true },
958
+ inUse: { get: () => read("inUse"), enumerable: true, configurable: true },
959
+ },
960
+ );
961
+ };
962
+ stats = {
963
+ actions: count("actions"),
964
+ bindings: count("bindings"),
965
+ controlInterpolants: count("controlInterpolants"),
966
+ };
967
+ mixerStats.set(this, stats);
968
+ return stats;
969
+ }
970
+ : undefined) ??
971
+ (labelled.has(property)
972
+ ? function (this: object) {
973
+ let known = labels.get(this);
974
+ if (known === undefined) {
975
+ known = new Map();
976
+ labels.set(this, known);
977
+ }
978
+ if (!known.has(property))
979
+ known.set(property, fromEngine(runtime.get(refOf(this), property)));
980
+ return known.get(property);
981
+ }
982
+ : function (this: object) {
983
+ return fromEngine(runtime.get(refOf(this), property));
984
+ }),
985
+ ...(lane !== undefined && write !== undefined
986
+ ? {
987
+ set(this: object, value: number) {
988
+ write(addressOf(this) + (lane[0] ?? 0), value);
989
+ },
990
+ }
991
+ : setters.has(property)
992
+ ? {
993
+ set(this: object, value: unknown) {
994
+ // A flag write of the value the flag holds changes nothing in the engine: a game
995
+ // writes `visible` on hundreds of nodes a frame, so those stay out of the bridge.
996
+ if (flag !== undefined && typeof value === "boolean" && flag(this) === value)
997
+ return;
998
+ labels.delete(this);
999
+ runtime.set(refOf(this), property, toEngine(value));
1000
+ },
1001
+ }
1002
+ : {}),
1003
+ });
1004
+ }
1005
+ // Games turn objects every frame: an object's `rotation` is written in place (the transform page's
1006
+ // rotation column), and its quaternion follows here, as three's onRotationChange does. Any other
1007
+ // Euler, or a set with a new order, still crosses, callback and all. Ported from feat/native-engine
1008
+ // 07297c986 and 5ef18a54f.
1009
+ const order = binding.fields?.__order;
1010
+ const quaternion = registry.classes.Quaternion?.fields;
1011
+ const readLane = runtime.readDoubles;
1012
+ const readByte = runtime.readByte;
1013
+ if (name === "Euler" && order && quaternion && readLane && readByte && write) {
1014
+ const angles = ["x", "y", "z"].map((lane) => binding.fields?.[lane]?.[0] ?? 0);
1015
+ const targets = ["x", "y", "z", "w"].map((lane) => quaternion[lane]?.[0] ?? 0);
1016
+ // three's setFromEuler: each order only signs the second terms, in the engine enum's order.
1017
+ const names = ["XYZ", "YXZ", "ZXY", "ZYX", "YZX", "XZY"];
1018
+ const signs = [
1019
+ [1, -1, 1, -1],
1020
+ [1, -1, -1, 1],
1021
+ [-1, 1, 1, -1],
1022
+ [-1, 1, -1, 1],
1023
+ [1, 1, -1, -1],
1024
+ [-1, -1, 1, 1],
1025
+ ];
1026
+ // Two writes per object per frame land here (R5 turns x then y on 4,096 cubes), so the hot path
1027
+ // allocates nothing: offsets are numbers, the owner's quaternion address is kept per Euler (an
1028
+ // engine object never moves), and lanes are read off HEAPF64 when the runtime has it.
1029
+ const [ox = 0, oy = 0, oz = 0] = angles;
1030
+ const [qx = 0, qy = 0, qz = 0, qw = 0] = targets;
1031
+ const orderAt = order[0] ?? 0;
1032
+ const heap = runtime.heapF64;
1033
+ const lane = heap
1034
+ ? (address: number) => heap()[address / 8] as number
1035
+ : (address: number) => readLane(address, 1) as number;
1036
+ // An object's rotation -> [its address, its owner's quaternion address]: one lookup per write.
1037
+ const places = new WeakMap<object, [number, number]>();
1038
+ const placeOf = (euler: object): [number, number] | undefined => {
1039
+ let place = places.get(euler);
1040
+ if (place === undefined) {
1041
+ const owner = rotations.get(euler);
1042
+ if (owner === undefined) return undefined;
1043
+ place = [addressOf(euler), addressOf((owner as { quaternion: object }).quaternion)];
1044
+ places.set(euler, place);
1045
+ }
1046
+ return place;
1047
+ };
1048
+ const sync = (at: number, q: number) => {
1049
+ const x = lane(at + ox) / 2;
1050
+ const y = lane(at + oy) / 2;
1051
+ const z = lane(at + oz) / 2;
1052
+ const sign = (signs[readByte(at + orderAt)] ?? signs[0]) as number[];
1053
+ const c1 = Math.cos(x);
1054
+ const c2 = Math.cos(y);
1055
+ const c3 = Math.cos(z);
1056
+ const s1 = Math.sin(x);
1057
+ const s2 = Math.sin(y);
1058
+ const s3 = Math.sin(z);
1059
+ write(q + qx, s1 * c2 * c3 + (sign[0] as number) * c1 * s2 * s3);
1060
+ write(q + qy, c1 * s2 * c3 + (sign[1] as number) * s1 * c2 * s3);
1061
+ write(q + qz, c1 * c2 * s3 + (sign[2] as number) * s1 * s2 * c3);
1062
+ write(q + qw, c1 * c2 * c3 + (sign[3] as number) * s1 * s2 * s3);
1063
+ };
1064
+ angles.forEach((offset, i) => {
1065
+ const lane = "xyz"[i] as string;
1066
+ const crossing = Object.getOwnPropertyDescriptor(prototype, lane);
1067
+ Object.defineProperty(prototype, lane, {
1068
+ ...crossing,
1069
+ set(this: object, value: number) {
1070
+ const place = placeOf(this);
1071
+ if (place === undefined) return crossing?.set?.call(this, value);
1072
+ write(place[0] + offset, value);
1073
+ sync(place[0], place[1]);
1074
+ },
1075
+ });
1076
+ });
1077
+ const set = prototype.set as (...args: unknown[]) => unknown;
1078
+ Object.defineProperty(prototype, "set", {
1079
+ configurable: true,
1080
+ writable: true,
1081
+ value(this: object, ...args: unknown[]) {
1082
+ const place = placeOf(this);
1083
+ if (place === undefined) return set.apply(this, args);
1084
+ const [at, q] = place;
1085
+ // Games pass their one order on every set; only a new order goes to the engine.
1086
+ if (args[3] !== undefined && args[3] !== names[readByte(at + (order[0] ?? 0))])
1087
+ return set.apply(this, args);
1088
+ angles.forEach((offset, i) => write(at + offset, args[i] as number));
1089
+ sync(at, q);
1090
+ return this;
1091
+ },
1092
+ });
1093
+ }
1094
+ // A dotted path whose head is no member of its own (three's plain `morphAttributes` object) is
1095
+ // a holder made per read, as the V8 adapter makes it: each tail reads and writes the full path.
1096
+ const holders = new Map<string, string[]>();
1097
+ // A getter-only head (three's `drawRange`) is a holder too, when every path under it is one level deep.
1098
+ const flatGetters = binding.getters.filter(
1099
+ (path) =>
1100
+ path.indexOf(".") === path.lastIndexOf(".") &&
1101
+ !binding.getters
1102
+ .concat(binding.members)
1103
+ .some(
1104
+ (other) =>
1105
+ other.startsWith(`${path.slice(0, path.indexOf("."))}.`) &&
1106
+ other.split(".").length > 2,
1107
+ ),
1108
+ );
1109
+ for (const path of new Set([...binding.setters, ...flatGetters])) {
1110
+ const dot = path.indexOf(".");
1111
+ if (dot < 0) continue;
1112
+ const head = path.slice(0, dot);
1113
+ if (binding.members.includes(head) || binding.getters.includes(head)) continue;
1114
+ const tails = holders.get(head) ?? [];
1115
+ if (!tails.includes(path)) tails.push(path);
1116
+ holders.set(head, tails);
1117
+ }
1118
+ for (const [head, paths] of holders) {
1119
+ Object.defineProperty(prototype, head, {
1120
+ configurable: true,
1121
+ get(this: object) {
1122
+ const ref = refOf(this);
1123
+ const holder = {};
1124
+ for (const path of paths) {
1125
+ const readable = binding.members.includes(path) || binding.getters.includes(path);
1126
+ Object.defineProperty(holder, path.slice(head.length + 1), {
1127
+ enumerable: true,
1128
+ ...(readable ? { get: () => fromEngine(runtime.get(ref, path)) } : {}),
1129
+ ...(setters.has(path)
1130
+ ? { set: (value: unknown) => runtime.set(ref, path, toEngine(value)) }
1131
+ : {}),
1132
+ });
1133
+ }
1134
+ return holder;
1135
+ },
1136
+ });
1137
+ }
1138
+ // A write-only setter (three's `texture.needsUpdate`) is a property too: without an accessor
1139
+ // the write lands on a plain JS property and never reaches the engine.
1140
+ for (const property of binding.setters) {
1141
+ if (property.includes(".") || Object.hasOwn(accessors, property)) continue;
1142
+ Object.defineProperty(accessors, property, {
1143
+ configurable: true,
1144
+ set(this: object, value: unknown) {
1145
+ runtime.set(refOf(this), property, toEngine(value));
1146
+ },
1147
+ });
1148
+ }
1149
+ for (const callback of binding.callbacks) {
1150
+ Object.defineProperty(prototype, callback, {
1151
+ configurable: true,
1152
+ get(this: object) {
1153
+ return callbackFunctions.get(this)?.get(callback) ?? null;
1154
+ },
1155
+ set(this: object, fn: unknown) {
1156
+ const ref = refOf(this);
1157
+ const functions = callbackFunctions.get(this) ?? new Map();
1158
+ if (fn === null || fn === undefined) {
1159
+ runtime.setCallback(ref, callback, null);
1160
+ functions.delete(callback);
1161
+ callbackNames.get(ref.key)?.delete(callback);
1162
+ return;
1163
+ }
1164
+ if (typeof fn !== "function")
1165
+ throw new TypeError(`${callback} must be a function or null`);
1166
+ const self = new WeakRef(this);
1167
+ runtime.setCallback(ref, callback, (args) => {
1168
+ const target = self.deref();
1169
+ const current =
1170
+ target === undefined ? undefined : callbackFunctions.get(target)?.get(callback);
1171
+ current?.apply(target, args.map(fromEngine));
1172
+ });
1173
+ functions.set(callback, fn as (...args: unknown[]) => unknown);
1174
+ callbackFunctions.set(this, functions);
1175
+ callbackNames.set(ref.key, (callbackNames.get(ref.key) ?? new Set()).add(callback));
1176
+ hold(this);
1177
+ },
1178
+ });
1179
+ }
1180
+ // three's EventDispatcher, as the V8 adapter keeps it: listeners live in JS, and the engine
1181
+ // calls back once per native event type something listens to; `target` is set while they run.
1182
+ if (binding.methods.includes("addEventListener")) {
1183
+ const native = new Set(binding.events ?? []);
1184
+ type Listener = (this: object, event: Record<string, unknown>) => void;
1185
+ const listeners = new WeakMap<object, Map<string, Listener[]>>();
1186
+ const dispatch = (target: object, event: Record<string, unknown>): void => {
1187
+ const list = listeners.get(target)?.get(String(event.type));
1188
+ if (list === undefined) return;
1189
+ event.target = target;
1190
+ for (const listener of [...list]) listener.call(target, event);
1191
+ event.target = null;
1192
+ };
1193
+ const listenerArgs = (name: string, type: unknown, listener: unknown): Listener => {
1194
+ if (typeof type !== "string" || typeof listener !== "function")
1195
+ throw new TypeError(`${name} needs a type and a function`);
1196
+ return listener as Listener;
1197
+ };
1198
+ Object.defineProperties(prototype, {
1199
+ addEventListener: {
1200
+ configurable: true,
1201
+ writable: true,
1202
+ value(this: object, type: unknown, fn: unknown): void {
1203
+ const listener = listenerArgs("addEventListener", type, fn);
1204
+ const table = listeners.get(this) ?? new Map<string, Listener[]>();
1205
+ listeners.set(this, table);
1206
+ let list = table.get(type as string);
1207
+ if (list === undefined) {
1208
+ list = [];
1209
+ table.set(type as string, list);
1210
+ if (native.has(type as string)) {
1211
+ const ref = refOf(this);
1212
+ const self = new WeakRef(this);
1213
+ runtime.setCallback(ref, type as string, (args) => {
1214
+ const target = self.deref();
1215
+ if (target !== undefined)
1216
+ dispatch(target, fromEngine(args[0] as EngineValue) as Record<string, unknown>);
1217
+ });
1218
+ callbackNames.set(
1219
+ ref.key,
1220
+ (callbackNames.get(ref.key) ?? new Set()).add(type as string),
1221
+ );
1222
+ hold(this);
1223
+ }
1224
+ }
1225
+ if (!list.includes(listener)) list.push(listener);
1226
+ },
1227
+ },
1228
+ hasEventListener: {
1229
+ configurable: true,
1230
+ writable: true,
1231
+ value(this: object, type: unknown, fn: unknown): boolean {
1232
+ const listener = listenerArgs("hasEventListener", type, fn);
1233
+ return (
1234
+ listeners
1235
+ .get(this)
1236
+ ?.get(type as string)
1237
+ ?.includes(listener) ?? false
1238
+ );
1239
+ },
1240
+ },
1241
+ removeEventListener: {
1242
+ configurable: true,
1243
+ writable: true,
1244
+ value(this: object, type: unknown, fn: unknown): void {
1245
+ const listener = listenerArgs("removeEventListener", type, fn);
1246
+ const table = listeners.get(this);
1247
+ const list = table?.get(type as string);
1248
+ if (table === undefined || list === undefined || !list.includes(listener)) return;
1249
+ list.splice(list.indexOf(listener), 1);
1250
+ if (list.length > 0) return;
1251
+ table.delete(type as string);
1252
+ if (native.has(type as string)) {
1253
+ const ref = refOf(this);
1254
+ runtime.setCallback(ref, type as string, null);
1255
+ callbackNames.get(ref.key)?.delete(type as string);
1256
+ }
1257
+ },
1258
+ },
1259
+ dispatchEvent: {
1260
+ configurable: true,
1261
+ writable: true,
1262
+ value(this: object, event: unknown): void {
1263
+ if (typeof event !== "object" || event === null)
1264
+ throw new TypeError("dispatchEvent needs an event object");
1265
+ dispatch(this, event as Record<string, unknown>);
1266
+ },
1267
+ },
1268
+ });
1269
+ }
1270
+ if (binding.members.includes("parent") || binding.getters.includes("parent")) {
1271
+ Object.defineProperty(prototype, "userData", {
1272
+ configurable: true,
1273
+ get(this: object) {
1274
+ if (!userData.has(this)) userData.set(this, {});
1275
+ return userData.get(this);
1276
+ },
1277
+ set(this: object, value: unknown) {
1278
+ userData.set(this, value);
1279
+ },
1280
+ });
1281
+ defineTraversal(
1282
+ prototype,
1283
+ name,
1284
+ binding.members.includes("children") || binding.getters.includes("children"),
1285
+ binding.methods.includes("__walk"),
1286
+ );
1287
+ }
1288
+ classes[name] = cls;
1289
+ byType.set(runtime.typeId(name), { prototype: accessors });
1290
+ typeNames.set(runtime.typeId(name), name);
1291
+ }
1292
+ for (const name of ATTRIBUTE_CLASSES) {
1293
+ const cls = classes[name];
1294
+ if (cls !== undefined) withUpdateRanges(cls.prototype);
1295
+ }
1296
+ if (attributeArray !== undefined && attributeWrite !== undefined) {
1297
+ for (const name of ATTRIBUTE_CLASSES) {
1298
+ const cls = classes[name];
1299
+ if (cls === undefined) continue;
1300
+ Object.defineProperty(cls.prototype, "array", {
1301
+ configurable: true,
1302
+ get(this: object) {
1303
+ let entry = arrays.get(this);
1304
+ if (entry === undefined) {
1305
+ entry = { array: attributeArray.call(runtime, refOf(this)) };
1306
+ arrays.set(this, entry);
1307
+ }
1308
+ // A storage attribute's array is its initial contents: a kernel writes the GPU copy, never this array,
1309
+ // so reading it is not an edit, and writing it back would overwrite the kernel's result.
1310
+ const flags = this as {
1311
+ isStorageBufferAttribute?: boolean;
1312
+ isStorageInstancedBufferAttribute?: boolean;
1313
+ };
1314
+ if (!flags.isStorageBufferAttribute && !flags.isStorageInstancedBufferAttribute)
1315
+ pending.add(this);
1316
+ return entry.array;
1317
+ },
1318
+ });
1319
+ // needsUpdate is a property write, not a call: it hands the shadow to the engine as it stands.
1320
+ const needsUpdate = Object.getOwnPropertyDescriptor(cls.prototype, "needsUpdate");
1321
+ if (needsUpdate?.set !== undefined)
1322
+ Object.defineProperty(cls.prototype, "needsUpdate", {
1323
+ ...needsUpdate,
1324
+ set(this: object, value: unknown) {
1325
+ const entry = arrays.get(this);
1326
+ if (value === true && entry !== undefined) {
1327
+ attributeWrite.call(runtime, refOf(this), entry.array);
1328
+ pending.delete(this);
1329
+ }
1330
+ needsUpdate.set?.call(this, value);
1331
+ },
1332
+ });
1333
+ }
1334
+ }
1335
+ const entries = new Map((catalog?.entries ?? []).map((entry) => [entry.name, entry]));
1336
+ const isFlag = (field: { name: string; type: string; mutable?: boolean }) =>
1337
+ /^is[A-Z]/u.test(field.name) &&
1338
+ (field.type === "true" || (field.type === "boolean" && field.mutable === false));
1339
+ for (const [name, cls] of Object.entries(classes)) {
1340
+ const entry = entries.get(name);
1341
+ const parent = entry?.extends ? classes[entry.extends] : undefined;
1342
+ if (parent !== undefined) Object.setPrototypeOf(cls.prototype, parent.prototype);
1343
+ // Flags come from the whole chain: `Material` is unbound, yet a material is `isMaterial`.
1344
+ for (
1345
+ let link = entry;
1346
+ link !== undefined;
1347
+ link = link.extends ? entries.get(link.extends) : undefined
1348
+ )
1349
+ for (const field of (link.fields ?? []).filter(isFlag))
1350
+ Object.defineProperty(cls.prototype, field.name, { configurable: true, value: true });
1351
+ }
1352
+ return {
1353
+ classes,
1354
+ wrap,
1355
+ crossings: () => crossings,
1356
+ collect() {
1357
+ // A wrapper handed out since the last safe point is asked now: the engine either references it (it
1358
+ // settles) or does not (JS alone keeps it). A settled wrapper is asked again a sixty-fourth of the
1359
+ // settled set per safe point, round robin (a live Set iterator): Midway settles about 50,000
1360
+ // scene-attached wrappers, and asking an eighth of them every frame cost 2.5 ms of a 21 ms frame.
1361
+ // The sixty-fourth is of the pass's peak, so releases during a pass do not shrink it: a wrapper the
1362
+ // engine lets go is asked within two passes (tests/browser-backend-gc.ts). Holding a wrapper a
1363
+ // little longer only delays its release.
1364
+ peak = Math.max(peak, settled.size);
1365
+ const budget = Math.ceil(peak / SETTLED_PASS);
1366
+ const candidates: object[] = [...held];
1367
+ const fresh = candidates.length;
1368
+ while (candidates.length < fresh + budget) {
1369
+ const next = cursor.next();
1370
+ if (!next.done) {
1371
+ candidates.push(next.value);
1372
+ continue;
1373
+ }
1374
+ cursor = settled.values();
1375
+ peak = settled.size;
1376
+ // An emptied set would restart forever: a safe point that let the last wrapper go hung here.
1377
+ if (candidates.length > fresh || settled.size === 0) break;
1378
+ }
1379
+ const counts = runtime.engineReferences?.(candidates.map(refOf));
1380
+ candidates.forEach((wrapper, i) => {
1381
+ const referenced =
1382
+ counts !== undefined
1383
+ ? (counts[i] as number) > 0
1384
+ : callbackNames.has(refOf(wrapper).key) &&
1385
+ runtime.get(refOf(wrapper), "parent") !== null;
1386
+ if (i < fresh) {
1387
+ held.delete(wrapper);
1388
+ if (referenced) settled.add(wrapper);
1389
+ } else if (!referenced) settled.delete(wrapper);
1390
+ });
1391
+ },
1392
+ };
1393
+ }
1394
+
1395
+ /**
1396
+ * The engine's C ABI as built by `tn-native-engine-abi-module` (Emscripten, wasm32). The names are
1397
+ * Emscripten's (`HEAPU8`, `_malloc`, `_tn_*`), so they are declared as record keys.
1398
+ */
1399
+ type AbiCall =
1400
+ | "_malloc"
1401
+ | "_free"
1402
+ | "_tn_engine_version"
1403
+ | "_tn_context_create"
1404
+ | "_tn_type_id"
1405
+ | "_tn_object_release"
1406
+ | "_tn_object_engine_references"
1407
+ | "_tn_construct"
1408
+ | "_tn_invoke"
1409
+ | "_tn_get"
1410
+ | "_tn_set"
1411
+ | "_tn_set_callback"
1412
+ | "_tn_diagnostic_release";
1413
+ export type TnAbiModule = Record<AbiCall, (...args: number[]) => number> &
1414
+ Partial<
1415
+ Record<"_tnw_attribute_view" | "_tnw_attribute_view_release", (...args: number[]) => number>
1416
+ > &
1417
+ Record<"HEAPU8", Uint8Array> &
1418
+ Record<"HEAPF64", Float64Array> &
1419
+ Record<"UTF8ToString", (pointer: number, maxBytes?: number) => string> &
1420
+ Record<
1421
+ "addFunction",
1422
+ (fn: (...args: number[]) => number | undefined, signature: string) => number
1423
+ > & {
1424
+ stringToUTF8(text: string, pointer: number, maxBytes: number): void;
1425
+ lengthBytesUTF8(text: string): number;
1426
+ };
1427
+
1428
+ // wasm32 layouts of tn_abi.h, measured with offsetof under emcc: tn_handle_t 12 bytes; tn_value_t
1429
+ // 56 bytes (kind 0, boolean 4, number 8, handle 16, text 32, count 40, numbers 48); tn_diagnostic_t
1430
+ // 8 bytes (message 0, code 4); tn_version_info_t 32 bytes. A struct passed by value goes by pointer.
1431
+ const HANDLE = 12;
1432
+ const VALUE = 56;
1433
+ const KIND = {
1434
+ null: 0,
1435
+ number: 1,
1436
+ bool: 2,
1437
+ string: 3,
1438
+ handle: 4,
1439
+ numbers: 5,
1440
+ array: 6,
1441
+ record: 7,
1442
+ undefined: 8,
1443
+ } as const;
1444
+
1445
+ // wasm32 layout of tn_tsl_arg_t (tn_tsl.h): kind 0, lanes 4, node 8 (u64), number 16, text 24,
1446
+ // numbers 32 (four f64); 64 bytes. A handle argument's 12 bytes start at lanes (4) and run through node.
1447
+ const TSL_ARG = 64;
1448
+ const TSL_KIND = {
1449
+ node: 0,
1450
+ number: 1,
1451
+ string: 2,
1452
+ named: 3,
1453
+ rgb: 4,
1454
+ vector: 5,
1455
+ other: 6,
1456
+ handle: 7,
1457
+ } as const;
1458
+ type TslCall =
1459
+ | "_tn_tsl_call"
1460
+ | "_tn_tsl_release"
1461
+ | "_tn_tsl_set"
1462
+ | "_tn_tsl_set_uniform"
1463
+ | "_tn_tsl_effect_parameter"
1464
+ | "_tnw_web_set_post"
1465
+ | "_tnw_web_compute"
1466
+ | "_tnw_web_compute_flush"
1467
+ | "_tnw_web_read_storage"
1468
+ | "_tnw_web_read_storage_size"
1469
+ | "_tnw_web_read_storage_take"
1470
+ | "_tnw_web_delete_storage"
1471
+ | "_tnw_web_poll"
1472
+ | "_tnw_web_error";
1473
+
1474
+ interface IAbiHelpers {
1475
+ scoped<T>(work: () => T): T;
1476
+ alloc(size: number): number;
1477
+ string(text: string): { pointer: number; bytes: number };
1478
+ diagnostic(): number;
1479
+ check(status: number, diag: number, what: string): void;
1480
+ handleOf(ref: IEngineRef): number;
1481
+ writeHandle(pointer: number, ref: IEngineRef): void;
1482
+ view(): DataView;
1483
+ }
1484
+
1485
+ /** The engine glTF loader over the product web host's `tnw_web_load_gltf`, when the module has it. */
1486
+ function gltfOf(
1487
+ abi: TnAbiModule,
1488
+ context: number,
1489
+ h: Pick<IAbiHelpers, "scoped" | "alloc"> & { keyOf(pointer: number): IEngineRef },
1490
+ ): Pick<IBrowserRuntime, "loadGltf"> {
1491
+ // quality-allow: the Emscripten module is read through the exports this call site names, not its full surface.
1492
+ const host = abi as unknown as Partial<
1493
+ Record<
1494
+ | "_tnw_web_load_gltf"
1495
+ | "_tnw_web_load_error"
1496
+ | "_tnw_web_gltf_file"
1497
+ | "_tnw_web_gltf_files_clear",
1498
+ (...args: number[]) => number
1499
+ >
1500
+ >;
1501
+ const {
1502
+ _tnw_web_load_gltf: load,
1503
+ _tnw_web_load_error: error,
1504
+ _tnw_web_gltf_file: file,
1505
+ _tnw_web_gltf_files_clear: clearFiles,
1506
+ } = host;
1507
+ if (load === undefined || error === undefined) return {};
1508
+ return {
1509
+ loadGltf: (bytes, files) =>
1510
+ h.scoped(() => {
1511
+ // Files the model names by relative uri (shared images), read by the engine loader.
1512
+ if (files !== undefined && files.size > 0) {
1513
+ if (file === undefined || clearFiles === undefined)
1514
+ throw new Error(
1515
+ "TN_WASM_GLTF_FILES_UNAVAILABLE: this web engine cannot read a model's image files",
1516
+ );
1517
+ for (const [uri, content] of files) {
1518
+ const name = h.alloc(abi.lengthBytesUTF8(uri) + 1);
1519
+ abi.stringToUTF8(uri, name, abi.lengthBytesUTF8(uri) + 1);
1520
+ const copy = h.alloc(Math.max(1, content.byteLength));
1521
+ abi.HEAPU8.set(content, copy);
1522
+ file(name, copy, content.byteLength);
1523
+ }
1524
+ }
1525
+ try {
1526
+ const data = h.alloc(Math.max(1, bytes.byteLength));
1527
+ abi.HEAPU8.set(bytes, data);
1528
+ const count = h.alloc(4);
1529
+ // Retried once with the exact size when the model has more clips than the first guess.
1530
+ for (let capacity = 64; ; ) {
1531
+ const out = h.alloc(HANDLE * capacity);
1532
+ const status = load(context, data, bytes.byteLength, out, capacity, count);
1533
+ const needed = new DataView(abi.HEAPU8.buffer).getUint32(count, true);
1534
+ if (status === 0) {
1535
+ const refs = Array.from({ length: needed }, (_, i) => h.keyOf(out + i * HANDLE));
1536
+ return { scene: refs[0] as IEngineRef, animations: refs.slice(1) };
1537
+ }
1538
+ const reason = abi.UTF8ToString(error());
1539
+ if (reason !== "TN_WASM_GLTF_CAPACITY" || needed <= capacity) throw new Error(reason);
1540
+ capacity = needed;
1541
+ }
1542
+ } finally {
1543
+ clearFiles?.();
1544
+ }
1545
+ }),
1546
+ };
1547
+ }
1548
+
1549
+ /** TSL by name over `tn_tsl_call`, when the module exports it (the product web host does). */
1550
+ function tslOf(
1551
+ abi: TnAbiModule,
1552
+ context: number,
1553
+ h: IAbiHelpers,
1554
+ ): { tsl: ITslRuntime } | undefined {
1555
+ // Node ids are u64 in the C ABI; Emscripten passes a 64-bit parameter as a BigInt.
1556
+ // quality-allow: the Emscripten module is read through the TSL call exports this call site names, not its full surface.
1557
+ const calls = abi as unknown as Partial<
1558
+ Record<TslCall, (...args: (number | bigint)[]) => number>
1559
+ >;
1560
+ const {
1561
+ _tn_tsl_call: call,
1562
+ _tn_tsl_release: release,
1563
+ _tn_tsl_set: set,
1564
+ _tn_tsl_set_uniform: setUniform,
1565
+ _tn_tsl_effect_parameter: effectParameter,
1566
+ _tnw_web_set_post: setPost,
1567
+ _tnw_web_compute: computeNode,
1568
+ _tnw_web_compute_flush: computeFlush,
1569
+ _tnw_web_read_storage: readStorage,
1570
+ _tnw_web_read_storage_size: readStorageSize,
1571
+ _tnw_web_read_storage_take: readStorageTake,
1572
+ _tnw_web_delete_storage: deleteStorage,
1573
+ _tnw_web_poll: poll,
1574
+ _tnw_web_error: webError,
1575
+ } = calls;
1576
+ if (
1577
+ call === undefined ||
1578
+ release === undefined ||
1579
+ set === undefined ||
1580
+ setUniform === undefined ||
1581
+ effectParameter === undefined
1582
+ )
1583
+ return undefined;
1584
+ // Writes tn_tsl_arg_t values; text is allocated first, since an allocation can grow the memory.
1585
+ const writeArgs = (args: readonly TslArgValue[]): number => {
1586
+ const pointer = h.alloc(Math.max(TSL_ARG, args.length * TSL_ARG));
1587
+ args.forEach((arg, i) => {
1588
+ const at = pointer + i * TSL_ARG;
1589
+ const text = arg.kind === "string" || arg.kind === "named" ? h.string(arg.text).pointer : 0;
1590
+ const v = h.view();
1591
+ v.setUint32(at, TSL_KIND[arg.kind], true);
1592
+ if (arg.kind === "node") v.setBigUint64(at + 8, BigInt(arg.node), true);
1593
+ else if (arg.kind === "number") v.setFloat64(at + 16, arg.number, true);
1594
+ else if (arg.kind === "rgb" || arg.kind === "vector") {
1595
+ v.setUint32(at + 4, arg.numbers.length, true);
1596
+ arg.numbers.forEach((c, j) => v.setFloat64(at + 32 + j * 8, c, true));
1597
+ } else if (arg.kind === "handle") h.writeHandle(at + 4, arg.ref);
1598
+ else v.setUint32(at + 24, text, true);
1599
+ });
1600
+ return pointer;
1601
+ };
1602
+ const nodeOf = (node: number | null): number => {
1603
+ if (node === null) return 0;
1604
+ const pointer = h.alloc(8);
1605
+ h.view().setBigUint64(pointer, BigInt(node), true);
1606
+ return pointer;
1607
+ };
1608
+ return {
1609
+ tsl: {
1610
+ call: (name, receiver, args) =>
1611
+ h.scoped(() => {
1612
+ const pointer = writeArgs(args);
1613
+ const self = nodeOf(receiver);
1614
+ const out = h.alloc(8);
1615
+ const diag = h.diagnostic();
1616
+ h.check(
1617
+ call(context, h.string(name).pointer, self, pointer, args.length, out, diag),
1618
+ diag,
1619
+ `TSL ${name}`,
1620
+ );
1621
+ return Number(h.view().getBigUint64(out, true));
1622
+ }),
1623
+ release: (node) =>
1624
+ h.scoped(() => {
1625
+ const diag = h.diagnostic();
1626
+ release(context, BigInt(node), diag);
1627
+ abi._tn_diagnostic_release(diag);
1628
+ }),
1629
+ set: (material, path, node) =>
1630
+ h.scoped(() => {
1631
+ const diag = h.diagnostic();
1632
+ h.check(
1633
+ set(context, h.handleOf(material), h.string(path).pointer, BigInt(node), diag),
1634
+ diag,
1635
+ `set ${path}`,
1636
+ );
1637
+ }),
1638
+ effectParameter: (node, name, value) =>
1639
+ h.scoped(() => {
1640
+ const self = nodeOf(node);
1641
+ const input = value === undefined ? 0 : h.alloc(8);
1642
+ if (value !== undefined) h.view().setFloat64(input, value, true);
1643
+ const out = h.alloc(8);
1644
+ const diag = h.diagnostic();
1645
+ h.check(
1646
+ effectParameter(context, self, h.string(name).pointer, input, out, diag),
1647
+ diag,
1648
+ `effect ${name}`,
1649
+ );
1650
+ return h.view().getFloat64(out, true);
1651
+ }),
1652
+ // three's RenderPipeline on the product web host: the graph between scene and output.
1653
+ setPost: (node) =>
1654
+ h.scoped(() => {
1655
+ if (setPost === undefined) throw new Error("TN_WASM_POST: this module has no web host");
1656
+ if (setPost(context, nodeOf(node)) !== 0) throw new Error("TN_WASM_POST: refused");
1657
+ }),
1658
+ // PRD-620: renderer.compute and storage reads over the product web host.
1659
+ compute: (node) =>
1660
+ h.scoped(() => {
1661
+ if (computeNode === undefined || webError === undefined)
1662
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
1663
+ if (computeNode(context, nodeOf(node)) !== 0)
1664
+ throw new Error(abi.UTF8ToString(webError()));
1665
+ }),
1666
+ readStorage: async (attribute) => {
1667
+ if (
1668
+ readStorage === undefined ||
1669
+ readStorageSize === undefined ||
1670
+ readStorageTake === undefined ||
1671
+ computeFlush === undefined ||
1672
+ poll === undefined ||
1673
+ webError === undefined
1674
+ )
1675
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
1676
+ const id = h.scoped(() => {
1677
+ const pointer = h.alloc(HANDLE);
1678
+ h.writeHandle(pointer, attribute);
1679
+ return readStorage(pointer);
1680
+ });
1681
+ if (id === 0) throw new Error(abi.UTF8ToString(webError()));
1682
+ computeFlush();
1683
+ for (;;) {
1684
+ poll();
1685
+ const size = readStorageSize(id);
1686
+ if (size > 0 || readStorageTake(id, 0, 0) < 0) {
1687
+ const out = abi._malloc(size) >>> 0;
1688
+ try {
1689
+ if (readStorageTake(id, out, size) === 1)
1690
+ return abi.HEAPU8.slice(out, out + size).buffer;
1691
+ } finally {
1692
+ abi._free(out);
1693
+ }
1694
+ throw new Error("TN_NATIVE_READ_STORAGE: the read failed");
1695
+ }
1696
+ await new Promise((resolve) => setTimeout(resolve, 0));
1697
+ }
1698
+ },
1699
+ deleteStorage: (attribute) =>
1700
+ h.scoped(() => {
1701
+ if (deleteStorage === undefined || webError === undefined)
1702
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
1703
+ const pointer = h.alloc(HANDLE);
1704
+ h.writeHandle(pointer, attribute);
1705
+ if (deleteStorage(pointer) !== 0) throw new Error(abi.UTF8ToString(webError()));
1706
+ }),
1707
+ setUniform: (node, lanes) =>
1708
+ h.scoped(() => {
1709
+ const pointer = h.alloc(8);
1710
+ const values = h.alloc(Math.max(8, lanes.length * 8));
1711
+ const v = h.view();
1712
+ v.setBigUint64(pointer, BigInt(node), true);
1713
+ lanes.forEach((lane, i) => v.setFloat64(values + i * 8, lane, true));
1714
+ const diag = h.diagnostic();
1715
+ h.check(setUniform(context, pointer, values, lanes.length, diag), diag, "uniform.value");
1716
+ }),
1717
+ },
1718
+ };
1719
+ }
1720
+
1721
+ /** The runtime over a loaded ABI module: one engine context, every call checked. */
1722
+ /**
1723
+ * Opt-in boundary census for `pnpm profile:wasm-page --calls`: while the page sets
1724
+ * `globalThis.__tnCallCounts` to a Map, every engine get, set and invoke counts under
1725
+ * "<kind> <type id>.<name>" (`__tnEngineTypes` names the type ids). Off, it costs one global read.
1726
+ */
1727
+ function countCall(kind: string, self: IEngineRef, name: string): void {
1728
+ const counts = (globalThis as { __tnCallCounts?: Map<string, number> }).__tnCallCounts;
1729
+ if (counts === undefined) return;
1730
+ const key = `${kind} ${self.type}.${name}`;
1731
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1732
+ }
1733
+
1734
+ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
1735
+ let dataView = new DataView(abi.HEAPU8.buffer);
1736
+ const view = () => {
1737
+ if (dataView.buffer !== abi.HEAPU8.buffer) dataView = new DataView(abi.HEAPU8.buffer);
1738
+ return dataView;
1739
+ };
1740
+ // Each call frees what it allocated, and only that: a callback can run a nested call.
1741
+ // A call's scratch (its handle, arguments, result and diagnostic) comes from one arena that each
1742
+ // scope rewinds, a stack as nested calls (a callback inside an invoke) need; a scope that outgrows
1743
+ // it falls back to malloc and frees on exit. Every engine call crosses here, many per frame.
1744
+ const arenaSize = 64 * 1024;
1745
+ const arenaBase = abi._malloc(arenaSize) >>> 0;
1746
+ let arenaTop = arenaBase;
1747
+ const allocations: number[] = [];
1748
+ const alloc = (size: number): number => {
1749
+ const aligned = (size + 7) & ~7;
1750
+ let pointer: number;
1751
+ if (arenaTop + aligned <= arenaBase + arenaSize) {
1752
+ pointer = arenaTop;
1753
+ arenaTop += aligned;
1754
+ } else {
1755
+ // `>>> 0`: the module addresses up to 4 GB, and an export returns a pointer as a signed i32.
1756
+ pointer = abi._malloc(size) >>> 0;
1757
+ allocations.push(pointer);
1758
+ }
1759
+ abi.HEAPU8.fill(0, pointer, pointer + size);
1760
+ return pointer;
1761
+ };
1762
+ const scoped = <T>(work: () => T): T => {
1763
+ const mark = allocations.length;
1764
+ const top = arenaTop;
1765
+ try {
1766
+ return work();
1767
+ } finally {
1768
+ for (const pointer of allocations.splice(mark)) abi._free(pointer);
1769
+ arenaTop = top;
1770
+ }
1771
+ };
1772
+ const string = (text: string): { pointer: number; bytes: number } => {
1773
+ const bytes = abi.lengthBytesUTF8(text);
1774
+ const pointer = alloc(bytes + 1);
1775
+ abi.stringToUTF8(text, pointer, bytes + 1);
1776
+ return { pointer, bytes };
1777
+ };
1778
+ // Member, method and class names: a bounded set, encoded once and kept for the module's life.
1779
+ const names = new Map<string, number>();
1780
+ const name = (text: string): number => {
1781
+ let pointer = names.get(text);
1782
+ if (pointer === undefined) {
1783
+ const bytes = abi.lengthBytesUTF8(text);
1784
+ pointer = abi._malloc(bytes + 1) >>> 0;
1785
+ abi.stringToUTF8(text, pointer, bytes + 1);
1786
+ names.set(text, pointer);
1787
+ }
1788
+ return pointer;
1789
+ };
1790
+ const diagnostic = () => alloc(8);
1791
+ const check = (status: number, diag: number, what: string) => {
1792
+ if (status === 0) return;
1793
+ const message = view().getUint32(diag, true);
1794
+ const text = message === 0 ? "" : abi.UTF8ToString(message);
1795
+ abi._tn_diagnostic_release(diag);
1796
+ throw new Error(`TN_ABI_${status}: ${what}${text ? `: ${text}` : ""}`);
1797
+ };
1798
+ // A handle is three words in memory: type and context as two halves of the first, then index and
1799
+ // generation. A ref made here keeps those words, so writing one back is three stores, no parse.
1800
+ let words = new Uint32Array(abi.HEAPU8.buffer);
1801
+ const wordView = () => {
1802
+ if (words.buffer !== abi.HEAPU8.buffer) words = new Uint32Array(abi.HEAPU8.buffer);
1803
+ return words;
1804
+ };
1805
+ const keyOf = (pointer: number): IEngineRef => {
1806
+ const v = view();
1807
+ const type = v.getUint16(pointer, true);
1808
+ const context = v.getUint16(pointer + 2, true);
1809
+ const index = v.getUint32(pointer + 4, true);
1810
+ const generation = v.getUint32(pointer + 8, true);
1811
+ const ref: IPackedRef = {
1812
+ key: `${type}:${context}:${index}:${generation}`,
1813
+ type,
1814
+ w0: (type | (context << 16)) >>> 0,
1815
+ w1: index,
1816
+ w2: generation,
1817
+ };
1818
+ return ref;
1819
+ };
1820
+ const writeHandle = (pointer: number, ref: IEngineRef) => {
1821
+ let packed = ref as Partial<IPackedRef>;
1822
+ if (packed.w0 === undefined) {
1823
+ // A ref some other source made: parse its key once and keep the words on it.
1824
+ const [type = 0, context = 0, index = 0, generation = 0] = ref.key.split(":").map(Number);
1825
+ packed = Object.isExtensible(ref) ? (ref as IPackedRef) : { ...ref };
1826
+ Object.assign(packed, { w0: (type | (context << 16)) >>> 0, w1: index, w2: generation });
1827
+ }
1828
+ if ((pointer & 3) === 0) {
1829
+ const at = pointer >>> 2;
1830
+ const w = wordView();
1831
+ w[at] = packed.w0 as number;
1832
+ w[at + 1] = packed.w1 as number;
1833
+ w[at + 2] = packed.w2 as number;
1834
+ return;
1835
+ }
1836
+ const v = view();
1837
+ v.setUint32(pointer, packed.w0 as number, true);
1838
+ v.setUint32(pointer + 4, packed.w1 as number, true);
1839
+ v.setUint32(pointer + 8, packed.w2 as number, true);
1840
+ };
1841
+ const handleOf = (ref: IEngineRef): number => {
1842
+ const pointer = alloc(HANDLE);
1843
+ writeHandle(pointer, ref);
1844
+ return pointer;
1845
+ };
1846
+ const writeValue = (pointer: number, value: EngineValue) => {
1847
+ const v = view();
1848
+ if (value === null) return v.setUint32(pointer, KIND.null, true);
1849
+ if (value === undefined) return v.setUint32(pointer, KIND.undefined, true);
1850
+ if (typeof value === "number") {
1851
+ v.setUint32(pointer, KIND.number, true);
1852
+ return v.setFloat64(pointer + 8, value, true);
1853
+ }
1854
+ if (typeof value === "boolean") {
1855
+ v.setUint32(pointer, KIND.bool, true);
1856
+ return v.setUint32(pointer + 4, value ? 1 : 0, true);
1857
+ }
1858
+ if (typeof value === "string") {
1859
+ const text = string(value);
1860
+ const w = view();
1861
+ w.setUint32(pointer, KIND.string, true);
1862
+ w.setUint32(pointer + 32, text.pointer, true);
1863
+ return w.setBigUint64(pointer + 40, BigInt(text.bytes), true);
1864
+ }
1865
+ if (isRef(value)) {
1866
+ v.setUint32(pointer, KIND.handle, true);
1867
+ return writeHandle(pointer + 16, value);
1868
+ }
1869
+ if (!Array.isArray(value)) {
1870
+ // A record: count key/value pairs, each key a string value, as the engine returns one.
1871
+ const entries = Object.entries(value as Record<string, EngineValue>);
1872
+ const children = values(entries.flat());
1873
+ const w = view();
1874
+ w.setUint32(pointer, KIND.record, true);
1875
+ w.setUint32(pointer + 48, children, true);
1876
+ return w.setBigUint64(pointer + 40, BigInt(entries.length), true);
1877
+ }
1878
+ if (value.every((item) => typeof item === "number")) {
1879
+ const numbers = alloc(Math.max(8, value.length * 8));
1880
+ abi.HEAPF64.set(value as number[], numbers / 8);
1881
+ const typed = (value as { [TYPED]?: string })[TYPED];
1882
+ const name = typed === undefined ? 0 : string(typed).pointer;
1883
+ const w = view();
1884
+ w.setUint32(pointer, KIND.numbers, true);
1885
+ w.setUint32(pointer + 32, name, true);
1886
+ w.setUint32(pointer + 48, numbers, true);
1887
+ w.setBigUint64(pointer + 40, BigInt(value.length), true);
1888
+ } else {
1889
+ const children = values(value);
1890
+ const w = view();
1891
+ w.setUint32(pointer, KIND.array, true);
1892
+ w.setUint32(pointer + 48, children, true);
1893
+ w.setBigUint64(pointer + 40, BigInt(value.length), true);
1894
+ }
1895
+ };
1896
+ const values = (args: readonly EngineValue[]): number => {
1897
+ const pointer = alloc(Math.max(VALUE, args.length * VALUE));
1898
+ args.forEach((arg, i) => writeValue(pointer + i * VALUE, arg));
1899
+ return pointer;
1900
+ };
1901
+ const readValue = (pointer: number): EngineValue => {
1902
+ const v = view();
1903
+ switch (v.getUint32(pointer, true)) {
1904
+ case KIND.undefined:
1905
+ return undefined;
1906
+ case KIND.number:
1907
+ return v.getFloat64(pointer + 8, true);
1908
+ case KIND.bool:
1909
+ return v.getUint32(pointer + 4, true) !== 0;
1910
+ case KIND.string:
1911
+ return abi.UTF8ToString(
1912
+ v.getUint32(pointer + 32, true),
1913
+ Number(v.getBigUint64(pointer + 40, true)),
1914
+ );
1915
+ case KIND.handle:
1916
+ return keyOf(pointer + 16);
1917
+ case KIND.array: {
1918
+ const at = v.getUint32(pointer + 48, true);
1919
+ return Array.from({ length: Number(v.getBigUint64(pointer + 40, true)) }, (_, i) =>
1920
+ readValue(at + i * VALUE),
1921
+ );
1922
+ }
1923
+ case KIND.record: {
1924
+ const at = v.getUint32(pointer + 48, true);
1925
+ return Object.fromEntries(
1926
+ Array.from({ length: Number(v.getBigUint64(pointer + 40, true)) }, (_, i) => {
1927
+ const key = readValue(at + i * 2 * VALUE);
1928
+ if (typeof key !== "string") throw new TypeError("TN_ABI_RECORD_KEY: expected string");
1929
+ return [key, readValue(at + (i * 2 + 1) * VALUE)];
1930
+ }),
1931
+ );
1932
+ }
1933
+ case KIND.numbers: {
1934
+ const at = v.getUint32(pointer + 48, true) / 8;
1935
+ return Array.from(
1936
+ abi.HEAPF64.subarray(at, at + Number(v.getBigUint64(pointer + 40, true))),
1937
+ );
1938
+ }
1939
+ default:
1940
+ return null;
1941
+ }
1942
+ };
1943
+
1944
+ // Callbacks: one invoke and one release trampoline in the function table; the context is a
1945
+ // handler id, and the engine's release (once per pair) forgets it.
1946
+ const handlers = new Map<number, (args: readonly EngineValue[]) => void>();
1947
+ let nextHandler = 1;
1948
+ let invokeTrampoline = 0;
1949
+ let releaseTrampoline = 0;
1950
+ const trampolines = () => {
1951
+ if (invokeTrampoline !== 0) return;
1952
+ invokeTrampoline = abi.addFunction((id, rawArgs, count, rawError, capacity) => {
1953
+ // Pointers arrive as signed i32; the module addresses up to 4 GB.
1954
+ const args = (rawArgs ?? 0) >>> 0;
1955
+ const error = (rawError ?? 0) >>> 0;
1956
+ const handler = handlers.get(id ?? 0);
1957
+ if (handler === undefined) return 0;
1958
+ const decoded: EngineValue[] = [];
1959
+ for (let i = 0; i < (count ?? 0); i++) decoded.push(readValue(args + i * VALUE));
1960
+ try {
1961
+ handler(decoded);
1962
+ return 0;
1963
+ } catch (thrown) {
1964
+ abi.stringToUTF8(
1965
+ thrown instanceof Error ? thrown.message : String(thrown),
1966
+ error,
1967
+ capacity ?? 0,
1968
+ );
1969
+ return 8; // TN_ERROR_INVALID_STATE: the engine records it and goes on
1970
+ }
1971
+ }, "iiiiii");
1972
+ releaseTrampoline = abi.addFunction((id) => {
1973
+ handlers.delete(id ?? 0);
1974
+ return undefined;
1975
+ }, "vi");
1976
+ };
1977
+
1978
+ // A view over the attribute's storage, used only inside one call: the lease pins the storage and
1979
+ // nothing in between can grow the memory and detach the view. A kept view would detach on growth,
1980
+ // so the back end keeps JS arrays and copies through this (see defineBrowserClasses).
1981
+ const withAttributeView = <T>(self: IEngineRef, use: (view: TypedArray) => T): T =>
1982
+ scoped(() => {
1983
+ const call = abi._tnw_attribute_view;
1984
+ if (call === undefined)
1985
+ throw new TypeError("TN_WASM_MODULE: this module exports no attribute views");
1986
+ const out = alloc(24);
1987
+ const lease = call(handleOf(self), out);
1988
+ if (lease === 0) throw new TypeError("TN_NATIVE_UNSUPPORTED array: not an attribute");
1989
+ try {
1990
+ const v = view();
1991
+ const [address, count, scalar] = [0, 8, 16].map((at) =>
1992
+ Number(v.getBigUint64(out + at, true)),
1993
+ );
1994
+ const Typed = SCALARS[scalar ?? -1];
1995
+ if (Typed === undefined)
1996
+ throw new TypeError(`TN_NATIVE_UNSUPPORTED array: scalar ${String(scalar)}`);
1997
+ return use(new Typed(abi.HEAPU8.buffer as ArrayBuffer, address ?? 0, count ?? 0));
1998
+ } finally {
1999
+ abi._tnw_attribute_view_release?.(lease);
2000
+ }
2001
+ });
2002
+
2003
+ const context = scoped(() => {
2004
+ const version = alloc(32);
2005
+ abi._tn_engine_version(version);
2006
+ const contextOut = alloc(4);
2007
+ const diag = diagnostic();
2008
+ check(abi._tn_context_create(contextOut, version, diag), diag, "tn_context_create");
2009
+ return view().getUint32(contextOut, true);
2010
+ });
2011
+
2012
+ return {
2013
+ ...(tslOf(abi, context, {
2014
+ scoped,
2015
+ alloc,
2016
+ string,
2017
+ diagnostic,
2018
+ check,
2019
+ handleOf,
2020
+ writeHandle,
2021
+ view,
2022
+ }) ?? {}),
2023
+ ...gltfOf(abi, context, { scoped, alloc, keyOf }),
2024
+ typeId: (className) => abi._tn_type_id(name(className)),
2025
+ construct: (className, args) =>
2026
+ scoped(() => {
2027
+ const out = alloc(HANDLE);
2028
+ const diag = diagnostic();
2029
+ check(
2030
+ abi._tn_construct(
2031
+ context,
2032
+ string(className).pointer,
2033
+ values(args),
2034
+ args.length,
2035
+ out,
2036
+ diag,
2037
+ ),
2038
+ diag,
2039
+ `new ${className}`,
2040
+ );
2041
+ return keyOf(out);
2042
+ }),
2043
+ invoke: (self, method, args) =>
2044
+ scoped(() => {
2045
+ countCall("call", self, method);
2046
+ const out = alloc(VALUE);
2047
+ const diag = diagnostic();
2048
+ check(
2049
+ abi._tn_invoke(handleOf(self), name(method), values(args), args.length, out, diag),
2050
+ diag,
2051
+ `${method}()`,
2052
+ );
2053
+ return readValue(out);
2054
+ }),
2055
+ engineReferences: (refs) =>
2056
+ scoped(() => {
2057
+ const handles = alloc(Math.max(1, refs.length) * HANDLE);
2058
+ refs.forEach((ref, i) => writeHandle(handles + i * HANDLE, ref));
2059
+ const out = alloc(Math.max(1, refs.length) * 4);
2060
+ abi._tn_object_engine_references(handles, refs.length, out);
2061
+ const v = view();
2062
+ return refs.map((_, i) => v.getUint32(out + i * 4, true));
2063
+ }),
2064
+ readByte: (address) => abi.HEAPU8[address] as number,
2065
+ writeDouble: (address, value) => {
2066
+ abi.HEAPF64[address / 8] = value;
2067
+ },
2068
+ heapF64: () => abi.HEAPF64,
2069
+ readDoubles: (address, count) => {
2070
+ const at = address / 8;
2071
+ return count === 1
2072
+ ? (abi.HEAPF64[at] as number)
2073
+ : Array.from(abi.HEAPF64.subarray(at, at + count));
2074
+ },
2075
+ get: (self, path) =>
2076
+ scoped(() => {
2077
+ countCall("get", self, path);
2078
+ const out = alloc(VALUE);
2079
+ const diag = diagnostic();
2080
+ check(abi._tn_get(handleOf(self), name(path), out, diag), diag, `get ${path}`);
2081
+ return readValue(out);
2082
+ }),
2083
+ set: (self, path, value) =>
2084
+ scoped(() => {
2085
+ countCall("set", self, path);
2086
+ const pointer = values([value]);
2087
+ const diag = diagnostic();
2088
+ check(abi._tn_set(handleOf(self), name(path), pointer, diag), diag, `set ${path}`);
2089
+ }),
2090
+ release: (self) =>
2091
+ scoped(() => {
2092
+ const diag = diagnostic();
2093
+ abi._tn_object_release(handleOf(self), diag);
2094
+ abi._tn_diagnostic_release(diag);
2095
+ }),
2096
+ attributeArray: (self, offset, count) =>
2097
+ withAttributeView(self, (target) => {
2098
+ const from = offset === undefined ? 0 : offset;
2099
+ const length = count === undefined ? target.length - from : count;
2100
+ if (
2101
+ !Number.isSafeInteger(from) ||
2102
+ !Number.isSafeInteger(length) ||
2103
+ from < 0 ||
2104
+ length < 0 ||
2105
+ from + length > target.length
2106
+ )
2107
+ throw new RangeError(
2108
+ `TN_NATIVE_ATTRIBUTE_RANGE: [${String(from)}, ${String(length)}) is outside ${String(target.length)} elements`,
2109
+ );
2110
+ return target.subarray(from, from + length).slice();
2111
+ }),
2112
+ attributeWrite: (self, array, offset) =>
2113
+ withAttributeView(self, (target) => {
2114
+ // An omitted offset writes the whole attribute, so the array must be its exact data; an
2115
+ // explicit offset (including 0) writes that subrange.
2116
+ if (offset === undefined) {
2117
+ if (target.length !== array.length)
2118
+ throw new RangeError(
2119
+ `TN_NATIVE_ATTRIBUTE_LENGTH: attribute.array has ${String(array.length)} elements, the attribute ${String(target.length)}`,
2120
+ );
2121
+ target.set(array);
2122
+ return;
2123
+ }
2124
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset + array.length > target.length)
2125
+ throw new RangeError(
2126
+ `TN_NATIVE_ATTRIBUTE_LENGTH: attribute.array has ${String(array.length)} elements at ${String(offset)}, the attribute ${String(target.length)}`,
2127
+ );
2128
+ target.set(array, offset);
2129
+ }),
2130
+ setCallback: (self, name, handler) =>
2131
+ scoped(() => {
2132
+ const diag = diagnostic();
2133
+ if (handler === null) {
2134
+ check(
2135
+ abi._tn_set_callback(handleOf(self), string(name).pointer, 0, 0, 0, diag),
2136
+ diag,
2137
+ `clear ${name}`,
2138
+ );
2139
+ return;
2140
+ }
2141
+ trampolines();
2142
+ const id = nextHandler++;
2143
+ handlers.set(id, handler);
2144
+ const status = abi._tn_set_callback(
2145
+ handleOf(self),
2146
+ string(name).pointer,
2147
+ invokeTrampoline,
2148
+ id,
2149
+ releaseTrampoline,
2150
+ diag,
2151
+ );
2152
+ if (status !== 0) handlers.delete(id); // a refused pair was never taken
2153
+ check(status, diag, `set ${name}`);
2154
+ }),
2155
+ };
2156
+ }