@threenative/core 0.3.6 → 0.3.8

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 (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Jz4Fdoeb.d.ts → game-cb99J-YE.d.ts} +100 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22443 -12423
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +48 -9
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +525 -105
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +25 -1
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +54 -8
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
@@ -0,0 +1,792 @@
1
+ import { type BufferGeometry, type Material, type Mesh, Object3D } from "three";
2
+
3
+ import { isEngineRenderHook } from "./engine-render-hook.js";
4
+ import type { Registry } from "./entities.js";
5
+ import { mergeByMaterial } from "./merge-parts.js";
6
+ import { displacesVertices, hasMorphAttributes } from "./projection-plan.js";
7
+ import { unbilled } from "./startup-offscreen-bytes.js";
8
+
9
+ /**
10
+ * Static meshes that share a material become one draw, with no call from the game.
11
+ *
12
+ * `mergeByMaterial` was an opt-in call, so every kit that forgot it drew one mesh per box: the
13
+ * shooter town drew 375 times until a hand-written `collapseTown` merged it. The engine now makes
14
+ * that choice where it can measure it. A mesh is merged when the scene has stopped changing for
15
+ * {@link SETTLE_FRAMES} frames and the mesh did not move, hide or change material in them. The game
16
+ * calls nothing and keeps its own objects.
17
+ *
18
+ * **Correctness is unconditional, the merge is opportunistic.** The sources leave the graph but stay
19
+ * alive, and every one is checked each frame. When the game moves, hides, re-materials or re-adds a
20
+ * source, or moves an ancestor of one, that source comes back at once and its triangles are zeroed
21
+ * in the merged index, so nothing is rebuilt and nothing pops. A raycast against the merged mesh is
22
+ * answered by the sources, so a hit still names the authored mesh with its own `userData`.
23
+ *
24
+ * Only appearance-neutral meshes qualify: opaque, single material, a plain `position`/`normal`/`uv`
25
+ * geometry, no render hook, no skin, morph, instancing or vertex displacement. Everything else keeps
26
+ * its draw. The merged mesh keeps the game's own material and shadow, layer and render-order flags.
27
+ *
28
+ * **Named overrides, both reported.** `userData.batch = "off"` on a mesh or any ancestor keeps that
29
+ * subtree out. `autoBatch: false` in the game config switches the pass off.
30
+ */
31
+
32
+ /** Marker printed when meshes merge or come back, and once when the pass is off. */
33
+ export const AUTO_BATCH_MARKER = "TN_AUTO_BATCH";
34
+
35
+ /**
36
+ * Frames the scene must hold still before it merges. Any motion at all, however small, differs
37
+ * bit for bit between two frames, so three are enough for anything that moves on its own, and the
38
+ * pass finishes inside the startup cover, where one expensive frame is not a hitch the player sees.
39
+ * A mesh that only moves on an event is the guard's job, not this window's.
40
+ */
41
+ const SETTLE_FRAMES = 3;
42
+
43
+ /**
44
+ * Milliseconds a frame may spend checking merged sources for changes, in the default `"spread"`
45
+ * guard. A source costs a few microseconds to check on the native engine (every property read
46
+ * crosses the bridge), so 8,000 sources checked every frame cost 20 to 40 ms; a slice per frame
47
+ * bounds the cost and the report states how many frames a change can then go unseen.
48
+ */
49
+ const GUARD_BUDGET_MS = 0.5;
50
+
51
+ /** Sources the native engine's guard compares per call, between two reads of the budget clock. */
52
+ const ENGINE_GUARD_CHUNK = 2048;
53
+
54
+ /**
55
+ * The native engine's own guard (bindings_scene.cpp): it keeps each source's state as merged and
56
+ * compares it in place, so a lap of 8,000 sources fits the budget the JS slice spent on 200.
57
+ */
58
+ interface IEngineGuard {
59
+ __tnGuardWatch(sources: readonly Mesh[]): number;
60
+ __tnGuardCheck(limit: number): ArrayLike<number>;
61
+ }
62
+
63
+ function engineGuardOf(scene: Object3D): IEngineGuard | undefined {
64
+ const host = scene as Object3D & Partial<IEngineGuard>;
65
+ return typeof host.__tnGuardWatch === "function" && typeof host.__tnGuardCheck === "function"
66
+ ? (host as Object3D & IEngineGuard)
67
+ : undefined;
68
+ }
69
+
70
+ /**
71
+ * Meshes under a game-held object that still count as that object's own parts. A held group above
72
+ * this is the level container, not a live prop, and its contents stay eligible.
73
+ */
74
+ const HELD_SUBTREE_MAX_MESHES = 256;
75
+
76
+ /** Frames the scene's shape must stay unchanged before the movement watch starts. */
77
+ const QUIET_FRAMES = 1;
78
+
79
+ /**
80
+ * Vertices one merged mesh holds before a second starts, so no single first-draw upload is a stall
81
+ * (the same bound world chunks use: 4 MiB of position, normal and uv).
82
+ */
83
+ const MAX_GROUP_VERTICES = (4 * 1024 * 1024) / 32;
84
+
85
+ const SNAPSHOT_LENGTH = 32;
86
+
87
+ const ALLOWED_ATTRIBUTES = new Set(["position", "normal", "uv"]);
88
+
89
+ /**
90
+ * The `autoBatch` object form of the game config.
91
+ *
92
+ * `guard: "spread"` (default) checks a time-bounded slice of the merged sources each frame, so a
93
+ * change the game makes to one is seen within `guardStaleFrames` frames, which the report states.
94
+ * `guard: "everyFrame"` checks every source every frame: exact, and it costs what the report says.
95
+ */
96
+ export interface IAutoBatchConfig {
97
+ readonly guard?: "spread" | "everyFrame";
98
+ }
99
+
100
+ export interface IAutoBatchOptions extends IAutoBatchConfig {
101
+ /** `false` is the named override: nothing merges, and the pass says so once. Default true. */
102
+ readonly enabled?: boolean;
103
+ /** The game's entities: the objects they hold are live props and keep their own draw. */
104
+ readonly entities?: Registry;
105
+ /** Where marker lines go. Default `console.info`. */
106
+ readonly report?: (line: string) => void;
107
+ /** Test seam for the settle window. */
108
+ readonly settleFrames?: number;
109
+ }
110
+
111
+ /** What the pass has done, cumulative except the two scan counts, which describe the last scan. */
112
+ export interface IAutoBatchCensus {
113
+ readonly enabled: boolean;
114
+ /** Source meshes now drawn through a merged mesh. */
115
+ readonly meshes: number;
116
+ /** Merged meshes drawn for them. */
117
+ readonly draws: number;
118
+ /** Meshes kept out by `userData.batch = "off"` in the last scan. */
119
+ readonly optedOut: number;
120
+ /** Meshes that moved or changed while the scene settled in the last scan. */
121
+ readonly unsettled: number;
122
+ /** Sources given back after the game changed them. */
123
+ readonly restored: number;
124
+ /** Merges the engine refused; the meshes stay as authored. */
125
+ readonly refused: number;
126
+ /** Meshes kept out because a game entity holds them, in the last scan. */
127
+ readonly heldByEntities: number;
128
+ /** Frames a change to one merged source can go unseen: 1 when every source is checked each frame. */
129
+ readonly guardStaleFrames: number;
130
+ }
131
+
132
+ interface IGroup {
133
+ readonly merged: Mesh;
134
+ readonly sources: IRecord[];
135
+ live: number;
136
+ }
137
+
138
+ interface IRecord {
139
+ readonly mesh: Mesh;
140
+ readonly parent: Object3D | null;
141
+ readonly material: Material;
142
+ readonly geometry: BufferGeometry;
143
+ readonly stamp: Float64Array;
144
+ readonly group: IGroup;
145
+ /** The source's vertices in the merged position buffer: [vertexStart, vertexStart + vertexCount). */
146
+ readonly vertexStart: number;
147
+ readonly vertexCount: number;
148
+ out: boolean;
149
+ }
150
+
151
+ interface IAncestor {
152
+ readonly parent: Object3D | null;
153
+ readonly stamp: Float64Array;
154
+ readonly records: IRecord[];
155
+ }
156
+
157
+ type State = "idle" | "quiet" | "watching";
158
+
159
+ const scratch = new Float64Array(SNAPSHOT_LENGTH);
160
+
161
+ /** Sources still drawn through a merged mesh, mapped to the group that draws them. */
162
+ const sourceGroups = new WeakMap<Object3D, IGroup>();
163
+
164
+ /** True while the engine draws `object` through a merged mesh and keeps it hidden. */
165
+ export function isAutoBatchSource(object: Object3D): boolean {
166
+ return sourceGroups.has(object);
167
+ }
168
+
169
+ /** What a ray test needs to answer for a hidden source from its merged mesh. */
170
+ export interface IAutoBatchPick {
171
+ readonly merged: Mesh;
172
+ /** The authored source that owns merged vertex `vertex`, or `undefined` once it has come back. */
173
+ sourceAt(vertex: number): Mesh | undefined;
174
+ }
175
+
176
+ /**
177
+ * The merged mesh that draws `source` in its place, or `undefined` when it is drawn on its own.
178
+ *
179
+ * A picker asks this so a ray tests one merged mesh's hierarchy instead of every source's own, and
180
+ * still names the authored mesh it hit.
181
+ */
182
+ export function autoBatchOf(source: Object3D): IAutoBatchPick | undefined {
183
+ const group = sourceGroups.get(source);
184
+ if (group === undefined) return undefined;
185
+ return { merged: group.merged, sourceAt: (vertex) => sourceAtVertex(group, vertex) };
186
+ }
187
+
188
+ function sourceAtVertex(group: IGroup, vertex: number): Mesh | undefined {
189
+ const { sources } = group;
190
+ let low = 0;
191
+ let high = sources.length - 1;
192
+ while (low < high) {
193
+ const middle = (low + high + 1) >> 1;
194
+ if ((sources[middle] as IRecord).vertexStart <= vertex) low = middle;
195
+ else high = middle - 1;
196
+ }
197
+ const record = sources[low];
198
+ return record === undefined || record.out ? undefined : record.mesh;
199
+ }
200
+
201
+ /** Merged meshes this pass made: a ray test skips them, because the authored sources answer it. */
202
+ const mergedMeshes = new WeakSet<object>();
203
+
204
+ export function isAutoBatchMerged(object: object): boolean {
205
+ return mergedMeshes.has(object);
206
+ }
207
+
208
+ /**
209
+ * Adds to one costly step by name in `globalThis.__tnEngineCost`, the bag a playtest reads per frame
210
+ * (three-native reports it as TN_ENGINE_COST), so a kit that brings back a per-frame cost fails its bound.
211
+ */
212
+ function countEngineCost(name: string, count: number): void {
213
+ if (count === 0) return;
214
+ const host = globalThis as { __tnEngineCost?: Record<string, number> };
215
+ host.__tnEngineCost ??= {};
216
+ host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + count;
217
+ }
218
+
219
+ /** Frames of guard cost averaged into the one `guard` marker line. */
220
+ const GUARD_REPORT_FRAMES = 120;
221
+
222
+ /** Position, rotation, scale, visibility, shadow and layer flags, and the manual matrix if any. */
223
+ function writeStamp(object: Object3D, into: Float64Array): void {
224
+ const { position, quaternion, scale } = object;
225
+ into[0] = position.x;
226
+ into[1] = position.y;
227
+ into[2] = position.z;
228
+ into[3] = quaternion.x;
229
+ into[4] = quaternion.y;
230
+ into[5] = quaternion.z;
231
+ into[6] = quaternion.w;
232
+ into[7] = scale.x;
233
+ into[8] = scale.y;
234
+ into[9] = scale.z;
235
+ into[10] = object.visible ? 1 : 0;
236
+ into[11] = object.castShadow ? 1 : 0;
237
+ into[12] = object.receiveShadow ? 1 : 0;
238
+ into[13] = object.renderOrder;
239
+ into[14] = object.layers.mask;
240
+ into[15] = object.matrixAutoUpdate ? 0 : 1;
241
+ // Clear the matrix slots too: `stampMatches` reuses one buffer, and a tail left by the last
242
+ // object with its own matrix made a still parent read as moved.
243
+ if (object.matrixAutoUpdate) {
244
+ into.fill(0, 16);
245
+ return;
246
+ }
247
+ const elements = object.matrix.elements;
248
+ for (let element = 0; element < 16; element += 1) into[16 + element] = elements[element] ?? 0;
249
+ }
250
+
251
+ function stampMatches(object: Object3D, stamp: Float64Array): boolean {
252
+ writeStamp(object, scratch);
253
+ for (let at = 0; at < SNAPSHOT_LENGTH; at += 1) if (scratch[at] !== stamp[at]) return false;
254
+ return true;
255
+ }
256
+
257
+ function isMesh(object: Object3D): object is Mesh {
258
+ return (object as Mesh).isMesh === true;
259
+ }
260
+
261
+ /** Whether the mesh is an ordinary opaque single-material draw the renderer owes nothing special. */
262
+ function plainDraw(mesh: Mesh): boolean {
263
+ const flags = mesh as Mesh & {
264
+ isInstancedMesh?: boolean;
265
+ isBatchedMesh?: boolean;
266
+ isSkinnedMesh?: boolean;
267
+ customDepthMaterial?: unknown;
268
+ customDistanceMaterial?: unknown;
269
+ };
270
+ if (flags.isInstancedMesh === true || flags.isBatchedMesh === true) return false;
271
+ if (flags.isSkinnedMesh === true || mesh.userData.autoBatch !== undefined) return false;
272
+ if (flags.customDepthMaterial != null || flags.customDistanceMaterial != null) return false;
273
+ const material = mesh.material as Material | Material[];
274
+ if (Array.isArray(material) || material.transparent || displacesVertices(material)) return false;
275
+ return [mesh.onBeforeRender, mesh.onAfterRender].every(
276
+ (hook) =>
277
+ hook === Object3D.prototype.onBeforeRender ||
278
+ hook === Object3D.prototype.onAfterRender ||
279
+ isEngineRenderHook(hook),
280
+ );
281
+ }
282
+
283
+ /** Whether baking the geometry into a merged buffer keeps every channel the draw reads. */
284
+ function bakeable(geometry: BufferGeometry): boolean {
285
+ if (geometry.getAttribute("position") === undefined || hasMorphAttributes(geometry)) return false;
286
+ if ((geometry as { indirect?: unknown }).indirect != null) return false;
287
+ const range = geometry.drawRange;
288
+ if (range.start !== 0 || Number.isFinite(range.count)) return false;
289
+ for (const name in geometry.attributes) if (!ALLOWED_ATTRIBUTES.has(name)) return false;
290
+ return true;
291
+ }
292
+
293
+ /** Whether merging this mesh leaves the frame looking the same. */
294
+ function mergeable(mesh: Mesh): boolean {
295
+ return plainDraw(mesh) && bakeable(mesh.geometry) && mesh.matrixWorld.determinant() > 0;
296
+ }
297
+
298
+ /** Meshes with equal keys can share a merged mesh without changing how any of them draws. */
299
+ function flagKey(mesh: Mesh): string {
300
+ const { geometry } = mesh;
301
+ const uv = geometry.getAttribute("uv") === undefined ? 0 : 1;
302
+ const normal = geometry.getAttribute("normal") === undefined ? 0 : 1;
303
+ return `${mesh.castShadow}|${mesh.receiveShadow}|${mesh.layers.mask}|${mesh.renderOrder}|${mesh.frustumCulled}|${uv}${normal}`;
304
+ }
305
+
306
+ function countMeshes(root: Object3D): number {
307
+ let count = 0;
308
+ root.traverse((object) => {
309
+ if (isMesh(object)) count += 1;
310
+ });
311
+ return count;
312
+ }
313
+
314
+ /** Objects the game's entities hold in their public fields, up to three levels deep. */
315
+ function heldObjects(entities: Registry | undefined): Set<Object3D> {
316
+ const held = new Set<Object3D>();
317
+ if (entities === undefined) return held;
318
+ const seen = new Set<object>();
319
+ const visit = (value: unknown, depth: number): void => {
320
+ if (typeof value !== "object" || value === null || seen.has(value) || seen.size > 20_000)
321
+ return;
322
+ seen.add(value);
323
+ if ((value as Object3D).isObject3D === true) {
324
+ held.add(value as Object3D);
325
+ return;
326
+ }
327
+ if (depth === 0) return;
328
+ for (const key of Object.keys(value)) visit((value as Record<string, unknown>)[key], depth - 1);
329
+ };
330
+ entities.forEach((_name, entity) => visit(entity, 3));
331
+ return held;
332
+ }
333
+
334
+ export class AutoBatch {
335
+ readonly #scene: Object3D;
336
+ readonly #enabled: boolean;
337
+ readonly #report: (line: string) => void;
338
+ readonly #settleFrames: number;
339
+ /** Objects that must never merge again: a source the game changed, an ancestor it moved. */
340
+ readonly #excluded = new WeakSet<Object3D>();
341
+ #records: IRecord[] = [];
342
+ readonly #ancestors = new Map<Object3D, IAncestor>();
343
+ #watched = new Map<Mesh, Float64Array>();
344
+ #state: State = "idle";
345
+ #known = Number.NaN;
346
+ #seen = 0;
347
+ #frames = 0;
348
+ #announcedOff = false;
349
+ #meshes = 0;
350
+ #draws = 0;
351
+ #optedOut = 0;
352
+ #unsettled = 0;
353
+ #restored = 0;
354
+ #refused = 0;
355
+ #guardMs = 0;
356
+ #guardFrames = 0;
357
+ #held = 0;
358
+ #cursor = 0;
359
+ #staleFrames = 1;
360
+ readonly #entities: Registry | undefined;
361
+ readonly #everyFrame: boolean;
362
+ readonly #engine: IEngineGuard | undefined;
363
+ /** Adds and removes counted at the scene's top two levels; see {@link AutoBatch.#shape}. */
364
+ #shapeChanges = 0;
365
+ /** Top-level children whose own `childadded` and `childremoved` are counted. */
366
+ readonly #levelOne = new Set<Object3D>();
367
+ /** Children added to or removed from the scene since the last frame, to start or stop counting. */
368
+ #arrived: Object3D[] = [];
369
+ readonly #onTopChild = (event: { child: Object3D }): void => {
370
+ this.#shapeChanges += 1;
371
+ this.#arrived.push(event.child);
372
+ };
373
+ readonly #onChild = (): void => {
374
+ this.#shapeChanges += 1;
375
+ };
376
+
377
+ constructor(scene: Object3D, options: IAutoBatchOptions = {}) {
378
+ this.#scene = scene;
379
+ this.#enabled = options.enabled !== false;
380
+ this.#report = options.report ?? ((line) => console.info(line));
381
+ this.#settleFrames = options.settleFrames ?? SETTLE_FRAMES;
382
+ this.#entities = options.entities;
383
+ this.#everyFrame = options.guard === "everyFrame";
384
+ this.#engine = engineGuardOf(scene);
385
+ if (!this.#enabled) return;
386
+ scene.addEventListener("childadded", this.#onTopChild);
387
+ scene.addEventListener("childremoved", this.#onTopChild);
388
+ this.#arrived = [...scene.children];
389
+ }
390
+
391
+ get census(): IAutoBatchCensus {
392
+ return {
393
+ enabled: this.#enabled,
394
+ meshes: this.#meshes,
395
+ draws: this.#draws,
396
+ optedOut: this.#optedOut,
397
+ unsettled: this.#unsettled,
398
+ restored: this.#restored,
399
+ refused: this.#refused,
400
+ heldByEntities: this.#held,
401
+ guardStaleFrames: this.#staleFrames,
402
+ };
403
+ }
404
+
405
+ /** Once per frame, before the scene is walked for drawing. */
406
+ update(): void {
407
+ if (!this.#enabled) {
408
+ if (!this.#announcedOff) {
409
+ this.#announcedOff = true;
410
+ this.#report(
411
+ `${AUTO_BATCH_MARKER}:${JSON.stringify({ enabled: false, override: "autoBatch: false" })}`,
412
+ );
413
+ }
414
+ return;
415
+ }
416
+ this.#verify();
417
+ const shape = this.#shape();
418
+ if (this.#state === "idle") {
419
+ if (shape === this.#known) return;
420
+ this.#state = "quiet";
421
+ this.#seen = shape;
422
+ this.#frames = 0;
423
+ return;
424
+ }
425
+ if (shape !== this.#seen) {
426
+ this.#state = "quiet";
427
+ this.#seen = shape;
428
+ this.#frames = 0;
429
+ return;
430
+ }
431
+ this.#frames += 1;
432
+ if (this.#state === "quiet" && this.#frames >= QUIET_FRAMES) {
433
+ this.#watched = this.#snapshot();
434
+ this.#state = "watching";
435
+ this.#frames = 0;
436
+ if (this.#watched.size < 2) {
437
+ // Nothing here can share a draw: the pass is finished until the scene's shape changes.
438
+ this.#known = shape;
439
+ this.#state = "idle";
440
+ }
441
+ } else if (this.#state === "watching" && this.#frames >= this.#settleFrames) {
442
+ this.#settle();
443
+ }
444
+ }
445
+
446
+ /**
447
+ * Merges now, without waiting for the scene to hold still. For the caller that knows nothing has
448
+ * moved yet: the first warm-up runs before any frame, so the merged meshes are what it compiles.
449
+ * Anything that does move later is given back by the guard.
450
+ */
451
+ settleNow(): void {
452
+ if (!this.#enabled) return;
453
+ const meshes = this.#snapshot();
454
+ if (meshes.size >= 2) this.#merge([...meshes.keys()]);
455
+ this.#watchEngine();
456
+ this.#known = this.#shape();
457
+ this.#state = "idle";
458
+ }
459
+
460
+ /** Gives every source back and forgets the scene; the game is leaving it. */
461
+ reset(): void {
462
+ for (const record of this.#records) if (!record.out) this.#giveBack(record);
463
+ this.#records = [];
464
+ this.#watchEngine();
465
+ this.#ancestors.clear();
466
+ this.#watched.clear();
467
+ this.#state = "idle";
468
+ this.#known = Number.NaN;
469
+ }
470
+
471
+ /**
472
+ * Changes when something is added to or removed from the scene's top two levels. three's own graph
473
+ * events count it, so a still frame reads no `children` list: on the native engine each read wraps
474
+ * every child across the bridge, and polling the shooter town's shape cost 10 ms a frame.
475
+ */
476
+ #shape(): number {
477
+ for (const child of this.#arrived.splice(0)) {
478
+ const top = child.parent === this.#scene;
479
+ if (top === this.#levelOne.has(child)) continue;
480
+ if (top) {
481
+ child.addEventListener("childadded", this.#onChild);
482
+ child.addEventListener("childremoved", this.#onChild);
483
+ this.#levelOne.add(child);
484
+ } else {
485
+ child.removeEventListener("childadded", this.#onChild);
486
+ child.removeEventListener("childremoved", this.#onChild);
487
+ this.#levelOne.delete(child);
488
+ }
489
+ }
490
+ return this.#shapeChanges;
491
+ }
492
+
493
+ /**
494
+ * Eligible meshes with the world matrix they were drawn at. Runs only while the scene settles, so
495
+ * its reads are no game's steady cost and the bridge census leaves them out.
496
+ */
497
+ #snapshot(): Map<Mesh, Float64Array> {
498
+ return unbilled(() => {
499
+ this.#scene.updateMatrixWorld(true);
500
+ const found = new Map<Mesh, Float64Array>();
501
+ this.#optedOut = 0;
502
+ this.#held = 0;
503
+ const held = heldObjects(this.#entities);
504
+ this.#walk(this.#scene, false, held, (mesh) => {
505
+ found.set(mesh, Float64Array.from(mesh.matrixWorld.elements));
506
+ });
507
+ return found;
508
+ });
509
+ }
510
+
511
+ #walk(
512
+ object: Object3D,
513
+ off: boolean,
514
+ held: ReadonlySet<Object3D>,
515
+ visit: (mesh: Mesh) => void,
516
+ ): void {
517
+ for (const child of object.children) {
518
+ if (
519
+ !child.visible ||
520
+ this.#excluded.has(child) ||
521
+ (child as { isLOD?: boolean }).isLOD === true
522
+ )
523
+ continue;
524
+ if (held.has(child)) {
525
+ const parts = countMeshes(child);
526
+ if (parts <= HELD_SUBTREE_MAX_MESHES) {
527
+ this.#held += parts;
528
+ continue;
529
+ }
530
+ }
531
+ const skip = off || child.userData.batch === "off";
532
+ if (isMesh(child) && mergeable(child)) {
533
+ if (skip) this.#optedOut += 1;
534
+ else visit(child);
535
+ }
536
+ this.#walk(child, skip, held, visit);
537
+ }
538
+ }
539
+
540
+ #settle(): void {
541
+ const before = this.#watched;
542
+ const stable = new Map<Mesh, Float64Array>();
543
+ const now = this.#snapshot();
544
+ let moved = 0;
545
+ for (const [mesh, matrix] of now) {
546
+ const earlier = before.get(mesh);
547
+ if (earlier !== undefined && matrix.every((value, at) => value === earlier[at]))
548
+ stable.set(mesh, matrix);
549
+ else if (earlier !== undefined) moved += 1;
550
+ }
551
+ this.#unsettled = moved;
552
+ this.#watched = new Map();
553
+ this.#merge([...stable.keys()]);
554
+ this.#watchEngine();
555
+ this.#known = this.#shape();
556
+ this.#state = "idle";
557
+ }
558
+
559
+ #merge(meshes: Mesh[]): void {
560
+ const kinds = new Map<string, Map<Material, Mesh[]>>();
561
+ for (const mesh of meshes) {
562
+ const key = flagKey(mesh);
563
+ const byMaterial = kinds.get(key) ?? new Map<Material, Mesh[]>();
564
+ kinds.set(key, byMaterial);
565
+ const material = mesh.material as Material;
566
+ const list = byMaterial.get(material);
567
+ if (list === undefined) byMaterial.set(material, [mesh]);
568
+ else list.push(mesh);
569
+ }
570
+ const before = this.#draws;
571
+ for (const byMaterial of kinds.values()) {
572
+ const members = new Set<Mesh>();
573
+ for (const list of byMaterial.values())
574
+ if (list.length > 1) for (const mesh of list) members.add(mesh);
575
+ if (members.size > 0) this.#mergeKind(members);
576
+ }
577
+ if (this.#draws === before && this.#refused === 0) return;
578
+ this.#report(`${AUTO_BATCH_MARKER}:${JSON.stringify({ event: "merged", ...this.census })}`);
579
+ }
580
+
581
+ #mergeKind(members: Set<Mesh>): void {
582
+ const first = members.values().next().value as Mesh;
583
+ const groups: Array<{ merged: Mesh; sources: readonly Mesh[] }> = [];
584
+ try {
585
+ mergeByMaterial(this.#scene, {
586
+ label: "autobatch",
587
+ maxGroupVertices: MAX_GROUP_VERTICES,
588
+ skip: (mesh) => !members.has(mesh),
589
+ onGroup: (merged, sources) => groups.push({ merged, sources }),
590
+ });
591
+ } catch (error) {
592
+ // A merge the baker refuses leaves the meshes as authored; the engine says why and moves on.
593
+ for (const mesh of members) this.#excluded.add(mesh);
594
+ this.#refused += 1;
595
+ this.#report(
596
+ `${AUTO_BATCH_MARKER}:${JSON.stringify({ event: "refused", reason: String(error) })}`,
597
+ );
598
+ return;
599
+ }
600
+ for (const { merged, sources } of groups) this.#adopt(merged, sources, first);
601
+ }
602
+
603
+ #adopt(merged: Mesh, sources: readonly Mesh[], flags: Mesh): void {
604
+ merged.castShadow = flags.castShadow;
605
+ merged.receiveShadow = flags.receiveShadow;
606
+ merged.renderOrder = flags.renderOrder;
607
+ merged.frustumCulled = flags.frustumCulled;
608
+ merged.layers.mask = flags.layers.mask;
609
+ merged.name = "autobatch";
610
+ merged.userData.autoBatch = sources.length;
611
+ mergedMeshes.add(merged);
612
+ const deindexed = merged.geometry.index === null;
613
+ const group: IGroup = { merged, sources: [], live: sources.length };
614
+ let vertexStart = 0;
615
+ for (const mesh of sources) {
616
+ const { geometry } = mesh;
617
+ const positions = geometry.getAttribute("position").count;
618
+ const vertexCount = deindexed ? (geometry.index?.count ?? positions) : positions;
619
+ const record: IRecord = {
620
+ mesh,
621
+ parent: mesh.parent,
622
+ material: mesh.material as Material,
623
+ geometry,
624
+ stamp: new Float64Array(SNAPSHOT_LENGTH),
625
+ group,
626
+ vertexStart,
627
+ vertexCount,
628
+ out: false,
629
+ };
630
+ vertexStart += vertexCount;
631
+ // The source stays where the game put it, so rays, `userData` and world matrices keep working.
632
+ // Only the renderer is told not to draw it.
633
+ mesh.visible = false;
634
+ writeStamp(mesh, record.stamp);
635
+ group.sources.push(record);
636
+ sourceGroups.set(mesh, group);
637
+ this.#records.push(record);
638
+ for (let node = mesh.parent; node !== null && node !== this.#scene; node = node.parent) {
639
+ let entry = this.#ancestors.get(node);
640
+ if (entry === undefined) {
641
+ entry = { parent: node.parent, stamp: new Float64Array(SNAPSHOT_LENGTH), records: [] };
642
+ writeStamp(node, entry.stamp);
643
+ this.#ancestors.set(node, entry);
644
+ }
645
+ entry.records.push(record);
646
+ }
647
+ }
648
+ this.#scene.add(merged);
649
+ this.#meshes += sources.length;
650
+ this.#draws += 1;
651
+ }
652
+
653
+ #verify(): void {
654
+ if (this.#records.length === 0) return;
655
+ const started = performance.now();
656
+ let given = this.#checkAncestors();
657
+ given += this.#checkSources(started);
658
+ this.#guardMs += performance.now() - started;
659
+ this.#guardFrames += 1;
660
+ if (this.#guardFrames === GUARD_REPORT_FRAMES) {
661
+ this.#report(
662
+ `${AUTO_BATCH_MARKER}:${JSON.stringify({ event: "guard", frames: GUARD_REPORT_FRAMES, avgMs: this.#guardMs / GUARD_REPORT_FRAMES, ...this.census })}`,
663
+ );
664
+ }
665
+ if (given === 0) return;
666
+ this.#records = this.#records.filter((record) => !record.out);
667
+ this.#cursor = 0;
668
+ this.#watchEngine();
669
+ this.#report(
670
+ `${AUTO_BATCH_MARKER}:${JSON.stringify({ event: "restored", given, ...this.census })}`,
671
+ );
672
+ }
673
+
674
+ /** Every frame, because there are few ancestors and one moved parent changes thousands of sources. */
675
+ #checkAncestors(): number {
676
+ let given = 0;
677
+ for (const [node, entry] of this.#ancestors) {
678
+ if (node.parent === entry.parent && stampMatches(node, entry.stamp)) continue;
679
+ this.#excluded.add(node);
680
+ this.#ancestors.delete(node);
681
+ for (const record of entry.records) {
682
+ if (record.out) continue;
683
+ this.#giveBack(record);
684
+ given += 1;
685
+ }
686
+ }
687
+ return given;
688
+ }
689
+
690
+ /**
691
+ * Hands the engine's guard the sources as they are now. It runs in the same frame as each merge
692
+ * and each give-back, so no game code runs between the state merged and the state watched.
693
+ */
694
+ #watchEngine(): void {
695
+ this.#engine?.__tnGuardWatch(this.#records.map((record) => record.mesh));
696
+ }
697
+
698
+ /** A slice of the sources bounded by {@link GUARD_BUDGET_MS}, or all of them under `everyFrame`. */
699
+ #checkSources(started: number): number {
700
+ if (this.#engine !== undefined) return this.#checkInEngine(this.#engine, started);
701
+ const records = this.#records;
702
+ let given = 0;
703
+ let checked = 0;
704
+ while (checked < records.length) {
705
+ const record = records[this.#cursor] as IRecord;
706
+ this.#cursor = (this.#cursor + 1) % records.length;
707
+ checked += 1;
708
+ if (record.out) continue;
709
+ const { mesh } = record;
710
+ if (
711
+ mesh.parent !== record.parent ||
712
+ mesh.material !== record.material ||
713
+ mesh.geometry !== record.geometry ||
714
+ !stampMatches(mesh, record.stamp)
715
+ ) {
716
+ this.#giveBack(record);
717
+ given += 1;
718
+ }
719
+ if (
720
+ !this.#everyFrame &&
721
+ (checked & 15) === 0 &&
722
+ performance.now() - started > GUARD_BUDGET_MS
723
+ )
724
+ break;
725
+ }
726
+ this.#staleFrames = Math.ceil(records.length / Math.max(1, checked));
727
+ countEngineCost("autoBatchJsSourceChecks", checked);
728
+ return given;
729
+ }
730
+
731
+ /**
732
+ * {@link #checkSources} on the engine, compared where the state lives. A whole lap fits the budget
733
+ * there, but a frame need not pay for it: `spread` checks one lap per settle window, so a change is
734
+ * seen within the frames the merge waited to call the mesh still, under the same budget.
735
+ */
736
+ #checkInEngine(engine: IEngineGuard, started: number): number {
737
+ const records = this.#records;
738
+ const lap = this.#everyFrame
739
+ ? records.length
740
+ : Math.ceil(records.length / Math.max(1, this.#settleFrames));
741
+ let given = 0;
742
+ let checked = 0;
743
+ while (checked < lap) {
744
+ const limit = this.#everyFrame ? lap : Math.min(ENGINE_GUARD_CHUNK, lap - checked);
745
+ const changed = engine.__tnGuardCheck(limit);
746
+ for (let at = 0; at < changed.length; at += 1) {
747
+ const record = records[changed[at] as number];
748
+ if (record === undefined || record.out) continue;
749
+ this.#giveBack(record);
750
+ given += 1;
751
+ }
752
+ checked += limit;
753
+ if (!this.#everyFrame && performance.now() - started > GUARD_BUDGET_MS) break;
754
+ }
755
+ this.#staleFrames = Math.ceil(records.length / Math.max(1, checked));
756
+ return given;
757
+ }
758
+
759
+ /** The game changed this source: draw it on its own again and collapse its triangles in the merge. */
760
+ #giveBack(record: IRecord): void {
761
+ if (record.out) return;
762
+ record.out = true;
763
+ sourceGroups.delete(record.mesh);
764
+ this.#excluded.add(record.mesh);
765
+ this.#restored += 1;
766
+ this.#meshes -= 1;
767
+ record.mesh.visible = true;
768
+ const { group } = record;
769
+ group.live -= 1;
770
+ if (group.live > 0) this.#collapse(record);
771
+ if (group.live > 0 || group.merged.parent === null) return;
772
+ group.merged.removeFromParent();
773
+ group.merged.geometry.dispose();
774
+ this.#draws -= 1;
775
+ }
776
+
777
+ /**
778
+ * Every vertex of the source goes to the origin, so its triangles have no area and draw nothing.
779
+ * The index is left alone: a picker's hierarchy may have reordered it, but vertices stay put.
780
+ * A group with no source left skips this, because its geometry is disposed in the same call and a
781
+ * queued upload would name a buffer that no longer exists.
782
+ */
783
+ #collapse(record: IRecord): void {
784
+ const position = record.group.merged.geometry.getAttribute("position");
785
+ (position.array as Float32Array).fill(
786
+ 0,
787
+ record.vertexStart * position.itemSize,
788
+ (record.vertexStart + record.vertexCount) * position.itemSize,
789
+ );
790
+ position.needsUpdate = true;
791
+ }
792
+ }