@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.
@@ -14,6 +14,16 @@ export interface IUpdateFrame {
14
14
  frameId: number;
15
15
  camera?: unknown;
16
16
  scene?: unknown;
17
+ renderer?: unknown;
18
+ }
19
+
20
+ /** What one sync is for: the draw's camera and root, the renderer's frame, and a dispatch's kernels (engine node ids). */
21
+ export interface ISyncFrame {
22
+ camera?: unknown;
23
+ scene?: unknown;
24
+ renderer?: unknown;
25
+ frameId?: number;
26
+ kernels?: readonly number[];
17
27
  }
18
28
 
19
29
  interface IUniformState {
@@ -28,22 +38,59 @@ interface IUniformState {
28
38
  ranFrame?: number;
29
39
  /** The lanes last written to the engine: an unchanged value is not written again. */
30
40
  lanes?: readonly number[];
41
+ /** True when sync() scans this uniform's value object every call (it could not be watched). */
42
+ scanned?: boolean;
31
43
  /** Reused extraction storage, never aliased with `lanes`: the sink reads it before it is refilled. */
32
44
  scratch?: number[];
33
45
  }
34
46
 
47
+ /** A watched value's hook back to scanning, called by a back end before it replaces the value's lanes. */
48
+ export const UNWATCH = Symbol.for("threenative.uniformUnwatch");
49
+
50
+ /** The lanes a watched value object (Color, VectorN) carries as plain fields. */
51
+ const WATCHED_LANES = ["x", "y", "z", "w", "r", "g", "b"] as const;
52
+
35
53
  function sameLanes(a: readonly number[] | undefined, b: readonly number[]): boolean {
36
54
  if (a === undefined || a.length !== b.length) return false;
37
55
  for (let i = 0; i < b.length; i++) if (!Object.is(a[i], b[i])) return false;
38
56
  return true;
39
57
  }
40
58
 
59
+ /** A three Matrix3 or Matrix4's elements (9 or 16 numbers), or undefined for any other value. */
60
+ export function matrixElements(value: unknown): ArrayLike<number> | undefined {
61
+ if (typeof value !== "object" || value === null) return undefined;
62
+ const elements = (value as { elements?: unknown }).elements;
63
+ if (
64
+ (Array.isArray(elements) || ArrayBuffer.isView(elements)) &&
65
+ ((elements as ArrayLike<number>).length === 16 || (elements as ArrayLike<number>).length === 9)
66
+ )
67
+ return elements as ArrayLike<number>;
68
+ return undefined;
69
+ }
70
+
71
+ /** "mat3" or "mat4" for a three Matrix3 or Matrix4, the type its uniform is made at; otherwise undefined. */
72
+ function matrixType(value: unknown): "mat3" | "mat4" | undefined {
73
+ if (typeof value !== "object" || value === null) return undefined;
74
+ const v = value as { isMatrix3?: unknown; isMatrix4?: unknown };
75
+ return v.isMatrix3 === true ? "mat3" : v.isMatrix4 === true ? "mat4" : undefined;
76
+ }
77
+
41
78
  /**
42
- * One float per lane: a number, a Color's r, g, b, or a VectorN's x, y, z, w. `out`, when given,
43
- * receives the lanes and is returned, so a uniform can refill one bounded scratch array per sync.
79
+ * One float per lane: a number, a Color's r, g, b, a VectorN's x, y, z, w, or a Matrix3/Matrix4's
80
+ * elements (column-major, as three stores them). `out`, when given, receives the lanes and is
81
+ * returned, so a uniform can refill one bounded scratch array per sync.
44
82
  */
45
83
  export function uniformLanes(value: unknown, out?: number[]): number[] {
84
+ // A Matrix3 or Matrix4: its column-major elements, the order the engine writes a matN uniform in.
85
+ const elements = matrixElements(value);
86
+ if (elements === undefined) return valueLanes(value, out ?? []);
46
87
  const lanes = out ?? [];
88
+ lanes.length = elements.length;
89
+ for (let i = 0; i < elements.length; i += 1) lanes[i] = elements[i] as number;
90
+ return lanes;
91
+ }
92
+
93
+ function valueLanes(value: unknown, lanes: number[]): number[] {
47
94
  if (typeof value === "number") {
48
95
  lanes.length = 1;
49
96
  lanes[0] = value;
@@ -67,7 +114,9 @@ export function uniformLanes(value: unknown, out?: number[]): number[] {
67
114
  return lanes;
68
115
  }
69
116
  }
70
- throw new TypeError(`TN_TSL_UNIFORM_VALUE: ${String(value)} is not a number, Color or vector`);
117
+ throw new TypeError(
118
+ `TN_TSL_UNIFORM_VALUE: ${String(value)} is not a number, Color, vector or Matrix3/Matrix4`,
119
+ );
71
120
  }
72
121
 
73
122
  function referenceValue(property: string, type: string, object: unknown): unknown {
@@ -99,11 +148,17 @@ function referenceValue(property: string, type: string, object: unknown): unknow
99
148
  * Wraps a back end's `uniform` so each uniform node it returns answers `.value` (an accessor on the
100
149
  * node itself: a V8 node has no prototype of its own to carry it) and three's update hooks. `setValues`
101
150
  * writes a node's lanes into the engine. `sync()` runs once per render: the update callbacks first,
102
- * then the edited objects' lanes, each written only when its lanes changed.
151
+ * then the edited objects' lanes, each written only when its lanes changed. With `setMany`, every
152
+ * write of one sync crosses as one call (node i takes `counts[i]` of the packed `lanes`, PRD-828);
153
+ * a `.value` set outside a sync still goes through `setValues` at once. `reads` (PRD-878) asks the engine which
154
+ * of the hooked nodes one draw or dispatch reads, as indices into `hooked`; undefined runs every hook, as a
155
+ * scene's render does.
103
156
  */
104
157
  export function liveUniforms<TNode extends object>(
105
158
  uniform: (value: unknown, type?: unknown) => TNode,
106
159
  setValues: (node: TNode, lanes: readonly number[]) => void,
160
+ setMany?: (nodes: readonly TNode[], counts: readonly number[], lanes: readonly number[]) => void,
161
+ reads?: (frame: ISyncFrame, hooked: readonly TNode[]) => ArrayLike<number> | undefined,
107
162
  ): {
108
163
  uniform: (value: unknown, type?: unknown) => TNode;
109
164
  uniformArray: (
@@ -111,7 +166,7 @@ export function liveUniforms<TNode extends object>(
111
166
  type?: string,
112
167
  ) => { array: unknown[]; element(index: unknown): TNode };
113
168
  reference(property: string, type: string, object?: unknown): TNode;
114
- sync(frame?: { camera?: unknown; scene?: unknown; frameId?: number }): void;
169
+ sync(frame?: ISyncFrame): void;
115
170
  } {
116
171
  const debug = debugRequested();
117
172
  const host = globalThis as {
@@ -140,12 +195,127 @@ export function liveUniforms<TNode extends object>(
140
195
  };
141
196
  };
142
197
  const states = new WeakMap<object, IUniformState>();
198
+ // Object values sync() must scan every call: a matrix (its elements edit in place) or an object whose lanes it
199
+ // cannot watch (accessors, a frozen or native object).
200
+ // A hook's node or an object-valued node (`uniform(camera.matrixWorld)`) is chained into a material and dropped,
201
+ // so the wrapper is all JS holds, and a collected wrapper silently ended its updates (a stale eye in a post
202
+ // pass). An object-valued node is therefore pinned through the value the game owns, not forever: it lives as long
203
+ // as the object it reads, so a per-material matrix is released with that matrix instead of growing a page-wide set
204
+ // every sync walks. ponytail: the value is the closest owner this module sees; the engine release of such a node
205
+ // waits too.
143
206
  const objects = new Set<WeakRef<TNode>>();
144
- // Strong: a hook's node is chained into a material and dropped, so the wrapper is all JS holds, and a
145
- // collected wrapper silently ended its updates. ponytail: kept for the page's life; the engine release
146
- // of such a node waits too. Release with the owning material if a game builds hooked uniforms in a loop.
147
- const updating = new Set<TNode>();
207
+ const pinned = new WeakMap<object, TNode[]>();
208
+ // The node lives exactly as long as `value` does, so a wrapper the game dropped is released with the object it
209
+ // reads.
210
+ const own = (node: TNode, value: object) => {
211
+ const owners = pinned.get(value);
212
+ if (owners === undefined) pinned.set(value, [node]);
213
+ else owners.push(node);
214
+ };
215
+ // A plain Color or VectorN value is watched instead: its lanes become accessors that mark the uniforms reading it
216
+ // dirty, so a sync reads only what was edited since the last one, however many uniforms the app holds. An edit
217
+ // between two renders of one frame still reaches the second (FluidVolume edits uniforms between its passes).
218
+ const watchers = new WeakMap<object, WeakRef<TNode>[]>();
219
+ // Weak, as `objects` is: the value owns the node (own), and an entry whose node went with its value is dropped by
220
+ // the sync that finds it gone.
221
+ const dirty = new Set<WeakRef<TNode>>();
222
+ const watch = (node: TNode, value: object): boolean => {
223
+ if (matrixType(value) !== undefined) return false;
224
+ const known = watchers.get(value);
225
+ if (known !== undefined) {
226
+ known.push(new WeakRef(node));
227
+ own(node, value);
228
+ return true;
229
+ }
230
+ const keys = WATCHED_LANES.filter((key) => Object.hasOwn(value, key));
231
+ const plain = (key: string) => {
232
+ const field = Object.getOwnPropertyDescriptor(value, key);
233
+ return (
234
+ field !== undefined &&
235
+ "value" in field &&
236
+ field.writable === true &&
237
+ field.configurable === true
238
+ );
239
+ };
240
+ if (keys.length === 0 || !keys.every(plain)) return false;
241
+ const readers = [new WeakRef(node)];
242
+ watchers.set(value, readers);
243
+ own(node, value);
244
+ // The Wasm back end gives a value it adopts (promote) engine-backed lanes: it calls this first, and the
245
+ // uniforms reading it go back to being scanned.
246
+ Object.defineProperty(value, UNWATCH, {
247
+ configurable: true,
248
+ value: () => {
249
+ watchers.delete(value);
250
+ for (const reader of readers) {
251
+ const target = reader.deref();
252
+ const state = target === undefined ? undefined : states.get(target);
253
+ if (target === undefined || state === undefined || state.scanned === true) continue;
254
+ state.scanned = true;
255
+ objects.add(new WeakRef(target));
256
+ own(target, value);
257
+ }
258
+ },
259
+ });
260
+ for (const key of keys) {
261
+ let lane = (value as Record<string, unknown>)[key];
262
+ Object.defineProperty(value, key, {
263
+ configurable: true,
264
+ enumerable: true,
265
+ get: () => lane,
266
+ set: (next: unknown) => {
267
+ if (Object.is(next, lane)) return;
268
+ lane = next;
269
+ for (const reader of readers) {
270
+ const target = reader.deref();
271
+ if (target !== undefined) dirty.add(new WeakRef(target));
272
+ }
273
+ },
274
+ });
275
+ }
276
+ return true;
277
+ };
278
+ const track = (node: TNode, state: IUniformState, value: unknown) => {
279
+ if (typeof value !== "object" || value === null) return;
280
+ dirty.add(new WeakRef(node)); // its first sync writes it, as a scan did
281
+ if (state.scanned !== true && !watch(node, value)) {
282
+ state.scanned = true;
283
+ objects.add(new WeakRef(node));
284
+ own(node, value);
285
+ }
286
+ };
287
+ // Every node with an update callback, in the order its first callback was set (the engine's `reads` indexes it).
288
+ const updating: TNode[] = [];
289
+ // The render hooks alone: a nested render of a frame whose frame hooks all ran walks only these.
290
+ const renders = new Set<TNode>();
291
+ let hookedFrame: number | undefined;
148
292
  let frameId = 0;
293
+ // One sync's writes, sent as one crossing at its end (PRD-828); a write outside a sync goes at once.
294
+ let batching = false;
295
+ const pendingNodes: TNode[] = [];
296
+ const pendingCounts: number[] = [];
297
+ const pendingLanes: number[] = [];
298
+ const clear = () => {
299
+ pendingNodes.length = 0;
300
+ pendingCounts.length = 0;
301
+ pendingLanes.length = 0;
302
+ };
303
+ // A batch that was refused or never sent (a hook threw) counts as not uploaded: the next sync writes each
304
+ // node's current value again, so a `.value` set in between is not overwritten by a stale lane.
305
+ const requeue = () => {
306
+ for (const node of pendingNodes) {
307
+ const state = states.get(node);
308
+ if (state !== undefined) state.lanes = undefined;
309
+ dirty.add(new WeakRef(node));
310
+ }
311
+ clear();
312
+ };
313
+ const flush = () => {
314
+ if (pendingNodes.length === 0 || setMany === undefined) return;
315
+ setMany(pendingNodes, pendingCounts, pendingLanes);
316
+ if (debug) count("uniformWriteCrossings");
317
+ clear();
318
+ };
149
319
  // An unchanged value is not written again: an edited Color or vector is found by its lanes, and a
150
320
  // hook that returns the same number every render costs no engine write.
151
321
  const write = (node: TNode, state: IUniformState, lanes: readonly number[]) => {
@@ -163,27 +333,68 @@ export function liveUniforms<TNode extends object>(
163
333
  // A snapshot for the sink and the state: `lanes` is the state's scratch, refilled by the next
164
334
  // extraction, so a sink that keeps its argument must not see later values.
165
335
  const written = lanes.slice();
166
- setValues(node, written);
336
+ if (batching) {
337
+ pendingNodes.push(node);
338
+ pendingCounts.push(written.length);
339
+ for (const lane of written) pendingLanes.push(lane);
340
+ } else {
341
+ setValues(node, written);
342
+ if (debug) count("uniformWriteCrossings");
343
+ }
167
344
  if (debug) {
168
345
  count("uniformWrites");
169
346
  count("uniformLaneWrites", lanes.length);
170
347
  }
171
348
  state.lanes = written;
172
349
  };
350
+ // One sync's frame: one object, refilled each sync, as three's NodeFrame is one object.
351
+ const frame: IUpdateFrame = { frameId: 0 };
352
+ // Runs one node's update callback for this sync and writes what it returns.
353
+ const updateNode = (node: TNode, rendererFrame: number | undefined): void => {
354
+ const state = states.get(node);
355
+ if (state?.update === undefined) return;
356
+ if (state.updateType === "frame" && rendererFrame !== undefined) {
357
+ if (state.ranFrame === rendererFrame) return;
358
+ state.ranFrame = rendererFrame;
359
+ }
360
+ let next: unknown;
361
+ if (debug) {
362
+ const callbackStart = performance.now();
363
+ count(state.updateType === "frame" ? "uniformFrameCallbacks" : "uniformRenderCallbacks");
364
+ try {
365
+ next = state.update(frame);
366
+ } finally {
367
+ const elapsed = performance.now() - callbackStart;
368
+ count("uniformCallbackMs", elapsed);
369
+ if (state.debugSource !== undefined)
370
+ count(`uniformCallback:${state.debugSource}Ms`, elapsed, state.debugSource);
371
+ }
372
+ } else next = state.update(frame);
373
+ if (next !== undefined) (node as { value: unknown }).value = next;
374
+ };
173
375
  const live = {
174
376
  uniform(value: unknown, type?: unknown): TNode {
175
- const node = type === undefined ? uniform(value) : uniform(value, type);
377
+ // A matrix uniform is made by its type name at identity, then given the matrix's elements.
378
+ const matrix = matrixType(value);
379
+ const node =
380
+ matrix !== undefined
381
+ ? uniform(matrix)
382
+ : type === undefined
383
+ ? uniform(value)
384
+ : uniform(value, type);
176
385
  const state: IUniformState = { value, scratch: [] };
177
386
  states.set(node, state);
387
+ if (matrix !== undefined) write(node, state, uniformLanes(value, state.scratch));
178
388
  Object.defineProperty(node, "value", {
179
389
  configurable: true,
180
390
  get: () => state.value,
181
391
  set: (next: unknown) => {
182
392
  write(node, state, uniformLanes(next, state.scratch));
393
+ if (next !== state.value) track(node, state, next);
183
394
  state.value = next;
184
395
  },
185
396
  });
186
- if (typeof value === "object" && value !== null) objects.add(new WeakRef(node));
397
+ track(node, state, value);
187
398
  // three's UniformNode.onUpdate: the callback runs with the node as `this` and its result,
188
399
  // unless undefined, becomes the value. RENDER runs once per sync (one per render call); FRAME
189
400
  // runs once per renderer frame. A post chain renders about ten passes a frame (Lantern Vale), and
@@ -196,7 +407,10 @@ export function liveUniforms<TNode extends object>(
196
407
  throw new Error(
197
408
  `TN_TSL_UPDATE_UNSUPPORTED: a native uniform updates per frame or render, not per '${updateType}'`,
198
409
  );
199
- if (state.update === undefined) updating.add(node);
410
+ if (state.update === undefined) updating.push(node);
411
+ if (updateType === "render") renders.add(node);
412
+ else renders.delete(node);
413
+ hookedFrame = undefined; // a frame hook added mid-frame runs at the next render
200
414
  state.update = (frame) => callback.call(node, frame, node);
201
415
  state.updateType = updateType;
202
416
  if (debug) {
@@ -239,70 +453,82 @@ export function liveUniforms<TNode extends object>(
239
453
  },
240
454
  /**
241
455
  * three's uniformArray(values): `element(i)` at a constant index is a uniform that reads
242
- * `values[i]` before each render, as UniformArrayNode copies its array per update. ponytail: a
243
- * node index needs an engine uniform array; it is refused by name.
456
+ * `values[i]` before each render, as UniformArrayNode copies its array per update. A node index
457
+ * (a Loop's `i`) selects among those uniforms. ponytail: one select per element on each read; an
458
+ * engine uniform array when a game indexes long arrays.
244
459
  */
245
460
  uniformArray(values: unknown[]) {
246
461
  if (!Array.isArray(values))
247
462
  throw new TypeError("TN_TSL_UNIFORM_ARRAY: uniformArray takes an array");
248
463
  const elements = new Map<number, TNode>();
249
- return {
250
- array: values,
251
- element(index: unknown): TNode {
252
- if (
253
- typeof index !== "number" ||
254
- !Number.isInteger(index) ||
255
- index < 0 ||
256
- index >= values.length
257
- )
258
- throw new RangeError(
259
- `TN_TSL_UNIFORM_ARRAY: element needs a constant index in [0, ${values.length})`,
260
- );
261
- let node = elements.get(index);
262
- if (node === undefined) {
263
- node = live.uniform(values[index]);
264
- // quality-allow: TNode does not expose internal onRenderUpdate hook from WebGPU node system.
265
- const updatable = node as unknown as {
266
- onRenderUpdate: (callback: () => unknown) => void;
267
- };
268
- updatable.onRenderUpdate(() => values[index]);
269
- elements.set(index, node);
270
- }
271
- return node;
272
- },
464
+ type IIndexNode = { equal(k: number): { select(a: TNode, b: TNode): TNode } };
465
+ const element = (index: unknown): TNode => {
466
+ if (
467
+ typeof index === "object" &&
468
+ index !== null &&
469
+ typeof (index as Partial<IIndexNode>).equal === "function" &&
470
+ values.length > 0
471
+ ) {
472
+ let picked = element(values.length - 1);
473
+ for (let k = values.length - 2; k >= 0; k--)
474
+ picked = (index as IIndexNode).equal(k).select(element(k), picked);
475
+ return picked;
476
+ }
477
+ if (
478
+ typeof index !== "number" ||
479
+ !Number.isInteger(index) ||
480
+ index < 0 ||
481
+ index >= values.length
482
+ )
483
+ throw new RangeError(
484
+ `TN_TSL_UNIFORM_ARRAY: element needs a constant index in [0, ${values.length})`,
485
+ );
486
+ let node = elements.get(index);
487
+ if (node === undefined) {
488
+ node = live.uniform(values[index]);
489
+ // quality-allow: TNode does not expose internal onRenderUpdate hook from WebGPU node system.
490
+ const updatable = node as unknown as {
491
+ onRenderUpdate: (callback: () => unknown) => void;
492
+ };
493
+ updatable.onRenderUpdate(() => values[index]);
494
+ elements.set(index, node);
495
+ }
496
+ return node;
273
497
  };
498
+ return { array: values, element };
274
499
  },
275
- sync(extra?: { camera?: unknown; scene?: unknown; frameId?: number }) {
500
+ sync(extra?: ISyncFrame) {
276
501
  // `extra.frameId` is the renderer's frame: every render, target draw and compute of one frame
277
502
  // shares it. The callbacks see this module's own counter, as three's NodeFrame counts renders.
278
503
  const started = debug ? performance.now() : 0;
279
504
  if (debug) count("uniformSyncCalls");
505
+ const outer = !batching;
506
+ batching = setMany !== undefined;
280
507
  try {
281
508
  const rendererFrame = extra?.frameId;
282
- const frame: IUpdateFrame = { ...extra, frameId: ++frameId };
283
- for (const node of updating) {
284
- const state = states.get(node);
285
- if (state?.update === undefined) continue;
286
- if (state.updateType === "frame" && rendererFrame !== undefined) {
287
- if (state.ranFrame === rendererFrame) continue;
288
- state.ranFrame = rendererFrame;
509
+ frame.frameId = ++frameId;
510
+ frame.camera = extra?.camera;
511
+ frame.scene = extra?.scene;
512
+ frame.renderer = extra?.renderer;
513
+ // A nested render of a frame whose frame hooks already ran skips them without walking them.
514
+ const nested = rendererFrame !== undefined && rendererFrame === hookedFrame;
515
+ // A draw of one mesh or a dispatch runs only the hooks its graphs read (the engine answers which).
516
+ const picked = extra === undefined ? undefined : reads?.(extra, updating);
517
+ if (picked !== undefined)
518
+ for (let index = 0; index < picked.length; index += 1)
519
+ updateNode(updating[picked[index] as number] as TNode, rendererFrame);
520
+ else for (const node of nested ? renders : updating) updateNode(node, rendererFrame);
521
+ // Only once every hook returned: one that threw leaves later frame hooks to the next render. A picked
522
+ // sync ran some hooks only, so it does not stand for the frame's.
523
+ if (picked === undefined) hookedFrame = rendererFrame;
524
+ // Deleted only once written: a sink that throws leaves the rest to retry at the next sync.
525
+ for (const ref of dirty) {
526
+ const node = ref.deref();
527
+ if (node !== undefined) {
528
+ const state = states.get(node);
529
+ if (state !== undefined) write(node, state, uniformLanes(state.value, state.scratch));
289
530
  }
290
- let next: unknown;
291
- if (debug) {
292
- const callbackStart = performance.now();
293
- count(
294
- state.updateType === "frame" ? "uniformFrameCallbacks" : "uniformRenderCallbacks",
295
- );
296
- try {
297
- next = state.update(frame);
298
- } finally {
299
- const elapsed = performance.now() - callbackStart;
300
- count("uniformCallbackMs", elapsed);
301
- if (state.debugSource !== undefined)
302
- count(`uniformCallback:${state.debugSource}Ms`, elapsed, state.debugSource);
303
- }
304
- } else next = state.update(frame);
305
- if (next !== undefined) (node as { value: unknown }).value = next;
531
+ dirty.delete(ref);
306
532
  }
307
533
  for (const ref of objects) {
308
534
  const node = ref.deref();
@@ -313,7 +539,12 @@ export function liveUniforms<TNode extends object>(
313
539
  const state = states.get(node);
314
540
  if (state !== undefined) write(node, state, uniformLanes(state.value, state.scratch));
315
541
  }
542
+ flush();
316
543
  } finally {
544
+ if (outer) {
545
+ batching = false;
546
+ requeue();
547
+ }
317
548
  if (debug) count("uniformSyncMs", performance.now() - started);
318
549
  }
319
550
  },
@@ -22,6 +22,22 @@ const MUTATORS = new Set([
22
22
  "copyWithin",
23
23
  ]);
24
24
 
25
+ const UPLOAD_RANGES = Symbol("tnUploadRanges");
26
+
27
+ /**
28
+ * The `{ start, count }` element ranges the attribute's next upload sends, or none for the whole array,
29
+ * as three's `WebGPUAttributeUtils.updateAttribute` reads `updateRanges`. Malformed engine JSON throws.
30
+ */
31
+ export function uploadRanges(attribute: object): readonly IRange[] {
32
+ const read = Reflect.get(attribute, UPLOAD_RANGES) as (() => string) | undefined;
33
+ const json = read?.call(attribute) ?? "[]";
34
+ if (json === "[]") return [];
35
+ const ranges = JSON.parse(json) as unknown;
36
+ if (!Array.isArray(ranges))
37
+ throw new TypeError(`TN_NATIVE_UNSUPPORTED updateRanges: expected a JSON array, got ${json}`);
38
+ return ranges as IRange[];
39
+ }
40
+
25
41
  export function withUpdateRanges(prototype: object): void {
26
42
  const read = Object.getOwnPropertyDescriptor(prototype, "updateRanges")?.get;
27
43
  const proto = prototype as {
@@ -43,6 +59,13 @@ export function withUpdateRanges(prototype: object): void {
43
59
  emptied.delete(this);
44
60
  return result;
45
61
  };
62
+ // The ranges the engine's next upload sends, as one getter read: no proxy, no parse when empty.
63
+ Object.defineProperty(prototype, UPLOAD_RANGES, {
64
+ configurable: true,
65
+ value(this: object): string {
66
+ return emptied.has(this) ? "[]" : String(read.call(this));
67
+ },
68
+ });
46
69
  Object.defineProperty(prototype, "updateRanges", {
47
70
  configurable: true,
48
71
  get(this: object) {
@@ -50,11 +73,14 @@ export function withUpdateRanges(prototype: object): void {
50
73
  if (cached !== undefined) return cached;
51
74
  const target: IRange[] = [];
52
75
  let snapshot: unknown;
76
+ // The records as the engine last had them: a record edited in place differs from it.
77
+ let mirror = "[]";
53
78
  const refresh = () => {
54
79
  const current = emptied.delete(this) ? "[]" : (read.call(this) as unknown);
55
80
  if (current === snapshot) return;
56
81
  target.splice(0, target.length, ...(JSON.parse(String(current)) as IRange[]));
57
82
  snapshot = current;
83
+ mirror = JSON.stringify(target);
58
84
  };
59
85
  const validate = (ranges: readonly IRange[]) => {
60
86
  for (const range of ranges)
@@ -74,6 +100,7 @@ export function withUpdateRanges(prototype: object): void {
74
100
  clear.call(this);
75
101
  for (const range of target) add.call(this, range.start, range.count);
76
102
  snapshot = undefined;
103
+ mirror = JSON.stringify(target);
77
104
  };
78
105
  const guarded = <T>(change: () => T): T => {
79
106
  refresh();
@@ -94,7 +121,9 @@ export function withUpdateRanges(prototype: object): void {
94
121
  refresh();
95
122
  for (const range of ranges) add.call(owner, range.start, range.count);
96
123
  snapshot = undefined;
97
- return target.push(...ranges);
124
+ const length = target.push(...ranges);
125
+ mirror = JSON.stringify(target);
126
+ return length;
98
127
  };
99
128
  if (typeof key === "string" && MUTATORS.has(key))
100
129
  return (...args: unknown[]) =>
@@ -126,6 +155,26 @@ export function withUpdateRanges(prototype: object): void {
126
155
  return Reflect.getOwnPropertyDescriptor(array, key);
127
156
  },
128
157
  });
158
+ // A record is an ordinary object, as three's is, so an edit in place (`last.count = n`, core's
159
+ // addRange) reaches the engine when needsUpdate publishes it, as the V8 adapter does (PRD-857).
160
+ let holder: object | null = Object.getPrototypeOf(this) as object | null;
161
+ let publish: PropertyDescriptor | undefined;
162
+ while (holder !== null && publish === undefined) {
163
+ publish = Object.getOwnPropertyDescriptor(holder, "needsUpdate");
164
+ holder = Object.getPrototypeOf(holder) as object | null;
165
+ }
166
+ if (publish?.set !== undefined) {
167
+ const set = publish.set;
168
+ const get = publish.get;
169
+ Object.defineProperty(this, "needsUpdate", {
170
+ configurable: true,
171
+ ...(get === undefined ? {} : { get: () => get.call(owner) }),
172
+ set(value: unknown) {
173
+ if (value && JSON.stringify(target) !== mirror) write();
174
+ set.call(owner, value);
175
+ },
176
+ });
177
+ }
129
178
  proxies.set(this, proxy);
130
179
  return proxy;
131
180
  },