@threenative/terrain 0.1.6 → 0.1.8

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 (127) hide show
  1. package/AGENT_GUIDE.md +19 -4
  2. package/dist/editor/index.d.ts +160 -5
  3. package/dist/editor/index.js +3783 -1406
  4. package/dist/editor/server.d.ts +2 -2
  5. package/dist/editor/server.js +555 -121
  6. package/dist/editor/worker.d.ts +33 -1
  7. package/dist/editor/worker.js +444 -110
  8. package/dist/export.d.ts +11 -9
  9. package/dist/export.js +22 -34
  10. package/dist/index.d.ts +727 -73
  11. package/dist/index.js +2434 -553
  12. package/dist/kit.d.ts +56 -0
  13. package/dist/kit.js +2524 -0
  14. package/dist/mcp/cook-child.d.ts +2 -0
  15. package/dist/mcp/cook-child.js +3705 -0
  16. package/dist/mcp/server.d.ts +7 -0
  17. package/dist/mcp/server.js +3279 -0
  18. package/dist/{server-ByM2hmYJ.d.ts → server-C8Ydr_IM.d.ts} +3 -2
  19. package/dist/starter.d.ts +143 -0
  20. package/dist/starter.js +1030 -0
  21. package/dist/{terrain-gPnkCU6S.d.ts → terrain-B3DkduPw.d.ts} +3 -2
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-Ant8-Axc.d.ts → types-CPYAc9vo.d.ts} +13 -4
  24. package/dist/world-package-B7KGYIou.d.ts +94 -0
  25. package/package.json +28 -6
  26. package/starter/alpine/README.md +77 -1
  27. package/starter/alpine/bake.mjs +4 -116
  28. package/starter/alpine/biome.data.json +114 -0
  29. package/starter/alpine/heightmap.r16 +0 -0
  30. package/starter/alpine/recipe.json +3 -66051
  31. package/starter/alpine/world.ts +45 -293
  32. package/starter/coastal/README.md +77 -1
  33. package/starter/coastal/bake.mjs +4 -116
  34. package/starter/coastal/biome.data.json +135 -0
  35. package/starter/coastal/heightmap.r16 +0 -0
  36. package/starter/coastal/recipe.json +3 -66051
  37. package/starter/coastal/sea.ts +49 -16
  38. package/starter/coastal/world.ts +53 -318
  39. package/starter/desert/README.md +77 -1
  40. package/starter/desert/bake.mjs +4 -116
  41. package/starter/desert/biome.data.json +114 -0
  42. package/starter/desert/heightmap.r16 +0 -0
  43. package/starter/desert/recipe.json +3 -66051
  44. package/starter/desert/world.ts +45 -293
  45. package/starter/forest/README.md +84 -4
  46. package/starter/forest/assets.json +32 -0
  47. package/starter/forest/bake.mjs +6 -116
  48. package/starter/forest/biome.data.json +150 -0
  49. package/starter/forest/heightmap.r16 +0 -0
  50. package/starter/forest/recipe.json +192 -4428
  51. package/starter/forest/sky.ts +11 -0
  52. package/starter/forest/water.ts +30 -20
  53. package/starter/forest/world.ts +86 -322
  54. package/starter/tundra/README.md +77 -1
  55. package/starter/tundra/bake.mjs +4 -116
  56. package/starter/tundra/biome.data.json +131 -0
  57. package/starter/tundra/heightmap.r16 +0 -0
  58. package/starter/tundra/recipe.json +18 -66066
  59. package/starter/tundra/world.ts +65 -319
  60. package/starter-assets.json +6 -0
  61. package/{starter-assets/credits.json → starter-credits.json} +12 -105
  62. package/starter-assets/bark_brown_02/bark_brown_02_diff_1k.jpg +0 -0
  63. package/starter-assets/bark_brown_02/bark_brown_02_nor_gl_1k.jpg +0 -0
  64. package/starter-assets/bark_brown_02/bark_brown_02_rough_1k.jpg +0 -0
  65. package/starter-assets/boulder_01/boulder-mid.glb +0 -0
  66. package/starter-assets/boulder_01/boulder-near.glb +0 -0
  67. package/starter-assets/cliff_side/cliff_side_ao_1k.jpg +0 -0
  68. package/starter-assets/cliff_side/cliff_side_diff_1k.jpg +0 -0
  69. package/starter-assets/cliff_side/cliff_side_nor_gl_1k.jpg +0 -0
  70. package/starter-assets/cliff_side/cliff_side_rough_1k.jpg +0 -0
  71. package/starter-assets/fern_02/fern_02_alpha_512.png +0 -0
  72. package/starter-assets/fern_02/fern_02_diff_512.jpg +0 -0
  73. package/starter-assets/fern_02/fern_02_nor_gl_512.jpg +0 -0
  74. package/starter-assets/fir_tree_01/fir-b-lod1.glb +0 -0
  75. package/starter-assets/fir_tree_01/fir-b-lod2.glb +0 -0
  76. package/starter-assets/fir_tree_01/fir-c-lod1.glb +0 -0
  77. package/starter-assets/fir_tree_01/fir-c-lod2.glb +0 -0
  78. package/starter-assets/fir_tree_01/fir_tree_01_twig_arm_1k.jpg +0 -0
  79. package/starter-assets/fir_tree_01/fir_tree_01_twig_diff_1k.jpg +0 -0
  80. package/starter-assets/fir_tree_01/fir_tree_01_twig_nor_gl_1k.jpg +0 -0
  81. package/starter-assets/forest_ground_04/forest_ground_04_ao_1k.jpg +0 -0
  82. package/starter-assets/forest_ground_04/forest_ground_04_diff_1k.jpg +0 -0
  83. package/starter-assets/forest_ground_04/forest_ground_04_nor_gl_1k.jpg +0 -0
  84. package/starter-assets/forest_ground_04/forest_ground_04_rough_1k.jpg +0 -0
  85. package/starter-assets/forest_leaves_02/forest_leaves_02_arm_512.jpg +0 -0
  86. package/starter-assets/forest_leaves_02/forest_leaves_02_diff_512.jpg +0 -0
  87. package/starter-assets/forest_leaves_02/forest_leaves_02_nor_gl_512.jpg +0 -0
  88. package/starter-assets/grass_medium_02/grass_medium_02_alpha_512.png +0 -0
  89. package/starter-assets/grass_medium_02/grass_medium_02_diff_512.jpg +0 -0
  90. package/starter-assets/grass_medium_02/grass_medium_02_nor_gl_512.jpg +0 -0
  91. package/starter-assets/hdri/kloofendal_48d_partly_cloudy_1k.hdr +0 -0
  92. package/starter-assets/leafy_grass/leafy_grass_ao_1k.jpg +0 -0
  93. package/starter-assets/leafy_grass/leafy_grass_diff_1k.jpg +0 -0
  94. package/starter-assets/leafy_grass/leafy_grass_nor_gl_1k.jpg +0 -0
  95. package/starter-assets/leafy_grass/leafy_grass_rough_1k.jpg +0 -0
  96. package/starter-assets/lichen_rock/lichen_rock_arm_512.jpg +0 -0
  97. package/starter-assets/lichen_rock/lichen_rock_diff_512.jpg +0 -0
  98. package/starter-assets/lichen_rock/lichen_rock_nor_gl_512.jpg +0 -0
  99. package/starter-assets/mossy_rock/mossy_rock_ao_1k.jpg +0 -0
  100. package/starter-assets/mossy_rock/mossy_rock_diff_1k.jpg +0 -0
  101. package/starter-assets/mossy_rock/mossy_rock_nor_gl_1k.jpg +0 -0
  102. package/starter-assets/mossy_rock/mossy_rock_rough_1k.jpg +0 -0
  103. package/starter-assets/needle-atlas.png +0 -0
  104. package/starter-assets/needle-surface.png +0 -0
  105. package/starter-assets/river_small_rocks/river_small_rocks_arm_512.jpg +0 -0
  106. package/starter-assets/river_small_rocks/river_small_rocks_diff_512.jpg +0 -0
  107. package/starter-assets/river_small_rocks/river_small_rocks_nor_gl_512.jpg +0 -0
  108. package/starter-assets/rock_boulder_dry/rock_boulder_dry_arm_512.jpg +0 -0
  109. package/starter-assets/rock_boulder_dry/rock_boulder_dry_diff_512.jpg +0 -0
  110. package/starter-assets/rock_boulder_dry/rock_boulder_dry_nor_gl_512.jpg +0 -0
  111. package/starter-assets/rocks/boulder-mid.glb +0 -0
  112. package/starter-assets/rocks/boulder-near.glb +0 -0
  113. package/starter-assets/rocks/boulder-prep.json +0 -37
  114. package/starter-assets/rocks/rock01-mid.glb +0 -0
  115. package/starter-assets/rocks/rock01-near.glb +0 -0
  116. package/starter-assets/rocks/rock01-prep.json +0 -37
  117. package/starter-assets/rocks/rock04-mid.glb +0 -0
  118. package/starter-assets/rocks/rock04-near.glb +0 -0
  119. package/starter-assets/rocks/rock04-prep.json +0 -37
  120. package/starter-assets/sand_01/sand_01_ao_1k.jpg +0 -0
  121. package/starter-assets/sand_01/sand_01_diff_1k.jpg +0 -0
  122. package/starter-assets/sand_01/sand_01_nor_gl_1k.jpg +0 -0
  123. package/starter-assets/sand_01/sand_01_rough_1k.jpg +0 -0
  124. package/starter-assets/snow_02/snow_02_ao_1k.jpg +0 -0
  125. package/starter-assets/snow_02/snow_02_diff_1k.jpg +0 -0
  126. package/starter-assets/snow_02/snow_02_nor_gl_1k.jpg +0 -0
  127. package/starter-assets/snow_02/snow_02_rough_1k.jpg +0 -0
