@threenative/core 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.
Files changed (60) hide show
  1. package/capabilities.json +1008 -83
  2. package/dist/{chunk-4SRAQFTU.js → chunk-2GPHICV6.js} +1 -1
  3. package/dist/{chunk-EEABDLUC.js → chunk-5C4TCWI3.js} +2 -2
  4. package/dist/{chunk-DIPIJICH.js → chunk-FQURMC2F.js} +122 -18
  5. package/dist/{chunk-EFWZWLPY.js → chunk-OMGIYWW7.js} +400 -13
  6. package/dist/{chunk-SV4QVUTQ.js → chunk-QAQHYOWY.js} +1 -1
  7. package/dist/{chunk-GYUZJQ7U.js → chunk-VQRPEOKY.js} +4 -1
  8. package/dist/hot.js +10 -2
  9. package/dist/index.d.ts +608 -16
  10. package/dist/index.js +2037 -633
  11. package/dist/{model-lod-DPTzeCcD.d.ts → model-lod-B921F6kQ.d.ts} +0 -10
  12. package/dist/playtest.js +3 -3
  13. package/dist/{quality-BYqKGAwo.d.ts → quality-BADStsTn.d.ts} +2 -2
  14. package/dist/render-environment.d.ts +1 -1
  15. package/dist/ui-layer.js +2 -2
  16. package/dist/worker.js +2 -2
  17. package/dist/world.d.ts +14 -4
  18. package/dist/world.js +179 -36
  19. package/mcp/animation-server.mjs +1 -1
  20. package/mcp/engine-server.mjs +44 -17
  21. package/mcp/servers.mjs +4 -4
  22. package/package.json +6 -6
  23. package/patches/three@0.187.0-prd269-upgrade.patch +126 -2
  24. package/patches/three@0.187.0.patch +108 -21
  25. package/scripts/ensure-mcp.mjs +6 -1
  26. package/src/clustered-batch.ts +146 -3
  27. package/src/clustered-mesh.ts +548 -20
  28. package/src/debug.ts +16 -0
  29. package/src/displaced-surface.ts +428 -0
  30. package/src/engine-hooks.ts +29 -0
  31. package/src/frame-budget.ts +16 -0
  32. package/src/generated/console-markers.ts +1 -0
  33. package/src/grass-field.ts +628 -0
  34. package/src/grounding.ts +19 -10
  35. package/src/hot.ts +18 -2
  36. package/src/index.ts +112 -0
  37. package/src/instanced-batch-lod.ts +54 -0
  38. package/src/model-lod.ts +77 -1
  39. package/src/pose-measure.ts +27 -2
  40. package/src/render/material-key.ts +21 -1
  41. package/src/render/screen-probe-gather.ts +303 -0
  42. package/src/render/short-range-ao.ts +274 -0
  43. package/src/render/world-impostor-surface.ts +98 -3
  44. package/src/render-camera-cull.ts +9 -3
  45. package/src/renderer.ts +26 -4
  46. package/src/scatter-field.ts +497 -0
  47. package/src/startup-offscreen-bytes.ts +11 -5
  48. package/src/state.ts +16 -3
  49. package/src/static-transform.ts +109 -6
  50. package/src/tile-ring.ts +294 -0
  51. package/src/version.ts +1 -1
  52. package/src/warmup.ts +15 -2
  53. package/src/world-cell-batches.ts +4 -0
  54. package/src/world-cell-data.ts +7 -0
  55. package/src/world-cell-models.ts +36 -8
  56. package/src/world-cell-render-gpu-dress.ts +4 -2
  57. package/src/world-cell-render-util.ts +2 -2
  58. package/src/world-cells.ts +1 -1
  59. package/src/world-river-ribbon.ts +13 -22
  60. package/src/world-water-bodies.ts +113 -3
@@ -1,9 +1,11 @@
1
- import { Vector3, Sphere, Mesh, BufferAttribute, BufferGeometry, InstancedMesh, Object3D, Group, Box3, Matrix4, Frustum } from 'three';
1
+ import { Vector3, Sphere, Frustum, Matrix4, Mesh, Quaternion, BufferAttribute, BufferGeometry, InstancedMesh, Object3D, Group, Box3 } from 'three';
2
2
 
3
3
  // src/clustered-mesh.ts
4
+ var NO_CLUSTER_GROUP = 4294967295;
4
5
  var MIN_DISTANCE = 1e-4;
5
6
  var DEFAULT_ERROR_PIXELS = 1;
6
7
  var RECUT_FRACTION = 1e-3;
8
+ var DEFAULT_VIEW_MARGIN = Math.PI / 90;
7
9
  function pixelsPerUnit(camera, viewportHeight) {
8
10
  const perspective = camera;
9
11
  if (perspective.isPerspectiveCamera !== true || perspective.fov === void 0)
@@ -50,6 +52,127 @@ function selectClusterCut(table, camera, scale, errorPixels, out) {
50
52
  }
51
53
  return selected;
52
54
  }
