@threenative/three-native 0.3.13 → 0.3.16

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/three-native",
3
- "version": "0.3.13",
3
+ "version": "0.3.16",
4
4
  "license": "MIT",
5
5
  "description": "The native engine's machine-readable compatibility catalog and the generators that adapt it to TypeScript declarations and the C binding ABI.",
6
6
  "keywords": [
@@ -428,6 +428,16 @@ export interface IScreenSpaceGiOptions {
428
428
  * the shadowed walls nearby while its bright directions leave the screen. Missing means 0, as three's SSGINode.
429
429
  */
430
430
  readonly fallback?: (position: TslNode, direction: TslNode, normal: TslNode) => TslNode;
431
+ /**
432
+ * What a ray that leaves the screen finds in the tier past the screen: Unreal continues the ray in the distance field
433
+ * up to the radiance cache's coverage and reads the cache there, so a miss is a direction's radiance and not the
434
+ * pixel's mean (`ScreenProbeGather` composes that walk). Called for each ray that found nothing on screen, with the
435
+ * receiver's view-space position, the ray's unit view-space direction and its normal, and answers the light that
436
+ * arrives from off screen minus what the frame already holds at the pixel: the composite adds the pixel's own
437
+ * indirect diffuse, so a value that did not take it out would count it twice. Missing means 0, as three's SSGINode
438
+ * and this gather before PRD-640 Phase 2: a miss then leaves the pixel's cache average in place.
439
+ */
440
+ readonly miss?: (position: TslNode, direction: TslNode, normal: TslNode) => TslNode;
431
441
  /**
432
442
  * Gather with screen probes instead of per-pixel rays (Unreal's ScreenProbeGather): one probe per
433
443
  * `downsampleFactor` pixel tile traces an octahedron of rays, the probe radiance is turned into an irradiance
@@ -625,6 +635,11 @@ export function defineScreenSpaceGi(tsl: IScreenSpaceTsl) {
625
635
  const fallback = options.fallback?.(position, direction, normal) ?? vec3(0, 0, 0);
626
636
  gathered.assign(gathered.add(hit.radiance.sub(fallback).mul(hit.weight)));
627
637
  hits.assign(hits.add(hit.weight));
638
+ }).Else(() => {
639
+ // A ray the screen cannot answer reaches the tier past it (the world-space trace and the radiance cache):
640
+ // the delta over what the pixel's own indirect diffuse already holds, at the ray's weight.
641
+ const past = options.miss?.(position, direction, normal);
642
+ if (past !== undefined) gathered.assign(gathered.add(past));
628
643
  });
629
644
  },
630
645
  );
@@ -690,10 +705,11 @@ function octahedronEncode(tsl: IScreenSpaceTsl, direction: TslNode): TslNode {
690
705
  /**
691
706
  * The screen-probe gather (PRD-640). Three passes, none per pixel until the last:
692
707
  * 1. trace one texel per ray: a probe per tile traces an `n x n` octahedron of rays (view space) and keeps the lit
693
- * colour each hit found and its weight.
708
+ * colour each hit found and its weight, or, where the screen has nothing, what the tier past it answers
709
+ * (`miss`: the world-space trace and the radiance cache).
694
710
  * 2. filter each probe turns its rays into an irradiance octahedron: per direction, the cosine-weighted mean of
695
- * `hit - fallback` (the trace subtracts the cache along each ray), so a ray that leaves the screen keeps
696
- * the cache. A pixel then reads one bilinear tap instead of 64 rays.
711
+ * `hit - fallback` (the trace subtracts the cache along each ray), so a ray that hits keeps the screen's
712
+ * light and a ray that misses keeps the tier beyond it. A pixel then reads one bilinear tap, not 64 rays.
697
713
  * 3. gather each pixel blends the four nearest probes by position, depth-plane distance and normal agreement, and
698
714
  * reads each probe's irradiance along the pixel normal. A pixel no probe can see gets the cache alone.
699
715
  */
@@ -776,6 +792,11 @@ function defineScreenProbes(
776
792
  const hit = shade(trace.hitCoordinate, trace.hitDistance, direction);
777
793
  const believed = options.fallback?.(position, direction, normal) ?? vec3(0, 0, 0);
778
794
  result.assign(vec4(hit.radiance.sub(believed).mul(hit.weight), hit.weight));
795
+ }).Else(() => {
796
+ // A ray the screen cannot answer carries the tier past it: the filter mixes it with the probe's other rays, so a
797
+ // probe keeps a direction's radiance where the frame ends (the `a` channel stays the hit share).
798
+ const past = options.miss?.(position, direction, normal);
799
+ if (past !== undefined) result.assign(vec4(past, 0));
779
800
  });
780
801
  });
