@threenative/core 0.3.4 → 0.3.6

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +57 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2408 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +574 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +850 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,638 @@
1
+ import { BufferAttribute, BufferGeometry, type Camera, type Material, Mesh, Vector3 } from "three";
2
+
3
+ /**
4
+ * A mesh that draws only the clusters this camera can resolve.
5
+ *
6
+ * The asset pipeline bakes a cluster DAG into the `.glb` (`TN_virtual_geometry`); the loader returns
7
+ * one of these when it finds one, and an ordinary `Mesh` when it does not. Nothing about how the
8
+ * mesh looks lives here: `geometry`, `material` and every appearance parameter are the game's, and
9
+ * swapping the surface at any time swaps what draws.
10
+ *
11
+ * The rule, and it asks a cluster nothing about its neighbours: **draw a cluster when its own error
12
+ * projects to fewer screen pixels than the threshold, and its parent group's does not.** Each side
13
+ * is projected through the sphere of the group it belongs to, which is what keeps the cut watertight
14
+ * as the camera moves — a group's sphere encloses every child's, so the parent's projected error can
15
+ * never fall below a child's.
16
+ */
17
+
18
+ /** The baked payload, exactly as `TN_virtual_geometry` stores it. */
19
+ export interface IClusterTable {
20
+ /** Per cluster, `[centreX, centreY, centreZ, radius]`. Culling reads it; PRD-283 will. */
21
+ readonly bounds: Float32Array;
22
+ /** Per cluster, `[axisX, axisY, axisZ, cutoff]`. */
23
+ readonly cones: Float32Array;
24
+ /** Per cluster, `[ownError, parentError]`, in the mesh's own units. */
25
+ readonly errors: Float32Array;
26
+ /** Cluster-ordered triangles for every level, indexing the geometry's vertex buffer. */
27
+ readonly indices: Uint32Array;
28
+ /** Per cluster, the sphere `parentError` is projected through. */
29
+ readonly parentSpheres: Float32Array;
30
+ /** Per cluster, `[start, count]` into {@link IClusterTable.indices}. */
31
+ readonly ranges: Uint32Array;
32
+ /** Per cluster, the sphere its own error is projected through. */
33
+ readonly sourceSpheres: Float32Array;
34
+ }
35
+
36
+ export interface IClusteredMeshOptions {
37
+ /**
38
+ * Screen-space error a cluster may show, in pixels, before its children are drawn instead.
39
+ *
40
+ * One pixel is the honest default: the point of the technique is that what the camera cannot
41
+ * resolve is never submitted. Raising it trades fidelity for triangles, and the number is the
42
+ * game's to choose.
43
+ */
44
+ readonly errorPixels?: number;
45
+ /**
46
+ * How far the camera must move, in the mesh's own units, before the cut is taken again.
47
+ *
48
+ * Popping is a defect, not a tuning parameter: a camera standing still and breathing must not
49
+ * flip a cluster back and forth. Below this the previous cut is kept, which is always a cut some
50
+ * camera would have chosen and therefore always watertight. Default is a thousandth of the mesh's
51
+ * radius.
52
+ */
53
+ readonly recutDistance?: number;
54
+ }
55
+
56
+ /** A cluster nearer than this to the camera is treated as this far away, rather than dividing by zero. */
57
+ const MIN_DISTANCE = 1e-4;
58
+
59
+ const DEFAULT_ERROR_PIXELS = 1;
60
+ const RECUT_FRACTION = 0.001;
61
+
62
+ /**
63
+ * The two things a screen-space error needs from a camera.
64
+ *
65
+ * Structural rather than `PerspectiveCamera`, because a game may hand over its own camera subclass
66
+ * and this asks it for nothing else.
67
+ */
68
+ interface IPerspectiveCameraLike extends Camera {
69
+ readonly fov?: number;
70
+ readonly isPerspectiveCamera?: boolean;
71
+ }
72
+
73
+ /**
74
+ * Pixels a one-unit object one unit away covers.
75
+ *
76
+ * Perspective only, and it throws otherwise rather than guessing: an orthographic cut has no
77
+ * distance term at all and silently returning the wrong scale would show as a mesh that never
78
+ * refines.
79
+ */
80
+ export function pixelsPerUnit(camera: Camera, viewportHeight: number): number {
81
+ const perspective: IPerspectiveCameraLike = camera;
82
+ if (perspective.isPerspectiveCamera !== true || perspective.fov === undefined)
83
+ throw new Error(
84
+ "ClusteredMesh needs a perspective camera: a screen-space error has no meaning without one.",
85
+ );
86
+ if (!(viewportHeight > 0))
87
+ throw new Error(`ClusteredMesh needs a positive viewport height, got ${viewportHeight}.`);
88
+ return viewportHeight / (2 * Math.tan((perspective.fov * Math.PI) / 360));
89
+ }
90
+
91
+ function projectedError(
92
+ error: number,
93
+ spheres: Float32Array,
94
+ cluster: number,
95
+ camera: Vector3,
96
+ scale: number,
97
+ ): number {
98
+ const dx = camera.x - (spheres[cluster * 4] as number);
99
+ const dy = camera.y - (spheres[cluster * 4 + 1] as number);
100
+ const dz = camera.z - (spheres[cluster * 4 + 2] as number);
101
+ const distance = Math.sqrt(dx * dx + dy * dy + dz * dz) - (spheres[cluster * 4 + 3] as number);
102
+ return (error * scale) / Math.max(distance, MIN_DISTANCE);
103
+ }
104
+
105
+ /**
106
+ * The cut, as a list of cluster indices, written into `out`.
107
+ *
108
+ * Pure, and the oracle PRD-283's kernel is graded against: same table, same camera, same threshold,
109
+ * same set — or the kernel is wrong.
110
+ *
111
+ * @returns how many clusters were selected.
112
+ */
113
+ export function selectClusterCut(
114
+ table: IClusterTable,
115
+ camera: Vector3,
116
+ scale: number,
117
+ errorPixels: number,
118
+ out: Uint32Array,
119
+ ): number {
120
+ const clusters = table.ranges.length / 2;
121
+ let selected = 0;
122
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
123
+ const own = projectedError(
124
+ table.errors[cluster * 2] as number,
125
+ table.sourceSpheres,
126
+ cluster,
127
+ camera,
128
+ scale,
129
+ );
130
+ if (own > errorPixels) continue;
131
+ const parent = projectedError(
132
+ table.errors[cluster * 2 + 1] as number,
133
+ table.parentSpheres,
134
+ cluster,
135
+ camera,
136
+ scale,
137
+ );
138
+ if (parent <= errorPixels) continue;
139
+ if (selected >= out.length)
140
+ throw new Error(
141
+ `ClusteredMesh selected more than the ${out.length} clusters level 0 holds; the table is inconsistent.`,
142
+ );
143
+ out[selected] = cluster;
144
+ selected += 1;
145
+ }
146
+ return selected;
147
+ }
148
+
149
+ /** Index slots the finest possible cut needs: every cluster whose own error is zero. */
150
+ function finestIndexCount(table: IClusterTable): number {
151
+ let count = 0;
152
+ for (let cluster = 0; cluster * 2 < table.ranges.length; cluster += 1)
153
+ if ((table.errors[cluster * 2] as number) === 0)
154
+ count += table.ranges[cluster * 2 + 1] as number;
155
+ return count;
156
+ }
157
+
158
+ export class ClusteredMesh extends Mesh {
159
+ /** The baked payload. The bake is the only thing that writes it; a copy takes the source's. */
160
+ table!: IClusterTable;
161
+ /** Screen-space error budget in pixels. Writable — it is the game's call. */
162
+ errorPixels: number;
163
+ /** Camera movement, in the mesh's own units, below which the previous cut is kept. */
164
+ recutDistance: number;
165
+
166
+ #cut!: Uint32Array;
167
+ #selection!: Uint32Array;
168
+ readonly #cameraLocal = new Vector3();
169
+ readonly #lastCut = new Vector3();
170
+ #drawnClusters = 0;
171
+ #drawnIndices = 0;
172
+ #hasCut = false;
173
+ #lastScale = 0;
174
+ #lastErrorPixels = 0;
175
+
176
+ constructor(
177
+ geometry: BufferGeometry,
178
+ surface: Material | Material[],
179
+ table: IClusterTable,
180
+ options: IClusteredMeshOptions = {},
181
+ ) {
182
+ super(geometry, surface);
183
+ assertTable(table);
184
+ this.errorPixels = options.errorPixels ?? DEFAULT_ERROR_PIXELS;
185
+ this.recutDistance = options.recutDistance ?? radiusOf(table) * RECUT_FRACTION;
186
+ this.#load(table, geometry);
187
+ // Full detail until something cuts it. Virtual geometry ships on by default, so the mesh a
188
+ // game never touches has to draw exactly what an ordinary `Mesh` would have drawn — a class
189
+ // that starts invisible and waits to be updated would turn the default into a blank screen.
190
+ // `update` only ever takes detail away from here.
191
+ this.#compact(this.#finestCut());
192
+ }
193
+
194
+ /** Points this mesh at `table`, and installs its cut on the geometry it is going to draw. */
195
+ #load(table: IClusterTable, geometry: BufferGeometry): void {
196
+ this.table = table;
197
+ this.#cut = new Uint32Array(finestIndexCount(table));
198
+ this.#selection = new Uint32Array(table.ranges.length / 2);
199
+ // The geometry draws out of the cut buffer from here on. Its vertex attributes are untouched:
200
+ // every level of the DAG indexes the vertices the mesh already shipped.
201
+ //
202
+ // `BufferAttribute`, never `Uint32BufferAttribute`: the typed subclasses *copy* the array they
203
+ // are given, so the cut this class writes every frame would never reach the GPU and the mesh
204
+ // would draw a buffer of zeros — degenerate triangles, an empty screen, and no error anywhere.
205
+ geometry.setIndex(new BufferAttribute(this.#cut, 1));
206
+ }
207
+
208
+ /**
209
+ * A second mesh over the same body, cut for its own place in the scene.
210
+ *
211
+ * three's `Object3D.clone` builds through `new this.constructor()`, and this class's constructor
212
+ * wants a table — so every game that stood a second copy of a cooked model where it wanted a
213
+ * statue died in `assertTable` before drawing anything. The arguments are the source's own,
214
+ * which is what a copy is.
215
+ */
216
+ override clone(recursive = true): this {
217
+ return new ClusteredMesh(withOwnCut(this.geometry), this.material, this.table, {
218
+ errorPixels: this.errorPixels,
219
+ recutDistance: this.recutDistance,
220
+ }).copy(this, recursive) as this;
221
+ }
222
+
223
+ /**
224
+ * Becomes a copy of `source`, sharing the bake and the vertices and keeping a cut of its own.
225
+ *
226
+ * `Mesh.copy` shares the geometry outright, which this class cannot let it do: the cut lives in
227
+ * the geometry's index buffer, so two meshes on one geometry would overwrite each other's index
228
+ * every frame and both would draw whichever spoke last. The copy takes the vertex attributes by
229
+ * reference instead — one copy of them on the GPU, because three keys its attributes on the
230
+ * attribute — and the shared table, which is frozen at bake time and cannot go stale.
231
+ */
232
+ override copy(source: this, recursive = true): this {
233
+ super.copy(source, recursive);
234
+ if (!(source instanceof ClusteredMesh)) return this;
235
+ const geometry = withOwnCut(source.geometry);
236
+ this.#load(source.table, geometry);
237
+ this.geometry = geometry;
238
+ this.errorPixels = source.errorPixels;
239
+ this.recutDistance = source.recutDistance;
240
+ // Nothing this copy has drawn yet, so the next update has to cut it for where it stands.
241
+ this.#hasCut = false;
242
+ this.#compact(this.#finestCut());
243
+ return this;
244
+ }
245
+
246
+ /** Every cluster the bake produced from the source triangles — the mesh as authored. */
247
+ #finestCut(): number {
248
+ let selected = 0;
249
+ for (let cluster = 0; cluster * 2 < this.table.ranges.length; cluster += 1)
250
+ if ((this.table.errors[cluster * 2] as number) === 0) {
251
+ this.#selection[selected] = cluster;
252
+ selected += 1;
253
+ }
254
+ return selected;
255
+ }
256
+
257
+ /** Clusters in the current cut. */
258
+ get drawnClusters(): number {
259
+ return this.#drawnClusters;
260
+ }
261
+
262
+ /** Triangles the current cut submits. */
263
+ get drawnTriangles(): number {
264
+ return this.#drawnIndices / 3;
265
+ }
266
+
267
+ /**
268
+ * Chooses this frame's cut and compacts it into one index range.
269
+ *
270
+ * Called by the game before it renders, not from `onBeforeRender`: an empty cut has to skip the
271
+ * draw rather than submit a zero-count one, and by the time three calls `onBeforeRender` the draw
272
+ * is already on the list. A mesh this leaves invisible is made visible again by the next call,
273
+ * which is why the call belongs in the frame loop rather than in the renderer.
274
+ *
275
+ * @returns triangles the mesh will draw.
276
+ */
277
+ update(camera: Camera, viewportHeight: number): number {
278
+ const scale = pixelsPerUnit(camera, viewportHeight);
279
+ this.updateWorldMatrix(true, false);
280
+ camera.updateWorldMatrix(true, false);
281
+ this.#cameraLocal.setFromMatrixPosition(camera.matrixWorld);
282
+ this.worldToLocal(this.#cameraLocal);
283
+
284
+ const moved = this.#cameraLocal.distanceTo(this.#lastCut);
285
+ const settled =
286
+ this.#hasCut &&
287
+ moved <= this.recutDistance &&
288
+ scale === this.#lastScale &&
289
+ this.errorPixels === this.#lastErrorPixels;
290
+ if (settled) return this.drawnTriangles;
291
+
292
+ this.#lastCut.copy(this.#cameraLocal);
293
+ this.#lastScale = scale;
294
+ this.#lastErrorPixels = this.errorPixels;
295
+ this.#hasCut = true;
296
+ this.#compact(
297
+ selectClusterCut(this.table, this.#cameraLocal, scale, this.errorPixels, this.#selection),
298
+ );
299
+ return this.drawnTriangles;
300
+ }
301
+
302
+ #compact(selected: number): void {
303
+ let cursor = 0;
304
+ for (let slot = 0; slot < selected; slot += 1) {
305
+ const cluster = this.#selection[slot] as number;
306
+ const start = this.table.ranges[cluster * 2] as number;
307
+ const count = this.table.ranges[cluster * 2 + 1] as number;
308
+ this.#cut.set(this.table.indices.subarray(start, start + count), cursor);
309
+ cursor += count;
310
+ }
311
+ this.#drawnClusters = selected;
312
+ this.#drawnIndices = cursor;
313
+ const index = this.geometry.getIndex();
314
+ if (index !== null && cursor > 0) {
315
+ index.addUpdateRange(0, cursor);
316
+ index.needsUpdate = true;
317
+ }
318
+ this.geometry.setDrawRange(0, cursor);
319
+ // Nothing resolved, so nothing is submitted. A zero-count draw costs a pipeline switch, warns
320
+ // nobody, and is exactly the failure `projection-apply.ts` records for `InstancedMesh`.
321
+ this.visible = cursor > 0;
322
+ }
323
+ }
324
+
325
+ /**
326
+ * The same vertices under a second geometry, so a second mesh can hold a cut of its own.
327
+ *
328
+ * `BufferGeometry.clone()` would do this and would also copy every position, normal and uv — the
329
+ * memory a cooked model exists not to spend twice. Sharing the `BufferAttribute` objects shares
330
+ * their GPU buffers too, because three keys its attribute cache on the attribute, not the geometry.
331
+ */
332
+ function withOwnCut(geometry: BufferGeometry): BufferGeometry {
333
+ const shell = new BufferGeometry();
334
+ for (const [name, attribute] of Object.entries(geometry.attributes))
335
+ shell.setAttribute(name, attribute);
336
+ shell.boundingSphere = geometry.boundingSphere;
337
+ shell.boundingBox = geometry.boundingBox;
338
+ shell.groups = [...geometry.groups];
339
+ return shell;
340
+ }
341
+
342
+ function radiusOf(table: IClusterTable): number {
343
+ let radius = 0;
344
+ for (let cluster = 0; cluster * 4 < table.bounds.length; cluster += 1)
345
+ radius = Math.max(radius, table.bounds[cluster * 4 + 3] as number);
346
+ return radius;
347
+ }
348
+
349
+ function assertTable(table: IClusterTable): void {
350
+ const clusters = table.ranges.length / 2;
351
+ if (clusters === 0 || table.ranges.length % 2 !== 0)
352
+ throw new Error(`ClusteredMesh needs at least one cluster, got ${table.ranges.length / 2}.`);
353
+ const widths: [keyof IClusterTable, number][] = [
354
+ ["bounds", 4],
355
+ ["cones", 4],
356
+ ["errors", 2],
357
+ ["parentSpheres", 4],
358
+ ["sourceSpheres", 4],
359
+ ];
360
+ for (const [name, width] of widths) {
361
+ const array = table[name] as Float32Array;
362
+ if (array.length !== clusters * width)
363
+ throw new Error(
364
+ `ClusteredMesh table.${name} holds ${array.length} values for ${clusters} clusters; it needs ${clusters * width}.`,
365
+ );
366
+ }
367
+ for (let cluster = 0; cluster < clusters; cluster += 1) {
368
+ const start = table.ranges[cluster * 2] as number;
369
+ const count = table.ranges[cluster * 2 + 1] as number;
370
+ if (count === 0 || count % 3 !== 0 || start + count > table.indices.length)
371
+ throw new Error(
372
+ `ClusteredMesh cluster ${cluster} names indices ${start}..${start + count}, which the ${table.indices.length}-index buffer does not hold.`,
373
+ );
374
+ }
375
+ }
376
+
377
+ /** The glTF extension the asset pipeline writes the DAG into. */
378
+ export const TN_VIRTUAL_GEOMETRY = "TN_virtual_geometry";
379
+
380
+ interface IVirtualGeometryDef {
381
+ readonly clusterBounds: number;
382
+ readonly clusterCones: number;
383
+ readonly clusterErrors: number;
384
+ readonly clusterParentSpheres: number;
385
+ readonly clusterRanges: number;
386
+ readonly clusterSourceSpheres: number;
387
+ readonly indices: number;
388
+ }
389
+
390
+ interface IGltfParserLike {
391
+ readonly associations: Map<object, { meshes?: number; primitives?: number }>;
392
+ getDependency(type: string, index: number): Promise<{ array: ArrayLike<number> }>;
393
+ readonly json: {
394
+ meshes?: { primitives?: { extensions?: Record<string, unknown> }[] }[];
395
+ };
396
+ }
397
+
398
+ function typedFloat(array: ArrayLike<number>): Float32Array {
399
+ return array instanceof Float32Array ? array : Float32Array.from(array);
400
+ }
401
+
402
+ function typedUint(array: ArrayLike<number>): Uint32Array {
403
+ return array instanceof Uint32Array ? array : Uint32Array.from(array);
404
+ }
405
+
406
+ const TABLE_FIELDS: readonly (keyof IVirtualGeometryDef)[] = [
407
+ "clusterBounds",
408
+ "clusterCones",
409
+ "clusterErrors",
410
+ "clusterParentSpheres",
411
+ "clusterRanges",
412
+ "clusterSourceSpheres",
413
+ "indices",
414
+ ];
415
+
416
+ async function readTable(
417
+ parser: IGltfParserLike,
418
+ def: IVirtualGeometryDef,
419
+ ): Promise<IClusterTable> {
420
+ // Fails closed. A file written by an older bake is missing fields this one needs, and a missing
421
+ // field would otherwise surface as an unreadable crash inside `GLTFLoader` rather than as a
422
+ // sentence naming the asset that needs re-baking.
423
+ const missing = TABLE_FIELDS.filter((field) => typeof def[field] !== "number");
424
+ if (missing.length > 0)
425
+ throw new Error(
426
+ `TN_VIRTUAL_GEOMETRY_INCOMPLETE: the ${TN_VIRTUAL_GEOMETRY} payload is missing ${missing.join(", ")}; re-bake the model with the current asset pipeline.`,
427
+ );
428
+ const accessor = async (index: number): Promise<ArrayLike<number>> =>
429
+ (await parser.getDependency("accessor", index)).array;
430
+ const [bounds, cones, errors, parentSpheres, ranges, sourceSpheres, indices] = await Promise.all([
431
+ accessor(def.clusterBounds),
432
+ accessor(def.clusterCones),
433
+ accessor(def.clusterErrors),
434
+ accessor(def.clusterParentSpheres),
435
+ accessor(def.clusterRanges),
436
+ accessor(def.clusterSourceSpheres),
437
+ accessor(def.indices),
438
+ ]);
439
+ return {
440
+ bounds: typedFloat(bounds as Float32Array),
441
+ cones: typedFloat(cones as Float32Array),
442
+ errors: typedFloat(errors as Float32Array),
443
+ indices: typedUint(indices as Uint32Array),
444
+ parentSpheres: typedFloat(parentSpheres as Float32Array),
445
+ ranges: typedUint(ranges as Uint32Array),
446
+ sourceSpheres: typedFloat(sourceSpheres as Float32Array),
447
+ };
448
+ }
449
+
450
+ /**
451
+ * `GLTFLoader` plugin that returns a {@link ClusteredMesh} for any primitive carrying the bake.
452
+ *
453
+ * A game that never turned the pipeline pass on never meets this class; a game that did gets the
454
+ * clustered mesh with no code change beyond calling {@link updateClusteredMeshes} once a frame.
455
+ * There is no runtime switch, because a minutes-long bake cannot happen at run time and a second
456
+ * way to say the same thing is a second thing to get wrong.
457
+ */
458
+ export class VirtualGeometryPlugin {
459
+ readonly name = TN_VIRTUAL_GEOMETRY;
460
+
461
+ constructor(private readonly parser: IGltfParserLike) {}
462
+
463
+ async afterRoot(result: { scene?: Mesh }): Promise<void> {
464
+ void result;
465
+ const swaps: { clustered: ClusteredMesh; plain: Mesh }[] = [];
466
+ for (const [object, association] of this.parser.associations) {
467
+ const plain = object as Mesh;
468
+ // Files baked before the bake learned to skip skinned bodies still carry the extension.
469
+ if (plain.isMesh !== true || (plain as { isSkinnedMesh?: boolean }).isSkinnedMesh === true)
470
+ continue;
471
+ const { meshes, primitives } = association;
472
+ if (meshes === undefined || primitives === undefined) continue;
473
+ const def = this.parser.json.meshes?.[meshes]?.primitives?.[primitives]?.extensions?.[
474
+ TN_VIRTUAL_GEOMETRY
475
+ ] as IVirtualGeometryDef | undefined;
476
+ if (def === undefined) continue;
477
+ const clustered = new ClusteredMesh(
478
+ plain.geometry,
479
+ plain.material,
480
+ await readTable(this.parser, def),
481
+ );
482
+ clustered.name = plain.name;
483
+ clustered.position.copy(plain.position);
484
+ clustered.quaternion.copy(plain.quaternion);
485
+ clustered.scale.copy(plain.scale);
486
+ clustered.castShadow = plain.castShadow;
487
+ clustered.receiveShadow = plain.receiveShadow;
488
+ swaps.push({ clustered, plain });
489
+ }
490
+ for (const { clustered, plain } of swaps) {
491
+ const parent = plain.parent;
492
+ if (parent === null) continue;
493
+ parent.add(clustered);
494
+ parent.remove(plain);
495
+ this.parser.associations.set(
496
+ clustered,
497
+ this.parser.associations.get(plain) ?? { meshes: undefined, primitives: undefined },
498
+ );
499
+ }
500
+ }
501
+ }
502
+
503
+ /** What a batch root exposes to the walk. Structural, so this module does not import the batch. */
504
+ interface IClusteredBatchRootLike {
505
+ readonly batch: { update(camera: Camera, viewportHeight: number): number };
506
+ }
507
+
508
+ function isBatchRoot(object: object): object is IClusteredBatchRootLike {
509
+ const candidate = (object as Partial<IClusteredBatchRootLike>).batch;
510
+ return typeof (candidate as { update?: unknown } | undefined)?.update === "function";
511
+ }
512
+
513
+ /** The event surface this module subscribes to. Structural, so traverse-only stand-ins keep working. */
514
+ interface IGraphNode {
515
+ addEventListener(type: string, listener: (event: never) => void): void;
516
+ removeEventListener(type: string, listener: (event: never) => void): void;
517
+ traverse(callback: (object: object) => void): void;
518
+ }
519
+
520
+ interface IChildGraphEvent {
521
+ readonly child?: unknown;
522
+ }
523
+
524
+ interface ITrackedRoot {
525
+ /** Every clustered mesh and batch root currently under the root. */
526
+ readonly items: Set<object>;
527
+ /** Nodes already carrying this root's listeners. */
528
+ readonly hooked: WeakSet<object>;
529
+ readonly onAdded: (event: IChildGraphEvent) => void;
530
+ readonly onRemoved: (event: IChildGraphEvent) => void;
531
+ }
532
+
533
+ /**
534
+ * Per-root tracking, keyed weakly so a disposed scene drops out on its own: the map holds no
535
+ * strong reference to any root, and a tracking holds none back to its root either.
536
+ */
537
+ const trackedRoots = new WeakMap<object, ITrackedRoot>();
538
+
539
+ function isGraphNode(root: object): root is IGraphNode {
540
+ const candidate = root as Partial<IGraphNode>;
541
+ return (
542
+ typeof candidate.traverse === "function" &&
543
+ typeof candidate.addEventListener === "function" &&
544
+ typeof candidate.removeEventListener === "function"
545
+ );
546
+ }
547
+
548
+ /** Subscribes a subtree that just arrived under a tracked root, collecting what it holds. */
549
+ function hookSubtree(tracking: ITrackedRoot, subtree: object): void {
550
+ (subtree as IGraphNode).traverse((node) => {
551
+ if (node instanceof ClusteredMesh || isBatchRoot(node)) tracking.items.add(node);
552
+ if (tracking.hooked.has(node)) return;
553
+ tracking.hooked.add(node);
554
+ const link = node as Partial<IGraphNode>;
555
+ // A traverse-only stand-in nested inside a real graph cannot carry listeners; it also cannot
556
+ // be a clustered mesh or a batch root, both of which extend `Object3D`.
557
+ if (typeof link.addEventListener !== "function") return;
558
+ link.addEventListener("childadded", tracking.onAdded);
559
+ (link as IGraphNode).addEventListener("childremoved", tracking.onRemoved);
560
+ });
561
+ }
562
+
563
+ /** Forgets a subtree that just left a tracked root, detaching its listeners as it goes. */
564
+ function unhookSubtree(tracking: ITrackedRoot, subtree: object): void {
565
+ (subtree as IGraphNode).traverse((node) => {
566
+ tracking.items.delete(node);
567
+ if (!tracking.hooked.has(node)) return;
568
+ tracking.hooked.delete(node);
569
+ const link = node as Partial<IGraphNode>;
570
+ if (typeof link.removeEventListener !== "function") return;
571
+ link.removeEventListener("childadded", tracking.onAdded);
572
+ (link as IGraphNode).removeEventListener("childremoved", tracking.onRemoved);
573
+ });
574
+ }
575
+
576
+ function trackRoot(root: IGraphNode): ITrackedRoot {
577
+ const existing = trackedRoots.get(root);
578
+ if (existing !== undefined) return existing;
579
+ const tracking: ITrackedRoot = {
580
+ hooked: new WeakSet(),
581
+ items: new Set(),
582
+ onAdded: (event) => {
583
+ const child: unknown = event.child;
584
+ if (typeof child === "object" && child !== null && isGraphNode(child))
585
+ hookSubtree(tracking, child);
586
+ },
587
+ onRemoved: (event) => {
588
+ const child: unknown = event.child;
589
+ if (
590
+ typeof child === "object" &&
591
+ child !== null &&
592
+ typeof (child as Partial<IGraphNode>).traverse === "function"
593
+ )
594
+ unhookSubtree(tracking, child);
595
+ },
596
+ };
597
+ trackedRoots.set(root, tracking);
598
+ // One census per root, ever: every later arrival and departure reports itself through the
599
+ // `childadded` / `childremoved` events three fires on the direct parent, and `add` removes
600
+ // from the old parent first, so a reparent is a removal followed by an arrival.
601
+ hookSubtree(tracking, root);
602
+ return tracking;
603
+ }
604
+
605
+ function trianglesOf(object: object, camera: Camera, viewportHeight: number): number {
606
+ if (object instanceof ClusteredMesh) return object.update(camera, viewportHeight);
607
+ if (isBatchRoot(object)) return object.batch.update(camera, viewportHeight);
608
+ return 0;
609
+ }
610
+
611
+ /**
612
+ * Takes every clustered mesh and every clustered batch under `root` through this frame's cut.
613
+ *
614
+ * The engine calls this itself, once a frame, before the render — virtual geometry ships on and a
615
+ * game that has to remember to call something has not been given it. The first call censuses the
616
+ * root once and subscribes to its graph events; later calls walk only the clustered meshes and
617
+ * batch roots themselves, so a scene holding neither costs a map lookup.
618
+ *
619
+ * @returns triangles the clustered meshes and batches will submit.
620
+ */
621
+ export function updateClusteredMeshes(
622
+ root: { traverse(callback: (object: object) => void): void },
623
+ camera: Camera,
624
+ viewportHeight: number,
625
+ ): number {
626
+ // A bare traverse-only stand-in has no event surface to subscribe to, so it keeps the old
627
+ // discovery walk. Everything three builds takes the tracked path.
628
+ if (!isGraphNode(root)) {
629
+ let triangles = 0;
630
+ root.traverse((object) => {
631
+ triangles += trianglesOf(object, camera, viewportHeight);
632
+ });
633
+ return triangles;
634
+ }
635
+ let triangles = 0;
636
+ for (const item of trackRoot(root).items) triangles += trianglesOf(item, camera, viewportHeight);
637
+ return triangles;
638
+ }