@threenative/terrain 0.1.9 → 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 (243) hide show
  1. package/README.md +40 -59
  2. package/THIRD_PARTY_NOTICES.md +2 -1
  3. package/dist/bake-DJ5cxg0C.d.ts +82 -0
  4. package/dist/editor/index.d.ts +4 -4
  5. package/dist/editor/index.js +130 -128
  6. package/dist/editor/server.d.ts +2 -2
  7. package/dist/editor/server.js +38 -35
  8. package/dist/editor/worker.d.ts +1 -1
  9. package/dist/editor/worker.js +101 -101
  10. package/dist/export.d.ts +1 -1
  11. package/dist/index.d.ts +156 -273
  12. package/dist/index.js +562 -378
  13. package/dist/kit-world.d.ts +107 -0
  14. package/dist/kit-world.js +5134 -0
  15. package/dist/kit.d.ts +21 -4
  16. package/dist/kit.js +337 -223
  17. package/dist/mcp/cook-child.js +1963 -1543
  18. package/dist/mcp/server.js +716 -429
  19. package/dist/prop-package-Dwz0EWoB.d.ts +141 -0
  20. package/dist/{server-B5RdvEAC.d.ts → server-LnFwY8sr.d.ts} +1 -1
  21. package/dist/starter.d.ts +1142 -7
  22. package/dist/starter.js +2102 -120
  23. package/dist/{terrain-CAEaW0mQ.d.ts → terrain-DYCyAOCJ.d.ts} +1 -1
  24. package/dist/three.d.ts +1 -1
  25. package/dist/three.js +1 -1
  26. package/dist/{types-BpH00qsx.d.ts → types-kpI0C4hW.d.ts} +1 -1
  27. package/dist/{world-package-B8QgHjAQ.d.ts → world-package-DqJC3-Nn.d.ts} +2 -2
  28. package/docs/authoring/editor.md +73 -0
  29. package/docs/authoring/new-environment.md +97 -0
  30. package/docs/authoring/recipes.md +97 -0
  31. package/docs/authoring/world-export.md +66 -0
  32. package/package.json +24 -8
  33. package/starter/alpine/README.md +22 -12
  34. package/starter/alpine/bake.mjs +14 -1
  35. package/starter/alpine/biome.data.json +187 -25
  36. package/starter/alpine/heightmap.r16 +0 -0
  37. package/starter/alpine/playerRig.ts +89 -0
  38. package/starter/alpine/recipe.json +169 -15
  39. package/starter/alpine/render/bakedFile.ts +17 -0
  40. package/starter/alpine/render/benchmark.ts +77 -0
  41. package/starter/alpine/render/biomeData.ts +14 -0
  42. package/starter/alpine/render/biomes.ts +687 -0
  43. package/starter/alpine/render/ground/cover.ts +565 -0
  44. package/starter/alpine/render/ground/horizon.ts +219 -0
  45. package/starter/alpine/render/ground/palette.d.ts +1 -0
  46. package/starter/alpine/render/ground/palette.js +11 -0
  47. package/starter/alpine/render/ground/scatter.ts +104 -0
  48. package/starter/alpine/render/ground/terrain.ts +1860 -0
  49. package/starter/alpine/render/kitAssets.ts +28 -0
  50. package/starter/alpine/render/loading.ts +354 -0
  51. package/starter/alpine/render/lookKnobs.ts +37 -0
  52. package/starter/alpine/render/orbitCamera.ts +155 -0
  53. package/starter/alpine/render/props/farForest.ts +94 -0
  54. package/starter/alpine/render/props/pack.ts +1114 -0
  55. package/starter/alpine/render/props/prepared.ts +225 -0
  56. package/starter/alpine/render/props/propMaterials.ts +1239 -0
  57. package/starter/alpine/render/props/propProgress.ts +2 -0
  58. package/starter/alpine/render/props/propWorld.ts +105 -0
  59. package/starter/alpine/render/props/props.ts +633 -0
  60. package/starter/alpine/render/props/spruce.ts +440 -0
  61. package/starter/alpine/render/sky/atmosphere.ts +329 -0
  62. package/starter/alpine/render/sky/sky.ts +382 -0
  63. package/starter/alpine/render/texturePreparation.ts +135 -0
  64. package/starter/alpine/render/water/river.ts +1132 -0
  65. package/starter/alpine/render/worldNames.ts +6 -0
  66. package/starter/alpine/scene.ts +715 -0
  67. package/starter/alpine/sceneProps.ts +561 -0
  68. package/starter/alpine/sceneState.ts +33 -0
  69. package/starter/alpine/world/terrainAssets.ts +145 -0
  70. package/starter/alpine/world/walkBand.ts +47 -0
  71. package/starter/alpine/world/water.ts +74 -0
  72. package/starter/alpine/worlds.ts +13 -0
  73. package/starter/arbor/wind.ts +84 -0
  74. package/starter/coastal/README.md +26 -25
  75. package/starter/coastal/assets.json +10 -0
  76. package/starter/coastal/bake.mjs +14 -1
  77. package/starter/coastal/biome.data.json +18 -3
  78. package/starter/coastal/playerRig.ts +89 -0
  79. package/starter/coastal/recipe.json +220 -18
  80. package/starter/coastal/render/bakedFile.ts +17 -0
  81. package/starter/coastal/render/benchmark.ts +81 -0
  82. package/starter/coastal/render/biomeData.ts +14 -0
  83. package/starter/coastal/render/biomes.ts +678 -0
  84. package/starter/coastal/render/ground/cover.ts +565 -0
  85. package/starter/coastal/render/ground/horizon.ts +219 -0
  86. package/starter/coastal/render/ground/palette.d.ts +1 -0
  87. package/starter/coastal/render/ground/palette.js +11 -0
  88. package/starter/coastal/render/ground/scatter.ts +104 -0
  89. package/starter/coastal/render/ground/terrain.ts +1829 -0
  90. package/starter/coastal/render/kitAssets.ts +28 -0
  91. package/starter/coastal/render/loading.ts +354 -0
  92. package/starter/coastal/render/lookKnobs.ts +37 -0
  93. package/starter/coastal/render/orbitCamera.ts +155 -0
  94. package/starter/coastal/render/props/farForest.ts +94 -0
  95. package/starter/coastal/render/props/pack.ts +1109 -0
  96. package/starter/coastal/render/props/prepared.ts +225 -0
  97. package/starter/coastal/render/props/propMaterials.ts +1239 -0
  98. package/starter/coastal/render/props/propProgress.ts +2 -0
  99. package/starter/coastal/render/props/propWorld.ts +105 -0
  100. package/starter/coastal/render/props/props.ts +633 -0
  101. package/starter/coastal/render/props/spruce.ts +440 -0
  102. package/starter/coastal/render/sky/atmosphere.ts +329 -0
  103. package/starter/coastal/render/sky/sky.ts +382 -0
  104. package/starter/coastal/render/texturePreparation.ts +135 -0
  105. package/starter/coastal/render/water/ocean.ts +284 -0
  106. package/starter/coastal/render/water/river.ts +1132 -0
  107. package/starter/coastal/render/worldNames.ts +6 -0
  108. package/starter/coastal/scene.ts +740 -0
  109. package/starter/coastal/sceneProps.ts +559 -0
  110. package/starter/coastal/sceneState.ts +33 -0
  111. package/starter/coastal/world/terrainAssets.ts +151 -0
  112. package/starter/coastal/world/walkBand.ts +47 -0
  113. package/starter/coastal/world/water.ts +74 -0
  114. package/starter/coastal/worlds.ts +13 -0
  115. package/starter/desert/README.md +51 -23
  116. package/starter/desert/bake-flora.mjs +142 -0
  117. package/starter/desert/bake-rocks.mjs +291 -0
  118. package/starter/desert/bake.mjs +14 -1
  119. package/starter/desert/biome.data.json +24 -12
  120. package/starter/desert/playerRig.ts +89 -0
  121. package/starter/desert/recipe.json +63 -16
  122. package/starter/desert/render/bakedFile.ts +17 -0
  123. package/starter/desert/render/benchmark.ts +79 -0
  124. package/starter/desert/render/biomeData.ts +14 -0
  125. package/starter/desert/render/biomes.ts +660 -0
  126. package/starter/desert/render/ground/cover.ts +565 -0
  127. package/starter/desert/render/ground/debris.ts +136 -0
  128. package/starter/desert/render/ground/horizon.ts +219 -0
  129. package/starter/desert/render/ground/palette.d.ts +1 -0
  130. package/starter/desert/render/ground/palette.js +11 -0
  131. package/starter/desert/render/ground/scatter.ts +104 -0
  132. package/starter/desert/render/ground/terrain.ts +1854 -0
  133. package/starter/desert/render/kitAssets.ts +28 -0
  134. package/starter/desert/render/loading.ts +354 -0
  135. package/starter/desert/render/lookKnobs.ts +37 -0
  136. package/starter/desert/render/orbitCamera.ts +155 -0
  137. package/starter/desert/render/props/farForest.ts +96 -0
  138. package/starter/desert/render/props/formations.ts +630 -0
  139. package/starter/desert/render/props/pack.ts +1195 -0
  140. package/starter/desert/render/props/prepared.ts +225 -0
  141. package/starter/desert/render/props/propMaterials.ts +1255 -0
  142. package/starter/desert/render/props/propProgress.ts +2 -0
  143. package/starter/desert/render/props/propWorld.ts +105 -0
  144. package/starter/desert/render/props/props.ts +624 -0
  145. package/starter/desert/render/props/spruce.ts +440 -0
  146. package/starter/desert/render/sand.ts +581 -0
  147. package/starter/desert/render/sky/atmosphere.ts +329 -0
  148. package/starter/desert/render/sky/sky.ts +382 -0
  149. package/starter/desert/render/texturePreparation.ts +135 -0
  150. package/starter/desert/render/water/river.ts +1132 -0
  151. package/starter/desert/render/worldNames.ts +6 -0
  152. package/starter/desert/scene.ts +748 -0
  153. package/starter/desert/sceneProps.ts +562 -0
  154. package/starter/desert/sceneState.ts +33 -0
  155. package/starter/desert/world/terrainAssets.ts +162 -0
  156. package/starter/desert/world/walkBand.ts +47 -0
  157. package/starter/desert/world/water.ts +74 -0
  158. package/starter/desert/worlds.ts +13 -0
  159. package/starter/forest/README.md +59 -116
  160. package/starter/forest/assets.json +14 -14
  161. package/starter/forest/bake.mjs +26 -4
  162. package/starter/forest/playerRig.ts +89 -0
  163. package/starter/forest/recipe.json +233 -43
  164. package/starter/forest/render/bakedFile.ts +17 -0
  165. package/starter/forest/render/benchmark.ts +77 -0
  166. package/starter/forest/render/biomeData.ts +14 -0
  167. package/starter/forest/render/biomes.ts +637 -0
  168. package/starter/forest/render/ground/cover.ts +565 -0
  169. package/starter/forest/render/ground/horizon.ts +219 -0
  170. package/starter/forest/render/ground/palette.d.ts +1 -0
  171. package/starter/forest/render/ground/palette.js +11 -0
  172. package/starter/forest/render/ground/scatter.ts +104 -0
  173. package/starter/forest/render/ground/terrain.ts +1796 -0
  174. package/starter/forest/render/kitAssets.ts +28 -0
  175. package/starter/forest/render/loading.ts +354 -0
  176. package/starter/forest/render/lookKnobs.ts +37 -0
  177. package/starter/forest/render/orbitCamera.ts +155 -0
  178. package/starter/forest/render/props/farForest.ts +94 -0
  179. package/starter/forest/render/props/pack.ts +1078 -0
  180. package/starter/forest/render/props/prepared.ts +226 -0
  181. package/starter/forest/render/props/propMaterials.ts +1247 -0
  182. package/starter/forest/render/props/propProgress.ts +2 -0
  183. package/starter/forest/render/props/propWorld.ts +105 -0
  184. package/starter/forest/render/props/props.ts +624 -0
  185. package/starter/forest/render/props/spruce.ts +440 -0
  186. package/starter/forest/render/sky/atmosphere.ts +329 -0
  187. package/starter/forest/render/sky/sky.ts +382 -0
  188. package/starter/forest/render/texturePreparation.ts +135 -0
  189. package/starter/forest/render/water/river.ts +1132 -0
  190. package/starter/forest/render/worldNames.ts +6 -0
  191. package/starter/forest/scene.ts +715 -0
  192. package/starter/forest/sceneProps.ts +559 -0
  193. package/starter/forest/sceneState.ts +33 -0
  194. package/starter/forest/surface.json +2 -2
  195. package/starter/forest/world/terrainAssets.ts +158 -0
  196. package/starter/forest/world/walkBand.ts +47 -0
  197. package/starter/forest/world/water.ts +74 -0
  198. package/starter/forest/worlds.ts +13 -0
  199. package/starter/tundra/README.md +35 -14
  200. package/starter/tundra/bake.mjs +14 -1
  201. package/starter/tundra/biome.data.json +6 -6
  202. package/starter/tundra/playerRig.ts +89 -0
  203. package/starter/tundra/recipe.json +111 -110
  204. package/starter/tundra/render/bakedFile.ts +17 -0
  205. package/starter/tundra/render/benchmark.ts +79 -0
  206. package/starter/tundra/render/biomeData.ts +14 -0
  207. package/starter/tundra/render/biomes.ts +714 -0
  208. package/starter/tundra/render/ground/cover.ts +565 -0
  209. package/starter/tundra/render/ground/horizon.ts +219 -0
  210. package/starter/tundra/render/ground/palette.d.ts +1 -0
  211. package/starter/tundra/render/ground/palette.js +11 -0
  212. package/starter/tundra/render/ground/scatter.ts +104 -0
  213. package/starter/tundra/render/ground/terrain.ts +1874 -0
  214. package/starter/tundra/render/kitAssets.ts +28 -0
  215. package/starter/tundra/render/loading.ts +354 -0
  216. package/starter/tundra/render/lookKnobs.ts +37 -0
  217. package/starter/tundra/render/orbitCamera.ts +155 -0
  218. package/starter/tundra/render/props/farForest.ts +96 -0
  219. package/starter/tundra/render/props/pack.ts +1088 -0
  220. package/starter/tundra/render/props/prepared.ts +225 -0
  221. package/starter/tundra/render/props/propMaterials.ts +1247 -0
  222. package/starter/tundra/render/props/propProgress.ts +2 -0
  223. package/starter/tundra/render/props/propWorld.ts +105 -0
  224. package/starter/tundra/render/props/props.ts +624 -0
  225. package/starter/tundra/render/props/spruce.ts +440 -0
  226. package/starter/tundra/render/sky/atmosphere.ts +329 -0
  227. package/starter/tundra/render/sky/sky.ts +382 -0
  228. package/starter/tundra/render/texturePreparation.ts +135 -0
  229. package/starter/tundra/render/water/river.ts +1132 -0
  230. package/starter/tundra/render/worldNames.ts +6 -0
  231. package/starter/tundra/scene.ts +715 -0
  232. package/starter/tundra/sceneProps.ts +559 -0
  233. package/starter/tundra/sceneState.ts +33 -0
  234. package/starter/tundra/world/terrainAssets.ts +159 -0
  235. package/starter/tundra/world/walkBand.ts +47 -0
  236. package/starter/tundra/world/water.ts +74 -0
  237. package/starter/tundra/worlds.ts +13 -0
  238. package/starter-assets.json +4 -4
  239. package/starter-credits.json +901 -15
  240. package/AGENT_GUIDE.md +0 -209
  241. package/starter/forest/sky.ts +0 -38
  242. package/starter/forest/water.ts +0 -257
  243. package/starter/forest/world.ts +0 -182
