@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,198 @@
1
+ import type { SharedBatch } from "./world-cell-batches.js";
2
+ import type { IAssetPart, ICellBatch, IResidentCell } from "./world-cell-data.js";
3
+ import type { ICellRenderHost } from "./world-cell-render.js";
4
+ import type { WorldGpuScene } from "./world-gpu-scene.js";
5
+ import type { IWorldPackage } from "./world-package.js";
6
+
7
+ /**
8
+ * Who claims a shadow: whether a level casts at all, which shape it casts with, and the block one
9
+ * cell takes in its caster cluster or in the key's wide mesh.
10
+ *
11
+ * These are the decisions the caster halves are made of, and the main cull, the swap and the LOD
12
+ * path read them as well as this module's own claims. They keep no state: a claim is a segment in a
13
+ * `SharedBatch`, and every batch is the world's.
14
+ */
15
+
16
+ /** What a claim needs from the renderer it is made for. */
17
+ export interface IShadowClaimHost {
18
+ render(): ICellRenderHost;
19
+ manifest(): IWorldPackage;
20
+ smallCasterMetres(): number;
21
+ castShadowLevels(): number;
22
+ shadowMinLevel(): number;
23
+ /** Authored parts are kept as their own casters, so a generated impostor does not replace them. */
24
+ preserveAuthoredParts(): boolean;
25
+ gpuScene(): WorldGpuScene;
26
+ /** Resident placements per canonical asset, which a released key's block goes back from. */
27
+ resident(): Map<string, number>;
28
+ /** The caster cluster one cell's records go to, minted on first use. */
29
+ casterFor(
30
+ assetId: string,
31
+ entry: ICellBatch,
32
+ cell: IResidentCell,
33
+ level?: number,
34
+ ): SharedBatch | undefined;
35
+ /** The key's whole-asset wide caster, minted on first use. */
36
+ wideFor(assetId: string, entry: ICellBatch, level?: number): SharedBatch | undefined;
37
+ /** A block in `shared` for one cell's records, grown when the batch is full. */
38
+ segmentIn(shared: SharedBatch, count: number, cluster?: string): number | undefined;
39
+ /** Fresh meshes already charged against this update's allowance. */
40
+ freshCount(): number;
41
+ /** Record that a key's placed count changed, which the caster's own gate reads. */
42
+ countPlaced(entry: ICellBatch, placed: number): void;
43
+ }
44
+
45
+ /**
46
+ * Whether this level's own batches cast. Only the caster clusters ask; a main mesh never casts, so
47
+ * the shadow map holds exactly the cluster meshes a level's window covers.
48
+ */
49
+ export function casts(host: IShadowClaimHost, level: number): boolean {
50
+ return host.castShadowLevels() > level;
51
+ }
52
+
53
+ /**
54
+ * An asset too small to resolve in any window but the finest one's, so its wide caster goes on
55
+ * that level's layer alone. Measured on the authored bounds the package carries, which is the one
56
+ * number a world has for every asset it never loaded a tree for.
57
+ */
58
+ export function smallCaster(host: IShadowClaimHost, assetId: string): boolean {
59
+ const bounds = host.manifest().assets[assetId]?.bounds;
60
+ if (bounds === undefined) return false;
61
+ return bounds.max[1] - bounds.min[1] < host.smallCasterMetres();
62
+ }
63
+
64
+ /**
65
+ * Whether this entry owes a wide caster. Generated whole-asset impostors use only part 0; preserved
66
+ * authored parts retain each part's own caster and transform.
67
+ */
68
+ export function wideOwed(host: IShadowClaimHost, assetId: string, part: number): boolean {
69
+ if (part === 0) return true;
70
+ return host.preserveAuthoredParts() || host.render().asset(assetId)?.impostor === undefined;
71
+ }
72
+
73
+ /**
74
+ * The level a cell batch casts with: its own when that level casts, otherwise the coarsest
75
+ * casting level, when that level holds the same parts — a chain's derived levels do, authored
76
+ * `lods` need not — so a tree past `castLevels` keeps its shadow in the last shape that has a
77
+ * caster rather than leaving a hole in the map (PRD-541). `undefined`: it casts nothing.
78
+ */
79
+ export function castLevelOf(host: IShadowClaimHost, entry: ICellBatch): number | undefined {
80
+ const floor = shadowFloorOf(host, entry.asset);
81
+ if (entry.level < floor) return floor;
82
+ if (casts(host, entry.level)) return entry.level;
83
+ if (host.castShadowLevels() === 0) return undefined;
84
+ const asset = host.render().asset(entry.asset);
85
+ if (asset === undefined || asset.definition.lods !== undefined) return undefined;
86
+ const level = Math.min(entry.level, host.castShadowLevels()) - 1;
87
+ return asset.levels[level]?.[entry.part] === undefined ? undefined : level;
88
+ }
89
+
90
+ /**
91
+ * The level this asset's finer placements cast in (`shadows.minLevel`), clamped to a casting
92
+ * level. 0 when a finer level's parts do not line up with it, since a caster draws its own entry's
93
+ * part index and matrices in that level's shape, and when the shadow levels draw the GPU keys.
94
+ */
95
+ export function shadowFloorOf(host: IShadowClaimHost, assetId: string): number {
96
+ const asset = host.render().asset(assetId);
97
+ if (asset === undefined || keysForShadow(host)) return 0;
98
+ const floor = Math.min(
99
+ host.shadowMinLevel(),
100
+ host.castShadowLevels() - 1,
101
+ asset.levels.length - 1,
102
+ );
103
+ const coarse = asset.levels[floor];
104
+ if (floor <= 0 || coarse === undefined) return 0;
105
+ for (let level = 0; level < floor; level++) {
106
+ const parts = asset.levels[level];
107
+ if (parts?.length !== coarse.length) return 0;
108
+ for (const [index, part] of parts.entries())
109
+ if (!part.local.equals((coarse[index] as IAssetPart).local)) return 0;
110
+ }
111
+ return floor;
112
+ }
113
+
114
+ /**
115
+ * Whether a shadow level draws this world's keys instead of its two caster halves: the GPU scene
116
+ * is up *and* a provider registered on it, which `?tnShadowGpuKeys=1` is what asks for. Both, or
117
+ * neither — a provider with the scene off is a world whose shadow maps have nothing to draw, so
118
+ * the world keeps the caster path until both are true.
119
+ */
120
+ export function keysForShadow(host: IShadowClaimHost): boolean {
121
+ return host.gpuScene().on && host.gpuScene().shadowKeys;
122
+ }
123
+
124
+ /**
125
+ * Claim this cell's block in its caster cluster, when the level casts and it does not have one.
126
+ * `false` means the frame's fresh allowance is spent and the swap waits, so the main mesh and its
127
+ * cluster are never half attached.
128
+ */
129
+ export function claimCaster(
130
+ host: IShadowClaimHost,
131
+ assetId: string,
132
+ entry: ICellBatch,
133
+ cell: IResidentCell,
134
+ ): boolean {
135
+ const level = castLevelOf(host, entry);
136
+ if (entry.casterSegment >= 0 || level === undefined) return true;
137
+ // Nothing to claim, and nothing to wait for: a world whose levels draw its keys mints no caster
138
+ // half at all (`#casterFor`), so reading that as a spent allowance refused every swap in the
139
+ // world — the main mesh was never attached, no cell published its placements, and the main pass
140
+ // drew nothing while its meshes sat there prewarmed and empty.
141
+ if (keysForShadow(host)) return true;
142
+ const caster = host.casterFor(assetId, entry, cell, level);
143
+ const at = caster === undefined ? undefined : host.segmentIn(caster, entry.batch.count);
144
+ if (caster === undefined || at === undefined) return false;
145
+ entry.caster = caster;
146
+ entry.casterSegment = at;
147
+ return true;
148
+ }
149
+
150
+ /**
151
+ * Claim this cell's block in its key's wide caster mesh, when the level casts and it does not
152
+ * have one. `false` means the frame's fresh allowance is spent and the swap waits, so the
153
+ * clusters and the wide half are never half attached.
154
+ */
155
+ export function claimWide(host: IShadowClaimHost, assetId: string, entry: ICellBatch): boolean {
156
+ const level = castLevelOf(host, entry);
157
+ if (entry.wideSegment >= 0 || level === undefined) return true;
158
+ // A part the asset's one whole-asset representation already covers: the entry keeps its near
159
+ // main and cluster, and the far shadow reads part 0's one quad; see `#wideOwed`.
160
+ if (!wideOwed(host, assetId, entry.part)) return true;
161
+ // As `#claimCaster`: the key twin is this level's wide half, and there is no mesh to wait on.
162
+ if (keysForShadow(host)) return true;
163
+ const wide = host.wideFor(assetId, entry, level);
164
+ // The impostor's far half draws the placement root, not `placement * part local`, so its block
165
+ // is sized to the root records the build kept beside the part's own; see `ICellBatch.wideRoot`.
166
+ const count = entry.wideRoot?.count ?? entry.batch.count;
167
+ const at = wide === undefined ? undefined : host.segmentIn(wide, count);
168
+ if (wide === undefined || at === undefined) return false;
169
+ entry.wide = wide;
170
+ entry.wideSegment = at;
171
+ return true;
172
+ }
173
+
174
+ export function clearSegment(host: IShadowClaimHost, entry: ICellBatch): void {
175
+ if (entry.shared !== undefined && entry.segment >= 0) entry.shared.clear(entry.segment);
176
+ // The source records go back with the block that held them, on every path a cell's records leave:
177
+ // a refilter's replacement, an eviction, and a queued build dropped with its cell. Releasing one
178
+ // twice is a no-op, which is what lets a level's parts share a single list.
179
+ if (entry.gpu !== undefined) {
180
+ const placed = entry.gpu.length;
181
+ for (const at of entry.gpu) host.gpuScene().release(at);
182
+ const left = (host.resident().get(entry.asset) ?? 0) - placed;
183
+ if (left > 0) host.resident().set(entry.asset, left);
184
+ else host.resident().delete(entry.asset);
185
+ // Before the halves go below, which is what clears the handles this reads.
186
+ host.countPlaced(entry, -placed);
187
+ }
188
+ entry.gpu = undefined;
189
+ if (entry.caster !== undefined && entry.casterSegment >= 0)
190
+ entry.caster.clear(entry.casterSegment);
191
+ if (entry.wide !== undefined && entry.wideSegment >= 0) entry.wide.clear(entry.wideSegment);
192
+ entry.shared = undefined;
193
+ entry.segment = -1;
194
+ entry.caster = undefined;
195
+ entry.casterSegment = -1;
196
+ entry.wide = undefined;
197
+ entry.wideSegment = -1;
198
+ }
@@ -0,0 +1,259 @@
1
+ import { BufferGeometry, InstancedMesh, type Material, type Mesh, type Object3D } from "three";
2
+ import {
3
+ composeSilencedByFreeze,
4
+ isStatic,
5
+ markStatic,
6
+ worldSilencedByFreeze,
7
+ } from "./static-transform.js";
8
+ import type { SharedBatch } from "./world-cell-batches.js";
9
+ import { clusterOf } from "./world-cell-data.js";
10
+
11
+ /**
12
+ * The pieces of world-cell rendering that hold no world: the constants the cull, the shadow claims
13
+ * and the bundles all read, and the small mesh and hash helpers every one of them calls.
14
+ *
15
+ * Nothing here reads a cell, a batch or a scene, so any of the modules PRD-798 split `CellRender`
16
+ * into can use it without a host of its own.
17
+ */
18
+
19
+ /**
20
+ * Instance-matrix bytes a world keeps in released shared batches, oldest dropped first. A batch is
21
+ * sized to its asset's largest cell times the resident cells, so on a 2 km package one runs 80 kB
22
+ * median and 0.9 MB worst, and every key in the world at once is 26 MB. The budget holds the walk's
23
+ * own back-traffic — a batch leaves when the last cell holding its asset leaves, and is wanted
24
+ * again a few hundred metres back — and lets the rest go, so a session that crosses the whole map
25
+ * does not carry the whole map.
26
+ */
27
+ export const RETIRED_SHARED_BYTES = 8_000_000;
28
+
29
+ /**
30
+ * How far past the frustum a world-grid square is kept inside the main pass's draw window, in metres.
31
+ *
32
+ * The window is decided once per draw, from the camera that draw uses, and a square that has just
33
+ * left the frustum is dropped from it — so a square at the frustum's edge would be drawn in one
34
+ * frame and not the next, and a tree on that edge pops in at the edge of the screen. Growing each
35
+ * square's box by this margin keeps a band of it in the window while it is still off screen, so a
36
+ * tree crosses into view already there.
37
+ *
38
+ * An eighth of the default 64 m square is deliberately small. It has to exceed what a camera
39
+ * travels between two draws — 8 m a frame is 480 m/s at 60 fps, so no playable camera reaches it —
40
+ * and nothing more, because every metre of it is a metre of geometry the vertex stage still shades.
41
+ */
42
+ export const MAIN_CULL_PAD_METRES = 8;
43
+ /**
44
+ * Fade band, as a share of each gate, for an undithered LOD switch: 1 mm at a 10 m gate and 15 mm at
45
+ * 150 m, so every pixel of a placement takes the same level. Nonzero, so the mask never divides zero
46
+ * by zero exactly at the gate.
47
+ */
48
+ export const UNDITHERED_LOD_WIDTH = 1e-4;
49
+
50
+ const slotFree = new WeakSet<Material>();
51
+ /**
52
+ * Refuse a part material whose node graph reads `instanceIndex`. WorldCells repacks instance slots on
53
+ * every refilter, main-pass cull and LOD switch, so a value hashed from the slot moves to another
54
+ * placement as the viewer walks: Strata's wind phase snapped each crown's top about every 0.7 s.
55
+ * ponytail: walks the material's `*Node` slots as built; an index read hidden inside an unbuilt `Fn`
56
+ * body is not seen until a builder runs it.
57
+ */
58
+ export function assertSlotFree(material: Material, assetId: string): void {
59
+ if (slotFree.has(material)) return;
60
+ const seen = new Set<object>();
61
+ const reads = (value: unknown): boolean => {
62
+ if (typeof value !== "object" || value === null || seen.has(value)) return false;
63
+ seen.add(value);
64
+ const node = value as { isNode?: boolean; isIndexNode?: boolean; scope?: string };
65
+ if (node.isIndexNode === true && node.scope === "instance") return true;
66
+ for (const child of Object.values(value))
67
+ if (
68
+ Array.isArray(child)
69
+ ? child.some(reads)
70
+ : (child as { isNode?: boolean } | null)?.isNode === true && reads(child)
71
+ )
72
+ return true;
73
+ return false;
74
+ };
75
+ for (const [key, value] of Object.entries(material))
76
+ if (
77
+ key.endsWith("Node") &&
78
+ (value as { isNode?: boolean } | null)?.isNode === true &&
79
+ reads(value)
80
+ )
81
+ throw new Error(
82
+ `WorldCells asset "${assetId}" material "${material.name}" reads instanceIndex in ${key}. WorldCells repacks instance slots as the viewer moves, so a per-instance value from the slot jumps between placements; use instanceRandom() from @threenative/core/world.`,
83
+ );
84
+ slotFree.add(material);
85
+ }
86
+
87
+ /**
88
+ * Side of the main cull's own visibility cell, in metres, when it divides the package's `cellSize`.
89
+ *
90
+ * This is the finest grid the main pass can cull on, and it is not a free parameter: a shared
91
+ * batch's block is one *world* cell's records and placements never move, so a world cell cannot be
92
+ * spread across two cells of a finer grid without giving every world cell its own block — one more
93
+ * main mesh per key, which is the cost this whole cull exists to avoid. So a package whose
94
+ * `cellSize` is not a whole multiple of 32 m falls back to its own `cellSize`, which is the square
95
+ * its placements are already cut on, and the rule below is the whole of it.
96
+ *
97
+ * A visibility cell is a sub-square of the shadow caster's world-grid square, and it is deliberately
98
+ * finer than that square: `clusterSize` is sized for how many meshes a shadow level submits, while
99
+ * this is sized for how little geometry the vertex stage is handed. It is also the one volume the
100
+ * cull tests, so everything in it — a 64 m cell's XZ and the Y its own placements and asset bounds
101
+ * reach — is what a draw of that cell costs. See {@link WorldCells.#cullMainPass}.
102
+ */
103
+
104
+ export const MAIN_CULL_SQUARE_METRES = 32;
105
+
106
+ /**
107
+ * How often `TN_WORLD_MAIN_CULL` is printed. Five seconds is a line a playtest capture can hold and
108
+ * a walk long enough to see the window move; every frame is a wall of text over the marker it would
109
+ * report on.
110
+ */
111
+ export const MAIN_CULL_MARKER_MS = 5e3;
112
+
113
+ /** Separate shadow regions one tell carries per kind before the last one absorbs the rest. */
114
+ export const SHADOW_REGION_CAP = 64;
115
+
116
+ /**
117
+ * The name half a shadow key is minted under: `asset:level:part@gpu`, beside the main key it twins
118
+ * rather than in place of it, so both meshes exist — one for the main pass's compaction buffer and
119
+ * one for the shadow twin's, which is the whole difference between them.
120
+ */
121
+ export const GPU_KEY_SUFFIX = "@gpu";
122
+
123
+ /**
124
+ * How many groups the main record is split into. A record walks every draw in its group, so a mint
125
+ * on a streaming walk costs the draws of every shard it touches: Machinefall's ~200 recorded main
126
+ * draws re-recorded as one group put ~290 traversed draws in a frame. Eight shards still read 145,
127
+ * because one asset mints several keys (levels, parts) at once and they land in two or three shards;
128
+ * thirty-two keep a frame that touches several to a few dozen draws. A replay is one
129
+ * `executeBundles` per group, so a shard costs far less than the draws it stops re-walking.
130
+ */
131
+ const MAIN_BUNDLE_SHARDS = 32;
132
+
133
+ /** The shard a key lands in, from its name (FNV-1a), so a key keeps its group for its whole life. */
134
+ export function mainShard(key: string): number {
135
+ let hash = 0x811c9dc5;
136
+ for (let index = 0; index < key.length; index += 1) {
137
+ hash ^= key.charCodeAt(index);
138
+ hash = Math.imul(hash, 0x01000193);
139
+ }
140
+ return (hash >>> 0) % MAIN_BUNDLE_SHARDS;
141
+ }
142
+
143
+ /** Every mesh a prepared chunk draws through the main pass, in traversal order. */
144
+ export function chunkDraws(chunk: Object3D): Mesh[] {
145
+ const draws: Mesh[] = [];
146
+ chunk.traverse((node) => {
147
+ const mesh = node as Mesh;
148
+ if (mesh.isMesh === true && node.layers.isEnabled(0)) draws.push(mesh);
149
+ });
150
+ return draws;
151
+ }
152
+
153
+ /**
154
+ * A geometry that draws `source`'s shape through an indirect record: its own object, so the record is
155
+ * this mesh's, over the same attributes and index, so no vertex buffer is copied.
156
+ */
157
+ export function indirectView(
158
+ source: BufferGeometry,
159
+ args: Parameters<BufferGeometry["setIndirect"]>[0],
160
+ offset: number,
161
+ ): BufferGeometry {
162
+ const view = new BufferGeometry();
163
+ for (const [name, attribute] of Object.entries(source.attributes))
164
+ view.setAttribute(name, attribute);
165
+ view.setIndex(source.index);
166
+ view.morphAttributes = source.morphAttributes;
167
+ view.morphTargetsRelative = source.morphTargetsRelative;
168
+ for (const group of source.groups) view.addGroup(group.start, group.count, group.materialIndex);
169
+ view.boundingBox = source.boundingBox;
170
+ view.boundingSphere = source.boundingSphere;
171
+ view.setIndirect(args, offset);
172
+ return view;
173
+ }
174
+
175
+ /** The materials `redressMaterial` gave a mesh, disposed when the mesh is or when it is re-dressed. */
176
+ const redressed = new WeakMap<InstancedMesh, readonly Material[]>();
177
+
178
+ /**
179
+ * A new object drawing `geometry`, carrying everything `old` carried.
180
+ *
181
+ * Three builds an `InstancedMesh`'s instancing node when the object is first compiled, from the
182
+ * `instanceMatrix` it holds then, and keeps that node for the object's whole life — so a mesh the
183
+ * prewarm already compiled is not pointed at the GPU scene's storage buffer by writing a field onto
184
+ * it. Measured on machinefall: 3,724 indirect draws submitted in 2 s, over indirect records and
185
+ * drawn matrices that were correct at draw time, and a dressed forest that drew nothing at all,
186
+ * until every dressed mesh was a fresh object. A fresh object costs a uuid and a node build, which
187
+ * is what the prewarm paid for a mesh that was about to be replaced anyway; see `#dressGpu`.
188
+ */
189
+ export function freshMeshFor(
190
+ old: InstancedMesh,
191
+ geometry: BufferGeometry,
192
+ count: number,
193
+ ): InstancedMesh {
194
+ const next = new InstancedMesh(geometry, old.material, count);
195
+ next.name = old.name;
196
+ next.layers.mask = old.layers.mask;
197
+ next.castShadow = old.castShadow;
198
+ next.receiveShadow = old.receiveShadow;
199
+ next.renderOrder = old.renderOrder;
200
+ next.userData = old.userData;
201
+ next.position.copy(old.position);
202
+ next.quaternion.copy(old.quaternion);
203
+ next.scale.copy(old.scale);
204
+ next.matrix.copy(old.matrix);
205
+ next.matrixWorld.copy(old.matrixWorld);
206
+ // The authored flags, not the freeze's: a copied `matrixWorldAutoUpdate = false` reads to the new
207
+ // freeze as a game-owned world matrix, and a seated world drew every dressed tree at the package's
208
+ // absolute height.
209
+ next.matrixAutoUpdate = old.matrixAutoUpdate || composeSilencedByFreeze(old);
210
+ next.matrixWorldAutoUpdate = old.matrixWorldAutoUpdate || worldSilencedByFreeze(old);
211
+ // A dressed batch is frozen, and the freeze is keyed by the object: a replacement that did not
212
+ // re-arm it would compose its own world matrix every walk forever.
213
+ if (isStatic(old)) markStatic(next);
214
+ return next;
215
+ }
216
+
217
+ /**
218
+ * Give a mesh a material of its own, so the node three builds for it is its own rather than a shared
219
+ * one's, and dispose those materials with the mesh. The clones share every texture; only the
220
+ * material objects are new. See `#dressGpu`.
221
+ */
222
+ /**
223
+ * The world-grid square the follow point is in, as the `@x,z` half of a cluster key: the square a
224
+ * cell's caster cluster is named for, and the one a prewarm mints first.
225
+ */
226
+ export function followCluster(
227
+ follow: { readonly position: { x: number; z: number } },
228
+ minX: number,
229
+ minZ: number,
230
+ cellSize: number,
231
+ cellsPerCluster: number,
232
+ ): string {
233
+ return clusterOf(
234
+ Math.floor((follow.position.x - minX) / cellSize),
235
+ Math.floor((follow.position.z - minZ) / cellSize),
236
+ cellsPerCluster,
237
+ );
238
+ }
239
+
240
+ /** What a released batch costs to keep: its instance buffer, which is all of it. */
241
+ export function heldBytes(shared: SharedBatch): number {
242
+ // The count, never `array`: the records live in the engine (`world-cell-records.ts`), and a read
243
+ // of a JS copy would upload that stale copy over them.
244
+ return shared.mesh.instanceMatrix.count * 16 * Float32Array.BYTES_PER_ELEMENT;
245
+ }
246
+
247
+ export function redressMaterial(mesh: InstancedMesh): void {
248
+ for (const material of redressed.get(mesh) ?? []) material.dispose();
249
+ const clones: Material[] = [];
250
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
251
+ clones.push(material.clone());
252
+ mesh.material = Array.isArray(mesh.material) ? clones : (clones[0] as Material);
253
+ if (!redressed.has(mesh))
254
+ mesh.addEventListener("dispose", () => {
255
+ for (const material of redressed.get(mesh) ?? []) material.dispose();
256
+ redressed.delete(mesh);
257
+ });
258
+ redressed.set(mesh, clones);
259
+ }