@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,441 @@
1
+ import { type Camera, Frustum, Matrix4, type Object3D, Vector3 } from "three";
2
+
3
+ import { isRenderable } from "./projection-plan.js";
4
+
5
+ /**
6
+ * Do not submit what the render camera cannot resolve.
7
+ *
8
+ * Every 3D game eventually pays for the same mistake: a distant roster, a far hull, a prop that
9
+ * projects to a fraction of a pixel still costs a full draw submission — measured at roughly 14 µs
10
+ * per draw on the GPU-free CPU path — while contributing nothing a player can see. The engine
11
+ * knows the render camera, the object's world bounds and the drawing-buffer height, so it can take
12
+ * that draw without the game discovering the rule by hand.
13
+ *
14
+ * The rule is deliberately narrow, and it never acts on a bound it cannot trust. An object is
15
+ * skipped only when its **world bounding sphere** projects to fewer pixels than
16
+ * {@link DEFAULT_MINIMUM_PROJECTED_PIXELS} *in the camera about to render it*, and only when
17
+ * nothing offers a reason to keep it: {@link alwaysRender}, a shadow caster, a camera-attached
18
+ * object, an object that already set `frustumCulled = false`, or a bound that is absent,
19
+ * degenerate (a zero or non-finite radius is not a size) or stale (the position buffer was
20
+ * rewritten after the sphere was computed — a changed buffer is recomputed, never trusted). The
21
+ * one flag it writes is `Object3D.visible`,
22
+ * which three reads after batch grouping; `castShadow`, `layers` and `frustumCulled` are never
23
+ * touched, because flipping those per frame churns the projection's batch key and can make the
24
+ * whole scene decline.
25
+ *
26
+ * The default is conservative on purpose. An object whose projected diameter is below one pixel
27
+ * cannot cover a whole pixel of the frame; **0.5 px** is half of that bound and four times more
28
+ * conservative than the 2 px a shipped game tuned by a pixel-diff ladder. A game that measured its
29
+ * own scenery and wants more names a larger `renderer.minimumProjectedPixels`.
30
+ */
31
+
32
+ /**
33
+ * The projected diameter, in raster pixels, below which an object is not submitted.
34
+ *
35
+ * Half a pixel is the conservative rung: it removes only objects that cannot light a full pixel,
36
+ * rather than the objects a 2 px ladder removed. A game that wants the tuned cut sets
37
+ * `renderer.minimumProjectedPixels` on the same object it would have hand-rolled.
38
+ */
39
+ export const DEFAULT_MINIMUM_PROJECTED_PIXELS = 0.5;
40
+
41
+ /** The `userData` key {@link alwaysRender} writes, named so a report can tell what was overridden. */
42
+ export const ALWAYS_RENDER_KEY = "alwaysRender";
43
+
44
+ /** A sphere-like bound, structural so an `InstancedMesh`'s own bound and a geometry's both fit. */
45
+ interface IBoundingSphereLike {
46
+ readonly center: Vector3;
47
+ readonly radius: number;
48
+ }
49
+
50
+ interface ICullable {
51
+ boundingSphere?: IBoundingSphereLike | null;
52
+ geometry?: {
53
+ boundingSphere?: IBoundingSphereLike | null;
54
+ computeBoundingSphere?: () => void;
55
+ /** Three bumps `version` whenever the buffer is re-uploaded; it is how a stale bound is told. */
56
+ attributes?: { position?: { version?: number } };
57
+ };
58
+ }
59
+
60
+ /** Sentinel: the position buffer is rewritten so often that its bound cannot be trusted cheaply. */
61
+ const DYNAMIC_BOUNDS = Symbol("render-camera-cull-dynamic-bounds");
62
+
63
+ /** What the gate remembers about a geometry's position buffer between consults. */
64
+ interface IPositionVersion {
65
+ version: number;
66
+ /** True when the previous consult also saw a change, so this one is the second in a row. */
67
+ changedLastConsult: boolean;
68
+ /** True when a rewrite was exempted without a rescan, so the cached sphere is stale. */
69
+ stale: boolean;
70
+ }
71
+
72
+ /** A sphere nearer than this to the camera would divide by zero; treat it as this far away. */
73
+ const MIN_DISTANCE = 1e-4;
74
+
75
+ export interface IRenderCameraCullOptions {
76
+ /**
77
+ * Projected diameter in pixels below which an object is skipped, or `false` to leave every
78
+ * object drawn. Defaults to {@link DEFAULT_MINIMUM_PROJECTED_PIXELS}.
79
+ */
80
+ readonly minimumPixels?: number | false;
81
+ }
82
+
83
+ /**
84
+ * What the gate did on the last frame, in the shape a frame-budget window reports.
85
+ *
86
+ * `enabled: false` means the game declined the gate, and the counts are still measured — turning
87
+ * the convention off must not turn its measurement off. Every exemption is named separately so an
88
+ * override is visible rather than silent.
89
+ */
90
+ export interface IRenderCameraCullReport {
91
+ readonly schemaVersion: 1;
92
+ readonly enabled: boolean;
93
+ /**
94
+ * False when the camera has no perspective distance term (orthographic) or no viewport to
95
+ * project into; the gate then leaves the whole scene drawn rather than guessing.
96
+ */
97
+ readonly cameraResolved: boolean;
98
+ readonly thresholdPixels: number;
99
+ /** Renderables walked this frame. */
100
+ readonly considered: number;
101
+ /** Renderables hidden by this gate this frame. */
102
+ readonly culled: number;
103
+ readonly exemptCameraAttached: number;
104
+ readonly exemptMarked: number;
105
+ readonly exemptShadowCasters: number;
106
+ readonly exemptWithoutBounds: number;
107
+ /**
108
+ * Objects whose position buffer is rewritten every frame, so the gate cannot trust a bound it
109
+ * cannot afford to rescan. Kept drawn, like `frustumCulled = false`.
110
+ */
111
+ readonly exemptDynamicBounds: number;
112
+ /** Objects that already set `frustumCulled = false`, and so never had trustworthy bounds. */
113
+ readonly exemptFrustumCulled: number;
114
+ }
115
+
116
+ /**
117
+ * Keep an object drawn regardless of how small the render camera resolves it.
118
+ *
119
+ * The named per-object override for the projected-size gate, which is on by default. Mark the
120
+ * player's own cockpit, a nameplate, a quest marker, or anything a game never wants to pop out.
121
+ * `alwaysRender(object, false)` removes the marker. The count of marked objects is reported beside
122
+ * the cull, so an override is stated rather than hidden.
123
+ *
124
+ * @situation keep a small object drawn when the engine would skip it as too far to resolve
125
+ * @situation stop my cockpit, marker or player model popping out at distance
126
+ * @situation a tiny object disappeared at range and I need it always visible
127
+ * @constraint the marker is per object and survives scene rebuilds only as long as the object does
128
+ * @constraint disabling the gate (`renderer.minimumProjectedPixels: false`) keeps its measurement on
129
+ * @example alwaysRender(ctx.camera.children[0]); // a camera-attached cockpit stays drawn
130
+ */
131
+ export function alwaysRender(object: Object3D, enabled = true): void {
132
+ object.userData[ALWAYS_RENDER_KEY] = enabled;
133
+ // The native engine runs this cull itself and cannot read userData: it reads its own marker.
134
+ if (ENGINE_MARKER in object)
135
+ // quality-allow: the native engine player reads __alwaysRender directly off the object; not in Three.Object3D types.
136
+ (object as unknown as Record<string, boolean>)[ENGINE_MARKER] = enabled;
137
+ }
138
+
139
+ /** The native engine's alwaysRender marker, mirrored by {@link alwaysRender}. */
140
+ const ENGINE_MARKER = "__alwaysRender";
141
+
142
+ /**
143
+ * A scene root the native engine walks itself (scene/projected_cull.h): the same rule in one call
144
+ * instead of a walk that reads every object's bounds, matrices and flags across the boundary.
145
+ * Optional: a root without these members takes the JS walk below, unchanged.
146
+ */
147
+ interface IEngineCullRoot {
148
+ __cullProjected(
149
+ camera: Camera,
150
+ cameraResolved: boolean,
151
+ scale: number,
152
+ minimumPixels: number,
153
+ enabled: boolean,
154
+ ): readonly number[];
155
+ __restoreCull(): void;
156
+ }
157
+
158
+ function engineCullRoot(root: unknown): IEngineCullRoot | undefined {
159
+ const candidate = root as Partial<IEngineCullRoot> | null;
160
+ return typeof candidate?.__cullProjected === "function" &&
161
+ typeof candidate.__restoreCull === "function"
162
+ ? (candidate as IEngineCullRoot)
163
+ : undefined;
164
+ }
165
+
166
+ /**
167
+ * The per-frame projected-size gate. One instance lives for the life of a game.
168
+ *
169
+ * `apply` hides this frame's sub-threshold objects and `restore` puts them back once the renderer
170
+ * has drawn, so the authored scene is exactly as the game left it between frames. Neither call
171
+ * allocates per object: the traversal callback, the scratch vector and the hidden-object list are
172
+ * all owned by the instance.
173
+ */
174
+ export class RenderCameraCull {
175
+ readonly #enabled: boolean;
176
+ readonly #minimumPixels: number;
177
+ readonly #center = new Vector3();
178
+ readonly #frustum = new Frustum();
179
+ readonly #projectionScreen = new Matrix4();
180
+ readonly #hidden: Object3D[] = [];
181
+ readonly #visitor: (object: Object3D) => void;
182
+ /** Last position-buffer version seen per geometry, so a rewritten dynamic bound is recomputed. */
183
+ readonly #positionVersions = new WeakMap<object, IPositionVersion>();
184
+ #hiddenCount = 0;
185
+ #camera: Camera | undefined;
186
+ #cameraX = 0;
187
+ #cameraY = 0;
188
+ #cameraZ = 0;
189
+ #scale = 0;
190
+ #cameraResolved = true;
191
+ #considered = 0;
192
+ #culled = 0;
193
+ #exemptCameraAttached = 0;
194
+ #exemptMarked = 0;
195
+ #exemptShadowCasters = 0;
196
+ #exemptWithoutBounds = 0;
197
+ #exemptDynamicBounds = 0;
198
+ #exemptFrustumCulled = 0;
199
+ /** The engine root the last apply() culled through, restored by restore(). */
200
+ #engineRoot: IEngineCullRoot | undefined;
201
+
202
+ constructor(options: IRenderCameraCullOptions = {}) {
203
+ const requested = options.minimumPixels ?? DEFAULT_MINIMUM_PROJECTED_PIXELS;
204
+ if (requested !== false && (!Number.isFinite(requested) || requested <= 0)) {
205
+ throw new Error(
206
+ `renderer.minimumProjectedPixels must be false or a finite number greater than zero, received ${String(requested)}.`,
207
+ );
208
+ }
209
+ this.#enabled = requested !== false;
210
+ this.#minimumPixels = requested === false ? DEFAULT_MINIMUM_PROJECTED_PIXELS : requested;
211
+ this.#visitor = (object) => this.#visit(object);
212
+ }
213
+
214
+ get report(): IRenderCameraCullReport {
215
+ return {
216
+ schemaVersion: 1,
217
+ enabled: this.#enabled,
218
+ cameraResolved: this.#cameraResolved,
219
+ thresholdPixels: this.#minimumPixels,
220
+ considered: this.#considered,
221
+ culled: this.#culled,
222
+ exemptCameraAttached: this.#exemptCameraAttached,
223
+ exemptMarked: this.#exemptMarked,
224
+ exemptShadowCasters: this.#exemptShadowCasters,
225
+ exemptWithoutBounds: this.#exemptWithoutBounds,
226
+ exemptDynamicBounds: this.#exemptDynamicBounds,
227
+ exemptFrustumCulled: this.#exemptFrustumCulled,
228
+ };
229
+ }
230
+
231
+ /**
232
+ * Hides every renderable under `root` that this camera resolves to fewer than the threshold,
233
+ * then calls `restore` implicitly on the next call. Call {@link restore} after the render.
234
+ *
235
+ * The walk visits only visible subtrees — a game-hidden LOD level or stand-in is already not
236
+ * submitted, so descending into it would waste the walk and could hide/restore a node the game
237
+ * deliberately left out.
238
+ */
239
+ apply(
240
+ root: { traverseVisible(callback: (object: Object3D) => void): void },
241
+ camera: Camera,
242
+ viewportHeight: number,
243
+ ): void {
244
+ this.restore();
245
+ this.#considered = 0;
246
+ this.#culled = 0;
247
+ this.#exemptCameraAttached = 0;
248
+ this.#exemptMarked = 0;
249
+ this.#exemptShadowCasters = 0;
250
+ this.#exemptWithoutBounds = 0;
251
+ this.#exemptDynamicBounds = 0;
252
+ this.#exemptFrustumCulled = 0;
253
+ this.#cameraResolved = true;
254
+ this.#camera = undefined;
255
+ // The walk runs whether or not the gate is enabled: turning the convention off must not turn
256
+ // its measurement off, so a disabled gate still reports what it considered and would have
257
+ // skipped. Only the hide below is gated by `#enabled`.
258
+ const perspective = camera as Camera & { isPerspectiveCamera?: boolean; fov?: number };
259
+ const engine = engineCullRoot(root);
260
+ if (!Number.isFinite(viewportHeight) || viewportHeight <= 0) {
261
+ this.#cameraResolved = false;
262
+ } else if (
263
+ perspective.isPerspectiveCamera !== true ||
264
+ typeof perspective.fov !== "number" ||
265
+ !(perspective.fov > 0 && perspective.fov < 180)
266
+ ) {
267
+ // An orthographic camera has no distance term, so a projected size has no meaning. Leave the
268
+ // whole scene drawn rather than guessing; a game that wants the cut there names a threshold
269
+ // on the camera itself.
270
+ this.#cameraResolved = false;
271
+ } else {
272
+ if (camera.matrixWorldAutoUpdate === true) camera.updateMatrixWorld();
273
+ this.#camera = camera;
274
+ this.#scale = viewportHeight / (2 * Math.tan((perspective.fov * Math.PI) / 360));
275
+ }
276
+ if (engine !== undefined) {
277
+ // The engine walks with its own camera position and frustum; it answers the eight counters.
278
+ const counts = engine.__cullProjected(
279
+ camera,
280
+ this.#cameraResolved,
281
+ this.#scale,
282
+ this.#minimumPixels,
283
+ this.#enabled,
284
+ );
285
+ // Indexed, not destructured: a destructuring assignment runs the iterator protocol.
286
+ this.#considered = counts[0] as number;
287
+ this.#culled = counts[1] as number;
288
+ this.#exemptCameraAttached = counts[2] as number;
289
+ this.#exemptMarked = counts[3] as number;
290
+ this.#exemptShadowCasters = counts[4] as number;
291
+ this.#exemptWithoutBounds = counts[5] as number;
292
+ this.#exemptDynamicBounds = counts[6] as number;
293
+ this.#exemptFrustumCulled = counts[7] as number;
294
+ this.#engineRoot = engine;
295
+ return;
296
+ }
297
+ if (this.#camera !== undefined) {
298
+ const elements = camera.matrixWorld.elements;
299
+ this.#cameraX = elements[12] as number;
300
+ this.#cameraY = elements[13] as number;
301
+ this.#cameraZ = elements[14] as number;
302
+ // The main frustum is what tells an off-camera shadow caster from a visible but unresolvable
303
+ // one. Perspective cameras keep `matrixWorldInverse` in step inside `updateMatrixWorld`.
304
+ this.#projectionScreen.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
305
+ this.#frustum.setFromProjectionMatrix(this.#projectionScreen);
306
+ }
307
+ root.traverseVisible(this.#visitor);
308
+ }
309
+
310
+ /** Undoes every hide this gate made, leaving the authored scene as the game left it. */
311
+ restore(): void {
312
+ this.#engineRoot?.__restoreCull();
313
+ this.#engineRoot = undefined;
314
+ for (let index = 0; index < this.#hiddenCount; index += 1) {
315
+ (this.#hidden[index] as Object3D).visible = true;
316
+ }
317
+ this.#hiddenCount = 0;
318
+ }
319
+
320
+ dispose(): void {
321
+ this.restore();
322
+ this.#camera = undefined;
323
+ }
324
+
325
+ #visit(object: Object3D): void {
326
+ if (!isRenderable(object)) return;
327
+ this.#considered += 1;
328
+ if (this.#isCameraAttached(object)) {
329
+ this.#exemptCameraAttached += 1;
330
+ return;
331
+ }
332
+ if (object.userData[ALWAYS_RENDER_KEY] === true) {
333
+ this.#exemptMarked += 1;
334
+ return;
335
+ }
336
+ // `frustumCulled = false` is the game's standing instruction that its bounds cannot be
337
+ // trusted — the pooled tracer, particle and whitewater batches set it for exactly that
338
+ // reason. A second, stricter cull does not get to override the opt-out.
339
+ if (object.frustumCulled === false) {
340
+ this.#exemptFrustumCulled += 1;
341
+ return;
342
+ }
343
+ // A shadow can be cast from far outside the main view, so a caster off the main camera is
344
+ // never dropped on the main camera's projection alone. This is the most-permissive
345
+ // multi-camera rule the engine can apply: the per-light shadow cameras are three's own and not
346
+ // cheaply enumerable here, so where the gate cannot know, it keeps the caster. A caster the
347
+ // main camera *can* see is ordinary geometry — its shadow is in view with it, and a
348
+ // sub-resolution object casts a sub-resolution shadow.
349
+ const sphere = boundsOf(object, this.#positionVersions);
350
+ // A buffer rewritten every frame has extents the gate cannot know without a full scan each
351
+ // frame, which costs more than the draw it might remove. Keep it drawn, like an opt-out.
352
+ if (sphere === DYNAMIC_BOUNDS) {
353
+ this.#exemptDynamicBounds += 1;
354
+ return;
355
+ }
356
+ // A zero or non-finite radius is not a size: a point has no projected diameter, and a pooled
357
+ // buffer whose first compute saw it empty caches exactly that. Read it as "no usable bounds"
358
+ // and keep the object, never as "infinitely small" and delete it.
359
+ if (sphere === undefined || !(Number.isFinite(sphere.radius) && sphere.radius > 0)) {
360
+ this.#exemptWithoutBounds += 1;
361
+ return;
362
+ }
363
+ this.#center.copy(sphere.center).applyMatrix4(object.matrixWorld);
364
+ if (
365
+ object.castShadow === true &&
366
+ (!this.#cameraResolved || !this.#frustum.containsPoint(this.#center))
367
+ ) {
368
+ this.#exemptShadowCasters += 1;
369
+ return;
370
+ }
371
+ if (!this.#enabled || !this.#cameraResolved) return;
372
+ const dx = this.#center.x - this.#cameraX;
373
+ const dy = this.#center.y - this.#cameraY;
374
+ const dz = this.#center.z - this.#cameraZ;
375
+ const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
376
+ const worldRadius = sphere.radius * object.matrixWorld.getMaxScaleOnAxis();
377
+ const projectedDiameter =
378
+ (2 * worldRadius * this.#scale) / Math.max(distance - worldRadius, MIN_DISTANCE);
379
+ if (projectedDiameter >= this.#minimumPixels) return;
380
+ object.visible = false;
381
+ this.#hidden[this.#hiddenCount] = object;
382
+ this.#hiddenCount += 1;
383
+ this.#culled += 1;
384
+ }
385
+
386
+ #isCameraAttached(object: Object3D): boolean {
387
+ const camera = this.#camera;
388
+ if (camera === undefined) return false;
389
+ for (let node = object.parent; node !== null; node = node.parent) {
390
+ if (node === camera) return true;
391
+ }
392
+ return false;
393
+ }
394
+ }
395
+
396
+ function boundsOf(
397
+ object: Object3D,
398
+ versions: WeakMap<object, IPositionVersion>,
399
+ ): IBoundingSphereLike | typeof DYNAMIC_BOUNDS | undefined {
400
+ const cullable = object as ICullable;
401
+ // An `InstancedMesh` carries its own instance-aware bound; the geometry one is not it.
402
+ if (cullable.boundingSphere != null) return cullable.boundingSphere;
403
+ const geometry = cullable.geometry;
404
+ if (geometry === undefined) return undefined;
405
+ const version = geometry.attributes?.position?.version;
406
+ if (geometry.boundingSphere == null) {
407
+ geometry.computeBoundingSphere?.();
408
+ if (version !== undefined)
409
+ versions.set(geometry, { version, changedLastConsult: false, stale: false });
410
+ return geometry.boundingSphere ?? undefined;
411
+ }
412
+ if (version === undefined) return geometry.boundingSphere ?? undefined;
413
+ const known = versions.get(geometry);
414
+ if (known === undefined) {
415
+ versions.set(geometry, { version, changedLastConsult: false, stale: false });
416
+ return geometry.boundingSphere ?? undefined;
417
+ }
418
+ if (known.version === version) {
419
+ // A buffer that settled after a per-frame rewrite has knowable extents again: scan it once and
420
+ // cull it like any other, rather than exempting it for the rest of the run. Settling also lets
421
+ // the next change count as a fresh one rather than as the second frame of a rewrite.
422
+ if (known.stale) geometry.computeBoundingSphere?.();
423
+ known.changedLastConsult = false;
424
+ known.stale = false;
425
+ return geometry.boundingSphere ?? undefined;
426
+ }
427
+ known.version = version;
428
+ if (known.changedLastConsult) {
429
+ // The buffer moved again on the very next consult: it is rewritten every frame. A full
430
+ // vertex/instance scan per frame costs more than the draw it might remove, and the extents are
431
+ // not knowable without it — so treat the bound like `frustumCulled = false` and keep drawing.
432
+ known.stale = true;
433
+ return DYNAMIC_BOUNDS;
434
+ }
435
+ // The buffer was rewritten under a cached sphere, which is now a stale size that *looks* valid.
436
+ // Recompute rather than trust it. Only a changed buffer pays this, so a static scene computes
437
+ // once and a dynamic one pays only where its bounds are actually consulted.
438
+ geometry.computeBoundingSphere?.();
439
+ known.changedLastConsult = true;
440
+ return geometry.boundingSphere ?? undefined;
441
+ }