@@ -0,0 +1,1874 @@
1
+ import type { IAssetLoader } from "@threenative/core";
2
+ import {
3
+ Heightfield,
4
+ type HeightfieldCollar,
5
+ bakedFractalNoise,
6
+ bakedNoise,
7
+ loadTerrainSplat,
8
+ } from "@threenative/core/world";
9
+ import { waterlineRadius } from "@threenative/core/world";
10
+ import { createSegmentIndex, paintCanopyCover } from "@threenative/terrain";
11
+ import {
12
+ COLLAR_UNDER_TILE,
13
+ STREAM_TILE,
14
+ TILE_INSIDE_SQUARE,
15
+ collarMorph,
16
+ } from "@threenative/terrain/starter";
17
+ import {
18
+ ClampToEdgeWrapping,
19
+ DataTexture,
20
+ DataUtils,
21
+ Float32BufferAttribute,
22
+ HalfFloatType,
23
+ LinearFilter,
24
+ MathUtils,
25
+ Mesh,
26
+ MeshStandardMaterial,
27
+ RGBAFormat,
28
+ RepeatWrapping,
29
+ type Texture,
30
+ type Vector2,
31
+ Vector3,
32
+ } from "three";
33
+ import {
34
+ abs,
35
+ attribute,
36
+ clamp,
37
+ dot,
38
+ float,
39
+ fract,
40
+ fwidth,
41
+ max,
42
+ min,
43
+ mix,
44
+ mx_noise_float,
45
+ normalWorld,
46
+ normalWorldGeometry,
47
+ normalize,
48
+ oneMinus,
49
+ positionView,
50
+ positionWorld,
51
+ rotateUV,
52
+ sign,
53
+ smoothstep,
54
+ texture,
55
+ transformNormalToView,
56
+ vec2,
57
+ vec3,
58
+ vec4,
59
+ } from "three/tsl";
60
+ import type { Node, UniformNode } from "three/webgpu";
61
+ import { MeshStandardNodeMaterial } from "three/webgpu";
62
+ import { GROUND_TILE, type LayerKey, ROCKFACE_MAPS } from "../../world/terrainAssets.js";
63
+ import { alpineRockColor, alpineRockTap, desertRockColor } from "../biomes.js";
64
+ // The ground's look, and every number in it, lives in this game: which surface covers which
65
+ // height and slope, how many metres one texture tile spans, and how the blend edges break. The
66
+ // evaluator in `packages/terrain` produces heights and eight material channels; none of that is a
67
+ // picture, and this file is the only place that decides what one looks like.
68
+ //
69
+ // Layer weights are read from the baked heightfield where it is drawn — its own world height, its
70
+ // own geometric normal, and the palette the bake painted — so a cliff is rock because it is steep,
71
+ // a beach is sand because it sits near the sea level the bake recorded, and snow settles only on
72
+ // the high flat ground. Nothing here resamples the terrain or adds a mask texture that could
73
+ // disagree with the geometry.
74
+ //
75
+ // Texture budget: six albedos + four normals + curvature + two shadow levels × two = 15/16.
76
+ import {
77
+ BIOMES,
78
+ type IBiome,
79
+ type IWorldBiome,
80
+ biomeWeights,
81
+ elevationBand,
82
+ measureBiome,
83
+ } from "../biomes.js";
84
+ import { LOOK } from "../lookKnobs.js";
85
+ import { loadSkyLight, skyIrradiance } from "../props/pack.js";
86
+ import { SUN_VECTOR } from "../sky/sky.js";
87
+ import {
88
+ type IBakedLake,
89
+ type IBakedRiver,
90
+ REFLECTED_LAYER,
91
+ surfaceHeights,
92
+ } from "../water/river.js";
93
+ import { WORLD } from "../worldNames.js";
94
+ import {
95
+ COLLAR_CURVE,
96
+ type IPackedMassif,
97
+ collarColors,
98
+ createHorizonCollar,
99
+ horizonSurroundings,
100
+ } from "./horizon.js";
101
+
102
+ export interface IBakedWorld {
103
+ size: number;
104
+ resolution: number;
105
+ heights: number[];
106
+ colors: number[];
107
+ erosion?: { flow: number[]; sediment: number[]; deposition: number[]; talus: number[] };
108
+ waterLevel: number | null;
109
+ lakes?: readonly IBakedLake[];
110
+ rivers?: readonly IBakedRiver[];
111
+ }
112
+
113
+ /** One transport mask shared by the terrain splat and rock placement. */
114
+ export function depositAtIndex(data: Pick<IBakedWorld, "erosion">, vertex: number): number {
115
+ const sediment = data.erosion?.sediment[vertex] ?? 0;
116
+ const hydraulic = (data.erosion?.deposition[vertex] ?? 0) / (1 + Math.sqrt(sediment));
117
+ return Math.min(1, hydraulic * 0.25 + (data.erosion?.talus[vertex] ?? 0) * 0.3);
118
+ }
119
+
120
+ /**
121
+ * The ground's own curvature, sampled from a height texture, as the material's curvature term.
122
+ *
123
+ * This is the one signal the ground material cannot get any other way, and it is what separates a
124
+ * hillside with hollows in it from a hillside with a colour painted on it. The heightfield's own
125
+ * samples give a Laplacian: positive where the ground is concave (a hollow, a gully, the crease
126
+ * where two slopes meet), negative on a nose or a rib. Both the moss and the rock below read it, so
127
+ * moss grows in the crease at the bottom of a slope and rock shows on the rib at the top, which is
128
+ * where each actually grows — rather than both keysing off slope alone and covering a whole face.
129
+ *
130
+ * Built once in `createTerrain` from the same heights the geometry and the collider were built from,
131
+ * so it cannot disagree with either.
132
+ */
133
+ export interface IGroundCurvature {
134
+ /** +1 in a hollow, -1 on a rib, ~0 on flat ground. */
135
+ readonly node: Node<"float">;
136
+ readonly texture: DataTexture;
137
+ readonly wetBank: Node<"float">;
138
+ readonly flow: Node<"float">;
139
+ readonly deposits: Node<"float">;
140
+ }
141
+
142
+ interface ILayerMaps {
143
+ diffuse: Texture;
144
+ normal?: Texture;
145
+ }
146
+
147
+ /**
148
+ * The stand-in for a ground layer the biome does not paint. White, because every consumer multiplies
149
+ * it by that layer's mask weight, and a layer with no mask row has zero weight everywhere.
150
+ */
151
+ const NEUTRAL_GROUND = new DataTexture(new Uint8Array([255, 255, 255, 255]), 1, 1);
152
+ NEUTRAL_GROUND.needsUpdate = true;
153
+
154
+ /** Props draw at render order 0 and the water at 2: the ground draws between them. */
155
+ const GROUND_RENDER_ORDER = 1;
156
+ /**
157
+ * The beach band, in metres above the bake's own sea level.
158
+ *
159
+ * Wide, because this coast rises a few degrees: a 3 m band is a 30 m walk of beach here and stops
160
+ * halfway up it. The bake paints sand below 6 m for the same reason.
161
+ */
162
+ const SHORE = { beach: 6, wet: -0.5 };
163
+
164
+ /**
165
+ * The wet band, and what it does to the sand.
166
+ *
167
+ * Sand that the sea has just left is darker and more saturated than the sand above it, because the
168
+ * water is still in the pores and the grains are closer together for it. The band is a metre and a half
169
+ * of height above the bake's own sea level and it feathers: a hard line at the high-water mark is
170
+ * exactly the "straight-edged white shape" the foam work removed from the water.
171
+ *
172
+ * It is also the reason the beach reads as a *beach* rather than as a tan field, and it is a colour
173
+ * the sand layer cannot supply on its own because it is a fact about the water's last reach, not about
174
+ * the sand.
175
+ */
176
+ const WET_SAND = {
177
+ /** Height above sea level over which the band fades out, in metres. */
178
+ band: 2.8,
179
+ /** How much darker and how much more saturated the wet sand is. */
180
+ darken: vec3(0.38, 0.4, 0.42),
181
+ /** The grain the band adds: wet sand is smooth and packed, so the ripples flatten in it. */
182
+ calm: 0.45,
183
+ } as const;
184
+
185
+ /**
186
+ * What makes the ground grass rather than the dry autumn meadow the CC0 set photographs.
187
+ *
188
+ * Leafy Grass is a real meadow in October: brown thatch with green sprigs. A temperate starter
189
+ * wants June, so this trades red for green on that one layer and leaves the texture's own detail,
190
+ * its normal map and every other surface alone.
191
+ */
192
+ const MEADOW = vec3(0.47, 0.72, 0.4);
193
+ /** A spruce forest's meadow: dark olive, not lawn green (Project Nature's spruce forest frames). */
194
+ const FOREST_MEADOW = vec3(0.4, 0.58, 0.27);
195
+ /** How much of the vegetation's sky light the ground receives; the vegetation's own is 1.13. */
196
+ const GROUND_SKY_LIGHT = 0.6;
197
+ /** Multiplier that turns meadow turf into shaded needle litter under a stand. */
198
+ const FOREST_FLOOR = vec3(0.4, 0.4, 0.27);
199
+ /**
200
+ * Bare earth between the stands, on top of the litter tint: a spruce floor's humus reads L* 29-37 at
201
+ * the walk pose (PRD-855), and the litter tint alone left it at 53, brighter than the turf beside it.
202
+ */
203
+ const BARE_SOIL = vec3(0.4, 0.38, 0.37);
204
+ /**
205
+ * Albedo of the backdrop's closed spruce cover, crowns and the shade between them averaged: the hue of
206
+ * the playable forest's own crowns in the overview (linear 0.74 : 1 : 0.28), a little bluer, so the
207
+ * far slopes and the near stands read as one forest.
208
+ */
209
+ const BACKDROP_SPRUCE = vec3(0.019, 0.028, 0.013);
210
+ /** Albedo of the meadow gaps in the backdrop's cover: dull olive turf, not lawn. */
211
+ const BACKDROP_CLEARING = vec3(0.042, 0.052, 0.022);
212
+ /**
213
+ * The surveyed surroundings carry no stands (the bake plants only the playable square), so past the
214
+ * square's edge the forest hillside is an open sunlit meadow: lawn turf, no needle-soil patches, and
215
+ * the vista's ground cover (`meadowCover`).
216
+ */
217
+ export const OPEN_MEADOW = true;
218
+
219
+ /** Continuous stochastic warp: no hard cell boundaries in colour or normals. */
220
+ export function tiledUV(
221
+ key: LayerKey,
222
+ scale = 1,
223
+ plane: Node<"vec2"> = positionWorld.xz,
224
+ ): Node<"vec2"> {
225
+ const base = plane.div(GROUND_TILE[key] * scale);
226
+ const warp = vec2(
227
+ bakedNoise(positionWorld.mul(0.025)),
228
+ bakedNoise(positionWorld.mul(0.025).add(vec3(17, 0, 29))),
229
+ );
230
+ return rotateUV(base, float(scale === 1 ? 0.38 : -0.73), vec2(0)).add(warp.mul(0.35));
231
+ }
232
+
233
+ /** Shared floor sampling: two rotated scales, with continuous world-space blend weights. */
234
+ export function groundLayer(
235
+ source: Texture,
236
+ key: LayerKey,
237
+ plane = positionWorld.xz,
238
+ ): Node<"vec4"> {
239
+ const patch = smoothstep(-0.35, 0.35, bakedNoise(positionWorld.mul(0.025)));
240
+ const far = smoothstep(10, 70, positionView.length());
241
+ const mid = mix(
242
+ texture(source, tiledUV(key, 1, plane)),
243
+ texture(source, tiledUV(key, 2.35, plane)),
244
+ mix(patch.mul(0.65), patch.mul(0.5).add(0.25), far),
245
+ );
246
+ const near = mix(
247
+ mid,
248
+ texture(source, tiledUV(key, 0.23, plane)),
249
+ oneMinus(smoothstep(5, 24, positionView.length())).mul(0.2),
250
+ );
251
+ return mix(
252
+ near,
253
+ texture(source, tiledUV(key, 18, plane)),
254
+ smoothstep(100, 380, positionView.length()).mul(0.72),
255
+ );
256
+ }
257
+
258
+ /** Turf colour shared by the landscape and soil banked against a rock. */
259
+ export function groundTurf(
260
+ sampled: Node<"vec3">,
261
+ biome?: IBiome,
262
+ hollow: Node<"float"> = float(0),
263
+ /** 0..1: how far a forest fragment is into open meadow, which takes the lawn turf instead. */
264
+ open: Node<"float"> = float(0),
265
+ ): Node<"vec3"> {
266
+ const distance = positionView.length();
267
+ const broad = bakedFractalNoise(vec3(positionWorld.x, 0, positionWorld.z).mul(0.006), 2);
268
+ const dry = smoothstep(-0.45, 0.45, broad.sub(hollow.mul(0.06)));
269
+ const tufts = bakedNoise(positionWorld.mul(0.75))
270
+ .mul(0.22)
271
+ .mul(oneMinus(smoothstep(45, 140, distance)))
272
+ .add(1);
273
+ const temperate = !biome || biome.lawnGround;
274
+ if (!temperate) {
275
+ const tint = vec3(...biome.grassTint);
276
+ if (!biome.crestTurf) return sampled.mul(tint);
277
+ const cover = vec3(0.075, 0.12, 0.028).mul(mix(0.91, 1.08, dry));
278
+ return mix(sampled.mul(tint), cover, smoothstep(65, 180, distance).mul(0.85));
279
+ }
280
+ const olive = biome?.oliveMeadow ?? false;
281
+ const own = biome?.turf;
282
+ const lawn = own
283
+ ? mix(vec3(...own.field[0]), vec3(...own.field[1]), dry)
284
+ : mix(vec3(0.042, 0.072, 0.018), vec3(0.062, 0.102, 0.029), dry);
285
+ const field = (
286
+ olive ? mix(mix(vec3(0.045, 0.062, 0.022), vec3(0.06, 0.082, 0.03), dry), lawn, open) : lawn
287
+ )
288
+ .mul(tufts)
289
+ .mul(mix(0.92, 1.08, smoothstep(0.6, -0.6, hollow)));
290
+ // Open meadow: sward patches metres across, sunlit and deep, so a slope past the grass draw reach
291
+ // still reads as grass rather than one flat tone.
292
+ const sward = mix(
293
+ 0.5,
294
+ 0.95,
295
+ smoothstep(
296
+ -0.45,
297
+ 0.45,
298
+ bakedFractalNoise(vec3(positionWorld.x, 0, positionWorld.z).mul(0.09), 2),
299
+ ),
300
+ );
301
+ const turf = mix(
302
+ sampled.mul(own ? vec3(...own.photo) : olive ? mix(FOREST_MEADOW, MEADOW, open) : MEADOW),
303
+ field,
304
+ // Open meadow: the photograph's thatch (albedo 0.15) only carries detail under a dark lawn.
305
+ smoothstep(60, 220, distance)
306
+ .mul(0.55)
307
+ .max(open.mul(0.6)),
308
+ ).mul(mix(float(1), sward, open));
309
+ return turf;
310
+ }
311
+
312
+ function rockLayer(
313
+ source: Texture,
314
+ plane: Node<"vec2">,
315
+ biome?: IBiome,
316
+ relief = false,
317
+ ): Node<"vec4"> {
318
+ const patch = smoothstep(-0.35, 0.35, bakedNoise(positionWorld.mul(0.025)));
319
+ const tap = (scale: number, angle: number, offset: Node<"vec2">) => {
320
+ const sampled = texture(source, rotateUV(plane.div(scale), float(angle), vec2(0)).add(offset));
321
+ if (!relief) return sampled;
322
+ const tangent = rotateUV(sampled.xy.mul(2).sub(1), float(-angle), vec2(0));
323
+ return vec4(tangent, sampled.z.mul(2).sub(1), 1);
324
+ };
325
+ return biome?.crestRock
326
+ ? alpineRockTap(source, plane, relief)
327
+ : biome?.mesaRock
328
+ ? mix(
329
+ tap(11, 0.035, vec2(mx_noise_float(positionWorld.xz.mul(0.009)).mul(0.9), 0)),
330
+ tap(27, -0.045, vec2(0.37, 0.61)),
331
+ patch.mul(0.5).add(0.25),
332
+ )
333
+ : mix(tap(6.7, 0.57, vec2(0)), tap(11.3, -0.83, vec2(0.37, 0.61)), patch);
334
+ }
335
+
336
+ /** The bedrock projection shared by the landscape and a rock's contact band. */
337
+ export function stoneAlbedo(
338
+ source: Texture,
339
+ biome?: IBiome,
340
+ normal = normalWorldGeometry,
341
+ ): Node<"vec3"> {
342
+ const axis = abs(normal).pow(4);
343
+ const share = axis.div(axis.x.add(axis.y).add(axis.z));
344
+ const other = biome !== undefined && !biome.lawnGround;
345
+ const tap = (plane: Node<"vec2">) =>
346
+ other ? rockLayer(source, plane, biome).rgb : texture(source, tiledUV("rock", 1, plane)).rgb;
347
+ return share.x
348
+ .mul(tap(positionWorld.zy))
349
+ .add(share.y.mul(tap(positionWorld.xz)))
350
+ .add(share.z.mul(tap(positionWorld.xy)));
351
+ }
352
+
353
+ export function stoneColor(sampled: Node<"vec3">, biome?: IBiome): Node<"vec3"> {
354
+ const look = biome ?? BIOMES.tundra;
355
+ if (look.crestRock) return alpineRockColor(sampled);
356
+ if (look.mesaRock) return desertRockColor(sampled);
357
+ const grey = dot(sampled, vec3(0.2126, 0.7152, 0.0722));
358
+ return mix(sampled, vec3(grey), look.stoneGrey).mul(vec3(...look.stoneTint));
359
+ }
360
+
361
+ export function stoneRelief(
362
+ source: Texture,
363
+ biome?: IBiome,
364
+ normal = normalWorldGeometry,
365
+ ): Node<"vec3"> {
366
+ if (!biome || biome.lawnGround) return triplanarRelief(source, "rock", 1, normal).tilt;
367
+ const axis = abs(normal).pow(4);
368
+ const share = axis.div(axis.x.add(axis.y).add(axis.z));
369
+ const x = rockLayer(source, positionWorld.zy, biome, true);
370
+ const y = rockLayer(source, positionWorld.xz, biome, true);
371
+ const z = rockLayer(source, positionWorld.xy, biome, true);
372
+ return share.x
373
+ .mul(vec3(0, x.y, x.x.mul(sign(normal.x))))
374
+ .add(share.y.mul(vec3(y.x, 0, y.y)))
375
+ .add(share.z.mul(vec3(z.x.mul(sign(normal.z)), z.y, 0)));
376
+ }
377
+
378
+ /**
379
+ * One normal map's two answers on the ground plane: the tilt it asks for, and how much of its own
380
+ * up-facing it kept.
381
+ *
382
+ * Only the two tangential channels go into the tilt. The surface direction is already the
383
+ * heightfield's own normal, and folding a second "out of the surface" term in here would cancel the
384
+ * relief this map exists to add. On the ground plane the map's red runs along +x and its green
385
+ * along +z. The third channel is not thrown away: it is the crevice term below.
386
+ */
387
+ interface IRelief {
388
+ /** How much this texel faces up, 0..1. A crevice is a texel that does not. */
389
+ readonly crevice: Node<"float">;
390
+ readonly tilt: Node<"vec3">;
391
+ }
392
+
393
+ function planarRelief(source: Texture, uv: Node<"vec2">, strength: number, angle = 0.38): IRelief {
394
+ const sample = texture(source, uv);
395
+ const tangent = rotateUV(sample.xy.mul(2).sub(1), float(-angle), vec2(0));
396
+ return {
397
+ crevice: sample.z,
398
+ tilt: vec3(tangent.x, 0, tangent.y).mul(strength),
399
+ };
400
+ }
401
+
402
+ /**
403
+ * The same relief projected on all three axes — this is what keeps a cliff from smearing.
404
+ *
405
+ * Each projection owns a different pair of world axes, so one map tilts the surface along a
406
+ * different direction per axis and the three are recombined by the surface's own blend weights. The
407
+ * crevice term is the one projection, because a crease is a crease whichever way the cliff faces.
408
+ *
409
+ * `roughnessScale` widens the sample spacing on the wall projections. A cliff nine metres of strata
410
+ * across reads a nine-metre map at a one-metre scale as an unreadable fine band along its own
411
+ * tangential direction, which is what a wall projection always does without this.
412
+ */
413
+ function triplanarRelief(
414
+ source: Texture,
415
+ key: LayerKey,
416
+ roughnessScale = 1,
417
+ normal = normalWorldGeometry,
418
+ ): IRelief {
419
+ const tap = (plane: Node<"vec2">) => {
420
+ const sampled = texture(source, tiledUV(key, roughnessScale, plane));
421
+ const tangent = rotateUV(
422
+ sampled.xy.mul(2).sub(1),
423
+ float(roughnessScale === 1 ? -0.38 : 0.73),
424
+ vec2(0),
425
+ );
426
+ return vec3(tangent, sampled.z.mul(2).sub(1));
427
+ };
428
+ const x = tap(positionWorld.zy);
429
+ const y = tap(positionWorld.xz);
430
+ const z = tap(positionWorld.xy);
431
+ const axis = abs(normal).pow(4);
432
+ const weight = axis.div(axis.x.add(axis.y).add(axis.z));
433
+ return {
434
+ crevice: float(1),
435
+ tilt: weight.x
436
+ .mul(vec3(0, x.y, x.x.mul(sign(normal.x))))
437
+ .add(weight.y.mul(vec3(y.x, 0, y.y)))
438
+ .add(weight.z.mul(vec3(z.x.mul(sign(normal.z)), z.y, 0))),
439
+ };
440
+ }
441
+
442
+ /**
443
+ * How steep a face has to be before a layer stops being projected onto the ground plane.
444
+ *
445
+ * A planar projection is exact on flat ground and wrong everywhere else, and it is *very* wrong on a
446
+ * slope: the map is stretched along the slope's own direction by the reciprocal of the cosine, so a
447
+ * thirty-degree hillside turns a 2.6 m grass tile into a five-metre smear. Thirty-five degrees is
448
+ * where that smear stops being invisible — below it the slope is gentle enough that the detail still
449
+ * reads, above it the triplanar takes over.
450
+ */
451
+ // Slope is 1 − cos(angle): 0.18 is 35°, not the sine of 35°.
452
+ const TRIPLANAR_SLOPE = 0.18;
453
+
454
+ /** Wind ripples share one world-space phase; changing normals must not bend the phase. */
455
+ const RIPPLE = {
456
+ /** Crests per metre across the fall line. Real ripples are 5-20 cm apart; these read at 25 cm. */
457
+ frequency: 4,
458
+ /** How far the crests tilt the surface, and how much their spacing wanders. */
459
+ strength: 0.065,
460
+ wander: 1.4,
461
+ } as const;
462
+
463
+ function sandRipples(direction?: Node<"vec2">): Node<"vec3"> {
464
+ // A coherent wind direction avoids radial stripes where a beach normal changes.
465
+ const fall = direction ?? vec2(0.83, 0.56);
466
+ const downhill = fall.length().max(float(0.0001));
467
+ const across = vec2(fall.x.div(downhill), fall.y.div(downhill));
468
+ // Distance across the wind, in metres; slow noise breaks a perfect comb.
469
+ const phase = positionWorld.x
470
+ .mul(across.x)
471
+ .add(positionWorld.z.mul(across.y))
472
+ .mul(RIPPLE.frequency * Math.PI * 2);
473
+ const wobble = bakedNoise(positionWorld.mul(0.09)).mul(RIPPLE.wander);
474
+ const crest = phase.add(wobble).sin();
475
+ // Subtle relief disappears before the crests become smaller than a pixel.
476
+ return vec3(across.x, 0, across.y)
477
+ .mul(crest)
478
+ .mul(RIPPLE.strength)
479
+ .mul(oneMinus(smoothstep(8, 35, positionView.length())));
480
+ }
481
+
482
+ /**
483
+ * One albedo map projected on all three axes, recombined by the surface's own normal.
484
+ *
485
+ * This is the same idea as {@link triplanarRelief} on the colour side, and it is what a hillside
486
+ * needs: a planar projection stretches the map by the reciprocal of the cosine of the slope, so the
487
+ * further off flat the ground gets the more the detail smears along the fall line. Sampling the three
488
+ * world-axis planes and blending by `|n|` costs two extra taps and buys a hillside with detail on it
489
+ * at every angle.
490
+ *
491
+ * The wall projections sample at a coarser spacing than the floor one, because a vertical face has no
492
+ * floor projection to fall back on and at full density a nine-metre tile turns into fine stripes down
493
+ * its own length.
494
+ */
495
+ function triplanarAlbedo(source: Texture, key: LayerKey, scale = 1): Node<"vec4"> {
496
+ const axis = abs(normalWorldGeometry).pow(4);
497
+ const weight = axis.div(axis.x.add(axis.y).add(axis.z));
498
+ const x = texture(source, tiledUV(key, scale, positionWorld.zy));
499
+ const y = texture(source, tiledUV(key, scale));
500
+ const z = texture(source, tiledUV(key, scale, positionWorld.xy));
501
+ return weight.x.mul(x).add(weight.y.mul(y)).add(weight.z.mul(z)) as Node<"vec4">;
502
+ }
503
+
504
+ /**
505
+ * A third of a metre of ground grain, as a tilt in world space.
506
+ *
507
+ * The last scale of detail on the ground is not a texture: it is the difference between a surface
508
+ * that is *smooth* and one that is *smooth at a hundred metres*. One fractal noise field, differenced
509
+ * into a gradient, gives it for the price of four instructions and no sampler at all — and the ground
510
+ * material is already at eleven sampled textures, so a twelfth map is not available however much this
511
+ * detail wants it.
512
+ *
513
+ * It is deliberately faint. This is a third of a metre of clumping between the blades, not the blades
514
+ * themselves, and the capture that showed a speckled meadow is what happens when it is not: a normal
515
+ * perturbation this high-frequency reads as static underfoot and as noise at any distance, and it
516
+ * costs the eye the thing it was added for.
517
+ */
518
+ function microGrain(): Node<"vec3"> {
519
+ const field = (p: Node<"vec3">) => bakedFractalNoise(p.mul(2.6), 2, 2, 0.5);
520
+ const here = field(positionWorld);
521
+ const step = float(0.22);
522
+ const dx = here.sub(field(positionWorld.add(vec3(step, 0, 0))));
523
+ const dz = here.sub(field(positionWorld.add(vec3(0, 0, step))));
524
+ return vec3(dx, 0, dz).div(step).mul(0.06);
525
+ }
526
+
527
+ /** Crown radius in metres per unit of placement scale, for the trees that drop needle litter. */
528
+ /**
529
+ * The crown radius that shades the ground under each tree, metres. The bake paints the canopy cover
530
+ * map from these rows; a species absent here shades nothing. Alpine crowns are smaller than the
531
+ * forest's spruce: the trees are shorter and the light is flatter.
532
+ */
533
+ export const CANOPY_CROWN: Readonly<Record<string, number>> = {
534
+ spruce: 6,
535
+ scotspine: 5,
536
+ blackspruce: 4.5,
537
+ sapling: 2.5,
538
+ };
539
+
540
+ /**
541
+ * Paint each placed tree's crown into the terrain's `canopy` vertex attribute, so the ground under a
542
+ * stand reads as forest floor rather than meadow turf. Vertices are row-major Z then X, centred at
543
+ * zero, at the heightfield's own spacing.
544
+ */
545
+ export function paintCanopy(
546
+ mesh: Mesh,
547
+ data: Pick<IBakedWorld, "size" | "resolution">,
548
+ placements: readonly {
549
+ readonly asset: string;
550
+ readonly position: readonly number[];
551
+ readonly scale: number;
552
+ }[],
553
+ ): void {
554
+ const cover = mesh.geometry.getAttribute("canopy");
555
+ if (!(cover instanceof Float32BufferAttribute) || data.resolution < 2) return;
556
+ paintCanopyCover(cover.array as Float32Array, data, placements, CANOPY_CROWN);
557
+ cover.needsUpdate = true;
558
+ }
559
+
560
+ /**
561
+ * The ground material: one lit surface whose colour is a blend of six PBR layers, blended in weight
562
+ * order outwards from the base surface.
563
+ */
564
+ export async function createGroundMaterial(
565
+ data: IBakedWorld,
566
+ assets: IAssetLoader,
567
+ curvature: IGroundCurvature,
568
+ biome?: IBiome,
569
+ /**
570
+ * A streamed tile carries no painted `canopy` or baked `sky`: it lies past the trees and keeps the
571
+ * whole sky, exactly as the collar's own attributes say.
572
+ */
573
+ streamed = false,
574
+ ): Promise<MeshStandardNodeMaterial> {
575
+ const canopyCover = (): Node<"float"> =>
576
+ streamed ? float(0) : attribute<"float">("canopy", "float");
577
+ const skyShare = (): Node<"float"> => (streamed ? float(1) : attribute<"float">("sky", "float"));
578
+ const measured =
579
+ biome && "heightBands" in biome
580
+ ? (biome as IWorldBiome)
581
+ : measureBiome(biome ?? BIOMES.tundra, data.heights);
582
+ const look = biome ?? BIOMES.tundra;
583
+ const maps: Partial<Record<LayerKey, ILayerMaps>> = {};
584
+ const material = new MeshStandardNodeMaterial({ metalness: 0, roughness: 0.94 });
585
+ material.userData.biome = look.world;
586
+ material.userData.erosion = data.erosion !== undefined;
587
+ const held = new Set<Texture>([curvature.texture]);
588
+ // The forest's alpine backdrop shades from the unfiltered survey (owner, 2026-11-04: "mountain
589
+ // tops textures and heightmaps suck"); the sixteenth binding, so only this world takes it.
590
+ const collar = look.surveyCollar ? buildCollarRelief(look.world) : undefined;
591
+ if (collar) held.add(collar.texture);
592
+ // A biome carries the layers it paints, and this material knows the forest's eight. A world with
593
+ // fewer (the alpine kit writes rock, dirt and snow) has no mask weight anywhere for the rest, so a
594
+ // shared white tap stands in: one texture, no colour, and the world still draws.
595
+ const warned = new Set<LayerKey>();
596
+ const layer = (key: LayerKey): ILayerMaps => {
597
+ const found = maps[key];
598
+ if (found?.diffuse) return found;
599
+ if (!warned.has(key)) {
600
+ warned.add(key);
601
+ console.warn(
602
+ `TN_GROUND_MAP_MISSING Ground layer '${key}' has no diffuse texture; its mask weights are zero, so it draws as white`,
603
+ );
604
+ }
605
+ return { diffuse: NEUTRAL_GROUND };
606
+ };
607
+
608
+ const otherBiome = biome !== undefined && !biome.lawnGround;
609
+ const macro = bakedFractalNoise(vec3(positionWorld.x, 0, positionWorld.z).mul(0.014), 3);
610
+ const mottling = bakedNoise(vec3(positionWorld.x, 0, positionWorld.z).mul(0.045));
611
+
612
+ // --- where each surface sits -------------------------------------------------------------
613
+ const slope = normalWorldGeometry.y.abs().oneMinus();
614
+ const breakUp = bakedFractalNoise(positionWorld.mul(0.05), 3);
615
+ const steep = clamp(slope.add(breakUp.mul(0.05)), 0, 1);
616
+ // +1 in a hollow, -1 on a rib. The two ends of the ground's own shape, which slope cannot tell
617
+ // apart: a gully and a nose are both steep, and they are not the same surface.
618
+ const outside = max(abs(positionWorld.x), abs(positionWorld.z));
619
+ const hollow = curvature.node.mul(
620
+ oneMinus(smoothstep(data.size / 2, data.size / 2 + 28, outside)),
621
+ );
622
+ // Forest only: the open meadow past the square's edge (`OPEN_MEADOW`), eased in over 40 m.
623
+ const open =
624
+ OPEN_MEADOW && look.openMeadow
625
+ ? smoothstep(data.size / 2, data.size / 2 + 40, outside)
626
+ : float(0);
627
+ // Material placement follows the actual landform, never the bake's brown blob palette.
628
+ const drainage = smoothstep(0.12, 0.65, curvature.flow);
629
+ const deposits = smoothstep(0.08, 0.6, curvature.deposits);
630
+ const scour = drainage.mul(smoothstep(0.035, 0.18, slope));
631
+ // The material's transport terms read the erosion bake through the curvature texture.
632
+ const flow = curvature.flow;
633
+ const sediment = deposits;
634
+ const rib = smoothstep(-0.02, -0.45, hollow);
635
+ const alpine = elevationBand(
636
+ measured,
637
+ measured.heightBands.alpine,
638
+ positionWorld.y.add(breakUp.mul(5)),
639
+ );
640
+ // No recorded sea level means an inland world, and an inland world has no beach.
641
+ const sand =
642
+ data.waterLevel === null
643
+ ? float(0)
644
+ : smoothstep(float(SHORE.beach), float(SHORE.wet), positionWorld.y.sub(data.waterLevel)).mul(
645
+ smoothstep(0.34, 0.1, steep),
646
+ );
647
+ /**
648
+ * How wet the sand under this fragment is, 0..1: one at the sea surface, gone `WET_SAND.band`
649
+ * metres above it.
650
+ *
651
+ * The band is broken by the same slow noise the litter uses so the high-water mark is a ragged edge
652
+ * rather than a contour line — the same reason the foam's outer edge wanders in `ocean.ts`.
653
+ */
654
+ const wetness = (): Node<"float"> => {
655
+ if (data.waterLevel === null) return float(0);
656
+ const above = positionWorld.y.sub(float(data.waterLevel));
657
+ const wander = bakedFractalNoise(positionWorld.mul(0.06), 3).mul(0.55).add(0.5);
658
+ return float(1).sub(
659
+ smoothstep(float(0), float(otherBiome ? 1.6 : WET_SAND.band), above.div(wander)),
660
+ );
661
+ };
662
+ const weights: Record<LayerKey, Node<"float">> = {
663
+ // The bake painted its beach in the same red-over-green as its dirt, so the height rule above
664
+ // has to be the one that speaks for the shore; painted dirt steps aside where it does.
665
+ dirt: max(
666
+ drainage.mul(0.18).max(sediment.mul(0.5)),
667
+ smoothstep(0.025, 0.18, steep)
668
+ .mul(smoothstep(-0.12, 0.32, breakUp))
669
+ .mul(0.48),
670
+ ).mul(sand.oneMinus()),
671
+ grass: float(1),
672
+ moss: drainage.mul(smoothstep(0.02, 0.14, steep)).mul(0.24),
673
+ sand,
674
+ // Rock shows where the ground is steep *and* convex — the nose of a rib, the face of a scarp. On a
675
+ // concave slope the ground is covered by what has fallen into it, which is the moss above, so the
676
+ // steepness term is scaled down in a hollow rather than replaced: bare rock still shows at a
677
+ // scarp's foot where the ground is steep and the debris has not arrived yet.
678
+ // Soil holds on ordinary hills; only scarps expose bedrock (34–48 degrees).
679
+ rock: smoothstep(0.17, 0.33, steep.add(rib.mul(0.04)).add(breakUp.mul(0.025)))
680
+ .mul(mix(0.65, 1, elevationBand(measured, measured.heightBands.rock)))
681
+ .mul(oneMinus(smoothstep(0.15, 0.8, hollow).mul(0.25))),
682
+ snow: elevationBand(measured, measured.snowBand).mul(
683
+ smoothstep(measured.snowFractions[2], 0.06, steep),
684
+ ),
685
+ };
686
+
687
+ Object.assign(weights, biomeWeights(measured, steep, hollow, breakUp));
688
+ if (look.snowPatches) {
689
+ // Snowbanks that outlast June: broad noise picks them, a hollow holds them first, a slope sheds them.
690
+ // Not in a stream's swale or a pond's basin: those melt out first, and water would cover them.
691
+ const lying = bakedFractalNoise(
692
+ vec3(positionWorld.x, 0, positionWorld.z).mul(1 / look.snowPatches.metres),
693
+ 3,
694
+ ).add(hollow.max(0).mul(0.2));
695
+ const edge = 0.5 - look.snowPatches.cover;
696
+ weights.snow = max(
697
+ weights.snow,
698
+ smoothstep(edge, edge + 0.12, lying)
699
+ .mul(smoothstep(0.24, 0.1, steep))
700
+ .mul(oneMinus(drainage))
701
+ .mul(smoothstep(31, 34, positionWorld.y)),
702
+ );
703
+ }
704
+ // Needle litter and crown shade under the placed stands, as a multiplicative floor tint.
705
+ let forestFloor: Node<"float"> = float(0);
706
+ let bareSoil: Node<"float"> = float(0);
707
+ // Transport, slope and shelter choose the splat; noise only frays the material's edge.
708
+ weights.rock = max(weights.rock, scour.mul(0.9)).mul(oneMinus(deposits.mul(0.22)));
709
+ if (look.crestRock) weights.rock = max(weights.rock, smoothstep(0.08, 0.22, slope));
710
+ weights.dirt = max(weights.dirt.mul(0.45), deposits.mul(0.85))
711
+ .mul(oneMinus(smoothstep(0.22, 0.4, slope)))
712
+ .mul(sand.oneMinus());
713
+ if (look.mossGround) {
714
+ weights.moss = hollow
715
+ .max(0)
716
+ .mul(oneMinus(drainage))
717
+ .mul(smoothstep(0.12, 0.025, slope))
718
+ .mul(oneMinus(weights.snow))
719
+ .mul(0.7);
720
+ }
721
+ if (!otherBiome) {
722
+ // Ordinary forest hills carry turf; reserve exposed soil for drainage banks.
723
+ if (look.woodedGround)
724
+ weights.dirt = drainage.mul(0.18).max(sediment.mul(0.5)).mul(sand.oneMinus());
725
+ if (look.woodedGround) {
726
+ // Needle litter lies under the trees that were actually placed (`paintCanopy`), frayed by noise
727
+ // at its edge. The old sine-sum stand mask no longer matched the value-noise scatter, and its
728
+ // 38 m fade left every stand standing on meadow turf from any height.
729
+ const litter = smoothstep(0, 0.6, canopyCover())
730
+ .mul(mix(0.72, 1, smoothstep(-0.5, 0.5, bakedNoise(positionWorld.mul(2.2)))))
731
+ .mul(oneMinus(smoothstep(300, 600, positionView.length())))
732
+ .mul(0.85);
733
+ weights.dirt = weights.dirt.max(litter.mul(0.25));
734
+ forestFloor = litter;
735
+ // The bare patches are the wood's own: a ground drawn with no look keeps its litter only.
736
+ if (biome?.woodedGround) {
737
+ // Bare earth breaks the meadow in broad patches, as on a real spruce slope: broad noise
738
+ // picks them, finer noise frays their edge, a hollow keeps its turf. They fade out by 350 m
739
+ // so a far slope does not print the noise as camouflage.
740
+ const bare = smoothstep(
741
+ 0.16,
742
+ 0.5,
743
+ macro.add(mottling.mul(0.85)).sub(hollow.max(0).mul(0.2)),
744
+ )
745
+ .mul(oneMinus(smoothstep(150, 350, positionView.length())))
746
+ .mul(oneMinus(open));
747
+ weights.dirt = weights.dirt.max(bare.mul(0.8));
748
+ // The soil takes the litter's warm needle tint in full, not the dirt photograph's grey gravel.
749
+ forestFloor = forestFloor.max(bare);
750
+ bareSoil = bare;
751
+ }
752
+ }
753
+ // Coastal soil patches remain; the forest meadow keeps turf between distant blade clusters.
754
+ if (look.shoreGround) {
755
+ const dry = smoothstep(0.14, 0.42, macro.add(mottling.mul(0.85)).sub(hollow.mul(0.12)));
756
+ weights.dirt = max(weights.dirt, dry.mul(0.7)).mul(sand.oneMinus());
757
+ }
758
+ weights.moss = hollow
759
+ .max(0)
760
+ .mul(oneMinus(drainage))
761
+ .mul(smoothstep(0.15, 0.025, slope))
762
+ .mul(0.5);
763
+ if (biome?.woodedGround) {
764
+ // A spruce floor is moss and needles, not turf and not bare sand: under the placed crowns and
765
+ // on the wood's bare patches the moss layer grows in broad cushions, frayed by a finer noise,
766
+ // and the needle soil shows between them. In the low sun the old floor drew as pale sand.
767
+ const cushions = smoothstep(
768
+ -0.25,
769
+ 0.3,
770
+ bakedNoise(vec3(positionWorld.x, 0, positionWorld.z).mul(0.35)).add(mottling.mul(0.5)),
771
+ );
772
+ weights.moss = weights.moss.max(forestFloor.mul(cushions).mul(0.85));
773
+ }
774
+ }
775
+
776
+ // --- how each surface looks -------------------------------------------------------------
777
+ // Apply observed deposition after biome placement so dry/snow-world rules cannot erase it.
778
+ weights.dirt = weights.dirt.max(sediment.mul(0.5)).max(flow.mul(0.28)).mul(sand.oneMinus());
779
+ // The layers that cover most of a meadow take a second, larger scale faded in with distance: one
780
+ // tile under the player's feet, a coarser one near the horizon, and no single lattice for the eye
781
+ // to find anywhere between.
782
+ const far = smoothstep(float(10), float(70), positionView.length());
783
+ const patch = smoothstep(-0.35, 0.35, bakedNoise(positionWorld.mul(0.025)));
784
+ const tileBlend = mix(patch.mul(0.65), patch.mul(0.5).add(0.25), far);
785
+ // How much of a layer is projected onto the ground plane and how much onto the walls. Zero on the
786
+ // meadow, one on a cliff, and eased across the thirty-five degrees where a planar projection stops
787
+ // being an approximation and becomes a smear.
788
+ const planarShare = float(1).sub(
789
+ smoothstep(float(TRIPLANAR_SLOPE * 0.55), float(TRIPLANAR_SLOPE * 1.6), steep),
790
+ );
791
+
792
+ /**
793
+ * One layer's albedo: the ground plane near the camera, the walls on a slope, and a coarser tile
794
+ * faded in with distance so the horizon is not a field of half-resolved texels.
795
+ *
796
+ * The two planar scales are what the last captures' "flat green tint" was not: a single scale at
797
+ * 2.6 m is a dozen pixels wide from fifty metres away, and the middle distance goes to a wash. The
798
+ * two are blended rather than switched so the crossover has no seam to find.
799
+ */
800
+
801
+ const albedoOf = (key: LayerKey): Node<"vec4"> => {
802
+ const { diffuse } = layer(key);
803
+ const flat = groundLayer(diffuse, key);
804
+ if (look.mossGround && (key === "grass" || key === "dirt" || key === "moss")) {
805
+ // The same rotated two-scale floor and walls continue across the resident edge.
806
+ const axis = abs(normalWorldGeometry).pow(4);
807
+ const share = axis.div(axis.x.add(axis.y).add(axis.z));
808
+ const tap = (plane: Node<"vec2">) => groundLayer(diffuse, key, plane);
809
+ const sampled = share.x
810
+ .mul(tap(positionWorld.zy))
811
+ .add(share.y.mul(flat))
812
+ .add(share.z.mul(tap(positionWorld.xy))) as Node<"vec4">;
813
+ return key === "dirt"
814
+ ? vec4(sampled.rgb.mul(vec3(0.7, 0.58, 0.42)), sampled.a)
815
+ : key === "moss"
816
+ ? vec4(sampled.rgb.mul(vec3(1.08, 1.07, 0.65)), sampled.a)
817
+ : sampled;
818
+ }
819
+ const walls =
820
+ key === "rock" ? vec4(stoneAlbedo(diffuse, biome), 1) : triplanarAlbedo(diffuse, key);
821
+ const blended = key === "rock" ? walls : mix(walls, flat, planarShare);
822
+ if (key === "snow" && biome) return vec4(blended.rgb.mul(vec3(...biome.snowTint)), blended.a);
823
+ // The wet band, applied to the sand only. It belongs here rather than in the layer blend below
824
+ // because it is a *height* fact about the water's last reach, not a weight another surface has.
825
+ if (key === "rock") {
826
+ const stone = stoneColor(blended.rgb, biome);
827
+ // Resolved stone underfoot; broad weathering once the photograph's repeats become visible.
828
+ const weathering = bakedFractalNoise(positionWorld.mul(vec3(0.005, 0.011, 0.005)), 2)
829
+ .mul(0.18)
830
+ .add(1);
831
+ const large = triplanarAlbedo(diffuse, key, 16).rgb;
832
+ const massif = look.crestRock
833
+ ? alpineRockColor(large)
834
+ : look.mesaRock
835
+ ? desertRockColor(large)
836
+ : large.mul(vec3(...look.stoneTint));
837
+ const distant = mix(
838
+ vec3(...(look.groundDistantStone ?? look.distantStone)),
839
+ massif,
840
+ 0.65,
841
+ ).mul(weathering);
842
+ return vec4(
843
+ mix(stone, distant, smoothstep(35, 220, positionView.length()).mul(look.distantStoneShare)),
844
+ blended.a,
845
+ );
846
+ }
847
+ if (key !== "sand" || data.waterLevel === null) return blended;
848
+ const wet = wetness();
849
+ const wrack = otherBiome
850
+ ? float(0)
851
+ : oneMinus(
852
+ smoothstep(
853
+ 0.07,
854
+ 0.21,
855
+ positionWorld.y
856
+ .sub(2.1)
857
+ .sub(bakedNoise(positionWorld.mul(0.05)).mul(0.5))
858
+ .abs(),
859
+ ),
860
+ )
861
+ .mul(smoothstep(-0.1, 0.15, bakedNoise(positionWorld.mul(0.65))))
862
+ // Subpixel wrack fragments read as brown loops from the overview.
863
+ .mul(oneMinus(smoothstep(60, 120, positionView.length())));
864
+ const sandColor = otherBiome
865
+ ? blended.rgb
866
+ : mix(blended.rgb, vec3(dot(blended.rgb, vec3(0.2126, 0.7152, 0.0722))), 0.55).mul(
867
+ vec3(1.95, 1.82, 1.55),
868
+ );
869
+ return vec4(
870
+ sandColor
871
+ .mul(mix(vec3(1), vec3(0.45, 0.37, 0.24), wrack))
872
+ .mul(mix(float(1), otherBiome ? vec3(0.52, 0.5, 0.55) : WET_SAND.darken, wet)),
873
+ blended.a,
874
+ );
875
+ };
876
+
877
+ // The relief takes the same scales as the colour, or the ground keeps its detail underfoot and goes
878
+ // flat past twenty metres.
879
+ const reliefOf = (key: LayerKey, strength: number): IRelief => {
880
+ const source = layer(key).normal;
881
+ if (source === undefined)
882
+ return {
883
+ crevice: float(1),
884
+ tilt: key === "sand" ? sandRipples() : key === "snow" ? microGrain().mul(0.4) : vec3(0),
885
+ };
886
+ if (key === "rock") {
887
+ const walls = { crevice: float(1), tilt: stoneRelief(source, biome) };
888
+ return {
889
+ crevice: walls.crevice,
890
+ tilt: mix(
891
+ walls.tilt.mul(strength),
892
+ triplanarRelief(source, key, 12).tilt.mul(strength * 0.45),
893
+ smoothstep(80, 320, positionView.length()),
894
+ ),
895
+ };
896
+ }
897
+ const near = planarRelief(source, tiledUV(key), strength);
898
+ const coarse = planarRelief(source, tiledUV(key, 2.35), strength * 0.6, -0.73);
899
+ const flat: IRelief = {
900
+ crevice: mix(near.crevice, coarse.crevice, tileBlend),
901
+ tilt: mix(near.tilt, coarse.tilt, tileBlend)
902
+ .add(
903
+ planarRelief(source, tiledUV(key, 0.18), strength * 0.42, -0.73).tilt.mul(
904
+ oneMinus(smoothstep(6, 28, positionView.length())),
905
+ ),
906
+ )
907
+ .mul(mix(1, 0.35, smoothstep(60, 240, positionView.length()))),
908
+ };
909
+ // Rock's strata are metres across, so its wall projection samples at its own tile size; grass and
910
+ // dirt sample at theirs, which is why a cliff's grass fringe keeps the same grain as the meadow.
911
+ const walls = triplanarRelief(source, key);
912
+ const blended: IRelief = {
913
+ crevice: mix(walls.crevice, flat.crevice, planarShare),
914
+ tilt: mix(walls.tilt.mul(strength), flat.tilt, planarShare),
915
+ };
916
+ // Sand has no normal map at all, so its relief is entirely the ripple field below — and the
917
+ // ripples flatten in the wet band, because wet sand is packed and the sea has ironed them out.
918
+ return key === "sand"
919
+ ? {
920
+ ...blended,
921
+ tilt: blended.tilt.add(sandRipples().mul(float(1).sub(wetness().mul(WET_SAND.calm)))),
922
+ }
923
+ : blended;
924
+ };
925
+
926
+ let snowCover: Node<"float"> = float(0);
927
+ const samples: Partial<Record<LayerKey, { surface: Node<"vec4">; relief: IRelief }>> = {};
928
+ material.addEventListener("dispose", () => {
929
+ for (const source of held) source.dispose();
930
+ });
931
+ try {
932
+ // The cliffs take the rock face (`ROCKFACE_MAPS`) in place of the rock layer's own maps.
933
+ const rockPaths = otherBiome ? biome.maps.rock : ROCKFACE_MAPS;
934
+ if (!otherBiome) {
935
+ const diffuse = await get(assets, rockPaths.diffuse, false);
936
+ if (diffuse) {
937
+ held.add(diffuse);
938
+ const normal = rockPaths.normal ? await get(assets, rockPaths.normal, true) : undefined;
939
+ if (normal) held.add(normal);
940
+ maps.rock = { diffuse, normal };
941
+ }
942
+ }
943
+ return (await loadTerrainSplat({
944
+ assets,
945
+ url: `world/${biome?.world ?? WORLD}.world.json`,
946
+ layerSample: ({ layer: descriptor, diffuse, normal: normalMap }) => {
947
+ const key = descriptor.id as LayerKey;
948
+ maps[key] ??= { diffuse, normal: normalMap };
949
+ const surface = albedoOf(key);
950
+ const relief = reliefOf(
951
+ key,
952
+ key === "grass" ? 0.38 : key === "rock" ? 0.52 : key === "snow" ? 0.18 : 0.32,
953
+ );
954
+ samples[key] = { surface, relief };
955
+ if (key !== "grass") return { color: surface.rgb, normal: relief.tilt };
956
+ let normal = relief.tilt
957
+ .mul(weights.grass)
958
+ .mul(look.crestTurf ? mix(1, 0.05, smoothstep(45, 130, positionView.length())) : 1)
959
+ .add(microGrain().mul(oneMinus(smoothstep(12, 60, positionView.length()))));
960
+ if (look.sandRipples) normal = normal.add(sandRipples(vec2(0.53, 0.85)).mul(weights.grass));
961
+ const turf = groundTurf(surface.rgb, biome, hollow, open);
962
+ // Open turf in the wood takes the row's `turfTint`; under the crowns the needle litter
963
+ // (`FOREST_FLOOR`) already owns the tone, so the tint fades out with the canopy.
964
+ return {
965
+ color: look.woodedGround
966
+ ? turf.mul(mix(LOOK.turf, vec3(1), smoothstep(0, 0.6, canopyCover())))
967
+ : turf,
968
+ normal,
969
+ };
970
+ },
971
+ // Geometry, transport and curvature choose placement; the packaged masks remain authored data.
972
+ layerWeight: (_masked, { layer: descriptor }) => {
973
+ const key = descriptor.id as LayerKey;
974
+ const weight = weights[key];
975
+ const sample = samples[key];
976
+ if (!sample) throw new RangeError(`Ground layer '${key}' was not sampled`);
977
+ const { surface, relief } = sample;
978
+ // No displacement maps in these starter sets: normal relief breaks the blend edge,
979
+ // while slope, elevation and curvature determine which surface belongs here.
980
+ const reliefHeight = relief.crevice.sub(0.8).mul(0.12).add(breakUp.mul(0.045));
981
+ // The photograph's relief and metre-scale breakup cut pockets into the soil/rock boundary.
982
+ const rockHeight = dot(surface.rgb, vec3(0.2126, 0.7152, 0.0722))
983
+ .sub(0.1)
984
+ .mul(0.7)
985
+ .add(bakedNoise(positionWorld.mul(0.65)).mul(0.16));
986
+ const over =
987
+ key === "snow" && otherBiome
988
+ ? weight.mul(float(1).add(breakUp.mul(0.025))).clamp(0, 1)
989
+ : key === "rock"
990
+ ? smoothstep(0.34, 0.51, weight.add(rockHeight))
991
+ : smoothstep(0.12, 0.82, weight.add(reliefHeight));
992
+ if (key === "snow") snowCover = over;
993
+ return over;
994
+ },
995
+ materialFactory: ({ color, normal }) => {
996
+ const albedo = vec4(color, 1);
997
+ // Concavity occludes sky bounce, leaving direct sunlight physically separate; the
998
+ // horizon the surrounding relief makes (`skyVisibility`) shades valleys and gorges too.
999
+ material.aoNode = mix(float(1), float(0.88), smoothstep(0.2, 0.85, hollow)).mul(skyShare());
1000
+
1001
+ // 50–200 metre vegetation tones survive texture mipmapping in the overview.
1002
+ const dryness = otherBiome
1003
+ ? smoothstep(
1004
+ -0.18,
1005
+ 0.22,
1006
+ bakedFractalNoise(positionWorld.mul(0.006), 3)
1007
+ .sub(hollow.mul(0.16))
1008
+ .add(alpine.mul(0.06)),
1009
+ )
1010
+ : max(deposits.mul(0.7), drainage.mul(smoothstep(0.015, 0.12, slope)).mul(0.4));
1011
+ const tone = otherBiome
1012
+ ? mix(vec3(0.92, 0.94, 0.91), vec3(1.08, 1.03, 0.95), dryness)
1013
+ : mix(vec3(0.9, 0.95, 0.84), vec3(1.03, 1.04, 0.95), dryness);
1014
+ const vegetation = oneMinus(max(max(weights.rock, weights.snow), weights.sand));
1015
+ // Past the square the forest's hills are its wooded lower slopes: seen from 150 m and more
1016
+ // they take the backdrop's spruce cover from 40 m inside the edge, while the meadow under the
1017
+ // player's feet keeps the playable ground's own turf.
1018
+ // A tundra's own turf runs on past the edge, so its square keeps its ground to the edge too.
1019
+ const continuation =
1020
+ !otherBiome && !look.surveyedBackdrop && !look.turf
1021
+ ? max(
1022
+ smoothstep(data.size / 2 + 60, data.size / 2 + 280, outside),
1023
+ smoothstep(data.size / 2 - 40, data.size / 2 + 20, outside).mul(
1024
+ smoothstep(150, 350, positionView.length()),
1025
+ ),
1026
+ )
1027
+ : smoothstep(data.size / 2 + 60, data.size / 2 + 280, outside);
1028
+ const strata = bakedFractalNoise(positionWorld.mul(vec3(0.018, 0.035, 0.018)), 3);
1029
+ // The forest's backdrop is alpine (owner goal 2026-11-04); the coast keeps its survey's look.
1030
+ const crestBackdrop = !look.surveyedBackdrop;
1031
+ // Where the collar mesh blends to its prefiltered field (300 m past the edge and on), its
1032
+ // shading reads the unfiltered survey instead; the vista's near meadow keeps the mesh.
1033
+ const reliefWeight = collar
1034
+ ? smoothstep(data.size / 2 + 300, data.size / 2 + 600, outside)
1035
+ : float(0);
1036
+ const surveyedNormal = collar
1037
+ ? normalize(mix(normalWorldGeometry, collar.normal, reliefWeight))
1038
+ : normalWorldGeometry;
1039
+ const crestSteep = collar
1040
+ ? clamp(oneMinus(surveyedNormal.y.abs()).add(breakUp.mul(0.05)), 0, 1)
1041
+ : steep;
1042
+ // Talus at the feet of cliff bands: the same rock, finer and paler.
1043
+ const scree = collar ? collar.scree.mul(reliefWeight) : float(0);
1044
+ // Bedding: strata on the steep rock, each a cliff under a ledge, as the goal frame's faces
1045
+ // break into bands (owner, 2026-11-04). Real beds dip about 20 degrees, thin and thicken, and
1046
+ // break along the strike; level, evenly spaced, unbroken rings read as artificial contour
1047
+ // lines (owner, 2026-11-07). The phase is antialiased by its own screen derivative, so a band
1048
+ // thinner than a pixel greys out instead of crawling. No noise feeds back into its own domain:
1049
+ // that warp curled the beds into marbled swirls (owner, 2026-11-09); beds bend only gently.
1050
+ const dipped = positionWorld.y
1051
+ .add(positionWorld.x.mul(0.3))
1052
+ .sub(positionWorld.z.mul(0.18))
1053
+ .add(bakedFractalNoise(positionWorld.mul(0.004), 2).mul(20));
1054
+ const bedding = dipped.div(34);
1055
+ const phase = fract(bedding);
1056
+ const blur = fwidth(bedding).min(0.25);
1057
+ const ledge = smoothstep(float(0.8).sub(blur), float(0.88).add(blur), phase).mul(
1058
+ oneMinus(smoothstep(float(0.95).sub(blur), float(1).add(blur), phase)),
1059
+ );
1060
+ const wall = smoothstep(float(0.08).sub(blur), float(0.2).add(blur), phase).mul(
1061
+ oneMinus(smoothstep(float(0.66).sub(blur), float(0.8).add(blur), phase)),
1062
+ );
1063
+ // A bed runs a few hundred metres along the face and pinches out under scree and couloirs.
1064
+ const runs = smoothstep(
1065
+ -0.05,
1066
+ 0.3,
1067
+ bakedFractalNoise(positionWorld.mul(vec3(0.006, 0.03, 0.006)), 2),
1068
+ );
1069
+ // Not every face is bedded: kilometre patches carry bands, the rest stays massive rock.
1070
+ const bedded = collar
1071
+ ? smoothstep(-0.15, 0.25, bakedFractalNoise(positionWorld.mul(0.0018), 2))
1072
+ .mul(runs)
1073
+ .mul(reliefWeight)
1074
+ : float(0);
1075
+ // Crag ribs that the prefiltered 10 m backdrop mesh cannot carry: 35 m across and 90 m down
1076
+ // the fall line, as couloirs and buttresses run. Their gradient tilts the normal and their
1077
+ // creases darken the rock, so cliff bands read at two kilometres.
1078
+ // The forest's massif (the only lawn world with a crest backdrop) takes three scales instead:
1079
+ // 350, 120 and 41 m across, each 2.3 times longer down the fall line, as a 110 m relief whose
1080
+ // every octave tilts the face by the same angle, so spurs and couloirs catch the low sun at
1081
+ // every range.
1082
+ const massif = !otherBiome && crestBackdrop;
1083
+ const facetAt = (x: number, y: number, z: number) =>
1084
+ massif
1085
+ ? bakedFractalNoise(
1086
+ positionWorld.add(vec3(x, y, z)).mul(vec3(1 / 350, 1 / 800, 1 / 350)),
1087
+ 3,
1088
+ 2.9,
1089
+ 0.33,
1090
+ )
1091
+ : bakedFractalNoise(positionWorld.add(vec3(x, y, z)).mul(vec3(0.028, 0.011, 0.028)), 2);
1092
+ const facet = facetAt(0, 0, 0);
1093
+ const facetTilt = vec3(
1094
+ facet.sub(facetAt(6, 0, 0)),
1095
+ facet.sub(facetAt(0, 6, 0)),
1096
+ facet.sub(facetAt(0, 0, 6)),
1097
+ ).mul(massif ? 110 / 6 : 1.4);
1098
+ // Reuse the resident maps at massif scale: steep faces project onto their own axes.
1099
+ const turf = triplanarAlbedo(layer("grass").diffuse, "grass", 12).rgb;
1100
+ // The forest's lower slopes are a closed spruce cover drawn by material alone: 11 m crowns
1101
+ // with dark gaps, denser and sparser stands, darker in the hollows, opened by kilometre meadow clearings.
1102
+ // Past 1 km a crown is a few pixels: its contrast fades, so the cover does not scale over.
1103
+ // One baked read repeats every 8 noise units (88 m at this scale) and drew a checker under the
1104
+ // fog; a second read on a lattice turned 37 degrees and 1.53 times finer breaks the period.
1105
+ const crownField = bakedNoise(positionWorld.div(11))
1106
+ .add(
1107
+ bakedNoise(
1108
+ vec3(
1109
+ positionWorld.x.mul(0.8).add(positionWorld.z.mul(0.6)),
1110
+ positionWorld.y,
1111
+ positionWorld.z.mul(0.8).sub(positionWorld.x.mul(0.6)),
1112
+ ).div(7.2),
1113
+ 1,
1114
+ 0,
1115
+ 2,
1116
+ ),
1117
+ )
1118
+ .mul(0.7);
1119
+ const crowns = mix(
1120
+ smoothstep(-0.3, 0.35, crownField),
1121
+ float(0.55),
1122
+ smoothstep(400, 1200, positionView.length()).mul(0.8),
1123
+ );
1124
+ const clumps = bakedFractalNoise(positionWorld.div(160), 2);
1125
+ const clearings = smoothstep(
1126
+ 0.28,
1127
+ 0.5,
1128
+ bakedFractalNoise(positionWorld.mul(0.008), 2).sub(crestSteep.mul(0.4)),
1129
+ );
1130
+ const cover = mix(
1131
+ BACKDROP_SPRUCE.mul(mix(0.4, 1.3, crowns))
1132
+ .mul(clumps.mul(0.15).add(1))
1133
+ .mul(
1134
+ mix(float(1), float(0.7), collar ? smoothstep(0.1, 0.5, collar.hollow) : float(0)),
1135
+ ),
1136
+ BACKDROP_CLEARING.mul(mix(0.85, 1.1, crowns)),
1137
+ clearings,
1138
+ );
1139
+ // The coast's surveyed backdrop is an open lawn.
1140
+ const forest = crestBackdrop
1141
+ ? cover
1142
+ : turf.mul(MEADOW).mul(mix(0.5, 0.85, breakUp.add(0.5)));
1143
+ // The massif reads at 1-3 km: the rock map tiles at 60 m and 220 m, blended by kilometre
1144
+ // noise, so no face repeats or smears at that range. Unwarped: the ground's 40 m UV warp
1145
+ // swirled a tile this large into marble. The scan is a red-brown boulder; under blue air it
1146
+ // read magenta, so the massif takes its luminance only.
1147
+ const rockAxis = abs(normalWorldGeometry).pow(4);
1148
+ const rockShare = rockAxis.div(rockAxis.x.add(rockAxis.y).add(rockAxis.z));
1149
+ const massifTap = (source: Texture, size: number, offset: number): Node<"vec3"> =>
1150
+ rockShare.x
1151
+ .mul(texture(source, positionWorld.zy.div(size).add(offset)).rgb)
1152
+ .add(rockShare.y.mul(texture(source, positionWorld.xz.div(size).add(offset)).rgb))
1153
+ .add(rockShare.z.mul(texture(source, positionWorld.xy.div(size).add(offset)).rgb));
1154
+ const massifRock = mix(
1155
+ massifTap(layer("rock").diffuse, 60, 0),
1156
+ massifTap(layer("rock").diffuse, 220, 0.37),
1157
+ smoothstep(-0.3, 0.3, bakedNoise(positionWorld.mul(0.0021))),
1158
+ );
1159
+ const crag = (
1160
+ look.surveyedBackdrop
1161
+ ? triplanarAlbedo(layer("rock").diffuse, "rock", 6).rgb
1162
+ : // At half its contrast the scan's boulder seams stop drawing a crack net over the faces.
1163
+ vec3(
1164
+ dot(massifRock, vec3(0.2126, 0.7152, 0.0722))
1165
+ .sub(0.07)
1166
+ .mul(0.5)
1167
+ .add(0.07),
1168
+ )
1169
+ .mul(vec3(0.93, 0.99, 1.04))
1170
+ .mul(LOOK.rock)
1171
+ )
1172
+ .mul(crestBackdrop ? vec3(0.62) : vec3(0.62, 0.66, 0.67))
1173
+ .mul(strata.mul(crestBackdrop ? 0.15 : 0.35).add(1))
1174
+ .mul(crestBackdrop ? mix(0.6, 1.15, smoothstep(-0.4, 0.4, facet)) : float(1))
1175
+ // Kilometre-scale warm and cool rock, so whole faces do not read one flat grey.
1176
+ .mul(
1177
+ crestBackdrop
1178
+ ? mix(
1179
+ vec3(0.95, 0.98, 1.03),
1180
+ vec3(1.05, 1.02, 0.97),
1181
+ smoothstep(-0.3, 0.3, bakedFractalNoise(positionWorld.mul(0.0025), 2)),
1182
+ )
1183
+ : vec3(1),
1184
+ );
1185
+ // Runoff and lichen stain steep rock in streaks down the fall line, metres wide and tens long.
1186
+ const streaks = smoothstep(
1187
+ -0.35,
1188
+ 0.35,
1189
+ bakedFractalNoise(positionWorld.mul(vec3(0.045, 0.006, 0.045)), 3),
1190
+ );
1191
+ const talus = triplanarAlbedo(layer("rock").diffuse, "rock", 1.2).rgb;
1192
+ const rubble = (
1193
+ crestBackdrop
1194
+ ? vec3(dot(talus, vec3(0.2126, 0.7152, 0.0722))).mul(vec3(0.66, 0.67, 0.69))
1195
+ : talus.mul(vec3(0.66, 0.65, 0.62))
1196
+ ).mul(mix(0.85, 1.1, bakedNoise(positionWorld.mul(0.08)).add(0.5)));
1197
+ // A ragged treeline: spurs of forest climb 90 m higher or stop 90 m lower along the slope.
1198
+ const treeline = elevationBand(
1199
+ measured,
1200
+ measured.heightBands.treeline,
1201
+ positionWorld.y
1202
+ .add(breakUp.mul(24))
1203
+ .add(crestBackdrop ? bakedFractalNoise(positionWorld.mul(0.006), 2).mul(90) : float(0)),
1204
+ );
1205
+ // Rock from about 31 degrees. The wood's spruce stands to 36-46 degrees (its far-forest slope
1206
+ // row), so its cover holds to there: at 31 a surveyed massif's wooded flanks drew bare rock.
1207
+ const face = look.woodedGround
1208
+ ? smoothstep(0.19, 0.31, crestSteep.add(strata.mul(0.055)))
1209
+ : smoothstep(0.14, 0.3, crestSteep.add(strata.mul(0.055)));
1210
+ const bands = bedded.mul(face);
1211
+ const snowline = elevationBand(
1212
+ measured,
1213
+ measured.heightBands.cap,
1214
+ positionWorld.y.add(breakUp.mul(28)),
1215
+ );
1216
+ // Snow fields, not ledge lines (owner, 2026-11-09): full cover above the snowline on faces
1217
+ // that point up, tongues 160 m further down the gullies, broken patches 150 m under the
1218
+ // line, and none on wall rock. The facets lift or drop each field's edge, so its rim follows
1219
+ // the ribs instead of a contour.
1220
+ const gully = collar ? smoothstep(0.05, 0.4, collar.hollow).mul(reliefWeight) : float(0);
1221
+ const lying = oneMinus(
1222
+ smoothstep(0.3, 0.48, crestSteep.sub(facet.mul(0.25)).sub(gully.mul(0.1))),
1223
+ );
1224
+ const fields = elevationBand(
1225
+ measured,
1226
+ measured.heightBands.cap,
1227
+ positionWorld.y.add(breakUp.mul(28)).add(gully.mul(160)),
1228
+ ).mul(oneMinus(smoothstep(-0.25, -0.45, bakedFractalNoise(positionWorld.mul(0.006), 2))));
1229
+ const patches = smoothstep(
1230
+ measured.heightBands.cap[0] - 150,
1231
+ measured.heightBands.cap[0] - 20,
1232
+ positionWorld.y.add(breakUp.mul(28)),
1233
+ ).mul(
1234
+ smoothstep(
1235
+ 0.12,
1236
+ 0.3,
1237
+ bakedFractalNoise(positionWorld.mul(0.011), 2).add(gully.mul(0.35)).add(facet.mul(0.2)),
1238
+ ),
1239
+ );
1240
+ const cap = crestBackdrop
1241
+ ? fields.max(patches).mul(lying)
1242
+ : snowline.mul(oneMinus(smoothstep(0.18, 0.42, steep)));
1243
+ // The massif's snow is unwarped too: the ground's UV warp at a 96 m tile swirled it.
1244
+ const snow = crestBackdrop
1245
+ ? massifTap(layer("snow").diffuse, 60, 0.21)
1246
+ : triplanarAlbedo(layer("snow").diffuse, "snow", 8).rgb;
1247
+ // Each band is a darker wall under a paler ledge.
1248
+ const banded = crag
1249
+ .mul(mix(float(1), mix(float(1.08), float(0.8), wall), bands))
1250
+ .mul(mix(float(1), mix(float(0.78), float(1.04), streaks), face));
1251
+ const bare = mix(banded, rubble, scree);
1252
+ // A tundra's ring is turf above its tree line, fellfield rubble towards the summits, and rock
1253
+ // only on faces and scree; a massif's is bare rock from the tree line up.
1254
+ const tundraTurf = look.turf
1255
+ ? mix(
1256
+ mix(
1257
+ vec3(...look.turf.field[0]),
1258
+ vec3(...look.turf.field[1]),
1259
+ smoothstep(-0.3, 0.3, bakedFractalNoise(positionWorld.mul(0.004), 2)),
1260
+ ),
1261
+ rubble.mul(0.55),
1262
+ elevationBand(
1263
+ measured,
1264
+ [measured.heightBands.cap[0] - 240, measured.heightBands.cap[0] - 40],
1265
+ positionWorld.y.add(breakUp.mul(28)),
1266
+ ).mul(0.75),
1267
+ )
1268
+ : undefined;
1269
+ const mountain = mix(
1270
+ tundraTurf
1271
+ ? mix(mix(forest, tundraTurf, treeline), bare, max(face, scree))
1272
+ : mix(forest, bare, max(max(treeline, face), scree)),
1273
+ snow,
1274
+ cap,
1275
+ );
1276
+ material.colorNode = mix(
1277
+ albedo.rgb.mul(mix(vec3(1), tone, vegetation)),
1278
+ otherBiome ? albedo.rgb : mountain,
1279
+ continuation,
1280
+ )
1281
+ .mul(mix(vec3(1), vec3(0.42, 0.46, 0.42), curvature.wetBank))
1282
+ .mul(mix(vec3(1), FOREST_FLOOR, forestFloor))
1283
+ .mul(mix(vec3(1), BARE_SOIL, bareSoil));
1284
+ material.roughnessNode = mix(
1285
+ mix(
1286
+ otherBiome ? 0.94 : mix(0.88, 0.98, dryness),
1287
+ float(0.91).sub(
1288
+ smoothstep(0.48, 0.68, bakedNoise(positionWorld.mul(60)))
1289
+ .mul(oneMinus(smoothstep(3, 14, positionView.length())))
1290
+ .mul(0.5),
1291
+ ),
1292
+ snowCover,
1293
+ ),
1294
+ 0.48,
1295
+ curvature.wetBank,
1296
+ );
1297
+ if (!otherBiome) {
1298
+ material.roughnessNode = mix(
1299
+ material.roughnessNode as Node<"float">,
1300
+ 0.52,
1301
+ sand.mul(wetness()),
1302
+ );
1303
+ // A little albedo-coloured bounce keeps unlit rock faces legible without changing the sky rig.
1304
+ material.emissiveNode = (material.colorNode as Node<"vec3">).mul(
1305
+ weights.rock.max(continuation).mul(0.08),
1306
+ );
1307
+ }
1308
+ // Distant faces resolve broad rock strata, rather than subpixel meadow normals.
1309
+ const rockNormal = layer("rock").normal;
1310
+ // The forest's massif takes its relief from the facets alone: the rock normal map reads
1311
+ // through the ground's UV warp, which at a 30 m tile drew curled lines over every face.
1312
+ const mountainTilt = (
1313
+ rockNormal === undefined || massif
1314
+ ? vec3(0)
1315
+ : triplanarRelief(rockNormal, "rock", 8).tilt.mul(face).mul(oneMinus(cap)).mul(0.32)
1316
+ ).add(
1317
+ crestBackdrop
1318
+ ? facetTilt
1319
+ // Turf above a tundra's tree line keeps its soft relief; only faces take the crags.
1320
+ .mul(mix(0.35, 1, look.turf ? face : max(treeline, face)))
1321
+ .mul(oneMinus(cap.mul(0.6)))
1322
+ : vec3(0),
1323
+ );
1324
+ // Distant alpine rock previously discarded all normal relief; snow weights stay unchanged.
1325
+ const distantTilt = look.crestRock ? mountainTilt.mul(weights.rock) : mountainTilt;
1326
+ const tilt = look.continuationTilt ? mix(normal, distantTilt, continuation) : normal;
1327
+ // Detail is tangential; it must not rotate the whole hillside towards a fixed diagonal.
1328
+ const outward = normalize(
1329
+ vec3(surveyedNormal.x, 0, surveyedNormal.z).add(vec3(0.0001, 0, 0)),
1330
+ );
1331
+ const bandTilt = vec3(0, 1, 0)
1332
+ .sub(surveyedNormal)
1333
+ .mul(ledge.mul(0.7))
1334
+ .add(outward.sub(surveyedNormal).mul(wall.mul(0.35)))
1335
+ .mul(bands);
1336
+ const detail = tilt
1337
+ .add(bandTilt)
1338
+ .sub(surveyedNormal.mul(dot(surveyedNormal, tilt.add(bandTilt))));
1339
+ // A bump cannot light a face its own slope turns from the sun: the face's relief would
1340
+ // self-shadow it. Without this the low sun lit the massif's shaded walls in soft, cloud-like
1341
+ // wisps wherever the relief tilted toward it (owner, 2026-11-09). In shade the relief still
1342
+ // turns the face to more or less sky.
1343
+ const tangent = massif
1344
+ ? detail.sub(
1345
+ SUN_VECTOR.mul(
1346
+ max(dot(detail, SUN_VECTOR), 0)
1347
+ .mul(oneMinus(smoothstep(-0.05, 0.25, dot(surveyedNormal, SUN_VECTOR))))
1348
+ .mul(continuation),
1349
+ ),
1350
+ )
1351
+ : detail;
1352
+ const crystals = microGrain()
1353
+ .mul(snowCover)
1354
+ .mul(oneMinus(smoothstep(4, 22, positionView.length())));
1355
+ material.normalNode = transformNormalToView(
1356
+ normalize(surveyedNormal.add(tangent).add(crystals)),
1357
+ );
1358
+ return material;
1359
+ },
1360
+ })) as MeshStandardNodeMaterial;
1361
+ } catch (error) {
1362
+ material.dispose();
1363
+ throw error;
1364
+ }
1365
+ }
1366
+
1367
+ /**
1368
+ * The baked heightfield, its geometry, and the lit ground material once the PBR maps arrive.
1369
+ *
1370
+ * `enter` is synchronous and the physics collider is built from this very mesh, so the mesh exists
1371
+ * immediately and draws with flat vertex colours until the textures settle. A map that never loads
1372
+ * keeps that fallback rather than failing the world: the terrain still has to collide on a host
1373
+ * with no asset server.
1374
+ */
1375
+ /**
1376
+ * The square around the player that streamed tiles draw (PRD-790): centre and half-width in metres.
1377
+ * The collar draws everywhere outside it, and the tiles draw only inside it and past the playable
1378
+ * square, so each point of ground is drawn once.
1379
+ */
1380
+ export interface ITerrainStream {
1381
+ readonly centre: UniformNode<"vec2", Vector2>;
1382
+ readonly half: UniformNode<"float", number>;
1383
+ /** Receives the tiles' own ground material once the square's ground is in place. */
1384
+ readonly tiles: (material: MeshStandardNodeMaterial) => void;
1385
+ }
1386
+
1387
+ export function createTerrain(
1388
+ data: IBakedWorld,
1389
+ assets?: IAssetLoader,
1390
+ biome?: IBiome,
1391
+ /** The baked `skyVisibility` per vertex; without it the ground keeps the whole sky. */
1392
+ sky?: Float32Array,
1393
+ stream?: ITerrainStream,
1394
+ ): { collar: HeightfieldCollar; field: Heightfield; mesh: Mesh } {
1395
+ const field = new Heightfield({
1396
+ rows: data.resolution,
1397
+ columns: data.resolution,
1398
+ width: data.size,
1399
+ depth: data.size,
1400
+ origin: { x: 0, z: 0 },
1401
+ heights: new Float32Array(data.heights),
1402
+ });
1403
+ const geometry = field.toGeometry();
1404
+ if (data.colors.length !== geometry.getAttribute("position").count * 3)
1405
+ throw new RangeError("Baked terrain colours do not match the heightfield");
1406
+ geometry.setAttribute("color", new Float32BufferAttribute(data.colors, 3));
1407
+ // Crown cover per vertex, painted from the scattered trees by `paintCanopy`; zero until then.
1408
+ geometry.setAttribute(
1409
+ "canopy",
1410
+ new Float32BufferAttribute(new Float32Array(geometry.getAttribute("position").count), 1),
1411
+ );
1412
+ // The share of the sky each vertex sees past the relief around it, for the ground's ambient term.
1413
+ const vertices = geometry.getAttribute("position").count;
1414
+ if (sky && sky.length !== vertices)
1415
+ throw new RangeError(`Baked sky visibility has ${sky.length} values for ${vertices} vertices`);
1416
+ geometry.setAttribute(
1417
+ "sky",
1418
+ new Float32BufferAttribute(sky ?? new Float32Array(vertices).fill(1), 1),
1419
+ );
1420
+ const material = new MeshStandardMaterial({ vertexColors: true, roughness: 0.95 });
1421
+ const mesh: Mesh = new Mesh(geometry, material);
1422
+ mesh.name = "authored-terrain";
1423
+ // The ground is under everything and its material is the frame's dearest: drawn in sort order it
1424
+ // shaded every pixel a crown or a blade then covered. After the props, the depth test rejects those
1425
+ // first (forest player pose, RTX 2080, 913x881: 13.6 ms of GPU with the ground in sort order, 8.9 ms
1426
+ // after the props). The water keeps its place after the ground at render order 2.
1427
+ mesh.renderOrder = GROUND_RENDER_ORDER;
1428
+ mesh.layers.enable(REFLECTED_LAYER);
1429
+ mesh.receiveShadow = true;
1430
+ mesh.castShadow = biome?.terrainCastsShadow ?? false;
1431
+ const collar = createHorizonCollar(data, WORLD);
1432
+ const horizonGeometry = collar.geometry;
1433
+ horizonGeometry.setAttribute("color", new Float32BufferAttribute(collarColors(collar, data), 3));
1434
+ horizonGeometry.computeVertexNormals();
1435
+ const edgePositions = horizonGeometry.getAttribute("position");
1436
+ const edgeNormals = horizonGeometry.getAttribute("normal");
1437
+ const groundNormals = geometry.getAttribute("normal");
1438
+ let horizonSeamGap = 0;
1439
+ for (let vertex = 0; vertex < (data.resolution - 1) * 4; vertex++) {
1440
+ const column = Math.round(
1441
+ (edgePositions.getX(vertex) / data.size + 0.5) * (data.resolution - 1),
1442
+ );
1443
+ const row = Math.round((edgePositions.getZ(vertex) / data.size + 0.5) * (data.resolution - 1));
1444
+ const edge = row * data.resolution + column;
1445
+ horizonSeamGap = Math.max(
1446
+ horizonSeamGap,
1447
+ Math.abs(edgePositions.getY(vertex) - (data.heights[edge] as number)),
1448
+ );
1449
+ edgeNormals.setXYZ(
1450
+ vertex,
1451
+ groundNormals.getX(edge),
1452
+ groundNormals.getY(edge),
1453
+ groundNormals.getZ(edge),
1454
+ );
1455
+ }
1456
+ // The snow and mat masks read normals: blend the collar too, rather than only its boundary
1457
+ // vertices, and reach as far past the square as those masks do.
1458
+ const collarBand = biome?.groundCollarMeters ?? 0;
1459
+ if (collarBand > 0) {
1460
+ const perimeter = (data.resolution - 1) * 4;
1461
+ const normal = new Vector3();
1462
+ const boundary = new Vector3();
1463
+ for (let vertex = perimeter; vertex < edgePositions.count; vertex++) {
1464
+ const distance =
1465
+ Math.max(Math.abs(edgePositions.getX(vertex)), Math.abs(edgePositions.getZ(vertex))) -
1466
+ data.size / 2;
1467
+ if (distance >= collarBand) break;
1468
+ normal
1469
+ .fromBufferAttribute(edgeNormals, vertex)
1470
+ .lerp(
1471
+ boundary.fromBufferAttribute(edgeNormals, vertex % perimeter),
1472
+ 1 - MathUtils.smoothstep(distance, 0, collarBand),
1473
+ )
1474
+ .normalize();
1475
+ edgeNormals.setXYZ(vertex, normal.x, normal.y, normal.z);
1476
+ }
1477
+ }
1478
+ mesh.userData.horizonSeamGap = horizonSeamGap;
1479
+ mesh.userData.horizonSeamSamples = (data.resolution - 1) * 4;
1480
+ horizonGeometry.setAttribute(
1481
+ "canopy",
1482
+ new Float32BufferAttribute(new Float32Array(edgePositions.count), 1),
1483
+ );
1484
+ // The ground material reads `sky` too; the collar lies past the baked square and keeps the sky.
1485
+ horizonGeometry.setAttribute(
1486
+ "sky",
1487
+ new Float32BufferAttribute(new Float32Array(edgePositions.count).fill(1), 1),
1488
+ );
1489
+ const horizon: Mesh = new Mesh(horizonGeometry, material);
1490
+ horizon.name = "temperate-distant-ridges";
1491
+ horizon.renderOrder = GROUND_RENDER_ORDER;
1492
+ horizon.layers.enable(REFLECTED_LAYER);
1493
+ horizon.receiveShadow = true;
1494
+ // Scenery beyond the collider: no ray stands on it, and a picking tree over its 1.5M triangles
1495
+ // cost the first ground contact 1.1 s, which landed on the first rendered frame.
1496
+ horizon.raycast = () => undefined;
1497
+ mesh.add(horizon);
1498
+ geometry.addEventListener("dispose", () => horizon.geometry.dispose());
1499
+
1500
+ const curvature = buildCurvature(data, field, biome);
1501
+ let disposed = false;
1502
+ geometry.addEventListener("dispose", () => {
1503
+ disposed = true;
1504
+ });
1505
+ if (assets !== undefined)
1506
+ void Promise.all([
1507
+ createGroundMaterial(data, assets, curvature, biome),
1508
+ stream ? createGroundMaterial(data, assets, curvature, biome, true) : undefined,
1509
+ ])
1510
+ .then(([ground, tile]) => {
1511
+ // Anything but the flat placeholder means the scene already moved on; a material nothing
1512
+ // draws holds GPU memory until its textures are released.
1513
+ if (disposed || mesh.material !== material) {
1514
+ tile?.dispose();
1515
+ return ground.dispose();
1516
+ }
1517
+ mesh.material = ground;
1518
+ horizon.material = ground;
1519
+ material.dispose();
1520
+ const surfaces = [ground];
1521
+ if (stream && tile) {
1522
+ // Chebyshev distance from the streamed square's centre, against its half-width.
1523
+ const fromCentre = max(
1524
+ abs(positionWorld.x.sub(stream.centre.x)),
1525
+ abs(positionWorld.z.sub(stream.centre.y)),
1526
+ );
1527
+ const far = ground.clone();
1528
+ // The collar draws under the block's edge too: the depth test picks the nearer surface there.
1529
+ far.maskNode = fromCentre.greaterThanEqual(stream.half.sub(COLLAR_UNDER_TILE));
1530
+ horizon.material = far;
1531
+ // The outermost streamed tile slides onto the collar's drawn height (PRD-790 box 2).
1532
+ tile.positionNode = collarMorph(collar, COLLAR_CURVE, stream, STREAM_TILE);
1533
+ tile.maskNode = fromCentre
1534
+ .lessThan(stream.half)
1535
+ // The skirt each tile hangs on the square's edge draws too, under the square's cracks.
1536
+ .and(
1537
+ max(abs(positionWorld.x), abs(positionWorld.z)).greaterThan(
1538
+ data.size / 2 - TILE_INSIDE_SQUARE,
1539
+ ),
1540
+ );
1541
+ surfaces.push(far, tile);
1542
+ geometry.addEventListener("dispose", () => far.dispose());
1543
+ stream.tiles(tile);
1544
+ }
1545
+ // The ground took no image-based light, so terrain in shadow fell to near-black while every
1546
+ // plant on it read the sky. It reads the same clamped sky the vegetation does.
1547
+ if (biome === undefined || biome.lawnGround)
1548
+ void loadSkyLight(assets).then((sky) => {
1549
+ if (!sky || mesh.material !== ground || !ground.colorNode) return;
1550
+ // An envMap would be the ground's 17th sampler; the diffuse sky it carries is two colours.
1551
+ const { up, down } = skyIrradiance(sky);
1552
+ for (const surface of surfaces) {
1553
+ surface.emissiveNode = (surface.colorNode as Node<"vec3">)
1554
+ .mul(mix(vec3(...down), vec3(...up), normalWorld.y.mul(0.5).add(0.5)))
1555
+ .mul(GROUND_SKY_LIGHT);
1556
+ surface.needsUpdate = true;
1557
+ }
1558
+ });
1559
+ })
1560
+ // A map that never arrives, or a set this material cannot bind, leaves the ground on its
1561
+ // baked vertex colours. It must still collide and still draw, and the console says why.
1562
+ .catch((error) => {
1563
+ console.warn(`TN_GROUND_MAP_MISSING ${error instanceof Error ? error.message : error}`);
1564
+ // The ground itself is fine — it keeps its baked vertex colours — but the streamed block's
1565
+ // handshake must still land: the spawn gate waits on it, so a missing map would hold a player
1566
+ // behind the cover for the whole deadline. The placeholder draws the tiles until the map does.
1567
+ // The placeholder is a plain material, not a node surface; it is only here to land the join.
1568
+ stream?.tiles(material as unknown as MeshStandardNodeMaterial);
1569
+ });
1570
+ return { collar, field, mesh };
1571
+ }
1572
+
1573
+ /**
1574
+ * Cook the heightfield's own curvature into a texture the ground material can read.
1575
+ *
1576
+ * A five-point Laplacian over the baked samples, evaluated once on the CPU and stored as half floats:
1577
+ * `h(-1) + h(+1) + h(-w) + h(+w) - 4h(0)`, which is positive in a hollow and negative on a rib. The
1578
+ * divisor is the sample spacing squared, so the number is in 1/m and does not change meaning when the
1579
+ * world's resolution does, and the gain is chosen so a valley a few metres deep reads near +1.
1580
+ *
1581
+ * Half float rather than byte because the range matters: a byte would quantise the sign of a
1582
+ * near-flat field into blocks, and the sign is the whole of the answer.
1583
+ *
1584
+ * One curvature binding plus six albedos, four normals and four shadow maps is fifteen.
1585
+ */
1586
+ function buildCurvature(data: IBakedWorld, field: Heightfield, biome?: IBiome): IGroundCurvature {
1587
+ const resolution = data.resolution;
1588
+ const heights = data.heights;
1589
+ const spacing = data.size / (resolution - 1);
1590
+ const at = (row: number, column: number): number =>
1591
+ heights[
1592
+ Math.min(resolution - 1, Math.max(0, row)) * resolution +
1593
+ Math.min(resolution - 1, Math.max(0, column))
1594
+ ] as number;
1595
+ // Wet only as far as the drawn pond reaches (`lakeReach` caps it at the lake's radius): a kettle
1596
+ // in an open pan has a waterline radius across the whole low plain, which darkened 40% of the
1597
+ // tundra's square to a wet bank with no water on it.
1598
+ const lakes = (data.lakes ?? []).map((lake) => ({
1599
+ ...lake,
1600
+ reach: Math.min(waterlineRadius(field, lake.at, lake.level), lake.radius),
1601
+ }));
1602
+ const rivers = (data.rivers ?? []).flatMap((river) => {
1603
+ const levels = surfaceHeights(field, river.points);
1604
+ return river.points.map(([x = 0, , z = 0], index) => ({
1605
+ x,
1606
+ z,
1607
+ level: levels[index] as number,
1608
+ }));
1609
+ });
1610
+ // River stations indexed at their 13 m wet margin. It is this ground shader's own number: the drawn
1611
+ // ribbon sizes itself from `WATER_RIBBON_REACH` in river.ts. A vertex tests only
1612
+ // the stations that can reach it rather than every station of every river.
1613
+ const RIVER_REACH = 13;
1614
+ const stations = createSegmentIndex(
1615
+ rivers.map((station) => ({
1616
+ a: [station.x, station.z] as const,
1617
+ b: [station.x, station.z] as const,
1618
+ reach: RIVER_REACH,
1619
+ data: station,
1620
+ })),
1621
+ RIVER_REACH,
1622
+ );
1623
+ // Both channels share one sampler: measured concavity and the water's actual wet margin.
1624
+ const transport = data.erosion;
1625
+ if (transport) {
1626
+ for (const key of ["flow", "sediment", "deposition", "talus"] as const) {
1627
+ const values = transport[key];
1628
+ if (
1629
+ !Array.isArray(values) ||
1630
+ values.length !== heights.length ||
1631
+ !values.every((value) => Number.isFinite(value) && value >= 0)
1632
+ )
1633
+ throw new RangeError(`Baked erosion '${key}' does not match the canonical heightfield`);
1634
+ }
1635
+ }
1636
+ const sortedFlow = [...(transport?.flow ?? [])].sort((a, b) => a - b);
1637
+ const medianFlow = sortedFlow[Math.floor(sortedFlow.length * 0.5)] ?? 0;
1638
+ const channelFlow = sortedFlow[Math.floor(sortedFlow.length * 0.98)] ?? 1;
1639
+ const pixels = new Uint16Array(resolution * resolution * 4);
1640
+ for (let row = 0; row < resolution; row += 1) {
1641
+ for (let column = 0; column < resolution; column += 1) {
1642
+ const laplacian =
1643
+ at(row, column - 4) +
1644
+ at(row, column + 4) +
1645
+ at(row - 4, column) +
1646
+ at(row + 4, column) -
1647
+ 4 * at(row, column);
1648
+ // An eight-metre neighbourhood picks out channels and hollows, suppressing tiny baked bumps.
1649
+ const vertex = row * resolution + column;
1650
+ const index = vertex * 4;
1651
+ pixels[index] = DataUtils.toHalfFloat(
1652
+ Math.max(-1, Math.min(1, (laplacian / (spacing * spacing * 16)) * 36)),
1653
+ );
1654
+ const x = column * spacing - data.size / 2;
1655
+ const z = row * spacing - data.size / 2;
1656
+ const height = at(row, column);
1657
+ const margin = (level: number): number =>
1658
+ Math.max(0, Math.min(1, (level + 1.1 - height) / 1.1));
1659
+ let wet = 0;
1660
+ for (const lake of lakes) {
1661
+ const distance = Math.hypot(x - (lake.at[0] ?? 0), z - (lake.at[1] ?? 0));
1662
+ if (distance <= lake.reach + 3) wet = Math.max(wet, margin(lake.level));
1663
+ }
1664
+ for (const station of stations.nearby(x, z)) {
1665
+ if (Math.hypot(x - station.x, z - station.z) <= RIVER_REACH)
1666
+ wet = Math.max(wet, margin(station.level));
1667
+ }
1668
+ pixels[index + 1] = DataUtils.toHalfFloat(wet);
1669
+ pixels[index + 2] = DataUtils.toHalfFloat(
1670
+ Math.max(
1671
+ 0,
1672
+ Math.min(
1673
+ 1,
1674
+ ((transport?.flow[vertex] ?? 0) - medianFlow) / Math.max(1, channelFlow - medianFlow),
1675
+ ),
1676
+ ),
1677
+ );
1678
+ // Thermal deposits are actual cliff-foot transport. Hydraulic fines collect where water
1679
+ // carries a load and slows; normalise by carried load to avoid painting every rain visit.
1680
+ pixels[index + 3] = DataUtils.toHalfFloat(depositAtIndex(data, vertex));
1681
+ }
1682
+ }
1683
+ const cooked = new DataTexture(pixels, resolution, resolution, RGBAFormat, HalfFloatType);
1684
+ cooked.minFilter = LinearFilter;
1685
+ cooked.magFilter = LinearFilter;
1686
+ cooked.wrapS = ClampToEdgeWrapping;
1687
+ cooked.wrapT = ClampToEdgeWrapping;
1688
+ cooked.needsUpdate = true;
1689
+ const uv = vec2(
1690
+ positionWorld.x.div(float(data.size)).add(0.5),
1691
+ positionWorld.z.div(float(data.size)).add(0.5),
1692
+ );
1693
+ const sampled = texture(cooked, uv);
1694
+ // A clamped wet boundary texel must not become a stripe across the continuation mesh.
1695
+ const outside = max(abs(positionWorld.x), abs(positionWorld.z));
1696
+ const collar = biome?.groundCollarMeters ?? 0;
1697
+ const resident = oneMinus(
1698
+ smoothstep(data.size / 2 - Math.max(collar, spacing * 2), data.size / 2 + collar, outside),
1699
+ );
1700
+ return {
1701
+ node: sampled.r,
1702
+ texture: cooked,
1703
+ wetBank: sampled.g.mul(resident),
1704
+ flow: sampled.b.mul(resident),
1705
+ deposits: sampled.a.mul(resident),
1706
+ };
1707
+ }
1708
+
1709
+ /** The collar's own relief at the survey's 9.8 m cells, for the pixels its prefiltered mesh smooths. */
1710
+ export interface ICollarRelief {
1711
+ readonly texture: DataTexture;
1712
+ /** World normal of the unfiltered surroundings. */
1713
+ readonly normal: Node<"vec3">;
1714
+ /** +1 in a gully or hollow, -1 on a rib. */
1715
+ readonly hollow: Node<"float">;
1716
+ /** 1 on talus at the foot of a cliff band. */
1717
+ readonly scree: Node<"float">;
1718
+ }
1719
+
1720
+ /**
1721
+ * Per-pixel relief for the collar, as UE shades a landscape from its normal map rather than the LOD
1722
+ * mesh (UE 5.8.3: Engine/Shaders/Private/LandscapeVertexFactory.ush:391-401). Past about 300 m the
1723
+ * collar draws a prefiltered field on a 14-18 m ring grid, so its cliffs, gullies and ledges exist
1724
+ * only in this texture. Half float like the curvature: the normal lanes are signed.
1725
+ */
1726
+ export function buildCollarRelief(name: string): ICollarRelief | undefined {
1727
+ const source = horizonSurroundings(name);
1728
+ if (source === undefined) return undefined;
1729
+ const n = source.resolution;
1730
+ const massif = source.massif && decodeMassif(source.massif);
1731
+ // One atlas, one binding (the ground already samples sixteen): the collar's cells on the left,
1732
+ // a placed massif's own 4 m cells on the right, each read through its own clamped UV.
1733
+ const width = n + (massif?.columns ?? 0);
1734
+ const height = Math.max(n, massif?.rows ?? 0);
1735
+ const pixels = new Uint16Array(width * height * 4);
1736
+ writeRelief(pixels, width, 0, n, n, source.size / (n - 1), source.heights);
1737
+ if (massif)
1738
+ writeRelief(pixels, width, n, massif.columns, massif.rows, massif.spacing, massif.heights);
1739
+ const cooked = new DataTexture(pixels, width, height, RGBAFormat, HalfFloatType);
1740
+ cooked.minFilter = LinearFilter;
1741
+ cooked.magFilter = LinearFilter;
1742
+ cooked.wrapS = ClampToEdgeWrapping;
1743
+ cooked.wrapT = ClampToEdgeWrapping;
1744
+ cooked.needsUpdate = true;
1745
+ // Grid points sit on texel centres: column c of the collar is at (c + 0.5) / width.
1746
+ const collarUv = vec2(positionWorld.x, positionWorld.z)
1747
+ .div(source.size)
1748
+ .add(0.5)
1749
+ .mul(n - 1)
1750
+ .clamp(0, n - 1)
1751
+ .add(0.5)
1752
+ .div(vec2(width, height));
1753
+ let sampled: Node<"vec4"> = texture(cooked, collarUv);
1754
+ if (massif) {
1755
+ const cell = vec2(positionWorld.x, positionWorld.z)
1756
+ .sub(vec2(massif.origin[0], massif.origin[1]))
1757
+ .div(massif.spacing);
1758
+ const last = vec2(massif.columns - 1, massif.rows - 1);
1759
+ const inner = min(min(cell.x, cell.y), min(last.x.sub(cell.x), last.y.sub(cell.y)));
1760
+ const fine = texture(
1761
+ cooked,
1762
+ cell
1763
+ .clamp(vec2(0, 0), last)
1764
+ .add(vec2(n + 0.5, 0.5))
1765
+ .div(vec2(width, height)),
1766
+ );
1767
+ sampled = mix(sampled, fine, smoothstep(0, 3, inner));
1768
+ }
1769
+ return {
1770
+ texture: cooked,
1771
+ normal: vec3(
1772
+ sampled.r,
1773
+ float(1).sub(sampled.r.mul(sampled.r)).sub(sampled.g.mul(sampled.g)).max(0).sqrt(),
1774
+ sampled.g,
1775
+ ),
1776
+ hollow: sampled.b,
1777
+ scree: sampled.a,
1778
+ };
1779
+ }
1780
+
1781
+ /** A massif's heights from `horizon.json`: int16 decimetres above `offset`, base64. */
1782
+ function decodeMassif(packed: IPackedMassif) {
1783
+ const bytes = Uint8Array.from(atob(packed.heights), (c) => c.charCodeAt(0));
1784
+ const raw = new Int16Array(bytes.buffer, 0, packed.columns * packed.rows);
1785
+ return { ...packed, heights: Float32Array.from(raw, (dm) => packed.offset + dm / 10) };
1786
+ }
1787
+
1788
+ /**
1789
+ * Normal, hollow and talus texels for a `columns` x `rows` height grid at `cell` metres, written
1790
+ * into the atlas from column `x0`. The talus and hollow reach are in metres, so a 4 m grid reads
1791
+ * the same landforms as the 9.8 m collar, only sharper.
1792
+ */
1793
+ function writeRelief(
1794
+ pixels: Uint16Array,
1795
+ width: number,
1796
+ x0: number,
1797
+ columns: number,
1798
+ rows: number,
1799
+ cell: number,
1800
+ heights: ArrayLike<number>,
1801
+ ): void {
1802
+ const at = (row: number, column: number): number =>
1803
+ heights[
1804
+ Math.min(rows - 1, Math.max(0, row)) * columns + Math.min(columns - 1, Math.max(0, column))
1805
+ ] as number;
1806
+ const slopes = new Float32Array(columns * rows);
1807
+ for (let row = 0; row < rows; row++)
1808
+ for (let column = 0; column < columns; column++)
1809
+ slopes[row * columns + column] = Math.atan(
1810
+ Math.hypot(
1811
+ (at(row, column + 1) - at(row, column - 1)) / (2 * cell),
1812
+ (at(row + 1, column) - at(row - 1, column)) / (2 * cell),
1813
+ ),
1814
+ );
1815
+ const slopeAt = (row: number, column: number): number =>
1816
+ slopes[
1817
+ Math.min(rows - 1, Math.max(0, row)) * columns + Math.min(columns - 1, Math.max(0, column))
1818
+ ] as number;
1819
+ const degrees = Math.PI / 180;
1820
+ const band = (edge0: number, edge1: number, value: number): number => {
1821
+ const t = Math.max(0, Math.min(1, (value - edge0) / (edge1 - edge0)));
1822
+ return MathUtils.smoothstep(t, 0, 1);
1823
+ };
1824
+ // The 9.8 m collar measured a hollow across 2 cells and talus within 3 cells; keep those metres.
1825
+ const span = Math.max(2, Math.round(19.6 / cell));
1826
+ const step = Math.max(1, Math.round(9.8 / cell));
1827
+ for (let row = 0; row < rows; row++)
1828
+ for (let column = 0; column < columns; column++) {
1829
+ const height = at(row, column);
1830
+ const dx = (at(row, column + 1) - at(row, column - 1)) / (2 * cell);
1831
+ const dz = (at(row + 1, column) - at(row - 1, column)) / (2 * cell);
1832
+ const length = Math.hypot(dx, 1, dz);
1833
+ // A gully 5 m deep across 20 m reads near +1.
1834
+ const laplacian =
1835
+ (at(row, column - span) +
1836
+ at(row, column + span) +
1837
+ at(row - span, column) +
1838
+ at(row + span, column) -
1839
+ 4 * height) /
1840
+ (span * cell) ** 2;
1841
+ // Talus lies at 25-40 degrees under a face steeper than about 45 degrees within 30 m uphill.
1842
+ let cliffAbove = 0;
1843
+ for (let dr = -3; dr <= 3; dr++)
1844
+ for (let dc = -3; dc <= 3; dc++)
1845
+ if (at(row + dr * step, column + dc * step) > height + 8)
1846
+ cliffAbove = Math.max(
1847
+ cliffAbove,
1848
+ band(42 * degrees, 50 * degrees, slopeAt(row + dr * step, column + dc * step)),
1849
+ );
1850
+ const slope = slopes[row * columns + column] as number;
1851
+ const talus =
1852
+ band(22 * degrees, 28 * degrees, slope) * (1 - band(38 * degrees, 44 * degrees, slope));
1853
+ const texel = (row * width + x0 + column) * 4;
1854
+ pixels[texel] = DataUtils.toHalfFloat(-dx / length);
1855
+ pixels[texel + 1] = DataUtils.toHalfFloat(-dz / length);
1856
+ pixels[texel + 2] = DataUtils.toHalfFloat(Math.max(-1, Math.min(1, laplacian * 20)));
1857
+ pixels[texel + 3] = DataUtils.toHalfFloat(talus * cliffAbove);
1858
+ }
1859
+ }
1860
+
1861
+ async function get(
1862
+ assets: IAssetLoader,
1863
+ path: string,
1864
+ data: boolean,
1865
+ ): Promise<Texture | undefined> {
1866
+ // A clone without the licensed `local-assets/` draws the baked vertex colours; the warning names
1867
+ // the file, so a white ground on a machine that should have the art is one console line away.
1868
+ return assets.texture(path, { anisotropy: 8, data, wrap: RepeatWrapping }).catch((error) => {
1869
+ console.warn(
1870
+ `TN_GROUND_MAP_MISSING ${path}: ${error instanceof Error ? error.message : error}`,
1871
+ );
1872
+ return undefined;
1873
+ });
1874
+ }