781
802
  return result;
@@ -73,6 +73,8 @@ export interface IBrowserRuntime {
73
73
  release(self: IEngineRef): void;
74
74
  /** For each ref, how many references other engine objects hold to its object; one call a batch. */
75
75
  engineReferences?(refs: readonly IEngineRef[]): ArrayLike<number>;
76
+ /** PRD-898 J5: moves whenever an `engineReferences` count may have changed (`tn_ownership_epoch`). */
77
+ ownershipEpoch?(): number;
76
78
  /**
77
79
  * PRD-828: advances a batch of animation rigs in one crossing — the weight ramp, the stride rate and
78
80
  * one mixer step each. A backend that cannot batch leaves it out and the JS loop keeps running.
@@ -83,10 +85,10 @@ export interface IBrowserRuntime {
83
85
  /** Doubles at `address` in the engine's memory (one as a number, more as an array); Wasm only. */
84
86
  readDoubles?(address: number, count: number): number | number[];
85
87
  /**
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
+ * The engine's memory as doubles, current and reaching at least byte `end`: the view is replaced
89
+ * when the memory grows, so a caller reads it per operation and never keeps it. Wasm only.
88
90
  */
89
- heapF64?(): Float64Array;
91
+ heapF64?(end: number): Float64Array;
90
92
  /** The byte at `address` in the engine's memory; Wasm only. A registry field `[offset, 0]` is a byte flag. */
91
93
  readByte?(address: number): number;
92
94
  /** The 32-bit word at `address` in the engine's memory (the hierarchy counter's low word); Wasm only. */
@@ -156,7 +158,10 @@ type AbiCall =
156
158
  | "_tn_anim_tick";
157
159
  export type TnAbiModule = Record<AbiCall, (...args: number[]) => number> &
158
160
  Partial<
159
- Record<"_tnw_attribute_view" | "_tnw_attribute_view_release", (...args: number[]) => number>
161
+ Record<
162
+ "_tnw_attribute_view" | "_tnw_attribute_view_release" | "_tn_ownership_epoch",
163
+ (...args: number[]) => number
164
+ >
160
165
  > &
161
166
  Record<"HEAPU8", Uint8Array> &
162
167
  Record<"HEAPF64", Float64Array> &
@@ -169,6 +174,28 @@ export type TnAbiModule = Record<AbiCall, (...args: number[]) => number> &
169
174
  lengthBytesUTF8(text: string): number;
170
175
  };
171
176
 
177
+ /**
178
+ * The engine's memory as bytes, reaching at least `end`. Shared memory (the threaded build) grows from
179
+ * any thread, and Emscripten refreshes a thread's views only inside its own glue: after a pool worker
180
+ * grew it, HEAPU8 here stayed short and a pointer past it threw "Offset is outside the bounds of the
181
+ * DataView". A shared buffer never detaches, so a short view is right below its end: only an access
182
+ * past it reads `memory.buffer`, and the fresh views go onto the module for every other reader.
183
+ */
184
+ export function heapFor(abi: TnAbiModule, end: number): Uint8Array {
185
+ if (end <= abi.HEAPU8.byteLength) return abi.HEAPU8;
186
+ const buffer = (abi as { wasmMemory?: WebAssembly.Memory }).wasmMemory?.buffer;
187
+ if (
188
+ buffer !== undefined &&
189
+ buffer.byteLength > abi.HEAPU8.byteLength &&
190
+ typeof SharedArrayBuffer !== "undefined" &&
191
+ buffer instanceof SharedArrayBuffer
192
+ ) {
193
+ abi.HEAPU8 = new Uint8Array(buffer);
194
+ abi.HEAPF64 = new Float64Array(buffer);
195
+ }
196
+ return abi.HEAPU8;
197
+ }
198
+
172
199
  // wasm32 layouts of tn_abi.h, measured with offsetof under emcc: tn_handle_t 12 bytes; tn_value_t
