@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
@@ -1,49 +1,15 @@
1
- import { existsSync, readFileSync } from 'fs';
2
- import { mkdir, rm, lstat, realpath, readFile, mkdtemp, rename, writeFile, copyFile } from 'fs/promises';
1
+ import { existsSync, statSync, readdirSync, readFileSync } from 'fs';
2
+ import { mkdir, mkdtemp, rm, lstat, realpath, readFile, rename, writeFile, copyFile } from 'fs/promises';
3
+ import { tmpdir, homedir } from 'os';
3
4
  import { relative, sep, join as join$1, dirname, resolve, isAbsolute } from 'path';
4
5
  import { fileURLToPath, pathToFileURL } from 'url';
5
6
  import '@threenative/core/world';
6
7
  import '@threenative/core';
7
8
  import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
8
9
  import { createHash } from 'crypto';
9
- import { homedir } from 'os';
10
- import { gunzipSync, inflateSync } from 'zlib';
10
+ import { gunzipSync } from 'zlib';
11
11
 
12
- // src/mcp/cook.ts
13
-
14
- // src/core/bands.ts
15
- function measureBands(layers, heights) {
16
- if (heights.length === 0) throw new RangeError("Terrain elevation samples are empty");
17
- let min = Number.POSITIVE_INFINITY;
18
- let max = Number.NEGATIVE_INFINITY;
19
- for (let index = 0; index < heights.length; index += 1) {
20
- const height = heights[index];
21
- if (!Number.isFinite(height)) throw new RangeError("Terrain elevation sample is nonfinite");
22
- min = Math.min(min, height);
23
- max = Math.max(max, height);
24
- }
25
- const span = max - min;
26
- if (!Number.isFinite(span)) throw new RangeError("Terrain elevation range is nonfinite");
27
- const resolve3 = (fraction) => {
28
- const height = min + fraction * span;
29
- if (!Number.isFinite(height)) throw new RangeError("Terrain elevation band is nonfinite");
30
- return height;
31
- };
32
- let snowBand = null;
33
- let snowShed = null;
34
- const bands = {};
35
- for (const layer2 of layers) {
36
- const band2 = [resolve3(layer2.from), resolve3(layer2.to)];
37
- if (layer2.layer === "snow") {
38
- snowBand = band2;
39
- if (layer2.shedFrom !== void 0 && layer2.shedTo !== void 0)
40
- snowShed = [layer2.shedFrom, layer2.shedTo];
41
- } else {
42
- bands[layer2.layer] = band2;
43
- }
44
- }
45
- return { bands, elevationRange: [min, max], snowBand, snowShed };
46
- }
12
+ // src/cook/cook.ts
47
13
 
48
14
  // src/core/math.ts
49
15
  var clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
@@ -199,152 +165,481 @@ function splinePoints(points, step = 3, smooth = true) {
199
165
  out.push([last[0], last[1], last[2]]);
200
166
  return out;
201
167
  }
168
+ var round = (value) => Math.round(value * 1e3) / 1e3;
202
169
 
