@threenative/core 0.3.3 → 0.3.5

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 (182) hide show
  1. package/capabilities.json +2019 -59
  2. package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
  3. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  4. package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  5. package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
  6. package/dist/hot.d.ts +5 -5
  7. package/dist/index.d.ts +1131 -105
  8. package/dist/index.js +15201 -4782
  9. package/dist/model-lod-BDAUYgsS.d.ts +197 -0
  10. package/dist/playtest.d.ts +6 -4
  11. package/dist/playtest.js +84 -11
  12. package/dist/react-css.d.ts +62 -0
  13. package/dist/react-css.js +591 -0
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
  16. package/dist/terrain-jobs-worker.d.ts +2 -0
  17. package/dist/terrain-jobs-worker.js +130 -0
  18. package/dist/ui-layer.d.ts +5 -3
  19. package/dist/ui-layer.js +59 -8
  20. package/dist/world.d.ts +1596 -17
  21. package/dist/world.js +17035 -521
  22. package/gpl/fixtures/make_world_fixture.py +184 -0
  23. package/gpl/recipes/_common.py +11 -0
  24. package/gpl/recipes/decimate.py +11 -5
  25. package/gpl/recipes/export_world.py +699 -0
  26. package/mcp/blender-server.mjs +61 -4
  27. package/mcp/blender.mjs +3 -4
  28. package/mcp/engine-server.mjs +55 -21
  29. package/mcp/servers.mjs +4 -4
  30. package/package.json +15 -9
  31. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  32. package/patches/three@0.185.1.patch +8246 -389
  33. package/scripts/apply-three-patch.mjs +123 -41
  34. package/src/animation-blend.ts +264 -0
  35. package/src/animation-composition.ts +362 -0
  36. package/src/animation-layers.ts +260 -0
  37. package/src/animation-root-motion.ts +283 -0
  38. package/src/animation.ts +896 -0
  39. package/src/assets.ts +1303 -0
  40. package/src/atmosphere/index.ts +335 -0
  41. package/src/atmosphere/luts.ts +298 -0
  42. package/src/atmosphere/params.ts +323 -0
  43. package/src/audio.ts +912 -0
  44. package/src/billboard.ts +124 -0
  45. package/src/bone-lengths.ts +157 -0
  46. package/src/camera-shake.ts +116 -0
  47. package/src/canvas-layer.ts +47 -0
  48. package/src/clip-audit.ts +401 -0
  49. package/src/clustered-batch.ts +492 -0
  50. package/src/clustered-mesh.ts +638 -0
  51. package/src/compute-driven.ts +176 -0
  52. package/src/compute-timing.ts +318 -0
  53. package/src/config.ts +593 -0
  54. package/src/debug.ts +82 -0
  55. package/src/engine-render-hook.ts +25 -0
  56. package/src/entities.ts +79 -0
  57. package/src/entity-snapshot.ts +53 -0
  58. package/src/flight.ts +683 -0
  59. package/src/fluid-field.ts +748 -0
  60. package/src/fluid-particles.ts +1253 -0
  61. package/src/frame-budget.ts +1368 -0
  62. package/src/game.ts +2390 -0
  63. package/src/geometry-capture.ts +1098 -0
  64. package/src/gpu-class.ts +160 -0
  65. package/src/gpu-frame-observation.ts +424 -0
  66. package/src/gpu-readback.ts +143 -0
  67. package/src/gpu-scene-bvh.ts +464 -0
  68. package/src/grounding.ts +100 -0
  69. package/src/hot.ts +161 -0
  70. package/src/import-meta.d.ts +13 -0
  71. package/src/index.ts +1536 -0
  72. package/src/input.ts +690 -0
  73. package/src/instanced-batch-lod.ts +283 -0
  74. package/src/instanced-batch.ts +274 -0
  75. package/src/interpolation.ts +129 -0
  76. package/src/launch-diagnostics.ts +161 -0
  77. package/src/loop.ts +564 -0
  78. package/src/matrix-world.ts +245 -0
  79. package/src/merge-parts.ts +812 -0
  80. package/src/model-lod.ts +1315 -0
  81. package/src/net-protocol.ts +333 -0
  82. package/src/net-session.ts +477 -0
  83. package/src/net.ts +80 -0
  84. package/src/ocean/fft.ts +72 -0
  85. package/src/ocean/spectral.ts +728 -0
  86. package/src/particle-significance.ts +102 -0
  87. package/src/particles.ts +648 -0
  88. package/src/path-follow.ts +175 -0
  89. package/src/picking.ts +250 -0
  90. package/src/pipeline-census.ts +1566 -0
  91. package/src/platform.ts +210 -0
  92. package/src/playtest.ts +839 -0
  93. package/src/pointer-events.ts +411 -0
  94. package/src/pose-measure.ts +435 -0
  95. package/src/profiling/FrameCounters.ts +231 -0
  96. package/src/profiling/Spans.ts +548 -0
  97. package/src/profiling/opacity-convention.ts +21 -0
  98. package/src/profiling/render-list-validate.ts +175 -0
  99. package/src/profiling/render-trap-audit.ts +84 -0
  100. package/src/profiling/scene-warning.ts +190 -0
  101. package/src/profiling/span-probes.ts +191 -0
  102. package/src/profiling/unlit-foliage-warning.ts +149 -0
  103. package/src/projection-apply.ts +1529 -0
  104. package/src/projection-marker.ts +142 -0
  105. package/src/projection-plan.ts +1258 -0
  106. package/src/projection-skinned.ts +419 -0
  107. package/src/projection-stability.ts +409 -0
  108. package/src/projection-uniform.ts +328 -0
  109. package/src/random.ts +41 -0
  110. package/src/react-css.ts +604 -0
  111. package/src/react-glyphs.ts +114 -0
  112. package/src/react-host.ts +576 -0
  113. package/src/react-layout.ts +265 -0
  114. package/src/react.ts +60 -0
  115. package/src/render/alpha-antialiasing.ts +159 -0
  116. package/src/render/batched-velocity.ts +126 -0
  117. package/src/render/chain.ts +1021 -0
  118. package/src/render/daylight.ts +189 -0
  119. package/src/render/depth-pyramid.ts +596 -0
  120. package/src/render/foliage-alpha.ts +166 -0
  121. package/src/render/material-key.ts +60 -0
  122. package/src/render/mesh-pool.ts +144 -0
  123. package/src/render/probe-volume.ts +1668 -0
  124. package/src/render/resolution-subrect.ts +253 -0
  125. package/src/render/velocity.ts +442 -0
  126. package/src/render/virtual-shadow-pages.ts +827 -0
  127. package/src/render/virtual-shadow-partial.ts +174 -0
  128. package/src/render/virtual-shadow.ts +3330 -0
  129. package/src/render/world-impostor-surface.ts +722 -0
  130. package/src/render/world-impostor.ts +558 -0
  131. package/src/render-camera-cull.ts +441 -0
  132. package/src/render-pass-budget.ts +501 -0
  133. package/src/renderProjection.ts +758 -0
  134. package/src/renderer-config.ts +127 -0
  135. package/src/renderer.ts +1847 -0
  136. package/src/replay-protocol.ts +85 -0
  137. package/src/replay.ts +205 -0
  138. package/src/resolution-scaler.ts +819 -0
  139. package/src/rig-preparation.ts +271 -0
  140. package/src/ripple-field.ts +432 -0
  141. package/src/scale.ts +109 -0
  142. package/src/scene.ts +239 -0
  143. package/src/schedule.ts +155 -0
  144. package/src/skeletal-mesh.ts +61 -0
  145. package/src/skeleton.ts +100 -0
  146. package/src/snow-field.ts +744 -0
  147. package/src/softbody-topology.ts +269 -0
  148. package/src/softbody.ts +516 -0
  149. package/src/sprite-animator.ts +222 -0
  150. package/src/startup-readiness.ts +386 -0
  151. package/src/state.ts +66 -0
  152. package/src/static-transform.ts +274 -0
  153. package/src/storage-buffer.ts +253 -0
  154. package/src/streaming.ts +308 -0
  155. package/src/target-fps.ts +92 -0
  156. package/src/terrain-jobs-worker.ts +17 -0
  157. package/src/terrain-jobs.ts +353 -0
  158. package/src/textures.ts +39 -0
  159. package/src/tracers.ts +237 -0
  160. package/src/ui-bridge.ts +368 -0
  161. package/src/ui-hit-regions.ts +380 -0
  162. package/src/ui-layer.ts +83 -0
  163. package/src/ui-state.ts +220 -0
  164. package/src/version.ts +2 -0
  165. package/src/viewport.ts +253 -0
  166. package/src/warmup.ts +1357 -0
  167. package/src/water-surface.ts +384 -0
  168. package/src/wave-field.ts +524 -0
  169. package/src/world-capabilities.ts +131 -0
  170. package/src/world-cell-proxy.ts +392 -0
  171. package/src/world-cells.ts +10564 -0
  172. package/src/world-gpu-scene.ts +3354 -0
  173. package/src/world-heightmap.ts +82 -0
  174. package/src/world-package.ts +469 -0
  175. package/src/world-passes.ts +582 -0
  176. package/src/world-region.ts +17 -0
  177. package/src/world-terrain-splat.ts +564 -0
  178. package/src/world-tiles.ts +3826 -0
  179. package/src/world-topology.ts +370 -0
  180. package/src/world-validate.ts +48 -0
  181. package/src/world.ts +805 -0
  182. package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
