@threenative/terrain 0.1.11 → 0.1.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 (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,715 @@
1
+ import {
2
+ Scene,
3
+ VirtualShadowNode,
4
+ addInSlices,
5
+ type defineGame,
6
+ markStatic,
7
+ } from "@threenative/core";
8
+ import { Heightfield, warmUnculled } from "@threenative/core/world";
9
+ import { CollisionShape3D, type IPhysicsContext, RigidBody3D } from "@threenative/physics";
10
+ import { addStreamedGround, createSpawnGate } from "@threenative/terrain/starter";
11
+ import {
12
+ beginScene,
13
+ createMeasure,
14
+ createRevealProbe,
15
+ enterView,
16
+ launchedAt,
17
+ leaveScene,
18
+ observeFrame,
19
+ observeWindow,
20
+ publish,
21
+ } from "@threenative/terrain/starter";
22
+ import {
23
+ type AnimationClip,
24
+ Mesh,
25
+ MeshStandardMaterial,
26
+ type PerspectiveCamera,
27
+ Vector2,
28
+ Vector3,
29
+ } from "three";
30
+ import { uniform } from "three/tsl";
31
+ import type { MeshStandardNodeMaterial } from "three/webgpu";
32
+ import { type IMannequin, type IPlayerRig, createPlayerRig } from "./playerRig.js";
33
+ import { BENCHMARK, type ViewName, posesFor } from "./render/benchmark.js";
34
+ import { biomeSpec } from "./render/biomeData.js";
35
+ import { BIOMES, type IWorldBiome, measureBiome } from "./render/biomes.js";
36
+ import {
37
+ COLLAR_CURVE,
38
+ HORIZON_REACH,
39
+ createWorldHeight,
40
+ loadHorizonSurroundings,
41
+ } from "./render/ground/horizon.js";
42
+ import { type IBakedWorld, type ITerrainStream, createTerrain } from "./render/ground/terrain.js";
43
+ import { alpineAssets } from "./render/kitAssets.js";
44
+ import { createLoadingScreen } from "./render/loading.js";
45
+ import { loadCanopy, loadPropPackage, loadSky, propCounts } from "./render/props/propWorld.js";
46
+ import { invalidatePropShadows } from "./render/props/propWorld.js";
47
+ import { buildPropVariants } from "./render/props/props.js";
48
+ import { type IOutdoorSky, createOutdoorSky, installOutdoorOcclusion } from "./render/sky/sky.js";
49
+ import { type IRiverWater, WATER_LAYER, createLakes, createRivers } from "./render/water/river.js";
50
+ import { WORLD } from "./render/worldNames.js";
51
+ import { type IMeadow, type Scatter, type Variants, createMeadow } from "./sceneProps.js";
52
+ import { type TerrainCtx, type TerrainState, initialState } from "./sceneState.js";
53
+ import { walkBandSlices } from "./world/walkBand.js";
54
+ import { waterCurrentAt, waterSurfaceAt } from "./world/water.js";
55
+ import { loadBakedWorld } from "./worlds.js";
56
+
57
+ /**
58
+ * The mannequin's two swim clips (Universal Animation Library 1, CC0), copied by the bake. They are
59
+ * authored with the root on the waterline, so a swimming figure's root rides the water surface.
60
+ */
61
+ const SWIM_CLIPS = "mannequin-swim.glb";
62
+ /** The player's model, from the game's own asset root (the scaffold ships it). */
63
+ const MANNEQUIN = "mannequin.glb";
64
+
65
+ const world = WORLD;
66
+ // What the game resolves this world from: its rules, and the look it is graded under.
67
+ const spec = biomeSpec(world);
68
+ const look = BIOMES[world];
69
+
70
+ /**
71
+ * The forest: terrain, streamed ground, sky, water, props, the player and its follow camera, and the
72
+ * fixed benchmark views (`V`). Register it as a scene and spread {@link ALPINE_GAME} into `defineGame`.
73
+ */
74
+ export class AlpineScene extends Scene<TerrainState, IPhysicsContext> {
75
+ static override readonly initialState = initialState;
76
+ #data: IBakedWorld | undefined;
77
+ #biome: IWorldBiome | undefined;
78
+ #erosionSamples = { flow: 0, deposition: 0 };
79
+ #scatter: Scatter | undefined;
80
+ #terrain: ReturnType<typeof createTerrain> | undefined;
81
+ #fallbackParts: Variants | undefined;
82
+ /** Bumped when a scene is left, so a band build still slicing stops instead of joining the next scene. */
83
+ #bandLoad = 0;
84
+ /** PRD-790: the streamed ground past the square. */
85
+ #stream: { split: ITerrainStream; material: Promise<MeshStandardNodeMaterial> } | undefined;
86
+ #mannequin: IMannequin | undefined;
87
+ #swimClips: readonly AnimationClip[] = [];
88
+ #rig: IPlayerRig | undefined;
89
+ #meadow: IMeadow | undefined;
90
+ #assets: ReturnType<typeof alpineAssets> | undefined;
91
+ override async load(ctx: TerrainCtx): Promise<void> {
92
+ const assets = alpineAssets(ctx.assets);
93
+ this.#assets = assets;
94
+ const [baked, mannequin, swim] = await Promise.all([
95
+ loadBakedWorld(assets),
96
+ ctx.assets.model<IMannequin>(MANNEQUIN),
97
+ assets.model<IMannequin>(SWIM_CLIPS),
98
+ ]);
99
+ this.#data = baked;
100
+ this.#mannequin = mannequin;
101
+ this.#swimClips = swim.animations;
102
+ this.#biome = measureBiome(look, this.#data.heights);
103
+ const horizon = loadHorizonSurroundings(assets);
104
+ const [packageData, canopy, sky] = await Promise.all([
105
+ loadPropPackage(assets, world),
106
+ loadCanopy(assets, world),
107
+ loadSky(assets, world),
108
+ ]);
109
+ this.#scatter = { package: packageData, canopy, counts: propCounts(packageData) };
110
+ await horizon;
111
+ // Prepare scenery while the scene loads; enter only attaches it.
112
+ // PRD-790: the ground streams past the playable square.
113
+ let tileSurface: (material: MeshStandardNodeMaterial) => void = () => undefined;
114
+ const material = new Promise<MeshStandardNodeMaterial>((resolve) => {
115
+ tileSurface = resolve;
116
+ });
117
+ const split: ITerrainStream = {
118
+ centre: uniform(new Vector2()),
119
+ half: uniform(0),
120
+ tiles: (surface) => tileSurface(surface),
121
+ };
122
+ this.#stream = { split, material };
123
+ this.#terrain = createTerrain(this.#data, assets, this.#biome, sky, split);
124
+ this.#sky = createOutdoorSky(ctx.camera, this.#biome, ctx.renderer);
125
+ // The sky's LUT dispatch builds its compute nodes: 13-16 ms, paid here behind the curtain so
126
+ // `enter`'s own `ctx.add` finds the renderer already attached (PRD-585, `enterMs` <= 50).
127
+ this.#sky.atmosphere.attachRenderer(ctx.renderer);
128
+ this.#lake = createLakes(this.#data.lakes ?? [], this.#terrain.field);
129
+ // A braided river network is 15-18 ms of geometry: built with the lake, attached in `enter`.
130
+ this.#river = createRivers(
131
+ this.#data.rivers ?? [],
132
+ this.#terrain.field,
133
+ look.riverMirrorsPonds ? this.#lake?.reflectionAt : undefined,
134
+ );
135
+ this.#erosionSamples = {
136
+ flow: this.#data.erosion?.flow.filter((value) => value > 0).length ?? 0,
137
+ deposition: this.#data.erosion?.deposition.filter((value) => value > 0).length ?? 0,
138
+ };
139
+ this.#fallbackParts = buildPropVariants(undefined, look.saplingHeight ?? undefined);
140
+ }
141
+ #elapsed = 0;
142
+ #sky: IOutdoorSky | undefined;
143
+ #river: IRiverWater | undefined;
144
+ #lake: IRiverWater | undefined;
145
+
146
+ override exit(ctx: TerrainCtx): void {
147
+ leaveScene();
148
+ ctx.state.set({ currentViewWindows: 0 });
149
+ this.#bandLoad++;
150
+ }
151
+
152
+ override enter(ctx: TerrainCtx): void {
153
+ const enterStart = performance.now();
154
+ const assets = this.#assets;
155
+ if (!assets) throw new Error(`World ${world} was not loaded`);
156
+ ctx.add(ctx.camera);
157
+ const data = this.#data;
158
+ if (!data) throw new Error(`World ${world} was not loaded`);
159
+ const sky = this.#sky;
160
+ if (!sky) throw new Error(`World ${world} sky was not loaded`);
161
+ // ctx.goto carries state; camera names from the outgoing biome must not carry with it.
162
+ ctx.state.set({
163
+ view: "player",
164
+ currentViewWindows: 0,
165
+ worldReady: false,
166
+ spawnReadiness: [],
167
+ loadingError: "",
168
+ spawnCellsRequired: 0,
169
+ spawnCellsLoaded: 0,
170
+ compressedTexturesPrepared: 0,
171
+ revealComplete: false,
172
+ });
173
+ let released = false;
174
+ let meadow: IMeadow | undefined;
175
+ const reveal = createRevealProbe({
176
+ camera: () => ctx.camera as PerspectiveCamera,
177
+ pipelineCensus: () => ctx.renderer.pipelineCensus?.(),
178
+ engineCompiles: () => {
179
+ const engine = (ctx.renderer.raw as { info?: { engine?: { compiles?: unknown } } }).info
180
+ ?.engine;
181
+ return typeof engine?.compiles === "number" ? engine.compiles : undefined;
182
+ },
183
+ covered: () => ctx.canvasLayer.opaque,
184
+ phase: () => ctx.startup.phase,
185
+ shadowNode: () => this.#sky?.sun.shadow.shadowNode,
186
+ pendingImpostors: () =>
187
+ meadow?.props?.worlds.reduce((sum, stream) => sum + stream.stats().impostor.pending, 0) ??
188
+ 0,
189
+ released: () => released,
190
+ afterPhysics: (callback) => ctx.afterPhysics(callback),
191
+ revealed: () => ctx.state.set({ revealComplete: true }),
192
+ });
193
+ // One scene-local spawn gate: a single deadline, settled once by the world readiness join, a
194
+ // failure or teardown. `@threenative/terrain/starter` owns it and reports the one line a failed spawn leaves.
195
+ const gate = createSpawnGate(ctx, {
196
+ world,
197
+ progress: () => (meadow?.progress() ?? 0) + ctx.state.getState().spawnCellsLoaded,
198
+ witness: () => meadow?.witness,
199
+ released: () => released,
200
+ });
201
+ gate.hold();
202
+ const loading = createLoadingScreen({
203
+ ...ctx,
204
+ onReveal: reveal.initialize,
205
+ keepWorldRendering: false,
206
+ startup: {
207
+ get progress() {
208
+ const state = ctx.state.getState();
209
+ const coverage =
210
+ state.spawnCellsRequired > 0 ? state.spawnCellsLoaded / state.spawnCellsRequired : 0;
211
+ return Math.min(0.99, (ctx.startup.progress + coverage) / 2);
212
+ },
213
+ whenReady: () => Promise.all([ctx.startup.whenReady(), gate.promise]).then(() => undefined),
214
+ },
215
+ });
216
+ ctx.afterPhysics(() => loading.update());
217
+ const biome = this.#biome;
218
+ if (!biome) throw new Error(`World ${world} elevations were not measured`);
219
+ const terrain = this.#terrain;
220
+ const field = terrain?.field;
221
+ if (!field) throw new Error(`World ${world} terrain was not loaded`);
222
+ const mesh = terrain?.mesh;
223
+ const collar = terrain?.collar;
224
+ if (mesh) {
225
+ // Every scene that draws a terrain mesh has a collar: `createTerrain` builds both.
226
+ if (!collar) throw new Error(`World ${world} has no horizon collar`);
227
+ ctx.add(mesh);
228
+ // Scenery: nothing moves the ground, so its transform is composed once instead of every frame.
229
+ markStatic(mesh);
230
+ const ground = new RigidBody3D({
231
+ object: mesh,
232
+ physics: ctx.physics,
233
+ type: "fixed",
234
+ entity: "terrain",
235
+ // 4: what the player walks on, props included. 8: the ground alone, for ground queries.
236
+ collisionLayer: 4 | 8,
237
+ shape: CollisionShape3D.heightfield(field.rows, field.columns, field.toColliderHeights(), {
238
+ x: data.size,
239
+ y: 1,
240
+ z: data.size,
241
+ }),
242
+ });
243
+ // The surveyed hills past the square are ground too, out to the walk band: their collider is
244
+ // the drawn triangles, so feet meet what the eye sees. Four fixed walls 2 m inside the band's
245
+ // outer edge are the level's blocking volumes; past them is only scenery.
246
+ const band = collar.walk;
247
+ const bandBodies: RigidBody3D[] = [];
248
+ // That band is 188 416 triangles, and the player spawns at least 256 m inside it, so no foot
249
+ // touches it in the frames it is missing: it is not built in `enter`. One fixed body per ring
250
+ // slice is built on this scene's own first frames instead, with the loading curtain held up
251
+ // until the last one exists. From a frame and not from `load()`: `deterministicRestart`
252
+ // replaces the simulation at the outgoing scene's exit, so a body built before that would be
253
+ // a body in a world that no longer exists.
254
+ const bandLoad = this.#bandLoad;
255
+ let bandStarted = false;
256
+ ctx.afterPhysics(() => {
257
+ if (bandStarted) return;
258
+ bandStarted = true;
259
+ const work = addInSlices(
260
+ walkBandSlices(band, collar.perimeter),
261
+ (slice) =>
262
+ bandBodies.push(
263
+ new RigidBody3D({
264
+ physics: ctx.physics,
265
+ type: "fixed",
266
+ entity: "terrain",
267
+ collisionLayer: 4 | 8,
268
+ position: { x: mesh.position.x, y: mesh.position.y, z: mesh.position.z },
269
+ shape: CollisionShape3D.trimesh(slice.vertices, slice.indices),
270
+ }),
271
+ ),
272
+ // One slice a frame, and not one slice more once this scene is left: a body must never
273
+ // land in the simulation that replaced this one.
274
+ { sliceSize: 1, while: () => bandLoad === this.#bandLoad },
275
+ );
276
+ if (ctx.startup.phase !== "ready") ctx.startup.hold("strata-collar", work);
277
+ void work.catch((error) => {
278
+ if (!released) gate.fail(error);
279
+ });
280
+ });
281
+ // Streamed ground reaches the collar's rim; without it the walk band is the level.
282
+ const edge = data.size / 2 + (this.#stream ? HORIZON_REACH - 40 : band.extent);
283
+ const walls = [-1, 1].flatMap((side) =>
284
+ [
285
+ { x: side * edge, z: 0, width: 4, depth: edge * 2 },
286
+ { x: 0, z: side * edge, width: edge * 2, depth: 4 },
287
+ ].map(
288
+ ({ x, z, width, depth }) =>
289
+ new RigidBody3D({
290
+ physics: ctx.physics,
291
+ type: "fixed",
292
+ collisionLayer: 4,
293
+ position: { x, y: 0, z },
294
+ shape: CollisionShape3D.box(width, 4000, depth),
295
+ }),
296
+ ),
297
+ );
298
+ ctx.entities.add("terrain", {
299
+ mesh,
300
+ dispose: () => {
301
+ for (const wall of walls) wall.dispose();
302
+ for (const body of bandBodies.splice(0)) body.dispose();
303
+ ground.dispose();
304
+ mesh.geometry.dispose();
305
+ (mesh.material as MeshStandardMaterial).dispose();
306
+ },
307
+ });
308
+ }
309
+ // One rig owns the whole of the sky, the sun, the shadows that follow the eye, the haze the
310
+ // far ridges fade into and the tone curve. It used to be a flat `Color` background, a
311
+ // hand-set `FogExp2`, a sun with a five metre shadow box that missed everything, and no tone
312
+ // mapping at all; the numbers behind all of that now live in `src/render/sky/sky.ts`.
313
+ ctx.add(sky.daylight);
314
+ ctx.add(sky.atmosphere);
315
+ ctx.add(sky.sun);
316
+ this.#sky = sky;
317
+ ctx.entities.add("sun", {
318
+ object: sky.sun,
319
+ debug: () => ({ x: sky.sunX }),
320
+ dispose: installOutdoorOcclusion(ctx, biome),
321
+ });
322
+
323
+ const mannequin = this.#mannequin;
324
+ if (!mannequin) throw new Error(`World ${world} mannequin was not loaded`);
325
+ // The capsule, the mannequin that rides it and the follow camera live in `src/playerRig.ts`:
326
+ // this scene wires them and hands the model and the swim clips over.
327
+ const rig = createPlayerRig(ctx, {
328
+ at: spec.spawn.at,
329
+ cameraOffset: spec.spawn.cameraOffset,
330
+ field,
331
+ focusShadows: (at) => this.#sky?.focusShadows(at),
332
+ horizon: () =>
333
+ mesh
334
+ ? {
335
+ seamGap: mesh.userData.horizonSeamGap,
336
+ samples: mesh.userData.horizonSeamSamples,
337
+ }
338
+ : { observed: false },
339
+ mannequin,
340
+ staged: false,
341
+ swimClips: this.#swimClips,
342
+ vista: look.vistaAim !== null,
343
+ world,
344
+ });
345
+ this.#rig = rig;
346
+ const player = rig.body;
347
+ const actor = rig.actor;
348
+ const stream = this.#stream;
349
+ // ponytail: a ground material that never loads leaves this pending, and the spawn deadline
350
+ // then fails the scene by name.
351
+ let groundReady: Promise<void> | undefined;
352
+ if (stream && mesh && collar) {
353
+ const streamLoad = this.#bandLoad;
354
+ groundReady = stream.material.then((surface) => {
355
+ if (streamLoad !== this.#bandLoad) return surface.dispose();
356
+ const ground = addStreamedGround({
357
+ ctx,
358
+ name: world,
359
+ size: data.size,
360
+ resolution: data.resolution,
361
+ height: createWorldHeight(data, world),
362
+ collar,
363
+ curve: COLLAR_CURVE,
364
+ reach: HORIZON_REACH,
365
+ stream: stream.split,
366
+ surface,
367
+ follow: actor,
368
+ report: (facts) => ctx.state.set(facts),
369
+ });
370
+ ctx.entities.add("streamed-ground", { tiles: ground.tiles, dispose: ground.dispose });
371
+ return ground.ready;
372
+ });
373
+ }
374
+
375
+ const fixture = new Heightfield({
376
+ rows: 17,
377
+ columns: 17,
378
+ width: 16,
379
+ depth: 16,
380
+ origin: { x: 0, z: 0 },
381
+ heights: Float32Array.from(
382
+ { length: 17 * 17 },
383
+ (_, i) => ((i % 17) * 13 + Math.floor(i / 17) * 7 + (i % 17) * Math.floor(i / 17) * 3) % 11,
384
+ ),
385
+ });
386
+ const probeMesh = new Mesh(fixture.toGeometry(), new MeshStandardMaterial({ color: 0xd3a168 }));
387
+ probeMesh.position.x = 600;
388
+ probeMesh.visible = false; // engine-override: the physics fixture must not render
389
+ ctx.add(probeMesh);
390
+ const probeBody = new RigidBody3D({
391
+ object: probeMesh,
392
+ physics: ctx.physics,
393
+ type: "fixed",
394
+ collisionLayer: 2,
395
+ shape: CollisionShape3D.heightfield(17, 17, fixture.toColliderHeights(), {
396
+ x: 16,
397
+ y: 1,
398
+ z: 16,
399
+ }),
400
+ });
401
+ ctx.entities.add("asymmetric-terrain", {
402
+ mesh: probeMesh,
403
+ dispose: () => {
404
+ probeBody.dispose();
405
+ probeMesh.geometry.dispose();
406
+ probeMesh.material.dispose();
407
+ },
408
+ });
409
+
410
+ // The water in the channels the bake carved. A world with no river gets nothing. Water draws on
411
+ // its own layer so the lake's mirror can leave it out; the eye sees both.
412
+ ctx.camera.layers.enable(WATER_LAYER);
413
+ const lake = this.#lake;
414
+ if (lake) {
415
+ // The lake's mirror renders only when the lake draws, and each surface it reflects builds
416
+ // its pipeline on that first mirror draw. So the lake draws unculled for two world draws
417
+ // behind the curtain and the spawn join waits for them (PRD-790). Re-culled before the
418
+ // holds release: the held startup compile copies the screen in the canvas format, which the
419
+ // lake's refraction refuses.
420
+ const warmed = warmUnculled(ctx, lake.mesh);
421
+ groundReady =
422
+ groundReady === undefined
423
+ ? warmed
424
+ : Promise.all([groundReady, warmed]).then(() => undefined);
425
+ const centre = lake.mesh.geometry.getAttribute("position");
426
+ const at = data.lakes?.[0]?.at;
427
+ let lakeFootprintError = 0;
428
+ // Every pond a bundled water body draws has a baked footprint of its own; a lake drawn alone
429
+ // draws one group, and the loop leaves the error at nought.
430
+ const geometry = lake.mesh.geometry;
431
+ for (const [index, group] of geometry.groups.entries()) {
432
+ const pond = data.lakes?.[index];
433
+ if (!pond) throw new Error("A drawn pond has no baked footprint");
434
+ for (let i = group.start; i < group.start + group.count; i++) {
435
+ const vertex = geometry.index?.getX(i) ?? i;
436
+ lakeFootprintError = Math.max(
437
+ lakeFootprintError,
438
+ Math.hypot(
439
+ centre.getX(vertex) - (pond.at[0] ?? 0),
440
+ centre.getZ(vertex) - (pond.at[1] ?? 0),
441
+ ) - pond.radius,
442
+ );
443
+ }
444
+ }
445
+ ctx.state.set({
446
+ lakeFootprintError,
447
+ lakeSurfaceCount: Math.max(1, lake.mesh.geometry.groups.length),
448
+ lakeTriangles: (lake.mesh.geometry.index?.count ?? 0) / 3,
449
+ lakePlacementError: Math.hypot(
450
+ centre.getX(0) - (at?.[0] ?? 0),
451
+ centre.getZ(0) - (at?.[1] ?? 0),
452
+ ),
453
+ });
454
+ ctx.add(lake.mesh);
455
+ ctx.entities.add("lake", { mesh: lake.mesh, dispose: () => lake.dispose() });
456
+ }
457
+ // --- the meadow's props -------------------------------------------------------------------
458
+ //
459
+ // The props build on the first physics step, not here: both ways of asking the world where the
460
+ // ground is need a stepped world. `src/sceneProps.ts` owns that build, the staged kit's arm and
461
+ // the spawn joins it reports.
462
+ const erosionFlowSamples = this.#erosionSamples.flow;
463
+ const erosionDepositSamples = this.#erosionSamples.deposition;
464
+ // Every fixed camera stands in a clearing: a trunk a metre from the lens is a green wall, not a
465
+ // framing, and the seed decides where trees land, so the eyes are kept open by rule.
466
+ const river = this.#river;
467
+ if (river) {
468
+ ctx.state.set({
469
+ riverSurfaceCount: river.mesh.geometry.groups.filter((group) => group.count > 0).length,
470
+ });
471
+ ctx.add(river.mesh);
472
+ ctx.entities.add("river", { mesh: river.mesh, dispose: () => river.dispose() });
473
+ }
474
+ // The player swims in the river and lake drawn above: the same splines, levels and reach.
475
+ {
476
+ const rivers = data.rivers ?? [];
477
+ const lakes = data.lakes ?? [];
478
+ player.water = waterSurfaceAt(rivers, lakes, field, undefined);
479
+ player.waterCurrent = waterCurrentAt(rivers, lakes, field, undefined);
480
+ }
481
+ this.#meadow = meadow = createMeadow({
482
+ assets,
483
+ biome,
484
+ collar,
485
+ ctx,
486
+ data,
487
+ fallbackParts: this.#fallbackParts,
488
+ field,
489
+ gate,
490
+ invalidateShadows: (region) => {
491
+ const shadows = sky.sun.shadow.shadowNode;
492
+ if (shadows instanceof VirtualShadowNode) invalidatePropShadows(shadows, region);
493
+ },
494
+ loading,
495
+ look,
496
+ mesh,
497
+ release: () => {
498
+ released = true;
499
+ },
500
+ released: () => released,
501
+ reveal,
502
+ scatter: this.#scatter,
503
+ spawn: rig.spawn,
504
+ groundReady,
505
+ world,
506
+ });
507
+
508
+ let frames = 0;
509
+ let readyTimePending = false;
510
+ beginScene(world);
511
+ const measure = createMeasure({
512
+ world,
513
+ physics: ctx.physics,
514
+ raycast: (options) => ctx.raycast(options),
515
+ actor,
516
+ player,
517
+ size: data.size,
518
+ mesh,
519
+ stage: undefined,
520
+ fixture,
521
+ probeMesh,
522
+ swimmingClip: () => rig.playsSwimClip(),
523
+ hasPropColliders: () => meadow?.colliders !== undefined,
524
+ eye: () => ctx.camera.position,
525
+ camera: () => ctx.camera as PerspectiveCamera,
526
+ ocean: undefined,
527
+ spawnReady: () => gate.ready,
528
+ terrainTargets: () => mesh,
529
+ view: () => ctx.state.getState().view,
530
+ });
531
+ ctx.afterPhysics(() => {
532
+ measure.step();
533
+ // The props are placed here rather than in `enter`: their ground query asks the stepped
534
+ // world where the surface is, and neither the ray tree nor the collider answers before the
535
+ // solver has run once.
536
+ meadow?.colliders?.update();
537
+ const work = meadow?.start();
538
+ if (work !== undefined) {
539
+ if (ctx.startup.phase !== "ready") ctx.startup.hold("strata-props", work);
540
+ void work.catch((error) => {
541
+ if (!released) gate.fail(error);
542
+ });
543
+ }
544
+ frames++;
545
+ // `props.meshes` walks every streamed world; three walks per fixed step were 8.3 s of a
546
+ // 15.6 s main-thread stall in a profiled session (PRD-541). Half a second is fresh enough.
547
+ if (frames % 30 === 1) {
548
+ const meshes = meadow?.props?.meshes ?? [];
549
+ measure.countProps(
550
+ meshes,
551
+ meadow?.props?.worlds.find((stream) => stream.name === "strata-props:far:false"),
552
+ );
553
+ }
554
+ const streaming = meadow?.props?.stats();
555
+ const spawnReadiness = [...(meadow?.joins ?? [])].map(([stream, status], index) => {
556
+ if (gate.ready)
557
+ return { name: stream.name, ...ctx.state.getState().spawnReadiness[index], ...status };
558
+ const stats = stream.stats();
559
+ return {
560
+ name: stream.name,
561
+ observedFrame: frames,
562
+ ...status,
563
+ ...stream.readinessAt(rig.spawn, 60),
564
+ admissionBacklog: stats.admission.backlog,
565
+ impostorPending: stats.impostor.pending,
566
+ };
567
+ });
568
+ const worldReady = gate.ready;
569
+ if (gate.error) ctx.state.set({ loadingError: gate.error });
570
+ if (worldReady && !released && !readyTimePending && ctx.state.getState().timeToReadyMs < 0) {
571
+ readyTimePending = true;
572
+ void ctx.startup.whenReady().then(() => {
573
+ if (!released) ctx.state.set({ timeToReadyMs: Date.now() - launchedAt });
574
+ });
575
+ }
576
+ publish(ctx, {
577
+ world,
578
+ groundBiome: mesh
579
+ ? ((mesh.material as MeshStandardMaterial).userData.biome ?? "baked")
580
+ : "baked",
581
+ elevation: biome.elevationRange,
582
+ snowBand: biome.snowBand,
583
+ worldReady,
584
+ spawnReadiness,
585
+ spawnCells: gate.cells,
586
+ streaming,
587
+ terrainTransportBound:
588
+ (mesh?.material as MeshStandardMaterial | undefined)?.userData.erosion === true &&
589
+ erosionFlowSamples > 1000 &&
590
+ erosionDepositSamples > 100,
591
+ erosion: { flow: erosionFlowSamples, deposition: erosionDepositSamples },
592
+ sunX: sky.sunX,
593
+ frames,
594
+ propColliders: meadow?.colliders?.stats().resident ?? 0,
595
+ ...measure.facts(),
596
+ farForest: meadow?.farForest ?? 0,
597
+ preparedLodBaseSpread: meadow?.preparedLodBaseSpread ?? 0,
598
+ compressedTexturesPrepared: meadow?.compressedTexturesPrepared ?? 0,
599
+ preparedLevelsWithoutSolid: meadow?.preparedLevelsWithoutSolid ?? 0,
600
+ });
601
+ });
602
+ // --- the fixed benchmark cameras ---------------------------------------------------------
603
+ //
604
+ // Three framings, all fixed in world metres: the one the player walks behind, the eye-height
605
+ // meadow view the rubric asks for, and the overview. They are data rather than a camera rig
606
+ // so a capture at seed 73 is the same picture on every machine.
607
+ // Distance detail, once the camera is placed for this frame: a prepared tree draws from its
608
+ // full geometry inside the near band and from the mid level beyond it, with a fifth of the
609
+ // band of slack so a camera on the boundary does not alternate the tree between two levels.
610
+ const poses = posesFor(world, data.size);
611
+ const at = (x: number, z: number, up: number): Vector3 =>
612
+ new Vector3(x, field.heightAt(x, z) + up, z);
613
+ ctx.beforeRender(() => {
614
+ observeFrame(ctx);
615
+ const view = ctx.state.getState().view;
616
+ rig.figure.root.visible = view === "player" && !ctx.state.getState().showcase;
617
+ if (view === "player") {
618
+ // Forest and tundra: the orbit camera framed the player after physics.
619
+ const aim = look.vistaAim;
620
+ if (!aim) return;
621
+ ctx.camera.position.copy(actor.position).add(new Vector3(...spec.spawn.cameraOffset));
622
+ const [aimX, aimZ] = aim.at;
623
+ // A look's aim stands on the player's own ground, or level with the water it looks over.
624
+ const aimY = aim.rise === null ? (data.waterLevel ?? 0) : actor.position.y + aim.rise;
625
+ ctx.camera.lookAt(actor.position.x + aimX, aimY, actor.position.z + aimZ);
626
+ return;
627
+ }
628
+ // A view this world has no framing for falls back to its overview rather than throwing:
629
+ // the cycle can only produce framings the world declares, and this is the last line of
630
+ // defence against a state that arrived from somewhere else.
631
+ const pose = poses[view] ?? poses.overview;
632
+ if (pose === undefined) throw new RangeError(`World '${world}' has no overview framing`);
633
+ ctx.camera.position.copy(
634
+ pose.eyeY === undefined
635
+ ? at(pose.at[0], pose.at[1], pose.eye)
636
+ : // Never under the drawn ground: a cooked world (`STRATA_WORLD`) has other hills there.
637
+ new Vector3(
638
+ pose.at[0],
639
+ Math.max(
640
+ pose.eyeY,
641
+ (collar?.heightAt(pose.at[0], pose.at[1]) ??
642
+ field.heightAt(pose.at[0], pose.at[1])) + 1.7,
643
+ ),
644
+ pose.at[1],
645
+ ),
646
+ );
647
+ ctx.camera.lookAt(
648
+ pose.lookY === undefined
649
+ ? at(pose.look[0], pose.look[1], pose.lookUp)
650
+ : new Vector3(pose.look[0], pose.lookY, pose.look[1]),
651
+ );
652
+ // After the camera is placed, not before: the band is a function of where the eye is, and
653
+ // the framing is what moved it.
654
+ });
655
+ ctx.state.set({ enterMs: performance.now() - enterStart });
656
+ }
657
+
658
+ override update(ctx: TerrainCtx, dt: number): void {
659
+ this.#elapsed += dt;
660
+ this.#meadow?.advance(this.#elapsed);
661
+ const playable = ctx.state.getState().worldReady && ctx.startup.phase === "ready";
662
+ if (playable && ctx.input.justPressed("view")) {
663
+ const cycle = BENCHMARK[world].views;
664
+ const current = cycle.indexOf(ctx.state.getState().view as ViewName);
665
+ const next = cycle[(current + 1) % cycle.length] ?? "player";
666
+ // Keyed by world as well as view: `meadow-close` frames a different hillside in each world,
667
+ // so folding them together would report one number for two different pictures.
668
+ const entered = enterView(world, next);
669
+ ctx.state.set({ view: next, currentViewWindows: entered.windows });
670
+ }
671
+ this.#river?.advance(this.#elapsed);
672
+ this.#lake?.advance(this.#elapsed);
673
+ if (playable && ctx.input.justPressed("light"))
674
+ this.#sky?.setSunX(this.#sky.sunX < 0 ? 180 : -180);
675
+ const player = this.#rig?.body;
676
+ if (!player) return;
677
+ const move = playable ? ctx.input.vector("move") : { x: 0, y: 0 };
678
+ // Camera-relative: up on the stick runs along the ground where the camera looks.
679
+ const yaw = this.#rig?.yaw() ?? 0;
680
+ const [forwardX, forwardZ] = [-Math.sin(yaw), -Math.cos(yaw)];
681
+ const pace = this.#rig?.pace(playable && ctx.input.pressed("sprint")) ?? 0;
682
+ player.velocity.x = (forwardX * move.y - forwardZ * move.x) * pace;
683
+ player.velocity.z = (forwardZ * move.y + forwardX * move.x) * pace;
684
+ if (playable && ctx.input.justPressed("jump") && player.grounded) player.velocity.y = 5;
685
+ player.moveAndSlide(dt);
686
+ this.#rig?.animate(dt);
687
+ }
688
+ }
689
+
690
+ /**
691
+ * The game options the forest needs: its input map, a camera that reaches the 5 km sky, and the
692
+ * frame-budget window its diagnostics read. Spread them into `defineGame` with the game's own
693
+ * plugins (`rapier()` at least), then register {@link AlpineScene}.
694
+ */
695
+ export const ALPINE_GAME = {
696
+ camera: { projection: "perspective", fov: 60, far: 5000 },
697
+ initialState,
698
+ input: {
699
+ move: {
700
+ down: ["ArrowDown", "KeyS"],
701
+ left: ["ArrowLeft", "KeyA"],
702
+ right: ["ArrowRight", "KeyD"],
703
+ up: ["ArrowUp", "KeyW"],
704
+ },
705
+ jump: { keys: ["Space"] },
706
+ sprint: { keys: ["ShiftLeft", "ShiftRight"] },
707
+ look: { pointerRelative: true },
708
+ view: { keys: ["KeyV"] },
709
+ light: { keys: ["KeyL"] },
710
+ },
711
+ // Windows close every ten presents; the scene reads each into state, which puts the measured
712
+ // draw count and frame cost into a run report.
713
+ frameBudget: { onWindow: observeWindow, reportEvery: 10 },
714
+ renderer: { preferWebGPU: true, resolutionScale: "auto" },
715
+ } satisfies Partial<Parameters<typeof defineGame<TerrainState, IPhysicsContext>>[0]>;