@threenative/core 0.3.15 → 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.
@@ -35,3 +35,32 @@ export function copyMatrixWorld(object: Object3D, target: Matrix4): boolean {
35
35
  hook.call(object, target);
36
36
  return true;
37
37
  }
38
+
39
+ /**
40
+ * PRD-898 J4: the owned engine's posed-bounds call. `root.__tnSphereBounds(objects, radii)` runs
41
+ * `root.updateWorldMatrix(true, true)` and answers `[minX, minY, minZ, maxX, maxY, maxZ]` over a sphere
42
+ * of `radii[i]` at each object's world origin, in one crossing instead of one per bone. The engine
43
+ * defines it in `runtime-native/src/engine/abi/bindings_scene.cpp`; plain three.js has none.
44
+ */
45
+ export const SPHERE_BOUNDS_HOOK = "__tnSphereBounds";
46
+
47
+ /** The spheres are handed to the engine once; the per-frame call then takes no arguments. */
48
+ export const SPHERE_BOUNDS_ATTACH_HOOK = "__tnSphereBoundsAttach";
49
+
50
+ interface ISphereBoundsHooks {
51
+ readonly attach: (objects: readonly Object3D[], radii: readonly number[]) => void;
52
+ readonly bounds: () => readonly number[];
53
+ }
54
+
55
+ /** The engine's sphere-bounds calls on `root`, or undefined on plain three.js. */
56
+ export function sphereBoundsHook(root: Object3D): ISphereBoundsHooks | undefined {
57
+ const carrier = root as Object3D & Record<string, unknown>;
58
+ const attach = carrier[SPHERE_BOUNDS_ATTACH_HOOK];
59
+ const bounds = carrier[SPHERE_BOUNDS_HOOK];
60
+ return typeof attach === "function" && typeof bounds === "function"
61
+ ? {
62
+ attach: attach as ISphereBoundsHooks["attach"],
63
+ bounds: bounds as ISphereBoundsHooks["bounds"],
64
+ }
65
+ : undefined;
66
+ }
package/src/grounding.ts CHANGED
@@ -47,23 +47,25 @@ export class GroundSnap {
47
47
  throw new Error("GroundSnap dt must be finite and non-negative.");
48
48
  validateMaxRate(this.maxRate);
49
49
 
50
- const before = posedBounds(this.model, this.meshes);
51
- if (!Number.isFinite(before.min[1])) {
50
+ const lowest = posedBounds(this.model, this.meshes).min[1];
51
+ if (!Number.isFinite(lowest)) {
52
52
  this.clearance = null;
53
53
  return;
54
54
  }
55
55
 
56
- const desired = surfaceY - before.min[1];
56
+ const desired = surfaceY - lowest;
57
57
  const correction =
58
58
  this.maxRate === undefined || desired > 0 ? desired : Math.max(desired, -this.maxRate * dt);
59
- if (this.enabled) this.applyWorldCorrection(group, correction);
59
+ const moved = this.enabled && correction !== 0;
60
+ if (moved) this.applyWorldCorrection(group, correction);
60
61
 
61
- // Re-read after the move. The group may be under a scaled or rotated parent, so the local
62
- // correction is not always one world metre for one local metre. posedBounds forces its own
63
- // whole-subtree matrix pass, so no explicit update here — that was a second full pass per
64
- // grounded character per frame buying nothing the measurement below does not redo.
65
- const after = posedBounds(this.model, this.meshes);
66
- this.clearance = after.min[1] - surfaceY;
62
+ // PRD-898 J4: the correction is a world-space translation of `group`, so when `group` carries the
63
+ // model the lowest point moved by exactly `correction` and a second measurement (a whole-subtree
64
+ // matrix pass per grounded character per frame) would only re-read it. A `group` that does not
65
+ // carry the model is measured again, as before.
66
+ if (!moved) this.clearance = lowest - surfaceY;
67
+ else if (carries(group, this.model)) this.clearance = lowest + correction - surfaceY;
68
+ else this.clearance = posedBounds(this.model, this.meshes).min[1] - surfaceY;
67
69
  }
68
70
 
69
71
  private applyWorldCorrection(group: Object3D, correction: number): void {
@@ -94,6 +96,13 @@ export class GroundSnap {
94
96
  }
95
97
  }
96
98
 
99
+ /** Whether `group` is `model` or one of its ancestors, so moving it moves the model. */
100
+ function carries(group: Object3D, model: Object3D): boolean {
101
+ for (let node: Object3D | null = model; node !== null; node = node.parent)
102
+ if (node === group) return true;
103
+ return false;
104
+ }
105
+
97
106
  function validateMaxRate(maxRate: number | undefined): void {
98
107
  if (maxRate !== undefined && (!Number.isFinite(maxRate) || maxRate < 0)) {
99
108
  throw new Error("GroundSnap maxRate must be finite and non-negative.");
package/src/hot.ts CHANGED
@@ -131,6 +131,23 @@ function diagnostics<TState extends Record<string, unknown>, TPhysics>(
131
131
  physics: typeof physics?.numBodies === "function" ? physics.numBodies() : null,
132
132
  };
133
133
  }
134
+ /**
135
+ * Name the class and the shape to store: an agent told only "plain objects" rewrites the wrong thing
136
+ * (hosted Studio, 2026-11-17: a Vector3 in state reloaded the page on every edit).
137
+ */
138
+ function notPlain(value: object, prototype: object, path: string): Error {
139
+ const named = (prototype as { constructor?: { name?: unknown } }).constructor?.name;
140
+ const name = typeof named === "string" && named.length > 0 ? named : "class instance";
141
+ // three keeps some fields private (`Quaternion._x`): the shape to store is the public name.
142
+ const keys = Object.keys(value).map((key) => key.replace(/^_/u, ""));
143
+ const shape =
144
+ keys.length > 0 && keys.length <= 6
145
+ ? `{ ${keys.join(", ")} } as a plain object`
146
+ : "its data as plain values";
147
+ return new Error(
148
+ `Hot reload state ${path} must contain only plain objects: it is a ${name}. Store ${shape} and rebuild the ${name} where the code needs it.`,
149
+ );
150
+ }
134
151
  function visitPortable(value: unknown, path: string, ancestors: Set<object>): void {
135
152
  if (value === null) return;
136
153
  if (typeof value === "string" || typeof value === "boolean") return;
@@ -149,8 +166,7 @@ function visitPortable(value: unknown, path: string, ancestors: Set<object>): vo
149
166
  return;
150
167
  }
151
168
  const prototype = Object.getPrototypeOf(value);
152
- if (prototype !== Object.prototype && prototype !== null)
153
- throw new Error(`Hot reload state ${path} must contain only plain objects.`);
169
+ if (prototype !== Object.prototype && prototype !== null) throw notPlain(value, prototype, path);
154
170
  ancestors.add(value);
155
171
  for (const key of Object.keys(value))
156
172
  visitPortable((value as Record<string, unknown>)[key], `${path}.${key}`, ancestors);
package/src/index.ts CHANGED
@@ -1574,7 +1574,7 @@ export type {
1574
1574
  * @constraint call `update(follow)` once per rendered frame
1575
1575
  * @constraint `place` runs once per candidate per tile build: return false for paths and clearings
1576
1576
  * @constraint rotating or scaling the field is not supported; translating it is
1577
- * @requires npm i -D @threenative/procedural-vegetation for the bake these instances come from
1577
+ * @requires npm i -D @threenative/procedural-environment for the bake these instances come from
1578
1578
  * @example
1579
1579
  * const floor = new ScatterField3D({ parts: [{ lods, material }], getHeight, density: 0.05, place });
1580
1580
  * ctx.add(floor);
@@ -11,6 +11,7 @@ import {
11
11
  DISCRETE_LOD_DEFAULT_HYSTERESIS,
12
12
  type IModelLodController,
13
13
  biasedLodDistance,
14
+ lodBias,
14
15
  lodChainOf,
15
16
  registerModelLodController,
16
17
  selectLodFor,
@@ -155,6 +156,24 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
155
156
  const sphere = new Sphere();
156
157
  let children: InstancedMesh[] = [];
157
158
  let triangles = 0;
159
+ // PRD-898 J3: on the owned engine the per-instance sort below is one call a frame
160
+ // (`lod::selectInstancedLods`), handed the partitions once, instead of three crossings per instance.
161
+ const engine = instancedLodHooks(mesh);
162
+ let attached = false;
163
+ function attachEngine(hooks: IInstancedLodHooks): void {
164
+ const authored = options.lods !== undefined;
165
+ hooks.attach.call(
166
+ mesh,
167
+ children,
168
+ Array.from(partitionOf),
169
+ authored ? distances : [],
170
+ [local.center.x, local.center.y, local.center.z, local.radius],
171
+ authored ? null : [...(chain?.errors ?? [])],
172
+ budget,
173
+ hysteresis,
174
+ );
175
+ attached = true;
176
+ }
158
177
  function ensureChildren(): void {
159
178
  if (children.length > 0) return;
160
179
  children = groups.flatMap((indices, partition) =>
@@ -186,6 +205,11 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
186
205
  },
187
206
  update(camera: Camera, viewportHeight: number): void {
188
207
  ensureChildren();
208
+ if (engine !== undefined) {
209
+ if (!attached) attachEngine(engine);
210
+ triangles = engine.update.call(mesh, camera, viewportHeight, lodBias());
211
+ return;
212
+ }
189
213
  triangles = 0;
190
214
  mesh.updateWorldMatrix(true, false);
191
215
  camera.getWorldPosition(cameraPosition);
@@ -258,6 +282,7 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
258
282
  child.dispose();
259
283
  }
260
284
  children = [];
285
+ attached = false;
261
286
  mesh.geometry = base;
262
287
  triangles = 0;
263
288
  },
@@ -276,3 +301,32 @@ export function attachInstancedLod(mesh: InstancedMesh, options: IInstancedLodOp
276
301
  ensureChildren();
277
302
  mesh.addEventListener("dispose", () => controller.release());
278
303
  }
304
+
305
+ interface IInstancedLodHooks {
306
+ readonly attach: (
307
+ children: readonly InstancedMesh[],
308
+ partitionOf: readonly number[],
309
+ distances: readonly number[],
310
+ local: readonly number[],
311
+ chainErrors: readonly number[] | null,
312
+ budget: number,
313
+ hysteresis: number,
314
+ ) => void;
315
+ readonly update: (camera: Camera, viewportHeight: number, bias: number) => number;
316
+ }
317
+
318
+ /** The owned engine's instanced LOD calls (abi/bindings_scene.cpp), or undefined on plain three.js. */
319
+ function instancedLodHooks(mesh: InstancedMesh): IInstancedLodHooks | undefined {
320
+ const carrier = mesh as InstancedMesh & {
321
+ readonly __tnInstancedLodAttach?: unknown;
322
+ readonly __tnInstancedLodUpdate?: unknown;
323
+ };
324
+ const attach = carrier.__tnInstancedLodAttach;
325
+ const update = carrier.__tnInstancedLodUpdate;
326
+ return typeof attach === "function" && typeof update === "function"
327
+ ? {
328
+ attach: attach as IInstancedLodHooks["attach"],
329
+ update: update as IInstancedLodHooks["update"],
330
+ }
331
+ : undefined;
332
+ }
package/src/model-lod.ts CHANGED
@@ -404,6 +404,35 @@ class ModelLod {
404
404
  return this.#chain.base;
405
405
  }
406
406
 
407
+ /** PRD-898 J2: whether the engine's batched selection can run this one (the join authority cannot). */
408
+ get batchable(): boolean {
409
+ return this.#rung === undefined || !this.#authority;
410
+ }
411
+
412
+ #attached = false;
413
+
414
+ /** The mesh for `__tnModelLodSelect`, its chain handed to the engine on first use. */
415
+ engineMesh(): Mesh {
416
+ if (!this.#attached) {
417
+ const { center, radius } = this.#chain.sphere;
418
+ (this.#mesh as Mesh & IModelLodEngineMesh).__tnModelLodAttach(
419
+ [...this.#chain.errors],
420
+ [center.x, center.y, center.z, radius],
421
+ this.#policy.maxPixelError,
422
+ this.#policy.hysteresis,
423
+ this.#current,
424
+ );
425
+ this.#attached = true;
426
+ }
427
+ return this.#mesh;
428
+ }
429
+
430
+ /** The level the engine's batched selection chose. */
431
+ applyLevel(index: number): void {
432
+ this.#current = index;
433
+ this.#mesh.geometry = this.#chain.levels[index] as BufferGeometry;
434
+ }
435
+
407
436
  get triangles(): number {
408
437
  // With a joined rung active, the authored primitives draw nothing and the proxy draws the
409
438
  // collapse: the authority reports the rung's triangles, every hidden sibling reports zero.
@@ -501,6 +530,23 @@ class ModelLod {
501
530
  }
502
531
  }
503
532
 
533
+ /** The owned engine's ModelLod calls (abi/bindings_scene.cpp), absent on plain three.js. */
534
+ interface IModelLodEngineMesh {
535
+ __tnModelLodAttach(
536
+ errors: readonly number[],
537
+ local: readonly number[],
538
+ maxPixelError: number,
539
+ hysteresis: number,
540
+ current: number,
541
+ ): void;
542
+ }
543
+
544
+ type ModelLodSelect = (viewportHeight: number, bias: number) => readonly number[];
545
+
546
+ interface IModelLodEngineSet {
547
+ __tnModelLodMeshes(meshes: readonly Mesh[]): void;
548
+ }
549
+
504
550
  /** Resolved runtime policy the loader stamps onto a controller, from the manifest. */
505
551
  export interface IModelLodPolicy {
506
552
  readonly hysteresis: number;
@@ -1416,6 +1462,29 @@ function trackRoot(root: IGraphNode): ITrackedRoot {
1416
1462
  *
1417
1463
  * @returns triangles the managed meshes will submit this frame.
1418
1464
  */
1465
+ /** The batched set the engine holds (`__tnModelLodMeshes`), resent only when it changes. */
1466
+ let engineBatch: readonly ModelLod[] = [];
1467
+
1468
+ /** One engine call selects every batched ModelLod; only the changed levels come back. */
1469
+ function selectBatched(
1470
+ select: ModelLodSelect,
1471
+ camera: Camera,
1472
+ batched: readonly ModelLod[],
1473
+ viewportHeight: number,
1474
+ ): void {
1475
+ if (
1476
+ batched.length !== engineBatch.length ||
1477
+ batched.some((entry, i) => entry !== engineBatch[i])
1478
+ ) {
1479
+ const meshes = batched.map((entry) => entry.engineMesh());
1480
+ (camera as Camera & IModelLodEngineSet).__tnModelLodMeshes(meshes);
1481
+ engineBatch = batched;
1482
+ }
1483
+ const changed = select.call(camera, viewportHeight, lodBias());
1484
+ for (let i = 0; i < changed.length; i += 2)
1485
+ (batched[changed[i] as number] as ModelLod).applyLevel(changed[i + 1] as number);
1486
+ }
1487
+
1419
1488
  export function updateModelLods(
1420
1489
  root: { traverse(callback: (object: object) => void): void },
1421
1490
  camera: Camera,
@@ -1436,6 +1505,10 @@ export function updateModelLods(
1436
1505
  return triangles;
1437
1506
  }
1438
1507
  const tracking = trackRoot(root);
1508
+ // PRD-898 J2: on the owned engine every plain selection is one call, and only changed levels return.
1509
+ const hook = (camera as Camera & { __tnModelLodSelect?: unknown }).__tnModelLodSelect;
1510
+ const select = typeof hook === "function" ? (hook as ModelLodSelect) : undefined;
1511
+ const batched: ModelLod[] = [];
1439
1512
  for (const mesh of tracking.items) {
1440
1513
  const entry = controllerFor(mesh);
1441
1514
  if (entry === undefined) {
@@ -1443,8 +1516,11 @@ export function updateModelLods(
1443
1516
  if (!streaming.has(mesh.geometry)) tracking.items.delete(mesh);
1444
1517
  continue;
1445
1518
  }
1446
- entry.update(camera, viewportHeight);
1519
+ if (select !== undefined && entry instanceof ModelLod && entry.batchable) batched.push(entry);
1520
+ else entry.update(camera, viewportHeight);
1447
1521
  }
1522
+ if (select !== undefined && batched.length > 0)
1523
+ selectBatched(select, camera, batched, viewportHeight);
1448
1524
  let triangles = 0;
1449
1525
  for (const mesh of tracking.items) triangles += controllers.get(mesh)?.triangles ?? 0;
1450
1526
  return triangles;
@@ -1,5 +1,6 @@
1
1
  import { AttachedBindMode, Box3, type Object3D, Quaternion, Vector3 } from "three";
2
2
  import type { Mesh, SkinnedMesh } from "three";
3
+ import { sphereBoundsHook } from "./engine-hooks.js";
3
4
 
4
5
  /**
5
6
  * Brings every attached-mode skinned mesh under `root` to the bind state the renderer would give it.
@@ -414,11 +415,35 @@ function getEnvelope(
414
415
  * read one world-matrix translation per contributing bone and allocate nothing. The returned
415
416
  * object is cached for the root and updated in place; copy it if it must outlive the next call.
416
417
  */
418
+ /** PRD-898 J4: which envelope's spheres the engine holds for each root. */
419
+ const engineEnvelope = new WeakMap<Object3D, IPosedBoundsEnvelope>();
420
+
417
421
  export function posedBounds(root: Object3D, meshes?: readonly Object3D[]): IThreePoseBounds {
418
422
  const envelope = getEnvelope(root, meshes);
419
- root.updateWorldMatrix(true, true);
420
- rawBounds(envelope, envelope.raw);
421
423
  const raw = envelope.raw;
424
+ // PRD-898 J4: on the owned engine the matrix pass and every sphere read are one call.
425
+ const engine = sphereBoundsHook(root);
426
+ if (engine === undefined) {
427
+ root.updateWorldMatrix(true, true);
428
+ rawBounds(envelope, raw);
429
+ } else {
430
+ // The engine keeps one sphere set per root: hand this envelope's over when it is not the one held.
431
+ if (engineEnvelope.get(root) !== envelope) {
432
+ engine.attach.call(
433
+ root,
434
+ [...envelope.bones.map((s) => s.bone), ...envelope.statics.map((s) => s.object)],
435
+ [...envelope.bones.map((s) => s.radius), ...envelope.statics.map((s) => s.radius)],
436
+ );
437
+ engineEnvelope.set(root, envelope);
438
+ }
439
+ const box = engine.bounds.call(root);
440
+ raw.minX = box[0] ?? Number.POSITIVE_INFINITY;
441
+ raw.minY = box[1] ?? Number.POSITIVE_INFINITY;
442
+ raw.minZ = box[2] ?? Number.POSITIVE_INFINITY;
443
+ raw.maxX = box[3] ?? Number.NEGATIVE_INFINITY;
444
+ raw.maxY = box[4] ?? Number.NEGATIVE_INFINITY;
445
+ raw.maxZ = box[5] ?? Number.NEGATIVE_INFINITY;
446
+ }
422
447
  const min = envelope.result.min;
423
448
  const max = envelope.result.max;
424
449
  const size = envelope.result.size;
@@ -140,6 +140,7 @@ const normal = new Vector3();
140
140
  * @situation scatter fallen logs, twigs, leaf litter, stones and ferns over a forest floor
141
141
  * @situation stream instanced props of any baked mesh round the player without one draw per prop
142
142
  * @situation place rocks, debris or plants on a heightfield with distance thinning and level of detail
143
+ * @alias scatter rocks, debris and plants over terrain
143
144
  * @constraint call `update(follow)` once per rendered frame
144
145
  * @constraint `place` runs once per candidate per tile build: return false for paths and clearings
145
146
  * @constraint rotating or scaling the field is not supported; translating it is
@@ -198,6 +198,10 @@ function freezeRoot(root: Object3D, engine: boolean): number {
198
198
  const snapshot = existing?.snapshot ?? new Float64Array(SNAPSHOT_LENGTH);
199
199
  writeSnapshot(root, snapshot);
200
200
  const version = (existing?.version ?? 0) + 1;
201
+ // PRD-898 J1: on the owned engine the engine keeps its own record for the one-call check.
202
+ const watch = (root as Object3D & Partial<IStaticEngineRoot>).__tnStaticWatch;
203
+ if (typeof watch === "function") watch.call(root);
204
+ if (existing === undefined) engineRoots = undefined;
201
205
  frozen.set(
202
206
  root,
203
207
  engine
@@ -216,6 +220,7 @@ function freezeRoot(root: Object3D, engine: boolean): number {
216
220
  */
217
221
  export function unmarkStatic(root: Object3D): void {
218
222
  if (!frozen.delete(root)) return;
223
+ engineRoots = undefined;
219
224
  if (worldSilenced.delete(root)) root.matrixWorldAutoUpdate = true;
220
225
  root.traverse((object) => {
221
226
  if (composeSilenced.delete(object)) object.matrixAutoUpdate = true;
@@ -271,6 +276,17 @@ export interface IStaticTransformCensus {
271
276
 
272
277
  let rearmedSinceCensus = 0;
273
278
 
279
+ /** The owned engine's frozen-root calls (abi/bindings_scene.cpp), absent on plain three.js. */
280
+ interface IStaticEngineRoot {
281
+ __tnStaticWatch(): void;
282
+ /** Hands over the frozen set, in map order; sent only when a root is added or removed. */
283
+ __tnStaticRoots(roots: readonly Object3D[]): void;
284
+ __tnStaticChanged(): readonly number[];
285
+ }
286
+
287
+ /** Frozen roots in map order for the engine check, rebuilt only when a root is added or removed. */
288
+ let engineRoots: Object3D[] | undefined;
289
+
274
290
  /**
275
291
  * Re-arms any frozen root whose authored transform has changed since it was frozen.
276
292
  *
@@ -281,6 +297,23 @@ let rearmedSinceCensus = 0;
281
297
  */
282
298
  export function refreshStaticTransforms(): void {
283
299
  if (frozen.size === 0) return;
300
+ const first = frozen.keys().next().value as Object3D & Partial<IStaticEngineRoot>;
301
+ const changed = first.__tnStaticChanged;
302
+ if (typeof changed === "function") {
303
+ // PRD-898 J1: one engine call compares every root with the record it took at freeze; JavaScript
304
+ // visits only the roots that moved.
305
+ if (engineRoots === undefined) {
306
+ engineRoots = [...frozen.keys()];
307
+ (first.__tnStaticRoots as IStaticEngineRoot["__tnStaticRoots"]).call(first, engineRoots);
308
+ }
309
+ const roots = engineRoots;
310
+ for (const index of changed.call(first)) {
311
+ const root = roots[index] as Object3D;
312
+ freezeRoot(root, frozen.get(root)?.parent !== undefined);
313
+ rearmedSinceCensus += 1;
314
+ }
315
+ return;
316
+ }
284
317
  parentMovedThisFrame.clear();
285
318
  for (const entry of frozen.values()) {
286
319
  const engine = entry.parent !== undefined;
@@ -344,6 +377,7 @@ export function staticTransformCensus(): IStaticTransformCensus {
344
377
  /** Drops every registration. A game that tore down its scene must not keep its roots alive. */
345
378
  export function resetStaticTransforms(): void {
346
379
  frozen.clear();
380
+ engineRoots = undefined;
347
381
  parentMovedThisFrame.clear();
348
382
  rearmedSinceCensus = 0;
349
383
  }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // Generated by scripts/generate-version.mjs - do not edit. Source: package.json.
2
- export const CORE_VERSION = "0.3.15";
2
+ export const CORE_VERSION = "0.3.16";