@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
@@ -0,0 +1,562 @@
1
+ import type { IAssetLoader } from "@threenative/core";
2
+ import {
3
+ type Heightfield,
4
+ type HeightfieldCollar,
5
+ type IShadowRegion,
6
+ type WorldCells,
7
+ surfaceSampler,
8
+ } from "@threenative/core/world";
9
+ import { ScatterColliders } from "@threenative/physics";
10
+ import type { ISpawnGate, ISpawnWitness } from "@threenative/terrain/starter";
11
+ import type { IRevealProbe } from "@threenative/terrain/starter";
12
+ import {
13
+ Float32BufferAttribute,
14
+ Mesh,
15
+ type Object3D,
16
+ OrthographicCamera,
17
+ PerspectiveCamera,
18
+ Vector3,
19
+ } from "three";
20
+ import { posesFor } from "./render/benchmark.js";
21
+ import type { IBiome, IWorldBiome, WorldName } from "./render/biomes.js";
22
+ import { desertDebris } from "./render/ground/debris.js";
23
+ import { HORIZON_WALK_BAND } from "./render/ground/horizon.js";
24
+ import { meadowCover } from "./render/ground/scatter.js";
25
+ import { type IBakedWorld, OPEN_MEADOW } from "./render/ground/terrain.js";
26
+ import {
27
+ FAR_FOREST,
28
+ FAR_FOREST_WORLDS,
29
+ collarSampler,
30
+ farForestPlacements,
31
+ } from "./render/props/farForest.js";
32
+ import { loadPack, loadSkyLight } from "./render/props/pack.js";
33
+ import { loadPreparedProps } from "./render/props/prepared.js";
34
+ import { createPropSurfaces } from "./render/props/propMaterials.js";
35
+ import type { IPropPreparationProgress } from "./render/props/propProgress.js";
36
+ import type { IScatter } from "./render/props/propWorld.js";
37
+ import { streamProps } from "./render/props/propWorld.js";
38
+ import {
39
+ type PropGroundQuery,
40
+ buildPropVariants,
41
+ flatPropMaterials,
42
+ variantFor,
43
+ } from "./render/props/props.js";
44
+ import { SHADOW_REACH } from "./render/sky/sky.js";
45
+ import { preparePropTextures } from "./render/texturePreparation.js";
46
+ import type { TerrainCtx } from "./sceneState.js";
47
+
48
+ /** The whole set of placements one world scatters, with the canopy weight painted from them. */
49
+ export type Scatter = IScatter;
50
+ /** The built prop variants, keyed by `asset:variant`. */
51
+ export type Variants = ReturnType<typeof buildPropVariants>;
52
+ /** The streamed worlds the meadow builds, once they have landed. */
53
+ type StreamedProps = Awaited<ReturnType<typeof streamProps>>;
54
+ /** One streamed world's spawn join: data and draws, reported separately. */
55
+ export type IPropJoins = Map<WorldCells, { data: string; prewarm: string }>;
56
+
57
+ export interface IMeadowOptions {
58
+ readonly ctx: TerrainCtx;
59
+ /** The forest's own asset loader (`forestAssets`): art and baked files under the kit's root. */
60
+ readonly assets: IAssetLoader;
61
+ readonly world: WorldName;
62
+ readonly data: IBakedWorld;
63
+ /** The biome row's look values: what the props are, and how they sit on the ground. */
64
+ readonly look: IBiome;
65
+ /** The measured elevations of the world this meadow draws. */
66
+ readonly biome: IWorldBiome;
67
+ readonly field: Heightfield;
68
+ /** The drawn terrain mesh. */
69
+ readonly mesh: Mesh | undefined;
70
+ readonly collar: HeightfieldCollar | undefined;
71
+ readonly scatter: Scatter | undefined;
72
+ readonly fallbackParts: Variants | undefined;
73
+ /** Where the player starts in this world: the point every stream measures its spawn cells around. */
74
+ readonly spawn: Vector3;
75
+ /** PRD-790: the streamed ground's first tiles, drawn behind the curtain. */
76
+ readonly groundReady?: Promise<void> | undefined;
77
+ readonly gate: ISpawnGate;
78
+ readonly reveal: IRevealProbe;
79
+ readonly loading: { readonly finish: () => void };
80
+ /** True once the scene tore this world down. */
81
+ readonly released: () => boolean;
82
+ /** Marks the scene released: nothing in this meadow may revive it after that. */
83
+ readonly release: () => void;
84
+ readonly invalidateShadows: (region?: IShadowRegion) => void;
85
+ }
86
+
87
+ export interface IMeadow {
88
+ /** Starts the build on the first physics step, once; undefined when there is nothing to build. */
89
+ readonly start: () => Promise<void> | undefined;
90
+ /** The streamed world, once it landed. */
91
+ readonly props: StreamedProps | undefined;
92
+ readonly colliders: ScatterColliders | undefined;
93
+ /** One entry per streamed world's spawn join, for the frame report. */
94
+ readonly joins: IPropJoins;
95
+ readonly farForest: number;
96
+ readonly preparedLodBaseSpread: number;
97
+ readonly compressedTexturesPrepared: number;
98
+ readonly preparedLevelsWithoutSolid: number;
99
+ /** Where preparation stands, for the spawn failure report. */
100
+ readonly witness: ISpawnWitness;
101
+ /** Completed preparation work, so the loading screen cannot claim progress a stall did not make. */
102
+ readonly progress: () => number;
103
+ /** Advances the prop surface shaders by the scene's own clock. */
104
+ readonly advance: (elapsed: number) => void;
105
+ }
106
+
107
+ /**
108
+ * The meadow: every prop, rock and tree a world draws, and the water the bake carved into it.
109
+ *
110
+ * The build waits for the first physics step rather than `enter`, because both ways of asking the
111
+ * world where the ground is need a world that has been stepped: the ray query walks the heightfield's
112
+ * own triangles and the collider is not in the space until the solver runs. Asking in `enter`
113
+ * returns "no ground here" for every prop on a perfectly solid hillside.
114
+ */
115
+ export function createMeadow(options: IMeadowOptions): IMeadow {
116
+ const {
117
+ assets,
118
+ biome,
119
+ collar,
120
+ ctx,
121
+ data,
122
+ fallbackParts,
123
+ field,
124
+ gate,
125
+ groundReady,
126
+ invalidateShadows,
127
+ loading,
128
+ look,
129
+ mesh,
130
+ release,
131
+ released,
132
+ reveal,
133
+ scatter,
134
+ spawn,
135
+ world,
136
+ } = options;
137
+ // The gate's deadline, joins and its two settlements, under the names this build has always used.
138
+ const { deadlineAt, fail: failSpawn, land, settle } = gate;
139
+ const textureUploads = new AbortController();
140
+ let propsStage = "waiting-for-physics";
141
+ let preparation: IPropPreparationProgress | undefined;
142
+ let buildStartedAt: number | undefined;
143
+ let phaseStartedAt: number | undefined;
144
+ let lastProgressAt: number | undefined;
145
+ let completedPropsWork = 0;
146
+ let props: StreamedProps | undefined;
147
+ let propColliders: ScatterColliders | undefined;
148
+ let building = false;
149
+ let preparedDispose: (() => void) | undefined;
150
+ let surfacesDispose: (() => void) | undefined;
151
+ let surfaces: { advance: (elapsed: number) => void } | undefined;
152
+ let buildProps: (() => Promise<void>) | undefined;
153
+ // What the prepared files measured on load. Published rather than thrown on, because a number in
154
+ // the run report says which level is off the ground and a stack trace does not.
155
+ let preparedLodBaseSpread = 0;
156
+ let compressedTexturesPrepared = 0;
157
+ let preparedLevelsWithoutSolid = 0;
158
+ let farForestCount = 0;
159
+ /** One status record per streamed world's spawn join, for the frame report. */
160
+ const spawnJoins: IPropJoins = new Map();
161
+
162
+ {
163
+ if (!mesh || !collar || !scatter || scatter.canopy.length !== data.resolution ** 2)
164
+ throw new Error(`World ${world} placements do not match the terrain`);
165
+ if (!fallbackParts) throw new Error(`World ${world} prop variants were not loaded`);
166
+ mesh.geometry.setAttribute("canopy", new Float32BufferAttribute(scatter.canopy, 1));
167
+ const fallbackSaplingHeight = look.saplingHeight ?? undefined;
168
+ let propParts = fallbackParts;
169
+ const flat = flatPropMaterials();
170
+ ctx.entities.add("props-lifetime", {
171
+ dispose: () => {
172
+ release();
173
+ textureUploads.abort(new Error("Strata scene released during texture preparation."));
174
+ settle(new Error("Strata spawn cancelled"));
175
+ loading.finish();
176
+ surfacesDispose?.();
177
+ flat.dispose();
178
+ preparedDispose?.();
179
+ props?.dispose();
180
+ propColliders?.dispose();
181
+ for (const parts of propParts.values()) for (const part of parts) part.geometry.dispose();
182
+ },
183
+ });
184
+ // Ground contact is a ray query against the drawn terrain and the terrain's collider, never the
185
+ // bilinear sampler: a spruce floating a centimetre above the visible surface reads as a mistake
186
+ // at exactly the distance a player spends most of their time at.
187
+ mesh.updateMatrixWorld(true);
188
+ mesh.geometry.computeBoundingBox();
189
+ const top = mesh.geometry.boundingBox?.max.y ?? 0;
190
+ // The surroundings rise above the square's top, so their collider ray starts above both.
191
+ const ridges = mesh.getObjectByName("temperate-distant-ridges");
192
+ if (ridges instanceof Mesh) ridges.geometry.computeBoundingBox();
193
+ const rayTop =
194
+ Math.max(top, ridges instanceof Mesh ? (ridges.geometry.boundingBox?.max.y ?? top) : top) + 2;
195
+ const groundSample = surfaceSampler(field, mesh.matrixWorld);
196
+ // Past the walk band's collider the drawn collar is the ground (`farForest.ts`).
197
+ const collarGround = collarSampler(collar);
198
+ const groundAt: PropGroundQuery = (placement, at) => {
199
+ const [x, , z] = at;
200
+ let visual = groundSample(x, z);
201
+ if (visual === null) {
202
+ visual =
203
+ ctx.raycast({
204
+ direction: new Vector3(0, -1, 0),
205
+ origin: new Vector3(x, top + 2, z),
206
+ targets: [mesh],
207
+ })?.point.y ?? null;
208
+ }
209
+ const physical = ctx.physics.directSpaceState.intersectRay({
210
+ collisionMask: 8,
211
+ from: { x, y: rayTop, z },
212
+ to: { x, y: -100, z },
213
+ });
214
+ let height = visual ?? physical?.position.y ?? collarGround.at(x, z) ?? null;
215
+ if (
216
+ height !== null &&
217
+ look.stoneSinkShare !== null &&
218
+ ["boulder", "riverrock", "scree", "mountain", "volcanic", "reveal"].includes(
219
+ placement.asset,
220
+ )
221
+ ) {
222
+ const stone = propParts
223
+ .get(`${placement.asset}:${variantFor(placement, placement.asset)}`)
224
+ ?.find((part) => part.role === "stone")?.geometry;
225
+ stone?.computeBoundingBox();
226
+ const box = stone?.boundingBox;
227
+ if (box) {
228
+ // GroundSnap's single lowest point left the downhill footprint hanging on thin stones.
229
+ const reach =
230
+ Math.max(box.max.x - box.min.x, box.max.z - box.min.z) * placement.scale * 0.5;
231
+ for (const [dx, dz] of [
232
+ [-reach, 0],
233
+ [reach, 0],
234
+ [0, -reach],
235
+ [0, reach],
236
+ ]) {
237
+ const footX = x + (dx ?? 0);
238
+ const footZ = z + (dz ?? 0);
239
+ const foot =
240
+ groundSample(footX, footZ) ??
241
+ ctx.raycast({
242
+ direction: new Vector3(0, -1, 0),
243
+ origin: new Vector3(footX, top + 2, footZ),
244
+ targets: [mesh],
245
+ })?.point.y ??
246
+ null;
247
+ if (foot !== null) height = Math.min(height, foot);
248
+ }
249
+ height -= (box.max.y - box.min.y) * placement.scale * look.stoneSinkShare;
250
+ }
251
+ }
252
+ const [originX, originY, originZ] = placement.position;
253
+ // Past the square there is no Heightfield: an authored y there is its own offset.
254
+ const resident = Math.abs(originX) <= data.size / 2 && Math.abs(originZ) <= data.size / 2;
255
+ return {
256
+ height,
257
+ offset: resident ? originY - field.heightAt(originX, originZ) : originY,
258
+ };
259
+ };
260
+ // The prepared art is asked for here rather than in `enter`, and the variants it fills are not
261
+ // built again: a game with the licensed Landscape Pro models has the pack's own pines, shrubs and
262
+ // photoscanned stone, a game without them has the procedural spruce, the procedural boulder and
263
+ // the starter's own clumps, and neither waits on the other. Both loaders run together and fail
264
+ // soft per file, so one missing species costs that species and nothing else. One load, because
265
+ // `afterPhysics` runs every frame.
266
+ buildProps = async (): Promise<void> => {
267
+ // The capsule mesh named "player" (the body has no transform), looked up once, else the eye.
268
+ let actor: Object3D | undefined;
269
+ const followed = (): Vector3 => {
270
+ actor ??= ctx.scene.getObjectByName("player");
271
+ return actor?.position ?? ctx.camera.position;
272
+ };
273
+ buildStartedAt = performance.now();
274
+ propsStage = "assets";
275
+ const [prepared, pack, skyLight] = await Promise.all([
276
+ loadPreparedProps(assets),
277
+ loadPack(assets, world, data, ctx.state.getState().canopyComparison, biome, scatter.canopy),
278
+ loadSkyLight(assets),
279
+ ]);
280
+ preparedDispose = () => {
281
+ prepared.dispose();
282
+ pack.dispose();
283
+ };
284
+ if (released()) {
285
+ preparedDispose();
286
+ return;
287
+ }
288
+ preparedLodBaseSpread = prepared.lodBaseSpread;
289
+ preparedLevelsWithoutSolid = prepared.levelsWithoutSolid;
290
+ const parts = new Map([...prepared.parts, ...pack.parts]);
291
+ // A look whose stones use both scans fills the otherwise primitive slot with the second.
292
+ const dryStone = prepared.parts.get("boulder:1");
293
+ if (look.stoneScans > 1 && dryStone && !pack.parts.has("boulder:0"))
294
+ parts.set("boulder:0", dryStone);
295
+ propParts = buildPropVariants(parts, fallbackSaplingHeight);
296
+ propsStage = "surfaces";
297
+ const built = await createPropSurfaces(assets, data, biome, skyLight);
298
+ surfaces = built;
299
+ surfacesDispose = built.dispose;
300
+ if (released()) {
301
+ built.dispose();
302
+ return;
303
+ }
304
+ propsStage = "textures";
305
+ let preparedTextures = 0;
306
+ await preparePropTextures(
307
+ ctx.renderer,
308
+ [
309
+ ...[...propParts.values()].flatMap((parts) =>
310
+ parts.flatMap((part) => (part.material ? [part.material] : [])),
311
+ ),
312
+ ...Object.values(built.materials),
313
+ ],
314
+ textureUploads.signal,
315
+ (completed) => {
316
+ completedPropsWork += completed - preparedTextures;
317
+ preparedTextures = completed;
318
+ },
319
+ (completed) => {
320
+ compressedTexturesPrepared = completed;
321
+ },
322
+ );
323
+ if (released()) return;
324
+ propsStage = "streaming";
325
+ // A fixed view standing on the surroundings gets the meadow the bake cannot place there.
326
+ const vista = OPEN_MEADOW ? posesFor(world, data.size).vista : undefined;
327
+ // Spruce across the valley past the square; `?farForest=on` plants them.
328
+ const vistaEye = posesFor(world, data.size).vista?.at;
329
+ const far =
330
+ FAR_FOREST_WORLDS.includes(world) && FAR_FOREST && ridges instanceof Mesh
331
+ ? farForestPlacements({
332
+ size: data.size,
333
+ resolution: data.resolution,
334
+ collar,
335
+ world,
336
+ treeline: biome.heightBands.treeline,
337
+ rivers: data.rivers,
338
+ lakes: data.lakes,
339
+ clear: vistaEye ? [[vistaEye[0], vistaEye[1], 55]] : [],
340
+ seaLevel: data.waterLevel,
341
+ })
342
+ : [];
343
+ farForestCount = far.length;
344
+ props = await streamProps({
345
+ // The bake's containers, and only the view cover the game plants at load: the meadow the
346
+ // camera stands in and the collar past the square, both compiled through the package.
347
+ package: scatter.package,
348
+ placements: [
349
+ ...(vista
350
+ ? meadowCover(
351
+ { x: vista.at[0], z: vista.at[1] },
352
+ { x: vista.look[0], z: vista.look[1] },
353
+ data.size / 2,
354
+ HORIZON_WALK_BAND - 12,
355
+ ).filter(({ position: [x, , z] }) => {
356
+ // A cooked coast's sea covers the ground past the square: no meadow under it.
357
+ if (data.waterLevel === null) return true;
358
+ const ground = groundSample(x, z) ?? collarGround.at(x, z);
359
+ return ground === null || ground > data.waterLevel + 0.35;
360
+ })
361
+ : []),
362
+ ...far,
363
+ // The talus under the buttes and the stones and dead wood on the flats.
364
+ ...desertDebris(data),
365
+ ],
366
+ groundAt,
367
+ parts: propParts,
368
+ materials: built.materials,
369
+ assets,
370
+ // The player, not the orbiting eye: turning the camera in place must not swap tree LODs.
371
+ // A fixed view streams around its own eye, as UE grass follows the rendered view
372
+ // (UE 5.8.3: Engine/Source/Runtime/Landscape/Private/LandscapeSubsystem.cpp:641);
373
+ // `?meadow=off` keeps the player.
374
+ follow: {
375
+ get position() {
376
+ return OPEN_MEADOW && ctx.state.getState().view !== "player"
377
+ ? ctx.camera.position
378
+ : followed();
379
+ },
380
+ },
381
+ size: data.size,
382
+ standShade: look.standShade,
383
+ shadowReach: SHADOW_REACH,
384
+ horizonDistance:
385
+ ctx.camera instanceof PerspectiveCamera || ctx.camera instanceof OrthographicCamera
386
+ ? ctx.camera.far
387
+ : 5000,
388
+ whileCurrent: () => !released(),
389
+ onProgress: (progress) => {
390
+ const progressedAt = performance.now();
391
+ const previousPreparation = preparation;
392
+ if (
393
+ previousPreparation === undefined ||
394
+ previousPreparation.phase !== progress.phase ||
395
+ previousPreparation.bucket !== progress.bucket
396
+ )
397
+ phaseStartedAt = progressedAt;
398
+ lastProgressAt = progressedAt;
399
+ const previous =
400
+ preparation?.phase === progress.phase && preparation.bucket === progress.bucket
401
+ ? preparation.added
402
+ : 0;
403
+ completedPropsWork += Math.max(0, progress.added - previous);
404
+ preparation = progress;
405
+ },
406
+ onPublication: (bounds) => reveal.publishedBatch(bounds),
407
+ invalidateShadows: (region) => invalidateShadows(region),
408
+ });
409
+ if (!props) return;
410
+ const streamed = props;
411
+ if (released()) {
412
+ streamed.dispose();
413
+ return;
414
+ }
415
+ // ctx.add registers render-cadence processing. Never manually update these worlds.
416
+ for (const stream of streamed.worlds) ctx.add(stream);
417
+ // Rocks and trunks are solid: the stone or bark part each placement is grounded by, with a body
418
+ // near the player. Leaves, needles, grass and flowers have no such part and stay open.
419
+ // Layer 16 holds prop bodies alone, for the overlap measure.
420
+ propColliders = new ScatterColliders({
421
+ physics: ctx.physics,
422
+ follow: {
423
+ get position() {
424
+ return followed();
425
+ },
426
+ },
427
+ collisionLayer: 4 | 16,
428
+ instances: [...streamed.byId.values()].flatMap(({ placement, pose }) => {
429
+ const solid = propParts
430
+ .get(`${placement.asset}:${variantFor(placement, placement.asset)}`)
431
+ ?.find((part) => part.role === "bark" || part.role === "stone");
432
+ return solid ? [{ geometry: solid.geometry, matrix: pose }] : [];
433
+ }),
434
+ });
435
+ // Prewarm borrows actual world draws only after registration. Grounding and package preparation
436
+ // have no attached stream to prewarm and keep the opaque curtain's draw gate.
437
+ ctx.canvasLayer.keepWorldRendering = true;
438
+ propsStage = "attached";
439
+ // Armed once, after the streams attach: the fixed spawn data join plus each draw join, bounded
440
+ // by the deadline taken at scene entry. `WorldCells.whenSpawnReady` owns the data authority and
441
+ // each streamed world's `prewarmed` owns the draw.
442
+ const remaining = deadlineAt - performance.now();
443
+ if (remaining <= 0) {
444
+ failSpawn("Strata spawn admission exceeded 120000 ms");
445
+ } else {
446
+ const joins = streamed.worlds.map((stream) => {
447
+ const status = { data: "pending", prewarm: "pending" };
448
+ spawnJoins.set(stream, status);
449
+ const ready = stream.whenSpawnReady(spawn, 60, remaining);
450
+ // Observe settlement without replacing the promises the spawn join awaits.
451
+ void ready.then(
452
+ () => {
453
+ status.data = "resolved";
454
+ },
455
+ () => {
456
+ status.data = "rejected";
457
+ },
458
+ );
459
+ void stream.prewarmed.then(
460
+ () => {
461
+ status.prewarm = "resolved";
462
+ },
463
+ () => {
464
+ status.prewarm = "rejected";
465
+ },
466
+ );
467
+ return { ready, stream };
468
+ });
469
+ // Every streamed world joins its draw gate: the engine settles it for a world that holds no
470
+ // cell here and so has nothing to prewarm, which is the meadow a fixed view plants streams
471
+ // in when the view reaches it.
472
+ void Promise.all([
473
+ Promise.all(joins.map((join) => join.ready)),
474
+ ...joins.map((join) => join.stream.prewarmed),
475
+ groundReady,
476
+ ]).then(
477
+ ([regions]) => {
478
+ land({
479
+ loadedCells: regions.reduce((sum, region) => sum + region.loadedCells, 0),
480
+ requiredCells: regions.reduce((sum, region) => sum + region.requiredCells, 0),
481
+ });
482
+ },
483
+ (reason) => failSpawn(reason),
484
+ );
485
+ }
486
+
487
+ ctx.entities.add("props", {
488
+ object: streamed.worlds[0],
489
+ debug: () => ({
490
+ reveal: reveal.readout(),
491
+ streaming: props?.stats(),
492
+ colliders: propColliders?.stats(),
493
+ boulders: scatter.counts.boulder,
494
+ bushes: scatter.counts.bush,
495
+ ferns: scatter.counts.fern,
496
+ draws: props?.meshes.length ?? 0,
497
+ grass: scatter.counts.grass,
498
+ poppies: scatter.counts.poppy,
499
+ saplings: scatter.counts.sapling,
500
+ scrub: scatter.counts.scrub,
501
+ spruces: scatter.counts.spruce,
502
+ totalInstances: props?.meshes.reduce((sum, draw) => sum + draw.count, 0) ?? 0,
503
+ triangles:
504
+ props?.meshes.reduce(
505
+ (sum, draw) => sum + (draw.count * (draw.geometry.index?.count ?? 0)) / 3,
506
+ 0,
507
+ ) ?? 0,
508
+ }),
509
+ });
510
+ };
511
+ }
512
+
513
+ return {
514
+ /** The build starts once, from the first physics step, and returns its own work. */
515
+ start: (): Promise<void> | undefined => {
516
+ if (buildProps === undefined || props !== undefined || building) return undefined;
517
+ building = true;
518
+ return buildProps();
519
+ },
520
+ advance: (elapsed: number): void => {
521
+ surfaces?.advance(elapsed);
522
+ },
523
+ progress: () =>
524
+ completedPropsWork +
525
+ (preparation?.prewarmedWorlds ?? 0) +
526
+ (props?.worlds.reduce((sum, stream) => {
527
+ const stats = stream.stats();
528
+ return sum + stats.admissionCompletedUnits + stats.prewarmMinted;
529
+ }, 0) ?? 0),
530
+ get colliders(): ScatterColliders | undefined {
531
+ return propColliders;
532
+ },
533
+ get compressedTexturesPrepared(): number {
534
+ return compressedTexturesPrepared;
535
+ },
536
+ get farForest(): number {
537
+ return farForestCount;
538
+ },
539
+ joins: spawnJoins,
540
+ get preparedLevelsWithoutSolid(): number {
541
+ return preparedLevelsWithoutSolid;
542
+ },
543
+ get preparedLodBaseSpread(): number {
544
+ return preparedLodBaseSpread;
545
+ },
546
+ get props(): StreamedProps | undefined {
547
+ return props;
548
+ },
549
+ get witness(): ISpawnWitness {
550
+ return {
551
+ added: preparation?.added ?? null,
552
+ bucket: preparation?.bucket ?? null,
553
+ buildStartedAt,
554
+ lastProgressAt,
555
+ phase: preparation?.phase,
556
+ phaseStartedAt,
557
+ stage: propsStage,
558
+ total: preparation?.total ?? null,
559
+ };
560
+ },
561
+ };
562
+ }
@@ -0,0 +1,33 @@
1
+ import type { ICtx } from "@threenative/core";
2
+ import type { IPhysicsContext } from "@threenative/physics";
3
+ import { createDiagnosticsState } from "@threenative/terrain/starter";
4
+ import type { ICanopyComparison } from "./render/props/pack.js";
5
+ import { WORLD } from "./render/worldNames.js";
6
+
7
+ /**
8
+ * The state this game reports through: every measurement the package's diagnostics own, plus the
9
+ * values that are a look decision rather than a measurement.
10
+ *
11
+ * It lives here rather than in `game.ts` because the scene's collaborators — the spawn gate, the
12
+ * meadow build, the player rig — read and write the same store, and importing the state shape from
13
+ * the scene that composes them would close a cycle.
14
+ */
15
+ export const initialState = {
16
+ ...createDiagnosticsState(WORLD),
17
+ canopyComparison: { normals: "authored", specular: "disabled" } as ICanopyComparison,
18
+ showcase: false,
19
+ /** "off" when the `?stream=off` override is in use, so a run reports the arm it ran. */
20
+ streamOverride: "" as "" | "off",
21
+ /** PRD-790 streamed ground (on by default): resident tiles, and the half-width of the square they draw. */
22
+ streamTiles: 0,
23
+ streamCoveredHalf: 0,
24
+ /** Largest tile-edge height gap; -1 until `?tnTerrainValidate=1` measures it. */
25
+ streamSeamGap: -1,
26
+ /** Largest height step at a tile vertex where the tiles meet the collar; -1 until measured. */
27
+ streamCollarGap: -1,
28
+ /** Largest step between those vertices, where a fold of the collar's triangles crosses a tile edge. */
29
+ streamCollarFold: -1,
30
+ };
31
+
32
+ export type TerrainState = typeof initialState;
33
+ export type TerrainCtx = ICtx<TerrainState, IPhysicsContext>;