203
- // src/core/erosion.ts
204
- function thermal(height, n, size, { iterations = 20, talus = 32, rate = 0.22 } = {}, observations) {
205
- if (!Number.isInteger(n) || n < 2)
206
- throw RangeError("Thermal erosion requires grid resolution n >= 2");
207
- if (!Number.isInteger(iterations) || iterations < 0 || iterations > 200)
208
- throw RangeError("Thermal erosion iterations must be between 0 and 200");
209
- const h = height.slice();
210
- const delta = new Float64Array(h.length);
211
- const limit = Math.tan(talus * Math.PI / 180) * (size / (n - 1));
212
- for (let k = 0; k < iterations; k += 1) {
213
- delta.fill(0);
214
- for (let z = 0; z < n; z += 1) {
215
- for (let x = 0; x < n; x += 1) {
216
- const i = z * n + x;
217
- const here = h[i];
218
- let best = -1;
219
- let diff = limit;
220
- if (x > 0 && here - h[i - 1] > diff) {
221
- diff = here - h[i - 1];
222
- best = i - 1;
223
- }
224
- if (x < n - 1 && here - h[i + 1] > diff) {
225
- diff = here - h[i + 1];
226
- best = i + 1;
227
- }
228
- if (z > 0 && here - h[i - n] > diff) {
229
- diff = here - h[i - n];
230
- best = i - n;
231
- }
232
- if (z < n - 1 && here - h[i + n] > diff) {
233
- diff = here - h[i + n];
234
- best = i + n;
235
- }
236
- if (best >= 0) {
237
- const transfer = (diff - limit) * rate;
238
- delta[i] = delta[i] - transfer;
239
- delta[best] = delta[best] + transfer;
240
- if (observations)
241
- observations.talus[best] = observations.talus[best] + transfer;
242
- }
243
- }
170
+ // src/core/masks.ts
171
+ var MATERIAL_IDS = Object.freeze([
172
+ "grass",
173
+ "dirt",
174
+ "rock",
175
+ "snow",
176
+ "sand",
177
+ "mud",
178
+ "road",
179
+ "moss"
180
+ ]);
181
+ var range = (v, min, max, fade = 0) => fade > 0 ? smoothstep(min - fade, min, v) * (1 - smoothstep(max, max + fade, v)) : Number(v >= min && v <= max);
182
+ function compileMask(mask, s) {
183
+ if (!mask || mask.type === "all") return () => 1;
184
+ switch (mask.type) {
185
+ case "none":
186
+ return () => 0;
187
+ case "circle": {
188
+ const centre = mask.at;
189
+ return (i, x, z) => falloff(
190
+ Math.hypot(x - centre[0], z - centre[1]),
191
+ mask.radius,
192
+ mask.falloff ?? 0.6
193
+ );
244
194
  }
245
- for (let i = 0; i < h.length; i += 1) h[i] = h[i] + delta[i];
195
+ case "rectangle": {
196
+ const centre = mask.at;
197
+ const rad = (mask.rotation ?? 0) * Math.PI / 180;
198
+ const c = Math.cos(rad);
199
+ const sn = Math.sin(rad);
200
+ const size = Array.isArray(mask.size) ? mask.size : [mask.size, mask.size];
201
+ return (i, x, z) => {
202
+ const dx = x - centre[0];
203
+ const dz = z - centre[1];
204
+ return falloff(
205
+ Math.max(
206
+ Math.abs(dx * c + dz * sn) / (size[0] / 2),
207
+ Math.abs(-dx * sn + dz * c) / (size[1] / 2)
208
+ ),
209
+ 1,
210
+ mask.falloff ?? 0.2
211
+ );
212
+ };
213
+ }
214
+ case "height":
215
+ return (i) => range(s.height[i], mask.min ?? -1e9, mask.max ?? 1e9, mask.fade);
216
+ case "slope":
217
+ return (i) => range(slopeAtIndex(s, i), mask.min ?? 0, mask.max ?? 90, mask.fade);
218
+ case "noise":
219
+ return (i, x, z) => smoothstep(
220
+ (mask.threshold ?? 0.5) - (mask.fade ?? 0.15),
221
+ (mask.threshold ?? 0.5) + (mask.fade ?? 0.15),
222
+ noise2(x / mask.scale, z / mask.scale, mask.seed ?? s.seed) * 0.5 + 0.5
223
+ );
224
+ case "biome": {
225
+ const field = s.biomes[mask.name];
226
+ return (i) => field?.[i] ?? 0;
227
+ }
228
+ case "material": {
229
+ const channel = MATERIAL_IDS.indexOf(mask.name);
230
+ if (channel < 0) throw Error(`Unknown material: ${String(mask.name)}`);
231
+ return (i) => s.splat[i * 8 + channel];
232
+ }
233
+ case "not": {
234
+ const inner = compileMask(mask.mask, s);
235
+ return (i, x, z) => 1 - inner(i, x, z);
236
+ }
237
+ case "and": {
238
+ const inner = (mask.masks ?? []).map((entry) => compileMask(entry, s));
239
+ return (i, x, z) => inner.reduce((value, sample) => value * sample(i, x, z), 1);
240
+ }
241
+ case "or": {
242
+ const inner = (mask.masks ?? []).map((entry) => compileMask(entry, s));
243
+ return (i, x, z) => 1 - inner.reduce((value, sample) => value * (1 - sample(i, x, z)), 1);
244
+ }
245
+ default:
246
+ throw Error(`Unknown mask: ${String(mask.type)}`);
246
247
  }
247
- return h;
248
248
  }
249
- var brushes = /* @__PURE__ */ new Map();
250
- function brush(radius) {
251
- let cells = brushes.get(radius);
252
- if (!cells) {
253
- const dx = [];
254
- const dz = [];
255
- const raw = [];
256
- let total = 0;
257
- for (let z = -radius; z <= radius; z += 1) {
258
- for (let x = -radius; x <= radius; x += 1) {
259
- const d = Math.hypot(x, z);
260
- if (d > radius) continue;
261
- const weight2 = 1 - d / (radius + 1);
262
- dx.push(x);
263
- dz.push(z);
264
- raw.push(weight2);
265
- total += weight2;
266
- }
249
+ function rasterMask(mask, s) {
250
+ if (!mask || mask.type === "all") return null;
251
+ const out = new Float32Array(s.height.length);
252
+ const sample = compileMask(mask, s);
253
+ for (let z = 0; z < s.resolution; z += 1) {
254
+ for (let x = 0; x < s.resolution; x += 1) {
255
+ const i = z * s.resolution + x;
256
+ out[i] = clamp(sample(i, world(s, x), world(s, z)));
267
257
  }
268
- const weight = Float64Array.from(raw, (w) => w / total);
269
- let full = 0;
270
- for (let k = 0; k < weight.length; k += 1) full += weight[k];
271
- cells = { dx: Int32Array.from(dx), dz: Int32Array.from(dz), full, radius, weight };
272
- brushes.set(radius, cells);
273
258
  }
274
- return cells;
259
+ return out;
275
260
  }
276
- var MAX_AUTOMATIC_DROPLETS = 1025 * 1025;
277
- var MAX_EXPLICIT_DROPLETS = 2e5;
278
- function hydraulic(height, n, size, options = {}, observations) {
279
- const {
280
- droplets: requestedDroplets,
281
- // A droplet has to be able to cross the world, so its step budget scales with the grid: a
282
- // fixed 40 barely leaves a 257 world while a 65 world would walk off it in a few steps.
283
- maxSteps = Math.round(Math.min(64, Math.max(24, n / 4))),
284
- inertia = 0.2,
285
- capacity = 4,
286
- // Each step takes a small bite of the sediment the droplet can carry. A big bite carves
287
- // fewer, deeper dimples that stand proud of their neighbours as spikes; many shallow bites
288
- // over the same lines incise the same drainage with a smooth surface.
289
- erosion = 0.03,
290
- deposition = 0.3,
291
- evaporation = 0.025,
292
- seed = 1,
293
- brushRadius = 3
294
- } = options;
295
- if (!Number.isInteger(n) || n < 2)
296
- throw RangeError("Hydraulic erosion requires grid resolution n >= 2");
297
- const droplets = requestedDroplets === void 0 ? Math.min(n * n, MAX_AUTOMATIC_DROPLETS) : requestedDroplets;
298
- if (!Number.isSafeInteger(droplets) || droplets < 0)
299
- throw RangeError("Hydraulic erosion droplets must be a non-negative integer");
300
- if (requestedDroplets !== void 0 && droplets > MAX_EXPLICIT_DROPLETS)
301
- throw RangeError(`Hydraulic erosion droplets must not exceed ${String(MAX_EXPLICIT_DROPLETS)}`);
302
- if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 128)
303
- throw RangeError("Hydraulic erosion maxSteps must be between 1 and 128");
304
- const h = Float64Array.from(height);
305
- const rnd = random(seed);
306
- const cell = size / (n - 1);
307
- const minSlope = 5e-3 * cell;
308
- const oneMinusInertia = 1 - inertia;
309
- const oneMinusEvaporation = 1 - evaporation;
310
- const brushCells = brush(brushRadius);
311
- const brushDx = brushCells.dx;
312
- const brushDz = brushCells.dz;
313
- const brushWeight = brushCells.weight;
314
- const brushCount = brushDx.length;
315
- const brushFull = brushCells.full;
316
- const brushEdge = brushCells.radius;
317
- const brushOffset = new Int32Array(brushCount);
318
- for (let k = 0; k < brushCount; k += 1)
319
- brushOffset[k] = brushDz[k] * n + brushDx[k];
320
- const obsFlow = observations?.flow;
321
- const obsSediment = observations?.sediment;
322
- const obsDeposition = observations?.deposition;
323
- const spread = (x, z, amount, floor = Number.NEGATIVE_INFINITY) => {
324
- if (amount === 0) return 0;
325
- const interior = x >= brushEdge && x < n - brushEdge && z >= brushEdge && z < n - brushEdge;
326
- if (interior) {
327
- const total2 = brushFull;
328
- if (total2 <= 0) return 0;
329
- const base = z * n + x;
330
- if (amount < 0) {
331
- let moved = 0;
332
- for (let k = 0; k < brushCount; k += 1) {
333
- const i = base + brushOffset[k];
334
- const share2 = amount * brushWeight[k] / total2;
335
- const avail = h[i] - floor;
336
- const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
337
- h[i] = h[i] + change;
338
- moved += change;
339
- }
340
- return moved;
341
- }
342
- if (obsDeposition !== void 0) {
343
- for (let k = 0; k < brushCount; k += 1) {
344
- const i = base + brushOffset[k];
345
- const share2 = amount * brushWeight[k] / total2;
346
- h[i] = h[i] + share2;
347
- obsDeposition[i] = obsDeposition[i] + share2;
261
+ function paintWeights(s, i, channel, weight) {
262
+ const w = clamp(weight);
263
+ const base = i * 8;
264
+ for (let c = 0; c < 8; c += 1)
265
+ s.splat[base + c] = s.splat[base + c] * (1 - w) + (c === channel ? w : 0);
266
+ }
267
+
268
+ // src/package/world-package.ts
269
+ var HEIGHTMAP_MAX = 65535;
270
+ var RECORD_VALUES = 8;
271
+ var COMPONENTS = ["r", "g", "b", "a"];
272
+ var PLANES = MATERIAL_IDS.length / COMPONENTS.length;
273
+ var SCALE_TOLERANCE = 1e-3;
274
+ var SLOTS = MATERIAL_IDS.map((id, channel) => ({
275
+ channel,
276
+ component: COMPONENTS[channel % COMPONENTS.length],
277
+ componentIndex: channel % COMPONENTS.length,
278
+ id,
279
+ plane: Math.floor(channel / COMPONENTS.length)
280
+ }));
281
+ function poseOf(item) {
282
+ if (item.transform === void 0)
283
+ return {
284
+ position: item.position,
285
+ quaternion: [0, Math.sin(item.rotation / 2), 0, Math.cos(item.rotation / 2)],
286
+ scale: [item.scale, item.scale, item.scale]
287
+ };
288
+ const { position, quaternion, scale } = item.transform;
289
+ return { position, quaternion, scale };
290
+ }
291
+ function uniformScale(asset, id, scale) {
292
+ const mean = (scale[0] + scale[1] + scale[2]) / 3;
293
+ const magnitude = Math.abs(mean);
294
+ const deviation = Math.max(
295
+ Math.abs(scale[0] - mean),
296
+ Math.abs(scale[1] - mean),
297
+ Math.abs(scale[2] - mean)
298
+ );
299
+ if (!(magnitude > 0) || deviation > magnitude * SCALE_TOLERANCE)
300
+ throw Error(
301
+ `World package: placement '${id}' of asset '${asset}' is scaled ${JSON.stringify(scale)}; a placement record carries one uniform scale.`
302
+ );
303
+ return mean;
304
+ }
305
+ function writePlacementRecord(out, offset, item, extent) {
306
+ if (item.transform === void 0 && !Number.isFinite(item.rotation))
307
+ throw Error(`World package: placement '${item.id}' has a non-finite rotation.`);
308
+ const { position, quaternion, scale } = poseOf(item);
309
+ if (!Number.isFinite(position[0]) || !Number.isFinite(position[1]) || !Number.isFinite(position[2]))
310
+ throw Error(
311
+ `World package: placement '${item.id}' has a non-finite position [${position.join(", ")}].`
312
+ );
313
+ if (position[0] < extent.minX || position[0] > extent.minX + extent.sizeX || position[2] < extent.minZ || position[2] > extent.minZ + extent.sizeZ)
314
+ throw Error(
315
+ `World package: placement '${item.id}' position [${position[0]}, ${position[2]}] is outside extent bounds [${extent.minX}..${extent.minX + extent.sizeX}, ${extent.minZ}..${extent.minZ + extent.sizeZ}].`
316
+ );
317
+ const length = Math.hypot(...quaternion);
318
+ if (!(length > 0)) throw Error(`World package: placement '${item.id}' has a zero quaternion.`);
319
+ out[offset] = position[0];
320
+ out[offset + 1] = position[1];
321
+ out[offset + 2] = position[2];
322
+ out[offset + 3] = quaternion[0] / length;
323
+ out[offset + 4] = quaternion[1] / length;
324
+ out[offset + 5] = quaternion[2] / length;
325
+ out[offset + 6] = quaternion[3] / length;
326
+ out[offset + 7] = uniformScale(item.asset, item.id, scale);
327
+ }
328
+ function placementCells(state, assets, cellSize, extent) {
329
+ const cells = /* @__PURE__ */ new Map();
330
+ const cellOf = (value, min, size) => Math.min(
331
+ Math.max(1, Math.ceil(size / cellSize)) - 1,
332
+ Math.max(0, Math.floor((value - min) / cellSize))
333
+ );
334
+ for (const item of state.instances) {
335
+ if (assets[item.asset] === void 0)
336
+ throw Error(
337
+ `World package: placement '${item.id}' names asset '${item.asset}', which options.assets does not.`
338
+ );
339
+ const x = cellOf(item.position[0], extent.minX, extent.sizeX);
340
+ const z = cellOf(item.position[2], extent.minZ, extent.sizeZ);
341
+ const key = `${String(x)},${String(z)}`;
342
+ let cell = cells.get(key);
343
+ if (cell === void 0) {
344
+ cell = { items: /* @__PURE__ */ new Map(), x, z };
345
+ cells.set(key, cell);
346
+ }
347
+ const bucket = cell.items.get(item.asset);
348
+ if (bucket === void 0) cell.items.set(item.asset, [item]);
349
+ else bucket.push(item);
350
+ }
351
+ const buffer = new ArrayBuffer(state.instances.length * RECORD_VALUES * 4);
352
+ const records = new Float32Array(buffer);
353
+ const ordered = [];
354
+ const ids = [];
355
+ let written2 = 0;
356
+ const byId = (left, right) => left[0] < right[0] ? -1 : 1;
357
+ for (const cell of [...cells.values()].sort((a, b) => a.x - b.x || a.z - b.z)) {
358
+ const runs = [];
359
+ for (const [asset, items] of [...cell.items.entries()].sort(byId)) {
360
+ runs.push({ asset, count: items.length, offset: written2 });
361
+ for (const item of items) {
362
+ writePlacementRecord(records, written2 * RECORD_VALUES, item, extent);
363
+ ids.push(item.id);
364
+ written2 += 1;
365
+ }
366
+ }
367
+ ordered.push({ runs, x: cell.x, z: cell.z });
368
+ }
369
+ return { bytes: new Uint8Array(buffer), cells: ordered, ids };
370
+ }
371
+ function bakeWorldPackage(state, options) {
372
+ const { size, resolution } = state;
373
+ const cellSize = options.cellSize ?? 64;
374
+ if (!Number.isFinite(cellSize) || cellSize <= 0)
375
+ throw Error(
376
+ `World package: cellSize must be a positive finite number, got ${String(cellSize)}.`
377
+ );
378
+ const { assets, layers, names } = options;
379
+ const heightmapName = names?.heightmap ?? "heightmap.u16";
380
+ const placementsName = names?.placements ?? "placements.bin";
381
+ const placementIdsName = names?.placementIds ?? "placement-ids.json";
382
+ const splatName = names?.splat ?? "splat.rgba";
383
+ const extent = { minX: -size / 2, minZ: -size / 2, sizeX: size, sizeZ: size };
384
+ let heightMin = Number.POSITIVE_INFINITY;
385
+ let heightMax = Number.NEGATIVE_INFINITY;
386
+ for (const height of state.height) {
387
+ if (!Number.isFinite(height)) throw Error("World package: terrain heights must be finite.");
388
+ heightMin = Math.min(heightMin, height);
389
+ heightMax = Math.max(heightMax, height);
390
+ }
391
+ if (heightMax - heightMin < 1e-6) heightMax = heightMin + 1;
392
+ const heightmap = new Uint8Array(resolution * resolution * 2);
393
+ const heights = new DataView(heightmap.buffer);
394
+ for (let i = 0; i < state.height.length; i += 1)
395
+ heights.setUint16(
396
+ i * 2,
397
+ Math.round(
398
+ (state.height[i] - heightMin) / (heightMax - heightMin) * HEIGHTMAP_MAX
399
+ ),
400
+ true
401
+ );
402
+ const placements = placementCells(state, assets, cellSize, extent);
403
+ return {
404
+ files: {
405
+ [heightmapName]: heightmap,
406
+ [placementsName]: placements.bytes,
407
+ [placementIdsName]: new TextEncoder().encode(`${JSON.stringify(placements.ids)}
408
+ `),
409
+ [splatName]: splatBytes(state, resolution)
410
+ },
411
+ manifest: {
412
+ assets,
413
+ cellSize,
414
+ cells: placements.cells,
415
+ extent,
416
+ placements: placementsName,
417
+ placementIds: placementIdsName,
418
+ terrain: {
419
+ columns: resolution,
420
+ heightMax,
421
+ heightMin,
422
+ heightmap: heightmapName,
423
+ layers: { splat: splatName, ...layers },
424
+ rows: resolution,
425
+ spacing: size / (resolution - 1)
426
+ },
427
+ version: 1
428
+ },
429
+ splat: {
430
+ masks: Object.fromEntries(SLOTS.map(({ component, id, plane }) => [id, [plane, component]])),
431
+ planes: PLANES,
432
+ size: resolution
433
+ }
434
+ };
435
+ }
436
+ function splatBytes(state, resolution) {
437
+ const planeBytes = resolution * resolution * 4;
438
+ if (state.splat.length !== resolution * resolution * MATERIAL_IDS.length)
439
+ throw Error(
440
+ `World package: splat has ${String(state.splat.length)} weights, expected ${String(resolution * resolution * MATERIAL_IDS.length)}.`
441
+ );
442
+ const bytes = new Uint8Array(planeBytes * PLANES);
443
+ for (let row2 = 0; row2 < resolution; row2 += 1) {
444
+ const source = (resolution - 1 - row2) * resolution;
445
+ const rowOffset = row2 * resolution * 4;
446
+ for (let column2 = 0; column2 < resolution; column2 += 1) {
447
+ const sample = (source + column2) * MATERIAL_IDS.length;
448
+ const rowCol = rowOffset + column2 * 4;
449
+ for (const slot of SLOTS) {
450
+ const weight = state.splat[sample + slot.channel];
451
+ bytes[slot.plane * planeBytes + rowCol + slot.componentIndex] = Math.round(
452
+ (weight <= 0 ? 0 : weight >= 1 ? 1 : weight) * 255
453
+ );
454
+ }
455
+ }
456
+ }
457
+ return bytes;
458
+ }
459
+ new ImprovedNoise();
460
+ new ImprovedNoise();
461
+ var TRUNKS = /* @__PURE__ */ new Set(["spruce", "sapling"]);
462
+ /* @__PURE__ */ new Set([...TRUNKS, "boulder", "bush", "deadfall"]);
463
+
464
+ // src/biome/bands.ts
465
+ function measureBands(layers, heights) {
466
+ if (heights.length === 0) throw new RangeError("Terrain elevation samples are empty");
467
+ let min = Number.POSITIVE_INFINITY;
468
+ let max = Number.NEGATIVE_INFINITY;
469
+ for (let index = 0; index < heights.length; index += 1) {
470
+ const height = heights[index];
471
+ if (!Number.isFinite(height)) throw new RangeError("Terrain elevation sample is nonfinite");
472
+ min = Math.min(min, height);
473
+ max = Math.max(max, height);
474
+ }
475
+ const span = max - min;
476
+ if (!Number.isFinite(span)) throw new RangeError("Terrain elevation range is nonfinite");
477
+ const resolve5 = (fraction) => {
478
+ const height = min + fraction * span;
479
+ if (!Number.isFinite(height)) throw new RangeError("Terrain elevation band is nonfinite");
480
+ return height;
481
+ };
482
+ let snowBand = null;
483
+ let snowShed = null;
484
+ const bands = {};
485
+ for (const layer2 of layers) {
486
+ const band2 = [resolve5(layer2.from), resolve5(layer2.to)];
487
+ if (layer2.layer === "snow") {
488
+ snowBand = band2;
489
+ if (layer2.shedFrom !== void 0 && layer2.shedTo !== void 0)
490
+ snowShed = [layer2.shedFrom, layer2.shedTo];
491
+ } else {
492
+ bands[layer2.layer] = band2;
493
+ }
494
+ }
495
+ return { bands, elevationRange: [min, max], snowBand, snowShed };
496
+ }
497
+
498
+ // src/core/erosion.ts
499
+ function thermal(height, n, size, { iterations = 20, talus = 32, rate = 0.22 } = {}, observations) {
500
+ if (!Number.isInteger(n) || n < 2)
501
+ throw RangeError("Thermal erosion requires grid resolution n >= 2");
502
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > 200)
503
+ throw RangeError("Thermal erosion iterations must be between 0 and 200");
504
+ const h = height.slice();
505
+ const delta = new Float64Array(h.length);
506
+ const limit = Math.tan(talus * Math.PI / 180) * (size / (n - 1));
507
+ for (let k = 0; k < iterations; k += 1) {
508
+ delta.fill(0);
509
+ for (let z = 0; z < n; z += 1) {
510
+ for (let x = 0; x < n; x += 1) {
511
+ const i = z * n + x;
512
+ const here = h[i];
513
+ let best = -1;
514
+ let diff = limit;
515
+ if (x > 0 && here - h[i - 1] > diff) {
516
+ diff = here - h[i - 1];
517
+ best = i - 1;
518
+ }
519
+ if (x < n - 1 && here - h[i + 1] > diff) {
520
+ diff = here - h[i + 1];
521
+ best = i + 1;
522
+ }
523
+ if (z > 0 && here - h[i - n] > diff) {
524
+ diff = here - h[i - n];
525
+ best = i - n;
526
+ }
527
+ if (z < n - 1 && here - h[i + n] > diff) {
528
+ diff = here - h[i + n];
529
+ best = i + n;
530
+ }
531
+ if (best >= 0) {
532
+ const transfer = (diff - limit) * rate;
533
+ delta[i] = delta[i] - transfer;
534
+ delta[best] = delta[best] + transfer;
535
+ if (observations)
536
+ observations.talus[best] = observations.talus[best] + transfer;
537
+ }
538
+ }
539
+ }
540
+ for (let i = 0; i < h.length; i += 1) h[i] = h[i] + delta[i];
541
+ }
542
+ return h;
543
+ }
544
+ var brushes = /* @__PURE__ */ new Map();
545
+ function brush(radius) {
546
+ let cells = brushes.get(radius);
547
+ if (!cells) {
548
+ const dx = [];
549
+ const dz = [];
550
+ const raw = [];
551
+ let total = 0;
552
+ for (let z = -radius; z <= radius; z += 1) {
553
+ for (let x = -radius; x <= radius; x += 1) {
554
+ const d = Math.hypot(x, z);
555
+ if (d > radius) continue;
556
+ const weight2 = 1 - d / (radius + 1);
557
+ dx.push(x);
558
+ dz.push(z);
559
+ raw.push(weight2);
560
+ total += weight2;
561
+ }
562
+ }
563
+ const weight = Float64Array.from(raw, (w) => w / total);
564
+ let full = 0;
565
+ for (let k = 0; k < weight.length; k += 1) full += weight[k];
566
+ cells = { dx: Int32Array.from(dx), dz: Int32Array.from(dz), full, radius, weight };
567
+ brushes.set(radius, cells);
568
+ }
569
+ return cells;
570
+ }
571
+ var MAX_AUTOMATIC_DROPLETS = 1025 * 1025;
572
+ var MAX_EXPLICIT_DROPLETS = 2e5;
573
+ function hydraulic(height, n, size, options = {}, observations) {
574
+ const {
575
+ droplets: requestedDroplets,
576
+ // A droplet has to be able to cross the world, so its step budget scales with the grid: a
577
+ // fixed 40 barely leaves a 257 world while a 65 world would walk off it in a few steps.
578
+ maxSteps = Math.round(Math.min(64, Math.max(24, n / 4))),
579
+ inertia = 0.2,
580
+ capacity = 4,
581
+ // Each step takes a small bite of the sediment the droplet can carry. A big bite carves
582
+ // fewer, deeper dimples that stand proud of their neighbours as spikes; many shallow bites
583
+ // over the same lines incise the same drainage with a smooth surface.
584
+ erosion = 0.03,
585
+ deposition = 0.3,
586
+ evaporation = 0.025,
587
+ seed = 1,
588
+ brushRadius = 3
589
+ } = options;
590
+ if (!Number.isInteger(n) || n < 2)
591
+ throw RangeError("Hydraulic erosion requires grid resolution n >= 2");
592
+ const droplets = requestedDroplets === void 0 ? Math.min(n * n, MAX_AUTOMATIC_DROPLETS) : requestedDroplets;
593
+ if (!Number.isSafeInteger(droplets) || droplets < 0)
594
+ throw RangeError("Hydraulic erosion droplets must be a non-negative integer");
595
+ if (requestedDroplets !== void 0 && droplets > MAX_EXPLICIT_DROPLETS)
596
+ throw RangeError(`Hydraulic erosion droplets must not exceed ${String(MAX_EXPLICIT_DROPLETS)}`);
597
+ if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 128)
598
+ throw RangeError("Hydraulic erosion maxSteps must be between 1 and 128");
599
+ const h = Float64Array.from(height);
600
+ const rnd = random(seed);
601
+ const cell = size / (n - 1);
602
+ const minSlope = 5e-3 * cell;
603
+ const oneMinusInertia = 1 - inertia;
604
+ const oneMinusEvaporation = 1 - evaporation;
605
+ const brushCells = brush(brushRadius);
606
+ const brushDx = brushCells.dx;
607
+ const brushDz = brushCells.dz;
608
+ const brushWeight = brushCells.weight;
609
+ const brushCount = brushDx.length;
610
+ const brushFull = brushCells.full;
611
+ const brushEdge = brushCells.radius;
612
+ const brushOffset = new Int32Array(brushCount);
613
+ for (let k = 0; k < brushCount; k += 1)
614
+ brushOffset[k] = brushDz[k] * n + brushDx[k];
615
+ const obsFlow = observations?.flow;
616
+ const obsSediment = observations?.sediment;
617
+ const obsDeposition = observations?.deposition;
618
+ const spread = (x, z, amount, floor = Number.NEGATIVE_INFINITY) => {
619
+ if (amount === 0) return 0;
620
+ const interior = x >= brushEdge && x < n - brushEdge && z >= brushEdge && z < n - brushEdge;
621
+ if (interior) {
622
+ const total2 = brushFull;
623
+ if (total2 <= 0) return 0;
624
+ const base = z * n + x;
625
+ if (amount < 0) {
626
+ let moved = 0;
627
+ for (let k = 0; k < brushCount; k += 1) {
628
+ const i = base + brushOffset[k];
629
+ const share2 = amount * brushWeight[k] / total2;
630
+ const avail = h[i] - floor;
631
+ const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
632
+ h[i] = h[i] + change;
633
+ moved += change;
634
+ }
635
+ return moved;
636
+ }
637
+ if (obsDeposition !== void 0) {
638
+ for (let k = 0; k < brushCount; k += 1) {
639
+ const i = base + brushOffset[k];
640
+ const share2 = amount * brushWeight[k] / total2;
641
+ h[i] = h[i] + share2;
642
+ obsDeposition[i] = obsDeposition[i] + share2;
348
643
  }
349
644
  } else {
350
645
  for (let k = 0; k < brushCount; k += 1) {
@@ -793,135 +1088,37 @@ function gully(height, n, size, { iterations = 200, capacity = 0.05, rain = 5e-4
793
1088
  load += cut;
794
1089
  } else {
795
1090
  const drop = DEPOSIT * (load - transport);
796
- surface += drop;
797
- load -= drop;
798
- }
799
- hTmp[i] = surface;
800
- sedTmp[i] = load;
801
- }
802
- }
803
- const passed = h;
804
- h = hTmp;
805
- hTmp = passed;
806
- for (let z = 0; z < n; z += 1) {
807
- for (let x = 0; x < n; x += 1) {
808
- const i = z * n + x;
809
- let load = sedTmp[i] * (1 - share2(
810
- fluxL[i] + fluxR[i] + fluxT[i] + fluxB[i],
811
- waterBefore[i]
812
- ));
813
- if (x > 0)
814
- load += sedTmp[i - 1] * share2(fluxR[i - 1], waterBefore[i - 1]);
815
- if (x < n - 1)
816
- load += sedTmp[i + 1] * share2(fluxL[i + 1], waterBefore[i + 1]);
817
- if (z > 0)
818
- load += sedTmp[i - n] * share2(fluxB[i - n], waterBefore[i - n]);
819
- if (z < n - 1)
820
- load += sedTmp[i + n] * share2(fluxT[i + n], waterBefore[i + n]);
821
- sediment[i] = load;
822
- water2[i] = water2[i] * evaporateKeep;
823
- }
824
- }
825
- }
826
- return Float32Array.from(h, (surface, i) => surface + sediment[i]);
827
- }
828
-
829
- // src/core/masks.ts
830
- var MATERIAL_IDS = Object.freeze([
831
- "grass",
832
- "dirt",
833
- "rock",
834
- "snow",
835
- "sand",
836
- "mud",
837
- "road",
838
- "moss"
839
- ]);
840
- var range = (v, min, max, fade = 0) => fade > 0 ? smoothstep(min - fade, min, v) * (1 - smoothstep(max, max + fade, v)) : Number(v >= min && v <= max);
841
- function compileMask(mask, s) {
842
- if (!mask || mask.type === "all") return () => 1;
843
- switch (mask.type) {
844
- case "none":
845
- return () => 0;
846
- case "circle": {
847
- const centre = mask.at;
848
- return (i, x, z) => falloff(
849
- Math.hypot(x - centre[0], z - centre[1]),
850
- mask.radius,
851
- mask.falloff ?? 0.6
852
- );
853
- }
854
- case "rectangle": {
855
- const centre = mask.at;
856
- const rad = (mask.rotation ?? 0) * Math.PI / 180;
857
- const c = Math.cos(rad);
858
- const sn = Math.sin(rad);
859
- const size = Array.isArray(mask.size) ? mask.size : [mask.size, mask.size];
860
- return (i, x, z) => {
861
- const dx = x - centre[0];
862
- const dz = z - centre[1];
863
- return falloff(
864
- Math.max(
865
- Math.abs(dx * c + dz * sn) / (size[0] / 2),
866
- Math.abs(-dx * sn + dz * c) / (size[1] / 2)
867
- ),
868
- 1,
869
- mask.falloff ?? 0.2
870
- );
871
- };
872
- }
873
- case "height":
874
- return (i) => range(s.height[i], mask.min ?? -1e9, mask.max ?? 1e9, mask.fade);
875
- case "slope":
876
- return (i) => range(slopeAtIndex(s, i), mask.min ?? 0, mask.max ?? 90, mask.fade);
877
- case "noise":
878
- return (i, x, z) => smoothstep(
879
- (mask.threshold ?? 0.5) - (mask.fade ?? 0.15),
880
- (mask.threshold ?? 0.5) + (mask.fade ?? 0.15),
881
- noise2(x / mask.scale, z / mask.scale, mask.seed ?? s.seed) * 0.5 + 0.5
882
- );
883
- case "biome": {
884
- const field = s.biomes[mask.name];
885
- return (i) => field?.[i] ?? 0;
886
- }
887
- case "material": {
888
- const channel = MATERIAL_IDS.indexOf(mask.name);
889
- if (channel < 0) throw Error(`Unknown material: ${String(mask.name)}`);
890
- return (i) => s.splat[i * 8 + channel];
891
- }
892
- case "not": {
893
- const inner = compileMask(mask.mask, s);
894
- return (i, x, z) => 1 - inner(i, x, z);
895
- }
896
- case "and": {
897
- const inner = (mask.masks ?? []).map((entry) => compileMask(entry, s));
898
- return (i, x, z) => inner.reduce((value, sample) => value * sample(i, x, z), 1);
899
- }
900
- case "or": {
901
- const inner = (mask.masks ?? []).map((entry) => compileMask(entry, s));
902
- return (i, x, z) => 1 - inner.reduce((value, sample) => value * (1 - sample(i, x, z)), 1);
903
- }
904
- default:
905
- throw Error(`Unknown mask: ${String(mask.type)}`);
906
- }
907
- }
908
- function rasterMask(mask, s) {
909
- if (!mask || mask.type === "all") return null;
910
- const out = new Float32Array(s.height.length);
911
- const sample = compileMask(mask, s);
912
- for (let z = 0; z < s.resolution; z += 1) {
913
- for (let x = 0; x < s.resolution; x += 1) {
914
- const i = z * s.resolution + x;
915
- out[i] = clamp(sample(i, world(s, x), world(s, z)));
1091
+ surface += drop;
1092
+ load -= drop;
1093
+ }
1094
+ hTmp[i] = surface;
1095
+ sedTmp[i] = load;
1096
+ }
1097
+ }
1098
+ const passed = h;
1099
+ h = hTmp;
1100
+ hTmp = passed;
1101
+ for (let z = 0; z < n; z += 1) {
1102
+ for (let x = 0; x < n; x += 1) {
1103
+ const i = z * n + x;
1104
+ let load = sedTmp[i] * (1 - share2(
1105
+ fluxL[i] + fluxR[i] + fluxT[i] + fluxB[i],
1106
+ waterBefore[i]
1107
+ ));
1108
+ if (x > 0)
1109
+ load += sedTmp[i - 1] * share2(fluxR[i - 1], waterBefore[i - 1]);
1110
+ if (x < n - 1)
1111
+ load += sedTmp[i + 1] * share2(fluxL[i + 1], waterBefore[i + 1]);
1112
+ if (z > 0)
1113
+ load += sedTmp[i - n] * share2(fluxB[i - n], waterBefore[i - n]);
1114
+ if (z < n - 1)
1115
+ load += sedTmp[i + n] * share2(fluxT[i + n], waterBefore[i + n]);
1116
+ sediment[i] = load;
1117
+ water2[i] = water2[i] * evaporateKeep;
1118
+ }
916
1119
  }
917
1120
  }
918
- return out;
919
- }
920
- function paintWeights(s, i, channel, weight) {
921
- const w = clamp(weight);
922
- const base = i * 8;
923
- for (let c = 0; c < 8; c += 1)
924
- s.splat[base + c] = s.splat[base + c] * (1 - w) + (c === channel ? w : 0);
1121
+ return Float32Array.from(h, (surface, i) => surface + sediment[i]);
925
1122
  }
926
1123
 
927
1124
  // src/core/scree.ts
@@ -2545,7 +2742,7 @@ var Terrain = class _Terrain {
2545
2742
  }
2546
2743
  };
2547
2744
 
2548
- // src/core/presets.ts
2745
+ // src/ground/presets.ts
2549
2746
  var LANDFORMS = {
2550
2747
  alpine: {
2551
2748
  summary: "Glacier-cut granite peaks: steep headwalls, sharp ar\xEAtes, dendritic gullies.",
@@ -2711,7 +2908,7 @@ function landform(kind, options = {}) {
2711
2908
  return t;
2712
2909
  }
2713
2910
 
2714
- // src/core/biome.ts
2911
+ // src/biome/biome.ts
2715
2912
  var SPEC_FIELDS = [
2716
2913
  "look",
2717
2914
  "bake",
@@ -2760,8 +2957,11 @@ var FOLIAGE_FIELDS = [
2760
2957
  "stands",
2761
2958
  "grassThreshold",
2762
2959
  "standThreshold",
2763
- "far"
2960
+ "far",
2961
+ "scale",
2962
+ "mask"
2764
2963
  ];
2964
+ var FOLIAGE_REQUIRED = FOLIAGE_FIELDS.filter((name) => name !== "scale" && name !== "mask");
2765
2965
  var FAR_FIELDS = [
2766
2966
  "cell",
2767
2967
  "spacing",
@@ -2959,7 +3159,7 @@ function cover(value, biome) {
2959
3159
  };
2960
3160
  }
2961
3161
  function foliage(value, biome, field) {
2962
- const row2 = closed(value, biome, field, FOLIAGE_FIELDS);
3162
+ const row2 = closed(value, biome, field, FOLIAGE_FIELDS, FOLIAGE_REQUIRED);
2963
3163
  const height = row2.height === null ? null : pair(row2.height, biome, `${field}.height`);
2964
3164
  return {
2965
3165
  species: text(row2.species, biome, `${field}.species`),
@@ -2971,9 +3171,19 @@ function foliage(value, biome, field) {
2971
3171
  stands: flag(row2.stands, biome, `${field}.stands`),
2972
3172
  grassThreshold: share(row2.grassThreshold, biome, `${field}.grassThreshold`),
2973
3173
  standThreshold: share(row2.standThreshold, biome, `${field}.standThreshold`),
2974
- far: far(row2.far, biome, `${field}.far`)
3174
+ far: far(row2.far, biome, `${field}.far`),
3175
+ ...row2.scale === void 0 ? {} : { scale: pair(row2.scale, biome, `${field}.scale`) },
3176
+ ...row2.mask === void 0 ? {} : { mask: standMask(row2.mask, biome, `${field}.mask`) }
2975
3177
  };
2976
3178
  }
3179
+ function standMask(value, biome, field) {
3180
+ try {
3181
+ validateMask(value);
3182
+ } catch (error) {
3183
+ fail2(biome, field, error.message);
3184
+ }
3185
+ return value;
3186
+ }
2977
3187
  function grass(value, biome, field) {
2978
3188
  const row2 = closed(value, biome, field, GRASS_FIELDS);
2979
3189
  const density = count(row2.density, biome, `${field}.density`);
@@ -3038,253 +3248,59 @@ function water(value, biome, field) {
3038
3248
  function bake(value, biome) {
3039
3249
  const row2 = closed(value, biome, "bake", BAKE_FIELDS);
3040
3250
  return {
3041
- file: text(row2.file, biome, "bake.file"),
3042
- key: row2.key === null ? null : text(row2.key, biome, "bake.key")
3043
- };
3044
- }
3045
- function spawn(value, biome) {
3046
- const row2 = closed(value, biome, "spawn", SPAWN_FIELDS);
3047
- return {
3048
- at: point2(row2.at, biome, "spawn.at"),
3049
- cameraOffset: point3(row2.cameraOffset, biome, "spawn.cameraOffset"),
3050
- focus: point2(row2.focus, biome, "spawn.focus")
3051
- };
3052
- }
3053
- function species(value, biome) {
3054
- if (!Array.isArray(value) || value.length === 0)
3055
- fail2(biome, "species", "must be a non-empty array of asset ids");
3056
- const names = value.map((name, index) => text(name, biome, `species[${index}]`));
3057
- for (const [index, name] of names.entries())
3058
- if (names.indexOf(name) !== index) fail2(biome, `species[${index}]`, `repeats '${name}'`);
3059
- return names;
3060
- }
3061
- function validateBiome(spec, name) {
3062
- if (typeof name !== "string" || name.trim() === "")
3063
- throw new TypeError("validateBiome needs the biome's name");
3064
- const biome = name;
3065
- const root = closed(spec, biome, "", SPEC_FIELDS);
3066
- const aliases = root.aliases;
3067
- if (!Array.isArray(aliases) || aliases.length === 0)
3068
- fail2(biome, "aliases", "must be a non-empty array of words");
3069
- const rows = (value, field, one) => {
3070
- if (!Array.isArray(value)) fail2(biome, field, "must be an array");
3071
- return value.map((entry, index) => one(entry, `${field}[${index}]`));
3072
- };
3073
- return {
3074
- look: text(root.look, biome, "look"),
3075
- bake: bake(root.bake, biome),
3076
- landform: oneOf(root.landform, biome, "landform", LANDFORM_KINDS),
3077
- sizeMeters: positive(root.sizeMeters, biome, "sizeMeters"),
3078
- seed: whole(root.seed, biome, "seed"),
3079
- stream: oneOf(root.stream, biome, "stream", STREAMS),
3080
- cover: cover(root.cover, biome),
3081
- foliage: rows(root.foliage, "foliage", (entry, at) => foliage(entry, biome, at)),
3082
- grass: rows(root.grass, "grass", (entry, at) => grass(entry, biome, at)),
3083
- layers: rows(root.layers, "layers", (entry, at) => layer(entry, biome, at)),
3084
- water: rows(root.water, "water", (entry, at) => water(entry, biome, at)),
3085
- spawn: spawn(root.spawn, biome),
3086
- species: species(root.species, biome),
3087
- aliases: aliases.map(
3088
- (word, index) => text(word, biome, `aliases[${index}]`).toLowerCase()
3089
- )
3090
- };
3091
- }
3092
- new ImprovedNoise();
3093
- new ImprovedNoise();
3094
-
3095
- // src/core/world-package.ts
3096
- var HEIGHTMAP_MAX = 65535;
3097
- var RECORD_VALUES = 8;
3098
- var COMPONENTS = ["r", "g", "b", "a"];
3099
- var PLANES = MATERIAL_IDS.length / COMPONENTS.length;
3100
- var SCALE_TOLERANCE = 1e-3;
3101
- var SLOTS = MATERIAL_IDS.map((id, channel) => ({
3102
- channel,
3103
- component: COMPONENTS[channel % COMPONENTS.length],
3104
- componentIndex: channel % COMPONENTS.length,
3105
- id,
3106
- plane: Math.floor(channel / COMPONENTS.length)
3107
- }));
3108
- function poseOf(item) {
3109
- if (item.transform === void 0)
3110
- return {
3111
- position: item.position,
3112
- quaternion: [0, Math.sin(item.rotation / 2), 0, Math.cos(item.rotation / 2)],
3113
- scale: [item.scale, item.scale, item.scale]
3114
- };
3115
- const { position, quaternion, scale } = item.transform;
3116
- return { position, quaternion, scale };
3117
- }
3118
- function uniformScale(asset, id, scale) {
3119
- const mean = (scale[0] + scale[1] + scale[2]) / 3;
3120
- const magnitude = Math.abs(mean);
3121
- const deviation = Math.max(
3122
- Math.abs(scale[0] - mean),
3123
- Math.abs(scale[1] - mean),
3124
- Math.abs(scale[2] - mean)
3125
- );
3126
- if (!(magnitude > 0) || deviation > magnitude * SCALE_TOLERANCE)
3127
- throw Error(
3128
- `World package: placement '${id}' of asset '${asset}' is scaled ${JSON.stringify(scale)}; a placement record carries one uniform scale.`
3129
- );
3130
- return mean;
3131
- }
3132
- function writePlacementRecord(out, offset, item, extent) {
3133
- if (item.transform === void 0 && !Number.isFinite(item.rotation))
3134
- throw Error(`World package: placement '${item.id}' has a non-finite rotation.`);
3135
- const { position, quaternion, scale } = poseOf(item);
3136
- if (!Number.isFinite(position[0]) || !Number.isFinite(position[1]) || !Number.isFinite(position[2]))
3137
- throw Error(
3138
- `World package: placement '${item.id}' has a non-finite position [${position.join(", ")}].`
3139
- );
3140
- if (position[0] < extent.minX || position[0] > extent.minX + extent.sizeX || position[2] < extent.minZ || position[2] > extent.minZ + extent.sizeZ)
3141
- throw Error(
3142
- `World package: placement '${item.id}' position [${position[0]}, ${position[2]}] is outside extent bounds [${extent.minX}..${extent.minX + extent.sizeX}, ${extent.minZ}..${extent.minZ + extent.sizeZ}].`
3143
- );
3144
- const length = Math.hypot(...quaternion);
3145
- if (!(length > 0)) throw Error(`World package: placement '${item.id}' has a zero quaternion.`);
3146
- out[offset] = position[0];
3147
- out[offset + 1] = position[1];
3148
- out[offset + 2] = position[2];
3149
- out[offset + 3] = quaternion[0] / length;
3150
- out[offset + 4] = quaternion[1] / length;
3151
- out[offset + 5] = quaternion[2] / length;
3152
- out[offset + 6] = quaternion[3] / length;
3153
- out[offset + 7] = uniformScale(item.asset, item.id, scale);
3154
- }
3155
- function placementCells(state, assets, cellSize, extent) {
3156
- const cells = /* @__PURE__ */ new Map();
3157
- const cellOf = (value, min, size) => Math.min(
3158
- Math.max(1, Math.ceil(size / cellSize)) - 1,
3159
- Math.max(0, Math.floor((value - min) / cellSize))
3160
- );
3161
- for (const item of state.instances) {
3162
- if (assets[item.asset] === void 0)
3163
- throw Error(
3164
- `World package: placement '${item.id}' names asset '${item.asset}', which options.assets does not.`
3165
- );
3166
- const x = cellOf(item.position[0], extent.minX, extent.sizeX);
3167
- const z = cellOf(item.position[2], extent.minZ, extent.sizeZ);
3168
- const key = `${String(x)},${String(z)}`;
3169
- let cell = cells.get(key);
3170
- if (cell === void 0) {
3171
- cell = { items: /* @__PURE__ */ new Map(), x, z };
3172
- cells.set(key, cell);
3173
- }
3174
- const bucket = cell.items.get(item.asset);
3175
- if (bucket === void 0) cell.items.set(item.asset, [item]);
3176
- else bucket.push(item);
3177
- }
3178
- const buffer = new ArrayBuffer(state.instances.length * RECORD_VALUES * 4);
3179
- const records = new Float32Array(buffer);
3180
- const ordered = [];
3181
- const ids = [];
3182
- let written = 0;
3183
- const byId = (left, right) => left[0] < right[0] ? -1 : 1;
3184
- for (const cell of [...cells.values()].sort((a, b) => a.x - b.x || a.z - b.z)) {
3185
- const runs = [];
3186
- for (const [asset, items] of [...cell.items.entries()].sort(byId)) {
3187
- runs.push({ asset, count: items.length, offset: written });
3188
- for (const item of items) {
3189
- writePlacementRecord(records, written * RECORD_VALUES, item, extent);
3190
- ids.push(item.id);
3191
- written += 1;
3192
- }
3193
- }
3194
- ordered.push({ runs, x: cell.x, z: cell.z });
3195
- }
3196
- return { bytes: new Uint8Array(buffer), cells: ordered, ids };
3197
- }
3198
- function bakeWorldPackage(state, options) {
3199
- const { size, resolution } = state;
3200
- const cellSize = options.cellSize ?? 64;
3201
- if (!Number.isFinite(cellSize) || cellSize <= 0)
3202
- throw Error(
3203
- `World package: cellSize must be a positive finite number, got ${String(cellSize)}.`
3204
- );
3205
- const { assets, layers, names } = options;
3206
- const heightmapName = names?.heightmap ?? "heightmap.u16";
3207
- const placementsName = names?.placements ?? "placements.bin";
3208
- const placementIdsName = names?.placementIds ?? "placement-ids.json";
3209
- const splatName = names?.splat ?? "splat.rgba";
3210
- const extent = { minX: -size / 2, minZ: -size / 2, sizeX: size, sizeZ: size };
3211
- let heightMin = Number.POSITIVE_INFINITY;
3212
- let heightMax = Number.NEGATIVE_INFINITY;
3213
- for (const height of state.height) {
3214
- if (!Number.isFinite(height)) throw Error("World package: terrain heights must be finite.");
3215
- heightMin = Math.min(heightMin, height);
3216
- heightMax = Math.max(heightMax, height);
3217
- }
3218
- if (heightMax - heightMin < 1e-6) heightMax = heightMin + 1;
3219
- const heightmap = new Uint8Array(resolution * resolution * 2);
3220
- const heights = new DataView(heightmap.buffer);
3221
- for (let i = 0; i < state.height.length; i += 1)
3222
- heights.setUint16(
3223
- i * 2,
3224
- Math.round(
3225
- (state.height[i] - heightMin) / (heightMax - heightMin) * HEIGHTMAP_MAX
3226
- ),
3227
- true
3228
- );
3229
- const placements = placementCells(state, assets, cellSize, extent);
3230
- return {
3231
- files: {
3232
- [heightmapName]: heightmap,
3233
- [placementsName]: placements.bytes,
3234
- [placementIdsName]: new TextEncoder().encode(`${JSON.stringify(placements.ids)}
3235
- `),
3236
- [splatName]: splatBytes(state, resolution)
3237
- },
3238
- manifest: {
3239
- assets,
3240
- cellSize,
3241
- cells: placements.cells,
3242
- extent,
3243
- placements: placementsName,
3244
- placementIds: placementIdsName,
3245
- terrain: {
3246
- columns: resolution,
3247
- heightMax,
3248
- heightMin,
3249
- heightmap: heightmapName,
3250
- layers: { splat: splatName, ...layers },
3251
- rows: resolution,
3252
- spacing: size / (resolution - 1)
3253
- },
3254
- version: 1
3255
- },
3256
- splat: {
3257
- masks: Object.fromEntries(SLOTS.map(({ component, id, plane }) => [id, [plane, component]])),
3258
- planes: PLANES,
3259
- size: resolution
3260
- }
3251
+ file: text(row2.file, biome, "bake.file"),
3252
+ key: row2.key === null ? null : text(row2.key, biome, "bake.key")
3261
3253
  };
3262
3254
  }
3263
- function splatBytes(state, resolution) {
3264
- const planeBytes = resolution * resolution * 4;
3265
- if (state.splat.length !== resolution * resolution * MATERIAL_IDS.length)
3266
- throw Error(
3267
- `World package: splat has ${String(state.splat.length)} weights, expected ${String(resolution * resolution * MATERIAL_IDS.length)}.`
3268
- );
3269
- const bytes = new Uint8Array(planeBytes * PLANES);
3270
- for (let row2 = 0; row2 < resolution; row2 += 1) {
3271
- const source = (resolution - 1 - row2) * resolution;
3272
- const rowOffset = row2 * resolution * 4;
3273
- for (let column2 = 0; column2 < resolution; column2 += 1) {
3274
- const sample = (source + column2) * MATERIAL_IDS.length;
3275
- const rowCol = rowOffset + column2 * 4;
3276
- for (const slot of SLOTS) {
3277
- const weight = state.splat[sample + slot.channel];
3278
- bytes[slot.plane * planeBytes + rowCol + slot.componentIndex] = Math.round(
3279
- (weight <= 0 ? 0 : weight >= 1 ? 1 : weight) * 255
3280
- );
3281
- }
3282
- }
3283
- }
3284
- return bytes;
3255
+ function spawn(value, biome) {
3256
+ const row2 = closed(value, biome, "spawn", SPAWN_FIELDS);
3257
+ return {
3258
+ at: point2(row2.at, biome, "spawn.at"),
3259
+ cameraOffset: point3(row2.cameraOffset, biome, "spawn.cameraOffset"),
3260
+ focus: point2(row2.focus, biome, "spawn.focus")
3261
+ };
3262
+ }
3263
+ function species(value, biome) {
3264
+ if (!Array.isArray(value) || value.length === 0)
3265
+ fail2(biome, "species", "must be a non-empty array of asset ids");
3266
+ const names = value.map((name, index) => text(name, biome, `species[${index}]`));
3267
+ for (const [index, name] of names.entries())
3268
+ if (names.indexOf(name) !== index) fail2(biome, `species[${index}]`, `repeats '${name}'`);
3269
+ return names;
3270
+ }
3271
+ function validateBiome(spec, name) {
3272
+ if (typeof name !== "string" || name.trim() === "")
3273
+ throw new TypeError("validateBiome needs the biome's name");
3274
+ const biome = name;
3275
+ const root = closed(spec, biome, "", SPEC_FIELDS);
3276
+ const aliases = root.aliases;
3277
+ if (!Array.isArray(aliases) || aliases.length === 0)
3278
+ fail2(biome, "aliases", "must be a non-empty array of words");
3279
+ const rows = (value, field, one) => {
3280
+ if (!Array.isArray(value)) fail2(biome, field, "must be an array");
3281
+ return value.map((entry, index) => one(entry, `${field}[${index}]`));
3282
+ };
3283
+ return {
3284
+ look: text(root.look, biome, "look"),
3285
+ bake: bake(root.bake, biome),
3286
+ landform: oneOf(root.landform, biome, "landform", LANDFORM_KINDS),
3287
+ sizeMeters: positive(root.sizeMeters, biome, "sizeMeters"),
3288
+ seed: whole(root.seed, biome, "seed"),
3289
+ stream: oneOf(root.stream, biome, "stream", STREAMS),
3290
+ cover: cover(root.cover, biome),
3291
+ foliage: rows(root.foliage, "foliage", (entry, at) => foliage(entry, biome, at)),
3292
+ grass: rows(root.grass, "grass", (entry, at) => grass(entry, biome, at)),
3293
+ layers: rows(root.layers, "layers", (entry, at) => layer(entry, biome, at)),
3294
+ water: rows(root.water, "water", (entry, at) => water(entry, biome, at)),
3295
+ spawn: spawn(root.spawn, biome),
3296
+ species: species(root.species, biome),
3297
+ aliases: aliases.map(
3298
+ (word, index) => text(word, biome, `aliases[${index}]`).toLowerCase()
3299
+ )
3300
+ };
3285
3301
  }
3286
3302
 
3287
- // src/core/bake-biome.ts
3303
+ // src/biome/bake-biome.ts
3288
3304
  function foliageScatterRules(foliage2, heights) {
3289
3305
  const [floor] = measureBands([], heights).elevationRange;
3290
3306
  return foliage2.map((row2) => ({
@@ -3295,6 +3311,8 @@ function foliageScatterRules(foliage2, heights) {
3295
3311
  maxSlope: row2.slope[1],
3296
3312
  minDistance: row2.spacing[0],
3297
3313
  ...row2.height === null ? {} : { minHeight: floor + row2.height[0], maxHeight: floor + row2.height[1] },
3314
+ ...row2.scale === void 0 ? {} : { scale: row2.scale },
3315
+ ...row2.mask === void 0 ? {} : { mask: row2.mask },
3298
3316
  avoidWater: true,
3299
3317
  opacity: 1,
3300
3318
  clear: []
@@ -3533,8 +3551,95 @@ async function decodeHeightPNG(input, options = {}) {
3533
3551
  hasEmbeddedRange: Number.isFinite(metadata.min) && Number.isFinite(metadata.max)
3534
3552
  };
3535
3553
  }
3554
+ var ENTRIES = ["index.js", "kit.js", "mcp/cook-child.js", "mcp/server.js"];
3555
+ function sourceFiles(directory, found = []) {
3556
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
3557
+ const absolute = join$1(directory, entry.name);
3558
+ if (entry.isDirectory()) sourceFiles(absolute, found);
3559
+ else if (entry.name.endsWith(".ts")) found.push(absolute);
3560
+ }
3561
+ return found;
3562
+ }
3563
+ var written = (file) => statSync(file).mtimeMs;
3564
+ function assertDistFresh(root) {
3565
+ const packageRoot = join$1(dirname(fileURLToPath(import.meta.url)), "..");
3566
+ const source = join$1(packageRoot, "src");
3567
+ if (!existsSync(source)) return;
3568
+ const built = ENTRIES.map((entry) => join$1(packageRoot, "dist", entry));
3569
+ if (!built.every((file) => existsSync(file))) return;
3570
+ const oldestBuild = Math.min(...built.map(written));
3571
+ const newestSource = Math.max(...sourceFiles(source).map(written));
3572
+ if (newestSource <= oldestBuild) return;
3573
+ throw new Error(
3574
+ "terrain: the built package is older than packages/terrain/src, so this bake would cook the previous world. Run: pnpm --filter @threenative/terrain build"
3575
+ );
3576
+ }
3577
+
3578
+ // src/core/stats.ts
3579
+ var CHANNEL_AREA_M2 = 1e5;
3580
+ var quantile = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
3581
+ function terrainStats(height, n, size) {
3582
+ const spacing = size / (n - 1);
3583
+ let low = Number.POSITIVE_INFINITY;
3584
+ let high = Number.NEGATIVE_INFINITY;
3585
+ let sum = 0;
3586
+ for (let i = 0; i < height.length; i += 1) {
3587
+ const v = height[i];
3588
+ low = Math.min(low, v);
3589
+ high = Math.max(high, v);
3590
+ sum += v;
3591
+ }
3592
+ const relief = high - low;
3593
+ const interior = (n - 2) * (n - 2);
3594
+ const slopes = new Float32Array(interior);
3595
+ const laplacian = new Float32Array(interior);
3596
+ let lapSum = 0;
3597
+ let k = 0;
3598
+ for (let z = 1; z < n - 1; z += 1) {
3599
+ for (let x = 1; x < n - 1; x += 1) {
3600
+ const i = z * n + x;
3601
+ const here = height[i];
3602
+ const east = height[i + 1];
3603
+ const west = height[i - 1];
3604
+ const south = height[i + n];
3605
+ const north = height[i - n];
3606
+ slopes[k] = Math.atan(Math.hypot(east - west, south - north) / (2 * spacing)) * 180 / Math.PI;
3607
+ laplacian[k] = (east + west + south + north - 4 * here) / (spacing * spacing);
3608
+ lapSum += laplacian[k];
3609
+ k += 1;
3610
+ }
3611
+ }
3612
+ const lapMean = lapSum / interior;
3613
+ let m2 = 0;
3614
+ let m4 = 0;
3615
+ for (let i = 0; i < interior; i += 1) {
3616
+ const d = laplacian[i] - lapMean;
3617
+ m2 += d * d;
3618
+ m4 += d * d * d * d;
3619
+ }
3620
+ m2 /= interior;
3621
+ m4 /= interior;
3622
+ slopes.sort();
3623
+ const filled = Float64Array.from(height);
3624
+ fillDepressions(filled, n);
3625
+ const flow = createFlow(n);
3626
+ routeFlow(filled, n, flow);
3627
+ const channelCells = CHANNEL_AREA_M2 / (spacing * spacing);
3628
+ let channels = 0;
3629
+ for (let i = 0; i < flow.cells.length; i += 1)
3630
+ if (flow.cells[i] >= channelCells) channels += 1;
3631
+ const areaKm2 = size * size / 1e6;
3632
+ return {
3633
+ relief,
3634
+ hypsometricIntegral: relief > 0 ? (sum / height.length - low) / relief : 0,
3635
+ slopeP50: quantile(slopes, 0.5),
3636
+ slopeP90: quantile(slopes, 0.9),
3637
+ drainageDensity: channels * spacing / 1e3 / areaKm2,
3638
+ curvatureKurtosis: m2 > 0 ? m4 / (m2 * m2) - 3 : 0
3639
+ };
3640
+ }
3536
3641
 
3537
- // src/core/massif.ts
3642
+ // src/ground/massif.ts
3538
3643
  function perimeterBase(n, edge, window, decay) {
3539
3644
  const loop = 4 * (n - 1);
3540
3645
  const at = (k) => {
@@ -3748,288 +3853,646 @@ function placeMassif(terrain, options) {
3748
3853
  const value = (raw + floor + Math.sqrt((raw - floor) ** 2 + 40 ** 2)) / 2;
3749
3854
  return [value, weight];
3750
3855
  };
3751
- const delta = new Float32Array(N * N);
3752
- for (let row2 = 0; row2 < N; row2++)
3753
- for (let column2 = 0; column2 < N; column2++) {
3754
- const x = column2 * cell - halfWorld;
3755
- const z = row2 * cell - halfWorld;
3756
- const [value, weight] = finalAt(x, z, coarse, coarseN);
3757
- if (weight > 0) {
3758
- const host = state.height[row2 * N + column2];
3759
- delta[row2 * N + column2] = weight * (value - host);
3856
+ const delta = new Float32Array(N * N);
3857
+ for (let row2 = 0; row2 < N; row2++)
3858
+ for (let column2 = 0; column2 < N; column2++) {
3859
+ const x = column2 * cell - halfWorld;
3860
+ const z = row2 * cell - halfWorld;
3861
+ const [value, weight] = finalAt(x, z, coarse, coarseN);
3862
+ if (weight > 0) {
3863
+ const host = state.height[row2 * N + column2];
3864
+ delta[row2 * N + column2] = weight * (value - host);
3865
+ }
3866
+ }
3867
+ const corners = [toWorld(0, 0), toWorld(1, 0), toWorld(0, 1), toWorld(1, 1)];
3868
+ const x0 = clamp(Math.min(...corners.map((p) => p[0])), -halfWorld, halfWorld);
3869
+ const x1 = clamp(Math.max(...corners.map((p) => p[0])), -halfWorld, halfWorld);
3870
+ const z0 = clamp(Math.min(...corners.map((p) => p[1])), -halfWorld, halfWorld);
3871
+ const z1 = clamp(Math.max(...corners.map((p) => p[1])), -halfWorld, halfWorld);
3872
+ const columns = Math.floor((x1 - x0) / spacing) + 1;
3873
+ const rows = Math.floor((z1 - z0) / spacing) + 1;
3874
+ const detail = new Float32Array(columns * rows);
3875
+ for (let row2 = 0; row2 < rows; row2++)
3876
+ for (let column2 = 0; column2 < columns; column2++) {
3877
+ const x = x0 + column2 * spacing;
3878
+ const z = z0 + row2 * spacing;
3879
+ const host = hostSmooth(x, z);
3880
+ const [value, weight] = finalAt(x, z, lifted, n);
3881
+ detail[row2 * columns + column2] = host + weight * (value - host);
3882
+ }
3883
+ const id = options.id ?? "massif";
3884
+ return {
3885
+ terrain: terrain.heightmap({
3886
+ id,
3887
+ data: { width: N, height: N, values: Array.from(delta) },
3888
+ blend: "add"
3889
+ }),
3890
+ placement: {
3891
+ tile: tile.id,
3892
+ at,
3893
+ rotation: turn * 180 / Math.PI,
3894
+ mirror,
3895
+ height,
3896
+ detail: { origin: [x0, z0], spacing, columns, rows, heights: detail }
3897
+ }
3898
+ };
3899
+ }
3900
+ var TILES = "https://tiles.mapterhorn.com";
3901
+ var TILE_PX = 512;
3902
+ var MAX_ZOOM = 17;
3903
+ var M_PER_DEG_LAT = 110574;
3904
+ var M_PER_DEG_LON = 111320;
3905
+ var EQUATOR_M_PER_PX = 40075016686e-3 / TILE_PX;
3906
+ var tileUrl = (z, x, y) => `${TILES}/${z}/${x}/${y}.webp`;
3907
+ function tileCacheDir() {
3908
+ const configured = process.env.TN_TERRAIN_TILE_CACHE;
3909
+ if (configured !== void 0 && configured !== "") return configured;
3910
+ return join$1(process.env.XDG_CACHE_HOME ?? join$1(homedir(), ".cache"), "threenative", "mapterhorn");
3911
+ }
3912
+ var column = (lon, z) => (lon + 180) / 360 * 2 ** z;
3913
+ function row(lat, z) {
3914
+ const rad = lat * Math.PI / 180;
3915
+ return (1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2 * 2 ** z;
3916
+ }
3917
+ var metersPerPixel = (lat, z) => EQUATOR_M_PER_PX * Math.cos(lat * Math.PI / 180) / 2 ** z;
3918
+ async function decodeTerrarium(bytes, url) {
3919
+ const { default: sharp } = await import('sharp');
3920
+ const { data, info } = await sharp(bytes).removeAlpha().raw().toBuffer({ resolveWithObject: true }).catch((error) => {
3921
+ throw new Error(
3922
+ `cook: ground survey tile ${url} could not be decoded (${error instanceof Error ? error.message : String(error)}).`
3923
+ );
3924
+ });
3925
+ if (info.width !== TILE_PX || info.height !== TILE_PX || info.channels !== 3) {
3926
+ throw new Error(
3927
+ `cook: ground survey tile ${url} is ${info.width}x${info.height} with ${info.channels} channels, not a ${TILE_PX} px RGB tile.`
3928
+ );
3929
+ }
3930
+ const heights = new Float32Array(TILE_PX * TILE_PX);
3931
+ for (let at = 0; at < heights.length; at += 1) {
3932
+ heights[at] = data[at * 3] * 256 + data[at * 3 + 1] + data[at * 3 + 2] / 256 - 32768;
3933
+ }
3934
+ return { width: TILE_PX, height: TILE_PX, heights };
3935
+ }
3936
+ async function loadTile(z, x, y) {
3937
+ const url = tileUrl(z, x, y);
3938
+ const file = join$1(tileCacheDir(), String(z), String(x), `${y}.webp`);
3939
+ const cached = await readFile(file).catch(() => void 0);
3940
+ if (cached !== void 0) return decodeTerrarium(new Uint8Array(cached), url);
3941
+ let bytes;
3942
+ try {
3943
+ const response = await fetch(url);
3944
+ if (response.status === 404) return void 0;
3945
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
3946
+ bytes = new Uint8Array(await response.arrayBuffer());
3947
+ } catch (error) {
3948
+ throw new Error(
3949
+ `cook: ground survey tile ${url} is not cached in ${tileCacheDir()} and could not be fetched (${error instanceof Error ? error.message : String(error)}). Pass ground: "procedural" to cook the preset's own noise instead.`
3950
+ );
3951
+ }
3952
+ const tile = await decodeTerrarium(bytes, url);
3953
+ await mkdir(dirname(file), { recursive: true });
3954
+ await writeFile(file, bytes);
3955
+ return tile;
3956
+ }
3957
+ var bilinear = (values, width, height, x, y) => {
3958
+ const fx = Math.min(width - 1, Math.max(0, x));
3959
+ const fy = Math.min(height - 1, Math.max(0, y));
3960
+ const x0 = Math.floor(fx);
3961
+ const y0 = Math.floor(fy);
3962
+ const x1 = Math.min(width - 1, x0 + 1);
3963
+ const y1 = Math.min(height - 1, y0 + 1);
3964
+ const tx = fx - x0;
3965
+ const ty = fy - y0;
3966
+ const top = values[y0 * width + x0] * (1 - tx) + values[y0 * width + x1] * tx;
3967
+ const bottom = values[y1 * width + x0] * (1 - tx) + values[y1 * width + x1] * tx;
3968
+ return top * (1 - ty) + bottom * ty;
3969
+ };
3970
+ async function stitch(survey, z) {
3971
+ const halfLat = survey.extentMeters / 2 / M_PER_DEG_LAT;
3972
+ const halfLon = survey.extentMeters / 2 / (M_PER_DEG_LON * Math.cos(survey.lat * Math.PI / 180));
3973
+ const west = column(survey.lon - halfLon, z);
3974
+ const east = column(survey.lon + halfLon, z);
3975
+ const north = row(survey.lat + halfLat, z);
3976
+ const south = row(survey.lat - halfLat, z);
3977
+ const x0 = Math.floor(west);
3978
+ const y0 = Math.floor(north);
3979
+ const width = (Math.floor(east) - x0 + 1) * TILE_PX;
3980
+ const height = (Math.floor(south) - y0 + 1) * TILE_PX;
3981
+ const stitched = new Float32Array(width * height);
3982
+ let missing = false;
3983
+ const tiles = [];
3984
+ for (let y = y0; y <= Math.floor(south); y += 1) {
3985
+ for (let x = x0; x <= Math.floor(east); x += 1) {
3986
+ tiles.push(
3987
+ loadTile(z, x, y).then((tile) => {
3988
+ if (tile === void 0) {
3989
+ missing = true;
3990
+ return;
3991
+ }
3992
+ for (let ty = 0; ty < TILE_PX; ty += 1) {
3993
+ for (let tx = 0; tx < TILE_PX; tx += 1) {
3994
+ stitched[((y - y0) * TILE_PX + ty) * width + (x - x0) * TILE_PX + tx] = tile.heights[ty * TILE_PX + tx];
3995
+ }
3996
+ }
3997
+ })
3998
+ );
3999
+ }
4000
+ }
4001
+ try {
4002
+ await Promise.all(tiles);
4003
+ } catch (error) {
4004
+ await Promise.allSettled(tiles);
4005
+ throw error;
4006
+ }
4007
+ if (missing) return void 0;
4008
+ return {
4009
+ stitched,
4010
+ width,
4011
+ height,
4012
+ left: (west - x0) * TILE_PX,
4013
+ top: (north - y0) * TILE_PX,
4014
+ spanX: (east - west) * TILE_PX,
4015
+ spanY: (south - north) * TILE_PX
4016
+ };
4017
+ }
4018
+ async function surveyHeights(survey, resolution) {
4019
+ if (!Number.isInteger(resolution) || resolution < 2 || resolution > 4097) {
4020
+ throw new RangeError(`cook: a survey needs a grid of 2..4097 samples, not ${resolution}.`);
4021
+ }
4022
+ const cell = survey.extentMeters / (resolution - 1);
4023
+ const wanted = Math.log2(metersPerPixel(survey.lat, 0) / cell);
4024
+ for (let z = Math.min(MAX_ZOOM, Math.max(0, Math.ceil(wanted))); z >= 0; z -= 1) {
4025
+ const raster = await stitch(survey, z);
4026
+ if (raster === void 0) continue;
4027
+ const { stitched, width, height, left, top, spanX, spanY } = raster;
4028
+ const values = new Float32Array(resolution * resolution);
4029
+ let min = Number.POSITIVE_INFINITY;
4030
+ let max = Number.NEGATIVE_INFINITY;
4031
+ for (let y = 0; y < resolution; y += 1) {
4032
+ for (let x = 0; x < resolution; x += 1) {
4033
+ const value = bilinear(
4034
+ stitched,
4035
+ width,
4036
+ height,
4037
+ left + x / (resolution - 1) * spanX,
4038
+ top + y / (resolution - 1) * spanY
4039
+ );
4040
+ values[y * resolution + x] = value;
4041
+ min = Math.min(min, value);
4042
+ max = Math.max(max, value);
3760
4043
  }
3761
4044
  }
3762
- const corners = [toWorld(0, 0), toWorld(1, 0), toWorld(0, 1), toWorld(1, 1)];
3763
- const x0 = clamp(Math.min(...corners.map((p) => p[0])), -halfWorld, halfWorld);
3764
- const x1 = clamp(Math.max(...corners.map((p) => p[0])), -halfWorld, halfWorld);
3765
- const z0 = clamp(Math.min(...corners.map((p) => p[1])), -halfWorld, halfWorld);
3766
- const z1 = clamp(Math.max(...corners.map((p) => p[1])), -halfWorld, halfWorld);
3767
- const columns = Math.floor((x1 - x0) / spacing) + 1;
3768
- const rows = Math.floor((z1 - z0) / spacing) + 1;
3769
- const detail = new Float32Array(columns * rows);
3770
- for (let row2 = 0; row2 < rows; row2++)
3771
- for (let column2 = 0; column2 < columns; column2++) {
3772
- const x = x0 + column2 * spacing;
3773
- const z = z0 + row2 * spacing;
3774
- const host = hostSmooth(x, z);
3775
- const [value, weight] = finalAt(x, z, lifted, n);
3776
- detail[row2 * columns + column2] = host + weight * (value - host);
4045
+ return {
4046
+ width: resolution,
4047
+ height: resolution,
4048
+ values,
4049
+ min,
4050
+ max,
4051
+ zoom: z,
4052
+ metersPerPixel: metersPerPixel(survey.lat, z)
4053
+ };
4054
+ }
4055
+ throw new Error(
4056
+ `cook: ground survey '${survey.name}' (${survey.lat}, ${survey.lon}) has no Mapterhorn tile at any zoom. Pass ground: "procedural" to cook the preset's own noise instead.`
4057
+ );
4058
+ }
4059
+
4060
+ // src/ground/surveys.ts
4061
+ var TILES2 = "Terrain tiles \xA9 Mapterhorn (https://mapterhorn.com/attribution), built from open elevation data; the producers and licences of its sources are listed there.";
4062
+ var USGS_3DEP = "United States 3DEP terrain data, U.S. Geological Survey (public domain, U.S. Government work).";
4063
+ var COPERNICUS = "Copernicus GLO-30 DEM, \xA9 DLR e.V. 2010-2014 and \xA9 Airbus Defence and Space GmbH 2014-2018, provided under COPERNICUS by the European Union and ESA; all rights reserved.";
4064
+ var SWISSTOPO = "swissALTI3D, Federal Office of Topography swisstopo (Open Government Data).";
4065
+ var IGN = "MNT LiDAR HD, Institut national de l'information g\xE9ographique et foresti\xE8re IGN (Licence Ouverte 2.0).";
4066
+ var GSI = "Digital elevation model of the Fundamental Geospatial Data, Geospatial Information Authority of Japan (\u56FD\u571F\u4EA4\u901A\u7701\u56FD\u571F\u5730\u7406\u9662).";
4067
+ var SURVEYS = {
4068
+ alpine: {
4069
+ name: "Matterhorn massif, Pennine Alps (Switzerland / Italy)",
4070
+ lat: 45.9763,
4071
+ lon: 7.6586,
4072
+ extentMeters: 6e3,
4073
+ attribution: `${SWISSTOPO} ${COPERNICUS} ${TILES2}`
4074
+ // measured: 2 164..4 468 m (the summit is 4 478 m, at 13 m per pixel)
4075
+ },
4076
+ temperateMountains: {
4077
+ name: "Sprague Lake and Glacier Creek, Rocky Mountain National Park, Colorado",
4078
+ lat: 40.32,
4079
+ lon: -105.6067,
4080
+ extentMeters: 6e3,
4081
+ attribution: `${USGS_3DEP} ${TILES2}`
4082
+ // measured: 2 385..3 433 m
4083
+ },
4084
+ rollingHills: {
4085
+ name: "Coon Valley, Driftless Area, Wisconsin",
4086
+ lat: 43.7019,
4087
+ lon: -91.0139,
4088
+ extentMeters: 6e3,
4089
+ attribution: `${USGS_3DEP} ${TILES2}`
4090
+ // measured: 211..391 m: 3 % relief over its 6 km, which is the preset's own 0.03 ratio
4091
+ },
4092
+ desertMesa: {
4093
+ name: "Monument Valley, Arizona / Utah",
4094
+ lat: 36.998,
4095
+ lon: -110.0985,
4096
+ extentMeters: 5e3,
4097
+ attribution: `${USGS_3DEP} ${TILES2}`
4098
+ // measured: 1 542..1 969 m (the valley floor to the butte tops)
4099
+ },
4100
+ coastalCliffs: {
4101
+ name: "\xC9tretat chalk cliffs, Normandy, France",
4102
+ lat: 49.707,
4103
+ lon: 0.203,
4104
+ extentMeters: 4e3,
4105
+ attribution: `${IGN} ${COPERNICUS} ${TILES2}`
4106
+ // measured: -3..109 m (the sea to the cliff top)
4107
+ },
4108
+ tundra: {
4109
+ name: "Trail Ridge, Rocky Mountain National Park, Colorado",
4110
+ lat: 40.4103,
4111
+ lon: -105.735,
4112
+ extentMeters: 5e3,
4113
+ attribution: `${USGS_3DEP} ${TILES2}`
4114
+ // measured: 2 946..3 798 m, above the tree line
4115
+ },
4116
+ volcanic: {
4117
+ name: "Mount Fuji, Honshu, Japan",
4118
+ lat: 35.3606,
4119
+ lon: 138.7274,
4120
+ extentMeters: 6e3,
4121
+ attribution: `${GSI} ${COPERNICUS} ${TILES2}`
4122
+ // measured: 1 535..3 770 m (the summit is 3 776 m)
4123
+ }
4124
+ };
4125
+ var MASSIFS = {
4126
+ temperateMountains: [
4127
+ {
4128
+ name: "Longs Peak and Mount Meeker, Rocky Mountain National Park, Colorado",
4129
+ lat: 40.2549,
4130
+ lon: -105.6101,
4131
+ extentMeters: 4400,
4132
+ attribution: `${USGS_3DEP} ${TILES2}`
3777
4133
  }
3778
- const id = options.id ?? "massif";
3779
- return {
3780
- terrain: terrain.heightmap({
3781
- id,
3782
- data: { width: N, height: N, values: Array.from(delta) },
3783
- blend: "add"
3784
- }),
3785
- placement: {
3786
- tile: tile.id,
3787
- at,
3788
- rotation: turn * 180 / Math.PI,
3789
- mirror,
3790
- height,
3791
- detail: { origin: [x0, z0], spacing, columns, rows, heights: detail }
4134
+ ],
4135
+ alpine: [
4136
+ {
4137
+ name: "Grand Teton and the Cathedral Group, Wyoming",
4138
+ lat: 43.7455,
4139
+ lon: -110.8024,
4140
+ extentMeters: 3600,
4141
+ attribution: `${USGS_3DEP} ${TILES2}`
4142
+ },
4143
+ {
4144
+ name: "Maroon Bells, Elk Mountains, Colorado",
4145
+ lat: 39.0708,
4146
+ lon: -106.989,
4147
+ extentMeters: 3600,
4148
+ attribution: `${USGS_3DEP} ${TILES2}`
3792
4149
  }
4150
+ ]
4151
+ };
4152
+ var LOCATION_EXTENT_METERS = 6e3;
4153
+ var finite = (value, axis) => {
4154
+ if (!Number.isFinite(value))
4155
+ throw new TypeError(`ground.location.${axis} must be a finite number.`);
4156
+ return value;
4157
+ };
4158
+ function locationSurvey(lat, lon) {
4159
+ const latitude = finite(lat, "lat");
4160
+ const longitude = finite(lon, "lon");
4161
+ if (Math.abs(latitude) > 90)
4162
+ throw new RangeError("ground.location.lat must be between -90 and 90.");
4163
+ if (Math.abs(longitude) > 180)
4164
+ throw new RangeError("ground.location.lon must be between -180 and 180.");
4165
+ return {
4166
+ name: `${latitude}, ${longitude}`,
4167
+ lat: latitude,
4168
+ lon: longitude,
4169
+ extentMeters: LOCATION_EXTENT_METERS,
4170
+ attribution: `${COPERNICUS} ${TILES2}`
3793
4171
  };
3794
4172
  }
3795
4173
 
3796
- // src/core/placements.ts
3797
- function validatePlacementOverrides(value = {}) {
3798
- finiteTree(value, "placementOverrides");
3799
- if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
3800
- throw new Error("Expected placementOverrides object");
3801
- return Object.fromEntries(
3802
- Object.entries(value).map(([key, entry]) => {
3803
- if (!key.length || key.length > 256)
3804
- throw new Error("Placement key must contain 1\u2013256 characters");
3805
- if (!entry || typeof entry !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(entry)))
3806
- throw new Error(`Invalid placement override '${key}'`);
3807
- const input = entry;
3808
- if (Object.keys(input).some(
3809
- (field) => !["position", "quaternion", "scale", "grounding"].includes(field)
3810
- ))
3811
- throw new Error(`Unknown placement override fields '${key}'`);
3812
- function vector(field, length) {
3813
- const values = input[field];
3814
- if (!Array.isArray(values) || values.length !== length || !Array.from(values).every(Number.isFinite))
3815
- throw new Error(`${key}.${field} must contain ${length} finite numbers`);
3816
- return Array.from(values);
4174
+ // src/ground/ground.ts
4175
+ async function readGroundHeightmap(projectRoot, asked) {
4176
+ const file = isAbsolute(asked.heightmap) ? asked.heightmap : resolve(projectRoot, asked.heightmap);
4177
+ const bytes = await readFile(file).catch(() => {
4178
+ throw new Error(`terrain_generate: ground.heightmap '${asked.heightmap}' cannot be read.`);
4179
+ });
4180
+ const range2 = asked.min === void 0 || asked.max === void 0 ? void 0 : { min: asked.min, max: asked.max };
4181
+ try {
4182
+ if (file.toLowerCase().endsWith(".r16")) {
4183
+ const side = Math.sqrt(bytes.length / 2);
4184
+ if (!Number.isInteger(side)) {
4185
+ throw new TypeError("a .r16 grid has no width of its own, so it must be square");
3817
4186
  }
3818
- const position = vector("position", 3);
3819
- const quaternion = vector("quaternion", 4);
3820
- const scale = vector("scale", 3);
3821
- if (scale.some((item) => item <= 0)) throw new Error(`${key}.scale must be positive`);
3822
- if (Math.abs(Math.hypot(...quaternion) - 1) > 1e-6)
3823
- throw new Error(`${key}.quaternion must be a unit quaternion`);
3824
- const grounding = input.grounding === void 0 ? true : input.grounding;
3825
- if (typeof grounding !== "boolean") throw new Error(`${key}.grounding must be boolean`);
3826
- return [key, { position, quaternion, scale, grounding }];
3827
- })
3828
- );
4187
+ if (range2 === void 0) {
4188
+ throw new TypeError("a .r16 grid carries no elevation range; name min and max in metres");
4189
+ }
4190
+ return decodeRAW16(bytes, { width: side, height: side, ...range2 });
4191
+ }
4192
+ const decoded = await decodeHeightPNG(bytes, range2 ?? {});
4193
+ if (decoded.bitDepth !== 16) {
4194
+ throw new TypeError(`it is ${decoded.bitDepth}-bit; export a 16-bit grayscale PNG`);
4195
+ }
4196
+ if (!decoded.hasEmbeddedRange && range2 === void 0) {
4197
+ throw new TypeError("it carries no elevation range; name min and max in metres");
4198
+ }
4199
+ return decoded;
4200
+ } catch (error) {
4201
+ throw new TypeError(
4202
+ `terrain_generate: ground.heightmap '${asked.heightmap}': ${error instanceof Error ? error.message : String(error)}`
4203
+ );
4204
+ }
3829
4205
  }
3830
- function applyPlacementOverrides(state, value) {
3831
- const overrides = validatePlacementOverrides(value);
3832
- const keys = new Set(state.instances.map((item) => item.id));
4206
+ function applyGroundLayer(layers, grid, scale, offset) {
4207
+ const at = layers.findIndex((layer2) => layer2.type === "heightmap" || layer2.type === "noise");
4208
+ const replaced = layers[at];
4209
+ if (replaced === void 0)
4210
+ throw new Error("cook: the recipe authors no ground layer to replace.");
4211
+ const preset = replaced.type === "noise";
4212
+ layers[at] = {
4213
+ id: "ground",
4214
+ type: "heightmap",
4215
+ enabled: replaced.enabled ?? true,
4216
+ opacity: replaced.opacity ?? 1,
4217
+ params: {
4218
+ // The recipe inlines its heights, so they are plain numbers on a 0.1 m lattice like the
4219
+ // starters' own crops: the same precision, and the same size of recipe.json.
4220
+ data: {
4221
+ width: grid.width,
4222
+ height: grid.height,
4223
+ values: Array.from(grid.values, (value) => Math.round(value * 10) / 10)
4224
+ },
4225
+ scale,
4226
+ offset
4227
+ }
4228
+ };
4229
+ if (!preset) return;
4230
+ for (let index = layers.length - 1; index >= 0; index -= 1) {
4231
+ const layer2 = layers[index];
4232
+ const shape = layer2.type === "stamp" ? layer2.params.shape : void 0;
4233
+ if (shape === "mountain" || shape === "crater") layers.splice(index, 1);
4234
+ }
4235
+ }
4236
+ function seededCrop(row2, seed) {
4237
+ if (seed === void 0) return row2;
4238
+ const next = random(hashString(`survey:${seed}`));
4239
+ const east = (next() * 2 - 1) * 0.6 * row2.extentMeters;
4240
+ const north = (next() * 2 - 1) * 0.6 * row2.extentMeters;
4241
+ return {
4242
+ ...row2,
4243
+ lat: row2.lat + north / 111320,
4244
+ lon: row2.lon + east / (111320 * Math.cos(row2.lat * Math.PI / 180))
4245
+ };
4246
+ }
4247
+ async function forestFloor(document, row2, seed) {
4248
+ const { resolution, size } = document.config;
4249
+ const next = random(hashString(`floor:${seed ?? 0}`));
4250
+ const spots = Array.from({ length: seed === void 0 ? 0 : 12 }, () => {
4251
+ const east = (next() * 2 - 1) * 0.4 * row2.extentMeters;
4252
+ const north = (next() * 2 - 1) * 0.4 * row2.extentMeters;
4253
+ return [north, east];
4254
+ });
4255
+ const patch = (north, east) => ({
4256
+ ...row2,
4257
+ lat: row2.lat + north / 111320,
4258
+ lon: row2.lon + east / (111320 * Math.cos(row2.lat * Math.PI / 180)),
4259
+ extentMeters: size
4260
+ });
4261
+ const fine = (resolution - 1) * 2 + 1;
4262
+ let picked;
4263
+ for (const [north, east] of [...spots, [0, 0]]) {
4264
+ const survey2 = patch(north, east);
4265
+ const sampled = await surveyHeights(survey2, fine);
4266
+ const gated = everyOther(sampled, resolution);
4267
+ const stats = terrainStats(gated.values, resolution, size);
4268
+ picked = { survey: survey2, grid: sampled.metersPerPixel <= size / (fine - 1) ? sampled : gated };
4269
+ if (isForestFloor(
4270
+ gated.max - gated.min,
4271
+ stats.slopeP90,
4272
+ size,
4273
+ flatShare(gated.values, resolution)
4274
+ ))
4275
+ break;
4276
+ }
4277
+ const { survey, grid } = picked;
4278
+ document.config.resolution = grid.width;
4279
+ applyGroundLayer(document.layers, grid, 1, -grid.min);
4280
+ const at = document.layers.findIndex((layer2) => layer2.type === "erode");
4281
+ document.layers = document.layers.filter((layer2) => layer2.type !== "erode");
4282
+ document.layers.splice(at < 0 ? 1 : at, 0, ...structuredClone(SURVEYED_EROSION));
3833
4283
  return {
3834
- ...state,
3835
- instances: state.instances.map((item) => {
3836
- const { transform: _, ...base } = item;
3837
- return Object.hasOwn(overrides, item.id) ? { ...base, transform: overrides[item.id] } : base;
3838
- }),
3839
- diagnostics: [
3840
- ...state.diagnostics.filter(
3841
- (message) => !message.startsWith("Unmatched placement override '")
3842
- ),
3843
- ...Object.keys(overrides).filter((key) => !keys.has(key)).map((key) => `Unmatched placement override '${key}'`)
3844
- ]
4284
+ survey: { row: survey, scale: 1, offset: -grid.min },
4285
+ ground: {
4286
+ source: "survey",
4287
+ name: survey.name,
4288
+ lat: survey.lat,
4289
+ lon: survey.lon,
4290
+ attribution: survey.attribution,
4291
+ ...tilesRead(grid)
4292
+ },
4293
+ readme: groundReadme(survey, grid)
3845
4294
  };
3846
4295
  }
3847
-
3848
- // src/core/stats.ts
3849
- var CHANNEL_AREA_M2 = 1e5;
3850
- var quantile = (sorted, q) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))];
3851
- function terrainStats(height, n, size) {
3852
- const spacing = size / (n - 1);
3853
- let low = Number.POSITIVE_INFINITY;
3854
- let high = Number.NEGATIVE_INFINITY;
3855
- let sum = 0;
3856
- for (let i = 0; i < height.length; i += 1) {
3857
- const v = height[i];
3858
- low = Math.min(low, v);
3859
- high = Math.max(high, v);
3860
- sum += v;
4296
+ function everyOther(grid, resolution) {
4297
+ const step = (grid.width - 1) / (resolution - 1);
4298
+ const values = new Float32Array(resolution * resolution);
4299
+ for (let r = 0; r < resolution; r++)
4300
+ for (let c = 0; c < resolution; c++)
4301
+ values[r * resolution + c] = grid.values[r * step * grid.width + c * step];
4302
+ let min = Number.POSITIVE_INFINITY;
4303
+ let max = Number.NEGATIVE_INFINITY;
4304
+ for (const value of values) {
4305
+ min = Math.min(min, value);
4306
+ max = Math.max(max, value);
3861
4307
  }
3862
- const relief = high - low;
3863
- const interior = (n - 2) * (n - 2);
3864
- const slopes = new Float32Array(interior);
3865
- const laplacian = new Float32Array(interior);
3866
- let lapSum = 0;
3867
- let k = 0;
3868
- for (let z = 1; z < n - 1; z += 1) {
3869
- for (let x = 1; x < n - 1; x += 1) {
3870
- const i = z * n + x;
3871
- const here = height[i];
3872
- const east = height[i + 1];
3873
- const west = height[i - 1];
3874
- const south = height[i + n];
3875
- const north = height[i - n];
3876
- slopes[k] = Math.atan(Math.hypot(east - west, south - north) / (2 * spacing)) * 180 / Math.PI;
3877
- laplacian[k] = (east + west + south + north - 4 * here) / (spacing * spacing);
3878
- lapSum += laplacian[k];
3879
- k += 1;
4308
+ return { ...grid, width: resolution, height: resolution, values, min, max };
4309
+ }
4310
+ var tilesRead = (grid) => ({
4311
+ tiles: "mapterhorn",
4312
+ zoom: grid.zoom,
4313
+ metersPerPixel: Math.round(grid.metersPerPixel * 100) / 100
4314
+ });
4315
+ var groundReadme = (survey, grid) => [
4316
+ "# Cooked terrain world",
4317
+ "",
4318
+ `The ground is a real survey: ${survey.name} at ${survey.lat}, ${survey.lon},`,
4319
+ `${survey.extentMeters} m across, read from Mapterhorn tiles at zoom ${grid.zoom} (${tilesRead(grid).metersPerPixel} m per pixel), resampled onto the recipe's grid.`,
4320
+ "",
4321
+ "## Data attribution",
4322
+ "",
4323
+ survey.attribution,
4324
+ ""
4325
+ ].join("\n");
4326
+ var SURVEYED_EROSION = [
4327
+ {
4328
+ type: "erode",
4329
+ id: "surface-runoff",
4330
+ params: {
4331
+ method: "hydraulic",
4332
+ droplets: 2e4,
4333
+ maxSteps: 45,
4334
+ capacity: 2,
4335
+ erosion: 0.015,
4336
+ strength: 2e-3,
4337
+ deposition: 0.2,
4338
+ evaporation: 0.035
3880
4339
  }
4340
+ },
4341
+ {
4342
+ type: "erode",
4343
+ id: "loose-talus",
4344
+ params: { method: "thermal", talus: 38, iterations: 1, rate: 4e-3 }
3881
4345
  }
3882
- const lapMean = lapSum / interior;
3883
- let m2 = 0;
3884
- let m4 = 0;
3885
- for (let i = 0; i < interior; i += 1) {
3886
- const d = laplacian[i] - lapMean;
3887
- m2 += d * d;
3888
- m4 += d * d * d * d;
4346
+ ];
4347
+ var FLOOR_RELIEF = 90;
4348
+ var FLOOR_SLOPE = 28;
4349
+ var FLOOR_FLAT = 0.02;
4350
+ function flatShare(values, resolution) {
4351
+ let flat = 0;
4352
+ for (let r = 1; r < resolution - 1; r++)
4353
+ for (let c = 1; c < resolution - 1; c++) {
4354
+ const h = values[r * resolution + c];
4355
+ const near = [
4356
+ values[r * resolution + c - 1],
4357
+ values[r * resolution + c + 1],
4358
+ values[(r - 1) * resolution + c],
4359
+ values[(r + 1) * resolution + c]
4360
+ ];
4361
+ if (near.every((n) => Math.abs(n - h) < 0.02)) flat++;
4362
+ }
4363
+ return flat / (resolution - 2) ** 2;
4364
+ }
4365
+ function isForestFloor(relief, slopeP90, size, flat = 0) {
4366
+ return relief <= FLOOR_RELIEF * Math.max(1, size / 512) && slopeP90 <= FLOOR_SLOPE && flat <= FLOOR_FLAT;
4367
+ }
4368
+ async function applyGround(document, request2, kind) {
4369
+ const asked = request2.ground;
4370
+ if (asked === "procedural") return { ground: { source: "procedural" } };
4371
+ if (asked !== void 0 && "heightmap" in asked) {
4372
+ applyGroundLayer(document.layers, await readGroundHeightmap(request2.projectRoot, asked), 1, 0);
4373
+ return { ground: { source: "heightmap", heightmap: asked.heightmap } };
3889
4374
  }
3890
- m2 /= interior;
3891
- m4 /= interior;
3892
- slopes.sort();
3893
- const filled = Float64Array.from(height);
3894
- fillDepressions(filled, n);
3895
- const flow = createFlow(n);
3896
- routeFlow(filled, n, flow);
3897
- const channelCells = CHANNEL_AREA_M2 / (spacing * spacing);
3898
- let channels = 0;
3899
- for (let i = 0; i < flow.cells.length; i += 1)
3900
- if (flow.cells[i] >= channelCells) channels += 1;
3901
- const areaKm2 = size * size / 1e6;
4375
+ const survey = asked !== void 0 ? locationSurvey(asked.location.lat, asked.location.lon) : kind === void 0 ? void 0 : seededCrop(SURVEYS[kind], request2.seed);
4376
+ if (survey === void 0) return { ground: { source: "procedural" } };
4377
+ if (request2.backdropRange !== void 0 && asked === void 0)
4378
+ return forestFloor(document, kind === void 0 ? survey : SURVEYS[kind], request2.seed);
4379
+ const grid = await surveyHeights(survey, document.config.resolution);
4380
+ const relief = kind === void 0 ? void 0 : LANDFORMS[kind].reliefRatio * document.config.size;
4381
+ const scale = relief === void 0 ? 1 : relief / (grid.max - grid.min || 1);
4382
+ applyGroundLayer(document.layers, grid, scale, -grid.min * scale);
3902
4383
  return {
3903
- relief,
3904
- hypsometricIntegral: relief > 0 ? (sum / height.length - low) / relief : 0,
3905
- slopeP50: quantile(slopes, 0.5),
3906
- slopeP90: quantile(slopes, 0.9),
3907
- drainageDensity: channels * spacing / 1e3 / areaKm2,
3908
- curvatureKurtosis: m2 > 0 ? m4 / (m2 * m2) - 3 : 0
4384
+ survey: { row: survey, scale, offset: -grid.min * scale },
4385
+ ground: {
4386
+ source: "survey",
4387
+ name: survey.name,
4388
+ lat: survey.lat,
4389
+ lon: survey.lon,
4390
+ attribution: survey.attribution,
4391
+ ...tilesRead(grid)
4392
+ },
4393
+ // The attribution rides with the kit: the data source requires it wherever the world is shipped.
4394
+ readme: groundReadme(survey, grid)
3909
4395
  };
3910
4396
  }
3911
-
3912
- // src/core/surveys.ts
3913
- var TILES = "AWS Terrain Tiles (github.com/tilezen/joerd, Mapzen terrain tiles).";
3914
- var USGS_3DEP = "United States 3DEP (formerly NED) terrain data courtesy of the U.S. Geological Survey.";
3915
- var EU_DEM = "Produced using Copernicus data and information funded by the European Union - EU-DEM layers.";
3916
- var SRTM = "SRTM data courtesy of the U.S. Geological Survey.";
3917
- var SURVEYS = {
3918
- alpine: {
3919
- name: "Matterhorn massif, Pennine Alps (Switzerland / Italy)",
3920
- lat: 45.9763,
3921
- lon: 7.6586,
3922
- extentMeters: 6e3,
3923
- zoom: 12,
3924
- attribution: `${EU_DEM} ${TILES}`
3925
- // measured: 2 168..4 352 m (the summit is 4 478 m, at about 30 m per pixel)
3926
- },
3927
- temperateMountains: {
3928
- name: "Sprague Lake and Glacier Creek, Rocky Mountain National Park, Colorado",
3929
- lat: 40.32,
3930
- lon: -105.6067,
3931
- extentMeters: 6e3,
3932
- zoom: 12,
3933
- attribution: `${USGS_3DEP} ${TILES}`
3934
- // measured: 2 387..3 434 m
3935
- },
3936
- rollingHills: {
3937
- name: "Coon Valley, Driftless Area, Wisconsin",
3938
- lat: 43.7019,
3939
- lon: -91.0139,
3940
- extentMeters: 6e3,
3941
- zoom: 12,
3942
- attribution: `${USGS_3DEP} ${TILES}`
3943
- // measured: 209..391 m: 3 % relief over its 6 km, which is the preset's own 0.03 ratio
3944
- },
3945
- desertMesa: {
3946
- name: "Monument Valley, Arizona / Utah",
3947
- lat: 36.998,
3948
- lon: -110.0985,
3949
- extentMeters: 5e3,
3950
- zoom: 12,
3951
- attribution: `${USGS_3DEP} ${TILES}`
3952
- // measured: 1 542..1 972 m (the valley floor to the butte tops)
3953
- },
3954
- coastalCliffs: {
3955
- name: "\xC9tretat chalk cliffs, Normandy, France",
3956
- lat: 49.707,
3957
- lon: 0.203,
3958
- extentMeters: 4e3,
3959
- zoom: 12,
3960
- attribution: `${EU_DEM} ${TILES}`
3961
- // measured: -9..112 m (the sea to the cliff top)
3962
- },
3963
- tundra: {
3964
- name: "Trail Ridge, Rocky Mountain National Park, Colorado",
3965
- lat: 40.4103,
3966
- lon: -105.735,
3967
- extentMeters: 5e3,
3968
- zoom: 12,
3969
- attribution: `${USGS_3DEP} ${TILES}`
3970
- // measured: 2 956..3 797 m, above the tree line
3971
- },
3972
- volcanic: {
3973
- name: "Mount Fuji, Honshu, Japan",
3974
- lat: 35.3606,
3975
- lon: 138.7274,
3976
- extentMeters: 6e3,
3977
- zoom: 12,
3978
- attribution: `${SRTM} ${TILES}`
3979
- // measured: 1 548..3 753 m (the summit is 3 776 m)
3980
- }
3981
- };
3982
- var MASSIFS = {
3983
- temperateMountains: [
3984
- {
3985
- name: "Longs Peak and Mount Meeker, Rocky Mountain National Park, Colorado",
3986
- lat: 40.2549,
3987
- lon: -105.6101,
3988
- extentMeters: 4400,
3989
- zoom: 12,
3990
- attribution: `${USGS_3DEP} ${TILES}`
4397
+ var RING_SCALE = 10;
4398
+ function massifBearing(cameraOffset) {
4399
+ const look = Math.atan2(-cameraOffset[2], -cameraOffset[0]) * 180 / Math.PI;
4400
+ return [look - MASSIF_SPREAD, look + MASSIF_SPREAD];
4401
+ }
4402
+ var MASSIF_SPREAD = 25;
4403
+ var MASSIF_ATTEMPTS = 6;
4404
+ var WOODED_FOOT = 0.6;
4405
+ function woodedFoot(detail, height) {
4406
+ const at = (r, c) => detail.heights[r * detail.columns + c];
4407
+ let floor = Number.POSITIVE_INFINITY;
4408
+ for (let i = 0; i < detail.heights.length; i++)
4409
+ floor = Math.min(floor, detail.heights[i]);
4410
+ const steep = Math.tan(40 * Math.PI / 180);
4411
+ let lower = 0;
4412
+ let gentle = 0;
4413
+ for (let r = 1; r < detail.rows - 1; r++)
4414
+ for (let c = 1; c < detail.columns - 1; c++) {
4415
+ const h = at(r, c);
4416
+ if (h < floor + 50 || h > floor + height / 2) continue;
4417
+ const dx = (at(r, c + 1) - at(r, c - 1)) / (2 * detail.spacing);
4418
+ const dz = (at(r + 1, c) - at(r - 1, c)) / (2 * detail.spacing);
4419
+ lower++;
4420
+ if (Math.hypot(dx, dz) < steep) gentle++;
4421
+ }
4422
+ return lower === 0 ? 0 : gentle / lower;
4423
+ }
4424
+ async function farRing(request2, kind, ground, config, cameraOffset) {
4425
+ const range2 = request2.backdropRange ?? kind;
4426
+ const rows = range2 === void 0 ? void 0 : MASSIFS[range2];
4427
+ if (request2.backdrop === "none" || rows === void 0 || ground.survey === void 0)
4428
+ return { decision: { source: "none" } };
4429
+ const { row: row2, scale, offset } = ground.survey;
4430
+ const resolution = 257;
4431
+ const MASSIF_RESOLUTION = 257;
4432
+ const fetchMassif = async (massif2) => {
4433
+ const grid = await surveyHeights(massif2, MASSIF_RESOLUTION).catch((error) => {
4434
+ throw new Error(
4435
+ `cook: far-ring massif '${massif2.name}': ${error instanceof Error ? error.message : String(error)} Pass backdrop: "none" to cook without the far ring.`
4436
+ );
4437
+ });
4438
+ return {
4439
+ id: massif2.name,
4440
+ size: massif2.extentMeters,
4441
+ resolution: MASSIF_RESOLUTION,
4442
+ heights: grid.values
4443
+ };
4444
+ };
4445
+ const [ringGrid, ...tiles] = await Promise.all([
4446
+ surveyHeights({ ...row2, extentMeters: row2.extentMeters * RING_SCALE }, resolution),
4447
+ ...rows.map(fetchMassif)
4448
+ ]);
4449
+ const size = config.size * RING_SCALE;
4450
+ const host = new Terrain({ size, resolution, seed: config.seed }).heightmap({
4451
+ id: "ring",
4452
+ data: {
4453
+ width: resolution,
4454
+ height: resolution,
4455
+ values: Array.from(ringGrid.values, (value) => value * scale + offset)
3991
4456
  }
3992
- ],
3993
- alpine: [
3994
- {
3995
- name: "Grand Teton and the Cathedral Group, Wyoming",
3996
- lat: 43.7455,
3997
- lon: -110.8024,
3998
- extentMeters: 3600,
3999
- zoom: 12,
4000
- attribution: `${USGS_3DEP} ${TILES}`
4001
- },
4002
- {
4003
- name: "Maroon Bells, Elk Mountains, Colorado",
4004
- lat: 39.0708,
4005
- lon: -106.989,
4006
- extentMeters: 3600,
4007
- zoom: 12,
4008
- attribution: `${USGS_3DEP} ${TILES}`
4457
+ });
4458
+ let chosen;
4459
+ let best = -1;
4460
+ for (let attempt = 0; attempt < MASSIF_ATTEMPTS && best < WOODED_FOOT; attempt++) {
4461
+ const placed = placeMassif(host, {
4462
+ seed: (request2.seed ?? config.seed) + attempt * 7919,
4463
+ tile: tiles,
4464
+ keepOut: config.size * 1.25,
4465
+ bearing: massifBearing(cameraOffset)
4466
+ });
4467
+ const foot = woodedFoot(placed.placement.detail, placed.placement.height);
4468
+ if (foot > best) {
4469
+ best = foot;
4470
+ chosen = placed;
4009
4471
  }
4010
- ]
4011
- };
4012
- var LOCATION_EXTENT_METERS = 6e3;
4013
- var LOCATION_ZOOM = 12;
4014
- var finite = (value, axis) => {
4015
- if (!Number.isFinite(value))
4016
- throw new TypeError(`ground.location.${axis} must be a finite number.`);
4017
- return value;
4018
- };
4019
- function locationSurvey(lat, lon) {
4020
- const latitude = finite(lat, "lat");
4021
- const longitude = finite(lon, "lon");
4022
- if (Math.abs(latitude) > 90)
4023
- throw new RangeError("ground.location.lat must be between -90 and 90.");
4024
- if (Math.abs(longitude) > 180)
4025
- throw new RangeError("ground.location.lon must be between -180 and 180.");
4472
+ }
4473
+ const { terrain, placement } = chosen;
4474
+ const picked = rows[tiles.findIndex((tile) => tile.id === placement.tile)];
4475
+ const decision = {
4476
+ source: "massif",
4477
+ name: picked.name,
4478
+ lat: picked.lat,
4479
+ lon: picked.lon,
4480
+ attribution: picked.attribution,
4481
+ at: [round(placement.at[0]), round(placement.at[1])],
4482
+ rotation: round(placement.rotation),
4483
+ mirror: placement.mirror,
4484
+ height: round(placement.height)
4485
+ };
4486
+ const heights = Array.from(terrain.evaluate().height, round);
4487
+ const { detail } = placement;
4488
+ const massif = {
4489
+ ...decision,
4490
+ detail: { ...detail, heights: Array.from(detail.heights, (h) => Math.round(h * 10) / 10) }
4491
+ };
4026
4492
  return {
4027
- name: `${latitude}, ${longitude}`,
4028
- lat: latitude,
4029
- lon: longitude,
4030
- extentMeters: LOCATION_EXTENT_METERS,
4031
- zoom: LOCATION_ZOOM,
4032
- attribution: `${SRTM} ${TILES}`
4493
+ decision,
4494
+ file: `${JSON.stringify({ size, resolution, heights, massif })}
4495
+ `
4033
4496
  };
4034
4497
  }
4035
4498
  function fail3(reason) {
@@ -4087,6 +4550,7 @@ async function extract(archive, target) {
4087
4550
  }
4088
4551
  fail3("END");
4089
4552
  }
4553
+ var DEFAULT_SKY_HDRI = "hdri/kloofendal_48d_partly_cloudy_1k.hdr";
4090
4554
  async function starterAssetsDir() {
4091
4555
  const root = dirname(fileURLToPath(import.meta.resolve("@threenative/terrain/package.json")));
4092
4556
  const local = join$1(root, "starter-assets");
@@ -4120,274 +4584,307 @@ async function starterAssetsDir() {
4120
4584
  archive = Buffer.concat(chunks);
4121
4585
  }
4122
4586
  if (archive.length !== manifest.bytes) fail3("SIZE");
4123
- if (createHash("sha256").update(archive).digest("hex") !== manifest.sha256) fail3("SHA256");
4124
- await mkdir(dirname(cache), { recursive: true });
4125
- const tmp = await mkdtemp(`${cache}.tmp-`);
4126
- try {
4127
- await extract(archive, tmp);
4128
- try {
4129
- await rename(tmp, cache);
4130
- } catch (error) {
4131
- if (!await isDirectory(cache) || !["EEXIST", "ENOTEMPTY"].includes(error.code ?? ""))
4132
- throw error;
4133
- }
4134
- } finally {
4135
- await rm(tmp, { recursive: true, force: true });
4136
- }
4137
- return cache;
4138
- }
4139
-
4140
- // src/mcp/glb-stats.ts
4141
- var GLB_MAGIC = 1179937895;
4142
- var JSON_CHUNK = 1313821514;
4143
- var INSTANCING = "EXT_mesh_gpu_instancing";
4144
- var TRIANGLE_MODES = /* @__PURE__ */ new Set([4, 5, 6]);
4145
- function jsonChunk(bytes) {
4146
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
4147
- if (bytes.byteLength < 20 || view.getUint32(0, true) !== GLB_MAGIC) {
4148
- throw new Error("glb-stats: not a GLB, the glTF binary header is missing.");
4149
- }
4150
- if (view.getUint32(4, true) !== 2 || view.getUint32(8, true) !== bytes.byteLength) {
4151
- throw new Error(
4152
- "glb-stats: the GLB version is not 2 or its header length is not the file size."
4153
- );
4154
- }
4155
- const length = view.getUint32(12, true);
4156
- if (view.getUint32(16, true) !== JSON_CHUNK || 20 + length > bytes.byteLength) {
4157
- throw new Error("glb-stats: the first GLB chunk is not a complete JSON chunk.");
4158
- }
4159
- return JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + length)));
4160
- }
4161
- function measureGlb(bytes) {
4162
- const gltf = jsonChunk(bytes);
4163
- const nodes = gltf.nodes ?? [];
4164
- const accessorCount = (index) => {
4165
- const count2 = index === void 0 ? void 0 : gltf.accessors?.[index]?.count;
4166
- if (count2 === void 0) throw new Error(`glb-stats: accessor ${index} is missing.`);
4167
- return count2;
4168
- };
4169
- const stats = { draws: 0, instances: 0, triangles: 0 };
4170
- const seen = /* @__PURE__ */ new Set();
4171
- const visit = (index) => {
4172
- const node = nodes[index];
4173
- if (node === void 0) throw new Error(`glb-stats: node ${index} is missing.`);
4174
- if (seen.has(index)) return;
4175
- seen.add(index);
4176
- if (node.mesh !== void 0) {
4177
- const mesh = gltf.meshes?.[node.mesh];
4178
- if (mesh === void 0) throw new Error(`glb-stats: mesh ${node.mesh} is missing.`);
4179
- const attributes = node.extensions?.[INSTANCING]?.attributes;
4180
- const copies = attributes === void 0 ? 1 : accessorCount(Object.values(attributes)[0]);
4181
- if (attributes !== void 0) stats.instances += copies;
4182
- for (const primitive of mesh.primitives) {
4183
- stats.draws += 1;
4184
- if (!TRIANGLE_MODES.has(primitive.mode ?? 4)) continue;
4185
- const vertices = accessorCount(primitive.indices ?? primitive.attributes.POSITION);
4186
- stats.triangles += (primitive.mode === 5 || primitive.mode === 6 ? Math.max(vertices - 2, 0) : Math.floor(vertices / 3)) * copies;
4187
- }
4188
- }
4189
- for (const child of node.children ?? []) visit(child);
4190
- };
4191
- const scene = gltf.scenes?.[gltf.scene ?? 0];
4192
- for (const root of scene?.nodes ?? (gltf.scenes === void 0 ? nodes.keys() : [])) visit(root);
4193
- return stats;
4194
- }
4195
- var TERRARIUM = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium";
4196
- var TILE_PX = 256;
4197
- var M_PER_DEG_LAT = 110574;
4198
- var M_PER_DEG_LON = 111320;
4199
- var tileUrl = (z, x, y) => `${TERRARIUM}/${z}/${x}/${y}.png`;
4200
- function tileCacheDir() {
4201
- const configured = process.env.TN_TERRAIN_TILE_CACHE;
4202
- if (configured !== void 0 && configured !== "") return configured;
4203
- return join$1(process.env.XDG_CACHE_HOME ?? join$1(homedir(), ".cache"), "threenative", "terrarium");
4204
- }
4205
- var column = (lon, z) => (lon + 180) / 360 * 2 ** z;
4206
- function row(lat, z) {
4207
- const rad = lat * Math.PI / 180;
4208
- return (1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2 * 2 ** z;
4209
- }
4210
- function readPNGChunks(bytes, url) {
4211
- const signature = [137, 80, 78, 71, 13, 10, 26, 10];
4212
- if (bytes.length < 33 || !signature.every((value, at) => bytes[at] === value)) {
4213
- throw new Error(`cook: ground survey tile ${url} is not a PNG.`);
4214
- }
4215
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
4216
- const decoder2 = new TextDecoder();
4217
- const idat = [];
4218
- let width = 0;
4219
- let height = 0;
4220
- let bitDepth = 0;
4221
- let colorType = 0;
4222
- let interlace = 0;
4223
- let offset = 8;
4224
- while (offset + 12 <= bytes.length) {
4225
- const length = view.getUint32(offset);
4226
- const type = decoder2.decode(bytes.subarray(offset + 4, offset + 8));
4227
- const end = offset + 12 + length;
4228
- if (end > bytes.length) throw new Error(`cook: ground survey tile ${url} is truncated.`);
4229
- if (type === "IHDR") {
4230
- width = view.getUint32(offset + 8);
4231
- height = view.getUint32(offset + 12);
4232
- bitDepth = bytes[offset + 16];
4233
- colorType = bytes[offset + 17];
4234
- interlace = bytes[offset + 20];
4235
- }
4236
- if (type === "IDAT") idat.push(bytes.subarray(offset + 8, end - 4));
4237
- if (type === "IEND") return { width, height, bitDepth, colorType, interlace, idat };
4238
- offset = end;
4239
- }
4240
- throw new Error(`cook: ground survey tile ${url} is incomplete.`);
4241
- }
4242
- function paeth2(left, up, corner) {
4243
- const p = left + up - corner;
4244
- const pa = Math.abs(p - left);
4245
- const pb = Math.abs(p - up);
4246
- const pc = Math.abs(p - corner);
4247
- if (pa <= pb && pa <= pc) return left;
4248
- return pb <= pc ? up : corner;
4249
- }
4250
- function predicted(filter, left, up, corner) {
4251
- if (filter === 1) return left;
4252
- if (filter === 2) return up;
4253
- if (filter === 3) return left + up >> 1;
4254
- if (filter === 4) return paeth2(left, up, corner);
4255
- return 0;
4256
- }
4257
- function unfilter(raw, width, height, channels, url) {
4258
- const stride = width * channels;
4259
- const pixels = new Uint8Array(stride * height);
4260
- for (let y = 0; y < height; y += 1) {
4261
- const filter = raw[y * (stride + 1)];
4262
- if (filter > 4)
4263
- throw new Error(`cook: ground survey tile ${url} uses PNG row filter ${filter}.`);
4264
- for (let x = 0; x < stride; x += 1) {
4265
- const at = y * stride + x;
4266
- const left = x >= channels ? pixels[at - channels] : 0;
4267
- const up = y > 0 ? pixels[at - stride] : 0;
4268
- const corner = y > 0 && x >= channels ? pixels[at - stride - channels] : 0;
4269
- const value = raw[y * (stride + 1) + 1 + x];
4270
- pixels[at] = value + predicted(filter, left, up, corner) & 255;
4271
- }
4272
- }
4273
- return pixels;
4274
- }
4275
- function decodeTerrarium(bytes, url) {
4276
- const png = readPNGChunks(bytes, url);
4277
- if (png.bitDepth !== 8 || png.colorType !== 2 || png.interlace !== 0) {
4278
- throw new Error(
4279
- `cook: ground survey tile ${url} is not an 8-bit RGB PNG (bit depth ${png.bitDepth}, colour type ${png.colorType}, interlace ${png.interlace}).`
4280
- );
4281
- }
4282
- const channels = 3;
4283
- const raw = inflateSync(Buffer.concat(png.idat));
4284
- if (raw.length !== (png.width * channels + 1) * png.height) {
4285
- throw new Error(`cook: ground survey tile ${url} decodes to ${raw.length} bytes, not a tile.`);
4286
- }
4287
- const pixels = unfilter(raw, png.width, png.height, channels, url);
4288
- const heights = new Float32Array(png.width * png.height);
4289
- for (let at = 0; at < heights.length; at += 1) {
4290
- heights[at] = pixels[at * channels] * 256 + pixels[at * channels + 1] + pixels[at * channels + 2] / 256 - 32768;
4291
- }
4292
- return { width: png.width, height: png.height, heights };
4293
- }
4294
- async function loadTile(z, x, y) {
4295
- const url = tileUrl(z, x, y);
4296
- const file = join$1(tileCacheDir(), String(z), String(x), `${y}.png`);
4297
- const cached = await readFile(file).catch(() => void 0);
4298
- if (cached !== void 0) return decodeTerrarium(new Uint8Array(cached), url);
4299
- let bytes;
4300
- try {
4301
- const response = await fetch(url);
4302
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
4303
- bytes = new Uint8Array(await response.arrayBuffer());
4304
- } catch (error) {
4305
- throw new Error(
4306
- `cook: ground survey tile ${url} is not cached in ${tileCacheDir()} and could not be fetched (${error instanceof Error ? error.message : String(error)}). Pass ground: "procedural" to cook the preset's own noise instead.`
4307
- );
4308
- }
4309
- const tile = decodeTerrarium(bytes, url);
4310
- await mkdir(dirname(file), { recursive: true });
4311
- await writeFile(file, bytes);
4312
- return tile;
4313
- }
4314
- var bilinear = (values, width, height, x, y) => {
4315
- const fx = Math.min(width - 1, Math.max(0, x));
4316
- const fy = Math.min(height - 1, Math.max(0, y));
4317
- const x0 = Math.floor(fx);
4318
- const y0 = Math.floor(fy);
4319
- const x1 = Math.min(width - 1, x0 + 1);
4320
- const y1 = Math.min(height - 1, y0 + 1);
4321
- const tx = fx - x0;
4322
- const ty = fy - y0;
4323
- const top = values[y0 * width + x0] * (1 - tx) + values[y0 * width + x1] * tx;
4324
- const bottom = values[y1 * width + x0] * (1 - tx) + values[y1 * width + x1] * tx;
4325
- return top * (1 - ty) + bottom * ty;
4326
- };
4327
- async function surveyHeights(survey, resolution) {
4328
- if (!Number.isInteger(resolution) || resolution < 2 || resolution > 4097) {
4329
- throw new RangeError(`cook: a survey needs a grid of 2..4097 samples, not ${resolution}.`);
4330
- }
4331
- const z = survey.zoom;
4332
- const halfLat = survey.extentMeters / 2 / M_PER_DEG_LAT;
4333
- const halfLon = survey.extentMeters / 2 / (M_PER_DEG_LON * Math.cos(survey.lat * Math.PI / 180));
4334
- const west = column(survey.lon - halfLon, z);
4335
- const east = column(survey.lon + halfLon, z);
4336
- const north = row(survey.lat + halfLat, z);
4337
- const south = row(survey.lat - halfLat, z);
4338
- const x0 = Math.floor(west);
4339
- const x1 = Math.floor(east);
4340
- const y0 = Math.floor(north);
4341
- const y1 = Math.floor(south);
4342
- const columns = x1 - x0 + 1;
4343
- const rows = y1 - y0 + 1;
4344
- const width = columns * TILE_PX;
4345
- const height = rows * TILE_PX;
4346
- const stitched = new Float32Array(width * height);
4347
- const tiles = [];
4348
- for (let y = y0; y <= y1; y += 1) {
4349
- for (let x = x0; x <= x1; x += 1) {
4350
- tiles.push(
4351
- loadTile(z, x, y).then((tile) => {
4352
- for (let ty = 0; ty < TILE_PX; ty += 1) {
4353
- for (let tx = 0; tx < TILE_PX; tx += 1) {
4354
- stitched[((y - y0) * TILE_PX + ty) * width + (x - x0) * TILE_PX + tx] = tile.heights[ty * TILE_PX + tx];
4355
- }
4356
- }
4357
- })
4358
- );
4359
- }
4360
- }
4361
- await Promise.all(tiles);
4362
- const left = (west - x0) * TILE_PX;
4363
- const top = (north - y0) * TILE_PX;
4364
- const spanX = (east - west) * TILE_PX;
4365
- const spanY = (south - north) * TILE_PX;
4366
- const values = new Float32Array(resolution * resolution);
4367
- let min = Number.POSITIVE_INFINITY;
4368
- let max = Number.NEGATIVE_INFINITY;
4369
- for (let y = 0; y < resolution; y += 1) {
4370
- for (let x = 0; x < resolution; x += 1) {
4371
- const value = bilinear(
4372
- stitched,
4373
- width,
4374
- height,
4375
- left + x / (resolution - 1) * spanX,
4376
- top + y / (resolution - 1) * spanY
4377
- );
4378
- values[y * resolution + x] = value;
4379
- min = Math.min(min, value);
4380
- max = Math.max(max, value);
4587
+ if (createHash("sha256").update(archive).digest("hex") !== manifest.sha256) fail3("SHA256");
4588
+ await mkdir(dirname(cache), { recursive: true });
4589
+ const tmp = await mkdtemp(`${cache}.tmp-`);
4590
+ try {
4591
+ await extract(archive, tmp);
4592
+ try {
4593
+ await rename(tmp, cache);
4594
+ } catch (error) {
4595
+ if (!await isDirectory(cache) || !["EEXIST", "ENOTEMPTY"].includes(error.code ?? ""))
4596
+ throw error;
4381
4597
  }
4598
+ } finally {
4599
+ await rm(tmp, { recursive: true, force: true });
4382
4600
  }
4383
- return { width: resolution, height: resolution, values, min, max };
4601
+ return cache;
4384
4602
  }
4385
4603
 
4386
- // src/core/kits.ts
4604
+ // src/biome/kits.ts
4387
4605
  var TERRAIN_KITS = ["forest", "coastal", "alpine", "desert", "tundra"];
4606
+ var PACKAGE = "@threenative/procedural-environment";
4607
+ var SPECIES = /^arbor:([a-z0-9]+)(?:@(\d{1,9}))?$/u;
4608
+ var LODS = [1, 2];
4609
+ function parseArborSpecies(species2) {
4610
+ if (!species2.startsWith("arbor:")) return void 0;
4611
+ const match = SPECIES.exec(species2);
4612
+ if (match === null)
4613
+ throw new Error(
4614
+ `cook: species '${species2}' must read arbor:<preset> or arbor:<preset>@<seed>, for example arbor:oak@7.`
4615
+ );
4616
+ return { preset: match[1], seed: match[2] === void 0 ? 1 : Number(match[2]) };
4617
+ }
4618
+ var idOf = (preset, seed) => `arbor-${preset}-${seed}`;
4619
+ function installedEntry(projectRoot) {
4620
+ let directory = resolve(projectRoot);
4621
+ while (true) {
4622
+ const manifestFile = join$1(directory, "node_modules", PACKAGE, "package.json");
4623
+ if (existsSync(manifestFile)) {
4624
+ const manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
4625
+ const root = manifest.exports?.["."];
4626
+ const file = (typeof root === "string" ? root : root?.import) ?? manifest.main;
4627
+ return file === void 0 ? void 0 : resolve(dirname(manifestFile), file);
4628
+ }
4629
+ const parent = dirname(directory);
4630
+ if (parent === directory) return void 0;
4631
+ directory = parent;
4632
+ }
4633
+ }
4634
+ async function loadVegetation(projectRoot, wanted) {
4635
+ const entry = installedEntry(projectRoot);
4636
+ if (entry === void 0 || !existsSync(entry))
4637
+ throw new Error(`cook: species '${wanted}' needs the Arbor bake: npm i -D ${PACKAGE}`);
4638
+ return await import(pathToFileURL(entry).href);
4639
+ }
4640
+ async function growArborAsset(projectRoot, scratch, species2, seedOffset = 0, patch = {}) {
4641
+ const parsed = parseArborSpecies(species2);
4642
+ if (parsed === void 0) throw new Error(`cook: species '${species2}' must start with arbor:.`);
4643
+ const seed = parsed.seed + seedOffset;
4644
+ const id = idOf(parsed.preset, seed);
4645
+ const vegetation = await loadVegetation(projectRoot, species2);
4646
+ if (!vegetation.vegetationPresets().some((p) => p.id === parsed.preset))
4647
+ throw new Error(
4648
+ `cook: species '${species2}' names no Arbor preset. Call vegetationPresets() from ${PACKAGE} for the ids.`
4649
+ );
4650
+ const files = await vegetation.bakeVegetation({
4651
+ lods: LODS,
4652
+ out: join$1(scratch, id),
4653
+ preset: parsed.preset,
4654
+ seed,
4655
+ ...patch
4656
+ });
4657
+ const [near, mid] = files;
4658
+ return { bounds: near.bounds, maxDistance: 600, mid: mid.path, midDistance: 45, near: near.path };
4659
+ }
4660
+ async function growArborRows(table, projectRoot, scratch, assetsDir = projectRoot) {
4661
+ let grew = false;
4662
+ for (const [id, spec] of Object.entries(table)) {
4663
+ const { arbor, form, leafImage, ...row2 } = spec;
4664
+ if (arbor === void 0) continue;
4665
+ const patch = {
4666
+ ...form === void 0 ? {} : { form },
4667
+ ...leafImage === void 0 ? {} : { leafImage: resolve(assetsDir, leafImage) }
4668
+ };
4669
+ table[id] = {
4670
+ ...await growArborAsset(projectRoot, scratch, `arbor:${arbor}`, 0, patch),
4671
+ ...row2
4672
+ };
4673
+ grew = true;
4674
+ }
4675
+ return grew;
4676
+ }
4677
+ async function growArborSpecies(options) {
4678
+ const { assetTable, biome, projectRoot, scratch, treeSpecies } = options;
4679
+ const named = new Set(
4680
+ [...biome.species, ...biome.foliage.map((row2) => row2.species)].filter(
4681
+ (id) => id.startsWith("arbor:")
4682
+ )
4683
+ );
4684
+ if (named.size === 0 && treeSpecies === void 0) return biome;
4685
+ const baked = /* @__PURE__ */ new Map();
4686
+ const grow = async (species2, seedOffset = 0) => {
4687
+ const parsed = parseArborSpecies(species2);
4688
+ const id = idOf(parsed.preset, parsed.seed + seedOffset);
4689
+ const asset = baked.get(id) ?? await growArborAsset(projectRoot, scratch, species2, seedOffset);
4690
+ baked.set(id, asset);
4691
+ return [id, asset];
4692
+ };
4693
+ if (treeSpecies !== void 0) {
4694
+ const art = assetTable;
4695
+ const families = new Set(
4696
+ Object.values(art).filter((spec) => spec.tree === true).map((spec) => dirname(spec.near))
4697
+ );
4698
+ const kitTrees = Object.keys(art).filter((id) => families.has(dirname(art[id]?.near ?? "")));
4699
+ if (kitTrees.length === 0) {
4700
+ const [id, asset] = await grow(treeSpecies);
4701
+ assetTable[id] = { ...asset, tree: true };
4702
+ }
4703
+ for (const [at, id] of kitTrees.entries()) {
4704
+ const [, asset] = await grow(treeSpecies, at);
4705
+ assetTable[id] = { ...asset, tree: art[id]?.tree === true };
4706
+ }
4707
+ }
4708
+ const ids = /* @__PURE__ */ new Map();
4709
+ for (const species2 of named) {
4710
+ const [id, asset] = await grow(species2);
4711
+ assetTable[id] = asset;
4712
+ ids.set(species2, id);
4713
+ }
4714
+ const rename2 = (species2) => ids.get(species2) ?? species2;
4715
+ return {
4716
+ ...biome,
4717
+ foliage: biome.foliage.map((row2) => ({ ...row2, species: rename2(row2.species) })),
4718
+ species: [...new Set(biome.species.map(rename2))]
4719
+ };
4720
+ }
4388
4721
  function isRecord(value) {
4389
4722
  return typeof value === "object" && value !== null && !Array.isArray(value);
4390
4723
  }
4724
+
4725
+ // src/request/ecoregions.ts
4726
+ var FAR = {
4727
+ cell: 6,
4728
+ spacing: [6.5, 13],
4729
+ spacingAt: [150, 1500],
4730
+ slope: [36, 46],
4731
+ meadowSlope: [12, 24],
4732
+ reach: 2300,
4733
+ treelineJitter: 30,
4734
+ stand: [0.26, 0.4],
4735
+ impostor: 110
4736
+ };
4737
+ var CLEARINGS = { type: "noise", scale: 90, threshold: 0.4, seed: 466600, fade: 0.06 };
4738
+ function canopyRow(species2, density, farSeed, scale = [0.55, 1], mask = {
4739
+ type: "and",
4740
+ masks: [CLEARINGS, { type: "noise", scale: 120, threshold: 0.44, seed: farSeed, fade: 0.24 }]
4741
+ }) {
4742
+ return {
4743
+ species: species2,
4744
+ density,
4745
+ slope: [0, 32],
4746
+ height: null,
4747
+ spacing: [3.2, 6.4],
4748
+ collision: "trunk",
4749
+ stands: true,
4750
+ grassThreshold: 0.3,
4751
+ standThreshold: 0.16,
4752
+ far: { ...FAR, seed: farSeed },
4753
+ scale,
4754
+ mask
4755
+ };
4756
+ }
4757
+ var ECOREGION_ROWS = [
4758
+ {
4759
+ id: "european-broadleaf",
4760
+ // "beech" alone stays a tree word (`TREE_WORD_ROWS`): only a region word selects this row.
4761
+ words: ["european", "europe"],
4762
+ kit: "forest",
4763
+ site: {
4764
+ name: "Hainich National Park, Thuringia, Germany",
4765
+ lat: 51.0833,
4766
+ lon: 10.4667,
4767
+ extentMeters: 3e3,
4768
+ attribution: `${COPERNICUS} ${TILES2}`
4769
+ // measured: 305..483 m over its 3 km, and 380..423 m at the world's own 512 m (a beech wood's
4770
+ // floor: 5.8 degrees at the 90th percentile, no hydro-flattened water)
4771
+ },
4772
+ canopy: ["fir", "fir-c"],
4773
+ overrides: {
4774
+ // The European beech forest's own mix: beech dominant, sessile oak and silver birch among it,
4775
+ // each at two seeds so no two trees of a species are the same bake.
4776
+ foliage: [
4777
+ canopyRow("arbor:beech@11", 900, 466611),
4778
+ canopyRow("arbor:beech@12", 900, 466612),
4779
+ canopyRow("arbor:oak@13", 650, 466613),
4780
+ canopyRow("arbor:oak@14", 650, 466614),
4781
+ canopyRow("arbor:birch@15", 450, 466615),
4782
+ canopyRow("arbor:birch@16", 450, 466616),
4783
+ // Beech regeneration: the young beech a closed beech wood grows in its own light gaps, so the
4784
+ // clearings fill with saplings (the kit's `firs-young` band, at the same scale).
4785
+ canopyRow("arbor:beech@20", 700, 466620, [0.2, 0.45], { type: "not", mask: CLEARINGS })
4786
+ ]
4787
+ }
4788
+ },
4789
+ {
4790
+ id: "boreal",
4791
+ words: ["boreal", "taiga", "nordic", "scandinavian"],
4792
+ kit: "forest",
4793
+ site: {
4794
+ name: "Oulanka National Park, Kuusamo, Finland",
4795
+ lat: 66.36221,
4796
+ lon: 29.3167,
4797
+ extentMeters: 3e3,
4798
+ attribution: `${COPERNICUS} ${TILES2}`
4799
+ // measured: 144..325 m over its 3 km, and 177..253 m at 512 m (a spruce stand: 15.4 degrees at
4800
+ // the 90th percentile, 0.6 % hydro-flattened water). Moved 500 m south of the old centre
4801
+ // (66.3667, 29.3167), whose 512 m crop was 8.5 % flattened river and lake water on Mapterhorn data.
4802
+ },
4803
+ canopy: ["fir", "fir-c"],
4804
+ overrides: {
4805
+ // The boreal mix of the kit's own stand: Norway spruce with downy birch and aspen, two bakes each.
4806
+ foliage: [
4807
+ canopyRow("arbor:spruce@21", 1e3, 466621),
4808
+ canopyRow("arbor:spruce@22", 1e3, 466622),
4809
+ canopyRow("arbor:birch@23", 600, 466623),
4810
+ canopyRow("arbor:birch@24", 600, 466624),
4811
+ canopyRow("arbor:aspen@25", 400, 466625),
4812
+ canopyRow("arbor:aspen@26", 400, 466626)
4813
+ ]
4814
+ }
4815
+ },
4816
+ {
4817
+ id: "mediterranean",
4818
+ words: ["mediterranean", "tuscan"],
4819
+ kit: "desert",
4820
+ site: {
4821
+ name: "Val d'Orcia, Tuscany, Italy",
4822
+ lat: 43.0667,
4823
+ lon: 11.6167,
4824
+ extentMeters: 3e3,
4825
+ attribution: `${COPERNICUS} ${TILES2}`
4826
+ // measured: 276..436 m over its 3 km, and 328..403 m at 512 m (a clay hillside with its olive
4827
+ // and cypress: 17.6 degrees at the 90th percentile)
4828
+ },
4829
+ // The desert kit ships no tree art of its own, so there is no authored canopy to replace.
4830
+ canopy: [],
4831
+ overrides: {
4832
+ // The Mediterranean hill's own three: olive, Italian cypress and downy oak, two bakes each.
4833
+ foliage: [
4834
+ canopyRow("arbor:olive@31", 500, 466631),
4835
+ canopyRow("arbor:olive@32", 500, 466632),
4836
+ canopyRow("arbor:cypress@33", 350, 466633),
4837
+ canopyRow("arbor:cypress@34", 350, 466634),
4838
+ canopyRow("arbor:oak@35", 300, 466635),
4839
+ canopyRow("arbor:oak@36", 300, 466636)
4840
+ ]
4841
+ }
4842
+ },
4843
+ {
4844
+ id: "pacific-northwest",
4845
+ // Two words, matched as the phrase a request writes them in; "pacific" and "northwest" alone
4846
+ // name nothing, so "a pacific island" stays the coastal world it is.
4847
+ words: ["pacific northwest", "cascadia"],
4848
+ kit: "forest",
4849
+ site: {
4850
+ name: "Humptulips valley, Olympic National Forest, Washington",
4851
+ lat: 47.19775,
4852
+ lon: -123.88678,
4853
+ extentMeters: 3e3,
4854
+ attribution: `${USGS_3DEP} ${TILES2}`
4855
+ // measured: 52..212 m over its 3 km, and 96..163 m at 512 m (a Douglas-fir valley floor: 25.9
4856
+ // degrees at the 90th percentile, under the 28 the floor accepts). Moved 1 km north-east of the
4857
+ // old centre (47.2, -123.9), whose 512 m crop read 31.0 degrees on Mapterhorn's lidar.
4858
+ },
4859
+ canopy: ["fir", "fir-c"],
4860
+ overrides: {
4861
+ // The coastal rainforest's own three: Douglas-fir, western redcedar and bigleaf maple.
4862
+ foliage: [
4863
+ canopyRow("arbor:douglasfir@41", 900, 466641),
4864
+ canopyRow("arbor:douglasfir@42", 900, 466642),
4865
+ canopyRow("arbor:redcedar@43", 550, 466643),
4866
+ canopyRow("arbor:redcedar@44", 550, 466644),
4867
+ canopyRow("arbor:bigleafmaple@45", 350, 466645),
4868
+ canopyRow("arbor:bigleafmaple@46", 350, 466646)
4869
+ ]
4870
+ }
4871
+ }
4872
+ ];
4873
+ ECOREGION_ROWS.flatMap(
4874
+ (row2) => row2.words.flatMap((word) => word.split(" "))
4875
+ );
4876
+ `A region word (${ECOREGION_ROWS.map((row2) => row2.words[0]).join(", ")}) cooks that region's own world: the row's real survey as the ground, its plant community as the canopy (several species, each baked at more than one seed), and the starter's own surface, understorey and water, reported as \`decided.region\`.`;
4877
+ function newBiomeSpec(base, name, overrides = {}) {
4878
+ return validateBiome(
4879
+ {
4880
+ ...base,
4881
+ ...overrides,
4882
+ aliases: overrides.aliases ?? [name],
4883
+ look: overrides.look ?? name
4884
+ },
4885
+ name
4886
+ );
4887
+ }
4391
4888
  async function resolveAssetSource(projectRoot) {
4392
4889
  const configFile = join$1(projectRoot, "threenative.config.ts");
4393
4890
  const exists = await lstat(configFile).then(
@@ -4426,8 +4923,7 @@ async function resolveAssetSource(projectRoot) {
4426
4923
  return sourceRoot;
4427
4924
  }
4428
4925
 
4429
- // src/mcp/cook.ts
4430
- var MISSING_ASSETS = "terrain_generate needs @threenative/assets in the game project. Run: npm i -D @threenative/assets";
4926
+ // src/population/foliage.ts
4431
4927
  function isTriple(value) {
4432
4928
  return Array.isArray(value) && value.length === 3 && value.every((entry) => typeof entry === "number" && Number.isFinite(entry));
4433
4929
  }
@@ -4441,62 +4937,85 @@ function parseBounds(value, species2) {
4441
4937
  }
4442
4938
  return { min, max };
4443
4939
  }
4444
- function installedEntry(projectRoot, name) {
4445
- let directory = resolve(projectRoot);
4446
- while (true) {
4447
- const manifestFile = join$1(directory, "node_modules", name, "package.json");
4448
- if (existsSync(manifestFile)) {
4449
- const manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
4450
- const root = manifest.exports?.["."];
4451
- const relative3 = (typeof root === "string" ? root : root?.import) ?? manifest.main;
4452
- return relative3 === void 0 ? void 0 : resolve(dirname(manifestFile), relative3);
4453
- }
4454
- const parent = dirname(directory);
4455
- if (parent === directory) return void 0;
4456
- directory = parent;
4457
- }
4940
+ var PLAY_AREA_CLEAR_RADIUS = 4;
4941
+ var PLAY_AREA_CLEAR = {
4942
+ mask: { type: "circle", at: [0, 0], radius: PLAY_AREA_CLEAR_RADIUS / 0.98, falloff: 0.02 },
4943
+ opacity: 1
4944
+ };
4945
+ function scatterFoliage(state, biome, kind, assetTable, replacedStand = false) {
4946
+ if (kind === void 0 && !replacedStand) return state;
4947
+ const tree = Object.keys(assetTable).find((id) => assetTable[id]?.tree === true);
4948
+ const foliage2 = biome.foliage.flatMap((row2, at) => {
4949
+ if (row2.density === 0) return [];
4950
+ if (row2.species in assetTable) return [row2];
4951
+ return at === 0 && tree !== void 0 ? [{ ...row2, species: tree }] : [];
4952
+ });
4953
+ if (foliage2.length === 0) return state;
4954
+ return finalizeState({
4955
+ ...state,
4956
+ scatterRules: [
4957
+ ...state.scatterRules,
4958
+ ...foliageScatterRules(foliage2, state.height).map((rule) => ({
4959
+ ...rule,
4960
+ clear: [...rule.clear, PLAY_AREA_CLEAR]
4961
+ }))
4962
+ ]
4963
+ });
4458
4964
  }
4459
- async function loadCooker(projectRoot) {
4460
- const entry = installedEntry(projectRoot, "@threenative/assets");
4461
- if (entry === void 0 || !existsSync(entry)) throw new Error(MISSING_ASSETS);
4462
- const loaded = await import(pathToFileURL(entry).href);
4463
- if (typeof loaded.cookTerrainWorld !== "function") {
4464
- throw new Error(`${MISSING_ASSETS} (the installed version has no cookTerrainWorld).`);
4465
- }
4466
- return loaded;
4965
+
4966
+ // src/population/placements.ts
4967
+ function validatePlacementOverrides(value = {}) {
4968
+ finiteTree(value, "placementOverrides");
4969
+ if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
4970
+ throw new Error("Expected placementOverrides object");
4971
+ return Object.fromEntries(
4972
+ Object.entries(value).map(([key, entry]) => {
4973
+ if (!key.length || key.length > 256)
4974
+ throw new Error("Placement key must contain 1\u2013256 characters");
4975
+ if (!entry || typeof entry !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(entry)))
4976
+ throw new Error(`Invalid placement override '${key}'`);
4977
+ const input = entry;
4978
+ if (Object.keys(input).some(
4979
+ (field) => !["position", "quaternion", "scale", "grounding"].includes(field)
4980
+ ))
4981
+ throw new Error(`Unknown placement override fields '${key}'`);
4982
+ function vector(field, length) {
4983
+ const values = input[field];
4984
+ if (!Array.isArray(values) || values.length !== length || !Array.from(values).every(Number.isFinite))
4985
+ throw new Error(`${key}.${field} must contain ${length} finite numbers`);
4986
+ return Array.from(values);
4987
+ }
4988
+ const position = vector("position", 3);
4989
+ const quaternion = vector("quaternion", 4);
4990
+ const scale = vector("scale", 3);
4991
+ if (scale.some((item) => item <= 0)) throw new Error(`${key}.scale must be positive`);
4992
+ if (Math.abs(Math.hypot(...quaternion) - 1) > 1e-6)
4993
+ throw new Error(`${key}.quaternion must be a unit quaternion`);
4994
+ const grounding = input.grounding === void 0 ? true : input.grounding;
4995
+ if (typeof grounding !== "boolean") throw new Error(`${key}.grounding must be boolean`);
4996
+ return [key, { position, quaternion, scale, grounding }];
4997
+ })
4998
+ );
4467
4999
  }
4468
- var round = (value) => Math.round(value * 1e3) / 1e3;
4469
- async function cookKit(request2) {
4470
- if (!TERRAIN_KITS.includes(request2.kit)) {
4471
- throw new Error(`cook: unknown kit '${request2.kit}'.`);
4472
- }
4473
- const assetSource = request2.assetSource ?? await resolveAssetSource(request2.projectRoot);
4474
- const logicalOut = relative(assetSource, request2.out);
4475
- if (logicalOut === "" || logicalOut === ".." || logicalOut.startsWith(`..${sep}`)) {
4476
- throw new Error(
4477
- "terrain_generate: out must be under assets.source so the build can list it in the manifest."
4478
- );
4479
- }
4480
- const cooker = await loadCooker(request2.projectRoot);
4481
- const packageRoot = join$1(dirname(fileURLToPath(import.meta.url)), "..", "..");
4482
- const kitDir = join$1(packageRoot, "starter", request2.kit);
4483
- const assetsDir = await starterAssetsDir();
4484
- await mkdir(dirname(request2.out), { recursive: true });
4485
- try {
4486
- await mkdir(request2.out);
4487
- } catch (error) {
4488
- if (error.code === "EEXIST") {
4489
- throw new Error(`cook: out '${request2.out}' already exists.`);
4490
- }
4491
- throw error;
4492
- }
4493
- try {
4494
- return await cookInto({ ...request2, assetSource }, cooker, kitDir, assetsDir);
4495
- } catch (error) {
4496
- await rm(request2.out, { recursive: true, force: true });
4497
- throw error;
4498
- }
5000
+ function applyPlacementOverrides(state, value) {
5001
+ const overrides = validatePlacementOverrides(value);
5002
+ const keys = new Set(state.instances.map((item) => item.id));
5003
+ return {
5004
+ ...state,
5005
+ instances: state.instances.map((item) => {
5006
+ const { transform: _, ...base } = item;
5007
+ return Object.hasOwn(overrides, item.id) ? { ...base, transform: overrides[item.id] } : base;
5008
+ }),
5009
+ diagnostics: [
5010
+ ...state.diagnostics.filter(
5011
+ (message) => !message.startsWith("Unmatched placement override '")
5012
+ ),
5013
+ ...Object.keys(overrides).filter((key) => !keys.has(key)).map((key) => `Unmatched placement override '${key}'`)
5014
+ ]
5015
+ };
4499
5016
  }
5017
+
5018
+ // src/water/stages.ts
4500
5019
  function applyWaterRows(layers, rows) {
4501
5020
  const unrouted = [];
4502
5021
  const queue = (kind) => layers.filter(
@@ -4595,7 +5114,21 @@ function shapeCoast(recipe) {
4595
5114
  params: { amplitude: 0, scale: 1, island: true, coastDepth: (border - sea + 3) / 0.676 }
4596
5115
  });
4597
5116
  }
4598
- function placeLakes(recipe, rows) {
5117
+ function unpinLakes(recipe) {
5118
+ const lakes = recipe.layers.filter(
5119
+ (layer2) => layer2.type === "water" && layer2.params.kind === "lake"
5120
+ );
5121
+ const centre = (layer2) => JSON.stringify(layer2.params.at);
5122
+ const centres = new Set(lakes.map(centre));
5123
+ recipe.layers = recipe.layers.filter(
5124
+ (layer2) => !lakes.includes(layer2) && !(layer2.type === "flatten" && centres.has(centre(layer2)))
5125
+ );
5126
+ return lakes.map((layer2) => ({
5127
+ kind: "lake",
5128
+ radius: layer2.params.radius
5129
+ }));
5130
+ }
5131
+ function placeLakes(recipe, rows, dig = true) {
4599
5132
  const sea = seaLevel(recipe);
4600
5133
  const placed = [];
4601
5134
  rows.forEach((row2, index) => {
@@ -4682,6 +5215,7 @@ function placeLakes(recipe, rows) {
4682
5215
  };
4683
5216
  };
4684
5217
  let found = site();
5218
+ if (found.depth < 1 && !dig) return;
4685
5219
  if (found.depth < 1) {
4686
5220
  radius = Math.min(radius, found.room * 0.55);
4687
5221
  recipe.layers.push({
@@ -4802,354 +5336,294 @@ function floodedBodies(state) {
4802
5336
  ...state.rivers.map((river) => ({ kind: "river", width: round(river.width) }))
4803
5337
  ];
4804
5338
  }
4805
- var PLAY_AREA_CLEAR_RADIUS = 23;
4806
- var PLAY_AREA_CLEAR = {
4807
- mask: { type: "circle", at: [0, 0], radius: PLAY_AREA_CLEAR_RADIUS / 0.98, falloff: 0.02 },
4808
- opacity: 1
4809
- };
4810
- function scatterFoliage(state, biome, kind, assetTable) {
4811
- if (kind === void 0) return state;
4812
- const tree = Object.keys(assetTable).find((id) => assetTable[id]?.tree === true);
4813
- const foliage2 = biome.foliage.flatMap((row2, at) => {
4814
- if (row2.density === 0) return [];
4815
- if (row2.species in assetTable) return [row2];
4816
- return at === 0 && tree !== void 0 ? [{ ...row2, species: tree }] : [];
4817
- });
4818
- if (foliage2.length === 0) return state;
4819
- return finalizeState({
4820
- ...state,
4821
- scatterRules: [
4822
- ...state.scatterRules,
4823
- ...foliageScatterRules(foliage2, state.height).map((rule) => ({
4824
- ...rule,
4825
- clear: [...rule.clear, PLAY_AREA_CLEAR]
4826
- }))
4827
- ]
4828
- });
4829
- }
4830
- async function readGroundHeightmap(projectRoot, asked) {
4831
- const file = isAbsolute(asked.heightmap) ? asked.heightmap : resolve(projectRoot, asked.heightmap);
4832
- const bytes = await readFile(file).catch(() => {
4833
- throw new Error(`terrain_generate: ground.heightmap '${asked.heightmap}' cannot be read.`);
4834
- });
4835
- const range2 = asked.min === void 0 || asked.max === void 0 ? void 0 : { min: asked.min, max: asked.max };
4836
- try {
4837
- if (file.toLowerCase().endsWith(".r16")) {
4838
- const side = Math.sqrt(bytes.length / 2);
4839
- if (!Number.isInteger(side)) {
4840
- throw new TypeError("a .r16 grid has no width of its own, so it must be square");
4841
- }
4842
- if (range2 === void 0) {
4843
- throw new TypeError("a .r16 grid carries no elevation range; name min and max in metres");
4844
- }
4845
- return decodeRAW16(bytes, { width: side, height: side, ...range2 });
4846
- }
4847
- const decoded = await decodeHeightPNG(bytes, range2 ?? {});
4848
- if (decoded.bitDepth !== 16) {
4849
- throw new TypeError(`it is ${decoded.bitDepth}-bit; export a 16-bit grayscale PNG`);
4850
- }
4851
- if (!decoded.hasEmbeddedRange && range2 === void 0) {
4852
- throw new TypeError("it carries no elevation range; name min and max in metres");
4853
- }
4854
- return decoded;
4855
- } catch (error) {
4856
- throw new TypeError(
4857
- `terrain_generate: ground.heightmap '${asked.heightmap}': ${error instanceof Error ? error.message : String(error)}`
5339
+
5340
+ // src/package/glb-stats.ts
5341
+ var GLB_MAGIC = 1179937895;
5342
+ var JSON_CHUNK = 1313821514;
5343
+ var INSTANCING = "EXT_mesh_gpu_instancing";
5344
+ var TRIANGLE_MODES = /* @__PURE__ */ new Set([4, 5, 6]);
5345
+ function jsonChunk(bytes) {
5346
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
5347
+ if (bytes.byteLength < 20 || view.getUint32(0, true) !== GLB_MAGIC) {
5348
+ throw new Error("glb-stats: not a GLB, the glTF binary header is missing.");
5349
+ }
5350
+ if (view.getUint32(4, true) !== 2 || view.getUint32(8, true) !== bytes.byteLength) {
5351
+ throw new Error(
5352
+ "glb-stats: the GLB version is not 2 or its header length is not the file size."
4858
5353
  );
4859
5354
  }
4860
- }
4861
- function applyGroundLayer(layers, grid, scale, offset) {
4862
- const at = layers.findIndex((layer2) => layer2.type === "heightmap" || layer2.type === "noise");
4863
- const replaced = layers[at];
4864
- if (replaced === void 0)
4865
- throw new Error("cook: the recipe authors no ground layer to replace.");
4866
- const preset = replaced.type === "noise";
4867
- layers[at] = {
4868
- id: "ground",
4869
- type: "heightmap",
4870
- enabled: replaced.enabled ?? true,
4871
- opacity: replaced.opacity ?? 1,
4872
- params: {
4873
- // The recipe inlines its heights, so they are plain numbers on a 0.1 m lattice like the
4874
- // starters' own crops: the same precision, and the same size of recipe.json.
4875
- data: {
4876
- width: grid.width,
4877
- height: grid.height,
4878
- values: Array.from(grid.values, (value) => Math.round(value * 10) / 10)
4879
- },
4880
- scale,
4881
- offset
4882
- }
4883
- };
4884
- if (!preset) return;
4885
- for (let index = layers.length - 1; index >= 0; index -= 1) {
4886
- const layer2 = layers[index];
4887
- const shape = layer2.type === "stamp" ? layer2.params.shape : void 0;
4888
- if (shape === "mountain" || shape === "crater") layers.splice(index, 1);
5355
+ const length = view.getUint32(12, true);
5356
+ if (view.getUint32(16, true) !== JSON_CHUNK || 20 + length > bytes.byteLength) {
5357
+ throw new Error("glb-stats: the first GLB chunk is not a complete JSON chunk.");
4889
5358
  }
5359
+ return JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + length)));
4890
5360
  }
4891
- function seededCrop(row2, seed) {
4892
- if (seed === void 0) return row2;
4893
- const next = random(hashString(`survey:${seed}`));
4894
- const east = (next() * 2 - 1) * 0.6 * row2.extentMeters;
4895
- const north = (next() * 2 - 1) * 0.6 * row2.extentMeters;
4896
- return {
4897
- ...row2,
4898
- lat: row2.lat + north / 111320,
4899
- lon: row2.lon + east / (111320 * Math.cos(row2.lat * Math.PI / 180))
4900
- };
4901
- }
4902
- async function forestFloor(document, row2, seed) {
4903
- const { resolution, size } = document.config;
4904
- const next = random(hashString(`floor:${seed ?? 0}`));
4905
- const spots = Array.from({ length: seed === void 0 ? 0 : 12 }, () => {
4906
- const east = (next() * 2 - 1) * 0.4 * row2.extentMeters;
4907
- const north = (next() * 2 - 1) * 0.4 * row2.extentMeters;
4908
- return [north, east];
4909
- });
4910
- const patch = (north, east) => ({
4911
- ...row2,
4912
- lat: row2.lat + north / 111320,
4913
- lon: row2.lon + east / (111320 * Math.cos(row2.lat * Math.PI / 180)),
4914
- extentMeters: size,
4915
- zoom: 15
4916
- });
4917
- let picked;
4918
- for (const [north, east] of [...spots, [0, 0]]) {
4919
- const survey2 = patch(north, east);
4920
- const grid2 = await surveyHeights(survey2, resolution);
4921
- const stats = terrainStats(grid2.values, resolution, size);
4922
- picked = { survey: survey2, grid: grid2 };
4923
- if (isForestFloor(grid2.max - grid2.min, stats.slopeP90, size, flatShare(grid2.values, resolution)))
4924
- break;
4925
- }
4926
- const { survey, grid } = picked;
4927
- applyGroundLayer(document.layers, grid, 1, -grid.min);
4928
- const at = document.layers.findIndex((layer2) => layer2.type === "erode");
4929
- document.layers = document.layers.filter((layer2) => layer2.type !== "erode");
4930
- document.layers.splice(at < 0 ? 1 : at, 0, ...structuredClone(SURVEYED_EROSION));
4931
- return {
4932
- survey: { row: survey, scale: 1, offset: -grid.min },
4933
- ground: {
4934
- source: "survey",
4935
- name: survey.name,
4936
- lat: survey.lat,
4937
- lon: survey.lon,
4938
- attribution: survey.attribution
4939
- },
4940
- readme: groundReadme(survey)
5361
+ function measureGlb(bytes) {
5362
+ const gltf = jsonChunk(bytes);
5363
+ const nodes = gltf.nodes ?? [];
5364
+ const accessorCount = (index) => {
5365
+ const count2 = index === void 0 ? void 0 : gltf.accessors?.[index]?.count;
5366
+ if (count2 === void 0) throw new Error(`glb-stats: accessor ${index} is missing.`);
5367
+ return count2;
4941
5368
  };
4942
- }
4943
- var groundReadme = (survey) => [
4944
- "# Cooked terrain world",
4945
- "",
4946
- `The ground is a real survey: ${survey.name} at ${survey.lat}, ${survey.lon},`,
4947
- `${survey.extentMeters} m across at zoom ${survey.zoom}, resampled onto the recipe's grid.`,
4948
- "",
4949
- "## Data attribution",
4950
- "",
4951
- survey.attribution,
4952
- ""
4953
- ].join("\n");
4954
- var SURVEYED_EROSION = [
4955
- {
4956
- type: "erode",
4957
- id: "surface-runoff",
4958
- params: {
4959
- method: "hydraulic",
4960
- droplets: 2e4,
4961
- maxSteps: 45,
4962
- capacity: 2,
4963
- erosion: 0.015,
4964
- strength: 2e-3,
4965
- deposition: 0.2,
4966
- evaporation: 0.035
4967
- }
4968
- },
4969
- {
4970
- type: "erode",
4971
- id: "loose-talus",
4972
- params: { method: "thermal", talus: 38, iterations: 1, rate: 4e-3 }
4973
- }
4974
- ];
4975
- var FLOOR_RELIEF = 90;
4976
- var FLOOR_SLOPE = 28;
4977
- var FLOOR_FLAT = 0.02;
4978
- function flatShare(values, resolution) {
4979
- let flat = 0;
4980
- for (let r = 1; r < resolution - 1; r++)
4981
- for (let c = 1; c < resolution - 1; c++) {
4982
- const h = values[r * resolution + c];
4983
- const near = [
4984
- values[r * resolution + c - 1],
4985
- values[r * resolution + c + 1],
4986
- values[(r - 1) * resolution + c],
4987
- values[(r + 1) * resolution + c]
4988
- ];
4989
- if (near.every((n) => Math.abs(n - h) < 0.02)) flat++;
5369
+ const stats = { draws: 0, instances: 0, triangles: 0 };
5370
+ const seen = /* @__PURE__ */ new Set();
5371
+ const visit = (index) => {
5372
+ const node = nodes[index];
5373
+ if (node === void 0) throw new Error(`glb-stats: node ${index} is missing.`);
5374
+ if (seen.has(index)) return;
5375
+ seen.add(index);
5376
+ if (node.mesh !== void 0) {
5377
+ const mesh = gltf.meshes?.[node.mesh];
5378
+ if (mesh === void 0) throw new Error(`glb-stats: mesh ${node.mesh} is missing.`);
5379
+ const attributes = node.extensions?.[INSTANCING]?.attributes;
5380
+ const copies = attributes === void 0 ? 1 : accessorCount(Object.values(attributes)[0]);
5381
+ if (attributes !== void 0) stats.instances += copies;
5382
+ for (const primitive of mesh.primitives) {
5383
+ stats.draws += 1;
5384
+ if (!TRIANGLE_MODES.has(primitive.mode ?? 4)) continue;
5385
+ const vertices = accessorCount(primitive.indices ?? primitive.attributes.POSITION);
5386
+ stats.triangles += (primitive.mode === 5 || primitive.mode === 6 ? Math.max(vertices - 2, 0) : Math.floor(vertices / 3)) * copies;
5387
+ }
4990
5388
  }
4991
- return flat / (resolution - 2) ** 2;
4992
- }
4993
- function isForestFloor(relief, slopeP90, size, flat = 0) {
4994
- return relief <= FLOOR_RELIEF * Math.max(1, size / 512) && slopeP90 <= FLOOR_SLOPE && flat <= FLOOR_FLAT;
5389
+ for (const child of node.children ?? []) visit(child);
5390
+ };
5391
+ const scene = gltf.scenes?.[gltf.scene ?? 0];
5392
+ for (const root of scene?.nodes ?? (gltf.scenes === void 0 ? nodes.keys() : [])) visit(root);
5393
+ return stats;
4995
5394
  }
4996
- async function applyGround(document, request2, kind) {
4997
- const asked = request2.ground;
4998
- if (asked === "procedural") return { ground: { source: "procedural" } };
4999
- if (asked !== void 0 && "heightmap" in asked) {
5000
- applyGroundLayer(document.layers, await readGroundHeightmap(request2.projectRoot, asked), 1, 0);
5001
- return { ground: { source: "heightmap", heightmap: asked.heightmap } };
5002
- }
5003
- const survey = asked !== void 0 ? locationSurvey(asked.location.lat, asked.location.lon) : kind === void 0 ? void 0 : seededCrop(SURVEYS[kind], request2.seed);
5004
- if (survey === void 0) return { ground: { source: "procedural" } };
5005
- if (request2.backdropRange !== void 0 && asked === void 0)
5006
- return forestFloor(document, kind === void 0 ? survey : SURVEYS[kind], request2.seed);
5007
- const grid = await surveyHeights(survey, document.config.resolution);
5008
- const relief = kind === void 0 ? void 0 : LANDFORMS[kind].reliefRatio * document.config.size;
5009
- const scale = relief === void 0 ? 1 : relief / (grid.max - grid.min || 1);
5010
- applyGroundLayer(document.layers, grid, scale, -grid.min * scale);
5011
- return {
5012
- survey: { row: survey, scale, offset: -grid.min * scale },
5013
- ground: {
5014
- source: "survey",
5015
- name: survey.name,
5016
- lat: survey.lat,
5017
- lon: survey.lon,
5018
- attribution: survey.attribution
5019
- },
5020
- // The attribution rides with the kit: the data source requires it wherever the world is shipped.
5021
- readme: groundReadme(survey)
5395
+
5396
+ // src/cook/reply.ts
5397
+ async function worldReply(input) {
5398
+ const {
5399
+ request: request2,
5400
+ cooked,
5401
+ baked,
5402
+ bands,
5403
+ state,
5404
+ biome,
5405
+ ground,
5406
+ farRing: farRing2,
5407
+ seed,
5408
+ arborTrees,
5409
+ started
5410
+ } = input;
5411
+ const { manifest, files } = baked;
5412
+ const shown = relative(await realpath(request2.projectRoot), request2.out).split(sep).join("/");
5413
+ const url = relative(request2.assetSource, request2.out).split(sep).join("/");
5414
+ const worldUrl = `${url}/world.json`;
5415
+ const ring = Math.ceil(Math.max(manifest.extent.sizeX, manifest.extent.sizeZ) / manifest.cellSize / 2) + 1;
5416
+ const instances = manifest.cells.reduce(
5417
+ (count2, cell) => count2 + cell.runs.reduce((sum, run) => sum + run.count, 0),
5418
+ 0
5419
+ );
5420
+ const placementBytes = files[manifest.placements];
5421
+ if (placementBytes === void 0)
5422
+ throw new Error("cook: world package has no placement records.");
5423
+ const budgets = {
5424
+ residentCells: Math.max(1, manifest.cells.length),
5425
+ instances: Math.max(1, instances),
5426
+ bytes: Math.max(1, placementBytes.byteLength)
5022
5427
  };
5428
+ const heightmapUrl = `${url}/${cooked.manifest.terrain.heightmap}`;
5429
+ const physical = JSON.stringify({
5430
+ extent: cooked.manifest.extent,
5431
+ terrain: cooked.manifest.terrain
5432
+ });
5433
+ return JSON.stringify({
5434
+ recipe: request2.kit,
5435
+ out: shown,
5436
+ worldGlb: `${shown}/world.glb`,
5437
+ recipeJson: `${shown}/recipe.json`,
5438
+ worldPackage: `${shown}/world.json`,
5439
+ ...measureGlb(cooked.worldGlb),
5440
+ placementCounts: cooked.placementCounts,
5441
+ biome: biome.look,
5442
+ ground: ground.ground,
5443
+ // The seed this world was cooked with: pass another as `seed` to reroll it.
5444
+ seed,
5445
+ backdrop: farRing2.decision,
5446
+ water: floodedBodies(state),
5447
+ bands,
5448
+ worldGlbBytes: cooked.worldGlb.length,
5449
+ ms: Math.round(performance.now() - started),
5450
+ load: [
5451
+ 'import { WorldCells as TerrainWorldCells, Heightfield as TerrainHeightfield, heightSamplerFromHeightmap as sampleTerrainHeight, loadWorldHeightmap as loadTerrainHeightmap, loadTerrainSplat, type IWorldCellsLoadOptions as TerrainWorldOptions } from "@threenative/core/world";',
5452
+ 'import { CollisionShape3D as TerrainCollisionShape, RigidBody3D as TerrainRigidBody } from "@threenative/physics";',
5453
+ 'import { Object3D as TerrainAnchor } from "three";',
5454
+ ...arborTrees ? ['import { arborWind } from "./render/arborWind.js";'] : [],
5455
+ "// This world is the level: delete the template's prototype arena (its grid ground, walls and ramp)",
5456
+ "// and keep only the player, spawned at the centre on terrainField.heightAt(0, 0) + terrainSeat.",
5457
+ `const terrainWorld = ${physical};`,
5458
+ `const [terrainHeightmapUrl] = await ctx.assets.resolve(${JSON.stringify(heightmapUrl)});`,
5459
+ 'if (terrainHeightmapUrl === undefined) throw new Error("terrain: the world heightmap is not served.");',
5460
+ "const terrainHeights = await loadTerrainHeightmap(terrainHeightmapUrl);",
5461
+ "const terrainField = TerrainHeightfield.fromSampler({",
5462
+ " columns: terrainWorld.terrain.columns,",
5463
+ " depth: terrainWorld.extent.sizeZ,",
5464
+ " origin: { x: terrainWorld.extent.minX + terrainWorld.extent.sizeX / 2, z: terrainWorld.extent.minZ + terrainWorld.extent.sizeZ / 2 },",
5465
+ " rows: terrainWorld.terrain.rows,",
5466
+ " sampleHeight: sampleTerrainHeight(terrainWorld.terrain, terrainWorld.extent, terrainHeights),",
5467
+ " width: terrainWorld.extent.sizeX,",
5468
+ "});",
5469
+ "const terrainCentre = { x: terrainWorld.extent.minX + terrainWorld.extent.sizeX / 2, z: terrainWorld.extent.minZ + terrainWorld.extent.sizeZ / 2 };",
5470
+ "// Seats the cooked centre pad 5 cm under the game's floor (y = 0), so the floor draws over it. Add",
5471
+ "// terrainSeat to a terrainField.heightAt read. Named override: terrainSeat = 0 keeps the cooked heights.",
5472
+ "const terrainSeat = -terrainField.heightAt(terrainCentre.x, terrainCentre.z) - 0.05;",
5473
+ "const terrainAnchor = new TerrainAnchor();",
5474
+ "terrainAnchor.position.set(terrainCentre.x, terrainSeat, terrainCentre.z);",
5475
+ "const terrainBody = new TerrainRigidBody({",
5476
+ ' entity: "terrain",',
5477
+ " object: terrainAnchor,",
5478
+ " physics: ctx.physics,",
5479
+ " shape: TerrainCollisionShape.heightfield(terrainField.rows, terrainField.columns, terrainField.toColliderHeights(), { x: terrainWorld.extent.sizeX, y: 1, z: terrainWorld.extent.sizeZ }),",
5480
+ ' type: "fixed",',
5481
+ "});",
5482
+ "let world: TerrainWorldCells | undefined;",
5483
+ "let terrainSurface: Awaited<ReturnType<typeof loadTerrainSplat>> | undefined;",
5484
+ "// The anchor owns the streamed world, caller-supplied surface and full-world collider.",
5485
+ 'terrainAnchor.addEventListener("removed", () => { world?.dispose(); terrainSurface?.dispose(); terrainBody.dispose(); });',
5486
+ "ctx.add(terrainAnchor);",
5487
+ "let terrainFollow = terrainAnchor;",
5488
+ 'let terrainInvalidate: NonNullable<TerrainWorldOptions["shadows"]>["invalidate"];',
5489
+ "try {",
5490
+ ` terrainSurface = await loadTerrainSplat({ assets: ctx.assets, renderer: ctx.renderer, url: ${JSON.stringify(worldUrl)} });`,
5491
+ " world = await TerrainWorldCells.load({",
5492
+ ` assets: ctx.assets, url: ${JSON.stringify(worldUrl)}, surface: terrainSurface,`,
5493
+ " follow: { get position() { return terrainFollow.position; } },",
5494
+ ` ring: ${ring}, budgets: ${JSON.stringify(budgets)}, terrain: { streamRadius: ${ring + 1} },`,
5495
+ " shadows: { cast: true, receive: true, invalidate: (region) => terrainInvalidate?.(region) },",
5496
+ ...arborTrees ? [" partMaterial: arborWind,"] : [],
5497
+ "});",
5498
+ " world.position.y = terrainSeat;",
5499
+ " ctx.add(world);",
5500
+ " // The curtain stays up until the ground the camera sees has streamed, so no tree stands over a hole.",
5501
+ " const terrainStreamed = world;",
5502
+ ' if (!ctx.startup.ready) ctx.startup.hold("terrain", () => { const ground = terrainStreamed.terrainReadinessInView(ctx.camera); return ground.loaded >= ground.required; });',
5503
+ "} catch (error) { terrainAnchor.removeFromParent(); throw error; }",
5504
+ 'const loadCells = (follow: TerrainAnchor, invalidate?: NonNullable<TerrainWorldOptions["shadows"]>["invalidate"]) => { terrainFollow = follow; terrainInvalidate = invalidate; };',
5505
+ "// Call loadCells(player.mesh) after creating the player; optionally forward streamed shadow invalidation."
5506
+ ].join("\n"),
5507
+ grass: grassSnippet(biome, state, cooked.manifest.extent),
5508
+ // The sway the load's `partMaterial: arborWind` names: write it to `trees.file` before the load runs.
5509
+ trees: arborTrees ? {
5510
+ file: "src/render/arborWind.ts",
5511
+ source: await readFile(new URL("../../starter/arbor/wind.ts", import.meta.url), "utf8")
5512
+ } : null
5513
+ });
5023
5514
  }
5024
- var RING_SCALE = 10;
5025
- function massifBearing(cameraOffset) {
5026
- const look = Math.atan2(-cameraOffset[2], -cameraOffset[0]) * 180 / Math.PI;
5027
- return [look - MASSIF_SPREAD, look + MASSIF_SPREAD];
5515
+ function grassSnippet(biome, state, extent) {
5516
+ if (biome.grass.length === 0) return null;
5517
+ const ocean = state.waters.find((water2) => water2.kind === "ocean");
5518
+ return [
5519
+ 'import { GrassField3D } from "@threenative/core";',
5520
+ 'import { grassFieldFromBiome } from "@threenative/terrain";',
5521
+ "// The look: copy src/render/grass.ts from the adventure kit (npm create threenative -- --template adventure).",
5522
+ 'import { grassBlade, grassMaterial } from "./render/grass.js";',
5523
+ // `as const` keeps the rows' [min, max] pairs as the tuples grassFieldFromBiome reads.
5524
+ `const grassBiome = ${JSON.stringify({ grass: biome.grass, seed: biome.seed })} as const;`,
5525
+ `const grassPlacement = grassFieldFromBiome(grassBiome, { heightAt: (x, z) => terrainField.heightAt(x, z) + terrainSeat, floor: terrainSeat, waterLevel: ${ocean === void 0 ? "null" : `${ocean.level} + terrainSeat`} });`,
5526
+ 'if (grassPlacement === null) throw new Error("terrain: the biome has no grass row.");',
5527
+ "// Named override: set grassKeepOut to a floor's half-size to keep blades from growing through it.",
5528
+ "const grassKeepOut: { x: number; z: number } | null = null;",
5529
+ "const grassCover = grassPlacement.getDensity;",
5530
+ `const grass = new GrassField3D({ ...grassPlacement, getDensity: (x, z, y, normalY) => (grassKeepOut !== null && Math.abs(x) < grassKeepOut.x && Math.abs(z) < grassKeepOut.z ? 0 : grassCover(x, z, y, normalY)), blade: grassBlade(), material: grassMaterial, bounds: { minX: ${extent.minX}, minZ: ${extent.minZ}, maxX: ${extent.minX + extent.sizeX}, maxZ: ${extent.minZ + extent.sizeZ} } });`,
5531
+ "ctx.add(grass);",
5532
+ "grass.prewarm();",
5533
+ "// In enter(), after creating the player: once per drawn frame the player parts the grass and the camera streams the chunks.",
5534
+ "ctx.beforeRender(() => { grass.pushers[0]?.set(player.position.x, player.position.y, player.position.z, 1.2); grass.update(ctx.camera); });"
5535
+ ].join("\n");
5028
5536
  }
5029
- var MASSIF_SPREAD = 25;
5030
- var MASSIF_ATTEMPTS = 6;
5031
- var WOODED_FOOT = 0.6;
5032
- function woodedFoot(detail, height) {
5033
- const at = (r, c) => detail.heights[r * detail.columns + c];
5034
- let floor = Number.POSITIVE_INFINITY;
5035
- for (let i = 0; i < detail.heights.length; i++)
5036
- floor = Math.min(floor, detail.heights[i]);
5037
- const steep = Math.tan(40 * Math.PI / 180);
5038
- let lower = 0;
5039
- let gentle = 0;
5040
- for (let r = 1; r < detail.rows - 1; r++)
5041
- for (let c = 1; c < detail.columns - 1; c++) {
5042
- const h = at(r, c);
5043
- if (h < floor + 50 || h > floor + height / 2) continue;
5044
- const dx = (at(r, c + 1) - at(r, c - 1)) / (2 * detail.spacing);
5045
- const dz = (at(r + 1, c) - at(r - 1, c)) / (2 * detail.spacing);
5046
- lower++;
5047
- if (Math.hypot(dx, dz) < steep) gentle++;
5537
+
5538
+ // src/cook/cook.ts
5539
+ var MISSING_ASSETS = "terrain_generate needs @threenative/assets in the game project. Run: npm i -D @threenative/assets";
5540
+ function installedEntry2(projectRoot, name) {
5541
+ let directory = resolve(projectRoot);
5542
+ while (true) {
5543
+ const manifestFile = join$1(directory, "node_modules", name, "package.json");
5544
+ if (existsSync(manifestFile)) {
5545
+ const manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
5546
+ const root = manifest.exports?.["."];
5547
+ const relative4 = (typeof root === "string" ? root : root?.import) ?? manifest.main;
5548
+ return relative4 === void 0 ? void 0 : resolve(dirname(manifestFile), relative4);
5048
5549
  }
5049
- return lower === 0 ? 0 : gentle / lower;
5550
+ const parent = dirname(directory);
5551
+ if (parent === directory) return void 0;
5552
+ directory = parent;
5553
+ }
5050
5554
  }
5051
- async function farRing(request2, kind, ground, config, cameraOffset) {
5052
- const range2 = request2.backdropRange ?? kind;
5053
- const rows = range2 === void 0 ? void 0 : MASSIFS[range2];
5054
- if (request2.backdrop === "none" || rows === void 0 || ground.survey === void 0)
5055
- return { decision: { source: "none" } };
5056
- const { row: row2, scale, offset } = ground.survey;
5057
- const resolution = 257;
5058
- const MASSIF_RESOLUTION = 257;
5059
- const fetchMassif = async (massif2) => {
5060
- const grid = await surveyHeights({ ...massif2, zoom: massif2.zoom + 1 }, MASSIF_RESOLUTION).catch(
5061
- (error) => {
5062
- throw new Error(
5063
- `cook: far-ring massif '${massif2.name}': ${error instanceof Error ? error.message : String(error)} Pass backdrop: "none" to cook without the far ring.`
5064
- );
5065
- }
5555
+ async function loadCooker(projectRoot) {
5556
+ const entry = installedEntry2(projectRoot, "@threenative/assets");
5557
+ if (entry === void 0 || !existsSync(entry)) throw new Error(MISSING_ASSETS);
5558
+ const loaded = await import(pathToFileURL(entry).href);
5559
+ if (typeof loaded.cookTerrainWorld !== "function") {
5560
+ throw new Error(`${MISSING_ASSETS} (the installed version has no cookTerrainWorld).`);
5561
+ }
5562
+ return loaded;
5563
+ }
5564
+ async function cookKit(request2) {
5565
+ assertDistFresh();
5566
+ if (!TERRAIN_KITS.includes(request2.kit)) {
5567
+ throw new Error(`cook: unknown kit '${request2.kit}'.`);
5568
+ }
5569
+ const assetSource = request2.assetSource ?? await resolveAssetSource(request2.projectRoot);
5570
+ const logicalOut = relative(assetSource, request2.out);
5571
+ if (logicalOut === "" || logicalOut === ".." || logicalOut.startsWith(`..${sep}`)) {
5572
+ throw new Error(
5573
+ "terrain_generate: out must be under assets.source so the build can list it in the manifest."
5066
5574
  );
5067
- return {
5068
- id: massif2.name,
5069
- size: massif2.extentMeters,
5070
- resolution: MASSIF_RESOLUTION,
5071
- heights: grid.values
5072
- };
5073
- };
5074
- const [ringGrid, ...tiles] = await Promise.all([
5075
- surveyHeights(
5076
- { ...row2, extentMeters: row2.extentMeters * RING_SCALE, zoom: Math.max(1, row2.zoom - 2) },
5077
- resolution
5078
- ),
5079
- ...rows.map(fetchMassif)
5080
- ]);
5081
- const size = config.size * RING_SCALE;
5082
- const host = new Terrain({ size, resolution, seed: config.seed }).heightmap({
5083
- id: "ring",
5084
- data: {
5085
- width: resolution,
5086
- height: resolution,
5087
- values: Array.from(ringGrid.values, (value) => value * scale + offset)
5088
- }
5089
- });
5090
- let chosen;
5091
- let best = -1;
5092
- for (let attempt = 0; attempt < MASSIF_ATTEMPTS && best < WOODED_FOOT; attempt++) {
5093
- const placed = placeMassif(host, {
5094
- seed: (request2.seed ?? config.seed) + attempt * 7919,
5095
- tile: tiles,
5096
- keepOut: config.size * 1.25,
5097
- bearing: massifBearing(cameraOffset)
5098
- });
5099
- const foot = woodedFoot(placed.placement.detail, placed.placement.height);
5100
- if (foot > best) {
5101
- best = foot;
5102
- chosen = placed;
5575
+ }
5576
+ const cooker = await loadCooker(request2.projectRoot);
5577
+ const packageRoot = join$1(dirname(fileURLToPath(import.meta.url)), "..", "..");
5578
+ const kitDir = join$1(packageRoot, "starter", request2.kit);
5579
+ const assetsDir = await starterAssetsDir();
5580
+ await mkdir(dirname(request2.out), { recursive: true });
5581
+ try {
5582
+ await mkdir(request2.out);
5583
+ } catch (error) {
5584
+ if (error.code === "EEXIST") {
5585
+ throw new Error(`cook: out '${request2.out}' already exists.`);
5103
5586
  }
5587
+ throw error;
5588
+ }
5589
+ const scratch = await mkdtemp(join$1(tmpdir(), "tn-arbor-"));
5590
+ try {
5591
+ return await cookInto({ ...request2, assetSource }, cooker, kitDir, assetsDir, scratch);
5592
+ } catch (error) {
5593
+ await rm(request2.out, { recursive: true, force: true });
5594
+ throw error;
5595
+ } finally {
5596
+ await rm(scratch, { recursive: true, force: true });
5104
5597
  }
5105
- const { terrain, placement } = chosen;
5106
- const picked = rows[tiles.findIndex((tile) => tile.id === placement.tile)];
5107
- const decision = {
5108
- source: "massif",
5109
- name: picked.name,
5110
- lat: picked.lat,
5111
- lon: picked.lon,
5112
- attribution: picked.attribution,
5113
- at: [round(placement.at[0]), round(placement.at[1])],
5114
- rotation: round(placement.rotation),
5115
- mirror: placement.mirror,
5116
- height: round(placement.height)
5117
- };
5118
- const heights = Array.from(terrain.evaluate().height, round);
5119
- const { detail } = placement;
5120
- const massif = {
5121
- ...decision,
5122
- detail: { ...detail, heights: Array.from(detail.heights, (h) => Math.round(h * 10) / 10) }
5123
- };
5124
- return {
5125
- decision,
5126
- file: `${JSON.stringify({ size, resolution, heights, massif })}
5127
- `
5128
- };
5129
5598
  }
5130
- async function cookInto(request2, cooker, kitDir, assetsDir) {
5599
+ async function cookInto(request2, cooker, kitDir, assetsDir, scratch) {
5131
5600
  const started = performance.now();
5132
5601
  const file = request2.spec ?? JSON.parse(await readFile(join$1(kitDir, "biome.data.json"), "utf8"));
5133
- const declared = request2.water === void 0 ? file : { ...file, water: request2.water };
5134
- const biome = validateBiome(declared, request2.biome ?? request2.kit);
5135
- const kind = request2.landform ?? (request2.spec === void 0 ? void 0 : biome.landform);
5602
+ const based = request2.region === void 0 ? file : newBiomeSpec(file, request2.region.id, request2.region.overrides);
5603
+ const declared = request2.water === void 0 ? based : { ...based, water: request2.water };
5604
+ const declaredBiome = validateBiome(declared, request2.biome ?? request2.region?.id ?? request2.kit);
5605
+ if (request2.treeSpecies !== void 0 && parseArborSpecies(request2.treeSpecies) === void 0)
5606
+ throw new Error(
5607
+ `cook: treeSpecies '${request2.treeSpecies}' must read arbor:<preset> or arbor:<preset>@<seed>.`
5608
+ );
5609
+ const kind = request2.landform ?? (request2.spec === void 0 ? void 0 : declaredBiome.landform);
5136
5610
  const recipe = kind === void 0 ? JSON.parse(await readFile(join$1(kitDir, "recipe.json"), "utf8")) : {
5137
5611
  recipe: landform(kind, {
5138
5612
  resolution: 257,
5139
- seed: request2.seed ?? biome.seed,
5140
- size: request2.sizeMeters ?? biome.sizeMeters
5613
+ seed: request2.seed ?? declaredBiome.seed,
5614
+ size: request2.sizeMeters ?? declaredBiome.sizeMeters
5141
5615
  }).toJSON()
5142
5616
  };
5143
5617
  const unrouted = request2.water === void 0 ? [] : applyWaterRows(recipe.recipe.layers, request2.water);
5144
5618
  if (request2.sizeMeters !== void 0) recipe.recipe.config.size = request2.sizeMeters;
5145
5619
  if (request2.seed !== void 0) recipe.recipe.config.seed = request2.seed;
5146
- const ground = await applyGround(recipe.recipe, request2, kind);
5620
+ const ground = request2.ground === void 0 && request2.region !== void 0 ? await forestFloor(recipe.recipe, request2.region.site, request2.seed) : await applyGround(recipe.recipe, request2, kind);
5147
5621
  const farRingResult = await farRing(
5148
5622
  request2,
5149
5623
  kind,
5150
5624
  ground,
5151
5625
  recipe.recipe.config,
5152
- biome.spawn.cameraOffset
5626
+ declaredBiome.spawn.cameraOffset
5153
5627
  );
5154
5628
  for (const layer2 of recipe.recipe.layers) {
5155
5629
  const data = layer2.params?.data;
@@ -5162,25 +5636,50 @@ async function cookInto(request2, cooker, kitDir, assetsDir) {
5162
5636
  }
5163
5637
  const assetTable = JSON.parse(await readFile(join$1(kitDir, "assets.json"), "utf8"));
5164
5638
  const surface = JSON.parse(await readFile(join$1(kitDir, "surface.json"), "utf8"));
5639
+ const canopy = request2.region?.canopy ?? [];
5640
+ for (const id of canopy) delete assetTable[id];
5641
+ if (canopy.length > 0) {
5642
+ recipe.recipe.layers = recipe.recipe.layers.filter(
5643
+ (layer2) => layer2.type !== "scatter" || !canopy.includes(layer2.params?.asset)
5644
+ );
5645
+ }
5646
+ const kitArbor = await growArborRows(assetTable, request2.projectRoot, scratch, assetsDir);
5647
+ const biome = await growArborSpecies({
5648
+ assetTable,
5649
+ biome: declaredBiome,
5650
+ projectRoot: request2.projectRoot,
5651
+ scratch,
5652
+ ...request2.treeSpecies === void 0 ? {} : { treeSpecies: request2.treeSpecies }
5653
+ });
5654
+ const arborTrees = kitArbor || biome !== declaredBiome;
5165
5655
  carveFeatures(recipe.recipe, request2.features ?? []);
5166
5656
  shapeCoast(recipe.recipe);
5657
+ const replaced = ground.ground.source === "survey" || ground.ground.source === "heightmap";
5658
+ if (kind === void 0 && replaced) placeLakes(recipe.recipe, unpinLakes(recipe.recipe), false);
5167
5659
  const lakes = unrouted.filter((row2) => row2.kind === "lake");
5168
5660
  if (lakes.length > 0) placeLakes(recipe.recipe, lakes);
5169
5661
  const rivers = unrouted.filter((row2) => row2.kind === "river");
5170
5662
  if (rivers.length > 0) routeRivers(recipe.recipe, rivers);
5171
5663
  const evaluated = Terrain.fromJSON(recipe.recipe).evaluate();
5172
5664
  const state = applyPlacementOverrides(
5173
- scatterFoliage(evaluated, biome, kind, assetTable),
5665
+ // A region always places its own rows: they are the stand, whether or not the kit shipped one.
5666
+ scatterFoliage(evaluated, biome, kind, assetTable, request2.region !== void 0),
5174
5667
  recipe.placementOverrides ?? {}
5175
5668
  );
5669
+ const impostors = new Map(
5670
+ biome.foliage.flatMap(
5671
+ (row2) => row2.far?.impostor === void 0 ? [] : [[row2.species, row2.far.impostor]]
5672
+ )
5673
+ );
5176
5674
  const species2 = Object.fromEntries(
5177
5675
  Object.entries(assetTable).map(([id, spec]) => [
5178
5676
  id,
5179
5677
  {
5180
- glb: join$1(assetsDir, spec.near),
5678
+ glb: resolve(assetsDir, spec.near),
5181
5679
  bounds: parseBounds(spec.bounds, id),
5182
- lods: spec.mid ? [{ distance: spec.midDistance ?? 40, glb: join$1(assetsDir, spec.mid) }] : [],
5183
- maxDistance: spec.maxDistance
5680
+ lods: spec.mid ? [{ distance: spec.midDistance ?? 40, glb: resolve(assetsDir, spec.mid) }] : [],
5681
+ maxDistance: spec.maxDistance,
5682
+ ...impostors.has(id) ? { impostorDistance: impostors.get(id) } : {}
5184
5683
  }
5185
5684
  ])
5186
5685
  );
@@ -5242,103 +5741,24 @@ ${farRingResult.decision.attribution}
5242
5741
  `${JSON.stringify({ ...surface, splat, textures: "textures" }, null, 2)}
5243
5742
  `
5244
5743
  );
5245
- await copyFile(
5246
- join$1(assetsDir, "hdri", "kloofendal_48d_partly_cloudy_1k.hdr"),
5247
- join$1(request2.out, "sky.hdr")
5248
- );
5744
+ await copyFile(join$1(assetsDir, DEFAULT_SKY_HDRI), join$1(request2.out, "sky.hdr"));
5249
5745
  await writeFile(join$1(request2.out, "recipe.json"), JSON.stringify(recipe.recipe));
5250
- const shown = relative(await realpath(request2.projectRoot), request2.out).split(sep).join("/");
5251
- const url = relative(request2.assetSource, request2.out).split(sep).join("/");
5252
- const worldUrl = `${url}/world.json`;
5253
- const ring = Math.ceil(Math.max(manifest.extent.sizeX, manifest.extent.sizeZ) / manifest.cellSize / 2) + 1;
5254
- const instances = manifest.cells.reduce(
5255
- (count2, cell) => count2 + cell.runs.reduce((sum, run) => sum + run.count, 0),
5256
- 0
5257
- );
5258
- const placementBytes = files[manifest.placements];
5259
- if (placementBytes === void 0)
5260
- throw new Error("cook: world package has no placement records.");
5261
- const budgets = {
5262
- residentCells: Math.max(1, manifest.cells.length),
5263
- instances: Math.max(1, instances),
5264
- bytes: Math.max(1, placementBytes.byteLength)
5265
- };
5266
- const heightmapUrl = `${url}/${cooked.manifest.terrain.heightmap}`;
5267
- const physical = JSON.stringify({
5268
- extent: cooked.manifest.extent,
5269
- terrain: cooked.manifest.terrain
5270
- });
5271
- return JSON.stringify({
5272
- recipe: request2.kit,
5273
- out: shown,
5274
- worldGlb: `${shown}/world.glb`,
5275
- recipeJson: `${shown}/recipe.json`,
5276
- worldPackage: `${shown}/world.json`,
5277
- ...measureGlb(cooked.worldGlb),
5278
- placementCounts: cooked.placementCounts,
5279
- biome: biome.look,
5280
- ground: ground.ground,
5281
- // The seed this world was cooked with: pass another as `seed` to reroll it.
5282
- seed: recipe.recipe.config.seed,
5283
- backdrop: farRingResult.decision,
5284
- water: floodedBodies(state),
5746
+ return worldReply({
5747
+ request: request2,
5748
+ cooked,
5749
+ baked: { manifest, splat, files },
5285
5750
  bands,
5286
- worldGlbBytes: cooked.worldGlb.length,
5287
- ms: Math.round(performance.now() - started),
5288
- load: [
5289
- 'import { WorldCells as TerrainWorldCells, Heightfield as TerrainHeightfield, heightSamplerFromHeightmap as sampleTerrainHeight, loadWorldHeightmap as loadTerrainHeightmap, loadTerrainSplat, type IWorldCellsLoadOptions as TerrainWorldOptions } from "@threenative/core/world";',
5290
- 'import { CollisionShape3D as TerrainCollisionShape, RigidBody3D as TerrainRigidBody } from "@threenative/physics";',
5291
- 'import { Object3D as TerrainAnchor } from "three";',
5292
- `const terrainWorld = ${physical};`,
5293
- `const [terrainHeightmapUrl] = await ctx.assets.resolve(${JSON.stringify(heightmapUrl)});`,
5294
- 'if (terrainHeightmapUrl === undefined) throw new Error("terrain: the world heightmap is not served.");',
5295
- "const terrainHeights = await loadTerrainHeightmap(terrainHeightmapUrl);",
5296
- "const terrainField = TerrainHeightfield.fromSampler({",
5297
- " columns: terrainWorld.terrain.columns,",
5298
- " depth: terrainWorld.extent.sizeZ,",
5299
- " origin: { x: terrainWorld.extent.minX + terrainWorld.extent.sizeX / 2, z: terrainWorld.extent.minZ + terrainWorld.extent.sizeZ / 2 },",
5300
- " rows: terrainWorld.terrain.rows,",
5301
- " sampleHeight: sampleTerrainHeight(terrainWorld.terrain, terrainWorld.extent, terrainHeights),",
5302
- " width: terrainWorld.extent.sizeX,",
5303
- "});",
5304
- "const terrainCentre = { x: terrainWorld.extent.minX + terrainWorld.extent.sizeX / 2, z: terrainWorld.extent.minZ + terrainWorld.extent.sizeZ / 2 };",
5305
- "// Seats the cooked centre pad 5 cm under the game's floor (y = 0), so the floor draws over it. Add",
5306
- "// terrainSeat to a terrainField.heightAt read. Named override: terrainSeat = 0 keeps the cooked heights.",
5307
- "const terrainSeat = -terrainField.heightAt(terrainCentre.x, terrainCentre.z) - 0.05;",
5308
- "const terrainAnchor = new TerrainAnchor();",
5309
- "terrainAnchor.position.set(terrainCentre.x, terrainSeat, terrainCentre.z);",
5310
- "const terrainBody = new TerrainRigidBody({",
5311
- ' entity: "terrain",',
5312
- " object: terrainAnchor,",
5313
- " physics: ctx.physics,",
5314
- " shape: TerrainCollisionShape.heightfield(terrainField.rows, terrainField.columns, terrainField.toColliderHeights(), { x: terrainWorld.extent.sizeX, y: 1, z: terrainWorld.extent.sizeZ }),",
5315
- ' type: "fixed",',
5316
- "});",
5317
- "let world: TerrainWorldCells | undefined;",
5318
- "let terrainSurface: Awaited<ReturnType<typeof loadTerrainSplat>> | undefined;",
5319
- "// The anchor owns the streamed world, caller-supplied surface and full-world collider.",
5320
- 'terrainAnchor.addEventListener("removed", () => { world?.dispose(); terrainSurface?.dispose(); terrainBody.dispose(); });',
5321
- "ctx.add(terrainAnchor);",
5322
- "let terrainFollow = terrainAnchor;",
5323
- 'let terrainInvalidate: NonNullable<TerrainWorldOptions["shadows"]>["invalidate"];',
5324
- "try {",
5325
- ` terrainSurface = await loadTerrainSplat({ assets: ctx.assets, renderer: ctx.renderer, url: ${JSON.stringify(worldUrl)} });`,
5326
- " world = await TerrainWorldCells.load({",
5327
- ` assets: ctx.assets, url: ${JSON.stringify(worldUrl)}, surface: terrainSurface,`,
5328
- " follow: { get position() { return terrainFollow.position; } },",
5329
- ` ring: ${ring}, budgets: ${JSON.stringify(budgets)}, terrain: { streamRadius: ${ring + 1} },`,
5330
- " shadows: { cast: true, receive: true, invalidate: (region) => terrainInvalidate?.(region) },",
5331
- "});",
5332
- " world.position.y = terrainSeat;",
5333
- " ctx.add(world);",
5334
- "} catch (error) { terrainAnchor.removeFromParent(); throw error; }",
5335
- 'const loadCells = (follow: TerrainAnchor, invalidate?: NonNullable<TerrainWorldOptions["shadows"]>["invalidate"]) => { terrainFollow = follow; terrainInvalidate = invalidate; };',
5336
- "// Call loadCells(player.mesh) after creating the player; optionally forward streamed shadow invalidation."
5337
- ].join("\n")
5751
+ state,
5752
+ biome,
5753
+ ground,
5754
+ farRing: farRingResult,
5755
+ seed: recipe.recipe.config.seed,
5756
+ arborTrees,
5757
+ started
5338
5758
  });
5339
5759
  }
5340
5760
 
5341
- // src/mcp/cook-child.ts
5761
+ // src/cook/cook-child.ts
5342
5762
  var request = JSON.parse(process.argv[2] ?? "null");
5343
5763
  if (typeof request !== "object" || request === null) {
5344
5764
  throw new Error("cook-child: the request must be a JSON object.");