@threenative/terrain 0.1.11 → 0.1.12

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 (218) hide show
  1. package/README.md +1 -0
  2. package/dist/bake-DJ5cxg0C.d.ts +82 -0
  3. package/dist/editor/index.d.ts +4 -4
  4. package/dist/editor/index.js +1 -1
  5. package/dist/editor/server.d.ts +2 -2
  6. package/dist/editor/worker.d.ts +1 -1
  7. package/dist/editor/worker.js +1 -1
  8. package/dist/export.d.ts +1 -1
  9. package/dist/index.d.ts +51 -222
  10. package/dist/index.js +111 -2
  11. package/dist/kit-world.d.ts +107 -0
  12. package/dist/kit-world.js +5134 -0
  13. package/dist/kit.d.ts +21 -4
  14. package/dist/kit.js +19 -4
  15. package/dist/mcp/cook-child.js +9 -6
  16. package/dist/mcp/server.js +14 -4
  17. package/dist/prop-package-Dwz0EWoB.d.ts +141 -0
  18. package/dist/{server-B5RdvEAC.d.ts → server-LnFwY8sr.d.ts} +1 -1
  19. package/dist/starter.d.ts +1141 -6
  20. package/dist/starter.js +1999 -17
  21. package/dist/{terrain-CAEaW0mQ.d.ts → terrain-DYCyAOCJ.d.ts} +1 -1
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-BpH00qsx.d.ts → types-kpI0C4hW.d.ts} +1 -1
  24. package/dist/{world-package-B8QgHjAQ.d.ts → world-package-DqJC3-Nn.d.ts} +2 -2
  25. package/docs/authoring/new-environment.md +97 -0
  26. package/package.json +8 -8
  27. package/starter/alpine/README.md +22 -14
  28. package/starter/alpine/bake.mjs +14 -1
  29. package/starter/alpine/biome.data.json +187 -25
  30. package/starter/alpine/heightmap.r16 +0 -0
  31. package/starter/alpine/playerRig.ts +89 -0
  32. package/starter/alpine/recipe.json +169 -15
  33. package/starter/alpine/render/bakedFile.ts +17 -0
  34. package/starter/alpine/render/benchmark.ts +77 -0
  35. package/starter/alpine/render/biomeData.ts +14 -0
  36. package/starter/alpine/render/biomes.ts +687 -0
  37. package/starter/alpine/render/ground/cover.ts +565 -0
  38. package/starter/alpine/render/ground/horizon.ts +219 -0
  39. package/starter/alpine/render/ground/palette.d.ts +1 -0
  40. package/starter/alpine/render/ground/palette.js +11 -0
  41. package/starter/alpine/render/ground/scatter.ts +104 -0
  42. package/starter/alpine/render/ground/terrain.ts +1860 -0
  43. package/starter/alpine/render/kitAssets.ts +28 -0
  44. package/starter/alpine/render/loading.ts +354 -0
  45. package/starter/alpine/render/lookKnobs.ts +37 -0
  46. package/starter/alpine/render/orbitCamera.ts +155 -0
  47. package/starter/alpine/render/props/farForest.ts +94 -0
  48. package/starter/alpine/render/props/pack.ts +1114 -0
  49. package/starter/alpine/render/props/prepared.ts +225 -0
  50. package/starter/alpine/render/props/propMaterials.ts +1239 -0
  51. package/starter/alpine/render/props/propProgress.ts +2 -0
  52. package/starter/alpine/render/props/propWorld.ts +105 -0
  53. package/starter/alpine/render/props/props.ts +633 -0
  54. package/starter/alpine/render/props/spruce.ts +440 -0
  55. package/starter/alpine/render/sky/atmosphere.ts +329 -0
  56. package/starter/alpine/render/sky/sky.ts +382 -0
  57. package/starter/alpine/render/texturePreparation.ts +135 -0
  58. package/starter/alpine/render/water/river.ts +1132 -0
  59. package/starter/alpine/render/worldNames.ts +6 -0
  60. package/starter/alpine/scene.ts +715 -0
  61. package/starter/alpine/sceneProps.ts +561 -0
  62. package/starter/alpine/sceneState.ts +33 -0
  63. package/starter/alpine/world/terrainAssets.ts +145 -0
  64. package/starter/alpine/world/walkBand.ts +47 -0
  65. package/starter/alpine/world/water.ts +74 -0
  66. package/starter/alpine/worlds.ts +13 -0
  67. package/starter/coastal/README.md +26 -27
  68. package/starter/coastal/assets.json +10 -0
  69. package/starter/coastal/bake.mjs +14 -1
  70. package/starter/coastal/biome.data.json +18 -3
  71. package/starter/coastal/playerRig.ts +89 -0
  72. package/starter/coastal/recipe.json +220 -18
  73. package/starter/coastal/render/bakedFile.ts +17 -0
  74. package/starter/coastal/render/benchmark.ts +81 -0
  75. package/starter/coastal/render/biomeData.ts +14 -0
  76. package/starter/coastal/render/biomes.ts +678 -0
  77. package/starter/coastal/render/ground/cover.ts +565 -0
  78. package/starter/coastal/render/ground/horizon.ts +219 -0
  79. package/starter/coastal/render/ground/palette.d.ts +1 -0
  80. package/starter/coastal/render/ground/palette.js +11 -0
  81. package/starter/coastal/render/ground/scatter.ts +104 -0
  82. package/starter/coastal/render/ground/terrain.ts +1829 -0
  83. package/starter/coastal/render/kitAssets.ts +28 -0
  84. package/starter/coastal/render/loading.ts +354 -0
  85. package/starter/coastal/render/lookKnobs.ts +37 -0
  86. package/starter/coastal/render/orbitCamera.ts +155 -0
  87. package/starter/coastal/render/props/farForest.ts +94 -0
  88. package/starter/coastal/render/props/pack.ts +1109 -0
  89. package/starter/coastal/render/props/prepared.ts +225 -0
  90. package/starter/coastal/render/props/propMaterials.ts +1239 -0
  91. package/starter/coastal/render/props/propProgress.ts +2 -0
  92. package/starter/coastal/render/props/propWorld.ts +105 -0
  93. package/starter/coastal/render/props/props.ts +633 -0
  94. package/starter/coastal/render/props/spruce.ts +440 -0
  95. package/starter/coastal/render/sky/atmosphere.ts +329 -0
  96. package/starter/coastal/render/sky/sky.ts +382 -0
  97. package/starter/coastal/render/texturePreparation.ts +135 -0
  98. package/starter/coastal/render/water/ocean.ts +284 -0
  99. package/starter/coastal/render/water/river.ts +1132 -0
  100. package/starter/coastal/render/worldNames.ts +6 -0
  101. package/starter/coastal/scene.ts +740 -0
  102. package/starter/coastal/sceneProps.ts +559 -0
  103. package/starter/coastal/sceneState.ts +33 -0
  104. package/starter/coastal/world/terrainAssets.ts +151 -0
  105. package/starter/coastal/world/walkBand.ts +47 -0
  106. package/starter/coastal/world/water.ts +74 -0
  107. package/starter/coastal/worlds.ts +13 -0
  108. package/starter/desert/README.md +51 -25
  109. package/starter/desert/bake-flora.mjs +142 -0
  110. package/starter/desert/bake-rocks.mjs +291 -0
  111. package/starter/desert/bake.mjs +14 -1
  112. package/starter/desert/biome.data.json +24 -12
  113. package/starter/desert/playerRig.ts +89 -0
  114. package/starter/desert/recipe.json +63 -16
  115. package/starter/desert/render/bakedFile.ts +17 -0
  116. package/starter/desert/render/benchmark.ts +79 -0
  117. package/starter/desert/render/biomeData.ts +14 -0
  118. package/starter/desert/render/biomes.ts +660 -0
  119. package/starter/desert/render/ground/cover.ts +565 -0
  120. package/starter/desert/render/ground/debris.ts +136 -0
  121. package/starter/desert/render/ground/horizon.ts +219 -0
  122. package/starter/desert/render/ground/palette.d.ts +1 -0
  123. package/starter/desert/render/ground/palette.js +11 -0
  124. package/starter/desert/render/ground/scatter.ts +104 -0
  125. package/starter/desert/render/ground/terrain.ts +1854 -0
  126. package/starter/desert/render/kitAssets.ts +28 -0
  127. package/starter/desert/render/loading.ts +354 -0
  128. package/starter/desert/render/lookKnobs.ts +37 -0
  129. package/starter/desert/render/orbitCamera.ts +155 -0
  130. package/starter/desert/render/props/farForest.ts +96 -0
  131. package/starter/desert/render/props/formations.ts +630 -0
  132. package/starter/desert/render/props/pack.ts +1195 -0
  133. package/starter/desert/render/props/prepared.ts +225 -0
  134. package/starter/desert/render/props/propMaterials.ts +1255 -0
  135. package/starter/desert/render/props/propProgress.ts +2 -0
  136. package/starter/desert/render/props/propWorld.ts +105 -0
  137. package/starter/desert/render/props/props.ts +624 -0
  138. package/starter/desert/render/props/spruce.ts +440 -0
  139. package/starter/desert/render/sand.ts +581 -0
  140. package/starter/desert/render/sky/atmosphere.ts +329 -0
  141. package/starter/desert/render/sky/sky.ts +382 -0
  142. package/starter/desert/render/texturePreparation.ts +135 -0
  143. package/starter/desert/render/water/river.ts +1132 -0
  144. package/starter/desert/render/worldNames.ts +6 -0
  145. package/starter/desert/scene.ts +748 -0
  146. package/starter/desert/sceneProps.ts +562 -0
  147. package/starter/desert/sceneState.ts +33 -0
  148. package/starter/desert/world/terrainAssets.ts +162 -0
  149. package/starter/desert/world/walkBand.ts +47 -0
  150. package/starter/desert/world/water.ts +74 -0
  151. package/starter/desert/worlds.ts +13 -0
  152. package/starter/forest/README.md +8 -5
  153. package/starter/forest/bake.mjs +21 -413
  154. package/starter/forest/playerRig.ts +37 -171
  155. package/starter/forest/recipe.json +237 -47
  156. package/starter/forest/render/biomes.ts +2 -1
  157. package/starter/forest/render/ground/horizon.ts +4 -302
  158. package/starter/forest/render/ground/terrain.ts +14 -32
  159. package/starter/forest/render/kitAssets.ts +3 -2
  160. package/starter/forest/render/props/farForest.ts +2 -1
  161. package/starter/forest/render/props/pack.ts +4 -2
  162. package/starter/forest/render/props/prepared.ts +2 -1
  163. package/starter/forest/render/props/propProgress.ts +1 -11
  164. package/starter/forest/render/props/propWorld.ts +48 -662
  165. package/starter/forest/render/props/props.ts +64 -248
  166. package/starter/forest/render/sky/sky.ts +2 -1
  167. package/starter/forest/render/worldNames.ts +6 -2
  168. package/starter/forest/scene.ts +34 -25
  169. package/starter/forest/sceneProps.ts +2 -2
  170. package/starter/forest/sceneState.ts +5 -4
  171. package/starter/forest/surface.json +2 -2
  172. package/starter/forest/worlds.ts +3 -2
  173. package/starter/tundra/README.md +35 -16
  174. package/starter/tundra/bake.mjs +14 -1
  175. package/starter/tundra/biome.data.json +6 -6
  176. package/starter/tundra/playerRig.ts +89 -0
  177. package/starter/tundra/recipe.json +111 -110
  178. package/starter/tundra/render/bakedFile.ts +17 -0
  179. package/starter/tundra/render/benchmark.ts +79 -0
  180. package/starter/tundra/render/biomeData.ts +14 -0
  181. package/starter/tundra/render/biomes.ts +714 -0
  182. package/starter/tundra/render/ground/cover.ts +565 -0
  183. package/starter/tundra/render/ground/horizon.ts +219 -0
  184. package/starter/tundra/render/ground/palette.d.ts +1 -0
  185. package/starter/tundra/render/ground/palette.js +11 -0
  186. package/starter/tundra/render/ground/scatter.ts +104 -0
  187. package/starter/tundra/render/ground/terrain.ts +1874 -0
  188. package/starter/tundra/render/kitAssets.ts +28 -0
  189. package/starter/tundra/render/loading.ts +354 -0
  190. package/starter/tundra/render/lookKnobs.ts +37 -0
  191. package/starter/tundra/render/orbitCamera.ts +155 -0
  192. package/starter/tundra/render/props/farForest.ts +96 -0
  193. package/starter/tundra/render/props/pack.ts +1088 -0
  194. package/starter/tundra/render/props/prepared.ts +225 -0
  195. package/starter/tundra/render/props/propMaterials.ts +1247 -0
  196. package/starter/tundra/render/props/propProgress.ts +2 -0
  197. package/starter/tundra/render/props/propWorld.ts +105 -0
  198. package/starter/tundra/render/props/props.ts +624 -0
  199. package/starter/tundra/render/props/spruce.ts +440 -0
  200. package/starter/tundra/render/sky/atmosphere.ts +329 -0
  201. package/starter/tundra/render/sky/sky.ts +382 -0
  202. package/starter/tundra/render/texturePreparation.ts +135 -0
  203. package/starter/tundra/render/water/river.ts +1132 -0
  204. package/starter/tundra/render/worldNames.ts +6 -0
  205. package/starter/tundra/scene.ts +715 -0
  206. package/starter/tundra/sceneProps.ts +559 -0
  207. package/starter/tundra/sceneState.ts +33 -0
  208. package/starter/tundra/world/terrainAssets.ts +159 -0
  209. package/starter/tundra/world/walkBand.ts +47 -0
  210. package/starter/tundra/world/water.ts +74 -0
  211. package/starter/tundra/worlds.ts +13 -0
  212. package/starter-assets.json +4 -4
  213. package/starter-credits.json +613 -10
  214. package/starter/forest/diagnostics.ts +0 -1020
  215. package/starter/forest/render/sky/skyVisibility.ts +0 -121
  216. package/starter/forest/spawnGate.ts +0 -183
  217. package/starter/forest/viewStatistics.ts +0 -47
  218. package/starter/forest/world/streamedGround.ts +0 -139
