@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,524 @@
1
+ import {
2
+ Fn,
3
+ If,
4
+ Loop,
5
+ Return,
6
+ abs,
7
+ atomicAdd,
8
+ float,
9
+ instanceIndex,
10
+ int,
11
+ length,
12
+ mat4,
13
+ max,
14
+ storage,
15
+ uint,
16
+ vec3,
17
+ } from "three/tsl";
18
+ import { biasedLodDistance } from "./model-lod.js";
19
+ import { type DepthPyramid, type IKernelOcclusion, occludedBy } from "./render/depth-pyramid.js";
20
+ import type {
21
+ IAssetSlot,
22
+ IGpuKernel,
23
+ IGpuPlacement,
24
+ IGpuSceneBuffers,
25
+ IKernelInput,
26
+ IKernelResult,
27
+ IRegion,
28
+ } from "./world-gpu-types.js";
29
+ import { PLACEMENT_ROWS, nodes } from "./world-gpu-types.js";
30
+ import { DRAW_ARGS_WORDS, LIVE_MATRIX, LOCAL_WORDS, compose } from "./world-gpu-validation.js";
31
+
32
+ /**
33
+ * The per-instance cull and LOD selection, in plain TypeScript: the reference the TSL kernel mirrors
34
+ * branch for branch, and the answer the CPU path is judged against.
35
+ *
36
+ * It runs in node with no GPU behind it, which is why it is what the tests prove. Nothing here
37
+ * allocates a buffer or reads a device: given the placements, the camera's planes and an asset's
38
+ * gate table, it returns the compacted survivors and the per-key counts one dispatch would produce.
39
+ */
40
+
41
+ /**
42
+ * The level one placement draws with, from an asset's gate table and the placement's own scale.
43
+ *
44
+ * Every gate but a whole-asset impostor's terminal is an authored world-metre distance, compared
45
+ * directly. The impostor's terminal gate is the base-sphere *projected* distance: the atlas is
46
+ * built for the asset's own LOD0 size, so a placement scaled ten times reaches the atlas ten times
47
+ * as far — its threshold is `base * |scale|`, floored by the last source gate it must stay strictly
48
+ * beyond. The floor is nudged one representable step past that gate: sharing the gate's own switch
49
+ * distance would let the terminal overwrite the last source level at every distance past it, so the
50
+ * source level would never draw. Read by {@link cullAndSelect} and mirrored by the kernel and the
51
+ * CPU path, so all three cross the same switch.
52
+ */
53
+ export function levelAtGates(
54
+ slot: Pick<IAssetSlot, "distances" | "impostor">,
55
+ distance: number,
56
+ scale: number,
57
+ ): number {
58
+ const last = slot.distances.length - 1;
59
+ const magnitude = Number.isFinite(scale) ? Math.abs(scale) : 1;
60
+ let level = 0;
61
+ for (let index = 1; index < slot.distances.length; index += 1) {
62
+ const gate = slot.distances[index] as number;
63
+ const threshold =
64
+ slot.impostor === true && index === last && last >= 1
65
+ ? Math.max(strictlyAfterGate(slot.distances[last - 1] as number), gate * magnitude)
66
+ : gate;
67
+ if (distance > threshold) level = index;
68
+ }
69
+ return level;
70
+ }
71
+
72
+ /**
73
+ * The last level at or below `level` that the scene can actually draw, which is where a placement
74
+ * goes when the gates name one the prewarm has not minted keys for.
75
+ *
76
+ * `WorldCells#gatesOf` names every level of an asset from the moment it is adopted and fills in the
77
+ * keys minted so far, so a chain that has widened holds `parts: 2,0,0,0` while the loading screen is
78
+ * up. The CPU path draws `asset.levels[level]` whatever the gates name and always has a shape there;
79
+ * a dispatch that took the named level would loop its zero keys and draw the placement nowhere, and
80
+ * with the bias raised the placements past the last source gate are exactly the far ones — a forest
81
+ * 80-300 m out standing in its own shadows, while the shadow halves, which take no bias and key
82
+ * themselves, still draw. One level down is the finest shape the scene holds, which is the level the
83
+ * prewarm is one frame from minting.
84
+ */
85
+ function drawableLevel(slot: Pick<IAssetSlot, "levels">, level: number): number {
86
+ for (let at = level; at > 0; at -= 1) if ((slot.levels[at]?.parts ?? 0) > 0) return at;
87
+ return 0;
88
+ }
89
+
90
+ /**
91
+ * The level a shadow map draws a placement at, or -1 when no level of its asset casts. A placement
92
+ * whose main level casts nothing falls back only when its asset permits it: derived chains past
93
+ * `castLevels` keep their shadow, drawn in the last shape that has a twin, rather than
94
+ * leaving a hole in the map (PRD-541). The level is then floored at the map's base and clamped to
95
+ * the last level that casts, so a coarse map draws the coarsest shape that has a twin. `base` past
96
+ * the chain is clamped by the chain length first.
97
+ */
98
+ function shadowLevel(
99
+ slot: Pick<IAssetSlot, "levels" | "shadowFallback">,
100
+ regions: readonly IRegion[],
101
+ drawn: number,
102
+ base: number,
103
+ ): number {
104
+ const casts = (at: number): boolean => {
105
+ const gate = slot.levels[at];
106
+ return gate !== undefined && gate.parts > 0 && regions[gate.firstKey]?.uncast !== true;
107
+ };
108
+ if (slot.shadowFallback === false && casts(drawn) === false) return -1;
109
+ // At or below `drawn` any casting level qualifies, above it only up to the map's base, so the
110
+ // last casting level in `[0, max(drawn, base)]` is both rules at once.
111
+ const last = Math.max(drawn, Math.min(base, slot.levels.length - 1));
112
+ let level = -1;
113
+ for (let at = 0; at <= last; at += 1) if (casts(at)) level = at;
114
+ return level;
115
+ }
116
+
117
+ /**
118
+ * One representable Float32 step past a gate: `g * (1 + 2^-22)`, two f32 ULPs at `g`'s exponent.
119
+ *
120
+ * A floored terminal gate must start strictly after the source gate it is floored by and must stay
121
+ * so once the threshold is stored and compared in f32, which a bare `g` does not: the terminal
122
+ * shares `g`'s switch distance and the later gate wins every comparison, starving the source level.
123
+ * A relative step, not a fixed metre margin, so the ordering holds at every authored scale.
124
+ */
125
+ /** One representable step past a gate, which the kernel and the reference both floor an impostor with. */
126
+ export const GATE_STEP = 2 ** -22;
127
+
128
+ function strictlyAfterGate(gate: number): number {
129
+ return gate + Math.abs(gate) * GATE_STEP;
130
+ }
131
+
132
+ /**
133
+ * One shadow map's own three numbers, which is the whole of what a level render knows that the main
134
+ * camera does not.
135
+ *
136
+ * They are the level's, never the camera's: a map's frustum is the light's window, its gate is the
137
+ * texel size it can resolve, and its base is the chain level the cluster path hands it — `#probe`
138
+ * swaps a coarse level's geometry for the coarsest shape, so a coarse map draws that shape whatever a
139
+ * placement's own distance would have selected. The distance itself is the main pass's, from the
140
+ * eye: a placement's shape and its cast come from the key the main pass draws it in.
141
+ */
142
+ export interface IShadowLevel {
143
+ /** The six frustum planes of this map's own shadow camera. */
144
+ readonly planes: Float32Array;
145
+ /** This map's texel gate in world metres: a placement narrower than it casts nothing here. */
146
+ readonly gate: number;
147
+ /**
148
+ * The chain level this map draws at, floored over the placement's own. 0 is the placement's own
149
+ * LOD by distance — what the finest map draws — and the coarsest index is what every level past
150
+ * the first draws. A base whose keys are not minted draws nothing, which is why a caller settling
151
+ * the prewarm first is the contract rather than a fallback.
152
+ *
153
+ * {@link COARSEST_SHADOW_LEVEL} is past every chain, and means the coarsest shape an asset has: a
154
+ * map that coarsens its casters does not know how long each asset's chain is, and the floor is
155
+ * clamped per asset, so one number asks every chain for its own coarsest level.
156
+ */
157
+ readonly base: number;
158
+ }
159
+
160
+ /**
161
+ * A {@link IShadowLevel.base} past every chain: the map draws every asset's coarsest shape, whatever
162
+ * distance selected it. Clamped to each asset's own last level, so an owner with no level count to
163
+ * hand — `VirtualShadowNode`, which coarsens a coarse level's casters without knowing an asset —
164
+ * can still ask.
165
+ */
166
+ export const COARSEST_SHADOW_LEVEL = 1 << 20;
167
+
168
+ /**
169
+ * The per-instance kernel, in plain TypeScript. The TSL kernel in {@link WorldGpuScene} is this
170
+ * loop with the same branches, and the test proves this one against the CPU path.
171
+ *
172
+ * One placement, in the order the source buffer holds them: a released record and a record whose
173
+ * asset is unknown are skipped, the bounding sphere is tested against the camera's six planes, the
174
+ * XZ distance picks the level through the asset's own gates and culls a record beyond its cull
175
+ * distance, and each part of that level takes the next free slot in its key's region and writes
176
+ * `placement * part offset` there. A region that is full is a dropped instance, never a write past
177
+ * the end of the buffer.
178
+ */
179
+ export function cullAndSelect(input: IKernelInput): IKernelResult {
180
+ return select(input, undefined);
181
+ }
182
+
183
+ /**
184
+ * The same kernel with a shadow map's own four numbers in place of the camera's, and nothing else
185
+ * changed: same regions, same keys, same `placement * part offset`, same capacity guard.
186
+ *
187
+ * The gate is applied to the placement's own diameter, where the cluster path applies it to the
188
+ * whole mesh and drops the square with it — so on a uniform-size fixture the two sets are the same
189
+ * set, and where a square mixes sizes this one is the finer of the two.
190
+ */
191
+ export function cullAndSelectShadow(input: IKernelInput, level: IShadowLevel): IKernelResult {
192
+ return select(input, level);
193
+ }
194
+
195
+ /**
196
+ * The one loop both references share. `shadow` is what makes the second one a variant rather than a
197
+ * fork: the main camera's planes, eye, no gate and no base are the degenerate case, so the two can
198
+ * never disagree by having been edited apart.
199
+ */
200
+ function select(input: IKernelInput, shadow: IShadowLevel | undefined): IKernelResult {
201
+ const { placements, camera, regions, slots } = input;
202
+ // A shadow map has no main camera to reproject into, so the test is the main pass's alone — a
203
+ // caster the eye cannot see still casts.
204
+ const occlusion = shadow === undefined ? input.occlusion : undefined;
205
+ const planes = shadow?.planes ?? camera.planes;
206
+ const metres = shadow?.gate ?? 0;
207
+ const base = shadow?.base ?? 0;
208
+ const counts = new Uint32Array(input.regionCount);
209
+ const args = new Uint32Array(input.regionCount * DRAW_ARGS_WORDS);
210
+ // The drawn buffer is the regions' own, so the reference allocates exactly what the GPU holds.
211
+ const capacity = regions.reduce(
212
+ (sum, region) => Math.max(sum, region.start + region.capacity),
213
+ 0,
214
+ );
215
+ const matrix = new Float32Array(capacity * LOCAL_WORDS);
216
+ for (const region of regions) {
217
+ args[region.argsIndex * DRAW_ARGS_WORDS + 4] = region.start;
218
+ }
219
+ let occludedInstances = 0;
220
+ let occludedTriangles = 0;
221
+ for (let index = 0; index < input.count; index += 1) {
222
+ const placement = placements[index];
223
+ if (placement === undefined || placement.slot < 0) continue;
224
+ const slot = slots[placement.slot];
225
+ if (slot === undefined) continue;
226
+ const at = placement.centre;
227
+ const radius = at[3] as number;
228
+ let visible = true;
229
+ for (let plane = 0; plane < 6; plane += 1) {
230
+ const offset = plane * 4;
231
+ const signed =
232
+ (planes[offset] as number) * (at[0] as number) +
233
+ (planes[offset + 1] as number) * (at[1] as number) +
234
+ (planes[offset + 2] as number) * (at[2] as number) +
235
+ (planes[offset + 3] as number);
236
+ if (signed < -radius) {
237
+ visible = false;
238
+ break;
239
+ }
240
+ }
241
+ if (visible === false) continue;
242
+ // Sub-texel, exactly as `#probe` decides it for a mesh: a caster this map cannot resolve casts
243
+ // no shadow a fragment could tell from ground cover.
244
+ if (radius * 2 < metres) continue;
245
+ const distance = Math.hypot((at[0] as number) - camera.x, (at[2] as number) - camera.z);
246
+ if (slot.cull !== undefined && distance > slot.cull) continue;
247
+ // Cull above is the authored distance; the level below is the biased one for the main pass — the
248
+ // same multiplier the kernel's uniform carries, so the reference and the dispatch cross a switch
249
+ // together. A shadow map takes the main pass's own level, from the eye: that is the key a
250
+ // placement is drawn in, and the cluster path casts each key's placements from that key's mesh.
251
+ const drawn = drawableLevel(
252
+ slot,
253
+ levelAtGates(slot, biasedLodDistance(distance), placement.scale ?? 1),
254
+ );
255
+ const level = shadow === undefined ? drawn : shadowLevel(slot, regions, drawn, base);
256
+ if (level < 0) continue;
257
+ const gate = slot.levels[level];
258
+ if (gate === undefined) continue;
259
+ const hidden =
260
+ occlusion !== undefined && occludedBy(occlusion, at, radius) ? occlusion : undefined;
261
+ for (let part = 0; part < gate.parts; part += 1) {
262
+ const region = regions[gate.firstKey + part];
263
+ if (region === undefined) continue;
264
+ // Counted either way: a measured run draws what it hides, so the count is the only place the
265
+ // answer can live.
266
+ if (hidden !== undefined) {
267
+ occludedInstances += 1;
268
+ occludedTriangles += region.indexCount / 3;
269
+ if (hidden.cull) continue;
270
+ }
271
+ const taken = counts[gate.firstKey + part] as number;
272
+ if (taken >= region.capacity) continue;
273
+ counts[gate.firstKey + part] = taken + 1;
274
+ args[region.argsIndex * DRAW_ARGS_WORDS + 1] = taken + 1;
275
+ compose(placement.matrix, region.local, matrix, (region.start + taken) * LOCAL_WORDS);
276
+ }
277
+ }
278
+ return {
279
+ args,
280
+ counts,
281
+ drawn: matrix,
282
+ ...(occlusion === undefined
283
+ ? {}
284
+ : { occluded: { instances: occludedInstances, triangles: occludedTriangles } }),
285
+ };
286
+ }
287
+
288
+ /**
289
+ * One asset's gates as its owner last published them: the source representation and its
290
+ * `asset.distances`/`cullDistance(definition.maxDistance)` snapshot at the completed swap boundary.
291
+ *
292
+ * Deliberately not an {@link IAssetSlot}. A slot is what this class wrote into its own table, and a
293
+ * table written before the owner's model widened its chain is the exact thing the check exists to
294
+ * catch — feeding it back in as the reference is the check agreeing with itself.
295
+ */
296
+ export interface ILiveAsset {
297
+ /** The asset id a main key is named `asset:level:part` with, which is the owner's own convention. */
298
+ readonly id: string;
299
+ /** Level switch distances, ascending, `0` first — the CPU publication snapshot. */
300
+ readonly distances: readonly number[];
301
+ /** `maxDistance` less its eighth, or `undefined`. */
302
+ readonly cull: number | undefined;
303
+ /** Index-aligned with `distances`; each level's parts, each part's own offset inside the model. */
304
+ readonly locals: readonly (readonly Float32Array[])[];
305
+ /** Whether the last level is a whole-asset impostor whose gate the placement's scale scales. */
306
+ readonly impostor?: boolean;
307
+ }
308
+
309
+ /**
310
+ * Every placement's own answer, from the owner's live gates, as the instances each main key must be
311
+ * holding: the same six-plane sphere test, the same `cull`, the same ascending `distance > gate`
312
+ * level test and the same `placement * part offset` composition {@link cullAndSelect} runs — over
313
+ * gates this file did not write.
314
+ *
315
+ * This is the one reference in the module that is not a mirror of the kernel's inputs. `cullAndSelect`
316
+ * reads the gate table out of the same class the kernel's buffer is written from, so a table holding
317
+ * the wrong distances makes both agree; here the caller passes the owner's own `distances`, so a
318
+ * table that was written before the chain widened, or before the last `maxDistance`, answers
319
+ * differently from the picture the CPU path draws.
320
+ */
321
+ export function liveKeyInstances(
322
+ placements: readonly IGpuPlacement[],
323
+ asset: (slot: number) => ILiveAsset | undefined,
324
+ camera: {
325
+ readonly planes: Float32Array;
326
+ readonly x: number;
327
+ readonly y: number;
328
+ readonly z: number;
329
+ },
330
+ ): Map<string, Float32Array> {
331
+ const words = new Map<string, number[]>();
332
+ for (const placement of placements) {
333
+ if (placement.slot < 0) continue;
334
+ const held = asset(placement.slot);
335
+ if (held === undefined) continue;
336
+ const at = placement.centre;
337
+ const radius = at[3] as number;
338
+ let visible = true;
339
+ for (let plane = 0; plane < 6; plane += 1) {
340
+ const offset = plane * 4;
341
+ const signed =
342
+ (camera.planes[offset] as number) * (at[0] as number) +
343
+ (camera.planes[offset + 1] as number) * (at[1] as number) +
344
+ (camera.planes[offset + 2] as number) * (at[2] as number) +
345
+ (camera.planes[offset + 3] as number);
346
+ if (signed < -radius) {
347
+ visible = false;
348
+ break;
349
+ }
350
+ }
351
+ if (visible === false) continue;
352
+ const distance = Math.hypot((at[0] as number) - camera.x, (at[2] as number) - camera.z);
353
+ if (held.cull !== undefined && distance > held.cull) continue;
354
+ // The dispatch's own bias and the same gate rule: this reference is what the dressed mesh's
355
+ // instances are checked against, so it must cross the impostor switch exactly as the kernel does.
356
+ const level = levelAtGates(held, biasedLodDistance(distance), placement.scale ?? 1);
357
+ const locals = held.locals[level];
358
+ if (locals === undefined) continue;
359
+ for (const [part, local] of locals.entries()) {
360
+ const key = `${held.id}:${String(level)}:${String(part)}`;
361
+ let run = words.get(key);
362
+ if (run === undefined) {
363
+ run = [];
364
+ words.set(key, run);
365
+ }
366
+ compose(placement.matrix, local, LIVE_MATRIX, 0);
367
+ for (const word of LIVE_MATRIX) run.push(word);
368
+ }
369
+ }
370
+ return new Map([...words].map(([key, run]) => [key, Float32Array.from(run)]));
371
+ }
372
+
373
+ /** One completed manual frame check, identified by the caller's frame and this scene's dispatch. */
374
+
375
+ /**
376
+ * What a built cull pass reads: the scene's buffers, the camera uniforms the dispatch wrote, and —
377
+ * only when a launch asked to measure — the pyramid it reprojects into.
378
+ *
379
+ * The measurement is a binding rather than a mode string: `view()` is the uniform the kernel was
380
+ * given last time, made on first use by the caller that owns the matrix, so a scene whose GPU pass
381
+ * never measures asks the backend for no extra uniform.
382
+ */
383
+ export interface ICullKernelInput {
384
+ readonly buffers: IGpuSceneBuffers;
385
+ /** The six frustum planes, as uniforms the dispatch wrote this frame. */
386
+ readonly planes: readonly unknown[];
387
+ /** `(placements, slots, keys, keys)`, written by the dispatch before it submits. */
388
+ readonly counts: unknown;
389
+ /** The eye the placement distance is measured from. */
390
+ readonly eye: unknown;
391
+ /** The adaptive LOD bias the gate compare is scaled by. */
392
+ readonly bias: unknown;
393
+ readonly occlusion?: {
394
+ readonly pyramid: DepthPyramid;
395
+ readonly cut: unknown;
396
+ view(): unknown;
397
+ };
398
+ }
399
+
400
+ /**
401
+ * The two dispatches, mirroring {@link cullAndSelect} branch for branch: one thread per key
402
+ * zeroes that key's instance count, one thread per resident placement appends its matrix to each
403
+ * of its level's parts.
404
+ */
405
+ export function buildCullKernel(input: ICullKernelInput): IGpuKernel {
406
+ const { buffers } = input;
407
+ const source = nodes(storage(buffers.source, "vec4", buffers.source.count));
408
+ const drawn = nodes(storage(buffers.drawn, "mat4", buffers.drawn.count));
409
+ const argsPlain = nodes(storage(buffers.args, "uint", buffers.args.count));
410
+ const argsAtomic = nodes(storage(buffers.args, "uint", buffers.args.count).toAtomic());
411
+ const keys = nodes(storage(buffers.keys, "vec4", buffers.keys.count));
412
+ const locals = nodes(storage(buffers.locals, "mat4", buffers.locals.count));
413
+ const gates = nodes(storage(buffers.gates, "vec4", buffers.gates.count));
414
+ const levels = nodes(storage(buffers.levels, "vec4", buffers.levels.count));
415
+ const counts = nodes(input.counts);
416
+ const eye = nodes(input.eye);
417
+ const bias = nodes(input.bias);
418
+ const planes = input.planes.map((plane) => nodes(plane));
419
+ // Measuring doubles the clear: the second thread per key zeroes that key's word of the
420
+ // measured-occlusion tally, which is why the args buffer is sized for it (see `argsWords`).
421
+ // A run that is not measuring never pays the second thread.
422
+ const clearWidth = input.occlusion === undefined ? 1 : 2;
423
+ const clear = Fn(() => {
424
+ If(instanceIndex.greaterThanEqual(counts.w.mul(clearWidth)), () => Return());
425
+ If(instanceIndex.lessThan(counts.w), () => {
426
+ const key = keys.element(instanceIndex);
427
+ argsPlain.element(key.z.mul(DRAW_ARGS_WORDS).add(1)).assign(int(0));
428
+ });
429
+ If(instanceIndex.greaterThanEqual(counts.w), () => {
430
+ argsPlain
431
+ .element(
432
+ nodes(counts.w.mul(DRAW_ARGS_WORDS)).add(
433
+ nodes(float(instanceIndex).sub(counts.w).floor()),
434
+ ),
435
+ )
436
+ .assign(int(0));
437
+ });
438
+ })().compute(Math.max(1, buffers.keys.count * clearWidth));
439
+ const cull = Fn(() => {
440
+ If(instanceIndex.greaterThanEqual(counts.x), () => Return());
441
+ // One placement is `PLACEMENT_ROWS` consecutive `vec4` rows: the world matrix's four columns,
442
+ // then the sphere, then `info`. Read as rows rather than as a struct element, which the owned
443
+ // engine refuses; the words are the ones `#writePlacement` wrote either way.
444
+ const base = instanceIndex.mul(uint(PLACEMENT_ROWS));
445
+ const matrix = mat4(
446
+ source.element(base),
447
+ source.element(base.add(uint(1))),
448
+ source.element(base.add(uint(2))),
449
+ source.element(base.add(uint(3))),
450
+ );
451
+ const centre = source.element(base.add(uint(4)));
452
+ const info = source.element(base.add(uint(5)));
453
+ const slot = info.x;
454
+ If(slot.lessThan(0.0), () => Return());
455
+ If(slot.greaterThanEqual(counts.y), () => Return());
456
+ const radius = centre.w;
457
+ for (const plane of planes) If(plane.dot(centre.xyz).lessThan(radius.negate()), () => Return());
458
+ const gate = gates.element(slot);
459
+ const distance = length(vec3(centre.x.sub(eye.x), 0.0, centre.z.sub(eye.z)));
460
+ If(gate.w.mod(2.0).greaterThan(0.5).and(distance.greaterThan(gate.z)), () => Return());
461
+ // Cull above is the authored distance; the level below is the same distance scaled by the
462
+ // adaptive bias, mirroring `cullAndSelect` and the CPU `model-lod` path.
463
+ const lodDistance = nodes(distance).mul(bias as never);
464
+ // The level, by the same ascending test the CPU runs: the last gate the placement is past.
465
+ // The loop is bounded by `gate.y` rather than unrolled, because a baked chain can carry more
466
+ // levels than any fixed count, and a level the loop stopped short of is a placement drawn at
467
+ // the wrong shape by however many levels it missed.
468
+ const level = int(0).toVar();
469
+ // The placement's own uniform scale, written into `info.y`; the whole-asset impostor's terminal
470
+ // gate is the base projected distance and is scaled by it. A mirrored placement's scale is
471
+ // negative, and the extent it reaches is the same, so the kernel takes the magnitude exactly as
472
+ // `levelAtGates` does; `info.y` is already finite-sanitised when the record is written.
473
+ const scale = abs(info.y);
474
+ Loop({ start: int(1), end: gate.y, type: "int", condition: "<" }, ({ i }: { i: unknown }) => {
475
+ const candidate = levels.element(gate.x.add(i as never));
476
+ const threshold = nodes(candidate.x).toVar();
477
+ // Only the terminal level carries this mark: its stored distance is the base-sphere projected
478
+ // one, so its real threshold is `max(strictly after last source gate, base * |scale|)`. The
479
+ // source floor is the previous level's own authored gate, unscaled and nudged one f32 step,
480
+ // so a small scale cannot starve the last source level by sharing its switch distance.
481
+ If(candidate.w.greaterThan(0.5), () => {
482
+ const previous = levels.element(gate.x.add(i as never).sub(1)).x;
483
+ const floor = previous.add(abs(previous).mul(GATE_STEP));
484
+ threshold.assign(max(floor, candidate.x.mul(scale)));
485
+ });
486
+ // A level the prewarm has minted no key for is not taken: the gate table names every level of
487
+ // an asset from the moment it is adopted, and the draw loop below would run this level's
488
+ // zero keys, so the placement would be selected and drawn nowhere while the CPU path drew it
489
+ // and its shadow halves drew under it. The last level that has keys keeps it. See
490
+ // `drawableLevel`, which the reference mirrors.
491
+ If(lodDistance.greaterThan(threshold), () => {
492
+ If(candidate.z.greaterThan(0.5), () => {
493
+ level.assign(i as never);
494
+ });
495
+ });
496
+ });
497
+ const at = levels.element(gate.x.add(level));
498
+ // The pyramid test, once per placement: a placement the frustum and the gates kept, reprojected
499
+ // into the previous frame's pyramid. Measured only, so the write below happens either way and
500
+ // the indirect counts are develop's.
501
+ const hidden = float(0).toVar();
502
+ const measure = input.occlusion;
503
+ if (measure !== undefined && measure.pyramid.levels > 0) {
504
+ hidden.assign(measure.pyramid.occluded(centre.xyz, radius, measure.view(), measure.cut));
505
+ }
506
+ Loop({ start: int(0), end: at.z, type: "int", condition: "<" }, ({ i }: { i: unknown }) => {
507
+ const keyIndex = at.y.add(i as never);
508
+ const key = keys.element(keyIndex);
509
+ If(hidden.greaterThan(0.5), () => {
510
+ atomicAdd(argsAtomic.element(counts.w.mul(DRAW_ARGS_WORDS).add(keyIndex)), int(1));
511
+ });
512
+ const taken = nodes(atomicAdd(argsAtomic.element(key.z.mul(DRAW_ARGS_WORDS).add(1)), int(1)));
513
+ If(taken.toFloat().lessThan(key.y), () => {
514
+ drawn.element(key.x.add(taken)).assign(matrix.mul(locals.element(keyIndex)));
515
+ });
516
+ });
517
+ })().compute(
518
+ // One thread per placement record, not per `vec4` row of the source buffer.
519
+ Math.max(1, Math.ceil(buffers.source.count / PLACEMENT_ROWS)),
520
+ );
521
+ clear.setName("worldGpuSceneClear");
522
+ cull.setName("worldGpuSceneCull");
523
+ return { clear, cull };
524
+ }