@threenative/three-native 0.3.11 → 0.3.13

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.
@@ -0,0 +1,621 @@
1
+ import type { TypedArray } from "./browser-marshal.js";
2
+ /**
3
+ * The engine's C ABI as the browser back end sees it (PRD-532, PRD-803): the runtime interface the
4
+ * classes call, the handle's packed words, the value layouts of `tn_abi.h`, and the two host
5
+ * integrations a module may carry (the glTF loader and TSL by name).
6
+ */
7
+ import type { ITslRuntime, TslArgValue } from "./browser-tsl.js";
8
+ import type { DebugTelemetry } from "./debug-telemetry.js";
9
+
10
+ /** A ref with its handle words kept (see `createWasmRuntime`): type | context << 16, index, generation. */
11
+ export interface IPackedRef extends IEngineRef {
12
+ w0: number;
13
+ w1: number;
14
+ w2: number;
15
+ }
16
+
17
+ /**
18
+ * The ref's handle words. A ref the runtime made carries them; any other ref is parsed once and keeps them, so
19
+ * writing a handle is three stores and never a key parse per call.
20
+ */
21
+ export function packedRef(ref: IEngineRef): IPackedRef {
22
+ const known = ref as Partial<IPackedRef>;
23
+ if (known.w0 !== undefined) return known as IPackedRef;
24
+ const [type = 0, context = 0, index = 0, generation = 0] = ref.key.split(":").map(Number);
25
+ const words = { w0: (type | (context << 16)) >>> 0, w1: index, w2: generation };
26
+ return Object.isExtensible(ref) ? Object.assign(ref, words) : { ...ref, ...words };
27
+ }
28
+
29
+ /** An engine object as the back end sees it: an opaque key and its catalog type id. */
30
+ export interface IEngineRef {
31
+ readonly key: string;
32
+ readonly type: number;
33
+ }
34
+
35
+ export function isRef(value: unknown): value is IEngineRef {
36
+ return typeof value === "object" && value !== null && "key" in value && "type" in value;
37
+ }
38
+
39
+ export type EngineValue =
40
+ | null
41
+ | undefined
42
+ | number
43
+ | boolean
44
+ | string
45
+ | TypedArray
46
+ | readonly EngineValue[]
47
+ | IEngineRef
48
+ | { readonly [key: string]: EngineValue };
49
+
50
+ /** PRD-828: one rig of an animation tick batch, as the backend takes it. */
51
+ export interface IAnimationTickBatch {
52
+ /** One entry per rig: the mixer, the rig's action (null when nothing plays), the body it strides from. */
53
+ readonly mixers: readonly IEngineRef[];
54
+ readonly actions: readonly (IEngineRef | null)[];
55
+ readonly roots: readonly (IEngineRef | null)[];
56
+ /**
57
+ * Five per rig: the stride interval, this tick's own time, the clip's ground speed, the rate this rule
58
+ * last applied (0 for none), and the flags word.
59
+ */
60
+ readonly values: Float64Array;
61
+ /** Three per rig, written by the call: stride rate, measured ground speed, flags. */
62
+ readonly status: Float64Array;
63
+ }
64
+
65
+ /** What the classes call; the Wasm ABI implements it, and a surface-only runtime refuses every call. */
66
+ export interface IBrowserRuntime {
67
+ readonly debugTelemetry?: DebugTelemetry;
68
+ typeId(className: string): number;
69
+ construct(className: string, args: readonly EngineValue[]): IEngineRef;
70
+ invoke(self: IEngineRef, method: string, args: readonly EngineValue[]): EngineValue;
71
+ get(self: IEngineRef, path: string): EngineValue;
72
+ set(self: IEngineRef, path: string, value: EngineValue): void;
73
+ release(self: IEngineRef): void;
74
+ /** For each ref, how many references other engine objects hold to its object; one call a batch. */
75
+ engineReferences?(refs: readonly IEngineRef[]): ArrayLike<number>;
76
+ /**
77
+ * PRD-828: advances a batch of animation rigs in one crossing — the weight ramp, the stride rate and
78
+ * one mixer step each. A backend that cannot batch leaves it out and the JS loop keeps running.
79
+ */
80
+ animTick?(batch: IAnimationTickBatch): void;
81
+ /** A numeric typed array argument crosses as is, no boxed copy; Wasm only. */
82
+ readonly typedArrays?: boolean;
83
+ /** Doubles at `address` in the engine's memory (one as a number, more as an array); Wasm only. */
84
+ readDoubles?(address: number, count: number): number | number[];
85
+ /**
86
+ * The engine's memory as doubles, current: Emscripten replaces the view when the memory grows, so a caller
87
+ * reads it per operation and never keeps it. Wasm only.
88
+ */
89
+ heapF64?(): Float64Array;
90
+ /** The byte at `address` in the engine's memory; Wasm only. A registry field `[offset, 0]` is a byte flag. */
91
+ readByte?(address: number): number;
92
+ /** The 32-bit word at `address` in the engine's memory (the hierarchy counter's low word); Wasm only. */
93
+ readWord?(address: number): number;
94
+ /** Writes one double at `address` in the engine's memory; Wasm only. */
95
+ writeDouble?(address: number, value: number): void;
96
+ /** Writes the byte at `address` in the engine's memory (a flag field); Wasm only. */
97
+ writeByte?(address: number, value: number): void;
98
+ /**
99
+ * A copy of the attribute's data, of its scalar type; three's `attribute.array` is built on it.
100
+ * With `offset`/`count`, a copy of that scalar subrange only (a per-vertex setter syncs one item).
101
+ */
102
+ attributeArray?(self: IEngineRef, offset?: number, count?: number): TypedArray;
103
+ /**
104
+ * Writes `array` into the attribute's data; present with attributeArray. With `offset`, writes that
105
+ * subrange; without it, `array` must be the attribute's whole data.
106
+ */
107
+ attributeWrite?(self: IEngineRef, array: TypedArray, offset?: number): void;
108
+ /** Sets (or, with null, clears) a callback the engine runs; `handler` gets the engine's arguments. */
109
+ setCallback(
110
+ self: IEngineRef,
111
+ name: string,
112
+ handler: ((args: readonly EngineValue[]) => void) | null,
113
+ ): void;
114
+ /** TSL by name (PRD-540), when the module carries `tn_tsl_call`. */
115
+ readonly tsl?: ITslRuntime;
116
+ /** A GLB through the engine's own glTF loader (PRD-540), when the module carries the web host. */
117
+ loadGltf?(
118
+ bytes: Uint8Array,
119
+ files?: ReadonlyMap<string, Uint8Array>,
120
+ ): {
121
+ readonly scene: IEngineRef;
122
+ readonly animations: IEngineRef[];
123
+ /** Every scene in file order; the default scene is one of them. */
124
+ readonly scenes: IEngineRef[];
125
+ };
126
+ /** `loadGltf` on the engine's loader thread (PRD-860), when the module carries it. */
127
+ loadGltfAsync?(
128
+ bytes: Uint8Array,
129
+ files?: ReadonlyMap<string, Uint8Array>,
130
+ ): Promise<{
131
+ readonly scene: IEngineRef;
132
+ readonly animations: IEngineRef[];
133
+ /** Every scene in file order; the default scene is one of them. */
134
+ readonly scenes: IEngineRef[];
135
+ }>;
136
+ }
137
+
138
+ /**
139
+ * The engine's C ABI as built by `tn-native-engine-abi-module` (Emscripten, wasm32). The names are
140
+ * Emscripten's (`HEAPU8`, `_malloc`, `_tn_*`), so they are declared as record keys.
141
+ */
142
+ type AbiCall =
143
+ | "_malloc"
144
+ | "_free"
145
+ | "_tn_engine_version"
146
+ | "_tn_context_create"
147
+ | "_tn_type_id"
148
+ | "_tn_object_release"
149
+ | "_tn_object_engine_references"
150
+ | "_tn_construct"
151
+ | "_tn_invoke"
152
+ | "_tn_get"
153
+ | "_tn_set"
154
+ | "_tn_set_callback"
155
+ | "_tn_diagnostic_release"
156
+ | "_tn_anim_tick";
157
+ export type TnAbiModule = Record<AbiCall, (...args: number[]) => number> &
158
+ Partial<
159
+ Record<"_tnw_attribute_view" | "_tnw_attribute_view_release", (...args: number[]) => number>
160
+ > &
161
+ Record<"HEAPU8", Uint8Array> &
162
+ Record<"HEAPF64", Float64Array> &
163
+ Record<"UTF8ToString", (pointer: number, maxBytes?: number) => string> &
164
+ Record<
165
+ "addFunction",
166
+ (fn: (...args: number[]) => number | undefined, signature: string) => number
167
+ > & {
168
+ stringToUTF8(text: string, pointer: number, maxBytes: number): void;
169
+ lengthBytesUTF8(text: string): number;
170
+ };
171
+
172
+ // wasm32 layouts of tn_abi.h, measured with offsetof under emcc: tn_handle_t 12 bytes; tn_value_t
173
+ // 56 bytes (kind 0, boolean 4, number 8, handle 16, text 32, count 40, numbers 48); tn_diagnostic_t
174
+ // 8 bytes (message 0, code 4); tn_version_info_t 32 bytes. A struct passed by value goes by pointer.
175
+ export const HANDLE = 12;
176
+ export const VALUE = 56;
177
+ export const KIND = {
178
+ null: 0,
179
+ number: 1,
180
+ bool: 2,
181
+ string: 3,
182
+ handle: 4,
183
+ numbers: 5,
184
+ array: 6,
185
+ record: 7,
186
+ undefined: 8,
187
+ bytes: 9,
188
+ } as const;
189
+
190
+ // wasm32 layout of tn_tsl_arg_t (tn_tsl.h): kind 0, lanes 4, node 8 (u64), number 16, text 24,
191
+ // numbers 32 (four f64); 64 bytes. A handle argument's 12 bytes start at lanes (4) and run through node.
192
+ const TSL_ARG = 64;
193
+ const TSL_KIND = {
194
+ node: 0,
195
+ number: 1,
196
+ string: 2,
197
+ named: 3,
198
+ rgb: 4,
199
+ vector: 5,
200
+ other: 6,
201
+ handle: 7,
202
+ } as const;
203
+ type TslCall =
204
+ | "_tn_tsl_call"
205
+ | "_tn_tsl_release"
206
+ | "_tn_tsl_set"
207
+ | "_tn_tsl_set_uniform"
208
+ | "_tn_tsl_set_uniforms"
209
+ | "_tn_tsl_reads"
210
+ | "_tn_tsl_effect_parameter"
211
+ | "_tnw_web_set_post"
212
+ | "_tnw_web_compute"
213
+ | "_tnw_web_compute_flush"
214
+ | "_tnw_web_read_storage"
215
+ | "_tnw_web_read_storage_size"
216
+ | "_tnw_web_read_storage_take"
217
+ | "_tnw_web_delete_storage"
218
+ | "_tnw_web_poll"
219
+ | "_tnw_web_error";
220
+
221
+ export interface IAbiHelpers {
222
+ scoped<T>(work: () => T): T;
223
+ alloc(size: number): number;
224
+ string(text: string): { pointer: number; bytes: number };
225
+ diagnostic(): number;
226
+ check(status: number, diag: number, what: string): void;
227
+ handleOf(ref: IEngineRef): number;
228
+ writeHandle(pointer: number, ref: IEngineRef): void;
229
+ view(): DataView;
230
+ }
231
+
232
+ /** `tnw_web_load_gltf`'s handles: the default scene, the clips, then every scene in file order. */
233
+ function splitModel(refs: IEngineRef[], scenes: number) {
234
+ const clipsEnd = refs.length - scenes;
235
+ return {
236
+ scene: refs[0] as IEngineRef,
237
+ animations: refs.slice(1, clipsEnd),
238
+ scenes: refs.slice(clipsEnd),
239
+ };
240
+ }
241
+
242
+ /** The engine glTF loader over the product web host's `tnw_web_load_gltf`, when the module has it. */
243
+ export function gltfOf(
244
+ abi: TnAbiModule,
245
+ context: number,
246
+ h: Pick<IAbiHelpers, "scoped" | "alloc"> & { keyOf(pointer: number): IEngineRef },
247
+ ): Pick<IBrowserRuntime, "loadGltf" | "loadGltfAsync"> {
248
+ // quality-allow: the Emscripten module is read through the exports this call site names, not its full surface.
249
+ const host = abi as unknown as Partial<
250
+ Record<
251
+ | "_tnw_web_load_gltf"
252
+ | "_tnw_web_load_gltf_begin"
253
+ | "_tnw_web_load_gltf_done"
254
+ | "_tnw_web_load_gltf_finish"
255
+ | "_tnw_web_load_error"
256
+ | "_tnw_web_gltf_file"
257
+ | "_tnw_web_gltf_files_clear",
258
+ (...args: number[]) => number
259
+ >
260
+ >;
261
+ const {
262
+ _tnw_web_load_gltf: load,
263
+ _tnw_web_load_gltf_begin: begin,
264
+ _tnw_web_load_gltf_done: done,
265
+ _tnw_web_load_gltf_finish: finish,
266
+ _tnw_web_load_error: error,
267
+ _tnw_web_gltf_file: file,
268
+ _tnw_web_gltf_files_clear: clearFiles,
269
+ } = host;
270
+ if (load === undefined || error === undefined) return {};
271
+ /** Files the model names by relative uri (shared images), kept for the engine loader's next load. */
272
+ const stageFiles = (files: ReadonlyMap<string, Uint8Array> | undefined): void => {
273
+ if (files === undefined || files.size === 0) return;
274
+ if (file === undefined || clearFiles === undefined)
275
+ throw new Error(
276
+ "TN_WASM_GLTF_FILES_UNAVAILABLE: this web engine cannot read a model's image files",
277
+ );
278
+ for (const [uri, content] of files) {
279
+ // tnw_web_gltf_file keeps its own copy, so this scratch is dead once it returns. One scope
280
+ // per file frees it at once: the peak is one file, not the sum of all of them.
281
+ h.scoped(() => {
282
+ const name = h.alloc(abi.lengthBytesUTF8(uri) + 1);
283
+ abi.stringToUTF8(uri, name, abi.lengthBytesUTF8(uri) + 1);
284
+ const copy = h.alloc(Math.max(1, content.byteLength));
285
+ abi.HEAPU8.set(content, copy);
286
+ file(name, copy, content.byteLength);
287
+ });
288
+ }
289
+ };
290
+ /**
291
+ * The handles `share(out, capacity, count, scenes)` writes, retried once at the exact size for a
292
+ * model with many clips.
293
+ */
294
+ const handles = (
295
+ share: (out: number, capacity: number, count: number, scenes: number) => number,
296
+ ) =>
297
+ h.scoped(() => {
298
+ const count = h.alloc(4);
299
+ const sceneCount = h.alloc(4);
300
+ for (let capacity = 64; ; ) {
301
+ const out = h.alloc(HANDLE * capacity);
302
+ const status = share(out, capacity, count, sceneCount);
303
+ const needed = new DataView(abi.HEAPU8.buffer).getUint32(count, true);
304
+ if (status === 0)
305
+ return splitModel(
306
+ Array.from({ length: needed }, (_, i) => h.keyOf(out + i * HANDLE)),
307
+ new DataView(abi.HEAPU8.buffer).getUint32(sceneCount, true),
308
+ );
309
+ const reason = abi.UTF8ToString(error());
310
+ if (reason !== "TN_WASM_GLTF_CAPACITY" || needed <= capacity) throw new Error(reason);
311
+ capacity = needed;
312
+ }
313
+ });
314
+ const loadGltf: NonNullable<IBrowserRuntime["loadGltf"]> = (bytes, files) =>
315
+ h.scoped(() => {
316
+ try {
317
+ stageFiles(files);
318
+ const data = h.alloc(Math.max(1, bytes.byteLength));
319
+ abi.HEAPU8.set(bytes, data);
320
+ return handles((out, capacity, count, scenes) =>
321
+ load(context, data, bytes.byteLength, out, capacity, count, scenes),
322
+ );
323
+ } finally {
324
+ clearFiles?.();
325
+ }
326
+ });
327
+ if (begin === undefined || done === undefined || finish === undefined) return { loadGltf };
328
+ return {
329
+ loadGltf,
330
+ // PRD-860: the engine parses on its loader thread, so a model that arrives during play costs the
331
+ // main thread a poll and the hand-over, not the 100-500 ms parse Midway's late fleet froze on.
332
+ loadGltfAsync: async (bytes, files) => {
333
+ const ticket = h.scoped(() => {
334
+ try {
335
+ stageFiles(files);
336
+ const data = h.alloc(Math.max(1, bytes.byteLength));
337
+ abi.HEAPU8.set(bytes, data);
338
+ // begin copies the bytes and takes the staged files with it.
339
+ return begin(data, bytes.byteLength);
340
+ } finally {
341
+ clearFiles?.();
342
+ }
343
+ });
344
+ if (ticket === 0) throw new Error("TN_WASM_GLTF: the engine refused the load");
345
+ while (done(ticket) === 0) await new Promise((resolve) => setTimeout(resolve, GLTF_POLL_MS));
346
+ return handles((out, capacity, count, scenes) =>
347
+ finish(context, ticket, out, capacity, count, scenes),
348
+ );
349
+ },
350
+ };
351
+ }
352
+
353
+ /** How often a pending engine glTF load is polled: a 4 ms timer costs nothing beside a 100 ms parse. */
354
+ const GLTF_POLL_MS = 4;
355
+
356
+ /** TSL by name over `tn_tsl_call`, when the module exports it (the product web host does). */
357
+ export function tslOf(
358
+ abi: TnAbiModule,
359
+ context: number,
360
+ h: IAbiHelpers,
361
+ ): { tsl: ITslRuntime } | undefined {
362
+ // Node ids are u64 in the C ABI; Emscripten passes a 64-bit parameter as a BigInt.
363
+ // quality-allow: the Emscripten module is read through the TSL call exports this call site names, not its full surface.
364
+ const calls = abi as unknown as Partial<
365
+ Record<TslCall, (...args: (number | bigint)[]) => number>
366
+ >;
367
+ const {
368
+ _tn_tsl_call: call,
369
+ _tn_tsl_release: release,
370
+ _tn_tsl_set: set,
371
+ _tn_tsl_set_uniform: setUniform,
372
+ _tn_tsl_set_uniforms: setUniforms,
373
+ _tn_tsl_reads: reads,
374
+ _tn_tsl_effect_parameter: effectParameter,
375
+ _tnw_web_set_post: setPost,
376
+ _tnw_web_compute: computeNode,
377
+ _tnw_web_compute_flush: computeFlush,
378
+ _tnw_web_read_storage: readStorage,
379
+ _tnw_web_read_storage_size: readStorageSize,
380
+ _tnw_web_read_storage_take: readStorageTake,
381
+ _tnw_web_delete_storage: deleteStorage,
382
+ _tnw_web_poll: poll,
383
+ _tnw_web_error: webError,
384
+ } = calls;
385
+ if (
386
+ call === undefined ||
387
+ release === undefined ||
388
+ set === undefined ||
389
+ setUniform === undefined ||
390
+ effectParameter === undefined
391
+ )
392
+ return undefined;
393
+ // PRD-878: the hooked uniform ids `reads` checks, kept in engine memory: the facade only appends to its list, so a
394
+ // query writes just the ids added since the last one.
395
+ let candidateAt = 0;
396
+ let candidateRoom = 0;
397
+ let candidatesWritten = 0;
398
+ // Writes tn_tsl_arg_t values; text is allocated first, since an allocation can grow the memory.
399
+ const writeArgs = (args: readonly TslArgValue[]): number => {
400
+ const pointer = h.alloc(Math.max(TSL_ARG, args.length * TSL_ARG));
401
+ args.forEach((arg, i) => {
402
+ const at = pointer + i * TSL_ARG;
403
+ const text = arg.kind === "string" || arg.kind === "named" ? h.string(arg.text).pointer : 0;
404
+ const v = h.view();
405
+ v.setUint32(at, TSL_KIND[arg.kind], true);
406
+ if (arg.kind === "node") v.setBigUint64(at + 8, BigInt(arg.node), true);
407
+ else if (arg.kind === "number") v.setFloat64(at + 16, arg.number, true);
408
+ else if (arg.kind === "rgb" || arg.kind === "vector") {
409
+ v.setUint32(at + 4, arg.numbers.length, true);
410
+ arg.numbers.forEach((c, j) => v.setFloat64(at + 32 + j * 8, c, true));
411
+ } else if (arg.kind === "handle") h.writeHandle(at + 4, arg.ref);
412
+ else v.setUint32(at + 24, text, true);
413
+ });
414
+ return pointer;
415
+ };
416
+ const nodeOf = (node: number | null): number => {
417
+ if (node === null) return 0;
418
+ const pointer = h.alloc(8);
419
+ h.view().setBigUint64(pointer, BigInt(node), true);
420
+ return pointer;
421
+ };
422
+ return {
423
+ tsl: {
424
+ call: (name, receiver, args) =>
425
+ h.scoped(() => {
426
+ const pointer = writeArgs(args);
427
+ const self = nodeOf(receiver);
428
+ const out = h.alloc(8);
429
+ const diag = h.diagnostic();
430
+ h.check(
431
+ call(context, h.string(name).pointer, self, pointer, args.length, out, diag),
432
+ diag,
433
+ `TSL ${name}`,
434
+ );
435
+ return Number(h.view().getBigUint64(out, true));
436
+ }),
437
+ release: (node) =>
438
+ h.scoped(() => {
439
+ const diag = h.diagnostic();
440
+ release(context, BigInt(node), diag);
441
+ abi._tn_diagnostic_release(diag);
442
+ }),
443
+ set: (material, path, node) =>
444
+ h.scoped(() => {
445
+ const diag = h.diagnostic();
446
+ h.check(
447
+ set(context, h.handleOf(material), h.string(path).pointer, BigInt(node), diag),
448
+ diag,
449
+ `set ${path}`,
450
+ );
451
+ }),
452
+ effectParameter: (node, name, value) =>
453
+ h.scoped(() => {
454
+ const self = nodeOf(node);
455
+ const input = value === undefined ? 0 : h.alloc(8);
456
+ if (value !== undefined) h.view().setFloat64(input, value, true);
457
+ const out = h.alloc(8);
458
+ const diag = h.diagnostic();
459
+ h.check(
460
+ effectParameter(context, self, h.string(name).pointer, input, out, diag),
461
+ diag,
462
+ `effect ${name}`,
463
+ );
464
+ return h.view().getFloat64(out, true);
465
+ }),
466
+ // three's RenderPipeline on the product web host: the graph between scene and output.
467
+ setPost: (node) =>
468
+ h.scoped(() => {
469
+ if (setPost === undefined) throw new Error("TN_WASM_POST: this module has no web host");
470
+ if (setPost(context, nodeOf(node), 0) !== 0) throw new Error("TN_WASM_POST: refused");
471
+ }),
472
+ setToneMapping: (node) =>
473
+ h.scoped(() => {
474
+ if (setPost === undefined)
475
+ throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_MISSING: no web output binding");
476
+ if (setPost(context, nodeOf(node), 1) !== 0)
477
+ throw new Error("TN_NATIVE_CUSTOM_TONEMAPPING_INVALID: refused output node");
478
+ }),
479
+ // PRD-620: renderer.compute and storage reads over the product web host.
480
+ compute: (node) =>
481
+ h.scoped(() => {
482
+ if (computeNode === undefined || webError === undefined)
483
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
484
+ if (computeNode(context, nodeOf(node)) !== 0)
485
+ throw new Error(abi.UTF8ToString(webError()));
486
+ }),
487
+ readStorage: async (attribute) => {
488
+ if (
489
+ readStorage === undefined ||
490
+ readStorageSize === undefined ||
491
+ readStorageTake === undefined ||
492
+ computeFlush === undefined ||
493
+ poll === undefined ||
494
+ webError === undefined
495
+ )
496
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
497
+ const id = h.scoped(() => {
498
+ const pointer = h.alloc(HANDLE);
499
+ h.writeHandle(pointer, attribute);
500
+ return readStorage(pointer);
501
+ });
502
+ if (id === 0) throw new Error(abi.UTF8ToString(webError()));
503
+ computeFlush();
504
+ for (;;) {
505
+ poll();
506
+ const size = readStorageSize(id);
507
+ if (size > 0 || readStorageTake(id, 0, 0) < 0) {
508
+ const out = abi._malloc(size) >>> 0;
509
+ try {
510
+ if (readStorageTake(id, out, size) === 1)
511
+ return abi.HEAPU8.slice(out, out + size).buffer;
512
+ } finally {
513
+ abi._free(out);
514
+ }
515
+ throw new Error("TN_NATIVE_READ_STORAGE: the read failed");
516
+ }
517
+ await new Promise((resolve) => setTimeout(resolve, 0));
518
+ }
519
+ },
520
+ deleteStorage: (attribute) =>
521
+ h.scoped(() => {
522
+ if (deleteStorage === undefined || webError === undefined)
523
+ throw new Error("TN_WASM_COMPUTE: this module has no web host");
524
+ const pointer = h.alloc(HANDLE);
525
+ h.writeHandle(pointer, attribute);
526
+ if (deleteStorage(pointer) !== 0) throw new Error(abi.UTF8ToString(webError()));
527
+ }),
528
+ setUniform: (node, lanes) =>
529
+ h.scoped(() => {
530
+ const pointer = h.alloc(8);
531
+ const values = h.alloc(Math.max(8, lanes.length * 8));
532
+ const v = h.view();
533
+ v.setBigUint64(pointer, BigInt(node), true);
534
+ lanes.forEach((lane, i) => v.setFloat64(values + i * 8, lane, true));
535
+ const diag = h.diagnostic();
536
+ h.check(setUniform(context, pointer, values, lanes.length, diag), diag, "uniform.value");
537
+ }),
538
+ ...(reads === undefined
539
+ ? {}
540
+ : {
541
+ reads: (
542
+ root: IEngineRef | undefined,
543
+ kernels: readonly number[],
544
+ candidates: readonly number[],
545
+ ): number[] => {
546
+ if (candidates.length > candidateRoom) {
547
+ if (candidateAt !== 0) abi._free(candidateAt);
548
+ candidateRoom = Math.max(16, candidates.length * 2);
549
+ // The ids, then room for as many u32 answers.
550
+ candidateAt = abi._malloc(candidateRoom * 12) >>> 0;
551
+ candidatesWritten = 0;
552
+ }
553
+ const ids = h.view();
554
+ for (; candidatesWritten < candidates.length; candidatesWritten += 1)
555
+ ids.setBigUint64(
556
+ candidateAt + candidatesWritten * 8,
557
+ BigInt(candidates[candidatesWritten] as number),
558
+ true,
559
+ );
560
+ return h.scoped(() => {
561
+ const rootAt = root === undefined ? 0 : h.alloc(HANDLE);
562
+ if (root !== undefined) h.writeHandle(rootAt, root);
563
+ const kernelAt = h.alloc(Math.max(8, kernels.length * 8));
564
+ const countAt = h.alloc(4);
565
+ const v = h.view();
566
+ kernels.forEach((kernel, i) =>
567
+ v.setBigUint64(kernelAt + i * 8, BigInt(kernel), true),
568
+ );
569
+ const out = candidateAt + candidateRoom * 8;
570
+ const diag = h.diagnostic();
571
+ h.check(
572
+ reads(
573
+ context,
574
+ rootAt,
575
+ kernelAt,
576
+ kernels.length,
577
+ candidateAt,
578
+ candidates.length,
579
+ out,
580
+ countAt,
581
+ diag,
582
+ ),
583
+ diag,
584
+ "uniform reads",
585
+ );
586
+ const after = h.view();
587
+ const picked: number[] = [];
588
+ for (let i = 0, count = after.getUint32(countAt, true); i < count; i += 1)
589
+ picked.push(after.getUint32(out + i * 4, true));
590
+ return picked;
591
+ });
592
+ },
593
+ }),
594
+ // PRD-828: a sync's changed uniforms as one `tn_tsl_set_uniforms` span; absent on an older module.
595
+ ...(setUniforms === undefined
596
+ ? {}
597
+ : {
598
+ setUniforms: (
599
+ nodes: readonly number[],
600
+ counts: readonly number[],
601
+ lanes: readonly number[],
602
+ ) =>
603
+ h.scoped(() => {
604
+ const ids = h.alloc(Math.max(8, nodes.length * 8));
605
+ const widths = h.alloc(Math.max(4, counts.length * 4));
606
+ const values = h.alloc(Math.max(8, lanes.length * 8));
607
+ const v = h.view();
608
+ nodes.forEach((node, i) => v.setBigUint64(ids + i * 8, BigInt(node), true));
609
+ counts.forEach((count, i) => v.setUint32(widths + i * 4, count, true));
610
+ lanes.forEach((lane, i) => v.setFloat64(values + i * 8, lane, true));
611
+ const diag = h.diagnostic();
612
+ h.check(
613
+ setUniforms(context, ids, widths, values, nodes.length, diag),
614
+ diag,
615
+ "uniform.value",
616
+ );
617
+ }),
618
+ }),
619
+ },
620
+ };
621
+ }