@@ -1,66 +1,35 @@
1
- // The game's prop worlds: the containers the bake wrote, posed on the ground and handed to WorldCells.
2
- //
3
- // What lives here and what does not:
4
- //
5
- // - The bake compiles the placements (`@threenative/terrain`'s `compilePropBuckets`): which streamed
6
- // world each record draws in, its cell, and its position, authored quaternion and scale. The game
7
- // loads those files; it holds no compiler.
8
- // - The editor and the scripts hold their placements live, so they pass them here and the package
9
- // compiles them. One call, one implementation, one layout.
10
- // - The pose stays the game's: `preparePose` grounds every record on the foot geometry the machine
11
- // loaded, with the record's quaternion as its pose override, so the boulder burial, the flat
12
- // footprint sink and the mountain base ring run exactly as they did before the bake owned the
13
- // container.
14
- // - Everything below the pose is `WorldCells`' own: admission, residency, LOD and shadows.
15
- import { type IAssetLoader, addInSlices, createAssetLoader } from "@threenative/core";
1
+ // The forest's prop worlds: the bake's containers, the meadow the game plants at load, and the
2
+ // terminal gate this kit gives its spruces. The container loop, the record poses and the loaders
3
+ // live in `@threenative/terrain/starter`; this file supplies the rows that make them the forest's.
4
+ import type { IAssetLoader } from "@threenative/core";
5
+ import type { IShadowRegion, IWorldCellsFollow } from "@threenative/core/world";
6
+ import type { IPlacement, IPropBucketPackage, IPropPackage } from "@threenative/terrain";
16
7
  import {
17
- type IShadowRegion,
18
- type IWorldAsset,
19
- type IWorldCellsFollow,
20
- type IWorldPackage,
21
- WorldCells,
22
- } from "@threenative/core/world";
23
- import {
24
- type IPlacement,
25
- type IPropBucketEntry,
26
- type IPropBucketPackage,
27
- type IPropPackage,
28
- PROP_CELL_SIZE,
29
- compilePropBuckets,
30
- decodePropBucket,
31
- propAssetOf,
32
- } from "@threenative/terrain";
33
- import {
34
- Box3,
35
- type Camera,
36
- Group,
37
- InstancedMesh,
38
- type Material,
39
- Mesh,
40
- Quaternion,
41
- Vector3,
42
- } from "three";
43
- import { fetchBakedFile } from "../bakedFile.js";
8
+ type IPropWorldOptions as IPackagePropWorldOptions,
9
+ type IPropPreparationProgress,
10
+ type IScatter,
11
+ invalidatePropShadows,
12
+ loadCanopy,
13
+ loadPropPackage,
14
+ loadSky,
15
+ propCounts as propCountsIn,
16
+ streamProps as streamPropsIn,
17
+ } from "@threenative/terrain/starter";
18
+ import type { Box3 } from "three";
44
19
  import { FAR_FOREST_IMPOSTOR, FAR_FOREST_LAYER } from "./farForest.js";