173
200
  // 56 bytes (kind 0, boolean 4, number 8, handle 16, text 32, count 40, numbers 48); tn_diagnostic_t
174
201
  // 8 bytes (message 0, code 4); tn_version_info_t 32 bytes. A struct passed by value goes by pointer.
@@ -226,7 +253,8 @@ export interface IAbiHelpers {
226
253
  check(status: number, diag: number, what: string): void;
227
254
  handleOf(ref: IEngineRef): number;
228
255
  writeHandle(pointer: number, ref: IEngineRef): void;
229
- view(): DataView;
256
+ /** The heap's DataView, reaching at least byte `end` (pass it for a pointer `alloc` did not make). */
257
+ view(end?: number): DataView;
230
258
  }
231
259
 
232
260
  /** `tnw_web_load_gltf`'s handles: the default scene, the clips, then every scene in file order. */
@@ -508,7 +536,7 @@ export function tslOf(
508
536
  const out = abi._malloc(size) >>> 0;
509
537
  try {
510
538
  if (readStorageTake(id, out, size) === 1)
511
- return abi.HEAPU8.slice(out, out + size).buffer;
539
+ return heapFor(abi, out + size).slice(out, out + size).buffer;
512
540
  } finally {
513
541
  abi._free(out);
514
542
  }
@@ -550,7 +578,7 @@ export function tslOf(
550
578
  candidateAt = abi._malloc(candidateRoom * 12) >>> 0;
551
579
  candidatesWritten = 0;
552
580
  }
553
- const ids = h.view();
581
+ const ids = h.view(candidateAt + candidateRoom * 12);
554
582
  for (; candidatesWritten < candidates.length; candidatesWritten += 1)
555
583
  ids.setBigUint64(
556
584
  candidateAt + candidatesWritten * 8,
@@ -87,6 +87,8 @@ export interface IBrowserEngine {
87
87
 
88
88
  /** Safe points a pass over the settled wrappers spans. */
89
89
  const SETTLED_PASS = 64;
90
+ /** Safe points between settled passes the ownership epoch did not ask for (adapter.cpp kFullEvery). */
91
+ const FULL_PASS_EVERY = 512;
90
92
 
91
93
  /** An engine object's address, kept on it after the first ask: every lane read and write needs it. */
92
94
  const ADDRESS = Symbol("tn.engineAddress");
@@ -328,6 +330,7 @@ export function defineBrowserClasses(
328
330
  debug?.crossing("call", self, method, typeNames.get(self.type) ?? String(self.type));
329
331
  return source.invoke(self, method, args);
330
332
  },
333
+ ...(source.ownershipEpoch === undefined ? {} : { ownershipEpoch: source.ownershipEpoch }),
331
334
  ...(source.engineReferences === undefined
332
335
  ? {}
333
336
  : {
@@ -625,6 +628,12 @@ export function defineBrowserClasses(
625
628
  };
626
629
  let cursor = settled.values(); // collect()'s place in `settled`
627
630
  let peak = 0; // the most wrappers settled since this pass of `cursor` began
631
+ // PRD-898 J5: a settled wrapper can only lose its engine references when the ownership epoch moves.
632
+ // While it stands still and no pass is due, a safe point asks nothing about the settled set.
633
+ let epochSeen: number | undefined;
634
+ let epochAtPass: number | undefined;
635
+ let passDue = true;
636
+ let sinceFullPass = 0;
628
637
  // userData is the game's: it lives with the wrapper, which `held` keeps while the engine references it.
629
638
  const userData = new WeakMap<object, unknown>();
630
639
  const shaderNodes = new Map<string, Map<string, unknown>>(); // material key -> slot -> TSL node
@@ -981,6 +990,14 @@ export function defineBrowserClasses(
981
990
  } finally {
982
991
  if (loans.length > mark) result = repay(mark, result);
983
992
  if (drives) animated = new WeakMap();
993
+ // A native record batch writes other attributes through the receiver's method.
994
+ // Keep their JS arrays current so a later read cannot upload pre-refilter data.
995
+ if (method === "__tnRecords" && Array.isArray(args[0])) {
996
+ for (const attribute of args[0] as object[]) {
997
+ const entry = arrays.get(attribute);
998
+ if (entry !== undefined) syncFull(attribute, entry);
999
+ }
1000
+ }
984
1001
  }
985
1002
  // The engine's clone and copy carry the material's graphs; the TSL nodes a slot reads back
986
1003
  // follow them, or `clone().maskNode` answers null and a composed mask drops the source's.
@@ -1069,8 +1086,9 @@ export function defineBrowserClasses(
1069
1086
  Object.getPrototypeOf(other) !== prototype
1070
1087
  )
1071
1088
  return engineCopy.call(this, other);
1072
- const from = (addressOf(other) + offset) / 8;
1073
- heapF64().copyWithin((addressOf(this) + offset) / 8, from, from + count);
1089
+ const to = addressOf(this) + offset;
1090
+ const from = addressOf(other) + offset;
1091
+ heapF64(Math.max(to, from) + count * 8).copyWithin(to / 8, from / 8, from / 8 + count);
1074
1092
  return this;
1075
1093
  },
1076
1094
  },
@@ -1084,9 +1102,9 @@ export function defineBrowserClasses(
1084
1102
  Object.getPrototypeOf(other) !== prototype
1085
1103
  )
1086
1104
  return engineEquals.call(this, other);
1087
- const heap = heapF64();
1088
1105
  const a = (addressOf(this) + offset) / 8;
1089
1106
  const b = (addressOf(other) + offset) / 8;
1107
+ const heap = heapF64((Math.max(a, b) + count) * 8);
1090
1108
  for (let i = 0; i < count; i++) if (heap[a + i] !== heap[b + i]) return false;
1091
1109
  return true;
1092
1110
  },
@@ -1886,8 +1904,17 @@ export function defineBrowserClasses(
1886
1904
  // The sixty-fourth is of the pass's peak, so releases during a pass do not shrink it: a wrapper the
1887
1905
  // engine lets go is asked within two passes (tests/browser-backend-gc.ts). Holding a wrapper a
1888
1906
  // little longer only delays its release.
1907
+ const epoch = runtime.ownershipEpoch?.();
1908
+ // The native adapter's rule (adapter.cpp `collect`): a change the epoch cannot see is caught by a
1909
+ // pass every FULL_PASS_EVERY safe points.
1910
+ if (epoch === undefined || epoch !== epochSeen || ++sinceFullPass >= FULL_PASS_EVERY) {
1911
+ epochSeen = epoch;
1912
+ sinceFullPass = 0;
1913
+ passDue = true;
1914
+ }
1915
+ if (held.size === 0 && !passDue) return;
1889
1916
  peak = Math.max(peak, settled.size);
1890
- const budget = Math.ceil(peak / SETTLED_PASS);
1917
+ const budget = passDue ? Math.ceil(peak / SETTLED_PASS) : 0;
1891
1918
  const candidates: object[] = [...held];
1892
1919
  const fresh = candidates.length;
1893
1920
  while (candidates.length < fresh + budget) {
@@ -1898,6 +1925,9 @@ export function defineBrowserClasses(
1898
1925
  }
1899
1926
  cursor = settled.values();
1900
1927
  peak = settled.size;
1928
+ // A whole pass ran with the epoch unmoved: nothing it already asked can have changed since.
1929
+ if (epoch !== undefined && epochAtPass === epoch) passDue = false;
1930
+ epochAtPass = epoch;
1901
1931
  // An emptied set would restart forever: a safe point that let the last wrapper go hung here.
1902
1932
  if (candidates.length > fresh || settled.size === 0) break;
1903
1933
  }
@@ -70,7 +70,9 @@ export function setValues(target: object, className: string, values: object): vo
70
70
  if (value === undefined) continue;
71
71
  const current = self[key];
72
72
  if (current === undefined)
73
- throw new TypeError(`TN_BROWSER_PARAMETER_UNSUPPORTED: ${className} has no '${key}'`);
73
+ throw new TypeError(
74
+ `TN_BROWSER_PARAMETER_UNSUPPORTED: ${className} has no '${key}'. The engine does not implement this parameter on ${className}: remove the key.`,
75
+ );
74
76
  if (isWrapperOf(current, "Color")) setColor(current, value);
75
77
  else if (isWrapperOf(current, "Vector3") && (value as { isVector3?: boolean }).isVector3)
76
78
  current.copy?.(value);
@@ -4,7 +4,7 @@
4
4
  * surface and every draw; this class turns three's calls into host calls and reports what the
5
5
  * engine did. What it does not implement throws its diagnostic rather than doing nothing.
6
6
  */
7
- import { packedRef } from "./browser-abi-types.js";
7
+ import { heapFor, packedRef } from "./browser-abi-types.js";
8
8
  import { TSL_NODE, type TnAbiModule, engineRef } from "./browser-backend.js";
9
9
  import { type ITslRuntime, defineTsl, isTslNode } from "./browser-tsl.js";
10
10
  import { debugTelemetry } from "./debug-telemetry.js";
@@ -189,7 +189,7 @@ export function defineWebRenderer(
189
189
  if (ref === undefined)
190
190
  throw new TypeError(`TN_WASM_RENDER: the ${what} is not an engine object.`);
191
191
  const { w0, w1, w2 } = packedRef(ref);
192
- const view = new DataView(module.HEAPU8.buffer);
192
+ const view = new DataView(heapFor(module, handles + offset + 12).buffer);
193
193
  view.setUint32(handles + offset, w0, true);
194
194
  view.setUint32(handles + offset + 4, w1, true);
195
195
  view.setUint32(handles + offset + 8, w2, true);
@@ -462,9 +462,7 @@ export function defineWebRenderer(
462
462
  throw new Error(
463
463
  `TN_WASM_ABI_MISMATCH: this facade speaks web host ABI ${WEB_HOST_ABI}, the engine ${engine ?? "none (older than ABI 2)"}: install create-threenative and @threenative/runtime-native from one build`,
464
464
  );
465
- started = this.domElement;
466
465
  module.specialHTMLTargets[CANVAS_TARGET] = this.domElement;
467
- handles = module._malloc(36) >>> 0;
468
466
  const selector = string(CANVAS_TARGET);
469
467
  try {
470
468
  check(
@@ -473,6 +471,10 @@ export function defineWebRenderer(
473
471
  } finally {
474
472
  module._free(selector);
475
473
  }
474
+ // Only a host that started owns this canvas. Marked before the init, a start that threw left the
475
+ // next renderer polling a host nobody started, Pending for ever (PRD-895).
476
+ started = this.domElement;
477
+ handles = module._malloc(36) >>> 0;
476
478
  } else {
477
479
  // The disposed renderer's post graph must not outlive its game.
478
480
  tsl?.setPost(null);
@@ -505,7 +507,12 @@ export function defineWebRenderer(
505
507
  ) as Record<WorkCountName, number>;
506
508
  }
507
509
  return this;
508
- })();
510
+ })().catch((error: unknown) => {
511
+ // A start that failed gives the page's one slot back, so the next start in this page (a hot
512
+ // reload) reports its own result instead of TN_WASM_RENDERER_SINGLE (PRD-894).
513
+ this.dispose();
514
+ throw error;
515
+ });
509
516
  return this.#initialized;
510
517
  }
511
518
 
@@ -1193,7 +1200,7 @@ export function defineWebRenderer(
1193
1200
  for (;;) {
1194
1201
  module._tnw_web_poll();
1195
1202
  const status = module._tnw_web_read_target_take(id, out, size);
1196
- if (status === 1) return module.HEAPU8.slice(out, out + size);
1203
+ if (status === 1) return heapFor(module, out + size).slice(out, out + size);
1197
1204
  // A read the lost device dropped says so, so the caller's report is read as that one loss.
1198
1205
  if (status < 0)
1199
1206
  throw new Error(
@@ -1263,7 +1270,9 @@ export function defineWebRenderer(
1263
1270
  module._tnw_web_poll();
1264
1271
  const status = module._tnw_web_read_target_take(id, out, bytes);
1265
1272
  if (status === 1)
1266
- return new Float32Array(module.HEAPU8.slice(out, out + bytes).buffer);
1273
+ return new Float32Array(
1274
+ heapFor(module, out + bytes).slice(out, out + bytes).buffer,
1275
+ );
1267
1276
  if (status < 0) throw new Error("TN_REFLECTION_CAPTURE_READ");
1268
1277
  await new Promise((resolve) => setTimeout(resolve, 0));
1269
1278
  }
@@ -311,7 +311,7 @@ export function defineValueViews(host: IValueViewHost): IValueViews {
311
311
  if (read === undefined || write === undefined) return;
312
312
  const heap = runtime.heapF64;
313
313
  const lane = heap
314
- ? (address: number): number => heap()[address / 8] as number
314
+ ? (address: number): number => heap(address + 8)[address / 8] as number
315
315
  : (address: number): number => read(address, 1) as number;
316
316
  if (name === "Quaternion" && binding.fields !== undefined) {
317
317
  const offsets = ["x", "y", "z", "w"].map((key) => binding.fields?.[key]?.[0] ?? 0);
@@ -458,7 +458,7 @@ export function defineValueViews(host: IValueViewHost): IValueViews {
458
458
  // a frame, and a copy call allocates two arrays a read.
459
459
  const refresh = heap
460
460
  ? (address: number, values: number[]): void => {
461
- const memory = heap();
461
+ const memory = heap(address + count * 8);
462
462
  for (let i = 0, at = address / 8; i < count; i++) values[i] = memory[at + i] as number;
463
463
  }
464
464
  : (address: number, values: number[]): void => {
@@ -472,7 +472,7 @@ export function defineValueViews(host: IValueViewHost): IValueViews {
472
472
  configurable: true,
473
473
  get(this: object): number[] {
474
474
  const address = addressOf(this) + offset;
475
- const memory = heap?.();
475
+ const memory = heap?.(address + count * 8);
476
476
  if (
477
477
  typeof SharedArrayBuffer !== "undefined" &&
478
478
  memory?.buffer instanceof SharedArrayBuffer
@@ -13,6 +13,7 @@ import {
13
13
  type TnAbiModule,
14
14
  VALUE,
15
15
  gltfOf,
16
+ heapFor,
16
17
  isRef,
17
18
  packedRef,
18
19
  tslOf,
@@ -37,24 +38,30 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
37
38
  let encoding = "arguments";
38
39
  // The heap's views, made again only when the memory grows: Emscripten replaces HEAPU8 then, so one
39
40
  // identity test per use stands in for reading two `.buffer`s, which every crossing paid (PRD-748).
41
+ // Shared memory can grow from another thread with no replacement here, but it never detaches: an
42
+ // access past `heapBytes` (an engine pointer's `end`) refreshes through `heapFor`.
40
43
  let heap = abi.HEAPU8;
41
44
  let heapBytes = heap.byteLength;
42
45
  let dataView = new DataView(heap.buffer);
43
46
  let words = new Uint32Array(heap.buffer);
44
- const grown = () => {
45
- debug?.add("wasmGrowthEvents", 1, "bridge");
46
- debug?.add("wasmGrowthBytes", Math.max(0, abi.HEAPU8.byteLength - heapBytes), "memory");
47
- heap = abi.HEAPU8;
47
+ const grown = (end: number) => {
48
+ const before = heapBytes;
49
+ heap = heapFor(abi, end);
48
50
  heapBytes = heap.byteLength;
49
51
  dataView = new DataView(heap.buffer);
50
52
  words = new Uint32Array(heap.buffer);
53
+ debug?.add("wasmGrowthEvents", 1, "bridge");
54
+ debug?.add("wasmGrowthBytes", Math.max(0, heapBytes - before), "memory");
51
55
  };
52
- const view = () => {
53
- if (abi.HEAPU8 !== heap) grown();
56
+ const reach = (end: number) => {
57
+ if (end > heapBytes) grown(end);
58
+ };
59
+ const view = (end = 0) => {
60
+ if (end > heapBytes || abi.HEAPU8 !== heap) grown(end);
54
61
  return dataView;
55
62
  };
56
- const wordView = () => {
57
- if (abi.HEAPU8 !== heap) grown();
63
+ const wordView = (end = 0) => {
64
+ if (end > heapBytes || abi.HEAPU8 !== heap) grown(end);
58
65
  return words;
59
66
  };
60
67
  // Each call frees what it allocated, and only that: a callback can run a nested call.
@@ -80,8 +87,8 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
80
87
  debug?.add("bridgeOverflowBytes", aligned, "bridge");
81
88
  }
82
89
  // A call's scratch is a few words (a handle, a value, a diagnostic): word stores beat a fill call.
83
- // `wordView` first: a `_malloc` above may have grown the memory.
84
- const w = wordView();
90
+ // `wordView` first: a `_malloc` above may have grown the memory, on this thread or another.
91
+ const w = wordView(pointer + aligned);
85
92
  if (aligned > 64) heap.fill(0, pointer, pointer + aligned);
86
93
  else for (let at = pointer >>> 2, end = (pointer + aligned) >>> 2; at < end; at++) w[at] = 0;
87
94
  return pointer;
@@ -228,7 +235,7 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
228
235
  return pointer;
229
236
  };
230
237
  const readValue = (pointer: number): EngineValue => {
231
- const v = view();
238
+ const v = view(pointer + VALUE);
232
239
  switch (v.getUint32(pointer, true)) {
233
240
  case KIND.undefined:
234
241
  return undefined;
@@ -261,9 +268,9 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
261
268
  }
262
269
  case KIND.numbers: {
263
270
  const at = v.getUint32(pointer + 48, true) / 8;
264
- return Array.from(
265
- abi.HEAPF64.subarray(at, at + Number(v.getBigUint64(pointer + 40, true))),
266
- );
271
+ const count = Number(v.getBigUint64(pointer + 40, true));
272
+ reach((at + count) * 8);
273
+ return Array.from(abi.HEAPF64.subarray(at, at + count));
267
274
  }
268
275
  default:
269
276
  return null;
@@ -323,6 +330,7 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
323
330
  const Typed = SCALARS[scalar ?? -1];
324
331
  if (Typed === undefined)
325
332
  throw new TypeError(`TN_NATIVE_UNSUPPORTED array: scalar ${String(scalar)}`);
333
+ reach((address ?? 0) + (count ?? 0) * Typed.BYTES_PER_ELEMENT);
326
334
  return use(new Typed(abi.HEAPU8.buffer as ArrayBuffer, address ?? 0, count ?? 0));
327
335
  } finally {
328
336
  abi._tnw_attribute_view_release?.(lease);
@@ -384,6 +392,9 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
384
392
  );
385
393
  return readValue(out);
386
394
  }),
395
+ ...(abi._tn_ownership_epoch === undefined
396
+ ? {}
397
+ : { ownershipEpoch: () => (abi._tn_ownership_epoch as () => number)() }),
387
398
  engineReferences: (refs) =>
388
399
  scoped(() => {
389
400
  const handles = alloc(Math.max(1, refs.length) * HANDLE);
@@ -423,16 +434,25 @@ export function createWasmRuntime(abi: TnAbiModule): IBrowserRuntime {
423
434
  batch.status[i] = after.getFloat64(status + i * 8, true);
424
435
  });
425
436
  },
426
- readByte: (address) => abi.HEAPU8[address] as number,
427
- readWord: (address) => view().getUint32(address, true),
437
+ readByte: (address) => {
438
+ reach(address + 1);
439
+ return abi.HEAPU8[address] as number;
440
+ },
441
+ readWord: (address) => view(address + 4).getUint32(address, true),
428
442
  writeDouble: (address, value) => {
443
+ reach(address + 8);
429
444
  abi.HEAPF64[address / 8] = value;
430
445
  },
431
446
  writeByte: (address, value) => {
447
+ reach(address + 1);
432
448
  abi.HEAPU8[address] = value;
433
449
  },
434
- heapF64: () => abi.HEAPF64,
450
+ heapF64: (end) => {
451
+ reach(end);
452
+ return abi.HEAPF64;
453
+ },
435
454
  readDoubles: (address, count) => {
455
+ reach(address + count * 8);
436
456
  const at = address / 8;
437
457
  return count === 1
438
458
  ? (abi.HEAPF64[at] as number)
@@ -3,6 +3,7 @@
3
3
  // The `TN_*` console markers the perf tooling parses. Add the colon where a line is matched.
4
4
  export const CONSOLE_MARKER = {
5
5
  bridgeCensus: "TN_BRIDGE_CENSUS",
6
+ firstFrame: "TN_FIRST_FRAME",
6
7
  frameBudget: "TN_FRAME_BUDGET",
7
8
  frameHitch: "TN_FRAME_HITCH",
8
9
  hostGap: "TN_HOST_GAP",
@@ -79,6 +79,7 @@ export const WEB_FRAME_FIELD = {
79
79
  textureCompressionBc: 87,
80
80
  virtualShadowPendingLevels: 88,
81
81
  frameSnapshot: 89,
82
+ prepassDraws: 90,
82
83
  } as const;
83
84
 
84
85
  export type WebFrameField = (typeof WEB_FRAME_FIELD)[keyof typeof WEB_FRAME_FIELD];
@@ -41,6 +41,8 @@ interface IGeometry {
41
41
  getAttribute(name: string): unknown;
42
42
  }
43
43
 
44
+ const undefinedOnMissing = new WeakSet<object>();
45
+
44
46
  function defineGeometrySurface(
45
47
  BufferGeometry: Constructor,
46
48
  geometries: readonly Constructor[],
@@ -82,6 +84,23 @@ function defineGeometrySurface(
82
84
  ).map(({ start, count, materialIndex }) => ({ start, count, materialIndex }));
83
85
  },
84
86
  });
87
+ // three answers a missing attribute with undefined and the engine with null, so a game's
88
+ // `getAttribute(name) === undefined` (a sway material picking its geometry) misread every
89
+ // geometry as carrying it and the draw failed TN_NATIVE_ATTRIBUTE_MISSING. The engine may define
90
+ // it on a shared base, so the method each class resolves is wrapped on that class.
91
+ const read = (prototype as { getAttribute?: unknown }).getAttribute;
92
+ if (typeof read === "function" && !undefinedOnMissing.has(read)) {
93
+ const answer = function (this: unknown, name: string): unknown {
94
+ return (read as (this: unknown, name: string) => unknown).call(this, name) ?? undefined;
95
+ };
96
+ undefinedOnMissing.add(answer);
97
+ Object.defineProperty(prototype, "getAttribute", {
98
+ configurable: true,
99
+ enumerable: false,
100
+ value: answer,
101
+ writable: true,
102
+ });
103
+ }
85
104
  // Each geometry class carries its own `attributes` accessor, so every one gets the view.
86
105
  Object.defineProperty(prototype, "attributes", {
87
106
  configurable: true,