@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,881 @@
1
+ import { type Camera, type DepthTexture, Matrix4, PerspectiveCamera, Vector3 } from "three";
2
+ import { uniform } from "three/tsl";
3
+ import { ReadbackBuffer } from "three/webgpu";
4
+ import { DepthPyramid, type OcclusionMode } from "./render/depth-pyramid.js";
5
+ import type { IRendererLike } from "./renderer.js";
6
+ import { cullAndSelect } from "./world-gpu-reference.js";
7
+ import {
8
+ type IAssetSlot,
9
+ type IDeviceLike,
10
+ type IGpuPlacement,
11
+ type IGpuSceneBufferFootprint,
12
+ type IGpuSceneBuffers,
13
+ type IKernelResult,
14
+ type IRegion,
15
+ type IValidationReadbacks,
16
+ type IValidationSnapshot,
17
+ LOCAL_WORDS,
18
+ PLACEMENT_WORDS,
19
+ TALLY_EVERY,
20
+ VALIDATE_EVERY,
21
+ } from "./world-gpu-types.js";
22
+ import {
23
+ DRAW_ARGS_WORDS,
24
+ type GpuSceneMemory,
25
+ type GpuSceneVerdict,
26
+ type IGpuSceneComparison,
27
+ type IGpuSceneValidation,
28
+ type IMeshDraw,
29
+ MATRIX_REPORTED_KEYS,
30
+ MATRIX_TOLERANCE,
31
+ MEMORY_FIELDS,
32
+ VALIDATE_REPORTED_KEYS,
33
+ compareMeshDraws,
34
+ sameMatrices,
35
+ validationReport,
36
+ word,
37
+ xyz,
38
+ zeroComparisonProbe,
39
+ } from "./world-gpu-validation.js";
40
+
41
+ /**
42
+ * Everything the GPU scene learns by reading the device back: the opt-in dispatch validation, the
43
+ * GPU-selected tally, and the measured occlusion pass that feeds them.
44
+ *
45
+ * These are the only parts of the scene that wait on a queue submission, and a game pays for none of
46
+ * them: they run on a validation's, a tally's or a measurement's own clock. They live apart from
47
+ * {@link WorldGpuScene} because the state they keep — one readback in flight, one landed sample, the
48
+ * previous frame's camera for the pyramid — is a group of its own.
49
+ *
50
+ * Everything here is a read of the scene: placements, regions, buffers, the planes and eye of the
51
+ * last dispatch, the gate table and the footprint. The one change it asks for is `restructure()`, a
52
+ * pyramid resize being a new pipeline for the cull kernel exactly as a grown buffer is.
53
+ */
54
+
55
+ /** Scratch the occlusion measurement builds its view and eye in, reused per frame. */
56
+ const _view = new Matrix4();
57
+ const _eye = new Vector3();
58
+
59
+ /** Camera travel in one dispatch that the occlusion test reads as a cut rather than a turn. */
60
+ const OCCLUSION_CUT_METRES = 2;
61
+
62
+ /** Two projection matrices are unchanged when every element is within this. */
63
+ const VIEW_EPSILON = 1e-6;
64
+
65
+ /** Whether the projection changed; ordinary camera travel and turns are not cuts. */
66
+ function sameProjection(left: Matrix4, right: Matrix4): boolean {
67
+ for (const [index, element] of right.elements.entries())
68
+ if (Math.abs((left.elements[index] as number) - element) > VIEW_EPSILON) return false;
69
+ return true;
70
+ }
71
+
72
+ /** What a readback sees of the scene it checks, asked at the moment each read uses it. */
73
+ export interface IReadbackHost {
74
+ /** Whether the scene is on at all, which is what makes a manual fence available. */
75
+ on(): boolean;
76
+ placements(): readonly IGpuPlacement[];
77
+ regions(): readonly IRegion[];
78
+ buffers(): IGpuSceneBuffers | undefined;
79
+ /** The six frustum planes of the last dispatched camera. */
80
+ planes(): Float32Array;
81
+ /** The eye that dispatch measured every placement's distance from. */
82
+ eye(): Vector3;
83
+ /** Resident placements the scene is drawing from. */
84
+ live(): number;
85
+ gates(): readonly IAssetSlot[];
86
+ footprint(): Record<string, IGpuSceneBufferFootprint>;
87
+ /** A structural change the scene has to answer: the cull kernel is a new pipeline. */
88
+ restructure(): void;
89
+ }
90
+
91
+ /**
92
+ * The report fields a readback owns, spread into {@link IWorldGpuSceneReport}.
93
+ *
94
+ * Every one is absent rather than zero until a sample lands: "the GPU selected nothing" and "nothing
95
+ * has been read back yet" are different facts, and a zero would merge them.
96
+ */
97
+ export interface IReadbackReport {
98
+ readonly gpuInstances?: number;
99
+ readonly gpuTriangles?: number;
100
+ readonly gpuTallyAgeFrames?: number;
101
+ readonly occlusion?: IOcclusionReport;
102
+ }
103
+
104
+ /**
105
+ * What the measured occlusion pass found, when a launch asked it to measure.
106
+ *
107
+ * `reason` names why it measured nothing (`no scene depth`), and the counts and `gpuTriangles` come
108
+ * from one landed dispatch, even if a later tally was skipped for occlusion.
109
+ */
110
+ export interface IOcclusionReport {
111
+ readonly mode: OcclusionMode;
112
+ readonly reason: string;
113
+ /** Pyramid levels and the dispatches that rebuild them each frame. */
114
+ readonly levels: number;
115
+ readonly buildDispatches: number;
116
+ /** The last landed sample, and the mean over every sample that landed. */
117
+ readonly instances: number;
118
+ readonly triangles: number;
119
+ readonly meanInstances: number;
120
+ readonly meanTriangles: number;
121
+ readonly samples: number;
122
+ /** `triangles / gpuTriangles` of the same sample, which is what the go/no-go multiplies. */
123
+ readonly share: number;
124
+ readonly gpuTriangles: number;
125
+ readonly ageFrames: number;
126
+ }
127
+
128
+ /** One completed manual frame check, identified by the caller's frame and this scene's dispatch. */
129
+ export interface IReadbackFrame extends IGpuSceneComparison {
130
+ /** The caller's rendered-frame identity, never inferred from readback timing. */
131
+ readonly frame: number;
132
+ /** The dispatch whose buffers and snapshot this readback completed against. */
133
+ readonly dispatch: number;
134
+ readonly verdict: GpuSceneVerdict;
135
+ }
136
+
137
+ export class WorldGpuReadback {
138
+ readonly #host: IReadbackHost;
139
+
140
+ constructor(host: IReadbackHost) {
141
+ this.#host = host;
142
+ }
143
+
144
+ /** How many dispatches the scene has submitted, which is the clock every sample is stamped on. */
145
+ #dispatched = 0;
146
+
147
+ #draws: (() => readonly IMeshDraw[]) | undefined;
148
+ #mismatches = 0;
149
+ #matrixMismatches = 0;
150
+ #meshMismatches = 0;
151
+ #compared = 0;
152
+ #verdict: GpuSceneVerdict = "ok";
153
+ #lines: string[] = [];
154
+ #validate = false;
155
+ #validating = false;
156
+ /** Manual frame fences replace periodic samples after the first completed fence. */
157
+ #manualOnly = false;
158
+ /** The last dispatch a manual frame fence consumed; periodic checks do not move this. */
159
+ #manualDispatch = -1;
160
+ /** Reused MAP_READ buffers keep validation from allocating two fresh GPU buffers on every check. */
161
+ #validationReadbacks: IValidationReadbacks | undefined;
162
+ /** Whether the owner asked for the GPU-selected main-pass tally; a validation turns it on too. */
163
+ #tally = false;
164
+ /** What a launch asked the pyramid occlusion test to do. `measure` never changes what is drawn. */
165
+ #occlusion: OcclusionMode = "off";
166
+ /** The max-distance chain, and the previous frame's camera the test reprojects into. */
167
+ readonly #pyramid = new DepthPyramid();
168
+ readonly #previousView = new Matrix4();
169
+ readonly #previousProjection = new Matrix4();
170
+ #previousDepth:
171
+ | {
172
+ texture: DepthTexture;
173
+ width: number;
174
+ height: number;
175
+ samples: number;
176
+ version: number;
177
+ }
178
+ | undefined;
179
+ readonly #previousEye = new Vector3();
180
+ /** The previous view the occlusion test reprojects into; its uniform is made by the first kernel
181
+ * that reads it, so a world whose GPU scene never builds one asks the backend for no mat4 uniform. */
182
+ readonly #occlusionMatrix = new Matrix4();
183
+ #occlusionView: ReturnType<typeof uniform> | undefined;
184
+ readonly #occlusionCut = uniform(1);
185
+ /** Why the measure mode measured nothing, or `""` while it is measuring. */
186
+ #occlusionReason = "";
187
+ /** The last landed tally's occlusion counts, and the running mean over every sample. */
188
+ #occludedInstances = 0;
189
+ #occludedTriangles = 0;
190
+ #occlusionTotalTriangles = 0;
191
+ #occlusionSample = -1;
192
+ #occlusionSamples = 0;
193
+ #occlusionSumInstances = 0;
194
+ #occlusionSumTriangles = 0;
195
+ #tallyPending = false;
196
+ /** Dispatch the in-flight tally readback was issued on, or `-1` when none is in flight. */
197
+ #tallyRequested = -1;
198
+ /** Dispatch whose GPU state the landed tally bytes hold, or `-1` before the first lands. */
199
+ #tallySample = -1;
200
+ #tallyInstances = 0;
201
+ #tallyTriangles = 0;
202
+ #watched = false;
203
+ /** The device's last uncaptured error, reported by the next check and then cleared. */
204
+ #deviceError = "";
205
+
206
+ /** Take the modes a launch asked for. Set every time, so a re-enable reads the new answer. */
207
+ configure(validate: boolean, tally: boolean, occlusion: OcclusionMode): void {
208
+ this.#validate = validate;
209
+ this.#tally = tally;
210
+ this.#occlusion = occlusion;
211
+ }
212
+
213
+ /** What a launch asked the pyramid occlusion test to do; `off` builds no pyramid and reads no depth. */
214
+ get occlusion(): OcclusionMode {
215
+ return this.#occlusion;
216
+ }
217
+
218
+ /** Whether a measurement runs this frame, which is also whether the kernel binds the pyramid. */
219
+ get measuring(): boolean {
220
+ return this.#occlusion !== "off";
221
+ }
222
+
223
+ setDispatched(count: number): void {
224
+ this.#dispatched = count;
225
+ }
226
+
227
+ /**
228
+ * The pyramid the cull kernel reprojects into, once a launch asked to measure: the chain itself,
229
+ * the frame's cut flag, and the view uniform, made on the first kernel that reads it so a run that
230
+ * never measures asks the backend for no extra mat4.
231
+ */
232
+ occlusionBinding():
233
+ | { readonly pyramid: DepthPyramid; readonly cut: unknown; view(): unknown }
234
+ | undefined {
235
+ if (this.#occlusion === "off") return undefined;
236
+ return { cut: this.#occlusionCut, pyramid: this.#pyramid, view: () => this.#view() };
237
+ }
238
+
239
+ #view(): unknown {
240
+ this.#occlusionView ??= uniform(this.#occlusionMatrix);
241
+ return this.#occlusionView;
242
+ }
243
+
244
+ /**
245
+ * This frame's sample, if one is due: a validation every {@link VALIDATE_EVERY} dispatches, or the
246
+ * tally on its own slower clock. A validation's own readback already holds the args, so the two
247
+ * never read the same dispatch twice.
248
+ */
249
+ sample(renderer: IRendererLike): void {
250
+ if (
251
+ this.#validate === true &&
252
+ this.#manualOnly === false &&
253
+ this.#validating === false &&
254
+ this.#dispatched % VALIDATE_EVERY === 0
255
+ )
256
+ this.#compare(renderer);
257
+ else if (
258
+ this.#validate === false &&
259
+ this.#tally === true &&
260
+ (this.#occlusion === "off" || this.#occlusionCut.value === 0) &&
261
+ this.#tallyPending === false &&
262
+ (this.#tallyRequested < 0 || this.#dispatched - this.#tallyRequested >= TALLY_EVERY)
263
+ )
264
+ this.#tallyRead(renderer);
265
+ }
266
+
267
+ /**
268
+ * What the last landed readback found, so a harness can read the answer without the log: the
269
+ * verdict, how many keys it actually compared, how many disagreed on the count, how many on what
270
+ * the draw reads, how many dressed meshes drew instances their own key never owned, and the lines.
271
+ */
272
+ get validation(): {
273
+ readonly verdict: GpuSceneVerdict;
274
+ readonly compared: number;
275
+ readonly mismatched: number;
276
+ readonly matricesMismatched: number;
277
+ readonly meshMismatched: number;
278
+ readonly lines: readonly string[];
279
+ } {
280
+ return {
281
+ verdict: this.#verdict,
282
+ compared: this.#compared,
283
+ mismatched: this.#mismatches,
284
+ matricesMismatched: this.#matrixMismatches,
285
+ meshMismatched: this.#meshMismatches,
286
+ lines: this.#lines,
287
+ };
288
+ }
289
+
290
+ /**
291
+ * Read back the dispatch that just ran, once, and resolve only after both targets have settled.
292
+ *
293
+ * This is an opt-in diagnostic seam for a harness that must fence one rendered frame before it
294
+ * advances the fixed-step clock. It does not change the periodic validation path or production
295
+ * dispatches; a caller that asks twice for one dispatch is refused rather than silently counting
296
+ * one frame twice.
297
+ */
298
+ fence(renderer: IRendererLike, frame: number): Promise<IReadbackFrame> {
299
+ if (!Number.isInteger(frame) || frame < 0)
300
+ return Promise.reject(
301
+ new Error("World GPU frame validation needs a non-negative integer frame."),
302
+ );
303
+ if (this.#host.on() === false)
304
+ return Promise.reject(new Error("World GPU scene validation is unavailable."));
305
+ if (this.#dispatched <= 0)
306
+ return Promise.reject(new Error("World GPU frame validation needs a completed dispatch."));
307
+ if (this.#validating)
308
+ return Promise.reject(
309
+ new Error("World GPU frame validation already has a pending readback."),
310
+ );
311
+ if (this.#manualDispatch === this.#dispatched)
312
+ return Promise.reject(new Error("World GPU dispatch was already manually validated."));
313
+ this.#manualOnly = true;
314
+ this.#manualDispatch = this.#dispatched;
315
+ return this.#compare(renderer, frame);
316
+ }
317
+
318
+ /**
319
+ * Where the independent per-mesh check gets the CPU path's own records, registered once by the
320
+ * owner and asked only on a check's frame.
321
+ *
322
+ * The scene cannot answer this for itself: the records are the owner's, and the meshes whose
323
+ * indirect offsets are the question are the owner's too. It is asked inside {@link compare}, before
324
+ * the readback is issued, so the instances it compares are the ones the dispatch just read rather
325
+ * than whatever the cells hold when the bytes land — the same snapshot rule the rest of the check
326
+ * is built on, and the reason a walk that streams while a readback is in flight cannot make the
327
+ * check compare two different worlds.
328
+ */
329
+ drawsFrom(provider: () => readonly IMeshDraw[]): void {
330
+ this.#draws = provider;
331
+ }
332
+
333
+ /**
334
+ * Hold the device's uncaptured errors, so a check can read them instead of the console.
335
+ *
336
+ * Three already chains its own `onuncapturederror` onto the same device and prints the message,
337
+ * which is the whole reason a refused pipeline reads as a healthy run: the evidence was on screen
338
+ * as a console line nothing compared against the counts. This wraps that handler rather than
339
+ * replacing it, so three's own reporting still fires, and the last message is folded into the next
340
+ * `TN_WORLD_GPU_SCENE_VALIDATE` line. Nothing is cleared except by a check that has reported it,
341
+ * so an error that arrives between two checks still lands on the one after.
342
+ */
343
+ watch(renderer: IRendererLike): void {
344
+ const device = (renderer.raw as { backend?: { device?: IDeviceLike } })?.backend?.device;
345
+ if (device === undefined || this.#watched) return;
346
+ this.#watched = true;
347
+ const previous = device.onuncapturederror;
348
+ device.onuncapturederror = (event: unknown): void => {
349
+ this.#deviceError = uncapturedMessage(event);
350
+ if (typeof previous === "function") previous.call(device, event);
351
+ };
352
+ }
353
+
354
+ /**
355
+ * One frame of `?tnOcclusion=measure`: rebuild the max-distance chain from the depth the previous
356
+ * frame's scene pass left behind, and point the test at the camera that depth was rendered with.
357
+ *
358
+ * The depth is last frame's on purpose. This runs in `beforeRender`, before the frame's own scene
359
+ * pass draws, so the texture still holds what the last one wrote — which is the only depth there
360
+ * is, and the reason the test reprojects rather than sampling the current frame.
361
+ *
362
+ * With no scene-pass depth — no render chain installed, so nothing rendered into a target of its
363
+ * own — the mode refuses and says so in `report().occlusion.reason` rather than reporting nothing
364
+ * hidden and reading as a cull that found no work.
365
+ */
366
+ measure(renderer: IRendererLike, camera: Camera): void {
367
+ this.#occlusionCut.value = 1;
368
+ // The main pass returns on an orthographic camera before it gets here (that is a shadow level's
369
+ // own), and a linear depth in metres is a perspective projection's to begin with.
370
+ if (!(camera instanceof PerspectiveCamera)) {
371
+ this.#previousDepth = undefined;
372
+ this.#occlusionReason = "refused: not a perspective camera";
373
+ return;
374
+ }
375
+ const raw = renderer.raw as { logarithmicDepthBuffer?: boolean; reversedDepthBuffer?: boolean };
376
+ if (raw?.logarithmicDepthBuffer || raw?.reversedDepthBuffer || camera.reversedDepth) {
377
+ this.#previousDepth = undefined;
378
+ this.#occlusionReason = "refused: nonstandard depth";
379
+ return;
380
+ }
381
+ const depth = renderer.scenePassDepth?.();
382
+ const width = depth?.width ?? 0;
383
+ const height = depth?.height ?? 0;
384
+ if (depth === undefined || width < 2 || height < 2) {
385
+ this.#previousDepth = undefined;
386
+ this.#occlusionReason = "refused: no scene depth";
387
+ return;
388
+ }
389
+ this.#occlusionReason = "";
390
+ // A resized depth resizes the chain, and the chain's two buffers are what the cull kernel reads,
391
+ // so a new chain is a new pipeline: structural, like every other grow in this class.
392
+ const resized = this.#pyramid.resize(width, height);
393
+ if (resized) this.#host.restructure();
394
+ _view.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
395
+ _eye.setFromMatrixPosition(camera.matrixWorld);
396
+ // A cut skips the test for the frame: a teleport moved the camera further than a walk step, and
397
+ // a projection change means the pyramid is a different camera's depth altogether.
398
+ // ponytail: 2 m of camera travel in one dispatch is a cut. A game that teleports further per
399
+ // step than that raises the bound; one that cuts under it gets a frame of frustum-only.
400
+ const samples = depth.samples ?? 1;
401
+ const previous = this.#previousDepth;
402
+ const depthChanged =
403
+ previous?.texture !== depth.texture ||
404
+ previous.width !== width ||
405
+ previous.height !== height ||
406
+ previous.samples !== samples ||
407
+ previous.version !== depth.texture.version;
408
+ this.#occlusionCut.value =
409
+ depthChanged ||
410
+ resized ||
411
+ !sameProjection(this.#previousProjection, camera.projectionMatrix) ||
412
+ _eye.distanceTo(this.#previousEye) > OCCLUSION_CUT_METRES
413
+ ? 1
414
+ : 0;
415
+ if (this.#occlusionCut.value !== 0)
416
+ this.#occlusionReason =
417
+ depthChanged || resized ? "skipped: depth changed" : "skipped: camera cut";
418
+ this.#previousDepth = {
419
+ texture: depth.texture,
420
+ width,
421
+ height,
422
+ samples,
423
+ version: depth.texture.version,
424
+ };
425
+ this.#previousProjection.copy(camera.projectionMatrix);
426
+ // The chain first, then the camera the chain belongs to: last frame's, which is what the
427
+ // previous frame's depth recorded.
428
+ this.#pyramid.build(renderer, depth.texture, camera.near, camera.far, samples);
429
+ this.#occlusionMatrix.copy(this.#previousView);
430
+ this.#previousView.copy(_view);
431
+ this.#previousEye.copy(_eye);
432
+ }
433
+
434
+ /**
435
+ * Ask for the indirect args back, once, and tally what the GPU selected into them.
436
+ *
437
+ * This is the certificate the frame budget could not have: `renderer.info.render.triangles` counts
438
+ * a mesh's CPU window, which for an indirect draw is its capacity and therefore an upper bound,
439
+ * while the args record holds the instance count the kernel actually wrote. The readback is the
440
+ * same one a validation uses — the renderer's one staging buffer — on a slower clock, and a frame
441
+ * whose predecessor is still in flight is skipped rather than queued.
442
+ */
443
+ #tallyRead(renderer: IRendererLike): void {
444
+ const args = this.#host.buffers()?.args;
445
+ if (args === undefined) return;
446
+ const issued = this.#dispatched;
447
+ this.#tallyRequested = issued;
448
+ this.#tallyPending = true;
449
+ // Streaming may grow the args tail while this copy is in flight. Decode its own layout.
450
+ const regions = this.#host.regions().map((region) => ({ argsIndex: region.argsIndex }));
451
+ const occlusionReason = this.#occlusionReason;
452
+ renderer
453
+ .readback(args)
454
+ .then((bytes) => this.#landTally(bytes, issued, regions, occlusionReason))
455
+ .catch(() => {
456
+ this.#tallyPending = false;
457
+ });
458
+ }
459
+
460
+ /**
461
+ * Sum the landed args records: `instanceCount` over every record, and `instanceCount x indexCount`
462
+ * divided by three. A record the GPU never wrote reads as the zero it holds, which is correct —
463
+ * a key that selected nothing draws nothing.
464
+ */
465
+ #landTally(
466
+ bytes: ArrayBuffer,
467
+ issued: number,
468
+ regions: readonly Pick<IRegion, "argsIndex">[],
469
+ occlusionReason: string,
470
+ ): void {
471
+ this.#tallyPending = false;
472
+ const words = new Uint32Array(bytes);
473
+ let instances = 0;
474
+ let products = 0;
475
+ for (const region of regions) {
476
+ const record = region.argsIndex * DRAW_ARGS_WORDS;
477
+ const count = word(words, record + 1);
478
+ instances += count;
479
+ products += count * word(words, record);
480
+ }
481
+ this.#tallyInstances = instances;
482
+ this.#tallyTriangles = products / 3;
483
+ this.#tallySample = issued;
484
+ if (this.#occlusion !== "off") this.#landOcclusion(words, issued, regions, occlusionReason);
485
+ }
486
+
487
+ /**
488
+ * What the measured cull hid, out of the same landed bytes as the drawn counts.
489
+ *
490
+ * The tail of the args buffer is one word per key of measured-occlusion instances, so a hidden
491
+ * part's triangles are that word times its own `indexCount` — the same product the tally above
492
+ * sums over the records, which is why both numbers can be divided into a share without a second
493
+ * readback or a second clock.
494
+ */
495
+ #landOcclusion(
496
+ words: Uint32Array,
497
+ issued: number,
498
+ regions: readonly Pick<IRegion, "argsIndex">[],
499
+ sampleReason: string,
500
+ ): void {
501
+ let reason = sampleReason;
502
+ const tail = regions.length * DRAW_ARGS_WORDS;
503
+ if (reason === "" && words.length < tail + regions.length) reason = "skipped: short readback";
504
+ if (
505
+ reason === "" &&
506
+ regions.some(
507
+ (region, index) =>
508
+ word(words, tail + index) > word(words, region.argsIndex * DRAW_ARGS_WORDS + 1),
509
+ )
510
+ )
511
+ reason = "skipped: inconsistent readback";
512
+ if (reason !== "") {
513
+ this.#occlusionReason = reason;
514
+ console.info(
515
+ `TN_WORLD_GPU_SCENE_OCCLUSION mode=${this.#occlusion} dispatch=${String(issued)} skipped=1 reason=${reason}`,
516
+ );
517
+ return;
518
+ }
519
+ let instances = 0;
520
+ let products = 0;
521
+ for (const [index, region] of regions.entries()) {
522
+ const count = word(words, regions.length * DRAW_ARGS_WORDS + index);
523
+ instances += count;
524
+ products += count * word(words, region.argsIndex * DRAW_ARGS_WORDS);
525
+ }
526
+ this.#occludedInstances = instances;
527
+ this.#occludedTriangles = products / 3;
528
+ this.#occlusionReason = "";
529
+ this.#occlusionSample = issued;
530
+ this.#occlusionTotalTriangles = this.#tallyTriangles;
531
+ this.#occlusionSamples += 1;
532
+ this.#occlusionSumInstances += instances;
533
+ this.#occlusionSumTriangles += this.#occludedTriangles;
534
+ const report = this.report().occlusion;
535
+ if (report === undefined) return;
536
+ const line =
537
+ `TN_WORLD_GPU_SCENE_OCCLUSION mode=${report.mode} levels=${String(report.levels)} ` +
538
+ `dispatch=${String(issued)} reason=${report.reason || "none"} ` +
539
+ `wouldCullInstances=${String(report.instances)} wouldCullTriangles=${String(report.triangles)} ` +
540
+ `gpuInstances=${String(this.#tallyInstances)} gpuTriangles=${String(this.#tallyTriangles)} ` +
541
+ `share=${report.share.toFixed(4)}`;
542
+ console.info(line);
543
+ }
544
+
545
+ /**
546
+ * Read the indirect args and the compacted matrices back and hold both against the reference, over
547
+ * the placements, camera and gate table the dispatch just read — copied at this moment, in this
548
+ * turn, so a structural change landing while the bytes are in flight changes nothing about what
549
+ * they are held against.
550
+ *
551
+ * The reference is {@link cullAndSelect} on the CPU, so this is the kernel measured against the
552
+ * loop it mirrors — the only place the TSL itself is ever checked. It costs two queue submissions
553
+ * and two mapped buffers every {@link VALIDATE_EVERY} dispatches, which is why it is a mode and
554
+ * not a default: a game never pays for it and a walk is never measured with it on. One check is in
555
+ * flight at a time, so every report answers a dispatch of its own.
556
+ *
557
+ * The counts alone are not the draw: a key can land every instance it owes into a record whose
558
+ * `firstInstance` points at the wrong run, or whose `indexCount` names no triangle, or into a
559
+ * region the mesh does not read — and a real WebGPU walk printed `ok` over 200 keys whose
560
+ * `indexCount` was zero, with the forest it was supposed to draw missing from the picture and its
561
+ * shadows still on the ground. So the matrices are read back too, and the same check that reads
562
+ * them holds the record's two CPU-owned words against what the key's geometry and layout say.
563
+ *
564
+ * And the third check reads nothing this file wrote: the owner's own dressed meshes, each with the
565
+ * indirect record its own geometry points at, against the instances the owner's own CPU path
566
+ * composes for the key that mesh is named. Both families above can only confirm that the kernel
567
+ * and the reference agree, which a wrong key-to-record mapping makes them agree on; only these two
568
+ * were not written by the same hand. See {@link compareMeshDraws}.
569
+ */
570
+ #compare(renderer: IRendererLike, frame = -1): Promise<IReadbackFrame> {
571
+ const snapshot = this.#snapshot();
572
+ if (snapshot.args === undefined || snapshot.drawn === undefined)
573
+ return Promise.reject(new Error("World GPU frame validation has no dispatched buffers."));
574
+ const reference = cullAndSelect(snapshot);
575
+ // Taken now, with the snapshot, and not when the readback lands: see `drawsFrom`.
576
+ const draws = this.#draws?.() ?? [];
577
+ const issued = this.#dispatched;
578
+ const readbacks = this.#readbacksFor(snapshot);
579
+ this.#validating = true;
580
+ const occlusionReason = this.#occlusionReason;
581
+ const reads = [
582
+ renderer.readback(snapshot.args, readbacks.args),
583
+ renderer.readback(snapshot.drawn, readbacks.drawn),
584
+ ] as const;
585
+ const complete = Promise.all(reads)
586
+ .then(([argsBytes, drawnBytes]) => {
587
+ // The same landed args feed the tally, so a validation pays for it and this adds no copy.
588
+ this.#landTally(argsBytes, issued, snapshot.regions, occlusionReason);
589
+ const input = this.#against(
590
+ snapshot,
591
+ reference,
592
+ new Uint32Array(argsBytes),
593
+ new Float32Array(drawnBytes),
594
+ draws,
595
+ );
596
+ const report = this.#publish(renderer, input);
597
+ return { ...input, dispatch: issued, frame, verdict: report.verdict };
598
+ })
599
+ .catch((reason: unknown) => {
600
+ // A readback that never lands is a check that never ran, and saying so is the whole point:
601
+ // this line used to end the chain and leave the last verdict standing as if it were fresh.
602
+ const input: IGpuSceneComparison = {
603
+ cause: `readback-failed: ${String(reason instanceof Error ? reason.message : reason)}`,
604
+ compared: 0,
605
+ deviceError: this.#deviceError,
606
+ instancesCpu: 0,
607
+ instancesGpu: 0,
608
+ matricesMismatched: 0,
609
+ meshMismatched: 0,
610
+ meshMismatches: [],
611
+ mismatched: 0,
612
+ mismatches: [],
613
+ matrixMismatches: [],
614
+ placed: snapshot.placed,
615
+ };
616
+ const report = this.#publish(renderer, input);
617
+ return { ...input, dispatch: issued, frame, verdict: report.verdict };
618
+ });
619
+ // Promise.all reports the first failure, but its rejection does not mean the other GPU copy has
620
+ // stopped. Release only after both copies settle, so a pending map cannot race a reused target.
621
+ return complete.finally(async () => {
622
+ await Promise.allSettled(reads);
623
+ readbacks.args.release();
624
+ readbacks.drawn.release();
625
+ if (this.#validationReadbacks !== readbacks) {
626
+ readbacks.args.dispose();
627
+ readbacks.drawn.dispose();
628
+ }
629
+ this.#validating = false;
630
+ });
631
+ }
632
+
633
+ #readbacksFor(snapshot: IValidationSnapshot): IValidationReadbacks {
634
+ const argsBytes = Math.max(
635
+ 4,
636
+ (snapshot.args as { array: { byteLength: number } }).array.byteLength,
637
+ );
638
+ const drawnBytes = Math.max(
639
+ 4,
640
+ (snapshot.drawn as { array: { byteLength: number } }).array.byteLength,
641
+ );
642
+ const current = this.#validationReadbacks;
643
+ if (
644
+ current !== undefined &&
645
+ current.args.maxByteLength >= argsBytes &&
646
+ current.drawn.maxByteLength >= drawnBytes
647
+ )
648
+ return current;
649
+ current?.args.dispose();
650
+ current?.drawn.dispose();
651
+ this.#validationReadbacks = {
652
+ args: new ReadbackBuffer(argsBytes),
653
+ drawn: new ReadbackBuffer(drawnBytes),
654
+ };
655
+ return this.#validationReadbacks;
656
+ }
657
+
658
+ /**
659
+ * A copy of everything the dispatch that is running right now reads: the source records, the slot
660
+ * and gate tables, the region and args layout, the frustum planes and the eye.
661
+ *
662
+ * One flat array holds the placement records and each copy is a view into it, so a twenty-thousand
663
+ * placement walk costs one allocation rather than forty thousand. The gate and region tables are
664
+ * copied shallowly, which is whole: an asset's gate definition is replaced rather than edited, and
665
+ * a region is spread into a fresh object, so nothing reachable from a snapshot can move under it.
666
+ */
667
+ #snapshot(): IValidationSnapshot {
668
+ const flat = new Float32Array(this.#host.placements().length * PLACEMENT_WORDS);
669
+ const placements = this.#host.placements().map((placement, index) => {
670
+ const at = index * PLACEMENT_WORDS;
671
+ flat.set(placement.matrix, at);
672
+ flat.set(placement.centre, at + LOCAL_WORDS);
673
+ return {
674
+ centre: flat.subarray(at + LOCAL_WORDS, at + LOCAL_WORDS + 4),
675
+ matrix: flat.subarray(at, at + LOCAL_WORDS),
676
+ scale: placement.scale,
677
+ slot: placement.slot,
678
+ };
679
+ });
680
+ return {
681
+ args: this.#host.buffers()?.args,
682
+ camera: {
683
+ planes: this.#host.planes().slice(),
684
+ x: this.#host.eye().x,
685
+ y: this.#host.eye().y,
686
+ z: this.#host.eye().z,
687
+ },
688
+ count: placements.length,
689
+ drawn: this.#host.buffers()?.drawn,
690
+ placed: this.#host.live(),
691
+ placements,
692
+ regionCount: this.#host.regions().length,
693
+ regions: this.#host.regions().map((region) => ({ ...region, local: region.local.slice() })),
694
+ slots: this.#host.gates().map((slot) => ({ ...slot })),
695
+ };
696
+ }
697
+
698
+ /** One readback's bytes against its own dispatch's reference: the counts, then the draw, then the meshes. */
699
+ #against(
700
+ snapshot: IValidationSnapshot,
701
+ reference: IKernelResult,
702
+ gpu: Uint32Array,
703
+ drawn: Float32Array,
704
+ draws: readonly IMeshDraw[],
705
+ ): IGpuSceneComparison {
706
+ const mismatches: string[] = [];
707
+ const matrixMismatches: string[] = [];
708
+ let mismatched = 0;
709
+ let matricesMismatched = 0;
710
+ let instancesGpu = 0;
711
+ let instancesCpu = 0;
712
+ for (const [index, region] of snapshot.regions.entries()) {
713
+ const record = region.argsIndex * DRAW_ARGS_WORDS;
714
+ // A readback that landed short is a mismatch, not a hole in the report: `word` reads out of
715
+ // range as the zero a record that was never written holds.
716
+ const landed = word(gpu, record + 1);
717
+ const expected = reference.counts[index] as number;
718
+ instancesGpu += landed;
719
+ instancesCpu += expected;
720
+ if (landed !== expected) {
721
+ mismatched += 1;
722
+ if (mismatches.length < VALIDATE_REPORTED_KEYS)
723
+ mismatches.push(
724
+ `${region.name ?? `#${String(index)}`} gpu=${String(landed)} cpu=${String(expected)}`,
725
+ );
726
+ }
727
+ const firstInstance = word(gpu, record + 4);
728
+ const indexCount = word(gpu, record);
729
+ const agrees =
730
+ firstInstance === region.start &&
731
+ indexCount === region.indexCount &&
732
+ sameMatrices(
733
+ drawn,
734
+ firstInstance,
735
+ landed,
736
+ reference.drawn,
737
+ region.start,
738
+ expected,
739
+ MATRIX_TOLERANCE,
740
+ );
741
+ if (agrees) continue;
742
+ matricesMismatched += 1;
743
+ if (matrixMismatches.length < MATRIX_REPORTED_KEYS)
744
+ matrixMismatches.push(
745
+ `${region.name ?? `#${String(index)}`} ` +
746
+ `first gpu=${xyz(drawn, firstInstance)} cpu=${xyz(reference.drawn, region.start)} ` +
747
+ `firstInstance gpu=${String(firstInstance)} expected=${String(region.start)} ` +
748
+ `indexCount gpu=${String(indexCount)} expected=${String(region.indexCount)}`,
749
+ );
750
+ }
751
+ // Off the snapshot's own regions: which key each mesh is, which record it reads and what it
752
+ // should be holding are the owner's numbers, and the whole point is that nothing in this file
753
+ // chose them.
754
+ const meshes = compareMeshDraws(gpu, drawn, draws, snapshot.regions);
755
+ // Both totals at zero is the case that never says why it saw nothing: name the snapshot's own
756
+ // camera and nearest live placement, the two inputs a real static validation needs to tell a
757
+ // missing source from a camera, sphere, range or frustum that rejected every one it held.
758
+ const probe =
759
+ instancesGpu === 0 && instancesCpu === 0 ? zeroComparisonProbe(snapshot) : undefined;
760
+ return {
761
+ compared: snapshot.regions.length,
762
+ deviceError: this.#deviceError,
763
+ instancesCpu,
764
+ instancesGpu,
765
+ matricesMismatched,
766
+ meshMismatched: meshes.mismatched,
767
+ meshMismatches: meshes.mismatches,
768
+ mismatched,
769
+ mismatches,
770
+ matrixMismatches,
771
+ placed: snapshot.placed,
772
+ ...(probe === undefined ? {} : { probe }),
773
+ };
774
+ }
775
+
776
+ /**
777
+ * One verdict, stored for a harness to read and printed once, with its cause if it failed.
778
+ *
779
+ * The line also carries what the device and this scene held when the check reported, read here
780
+ * rather than polled: `renderer.raw.info.memory` is Three's own tally and `footprint()` is this
781
+ * scene's allocation, so a readback that leaks its staging buffer shows up as growing
782
+ * `readbackBuffers`/`readbackBuffersSize` across reports instead of only as a later OOM. A backend
783
+ * that tracks no memory field contributes none, and no field is ever printed as a fake zero.
784
+ */
785
+ #publish(renderer: IRendererLike, input: IGpuSceneComparison): IGpuSceneValidation {
786
+ const source = (renderer.raw as { info?: { memory?: Partial<Record<string, unknown>> } })?.info
787
+ ?.memory;
788
+ let memory: GpuSceneMemory | undefined;
789
+ // A backend Three keeps no memory tally for contributes nothing, footprint included: a scene
790
+ // number printed next to absent device numbers reads as if the device had been measured.
791
+ if (source !== undefined) {
792
+ memory = {};
793
+ for (const name of MEMORY_FIELDS) {
794
+ const value = source[name];
795
+ if (typeof value === "number" && Number.isFinite(value)) memory[name] = value;
796
+ }
797
+ const footprint = Object.values(this.#host.footprint());
798
+ if (footprint.length > 0)
799
+ memory.footprintBytes = footprint.reduce((sum, buffer) => sum + buffer.bytes, 0);
800
+ }
801
+ const report = validationReport(
802
+ Object.keys(memory ?? {}).length === 0 ? input : { ...input, memory },
803
+ );
804
+ this.#verdict = report.verdict;
805
+ this.#compared = input.compared;
806
+ this.#mismatches = input.mismatched;
807
+ this.#matrixMismatches = input.matricesMismatched;
808
+ this.#meshMismatches = input.meshMismatched;
809
+ this.#lines = [...report.lines];
810
+ // Reported, so cleared: an error is folded into exactly the check that saw it.
811
+ this.#deviceError = "";
812
+ const name =
813
+ "log" in renderer ? (renderer.log as ((message: string) => void) | undefined) : undefined;
814
+ const say = typeof name === "function" ? name : console.info.bind(console);
815
+ say(report.line);
816
+ for (const line of report.lines) say(`TN_WORLD_GPU_SCENE_VALIDATE ${line}`);
817
+ return report;
818
+ }
819
+
820
+ /** What the tally and the occlusion measurement report, absent until a sample lands. */
821
+ report(): IReadbackReport {
822
+ return {
823
+ ...(this.#tallySample < 0
824
+ ? {}
825
+ : {
826
+ gpuInstances: this.#tallyInstances,
827
+ gpuTallyAgeFrames: this.#dispatched - this.#tallySample,
828
+ gpuTriangles: this.#tallyTriangles,
829
+ }),
830
+ ...(this.#occlusion === "off"
831
+ ? {}
832
+ : {
833
+ occlusion: {
834
+ ageFrames: this.#occlusionSample < 0 ? 0 : this.#dispatched - this.#occlusionSample,
835
+ buildDispatches: this.#pyramid.levels,
836
+ instances: this.#occludedInstances,
837
+ levels: this.#pyramid.levels,
838
+ meanInstances:
839
+ this.#occlusionSamples === 0
840
+ ? 0
841
+ : Math.round(this.#occlusionSumInstances / this.#occlusionSamples),
842
+ meanTriangles:
843
+ this.#occlusionSamples === 0
844
+ ? 0
845
+ : Math.round(this.#occlusionSumTriangles / this.#occlusionSamples),
846
+ mode: this.#occlusion,
847
+ reason: this.#occlusionReason,
848
+ samples: this.#occlusionSamples,
849
+ gpuTriangles: this.#occlusionTotalTriangles,
850
+ share:
851
+ this.#occlusionTotalTriangles === 0
852
+ ? 0
853
+ : this.#occludedTriangles / this.#occlusionTotalTriangles,
854
+ triangles: this.#occludedTriangles,
855
+ },
856
+ }),
857
+ };
858
+ }
859
+
860
+ /** Give back the staging buffers and the pyramid. A readback still in flight keeps its pair. */
861
+ dispose(): void {
862
+ const readbacks = this.#validationReadbacks;
863
+ this.#validationReadbacks = undefined;
864
+ if (!this.#validating) {
865
+ readbacks?.args.dispose();
866
+ readbacks?.drawn.dispose();
867
+ }
868
+ // Unsampled from here, so a report read after teardown says "nothing has been read back yet"
869
+ // rather than naming the last sample of a scene that no longer exists.
870
+ this.#tallyPending = false;
871
+ this.#tallyRequested = -1;
872
+ this.#tallySample = -1;
873
+ this.#pyramid.dispose();
874
+ }
875
+ }
876
+
877
+ function uncapturedMessage(event: unknown): string {
878
+ const error = (event as { error?: { message?: string; constructor?: { name?: string } } }).error;
879
+ const kind = error?.constructor?.name ?? "GPUError";
880
+ return `${kind}: ${(error?.message ?? "no message").replace(/\s+/gu, " ").trim()}`;
881
+ }