@@ -0,0 +1,3705 @@
1
+ import { existsSync, readFileSync } from 'fs';
2
+ import { mkdir, rm, lstat, realpath, readFile, mkdtemp, rename, writeFile, copyFile } from 'fs/promises';
3
+ import { relative, sep, join, dirname, resolve, isAbsolute } from 'path';
4
+ import { fileURLToPath, pathToFileURL } from 'url';
5
+ import '@threenative/core/world';
6
+ import '@threenative/core';
7
+ import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
8
+ import { createHash } from 'crypto';
9
+ import { homedir } from 'os';
10
+ import { gunzipSync } from 'zlib';
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
+ }
47
+
48
+ // src/core/math.ts
49
+ var clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
50
+ var lerp = (a, b, t) => a + (b - a) * t;
51
+ var smoothstep = (a, b, x) => {
52
+ if (a === b) return x >= b ? 1 : 0;
53
+ const t = clamp((x - a) / (b - a));
54
+ return t * t * (3 - 2 * t);
55
+ };
56
+ var hashString = (text2) => {
57
+ let h = 2166136261;
58
+ for (const c of text2) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
59
+ return h >>> 0;
60
+ };
61
+ function random(seed) {
62
+ let a = seed >>> 0;
63
+ return () => {
64
+ a |= 0;
65
+ a = a + 1831565813 | 0;
66
+ let t = Math.imul(a ^ a >>> 15, 1 | a);
67
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
68
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
69
+ };
70
+ }
71
+ var hash2 = (x, z, seed) => {
72
+ let n = Math.imul(x | 0, 374761393) ^ Math.imul(z | 0, 668265263) ^ seed;
73
+ n = Math.imul(n ^ n >>> 13, 1274126177);
74
+ return (n ^ n >>> 16) >>> 0;
75
+ };
76
+ var diagonalGradient = 0.7071;
77
+ var grad = (h, x, z) => {
78
+ switch (h & 7) {
79
+ case 0:
80
+ return x;
81
+ case 1:
82
+ return -x;
83
+ case 2:
84
+ return z;
85
+ case 3:
86
+ return -z;
87
+ case 4:
88
+ return (x + z) * diagonalGradient;
89
+ case 5:
90
+ return (x - z) * diagonalGradient;
91
+ case 6:
92
+ return (-x + z) * diagonalGradient;
93
+ default:
94
+ return (-x - z) * diagonalGradient;
95
+ }
96
+ };
97
+ function noise2(x, z, seed = 1) {
98
+ const ix = Math.floor(x);
99
+ const iz = Math.floor(z);
100
+ const fx = x - ix;
101
+ const fz = z - iz;
102
+ const u = fx * fx * fx * (fx * (fx * 6 - 15) + 10);
103
+ const v = fz * fz * fz * (fz * (fz * 6 - 15) + 10);
104
+ return lerp(
105
+ lerp(grad(hash2(ix, iz, seed), fx, fz), grad(hash2(ix + 1, iz, seed), fx - 1, fz), u),
106
+ lerp(
107
+ grad(hash2(ix, iz + 1, seed), fx, fz - 1),
108
+ grad(hash2(ix + 1, iz + 1, seed), fx - 1, fz - 1),
109
+ u
110
+ ),
111
+ v
112
+ ) * 1.65;
113
+ }
114
+ function fbm(inputX, inputZ, { seed = 1, octaves = 5, persistence = 0.5, lacunarity = 2, mode = "fbm" } = {}) {
115
+ let x = inputX;
116
+ let z = inputZ;
117
+ let value = 0;
118
+ let amplitude = 1;
119
+ let total = 0;
120
+ for (let i = 0; i < octaves; i += 1) {
121
+ let n = noise2(x + 13.17, z - 8.71, seed + i * 71);
122
+ if (mode === "ridged") n = (1 - Math.abs(n)) ** 2 * 2 - 1;
123
+ if (mode === "billow") n = Math.abs(n) * 2 - 1;
124
+ value += n * amplitude;
125
+ total += amplitude;
126
+ amplitude *= persistence;
127
+ x *= lacunarity;
128
+ z *= lacunarity;
129
+ }
130
+ return total ? value / total : 0;
131
+ }
132
+ var world = (grid, x) => x / (grid.resolution - 1) * grid.size - grid.size / 2;
133
+ function sampleGrid(a, width, height, u, v) {
134
+ const gx = clamp(u, 0, 1) * (width - 1);
135
+ const gz = clamp(v, 0, 1) * (height - 1);
136
+ const x = Math.min(width - 2, Math.floor(gx));
137
+ const z = Math.min(height - 2, Math.floor(gz));
138
+ const tx = gx - x;
139
+ const tz = gz - z;
140
+ return lerp(
141
+ lerp(a[z * width + x], a[z * width + x + 1], tx),
142
+ lerp(a[(z + 1) * width + x], a[(z + 1) * width + x + 1], tx),
143
+ tz
144
+ );
145
+ }
146
+ var sampleHeight = (grid, x, z) => sampleGrid(
147
+ grid.height,
148
+ grid.resolution,
149
+ grid.resolution,
150
+ x / grid.size + 0.5,
151
+ z / grid.size + 0.5
152
+ );
153
+ function gradientAt(grid, x, z) {
154
+ const d = grid.size / (grid.resolution - 1);
155
+ return [
156
+ (sampleHeight(grid, x + d, z) - sampleHeight(grid, x - d, z)) / (Math.min(grid.size / 2, x + d) - Math.max(-grid.size / 2, x - d) || d),
157
+ (sampleHeight(grid, x, z + d) - sampleHeight(grid, x, z - d)) / (Math.min(grid.size / 2, z + d) - Math.max(-grid.size / 2, z - d) || d)
158
+ ];
159
+ }
160
+ function slopeAtIndex(grid, i) {
161
+ const n = grid.resolution;
162
+ const x = i % n;
163
+ const z = Math.floor(i / n);
164
+ const dx = x > 0 && x < n - 1 ? 2 : 1;
165
+ const dz = z > 0 && z < n - 1 ? 2 : 1;
166
+ const cell = grid.size / (n - 1);
167
+ const gx = (grid.height[z * n + Math.min(x + 1, n - 1)] - grid.height[z * n + Math.max(x - 1, 0)]) / (dx * cell);
168
+ const gz = (grid.height[Math.min(z + 1, n - 1) * n + x] - grid.height[Math.max(z - 1, 0) * n + x]) / (dz * cell);
169
+ return Math.atan(Math.hypot(gx, gz)) * (180 / Math.PI);
170
+ }
171
+ function falloff(distance, radius, softness = 0.6) {
172
+ const d = distance / radius;
173
+ return d >= 1 ? 0 : 1 - smoothstep(1 - clamp(softness, 1e-5, 1), 1, d);
174
+ }
175
+ function splinePoints(points, step = 3, smooth = true) {
176
+ const out = [];
177
+ for (let k = 0; k < points.length - 1; k += 1) {
178
+ const a = points[Math.max(0, k - 1)];
179
+ const b = points[k];
180
+ const c = points[k + 1];
181
+ const d = points[Math.min(points.length - 1, k + 2)];
182
+ const count2 = Math.max(
183
+ 1,
184
+ Math.min(512, Math.ceil(Math.hypot(c[0] - b[0], c[2] - b[2]) / step))
185
+ );
186
+ for (let j = 0; j < count2; j += 1) {
187
+ const t = j / count2;
188
+ const t2 = t * t;
189
+ const t3 = t2 * t;
190
+ const cat = (dim) => 0.5 * (2 * b[dim] + (-a[dim] + c[dim]) * t + (2 * a[dim] - 5 * b[dim] + 4 * c[dim] - d[dim]) * t2 + (-a[dim] + 3 * b[dim] - 3 * c[dim] + d[dim]) * t3);
191
+ out.push([
192
+ smooth ? cat(0) : lerp(b[0], c[0], t),
193
+ lerp(b[1], c[1], t),
194
+ smooth ? cat(2) : lerp(b[2], c[2], t)
195
+ ]);
196
+ }
197
+ }
198
+ const last = points[points.length - 1];
199
+ out.push([last[0], last[1], last[2]]);
200
+ return out;
201
+ }
202
+
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
+ }
244
+ }
245
+ for (let i = 0; i < h.length; i += 1) h[i] = h[i] + delta[i];
246
+ }
247
+ return h;
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
+ }
267
+ }
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
+ }
274
+ return cells;
275
+ }
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;
348
+ }
349
+ } else {
350
+ for (let k = 0; k < brushCount; k += 1) {
351
+ const i = base + brushOffset[k];
352
+ const share2 = amount * brushWeight[k] / total2;
353
+ h[i] = h[i] + share2;
354
+ }
355
+ }
356
+ return amount;
357
+ }
358
+ let total = 0;
359
+ for (let k = 0; k < brushCount; k += 1) {
360
+ const ix = x + brushDx[k];
361
+ const iz = z + brushDz[k];
362
+ if (ix >= 0 && ix < n && iz >= 0 && iz < n) total += brushWeight[k];
363
+ }
364
+ if (total <= 0) return 0;
365
+ if (amount < 0) {
366
+ let moved = 0;
367
+ for (let k = 0; k < brushCount; k += 1) {
368
+ const ix = x + brushDx[k];
369
+ const iz = z + brushDz[k];
370
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
371
+ const i = iz * n + ix;
372
+ const share2 = amount * brushWeight[k] / total;
373
+ const avail = h[i] - floor;
374
+ const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
375
+ h[i] = h[i] + change;
376
+ moved += change;
377
+ }
378
+ return moved;
379
+ }
380
+ if (obsDeposition !== void 0) {
381
+ for (let k = 0; k < brushCount; k += 1) {
382
+ const ix = x + brushDx[k];
383
+ const iz = z + brushDz[k];
384
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
385
+ const i = iz * n + ix;
386
+ const share2 = amount * brushWeight[k] / total;
387
+ h[i] = h[i] + share2;
388
+ obsDeposition[i] = obsDeposition[i] + share2;
389
+ }
390
+ } else {
391
+ for (let k = 0; k < brushCount; k += 1) {
392
+ const ix = x + brushDx[k];
393
+ const iz = z + brushDz[k];
394
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
395
+ const i = iz * n + ix;
396
+ const share2 = amount * brushWeight[k] / total;
397
+ h[i] = h[i] + share2;
398
+ }
399
+ }
400
+ return amount;
401
+ };
402
+ const probeOld = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
403
+ const probeNext = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
404
+ const get = (x, z, out) => {
405
+ const ix = Math.min(n - 2, Math.floor(x));
406
+ const iz = Math.min(n - 2, Math.floor(z));
407
+ const tx = x - ix;
408
+ const tz = z - iz;
409
+ const i = iz * n + ix;
410
+ const h00 = h[i];
411
+ const h10 = h[i + 1];
412
+ const h01 = h[i + n];
413
+ const h11 = h[i + n + 1];
414
+ const g10 = h10 - h00;
415
+ const g01 = h01 - h00;
416
+ const v0 = h00 + g10 * tx;
417
+ const v1 = h01 + (h11 - h01) * tx;
418
+ out.value = v0 + (v1 - v0) * tz;
419
+ out.dx = (g10 + (h11 - h01 - g10) * tz) / cell;
420
+ out.dz = (g01 + (h11 - h10 - g01) * tx) / cell;
421
+ out.ix = ix;
422
+ out.iz = iz;
423
+ return out;
424
+ };
425
+ for (let k = 0; k < droplets; k += 1) {
426
+ let x = rnd() * (n - 1 - 1e-3);
427
+ let z = rnd() * (n - 1 - 1e-3);
428
+ let dx = 0;
429
+ let dz = 0;
430
+ let water2 = 1;
431
+ let speed = 1;
432
+ let sediment = 0;
433
+ for (let step = 0; step < maxSteps; step += 1) {
434
+ const old = get(x, z, probeOld);
435
+ if (obsFlow !== void 0 && obsSediment !== void 0) {
436
+ const tx = x - old.ix;
437
+ const tz = z - old.iz;
438
+ const i = old.iz * n + old.ix;
439
+ const w00 = (1 - tx) * (1 - tz);
440
+ const w10 = tx * (1 - tz);
441
+ const w01 = (1 - tx) * tz;
442
+ const w11 = tx * tz;
443
+ obsFlow[i] = obsFlow[i] + water2 * w00;
444
+ obsSediment[i] = obsSediment[i] + sediment * w00;
445
+ obsFlow[i + 1] = obsFlow[i + 1] + water2 * w10;
446
+ obsSediment[i + 1] = obsSediment[i + 1] + sediment * w10;
447
+ obsFlow[i + n] = obsFlow[i + n] + water2 * w01;
448
+ obsSediment[i + n] = obsSediment[i + n] + sediment * w01;
449
+ obsFlow[i + n + 1] = obsFlow[i + n + 1] + water2 * w11;
450
+ obsSediment[i + n + 1] = obsSediment[i + n + 1] + sediment * w11;
451
+ }
452
+ dx = dx * inertia - old.dx * oneMinusInertia;
453
+ dz = dz * inertia - old.dz * oneMinusInertia;
454
+ const largest = Math.max(Math.abs(dx), Math.abs(dz));
455
+ const scaledX = Math.abs(dx) / largest;
456
+ const scaledZ = Math.abs(dz) / largest;
457
+ let length = largest === 0 || largest === Number.POSITIVE_INFINITY ? largest : Math.sqrt(scaledX * scaledX + scaledZ * scaledZ) * largest;
458
+ if (length < 1e-9) {
459
+ const angle = rnd() * Math.PI * 2;
460
+ dx = Math.cos(angle);
461
+ dz = Math.sin(angle);
462
+ length = 1;
463
+ }
464
+ dx /= length;
465
+ dz /= length;
466
+ const nx = x + dx;
467
+ const nz = z + dz;
468
+ if (nx < 0 || nx >= n - 1 || nz < 0 || nz >= n - 1) {
469
+ sediment = 0;
470
+ break;
471
+ }
472
+ const next = get(nx, nz, probeNext);
473
+ const dh = next.value - old.value;
474
+ const slope = -dh;
475
+ const cap = (slope > minSlope ? slope : minSlope) * speed * water2 * capacity;
476
+ if (dh > 0 || sediment > cap) {
477
+ const amount = dh > 0 ? dh < sediment ? dh : sediment : (sediment - cap) * deposition;
478
+ spread(old.ix, old.iz, amount);
479
+ sediment -= amount;
480
+ } else {
481
+ const bite = (cap - sediment) * erosion;
482
+ const amount = bite < slope ? bite : slope;
483
+ sediment -= spread(old.ix, old.iz, -amount, next.value);
484
+ }
485
+ const sq = speed * speed - dh * 3;
486
+ speed = Math.sqrt(sq > 0.01 ? sq : 0.01);
487
+ water2 *= oneMinusEvaporation;
488
+ x = nx;
489
+ z = nz;
490
+ if (water2 < 0.02) break;
491
+ }
492
+ if (sediment > 0 && water2 < 0.02) {
493
+ const end = get(clamp(x, 0, n - 1.001), clamp(z, 0, n - 1.001), probeOld);
494
+ spread(end.ix, end.iz, sediment);
495
+ }
496
+ }
497
+ return Float32Array.from(h);
498
+ }
499
+
500
+ // src/core/fluvial.ts
501
+ var DX = Int8Array.of(-1, 0, 1, -1, 1, -1, 0, 1);
502
+ var DZ = Int8Array.of(-1, -1, -1, 0, 0, 1, 1, 1);
503
+ var DIST = Float64Array.from(DX, (dx, k) => Math.hypot(dx, DZ[k]));
504
+ var FILL_SLOPE = Math.tan(0.06 * Math.PI / 180);
505
+ var EPSILON = 1e-3;
506
+ function fillDepressions(h, n, epsilon = EPSILON) {
507
+ const total = n * n;
508
+ const keys = new Float64Array(total);
509
+ const cells = new Int32Array(total);
510
+ const closed2 = new Uint8Array(total);
511
+ let size = 0;
512
+ const push = (key, cell) => {
513
+ let k = size++;
514
+ while (k > 0) {
515
+ const parent = k - 1 >> 1;
516
+ if (keys[parent] <= key) break;
517
+ keys[k] = keys[parent];
518
+ cells[k] = cells[parent];
519
+ k = parent;
520
+ }
521
+ keys[k] = key;
522
+ cells[k] = cell;
523
+ };
524
+ const pop = () => {
525
+ const top = cells[0];
526
+ size -= 1;
527
+ const key = keys[size];
528
+ const cell = cells[size];
529
+ let k = 0;
530
+ for (; ; ) {
531
+ let child = 2 * k + 1;
532
+ if (child >= size) break;
533
+ if (child + 1 < size && keys[child + 1] < keys[child]) child += 1;
534
+ if (keys[child] >= key) break;
535
+ keys[k] = keys[child];
536
+ cells[k] = cells[child];
537
+ k = child;
538
+ }
539
+ keys[k] = key;
540
+ cells[k] = cell;
541
+ return top;
542
+ };
543
+ for (let z = 0; z < n; z += 1) {
544
+ for (let x = 0; x < n; x += 1) {
545
+ if (x > 0 && x < n - 1 && z > 0 && z < n - 1) continue;
546
+ const i = z * n + x;
547
+ closed2[i] = 1;
548
+ push(h[i], i);
549
+ }
550
+ }
551
+ while (size > 0) {
552
+ const c = pop();
553
+ const cx = c % n;
554
+ const cz = (c - cx) / n;
555
+ const level = h[c];
556
+ for (let k = 0; k < 8; k += 1) {
557
+ const x = cx + DX[k];
558
+ const z = cz + DZ[k];
559
+ if (x < 0 || z < 0 || x >= n || z >= n) continue;
560
+ const j = z * n + x;
561
+ if (closed2[j]) continue;
562
+ closed2[j] = 1;
563
+ if (h[j] <= level) h[j] = level + epsilon;
564
+ push(h[j], j);
565
+ }
566
+ }
567
+ }
568
+ function createFlow(n) {
569
+ const total = n * n;
570
+ return {
571
+ receiver: new Int32Array(total),
572
+ order: new Int32Array(total),
573
+ cells: new Float64Array(total)
574
+ };
575
+ }
576
+ function routeFlow(h, n, flow) {
577
+ const { receiver, order, cells } = flow;
578
+ const total = n * n;
579
+ const head = new Int32Array(total).fill(-1);
580
+ const next = new Int32Array(total);
581
+ let roots = 0;
582
+ for (let z = 0; z < n; z += 1) {
583
+ for (let x = 0; x < n; x += 1) {
584
+ const i = z * n + x;
585
+ let best = -1;
586
+ if (x > 0 && x < n - 1 && z > 0 && z < n - 1) {
587
+ const here = h[i];
588
+ let bestSlope = 0;
589
+ for (let k = 0; k < 8; k += 1) {
590
+ const j = i + DZ[k] * n + DX[k];
591
+ const slope = (here - h[j]) / DIST[k];
592
+ if (slope > bestSlope) {
593
+ bestSlope = slope;
594
+ best = j;
595
+ }
596
+ }
597
+ }
598
+ receiver[i] = best;
599
+ if (best < 0) order[roots++] = i;
600
+ else {
601
+ next[i] = head[best];
602
+ head[best] = i;
603
+ }
604
+ }
605
+ }
606
+ for (let k = 0; k < total; k += 1) {
607
+ const i = order[k];
608
+ for (let d = head[i]; d >= 0; d = next[d]) order[roots++] = d;
609
+ }
610
+ cells.fill(1);
611
+ for (let k = total - 1; k >= 0; k -= 1) {
612
+ const i = order[k];
613
+ const r = receiver[i];
614
+ if (r >= 0) cells[r] = cells[r] + cells[i];
615
+ }
616
+ }
617
+ function fluvial(height, n, size, {
618
+ iterations = 40,
619
+ uplift = 1e-3,
620
+ erodibility = 5e-6,
621
+ timeStep = 2e4,
622
+ concavity = 0.45,
623
+ talus = 35,
624
+ relief
625
+ } = {}) {
626
+ const total = n * n;
627
+ const spacing = size / (n - 1);
628
+ const h = Float64Array.from(height);
629
+ const band2 = Math.min(4, n - 1);
630
+ for (let a = 0; a < n; a += 1)
631
+ for (let d = 1; d <= band2; d += 1) {
632
+ h[a] = Math.min(h[a], h[d * n + a]);
633
+ h[(n - 1) * n + a] = Math.min(h[(n - 1) * n + a], h[(n - 1 - d) * n + a]);
634
+ h[a * n] = Math.min(h[a * n], h[a * n + d]);
635
+ h[a * n + n - 1] = Math.min(h[a * n + n - 1], h[a * n + n - 1 - d]);
636
+ }
637
+ fillDepressions(h, n, FILL_SLOPE * spacing);
638
+ let low = Number.POSITIVE_INFINITY;
639
+ let high = Number.NEGATIVE_INFINITY;
640
+ for (let i = 0; i < total; i += 1) {
641
+ low = Math.min(low, h[i]);
642
+ high = Math.max(high, h[i]);
643
+ }
644
+ const range2 = high - low || 1;
645
+ const rise = Float64Array.from(h, (v) => uplift * timeStep * (v - low) / range2);
646
+ const flow = createFlow(n);
647
+ const kdt = erodibility * timeStep;
648
+ const maxRise = Math.tan(talus * Math.PI / 180) * spacing;
649
+ const power = Float64Array.from(
650
+ { length: total + 1 },
651
+ (_, c) => (c * spacing * spacing) ** concavity
652
+ );
653
+ for (let step = 0; step < iterations; step += 1) {
654
+ routeFlow(h, n, flow);
655
+ const { order, receiver, cells } = flow;
656
+ for (let k = 0; k < total; k += 1) {
657
+ const i = order[k];
658
+ const r = receiver[i];
659
+ if (r < 0) continue;
660
+ const delta = Math.abs(r - i);
661
+ const run = delta === 1 || delta === n ? 1 : Math.SQRT2;
662
+ const factor = kdt * power[cells[i]] / (spacing * run);
663
+ const below = h[r];
664
+ const solved = (h[i] + rise[i] + factor * below) / (1 + factor);
665
+ h[i] = Math.max(Math.min(solved, below + maxRise * run), below + EPSILON);
666
+ }
667
+ }
668
+ for (let a = 0; a < n; a += 1) {
669
+ h[a] = h[n + a];
670
+ h[(n - 1) * n + a] = h[(n - 2) * n + a];
671
+ }
672
+ for (let a = 0; a < n; a += 1) {
673
+ h[a * n] = h[a * n + 1];
674
+ h[a * n + n - 1] = h[a * n + n - 2];
675
+ }
676
+ if (relief !== void 0) {
677
+ let lo = Number.POSITIVE_INFINITY;
678
+ let hi = Number.NEGATIVE_INFINITY;
679
+ for (const v of h) {
680
+ lo = Math.min(lo, v);
681
+ hi = Math.max(hi, v);
682
+ }
683
+ const gain = relief / (hi - lo || 1);
684
+ for (let i = 0; i < total; i += 1) h[i] = lo + (h[i] - lo) * gain;
685
+ }
686
+ return Float32Array.from(h);
687
+ }
688
+
689
+ // src/core/masks.ts
690
+ var MATERIAL_IDS = Object.freeze([
691
+ "grass",
692
+ "dirt",
693
+ "rock",
694
+ "snow",
695
+ "sand",
696
+ "mud",
697
+ "road",
698
+ "moss"
699
+ ]);
700
+ 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);
701
+ function compileMask(mask, s) {
702
+ if (!mask || mask.type === "all") return () => 1;
703
+ switch (mask.type) {
704
+ case "none":
705
+ return () => 0;
706
+ case "circle": {
707
+ const centre = mask.at;
708
+ return (i, x, z) => falloff(
709
+ Math.hypot(x - centre[0], z - centre[1]),
710
+ mask.radius,
711
+ mask.falloff ?? 0.6
712
+ );
713
+ }
714
+ case "rectangle": {
715
+ const centre = mask.at;
716
+ const rad = (mask.rotation ?? 0) * Math.PI / 180;
717
+ const c = Math.cos(rad);
718
+ const sn = Math.sin(rad);
719
+ const size = Array.isArray(mask.size) ? mask.size : [mask.size, mask.size];
720
+ return (i, x, z) => {
721
+ const dx = x - centre[0];
722
+ const dz = z - centre[1];
723
+ return falloff(
724
+ Math.max(
725
+ Math.abs(dx * c + dz * sn) / (size[0] / 2),
726
+ Math.abs(-dx * sn + dz * c) / (size[1] / 2)
727
+ ),
728
+ 1,
729
+ mask.falloff ?? 0.2
730
+ );
731
+ };
732
+ }
733
+ case "height":
734
+ return (i) => range(s.height[i], mask.min ?? -1e9, mask.max ?? 1e9, mask.fade);
735
+ case "slope":
736
+ return (i) => range(slopeAtIndex(s, i), mask.min ?? 0, mask.max ?? 90, mask.fade);
737
+ case "noise":
738
+ return (i, x, z) => smoothstep(
739
+ (mask.threshold ?? 0.5) - (mask.fade ?? 0.15),
740
+ (mask.threshold ?? 0.5) + (mask.fade ?? 0.15),
741
+ noise2(x / mask.scale, z / mask.scale, mask.seed ?? s.seed) * 0.5 + 0.5
742
+ );
743
+ case "biome": {
744
+ const field = s.biomes[mask.name];
745
+ return (i) => field?.[i] ?? 0;
746
+ }
747
+ case "material": {
748
+ const channel = MATERIAL_IDS.indexOf(mask.name);
749
+ if (channel < 0) throw Error(`Unknown material: ${String(mask.name)}`);
750
+ return (i) => s.splat[i * 8 + channel];
751
+ }
752
+ case "not": {
753
+ const inner = compileMask(mask.mask, s);
754
+ return (i, x, z) => 1 - inner(i, x, z);
755
+ }
756
+ case "and": {
757
+ const inner = (mask.masks ?? []).map((entry) => compileMask(entry, s));
758
+ return (i, x, z) => inner.reduce((value, sample) => value * sample(i, x, z), 1);
759
+ }
760
+ case "or": {
761
+ const inner = (mask.masks ?? []).map((entry) => compileMask(entry, s));
762
+ return (i, x, z) => 1 - inner.reduce((value, sample) => value * (1 - sample(i, x, z)), 1);
763
+ }
764
+ default:
765
+ throw Error(`Unknown mask: ${String(mask.type)}`);
766
+ }
767
+ }
768
+ function rasterMask(mask, s) {
769
+ if (!mask || mask.type === "all") return null;
770
+ const out = new Float32Array(s.height.length);
771
+ const sample = compileMask(mask, s);
772
+ for (let z = 0; z < s.resolution; z += 1) {
773
+ for (let x = 0; x < s.resolution; x += 1) {
774
+ const i = z * s.resolution + x;
775
+ out[i] = clamp(sample(i, world(s, x), world(s, z)));
776
+ }
777
+ }
778
+ return out;
779
+ }
780
+ function paintWeights(s, i, channel, weight) {
781
+ const w = clamp(weight);
782
+ const base = i * 8;
783
+ for (let c = 0; c < 8; c += 1)
784
+ s.splat[base + c] = s.splat[base + c] * (1 - w) + (c === channel ? w : 0);
785
+ }
786
+
787
+ // src/core/operations.ts
788
+ var OPERATION_TYPES = Object.freeze([
789
+ "noise",
790
+ "sculpt",
791
+ "smooth",
792
+ "flatten",
793
+ "ramp",
794
+ "stamp",
795
+ "erode",
796
+ "terrace",
797
+ "materials",
798
+ "paint",
799
+ "biome",
800
+ "scatter",
801
+ "clear",
802
+ "road",
803
+ "river",
804
+ "water",
805
+ "heightmap",
806
+ "paste"
807
+ ]);
808
+ function createState(config, resolution = config.resolution) {
809
+ const height = new Float32Array(resolution * resolution);
810
+ const splat = new Float32Array(height.length * 8);
811
+ for (let i = 0; i < height.length; i += 1) splat[i * 8] = 1;
812
+ return {
813
+ size: config.size,
814
+ resolution,
815
+ seed: config.seed,
816
+ height,
817
+ splat,
818
+ biomes: {},
819
+ scatterRules: [],
820
+ waterRules: [],
821
+ rivers: [],
822
+ instances: [],
823
+ waters: [],
824
+ diagnostics: []
825
+ };
826
+ }
827
+ function brushCenters(p, seed) {
828
+ const source = p.points ?? (p.at ? [p.at] : null);
829
+ if (!source) return null;
830
+ const radius = p.radius ?? 30;
831
+ const first = source[0];
832
+ if (!first) return null;
833
+ const out = [[first[0], first[1]]];
834
+ const step = Math.max(0.1, radius * 2 * (p.spacing ?? 0.15));
835
+ for (let k = 1; k < source.length; k += 1) {
836
+ const a = source[k - 1];
837
+ const b = source[k];
838
+ const count2 = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step));
839
+ for (let j = 1; j <= count2; j += 1)
840
+ out.push([lerp(a[0], b[0], j / count2), lerp(a[1], b[1], j / count2)]);
841
+ }
842
+ if (p.jitter) {
843
+ const rnd = random(seed);
844
+ for (const centre of out) {
845
+ const angle = rnd() * Math.PI * 2;
846
+ const offset = Math.sqrt(rnd()) * p.jitter * radius;
847
+ centre[0] += Math.cos(angle) * offset;
848
+ centre[1] += Math.sin(angle) * offset;
849
+ }
850
+ }
851
+ return out;
852
+ }
853
+ function brushWeights(s, p, mask, seed) {
854
+ const centers = brushCenters(p, seed);
855
+ if (!centers) return mask ?? new Float32Array(s.height.length).fill(1);
856
+ const n = s.resolution;
857
+ const r = p.radius ?? 30;
858
+ const cell = s.size / (n - 1);
859
+ const weights = new Float32Array(n * n);
860
+ const angle = (p.rotation ?? 0) * Math.PI / 180;
861
+ const cos = Math.cos(angle);
862
+ const sin = Math.sin(angle);
863
+ const bound = r * (p.shape === "square" ? Math.SQRT2 : 1);
864
+ for (const [cx, cz] of centers) {
865
+ const x0 = clamp(Math.floor((cx - bound + s.size / 2) / cell), 0, n - 1);
866
+ const x1 = clamp(Math.ceil((cx + bound + s.size / 2) / cell), 0, n - 1);
867
+ const z0 = clamp(Math.floor((cz - bound + s.size / 2) / cell), 0, n - 1);
868
+ const z1 = clamp(Math.ceil((cz + bound + s.size / 2) / cell), 0, n - 1);
869
+ for (let z = z0; z <= z1; z += 1) {
870
+ for (let x = x0; x <= x1; x += 1) {
871
+ const dx = world(s, x) - cx;
872
+ const dz = world(s, z) - cz;
873
+ const distance = p.shape === "square" ? Math.max(Math.abs(dx * cos + dz * sin), Math.abs(-dx * sin + dz * cos)) : Math.hypot(dx, dz);
874
+ const i = z * n + x;
875
+ weights[i] = Math.max(
876
+ weights[i],
877
+ falloff(distance, r, p.falloff ?? 0.6) * (mask?.[i] ?? 1)
878
+ );
879
+ }
880
+ }
881
+ }
882
+ return weights;
883
+ }
884
+ function followsTerrain(source, followTerrain) {
885
+ return followTerrain ?? source.some((point) => !Number.isFinite(point[1]));
886
+ }
887
+ function gradeToGround(s, points, p) {
888
+ const at = (k) => points[k];
889
+ const run = (k) => {
890
+ const a = at(k - 1);
891
+ const b = at(k);
892
+ return Math.hypot(b[0] - a[0], b[2] - a[2]);
893
+ };
894
+ const bed = points.map(([x, , z]) => sampleHeight(s, x, z));
895
+ let spacing = 0;
896
+ for (let k = 1; k < points.length && spacing === 0; k += 1) spacing = run(k);
897
+ spacing ||= 3;
898
+ const window = Math.max(1, Math.round(Math.max(8, p.width ?? 12) / spacing));
899
+ const profile = bed.slice();
900
+ for (let pass = 0; pass < 2; pass += 1) {
901
+ const next = profile.slice();
902
+ for (let k = 0; k < profile.length; k += 1) {
903
+ let sum = 0;
904
+ let count2 = 0;
905
+ for (let j = Math.max(0, k - window); j <= Math.min(profile.length - 1, k + window); j += 1) {
906
+ sum += profile[j];
907
+ count2 += 1;
908
+ }
909
+ next[k] = sum / count2;
910
+ }
911
+ for (let k = 0; k < profile.length; k += 1) profile[k] = next[k];
912
+ }
913
+ const maxCut = p.maxCut ?? 2.5;
914
+ const maxFill = p.maxFill ?? 1.5;
915
+ const grade2 = p.maxGrade ?? 0.12;
916
+ const limit = (k) => grade2 * Math.max(0.5, run(k));
917
+ for (let round2 = 0; round2 < 16; round2 += 1) {
918
+ let moved = 0;
919
+ for (let k = 1; k < profile.length; k += 1) {
920
+ const y = clamp(
921
+ profile[k],
922
+ profile[k - 1] - limit(k),
923
+ profile[k - 1] + limit(k)
924
+ );
925
+ moved += Math.abs(y - profile[k]);
926
+ profile[k] = y;
927
+ }
928
+ for (let k = profile.length - 2; k >= 0; k -= 1) {
929
+ const y = clamp(
930
+ profile[k],
931
+ profile[k + 1] - limit(k + 1),
932
+ profile[k + 1] + limit(k + 1)
933
+ );
934
+ moved += Math.abs(y - profile[k]);
935
+ profile[k] = y;
936
+ }
937
+ if (moved < 1e-4) break;
938
+ }
939
+ for (let k = 0; k < profile.length; k += 1)
940
+ profile[k] = clamp(
941
+ profile[k],
942
+ bed[k] - maxCut,
943
+ bed[k] + maxFill
944
+ );
945
+ for (let k = 0; k < points.length; k += 1) at(k)[1] = profile[k];
946
+ }
947
+ function applySpline(s, layer2, mask) {
948
+ const p = layer2.params;
949
+ const river = layer2.type === "river";
950
+ const ramp = layer2.type === "ramp";
951
+ const seed = p.seed ?? s.seed;
952
+ const raw = ramp ? [p.from, p.to] : p.points ?? [];
953
+ const follows = followsTerrain(raw, p.followTerrain);
954
+ const source = raw.map(
955
+ ([x, y, z]) => [x, Number.isFinite(y) ? y : 0, z]
956
+ );
957
+ const points = splinePoints(
958
+ source,
959
+ Math.max(1, (p.width ?? 12) * 0.22),
960
+ !ramp && p.smooth !== false
961
+ );
962
+ if (follows) gradeToGround(s, points, p);
963
+ const half = (p.width ?? 12) / 2;
964
+ const shoulder = p.shoulder ?? half;
965
+ const extent = half + shoulder;
966
+ const depth = p.depth ?? 4;
967
+ const alpha = layer2.opacity ?? 1;
968
+ const n = s.resolution;
969
+ const cell = s.size / (n - 1);
970
+ const dist = new Float32Array(n * n).fill(Number.POSITIVE_INFINITY);
971
+ const target = new Float32Array(n * n);
972
+ const bed = new Float32Array(n * n);
973
+ const floor = river ? 1.5 * depth : 0;
974
+ let reach = extent;
975
+ const raster = () => {
976
+ dist.fill(Number.POSITIVE_INFINITY);
977
+ for (let k = 1; k < points.length; k += 1) {
978
+ const a = points[k - 1];
979
+ const b = points[k];
980
+ const dx = b[0] - a[0];
981
+ const dz = b[2] - a[2];
982
+ const den = dx * dx + dz * dz;
983
+ if (den < 1e-12) continue;
984
+ const xmin = clamp(Math.floor((Math.min(a[0], b[0]) - reach + s.size / 2) / cell), 0, n - 1);
985
+ const xmax = clamp(Math.ceil((Math.max(a[0], b[0]) + reach + s.size / 2) / cell), 0, n - 1);
986
+ const zmin = clamp(Math.floor((Math.min(a[2], b[2]) - reach + s.size / 2) / cell), 0, n - 1);
987
+ const zmax = clamp(Math.ceil((Math.max(a[2], b[2]) + reach + s.size / 2) / cell), 0, n - 1);
988
+ for (let z = zmin; z <= zmax; z += 1) {
989
+ for (let x = xmin; x <= xmax; x += 1) {
990
+ const wx = world(s, x);
991
+ const wz = world(s, z);
992
+ const t = clamp(((wx - a[0]) * dx + (wz - a[2]) * dz) / den);
993
+ const d = Math.hypot(wx - a[0] - t * dx, wz - a[2] - t * dz);
994
+ const i = z * n + x;
995
+ if (d < dist[i]) {
996
+ dist[i] = d;
997
+ target[i] = lerp(a[1], b[1], t);
998
+ bed[i] = s.height[i];
999
+ }
1000
+ }
1001
+ }
1002
+ }
1003
+ };
1004
+ raster();
1005
+ let worst = 0;
1006
+ for (let i = 0; i < dist.length; i += 1)
1007
+ if (dist[i] <= extent)
1008
+ worst = Math.max(worst, Math.abs(target[i] - bed[i]));
1009
+ if (floor + 1.5 * worst > 0.05) {
1010
+ reach = extent + floor + 1.5 * worst;
1011
+ raster();
1012
+ }
1013
+ const material = MATERIAL_IDS.indexOf(p.material ?? (river ? "mud" : "road"));
1014
+ for (let i = 0; i < s.height.length; i += 1) {
1015
+ const d = dist[i];
1016
+ if (d > reach) continue;
1017
+ const pre = bed[i];
1018
+ const edge = Math.min(reach, extent + floor + 1.5 * Math.abs(target[i] - pre));
1019
+ const blend = 1 - smoothstep(half, edge, d);
1020
+ const w = blend * blend * (mask?.[i] ?? 1) * alpha;
1021
+ let y = target[i];
1022
+ if (river) {
1023
+ const bowl = 1 - 0.35 * clamp(d / half) ** 2;
1024
+ const bars = 1 + 0.22 * noise2(world(s, i % n) / (half * 8), world(s, Math.floor(i / n)) / (half * 8), seed + 7);
1025
+ y = Math.min(pre, y - depth * bowl * bars * blend);
1026
+ }
1027
+ s.height[i] = lerp(pre, y, w);
1028
+ if (material >= 0) paintWeights(s, i, material, w * (river ? 0.85 : 1));
1029
+ }
1030
+ if (river && p.water !== false)
1031
+ s.rivers.push({
1032
+ id: layer2.id,
1033
+ points,
1034
+ width: (p.width ?? 12) * (p.waterWidth ?? 0.76),
1035
+ color: p.color,
1036
+ opacity: alpha
1037
+ });
1038
+ }
1039
+ function applyOperation(s, layer2) {
1040
+ const { type, params: p } = layer2;
1041
+ const opacity = layer2.opacity ?? 1;
1042
+ if (layer2.enabled === false || opacity <= 0) return;
1043
+ const mask = rasterMask(layer2.mask, s);
1044
+ const weight = (i) => (mask?.[i] ?? 1) * opacity;
1045
+ const n = s.resolution;
1046
+ const seed = p.seed ?? s.seed;
1047
+ switch (type) {
1048
+ case "noise": {
1049
+ const amplitude = p.amplitude ?? 35;
1050
+ const scale = p.scale ?? 100;
1051
+ const warp = p.warp ?? 20;
1052
+ for (let z = 0; z < n; z += 1) {
1053
+ for (let x = 0; x < n; x += 1) {
1054
+ const i = z * n + x;
1055
+ const wx = world(s, x);
1056
+ const wz = world(s, z);
1057
+ const ox = noise2(wx / (scale * 1.7) + 17, wz / (scale * 1.7) - 19, seed + 29) * warp;
1058
+ const oz = noise2(wx / (scale * 1.7) - 27, wz / (scale * 1.7) + 12, seed + 31) * warp;
1059
+ let value = (p.base ?? 0) + fbm((wx + ox) / scale, (wz + oz) / scale, {
1060
+ seed,
1061
+ octaves: p.octaves,
1062
+ persistence: p.persistence,
1063
+ lacunarity: p.lacunarity,
1064
+ mode: p.mode
1065
+ }) * amplitude;
1066
+ if (p.island) {
1067
+ const r = Math.hypot(wx / (s.size * 0.59), wz / (s.size * 0.59));
1068
+ value = value * (1 - smoothstep(0.45, 1, r)) - (p.coastDepth ?? 15) * smoothstep(0.6, 1, r);
1069
+ }
1070
+ s.height[i] = p.blend === "replace" ? lerp(s.height[i], value, weight(i)) : s.height[i] + value * weight(i);
1071
+ }
1072
+ }
1073
+ break;
1074
+ }
1075
+ case "sculpt":
1076
+ case "flatten":
1077
+ case "smooth":
1078
+ case "paint": {
1079
+ const weights = brushWeights(s, p, mask, seed);
1080
+ const w = (i) => (weights?.[i] ?? 1) * opacity;
1081
+ if (type === "sculpt")
1082
+ for (let i = 0; i < s.height.length; i += 1)
1083
+ s.height[i] = s.height[i] + (p.strength ?? 5) * w(i);
1084
+ if (type === "flatten") {
1085
+ const level = "height" in p ? p.height : void 0;
1086
+ if (typeof level !== "number" || !Number.isFinite(level)) {
1087
+ const covered = brushWeights(s, p, mask, seed);
1088
+ let sum = 0;
1089
+ let total = 0;
1090
+ for (let i = 0; i < s.height.length; i += 1) {
1091
+ const share2 = covered[i] * opacity;
1092
+ sum += s.height[i] * share2;
1093
+ total += share2;
1094
+ }
1095
+ const target = total > 0 ? sum / total : 0;
1096
+ let delta = 0;
1097
+ for (let i = 0; i < s.height.length; i += 1)
1098
+ if (covered[i] > 0)
1099
+ delta = Math.max(delta, Math.abs(s.height[i] - target));
1100
+ const graded = brushWeights(
1101
+ s,
1102
+ { ...p, radius: (p.radius ?? 30) + 1.5 * delta },
1103
+ mask,
1104
+ seed
1105
+ );
1106
+ for (let i = 0; i < s.height.length; i += 1)
1107
+ s.height[i] = lerp(
1108
+ s.height[i],
1109
+ target,
1110
+ graded[i] * opacity * clamp(p.strength ?? 1)
1111
+ );
1112
+ } else
1113
+ for (let i = 0; i < s.height.length; i += 1)
1114
+ s.height[i] = lerp(s.height[i], level, w(i) * clamp(p.strength ?? 1));
1115
+ }
1116
+ if (type === "paint") {
1117
+ const channel = MATERIAL_IDS.indexOf(("material" in p ? p.material : void 0) ?? "dirt");
1118
+ for (let i = 0; i < s.height.length; i += 1)
1119
+ paintWeights(s, i, channel, w(i) * clamp(p.strength ?? 1));
1120
+ }
1121
+ if (type === "smooth")
1122
+ for (let k = 0; k < (("iterations" in p ? p.iterations : void 0) ?? 3); k += 1) {
1123
+ const old = s.height.slice();
1124
+ for (let z = 0; z < n; z += 1) {
1125
+ for (let x = 0; x < n; x += 1) {
1126
+ const i = z * n + x;
1127
+ if (w(i) === 0) continue;
1128
+ let total = 0;
1129
+ let count2 = 0;
1130
+ for (let dz = -1; dz <= 1; dz += 1) {
1131
+ for (let dx = -1; dx <= 1; dx += 1) {
1132
+ const xx = x + dx;
1133
+ const zz = z + dz;
1134
+ if (xx >= 0 && xx < n && zz >= 0 && zz < n) {
1135
+ total += old[zz * n + xx];
1136
+ count2 += 1;
1137
+ }
1138
+ }
1139
+ }
1140
+ s.height[i] = lerp(old[i], total / count2, w(i) * clamp(p.strength ?? 0.65));
1141
+ }
1142
+ }
1143
+ }
1144
+ break;
1145
+ }
1146
+ case "stamp":
1147
+ case "paste": {
1148
+ const at = p.at ?? [0, 0];
1149
+ const radius = p.radius ?? (p.size ? typeof p.size === "number" ? p.size / 2 : p.size.map((v) => v / 2) : 60);
1150
+ const extents = Array.isArray(radius) ? [radius[0] / 1, radius[1] / 1] : [radius / 1, radius / 1];
1151
+ const rot = (p.rotation ?? 0) * Math.PI / 180;
1152
+ const c = Math.cos(rot);
1153
+ const sn = Math.sin(rot);
1154
+ const shape = ("shape" in p ? p.shape : void 0) ?? "mountain";
1155
+ for (let z = 0; z < n; z += 1) {
1156
+ for (let x = 0; x < n; x += 1) {
1157
+ const i = z * n + x;
1158
+ const dx = world(s, x) - at[0];
1159
+ const dz = world(s, z) - at[1];
1160
+ const u = (dx * c + dz * sn) / extents[0] * (p.mirrorX ? -1 : 1);
1161
+ const v = (-dx * sn + dz * c) / extents[1] * (p.mirrorZ ? -1 : 1);
1162
+ const d = Math.hypot(u, v);
1163
+ let profile;
1164
+ let w = 1;
1165
+ if (p.data) {
1166
+ if (Math.abs(u) > 1 || Math.abs(v) > 1) continue;
1167
+ const source = p.data;
1168
+ profile = sampleGrid(
1169
+ source.values,
1170
+ source.width,
1171
+ source.height,
1172
+ u * 0.5 + 0.5,
1173
+ v * 0.5 + 0.5
1174
+ );
1175
+ w = falloff(Math.max(Math.abs(u), Math.abs(v)), 1, p.falloff ?? 0.12);
1176
+ } else {
1177
+ if (d >= 1) continue;
1178
+ const rough = 1 + (("roughness" in p ? p.roughness : void 0) ?? 0.13) * fbm(u * 5, v * 5, { seed, octaves: 3 });
1179
+ if (shape === "crater")
1180
+ profile = (Math.exp(-(((d - 0.67) / 0.14) ** 2)) * 0.48 - Math.exp(-((d / 0.49) ** 4)) * 0.6) * (1 - smoothstep(0.85, 1, d));
1181
+ else if (shape === "ridge")
1182
+ profile = Math.max(0, 1 - Math.abs(v)) ** 1.7 * (1 - smoothstep(0.35, 1, Math.abs(u))) * rough;
1183
+ else if (shape === "mesa") profile = (1 - smoothstep(0.5, 1, d)) * rough;
1184
+ else if (shape === "valley") profile = -(1 - smoothstep(0, 1, d)) * rough;
1185
+ else if (shape === "dune") profile = Math.max(0, 1 - d) ** 1.2 * (1 + 0.25 * u) * rough;
1186
+ else profile = Math.max(0, 1 - d) ** 1.65 * rough;
1187
+ profile *= ("amplitude" in p ? p.amplitude : void 0) ?? 45;
1188
+ w = falloff(d, 1, p.falloff ?? 0);
1189
+ }
1190
+ const alpha = weight(i) * w;
1191
+ const blend = p.blend ?? (type === "paste" ? "replace" : "add");
1192
+ const height = profile * (p.scale ?? 1) + (p.offset ?? 0);
1193
+ const value = blend === "replace" ? height : blend === "max" ? Math.max(s.height[i], height) : blend === "min" ? Math.min(s.height[i], height) : s.height[i] + height;
1194
+ s.height[i] = lerp(s.height[i], value, alpha);
1195
+ }
1196
+ }
1197
+ break;
1198
+ }
1199
+ case "erode": {
1200
+ const observations = {
1201
+ flow: new Float32Array(s.height.length),
1202
+ sediment: new Float32Array(s.height.length),
1203
+ deposition: new Float32Array(s.height.length),
1204
+ talus: new Float32Array(s.height.length)
1205
+ };
1206
+ s.erosion ??= structuredClone(observations);
1207
+ const eroded = p.method === "fluvial" ? fluvial(s.height, n, s.size, p) : p.method === "hydraulic" ? hydraulic(
1208
+ s.height,
1209
+ n,
1210
+ s.size,
1211
+ {
1212
+ seed,
1213
+ droplets: p.droplets,
1214
+ maxSteps: p.maxSteps,
1215
+ inertia: p.inertia,
1216
+ capacity: p.capacity,
1217
+ erosion: p.erosion,
1218
+ deposition: p.deposition,
1219
+ evaporation: p.evaporation
1220
+ },
1221
+ observations
1222
+ ) : thermal(s.height, n, s.size, p, observations);
1223
+ let influence = mask;
1224
+ if (p.at || p.points) influence = brushWeights(s, p, mask, seed);
1225
+ for (let i = 0; i < s.height.length; i += 1) {
1226
+ const alpha = (influence?.[i] ?? 1) * opacity * (p.strength ?? 1);
1227
+ s.height[i] = lerp(s.height[i], eroded[i], alpha);
1228
+ for (const key of ["flow", "sediment", "deposition", "talus"])
1229
+ s.erosion[key][i] = s.erosion[key][i] + observations[key][i] * alpha;
1230
+ }
1231
+ break;
1232
+ }
1233
+ case "terrace": {
1234
+ const step = p.step ?? 8;
1235
+ const softness = p.softness ?? 0.18;
1236
+ for (let i = 0; i < s.height.length; i += 1) {
1237
+ const v = (s.height[i] - (p.offset ?? 0)) / step;
1238
+ const base = Math.floor(v);
1239
+ const f = v - base;
1240
+ const target = (base + smoothstep(0.5 - softness * 0.5, 0.5 + softness * 0.5, f)) * step + (p.offset ?? 0);
1241
+ s.height[i] = lerp(s.height[i], target, weight(i) * (p.strength ?? 1));
1242
+ }
1243
+ break;
1244
+ }
1245
+ case "materials": {
1246
+ if (p.reset !== false)
1247
+ for (let i = 0; i < s.height.length; i += 1)
1248
+ paintWeights(s, i, MATERIAL_IDS.indexOf(p.base ?? "grass"), weight(i));
1249
+ for (const rule of p.rules ?? []) {
1250
+ const ruleMask = rasterMask(rule.mask, s);
1251
+ const channel = MATERIAL_IDS.indexOf(rule.material);
1252
+ for (let i = 0; i < s.height.length; i += 1)
1253
+ paintWeights(s, i, channel, (ruleMask?.[i] ?? 1) * weight(i) * (rule.strength ?? 1));
1254
+ }
1255
+ break;
1256
+ }
1257
+ case "biome": {
1258
+ const name = p.name ?? "forest";
1259
+ s.biomes[name] ??= new Float32Array(s.height.length);
1260
+ const values = s.biomes[name];
1261
+ const weights = brushWeights(s, p, mask, seed);
1262
+ for (let i = 0; i < values.length; i += 1)
1263
+ values[i] = lerp(
1264
+ values[i],
1265
+ p.value ?? 1,
1266
+ (weights?.[i] ?? 1) * opacity * (p.strength ?? 1)
1267
+ );
1268
+ break;
1269
+ }
1270
+ case "scatter":
1271
+ s.scatterRules.push({ id: layer2.id, ...p, mask: layer2.mask, opacity, clear: [] });
1272
+ break;
1273
+ case "clear": {
1274
+ if (p.target === "scatter" || p.target === "all") {
1275
+ for (const rule of s.scatterRules)
1276
+ if (!p.asset || rule.asset === p.asset)
1277
+ rule.clear.push({ mask: layer2.mask ?? { type: "all" }, opacity });
1278
+ }
1279
+ if (p.target === "biome" || p.target === "all")
1280
+ for (const [name, values] of Object.entries(s.biomes)) {
1281
+ if (p.name && p.name !== name) continue;
1282
+ for (let i = 0; i < values.length; i += 1)
1283
+ values[i] = values[i] * (1 - weight(i));
1284
+ }
1285
+ if (p.target === "paint" || p.target === "all")
1286
+ for (let i = 0; i < s.height.length; i += 1) paintWeights(s, i, 0, weight(i));
1287
+ break;
1288
+ }
1289
+ case "road":
1290
+ case "river":
1291
+ case "ramp":
1292
+ applySpline(s, layer2, mask);
1293
+ break;
1294
+ case "water":
1295
+ s.waterRules.push({ id: layer2.id, ...p, mask: layer2.mask, opacity });
1296
+ break;
1297
+ case "heightmap": {
1298
+ if (p.at !== void 0 || p.size !== void 0 || p.rotation !== void 0 || p.falloff !== void 0) {
1299
+ applyOperation(s, {
1300
+ ...layer2,
1301
+ type: "paste",
1302
+ params: { ...p, size: p.size ?? s.size, falloff: p.falloff ?? 0 }
1303
+ });
1304
+ break;
1305
+ }
1306
+ const data = p.data;
1307
+ for (let z = 0; z < n; z += 1) {
1308
+ for (let x = 0; x < n; x += 1) {
1309
+ const i = z * n + x;
1310
+ const value = sampleGrid(data.values, data.width, data.height, x / (n - 1), z / (n - 1)) * (p.scale ?? 1) + (p.offset ?? 0);
1311
+ s.height[i] = p.blend === "add" ? s.height[i] + value * weight(i) : lerp(s.height[i], value, weight(i));
1312
+ }
1313
+ }
1314
+ break;
1315
+ }
1316
+ default:
1317
+ throw Error(`Unsupported operation: ${String(layer2.type)}`);
1318
+ }
1319
+ }
1320
+ function finalizeState(s) {
1321
+ const n = s.resolution;
1322
+ const cell = s.size / (n - 1);
1323
+ s.waters = [];
1324
+ s.instances = [];
1325
+ for (const water2 of s.waterRules) {
1326
+ const mask = new Uint8Array(n * n);
1327
+ const queue = new Int32Array(n * n);
1328
+ const allowed = compileMask(water2.mask, s);
1329
+ const level = water2.level ?? 0;
1330
+ const at = water2.at ?? [0, 0];
1331
+ const radius = water2.radius ?? s.size;
1332
+ let front = 0;
1333
+ let back = 0;
1334
+ const eligible = (i) => {
1335
+ const x = world(s, i % n);
1336
+ const z = world(s, Math.floor(i / n));
1337
+ return s.height[i] < level && Math.hypot(x - at[0], z - at[1]) <= radius && allowed(i, x, z) > 0.05;
1338
+ };
1339
+ const push = (i) => {
1340
+ if (i >= 0 && i < n * n && !mask[i] && eligible(i)) {
1341
+ mask[i] = 1;
1342
+ queue[back] = i;
1343
+ back += 1;
1344
+ }
1345
+ };
1346
+ if (water2.kind === "ocean") {
1347
+ for (let k = 0; k < n; k += 1) {
1348
+ push(k);
1349
+ push((n - 1) * n + k);
1350
+ push(k * n);
1351
+ push(k * n + n - 1);
1352
+ }
1353
+ } else {
1354
+ const x = clamp(Math.round((at[0] + s.size / 2) / cell), 0, n - 1);
1355
+ const z = clamp(Math.round((at[1] + s.size / 2) / cell), 0, n - 1);
1356
+ push(z * n + x);
1357
+ }
1358
+ while (front < back) {
1359
+ const i = queue[front];
1360
+ front += 1;
1361
+ const x = i % n;
1362
+ const z = Math.floor(i / n);
1363
+ if (x > 0) push(i - 1);
1364
+ if (x < n - 1) push(i + 1);
1365
+ if (z > 0) push(i - n);
1366
+ if (z < n - 1) push(i + n);
1367
+ }
1368
+ s.waters.push({ ...water2, level, mask });
1369
+ if (!back)
1370
+ s.diagnostics.push(
1371
+ `Water '${water2.id}' has no flooded cells; its seed may be above the water level.`
1372
+ );
1373
+ }
1374
+ const wet = (i, x, z, h) => {
1375
+ if (s.waters.some((water2) => water2.mask[i])) return true;
1376
+ for (const river of s.rivers) {
1377
+ const half = river.width / 2;
1378
+ for (let k = 1; k < river.points.length; k += 1) {
1379
+ const a = river.points[k - 1];
1380
+ const b = river.points[k];
1381
+ if (x < Math.min(a[0], b[0]) - half || x > Math.max(a[0], b[0]) + half || z < Math.min(a[2], b[2]) - half || z > Math.max(a[2], b[2]) + half)
1382
+ continue;
1383
+ const dx = b[0] - a[0];
1384
+ const dz = b[2] - a[2];
1385
+ const t = clamp(((x - a[0]) * dx + (z - a[2]) * dz) / (dx * dx + dz * dz || 1));
1386
+ if (Math.hypot(x - a[0] - t * dx, z - a[2] - t * dz) < half && h <= lerp(a[1], b[1], t) + 0.2)
1387
+ return true;
1388
+ }
1389
+ }
1390
+ return false;
1391
+ };
1392
+ for (const rule of s.scatterRules) {
1393
+ const count2 = Math.round((rule.count ?? 300) * (rule.opacity ?? 1));
1394
+ const seed = (rule.seed ?? s.seed ^ hashString(rule.id)) >>> 0;
1395
+ const rnd = random(seed);
1396
+ const accept = compileMask(rule.mask, s);
1397
+ const clears = rule.clear.map((entry) => ({
1398
+ fn: compileMask(entry.mask, s),
1399
+ opacity: entry.opacity
1400
+ }));
1401
+ const distance = rule.minDistance ?? 4;
1402
+ const gridSize = Math.max(distance, 0.1);
1403
+ const buckets = /* @__PURE__ */ new Map();
1404
+ const accepted = [];
1405
+ const maxAttempts = count2 * 40;
1406
+ const scale = rule.scale ?? [0.8, 1.3];
1407
+ for (let attempt = 0; attempt < maxAttempts && accepted.length < count2; attempt += 1) {
1408
+ const x = (rnd() - 0.5) * s.size;
1409
+ const z = (rnd() - 0.5) * s.size;
1410
+ const acceptance = rnd();
1411
+ const scaleRandom = rnd();
1412
+ const yaw = rnd() * Math.PI * 2;
1413
+ const ix = clamp(Math.round((x / s.size + 0.5) * (n - 1)), 0, n - 1);
1414
+ const iz = clamp(Math.round((z / s.size + 0.5) * (n - 1)), 0, n - 1);
1415
+ const i = iz * n + ix;
1416
+ let w = accept(i, x, z);
1417
+ for (const clear of clears) w *= 1 - clear.fn(i, x, z) * clear.opacity;
1418
+ if (acceptance > w) continue;
1419
+ const h = sampleHeight(s, x, z);
1420
+ if (rule.avoidWater !== false && wet(i, x, z, h)) continue;
1421
+ if (h < (rule.minHeight ?? -1e9) || h > (rule.maxHeight ?? 1e9)) continue;
1422
+ const g = gradientAt(s, x, z);
1423
+ const slope = Math.atan(Math.hypot(g[0], g[1])) * (180 / Math.PI);
1424
+ if (slope < (rule.minSlope ?? 0) || slope > (rule.maxSlope ?? 90)) continue;
1425
+ const gx = Math.floor(x / gridSize);
1426
+ const gz = Math.floor(z / gridSize);
1427
+ let blocked = false;
1428
+ if (distance > 0)
1429
+ for (let dz = -1; dz <= 1 && !blocked; dz += 1) {
1430
+ for (let dx = -1; dx <= 1 && !blocked; dx += 1) {
1431
+ for (const j of buckets.get(`${gx + dx},${gz + dz}`) ?? []) {
1432
+ const other = accepted[j];
1433
+ if (Math.hypot(other.position[0] - x, other.position[2] - z) < distance) {
1434
+ blocked = true;
1435
+ break;
1436
+ }
1437
+ }
1438
+ }
1439
+ }
1440
+ if (blocked) continue;
1441
+ const index = accepted.length;
1442
+ const itemScale = Array.isArray(scale) ? lerp(scale[0], scale[1], scaleRandom) : scale;
1443
+ const normal = [-g[0], 1, -g[1]];
1444
+ const length = Math.hypot(normal[0], normal[1], normal[2]);
1445
+ accepted.push({
1446
+ id: `${rule.id}:candidate:${seed}:${attempt}`,
1447
+ layer: rule.id,
1448
+ asset: rule.asset,
1449
+ position: [x, h + (rule.offsetY ?? 0), z],
1450
+ rotation: yaw,
1451
+ scale: itemScale,
1452
+ normal: [normal[0] / length, normal[1] / length, normal[2] / length],
1453
+ alignToNormal: rule.alignToNormal ?? false
1454
+ });
1455
+ const key = `${gx},${gz}`;
1456
+ const bucket = buckets.get(key) ?? [];
1457
+ bucket.push(index);
1458
+ buckets.set(key, bucket);
1459
+ }
1460
+ for (const instance of accepted) s.instances.push(instance);
1461
+ if (accepted.length < count2)
1462
+ s.diagnostics.push(
1463
+ `Scatter '${rule.id}': placed ${accepted.length}/${count2}; masks or spacing exhausted the attempt budget.`
1464
+ );
1465
+ }
1466
+ return s;
1467
+ }
1468
+
1469
+ // src/core/validation.ts
1470
+ var RESOLUTIONS = Object.freeze([17, 33, 65, 129, 257, 513, 1025]);
1471
+ var brush2 = [
1472
+ "at",
1473
+ "points",
1474
+ "radius",
1475
+ "strength",
1476
+ "falloff",
1477
+ "shape",
1478
+ "rotation",
1479
+ "spacing",
1480
+ "jitter"
1481
+ ];
1482
+ var grade = ["followTerrain", "maxGrade", "maxCut", "maxFill"];
1483
+ var PARAMS = Object.freeze({
1484
+ noise: [
1485
+ "amplitude",
1486
+ "scale",
1487
+ "octaves",
1488
+ "persistence",
1489
+ "lacunarity",
1490
+ "mode",
1491
+ "warp",
1492
+ "base",
1493
+ "blend",
1494
+ "island",
1495
+ "coastDepth"
1496
+ ],
1497
+ sculpt: brush2,
1498
+ smooth: [...brush2, "iterations"],
1499
+ flatten: [...brush2, "height"],
1500
+ paint: [...brush2, "material"],
1501
+ stamp: [
1502
+ "at",
1503
+ "radius",
1504
+ "size",
1505
+ "amplitude",
1506
+ "shape",
1507
+ "rotation",
1508
+ "mirrorX",
1509
+ "mirrorZ",
1510
+ "blend",
1511
+ "roughness",
1512
+ "scale",
1513
+ "offset",
1514
+ "data",
1515
+ "falloff"
1516
+ ],
1517
+ paste: [
1518
+ "at",
1519
+ "size",
1520
+ "radius",
1521
+ "rotation",
1522
+ "mirrorX",
1523
+ "mirrorZ",
1524
+ "blend",
1525
+ "offset",
1526
+ "scale",
1527
+ "data",
1528
+ "falloff"
1529
+ ],
1530
+ erode: [
1531
+ ...brush2,
1532
+ "method",
1533
+ "iterations",
1534
+ "talus",
1535
+ "uplift",
1536
+ "erodibility",
1537
+ "timeStep",
1538
+ "relief",
1539
+ "rate",
1540
+ "droplets",
1541
+ "maxSteps",
1542
+ "inertia",
1543
+ "capacity",
1544
+ "erosion",
1545
+ "deposition",
1546
+ "evaporation"
1547
+ ],
1548
+ terrace: ["step", "softness", "strength", "offset"],
1549
+ materials: ["base", "rules", "reset"],
1550
+ biome: [...brush2, "name", "value"],
1551
+ scatter: [
1552
+ "asset",
1553
+ "count",
1554
+ "minDistance",
1555
+ "scale",
1556
+ "minHeight",
1557
+ "maxHeight",
1558
+ "minSlope",
1559
+ "maxSlope",
1560
+ "avoidWater",
1561
+ "offsetY",
1562
+ "alignToNormal"
1563
+ ],
1564
+ clear: ["target", "asset", "name"],
1565
+ road: ["points", "width", "shoulder", "material", "smooth", ...grade],
1566
+ river: [
1567
+ "points",
1568
+ "width",
1569
+ "shoulder",
1570
+ "depth",
1571
+ "material",
1572
+ "smooth",
1573
+ "water",
1574
+ "waterWidth",
1575
+ "color",
1576
+ "enforceDownhill",
1577
+ ...grade
1578
+ ],
1579
+ ramp: ["from", "to", "width", "shoulder", "material", ...grade],
1580
+ water: ["kind", "at", "radius", "level", "color"],
1581
+ heightmap: ["data", "scale", "offset", "blend", "at", "size", "rotation", "falloff"]
1582
+ });
1583
+ function fail(message) {
1584
+ throw new TypeError(message);
1585
+ }
1586
+ function finiteTree(value, path = "value", depth = 0) {
1587
+ if (depth > 32) fail(`${path}: nesting is too deep`);
1588
+ if (typeof value === "number") {
1589
+ if (!Number.isFinite(value)) fail(`${path} must be finite`);
1590
+ return;
1591
+ }
1592
+ if (value === void 0 || typeof value === "function" || typeof value === "bigint" || typeof value === "symbol")
1593
+ fail(`${path} is not JSON-serializable`);
1594
+ if (value && typeof value === "object") {
1595
+ if (ArrayBuffer.isView(value)) fail(`${path}: use a plain array in recipes`);
1596
+ for (const key of Object.keys(value)) {
1597
+ if (key === "__proto__" || key === "prototype" || key === "constructor")
1598
+ fail(`${path}: unsafe object key`);
1599
+ const entry = value[key];
1600
+ if (typeof entry === "number") {
1601
+ if (depth + 1 > 32) fail(`${path}.${key}: nesting is too deep`);
1602
+ if (!Number.isFinite(entry)) fail(`${path}.${key} must be finite`);
1603
+ continue;
1604
+ }
1605
+ finiteTree(entry, `${path}.${key}`, depth + 1);
1606
+ }
1607
+ }
1608
+ }
1609
+ var num = (v, name, min = -1e9, max = 1e9, integer = false) => {
1610
+ if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max || integer && !Number.isInteger(v))
1611
+ fail(`${name} must be ${integer ? "an integer" : "finite"} between ${min} and ${max}`);
1612
+ };
1613
+ var vec = (v, name, n) => {
1614
+ if (!Array.isArray(v) || v.length !== n) fail(`${name} must contain ${n} numbers`);
1615
+ for (const x of v) num(x, name);
1616
+ };
1617
+ var identifier = (v, name) => {
1618
+ if (typeof v !== "string" || v.length === 0 || v.length > 100 || ["__proto__", "prototype", "constructor"].includes(v))
1619
+ fail(`${name} must be a nonempty safe string, at most 100 characters`);
1620
+ };
1621
+ var enumeration = (v, name, choices) => {
1622
+ if (!choices.includes(v)) fail(`${name}: expected ${choices.join(", ")}`);
1623
+ };
1624
+ function validateConfig(config) {
1625
+ num(config.size, "size", 1, 1e5);
1626
+ if (!RESOLUTIONS.includes(config.resolution))
1627
+ fail(`resolution must be one of ${RESOLUTIONS.join(", ")}`);
1628
+ num(config.seed, "seed", 0, 4294967295, true);
1629
+ }
1630
+ function validateMask(m, depth = 0) {
1631
+ if (!m || typeof m !== "object" || depth > 20) fail("Invalid mask");
1632
+ enumeration(m.type, "mask.type", [
1633
+ "all",
1634
+ "none",
1635
+ "circle",
1636
+ "rectangle",
1637
+ "height",
1638
+ "slope",
1639
+ "noise",
1640
+ "biome",
1641
+ "material",
1642
+ "and",
1643
+ "or",
1644
+ "not"
1645
+ ]);
1646
+ const allowed = {
1647
+ all: [],
1648
+ none: [],
1649
+ circle: ["at", "radius", "falloff"],
1650
+ rectangle: ["at", "size", "rotation", "falloff"],
1651
+ height: ["min", "max", "fade"],
1652
+ slope: ["min", "max", "fade"],
1653
+ noise: ["scale", "threshold", "seed", "fade"],
1654
+ biome: ["name"],
1655
+ material: ["name"],
1656
+ and: ["masks"],
1657
+ or: ["masks"],
1658
+ not: ["mask"]
1659
+ };
1660
+ for (const key of Object.keys(m))
1661
+ if (key !== "type" && !allowed[m.type].includes(key)) fail(`Unknown mask field '${key}'`);
1662
+ if (m.rotation !== void 0) num(m.rotation, "mask.rotation");
1663
+ if (m.seed !== void 0) num(m.seed, "mask.seed", 0, 4294967295, true);
1664
+ if (m.type === "circle") {
1665
+ vec(m.at, "mask.at", 2);
1666
+ num(m.radius, "mask.radius", 1e-3, 1e6);
1667
+ }
1668
+ if (m.type === "rectangle") {
1669
+ vec(m.at, "mask.at", 2);
1670
+ const size = m.size;
1671
+ if (Array.isArray(size)) {
1672
+ vec(size, "mask.size", 2);
1673
+ for (const value of size) num(value, "mask.size", 1e-3, 1e6);
1674
+ } else num(size, "mask.size", 1e-3, 1e6);
1675
+ }
1676
+ if (["height", "slope"].includes(m.type)) {
1677
+ if (m.min !== void 0) num(m.min, "mask.min");
1678
+ if (m.max !== void 0) num(m.max, "mask.max");
1679
+ if ((m.min ?? -1e9) > (m.max ?? 1e9)) fail("mask.min must not exceed mask.max");
1680
+ if (m.fade !== void 0) num(m.fade, "mask.fade", 0, 1e6);
1681
+ }
1682
+ if (m.type === "noise") {
1683
+ num(m.scale, "mask.scale", 1e-3, 1e6);
1684
+ if (m.threshold !== void 0) num(m.threshold, "mask.threshold", 0, 1);
1685
+ if (m.fade !== void 0) num(m.fade, "mask.fade", 1e-6, 1);
1686
+ }
1687
+ if (m.type === "biome") identifier(m.name, "mask.name");
1688
+ if (m.type === "material") enumeration(m.name, "mask.material", MATERIAL_IDS);
1689
+ if (m.type === "not") validateMask(m.mask, depth + 1);
1690
+ if (["and", "or"].includes(m.type)) {
1691
+ if (!Array.isArray(m.masks) || m.masks.length > 32)
1692
+ fail("mask.masks must be an array of at most 32 masks");
1693
+ for (const entry of m.masks) validateMask(entry, depth + 1);
1694
+ }
1695
+ if (m.falloff !== void 0) num(m.falloff, "mask.falloff", 0, 1);
1696
+ }
1697
+ function splinePoint(v, name, follows) {
1698
+ if (!Array.isArray(v) || v.length !== 3) fail(`${name} must contain 3 numbers`);
1699
+ num(v[0], name);
1700
+ num(v[2], name);
1701
+ const y = v[1];
1702
+ if (y === null || y === void 0) {
1703
+ if (follows) return;
1704
+ fail(`${name} must contain 3 numbers`);
1705
+ }
1706
+ if (typeof y !== "number") fail(`${name} must contain 3 numbers`);
1707
+ if (!Number.isFinite(y) && !follows) fail(`${name} elevation must be finite`);
1708
+ }
1709
+ function layerFollowsTerrain(layer2) {
1710
+ if (!layer2 || typeof layer2 !== "object" || !["road", "river", "ramp"].includes(layer2.type))
1711
+ return false;
1712
+ const params = layer2.params ?? {};
1713
+ const source = layer2.type === "ramp" ? [params.from, params.to] : params.points;
1714
+ if (!Array.isArray(source)) return false;
1715
+ return followsTerrain(source, params.followTerrain);
1716
+ }
1717
+ function omittedElevations(layer2, follows) {
1718
+ if (!follows) return layer2;
1719
+ const params = layer2.params ?? {};
1720
+ const zero = (p) => Array.isArray(p) && p.length === 3 ? [p[0], 0, p[2]] : p;
1721
+ const points = params.points;
1722
+ const fixes = {
1723
+ ...Array.isArray(points) ? { points: points.map(zero) } : {},
1724
+ ...Array.isArray(params.from) ? { from: zero(params.from) } : {},
1725
+ ...Array.isArray(params.to) ? { to: zero(params.to) } : {}
1726
+ };
1727
+ return Object.keys(fixes).length ? { ...layer2, params: { ...params, ...fixes } } : layer2;
1728
+ }
1729
+ function validateLayer(layer2) {
1730
+ const follows = layerFollowsTerrain(layer2);
1731
+ finiteTree(omittedElevations(layer2, follows), "layer");
1732
+ if (!layer2 || typeof layer2 !== "object") fail("layer must be an object");
1733
+ for (const k of Object.keys(layer2))
1734
+ if (!["id", "name", "type", "params", "enabled", "opacity", "mask"].includes(k))
1735
+ fail(`Unknown layer field '${k}'`);
1736
+ identifier(layer2.id, "layer.id");
1737
+ enumeration(layer2.type, "operation", OPERATION_TYPES);
1738
+ if (layer2.name !== void 0) identifier(layer2.name, "layer.name");
1739
+ if (layer2.enabled !== void 0 && typeof layer2.enabled !== "boolean")
1740
+ fail("enabled must be boolean");
1741
+ if (layer2.opacity !== void 0) num(layer2.opacity, "opacity", 0, 1);
1742
+ if (layer2.mask) validateMask(layer2.mask);
1743
+ const params = layer2.params ?? {};
1744
+ if (!params || Array.isArray(params) || typeof params !== "object")
1745
+ fail("params must be an object");
1746
+ for (const k of Object.keys(params))
1747
+ if (!PARAMS[layer2.type].includes(k) && k !== "seed")
1748
+ fail(`Unknown ${layer2.type} parameter '${k}'`);
1749
+ for (const key of [
1750
+ "island",
1751
+ "mirrorX",
1752
+ "mirrorZ",
1753
+ "reset",
1754
+ "avoidWater",
1755
+ "alignToNormal",
1756
+ "smooth",
1757
+ "water",
1758
+ "enforceDownhill",
1759
+ "followTerrain"
1760
+ ])
1761
+ if (params[key] !== void 0 && typeof params[key] !== "boolean")
1762
+ fail(`${key} must be boolean`);
1763
+ if (params.seed !== void 0) num(params.seed, "seed", 0, 4294967295, true);
1764
+ if (params.at !== void 0) vec(params.at, "at", 2);
1765
+ if (params.from !== void 0) splinePoint(params.from, "from", follows);
1766
+ if (params.to !== void 0) splinePoint(params.to, "to", follows);
1767
+ const points = params.points;
1768
+ const isSpline = ["road", "river"].includes(layer2.type);
1769
+ if (points) {
1770
+ if (!Array.isArray(points) || !points.length || points.length > 8192)
1771
+ fail("points must have 1..8192 entries");
1772
+ const dimensions = isSpline ? 3 : 2;
1773
+ for (const point of points)
1774
+ if (isSpline) splinePoint(point, "point", follows);
1775
+ else vec(point, "point", dimensions);
1776
+ }
1777
+ if (Array.isArray(points) && !isSpline) {
1778
+ const stroke = points;
1779
+ const spacing = Math.max(
1780
+ 0.1,
1781
+ (params.radius ?? 30) * 2 * (params.spacing ?? 0.15)
1782
+ );
1783
+ let samples = 1;
1784
+ for (let k = 1; k < stroke.length; k += 1) {
1785
+ const next = stroke[k];
1786
+ const previous = stroke[k - 1];
1787
+ samples += Math.max(
1788
+ 1,
1789
+ Math.ceil(
1790
+ Math.hypot(
1791
+ next[0] - previous[0],
1792
+ next[1] - previous[1]
1793
+ ) / spacing
1794
+ )
1795
+ );
1796
+ }
1797
+ if (samples > 65536)
1798
+ fail(
1799
+ "Brush interpolation exceeds 65536 samples; increase radius/spacing or shorten the stroke"
1800
+ );
1801
+ }
1802
+ if (isSpline && (!Array.isArray(points) || points.length < 2))
1803
+ fail(`${layer2.type} requires at least two [x,y,z] points`);
1804
+ if (layer2.type === "ramp" && (!params.from || !params.to)) fail("ramp requires from and to");
1805
+ for (const key of ["radius", "size"]) {
1806
+ const value = params[key];
1807
+ if (value === void 0) continue;
1808
+ if (Array.isArray(value)) {
1809
+ vec(value, key, 2);
1810
+ for (const entry of value) num(entry, key, 1e-3, 1e6);
1811
+ } else num(value, key, 1e-3, 1e6);
1812
+ }
1813
+ if (Array.isArray(params.radius) && !["stamp", "paste"].includes(layer2.type))
1814
+ fail("Brush radius must be one number");
1815
+ for (const key of [
1816
+ "amplitude",
1817
+ "height",
1818
+ "base",
1819
+ "offset",
1820
+ "offsetY",
1821
+ "minHeight",
1822
+ "maxHeight",
1823
+ "level",
1824
+ "rotation"
1825
+ ])
1826
+ if (params[key] !== void 0 && !(key === "base" && layer2.type === "materials")) {
1827
+ if (params[key] !== null || key !== "height") num(params[key], key);
1828
+ }
1829
+ for (const key of ["width", "step"])
1830
+ if (params[key] !== void 0) num(params[key], key, 1e-3, 1e6);
1831
+ for (const key of [
1832
+ "warp",
1833
+ "shoulder",
1834
+ "roughness",
1835
+ "coastDepth",
1836
+ "minDistance",
1837
+ "depth",
1838
+ "capacity",
1839
+ "maxCut",
1840
+ "maxFill"
1841
+ ])
1842
+ if (params[key] !== void 0) num(params[key], key, 0, 1e6);
1843
+ for (const key of [
1844
+ "falloff",
1845
+ "jitter",
1846
+ "softness",
1847
+ "inertia",
1848
+ "erosion",
1849
+ "deposition",
1850
+ "evaporation",
1851
+ "rate",
1852
+ "value",
1853
+ "waterWidth",
1854
+ "maxGrade"
1855
+ ])
1856
+ if (params[key] !== void 0) num(params[key], key, 0, 1);
1857
+ if (params.spacing !== void 0) num(params.spacing, "spacing", 0.01, 2);
1858
+ if (params.strength !== void 0)
1859
+ num(
1860
+ params.strength,
1861
+ "strength",
1862
+ layer2.type === "sculpt" ? -1e4 : 0,
1863
+ layer2.type === "sculpt" ? 1e4 : 1
1864
+ );
1865
+ if (params.scale !== void 0) {
1866
+ const scale = params.scale;
1867
+ if (layer2.type === "scatter") {
1868
+ if (Array.isArray(scale)) {
1869
+ vec(scale, "scale", 2);
1870
+ if (scale[0] > scale[1]) fail("scale range is inverted");
1871
+ for (const entry of scale) num(entry, "scale", 1e-3, 1e4);
1872
+ } else num(scale, "scale", 1e-3, 1e4);
1873
+ } else num(scale, "scale", 1e-3, 1e6);
1874
+ }
1875
+ for (const [key, max] of [
1876
+ ["octaves", 10],
1877
+ ["iterations", 200],
1878
+ ["droplets", 2e5],
1879
+ ["maxSteps", 128],
1880
+ ["count", 2e4]
1881
+ ])
1882
+ if (params[key] !== void 0) num(params[key], key, key === "count" ? 0 : 1, max, true);
1883
+ if (params.persistence !== void 0) num(params.persistence, "persistence", 0.01, 1);
1884
+ if (params.lacunarity !== void 0) num(params.lacunarity, "lacunarity", 1, 4);
1885
+ for (const [key, min, max] of [
1886
+ ["uplift", 1e-9, 1],
1887
+ ["erodibility", 1e-9, 1],
1888
+ ["timeStep", 1, 1e7],
1889
+ ["relief", 1, 1e5]
1890
+ ])
1891
+ if (params[key] !== void 0) num(params[key], key, min, max);
1892
+ for (const key of ["minSlope", "maxSlope", "talus"])
1893
+ if (params[key] !== void 0) num(params[key], key, 0, key === "talus" ? 89.9 : 90);
1894
+ if (params.minHeight !== void 0 && params.maxHeight !== void 0 && params.minHeight > params.maxHeight)
1895
+ fail("height range is inverted");
1896
+ if (params.minSlope !== void 0 && params.maxSlope !== void 0 && params.minSlope > params.maxSlope)
1897
+ fail("slope range is inverted");
1898
+ if (params.material !== void 0) enumeration(params.material, "material", MATERIAL_IDS);
1899
+ if (layer2.type === "materials") {
1900
+ if (params.base !== void 0) enumeration(params.base, "base", MATERIAL_IDS);
1901
+ const rules = params.rules;
1902
+ if (!Array.isArray(rules) || rules.length > 64) fail("materials requires a rules array");
1903
+ for (const rule of rules) {
1904
+ enumeration(rule.material, "rule.material", MATERIAL_IDS);
1905
+ if (rule.mask) validateMask(rule.mask);
1906
+ if (rule.strength !== void 0) num(rule.strength, "rule.strength", 0, 1);
1907
+ }
1908
+ }
1909
+ if (params.method !== void 0)
1910
+ enumeration(params.method, "method", ["thermal", "hydraulic", "fluvial"]);
1911
+ if (params.mode !== void 0) enumeration(params.mode, "mode", ["fbm", "ridged", "billow"]);
1912
+ if (params.shape !== void 0)
1913
+ enumeration(
1914
+ params.shape,
1915
+ "shape",
1916
+ ["stamp"].includes(layer2.type) ? ["mountain", "crater", "ridge", "valley", "mesa", "dune"] : ["circle", "square"]
1917
+ );
1918
+ if (params.blend !== void 0)
1919
+ enumeration(
1920
+ params.blend,
1921
+ "blend",
1922
+ ["noise", "heightmap"].includes(layer2.type) ? ["add", "replace"] : ["add", "replace", "min", "max"]
1923
+ );
1924
+ if (layer2.type === "clear")
1925
+ enumeration(params.target, "clear.target", ["scatter", "paint", "biome", "all"]);
1926
+ if (layer2.type === "water") enumeration(params.kind ?? "lake", "water.kind", ["lake", "ocean"]);
1927
+ if (layer2.type === "river" && params.enforceDownhill && Array.isArray(points)) {
1928
+ const river = points;
1929
+ for (let i = 1; i < river.length; i += 1) {
1930
+ const next = river[i];
1931
+ const previous = river[i - 1];
1932
+ if (next[1] > previous[1])
1933
+ fail("River control-point elevations must be non-increasing");
1934
+ }
1935
+ }
1936
+ if (params.name !== void 0) identifier(params.name, "name");
1937
+ if (params.asset !== void 0) identifier(params.asset, "asset");
1938
+ if (layer2.type === "scatter" && typeof params.asset !== "string")
1939
+ fail(
1940
+ 'scatter requires an asset identifier; a document saved before `asset` was mandatory defaulted it to "pine", so add "asset": "pine" (or the asset it should place) to this layer'
1941
+ );
1942
+ if (["heightmap", "paste"].includes(layer2.type) && !params.data)
1943
+ fail(`${layer2.type} requires heightmap data`);
1944
+ const data = params.data;
1945
+ if (data) {
1946
+ num(data.width, "data.width", 2, 4097, true);
1947
+ num(data.height, "data.height", 2, 4097, true);
1948
+ if (!Array.isArray(data.values) || data.values.length !== data.width * data.height)
1949
+ fail("heightmap dimensions do not match values");
1950
+ for (const value of data.values)
1951
+ if (typeof value !== "number" || !Number.isFinite(value))
1952
+ fail("data.values must contain only finite numbers");
1953
+ }
1954
+ }
1955
+ function validateDocument(doc) {
1956
+ finiteTree(
1957
+ Array.isArray(doc.layers) ? {
1958
+ ...doc,
1959
+ layers: doc.layers.map((layer2) => omittedElevations(layer2, layerFollowsTerrain(layer2)))
1960
+ } : doc,
1961
+ "recipe"
1962
+ );
1963
+ if (doc.version !== 1) fail("Unsupported recipe version; expected 1");
1964
+ validateConfig(doc.config);
1965
+ if (!Array.isArray(doc.layers) || doc.layers.length > 512)
1966
+ fail("layers must be an array of at most 512 layers");
1967
+ const ids = /* @__PURE__ */ new Set();
1968
+ for (const layer2 of doc.layers) {
1969
+ validateLayer(layer2);
1970
+ if (ids.has(layer2.id)) fail(`Duplicate layer ID: ${layer2.id}`);
1971
+ ids.add(layer2.id);
1972
+ }
1973
+ }
1974
+
1975
+ // src/core/terrain.ts
1976
+ var TerrainEvaluator = class {
1977
+ cache = /* @__PURE__ */ new Map();
1978
+ bytes = 0;
1979
+ limit;
1980
+ constructor({ cacheMB = 48 } = {}) {
1981
+ if (!Number.isFinite(cacheMB) || cacheMB < 0)
1982
+ throw new RangeError("cacheMB must be finite and nonnegative");
1983
+ this.limit = cacheMB * 1024 * 1024;
1984
+ }
1985
+ clear() {
1986
+ this.cache.clear();
1987
+ this.bytes = 0;
1988
+ }
1989
+ evaluate(doc, { resolution = doc.config.resolution, signal, onProgress } = {}) {
1990
+ validateDocument(doc);
1991
+ validateConfig({ ...doc.config, resolution });
1992
+ const keys = [];
1993
+ let key = this.limit > 0 ? JSON.stringify({ ...doc.config, resolution }) : "";
1994
+ for (const layer2 of this.limit > 0 ? doc.layers : []) {
1995
+ key += `|${JSON.stringify(layer2)}`;
1996
+ keys.push(key);
1997
+ }
1998
+ let state;
1999
+ let start = 0;
2000
+ for (let i = keys.length - 1; i >= 0; i--) {
2001
+ const k = keys[i];
2002
+ const hit = this.cache.get(k);
2003
+ if (hit) {
2004
+ state = structuredClone(hit.state);
2005
+ start = i + 1;
2006
+ this.cache.delete(k);
2007
+ this.cache.set(k, hit);
2008
+ break;
2009
+ }
2010
+ }
2011
+ state ??= createState(doc.config, resolution);
2012
+ for (let i = start; i < doc.layers.length; i++) {
2013
+ signal?.throwIfAborted();
2014
+ const layer2 = doc.layers[i];
2015
+ applyOperation(state, layer2);
2016
+ onProgress?.({ index: i, total: doc.layers.length, id: layer2.id });
2017
+ const bytes = state.height.byteLength + state.splat.byteLength + Object.values(state.erosion ?? {}).reduce((n, a) => n + a.byteLength, 0) + Object.values(state.biomes).reduce((n, a) => n + a.byteLength, 0);
2018
+ if (bytes <= this.limit) {
2019
+ while (this.bytes + bytes > this.limit && this.cache.size) {
2020
+ const first = this.cache.entries().next().value;
2021
+ if (!first) break;
2022
+ this.bytes -= first[1].bytes;
2023
+ this.cache.delete(first[0]);
2024
+ }
2025
+ this.cache.set(keys[i], { state: structuredClone(state), bytes });
2026
+ this.bytes += bytes;
2027
+ }
2028
+ }
2029
+ signal?.throwIfAborted();
2030
+ if (!state.height.every(Number.isFinite))
2031
+ throw new Error("A terrain operation produced a non-finite height");
2032
+ return finalizeState(state);
2033
+ }
2034
+ };
2035
+ var Terrain = class _Terrain {
2036
+ _doc;
2037
+ _undo = [];
2038
+ _redo = [];
2039
+ _listeners = /* @__PURE__ */ new Set();
2040
+ _historyLimit;
2041
+ _transactionDepth = 0;
2042
+ _evaluator = new TerrainEvaluator();
2043
+ constructor({
2044
+ size = 512,
2045
+ resolution = 257,
2046
+ seed = 73,
2047
+ historyLimit = 60
2048
+ } = {}) {
2049
+ const config = { size, resolution, seed };
2050
+ validateConfig(config);
2051
+ if (!Number.isInteger(historyLimit) || historyLimit < 0)
2052
+ throw new RangeError("historyLimit must be a nonnegative integer");
2053
+ this._doc = { version: 1, config, layers: [] };
2054
+ this._historyLimit = historyLimit;
2055
+ }
2056
+ static fromJSON(json) {
2057
+ const doc = typeof json === "string" ? JSON.parse(json) : structuredClone(json);
2058
+ validateDocument(doc);
2059
+ const terrain = new _Terrain(doc.config);
2060
+ terrain._doc = doc;
2061
+ return terrain;
2062
+ }
2063
+ get layers() {
2064
+ return structuredClone(this._doc.layers);
2065
+ }
2066
+ get config() {
2067
+ return structuredClone(this._doc.config);
2068
+ }
2069
+ get canUndo() {
2070
+ return this._undo.length > 0;
2071
+ }
2072
+ get canRedo() {
2073
+ return this._redo.length > 0;
2074
+ }
2075
+ toJSON() {
2076
+ return structuredClone(this._doc);
2077
+ }
2078
+ subscribe(fn) {
2079
+ this._listeners.add(fn);
2080
+ return () => this._listeners.delete(fn);
2081
+ }
2082
+ _emit() {
2083
+ for (const fn of this._listeners) {
2084
+ try {
2085
+ fn(this);
2086
+ } catch (error) {
2087
+ console.error("Terrain subscriber failed:", error);
2088
+ }
2089
+ }
2090
+ }
2091
+ _change(fn) {
2092
+ const before = structuredClone(this._doc);
2093
+ try {
2094
+ fn();
2095
+ validateDocument(this._doc);
2096
+ } catch (error) {
2097
+ this._doc = before;
2098
+ throw error;
2099
+ }
2100
+ if (!this._transactionDepth) {
2101
+ this._undo.push(before);
2102
+ if (this._undo.length > this._historyLimit) this._undo.shift();
2103
+ this._redo = [];
2104
+ this._emit();
2105
+ }
2106
+ return this;
2107
+ }
2108
+ _id(type) {
2109
+ let i = 1;
2110
+ while (this._doc.layers.some((layer2) => layer2.id === `${type}-${i}`)) i++;
2111
+ return `${type}-${i}`;
2112
+ }
2113
+ add(layer2) {
2114
+ const next = { enabled: true, opacity: 1, ...structuredClone(layer2) };
2115
+ next.id ??= this._id(next.type);
2116
+ validateLayer(next);
2117
+ return this._change(() => {
2118
+ const i = this._doc.layers.findIndex((layer3) => layer3.id === next.id);
2119
+ if (i < 0) this._doc.layers.push(next);
2120
+ else this._doc.layers[i] = next;
2121
+ });
2122
+ }
2123
+ _operation(type, options) {
2124
+ const { id, label, enabled, opacity, mask, ...params } = options;
2125
+ if ("data" in params && params.data && typeof params.data === "object" && "values" in params.data && ArrayBuffer.isView(params.data.values)) {
2126
+ const data = params.data;
2127
+ Object.assign(params, { data: { ...data, values: Array.from(data.values) } });
2128
+ }
2129
+ const layer2 = { id: id ?? this._id(type), type, params };
2130
+ const optional = Object.fromEntries(
2131
+ Object.entries({ name: label, enabled, opacity, mask }).filter(
2132
+ ([, value]) => value !== void 0
2133
+ )
2134
+ );
2135
+ return this.add(Object.assign(layer2, optional));
2136
+ }
2137
+ layer(id) {
2138
+ const layer2 = this._doc.layers.find((layer3) => layer3.id === id);
2139
+ if (!layer2) throw new Error(`Unknown layer '${id}'`);
2140
+ return structuredClone(layer2);
2141
+ }
2142
+ update(id, patch) {
2143
+ const old = this.layer(id);
2144
+ const next = {
2145
+ ...old,
2146
+ ...structuredClone(patch),
2147
+ id,
2148
+ params: { ...old.params, ...structuredClone(patch.params ?? {}) }
2149
+ };
2150
+ const { mask: _mask, ...unmasked } = next;
2151
+ return this.add(patch.mask === null ? unmasked : next);
2152
+ }
2153
+ toggle(id, enabled = this.layer(id).enabled === false) {
2154
+ return this.update(id, { enabled });
2155
+ }
2156
+ move(id, index) {
2157
+ if (!Number.isInteger(index) || index < 0 || index >= this._doc.layers.length)
2158
+ throw new RangeError("Layer index out of bounds");
2159
+ return this._change(() => {
2160
+ const i = this._doc.layers.findIndex((layer3) => layer3.id === id);
2161
+ if (i < 0) throw new Error(`Unknown layer '${id}'`);
2162
+ const layer2 = this._doc.layers.splice(i, 1)[0];
2163
+ this._doc.layers.splice(index, 0, layer2);
2164
+ });
2165
+ }
2166
+ remove(id) {
2167
+ this.layer(id);
2168
+ return this._change(() => {
2169
+ this._doc.layers = this._doc.layers.filter((layer2) => layer2.id !== id);
2170
+ });
2171
+ }
2172
+ setConfig(patch) {
2173
+ const config = { ...this._doc.config, ...patch };
2174
+ validateConfig(config);
2175
+ return this._change(() => {
2176
+ this._doc.config = config;
2177
+ });
2178
+ }
2179
+ loadJSON(json) {
2180
+ const next = _Terrain.fromJSON(json).toJSON();
2181
+ return this._change(() => {
2182
+ this._doc = next;
2183
+ });
2184
+ }
2185
+ transaction(fn) {
2186
+ if (fn.constructor.name === "AsyncFunction")
2187
+ throw new TypeError("Transactions must be synchronous");
2188
+ const before = structuredClone(this._doc);
2189
+ const undo = this._undo.slice();
2190
+ const redo = this._redo.slice();
2191
+ this._transactionDepth++;
2192
+ try {
2193
+ const result = fn(this);
2194
+ if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function")
2195
+ throw new TypeError("Transactions must be synchronous");
2196
+ validateDocument(this._doc);
2197
+ this._transactionDepth--;
2198
+ if (!this._transactionDepth) {
2199
+ this._undo.push(before);
2200
+ if (this._undo.length > this._historyLimit) this._undo.shift();
2201
+ this._redo = [];
2202
+ this._emit();
2203
+ }
2204
+ return this;
2205
+ } catch (error) {
2206
+ this._transactionDepth--;
2207
+ this._doc = before;
2208
+ this._undo = undo;
2209
+ this._redo = redo;
2210
+ throw error;
2211
+ }
2212
+ }
2213
+ applyPatch(commands) {
2214
+ return this.transaction(() => {
2215
+ for (const command of commands) {
2216
+ switch (command.op) {
2217
+ case "upsert":
2218
+ this.add(command.layer);
2219
+ break;
2220
+ case "update":
2221
+ this.update(command.id, command.patch);
2222
+ break;
2223
+ case "remove":
2224
+ this.remove(command.id);
2225
+ break;
2226
+ case "move":
2227
+ this.move(command.id, command.index);
2228
+ break;
2229
+ case "toggle":
2230
+ this.toggle(command.id, command.enabled);
2231
+ break;
2232
+ default:
2233
+ throw new Error("Unknown patch command");
2234
+ }
2235
+ }
2236
+ });
2237
+ }
2238
+ undo() {
2239
+ const prior = this._undo.pop();
2240
+ if (prior) {
2241
+ this._redo.push(structuredClone(this._doc));
2242
+ this._doc = prior;
2243
+ this._emit();
2244
+ }
2245
+ return this;
2246
+ }
2247
+ redo() {
2248
+ const next = this._redo.pop();
2249
+ if (next) {
2250
+ this._undo.push(structuredClone(this._doc));
2251
+ this._doc = next;
2252
+ this._emit();
2253
+ }
2254
+ return this;
2255
+ }
2256
+ evaluate(options) {
2257
+ return this._evaluator.evaluate(this._doc, options);
2258
+ }
2259
+ clearCache() {
2260
+ this._evaluator.clear();
2261
+ }
2262
+ copyRegion({ at = [0, 0], size = 64, resolution = 33 } = {}) {
2263
+ if (!RESOLUTIONS.includes(resolution)) throw new RangeError("Unsupported copy resolution");
2264
+ if (!(size > 0 && Number.isFinite(size))) throw new RangeError("Copy size must be positive");
2265
+ const state = this.evaluate();
2266
+ const values = [];
2267
+ for (let z = 0; z < resolution; z++)
2268
+ for (let x = 0; x < resolution; x++)
2269
+ values.push(
2270
+ sampleHeight(
2271
+ state,
2272
+ at[0] + (x / (resolution - 1) - 0.5) * size,
2273
+ at[1] + (z / (resolution - 1) - 0.5) * size
2274
+ )
2275
+ );
2276
+ return { width: resolution, height: resolution, values };
2277
+ }
2278
+ inspect(options) {
2279
+ const state = this.evaluate(options);
2280
+ let min = Number.POSITIVE_INFINITY;
2281
+ let max = Number.NEGATIVE_INFINITY;
2282
+ for (const height of state.height) {
2283
+ min = Math.min(min, height);
2284
+ max = Math.max(max, height);
2285
+ }
2286
+ return {
2287
+ size: state.size,
2288
+ resolution: state.resolution,
2289
+ layers: this._doc.layers.length,
2290
+ vertices: state.height.length,
2291
+ triangles: 2 * (state.resolution - 1) ** 2,
2292
+ minHeight: min,
2293
+ maxHeight: max,
2294
+ instances: state.instances.length,
2295
+ diagnostics: state.diagnostics
2296
+ };
2297
+ }
2298
+ noise(options = {}) {
2299
+ return this._operation("noise", options);
2300
+ }
2301
+ sculpt(options = {}) {
2302
+ return this._operation("sculpt", options);
2303
+ }
2304
+ smooth(options = {}) {
2305
+ return this._operation("smooth", options);
2306
+ }
2307
+ flatten(options = {}) {
2308
+ return this._operation("flatten", options);
2309
+ }
2310
+ ramp(options) {
2311
+ return this._operation("ramp", options);
2312
+ }
2313
+ stamp(options = {}) {
2314
+ return this._operation("stamp", options);
2315
+ }
2316
+ erode(options = {}) {
2317
+ return this._operation("erode", options);
2318
+ }
2319
+ terrace(options = {}) {
2320
+ return this._operation("terrace", options);
2321
+ }
2322
+ materials(options) {
2323
+ return this._operation("materials", options);
2324
+ }
2325
+ paint(options = {}) {
2326
+ return this._operation("paint", options);
2327
+ }
2328
+ biome(options = {}) {
2329
+ return this._operation("biome", options);
2330
+ }
2331
+ scatter(options) {
2332
+ return this._operation("scatter", options);
2333
+ }
2334
+ clear(options) {
2335
+ return this._operation("clear", options);
2336
+ }
2337
+ road(options) {
2338
+ return this._operation("road", options);
2339
+ }
2340
+ river(options) {
2341
+ return this._operation("river", options);
2342
+ }
2343
+ water(options = {}) {
2344
+ return this._operation("water", options);
2345
+ }
2346
+ heightmap(options) {
2347
+ return this._operation("heightmap", options);
2348
+ }
2349
+ paste(options) {
2350
+ return this._operation("paste", options);
2351
+ }
2352
+ };
2353
+
2354
+ // src/core/presets.ts
2355
+ var LANDFORMS = {
2356
+ alpine: {
2357
+ summary: "Glacier-cut granite peaks: steep headwalls, sharp ar\xEAtes, dendritic gullies.",
2358
+ reliefRatio: 0.25,
2359
+ reference: "Longs Peak, Rocky Mountain National Park, Colorado (USGS 3DEP, DEM crop `alpine`)",
2360
+ target: { slopeP50: 27.3, slopeP90: 42.5, hypsometricIntegral: 0.452, curvatureKurtosis: 89.3 }
2361
+ },
2362
+ temperateMountains: {
2363
+ summary: "Forested mountain backdrop: rounded massifs cut by branching valleys.",
2364
+ reliefRatio: 0.17,
2365
+ reference: "Sprague Lake / Glacier Creek, Rocky Mountain National Park (DEM crop `forest`)",
2366
+ target: { slopeP50: 14.7, slopeP90: 28.1, hypsometricIntegral: 0.398, curvatureKurtosis: 13.7 }
2367
+ },
2368
+ rollingHills: {
2369
+ summary: "Low dendritic hills with convex ridges and gentle slopes.",
2370
+ reliefRatio: 0.03,
2371
+ reference: "Driftless Area, Wisconsin: fluvially dissected flat-lying bedrock, local relief up to about 115 m (WGNHS county reports); no DEM crop in the repo, so no measured target"
2372
+ },
2373
+ desertMesa: {
2374
+ summary: "Caprock mesas and buttes over a stepped, cliff-and-bench canyon landscape.",
2375
+ reliefRatio: 0.055,
2376
+ reference: "Valley of the Gods, Utah (DEM crop `desert`)",
2377
+ target: { slopeP50: 3.7, slopeP90: 16.9, hypsometricIntegral: 0.276, curvatureKurtosis: 203.9 }
2378
+ },
2379
+ coastalCliffs: {
2380
+ summary: "Island massif with steep rocky shore and drowned gullies.",
2381
+ reliefRatio: 0.075,
2382
+ reference: "Sand Beach / Great Head, Acadia National Park, Maine (DEM crop `coastal`)",
2383
+ target: { slopeP50: 1.6, slopeP90: 19.4, hypsometricIntegral: 0.11, curvatureKurtosis: 34.7 }
2384
+ },
2385
+ tundra: {
2386
+ summary: "Broad rounded uplands above the tree line with shallow glacial valleys.",
2387
+ reliefRatio: 0.15,
2388
+ reference: "Trail Ridge, Rocky Mountain National Park (DEM crop `tundra`)",
2389
+ target: { slopeP50: 17.1, slopeP90: 27.9, hypsometricIntegral: 0.473, curvatureKurtosis: 16.7 }
2390
+ },
2391
+ volcanic: {
2392
+ summary: "Stratovolcano cone with a summit crater and radial gullies.",
2393
+ reliefRatio: 0.18,
2394
+ reference: "Mayon Volcano, Philippines: summit 2469 m, slope about 1:2.5 above 500 m easing to 1:7.8 and 1:19.9 (JICA hazard report); no DEM crop in the repo, so no measured target"
2395
+ }
2396
+ };
2397
+ function landform(kind, options = {}) {
2398
+ const info = LANDFORMS[kind];
2399
+ if (!info) throw new TypeError(`Unknown landform kind: ${String(kind)}`);
2400
+ const { size = 5e3, resolution = 513, seed = 73 } = options;
2401
+ const s = size;
2402
+ const relief = options.relief ?? info.reliefRatio * s;
2403
+ const t = new Terrain({ size, resolution, seed });
2404
+ const uplift = (u) => u * (s / 5e3);
2405
+ const valleys = (u, talus, iterations) => ({
2406
+ id: "valleys",
2407
+ method: "fluvial",
2408
+ iterations,
2409
+ uplift: uplift(u),
2410
+ erodibility: 1e-5,
2411
+ talus,
2412
+ // Rescales the eroded surface, so the finished relief follows the request at any seed.
2413
+ relief
2414
+ });
2415
+ switch (kind) {
2416
+ case "alpine":
2417
+ t.noise({
2418
+ id: "massif",
2419
+ amplitude: relief * 3.01,
2420
+ scale: s * 0.535,
2421
+ octaves: 4,
2422
+ mode: "ridged",
2423
+ warp: s * 0.0706
2424
+ }).stamp({
2425
+ id: "peak",
2426
+ shape: "mountain",
2427
+ at: [0, 0],
2428
+ radius: s * 0.42,
2429
+ amplitude: relief * 7.83,
2430
+ roughness: 0.5
2431
+ }).erode(valleys(15e-5, 60.5, 49)).erode({ id: "talus", method: "thermal", iterations: 13, talus: 26.8 }).smooth({ id: "grain", iterations: 3 });
2432
+ break;
2433
+ case "temperateMountains":
2434
+ t.noise({
2435
+ id: "massif",
2436
+ amplitude: relief * 2.18,
2437
+ scale: s * 0.988,
2438
+ octaves: 4,
2439
+ mode: "fbm",
2440
+ warp: s * 0.0716
2441
+ }).stamp({
2442
+ id: "peak",
2443
+ shape: "mountain",
2444
+ at: [0, 0],
2445
+ radius: s * 0.42,
2446
+ amplitude: relief * 4.5,
2447
+ roughness: 0.5
2448
+ }).erode(valleys(413e-7, 30.2, 43)).smooth({ id: "grain", iterations: 3 });
2449
+ break;
2450
+ case "rollingHills":
2451
+ t.noise({
2452
+ id: "hills",
2453
+ amplitude: relief * 1.6,
2454
+ scale: s * 0.25,
2455
+ octaves: 4,
2456
+ mode: "fbm",
2457
+ warp: s * 0.05
2458
+ }).erode(valleys(1e-5, 12, 40)).smooth({ id: "grain", iterations: 2 });
2459
+ break;
2460
+ case "desertMesa":
2461
+ t.noise({
2462
+ id: "plateau",
2463
+ amplitude: relief * 1.75,
2464
+ scale: s * 0.447,
2465
+ octaves: 3,
2466
+ mode: "fbm",
2467
+ warp: s * 0.12
2468
+ }).erode(valleys(837e-6, 33.4, 28)).terrace({ id: "caprock", step: relief / 6, softness: 0.15, strength: 0.688 }).erode({ id: "talus", method: "thermal", iterations: 16, talus: 25 }).smooth({ id: "grain", iterations: 1 });
2469
+ break;
2470
+ case "coastalCliffs":
2471
+ t.noise({
2472
+ id: "island",
2473
+ amplitude: relief * 1.11,
2474
+ scale: s * 0.962,
2475
+ octaves: 6,
2476
+ mode: "ridged",
2477
+ warp: s * 0.0456,
2478
+ island: true,
2479
+ coastDepth: relief * 0.111
2480
+ }).erode(valleys(775e-7, 64.8, 55)).erode({ id: "talus", method: "thermal", iterations: 8, talus: 32.7 }).smooth({ id: "grain", iterations: 3 });
2481
+ break;
2482
+ case "tundra":
2483
+ t.noise({
2484
+ id: "uplands",
2485
+ amplitude: relief * 3.59,
2486
+ scale: s * 0.837,
2487
+ octaves: 4,
2488
+ mode: "fbm",
2489
+ warp: s * 0.097
2490
+ }).stamp({
2491
+ id: "ridge",
2492
+ shape: "mountain",
2493
+ at: [0, 0],
2494
+ radius: s * 0.42,
2495
+ amplitude: relief * 3.95,
2496
+ roughness: 0.5
2497
+ }).erode(valleys(869e-7, 30.1, 30)).erode({ id: "talus", method: "thermal", iterations: 8, talus: 26.2 });
2498
+ break;
2499
+ case "volcanic":
2500
+ t.noise({ id: "rubble", amplitude: relief * 0.04, scale: s * 0.1, octaves: 4, mode: "fbm" }).stamp({
2501
+ id: "cone",
2502
+ shape: "mountain",
2503
+ at: [0, 0],
2504
+ radius: s * 0.45,
2505
+ amplitude: relief,
2506
+ roughness: 0.15
2507
+ }).stamp({
2508
+ id: "crater",
2509
+ shape: "crater",
2510
+ at: [0, 0],
2511
+ radius: s * 0.07,
2512
+ amplitude: relief * 0.08,
2513
+ blend: "add"
2514
+ }).erode(valleys(3e-4, 38, 15)).erode({ id: "talus", method: "thermal", iterations: 8, talus: 36 }).smooth({ id: "grain", iterations: 1 });
2515
+ break;
2516
+ }
2517
+ return t;
2518
+ }
2519
+
2520
+ // src/core/biome.ts
2521
+ var SPEC_FIELDS = [
2522
+ "look",
2523
+ "bake",
2524
+ "landform",
2525
+ "sizeMeters",
2526
+ "seed",
2527
+ "stream",
2528
+ "cover",
2529
+ "foliage",
2530
+ "grass",
2531
+ "layers",
2532
+ "water",
2533
+ "spawn",
2534
+ "species",
2535
+ "aliases"
2536
+ ];
2537
+ var COVER_FIELDS = ["ground", "seed", "attempts", "stoneRadius", "clearings"];
2538
+ var COVER_GROUNDS = ["wood", "crag", "mesa", "mats"];
2539
+ var STREAMS = ["ordered", "seeded"];
2540
+ var DRIFT_FIELDS = ["field", "frequency", "offset", "amplitude", "band"];
2541
+ var DRIFT_FIELDS_NAMES = ["stand", "mats"];
2542
+ var FOLIAGE_FIELDS = [
2543
+ "species",
2544
+ "density",
2545
+ "slope",
2546
+ "height",
2547
+ "spacing",
2548
+ "collision",
2549
+ "stands",
2550
+ "grassThreshold",
2551
+ "standThreshold",
2552
+ "far"
2553
+ ];
2554
+ var FAR_FIELDS = [
2555
+ "cell",
2556
+ "spacing",
2557
+ "spacingAt",
2558
+ "slope",
2559
+ "meadowSlope",
2560
+ "reach",
2561
+ "treelineJitter",
2562
+ "stand",
2563
+ "seed",
2564
+ "impostor"
2565
+ ];
2566
+ var GRASS_FIELDS = [
2567
+ "species",
2568
+ "density",
2569
+ "slope",
2570
+ "height",
2571
+ "spacing",
2572
+ "slopeFalloff",
2573
+ "heightFalloff",
2574
+ "mats",
2575
+ "waterMargin",
2576
+ "beach",
2577
+ "detailSpacing",
2578
+ "drift",
2579
+ "bladeScale",
2580
+ "bladeJitter",
2581
+ "scrubChance",
2582
+ "scrubScale",
2583
+ "scrubJitter",
2584
+ "scrubBush",
2585
+ "shoreGround",
2586
+ "cobbledBed"
2587
+ ];
2588
+ var BAKE_FIELDS = ["file", "key"];
2589
+ var LAYER_FIELDS = ["layer", "from", "to", "shedFrom", "shedTo"];
2590
+ var LAYER_REQUIRED = ["layer", "from", "to"];
2591
+ var WATER_FIELDS = ["kind", "width", "radius", "depth", "level"];
2592
+ var WATER_REQUIRED = ["kind"];
2593
+ var SPAWN_FIELDS = ["at", "cameraOffset", "focus"];
2594
+ var LANDFORM_KINDS = Object.keys(LANDFORMS);
2595
+ var COLLISION_CLASSES = ["none", "trunk", "hull"];
2596
+ var WATER_KINDS = ["river", "lake", "ocean"];
2597
+ function fail2(biome, field, problem) {
2598
+ throw new TypeError(`${biome}: biome field '${field}' ${problem}.`);
2599
+ }
2600
+ function closed(value, biome, field, fields, required = fields) {
2601
+ const at = (name) => field === "" ? name : `${field}.${name}`;
2602
+ if (typeof value !== "object" || value === null || Array.isArray(value))
2603
+ fail2(biome, field || "<file>", "must be an object");
2604
+ const record = value;
2605
+ for (const key of Object.keys(record))
2606
+ if (!fields.includes(key)) fail2(biome, at(key), "is not a field a biome has");
2607
+ for (const key of required) if (!(key in record)) fail2(biome, at(key), "is missing");
2608
+ return record;
2609
+ }
2610
+ function count(value, biome, field, min = 0) {
2611
+ if (typeof value !== "number" || !Number.isFinite(value))
2612
+ fail2(biome, field, "must be a finite number");
2613
+ if (value < min) fail2(biome, field, `must be at least ${min}`);
2614
+ return value;
2615
+ }
2616
+ function positive(value, biome, field) {
2617
+ const number = count(value, biome, field);
2618
+ if (number === 0) fail2(biome, field, "must be greater than 0");
2619
+ return number;
2620
+ }
2621
+ function whole(value, biome, field, min = 0) {
2622
+ if (typeof value !== "number" || !Number.isSafeInteger(value))
2623
+ fail2(biome, field, "must be a whole number");
2624
+ if (value < min) fail2(biome, field, `must be at least ${min}`);
2625
+ return value;
2626
+ }
2627
+ function share(value, biome, field) {
2628
+ const number = count(value, biome, field);
2629
+ if (number > 1) fail2(biome, field, "must be at most 1");
2630
+ return number;
2631
+ }
2632
+ function flag(value, biome, field) {
2633
+ if (typeof value !== "boolean") fail2(biome, field, "must be true or false");
2634
+ return value;
2635
+ }
2636
+ function text(value, biome, field) {
2637
+ if (typeof value !== "string" || value.trim() === "")
2638
+ fail2(biome, field, "must be a non-empty string");
2639
+ return value;
2640
+ }
2641
+ function oneOf(value, biome, field, options) {
2642
+ if (typeof value !== "string" || !options.includes(value))
2643
+ fail2(biome, field, `must be one of ${options.join(", ")}`);
2644
+ return value;
2645
+ }
2646
+ function intervalOf(value, biome, field, size, min = 0, max = Number.POSITIVE_INFINITY) {
2647
+ if (!Array.isArray(value) || value.length !== size)
2648
+ fail2(biome, field, `must be an array of ${size} numbers`);
2649
+ const numbers = value.map((entry, index) => count(entry, biome, `${field}[${index}]`, min));
2650
+ if (numbers[0] > numbers[1])
2651
+ fail2(biome, field, "must ascend");
2652
+ for (const [index, entry] of numbers.entries())
2653
+ if (entry > max) fail2(biome, `${field}[${index}]`, `must be at most ${max}`);
2654
+ return numbers;
2655
+ }
2656
+ function band(value, biome, field) {
2657
+ if (!Array.isArray(value) || value.length !== 2)
2658
+ fail2(biome, field, "must be an array of 2 numbers");
2659
+ const [threshold = 0, span = 0] = value.map(
2660
+ (entry, index) => share(entry, biome, `${field}[${index}]`)
2661
+ );
2662
+ if (span === 0) fail2(biome, `${field}[1]`, "must be greater than 0");
2663
+ return [threshold, span];
2664
+ }
2665
+ function pair(value, biome, field, min = 0, max = Number.POSITIVE_INFINITY) {
2666
+ const [first = 0, second = 0] = intervalOf(value, biome, field, 2, min, max);
2667
+ return [first, second];
2668
+ }
2669
+ function pointOf(value, biome, field, size) {
2670
+ if (!Array.isArray(value) || value.length !== size)
2671
+ fail2(biome, field, `must be an array of ${size} numbers`);
2672
+ return value.map((entry, index) => {
2673
+ if (typeof entry !== "number" || !Number.isFinite(entry))
2674
+ fail2(biome, `${field}[${index}]`, "must be a finite number");
2675
+ return entry ?? 0;
2676
+ });
2677
+ }
2678
+ function point2(value, biome, field) {
2679
+ const [x = 0, z = 0] = pointOf(value, biome, field, 2);
2680
+ return [x, z];
2681
+ }
2682
+ function point3(value, biome, field) {
2683
+ const [x = 0, y = 0, z = 0] = pointOf(value, biome, field, 3);
2684
+ return [x, y, z];
2685
+ }
2686
+ function far(value, biome, field) {
2687
+ if (value === null) return null;
2688
+ const far2 = closed(value, biome, field, FAR_FIELDS);
2689
+ return {
2690
+ cell: positive(far2.cell, biome, `${field}.cell`),
2691
+ spacing: pair(far2.spacing, biome, `${field}.spacing`),
2692
+ spacingAt: pair(far2.spacingAt, biome, `${field}.spacingAt`),
2693
+ slope: pair(far2.slope, biome, `${field}.slope`, 0, 90),
2694
+ meadowSlope: pair(far2.meadowSlope, biome, `${field}.meadowSlope`, 0, 90),
2695
+ reach: positive(far2.reach, biome, `${field}.reach`),
2696
+ treelineJitter: count(far2.treelineJitter, biome, `${field}.treelineJitter`),
2697
+ stand: pair(far2.stand, biome, `${field}.stand`, 0, 1),
2698
+ seed: whole(far2.seed, biome, `${field}.seed`),
2699
+ impostor: count(far2.impostor, biome, `${field}.impostor`)
2700
+ };
2701
+ }
2702
+ function frequencies(value, biome, field) {
2703
+ const [x = 0, z = 0] = pointOf(value, biome, field, 2);
2704
+ if (x <= 0 || z <= 0) fail2(biome, field, "must be two positive frequencies");
2705
+ return [x, z];
2706
+ }
2707
+ function driftRow(value, biome, field) {
2708
+ const row = closed(value, biome, field, DRIFT_FIELDS);
2709
+ return {
2710
+ field: oneOf(row.field, biome, `${field}.field`, DRIFT_FIELDS_NAMES),
2711
+ frequency: frequencies(row.frequency, biome, `${field}.frequency`),
2712
+ offset: share(row.offset, biome, `${field}.offset`),
2713
+ amplitude: share(row.amplitude, biome, `${field}.amplitude`),
2714
+ band: band(row.band, biome, `${field}.band`)
2715
+ };
2716
+ }
2717
+ function clearing(value, biome, field) {
2718
+ if (!Array.isArray(value) || value.length !== 3)
2719
+ fail2(biome, field, "must be an array of 3 numbers");
2720
+ const [x = 0, z = 0, radius = 0] = pointOf(value, biome, field, 3);
2721
+ if (radius <= 0) fail2(biome, `${field}[2]`, "must be greater than 0");
2722
+ return [x, z, radius];
2723
+ }
2724
+ function cover(value, biome) {
2725
+ const row = closed(value, biome, "cover", COVER_FIELDS);
2726
+ const clearings = row.clearings;
2727
+ if (!Array.isArray(clearings)) fail2(biome, "cover.clearings", "must be an array");
2728
+ return {
2729
+ ground: oneOf(row.ground, biome, "cover.ground", COVER_GROUNDS),
2730
+ seed: whole(row.seed, biome, "cover.seed"),
2731
+ attempts: whole(row.attempts, biome, "cover.attempts", 1),
2732
+ stoneRadius: positive(row.stoneRadius, biome, "cover.stoneRadius"),
2733
+ clearings: clearings.map((entry, index) => clearing(entry, biome, `cover.clearings[${index}]`))
2734
+ };
2735
+ }
2736
+ function foliage(value, biome, field) {
2737
+ const row = closed(value, biome, field, FOLIAGE_FIELDS);
2738
+ const height = row.height === null ? null : pair(row.height, biome, `${field}.height`);
2739
+ return {
2740
+ species: text(row.species, biome, `${field}.species`),
2741
+ density: count(row.density, biome, `${field}.density`),
2742
+ slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
2743
+ height,
2744
+ spacing: pair(row.spacing, biome, `${field}.spacing`),
2745
+ collision: oneOf(row.collision, biome, `${field}.collision`, COLLISION_CLASSES),
2746
+ stands: flag(row.stands, biome, `${field}.stands`),
2747
+ grassThreshold: share(row.grassThreshold, biome, `${field}.grassThreshold`),
2748
+ standThreshold: share(row.standThreshold, biome, `${field}.standThreshold`),
2749
+ far: far(row.far, biome, `${field}.far`)
2750
+ };
2751
+ }
2752
+ function grass(value, biome, field) {
2753
+ const row = closed(value, biome, field, GRASS_FIELDS);
2754
+ const density = count(row.density, biome, `${field}.density`);
2755
+ if (density > 1) fail2(biome, `${field}.density`, "must be at most 1");
2756
+ return {
2757
+ species: text(row.species, biome, `${field}.species`),
2758
+ density,
2759
+ slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
2760
+ height: row.height === null ? null : pair(row.height, biome, `${field}.height`),
2761
+ spacing: positive(row.spacing, biome, `${field}.spacing`),
2762
+ slopeFalloff: count(row.slopeFalloff, biome, `${field}.slopeFalloff`),
2763
+ heightFalloff: count(row.heightFalloff, biome, `${field}.heightFalloff`),
2764
+ mats: row.mats === null ? null : band(row.mats, biome, `${field}.mats`),
2765
+ waterMargin: count(row.waterMargin, biome, `${field}.waterMargin`),
2766
+ beach: row.beach === null ? null : pair(row.beach, biome, `${field}.beach`),
2767
+ detailSpacing: positive(row.detailSpacing, biome, `${field}.detailSpacing`),
2768
+ drift: driftRow(row.drift, biome, `${field}.drift`),
2769
+ bladeScale: count(row.bladeScale, biome, `${field}.bladeScale`),
2770
+ bladeJitter: count(row.bladeJitter, biome, `${field}.bladeJitter`),
2771
+ scrubChance: share(row.scrubChance, biome, `${field}.scrubChance`),
2772
+ scrubScale: count(row.scrubScale, biome, `${field}.scrubScale`),
2773
+ scrubJitter: count(row.scrubJitter, biome, `${field}.scrubJitter`),
2774
+ scrubBush: flag(row.scrubBush, biome, `${field}.scrubBush`),
2775
+ shoreGround: flag(row.shoreGround, biome, `${field}.shoreGround`),
2776
+ cobbledBed: flag(row.cobbledBed, biome, `${field}.cobbledBed`)
2777
+ };
2778
+ }
2779
+ function layer(value, biome, field) {
2780
+ const row = closed(value, biome, field, LAYER_FIELDS, LAYER_REQUIRED);
2781
+ const from = count(row.from, biome, `${field}.from`);
2782
+ const to = count(row.to, biome, `${field}.to`);
2783
+ if (from >= to) fail2(biome, field, "must end above where it starts");
2784
+ const shedFrom = row.shedFrom === void 0 ? void 0 : count(row.shedFrom, biome, `${field}.shedFrom`, 0);
2785
+ const shedTo = row.shedTo === void 0 ? void 0 : count(row.shedTo, biome, `${field}.shedTo`, 0);
2786
+ for (const [key, entry] of [
2787
+ ["shedFrom", shedFrom],
2788
+ ["shedTo", shedTo]
2789
+ ])
2790
+ if (entry !== void 0 && entry > 1) fail2(biome, `${field}.${key}`, "must be at most 1");
2791
+ if (shedFrom !== void 0 && shedTo !== void 0 && shedFrom >= shedTo)
2792
+ fail2(biome, field, "must shed from a gentler slope than it sheds to");
2793
+ return {
2794
+ layer: text(row.layer, biome, `${field}.layer`),
2795
+ from,
2796
+ to,
2797
+ shedFrom,
2798
+ shedTo
2799
+ };
2800
+ }
2801
+ function water(value, biome, field) {
2802
+ const row = closed(value, biome, field, WATER_FIELDS, WATER_REQUIRED);
2803
+ const kind = oneOf(row.kind, biome, `${field}.kind`, WATER_KINDS);
2804
+ const width = row.width === void 0 ? void 0 : positive(row.width, biome, `${field}.width`);
2805
+ const radius = row.radius === void 0 ? void 0 : positive(row.radius, biome, `${field}.radius`);
2806
+ const depth = row.depth === void 0 ? void 0 : positive(row.depth, biome, `${field}.depth`);
2807
+ const level = row.level === void 0 ? void 0 : count(row.level, biome, `${field}.level`);
2808
+ if (kind === "river" && width === void 0) fail2(biome, `${field}.width`, "is missing");
2809
+ if (kind === "lake" && radius === void 0) fail2(biome, `${field}.radius`, "is missing");
2810
+ if (kind === "ocean" && level === void 0) fail2(biome, `${field}.level`, "is missing");
2811
+ return { kind, width, radius, depth, level };
2812
+ }
2813
+ function bake(value, biome) {
2814
+ const row = closed(value, biome, "bake", BAKE_FIELDS);
2815
+ return {
2816
+ file: text(row.file, biome, "bake.file"),
2817
+ key: row.key === null ? null : text(row.key, biome, "bake.key")
2818
+ };
2819
+ }
2820
+ function spawn(value, biome) {
2821
+ const row = closed(value, biome, "spawn", SPAWN_FIELDS);
2822
+ return {
2823
+ at: point2(row.at, biome, "spawn.at"),
2824
+ cameraOffset: point3(row.cameraOffset, biome, "spawn.cameraOffset"),
2825
+ focus: point2(row.focus, biome, "spawn.focus")
2826
+ };
2827
+ }
2828
+ function species(value, biome) {
2829
+ if (!Array.isArray(value) || value.length === 0)
2830
+ fail2(biome, "species", "must be a non-empty array of asset ids");
2831
+ const names = value.map((name, index) => text(name, biome, `species[${index}]`));
2832
+ for (const [index, name] of names.entries())
2833
+ if (names.indexOf(name) !== index) fail2(biome, `species[${index}]`, `repeats '${name}'`);
2834
+ return names;
2835
+ }
2836
+ function validateBiome(spec, name) {
2837
+ if (typeof name !== "string" || name.trim() === "")
2838
+ throw new TypeError("validateBiome needs the biome's name");
2839
+ const biome = name;
2840
+ const root = closed(spec, biome, "", SPEC_FIELDS);
2841
+ const aliases = root.aliases;
2842
+ if (!Array.isArray(aliases) || aliases.length === 0)
2843
+ fail2(biome, "aliases", "must be a non-empty array of words");
2844
+ const rows = (value, field, one) => {
2845
+ if (!Array.isArray(value)) fail2(biome, field, "must be an array");
2846
+ return value.map((entry, index) => one(entry, `${field}[${index}]`));
2847
+ };
2848
+ return {
2849
+ look: text(root.look, biome, "look"),
2850
+ bake: bake(root.bake, biome),
2851
+ landform: oneOf(root.landform, biome, "landform", LANDFORM_KINDS),
2852
+ sizeMeters: positive(root.sizeMeters, biome, "sizeMeters"),
2853
+ seed: whole(root.seed, biome, "seed"),
2854
+ stream: oneOf(root.stream, biome, "stream", STREAMS),
2855
+ cover: cover(root.cover, biome),
2856
+ foliage: rows(root.foliage, "foliage", (entry, at) => foliage(entry, biome, at)),
2857
+ grass: rows(root.grass, "grass", (entry, at) => grass(entry, biome, at)),
2858
+ layers: rows(root.layers, "layers", (entry, at) => layer(entry, biome, at)),
2859
+ water: rows(root.water, "water", (entry, at) => water(entry, biome, at)),
2860
+ spawn: spawn(root.spawn, biome),
2861
+ species: species(root.species, biome),
2862
+ aliases: aliases.map(
2863
+ (word, index) => text(word, biome, `aliases[${index}]`).toLowerCase()
2864
+ )
2865
+ };
2866
+ }
2867
+ new ImprovedNoise();
2868
+ new ImprovedNoise();
2869
+
2870
+ // src/core/world-package.ts
2871
+ var HEIGHTMAP_MAX = 65535;
2872
+ var RECORD_VALUES = 8;
2873
+ var COMPONENTS = ["r", "g", "b", "a"];
2874
+ var PLANES = MATERIAL_IDS.length / COMPONENTS.length;
2875
+ var SCALE_TOLERANCE = 1e-3;
2876
+ var SLOTS = MATERIAL_IDS.map((id, channel) => ({
2877
+ channel,
2878
+ component: COMPONENTS[channel % COMPONENTS.length],
2879
+ componentIndex: channel % COMPONENTS.length,
2880
+ id,
2881
+ plane: Math.floor(channel / COMPONENTS.length)
2882
+ }));
2883
+ function poseOf(item) {
2884
+ if (item.transform === void 0)
2885
+ return {
2886
+ position: item.position,
2887
+ quaternion: [0, Math.sin(item.rotation / 2), 0, Math.cos(item.rotation / 2)],
2888
+ scale: [item.scale, item.scale, item.scale]
2889
+ };
2890
+ const { position, quaternion, scale } = item.transform;
2891
+ return { position, quaternion, scale };
2892
+ }
2893
+ function uniformScale(asset, id, scale) {
2894
+ const mean = (scale[0] + scale[1] + scale[2]) / 3;
2895
+ const magnitude = Math.abs(mean);
2896
+ const deviation = Math.max(
2897
+ Math.abs(scale[0] - mean),
2898
+ Math.abs(scale[1] - mean),
2899
+ Math.abs(scale[2] - mean)
2900
+ );
2901
+ if (!(magnitude > 0) || deviation > magnitude * SCALE_TOLERANCE)
2902
+ throw Error(
2903
+ `World package: placement '${id}' of asset '${asset}' is scaled ${JSON.stringify(scale)}; a placement record carries one uniform scale.`
2904
+ );
2905
+ return mean;
2906
+ }
2907
+ function writePlacementRecord(out, offset, item, extent) {
2908
+ if (item.transform === void 0 && !Number.isFinite(item.rotation))
2909
+ throw Error(`World package: placement '${item.id}' has a non-finite rotation.`);
2910
+ const { position, quaternion, scale } = poseOf(item);
2911
+ if (!Number.isFinite(position[0]) || !Number.isFinite(position[1]) || !Number.isFinite(position[2]))
2912
+ throw Error(
2913
+ `World package: placement '${item.id}' has a non-finite position [${position.join(", ")}].`
2914
+ );
2915
+ if (position[0] < extent.minX || position[0] > extent.minX + extent.sizeX || position[2] < extent.minZ || position[2] > extent.minZ + extent.sizeZ)
2916
+ throw Error(
2917
+ `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}].`
2918
+ );
2919
+ const length = Math.hypot(...quaternion);
2920
+ if (!(length > 0)) throw Error(`World package: placement '${item.id}' has a zero quaternion.`);
2921
+ out[offset] = position[0];
2922
+ out[offset + 1] = position[1];
2923
+ out[offset + 2] = position[2];
2924
+ out[offset + 3] = quaternion[0] / length;
2925
+ out[offset + 4] = quaternion[1] / length;
2926
+ out[offset + 5] = quaternion[2] / length;
2927
+ out[offset + 6] = quaternion[3] / length;
2928
+ out[offset + 7] = uniformScale(item.asset, item.id, scale);
2929
+ }
2930
+ function placementCells(state, assets, cellSize, extent) {
2931
+ const cells = /* @__PURE__ */ new Map();
2932
+ const cellOf = (value, min, size) => Math.min(
2933
+ Math.max(1, Math.ceil(size / cellSize)) - 1,
2934
+ Math.max(0, Math.floor((value - min) / cellSize))
2935
+ );
2936
+ for (const item of state.instances) {
2937
+ if (assets[item.asset] === void 0)
2938
+ throw Error(
2939
+ `World package: placement '${item.id}' names asset '${item.asset}', which options.assets does not.`
2940
+ );
2941
+ const x = cellOf(item.position[0], extent.minX, extent.sizeX);
2942
+ const z = cellOf(item.position[2], extent.minZ, extent.sizeZ);
2943
+ const key = `${String(x)},${String(z)}`;
2944
+ let cell = cells.get(key);
2945
+ if (cell === void 0) {
2946
+ cell = { items: /* @__PURE__ */ new Map(), x, z };
2947
+ cells.set(key, cell);
2948
+ }
2949
+ const bucket = cell.items.get(item.asset);
2950
+ if (bucket === void 0) cell.items.set(item.asset, [item]);
2951
+ else bucket.push(item);
2952
+ }
2953
+ const buffer = new ArrayBuffer(state.instances.length * RECORD_VALUES * 4);
2954
+ const records = new Float32Array(buffer);
2955
+ const ordered = [];
2956
+ const ids = [];
2957
+ let written = 0;
2958
+ const byId = (left, right) => left[0] < right[0] ? -1 : 1;
2959
+ for (const cell of [...cells.values()].sort((a, b) => a.x - b.x || a.z - b.z)) {
2960
+ const runs = [];
2961
+ for (const [asset, items] of [...cell.items.entries()].sort(byId)) {
2962
+ runs.push({ asset, count: items.length, offset: written });
2963
+ for (const item of items) {
2964
+ writePlacementRecord(records, written * RECORD_VALUES, item, extent);
2965
+ ids.push(item.id);
2966
+ written += 1;
2967
+ }
2968
+ }
2969
+ ordered.push({ runs, x: cell.x, z: cell.z });
2970
+ }
2971
+ return { bytes: new Uint8Array(buffer), cells: ordered, ids };
2972
+ }
2973
+ function bakeWorldPackage(state, options) {
2974
+ const { size, resolution } = state;
2975
+ const cellSize = options.cellSize ?? 64;
2976
+ if (!Number.isFinite(cellSize) || cellSize <= 0)
2977
+ throw Error(
2978
+ `World package: cellSize must be a positive finite number, got ${String(cellSize)}.`
2979
+ );
2980
+ const { assets, layers, names } = options;
2981
+ const heightmapName = names?.heightmap ?? "heightmap.u16";
2982
+ const placementsName = names?.placements ?? "placements.bin";
2983
+ const placementIdsName = names?.placementIds ?? "placement-ids.json";
2984
+ const splatName = names?.splat ?? "splat.rgba";
2985
+ const extent = { minX: -size / 2, minZ: -size / 2, sizeX: size, sizeZ: size };
2986
+ let heightMin = Number.POSITIVE_INFINITY;
2987
+ let heightMax = Number.NEGATIVE_INFINITY;
2988
+ for (const height of state.height) {
2989
+ if (!Number.isFinite(height)) throw Error("World package: terrain heights must be finite.");
2990
+ heightMin = Math.min(heightMin, height);
2991
+ heightMax = Math.max(heightMax, height);
2992
+ }
2993
+ if (heightMax - heightMin < 1e-6) heightMax = heightMin + 1;
2994
+ const heightmap = new Uint8Array(resolution * resolution * 2);
2995
+ const heights = new DataView(heightmap.buffer);
2996
+ for (let i = 0; i < state.height.length; i += 1)
2997
+ heights.setUint16(
2998
+ i * 2,
2999
+ Math.round(
3000
+ (state.height[i] - heightMin) / (heightMax - heightMin) * HEIGHTMAP_MAX
3001
+ ),
3002
+ true
3003
+ );
3004
+ const placements = placementCells(state, assets, cellSize, extent);
3005
+ return {
3006
+ files: {
3007
+ [heightmapName]: heightmap,
3008
+ [placementsName]: placements.bytes,
3009
+ [placementIdsName]: new TextEncoder().encode(`${JSON.stringify(placements.ids)}
3010
+ `),
3011
+ [splatName]: splatBytes(state, resolution)
3012
+ },
3013
+ manifest: {
3014
+ assets,
3015
+ cellSize,
3016
+ cells: placements.cells,
3017
+ extent,
3018
+ placements: placementsName,
3019
+ placementIds: placementIdsName,
3020
+ terrain: {
3021
+ columns: resolution,
3022
+ heightMax,
3023
+ heightMin,
3024
+ heightmap: heightmapName,
3025
+ layers: { splat: splatName, ...layers },
3026
+ rows: resolution,
3027
+ spacing: size / (resolution - 1)
3028
+ },
3029
+ version: 1
3030
+ },
3031
+ splat: {
3032
+ masks: Object.fromEntries(SLOTS.map(({ component, id, plane }) => [id, [plane, component]])),
3033
+ planes: PLANES,
3034
+ size: resolution
3035
+ }
3036
+ };
3037
+ }
3038
+ function splatBytes(state, resolution) {
3039
+ const planeBytes = resolution * resolution * 4;
3040
+ if (state.splat.length !== resolution * resolution * MATERIAL_IDS.length)
3041
+ throw Error(
3042
+ `World package: splat has ${String(state.splat.length)} weights, expected ${String(resolution * resolution * MATERIAL_IDS.length)}.`
3043
+ );
3044
+ const bytes = new Uint8Array(planeBytes * PLANES);
3045
+ for (let row = 0; row < resolution; row += 1) {
3046
+ const source = (resolution - 1 - row) * resolution;
3047
+ const rowOffset = row * resolution * 4;
3048
+ for (let column = 0; column < resolution; column += 1) {
3049
+ const sample = (source + column) * MATERIAL_IDS.length;
3050
+ const rowCol = rowOffset + column * 4;
3051
+ for (const slot of SLOTS) {
3052
+ const weight = state.splat[sample + slot.channel];
3053
+ bytes[slot.plane * planeBytes + rowCol + slot.componentIndex] = Math.round(
3054
+ (weight <= 0 ? 0 : weight >= 1 ? 1 : weight) * 255
3055
+ );
3056
+ }
3057
+ }
3058
+ }
3059
+ return bytes;
3060
+ }
3061
+
3062
+ // src/core/bake-biome.ts
3063
+ function foliageScatterRules(foliage2, heights) {
3064
+ const [floor] = measureBands([], heights).elevationRange;
3065
+ return foliage2.map((row) => ({
3066
+ id: `foliage:${row.species}`,
3067
+ asset: row.species,
3068
+ count: row.density,
3069
+ minSlope: row.slope[0],
3070
+ maxSlope: row.slope[1],
3071
+ minDistance: row.spacing[0],
3072
+ ...row.height === null ? {} : { minHeight: floor + row.height[0], maxHeight: floor + row.height[1] },
3073
+ avoidWater: true,
3074
+ opacity: 1,
3075
+ clear: []
3076
+ }));
3077
+ }
3078
+ function bakeBiome(options) {
3079
+ const spec = validateBiome(options.spec, options.spec.look);
3080
+ const scatter = null;
3081
+ const state = options.state ;
3082
+ const baked = options.assets === void 0 ? null : bakeWorldPackage(state, {
3083
+ assets: options.assets,
3084
+ ...options.cellSize === void 0 ? {} : { cellSize: options.cellSize },
3085
+ ...options.layers === void 0 ? {} : { layers: options.layers },
3086
+ ...options.names === void 0 ? {} : { names: options.names }
3087
+ });
3088
+ const counts = /* @__PURE__ */ new Map();
3089
+ if (baked !== null) {
3090
+ let placed = 0;
3091
+ for (const cell of baked.manifest.cells)
3092
+ for (const run of cell.runs) {
3093
+ placed += run.count;
3094
+ counts.set(run.asset, (counts.get(run.asset) ?? 0) + run.count);
3095
+ }
3096
+ if (placed !== state.instances.length)
3097
+ throw new Error(
3098
+ `${spec.look}: the package carries ${String(placed)} placements for ${String(state.instances.length)} instances.`
3099
+ );
3100
+ }
3101
+ return {
3102
+ package: baked,
3103
+ bands: measureBands(spec.layers, options.state.height),
3104
+ placements: [...counts.entries()].map(([asset, count2]) => ({ asset, count: count2 })),
3105
+ scatter
3106
+ };
3107
+ }
3108
+
3109
+ // src/core/io.ts
3110
+ new TextEncoder();
3111
+ new TextDecoder();
3112
+ Uint32Array.from({ length: 256 }, (_, initial) => {
3113
+ let n = initial;
3114
+ for (let k = 0; k < 8; k++) n = n & 1 ? 3988292384 ^ n >>> 1 : n >>> 1;
3115
+ return n >>> 0;
3116
+ });
3117
+ function heightRange(values, { min, max } = {}) {
3118
+ for (const v of values) if (!Number.isFinite(v)) throw TypeError("Height data must be finite");
3119
+ if (min === void 0 || max === void 0) {
3120
+ let lo = Number.POSITIVE_INFINITY;
3121
+ let hi = Number.NEGATIVE_INFINITY;
3122
+ for (const v of values) {
3123
+ if (!Number.isFinite(v)) throw TypeError("Height data must be finite");
3124
+ lo = Math.min(lo, v);
3125
+ hi = Math.max(hi, v);
3126
+ }
3127
+ min ??= lo;
3128
+ max ??= hi > lo ? hi : lo + 1;
3129
+ }
3130
+ if (!Number.isFinite(min) || !Number.isFinite(max) || max <= min)
3131
+ throw RangeError("Height range must be finite and max > min");
3132
+ return { min, max };
3133
+ }
3134
+ function decodeRAW16(input, { width, height, min = 0, max = 1, littleEndian = true }) {
3135
+ const bytes = input instanceof Uint8Array ? input : new Uint8Array(input);
3136
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width * height > 4097 ** 2 || bytes.length !== width * height * 2)
3137
+ throw RangeError("RAW byte length must match width \xD7 height \xD7 2");
3138
+ heightRange([min, max], { min, max });
3139
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
3140
+ const values = new Float32Array(width * height);
3141
+ for (let i = 0; i < values.length; i++)
3142
+ values[i] = min + view.getUint16(i * 2, littleEndian) / 65535 * (max - min);
3143
+ return { width, height, values, min, max };
3144
+ }
3145
+
3146
+ // src/core/placements.ts
3147
+ function validatePlacementOverrides(value = {}) {
3148
+ finiteTree(value, "placementOverrides");
3149
+ if (!value || typeof value !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
3150
+ throw new Error("Expected placementOverrides object");
3151
+ return Object.fromEntries(
3152
+ Object.entries(value).map(([key, entry]) => {
3153
+ if (!key.length || key.length > 256)
3154
+ throw new Error("Placement key must contain 1\u2013256 characters");
3155
+ if (!entry || typeof entry !== "object" || ![Object.prototype, null].includes(Object.getPrototypeOf(entry)))
3156
+ throw new Error(`Invalid placement override '${key}'`);
3157
+ const input = entry;
3158
+ if (Object.keys(input).some(
3159
+ (field) => !["position", "quaternion", "scale", "grounding"].includes(field)
3160
+ ))
3161
+ throw new Error(`Unknown placement override fields '${key}'`);
3162
+ function vector(field, length) {
3163
+ const values = input[field];
3164
+ if (!Array.isArray(values) || values.length !== length || !Array.from(values).every(Number.isFinite))
3165
+ throw new Error(`${key}.${field} must contain ${length} finite numbers`);
3166
+ return Array.from(values);
3167
+ }
3168
+ const position = vector("position", 3);
3169
+ const quaternion = vector("quaternion", 4);
3170
+ const scale = vector("scale", 3);
3171
+ if (scale.some((item) => item <= 0)) throw new Error(`${key}.scale must be positive`);
3172
+ if (Math.abs(Math.hypot(...quaternion) - 1) > 1e-6)
3173
+ throw new Error(`${key}.quaternion must be a unit quaternion`);
3174
+ const grounding = input.grounding === void 0 ? true : input.grounding;
3175
+ if (typeof grounding !== "boolean") throw new Error(`${key}.grounding must be boolean`);
3176
+ return [key, { position, quaternion, scale, grounding }];
3177
+ })
3178
+ );
3179
+ }
3180
+ function applyPlacementOverrides(state, value) {
3181
+ const overrides = validatePlacementOverrides(value);
3182
+ const keys = new Set(state.instances.map((item) => item.id));
3183
+ return {
3184
+ ...state,
3185
+ instances: state.instances.map((item) => {
3186
+ const { transform: _, ...base } = item;
3187
+ return Object.hasOwn(overrides, item.id) ? { ...base, transform: overrides[item.id] } : base;
3188
+ }),
3189
+ diagnostics: [
3190
+ ...state.diagnostics.filter(
3191
+ (message) => !message.startsWith("Unmatched placement override '")
3192
+ ),
3193
+ ...Object.keys(overrides).filter((key) => !keys.has(key)).map((key) => `Unmatched placement override '${key}'`)
3194
+ ]
3195
+ };
3196
+ }
3197
+ function fail3(reason) {
3198
+ throw new Error(`TN_TERRAIN_ASSETS_${reason}`);
3199
+ }
3200
+ async function isDirectory(path) {
3201
+ return (await lstat(path).catch((error) => {
3202
+ if (error.code === "ENOENT") return void 0;
3203
+ throw error;
3204
+ }))?.isDirectory() === true;
3205
+ }
3206
+ async function extract(archive, target) {
3207
+ const tar = gunzipSync(archive, { maxOutputLength: 128 * 1024 * 1024 });
3208
+ const seen = /* @__PURE__ */ new Set();
3209
+ for (let at = 0; at + 512 <= tar.length; ) {
3210
+ const header = tar.subarray(at, at + 512);
3211
+ if (header.every((byte) => byte === 0)) {
3212
+ if (tar.length < at + 1024 || !tar.subarray(at).every((byte) => byte === 0) || seen.size === 0)
3213
+ fail3("END");
3214
+ return;
3215
+ }
3216
+ const text2 = (from, to) => header.subarray(from, to).toString("utf8").split("\0")[0] ?? "";
3217
+ const octal = (from, to) => {
3218
+ const value = text2(from, to).trim();
3219
+ if (!/^[0-7]+$/u.test(value)) fail3("HEADER");
3220
+ return Number.parseInt(value, 8);
3221
+ };
3222
+ const checksum = header.reduce(
3223
+ (sum, byte, index) => sum + (index >= 148 && index < 156 ? 32 : byte),
3224
+ 0
3225
+ );
3226
+ if (text2(257, 263) !== "ustar" || text2(263, 265) !== "00" || octal(148, 156) !== checksum)
3227
+ fail3("HEADER");
3228
+ const prefix = text2(345, 500);
3229
+ const name = `${prefix ? `${prefix}/` : ""}${text2(0, 100)}`.replace(/\/$/u, "");
3230
+ if (!name.startsWith("starter-assets/") && name !== "starter-assets") fail3("PATH");
3231
+ if (name.includes("\\") || name.split("/").some((part) => part === ".." || part === "." || part === "" || part.includes(":")))
3232
+ fail3("PATH");
3233
+ if (seen.has(name)) fail3("DUPLICATE");
3234
+ seen.add(name);
3235
+ const size = octal(124, 136);
3236
+ const type = header[156];
3237
+ if (type !== 48 && type !== 53) fail3("TYPE");
3238
+ if (!Number.isSafeInteger(size) || size < 0 || type === 53 && size !== 0 || name === "starter-assets" && type !== 53)
3239
+ fail3("SIZE");
3240
+ const next = at + 512 + Math.ceil(size / 512) * 512;
3241
+ if (next > tar.length) fail3("TRUNCATED");
3242
+ const path = join(target, ...name.split("/").slice(1));
3243
+ if (type === 53) await mkdir(path, { recursive: true, mode: 493 });
3244
+ else {
3245
+ await mkdir(dirname(path), { recursive: true, mode: 493 });
3246
+ await writeFile(path, tar.subarray(at + 512, at + 512 + size), { flag: "wx", mode: 420 });
3247
+ }
3248
+ at = next;
3249
+ }
3250
+ fail3("END");
3251
+ }
3252
+ async function starterAssetsDir() {
3253
+ const root = dirname(fileURLToPath(import.meta.resolve("@threenative/terrain/package.json")));
3254
+ const local = join(root, "starter-assets");
3255
+ if (await isDirectory(local)) return local;
3256
+ const manifest = JSON.parse(await readFile(join(root, "starter-assets.json"), "utf8"));
3257
+ if (!/^[a-f0-9]{64}$/u.test(manifest.sha256) || !Number.isSafeInteger(manifest.bytes) || manifest.bytes <= 0 || manifest.bytes > 128 * 1024 * 1024)
3258
+ fail3("MANIFEST");
3259
+ const cache = join(
3260
+ process.env.XDG_CACHE_HOME || join(homedir(), ".cache"),
3261
+ "threenative",
3262
+ "terrain-starter-assets",
3263
+ manifest.sha256
3264
+ );
3265
+ if (await isDirectory(cache)) return cache;
3266
+ const url = new URL(process.env.THREENATIVE_TERRAIN_ASSETS_URL || manifest.url);
3267
+ let archive;
3268
+ if (url.protocol === "file:") archive = await readFile(url);
3269
+ else {
3270
+ if (url.protocol !== "https:" && url.protocol !== "http:") fail3("URL");
3271
+ const response = await fetch(url);
3272
+ if (!response.ok) fail3(`HTTP: ${response.status} ${url.href}`);
3273
+ const declared = Number(response.headers.get("content-length") ?? manifest.bytes);
3274
+ if (declared !== manifest.bytes || !response.body) fail3("SIZE");
3275
+ const chunks = [];
3276
+ let total = 0;
3277
+ for await (const chunk of response.body) {
3278
+ total += chunk.length;
3279
+ if (total > manifest.bytes) fail3("SIZE");
3280
+ chunks.push(chunk);
3281
+ }
3282
+ archive = Buffer.concat(chunks);
3283
+ }
3284
+ if (archive.length !== manifest.bytes) fail3("SIZE");
3285
+ if (createHash("sha256").update(archive).digest("hex") !== manifest.sha256) fail3("SHA256");
3286
+ await mkdir(dirname(cache), { recursive: true });
3287
+ const tmp = await mkdtemp(`${cache}.tmp-`);
3288
+ try {
3289
+ await extract(archive, tmp);
3290
+ try {
3291
+ await rename(tmp, cache);
3292
+ } catch (error) {
3293
+ if (!await isDirectory(cache) || !["EEXIST", "ENOTEMPTY"].includes(error.code ?? ""))
3294
+ throw error;
3295
+ }
3296
+ } finally {
3297
+ await rm(tmp, { recursive: true, force: true });
3298
+ }
3299
+ return cache;
3300
+ }
3301
+
3302
+ // src/mcp/glb-stats.ts
3303
+ var GLB_MAGIC = 1179937895;
3304
+ var JSON_CHUNK = 1313821514;
3305
+ var INSTANCING = "EXT_mesh_gpu_instancing";
3306
+ var TRIANGLE_MODES = /* @__PURE__ */ new Set([4, 5, 6]);
3307
+ function jsonChunk(bytes) {
3308
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
3309
+ if (bytes.byteLength < 20 || view.getUint32(0, true) !== GLB_MAGIC) {
3310
+ throw new Error("glb-stats: not a GLB, the glTF binary header is missing.");
3311
+ }
3312
+ if (view.getUint32(4, true) !== 2 || view.getUint32(8, true) !== bytes.byteLength) {
3313
+ throw new Error(
3314
+ "glb-stats: the GLB version is not 2 or its header length is not the file size."
3315
+ );
3316
+ }
3317
+ const length = view.getUint32(12, true);
3318
+ if (view.getUint32(16, true) !== JSON_CHUNK || 20 + length > bytes.byteLength) {
3319
+ throw new Error("glb-stats: the first GLB chunk is not a complete JSON chunk.");
3320
+ }
3321
+ return JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + length)));
3322
+ }
3323
+ function measureGlb(bytes) {
3324
+ const gltf = jsonChunk(bytes);
3325
+ const nodes = gltf.nodes ?? [];
3326
+ const accessorCount = (index) => {
3327
+ const count2 = index === void 0 ? void 0 : gltf.accessors?.[index]?.count;
3328
+ if (count2 === void 0) throw new Error(`glb-stats: accessor ${index} is missing.`);
3329
+ return count2;
3330
+ };
3331
+ const stats = { draws: 0, instances: 0, triangles: 0 };
3332
+ const seen = /* @__PURE__ */ new Set();
3333
+ const visit = (index) => {
3334
+ const node = nodes[index];
3335
+ if (node === void 0) throw new Error(`glb-stats: node ${index} is missing.`);
3336
+ if (seen.has(index)) return;
3337
+ seen.add(index);
3338
+ if (node.mesh !== void 0) {
3339
+ const mesh = gltf.meshes?.[node.mesh];
3340
+ if (mesh === void 0) throw new Error(`glb-stats: mesh ${node.mesh} is missing.`);
3341
+ const attributes = node.extensions?.[INSTANCING]?.attributes;
3342
+ const copies = attributes === void 0 ? 1 : accessorCount(Object.values(attributes)[0]);
3343
+ if (attributes !== void 0) stats.instances += copies;
3344
+ for (const primitive of mesh.primitives) {
3345
+ stats.draws += 1;
3346
+ if (!TRIANGLE_MODES.has(primitive.mode ?? 4)) continue;
3347
+ const vertices = accessorCount(primitive.indices ?? primitive.attributes.POSITION);
3348
+ stats.triangles += (primitive.mode === 5 || primitive.mode === 6 ? Math.max(vertices - 2, 0) : Math.floor(vertices / 3)) * copies;
3349
+ }
3350
+ }
3351
+ for (const child of node.children ?? []) visit(child);
3352
+ };
3353
+ const scene = gltf.scenes?.[gltf.scene ?? 0];
3354
+ for (const root of scene?.nodes ?? (gltf.scenes === void 0 ? nodes.keys() : [])) visit(root);
3355
+ return stats;
3356
+ }
3357
+
3358
+ // src/core/kits.ts
3359
+ var TERRAIN_KITS = ["forest", "coastal", "alpine", "desert", "tundra"];
3360
+ function isRecord(value) {
3361
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3362
+ }
3363
+ async function resolveAssetSource(projectRoot) {
3364
+ const configFile = join(projectRoot, "threenative.config.ts");
3365
+ const exists = await lstat(configFile).then(
3366
+ () => true,
3367
+ (error) => {
3368
+ if (error.code === "ENOENT") return false;
3369
+ throw error;
3370
+ }
3371
+ );
3372
+ let source = "assets";
3373
+ if (exists) {
3374
+ const { loadConfigFromFile } = await import('vite');
3375
+ const loaded = await loadConfigFromFile(
3376
+ { command: "build", mode: "production" },
3377
+ configFile,
3378
+ projectRoot
3379
+ );
3380
+ const assets = loaded?.config?.assets;
3381
+ if (assets !== void 0) {
3382
+ if (!isRecord(assets)) throw new TypeError("terrain_generate: assets must be an object.");
3383
+ source = assets.source === void 0 ? "assets" : assets.source;
3384
+ }
3385
+ }
3386
+ if (typeof source !== "string" || source.trim() === "") {
3387
+ throw new TypeError("terrain_generate: assets.source must be a non-empty path.");
3388
+ }
3389
+ const configuredRoot = resolve(projectRoot, source);
3390
+ const sourceRoot = await realpath(configuredRoot).catch((error) => {
3391
+ if (error.code === "ENOENT") return configuredRoot;
3392
+ throw error;
3393
+ });
3394
+ const inside = relative(projectRoot, sourceRoot);
3395
+ if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
3396
+ throw new TypeError("terrain_generate: assets.source must be inside the project.");
3397
+ }
3398
+ return sourceRoot;
3399
+ }
3400
+
3401
+ // src/mcp/cook.ts
3402
+ var MISSING_ASSETS = "terrain_generate needs @threenative/assets in the game project. Run: npm i -D @threenative/assets";
3403
+ function isTriple(value) {
3404
+ return Array.isArray(value) && value.length === 3 && value.every((entry) => typeof entry === "number" && Number.isFinite(entry));
3405
+ }
3406
+ function parseBounds(value, species2) {
3407
+ const box = typeof value === "object" && value !== null ? value : {};
3408
+ const { min, max } = box;
3409
+ if (!isTriple(min) || !isTriple(max) || min.some((entry, axis) => entry > max[axis])) {
3410
+ throw new Error(
3411
+ `cook: species '${species2}' bounds must be { min: [x,y,z], max: [x,y,z] } with min <= max.`
3412
+ );
3413
+ }
3414
+ return { min, max };
3415
+ }
3416
+ function installedEntry(projectRoot, name) {
3417
+ let directory = resolve(projectRoot);
3418
+ while (true) {
3419
+ const manifestFile = join(directory, "node_modules", name, "package.json");
3420
+ if (existsSync(manifestFile)) {
3421
+ const manifest = JSON.parse(readFileSync(manifestFile, "utf8"));
3422
+ const root = manifest.exports?.["."];
3423
+ const relative3 = (typeof root === "string" ? root : root?.import) ?? manifest.main;
3424
+ return relative3 === void 0 ? void 0 : resolve(dirname(manifestFile), relative3);
3425
+ }
3426
+ const parent = dirname(directory);
3427
+ if (parent === directory) return void 0;
3428
+ directory = parent;
3429
+ }
3430
+ }
3431
+ async function loadCooker(projectRoot) {
3432
+ const entry = installedEntry(projectRoot, "@threenative/assets");
3433
+ if (entry === void 0 || !existsSync(entry)) throw new Error(MISSING_ASSETS);
3434
+ const loaded = await import(pathToFileURL(entry).href);
3435
+ if (typeof loaded.cookTerrainWorld !== "function") {
3436
+ throw new Error(`${MISSING_ASSETS} (the installed version has no cookTerrainWorld).`);
3437
+ }
3438
+ return loaded;
3439
+ }
3440
+ var round = (value) => Math.round(value * 1e3) / 1e3;
3441
+ async function cookKit(request2) {
3442
+ if (!TERRAIN_KITS.includes(request2.kit)) {
3443
+ throw new Error(`cook: unknown kit '${request2.kit}'.`);
3444
+ }
3445
+ const assetSource = request2.assetSource ?? await resolveAssetSource(request2.projectRoot);
3446
+ const logicalOut = relative(assetSource, request2.out);
3447
+ if (logicalOut === "" || logicalOut === ".." || logicalOut.startsWith(`..${sep}`)) {
3448
+ throw new Error(
3449
+ "terrain_generate: out must be under assets.source so the build can list it in the manifest."
3450
+ );
3451
+ }
3452
+ const cooker = await loadCooker(request2.projectRoot);
3453
+ const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
3454
+ const kitDir = join(packageRoot, "starter", request2.kit);
3455
+ const assetsDir = await starterAssetsDir();
3456
+ await mkdir(dirname(request2.out), { recursive: true });
3457
+ try {
3458
+ await mkdir(request2.out);
3459
+ } catch (error) {
3460
+ if (error.code === "EEXIST") {
3461
+ throw new Error(`cook: out '${request2.out}' already exists.`);
3462
+ }
3463
+ throw error;
3464
+ }
3465
+ try {
3466
+ return await cookInto({ ...request2, assetSource }, cooker, kitDir, assetsDir);
3467
+ } catch (error) {
3468
+ await rm(request2.out, { recursive: true, force: true });
3469
+ throw error;
3470
+ }
3471
+ }
3472
+ function applyWaterRows(layers, rows) {
3473
+ const queue = (kind) => layers.filter(
3474
+ (layer2) => kind === "river" ? layer2.type === "river" : layer2.type === "water" && layer2.params.kind !== "ocean"
3475
+ );
3476
+ const rivers = queue("river");
3477
+ const lakes = queue("lake");
3478
+ const keep = /* @__PURE__ */ new Set();
3479
+ for (const row of rows) {
3480
+ if (row.kind === "ocean") {
3481
+ layers.push({
3482
+ id: `ocean-${keep.size}`,
3483
+ type: "water",
3484
+ params: { kind: "ocean", level: row.level }
3485
+ });
3486
+ keep.add(layers[layers.length - 1]);
3487
+ continue;
3488
+ }
3489
+ const layer2 = (row.kind === "river" ? rivers : lakes).shift();
3490
+ if (layer2 === void 0) {
3491
+ throw new Error(
3492
+ `cook: water row '${row.kind}' has no ${row.kind} layer in the recipe to take it.`
3493
+ );
3494
+ }
3495
+ if (row.kind === "river") {
3496
+ layer2.params.waterWidth = row.width / (layer2.params.width ?? 12);
3497
+ if (row.depth !== void 0) layer2.params.depth = row.depth;
3498
+ } else layer2.params.radius = row.radius;
3499
+ keep.add(layer2);
3500
+ }
3501
+ const dropped = layers.filter(
3502
+ (layer2) => (layer2.type === "river" || layer2.type === "water") && !keep.has(layer2)
3503
+ );
3504
+ for (const layer2 of dropped) layers.splice(layers.indexOf(layer2), 1);
3505
+ }
3506
+ function floodedBodies(state) {
3507
+ return [
3508
+ ...state.waters.map(
3509
+ (water2) => water2.kind === "ocean" ? { kind: "ocean", level: water2.level } : { kind: "lake", radius: water2.radius ?? state.size, level: water2.level }
3510
+ ),
3511
+ ...state.rivers.map((river) => ({ kind: "river", width: round(river.width) }))
3512
+ ];
3513
+ }
3514
+ function scatterFoliage(state, biome, kind, assetTable) {
3515
+ const foliage2 = kind === void 0 ? [] : biome.foliage.filter((row) => row.density > 0 && row.species in assetTable);
3516
+ if (foliage2.length === 0) return state;
3517
+ return finalizeState({
3518
+ ...state,
3519
+ scatterRules: [...state.scatterRules, ...foliageScatterRules(foliage2, state.height)]
3520
+ });
3521
+ }
3522
+ async function cookInto(request2, cooker, kitDir, assetsDir) {
3523
+ const started = performance.now();
3524
+ const file = request2.spec ?? JSON.parse(await readFile(join(kitDir, "biome.data.json"), "utf8"));
3525
+ const declared = request2.water === void 0 ? file : { ...file, water: request2.water };
3526
+ const biome = validateBiome(declared, request2.biome ?? request2.kit);
3527
+ const kind = request2.landform ?? (request2.spec === void 0 ? void 0 : biome.landform);
3528
+ const recipe = kind === void 0 ? JSON.parse(await readFile(join(kitDir, "recipe.json"), "utf8")) : {
3529
+ recipe: landform(kind, {
3530
+ resolution: 257,
3531
+ seed: request2.seed ?? biome.seed,
3532
+ size: request2.sizeMeters ?? biome.sizeMeters
3533
+ }).toJSON()
3534
+ };
3535
+ if (request2.water !== void 0) applyWaterRows(recipe.recipe.layers, request2.water);
3536
+ if (request2.sizeMeters !== void 0) recipe.recipe.config.size = request2.sizeMeters;
3537
+ if (request2.seed !== void 0) recipe.recipe.config.seed = request2.seed;
3538
+ for (const layer2 of recipe.recipe.layers) {
3539
+ const data = layer2.params?.data;
3540
+ if (data?.raw16 === void 0) continue;
3541
+ const raw = await readFile(join(kitDir, data.raw16));
3542
+ data.values = Array.from(
3543
+ decodeRAW16(raw, data).values,
3544
+ (value) => Math.round(value * 10) / 10
3545
+ );
3546
+ }
3547
+ const assetTable = JSON.parse(await readFile(join(kitDir, "assets.json"), "utf8"));
3548
+ const surface = JSON.parse(await readFile(join(kitDir, "surface.json"), "utf8"));
3549
+ const evaluated = Terrain.fromJSON(recipe.recipe).evaluate();
3550
+ const state = applyPlacementOverrides(
3551
+ scatterFoliage(evaluated, biome, kind, assetTable),
3552
+ recipe.placementOverrides ?? {}
3553
+ );
3554
+ const species2 = Object.fromEntries(
3555
+ Object.entries(assetTable).map(([id, spec]) => [
3556
+ id,
3557
+ {
3558
+ glb: join(assetsDir, spec.near),
3559
+ bounds: parseBounds(spec.bounds, id),
3560
+ lods: spec.mid ? [{ distance: spec.midDistance ?? 40, glb: join(assetsDir, spec.mid) }] : [],
3561
+ maxDistance: spec.maxDistance
3562
+ }
3563
+ ])
3564
+ );
3565
+ const cooked = await cooker.cookTerrainWorld({
3566
+ state,
3567
+ species: species2,
3568
+ materials: {
3569
+ texturesDir: assetsDir,
3570
+ layers: [surface.base, ...surface.layers].map((layer2) => {
3571
+ const source = surface.sources[layer2.id];
3572
+ if (source === void 0) throw new Error(`cook: no source for layer '${layer2.id}'.`);
3573
+ return { id: layer2.id, ...source, diffMimeType: "image/jpeg", nrmMimeType: "image/jpeg" };
3574
+ })
3575
+ },
3576
+ out: request2.out,
3577
+ extraLayers: { table: "terrain-table.json" }
3578
+ });
3579
+ await writeFile(
3580
+ join(request2.out, "water.json"),
3581
+ `${JSON.stringify(
3582
+ {
3583
+ lakes: state.waters.map((lake) => ({
3584
+ id: lake.id,
3585
+ // The reply names each body's kind, so the file records it: an ocean is not a lake.
3586
+ kind: lake.kind ?? "lake",
3587
+ at: lake.at,
3588
+ radius: lake.radius,
3589
+ level: lake.level
3590
+ })),
3591
+ rivers: state.rivers.map((river) => ({
3592
+ id: river.id,
3593
+ width: round(river.width),
3594
+ points: river.points.map((point) => point.map(round))
3595
+ }))
3596
+ },
3597
+ null,
3598
+ 2
3599
+ )}
3600
+ `
3601
+ );
3602
+ const { bands, package: pkg } = bakeBiome({
3603
+ state,
3604
+ spec: biome,
3605
+ assets: cooked.manifest.assets});
3606
+ if (pkg === null) throw new Error("cook: the bake wrote no world package.");
3607
+ const { splat, manifest, files } = pkg;
3608
+ await writeFile(
3609
+ join(request2.out, "terrain-table.json"),
3610
+ `${JSON.stringify({ ...surface, splat, textures: "textures" }, null, 2)}
3611
+ `
3612
+ );
3613
+ await copyFile(
3614
+ join(assetsDir, "hdri", "kloofendal_48d_partly_cloudy_1k.hdr"),
3615
+ join(request2.out, "sky.hdr")
3616
+ );
3617
+ await writeFile(join(request2.out, "recipe.json"), JSON.stringify(recipe.recipe));
3618
+ const shown = relative(await realpath(request2.projectRoot), request2.out).split(sep).join("/");
3619
+ const url = relative(request2.assetSource, request2.out).split(sep).join("/");
3620
+ const worldUrl = `${url}/world.json`;
3621
+ const ring = Math.ceil(Math.max(manifest.extent.sizeX, manifest.extent.sizeZ) / manifest.cellSize / 2) + 1;
3622
+ const instances = manifest.cells.reduce(
3623
+ (count2, cell) => count2 + cell.runs.reduce((sum, run) => sum + run.count, 0),
3624
+ 0
3625
+ );
3626
+ const placementBytes = files[manifest.placements];
3627
+ if (placementBytes === void 0)
3628
+ throw new Error("cook: world package has no placement records.");
3629
+ const budgets = {
3630
+ residentCells: Math.max(1, manifest.cells.length),
3631
+ instances: Math.max(1, instances),
3632
+ bytes: Math.max(1, placementBytes.byteLength)
3633
+ };
3634
+ const heightmapUrl = `${url}/${cooked.manifest.terrain.heightmap}`;
3635
+ const physical = JSON.stringify({
3636
+ extent: cooked.manifest.extent,
3637
+ terrain: cooked.manifest.terrain
3638
+ });
3639
+ return JSON.stringify({
3640
+ recipe: request2.kit,
3641
+ out: shown,
3642
+ worldGlb: `${shown}/world.glb`,
3643
+ recipeJson: `${shown}/recipe.json`,
3644
+ worldPackage: `${shown}/world.json`,
3645
+ ...measureGlb(cooked.worldGlb),
3646
+ placementCounts: cooked.placementCounts,
3647
+ biome: biome.look,
3648
+ water: floodedBodies(state),
3649
+ bands,
3650
+ worldGlbBytes: cooked.worldGlb.length,
3651
+ ms: Math.round(performance.now() - started),
3652
+ load: [
3653
+ 'import { WorldCells as TerrainWorldCells, Heightfield as TerrainHeightfield, heightSamplerFromHeightmap as sampleTerrainHeight, loadWorldHeightmap as loadTerrainHeightmap, loadTerrainSplat, type IWorldCellsLoadOptions as TerrainWorldOptions } from "@threenative/core/world";',
3654
+ 'import { CollisionShape3D as TerrainCollisionShape, RigidBody3D as TerrainRigidBody } from "@threenative/physics";',
3655
+ 'import { Object3D as TerrainAnchor } from "three";',
3656
+ `const terrainWorld = ${physical};`,
3657
+ `const [terrainHeightmapUrl] = await ctx.assets.resolve(${JSON.stringify(heightmapUrl)});`,
3658
+ 'if (terrainHeightmapUrl === undefined) throw new Error("terrain: the world heightmap is not served.");',
3659
+ "const terrainHeights = await loadTerrainHeightmap(terrainHeightmapUrl);",
3660
+ "const terrainField = TerrainHeightfield.fromSampler({",
3661
+ " columns: terrainWorld.terrain.columns,",
3662
+ " depth: terrainWorld.extent.sizeZ,",
3663
+ " origin: { x: terrainWorld.extent.minX + terrainWorld.extent.sizeX / 2, z: terrainWorld.extent.minZ + terrainWorld.extent.sizeZ / 2 },",
3664
+ " rows: terrainWorld.terrain.rows,",
3665
+ " sampleHeight: sampleTerrainHeight(terrainWorld.terrain, terrainWorld.extent, terrainHeights),",
3666
+ " width: terrainWorld.extent.sizeX,",
3667
+ "});",
3668
+ "const terrainAnchor = new TerrainAnchor();",
3669
+ "terrainAnchor.position.set(terrainWorld.extent.minX + terrainWorld.extent.sizeX / 2, 0, terrainWorld.extent.minZ + terrainWorld.extent.sizeZ / 2);",
3670
+ "const terrainBody = new TerrainRigidBody({",
3671
+ ' entity: "terrain",',
3672
+ " object: terrainAnchor,",
3673
+ " physics: ctx.physics,",
3674
+ " shape: TerrainCollisionShape.heightfield(terrainField.rows, terrainField.columns, terrainField.toColliderHeights(), { x: terrainWorld.extent.sizeX, y: 1, z: terrainWorld.extent.sizeZ }),",
3675
+ ' type: "fixed",',
3676
+ "});",
3677
+ "let world: TerrainWorldCells | undefined;",
3678
+ "let terrainSurface: Awaited<ReturnType<typeof loadTerrainSplat>> | undefined;",
3679
+ "// The anchor owns the streamed world, caller-supplied surface and full-world collider.",
3680
+ 'terrainAnchor.addEventListener("removed", () => { world?.dispose(); terrainSurface?.dispose(); terrainBody.dispose(); });',
3681
+ "ctx.add(terrainAnchor);",
3682
+ "let terrainFollow = terrainAnchor;",
3683
+ 'let terrainInvalidate: NonNullable<TerrainWorldOptions["shadows"]>["invalidate"];',
3684
+ "try {",
3685
+ ` terrainSurface = await loadTerrainSplat({ assets: ctx.assets, renderer: ctx.renderer, url: ${JSON.stringify(worldUrl)} });`,
3686
+ " world = await TerrainWorldCells.load({",
3687
+ ` assets: ctx.assets, url: ${JSON.stringify(worldUrl)}, surface: terrainSurface,`,
3688
+ " follow: { get position() { return terrainFollow.position; } },",
3689
+ ` ring: ${ring}, budgets: ${JSON.stringify(budgets)}, terrain: { streamRadius: ${ring + 1} },`,
3690
+ " shadows: { cast: true, receive: true, invalidate: (region) => terrainInvalidate?.(region) },",
3691
+ "});",
3692
+ " ctx.add(world);",
3693
+ "} catch (error) { terrainAnchor.removeFromParent(); throw error; }",
3694
+ 'const loadCells = (follow: TerrainAnchor, invalidate?: NonNullable<TerrainWorldOptions["shadows"]>["invalidate"]) => { terrainFollow = follow; terrainInvalidate = invalidate; };',
3695
+ "// Call loadCells(player.mesh) after creating the player; optionally forward streamed shadow invalidation."
3696
+ ].join("\n")
3697
+ });
3698
+ }
3699
+
3700
+ // src/mcp/cook-child.ts
3701
+ var request = JSON.parse(process.argv[2] ?? "null");
3702
+ if (typeof request !== "object" || request === null) {
3703
+ throw new Error("cook-child: the request must be a JSON object.");
3704
+ }
3705
+ console.log(await cookKit(request));