@@ -0,0 +1,1098 @@
1
+ /**
2
+ * Per-object geometry cost, measured from what the renderer actually submitted.
3
+ *
4
+ * A total triangle counter cannot name the offender: a main character can cost 500 triangles while
5
+ * a barely visible tree submits two million, and both land in the same number. `FrameBudget` stays
6
+ * authoritative for a frame's per-pass totals; this attributes a slice of those totals to the
7
+ * objects that caused them, and reconciles the two so the difference is visible rather than
8
+ * assumed away.
9
+ *
10
+ * Three properties make it a measurement rather than a guess:
11
+ *
12
+ * 1. **It counts submissions, not scene contents.** The instrument is `onBeforeRender`, which the
13
+ * renderer calls once per object, per material group, per pass, *after* frustum and projected-
14
+ * size culling. A `visible` flag is a game's intent; a submission is what the GPU was handed.
15
+ * 2. **It is armed only on request.** Nothing is installed, walked or counted until a consumer asks
16
+ * for one capture, and every hook is removed when that frame ends, is cancelled, or the scene
17
+ * exits. An idle game pays nothing.
18
+ * 3. **It says "unavailable" with a reason.** A packed batch's per-member draws, an indirect
19
+ * counter with no readback, a geometry with no recoverable source detail: each is named, never
20
+ * reported as zero and never quietly dropped, and the unattributed remainder of every pass is
21
+ * reported beside the measured total.
22
+ *
23
+ * @situation find out which scene object is submitting the frame's triangles
24
+ * @situation tell a cheap foreground character from an expensive distant prop
25
+ */
26
+
27
+ import { Frustum, Matrix4, Sphere, Vector3 } from "three";
28
+ import type { Camera, Object3D } from "three";
29
+ import { markEngineRenderHook } from "./engine-render-hook.js";
30
+ import { baseGeometryOf, conservativeViewDepth, lodPixelScale, worldSphere } from "./model-lod.js";
31
+ import type { FramePassKind, IRenderPassSample } from "./render-pass-budget.js";
32
+
33
+ /** Rows returned when a request does not name a limit. */
34
+ export const GEOMETRY_CAPTURE_DEFAULT_LIMIT = 50;
35
+
36
+ /** The most rows one request may ask for. A transport carries a report, not a scene dump. */
37
+ export const GEOMETRY_CAPTURE_MAX_LIMIT = 500;
38
+
39
+ /** The inspection ceiling, shared with scene-node observation so one scene has one limit. */
40
+ export const GEOMETRY_CAPTURE_WALK_CAP = 50_000;
41
+
42
+ /** How long a request waits for a presented world frame before answering "unavailable". */
43
+ export const GEOMETRY_CAPTURE_TIMEOUT_MS = 2_000;
44
+
45
+ /** The `userData` key a loader stamps on a model root so a clone keeps its provenance. */
46
+ export const GEOMETRY_ASSET_KEY = "tnAssetPath";
47
+
48
+ /** The playtest capability a bridge advertises when a geometry capture can be requested. */
49
+ export const GEOMETRY_CAPTURE_CAPABILITY = "runtime.geometry" as const;
50
+
51
+ /** The orderings a request may ask for. Ranking happens over the inspected scope, then slices. */
52
+ export const GEOMETRY_CAPTURE_SORTS = ["triangles", "draws", "projected"] as const;
53
+
54
+ export type GeometryCaptureSort = (typeof GEOMETRY_CAPTURE_SORTS)[number];
55
+
56
+ export interface IGeometryCaptureRequest {
57
+ /** Rows to return, 1 to `GEOMETRY_CAPTURE_MAX_LIMIT`. */
58
+ readonly limit?: number;
59
+ readonly sort?: GeometryCaptureSort;
60
+ readonly timeoutMs?: number;
61
+ }
62
+
63
+ /** What a rendered object is: the game's own object, or the mirror standing in for some of them. */
64
+ export type GeometryOwnershipKind = "exact" | "instancedBatch" | "materialBatch";
65
+
66
+ export interface IGeometryOwnership {
67
+ readonly kind: GeometryOwnershipKind;
68
+ readonly sources: readonly Object3D[];
69
+ }
70
+
71
+ /** Where a row's triangle number came from, so a derived number is never read as a measured one. */
72
+ export type GeometryTriangleSource = "renderer" | "batchMembers";
73
+
74
+ export interface IGeometryPassCost {
75
+ readonly draws: number;
76
+ readonly triangles: number;
77
+ }
78
+
79
+ export interface IGeometryCapturePass extends IGeometryPassCost {
80
+ readonly kind: FramePassKind;
81
+ /** What the rows below account for. */
82
+ readonly attributedDraws: number;
83
+ readonly attributedTriangles: number;
84
+ /**
85
+ * Measured minus attributed. Negative means the rows over-claim — a derived batch sum, say —
86
+ * which is a finding, not something to clamp away.
87
+ */
88
+ readonly unattributedDraws: number;
89
+ readonly unattributedTriangles: number;
90
+ }
91
+
92
+ export interface IGeometryCaptureMesh {
93
+ readonly id: string;
94
+ readonly name: string;
95
+ readonly path: string;
96
+ readonly type: string;
97
+ /** LOD0 triangles of this mesh, when the source detail is recoverable. */
98
+ readonly fullDetailTriangles?: number;
99
+ /** Triangles in the buffer the renderer was pointed at this frame. */
100
+ readonly selectedDetailTriangles?: number;
101
+ readonly submittedTriangles?: number;
102
+ readonly trianglesSource?: GeometryTriangleSource;
103
+ readonly draws: number;
104
+ readonly materials: number;
105
+ readonly instances?: number;
106
+ readonly submissions: Readonly<Partial<Record<FramePassKind, IGeometryPassCost>>>;
107
+ readonly batchOwner?: string;
108
+ readonly visible: boolean;
109
+ readonly inFrustum?: boolean;
110
+ readonly unavailable?: readonly string[];
111
+ }
112
+
113
+ export interface IGeometryCaptureRow {
114
+ // --- Identity ---------------------------------------------------------------------------------
115
+ readonly id: string;
116
+ readonly generation: number;
117
+ readonly name: string;
118
+ readonly path: string;
119
+ readonly type: string;
120
+ /** The logical asset this row came from, when a loader stamped one. */
121
+ readonly asset?: string;
122
+
123
+ // --- Geometry ---------------------------------------------------------------------------------
124
+ readonly fullDetailTriangles?: number;
125
+ readonly selectedDetailTriangles?: number;
126
+ readonly submittedTriangles?: number;
127
+ readonly trianglesSource?: GeometryTriangleSource;
128
+ readonly lod?: { readonly level?: number; readonly levels?: number };
129
+
130
+ // --- Camera contribution ----------------------------------------------------------------------
131
+ /** Estimated projected diameter in drawing-buffer pixels. An estimate, never a pixel count. */
132
+ readonly projectedPixels?: number;
133
+ /**
134
+ * Where those bounds landed, in drawing-buffer pixels from the top-left. An overlay outlines
135
+ * this; it is the estimated bounds' centre, not a silhouette.
136
+ */
137
+ readonly projectedCenter?: readonly [number, number];
138
+ readonly viewportFraction?: number;
139
+ readonly cameraDistance?: number;
140
+ readonly inFrustum?: boolean;
141
+ readonly visibility: "submitted" | "notSubmitted";
142
+
143
+ // --- Repetition -------------------------------------------------------------------------------
144
+ /** Submitted copies of this row's geometry, instances included. */
145
+ readonly copies: number;
146
+ readonly instances?: number;
147
+ /** Triangles counted once per distinct geometry, for a unique-inventory reading. */
148
+ readonly uniqueTriangles?: number;
149
+
150
+ // --- Submission -------------------------------------------------------------------------------
151
+ readonly draws: number;
152
+ readonly materials: number;
153
+ readonly submissions: Readonly<Partial<Record<FramePassKind, IGeometryPassCost>>>;
154
+ readonly batch?: {
155
+ readonly kind: GeometryOwnershipKind;
156
+ readonly owner: string;
157
+ readonly members: number;
158
+ readonly perMemberDrawsAvailable: boolean;
159
+ };
160
+ readonly unavailable?: readonly string[];
161
+ readonly meshes: readonly IGeometryCaptureMesh[];
162
+ }
163
+
164
+ export interface IGeometryCaptureAsset {
165
+ readonly asset: string;
166
+ readonly objects: number;
167
+ readonly submittedTriangles?: number;
168
+ readonly draws: number;
169
+ /** Triangles of the distinct geometries this asset contributed, counted once each. */
170
+ readonly uniqueTriangles?: number;
171
+ readonly unavailable?: readonly string[];
172
+ }
173
+
174
+ export interface IGeometryCaptureReport {
175
+ readonly status: "captured" | "unavailable";
176
+ /** Set when `status` is `unavailable`. A stale capture is never returned as a fresh one. */
177
+ readonly reason?: string;
178
+ readonly capturedAtMs?: number;
179
+ readonly durationMs?: number;
180
+ readonly generation?: number;
181
+ readonly tick?: number;
182
+ readonly frame?: number;
183
+ readonly backend?: string;
184
+ readonly camera?: {
185
+ readonly type: "perspective" | "orthographic" | "unknown";
186
+ readonly position: readonly [number, number, number];
187
+ readonly fov?: number;
188
+ readonly zoom?: number;
189
+ readonly near?: number;
190
+ readonly far?: number;
191
+ };
192
+ readonly viewport?: { readonly width: number; readonly height: number };
193
+ readonly sort?: GeometryCaptureSort;
194
+ readonly limit?: number;
195
+ /** Rows the inspected scope produced before the limit sliced them. */
196
+ readonly matched?: number;
197
+ readonly returned?: number;
198
+ /** True when the limit cut rows; distinct from an incomplete inspection. */
199
+ readonly rowsTruncated?: boolean;
200
+ /** False when the walk cap stopped the inspection, so no ranking is a global claim. */
201
+ readonly inspectionComplete?: boolean;
202
+ readonly partialRanking?: boolean;
203
+ readonly inspectedNodes?: number;
204
+ readonly passes?: readonly IGeometryCapturePass[];
205
+ readonly objects?: readonly IGeometryCaptureRow[];
206
+ readonly assets?: readonly IGeometryCaptureAsset[];
207
+ }
208
+
209
+ /** What the owner of the render loop hands the capture for the frame it is about to draw. */
210
+ export interface IGeometryCaptureFrame {
211
+ /** The object actually rendered — the projection's mirror when there is one, not the authored scene. */
212
+ readonly root: Object3D;
213
+ readonly camera: Camera;
214
+ readonly viewportWidth: number;
215
+ readonly viewportHeight: number;
216
+ readonly generation: number;
217
+ readonly tick?: number;
218
+ readonly frame?: number;
219
+ readonly backend?: string;
220
+ /** Who owns each rendered object, when a mirror stands between the scene and the renderer. */
221
+ readonly ownership?: ReadonlyMap<Object3D, IGeometryOwnership>;
222
+ /** The innermost active render pass, so a shadow submission does not read as main. */
223
+ readonly activePassKind?: () => FramePassKind | undefined;
224
+ }
225
+
226
+ // --- Structural views of three's objects ---------------------------------------------------------
227
+ //
228
+ // Structural, not `instanceof`: the same shape has to accept a real `Mesh`, the mirror's stand-in
229
+ // and a unit test's minimal double, exactly as the projection and the pass budget already do.
230
+
231
+ interface IAttributeLike {
232
+ readonly count?: number;
233
+ }
234
+
235
+ interface IGeometryLike {
236
+ readonly attributes?: Record<string, IAttributeLike | undefined>;
237
+ readonly index?: IAttributeLike | null;
238
+ readonly drawRange?: { readonly start: number; readonly count: number };
239
+ readonly boundingSphere?: Sphere | null;
240
+ computeBoundingSphere?: () => void;
241
+ }
242
+
243
+ interface IRenderedLike {
244
+ readonly isMesh?: boolean;
245
+ readonly isPoints?: boolean;
246
+ readonly isLine?: boolean;
247
+ readonly isLineSegments?: boolean;
248
+ readonly isLineLoop?: boolean;
249
+ readonly isInstancedMesh?: boolean;
250
+ readonly isBatchedMesh?: boolean;
251
+ readonly isLOD?: boolean;
252
+ readonly count?: number;
253
+ readonly levels?: readonly unknown[];
254
+ readonly geometry?: IGeometryLike;
255
+ readonly material?: unknown;
256
+ onBeforeRender?: RenderCallback;
257
+ }
258
+
259
+ type RenderCallback = (
260
+ renderer: unknown,
261
+ scene: unknown,
262
+ camera: unknown,
263
+ geometry: unknown,
264
+ material: unknown,
265
+ group: unknown,
266
+ ) => void;
267
+
268
+ interface IGroupLike {
269
+ readonly count?: number;
270
+ }
271
+
272
+ interface ISubmissionRecord {
273
+ readonly object: Object3D;
274
+ draws: number;
275
+ triangles: number;
276
+ trianglesAvailable: boolean;
277
+ instances: number;
278
+ readonly byPass: Map<FramePassKind, { draws: number; triangles: number }>;
279
+ readonly materials: Set<unknown>;
280
+ readonly unavailable: Set<string>;
281
+ }
282
+
283
+ interface IArmedFrame extends IGeometryCaptureFrame {
284
+ readonly restore: (() => void)[];
285
+ readonly records: Map<Object3D, ISubmissionRecord>;
286
+ inspected: number;
287
+ complete: boolean;
288
+ }
289
+
290
+ interface IPendingRequest {
291
+ readonly limit: number;
292
+ readonly sort: GeometryCaptureSort;
293
+ readonly requestedAtMs: number;
294
+ readonly settle: (report: IGeometryCaptureReport) => void;
295
+ timer?: ReturnType<typeof setTimeout>;
296
+ }
297
+
298
+ const NO_OP_RENDER: RenderCallback = () => undefined;
299
+
300
+ function now(): number {
301
+ return globalThis.performance?.now() ?? Date.now();
302
+ }
303
+
304
+ function isTriangleObject(object: IRenderedLike): boolean {
305
+ if (object.isPoints === true) return false;
306
+ if (object.isLine === true || object.isLineSegments === true || object.isLineLoop === true) {
307
+ return false;
308
+ }
309
+ return true;
310
+ }
311
+
312
+ /** Triangles in a buffer, honouring the index, the draw range and a material group. */
313
+ function geometryTriangles(
314
+ geometry: IGeometryLike | undefined,
315
+ group?: IGroupLike,
316
+ ): number | undefined {
317
+ if (geometry === undefined) return undefined;
318
+ const available = geometry.index?.count ?? geometry.attributes?.position?.count;
319
+ if (available === undefined) return undefined;
320
+ const requested = group?.count ?? geometry.drawRange?.count;
321
+ const count =
322
+ requested === undefined || !Number.isFinite(requested)
323
+ ? available
324
+ : Math.max(0, Math.min(requested, available));
325
+ return Math.floor(count / 3);
326
+ }
327
+
328
+ /** The name a row shows. A name is a label, never an identity or an asset key. */
329
+ function displayName(object: Object3D): string {
330
+ return object.name === "" ? object.type : object.name;
331
+ }
332
+
333
+ function nodePath(object: Object3D, root: Object3D): string {
334
+ const parts: string[] = [];
335
+ let node: Object3D | null = object;
336
+ while (node !== null && node !== root) {
337
+ parts.push(node.name === "" ? node.type : node.name);
338
+ node = node.parent;
339
+ }
340
+ parts.reverse();
341
+ return `/${parts.join("/")}`;
342
+ }
343
+
344
+ function assetOf(object: Object3D): string | undefined {
345
+ let node: Object3D | null = object;
346
+ while (node !== null) {
347
+ const stamped = (node.userData as Record<string, unknown> | undefined)?.[GEOMETRY_ASSET_KEY];
348
+ if (typeof stamped === "string" && stamped !== "") return stamped;
349
+ node = node.parent;
350
+ }
351
+ return undefined;
352
+ }
353
+
354
+ /**
355
+ * The object a row is about: the nearest ancestor carrying asset provenance, otherwise the
356
+ * top-level child of the rendered root. A carrier's ninety-four meshes belong to the carrier.
357
+ */
358
+ function rowRootOf(object: Object3D, root: Object3D): Object3D {
359
+ let node: Object3D = object;
360
+ let candidate: Object3D = object;
361
+ while (node.parent !== null && node !== root) {
362
+ const stamped = (node.userData as Record<string, unknown> | undefined)?.[GEOMETRY_ASSET_KEY];
363
+ if (typeof stamped === "string" && stamped !== "") return node;
364
+ if (node.parent === root) candidate = node;
365
+ node = node.parent;
366
+ }
367
+ return candidate;
368
+ }
369
+
370
+ const sphereScratch = new Sphere();
371
+ const centreScratch = new Vector3();
372
+ const projectScratch = new Vector3();
373
+
374
+ /** The world bounding sphere of one rendered object, or undefined when it has no measurable bounds. */
375
+ function objectSphere(object: Object3D, into: Sphere): boolean {
376
+ const geometry = (object as IRenderedLike).geometry;
377
+ if (geometry === undefined) return false;
378
+ if (geometry.boundingSphere === undefined || geometry.boundingSphere === null) {
379
+ geometry.computeBoundingSphere?.();
380
+ }
381
+ const local = geometry.boundingSphere;
382
+ if (local === undefined || local === null) return false;
383
+ if (!Number.isFinite(local.radius)) return false;
384
+ worldSphere(local, object, into);
385
+ return Number.isFinite(into.radius);
386
+ }
387
+
388
+ interface ICameraLike {
389
+ readonly isOrthographicCamera?: boolean;
390
+ readonly isPerspectiveCamera?: boolean;
391
+ readonly fov?: number;
392
+ readonly zoom?: number;
393
+ readonly near?: number;
394
+ readonly far?: number;
395
+ }
396
+
397
+ /** Where a world point lands in drawing-buffer pixels, measured from the top-left. */
398
+ function projectedCenter(
399
+ centre: Vector3,
400
+ camera: Camera,
401
+ viewportWidth: number,
402
+ viewportHeight: number,
403
+ ): readonly [number, number] | undefined {
404
+ if (!(viewportWidth > 0) || !(viewportHeight > 0)) return undefined;
405
+ const ndc = projectScratch.copy(centre).project(camera);
406
+ if (!Number.isFinite(ndc.x) || !Number.isFinite(ndc.y)) return undefined;
407
+ return [(ndc.x * 0.5 + 0.5) * viewportWidth, (-ndc.y * 0.5 + 0.5) * viewportHeight];
408
+ }
409
+
410
+ /**
411
+ * Projected diameter in raster pixels, and the camera distance it was derived from.
412
+ *
413
+ * A camera at or inside the bounds has no meaningful projected size, so the estimate is the whole
414
+ * viewport rather than a small number: an unknown must never read as a confident small object.
415
+ */
416
+ function projectedSize(
417
+ sphere: Sphere,
418
+ camera: Camera,
419
+ viewportHeight: number,
420
+ ): { readonly pixels: number; readonly distance: number } | undefined {
421
+ if (!(viewportHeight > 0)) return undefined;
422
+ const like = camera as ICameraLike;
423
+ const near = like.near ?? 0.1;
424
+ const distance = centreScratch
425
+ .copy(sphere.center)
426
+ .distanceTo(camera.getWorldPosition(new Vector3()));
427
+ let depth: number;
428
+ let degenerate: boolean;
429
+ try {
430
+ const view = conservativeViewDepth(camera, sphere.center, sphere.radius, near);
431
+ depth = view.depth;
432
+ degenerate = view.degenerate;
433
+ } catch {
434
+ return undefined;
435
+ }
436
+ if (like.isOrthographicCamera !== true && degenerate) {
437
+ return { distance, pixels: viewportHeight };
438
+ }
439
+ try {
440
+ const scale = lodPixelScale(camera, viewportHeight, Math.max(depth, near));
441
+ if (!Number.isFinite(scale)) return { distance, pixels: viewportHeight };
442
+ return { distance, pixels: 2 * sphere.radius * scale };
443
+ } catch {
444
+ return undefined;
445
+ }
446
+ }
447
+
448
+ /**
449
+ * The renderer's backend, for the report's stamp. A capture that does not say which backend
450
+ * produced it cannot be compared against one from another platform.
451
+ */
452
+ export function rendererBackendIdentity(raw: unknown): string | undefined {
453
+ const backend = (raw as { backend?: object } | undefined)?.backend;
454
+ const name = (backend?.constructor as { name?: unknown } | undefined)?.name;
455
+ return typeof name === "string" && name.length > 0 ? name : undefined;
456
+ }
457
+
458
+ /**
459
+ * One on-demand per-object geometry capture. One instance lives for the life of a game; it holds
460
+ * no hooks and does no work between requests.
461
+ */
462
+ export class GeometryCapture {
463
+ #pending: IPendingRequest | undefined;
464
+ #armed: IArmedFrame | undefined;
465
+
466
+ /**
467
+ * Arms one capture and answers its report. A malformed request throws rather than quietly
468
+ * choosing a scope the caller did not ask for. Concurrent requests coalesce onto one frame.
469
+ */
470
+ request(request: IGeometryCaptureRequest = {}): Promise<IGeometryCaptureReport> {
471
+ const limit = request.limit ?? GEOMETRY_CAPTURE_DEFAULT_LIMIT;
472
+ if (!Number.isInteger(limit) || limit < 1 || limit > GEOMETRY_CAPTURE_MAX_LIMIT) {
473
+ throw new Error(
474
+ `TN_GEOMETRY_CAPTURE_LIMIT: limit must be an integer from 1 to ${String(GEOMETRY_CAPTURE_MAX_LIMIT)}, got ${String(request.limit)}.`,
475
+ );
476
+ }
477
+ const sort = request.sort ?? "triangles";
478
+ if (!GEOMETRY_CAPTURE_SORTS.includes(sort)) {
479
+ throw new Error(
480
+ `TN_GEOMETRY_CAPTURE_SORT: sort must be one of ${GEOMETRY_CAPTURE_SORTS.join(", ")}, got ${String(request.sort)}.`,
481
+ );
482
+ }
483
+ const timeoutMs = request.timeoutMs ?? GEOMETRY_CAPTURE_TIMEOUT_MS;
484
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
485
+ throw new Error(
486
+ `TN_GEOMETRY_CAPTURE_TIMEOUT: timeoutMs must be a positive number, got ${String(request.timeoutMs)}.`,
487
+ );
488
+ }
489
+ const existing = this.#pending;
490
+ if (existing !== undefined) {
491
+ // Coalesce: one frame answers both, on the widest scope asked for.
492
+ return new Promise<IGeometryCaptureReport>((resolve) => {
493
+ const previous = existing.settle;
494
+ const merged: IPendingRequest = {
495
+ ...existing,
496
+ limit: Math.max(existing.limit, limit),
497
+ settle: (report) => {
498
+ previous(report);
499
+ resolve(report);
500
+ },
501
+ };
502
+ this.#pending = merged;
503
+ });
504
+ }
505
+ return new Promise<IGeometryCaptureReport>((resolve) => {
506
+ const pending: IPendingRequest = {
507
+ limit,
508
+ requestedAtMs: now(),
509
+ settle: resolve,
510
+ sort,
511
+ };
512
+ pending.timer = setTimeout(() => {
513
+ // Never answer with the previous capture as if it were this one's frame.
514
+ this.#restore();
515
+ this.#pending = undefined;
516
+ resolve({
517
+ reason: `TN_GEOMETRY_CAPTURE_NO_FRAME: no world frame was presented within ${String(timeoutMs)} ms.`,
518
+ status: "unavailable",
519
+ });
520
+ }, timeoutMs);
521
+ pending.timer.unref?.();
522
+ this.#pending = pending;
523
+ });
524
+ }
525
+
526
+ /** True while a request is waiting, which is the only condition the render loop needs to test. */
527
+ armed(): boolean {
528
+ return this.#pending !== undefined;
529
+ }
530
+
531
+ /**
532
+ * Installs the frame's submission hooks. Called immediately before the world render, and only
533
+ * while `armed()`; an idle game never reaches it.
534
+ */
535
+ beginFrame(frame: IGeometryCaptureFrame): void {
536
+ if (this.#pending === undefined) return;
537
+ this.#restore();
538
+ const armed: IArmedFrame = {
539
+ ...frame,
540
+ complete: true,
541
+ inspected: 0,
542
+ records: new Map(),
543
+ restore: [],
544
+ };
545
+ this.#armed = armed;
546
+ frame.root.traverse((object) => {
547
+ if (!armed.complete) return;
548
+ const rendered = object as IRenderedLike;
549
+ if (rendered.geometry === undefined && rendered.isBatchedMesh !== true) return;
550
+ armed.inspected += 1;
551
+ if (armed.inspected > GEOMETRY_CAPTURE_WALK_CAP) {
552
+ armed.complete = false;
553
+ return;
554
+ }
555
+ this.#hook(armed, object);
556
+ });
557
+ }
558
+
559
+ /**
560
+ * Ends the frame: removes every hook, reconciles the rows against the measured pass totals and
561
+ * answers the waiting request.
562
+ */
563
+ finishFrame(passes: readonly IRenderPassSample[]): void {
564
+ const armed = this.#armed;
565
+ const pending = this.#pending;
566
+ this.#restore();
567
+ if (armed === undefined || pending === undefined) return;
568
+ if (pending.timer !== undefined) clearTimeout(pending.timer);
569
+ this.#pending = undefined;
570
+ pending.settle(buildReport(armed, passes, pending));
571
+ }
572
+
573
+ /** Drops a pending capture and every hook. A scene exit is not a reason to report a stale frame. */
574
+ cancel(reason: string): void {
575
+ const pending = this.#pending;
576
+ this.#restore();
577
+ this.#pending = undefined;
578
+ if (pending === undefined) return;
579
+ if (pending.timer !== undefined) clearTimeout(pending.timer);
580
+ pending.settle({ reason, status: "unavailable" });
581
+ }
582
+
583
+ #hook(armed: IArmedFrame, object: Object3D): void {
584
+ const rendered = object as IRenderedLike;
585
+ const own = Object.hasOwn(object, "onBeforeRender")
586
+ ? (rendered.onBeforeRender as RenderCallback | undefined)
587
+ : undefined;
588
+ const previous = own ?? NO_OP_RENDER;
589
+ const record: ISubmissionRecord = {
590
+ byPass: new Map(),
591
+ draws: 0,
592
+ instances: 1,
593
+ materials: new Set(),
594
+ object,
595
+ triangles: 0,
596
+ trianglesAvailable: true,
597
+ unavailable: new Set(),
598
+ };
599
+ armed.records.set(object, record);
600
+ const instrumented: RenderCallback = function instrumentedOnBeforeRender(
601
+ this: unknown,
602
+ renderer,
603
+ scene,
604
+ camera,
605
+ geometry,
606
+ material,
607
+ group,
608
+ ) {
609
+ const kind = armed.activePassKind?.() ?? "main";
610
+ const pass = record.byPass.get(kind) ?? { draws: 0, triangles: 0 };
611
+ pass.draws += 1;
612
+ record.draws += 1;
613
+ record.materials.add(material);
614
+ if (rendered.isInstancedMesh === true) {
615
+ record.instances = Math.max(record.instances, Math.max(0, rendered.count ?? 0));
616
+ }
617
+ if (rendered.isBatchedMesh === true) {
618
+ // One render object, many `drawIndexed` commands, and no per-member draw the renderer
619
+ // reports. The batch's own cost is derived from its members below, never guessed here.
620
+ record.trianglesAvailable = false;
621
+ record.unavailable.add("TN_GEOMETRY_BATCHED_MESH_SUBDRAWS");
622
+ } else if (!isTriangleObject(rendered)) {
623
+ // A line or a point submits a draw and no triangles. Counting its vertices as triangles is
624
+ // how a total starts disagreeing with the renderer.
625
+ } else {
626
+ const triangles = geometryTriangles(
627
+ geometry as IGeometryLike | undefined,
628
+ group as IGroupLike | undefined,
629
+ );
630
+ if (triangles === undefined) {
631
+ record.trianglesAvailable = false;
632
+ record.unavailable.add("TN_GEOMETRY_NO_POSITION_COUNT");
633
+ } else {
634
+ const instances =
635
+ rendered.isInstancedMesh === true ? Math.max(0, rendered.count ?? 0) : 1;
636
+ const submitted = triangles * instances;
637
+ record.triangles += submitted;
638
+ pass.triangles += submitted;
639
+ }
640
+ }
641
+ record.byPass.set(kind, pass);
642
+ previous.call(this, renderer, scene, camera, geometry, material, group);
643
+ };
644
+ // Engine bookkeeping, exactly as the world's prewarm borrow is: the capture counts the draws
645
+ // the frame really submits, so it claims no object and the scene render projection may fold
646
+ // the scene away underneath it. Unmarked, an armed capture declined the projection on every
647
+ // frame and the counter then reported the collapse it had prevented.
648
+ markEngineRenderHook(instrumented);
649
+ rendered.onBeforeRender = instrumented;
650
+ armed.restore.push(() => {
651
+ if (rendered.onBeforeRender !== instrumented) return;
652
+ // Deleted, not set to undefined: three calls `object.onBeforeRender(...)` unconditionally,
653
+ // so an own `undefined` shadows the prototype's no-op and throws on the next frame.
654
+ // quality-allow: delete is the restoration, not a leak; an own `undefined` would shadow the prototype no-op and throw
655
+ // biome-ignore lint/performance/noDelete: restoring the prototype lookup is the point.
656
+ if (own === undefined) delete rendered.onBeforeRender;
657
+ else rendered.onBeforeRender = own;
658
+ });
659
+ }
660
+
661
+ #restore(): void {
662
+ const armed = this.#armed;
663
+ if (armed === undefined) return;
664
+ for (const restore of armed.restore) restore();
665
+ armed.restore.length = 0;
666
+ this.#armed = undefined;
667
+ }
668
+ }
669
+
670
+ // --- Report assembly -----------------------------------------------------------------------------
671
+
672
+ interface IMeshDraft {
673
+ readonly record: ISubmissionRecord;
674
+ readonly source: Object3D;
675
+ readonly batchOwner?: string;
676
+ readonly trianglesSource: GeometryTriangleSource;
677
+ readonly triangles?: number;
678
+ readonly draws: number;
679
+ }
680
+
681
+ function meshDraftsOf(armed: IArmedFrame): IMeshDraft[] {
682
+ const drafts: IMeshDraft[] = [];
683
+ for (const record of armed.records.values()) {
684
+ const ownership = armed.ownership?.get(record.object);
685
+ if (ownership === undefined) {
686
+ drafts.push({
687
+ draws: record.draws,
688
+ record,
689
+ source: record.object,
690
+ trianglesSource: "renderer",
691
+ ...(record.trianglesAvailable ? { triangles: record.triangles } : {}),
692
+ });
693
+ continue;
694
+ }
695
+ if (ownership.kind === "exact") {
696
+ const source = ownership.sources[0] ?? record.object;
697
+ drafts.push({
698
+ draws: record.draws,
699
+ record,
700
+ source,
701
+ trianglesSource: "renderer",
702
+ ...(record.trianglesAvailable ? { triangles: record.triangles } : {}),
703
+ });
704
+ continue;
705
+ }
706
+ // A batch is one draw however many sources it folded. Charging a whole draw to each member is
707
+ // how a merged batch reads as more expensive than the objects it replaced.
708
+ const owner = displayName(record.object);
709
+ for (const source of ownership.sources) {
710
+ const geometry = (source as IRenderedLike).geometry;
711
+ const own = geometryTriangles(geometry);
712
+ drafts.push({
713
+ batchOwner: owner,
714
+ draws: 0,
715
+ record,
716
+ source,
717
+ trianglesSource: ownership.kind === "materialBatch" ? "batchMembers" : "renderer",
718
+ ...(own === undefined ? {} : { triangles: own }),
719
+ });
720
+ }
721
+ }
722
+ return drafts;
723
+ }
724
+
725
+ /**
726
+ * What one draft contributed to one pass.
727
+ *
728
+ * An ordinary object's per-pass triangles are the ones that pass measured. A batch member owns no
729
+ * pass record of its own — the batch does — so its own geometry is what it contributed to each
730
+ * pass the batch was drawn in, and never the batch's whole total.
731
+ */
732
+ function passTrianglesOf(draft: IMeshDraft, cost: { readonly triangles: number }): number {
733
+ if (draft.batchOwner === undefined) return cost.triangles;
734
+ return draft.triangles ?? 0;
735
+ }
736
+
737
+ function sum(values: readonly (number | undefined)[]): number | undefined {
738
+ let total = 0;
739
+ let any = false;
740
+ for (const value of values) {
741
+ if (value === undefined) continue;
742
+ total += value;
743
+ any = true;
744
+ }
745
+ return any ? total : undefined;
746
+ }
747
+
748
+ function buildReport(
749
+ armed: IArmedFrame,
750
+ passes: readonly IRenderPassSample[],
751
+ pending: IPendingRequest,
752
+ ): IGeometryCaptureReport {
753
+ const drafts = meshDraftsOf(armed);
754
+ const frustum = frustumOf(armed.camera);
755
+ const groups = new Map<Object3D, IMeshDraft[]>();
756
+ for (const draft of drafts) {
757
+ const root = rowRootOf(draft.source, armed.root);
758
+ const bucket = groups.get(root);
759
+ if (bucket === undefined) groups.set(root, [draft]);
760
+ else bucket.push(draft);
761
+ }
762
+
763
+ const rows: IGeometryCaptureRow[] = [];
764
+ let index = 0;
765
+ for (const [root, members] of groups) {
766
+ rows.push(rowOf(root, members, armed, index, frustum));
767
+ index += 1;
768
+ }
769
+
770
+ const sorted = rankRows(rows, pending.sort);
771
+ const returned = sorted.slice(0, pending.limit);
772
+ const asset = assetRowsOf(rows);
773
+ const passRows = reconcile(passes, drafts);
774
+
775
+ // Every optional field is omitted rather than set to `undefined`: this report crosses the
776
+ // playtest transport, which fails closed on a key whose value is not JSON — an explicit
777
+ // `frame: undefined` took a real browser run down before it was a conditional spread.
778
+ return {
779
+ assets: asset,
780
+ camera: cameraOf(armed.camera),
781
+ capturedAtMs: now(),
782
+ durationMs: now() - pending.requestedAtMs,
783
+ generation: armed.generation,
784
+ ...(armed.backend === undefined ? {} : { backend: armed.backend }),
785
+ ...(armed.frame === undefined ? {} : { frame: armed.frame }),
786
+ inspectedNodes: Math.min(armed.inspected, GEOMETRY_CAPTURE_WALK_CAP),
787
+ inspectionComplete: armed.complete,
788
+ limit: pending.limit,
789
+ matched: rows.length,
790
+ objects: returned,
791
+ partialRanking: !armed.complete || rows.length > pending.limit,
792
+ passes: passRows,
793
+ returned: returned.length,
794
+ rowsTruncated: rows.length > pending.limit,
795
+ sort: pending.sort,
796
+ status: "captured",
797
+ viewport: { height: armed.viewportHeight, width: armed.viewportWidth },
798
+ ...(armed.tick === undefined ? {} : { tick: armed.tick }),
799
+ };
800
+ }
801
+
802
+ function rankRows(
803
+ rows: readonly IGeometryCaptureRow[],
804
+ sort: GeometryCaptureSort,
805
+ ): IGeometryCaptureRow[] {
806
+ const key = (row: IGeometryCaptureRow): number | undefined =>
807
+ sort === "draws"
808
+ ? row.draws
809
+ : sort === "projected"
810
+ ? row.projectedPixels
811
+ : row.submittedTriangles;
812
+ // An unknown cost is not a small cost. Unknowns sort after every measured row rather than
813
+ // pretending to a zero that would park the frame's worst offender at the bottom.
814
+ return [...rows].sort((left, right) => {
815
+ const a = key(left);
816
+ const b = key(right);
817
+ if (a === undefined && b === undefined) return left.path.localeCompare(right.path);
818
+ if (a === undefined) return 1;
819
+ if (b === undefined) return -1;
820
+ if (a === b) return left.path.localeCompare(right.path);
821
+ return b - a;
822
+ });
823
+ }
824
+
825
+ function rowOf(
826
+ root: Object3D,
827
+ members: readonly IMeshDraft[],
828
+ armed: IArmedFrame,
829
+ index: number,
830
+ frustum: Frustum | undefined,
831
+ ): IGeometryCaptureRow {
832
+ const meshes: IGeometryCaptureMesh[] = [];
833
+ const submissions: Partial<Record<FramePassKind, { draws: number; triangles: number }>> = {};
834
+ const unavailable = new Set<string>();
835
+ const materials = new Set<unknown>();
836
+ const uniqueGeometries = new Map<unknown, number>();
837
+ const bounds = new Sphere();
838
+ let boundsKnown = false;
839
+ let draws = 0;
840
+ let copies = 0;
841
+ let instances: number | undefined;
842
+ let submitted: number | undefined;
843
+ let selected: number | undefined;
844
+ let full: number | undefined;
845
+ let trianglesSource: GeometryTriangleSource = "renderer";
846
+ let batch: IGeometryCaptureRow["batch"];
847
+
848
+ for (const member of members) {
849
+ const source = member.source;
850
+ const rendered = source as IRenderedLike;
851
+ let memberTriangles: number | undefined;
852
+ for (const [kind, cost] of member.record.byPass) {
853
+ const into = submissions[kind] ?? { draws: 0, triangles: 0 };
854
+ // A batch member owns no draw of its own; the batch row below carries it.
855
+ into.draws += member.batchOwner === undefined ? cost.draws : 0;
856
+ const contributed = member.triangles === undefined ? 0 : passTrianglesOf(member, cost);
857
+ into.triangles += contributed;
858
+ if (member.triangles !== undefined) memberTriangles = (memberTriangles ?? 0) + contributed;
859
+ submissions[kind] = into;
860
+ }
861
+ for (const reason of member.record.unavailable) unavailable.add(reason);
862
+ for (const material of member.record.materials) materials.add(material);
863
+ draws += member.draws;
864
+ copies += member.batchOwner === undefined ? member.record.instances : 1;
865
+ if (rendered.isInstancedMesh === true) {
866
+ instances = (instances ?? 0) + Math.max(0, rendered.count ?? 0);
867
+ }
868
+ if (memberTriangles !== undefined) submitted = (submitted ?? 0) + memberTriangles;
869
+ if (member.trianglesSource === "batchMembers") trianglesSource = "batchMembers";
870
+ const geometry = rendered.geometry;
871
+ const own = geometryTriangles(geometry);
872
+ if (own !== undefined) {
873
+ selected = (selected ?? 0) + own;
874
+ if (geometry !== undefined && !uniqueGeometries.has(geometry))
875
+ uniqueGeometries.set(geometry, own);
876
+ }
877
+ const base = baseTriangles(rendered);
878
+ if (base !== undefined) full = (full ?? 0) + base;
879
+ if (member.batchOwner !== undefined) {
880
+ batch = {
881
+ kind: member.trianglesSource === "batchMembers" ? "materialBatch" : "instancedBatch",
882
+ members: members.length,
883
+ owner: member.batchOwner,
884
+ perMemberDrawsAvailable: false,
885
+ };
886
+ }
887
+ if (objectSphere(source, sphereScratch)) {
888
+ if (boundsKnown) bounds.union(sphereScratch);
889
+ else {
890
+ bounds.copy(sphereScratch);
891
+ boundsKnown = true;
892
+ }
893
+ }
894
+ meshes.push({
895
+ draws: member.draws,
896
+ id: `${String(armed.generation)}:${String(index)}:${String(meshes.length)}`,
897
+ materials: member.record.materials.size,
898
+ name: displayName(source),
899
+ path: nodePath(source, armed.root),
900
+ submissions: Object.fromEntries(
901
+ [...member.record.byPass].map(([kind, cost]) => [
902
+ kind,
903
+ {
904
+ draws: member.batchOwner === undefined ? cost.draws : 0,
905
+ triangles: member.triangles === undefined ? 0 : passTrianglesOf(member, cost),
906
+ },
907
+ ]),
908
+ ),
909
+ type: source.type,
910
+ visible: source.visible,
911
+ ...(member.batchOwner === undefined ? {} : { batchOwner: member.batchOwner }),
912
+ ...(own === undefined ? {} : { selectedDetailTriangles: own }),
913
+ ...(base === undefined ? {} : { fullDetailTriangles: base }),
914
+ ...(memberTriangles === undefined ? {} : { submittedTriangles: memberTriangles }),
915
+ ...(memberTriangles === undefined ? {} : { trianglesSource: member.trianglesSource }),
916
+ ...(rendered.isInstancedMesh === true ? { instances: Math.max(0, rendered.count ?? 0) } : {}),
917
+ ...(member.record.unavailable.size === 0
918
+ ? {}
919
+ : { unavailable: [...member.record.unavailable] }),
920
+ });
921
+ }
922
+
923
+ const projected = boundsKnown
924
+ ? projectedSize(bounds, armed.camera, armed.viewportHeight)
925
+ : undefined;
926
+ const centre = boundsKnown
927
+ ? projectedCenter(bounds.center, armed.camera, armed.viewportWidth, armed.viewportHeight)
928
+ : undefined;
929
+ // Frustum membership of the union bounds. Unknown bounds leave it unstated rather than false:
930
+ // "not in the frustum" and "we could not tell" are different answers.
931
+ const inFrustum =
932
+ boundsKnown && frustum !== undefined ? frustum.intersectsSphere(bounds) : undefined;
933
+ if (!boundsKnown) unavailable.add("TN_GEOMETRY_NO_BOUNDS");
934
+ const viewportArea = armed.viewportWidth * armed.viewportHeight;
935
+ const lod = lodOf(root);
936
+
937
+ return {
938
+ copies,
939
+ draws,
940
+ generation: armed.generation,
941
+ id: `${String(armed.generation)}:${String(index)}`,
942
+ materials: materials.size,
943
+ meshes,
944
+ name: displayName(root),
945
+ path: nodePath(root, armed.root),
946
+ submissions,
947
+ type: root.type,
948
+ // Submission is a draw the renderer made, never a cost that happens to be known. A hidden
949
+ // mesh's triangle buffer is still countable; it was not drawn.
950
+ visibility: members.some((member) => member.record.draws > 0) ? "submitted" : "notSubmitted",
951
+ ...(batch === undefined ? {} : { batch }),
952
+ ...(assetOf(root) === undefined ? {} : { asset: assetOf(root) as string }),
953
+ ...(full === undefined ? {} : { fullDetailTriangles: full }),
954
+ ...(selected === undefined ? {} : { selectedDetailTriangles: selected }),
955
+ ...(submitted === undefined ? {} : { submittedTriangles: submitted }),
956
+ ...(submitted === undefined ? {} : { trianglesSource }),
957
+ ...(instances === undefined ? {} : { instances }),
958
+ ...(inFrustum === undefined ? {} : { inFrustum }),
959
+ ...(lod === undefined ? {} : { lod }),
960
+ ...(uniqueGeometries.size === 0
961
+ ? {}
962
+ : {
963
+ uniqueTriangles: [...uniqueGeometries.values()].reduce(
964
+ (total, value) => total + value,
965
+ 0,
966
+ ),
967
+ }),
968
+ ...(projected === undefined
969
+ ? {}
970
+ : {
971
+ cameraDistance: projected.distance,
972
+ projectedPixels: projected.pixels,
973
+ ...(centre === undefined ? {} : { projectedCenter: centre }),
974
+ ...(viewportArea > 0
975
+ ? { viewportFraction: (Math.PI * (projected.pixels / 2) ** 2) / viewportArea }
976
+ : {}),
977
+ }),
978
+ ...(unavailable.size === 0 ? {} : { unavailable: [...unavailable] }),
979
+ };
980
+ }
981
+
982
+ /** LOD0 triangles, when the discrete chain can still name the source detail. */
983
+ function baseTriangles(rendered: IRenderedLike): number | undefined {
984
+ if (rendered.geometry === undefined) return undefined;
985
+ try {
986
+ const base = baseGeometryOf(rendered as Parameters<typeof baseGeometryOf>[0]);
987
+ return geometryTriangles(base as IGeometryLike);
988
+ } catch {
989
+ return undefined;
990
+ }
991
+ }
992
+
993
+ /** The capture camera's frustum, or undefined when the camera cannot be projected. */
994
+ function frustumOf(camera: Camera): Frustum | undefined {
995
+ const matrix = new Matrix4();
996
+ const projection = camera.projectionMatrix;
997
+ if (projection === undefined) return undefined;
998
+ matrix.multiplyMatrices(projection, camera.matrixWorldInverse);
999
+ return new Frustum().setFromProjectionMatrix(matrix);
1000
+ }
1001
+
1002
+ function lodOf(object: Object3D): IGeometryCaptureRow["lod"] {
1003
+ const rendered = object as IRenderedLike;
1004
+ if (rendered.isLOD !== true) return undefined;
1005
+ const levels = rendered.levels?.length;
1006
+ return levels === undefined ? undefined : { levels };
1007
+ }
1008
+
1009
+ function cameraOf(camera: Camera): NonNullable<IGeometryCaptureReport["camera"]> {
1010
+ const like = camera as ICameraLike;
1011
+ const position = camera.getWorldPosition(new Vector3());
1012
+ return {
1013
+ position: [position.x, position.y, position.z],
1014
+ type:
1015
+ like.isOrthographicCamera === true
1016
+ ? "orthographic"
1017
+ : like.isPerspectiveCamera === true
1018
+ ? "perspective"
1019
+ : "unknown",
1020
+ ...(like.fov === undefined ? {} : { fov: like.fov }),
1021
+ ...(like.zoom === undefined ? {} : { zoom: like.zoom }),
1022
+ ...(like.near === undefined ? {} : { near: like.near }),
1023
+ ...(like.far === undefined ? {} : { far: like.far }),
1024
+ };
1025
+ }
1026
+
1027
+ function assetRowsOf(rows: readonly IGeometryCaptureRow[]): IGeometryCaptureAsset[] {
1028
+ const byAsset = new Map<string, IGeometryCaptureRow[]>();
1029
+ for (const row of rows) {
1030
+ // Procedural and unknown geometry stays explicitly unattributed. A matching display name is
1031
+ // never grounds for merging two assets.
1032
+ const key = row.asset ?? "unattributed";
1033
+ const bucket = byAsset.get(key);
1034
+ if (bucket === undefined) byAsset.set(key, [row]);
1035
+ else bucket.push(row);
1036
+ }
1037
+ return [...byAsset]
1038
+ .map(([asset, group]) => {
1039
+ const unavailable = new Set<string>();
1040
+ for (const row of group) for (const reason of row.unavailable ?? []) unavailable.add(reason);
1041
+ return {
1042
+ asset,
1043
+ draws: group.reduce((total, row) => total + row.draws, 0),
1044
+ objects: group.length,
1045
+ ...(sum(group.map((row) => row.submittedTriangles)) === undefined
1046
+ ? {}
1047
+ : { submittedTriangles: sum(group.map((row) => row.submittedTriangles)) as number }),
1048
+ ...(sum(group.map((row) => row.uniqueTriangles)) === undefined
1049
+ ? {}
1050
+ : { uniqueTriangles: sum(group.map((row) => row.uniqueTriangles)) as number }),
1051
+ ...(unavailable.size === 0 ? {} : { unavailable: [...unavailable] }),
1052
+ };
1053
+ })
1054
+ .sort((left, right) => (right.submittedTriangles ?? -1) - (left.submittedTriangles ?? -1));
1055
+ }
1056
+
1057
+ /**
1058
+ * Attributed rows against the frame's measured pass totals. The remainder is reported, not hidden:
1059
+ * a report whose rows quietly account for a third of the frame is worse than one that says so.
1060
+ */
1061
+ function reconcile(
1062
+ passes: readonly IRenderPassSample[],
1063
+ drafts: readonly IMeshDraft[],
1064
+ ): IGeometryCapturePass[] {
1065
+ const measured = new Map<FramePassKind, { draws: number; triangles: number }>();
1066
+ for (const pass of passes) {
1067
+ const into = measured.get(pass.kind) ?? { draws: 0, triangles: 0 };
1068
+ into.draws += pass.draws;
1069
+ into.triangles += pass.triangles;
1070
+ measured.set(pass.kind, into);
1071
+ }
1072
+ const attributed = new Map<FramePassKind, { draws: number; triangles: number }>();
1073
+ const seen = new Set<ISubmissionRecord>();
1074
+ for (const draft of drafts) {
1075
+ for (const [kind, cost] of draft.record.byPass) {
1076
+ const into = attributed.get(kind) ?? { draws: 0, triangles: 0 };
1077
+ // A record's own draws are counted once however many sources it folded.
1078
+ if (!seen.has(draft.record)) into.draws += cost.draws;
1079
+ into.triangles += draft.triangles === undefined ? 0 : passTrianglesOf(draft, cost);
1080
+ attributed.set(kind, into);
1081
+ }
1082
+ seen.add(draft.record);
1083
+ }
1084
+ const kinds = new Set<FramePassKind>([...measured.keys(), ...attributed.keys()]);
1085
+ return [...kinds].map((kind) => {
1086
+ const total = measured.get(kind) ?? { draws: 0, triangles: 0 };
1087
+ const rows = attributed.get(kind) ?? { draws: 0, triangles: 0 };
1088
+ return {
1089
+ attributedDraws: rows.draws,
1090
+ attributedTriangles: rows.triangles,
1091
+ draws: total.draws,
1092
+ kind,
1093
+ triangles: total.triangles,
1094
+ unattributedDraws: total.draws - rows.draws,
1095
+ unattributedTriangles: total.triangles - rows.triangles,
1096
+ };
1097
+ });
1098
+ }