55
+ function worldFrustum(camera, into, scratch) {
56
+ return into.setFromProjectionMatrix(
57
+ scratch.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse)
58
+ );
59
+ }
60
+ function outsideFrustum(frustum, center, radius) {
61
+ for (const plane of frustum.planes) if (plane.distanceToPoint(center) < -radius) return true;
62
+ return false;
63
+ }
64
+ function clusterTableRadius(table) {
65
+ let radius = 0;
66
+ const { bounds } = table;
67
+ for (let at = 0; at + 3 < bounds.length; at += 4)
68
+ radius = Math.max(
69
+ radius,
70
+ Math.hypot(bounds[at], bounds[at + 1], bounds[at + 2]) + bounds[at + 3]
71
+ );
72
+ return radius;
73
+ }
74
+ var hierarchies = /* @__PURE__ */ new WeakMap();
75
+ function clusterHierarchy(table) {
76
+ let hierarchy = hierarchies.get(table);
77
+ if (hierarchy === void 0) {
78
+ hierarchy = buildClusterHierarchy(table);
79
+ hierarchies.set(table, hierarchy);
80
+ }
81
+ return hierarchy;
82
+ }
83
+ function buildClusterHierarchy(table) {
84
+ const groups = table.groups;
85
+ if (groups === void 0)
86
+ throw new Error(
87
+ "ClusteredMesh needs table.groups to prune its cut by view: re-bake the model with the current asset pipeline."
88
+ );
89
+ const clusters = table.ranges.length / 2;
90
+ let groupCount = 0;
91
+ let rootCount = 0;
92
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
93
+ const group = groups[cluster * 2];
94
+ const source = groups[cluster * 2 + 1];
95
+ if (source !== NO_CLUSTER_GROUP) groupCount = Math.max(groupCount, source + 1);
96
+ if (group === NO_CLUSTER_GROUP) rootCount += 1;
97
+ else groupCount = Math.max(groupCount, group + 1);
98
+ }
99
+ const starts = new Uint32Array(groupCount + 1);
100
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
101
+ const group = groups[cluster * 2];
102
+ if (group !== NO_CLUSTER_GROUP) starts[group + 1] = starts[group + 1] + 1;
103
+ }
104
+ for (let group = 0; group < groupCount; group += 1)
105
+ starts[group + 1] = starts[group + 1] + starts[group];
106
+ const children = new Uint32Array(clusters);
107
+ const cursor = starts.slice();
108
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
109
+ const group = groups[cluster * 2];
110
+ if (group === NO_CLUSTER_GROUP) continue;
111
+ children[cursor[group]] = cluster;
112
+ cursor[group] = cursor[group] + 1;
113
+ }
114
+ const roots = new Uint32Array(rootCount);
115
+ let written = 0;
116
+ for (let cluster = 0; cluster < clusters; cluster += 1)
117
+ if (groups[cluster * 2] === NO_CLUSTER_GROUP) {
118
+ roots[written] = cluster;
119
+ written += 1;
120
+ }
121
+ const reached = reachableClusters({ children, groups, roots, starts });
122
+ if (reached !== clusters)
123
+ throw new Error(
124
+ `TN_CLUSTER_DAG_UNREACHABLE: the cluster DAG reaches ${reached} of ${clusters} clusters from its ${rootCount} roots; re-bake the model with the current asset pipeline.`
125
+ );
126
+ return { children, groups, roots, starts };
127
+ }
128
+ function reachableClusters(hierarchy) {
129
+ const { children, groups, roots, starts } = hierarchy;
130
+ const seen = new Uint8Array(groups.length / 2);
131
+ const stack = [];
132
+ for (const root of roots) {
133
+ seen[root] = 1;
134
+ stack.push(root);
135
+ }
136
+ let reached = roots.length;
137
+ while (stack.length > 0) {
138
+ const parent = groups[stack.pop() * 2 + 1];
139
+ if (parent === NO_CLUSTER_GROUP) continue;
140
+ for (let slot = starts[parent]; slot < starts[parent + 1]; slot += 1) {
141
+ const child = children[slot];
142
+ if (seen[child] === 1) continue;
143
+ seen[child] = 1;
144
+ reached += 1;
145
+ stack.push(child);
146
+ }
147
+ }
148
+ return reached;
149
+ }
150
+ var ClusterView = class {
151
+ #frustum = new Frustum();
152
+ #viewMatrix = new Matrix4();
153
+ #eye = new Vector3();
154
+ #center = new Vector3();
155
+ #toWorld = new Matrix4();
156
+ #scale = 1;
157
+ #margin = 0;
158
+ /** Points this view at `camera`, kept valid for a turn of `margin` radians. */
159
+ setFromCamera(camera, margin) {
160
+ camera.updateWorldMatrix(true, false);
161
+ worldFrustum(camera, this.#frustum, this.#viewMatrix);
162
+ this.#eye.setFromMatrixPosition(camera.matrixWorld);
163
+ this.#margin = 2 * Math.sin(margin / 2);
164
+ }
165
+ /** The transform from the units the spheres are given in to world space. */
166
+ setTransform(matrixWorld) {
167
+ this.#toWorld.copy(matrixWorld);
168
+ this.#scale = matrixWorld.getMaxScaleOnAxis();
169
+ }
170
+ touches(x, y, z, radius) {
171
+ this.#center.set(x, y, z).applyMatrix4(this.#toWorld);
172
+ const slack = this.#margin === 0 ? 0 : this.#center.distanceTo(this.#eye) * this.#margin;
173
+ return !outsideFrustum(this.#frustum, this.#center, radius * this.#scale + slack);
174
+ }
175
+ };
53
176
  function finestIndexCount(table) {
54
177
  let count = 0;
55
178
  for (let cluster = 0; cluster * 2 < table.ranges.length; cluster += 1)
@@ -57,6 +180,77 @@ function finestIndexCount(table) {
57
180
  count += table.ranges[cluster * 2 + 1];
58
181
  return count;
59
182
  }
183
+ var ClusterWalk = class {
184
+ #table;
185
+ #hierarchy;
186
+ #stack;
187
+ /** Which cut last descended into each group, so a group shared by siblings is visited once. */
188
+ #stamps;
189
+ #generation = 0;
190
+ constructor(table, hierarchy = clusterHierarchy(table)) {
191
+ this.#table = table;
192
+ this.#hierarchy = hierarchy;
193
+ this.#stack = new Uint32Array(table.ranges.length / 2);
194
+ this.#stamps = new Int32Array(hierarchy.starts.length);
195
+ }
196
+ /** The cut, as cluster indices, written into `out`; returns how many were selected. */
197
+ select(camera, scale, errorPixels, view, out) {
198
+ const { children, groups, roots, starts } = this.#hierarchy;
199
+ const { errors, parentSpheres, sourceSpheres } = this.#table;
200
+ this.#generation += 1;
201
+ const generation = this.#generation;
202
+ let selected = 0;
203
+ let depth = 0;
204
+ for (let root = 0; root < roots.length; root += 1) {
205
+ this.#stack[depth] = roots[root];
206
+ depth += 1;
207
+ while (depth > 0) {
208
+ depth -= 1;
209
+ const cluster = this.#stack[depth];
210
+ const own = projectedError(
211
+ errors[cluster * 2],
212
+ sourceSpheres,
213
+ cluster,
214
+ camera,
215
+ scale
216
+ );
217
+ if (own <= errorPixels) {
218
+ const parent = projectedError(
219
+ errors[cluster * 2 + 1],
220
+ parentSpheres,
221
+ cluster,
222
+ camera,
223
+ scale
224
+ );
225
+ if (parent <= errorPixels) continue;
226
+ if (selected >= out.length)
227
+ throw new Error(
228
+ `ClusteredMesh selected more than the ${out.length} clusters level 0 holds; the table is inconsistent.`
229
+ );
230
+ out[selected] = cluster;
231
+ selected += 1;
232
+ continue;
233
+ }
234
+ const source = groups[cluster * 2 + 1];
235
+ if (source === NO_CLUSTER_GROUP) continue;
236
+ if (this.#stamps[source] === generation) continue;
237
+ this.#stamps[source] = generation;
238
+ if (!view.touches(
239
+ sourceSpheres[cluster * 4],
240
+ sourceSpheres[cluster * 4 + 1],
241
+ sourceSpheres[cluster * 4 + 2],
242
+ sourceSpheres[cluster * 4 + 3]
243
+ ))
244
+ continue;
245
+ for (let slot = starts[source]; slot < starts[source + 1]; slot += 1) {
246
+ this.#stack[depth] = children[slot];
247
+ depth += 1;
248
+ }
249
+ }
250
+ }
251
+ return selected;
252
+ }
253
+ };
60
254
  var ClusteredMesh = class _ClusteredMesh extends Mesh {
61
255
  /** The baked payload. The bake is the only thing that writes it; a copy takes the source's. */
62
256
  table;
@@ -64,20 +258,45 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
64
258
  errorPixels;
65
259
  /** Camera movement, in the mesh's own units, below which the previous cut is kept. */
66
260
  recutDistance;
261
+ /**
262
+ * Whether the cut skips clusters the camera cannot see. Writable — a mesh drawn through a second
263
+ * camera can turn it off, and {@link ClusteredMesh.viewCullReport} says what happened either way.
264
+ */
265
+ viewCull;
266
+ /** Camera turn, in radians, the kept cut stays valid for. Writable. */
267
+ viewMargin;
67
268
  #cut;
68
269
  #selection;
270
+ #walk;
271
+ #view = new ClusterView();
69
272
  #cameraLocal = new Vector3();
70
273
  #lastCut = new Vector3();
274
+ #rotation = new Quaternion();
275
+ #lastRotation = new Quaternion();
276
+ #frustum = new Frustum();
277
+ #viewMatrix = new Matrix4();
278
+ #sphereCenter = new Vector3();
71
279
  #drawnClusters = 0;
72
280
  #drawnIndices = 0;
281
+ #drawnClustersOutsideView = 0;
282
+ #drawnTrianglesOutsideView = 0;
283
+ #recutMs = 0;
284
+ #recutBytes = 0;
285
+ #recutCount = 0;
73
286
  #hasCut = false;
287
+ #pruned = false;
74
288
  #lastScale = 0;
75
289
  #lastErrorPixels = 0;
290
+ /** The projection the cut was pruned by: an aspect or zoom change keeps the pixel scale. */
291
+ #lastProjection = new Matrix4();
76
292
  constructor(geometry, surface, table, options = {}) {
77
293
  super(geometry, surface);
78
294
  assertTable(table);
79
295
  this.errorPixels = options.errorPixels ?? DEFAULT_ERROR_PIXELS;
80
296
  this.recutDistance = options.recutDistance ?? radiusOf(table) * RECUT_FRACTION;
297
+ this.viewCull = options.viewCull ?? true;
298
+ this.viewMargin = options.viewMargin ?? DEFAULT_VIEW_MARGIN;
299
+ assertViewMargin(this.viewMargin);
81
300
  this.#load(table, geometry);
82
301
  this.#compact(this.#finestCut());
83
302
  }
@@ -86,6 +305,12 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
86
305
  this.table = table;
87
306
  this.#cut = new Uint32Array(finestIndexCount(table));
88
307
  this.#selection = new Uint32Array(table.ranges.length / 2);
308
+ this.#drawnClustersOutsideView = 0;
309
+ this.#drawnTrianglesOutsideView = 0;
310
+ this.#recutMs = 0;
311
+ this.#recutBytes = 0;
312
+ this.#recutCount = 0;
313
+ this.#walk = table.groups === void 0 ? void 0 : new ClusterWalk(table);
89
314
  geometry.setIndex(new BufferAttribute(this.#cut, 1));
90
315
  }
91
316
  /**
@@ -99,7 +324,9 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
99
324
  clone(recursive = true) {
100
325
  return new _ClusteredMesh(withOwnCut(this.geometry), this.material, this.table, {
101
326
  errorPixels: this.errorPixels,
102
- recutDistance: this.recutDistance
327
+ recutDistance: this.recutDistance,
328
+ viewCull: this.viewCull,
329
+ viewMargin: this.viewMargin
103
330
  }).copy(this, recursive);
104
331
  }
105
332
  /**
@@ -119,6 +346,8 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
119
346
  this.geometry = geometry;
120
347
  this.errorPixels = source.errorPixels;
121
348
  this.recutDistance = source.recutDistance;
349
+ this.viewCull = source.viewCull;
350
+ this.viewMargin = source.viewMargin;
122
351
  this.#hasCut = false;
123
352
  this.#compact(this.#finestCut());
124
353
  return this;
@@ -141,6 +370,56 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
141
370
  get drawnTriangles() {
142
371
  return this.#drawnIndices / 3;
143
372
  }
373
+ /**
374
+ * Triangles in the current cut whose cluster bounds lie wholly outside the view volume.
375
+ *
376
+ * A measurement, not a cull: PRD-600 records this number before and after the walk learns to skip
377
+ * what the view does not hold. It is taken when the cut is taken, so a still camera reads the
378
+ * number its standing cut was made with.
379
+ */
380
+ get drawnTrianglesOutsideView() {
381
+ return this.#drawnTrianglesOutsideView;
382
+ }
383
+ /** Clusters in the current cut whose bounds lie wholly outside the view volume. */
384
+ get drawnClustersOutsideView() {
385
+ return this.#drawnClustersOutsideView;
386
+ }
387
+ /**
388
+ * Milliseconds the last re-cut took, from choosing the cut to the index buffer being marked for
389
+ * upload.
390
+ *
391
+ * The whole re-cut, because that is the cost a game pays for turning the camera and the number
392
+ * `viewMargin` is chosen against. The bytes below are only the compact's copy, so the throughput
393
+ * this divides out is the pessimistic one.
394
+ */
395
+ get recutMs() {
396
+ return this.#recutMs;
397
+ }
398
+ /** Index bytes the last re-cut copied and uploaded. */
399
+ get recutBytes() {
400
+ return this.#recutBytes;
401
+ }
402
+ /** Throughput of the last re-cut's copy of the cut, in megabytes per second. */
403
+ get recutMegabytesPerSecond() {
404
+ return this.#recutMs > 0 ? this.#recutBytes / 1e3 / this.#recutMs : 0;
405
+ }
406
+ /** How many re-cuts this mesh has taken, so a reader can tell a fresh one from a stale reading. */
407
+ get recutCount() {
408
+ return this.#recutCount;
409
+ }
410
+ /**
411
+ * What this mesh does about clusters outside the view, and why.
412
+ *
413
+ * `"on"` when the cut is pruned, and a reason when it is not — a mesh that silently kept drawing
414
+ * what nobody can see would be a performance bug with no symptom, and one that silently dropped
415
+ * what a second camera can see would be a hole with no cause.
416
+ */
417
+ get viewCullReport() {
418
+ if (!this.viewCull) return "off (viewCull = false)";
419
+ if (this.castShadow) return "off (castShadow)";
420
+ if (this.#walk === void 0) return "off (no clusterGroups)";
421
+ return "on";
422
+ }
144
423
  /**
145
424
  * Chooses this frame's cut and compacts it into one index range.
146
425
  *
@@ -157,18 +436,71 @@ var ClusteredMesh = class _ClusteredMesh extends Mesh {
157
436
  camera.updateWorldMatrix(true, false);
158
437
  this.#cameraLocal.setFromMatrixPosition(camera.matrixWorld);
159
438
  this.worldToLocal(this.#cameraLocal);
439
+ camera.getWorldQuaternion(this.#rotation);
440
+ const pruned = this.viewCull && !this.castShadow && this.#walk !== void 0;
160
441
  const moved = this.#cameraLocal.distanceTo(this.#lastCut);
161
- const settled = this.#hasCut && moved <= this.recutDistance && scale === this.#lastScale && this.errorPixels === this.#lastErrorPixels;
442
+ const settled = this.#hasCut && pruned === this.#pruned && moved <= this.recutDistance && this.#rotation.angleTo(this.#lastRotation) <= this.viewMargin && scale === this.#lastScale && this.errorPixels === this.#lastErrorPixels && camera.projectionMatrix.equals(this.#lastProjection);
162
443
  if (settled) return this.drawnTriangles;
163
444
  this.#lastCut.copy(this.#cameraLocal);
445
+ this.#lastRotation.copy(this.#rotation);
164
446
  this.#lastScale = scale;
165
447
  this.#lastErrorPixels = this.errorPixels;
448
+ this.#lastProjection.copy(camera.projectionMatrix);
449
+ this.#pruned = pruned;
166
450
  this.#hasCut = true;
167
- this.#compact(
168
- selectClusterCut(this.table, this.#cameraLocal, scale, this.errorPixels, this.#selection)
169
- );
451
+ const started = performance.now();
452
+ const walk = this.#walk;
453
+ if (pruned && walk !== void 0) {
454
+ this.#view.setFromCamera(camera, this.viewMargin);
455
+ this.#view.setTransform(this.matrixWorld);
456
+ this.#compact(
457
+ walk.select(this.#cameraLocal, scale, this.errorPixels, this.#view, this.#selection)
458
+ );
459
+ } else {
460
+ this.#compact(
461
+ selectClusterCut(this.table, this.#cameraLocal, scale, this.errorPixels, this.#selection)
462
+ );
463
+ }
464
+ this.#recutMs = performance.now() - started;
465
+ this.#recutBytes = this.#drawnIndices * 4;
466
+ this.#recutCount += 1;
467
+ this.#countOutsideView(camera);
170
468
  return this.drawnTriangles;
171
469
  }
470
+ /**
471
+ * Records how much of this cut the view volume does not hold.
472
+ *
473
+ * Read-only and taken when a cut is taken, so it costs one sphere test per selected cluster on the
474
+ * re-cut path and nothing at all on a frame the cut settled. The mesh's own scale is folded into
475
+ * the radius the way three folds it into its own cull, so a scaled placement is measured as it
476
+ * draws.
477
+ */
478
+ #countOutsideView(camera) {
479
+ const frustum = worldFrustum(camera, this.#frustum, this.#viewMatrix);
480
+ const scale = this.matrixWorld.getMaxScaleOnAxis();
481
+ const world = this.matrixWorld;
482
+ let clusters = 0;
483
+ let indices = 0;
484
+ for (let slot = 0; slot < this.#drawnClusters; slot += 1) {
485
+ const cluster = this.#selection[slot];
486
+ const count = this.table.ranges[cluster * 2 + 1];
487
+ this.#sphereCenter.set(
488
+ this.table.bounds[cluster * 4],
489
+ this.table.bounds[cluster * 4 + 1],
490
+ this.table.bounds[cluster * 4 + 2]
491
+ ).applyMatrix4(world);
492
+ if (!outsideFrustum(
493
+ frustum,
494
+ this.#sphereCenter,
495
+ this.table.bounds[cluster * 4 + 3] * scale
496
+ ))
497
+ continue;
498
+ clusters += 1;
499
+ indices += count;
500
+ }
501
+ this.#drawnClustersOutsideView = clusters;
502
+ this.#drawnTrianglesOutsideView = indices / 3;
503
+ }
172
504
  #compact(selected) {
173
505
  let cursor = 0;
174
506
  for (let slot = 0; slot < selected; slot += 1) {
@@ -199,10 +531,13 @@ function withOwnCut(geometry) {
199
531
  return shell;
200
532
  }
201
533
  function radiusOf(table) {
202
- let radius = 0;
203
- for (let cluster = 0; cluster * 4 < table.bounds.length; cluster += 1)
204
- radius = Math.max(radius, table.bounds[cluster * 4 + 3]);
205
- return radius;
534
+ return clusterTableRadius(table);
535
+ }
536
+ function assertViewMargin(margin) {
537
+ if (!Number.isFinite(margin) || margin < 0 || margin >= Math.PI / 2)
538
+ throw new Error(
539
+ `ClusteredMesh viewMargin must be a turn in radians below a quarter circle, got ${margin}.`
540
+ );
206
541
  }
207
542
  function assertTable(table) {
208
543
  const clusters = table.ranges.length / 2;
@@ -222,6 +557,10 @@ function assertTable(table) {
222
557
  `ClusteredMesh table.${name} holds ${array.length} values for ${clusters} clusters; it needs ${clusters * width}.`
223
558
  );
224
559
  }
560
+ if (table.groups !== void 0 && table.groups.length !== clusters * 2)
561
+ throw new Error(
562
+ `ClusteredMesh table.groups holds ${table.groups.length} values for ${clusters} clusters; it needs ${clusters * 2}.`
563
+ );
225
564
  for (let cluster = 0; cluster < clusters; cluster += 1) {
226
565
  const start = table.ranges[cluster * 2];
227
566
  const count = table.ranges[cluster * 2 + 1];
@@ -242,6 +581,7 @@ var TABLE_FIELDS = [
242
581
  "clusterBounds",
243
582
  "clusterCones",
244
583
  "clusterErrors",
584
+ "clusterGroups",
245
585
  "clusterParentSpheres",
246
586
  "clusterRanges",
247
587
  "clusterSourceSpheres",
@@ -254,10 +594,11 @@ async function readTable(parser, def) {
254
594
  `TN_VIRTUAL_GEOMETRY_INCOMPLETE: the ${TN_VIRTUAL_GEOMETRY} payload is missing ${missing.join(", ")}; re-bake the model with the current asset pipeline.`
255
595
  );
256
596
  const accessor = async (index) => (await parser.getDependency("accessor", index)).array;
257
- const [bounds, cones, errors, parentSpheres, ranges, sourceSpheres, indices] = await Promise.all([
597
+ const [bounds, cones, errors, groups, parentSpheres, ranges, sourceSpheres, indices] = await Promise.all([
258
598
  accessor(def.clusterBounds),
259
599
  accessor(def.clusterCones),
260
600
  accessor(def.clusterErrors),
601
+ accessor(def.clusterGroups),
261
602
  accessor(def.clusterParentSpheres),
262
603
  accessor(def.clusterRanges),
263
604
  accessor(def.clusterSourceSpheres),
@@ -267,6 +608,7 @@ async function readTable(parser, def) {
267
608
  bounds: typedFloat(bounds),
268
609
  cones: typedFloat(cones),
269
610
  errors: typedFloat(errors),
611
+ groups: typedUint(groups),
270
612
  indices: typedUint(indices),
271
613
  parentSpheres: typedFloat(parentSpheres),
272
614
  ranges: typedUint(ranges),
@@ -405,6 +747,9 @@ var LOD_BIAS_KEY = /* @__PURE__ */ Symbol.for("threenative.lodBias");
405
747
  var lodBiasHost = globalThis;
406
748
  var lodBiasState = lodBiasHost[LOD_BIAS_KEY] ?? { value: 1 };
407
749
  lodBiasHost[LOD_BIAS_KEY] = lodBiasState;
750
+ function lodBias() {
751
+ return lodBiasState.value;
752
+ }
408
753
  function setLodBias(bias) {
409
754
  lodBiasState.value = Number.isFinite(bias) && bias >= 1 ? bias : 1;
410
755
  }
@@ -537,6 +882,31 @@ var ModelLod = class {
537
882
  get base() {
538
883
  return this.#chain.base;
539
884
  }
885
+ /** PRD-898 J2: whether the engine's batched selection can run this one (the join authority cannot). */
886
+ get batchable() {
887
+ return this.#rung === void 0 || !this.#authority;
888
+ }
889
+ #attached = false;
890
+ /** The mesh for `__tnModelLodSelect`, its chain handed to the engine on first use. */
891
+ engineMesh() {
892
+ if (!this.#attached) {
893
+ const { center, radius } = this.#chain.sphere;
894
+ this.#mesh.__tnModelLodAttach(
895
+ [...this.#chain.errors],
896
+ [center.x, center.y, center.z, radius],
897
+ this.#policy.maxPixelError,
898
+ this.#policy.hysteresis,
899
+ this.#current
900
+ );
901
+ this.#attached = true;
902
+ }
903
+ return this.#mesh;
904
+ }
905
+ /** The level the engine's batched selection chose. */
906
+ applyLevel(index) {
907
+ this.#current = index;
908
+ this.#mesh.geometry = this.#chain.levels[index];
909
+ }
540
910
  get triangles() {
541
911
  const rung = this.#rung;
542
912
  if (rung?.isHidden(this.#mesh)) return this.#authority ? rung.triangles : 0;
@@ -1228,6 +1598,17 @@ function trackRoot2(root) {
1228
1598
  hookSubtree2(tracking, root);
1229
1599
  return tracking;
1230
1600
  }
1601
+ var engineBatch = [];
1602
+ function selectBatched(select, camera, batched, viewportHeight) {
1603
+ if (batched.length !== engineBatch.length || batched.some((entry, i) => entry !== engineBatch[i])) {
1604
+ const meshes = batched.map((entry) => entry.engineMesh());
1605
+ camera.__tnModelLodMeshes(meshes);
1606
+ engineBatch = batched;
1607
+ }
1608
+ const changed = select.call(camera, viewportHeight, lodBias());
1609
+ for (let i = 0; i < changed.length; i += 2)
1610
+ batched[changed[i]].applyLevel(changed[i + 1]);
1611
+ }
1231
1612
  function updateModelLods(root, camera, viewportHeight) {
1232
1613
  camera.updateMatrixWorld();
1233
1614
  if (!isGraphNode2(root)) {
@@ -1242,14 +1623,20 @@ function updateModelLods(root, camera, viewportHeight) {
1242
1623
  return triangles2;
1243
1624
  }
1244
1625
  const tracking = trackRoot2(root);
1626
+ const hook = camera.__tnModelLodSelect;
1627
+ const select = typeof hook === "function" ? hook : void 0;
1628
+ const batched = [];
1245
1629
  for (const mesh of tracking.items) {
1246
1630
  const entry = controllerFor(mesh);
1247
1631
  if (entry === void 0) {
1248
1632
  if (!streaming.has(mesh.geometry)) tracking.items.delete(mesh);
1249
1633
  continue;
1250
1634
  }
1251
- entry.update(camera, viewportHeight);
1635
+ if (select !== void 0 && entry instanceof ModelLod && entry.batchable) batched.push(entry);
1636
+ else entry.update(camera, viewportHeight);
1252
1637
  }
1638
+ if (select !== void 0 && batched.length > 0)
1639
+ selectBatched(select, camera, batched, viewportHeight);
1253
1640
  let triangles = 0;
1254
1641
  for (const mesh of tracking.items) triangles += controllers.get(mesh)?.triangles ?? 0;
1255
1642
  return triangles;
@@ -1892,4 +2279,4 @@ function reconcile(passes, drafts) {
1892
2279
  });
1893
2280
  }
1894
2281
 
1895
- export { ClusteredMesh, DISCRETE_LOD_DEFAULT_ERROR_PIXELS, DISCRETE_LOD_DEFAULT_HYSTERESIS, DiscreteLodPlugin, GEOMETRY_ASSET_KEY, GEOMETRY_CAPTURE_CAPABILITY, GEOMETRY_CAPTURE_DEFAULT_LIMIT, GEOMETRY_CAPTURE_MAX_LIMIT, GEOMETRY_CAPTURE_SORTS, GEOMETRY_CAPTURE_TIMEOUT_MS, GEOMETRY_CAPTURE_WALK_CAP, GeometryCapture, LOD_NEAR_PLANE, TN_DISCRETE_LOD, TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin, baseGeometryOf, biasedLodDistance, isEngineRenderHook, isLodJoinProxy, isStreamedGeometry, lodChainOf, lodPixelScale, markEngineRenderHook, markStreamedGeometry, pixelsPerUnit, projectedLodError, registerModelLodController, rendererBackendIdentity, selectClusterCut, selectLodFor, selectLodLevel, setLodBias, setModelLodLayers, updateClusteredMeshes, updateModelLods, upgradeStreamedGeometry, worldSphere };
2282
+ export { ClusterView, ClusteredMesh, DEFAULT_VIEW_MARGIN, DISCRETE_LOD_DEFAULT_ERROR_PIXELS, DISCRETE_LOD_DEFAULT_HYSTERESIS, DiscreteLodPlugin, GEOMETRY_ASSET_KEY, GEOMETRY_CAPTURE_CAPABILITY, GEOMETRY_CAPTURE_DEFAULT_LIMIT, GEOMETRY_CAPTURE_MAX_LIMIT, GEOMETRY_CAPTURE_SORTS, GEOMETRY_CAPTURE_TIMEOUT_MS, GEOMETRY_CAPTURE_WALK_CAP, GeometryCapture, LOD_NEAR_PLANE, TN_DISCRETE_LOD, TN_VIRTUAL_GEOMETRY, VirtualGeometryPlugin, assertViewMargin, baseGeometryOf, biasedLodDistance, clusterTableRadius, isEngineRenderHook, isLodJoinProxy, isStreamedGeometry, lodBias, lodChainOf, lodPixelScale, markEngineRenderHook, markStreamedGeometry, outsideFrustum, pixelsPerUnit, projectedLodError, registerModelLodController, rendererBackendIdentity, selectClusterCut, selectLodFor, selectLodLevel, setLodBias, setModelLodLayers, updateClusteredMeshes, updateModelLods, upgradeStreamedGeometry, worldFrustum, worldSphere };
@@ -1,4 +1,4 @@
1
- import { readLaunchFlag } from './chunk-GYUZJQ7U.js';
1
+ import { readLaunchFlag } from './chunk-VQRPEOKY.js';
2
2
 
3
3
  // src/quiet-markers.ts
4
4
  var LOG_FLAG = "TN_LOG";
@@ -50,6 +50,9 @@ function envValue(name) {
50
50
  function debugFlag(name) {
51
51
  return readLaunchFlag({ environment: envName(name), query: name });
52
52
  }
53
+ function debugValue(name) {
54
+ return readLaunchValue({ environment: envName(name), query: name });
55
+ }
53
56
  function exposeDebug(name, value) {
54
57
  const isDev = import.meta.env?.DEV === true;
55
58
  if (!isDev) return;
@@ -277,4 +280,4 @@ function debugHotCalls(window) {
277
280
  return calls.length === 0 ? void 0 : `TN_HOT_CALL:${JSON.stringify({ window: window.window, intervalMs: interval, calls })}`;
278
281
  }
279
282
 
280
- export { countDebug, debugFlag, debugHotCalls, debugRequested, exposeDebug, formatDebugReport, isContentScaled, measureDebug, observeDebugGc, readLaunchFlag, readLaunchValue, readLaunchValues };
283
+ export { countDebug, debugFlag, debugHotCalls, debugRequested, debugValue, exposeDebug, formatDebugReport, isContentScaled, measureDebug, observeDebugGc, readLaunchFlag, readLaunchValue, readLaunchValues };
package/dist/hot.js CHANGED
@@ -80,6 +80,15 @@ function diagnostics(game, reloads) {
80
80
  physics: typeof physics?.numBodies === "function" ? physics.numBodies() : null
81
81
  };
82
82
  }
83
+ function notPlain(value, prototype, path) {
84
+ const named = prototype.constructor?.name;
85
+ const name = typeof named === "string" && named.length > 0 ? named : "class instance";
86
+ const keys = Object.keys(value).map((key) => key.replace(/^_/u, ""));
87
+ const shape = keys.length > 0 && keys.length <= 6 ? `{ ${keys.join(", ")} } as a plain object` : "its data as plain values";
88
+ return new Error(
89
+ `Hot reload state ${path} must contain only plain objects: it is a ${name}. Store ${shape} and rebuild the ${name} where the code needs it.`
90
+ );
91
+ }
83
92
  function visitPortable(value, path, ancestors) {
84
93
  if (value === null) return;
85
94
  if (typeof value === "string" || typeof value === "boolean") return;
@@ -98,8 +107,7 @@ function visitPortable(value, path, ancestors) {
98
107
  return;
99
108
  }
100
109
  const prototype = Object.getPrototypeOf(value);
101
- if (prototype !== Object.prototype && prototype !== null)
102
- throw new Error(`Hot reload state ${path} must contain only plain objects.`);
110
+ if (prototype !== Object.prototype && prototype !== null) throw notPlain(value, prototype, path);
103
111
  ancestors.add(value);
104
112
  for (const key of Object.keys(value))
105
113
  visitPortable(value[key], `${path}.${key}`, ancestors);