45
20
  import { standShaded } from "./propMaterials.js";
46
- import type { IPropPreparationProgress } from "./propProgress.js";
47
21
  import {
48
- type IPropInstance,
22
+ GROUND_RULES,
49
23
  type IPropMaterials,
50
24
  type IPropPart,
51
25
  LOD_BANDS,
26
+ NO_SHADOW_ASSETS,
52
27
  PROP_ASSETS,
53
28
  type PropGroundQuery,
54
- impostorDistanceForScale,
55
29
  lodSteps,
56
- preparePose,
57
- propKey,
58
- propRatio,
59
- spruceGateScales,
60
30
  streamedBucket,
61
31
  streamedReach,
62
32
  variantFor,
63
- withAuthoredPose,
64
33
  } from "./props.js";
65
34
 
66
35
  export interface IPropWorldOptions {
@@ -95,245 +64,6 @@ export interface IPropWorldOptions {
95
64
  readonly onPublication?: (bounds: Box3) => void;
96
65
  }
97
66
 
98
- // One shaded copy per source material and bucket kind: every tree of a variant shares its crown.
99
- const standMaterials = {
100
- far: new WeakMap<Material, Material>(),
101
- local: new WeakMap<Material, Material>(),
102
- };
103
- function standMaterial(
104
- source: Material,
105
- shade: readonly [number, number, number],
106
- shadowReach?: number,
107
- ): Material {
108
- const copies = standMaterials[shadowReach === undefined ? "far" : "local"];
109
- let shaded = copies.get(source);
110
- if (!shaded) {
111
- shaded = standShaded(source, shade, shadowReach);
112
- copies.set(source, shaded);
113
- }
114
- return shaded;
115
- }
116
-
117
- /** Keep WorldCells' changed caster bounds when forwarding to the existing shadow renderer. */
118
- export function invalidatePropShadows(
119
- shadow: { invalidateRegion(region: IShadowRegion): void; invalidateAll(): void },
120
- region?: IShadowRegion,
121
- ): void {
122
- if (region === undefined) shadow.invalidateAll();
123
- else shadow.invalidateRegion(region);
124
- }
125
-
126
- /** One placement as its container stores it: the record's numbers and the world it draws in. */
127
- interface IRecord {
128
- /** The model the record's run names: `asset:variant`, with the shape a non-uniform edit gave it. */
129
- readonly key: string;
130
- readonly placement: IPlacement;
131
- /** The quaternion the bake authored; `preparePose` takes it as the pose override. */
132
- readonly quaternion: readonly [number, number, number, number];
133
- readonly reach: number;
134
- }
135
-
136
- /** One grounded placement: the pose the game draws, and the variant its asset resolved to. */
137
- interface IGroundedRecord {
138
- readonly key: string;
139
- readonly placement: IPlacement;
140
- readonly pose: ReturnType<typeof preparePose>;
141
- readonly reach: number;
142
- readonly ratio: Vector3;
143
- readonly position: Vector3;
144
- readonly quaternion: Quaternion;
145
- readonly scale: number;
146
- }
147
-
148
- /** One world's baked props: the containers it streams, the canopy it shades and the counts it reports. */
149
- export interface IScatter {
150
- readonly package: IPropPackage;
151
- readonly canopy: Float32Array;
152
- readonly counts: Readonly<Record<string, number>>;
153
- }
154
-
155
- /** Records per asset across the package's buckets: what the run report calls the scatter's counts. */
156
- export function propCounts(pkg: IPropPackage): Record<string, number> {
157
- // Every asset the starter knows starts at 0. A world that places none of one still reports its
158
- // count, because the run report reads a fixed key per asset and an absent key is `undefined`,
159
- // which the playtest bridge refuses as an observation that is not JSON-safe.
160
- const counts: Record<string, number> = {};
161
- for (const asset of Object.keys(PROP_ASSETS)) counts[asset] = 0;
162
- for (const bucket of pkg.buckets)
163
- for (const cell of bucket.cells)
164
- for (const run of cell.runs) {
165
- const asset = propAssetOf(run.asset);
166
- counts[asset] = (counts[asset] ?? 0) + run.count;
167
- }
168
- return counts;
169
- }
170
-
171
- /** One bucket as the bake's manifest describes it: where its files are and what they hold. */
172
- interface IPropBucketManifest {
173
- readonly bucket: string;
174
- readonly kind: IPropBucketPackage["kind"];
175
- readonly extent: IPropBucketPackage["extent"];
176
- readonly cells: IPropBucketPackage["cells"];
177
- readonly placements: string;
178
- readonly reach: string;
179
- readonly ids: string;
180
- }
181
-
182
- /**
183
- * The baked prop package of one world, fetched as the bake wrote it.
184
- *
185
- * The files are the bake's output, not the game's: the manifest names one container, one reach array
186
- * and one placement-ID list per streamed world, and nothing here derives a placement.
187
- */
188
- export async function loadPropPackage(
189
- assets: Pick<IAssetLoader, "resolve">,
190
- world: string,
191
- ): Promise<IPropPackage> {
192
- const listing = (await (
193
- await fetchBakedFile(assets, `world/${world}.props.json`, "prop package")
194
- ).json()) as { version: 1; cellSize: number; buckets: IPropBucketManifest[] };
195
- if (listing.version !== 1)
196
- throw new Error(`Unsupported prop package: ${String(listing.version)}`);
197
- return {
198
- cellSize: listing.cellSize,
199
- buckets: await Promise.all(
200
- listing.buckets.map(async (bucket) => {
201
- const [records, reach, ids] = await Promise.all([
202
- fetchBakedFile(assets, `world/${bucket.placements}`, "prop records"),
203
- fetchBakedFile(assets, `world/${bucket.reach}`, "prop reach"),
204
- fetchBakedFile(assets, `world/${bucket.ids}`, "prop placement IDs"),
205
- ]);
206
- return {
207
- bucket: bucket.bucket,
208
- cells: bucket.cells,
209
- extent: bucket.extent,
210
- ids: (await ids.json()) as string[],
211
- kind: bucket.kind,
212
- placements: new Uint8Array(await records.arrayBuffer()),
213
- reach: new Float32Array(await reach.arrayBuffer()),
214
- };
215
- }),
216
- ),
217
- };
218
- }
219
-
220
- /** The canopy weight the ground shader reads, painted from the placements the bake drew. */
221
- export async function loadCanopy(
222
- assets: Pick<IAssetLoader, "resolve">,
223
- world: string,
224
- ): Promise<Float32Array> {
225
- const response = await fetchBakedFile(assets, `world/${world}.canopy.bin`, "canopy map");
226
- return new Float32Array(await response.arrayBuffer());
227
- }
228
-
229
- /** The share of the sky each terrain vertex sees past the relief, as `skyVisibility` baked it. */
230
- export async function loadSky(
231
- assets: Pick<IAssetLoader, "resolve">,
232
- world: string,
233
- ): Promise<Float32Array> {
234
- const response = await fetchBakedFile(assets, `world/${world}.sky.bin`, "sky visibility map");
235
- return Float32Array.from(new Uint8Array(await response.arrayBuffer()), (byte) => byte / 255);
236
- }
237
-
238
- /** The bucket's records as placements: the bake's own decode, with the record's model and pose. */
239
- function recordsOf(bucket: IPropBucketPackage): IRecord[] {
240
- return decodePropBucket(bucket).map((record) => ({
241
- key: record.key,
242
- // A run names the model it draws: the asset, the variant, and the shape when one scale cannot
243
- // carry the placement. The asset alone is what `preparePose` grounds.
244
- placement: {
245
- alignToNormal: false,
246
- asset: record.asset,
247
- id: record.id,
248
- layer: `temperate-${record.asset}`,
249
- normal: [0, 1, 0],
250
- position: [...record.position],
251
- rotation: 0,
252
- scale: record.scale,
253
- },
254
- quaternion: record.quaternion,
255
- reach: record.reach,
256
- }));
257
- }
258
-
259
- /** The variant counters the bake left: a live placement's fade continues the stream it joined. */
260
- function variantSeeds(records: readonly IRecord[]): Map<string, number> {
261
- const seeds = new Map<string, number>();
262
- for (const record of records) {
263
- const variant = `${record.placement.asset}:${variantFor(record.placement, record.placement.asset)}`;
264
- seeds.set(variant, (seeds.get(variant) ?? 0) + 1);
265
- }
266
- return seeds;
267
- }
268
-
269
- /** The streamed world a live placement joins, and how far it draws. */
270
- function liveEntries(
271
- placements: readonly IPlacement[],
272
- seeds: Map<string, number>,
273
- ): IPropBucketEntry[] {
274
- const indices = new Map(seeds);
275
- return placements.map((placement) => {
276
- const variant = `${placement.asset}:${variantFor(placement, placement.asset)}`;
277
- const index = indices.get(variant) ?? 0;
278
- indices.set(variant, index + 1);
279
- const reach = streamedReach(placement, index);
280
- return {
281
- bucket: streamedBucket(placement, reach),
282
- key: propKey(placement),
283
- kind: placement.layer === FAR_FOREST_LAYER ? "far" : "local",
284
- placement,
285
- reach,
286
- };
287
- });
288
- }
289
-
290
- /** The camera-independent stats the run report reads, summed over every streamed world. */
291
- function statsOf(worlds: readonly WorldCells[]) {
292
- return worlds.reduce(
293
- (sum, world) => {
294
- const s = world.stats();
295
- return {
296
- residentCells: sum.residentCells + s.residentCells,
297
- loadedCells: sum.loadedCells + s.loadedCells,
298
- instances: sum.instances + s.instances,
299
- evictions: sum.evictions + s.evictions,
300
- failures: sum.failures + s.failures,
301
- loadsInFlight: sum.loadsInFlight + s.loadsInFlight,
302
- loadsQueued: sum.loadsQueued + s.loadsQueued,
303
- pendingPrewarm: sum.pendingPrewarm + s.pendingPrewarm,
304
- impostor: {
305
- pending: sum.impostor.pending + s.impostor.pending,
306
- drawn: sum.impostor.drawn + s.impostor.drawn,
307
- },
308
- admissionMs: sum.admissionMs + s.admission.spentMs,
309
- admissionBacklog: sum.admissionBacklog + s.admission.backlog,
310
- admissionDeferred: sum.admissionDeferred + s.admission.deferred,
311
- };
312
- },
313
- {
314
- residentCells: 0,
315
- loadedCells: 0,
316
- instances: 0,
317
- evictions: 0,
318
- failures: 0,
319
- loadsInFlight: 0,
320
- loadsQueued: 0,
321
- pendingPrewarm: 0,
322
- impostor: { pending: 0, drawn: 0 },
323
- admissionMs: 0,
324
- admissionBacklog: 0,
325
- admissionDeferred: 0,
326
- },
327
- );
328
- }
329
-
330
- /** The placement IDs the bake wrote: the load plants only the ground the bake left out. */
331
- function bakedIds(plans: readonly IPropBucketPackage[]): Set<string> {
332
- const ids = new Set<string>();
333
- for (const plan of plans) for (const id of plan.ids) ids.add(id);
334
- return ids;
335
- }
336
-
337
67
  /**
338
68
  * Load the prop worlds, pose every record on the ground, and hand each bucket to `WorldCells`.
339
69
  *
@@ -342,378 +72,34 @@ function bakedIds(plans: readonly IPropBucketPackage[]): Set<string> {
342
72
  * each bucket loads as its own world.
343
73
  */
344
74
  export async function streamProps(options: IPropWorldOptions) {
345
- if (!options.whileCurrent()) return undefined;
346
- let compileSlices = 0;
347
- const worlds: WorldCells[] = [];
348
- const warmed = new Set<WorldCells>();
349
- let phase: IPropPreparationProgress["phase"] = "grounding";
350
- let currentBucket = "";
351
- function progress(added: number, total: number): void {
352
- options.onProgress?.({
353
- bucket: currentBucket,
354
- phase,
355
- added,
356
- total,
357
- worlds,
358
- get prewarmedWorlds() {
359
- return warmed.size;
360
- },
361
- });
362
- }
363
- function startPhase(next: IPropPreparationProgress["phase"], bucket = "", total = 0): void {
364
- phase = next;
365
- currentBucket = bucket;
366
- progress(0, total);
367
- }
368
- async function compile<T>(items: Iterable<T>, visit: (item: T) => void): Promise<boolean> {
369
- const report = await addInSlices(items, visit, {
370
- while: options.whileCurrent,
371
- onProgress: ({ added, total }) => progress(added, total),
372
- });
373
- compileSlices += report.slices;
374
- // Separate short dependent passes too: their combined work must not become one host task.
375
- await new Promise<void>((resolve) => setTimeout(resolve, 0));
376
- return !report.stopped && options.whileCurrent();
377
- }
378
- // The containers the run streams: the baked buckets it keeps, then the caller's live placements
379
- // compiled through the package. A live placement the bake already wrote is dropped, so a bake
380
- // that gains the far field needs no change here. The bake wins on a placement, not on a
381
- // container: the meadow a view plants off the square streams beside the bake's own `local:false`
382
- // container, which holds the square's scatter and nothing of that meadow.
383
- const plans = [...(options.package?.buckets ?? [])].filter(
384
- (bucket: IPropBucketPackage) => options.buckets?.(bucket) ?? true,
385
- );
386
- const decoded = plans.map(recordsOf);
387
- let live: Array<{ plan: IPropBucketPackage; records: IRecord[] }> = [];
388
- const placements = options.placements ?? [];
389
- if (placements.length > 0) {
390
- const baked = bakedIds(plans);
391
- const seeds = variantSeeds(decoded.flat());
392
- const entries = liveEntries(
393
- placements.filter((placement) => !baked.has(placement.id)),
394
- seeds,
395
- );
396
- const compiled = compilePropBuckets(
397
- entries.map((entry) => ({ ...entry, placement: withAuthoredPose(entry.placement) })),
398
- {
399
- cellSize: options.package?.cellSize ?? PROP_CELL_SIZE,
400
- bounds: {
401
- minX: -options.size / 2,
402
- minZ: -options.size / 2,
403
- sizeX: options.size,
404
- sizeZ: options.size,
405
- },
406
- },
407
- );
408
- // The container's records carry one uniform scale, so the source placement is what the pose
409
- // reads: an edited placement draws the shape its own transform names.
410
- const source = new Map(entries.map((entry) => [entry.placement.id, entry.placement]));
411
- live = compiled.buckets.map((plan) => ({
412
- plan,
413
- records: recordsOf(plan).map((record) => ({
414
- ...record,
415
- placement: source.get(record.placement.id) ?? record.placement,
416
- })),
417
- }));
418
- }
419
- const buckets = [
420
- ...plans.map((plan, index) => ({ plan, records: decoded[index] as IRecord[] })),
421
- ...live,
422
- ];
423
- const total = buckets.reduce((sum, bucket) => sum + bucket.records.length, 0);
424
-
425
- const grouped = new Map<IPropBucketPackage, IGroundedRecord[]>(
426
- buckets.map((bucket) => [bucket.plan, []]),
427
- );
428
- const byId = new Map<string, IPropInstance>();
429
- const shapes = new Map<string, { parts: IPropPart[]; ratio: Vector3 }>();
430
- startPhase("grounding", "", total);
431
- const report = await addInSlices(
432
- buckets.flatMap((bucket) => bucket.records.map((record) => ({ bucket: bucket.plan, record }))),
433
- ({ bucket, record }) => {
434
- const variant = `${record.placement.asset}:${variantFor(record.placement, record.placement.asset)}`;
435
- const chosen = options.parts.get(variant);
436
- const foot =
437
- chosen?.find((part) => part.role === "bark" || part.role === "stone") ?? chosen?.[0];
438
- if (!chosen || !foot) throw new Error(`Prop asset '${variant}' has no parts`);
439
- // A record's own pose is the authored one, which the bake stored; a live placement the editor
440
- // edited carries its transform, and the pose steps that burial owns run on the authored one.
441
- const pose = preparePose(
442
- foot.geometry,
443
- options.materials[foot.role],
444
- record.placement,
445
- record.placement.transform,
446
- options.groundAt,
447
- { quaternion: record.quaternion },
448
- );
449
- const position = new Vector3();
450
- const quaternion = new Quaternion();
451
- const scale = new Vector3();
452
- pose.matrix.decompose(position, quaternion, scale);
453
- const scalar = scale.x === 0 ? 1 : scale.x;
454
- // The container names one model per shape; the variant's own parts are what draw it.
455
- const ratio = new Vector3().fromArray(propRatio(record.key));
456
- shapes.set(record.key, { parts: chosen, ratio });
457
- const key = record.key;
458
- const list = grouped.get(bucket);
459
- if (!list) throw new Error(`Prop bucket '${bucket.bucket}' was not planned`);
460
- list.push({
461
- key,
462
- placement: record.placement,
463
- pose,
464
- reach: record.reach,
465
- ratio,
466
- position,
467
- quaternion,
468
- scale: scalar,
469
- });
470
- byId.set(record.placement.id, {
471
- ...pose,
472
- pose: pose.matrix,
473
- placement: record.placement,
474
- geometry: foot.geometry,
475
- material: foot.material ?? options.materials[foot.role],
476
- });
477
- },
478
- {
479
- while: options.whileCurrent,
480
- onProgress: ({ added, total: count }) => progress(added, count),
481
- },
482
- );
483
- if (report.stopped || !options.whileCurrent()) return undefined;
484
- const minSpruceScaleByVariant = spruceGateScales([...grouped.values()].flat());
485
-
486
- const cellSize = options.package?.cellSize ?? PROP_CELL_SIZE;
487
- const assets = options.assets ?? createAssetLoader();
488
- try {
489
- for (const [plan, list] of grouped) {
490
- if (!options.whileCurrent()) {
491
- for (const world of worlds) world.dispose();
492
- return undefined;
493
- }
494
- let minY = Number.POSITIVE_INFINITY;
495
- let maxY = Number.NEGATIVE_INFINITY;
496
- let maxReach = 0;
497
- startPhase("models", plan.bucket, list.length);
498
- const definitions: Record<string, IWorldAsset> = {};
499
- const models = new Map<string, Group>();
500
- if (
501
- !(await compile(list, (record) => {
502
- minY = Math.min(minY, record.position.y);
503
- maxY = Math.max(maxY, record.position.y);
504
- maxReach = Math.max(maxReach, record.reach);
505
- if (definitions[record.key]) return;
506
- const shape = shapes.get(record.key);
507
- if (!shape) throw new Error(`Missing shape '${record.key}'`);
508
- const levels = [...new Set(shape.parts.map((part) => part.level ?? 0))].sort(
509
- (a, b) => a - b,
510
- );
511
- // A far spruce stands 55 m or more from any eye (`clear` around the vista): it draws its
512
- // coarsest cooked level until the impostor. Its full chain put 14 M triangles in the vista.
513
- const far = plan.bucket.startsWith("far:") && record.key.startsWith("spruce:");
514
- const lods = (far ? [] : levels.slice(1)).map((level, i) => ({
515
- glb: `${record.key}/${level}.glb`,
516
- distance: lodSteps(record.placement.asset)[i === 0 ? 0 : 1],
517
- }));
518
- const bounds = new Box3();
519
- for (const level of levels) {
520
- const group = new Group();
521
- for (const part of shape.parts.filter((part) => (part.level ?? 0) === level)) {
522
- const own = part.material ?? options.materials[part.role];
523
- const mesh = new Mesh(
524
- part.geometry,
525
- options.standShade && record.key.startsWith("spruce:")
526
- ? standMaterial(
527
- own,
528
- options.standShade,
529
- plan.bucket.startsWith("far:") ? undefined : options.shadowReach,
530
- )
531
- : own,
532
- );
533
- mesh.scale.copy(shape.ratio);
534
- group.add(mesh);
535
- }
536
- group.updateMatrixWorld(true);
537
- bounds.union(new Box3().setFromObject(group)); // engine-override: measure generated LOD bounds for the streamed manifest
538
- models.set(`${record.key}/${level}.glb`, group);
539
- }
540
- definitions[record.key] = {
541
- glb: `${record.key}/${far ? levels.at(-1) : 0}.glb`,
542
- ...(record.key.startsWith("spruce:")
543
- ? {
544
- // The package rejects a terminal gate at or inside the last authored step.
545
- impostorDistance: plan.bucket.startsWith("far:")
546
- ? Math.max(
547
- FAR_FOREST_IMPOSTOR,
548
- (lods.at(-1)?.distance ?? 0) * (1 + Number.EPSILON),
549
- )
550
- : impostorDistanceForScale(
551
- minSpruceScaleByVariant.get(
552
- `${record.placement.asset}:${variantFor(record.placement, record.placement.asset)}`,
553
- ) ?? record.scale,
554
- lods.at(-1)?.distance ?? 0,
555
- ),
556
- }
557
- : {}),
558
- bounds: { min: bounds.min.toArray(), max: bounds.max.toArray() },
559
- lods,
560
- };
561
- }))
562
- ) {
563
- for (const world of worlds) world.dispose();
564
- return undefined;
565
- }
566
- // The container holds the authored pose; the ground the props meet is this machine's, and the
567
- // look steps that sink a stone into a slope are `preparePose`'s. So the record the engine
568
- // draws is the grounded one, written in the container's own record order.
569
- const placements = new Float32Array(list.length * 8);
570
- for (const [index, record] of list.entries())
571
- placements.set(
572
- [...record.position.toArray(), ...record.quaternion.toArray(), record.scale],
573
- index * 8,
574
- );
575
- const manifest: IWorldPackage = {
576
- version: 1,
577
- extent: plan.extent,
578
- cellSize,
579
- assets: definitions,
580
- cells: [...plan.cells],
581
- placements: "placements.bin",
582
- terrain: {
583
- heightmap: "unused.u16",
584
- columns: plan.extent.sizeX / cellSize + 1,
585
- rows: plan.extent.sizeZ / cellSize + 1,
586
- spacing: cellSize,
587
- heightMin: minY,
588
- heightMax: maxY,
589
- },
590
- };
591
- const farInstances = list.reduce(
592
- (count, record) =>
593
- count + (definitions[record.key]?.impostorDistance === undefined ? 0 : 1),
594
- 0,
595
- );
596
- // Two CPU-admitted levels need at most 16 bytes of published-range bounds per root.
597
- const rangeRoots = LOD_BANDS.hysteresis > 0 ? list.length : 0;
598
- const ring = Number.isFinite(maxReach)
599
- ? Math.ceil(maxReach / manifest.cellSize) + 1
600
- : Math.ceil(
601
- (options.horizonDistance ?? Math.hypot(plan.extent.sizeX, plan.extent.sizeZ)) /
602
- manifest.cellSize,
603
- ) + 1;
604
- startPhase("world-load", plan.bucket, list.length);
605
- const world = await WorldCells.load({
606
- url: "world.json",
607
- assets,
608
- surface: options.materials.bark,
609
- follow: options.follow,
610
- ring,
611
- // Models are already decoded; the reach ring includes a cell of admission headroom.
612
- // Predictive centring can otherwise evict visible placements after camera jumps.
613
- prefetchSeconds: 0,
614
- terrain: false,
615
- data: { manifest, placements: placements.buffer as ArrayBuffer },
616
- placementReach: plan.reach,
617
- gpuScene: false,
618
- bundles: options.bundles,
619
- onPublication: options.onPublication,
620
- // A whole-asset impostor is only authored for spruce. Other buckets retain their
621
- // authored scatter LODs without asking WorldCells to build a terminal atlas.
622
- impostors: farInstances > 0,
623
- adaptiveLod: false,
624
- preserveAuthoredParts: true,
625
- lodHysteresis: LOD_BANDS.hysteresis,
626
- // A tree standing in a dithered distance band crawled under 4x MSAA as the player walked;
627
- // UE's temporal swap finishes each tree's change in half a second instead.
628
- lodTransition: "temporal",
629
- transparentScatter: "blend",
630
- admissionBudgetMs: 2 / Math.max(1, grouped.size),
631
- budgets: {
632
- residentCells: Math.max(1, plan.cells.length),
633
- instances: Math.max(1, list.length + farInstances),
634
- bytes: Math.max(
635
- 32,
636
- placements.byteLength + rangeRoots * 16 + farInstances * (16 * 4 + 4),
637
- ),
638
- },
639
- shadows: {
640
- cast: plan.bucket.endsWith(":true") && options.castShadows !== false,
641
- castLevels: 3,
642
- // Shadows keep the mid spruce at every distance under the far band: a cached shadow page
643
- // redraws once a second and showed every near/mid swap since in one batch.
644
- minLevel: 1,
645
- receive: true,
646
- smallCasterMetres: 0.0001,
647
- invalidate: options.invalidateShadows,
648
- },
649
- loadModel: async (path) => {
650
- const model = models.get(path);
651
- if (!model) throw new Error(`Missing streamed model '${path}'`);
652
- return model;
653
- },
654
- });
655
- world.name = `strata-props:${plan.bucket}`;
656
- worlds.push(world);
657
- void world.prewarmed.then(() => warmed.add(world));
658
- }
659
- phase = "complete";
660
- currentBucket = "";
661
- progress(total, total);
662
- } catch (error) {
663
- for (const world of worlds) world.dispose();
664
- throw error;
665
- }
666
- grouped.clear();
667
- shapes.clear();
668
- function stats() {
669
- return statsOf(worlds);
670
- }
671
- return {
672
- worlds,
673
- byId,
674
- stats,
675
- compileSlices,
676
- readinessAt(camera: Camera) {
677
- const regions = worlds.map((world) => world.readinessAt(camera));
678
- const required = regions.reduce((n, r) => n + r.requiredCells, 0);
679
- const loaded = regions.reduce((n, r) => n + r.loadedCells, 0);
680
- return {
681
- required,
682
- loaded,
683
- failures: regions.reduce((n, r) => n + r.failures, 0),
684
- ready:
685
- warmed.size === worlds.length &&
686
- regions.every((r) => r.ready) &&
687
- worlds.every((world) => {
688
- const state = world.stats();
689
- return state.impostor.pending === 0 && state.pendingPrewarm === 0;
690
- }),
691
- };
692
- },
693
- get ready() {
694
- const s = stats();
695
- return (
696
- warmed.size === worlds.length &&
697
- s.loadsInFlight === 0 &&
698
- s.loadsQueued === 0 &&
699
- s.admissionBacklog === 0 &&
700
- s.pendingPrewarm === 0 &&
701
- s.impostor.pending === 0 &&
702
- s.failures === 0
703
- );
704
- },
705
- get meshes() {
706
- const meshes: InstancedMesh[] = [];
707
- for (const world of worlds)
708
- world.traverse((node) => {
709
- if (node instanceof InstancedMesh && node.layers.isEnabled(0) && node.visible)
710
- meshes.push(node);
711
- });
712
- return meshes;
713
- },
714
- dispose() {
715
- for (const world of worlds) world.dispose();
716
- byId.clear();
717
- },
75
+ const packageOptions: IPackagePropWorldOptions = {
76
+ ...options,
77
+ groundRules: GROUND_RULES,
78
+ surface: options.materials.bark,
79
+ materials: { ...options.materials },
80
+ variantOf: (placement) => variantFor(placement, placement.asset),
81
+ reachOf: streamedReach,
82
+ bucketOf: (placement, reach) => ({
83
+ name: streamedBucket(placement, reach),
84
+ kind: placement.layer === FAR_FOREST_LAYER ? "far" : "local",
85
+ shadows: !NO_SHADOW_ASSETS.has(placement.asset),
86
+ }),
87
+ lodOf: lodSteps,
88
+ lodHysteresis: LOD_BANDS.hysteresis,
89
+ lodFar: LOD_BANDS.far,
90
+ assetNames: Object.keys(PROP_ASSETS),
91
+ gateAsset: "spruce",
92
+ gateFarDistance: FAR_FOREST_IMPOSTOR,
93
+ shadeStand: standShaded,
94
+ shadowsOf: (bucket) => bucket.bucket.endsWith(":true"),
718
95
  };
96
+ return streamPropsIn(packageOptions);
719
97
  }
98
+
99
+ /** Records per asset across the package's buckets: what the run report calls the scatter's counts. */
100
+ export function propCounts(pkg: IPropPackage): Record<string, number> {
101
+ return propCountsIn(pkg, Object.keys(PROP_ASSETS));
102
+ }
103
+
104
+ export { invalidatePropShadows, loadCanopy, loadPropPackage, loadSky };
105
+ export type { IScatter, IPropPreparationProgress };