@threenative/terrain 0.1.7 → 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.
- package/AGENT_GUIDE.md +19 -4
- package/dist/editor/index.d.ts +160 -5
- package/dist/editor/index.js +3783 -1406
- package/dist/editor/server.d.ts +2 -2
- package/dist/editor/server.js +555 -121
- package/dist/editor/worker.d.ts +33 -1
- package/dist/editor/worker.js +444 -110
- package/dist/export.d.ts +11 -9
- package/dist/export.js +22 -34
- package/dist/index.d.ts +727 -73
- package/dist/index.js +2434 -553
- package/dist/kit.d.ts +56 -0
- package/dist/kit.js +2524 -0
- package/dist/mcp/cook-child.d.ts +2 -0
- package/dist/mcp/cook-child.js +3705 -0
- package/dist/mcp/server.d.ts +7 -0
- package/dist/mcp/server.js +3279 -0
- package/dist/{server-ByM2hmYJ.d.ts → server-C8Ydr_IM.d.ts} +3 -2
- package/dist/starter.d.ts +143 -0
- package/dist/starter.js +1030 -0
- package/dist/{terrain-gPnkCU6S.d.ts → terrain-B3DkduPw.d.ts} +3 -2
- package/dist/three.d.ts +1 -1
- package/dist/{types-Ant8-Axc.d.ts → types-CPYAc9vo.d.ts} +13 -4
- package/dist/world-package-B7KGYIou.d.ts +94 -0
- package/package.json +28 -6
- package/starter/alpine/README.md +77 -1
- package/starter/alpine/bake.mjs +4 -116
- package/starter/alpine/biome.data.json +114 -0
- package/starter/alpine/heightmap.r16 +0 -0
- package/starter/alpine/recipe.json +3 -66051
- package/starter/alpine/world.ts +45 -293
- package/starter/coastal/README.md +77 -1
- package/starter/coastal/bake.mjs +4 -116
- package/starter/coastal/biome.data.json +135 -0
- package/starter/coastal/heightmap.r16 +0 -0
- package/starter/coastal/recipe.json +3 -66051
- package/starter/coastal/sea.ts +49 -16
- package/starter/coastal/world.ts +53 -318
- package/starter/desert/README.md +77 -1
- package/starter/desert/bake.mjs +4 -116
- package/starter/desert/biome.data.json +114 -0
- package/starter/desert/heightmap.r16 +0 -0
- package/starter/desert/recipe.json +3 -66051
- package/starter/desert/world.ts +45 -293
- package/starter/forest/README.md +84 -4
- package/starter/forest/assets.json +32 -0
- package/starter/forest/bake.mjs +6 -116
- package/starter/forest/biome.data.json +150 -0
- package/starter/forest/heightmap.r16 +0 -0
- package/starter/forest/recipe.json +192 -4428
- package/starter/forest/sky.ts +11 -0
- package/starter/forest/water.ts +30 -20
- package/starter/forest/world.ts +86 -322
- package/starter/tundra/README.md +77 -1
- package/starter/tundra/bake.mjs +4 -116
- package/starter/tundra/biome.data.json +131 -0
- package/starter/tundra/heightmap.r16 +0 -0
- package/starter/tundra/recipe.json +18 -66066
- package/starter/tundra/world.ts +65 -319
- package/starter-assets.json +6 -0
- package/{starter-assets/credits.json → starter-credits.json} +12 -105
- package/starter-assets/bark_brown_02/bark_brown_02_diff_1k.jpg +0 -0
- package/starter-assets/bark_brown_02/bark_brown_02_nor_gl_1k.jpg +0 -0
- package/starter-assets/bark_brown_02/bark_brown_02_rough_1k.jpg +0 -0
- package/starter-assets/boulder_01/boulder-mid.glb +0 -0
- package/starter-assets/boulder_01/boulder-near.glb +0 -0
- package/starter-assets/cliff_side/cliff_side_ao_1k.jpg +0 -0
- package/starter-assets/cliff_side/cliff_side_diff_1k.jpg +0 -0
- package/starter-assets/cliff_side/cliff_side_nor_gl_1k.jpg +0 -0
- package/starter-assets/cliff_side/cliff_side_rough_1k.jpg +0 -0
- package/starter-assets/fern_02/fern_02_alpha_512.png +0 -0
- package/starter-assets/fern_02/fern_02_diff_512.jpg +0 -0
- package/starter-assets/fern_02/fern_02_nor_gl_512.jpg +0 -0
- package/starter-assets/fir_tree_01/fir-b-lod1.glb +0 -0
- package/starter-assets/fir_tree_01/fir-b-lod2.glb +0 -0
- package/starter-assets/fir_tree_01/fir-c-lod1.glb +0 -0
- package/starter-assets/fir_tree_01/fir-c-lod2.glb +0 -0
- package/starter-assets/fir_tree_01/fir_tree_01_twig_arm_1k.jpg +0 -0
- package/starter-assets/fir_tree_01/fir_tree_01_twig_diff_1k.jpg +0 -0
- package/starter-assets/fir_tree_01/fir_tree_01_twig_nor_gl_1k.jpg +0 -0
- package/starter-assets/forest_ground_04/forest_ground_04_ao_1k.jpg +0 -0
- package/starter-assets/forest_ground_04/forest_ground_04_diff_1k.jpg +0 -0
- package/starter-assets/forest_ground_04/forest_ground_04_nor_gl_1k.jpg +0 -0
- package/starter-assets/forest_ground_04/forest_ground_04_rough_1k.jpg +0 -0
- package/starter-assets/forest_leaves_02/forest_leaves_02_arm_512.jpg +0 -0
- package/starter-assets/forest_leaves_02/forest_leaves_02_diff_512.jpg +0 -0
- package/starter-assets/forest_leaves_02/forest_leaves_02_nor_gl_512.jpg +0 -0
- package/starter-assets/grass_medium_02/grass_medium_02_alpha_512.png +0 -0
- package/starter-assets/grass_medium_02/grass_medium_02_diff_512.jpg +0 -0
- package/starter-assets/grass_medium_02/grass_medium_02_nor_gl_512.jpg +0 -0
- package/starter-assets/hdri/kloofendal_48d_partly_cloudy_1k.hdr +0 -0
- package/starter-assets/leafy_grass/leafy_grass_ao_1k.jpg +0 -0
- package/starter-assets/leafy_grass/leafy_grass_diff_1k.jpg +0 -0
- package/starter-assets/leafy_grass/leafy_grass_nor_gl_1k.jpg +0 -0
- package/starter-assets/leafy_grass/leafy_grass_rough_1k.jpg +0 -0
- package/starter-assets/lichen_rock/lichen_rock_arm_512.jpg +0 -0
- package/starter-assets/lichen_rock/lichen_rock_diff_512.jpg +0 -0
- package/starter-assets/lichen_rock/lichen_rock_nor_gl_512.jpg +0 -0
- package/starter-assets/mossy_rock/mossy_rock_ao_1k.jpg +0 -0
- package/starter-assets/mossy_rock/mossy_rock_diff_1k.jpg +0 -0
- package/starter-assets/mossy_rock/mossy_rock_nor_gl_1k.jpg +0 -0
- package/starter-assets/mossy_rock/mossy_rock_rough_1k.jpg +0 -0
- package/starter-assets/needle-atlas.png +0 -0
- package/starter-assets/needle-surface.png +0 -0
- package/starter-assets/river_small_rocks/river_small_rocks_arm_512.jpg +0 -0
- package/starter-assets/river_small_rocks/river_small_rocks_diff_512.jpg +0 -0
- package/starter-assets/river_small_rocks/river_small_rocks_nor_gl_512.jpg +0 -0
- package/starter-assets/rock_boulder_dry/rock_boulder_dry_arm_512.jpg +0 -0
- package/starter-assets/rock_boulder_dry/rock_boulder_dry_diff_512.jpg +0 -0
- package/starter-assets/rock_boulder_dry/rock_boulder_dry_nor_gl_512.jpg +0 -0
- package/starter-assets/rocks/boulder-mid.glb +0 -0
- package/starter-assets/rocks/boulder-near.glb +0 -0
- package/starter-assets/rocks/boulder-prep.json +0 -37
- package/starter-assets/rocks/rock01-mid.glb +0 -0
- package/starter-assets/rocks/rock01-near.glb +0 -0
- package/starter-assets/rocks/rock01-prep.json +0 -37
- package/starter-assets/rocks/rock04-mid.glb +0 -0
- package/starter-assets/rocks/rock04-near.glb +0 -0
- package/starter-assets/rocks/rock04-prep.json +0 -37
- package/starter-assets/sand_01/sand_01_ao_1k.jpg +0 -0
- package/starter-assets/sand_01/sand_01_diff_1k.jpg +0 -0
- package/starter-assets/sand_01/sand_01_nor_gl_1k.jpg +0 -0
- package/starter-assets/sand_01/sand_01_rough_1k.jpg +0 -0
- package/starter-assets/snow_02/snow_02_ao_1k.jpg +0 -0
- package/starter-assets/snow_02/snow_02_diff_1k.jpg +0 -0
- package/starter-assets/snow_02/snow_02_nor_gl_1k.jpg +0 -0
- package/starter-assets/snow_02/snow_02_rough_1k.jpg +0 -0
|
@@ -0,0 +1,3279 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { realpathSync } from 'fs';
|
|
3
|
+
import { readFile, mkdir, writeFile, rm, lstat, realpath, readdir } from 'fs/promises';
|
|
4
|
+
import { resolve, relative, join, sep, isAbsolute, basename, dirname } from 'path';
|
|
5
|
+
import { createInterface } from 'readline';
|
|
6
|
+
import { fileURLToPath } from 'url';
|
|
7
|
+
import { spawn } from 'child_process';
|
|
8
|
+
|
|
9
|
+
function childExecArgv(execArgv) {
|
|
10
|
+
const out = [];
|
|
11
|
+
for (let i = 0; i < execArgv.length; i += 1) {
|
|
12
|
+
const flag2 = execArgv[i];
|
|
13
|
+
if (!/^--(inspect(-brk|-wait|-port|-publish-uid)?|debug-port|(cpu|heap)-prof(-[a-z]+)?)(=|$)/.test(
|
|
14
|
+
flag2
|
|
15
|
+
)) {
|
|
16
|
+
out.push(flag2);
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
if (!flag2.includes("=") && /-(port|dir|name|interval|uid)$/.test(flag2)) i += 1;
|
|
20
|
+
}
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
var IsolatedKillError = class extends Error {
|
|
24
|
+
};
|
|
25
|
+
function runIsolated({
|
|
26
|
+
command,
|
|
27
|
+
args,
|
|
28
|
+
timeoutMs,
|
|
29
|
+
signal
|
|
30
|
+
}) {
|
|
31
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
32
|
+
return Promise.reject(new RangeError("runIsolated: timeoutMs must be a positive number."));
|
|
33
|
+
}
|
|
34
|
+
if (signal?.aborted) {
|
|
35
|
+
return Promise.reject(
|
|
36
|
+
new IsolatedKillError("runIsolated: child was cancelled before it started.")
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
return new Promise((resolve3, reject) => {
|
|
40
|
+
const child = spawn(command, [...args], {
|
|
41
|
+
detached: process.platform !== "win32",
|
|
42
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
43
|
+
});
|
|
44
|
+
let stdout = "";
|
|
45
|
+
let stderr = "";
|
|
46
|
+
let killed;
|
|
47
|
+
let settled = false;
|
|
48
|
+
const finish = (error, result) => {
|
|
49
|
+
if (settled) return;
|
|
50
|
+
settled = true;
|
|
51
|
+
clearTimeout(timer);
|
|
52
|
+
signal?.removeEventListener("abort", onAbort);
|
|
53
|
+
if (error !== void 0) reject(error);
|
|
54
|
+
else resolve3(result);
|
|
55
|
+
};
|
|
56
|
+
const stop = (reason) => {
|
|
57
|
+
killed ??= new IsolatedKillError(reason);
|
|
58
|
+
try {
|
|
59
|
+
if (child.pid !== void 0 && process.platform !== "win32")
|
|
60
|
+
process.kill(-child.pid, "SIGKILL");
|
|
61
|
+
else child.kill("SIGKILL");
|
|
62
|
+
} catch {
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const timer = setTimeout(
|
|
66
|
+
() => stop(`runIsolated: child timed out after ${timeoutMs} ms and was killed.`),
|
|
67
|
+
timeoutMs
|
|
68
|
+
);
|
|
69
|
+
const onAbort = () => stop("runIsolated: child was cancelled and was killed.");
|
|
70
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
71
|
+
child.stdout.setEncoding("utf8");
|
|
72
|
+
child.stderr.setEncoding("utf8");
|
|
73
|
+
child.stdout.on("data", (chunk) => {
|
|
74
|
+
stdout += chunk;
|
|
75
|
+
});
|
|
76
|
+
child.stderr.on("data", (chunk) => {
|
|
77
|
+
stderr += chunk;
|
|
78
|
+
});
|
|
79
|
+
child.on("error", (error) => finish(error));
|
|
80
|
+
child.on("close", (code) => {
|
|
81
|
+
if (killed !== void 0) finish(killed);
|
|
82
|
+
else if (code === 0) finish(void 0, { stdout, stderr });
|
|
83
|
+
else finish(new Error(`runIsolated: child exited with code ${code}: ${stderr.trim()}`));
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// src/core/kits.ts
|
|
89
|
+
var TERRAIN_KITS = ["forest", "coastal", "alpine", "desert", "tundra"];
|
|
90
|
+
|
|
91
|
+
// src/core/biome-words.ts
|
|
92
|
+
var BIOME_WORDS = {
|
|
93
|
+
alpine: ["alpine", "mountain", "mountains", "snowy", "peaks"],
|
|
94
|
+
coastal: ["coastal", "beach", "coast", "sea", "ocean"],
|
|
95
|
+
desert: ["desert", "dune", "dunes", "sand"],
|
|
96
|
+
forest: ["forest", "pine", "pines", "woods", "woodland"],
|
|
97
|
+
tundra: ["tundra", "arctic", "ice"]
|
|
98
|
+
};
|
|
99
|
+
var BIOME_WORD_ROWS = TERRAIN_KITS.map((kit) => [kit, BIOME_WORDS[kit]]);
|
|
100
|
+
function biomeWordList() {
|
|
101
|
+
return BIOME_WORD_ROWS.map(([kit, words]) => `${kit} (${words.slice(1).join(", ")})`).join("; ");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// src/core/math.ts
|
|
105
|
+
var clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
|
|
106
|
+
var lerp = (a, b, t) => a + (b - a) * t;
|
|
107
|
+
var smoothstep = (a, b, x) => {
|
|
108
|
+
if (a === b) return x >= b ? 1 : 0;
|
|
109
|
+
const t = clamp((x - a) / (b - a));
|
|
110
|
+
return t * t * (3 - 2 * t);
|
|
111
|
+
};
|
|
112
|
+
var hashString = (text2) => {
|
|
113
|
+
let h = 2166136261;
|
|
114
|
+
for (const c of text2) h = Math.imul(h ^ c.charCodeAt(0), 16777619);
|
|
115
|
+
return h >>> 0;
|
|
116
|
+
};
|
|
117
|
+
function random(seed) {
|
|
118
|
+
let a = seed >>> 0;
|
|
119
|
+
return () => {
|
|
120
|
+
a |= 0;
|
|
121
|
+
a = a + 1831565813 | 0;
|
|
122
|
+
let t = Math.imul(a ^ a >>> 15, 1 | a);
|
|
123
|
+
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
|
|
124
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
var hash2 = (x, z, seed) => {
|
|
128
|
+
let n = Math.imul(x | 0, 374761393) ^ Math.imul(z | 0, 668265263) ^ seed;
|
|
129
|
+
n = Math.imul(n ^ n >>> 13, 1274126177);
|
|
130
|
+
return (n ^ n >>> 16) >>> 0;
|
|
131
|
+
};
|
|
132
|
+
var diagonalGradient = 0.7071;
|
|
133
|
+
var grad = (h, x, z) => {
|
|
134
|
+
switch (h & 7) {
|
|
135
|
+
case 0:
|
|
136
|
+
return x;
|
|
137
|
+
case 1:
|
|
138
|
+
return -x;
|
|
139
|
+
case 2:
|
|
140
|
+
return z;
|
|
141
|
+
case 3:
|
|
142
|
+
return -z;
|
|
143
|
+
case 4:
|
|
144
|
+
return (x + z) * diagonalGradient;
|
|
145
|
+
case 5:
|
|
146
|
+
return (x - z) * diagonalGradient;
|
|
147
|
+
case 6:
|
|
148
|
+
return (-x + z) * diagonalGradient;
|
|
149
|
+
default:
|
|
150
|
+
return (-x - z) * diagonalGradient;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
function noise2(x, z, seed = 1) {
|
|
154
|
+
const ix = Math.floor(x);
|
|
155
|
+
const iz = Math.floor(z);
|
|
156
|
+
const fx = x - ix;
|
|
157
|
+
const fz = z - iz;
|
|
158
|
+
const u = fx * fx * fx * (fx * (fx * 6 - 15) + 10);
|
|
159
|
+
const v = fz * fz * fz * (fz * (fz * 6 - 15) + 10);
|
|
160
|
+
return lerp(
|
|
161
|
+
lerp(grad(hash2(ix, iz, seed), fx, fz), grad(hash2(ix + 1, iz, seed), fx - 1, fz), u),
|
|
162
|
+
lerp(
|
|
163
|
+
grad(hash2(ix, iz + 1, seed), fx, fz - 1),
|
|
164
|
+
grad(hash2(ix + 1, iz + 1, seed), fx - 1, fz - 1),
|
|
165
|
+
u
|
|
166
|
+
),
|
|
167
|
+
v
|
|
168
|
+
) * 1.65;
|
|
169
|
+
}
|
|
170
|
+
function fbm(inputX, inputZ, { seed = 1, octaves = 5, persistence = 0.5, lacunarity = 2, mode = "fbm" } = {}) {
|
|
171
|
+
let x = inputX;
|
|
172
|
+
let z = inputZ;
|
|
173
|
+
let value = 0;
|
|
174
|
+
let amplitude = 1;
|
|
175
|
+
let total = 0;
|
|
176
|
+
for (let i = 0; i < octaves; i += 1) {
|
|
177
|
+
let n = noise2(x + 13.17, z - 8.71, seed + i * 71);
|
|
178
|
+
if (mode === "ridged") n = (1 - Math.abs(n)) ** 2 * 2 - 1;
|
|
179
|
+
if (mode === "billow") n = Math.abs(n) * 2 - 1;
|
|
180
|
+
value += n * amplitude;
|
|
181
|
+
total += amplitude;
|
|
182
|
+
amplitude *= persistence;
|
|
183
|
+
x *= lacunarity;
|
|
184
|
+
z *= lacunarity;
|
|
185
|
+
}
|
|
186
|
+
return total ? value / total : 0;
|
|
187
|
+
}
|
|
188
|
+
var world = (grid, x) => x / (grid.resolution - 1) * grid.size - grid.size / 2;
|
|
189
|
+
function sampleGrid(a, width, height, u, v) {
|
|
190
|
+
const gx = clamp(u, 0, 1) * (width - 1);
|
|
191
|
+
const gz = clamp(v, 0, 1) * (height - 1);
|
|
192
|
+
const x = Math.min(width - 2, Math.floor(gx));
|
|
193
|
+
const z = Math.min(height - 2, Math.floor(gz));
|
|
194
|
+
const tx = gx - x;
|
|
195
|
+
const tz = gz - z;
|
|
196
|
+
return lerp(
|
|
197
|
+
lerp(a[z * width + x], a[z * width + x + 1], tx),
|
|
198
|
+
lerp(a[(z + 1) * width + x], a[(z + 1) * width + x + 1], tx),
|
|
199
|
+
tz
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
var sampleHeight = (grid, x, z) => sampleGrid(
|
|
203
|
+
grid.height,
|
|
204
|
+
grid.resolution,
|
|
205
|
+
grid.resolution,
|
|
206
|
+
x / grid.size + 0.5,
|
|
207
|
+
z / grid.size + 0.5
|
|
208
|
+
);
|
|
209
|
+
function gradientAt(grid, x, z) {
|
|
210
|
+
const d = grid.size / (grid.resolution - 1);
|
|
211
|
+
return [
|
|
212
|
+
(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),
|
|
213
|
+
(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)
|
|
214
|
+
];
|
|
215
|
+
}
|
|
216
|
+
function slopeAtIndex(grid, i) {
|
|
217
|
+
const n = grid.resolution;
|
|
218
|
+
const x = i % n;
|
|
219
|
+
const z = Math.floor(i / n);
|
|
220
|
+
const dx = x > 0 && x < n - 1 ? 2 : 1;
|
|
221
|
+
const dz = z > 0 && z < n - 1 ? 2 : 1;
|
|
222
|
+
const cell = grid.size / (n - 1);
|
|
223
|
+
const gx = (grid.height[z * n + Math.min(x + 1, n - 1)] - grid.height[z * n + Math.max(x - 1, 0)]) / (dx * cell);
|
|
224
|
+
const gz = (grid.height[Math.min(z + 1, n - 1) * n + x] - grid.height[Math.max(z - 1, 0) * n + x]) / (dz * cell);
|
|
225
|
+
return Math.atan(Math.hypot(gx, gz)) * (180 / Math.PI);
|
|
226
|
+
}
|
|
227
|
+
function falloff(distance, radius, softness = 0.6) {
|
|
228
|
+
const d = distance / radius;
|
|
229
|
+
return d >= 1 ? 0 : 1 - smoothstep(1 - clamp(softness, 1e-5, 1), 1, d);
|
|
230
|
+
}
|
|
231
|
+
function splinePoints(points, step = 3, smooth = true) {
|
|
232
|
+
const out = [];
|
|
233
|
+
for (let k = 0; k < points.length - 1; k += 1) {
|
|
234
|
+
const a = points[Math.max(0, k - 1)];
|
|
235
|
+
const b = points[k];
|
|
236
|
+
const c = points[k + 1];
|
|
237
|
+
const d = points[Math.min(points.length - 1, k + 2)];
|
|
238
|
+
const count2 = Math.max(
|
|
239
|
+
1,
|
|
240
|
+
Math.min(512, Math.ceil(Math.hypot(c[0] - b[0], c[2] - b[2]) / step))
|
|
241
|
+
);
|
|
242
|
+
for (let j = 0; j < count2; j += 1) {
|
|
243
|
+
const t = j / count2;
|
|
244
|
+
const t2 = t * t;
|
|
245
|
+
const t3 = t2 * t;
|
|
246
|
+
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);
|
|
247
|
+
out.push([
|
|
248
|
+
smooth ? cat(0) : lerp(b[0], c[0], t),
|
|
249
|
+
lerp(b[1], c[1], t),
|
|
250
|
+
smooth ? cat(2) : lerp(b[2], c[2], t)
|
|
251
|
+
]);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const last = points[points.length - 1];
|
|
255
|
+
out.push([last[0], last[1], last[2]]);
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// src/core/erosion.ts
|
|
260
|
+
function thermal(height, n, size, { iterations = 20, talus = 32, rate = 0.22 } = {}, observations) {
|
|
261
|
+
if (!Number.isInteger(n) || n < 2)
|
|
262
|
+
throw RangeError("Thermal erosion requires grid resolution n >= 2");
|
|
263
|
+
if (!Number.isInteger(iterations) || iterations < 0 || iterations > 200)
|
|
264
|
+
throw RangeError("Thermal erosion iterations must be between 0 and 200");
|
|
265
|
+
const h = height.slice();
|
|
266
|
+
const delta = new Float64Array(h.length);
|
|
267
|
+
const limit = Math.tan(talus * Math.PI / 180) * (size / (n - 1));
|
|
268
|
+
for (let k = 0; k < iterations; k += 1) {
|
|
269
|
+
delta.fill(0);
|
|
270
|
+
for (let z = 0; z < n; z += 1) {
|
|
271
|
+
for (let x = 0; x < n; x += 1) {
|
|
272
|
+
const i = z * n + x;
|
|
273
|
+
const here = h[i];
|
|
274
|
+
let best = -1;
|
|
275
|
+
let diff = limit;
|
|
276
|
+
if (x > 0 && here - h[i - 1] > diff) {
|
|
277
|
+
diff = here - h[i - 1];
|
|
278
|
+
best = i - 1;
|
|
279
|
+
}
|
|
280
|
+
if (x < n - 1 && here - h[i + 1] > diff) {
|
|
281
|
+
diff = here - h[i + 1];
|
|
282
|
+
best = i + 1;
|
|
283
|
+
}
|
|
284
|
+
if (z > 0 && here - h[i - n] > diff) {
|
|
285
|
+
diff = here - h[i - n];
|
|
286
|
+
best = i - n;
|
|
287
|
+
}
|
|
288
|
+
if (z < n - 1 && here - h[i + n] > diff) {
|
|
289
|
+
diff = here - h[i + n];
|
|
290
|
+
best = i + n;
|
|
291
|
+
}
|
|
292
|
+
if (best >= 0) {
|
|
293
|
+
const transfer = (diff - limit) * rate;
|
|
294
|
+
delta[i] = delta[i] - transfer;
|
|
295
|
+
delta[best] = delta[best] + transfer;
|
|
296
|
+
if (observations)
|
|
297
|
+
observations.talus[best] = observations.talus[best] + transfer;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
for (let i = 0; i < h.length; i += 1) h[i] = h[i] + delta[i];
|
|
302
|
+
}
|
|
303
|
+
return h;
|
|
304
|
+
}
|
|
305
|
+
var brushes = /* @__PURE__ */ new Map();
|
|
306
|
+
function brush(radius) {
|
|
307
|
+
let cells = brushes.get(radius);
|
|
308
|
+
if (!cells) {
|
|
309
|
+
const dx = [];
|
|
310
|
+
const dz = [];
|
|
311
|
+
const raw = [];
|
|
312
|
+
let total = 0;
|
|
313
|
+
for (let z = -radius; z <= radius; z += 1) {
|
|
314
|
+
for (let x = -radius; x <= radius; x += 1) {
|
|
315
|
+
const d = Math.hypot(x, z);
|
|
316
|
+
if (d > radius) continue;
|
|
317
|
+
const weight2 = 1 - d / (radius + 1);
|
|
318
|
+
dx.push(x);
|
|
319
|
+
dz.push(z);
|
|
320
|
+
raw.push(weight2);
|
|
321
|
+
total += weight2;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const weight = Float64Array.from(raw, (w) => w / total);
|
|
325
|
+
let full = 0;
|
|
326
|
+
for (let k = 0; k < weight.length; k += 1) full += weight[k];
|
|
327
|
+
cells = { dx: Int32Array.from(dx), dz: Int32Array.from(dz), full, radius, weight };
|
|
328
|
+
brushes.set(radius, cells);
|
|
329
|
+
}
|
|
330
|
+
return cells;
|
|
331
|
+
}
|
|
332
|
+
var MAX_AUTOMATIC_DROPLETS = 1025 * 1025;
|
|
333
|
+
var MAX_EXPLICIT_DROPLETS = 2e5;
|
|
334
|
+
function hydraulic(height, n, size, options = {}, observations) {
|
|
335
|
+
const {
|
|
336
|
+
droplets: requestedDroplets,
|
|
337
|
+
// A droplet has to be able to cross the world, so its step budget scales with the grid: a
|
|
338
|
+
// fixed 40 barely leaves a 257 world while a 65 world would walk off it in a few steps.
|
|
339
|
+
maxSteps = Math.round(Math.min(64, Math.max(24, n / 4))),
|
|
340
|
+
inertia = 0.2,
|
|
341
|
+
capacity = 4,
|
|
342
|
+
// Each step takes a small bite of the sediment the droplet can carry. A big bite carves
|
|
343
|
+
// fewer, deeper dimples that stand proud of their neighbours as spikes; many shallow bites
|
|
344
|
+
// over the same lines incise the same drainage with a smooth surface.
|
|
345
|
+
erosion = 0.03,
|
|
346
|
+
deposition = 0.3,
|
|
347
|
+
evaporation = 0.025,
|
|
348
|
+
seed = 1,
|
|
349
|
+
brushRadius = 3
|
|
350
|
+
} = options;
|
|
351
|
+
if (!Number.isInteger(n) || n < 2)
|
|
352
|
+
throw RangeError("Hydraulic erosion requires grid resolution n >= 2");
|
|
353
|
+
const droplets = requestedDroplets === void 0 ? Math.min(n * n, MAX_AUTOMATIC_DROPLETS) : requestedDroplets;
|
|
354
|
+
if (!Number.isSafeInteger(droplets) || droplets < 0)
|
|
355
|
+
throw RangeError("Hydraulic erosion droplets must be a non-negative integer");
|
|
356
|
+
if (requestedDroplets !== void 0 && droplets > MAX_EXPLICIT_DROPLETS)
|
|
357
|
+
throw RangeError(`Hydraulic erosion droplets must not exceed ${String(MAX_EXPLICIT_DROPLETS)}`);
|
|
358
|
+
if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 128)
|
|
359
|
+
throw RangeError("Hydraulic erosion maxSteps must be between 1 and 128");
|
|
360
|
+
const h = Float64Array.from(height);
|
|
361
|
+
const rnd = random(seed);
|
|
362
|
+
const cell = size / (n - 1);
|
|
363
|
+
const minSlope = 5e-3 * cell;
|
|
364
|
+
const oneMinusInertia = 1 - inertia;
|
|
365
|
+
const oneMinusEvaporation = 1 - evaporation;
|
|
366
|
+
const brushCells = brush(brushRadius);
|
|
367
|
+
const brushDx = brushCells.dx;
|
|
368
|
+
const brushDz = brushCells.dz;
|
|
369
|
+
const brushWeight = brushCells.weight;
|
|
370
|
+
const brushCount = brushDx.length;
|
|
371
|
+
const brushFull = brushCells.full;
|
|
372
|
+
const brushEdge = brushCells.radius;
|
|
373
|
+
const brushOffset = new Int32Array(brushCount);
|
|
374
|
+
for (let k = 0; k < brushCount; k += 1)
|
|
375
|
+
brushOffset[k] = brushDz[k] * n + brushDx[k];
|
|
376
|
+
const obsFlow = observations?.flow;
|
|
377
|
+
const obsSediment = observations?.sediment;
|
|
378
|
+
const obsDeposition = observations?.deposition;
|
|
379
|
+
const spread = (x, z, amount, floor = Number.NEGATIVE_INFINITY) => {
|
|
380
|
+
if (amount === 0) return 0;
|
|
381
|
+
const interior = x >= brushEdge && x < n - brushEdge && z >= brushEdge && z < n - brushEdge;
|
|
382
|
+
if (interior) {
|
|
383
|
+
const total2 = brushFull;
|
|
384
|
+
if (total2 <= 0) return 0;
|
|
385
|
+
const base = z * n + x;
|
|
386
|
+
if (amount < 0) {
|
|
387
|
+
let moved = 0;
|
|
388
|
+
for (let k = 0; k < brushCount; k += 1) {
|
|
389
|
+
const i = base + brushOffset[k];
|
|
390
|
+
const share2 = amount * brushWeight[k] / total2;
|
|
391
|
+
const avail = h[i] - floor;
|
|
392
|
+
const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
|
|
393
|
+
h[i] = h[i] + change;
|
|
394
|
+
moved += change;
|
|
395
|
+
}
|
|
396
|
+
return moved;
|
|
397
|
+
}
|
|
398
|
+
if (obsDeposition !== void 0) {
|
|
399
|
+
for (let k = 0; k < brushCount; k += 1) {
|
|
400
|
+
const i = base + brushOffset[k];
|
|
401
|
+
const share2 = amount * brushWeight[k] / total2;
|
|
402
|
+
h[i] = h[i] + share2;
|
|
403
|
+
obsDeposition[i] = obsDeposition[i] + share2;
|
|
404
|
+
}
|
|
405
|
+
} else {
|
|
406
|
+
for (let k = 0; k < brushCount; k += 1) {
|
|
407
|
+
const i = base + brushOffset[k];
|
|
408
|
+
const share2 = amount * brushWeight[k] / total2;
|
|
409
|
+
h[i] = h[i] + share2;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return amount;
|
|
413
|
+
}
|
|
414
|
+
let total = 0;
|
|
415
|
+
for (let k = 0; k < brushCount; k += 1) {
|
|
416
|
+
const ix = x + brushDx[k];
|
|
417
|
+
const iz = z + brushDz[k];
|
|
418
|
+
if (ix >= 0 && ix < n && iz >= 0 && iz < n) total += brushWeight[k];
|
|
419
|
+
}
|
|
420
|
+
if (total <= 0) return 0;
|
|
421
|
+
if (amount < 0) {
|
|
422
|
+
let moved = 0;
|
|
423
|
+
for (let k = 0; k < brushCount; k += 1) {
|
|
424
|
+
const ix = x + brushDx[k];
|
|
425
|
+
const iz = z + brushDz[k];
|
|
426
|
+
if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
|
|
427
|
+
const i = iz * n + ix;
|
|
428
|
+
const share2 = amount * brushWeight[k] / total;
|
|
429
|
+
const avail = h[i] - floor;
|
|
430
|
+
const change = avail <= 0 ? -0 : -share2 < avail ? share2 : -avail;
|
|
431
|
+
h[i] = h[i] + change;
|
|
432
|
+
moved += change;
|
|
433
|
+
}
|
|
434
|
+
return moved;
|
|
435
|
+
}
|
|
436
|
+
if (obsDeposition !== void 0) {
|
|
437
|
+
for (let k = 0; k < brushCount; k += 1) {
|
|
438
|
+
const ix = x + brushDx[k];
|
|
439
|
+
const iz = z + brushDz[k];
|
|
440
|
+
if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
|
|
441
|
+
const i = iz * n + ix;
|
|
442
|
+
const share2 = amount * brushWeight[k] / total;
|
|
443
|
+
h[i] = h[i] + share2;
|
|
444
|
+
obsDeposition[i] = obsDeposition[i] + share2;
|
|
445
|
+
}
|
|
446
|
+
} else {
|
|
447
|
+
for (let k = 0; k < brushCount; k += 1) {
|
|
448
|
+
const ix = x + brushDx[k];
|
|
449
|
+
const iz = z + brushDz[k];
|
|
450
|
+
if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
|
|
451
|
+
const i = iz * n + ix;
|
|
452
|
+
const share2 = amount * brushWeight[k] / total;
|
|
453
|
+
h[i] = h[i] + share2;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return amount;
|
|
457
|
+
};
|
|
458
|
+
const probeOld = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
|
|
459
|
+
const probeNext = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
|
|
460
|
+
const get = (x, z, out) => {
|
|
461
|
+
const ix = Math.min(n - 2, Math.floor(x));
|
|
462
|
+
const iz = Math.min(n - 2, Math.floor(z));
|
|
463
|
+
const tx = x - ix;
|
|
464
|
+
const tz = z - iz;
|
|
465
|
+
const i = iz * n + ix;
|
|
466
|
+
const h00 = h[i];
|
|
467
|
+
const h10 = h[i + 1];
|
|
468
|
+
const h01 = h[i + n];
|
|
469
|
+
const h11 = h[i + n + 1];
|
|
470
|
+
const g10 = h10 - h00;
|
|
471
|
+
const g01 = h01 - h00;
|
|
472
|
+
const v0 = h00 + g10 * tx;
|
|
473
|
+
const v1 = h01 + (h11 - h01) * tx;
|
|
474
|
+
out.value = v0 + (v1 - v0) * tz;
|
|
475
|
+
out.dx = (g10 + (h11 - h01 - g10) * tz) / cell;
|
|
476
|
+
out.dz = (g01 + (h11 - h10 - g01) * tx) / cell;
|
|
477
|
+
out.ix = ix;
|
|
478
|
+
out.iz = iz;
|
|
479
|
+
return out;
|
|
480
|
+
};
|
|
481
|
+
for (let k = 0; k < droplets; k += 1) {
|
|
482
|
+
let x = rnd() * (n - 1 - 1e-3);
|
|
483
|
+
let z = rnd() * (n - 1 - 1e-3);
|
|
484
|
+
let dx = 0;
|
|
485
|
+
let dz = 0;
|
|
486
|
+
let water2 = 1;
|
|
487
|
+
let speed = 1;
|
|
488
|
+
let sediment = 0;
|
|
489
|
+
for (let step = 0; step < maxSteps; step += 1) {
|
|
490
|
+
const old = get(x, z, probeOld);
|
|
491
|
+
if (obsFlow !== void 0 && obsSediment !== void 0) {
|
|
492
|
+
const tx = x - old.ix;
|
|
493
|
+
const tz = z - old.iz;
|
|
494
|
+
const i = old.iz * n + old.ix;
|
|
495
|
+
const w00 = (1 - tx) * (1 - tz);
|
|
496
|
+
const w10 = tx * (1 - tz);
|
|
497
|
+
const w01 = (1 - tx) * tz;
|
|
498
|
+
const w11 = tx * tz;
|
|
499
|
+
obsFlow[i] = obsFlow[i] + water2 * w00;
|
|
500
|
+
obsSediment[i] = obsSediment[i] + sediment * w00;
|
|
501
|
+
obsFlow[i + 1] = obsFlow[i + 1] + water2 * w10;
|
|
502
|
+
obsSediment[i + 1] = obsSediment[i + 1] + sediment * w10;
|
|
503
|
+
obsFlow[i + n] = obsFlow[i + n] + water2 * w01;
|
|
504
|
+
obsSediment[i + n] = obsSediment[i + n] + sediment * w01;
|
|
505
|
+
obsFlow[i + n + 1] = obsFlow[i + n + 1] + water2 * w11;
|
|
506
|
+
obsSediment[i + n + 1] = obsSediment[i + n + 1] + sediment * w11;
|
|
507
|
+
}
|
|
508
|
+
dx = dx * inertia - old.dx * oneMinusInertia;
|
|
509
|
+
dz = dz * inertia - old.dz * oneMinusInertia;
|
|
510
|
+
const largest = Math.max(Math.abs(dx), Math.abs(dz));
|
|
511
|
+
const scaledX = Math.abs(dx) / largest;
|
|
512
|
+
const scaledZ = Math.abs(dz) / largest;
|
|
513
|
+
let length = largest === 0 || largest === Number.POSITIVE_INFINITY ? largest : Math.sqrt(scaledX * scaledX + scaledZ * scaledZ) * largest;
|
|
514
|
+
if (length < 1e-9) {
|
|
515
|
+
const angle = rnd() * Math.PI * 2;
|
|
516
|
+
dx = Math.cos(angle);
|
|
517
|
+
dz = Math.sin(angle);
|
|
518
|
+
length = 1;
|
|
519
|
+
}
|
|
520
|
+
dx /= length;
|
|
521
|
+
dz /= length;
|
|
522
|
+
const nx = x + dx;
|
|
523
|
+
const nz = z + dz;
|
|
524
|
+
if (nx < 0 || nx >= n - 1 || nz < 0 || nz >= n - 1) {
|
|
525
|
+
sediment = 0;
|
|
526
|
+
break;
|
|
527
|
+
}
|
|
528
|
+
const next = get(nx, nz, probeNext);
|
|
529
|
+
const dh = next.value - old.value;
|
|
530
|
+
const slope = -dh;
|
|
531
|
+
const cap = (slope > minSlope ? slope : minSlope) * speed * water2 * capacity;
|
|
532
|
+
if (dh > 0 || sediment > cap) {
|
|
533
|
+
const amount = dh > 0 ? dh < sediment ? dh : sediment : (sediment - cap) * deposition;
|
|
534
|
+
spread(old.ix, old.iz, amount);
|
|
535
|
+
sediment -= amount;
|
|
536
|
+
} else {
|
|
537
|
+
const bite = (cap - sediment) * erosion;
|
|
538
|
+
const amount = bite < slope ? bite : slope;
|
|
539
|
+
sediment -= spread(old.ix, old.iz, -amount, next.value);
|
|
540
|
+
}
|
|
541
|
+
const sq = speed * speed - dh * 3;
|
|
542
|
+
speed = Math.sqrt(sq > 0.01 ? sq : 0.01);
|
|
543
|
+
water2 *= oneMinusEvaporation;
|
|
544
|
+
x = nx;
|
|
545
|
+
z = nz;
|
|
546
|
+
if (water2 < 0.02) break;
|
|
547
|
+
}
|
|
548
|
+
if (sediment > 0 && water2 < 0.02) {
|
|
549
|
+
const end = get(clamp(x, 0, n - 1.001), clamp(z, 0, n - 1.001), probeOld);
|
|
550
|
+
spread(end.ix, end.iz, sediment);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
return Float32Array.from(h);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// src/core/fluvial.ts
|
|
557
|
+
var DX = Int8Array.of(-1, 0, 1, -1, 1, -1, 0, 1);
|
|
558
|
+
var DZ = Int8Array.of(-1, -1, -1, 0, 0, 1, 1, 1);
|
|
559
|
+
var DIST = Float64Array.from(DX, (dx, k) => Math.hypot(dx, DZ[k]));
|
|
560
|
+
var FILL_SLOPE = Math.tan(0.06 * Math.PI / 180);
|
|
561
|
+
var EPSILON = 1e-3;
|
|
562
|
+
function fillDepressions(h, n, epsilon = EPSILON) {
|
|
563
|
+
const total = n * n;
|
|
564
|
+
const keys = new Float64Array(total);
|
|
565
|
+
const cells = new Int32Array(total);
|
|
566
|
+
const closed2 = new Uint8Array(total);
|
|
567
|
+
let size = 0;
|
|
568
|
+
const push = (key, cell) => {
|
|
569
|
+
let k = size++;
|
|
570
|
+
while (k > 0) {
|
|
571
|
+
const parent = k - 1 >> 1;
|
|
572
|
+
if (keys[parent] <= key) break;
|
|
573
|
+
keys[k] = keys[parent];
|
|
574
|
+
cells[k] = cells[parent];
|
|
575
|
+
k = parent;
|
|
576
|
+
}
|
|
577
|
+
keys[k] = key;
|
|
578
|
+
cells[k] = cell;
|
|
579
|
+
};
|
|
580
|
+
const pop = () => {
|
|
581
|
+
const top = cells[0];
|
|
582
|
+
size -= 1;
|
|
583
|
+
const key = keys[size];
|
|
584
|
+
const cell = cells[size];
|
|
585
|
+
let k = 0;
|
|
586
|
+
for (; ; ) {
|
|
587
|
+
let child = 2 * k + 1;
|
|
588
|
+
if (child >= size) break;
|
|
589
|
+
if (child + 1 < size && keys[child + 1] < keys[child]) child += 1;
|
|
590
|
+
if (keys[child] >= key) break;
|
|
591
|
+
keys[k] = keys[child];
|
|
592
|
+
cells[k] = cells[child];
|
|
593
|
+
k = child;
|
|
594
|
+
}
|
|
595
|
+
keys[k] = key;
|
|
596
|
+
cells[k] = cell;
|
|
597
|
+
return top;
|
|
598
|
+
};
|
|
599
|
+
for (let z = 0; z < n; z += 1) {
|
|
600
|
+
for (let x = 0; x < n; x += 1) {
|
|
601
|
+
if (x > 0 && x < n - 1 && z > 0 && z < n - 1) continue;
|
|
602
|
+
const i = z * n + x;
|
|
603
|
+
closed2[i] = 1;
|
|
604
|
+
push(h[i], i);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
while (size > 0) {
|
|
608
|
+
const c = pop();
|
|
609
|
+
const cx = c % n;
|
|
610
|
+
const cz = (c - cx) / n;
|
|
611
|
+
const level = h[c];
|
|
612
|
+
for (let k = 0; k < 8; k += 1) {
|
|
613
|
+
const x = cx + DX[k];
|
|
614
|
+
const z = cz + DZ[k];
|
|
615
|
+
if (x < 0 || z < 0 || x >= n || z >= n) continue;
|
|
616
|
+
const j = z * n + x;
|
|
617
|
+
if (closed2[j]) continue;
|
|
618
|
+
closed2[j] = 1;
|
|
619
|
+
if (h[j] <= level) h[j] = level + epsilon;
|
|
620
|
+
push(h[j], j);
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
function createFlow(n) {
|
|
625
|
+
const total = n * n;
|
|
626
|
+
return {
|
|
627
|
+
receiver: new Int32Array(total),
|
|
628
|
+
order: new Int32Array(total),
|
|
629
|
+
cells: new Float64Array(total)
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
function routeFlow(h, n, flow) {
|
|
633
|
+
const { receiver, order, cells } = flow;
|
|
634
|
+
const total = n * n;
|
|
635
|
+
const head = new Int32Array(total).fill(-1);
|
|
636
|
+
const next = new Int32Array(total);
|
|
637
|
+
let roots = 0;
|
|
638
|
+
for (let z = 0; z < n; z += 1) {
|
|
639
|
+
for (let x = 0; x < n; x += 1) {
|
|
640
|
+
const i = z * n + x;
|
|
641
|
+
let best = -1;
|
|
642
|
+
if (x > 0 && x < n - 1 && z > 0 && z < n - 1) {
|
|
643
|
+
const here = h[i];
|
|
644
|
+
let bestSlope = 0;
|
|
645
|
+
for (let k = 0; k < 8; k += 1) {
|
|
646
|
+
const j = i + DZ[k] * n + DX[k];
|
|
647
|
+
const slope = (here - h[j]) / DIST[k];
|
|
648
|
+
if (slope > bestSlope) {
|
|
649
|
+
bestSlope = slope;
|
|
650
|
+
best = j;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
receiver[i] = best;
|
|
655
|
+
if (best < 0) order[roots++] = i;
|
|
656
|
+
else {
|
|
657
|
+
next[i] = head[best];
|
|
658
|
+
head[best] = i;
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
for (let k = 0; k < total; k += 1) {
|
|
663
|
+
const i = order[k];
|
|
664
|
+
for (let d = head[i]; d >= 0; d = next[d]) order[roots++] = d;
|
|
665
|
+
}
|
|
666
|
+
cells.fill(1);
|
|
667
|
+
for (let k = total - 1; k >= 0; k -= 1) {
|
|
668
|
+
const i = order[k];
|
|
669
|
+
const r = receiver[i];
|
|
670
|
+
if (r >= 0) cells[r] = cells[r] + cells[i];
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
function fluvial(height, n, size, {
|
|
674
|
+
iterations = 40,
|
|
675
|
+
uplift = 1e-3,
|
|
676
|
+
erodibility = 5e-6,
|
|
677
|
+
timeStep = 2e4,
|
|
678
|
+
concavity = 0.45,
|
|
679
|
+
talus = 35,
|
|
680
|
+
relief
|
|
681
|
+
} = {}) {
|
|
682
|
+
const total = n * n;
|
|
683
|
+
const spacing = size / (n - 1);
|
|
684
|
+
const h = Float64Array.from(height);
|
|
685
|
+
const band2 = Math.min(4, n - 1);
|
|
686
|
+
for (let a = 0; a < n; a += 1)
|
|
687
|
+
for (let d = 1; d <= band2; d += 1) {
|
|
688
|
+
h[a] = Math.min(h[a], h[d * n + a]);
|
|
689
|
+
h[(n - 1) * n + a] = Math.min(h[(n - 1) * n + a], h[(n - 1 - d) * n + a]);
|
|
690
|
+
h[a * n] = Math.min(h[a * n], h[a * n + d]);
|
|
691
|
+
h[a * n + n - 1] = Math.min(h[a * n + n - 1], h[a * n + n - 1 - d]);
|
|
692
|
+
}
|
|
693
|
+
fillDepressions(h, n, FILL_SLOPE * spacing);
|
|
694
|
+
let low = Number.POSITIVE_INFINITY;
|
|
695
|
+
let high = Number.NEGATIVE_INFINITY;
|
|
696
|
+
for (let i = 0; i < total; i += 1) {
|
|
697
|
+
low = Math.min(low, h[i]);
|
|
698
|
+
high = Math.max(high, h[i]);
|
|
699
|
+
}
|
|
700
|
+
const range2 = high - low || 1;
|
|
701
|
+
const rise = Float64Array.from(h, (v) => uplift * timeStep * (v - low) / range2);
|
|
702
|
+
const flow = createFlow(n);
|
|
703
|
+
const kdt = erodibility * timeStep;
|
|
704
|
+
const maxRise = Math.tan(talus * Math.PI / 180) * spacing;
|
|
705
|
+
const power = Float64Array.from(
|
|
706
|
+
{ length: total + 1 },
|
|
707
|
+
(_, c) => (c * spacing * spacing) ** concavity
|
|
708
|
+
);
|
|
709
|
+
for (let step = 0; step < iterations; step += 1) {
|
|
710
|
+
routeFlow(h, n, flow);
|
|
711
|
+
const { order, receiver, cells } = flow;
|
|
712
|
+
for (let k = 0; k < total; k += 1) {
|
|
713
|
+
const i = order[k];
|
|
714
|
+
const r = receiver[i];
|
|
715
|
+
if (r < 0) continue;
|
|
716
|
+
const delta = Math.abs(r - i);
|
|
717
|
+
const run = delta === 1 || delta === n ? 1 : Math.SQRT2;
|
|
718
|
+
const factor = kdt * power[cells[i]] / (spacing * run);
|
|
719
|
+
const below = h[r];
|
|
720
|
+
const solved = (h[i] + rise[i] + factor * below) / (1 + factor);
|
|
721
|
+
h[i] = Math.max(Math.min(solved, below + maxRise * run), below + EPSILON);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
for (let a = 0; a < n; a += 1) {
|
|
725
|
+
h[a] = h[n + a];
|
|
726
|
+
h[(n - 1) * n + a] = h[(n - 2) * n + a];
|
|
727
|
+
}
|
|
728
|
+
for (let a = 0; a < n; a += 1) {
|
|
729
|
+
h[a * n] = h[a * n + 1];
|
|
730
|
+
h[a * n + n - 1] = h[a * n + n - 2];
|
|
731
|
+
}
|
|
732
|
+
if (relief !== void 0) {
|
|
733
|
+
let lo = Number.POSITIVE_INFINITY;
|
|
734
|
+
let hi = Number.NEGATIVE_INFINITY;
|
|
735
|
+
for (const v of h) {
|
|
736
|
+
lo = Math.min(lo, v);
|
|
737
|
+
hi = Math.max(hi, v);
|
|
738
|
+
}
|
|
739
|
+
const gain = relief / (hi - lo || 1);
|
|
740
|
+
for (let i = 0; i < total; i += 1) h[i] = lo + (h[i] - lo) * gain;
|
|
741
|
+
}
|
|
742
|
+
return Float32Array.from(h);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// src/core/masks.ts
|
|
746
|
+
var MATERIAL_IDS = Object.freeze([
|
|
747
|
+
"grass",
|
|
748
|
+
"dirt",
|
|
749
|
+
"rock",
|
|
750
|
+
"snow",
|
|
751
|
+
"sand",
|
|
752
|
+
"mud",
|
|
753
|
+
"road",
|
|
754
|
+
"moss"
|
|
755
|
+
]);
|
|
756
|
+
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);
|
|
757
|
+
function compileMask(mask, s) {
|
|
758
|
+
if (!mask || mask.type === "all") return () => 1;
|
|
759
|
+
switch (mask.type) {
|
|
760
|
+
case "none":
|
|
761
|
+
return () => 0;
|
|
762
|
+
case "circle": {
|
|
763
|
+
const centre = mask.at;
|
|
764
|
+
return (i, x, z) => falloff(
|
|
765
|
+
Math.hypot(x - centre[0], z - centre[1]),
|
|
766
|
+
mask.radius,
|
|
767
|
+
mask.falloff ?? 0.6
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
case "rectangle": {
|
|
771
|
+
const centre = mask.at;
|
|
772
|
+
const rad = (mask.rotation ?? 0) * Math.PI / 180;
|
|
773
|
+
const c = Math.cos(rad);
|
|
774
|
+
const sn = Math.sin(rad);
|
|
775
|
+
const size = Array.isArray(mask.size) ? mask.size : [mask.size, mask.size];
|
|
776
|
+
return (i, x, z) => {
|
|
777
|
+
const dx = x - centre[0];
|
|
778
|
+
const dz = z - centre[1];
|
|
779
|
+
return falloff(
|
|
780
|
+
Math.max(
|
|
781
|
+
Math.abs(dx * c + dz * sn) / (size[0] / 2),
|
|
782
|
+
Math.abs(-dx * sn + dz * c) / (size[1] / 2)
|
|
783
|
+
),
|
|
784
|
+
1,
|
|
785
|
+
mask.falloff ?? 0.2
|
|
786
|
+
);
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
case "height":
|
|
790
|
+
return (i) => range(s.height[i], mask.min ?? -1e9, mask.max ?? 1e9, mask.fade);
|
|
791
|
+
case "slope":
|
|
792
|
+
return (i) => range(slopeAtIndex(s, i), mask.min ?? 0, mask.max ?? 90, mask.fade);
|
|
793
|
+
case "noise":
|
|
794
|
+
return (i, x, z) => smoothstep(
|
|
795
|
+
(mask.threshold ?? 0.5) - (mask.fade ?? 0.15),
|
|
796
|
+
(mask.threshold ?? 0.5) + (mask.fade ?? 0.15),
|
|
797
|
+
noise2(x / mask.scale, z / mask.scale, mask.seed ?? s.seed) * 0.5 + 0.5
|
|
798
|
+
);
|
|
799
|
+
case "biome": {
|
|
800
|
+
const field = s.biomes[mask.name];
|
|
801
|
+
return (i) => field?.[i] ?? 0;
|
|
802
|
+
}
|
|
803
|
+
case "material": {
|
|
804
|
+
const channel = MATERIAL_IDS.indexOf(mask.name);
|
|
805
|
+
if (channel < 0) throw Error(`Unknown material: ${String(mask.name)}`);
|
|
806
|
+
return (i) => s.splat[i * 8 + channel];
|
|
807
|
+
}
|
|
808
|
+
case "not": {
|
|
809
|
+
const inner = compileMask(mask.mask, s);
|
|
810
|
+
return (i, x, z) => 1 - inner(i, x, z);
|
|
811
|
+
}
|
|
812
|
+
case "and": {
|
|
813
|
+
const inner = (mask.masks ?? []).map((entry2) => compileMask(entry2, s));
|
|
814
|
+
return (i, x, z) => inner.reduce((value, sample) => value * sample(i, x, z), 1);
|
|
815
|
+
}
|
|
816
|
+
case "or": {
|
|
817
|
+
const inner = (mask.masks ?? []).map((entry2) => compileMask(entry2, s));
|
|
818
|
+
return (i, x, z) => 1 - inner.reduce((value, sample) => value * (1 - sample(i, x, z)), 1);
|
|
819
|
+
}
|
|
820
|
+
default:
|
|
821
|
+
throw Error(`Unknown mask: ${String(mask.type)}`);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
function rasterMask(mask, s) {
|
|
825
|
+
if (!mask || mask.type === "all") return null;
|
|
826
|
+
const out = new Float32Array(s.height.length);
|
|
827
|
+
const sample = compileMask(mask, s);
|
|
828
|
+
for (let z = 0; z < s.resolution; z += 1) {
|
|
829
|
+
for (let x = 0; x < s.resolution; x += 1) {
|
|
830
|
+
const i = z * s.resolution + x;
|
|
831
|
+
out[i] = clamp(sample(i, world(s, x), world(s, z)));
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
return out;
|
|
835
|
+
}
|
|
836
|
+
function paintWeights(s, i, channel, weight) {
|
|
837
|
+
const w = clamp(weight);
|
|
838
|
+
const base = i * 8;
|
|
839
|
+
for (let c = 0; c < 8; c += 1)
|
|
840
|
+
s.splat[base + c] = s.splat[base + c] * (1 - w) + (c === channel ? w : 0);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// src/core/operations.ts
|
|
844
|
+
var OPERATION_TYPES = Object.freeze([
|
|
845
|
+
"noise",
|
|
846
|
+
"sculpt",
|
|
847
|
+
"smooth",
|
|
848
|
+
"flatten",
|
|
849
|
+
"ramp",
|
|
850
|
+
"stamp",
|
|
851
|
+
"erode",
|
|
852
|
+
"terrace",
|
|
853
|
+
"materials",
|
|
854
|
+
"paint",
|
|
855
|
+
"biome",
|
|
856
|
+
"scatter",
|
|
857
|
+
"clear",
|
|
858
|
+
"road",
|
|
859
|
+
"river",
|
|
860
|
+
"water",
|
|
861
|
+
"heightmap",
|
|
862
|
+
"paste"
|
|
863
|
+
]);
|
|
864
|
+
function createState(config, resolution = config.resolution) {
|
|
865
|
+
const height = new Float32Array(resolution * resolution);
|
|
866
|
+
const splat = new Float32Array(height.length * 8);
|
|
867
|
+
for (let i = 0; i < height.length; i += 1) splat[i * 8] = 1;
|
|
868
|
+
return {
|
|
869
|
+
size: config.size,
|
|
870
|
+
resolution,
|
|
871
|
+
seed: config.seed,
|
|
872
|
+
height,
|
|
873
|
+
splat,
|
|
874
|
+
biomes: {},
|
|
875
|
+
scatterRules: [],
|
|
876
|
+
waterRules: [],
|
|
877
|
+
rivers: [],
|
|
878
|
+
instances: [],
|
|
879
|
+
waters: [],
|
|
880
|
+
diagnostics: []
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
function brushCenters(p, seed) {
|
|
884
|
+
const source = p.points ?? (p.at ? [p.at] : null);
|
|
885
|
+
if (!source) return null;
|
|
886
|
+
const radius = p.radius ?? 30;
|
|
887
|
+
const first = source[0];
|
|
888
|
+
if (!first) return null;
|
|
889
|
+
const out = [[first[0], first[1]]];
|
|
890
|
+
const step = Math.max(0.1, radius * 2 * (p.spacing ?? 0.15));
|
|
891
|
+
for (let k = 1; k < source.length; k += 1) {
|
|
892
|
+
const a = source[k - 1];
|
|
893
|
+
const b = source[k];
|
|
894
|
+
const count2 = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / step));
|
|
895
|
+
for (let j = 1; j <= count2; j += 1)
|
|
896
|
+
out.push([lerp(a[0], b[0], j / count2), lerp(a[1], b[1], j / count2)]);
|
|
897
|
+
}
|
|
898
|
+
if (p.jitter) {
|
|
899
|
+
const rnd = random(seed);
|
|
900
|
+
for (const centre of out) {
|
|
901
|
+
const angle = rnd() * Math.PI * 2;
|
|
902
|
+
const offset = Math.sqrt(rnd()) * p.jitter * radius;
|
|
903
|
+
centre[0] += Math.cos(angle) * offset;
|
|
904
|
+
centre[1] += Math.sin(angle) * offset;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
return out;
|
|
908
|
+
}
|
|
909
|
+
function brushWeights(s, p, mask, seed) {
|
|
910
|
+
const centers = brushCenters(p, seed);
|
|
911
|
+
if (!centers) return mask ?? new Float32Array(s.height.length).fill(1);
|
|
912
|
+
const n = s.resolution;
|
|
913
|
+
const r = p.radius ?? 30;
|
|
914
|
+
const cell = s.size / (n - 1);
|
|
915
|
+
const weights = new Float32Array(n * n);
|
|
916
|
+
const angle = (p.rotation ?? 0) * Math.PI / 180;
|
|
917
|
+
const cos = Math.cos(angle);
|
|
918
|
+
const sin = Math.sin(angle);
|
|
919
|
+
const bound = r * (p.shape === "square" ? Math.SQRT2 : 1);
|
|
920
|
+
for (const [cx, cz] of centers) {
|
|
921
|
+
const x0 = clamp(Math.floor((cx - bound + s.size / 2) / cell), 0, n - 1);
|
|
922
|
+
const x1 = clamp(Math.ceil((cx + bound + s.size / 2) / cell), 0, n - 1);
|
|
923
|
+
const z0 = clamp(Math.floor((cz - bound + s.size / 2) / cell), 0, n - 1);
|
|
924
|
+
const z1 = clamp(Math.ceil((cz + bound + s.size / 2) / cell), 0, n - 1);
|
|
925
|
+
for (let z = z0; z <= z1; z += 1) {
|
|
926
|
+
for (let x = x0; x <= x1; x += 1) {
|
|
927
|
+
const dx = world(s, x) - cx;
|
|
928
|
+
const dz = world(s, z) - cz;
|
|
929
|
+
const distance = p.shape === "square" ? Math.max(Math.abs(dx * cos + dz * sin), Math.abs(-dx * sin + dz * cos)) : Math.hypot(dx, dz);
|
|
930
|
+
const i = z * n + x;
|
|
931
|
+
weights[i] = Math.max(
|
|
932
|
+
weights[i],
|
|
933
|
+
falloff(distance, r, p.falloff ?? 0.6) * (mask?.[i] ?? 1)
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return weights;
|
|
939
|
+
}
|
|
940
|
+
function followsTerrain(source, followTerrain) {
|
|
941
|
+
return followTerrain ?? source.some((point) => !Number.isFinite(point[1]));
|
|
942
|
+
}
|
|
943
|
+
function gradeToGround(s, points, p) {
|
|
944
|
+
const at = (k) => points[k];
|
|
945
|
+
const run = (k) => {
|
|
946
|
+
const a = at(k - 1);
|
|
947
|
+
const b = at(k);
|
|
948
|
+
return Math.hypot(b[0] - a[0], b[2] - a[2]);
|
|
949
|
+
};
|
|
950
|
+
const bed = points.map(([x, , z]) => sampleHeight(s, x, z));
|
|
951
|
+
let spacing = 0;
|
|
952
|
+
for (let k = 1; k < points.length && spacing === 0; k += 1) spacing = run(k);
|
|
953
|
+
spacing ||= 3;
|
|
954
|
+
const window = Math.max(1, Math.round(Math.max(8, p.width ?? 12) / spacing));
|
|
955
|
+
const profile = bed.slice();
|
|
956
|
+
for (let pass = 0; pass < 2; pass += 1) {
|
|
957
|
+
const next = profile.slice();
|
|
958
|
+
for (let k = 0; k < profile.length; k += 1) {
|
|
959
|
+
let sum = 0;
|
|
960
|
+
let count2 = 0;
|
|
961
|
+
for (let j = Math.max(0, k - window); j <= Math.min(profile.length - 1, k + window); j += 1) {
|
|
962
|
+
sum += profile[j];
|
|
963
|
+
count2 += 1;
|
|
964
|
+
}
|
|
965
|
+
next[k] = sum / count2;
|
|
966
|
+
}
|
|
967
|
+
for (let k = 0; k < profile.length; k += 1) profile[k] = next[k];
|
|
968
|
+
}
|
|
969
|
+
const maxCut = p.maxCut ?? 2.5;
|
|
970
|
+
const maxFill = p.maxFill ?? 1.5;
|
|
971
|
+
const grade2 = p.maxGrade ?? 0.12;
|
|
972
|
+
const limit = (k) => grade2 * Math.max(0.5, run(k));
|
|
973
|
+
for (let round = 0; round < 16; round += 1) {
|
|
974
|
+
let moved = 0;
|
|
975
|
+
for (let k = 1; k < profile.length; k += 1) {
|
|
976
|
+
const y = clamp(
|
|
977
|
+
profile[k],
|
|
978
|
+
profile[k - 1] - limit(k),
|
|
979
|
+
profile[k - 1] + limit(k)
|
|
980
|
+
);
|
|
981
|
+
moved += Math.abs(y - profile[k]);
|
|
982
|
+
profile[k] = y;
|
|
983
|
+
}
|
|
984
|
+
for (let k = profile.length - 2; k >= 0; k -= 1) {
|
|
985
|
+
const y = clamp(
|
|
986
|
+
profile[k],
|
|
987
|
+
profile[k + 1] - limit(k + 1),
|
|
988
|
+
profile[k + 1] + limit(k + 1)
|
|
989
|
+
);
|
|
990
|
+
moved += Math.abs(y - profile[k]);
|
|
991
|
+
profile[k] = y;
|
|
992
|
+
}
|
|
993
|
+
if (moved < 1e-4) break;
|
|
994
|
+
}
|
|
995
|
+
for (let k = 0; k < profile.length; k += 1)
|
|
996
|
+
profile[k] = clamp(
|
|
997
|
+
profile[k],
|
|
998
|
+
bed[k] - maxCut,
|
|
999
|
+
bed[k] + maxFill
|
|
1000
|
+
);
|
|
1001
|
+
for (let k = 0; k < points.length; k += 1) at(k)[1] = profile[k];
|
|
1002
|
+
}
|
|
1003
|
+
function applySpline(s, layer2, mask) {
|
|
1004
|
+
const p = layer2.params;
|
|
1005
|
+
const river = layer2.type === "river";
|
|
1006
|
+
const ramp = layer2.type === "ramp";
|
|
1007
|
+
const seed = p.seed ?? s.seed;
|
|
1008
|
+
const raw = ramp ? [p.from, p.to] : p.points ?? [];
|
|
1009
|
+
const follows = followsTerrain(raw, p.followTerrain);
|
|
1010
|
+
const source = raw.map(
|
|
1011
|
+
([x, y, z]) => [x, Number.isFinite(y) ? y : 0, z]
|
|
1012
|
+
);
|
|
1013
|
+
const points = splinePoints(
|
|
1014
|
+
source,
|
|
1015
|
+
Math.max(1, (p.width ?? 12) * 0.22),
|
|
1016
|
+
!ramp && p.smooth !== false
|
|
1017
|
+
);
|
|
1018
|
+
if (follows) gradeToGround(s, points, p);
|
|
1019
|
+
const half = (p.width ?? 12) / 2;
|
|
1020
|
+
const shoulder = p.shoulder ?? half;
|
|
1021
|
+
const extent = half + shoulder;
|
|
1022
|
+
const depth = p.depth ?? 4;
|
|
1023
|
+
const alpha = layer2.opacity ?? 1;
|
|
1024
|
+
const n = s.resolution;
|
|
1025
|
+
const cell = s.size / (n - 1);
|
|
1026
|
+
const dist = new Float32Array(n * n).fill(Number.POSITIVE_INFINITY);
|
|
1027
|
+
const target = new Float32Array(n * n);
|
|
1028
|
+
const bed = new Float32Array(n * n);
|
|
1029
|
+
const floor = river ? 1.5 * depth : 0;
|
|
1030
|
+
let reach = extent;
|
|
1031
|
+
const raster = () => {
|
|
1032
|
+
dist.fill(Number.POSITIVE_INFINITY);
|
|
1033
|
+
for (let k = 1; k < points.length; k += 1) {
|
|
1034
|
+
const a = points[k - 1];
|
|
1035
|
+
const b = points[k];
|
|
1036
|
+
const dx = b[0] - a[0];
|
|
1037
|
+
const dz = b[2] - a[2];
|
|
1038
|
+
const den = dx * dx + dz * dz;
|
|
1039
|
+
if (den < 1e-12) continue;
|
|
1040
|
+
const xmin = clamp(Math.floor((Math.min(a[0], b[0]) - reach + s.size / 2) / cell), 0, n - 1);
|
|
1041
|
+
const xmax = clamp(Math.ceil((Math.max(a[0], b[0]) + reach + s.size / 2) / cell), 0, n - 1);
|
|
1042
|
+
const zmin = clamp(Math.floor((Math.min(a[2], b[2]) - reach + s.size / 2) / cell), 0, n - 1);
|
|
1043
|
+
const zmax = clamp(Math.ceil((Math.max(a[2], b[2]) + reach + s.size / 2) / cell), 0, n - 1);
|
|
1044
|
+
for (let z = zmin; z <= zmax; z += 1) {
|
|
1045
|
+
for (let x = xmin; x <= xmax; x += 1) {
|
|
1046
|
+
const wx = world(s, x);
|
|
1047
|
+
const wz = world(s, z);
|
|
1048
|
+
const t = clamp(((wx - a[0]) * dx + (wz - a[2]) * dz) / den);
|
|
1049
|
+
const d = Math.hypot(wx - a[0] - t * dx, wz - a[2] - t * dz);
|
|
1050
|
+
const i = z * n + x;
|
|
1051
|
+
if (d < dist[i]) {
|
|
1052
|
+
dist[i] = d;
|
|
1053
|
+
target[i] = lerp(a[1], b[1], t);
|
|
1054
|
+
bed[i] = s.height[i];
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
raster();
|
|
1061
|
+
let worst = 0;
|
|
1062
|
+
for (let i = 0; i < dist.length; i += 1)
|
|
1063
|
+
if (dist[i] <= extent)
|
|
1064
|
+
worst = Math.max(worst, Math.abs(target[i] - bed[i]));
|
|
1065
|
+
if (floor + 1.5 * worst > 0.05) {
|
|
1066
|
+
reach = extent + floor + 1.5 * worst;
|
|
1067
|
+
raster();
|
|
1068
|
+
}
|
|
1069
|
+
const material = MATERIAL_IDS.indexOf(p.material ?? (river ? "mud" : "road"));
|
|
1070
|
+
for (let i = 0; i < s.height.length; i += 1) {
|
|
1071
|
+
const d = dist[i];
|
|
1072
|
+
if (d > reach) continue;
|
|
1073
|
+
const pre = bed[i];
|
|
1074
|
+
const edge = Math.min(reach, extent + floor + 1.5 * Math.abs(target[i] - pre));
|
|
1075
|
+
const blend = 1 - smoothstep(half, edge, d);
|
|
1076
|
+
const w = blend * blend * (mask?.[i] ?? 1) * alpha;
|
|
1077
|
+
let y = target[i];
|
|
1078
|
+
if (river) {
|
|
1079
|
+
const bowl = 1 - 0.35 * clamp(d / half) ** 2;
|
|
1080
|
+
const bars = 1 + 0.22 * noise2(world(s, i % n) / (half * 8), world(s, Math.floor(i / n)) / (half * 8), seed + 7);
|
|
1081
|
+
y = Math.min(pre, y - depth * bowl * bars * blend);
|
|
1082
|
+
}
|
|
1083
|
+
s.height[i] = lerp(pre, y, w);
|
|
1084
|
+
if (material >= 0) paintWeights(s, i, material, w * (river ? 0.85 : 1));
|
|
1085
|
+
}
|
|
1086
|
+
if (river && p.water !== false)
|
|
1087
|
+
s.rivers.push({
|
|
1088
|
+
id: layer2.id,
|
|
1089
|
+
points,
|
|
1090
|
+
width: (p.width ?? 12) * (p.waterWidth ?? 0.76),
|
|
1091
|
+
color: p.color,
|
|
1092
|
+
opacity: alpha
|
|
1093
|
+
});
|
|
1094
|
+
}
|
|
1095
|
+
function applyOperation(s, layer2) {
|
|
1096
|
+
const { type, params: p } = layer2;
|
|
1097
|
+
const opacity = layer2.opacity ?? 1;
|
|
1098
|
+
if (layer2.enabled === false || opacity <= 0) return;
|
|
1099
|
+
const mask = rasterMask(layer2.mask, s);
|
|
1100
|
+
const weight = (i) => (mask?.[i] ?? 1) * opacity;
|
|
1101
|
+
const n = s.resolution;
|
|
1102
|
+
const seed = p.seed ?? s.seed;
|
|
1103
|
+
switch (type) {
|
|
1104
|
+
case "noise": {
|
|
1105
|
+
const amplitude = p.amplitude ?? 35;
|
|
1106
|
+
const scale = p.scale ?? 100;
|
|
1107
|
+
const warp = p.warp ?? 20;
|
|
1108
|
+
for (let z = 0; z < n; z += 1) {
|
|
1109
|
+
for (let x = 0; x < n; x += 1) {
|
|
1110
|
+
const i = z * n + x;
|
|
1111
|
+
const wx = world(s, x);
|
|
1112
|
+
const wz = world(s, z);
|
|
1113
|
+
const ox = noise2(wx / (scale * 1.7) + 17, wz / (scale * 1.7) - 19, seed + 29) * warp;
|
|
1114
|
+
const oz = noise2(wx / (scale * 1.7) - 27, wz / (scale * 1.7) + 12, seed + 31) * warp;
|
|
1115
|
+
let value = (p.base ?? 0) + fbm((wx + ox) / scale, (wz + oz) / scale, {
|
|
1116
|
+
seed,
|
|
1117
|
+
octaves: p.octaves,
|
|
1118
|
+
persistence: p.persistence,
|
|
1119
|
+
lacunarity: p.lacunarity,
|
|
1120
|
+
mode: p.mode
|
|
1121
|
+
}) * amplitude;
|
|
1122
|
+
if (p.island) {
|
|
1123
|
+
const r = Math.hypot(wx / (s.size * 0.59), wz / (s.size * 0.59));
|
|
1124
|
+
value = value * (1 - smoothstep(0.45, 1, r)) - (p.coastDepth ?? 15) * smoothstep(0.6, 1, r);
|
|
1125
|
+
}
|
|
1126
|
+
s.height[i] = p.blend === "replace" ? lerp(s.height[i], value, weight(i)) : s.height[i] + value * weight(i);
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
break;
|
|
1130
|
+
}
|
|
1131
|
+
case "sculpt":
|
|
1132
|
+
case "flatten":
|
|
1133
|
+
case "smooth":
|
|
1134
|
+
case "paint": {
|
|
1135
|
+
const weights = brushWeights(s, p, mask, seed);
|
|
1136
|
+
const w = (i) => (weights?.[i] ?? 1) * opacity;
|
|
1137
|
+
if (type === "sculpt")
|
|
1138
|
+
for (let i = 0; i < s.height.length; i += 1)
|
|
1139
|
+
s.height[i] = s.height[i] + (p.strength ?? 5) * w(i);
|
|
1140
|
+
if (type === "flatten") {
|
|
1141
|
+
const level = "height" in p ? p.height : void 0;
|
|
1142
|
+
if (typeof level !== "number" || !Number.isFinite(level)) {
|
|
1143
|
+
const covered = brushWeights(s, p, mask, seed);
|
|
1144
|
+
let sum = 0;
|
|
1145
|
+
let total = 0;
|
|
1146
|
+
for (let i = 0; i < s.height.length; i += 1) {
|
|
1147
|
+
const share2 = covered[i] * opacity;
|
|
1148
|
+
sum += s.height[i] * share2;
|
|
1149
|
+
total += share2;
|
|
1150
|
+
}
|
|
1151
|
+
const target = total > 0 ? sum / total : 0;
|
|
1152
|
+
let delta = 0;
|
|
1153
|
+
for (let i = 0; i < s.height.length; i += 1)
|
|
1154
|
+
if (covered[i] > 0)
|
|
1155
|
+
delta = Math.max(delta, Math.abs(s.height[i] - target));
|
|
1156
|
+
const graded = brushWeights(
|
|
1157
|
+
s,
|
|
1158
|
+
{ ...p, radius: (p.radius ?? 30) + 1.5 * delta },
|
|
1159
|
+
mask,
|
|
1160
|
+
seed
|
|
1161
|
+
);
|
|
1162
|
+
for (let i = 0; i < s.height.length; i += 1)
|
|
1163
|
+
s.height[i] = lerp(
|
|
1164
|
+
s.height[i],
|
|
1165
|
+
target,
|
|
1166
|
+
graded[i] * opacity * clamp(p.strength ?? 1)
|
|
1167
|
+
);
|
|
1168
|
+
} else
|
|
1169
|
+
for (let i = 0; i < s.height.length; i += 1)
|
|
1170
|
+
s.height[i] = lerp(s.height[i], level, w(i) * clamp(p.strength ?? 1));
|
|
1171
|
+
}
|
|
1172
|
+
if (type === "paint") {
|
|
1173
|
+
const channel = MATERIAL_IDS.indexOf(("material" in p ? p.material : void 0) ?? "dirt");
|
|
1174
|
+
for (let i = 0; i < s.height.length; i += 1)
|
|
1175
|
+
paintWeights(s, i, channel, w(i) * clamp(p.strength ?? 1));
|
|
1176
|
+
}
|
|
1177
|
+
if (type === "smooth")
|
|
1178
|
+
for (let k = 0; k < (("iterations" in p ? p.iterations : void 0) ?? 3); k += 1) {
|
|
1179
|
+
const old = s.height.slice();
|
|
1180
|
+
for (let z = 0; z < n; z += 1) {
|
|
1181
|
+
for (let x = 0; x < n; x += 1) {
|
|
1182
|
+
const i = z * n + x;
|
|
1183
|
+
if (w(i) === 0) continue;
|
|
1184
|
+
let total = 0;
|
|
1185
|
+
let count2 = 0;
|
|
1186
|
+
for (let dz = -1; dz <= 1; dz += 1) {
|
|
1187
|
+
for (let dx = -1; dx <= 1; dx += 1) {
|
|
1188
|
+
const xx = x + dx;
|
|
1189
|
+
const zz = z + dz;
|
|
1190
|
+
if (xx >= 0 && xx < n && zz >= 0 && zz < n) {
|
|
1191
|
+
total += old[zz * n + xx];
|
|
1192
|
+
count2 += 1;
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
s.height[i] = lerp(old[i], total / count2, w(i) * clamp(p.strength ?? 0.65));
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
break;
|
|
1201
|
+
}
|
|
1202
|
+
case "stamp":
|
|
1203
|
+
case "paste": {
|
|
1204
|
+
const at = p.at ?? [0, 0];
|
|
1205
|
+
const radius = p.radius ?? (p.size ? typeof p.size === "number" ? p.size / 2 : p.size.map((v) => v / 2) : 60);
|
|
1206
|
+
const extents = Array.isArray(radius) ? [radius[0] / 1, radius[1] / 1] : [radius / 1, radius / 1];
|
|
1207
|
+
const rot = (p.rotation ?? 0) * Math.PI / 180;
|
|
1208
|
+
const c = Math.cos(rot);
|
|
1209
|
+
const sn = Math.sin(rot);
|
|
1210
|
+
const shape = ("shape" in p ? p.shape : void 0) ?? "mountain";
|
|
1211
|
+
for (let z = 0; z < n; z += 1) {
|
|
1212
|
+
for (let x = 0; x < n; x += 1) {
|
|
1213
|
+
const i = z * n + x;
|
|
1214
|
+
const dx = world(s, x) - at[0];
|
|
1215
|
+
const dz = world(s, z) - at[1];
|
|
1216
|
+
const u = (dx * c + dz * sn) / extents[0] * (p.mirrorX ? -1 : 1);
|
|
1217
|
+
const v = (-dx * sn + dz * c) / extents[1] * (p.mirrorZ ? -1 : 1);
|
|
1218
|
+
const d = Math.hypot(u, v);
|
|
1219
|
+
let profile;
|
|
1220
|
+
let w = 1;
|
|
1221
|
+
if (p.data) {
|
|
1222
|
+
if (Math.abs(u) > 1 || Math.abs(v) > 1) continue;
|
|
1223
|
+
const source = p.data;
|
|
1224
|
+
profile = sampleGrid(
|
|
1225
|
+
source.values,
|
|
1226
|
+
source.width,
|
|
1227
|
+
source.height,
|
|
1228
|
+
u * 0.5 + 0.5,
|
|
1229
|
+
v * 0.5 + 0.5
|
|
1230
|
+
);
|
|
1231
|
+
w = falloff(Math.max(Math.abs(u), Math.abs(v)), 1, p.falloff ?? 0.12);
|
|
1232
|
+
} else {
|
|
1233
|
+
if (d >= 1) continue;
|
|
1234
|
+
const rough = 1 + (("roughness" in p ? p.roughness : void 0) ?? 0.13) * fbm(u * 5, v * 5, { seed, octaves: 3 });
|
|
1235
|
+
if (shape === "crater")
|
|
1236
|
+
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));
|
|
1237
|
+
else if (shape === "ridge")
|
|
1238
|
+
profile = Math.max(0, 1 - Math.abs(v)) ** 1.7 * (1 - smoothstep(0.35, 1, Math.abs(u))) * rough;
|
|
1239
|
+
else if (shape === "mesa") profile = (1 - smoothstep(0.5, 1, d)) * rough;
|
|
1240
|
+
else if (shape === "valley") profile = -(1 - smoothstep(0, 1, d)) * rough;
|
|
1241
|
+
else if (shape === "dune") profile = Math.max(0, 1 - d) ** 1.2 * (1 + 0.25 * u) * rough;
|
|
1242
|
+
else profile = Math.max(0, 1 - d) ** 1.65 * rough;
|
|
1243
|
+
profile *= ("amplitude" in p ? p.amplitude : void 0) ?? 45;
|
|
1244
|
+
w = falloff(d, 1, p.falloff ?? 0);
|
|
1245
|
+
}
|
|
1246
|
+
const alpha = weight(i) * w;
|
|
1247
|
+
const blend = p.blend ?? (type === "paste" ? "replace" : "add");
|
|
1248
|
+
const height = profile * (p.scale ?? 1) + (p.offset ?? 0);
|
|
1249
|
+
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;
|
|
1250
|
+
s.height[i] = lerp(s.height[i], value, alpha);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
break;
|
|
1254
|
+
}
|
|
1255
|
+
case "erode": {
|
|
1256
|
+
const observations = {
|
|
1257
|
+
flow: new Float32Array(s.height.length),
|
|
1258
|
+
sediment: new Float32Array(s.height.length),
|
|
1259
|
+
deposition: new Float32Array(s.height.length),
|
|
1260
|
+
talus: new Float32Array(s.height.length)
|
|
1261
|
+
};
|
|
1262
|
+
s.erosion ??= structuredClone(observations);
|
|
1263
|
+
const eroded = p.method === "fluvial" ? fluvial(s.height, n, s.size, p) : p.method === "hydraulic" ? hydraulic(
|
|
1264
|
+
s.height,
|
|
1265
|
+
n,
|
|
1266
|
+
s.size,
|
|
1267
|
+
{
|
|
1268
|
+
seed,
|
|
1269
|
+
droplets: p.droplets,
|
|
1270
|
+
maxSteps: p.maxSteps,
|
|
1271
|
+
inertia: p.inertia,
|
|
1272
|
+
capacity: p.capacity,
|
|
1273
|
+
erosion: p.erosion,
|
|
1274
|
+
deposition: p.deposition,
|
|
1275
|
+
evaporation: p.evaporation
|
|
1276
|
+
},
|
|
1277
|
+
observations
|
|
1278
|
+
) : thermal(s.height, n, s.size, p, observations);
|
|
1279
|
+
let influence = mask;
|
|
1280
|
+
if (p.at || p.points) influence = brushWeights(s, p, mask, seed);
|
|
1281
|
+
for (let i = 0; i < s.height.length; i += 1) {
|
|
1282
|
+
const alpha = (influence?.[i] ?? 1) * opacity * (p.strength ?? 1);
|
|
1283
|
+
s.height[i] = lerp(s.height[i], eroded[i], alpha);
|
|
1284
|
+
for (const key of ["flow", "sediment", "deposition", "talus"])
|
|
1285
|
+
s.erosion[key][i] = s.erosion[key][i] + observations[key][i] * alpha;
|
|
1286
|
+
}
|
|
1287
|
+
break;
|
|
1288
|
+
}
|
|
1289
|
+
case "terrace": {
|
|
1290
|
+
const step = p.step ?? 8;
|
|
1291
|
+
const softness = p.softness ?? 0.18;
|
|
1292
|
+
for (let i = 0; i < s.height.length; i += 1) {
|
|
1293
|
+
const v = (s.height[i] - (p.offset ?? 0)) / step;
|
|
1294
|
+
const base = Math.floor(v);
|
|
1295
|
+
const f = v - base;
|
|
1296
|
+
const target = (base + smoothstep(0.5 - softness * 0.5, 0.5 + softness * 0.5, f)) * step + (p.offset ?? 0);
|
|
1297
|
+
s.height[i] = lerp(s.height[i], target, weight(i) * (p.strength ?? 1));
|
|
1298
|
+
}
|
|
1299
|
+
break;
|
|
1300
|
+
}
|
|
1301
|
+
case "materials": {
|
|
1302
|
+
if (p.reset !== false)
|
|
1303
|
+
for (let i = 0; i < s.height.length; i += 1)
|
|
1304
|
+
paintWeights(s, i, MATERIAL_IDS.indexOf(p.base ?? "grass"), weight(i));
|
|
1305
|
+
for (const rule of p.rules ?? []) {
|
|
1306
|
+
const ruleMask = rasterMask(rule.mask, s);
|
|
1307
|
+
const channel = MATERIAL_IDS.indexOf(rule.material);
|
|
1308
|
+
for (let i = 0; i < s.height.length; i += 1)
|
|
1309
|
+
paintWeights(s, i, channel, (ruleMask?.[i] ?? 1) * weight(i) * (rule.strength ?? 1));
|
|
1310
|
+
}
|
|
1311
|
+
break;
|
|
1312
|
+
}
|
|
1313
|
+
case "biome": {
|
|
1314
|
+
const name = p.name ?? "forest";
|
|
1315
|
+
s.biomes[name] ??= new Float32Array(s.height.length);
|
|
1316
|
+
const values = s.biomes[name];
|
|
1317
|
+
const weights = brushWeights(s, p, mask, seed);
|
|
1318
|
+
for (let i = 0; i < values.length; i += 1)
|
|
1319
|
+
values[i] = lerp(
|
|
1320
|
+
values[i],
|
|
1321
|
+
p.value ?? 1,
|
|
1322
|
+
(weights?.[i] ?? 1) * opacity * (p.strength ?? 1)
|
|
1323
|
+
);
|
|
1324
|
+
break;
|
|
1325
|
+
}
|
|
1326
|
+
case "scatter":
|
|
1327
|
+
s.scatterRules.push({ id: layer2.id, ...p, mask: layer2.mask, opacity, clear: [] });
|
|
1328
|
+
break;
|
|
1329
|
+
case "clear": {
|
|
1330
|
+
if (p.target === "scatter" || p.target === "all") {
|
|
1331
|
+
for (const rule of s.scatterRules)
|
|
1332
|
+
if (!p.asset || rule.asset === p.asset)
|
|
1333
|
+
rule.clear.push({ mask: layer2.mask ?? { type: "all" }, opacity });
|
|
1334
|
+
}
|
|
1335
|
+
if (p.target === "biome" || p.target === "all")
|
|
1336
|
+
for (const [name, values] of Object.entries(s.biomes)) {
|
|
1337
|
+
if (p.name && p.name !== name) continue;
|
|
1338
|
+
for (let i = 0; i < values.length; i += 1)
|
|
1339
|
+
values[i] = values[i] * (1 - weight(i));
|
|
1340
|
+
}
|
|
1341
|
+
if (p.target === "paint" || p.target === "all")
|
|
1342
|
+
for (let i = 0; i < s.height.length; i += 1) paintWeights(s, i, 0, weight(i));
|
|
1343
|
+
break;
|
|
1344
|
+
}
|
|
1345
|
+
case "road":
|
|
1346
|
+
case "river":
|
|
1347
|
+
case "ramp":
|
|
1348
|
+
applySpline(s, layer2, mask);
|
|
1349
|
+
break;
|
|
1350
|
+
case "water":
|
|
1351
|
+
s.waterRules.push({ id: layer2.id, ...p, mask: layer2.mask, opacity });
|
|
1352
|
+
break;
|
|
1353
|
+
case "heightmap": {
|
|
1354
|
+
if (p.at !== void 0 || p.size !== void 0 || p.rotation !== void 0 || p.falloff !== void 0) {
|
|
1355
|
+
applyOperation(s, {
|
|
1356
|
+
...layer2,
|
|
1357
|
+
type: "paste",
|
|
1358
|
+
params: { ...p, size: p.size ?? s.size, falloff: p.falloff ?? 0 }
|
|
1359
|
+
});
|
|
1360
|
+
break;
|
|
1361
|
+
}
|
|
1362
|
+
const data = p.data;
|
|
1363
|
+
for (let z = 0; z < n; z += 1) {
|
|
1364
|
+
for (let x = 0; x < n; x += 1) {
|
|
1365
|
+
const i = z * n + x;
|
|
1366
|
+
const value = sampleGrid(data.values, data.width, data.height, x / (n - 1), z / (n - 1)) * (p.scale ?? 1) + (p.offset ?? 0);
|
|
1367
|
+
s.height[i] = p.blend === "add" ? s.height[i] + value * weight(i) : lerp(s.height[i], value, weight(i));
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
break;
|
|
1371
|
+
}
|
|
1372
|
+
default:
|
|
1373
|
+
throw Error(`Unsupported operation: ${String(layer2.type)}`);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
function finalizeState(s) {
|
|
1377
|
+
const n = s.resolution;
|
|
1378
|
+
const cell = s.size / (n - 1);
|
|
1379
|
+
s.waters = [];
|
|
1380
|
+
s.instances = [];
|
|
1381
|
+
for (const water2 of s.waterRules) {
|
|
1382
|
+
const mask = new Uint8Array(n * n);
|
|
1383
|
+
const queue = new Int32Array(n * n);
|
|
1384
|
+
const allowed = compileMask(water2.mask, s);
|
|
1385
|
+
const level = water2.level ?? 0;
|
|
1386
|
+
const at = water2.at ?? [0, 0];
|
|
1387
|
+
const radius = water2.radius ?? s.size;
|
|
1388
|
+
let front = 0;
|
|
1389
|
+
let back = 0;
|
|
1390
|
+
const eligible = (i) => {
|
|
1391
|
+
const x = world(s, i % n);
|
|
1392
|
+
const z = world(s, Math.floor(i / n));
|
|
1393
|
+
return s.height[i] < level && Math.hypot(x - at[0], z - at[1]) <= radius && allowed(i, x, z) > 0.05;
|
|
1394
|
+
};
|
|
1395
|
+
const push = (i) => {
|
|
1396
|
+
if (i >= 0 && i < n * n && !mask[i] && eligible(i)) {
|
|
1397
|
+
mask[i] = 1;
|
|
1398
|
+
queue[back] = i;
|
|
1399
|
+
back += 1;
|
|
1400
|
+
}
|
|
1401
|
+
};
|
|
1402
|
+
if (water2.kind === "ocean") {
|
|
1403
|
+
for (let k = 0; k < n; k += 1) {
|
|
1404
|
+
push(k);
|
|
1405
|
+
push((n - 1) * n + k);
|
|
1406
|
+
push(k * n);
|
|
1407
|
+
push(k * n + n - 1);
|
|
1408
|
+
}
|
|
1409
|
+
} else {
|
|
1410
|
+
const x = clamp(Math.round((at[0] + s.size / 2) / cell), 0, n - 1);
|
|
1411
|
+
const z = clamp(Math.round((at[1] + s.size / 2) / cell), 0, n - 1);
|
|
1412
|
+
push(z * n + x);
|
|
1413
|
+
}
|
|
1414
|
+
while (front < back) {
|
|
1415
|
+
const i = queue[front];
|
|
1416
|
+
front += 1;
|
|
1417
|
+
const x = i % n;
|
|
1418
|
+
const z = Math.floor(i / n);
|
|
1419
|
+
if (x > 0) push(i - 1);
|
|
1420
|
+
if (x < n - 1) push(i + 1);
|
|
1421
|
+
if (z > 0) push(i - n);
|
|
1422
|
+
if (z < n - 1) push(i + n);
|
|
1423
|
+
}
|
|
1424
|
+
s.waters.push({ ...water2, level, mask });
|
|
1425
|
+
if (!back)
|
|
1426
|
+
s.diagnostics.push(
|
|
1427
|
+
`Water '${water2.id}' has no flooded cells; its seed may be above the water level.`
|
|
1428
|
+
);
|
|
1429
|
+
}
|
|
1430
|
+
const wet = (i, x, z, h) => {
|
|
1431
|
+
if (s.waters.some((water2) => water2.mask[i])) return true;
|
|
1432
|
+
for (const river of s.rivers) {
|
|
1433
|
+
const half = river.width / 2;
|
|
1434
|
+
for (let k = 1; k < river.points.length; k += 1) {
|
|
1435
|
+
const a = river.points[k - 1];
|
|
1436
|
+
const b = river.points[k];
|
|
1437
|
+
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)
|
|
1438
|
+
continue;
|
|
1439
|
+
const dx = b[0] - a[0];
|
|
1440
|
+
const dz = b[2] - a[2];
|
|
1441
|
+
const t = clamp(((x - a[0]) * dx + (z - a[2]) * dz) / (dx * dx + dz * dz || 1));
|
|
1442
|
+
if (Math.hypot(x - a[0] - t * dx, z - a[2] - t * dz) < half && h <= lerp(a[1], b[1], t) + 0.2)
|
|
1443
|
+
return true;
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
return false;
|
|
1447
|
+
};
|
|
1448
|
+
for (const rule of s.scatterRules) {
|
|
1449
|
+
const count2 = Math.round((rule.count ?? 300) * (rule.opacity ?? 1));
|
|
1450
|
+
const seed = (rule.seed ?? s.seed ^ hashString(rule.id)) >>> 0;
|
|
1451
|
+
const rnd = random(seed);
|
|
1452
|
+
const accept = compileMask(rule.mask, s);
|
|
1453
|
+
const clears = rule.clear.map((entry2) => ({
|
|
1454
|
+
fn: compileMask(entry2.mask, s),
|
|
1455
|
+
opacity: entry2.opacity
|
|
1456
|
+
}));
|
|
1457
|
+
const distance = rule.minDistance ?? 4;
|
|
1458
|
+
const gridSize = Math.max(distance, 0.1);
|
|
1459
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
1460
|
+
const accepted = [];
|
|
1461
|
+
const maxAttempts = count2 * 40;
|
|
1462
|
+
const scale = rule.scale ?? [0.8, 1.3];
|
|
1463
|
+
for (let attempt = 0; attempt < maxAttempts && accepted.length < count2; attempt += 1) {
|
|
1464
|
+
const x = (rnd() - 0.5) * s.size;
|
|
1465
|
+
const z = (rnd() - 0.5) * s.size;
|
|
1466
|
+
const acceptance = rnd();
|
|
1467
|
+
const scaleRandom = rnd();
|
|
1468
|
+
const yaw = rnd() * Math.PI * 2;
|
|
1469
|
+
const ix = clamp(Math.round((x / s.size + 0.5) * (n - 1)), 0, n - 1);
|
|
1470
|
+
const iz = clamp(Math.round((z / s.size + 0.5) * (n - 1)), 0, n - 1);
|
|
1471
|
+
const i = iz * n + ix;
|
|
1472
|
+
let w = accept(i, x, z);
|
|
1473
|
+
for (const clear of clears) w *= 1 - clear.fn(i, x, z) * clear.opacity;
|
|
1474
|
+
if (acceptance > w) continue;
|
|
1475
|
+
const h = sampleHeight(s, x, z);
|
|
1476
|
+
if (rule.avoidWater !== false && wet(i, x, z, h)) continue;
|
|
1477
|
+
if (h < (rule.minHeight ?? -1e9) || h > (rule.maxHeight ?? 1e9)) continue;
|
|
1478
|
+
const g = gradientAt(s, x, z);
|
|
1479
|
+
const slope = Math.atan(Math.hypot(g[0], g[1])) * (180 / Math.PI);
|
|
1480
|
+
if (slope < (rule.minSlope ?? 0) || slope > (rule.maxSlope ?? 90)) continue;
|
|
1481
|
+
const gx = Math.floor(x / gridSize);
|
|
1482
|
+
const gz = Math.floor(z / gridSize);
|
|
1483
|
+
let blocked = false;
|
|
1484
|
+
if (distance > 0)
|
|
1485
|
+
for (let dz = -1; dz <= 1 && !blocked; dz += 1) {
|
|
1486
|
+
for (let dx = -1; dx <= 1 && !blocked; dx += 1) {
|
|
1487
|
+
for (const j of buckets.get(`${gx + dx},${gz + dz}`) ?? []) {
|
|
1488
|
+
const other = accepted[j];
|
|
1489
|
+
if (Math.hypot(other.position[0] - x, other.position[2] - z) < distance) {
|
|
1490
|
+
blocked = true;
|
|
1491
|
+
break;
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
if (blocked) continue;
|
|
1497
|
+
const index = accepted.length;
|
|
1498
|
+
const itemScale = Array.isArray(scale) ? lerp(scale[0], scale[1], scaleRandom) : scale;
|
|
1499
|
+
const normal = [-g[0], 1, -g[1]];
|
|
1500
|
+
const length = Math.hypot(normal[0], normal[1], normal[2]);
|
|
1501
|
+
accepted.push({
|
|
1502
|
+
id: `${rule.id}:candidate:${seed}:${attempt}`,
|
|
1503
|
+
layer: rule.id,
|
|
1504
|
+
asset: rule.asset,
|
|
1505
|
+
position: [x, h + (rule.offsetY ?? 0), z],
|
|
1506
|
+
rotation: yaw,
|
|
1507
|
+
scale: itemScale,
|
|
1508
|
+
normal: [normal[0] / length, normal[1] / length, normal[2] / length],
|
|
1509
|
+
alignToNormal: rule.alignToNormal ?? false
|
|
1510
|
+
});
|
|
1511
|
+
const key = `${gx},${gz}`;
|
|
1512
|
+
const bucket = buckets.get(key) ?? [];
|
|
1513
|
+
bucket.push(index);
|
|
1514
|
+
buckets.set(key, bucket);
|
|
1515
|
+
}
|
|
1516
|
+
for (const instance of accepted) s.instances.push(instance);
|
|
1517
|
+
if (accepted.length < count2)
|
|
1518
|
+
s.diagnostics.push(
|
|
1519
|
+
`Scatter '${rule.id}': placed ${accepted.length}/${count2}; masks or spacing exhausted the attempt budget.`
|
|
1520
|
+
);
|
|
1521
|
+
}
|
|
1522
|
+
return s;
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
// src/core/validation.ts
|
|
1526
|
+
var RESOLUTIONS = Object.freeze([17, 33, 65, 129, 257, 513, 1025]);
|
|
1527
|
+
var brush2 = [
|
|
1528
|
+
"at",
|
|
1529
|
+
"points",
|
|
1530
|
+
"radius",
|
|
1531
|
+
"strength",
|
|
1532
|
+
"falloff",
|
|
1533
|
+
"shape",
|
|
1534
|
+
"rotation",
|
|
1535
|
+
"spacing",
|
|
1536
|
+
"jitter"
|
|
1537
|
+
];
|
|
1538
|
+
var grade = ["followTerrain", "maxGrade", "maxCut", "maxFill"];
|
|
1539
|
+
var PARAMS = Object.freeze({
|
|
1540
|
+
noise: [
|
|
1541
|
+
"amplitude",
|
|
1542
|
+
"scale",
|
|
1543
|
+
"octaves",
|
|
1544
|
+
"persistence",
|
|
1545
|
+
"lacunarity",
|
|
1546
|
+
"mode",
|
|
1547
|
+
"warp",
|
|
1548
|
+
"base",
|
|
1549
|
+
"blend",
|
|
1550
|
+
"island",
|
|
1551
|
+
"coastDepth"
|
|
1552
|
+
],
|
|
1553
|
+
sculpt: brush2,
|
|
1554
|
+
smooth: [...brush2, "iterations"],
|
|
1555
|
+
flatten: [...brush2, "height"],
|
|
1556
|
+
paint: [...brush2, "material"],
|
|
1557
|
+
stamp: [
|
|
1558
|
+
"at",
|
|
1559
|
+
"radius",
|
|
1560
|
+
"size",
|
|
1561
|
+
"amplitude",
|
|
1562
|
+
"shape",
|
|
1563
|
+
"rotation",
|
|
1564
|
+
"mirrorX",
|
|
1565
|
+
"mirrorZ",
|
|
1566
|
+
"blend",
|
|
1567
|
+
"roughness",
|
|
1568
|
+
"scale",
|
|
1569
|
+
"offset",
|
|
1570
|
+
"data",
|
|
1571
|
+
"falloff"
|
|
1572
|
+
],
|
|
1573
|
+
paste: [
|
|
1574
|
+
"at",
|
|
1575
|
+
"size",
|
|
1576
|
+
"radius",
|
|
1577
|
+
"rotation",
|
|
1578
|
+
"mirrorX",
|
|
1579
|
+
"mirrorZ",
|
|
1580
|
+
"blend",
|
|
1581
|
+
"offset",
|
|
1582
|
+
"scale",
|
|
1583
|
+
"data",
|
|
1584
|
+
"falloff"
|
|
1585
|
+
],
|
|
1586
|
+
erode: [
|
|
1587
|
+
...brush2,
|
|
1588
|
+
"method",
|
|
1589
|
+
"iterations",
|
|
1590
|
+
"talus",
|
|
1591
|
+
"uplift",
|
|
1592
|
+
"erodibility",
|
|
1593
|
+
"timeStep",
|
|
1594
|
+
"relief",
|
|
1595
|
+
"rate",
|
|
1596
|
+
"droplets",
|
|
1597
|
+
"maxSteps",
|
|
1598
|
+
"inertia",
|
|
1599
|
+
"capacity",
|
|
1600
|
+
"erosion",
|
|
1601
|
+
"deposition",
|
|
1602
|
+
"evaporation"
|
|
1603
|
+
],
|
|
1604
|
+
terrace: ["step", "softness", "strength", "offset"],
|
|
1605
|
+
materials: ["base", "rules", "reset"],
|
|
1606
|
+
biome: [...brush2, "name", "value"],
|
|
1607
|
+
scatter: [
|
|
1608
|
+
"asset",
|
|
1609
|
+
"count",
|
|
1610
|
+
"minDistance",
|
|
1611
|
+
"scale",
|
|
1612
|
+
"minHeight",
|
|
1613
|
+
"maxHeight",
|
|
1614
|
+
"minSlope",
|
|
1615
|
+
"maxSlope",
|
|
1616
|
+
"avoidWater",
|
|
1617
|
+
"offsetY",
|
|
1618
|
+
"alignToNormal"
|
|
1619
|
+
],
|
|
1620
|
+
clear: ["target", "asset", "name"],
|
|
1621
|
+
road: ["points", "width", "shoulder", "material", "smooth", ...grade],
|
|
1622
|
+
river: [
|
|
1623
|
+
"points",
|
|
1624
|
+
"width",
|
|
1625
|
+
"shoulder",
|
|
1626
|
+
"depth",
|
|
1627
|
+
"material",
|
|
1628
|
+
"smooth",
|
|
1629
|
+
"water",
|
|
1630
|
+
"waterWidth",
|
|
1631
|
+
"color",
|
|
1632
|
+
"enforceDownhill",
|
|
1633
|
+
...grade
|
|
1634
|
+
],
|
|
1635
|
+
ramp: ["from", "to", "width", "shoulder", "material", ...grade],
|
|
1636
|
+
water: ["kind", "at", "radius", "level", "color"],
|
|
1637
|
+
heightmap: ["data", "scale", "offset", "blend", "at", "size", "rotation", "falloff"]
|
|
1638
|
+
});
|
|
1639
|
+
function fail(message) {
|
|
1640
|
+
throw new TypeError(message);
|
|
1641
|
+
}
|
|
1642
|
+
function finiteTree(value, path = "value", depth = 0) {
|
|
1643
|
+
if (depth > 32) fail(`${path}: nesting is too deep`);
|
|
1644
|
+
if (typeof value === "number") {
|
|
1645
|
+
if (!Number.isFinite(value)) fail(`${path} must be finite`);
|
|
1646
|
+
return;
|
|
1647
|
+
}
|
|
1648
|
+
if (value === void 0 || typeof value === "function" || typeof value === "bigint" || typeof value === "symbol")
|
|
1649
|
+
fail(`${path} is not JSON-serializable`);
|
|
1650
|
+
if (value && typeof value === "object") {
|
|
1651
|
+
if (ArrayBuffer.isView(value)) fail(`${path}: use a plain array in recipes`);
|
|
1652
|
+
for (const key of Object.keys(value)) {
|
|
1653
|
+
if (key === "__proto__" || key === "prototype" || key === "constructor")
|
|
1654
|
+
fail(`${path}: unsafe object key`);
|
|
1655
|
+
const entry2 = value[key];
|
|
1656
|
+
if (typeof entry2 === "number") {
|
|
1657
|
+
if (depth + 1 > 32) fail(`${path}.${key}: nesting is too deep`);
|
|
1658
|
+
if (!Number.isFinite(entry2)) fail(`${path}.${key} must be finite`);
|
|
1659
|
+
continue;
|
|
1660
|
+
}
|
|
1661
|
+
finiteTree(entry2, `${path}.${key}`, depth + 1);
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
var num = (v, name, min = -1e9, max = 1e9, integer = false) => {
|
|
1666
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v < min || v > max || integer && !Number.isInteger(v))
|
|
1667
|
+
fail(`${name} must be ${integer ? "an integer" : "finite"} between ${min} and ${max}`);
|
|
1668
|
+
};
|
|
1669
|
+
var vec = (v, name, n) => {
|
|
1670
|
+
if (!Array.isArray(v) || v.length !== n) fail(`${name} must contain ${n} numbers`);
|
|
1671
|
+
for (const x of v) num(x, name);
|
|
1672
|
+
};
|
|
1673
|
+
var identifier = (v, name) => {
|
|
1674
|
+
if (typeof v !== "string" || v.length === 0 || v.length > 100 || ["__proto__", "prototype", "constructor"].includes(v))
|
|
1675
|
+
fail(`${name} must be a nonempty safe string, at most 100 characters`);
|
|
1676
|
+
};
|
|
1677
|
+
var enumeration = (v, name, choices) => {
|
|
1678
|
+
if (!choices.includes(v)) fail(`${name}: expected ${choices.join(", ")}`);
|
|
1679
|
+
};
|
|
1680
|
+
function validateConfig(config) {
|
|
1681
|
+
num(config.size, "size", 1, 1e5);
|
|
1682
|
+
if (!RESOLUTIONS.includes(config.resolution))
|
|
1683
|
+
fail(`resolution must be one of ${RESOLUTIONS.join(", ")}`);
|
|
1684
|
+
num(config.seed, "seed", 0, 4294967295, true);
|
|
1685
|
+
}
|
|
1686
|
+
function validateMask(m, depth = 0) {
|
|
1687
|
+
if (!m || typeof m !== "object" || depth > 20) fail("Invalid mask");
|
|
1688
|
+
enumeration(m.type, "mask.type", [
|
|
1689
|
+
"all",
|
|
1690
|
+
"none",
|
|
1691
|
+
"circle",
|
|
1692
|
+
"rectangle",
|
|
1693
|
+
"height",
|
|
1694
|
+
"slope",
|
|
1695
|
+
"noise",
|
|
1696
|
+
"biome",
|
|
1697
|
+
"material",
|
|
1698
|
+
"and",
|
|
1699
|
+
"or",
|
|
1700
|
+
"not"
|
|
1701
|
+
]);
|
|
1702
|
+
const allowed = {
|
|
1703
|
+
all: [],
|
|
1704
|
+
none: [],
|
|
1705
|
+
circle: ["at", "radius", "falloff"],
|
|
1706
|
+
rectangle: ["at", "size", "rotation", "falloff"],
|
|
1707
|
+
height: ["min", "max", "fade"],
|
|
1708
|
+
slope: ["min", "max", "fade"],
|
|
1709
|
+
noise: ["scale", "threshold", "seed", "fade"],
|
|
1710
|
+
biome: ["name"],
|
|
1711
|
+
material: ["name"],
|
|
1712
|
+
and: ["masks"],
|
|
1713
|
+
or: ["masks"],
|
|
1714
|
+
not: ["mask"]
|
|
1715
|
+
};
|
|
1716
|
+
for (const key of Object.keys(m))
|
|
1717
|
+
if (key !== "type" && !allowed[m.type].includes(key)) fail(`Unknown mask field '${key}'`);
|
|
1718
|
+
if (m.rotation !== void 0) num(m.rotation, "mask.rotation");
|
|
1719
|
+
if (m.seed !== void 0) num(m.seed, "mask.seed", 0, 4294967295, true);
|
|
1720
|
+
if (m.type === "circle") {
|
|
1721
|
+
vec(m.at, "mask.at", 2);
|
|
1722
|
+
num(m.radius, "mask.radius", 1e-3, 1e6);
|
|
1723
|
+
}
|
|
1724
|
+
if (m.type === "rectangle") {
|
|
1725
|
+
vec(m.at, "mask.at", 2);
|
|
1726
|
+
const size = m.size;
|
|
1727
|
+
if (Array.isArray(size)) {
|
|
1728
|
+
vec(size, "mask.size", 2);
|
|
1729
|
+
for (const value of size) num(value, "mask.size", 1e-3, 1e6);
|
|
1730
|
+
} else num(size, "mask.size", 1e-3, 1e6);
|
|
1731
|
+
}
|
|
1732
|
+
if (["height", "slope"].includes(m.type)) {
|
|
1733
|
+
if (m.min !== void 0) num(m.min, "mask.min");
|
|
1734
|
+
if (m.max !== void 0) num(m.max, "mask.max");
|
|
1735
|
+
if ((m.min ?? -1e9) > (m.max ?? 1e9)) fail("mask.min must not exceed mask.max");
|
|
1736
|
+
if (m.fade !== void 0) num(m.fade, "mask.fade", 0, 1e6);
|
|
1737
|
+
}
|
|
1738
|
+
if (m.type === "noise") {
|
|
1739
|
+
num(m.scale, "mask.scale", 1e-3, 1e6);
|
|
1740
|
+
if (m.threshold !== void 0) num(m.threshold, "mask.threshold", 0, 1);
|
|
1741
|
+
if (m.fade !== void 0) num(m.fade, "mask.fade", 1e-6, 1);
|
|
1742
|
+
}
|
|
1743
|
+
if (m.type === "biome") identifier(m.name, "mask.name");
|
|
1744
|
+
if (m.type === "material") enumeration(m.name, "mask.material", MATERIAL_IDS);
|
|
1745
|
+
if (m.type === "not") validateMask(m.mask, depth + 1);
|
|
1746
|
+
if (["and", "or"].includes(m.type)) {
|
|
1747
|
+
if (!Array.isArray(m.masks) || m.masks.length > 32)
|
|
1748
|
+
fail("mask.masks must be an array of at most 32 masks");
|
|
1749
|
+
for (const entry2 of m.masks) validateMask(entry2, depth + 1);
|
|
1750
|
+
}
|
|
1751
|
+
if (m.falloff !== void 0) num(m.falloff, "mask.falloff", 0, 1);
|
|
1752
|
+
}
|
|
1753
|
+
function splinePoint(v, name, follows) {
|
|
1754
|
+
if (!Array.isArray(v) || v.length !== 3) fail(`${name} must contain 3 numbers`);
|
|
1755
|
+
num(v[0], name);
|
|
1756
|
+
num(v[2], name);
|
|
1757
|
+
const y = v[1];
|
|
1758
|
+
if (y === null || y === void 0) {
|
|
1759
|
+
if (follows) return;
|
|
1760
|
+
fail(`${name} must contain 3 numbers`);
|
|
1761
|
+
}
|
|
1762
|
+
if (typeof y !== "number") fail(`${name} must contain 3 numbers`);
|
|
1763
|
+
if (!Number.isFinite(y) && !follows) fail(`${name} elevation must be finite`);
|
|
1764
|
+
}
|
|
1765
|
+
function layerFollowsTerrain(layer2) {
|
|
1766
|
+
if (!layer2 || typeof layer2 !== "object" || !["road", "river", "ramp"].includes(layer2.type))
|
|
1767
|
+
return false;
|
|
1768
|
+
const params = layer2.params ?? {};
|
|
1769
|
+
const source = layer2.type === "ramp" ? [params.from, params.to] : params.points;
|
|
1770
|
+
if (!Array.isArray(source)) return false;
|
|
1771
|
+
return followsTerrain(source, params.followTerrain);
|
|
1772
|
+
}
|
|
1773
|
+
function omittedElevations(layer2, follows) {
|
|
1774
|
+
if (!follows) return layer2;
|
|
1775
|
+
const params = layer2.params ?? {};
|
|
1776
|
+
const zero = (p) => Array.isArray(p) && p.length === 3 ? [p[0], 0, p[2]] : p;
|
|
1777
|
+
const points = params.points;
|
|
1778
|
+
const fixes = {
|
|
1779
|
+
...Array.isArray(points) ? { points: points.map(zero) } : {},
|
|
1780
|
+
...Array.isArray(params.from) ? { from: zero(params.from) } : {},
|
|
1781
|
+
...Array.isArray(params.to) ? { to: zero(params.to) } : {}
|
|
1782
|
+
};
|
|
1783
|
+
return Object.keys(fixes).length ? { ...layer2, params: { ...params, ...fixes } } : layer2;
|
|
1784
|
+
}
|
|
1785
|
+
function validateLayer(layer2) {
|
|
1786
|
+
const follows = layerFollowsTerrain(layer2);
|
|
1787
|
+
finiteTree(omittedElevations(layer2, follows), "layer");
|
|
1788
|
+
if (!layer2 || typeof layer2 !== "object") fail("layer must be an object");
|
|
1789
|
+
for (const k of Object.keys(layer2))
|
|
1790
|
+
if (!["id", "name", "type", "params", "enabled", "opacity", "mask"].includes(k))
|
|
1791
|
+
fail(`Unknown layer field '${k}'`);
|
|
1792
|
+
identifier(layer2.id, "layer.id");
|
|
1793
|
+
enumeration(layer2.type, "operation", OPERATION_TYPES);
|
|
1794
|
+
if (layer2.name !== void 0) identifier(layer2.name, "layer.name");
|
|
1795
|
+
if (layer2.enabled !== void 0 && typeof layer2.enabled !== "boolean")
|
|
1796
|
+
fail("enabled must be boolean");
|
|
1797
|
+
if (layer2.opacity !== void 0) num(layer2.opacity, "opacity", 0, 1);
|
|
1798
|
+
if (layer2.mask) validateMask(layer2.mask);
|
|
1799
|
+
const params = layer2.params ?? {};
|
|
1800
|
+
if (!params || Array.isArray(params) || typeof params !== "object")
|
|
1801
|
+
fail("params must be an object");
|
|
1802
|
+
for (const k of Object.keys(params))
|
|
1803
|
+
if (!PARAMS[layer2.type].includes(k) && k !== "seed")
|
|
1804
|
+
fail(`Unknown ${layer2.type} parameter '${k}'`);
|
|
1805
|
+
for (const key of [
|
|
1806
|
+
"island",
|
|
1807
|
+
"mirrorX",
|
|
1808
|
+
"mirrorZ",
|
|
1809
|
+
"reset",
|
|
1810
|
+
"avoidWater",
|
|
1811
|
+
"alignToNormal",
|
|
1812
|
+
"smooth",
|
|
1813
|
+
"water",
|
|
1814
|
+
"enforceDownhill",
|
|
1815
|
+
"followTerrain"
|
|
1816
|
+
])
|
|
1817
|
+
if (params[key] !== void 0 && typeof params[key] !== "boolean")
|
|
1818
|
+
fail(`${key} must be boolean`);
|
|
1819
|
+
if (params.seed !== void 0) num(params.seed, "seed", 0, 4294967295, true);
|
|
1820
|
+
if (params.at !== void 0) vec(params.at, "at", 2);
|
|
1821
|
+
if (params.from !== void 0) splinePoint(params.from, "from", follows);
|
|
1822
|
+
if (params.to !== void 0) splinePoint(params.to, "to", follows);
|
|
1823
|
+
const points = params.points;
|
|
1824
|
+
const isSpline = ["road", "river"].includes(layer2.type);
|
|
1825
|
+
if (points) {
|
|
1826
|
+
if (!Array.isArray(points) || !points.length || points.length > 8192)
|
|
1827
|
+
fail("points must have 1..8192 entries");
|
|
1828
|
+
const dimensions = isSpline ? 3 : 2;
|
|
1829
|
+
for (const point of points)
|
|
1830
|
+
if (isSpline) splinePoint(point, "point", follows);
|
|
1831
|
+
else vec(point, "point", dimensions);
|
|
1832
|
+
}
|
|
1833
|
+
if (Array.isArray(points) && !isSpline) {
|
|
1834
|
+
const stroke = points;
|
|
1835
|
+
const spacing = Math.max(
|
|
1836
|
+
0.1,
|
|
1837
|
+
(params.radius ?? 30) * 2 * (params.spacing ?? 0.15)
|
|
1838
|
+
);
|
|
1839
|
+
let samples = 1;
|
|
1840
|
+
for (let k = 1; k < stroke.length; k += 1) {
|
|
1841
|
+
const next = stroke[k];
|
|
1842
|
+
const previous = stroke[k - 1];
|
|
1843
|
+
samples += Math.max(
|
|
1844
|
+
1,
|
|
1845
|
+
Math.ceil(
|
|
1846
|
+
Math.hypot(
|
|
1847
|
+
next[0] - previous[0],
|
|
1848
|
+
next[1] - previous[1]
|
|
1849
|
+
) / spacing
|
|
1850
|
+
)
|
|
1851
|
+
);
|
|
1852
|
+
}
|
|
1853
|
+
if (samples > 65536)
|
|
1854
|
+
fail(
|
|
1855
|
+
"Brush interpolation exceeds 65536 samples; increase radius/spacing or shorten the stroke"
|
|
1856
|
+
);
|
|
1857
|
+
}
|
|
1858
|
+
if (isSpline && (!Array.isArray(points) || points.length < 2))
|
|
1859
|
+
fail(`${layer2.type} requires at least two [x,y,z] points`);
|
|
1860
|
+
if (layer2.type === "ramp" && (!params.from || !params.to)) fail("ramp requires from and to");
|
|
1861
|
+
for (const key of ["radius", "size"]) {
|
|
1862
|
+
const value = params[key];
|
|
1863
|
+
if (value === void 0) continue;
|
|
1864
|
+
if (Array.isArray(value)) {
|
|
1865
|
+
vec(value, key, 2);
|
|
1866
|
+
for (const entry2 of value) num(entry2, key, 1e-3, 1e6);
|
|
1867
|
+
} else num(value, key, 1e-3, 1e6);
|
|
1868
|
+
}
|
|
1869
|
+
if (Array.isArray(params.radius) && !["stamp", "paste"].includes(layer2.type))
|
|
1870
|
+
fail("Brush radius must be one number");
|
|
1871
|
+
for (const key of [
|
|
1872
|
+
"amplitude",
|
|
1873
|
+
"height",
|
|
1874
|
+
"base",
|
|
1875
|
+
"offset",
|
|
1876
|
+
"offsetY",
|
|
1877
|
+
"minHeight",
|
|
1878
|
+
"maxHeight",
|
|
1879
|
+
"level",
|
|
1880
|
+
"rotation"
|
|
1881
|
+
])
|
|
1882
|
+
if (params[key] !== void 0 && !(key === "base" && layer2.type === "materials")) {
|
|
1883
|
+
if (params[key] !== null || key !== "height") num(params[key], key);
|
|
1884
|
+
}
|
|
1885
|
+
for (const key of ["width", "step"])
|
|
1886
|
+
if (params[key] !== void 0) num(params[key], key, 1e-3, 1e6);
|
|
1887
|
+
for (const key of [
|
|
1888
|
+
"warp",
|
|
1889
|
+
"shoulder",
|
|
1890
|
+
"roughness",
|
|
1891
|
+
"coastDepth",
|
|
1892
|
+
"minDistance",
|
|
1893
|
+
"depth",
|
|
1894
|
+
"capacity",
|
|
1895
|
+
"maxCut",
|
|
1896
|
+
"maxFill"
|
|
1897
|
+
])
|
|
1898
|
+
if (params[key] !== void 0) num(params[key], key, 0, 1e6);
|
|
1899
|
+
for (const key of [
|
|
1900
|
+
"falloff",
|
|
1901
|
+
"jitter",
|
|
1902
|
+
"softness",
|
|
1903
|
+
"inertia",
|
|
1904
|
+
"erosion",
|
|
1905
|
+
"deposition",
|
|
1906
|
+
"evaporation",
|
|
1907
|
+
"rate",
|
|
1908
|
+
"value",
|
|
1909
|
+
"waterWidth",
|
|
1910
|
+
"maxGrade"
|
|
1911
|
+
])
|
|
1912
|
+
if (params[key] !== void 0) num(params[key], key, 0, 1);
|
|
1913
|
+
if (params.spacing !== void 0) num(params.spacing, "spacing", 0.01, 2);
|
|
1914
|
+
if (params.strength !== void 0)
|
|
1915
|
+
num(
|
|
1916
|
+
params.strength,
|
|
1917
|
+
"strength",
|
|
1918
|
+
layer2.type === "sculpt" ? -1e4 : 0,
|
|
1919
|
+
layer2.type === "sculpt" ? 1e4 : 1
|
|
1920
|
+
);
|
|
1921
|
+
if (params.scale !== void 0) {
|
|
1922
|
+
const scale = params.scale;
|
|
1923
|
+
if (layer2.type === "scatter") {
|
|
1924
|
+
if (Array.isArray(scale)) {
|
|
1925
|
+
vec(scale, "scale", 2);
|
|
1926
|
+
if (scale[0] > scale[1]) fail("scale range is inverted");
|
|
1927
|
+
for (const entry2 of scale) num(entry2, "scale", 1e-3, 1e4);
|
|
1928
|
+
} else num(scale, "scale", 1e-3, 1e4);
|
|
1929
|
+
} else num(scale, "scale", 1e-3, 1e6);
|
|
1930
|
+
}
|
|
1931
|
+
for (const [key, max] of [
|
|
1932
|
+
["octaves", 10],
|
|
1933
|
+
["iterations", 200],
|
|
1934
|
+
["droplets", 2e5],
|
|
1935
|
+
["maxSteps", 128],
|
|
1936
|
+
["count", 2e4]
|
|
1937
|
+
])
|
|
1938
|
+
if (params[key] !== void 0) num(params[key], key, key === "count" ? 0 : 1, max, true);
|
|
1939
|
+
if (params.persistence !== void 0) num(params.persistence, "persistence", 0.01, 1);
|
|
1940
|
+
if (params.lacunarity !== void 0) num(params.lacunarity, "lacunarity", 1, 4);
|
|
1941
|
+
for (const [key, min, max] of [
|
|
1942
|
+
["uplift", 1e-9, 1],
|
|
1943
|
+
["erodibility", 1e-9, 1],
|
|
1944
|
+
["timeStep", 1, 1e7],
|
|
1945
|
+
["relief", 1, 1e5]
|
|
1946
|
+
])
|
|
1947
|
+
if (params[key] !== void 0) num(params[key], key, min, max);
|
|
1948
|
+
for (const key of ["minSlope", "maxSlope", "talus"])
|
|
1949
|
+
if (params[key] !== void 0) num(params[key], key, 0, key === "talus" ? 89.9 : 90);
|
|
1950
|
+
if (params.minHeight !== void 0 && params.maxHeight !== void 0 && params.minHeight > params.maxHeight)
|
|
1951
|
+
fail("height range is inverted");
|
|
1952
|
+
if (params.minSlope !== void 0 && params.maxSlope !== void 0 && params.minSlope > params.maxSlope)
|
|
1953
|
+
fail("slope range is inverted");
|
|
1954
|
+
if (params.material !== void 0) enumeration(params.material, "material", MATERIAL_IDS);
|
|
1955
|
+
if (layer2.type === "materials") {
|
|
1956
|
+
if (params.base !== void 0) enumeration(params.base, "base", MATERIAL_IDS);
|
|
1957
|
+
const rules = params.rules;
|
|
1958
|
+
if (!Array.isArray(rules) || rules.length > 64) fail("materials requires a rules array");
|
|
1959
|
+
for (const rule of rules) {
|
|
1960
|
+
enumeration(rule.material, "rule.material", MATERIAL_IDS);
|
|
1961
|
+
if (rule.mask) validateMask(rule.mask);
|
|
1962
|
+
if (rule.strength !== void 0) num(rule.strength, "rule.strength", 0, 1);
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
if (params.method !== void 0)
|
|
1966
|
+
enumeration(params.method, "method", ["thermal", "hydraulic", "fluvial"]);
|
|
1967
|
+
if (params.mode !== void 0) enumeration(params.mode, "mode", ["fbm", "ridged", "billow"]);
|
|
1968
|
+
if (params.shape !== void 0)
|
|
1969
|
+
enumeration(
|
|
1970
|
+
params.shape,
|
|
1971
|
+
"shape",
|
|
1972
|
+
["stamp"].includes(layer2.type) ? ["mountain", "crater", "ridge", "valley", "mesa", "dune"] : ["circle", "square"]
|
|
1973
|
+
);
|
|
1974
|
+
if (params.blend !== void 0)
|
|
1975
|
+
enumeration(
|
|
1976
|
+
params.blend,
|
|
1977
|
+
"blend",
|
|
1978
|
+
["noise", "heightmap"].includes(layer2.type) ? ["add", "replace"] : ["add", "replace", "min", "max"]
|
|
1979
|
+
);
|
|
1980
|
+
if (layer2.type === "clear")
|
|
1981
|
+
enumeration(params.target, "clear.target", ["scatter", "paint", "biome", "all"]);
|
|
1982
|
+
if (layer2.type === "water") enumeration(params.kind ?? "lake", "water.kind", ["lake", "ocean"]);
|
|
1983
|
+
if (layer2.type === "river" && params.enforceDownhill && Array.isArray(points)) {
|
|
1984
|
+
const river = points;
|
|
1985
|
+
for (let i = 1; i < river.length; i += 1) {
|
|
1986
|
+
const next = river[i];
|
|
1987
|
+
const previous = river[i - 1];
|
|
1988
|
+
if (next[1] > previous[1])
|
|
1989
|
+
fail("River control-point elevations must be non-increasing");
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
if (params.name !== void 0) identifier(params.name, "name");
|
|
1993
|
+
if (params.asset !== void 0) identifier(params.asset, "asset");
|
|
1994
|
+
if (layer2.type === "scatter" && typeof params.asset !== "string")
|
|
1995
|
+
fail(
|
|
1996
|
+
'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'
|
|
1997
|
+
);
|
|
1998
|
+
if (["heightmap", "paste"].includes(layer2.type) && !params.data)
|
|
1999
|
+
fail(`${layer2.type} requires heightmap data`);
|
|
2000
|
+
const data = params.data;
|
|
2001
|
+
if (data) {
|
|
2002
|
+
num(data.width, "data.width", 2, 4097, true);
|
|
2003
|
+
num(data.height, "data.height", 2, 4097, true);
|
|
2004
|
+
if (!Array.isArray(data.values) || data.values.length !== data.width * data.height)
|
|
2005
|
+
fail("heightmap dimensions do not match values");
|
|
2006
|
+
for (const value of data.values)
|
|
2007
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
2008
|
+
fail("data.values must contain only finite numbers");
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
function validateDocument(doc) {
|
|
2012
|
+
finiteTree(
|
|
2013
|
+
Array.isArray(doc.layers) ? {
|
|
2014
|
+
...doc,
|
|
2015
|
+
layers: doc.layers.map((layer2) => omittedElevations(layer2, layerFollowsTerrain(layer2)))
|
|
2016
|
+
} : doc,
|
|
2017
|
+
"recipe"
|
|
2018
|
+
);
|
|
2019
|
+
if (doc.version !== 1) fail("Unsupported recipe version; expected 1");
|
|
2020
|
+
validateConfig(doc.config);
|
|
2021
|
+
if (!Array.isArray(doc.layers) || doc.layers.length > 512)
|
|
2022
|
+
fail("layers must be an array of at most 512 layers");
|
|
2023
|
+
const ids = /* @__PURE__ */ new Set();
|
|
2024
|
+
for (const layer2 of doc.layers) {
|
|
2025
|
+
validateLayer(layer2);
|
|
2026
|
+
if (ids.has(layer2.id)) fail(`Duplicate layer ID: ${layer2.id}`);
|
|
2027
|
+
ids.add(layer2.id);
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
// src/core/terrain.ts
|
|
2032
|
+
var TerrainEvaluator = class {
|
|
2033
|
+
cache = /* @__PURE__ */ new Map();
|
|
2034
|
+
bytes = 0;
|
|
2035
|
+
limit;
|
|
2036
|
+
constructor({ cacheMB = 48 } = {}) {
|
|
2037
|
+
if (!Number.isFinite(cacheMB) || cacheMB < 0)
|
|
2038
|
+
throw new RangeError("cacheMB must be finite and nonnegative");
|
|
2039
|
+
this.limit = cacheMB * 1024 * 1024;
|
|
2040
|
+
}
|
|
2041
|
+
clear() {
|
|
2042
|
+
this.cache.clear();
|
|
2043
|
+
this.bytes = 0;
|
|
2044
|
+
}
|
|
2045
|
+
evaluate(doc, { resolution = doc.config.resolution, signal, onProgress } = {}) {
|
|
2046
|
+
validateDocument(doc);
|
|
2047
|
+
validateConfig({ ...doc.config, resolution });
|
|
2048
|
+
const keys = [];
|
|
2049
|
+
let key = this.limit > 0 ? JSON.stringify({ ...doc.config, resolution }) : "";
|
|
2050
|
+
for (const layer2 of this.limit > 0 ? doc.layers : []) {
|
|
2051
|
+
key += `|${JSON.stringify(layer2)}`;
|
|
2052
|
+
keys.push(key);
|
|
2053
|
+
}
|
|
2054
|
+
let state;
|
|
2055
|
+
let start = 0;
|
|
2056
|
+
for (let i = keys.length - 1; i >= 0; i--) {
|
|
2057
|
+
const k = keys[i];
|
|
2058
|
+
const hit = this.cache.get(k);
|
|
2059
|
+
if (hit) {
|
|
2060
|
+
state = structuredClone(hit.state);
|
|
2061
|
+
start = i + 1;
|
|
2062
|
+
this.cache.delete(k);
|
|
2063
|
+
this.cache.set(k, hit);
|
|
2064
|
+
break;
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
state ??= createState(doc.config, resolution);
|
|
2068
|
+
for (let i = start; i < doc.layers.length; i++) {
|
|
2069
|
+
signal?.throwIfAborted();
|
|
2070
|
+
const layer2 = doc.layers[i];
|
|
2071
|
+
applyOperation(state, layer2);
|
|
2072
|
+
onProgress?.({ index: i, total: doc.layers.length, id: layer2.id });
|
|
2073
|
+
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);
|
|
2074
|
+
if (bytes <= this.limit) {
|
|
2075
|
+
while (this.bytes + bytes > this.limit && this.cache.size) {
|
|
2076
|
+
const first = this.cache.entries().next().value;
|
|
2077
|
+
if (!first) break;
|
|
2078
|
+
this.bytes -= first[1].bytes;
|
|
2079
|
+
this.cache.delete(first[0]);
|
|
2080
|
+
}
|
|
2081
|
+
this.cache.set(keys[i], { state: structuredClone(state), bytes });
|
|
2082
|
+
this.bytes += bytes;
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
signal?.throwIfAborted();
|
|
2086
|
+
if (!state.height.every(Number.isFinite))
|
|
2087
|
+
throw new Error("A terrain operation produced a non-finite height");
|
|
2088
|
+
return finalizeState(state);
|
|
2089
|
+
}
|
|
2090
|
+
};
|
|
2091
|
+
var Terrain = class _Terrain {
|
|
2092
|
+
_doc;
|
|
2093
|
+
_undo = [];
|
|
2094
|
+
_redo = [];
|
|
2095
|
+
_listeners = /* @__PURE__ */ new Set();
|
|
2096
|
+
_historyLimit;
|
|
2097
|
+
_transactionDepth = 0;
|
|
2098
|
+
_evaluator = new TerrainEvaluator();
|
|
2099
|
+
constructor({
|
|
2100
|
+
size = 512,
|
|
2101
|
+
resolution = 257,
|
|
2102
|
+
seed = 73,
|
|
2103
|
+
historyLimit = 60
|
|
2104
|
+
} = {}) {
|
|
2105
|
+
const config = { size, resolution, seed };
|
|
2106
|
+
validateConfig(config);
|
|
2107
|
+
if (!Number.isInteger(historyLimit) || historyLimit < 0)
|
|
2108
|
+
throw new RangeError("historyLimit must be a nonnegative integer");
|
|
2109
|
+
this._doc = { version: 1, config, layers: [] };
|
|
2110
|
+
this._historyLimit = historyLimit;
|
|
2111
|
+
}
|
|
2112
|
+
static fromJSON(json) {
|
|
2113
|
+
const doc = typeof json === "string" ? JSON.parse(json) : structuredClone(json);
|
|
2114
|
+
validateDocument(doc);
|
|
2115
|
+
const terrain = new _Terrain(doc.config);
|
|
2116
|
+
terrain._doc = doc;
|
|
2117
|
+
return terrain;
|
|
2118
|
+
}
|
|
2119
|
+
get layers() {
|
|
2120
|
+
return structuredClone(this._doc.layers);
|
|
2121
|
+
}
|
|
2122
|
+
get config() {
|
|
2123
|
+
return structuredClone(this._doc.config);
|
|
2124
|
+
}
|
|
2125
|
+
get canUndo() {
|
|
2126
|
+
return this._undo.length > 0;
|
|
2127
|
+
}
|
|
2128
|
+
get canRedo() {
|
|
2129
|
+
return this._redo.length > 0;
|
|
2130
|
+
}
|
|
2131
|
+
toJSON() {
|
|
2132
|
+
return structuredClone(this._doc);
|
|
2133
|
+
}
|
|
2134
|
+
subscribe(fn) {
|
|
2135
|
+
this._listeners.add(fn);
|
|
2136
|
+
return () => this._listeners.delete(fn);
|
|
2137
|
+
}
|
|
2138
|
+
_emit() {
|
|
2139
|
+
for (const fn of this._listeners) {
|
|
2140
|
+
try {
|
|
2141
|
+
fn(this);
|
|
2142
|
+
} catch (error) {
|
|
2143
|
+
console.error("Terrain subscriber failed:", error);
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
_change(fn) {
|
|
2148
|
+
const before = structuredClone(this._doc);
|
|
2149
|
+
try {
|
|
2150
|
+
fn();
|
|
2151
|
+
validateDocument(this._doc);
|
|
2152
|
+
} catch (error) {
|
|
2153
|
+
this._doc = before;
|
|
2154
|
+
throw error;
|
|
2155
|
+
}
|
|
2156
|
+
if (!this._transactionDepth) {
|
|
2157
|
+
this._undo.push(before);
|
|
2158
|
+
if (this._undo.length > this._historyLimit) this._undo.shift();
|
|
2159
|
+
this._redo = [];
|
|
2160
|
+
this._emit();
|
|
2161
|
+
}
|
|
2162
|
+
return this;
|
|
2163
|
+
}
|
|
2164
|
+
_id(type) {
|
|
2165
|
+
let i = 1;
|
|
2166
|
+
while (this._doc.layers.some((layer2) => layer2.id === `${type}-${i}`)) i++;
|
|
2167
|
+
return `${type}-${i}`;
|
|
2168
|
+
}
|
|
2169
|
+
add(layer2) {
|
|
2170
|
+
const next = { enabled: true, opacity: 1, ...structuredClone(layer2) };
|
|
2171
|
+
next.id ??= this._id(next.type);
|
|
2172
|
+
validateLayer(next);
|
|
2173
|
+
return this._change(() => {
|
|
2174
|
+
const i = this._doc.layers.findIndex((layer3) => layer3.id === next.id);
|
|
2175
|
+
if (i < 0) this._doc.layers.push(next);
|
|
2176
|
+
else this._doc.layers[i] = next;
|
|
2177
|
+
});
|
|
2178
|
+
}
|
|
2179
|
+
_operation(type, options) {
|
|
2180
|
+
const { id, label, enabled, opacity, mask, ...params } = options;
|
|
2181
|
+
if ("data" in params && params.data && typeof params.data === "object" && "values" in params.data && ArrayBuffer.isView(params.data.values)) {
|
|
2182
|
+
const data = params.data;
|
|
2183
|
+
Object.assign(params, { data: { ...data, values: Array.from(data.values) } });
|
|
2184
|
+
}
|
|
2185
|
+
const layer2 = { id: id ?? this._id(type), type, params };
|
|
2186
|
+
const optional = Object.fromEntries(
|
|
2187
|
+
Object.entries({ name: label, enabled, opacity, mask }).filter(
|
|
2188
|
+
([, value]) => value !== void 0
|
|
2189
|
+
)
|
|
2190
|
+
);
|
|
2191
|
+
return this.add(Object.assign(layer2, optional));
|
|
2192
|
+
}
|
|
2193
|
+
layer(id) {
|
|
2194
|
+
const layer2 = this._doc.layers.find((layer3) => layer3.id === id);
|
|
2195
|
+
if (!layer2) throw new Error(`Unknown layer '${id}'`);
|
|
2196
|
+
return structuredClone(layer2);
|
|
2197
|
+
}
|
|
2198
|
+
update(id, patch) {
|
|
2199
|
+
const old = this.layer(id);
|
|
2200
|
+
const next = {
|
|
2201
|
+
...old,
|
|
2202
|
+
...structuredClone(patch),
|
|
2203
|
+
id,
|
|
2204
|
+
params: { ...old.params, ...structuredClone(patch.params ?? {}) }
|
|
2205
|
+
};
|
|
2206
|
+
const { mask: _mask, ...unmasked } = next;
|
|
2207
|
+
return this.add(patch.mask === null ? unmasked : next);
|
|
2208
|
+
}
|
|
2209
|
+
toggle(id, enabled = this.layer(id).enabled === false) {
|
|
2210
|
+
return this.update(id, { enabled });
|
|
2211
|
+
}
|
|
2212
|
+
move(id, index) {
|
|
2213
|
+
if (!Number.isInteger(index) || index < 0 || index >= this._doc.layers.length)
|
|
2214
|
+
throw new RangeError("Layer index out of bounds");
|
|
2215
|
+
return this._change(() => {
|
|
2216
|
+
const i = this._doc.layers.findIndex((layer3) => layer3.id === id);
|
|
2217
|
+
if (i < 0) throw new Error(`Unknown layer '${id}'`);
|
|
2218
|
+
const layer2 = this._doc.layers.splice(i, 1)[0];
|
|
2219
|
+
this._doc.layers.splice(index, 0, layer2);
|
|
2220
|
+
});
|
|
2221
|
+
}
|
|
2222
|
+
remove(id) {
|
|
2223
|
+
this.layer(id);
|
|
2224
|
+
return this._change(() => {
|
|
2225
|
+
this._doc.layers = this._doc.layers.filter((layer2) => layer2.id !== id);
|
|
2226
|
+
});
|
|
2227
|
+
}
|
|
2228
|
+
setConfig(patch) {
|
|
2229
|
+
const config = { ...this._doc.config, ...patch };
|
|
2230
|
+
validateConfig(config);
|
|
2231
|
+
return this._change(() => {
|
|
2232
|
+
this._doc.config = config;
|
|
2233
|
+
});
|
|
2234
|
+
}
|
|
2235
|
+
loadJSON(json) {
|
|
2236
|
+
const next = _Terrain.fromJSON(json).toJSON();
|
|
2237
|
+
return this._change(() => {
|
|
2238
|
+
this._doc = next;
|
|
2239
|
+
});
|
|
2240
|
+
}
|
|
2241
|
+
transaction(fn) {
|
|
2242
|
+
if (fn.constructor.name === "AsyncFunction")
|
|
2243
|
+
throw new TypeError("Transactions must be synchronous");
|
|
2244
|
+
const before = structuredClone(this._doc);
|
|
2245
|
+
const undo = this._undo.slice();
|
|
2246
|
+
const redo = this._redo.slice();
|
|
2247
|
+
this._transactionDepth++;
|
|
2248
|
+
try {
|
|
2249
|
+
const result = fn(this);
|
|
2250
|
+
if (result && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function")
|
|
2251
|
+
throw new TypeError("Transactions must be synchronous");
|
|
2252
|
+
validateDocument(this._doc);
|
|
2253
|
+
this._transactionDepth--;
|
|
2254
|
+
if (!this._transactionDepth) {
|
|
2255
|
+
this._undo.push(before);
|
|
2256
|
+
if (this._undo.length > this._historyLimit) this._undo.shift();
|
|
2257
|
+
this._redo = [];
|
|
2258
|
+
this._emit();
|
|
2259
|
+
}
|
|
2260
|
+
return this;
|
|
2261
|
+
} catch (error) {
|
|
2262
|
+
this._transactionDepth--;
|
|
2263
|
+
this._doc = before;
|
|
2264
|
+
this._undo = undo;
|
|
2265
|
+
this._redo = redo;
|
|
2266
|
+
throw error;
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
applyPatch(commands) {
|
|
2270
|
+
return this.transaction(() => {
|
|
2271
|
+
for (const command of commands) {
|
|
2272
|
+
switch (command.op) {
|
|
2273
|
+
case "upsert":
|
|
2274
|
+
this.add(command.layer);
|
|
2275
|
+
break;
|
|
2276
|
+
case "update":
|
|
2277
|
+
this.update(command.id, command.patch);
|
|
2278
|
+
break;
|
|
2279
|
+
case "remove":
|
|
2280
|
+
this.remove(command.id);
|
|
2281
|
+
break;
|
|
2282
|
+
case "move":
|
|
2283
|
+
this.move(command.id, command.index);
|
|
2284
|
+
break;
|
|
2285
|
+
case "toggle":
|
|
2286
|
+
this.toggle(command.id, command.enabled);
|
|
2287
|
+
break;
|
|
2288
|
+
default:
|
|
2289
|
+
throw new Error("Unknown patch command");
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
2292
|
+
});
|
|
2293
|
+
}
|
|
2294
|
+
undo() {
|
|
2295
|
+
const prior = this._undo.pop();
|
|
2296
|
+
if (prior) {
|
|
2297
|
+
this._redo.push(structuredClone(this._doc));
|
|
2298
|
+
this._doc = prior;
|
|
2299
|
+
this._emit();
|
|
2300
|
+
}
|
|
2301
|
+
return this;
|
|
2302
|
+
}
|
|
2303
|
+
redo() {
|
|
2304
|
+
const next = this._redo.pop();
|
|
2305
|
+
if (next) {
|
|
2306
|
+
this._undo.push(structuredClone(this._doc));
|
|
2307
|
+
this._doc = next;
|
|
2308
|
+
this._emit();
|
|
2309
|
+
}
|
|
2310
|
+
return this;
|
|
2311
|
+
}
|
|
2312
|
+
evaluate(options) {
|
|
2313
|
+
return this._evaluator.evaluate(this._doc, options);
|
|
2314
|
+
}
|
|
2315
|
+
clearCache() {
|
|
2316
|
+
this._evaluator.clear();
|
|
2317
|
+
}
|
|
2318
|
+
copyRegion({ at = [0, 0], size = 64, resolution = 33 } = {}) {
|
|
2319
|
+
if (!RESOLUTIONS.includes(resolution)) throw new RangeError("Unsupported copy resolution");
|
|
2320
|
+
if (!(size > 0 && Number.isFinite(size))) throw new RangeError("Copy size must be positive");
|
|
2321
|
+
const state = this.evaluate();
|
|
2322
|
+
const values = [];
|
|
2323
|
+
for (let z = 0; z < resolution; z++)
|
|
2324
|
+
for (let x = 0; x < resolution; x++)
|
|
2325
|
+
values.push(
|
|
2326
|
+
sampleHeight(
|
|
2327
|
+
state,
|
|
2328
|
+
at[0] + (x / (resolution - 1) - 0.5) * size,
|
|
2329
|
+
at[1] + (z / (resolution - 1) - 0.5) * size
|
|
2330
|
+
)
|
|
2331
|
+
);
|
|
2332
|
+
return { width: resolution, height: resolution, values };
|
|
2333
|
+
}
|
|
2334
|
+
inspect(options) {
|
|
2335
|
+
const state = this.evaluate(options);
|
|
2336
|
+
let min = Number.POSITIVE_INFINITY;
|
|
2337
|
+
let max = Number.NEGATIVE_INFINITY;
|
|
2338
|
+
for (const height of state.height) {
|
|
2339
|
+
min = Math.min(min, height);
|
|
2340
|
+
max = Math.max(max, height);
|
|
2341
|
+
}
|
|
2342
|
+
return {
|
|
2343
|
+
size: state.size,
|
|
2344
|
+
resolution: state.resolution,
|
|
2345
|
+
layers: this._doc.layers.length,
|
|
2346
|
+
vertices: state.height.length,
|
|
2347
|
+
triangles: 2 * (state.resolution - 1) ** 2,
|
|
2348
|
+
minHeight: min,
|
|
2349
|
+
maxHeight: max,
|
|
2350
|
+
instances: state.instances.length,
|
|
2351
|
+
diagnostics: state.diagnostics
|
|
2352
|
+
};
|
|
2353
|
+
}
|
|
2354
|
+
noise(options = {}) {
|
|
2355
|
+
return this._operation("noise", options);
|
|
2356
|
+
}
|
|
2357
|
+
sculpt(options = {}) {
|
|
2358
|
+
return this._operation("sculpt", options);
|
|
2359
|
+
}
|
|
2360
|
+
smooth(options = {}) {
|
|
2361
|
+
return this._operation("smooth", options);
|
|
2362
|
+
}
|
|
2363
|
+
flatten(options = {}) {
|
|
2364
|
+
return this._operation("flatten", options);
|
|
2365
|
+
}
|
|
2366
|
+
ramp(options) {
|
|
2367
|
+
return this._operation("ramp", options);
|
|
2368
|
+
}
|
|
2369
|
+
stamp(options = {}) {
|
|
2370
|
+
return this._operation("stamp", options);
|
|
2371
|
+
}
|
|
2372
|
+
erode(options = {}) {
|
|
2373
|
+
return this._operation("erode", options);
|
|
2374
|
+
}
|
|
2375
|
+
terrace(options = {}) {
|
|
2376
|
+
return this._operation("terrace", options);
|
|
2377
|
+
}
|
|
2378
|
+
materials(options) {
|
|
2379
|
+
return this._operation("materials", options);
|
|
2380
|
+
}
|
|
2381
|
+
paint(options = {}) {
|
|
2382
|
+
return this._operation("paint", options);
|
|
2383
|
+
}
|
|
2384
|
+
biome(options = {}) {
|
|
2385
|
+
return this._operation("biome", options);
|
|
2386
|
+
}
|
|
2387
|
+
scatter(options) {
|
|
2388
|
+
return this._operation("scatter", options);
|
|
2389
|
+
}
|
|
2390
|
+
clear(options) {
|
|
2391
|
+
return this._operation("clear", options);
|
|
2392
|
+
}
|
|
2393
|
+
road(options) {
|
|
2394
|
+
return this._operation("road", options);
|
|
2395
|
+
}
|
|
2396
|
+
river(options) {
|
|
2397
|
+
return this._operation("river", options);
|
|
2398
|
+
}
|
|
2399
|
+
water(options = {}) {
|
|
2400
|
+
return this._operation("water", options);
|
|
2401
|
+
}
|
|
2402
|
+
heightmap(options) {
|
|
2403
|
+
return this._operation("heightmap", options);
|
|
2404
|
+
}
|
|
2405
|
+
paste(options) {
|
|
2406
|
+
return this._operation("paste", options);
|
|
2407
|
+
}
|
|
2408
|
+
};
|
|
2409
|
+
|
|
2410
|
+
// src/core/presets.ts
|
|
2411
|
+
var LANDFORMS = {
|
|
2412
|
+
alpine: {
|
|
2413
|
+
summary: "Glacier-cut granite peaks: steep headwalls, sharp ar\xEAtes, dendritic gullies.",
|
|
2414
|
+
reliefRatio: 0.25,
|
|
2415
|
+
reference: "Longs Peak, Rocky Mountain National Park, Colorado (USGS 3DEP, DEM crop `alpine`)",
|
|
2416
|
+
target: { slopeP50: 27.3, slopeP90: 42.5, hypsometricIntegral: 0.452, curvatureKurtosis: 89.3 }
|
|
2417
|
+
},
|
|
2418
|
+
temperateMountains: {
|
|
2419
|
+
summary: "Forested mountain backdrop: rounded massifs cut by branching valleys.",
|
|
2420
|
+
reliefRatio: 0.17,
|
|
2421
|
+
reference: "Sprague Lake / Glacier Creek, Rocky Mountain National Park (DEM crop `forest`)",
|
|
2422
|
+
target: { slopeP50: 14.7, slopeP90: 28.1, hypsometricIntegral: 0.398, curvatureKurtosis: 13.7 }
|
|
2423
|
+
},
|
|
2424
|
+
rollingHills: {
|
|
2425
|
+
summary: "Low dendritic hills with convex ridges and gentle slopes.",
|
|
2426
|
+
reliefRatio: 0.03,
|
|
2427
|
+
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"
|
|
2428
|
+
},
|
|
2429
|
+
desertMesa: {
|
|
2430
|
+
summary: "Caprock mesas and buttes over a stepped, cliff-and-bench canyon landscape.",
|
|
2431
|
+
reliefRatio: 0.055,
|
|
2432
|
+
reference: "Valley of the Gods, Utah (DEM crop `desert`)",
|
|
2433
|
+
target: { slopeP50: 3.7, slopeP90: 16.9, hypsometricIntegral: 0.276, curvatureKurtosis: 203.9 }
|
|
2434
|
+
},
|
|
2435
|
+
coastalCliffs: {
|
|
2436
|
+
summary: "Island massif with steep rocky shore and drowned gullies.",
|
|
2437
|
+
reliefRatio: 0.075,
|
|
2438
|
+
reference: "Sand Beach / Great Head, Acadia National Park, Maine (DEM crop `coastal`)",
|
|
2439
|
+
target: { slopeP50: 1.6, slopeP90: 19.4, hypsometricIntegral: 0.11, curvatureKurtosis: 34.7 }
|
|
2440
|
+
},
|
|
2441
|
+
tundra: {
|
|
2442
|
+
summary: "Broad rounded uplands above the tree line with shallow glacial valleys.",
|
|
2443
|
+
reliefRatio: 0.15,
|
|
2444
|
+
reference: "Trail Ridge, Rocky Mountain National Park (DEM crop `tundra`)",
|
|
2445
|
+
target: { slopeP50: 17.1, slopeP90: 27.9, hypsometricIntegral: 0.473, curvatureKurtosis: 16.7 }
|
|
2446
|
+
},
|
|
2447
|
+
volcanic: {
|
|
2448
|
+
summary: "Stratovolcano cone with a summit crater and radial gullies.",
|
|
2449
|
+
reliefRatio: 0.18,
|
|
2450
|
+
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"
|
|
2451
|
+
}
|
|
2452
|
+
};
|
|
2453
|
+
|
|
2454
|
+
// src/core/biome.ts
|
|
2455
|
+
var SPEC_FIELDS = [
|
|
2456
|
+
"look",
|
|
2457
|
+
"bake",
|
|
2458
|
+
"landform",
|
|
2459
|
+
"sizeMeters",
|
|
2460
|
+
"seed",
|
|
2461
|
+
"stream",
|
|
2462
|
+
"cover",
|
|
2463
|
+
"foliage",
|
|
2464
|
+
"grass",
|
|
2465
|
+
"layers",
|
|
2466
|
+
"water",
|
|
2467
|
+
"spawn",
|
|
2468
|
+
"species",
|
|
2469
|
+
"aliases"
|
|
2470
|
+
];
|
|
2471
|
+
var COVER_FIELDS = ["ground", "seed", "attempts", "stoneRadius", "clearings"];
|
|
2472
|
+
var COVER_GROUNDS = ["wood", "crag", "mesa", "mats"];
|
|
2473
|
+
var STREAMS = ["ordered", "seeded"];
|
|
2474
|
+
var DRIFT_FIELDS = ["field", "frequency", "offset", "amplitude", "band"];
|
|
2475
|
+
var DRIFT_FIELDS_NAMES = ["stand", "mats"];
|
|
2476
|
+
var FOLIAGE_FIELDS = [
|
|
2477
|
+
"species",
|
|
2478
|
+
"density",
|
|
2479
|
+
"slope",
|
|
2480
|
+
"height",
|
|
2481
|
+
"spacing",
|
|
2482
|
+
"collision",
|
|
2483
|
+
"stands",
|
|
2484
|
+
"grassThreshold",
|
|
2485
|
+
"standThreshold",
|
|
2486
|
+
"far"
|
|
2487
|
+
];
|
|
2488
|
+
var FAR_FIELDS = [
|
|
2489
|
+
"cell",
|
|
2490
|
+
"spacing",
|
|
2491
|
+
"spacingAt",
|
|
2492
|
+
"slope",
|
|
2493
|
+
"meadowSlope",
|
|
2494
|
+
"reach",
|
|
2495
|
+
"treelineJitter",
|
|
2496
|
+
"stand",
|
|
2497
|
+
"seed",
|
|
2498
|
+
"impostor"
|
|
2499
|
+
];
|
|
2500
|
+
var GRASS_FIELDS = [
|
|
2501
|
+
"species",
|
|
2502
|
+
"density",
|
|
2503
|
+
"slope",
|
|
2504
|
+
"height",
|
|
2505
|
+
"spacing",
|
|
2506
|
+
"slopeFalloff",
|
|
2507
|
+
"heightFalloff",
|
|
2508
|
+
"mats",
|
|
2509
|
+
"waterMargin",
|
|
2510
|
+
"beach",
|
|
2511
|
+
"detailSpacing",
|
|
2512
|
+
"drift",
|
|
2513
|
+
"bladeScale",
|
|
2514
|
+
"bladeJitter",
|
|
2515
|
+
"scrubChance",
|
|
2516
|
+
"scrubScale",
|
|
2517
|
+
"scrubJitter",
|
|
2518
|
+
"scrubBush",
|
|
2519
|
+
"shoreGround",
|
|
2520
|
+
"cobbledBed"
|
|
2521
|
+
];
|
|
2522
|
+
var BAKE_FIELDS = ["file", "key"];
|
|
2523
|
+
var LAYER_FIELDS = ["layer", "from", "to", "shedFrom", "shedTo"];
|
|
2524
|
+
var LAYER_REQUIRED = ["layer", "from", "to"];
|
|
2525
|
+
var WATER_FIELDS = ["kind", "width", "radius", "depth", "level"];
|
|
2526
|
+
var WATER_REQUIRED = ["kind"];
|
|
2527
|
+
var SPAWN_FIELDS = ["at", "cameraOffset", "focus"];
|
|
2528
|
+
var LANDFORM_KINDS = Object.keys(LANDFORMS);
|
|
2529
|
+
var COLLISION_CLASSES = ["none", "trunk", "hull"];
|
|
2530
|
+
var WATER_KINDS = ["river", "lake", "ocean"];
|
|
2531
|
+
function fail2(biome, field, problem) {
|
|
2532
|
+
throw new TypeError(`${biome}: biome field '${field}' ${problem}.`);
|
|
2533
|
+
}
|
|
2534
|
+
function closed(value, biome, field, fields, required = fields) {
|
|
2535
|
+
const at = (name) => field === "" ? name : `${field}.${name}`;
|
|
2536
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
2537
|
+
fail2(biome, field || "<file>", "must be an object");
|
|
2538
|
+
const record = value;
|
|
2539
|
+
for (const key of Object.keys(record))
|
|
2540
|
+
if (!fields.includes(key)) fail2(biome, at(key), "is not a field a biome has");
|
|
2541
|
+
for (const key of required) if (!(key in record)) fail2(biome, at(key), "is missing");
|
|
2542
|
+
return record;
|
|
2543
|
+
}
|
|
2544
|
+
function count(value, biome, field, min = 0) {
|
|
2545
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
2546
|
+
fail2(biome, field, "must be a finite number");
|
|
2547
|
+
if (value < min) fail2(biome, field, `must be at least ${min}`);
|
|
2548
|
+
return value;
|
|
2549
|
+
}
|
|
2550
|
+
function positive(value, biome, field) {
|
|
2551
|
+
const number = count(value, biome, field);
|
|
2552
|
+
if (number === 0) fail2(biome, field, "must be greater than 0");
|
|
2553
|
+
return number;
|
|
2554
|
+
}
|
|
2555
|
+
function whole(value, biome, field, min = 0) {
|
|
2556
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value))
|
|
2557
|
+
fail2(biome, field, "must be a whole number");
|
|
2558
|
+
if (value < min) fail2(biome, field, `must be at least ${min}`);
|
|
2559
|
+
return value;
|
|
2560
|
+
}
|
|
2561
|
+
function share(value, biome, field) {
|
|
2562
|
+
const number = count(value, biome, field);
|
|
2563
|
+
if (number > 1) fail2(biome, field, "must be at most 1");
|
|
2564
|
+
return number;
|
|
2565
|
+
}
|
|
2566
|
+
function flag(value, biome, field) {
|
|
2567
|
+
if (typeof value !== "boolean") fail2(biome, field, "must be true or false");
|
|
2568
|
+
return value;
|
|
2569
|
+
}
|
|
2570
|
+
function text(value, biome, field) {
|
|
2571
|
+
if (typeof value !== "string" || value.trim() === "")
|
|
2572
|
+
fail2(biome, field, "must be a non-empty string");
|
|
2573
|
+
return value;
|
|
2574
|
+
}
|
|
2575
|
+
function oneOf(value, biome, field, options) {
|
|
2576
|
+
if (typeof value !== "string" || !options.includes(value))
|
|
2577
|
+
fail2(biome, field, `must be one of ${options.join(", ")}`);
|
|
2578
|
+
return value;
|
|
2579
|
+
}
|
|
2580
|
+
function intervalOf(value, biome, field, size, min = 0, max = Number.POSITIVE_INFINITY) {
|
|
2581
|
+
if (!Array.isArray(value) || value.length !== size)
|
|
2582
|
+
fail2(biome, field, `must be an array of ${size} numbers`);
|
|
2583
|
+
const numbers = value.map((entry2, index) => count(entry2, biome, `${field}[${index}]`, min));
|
|
2584
|
+
if (numbers[0] > numbers[1])
|
|
2585
|
+
fail2(biome, field, "must ascend");
|
|
2586
|
+
for (const [index, entry2] of numbers.entries())
|
|
2587
|
+
if (entry2 > max) fail2(biome, `${field}[${index}]`, `must be at most ${max}`);
|
|
2588
|
+
return numbers;
|
|
2589
|
+
}
|
|
2590
|
+
function band(value, biome, field) {
|
|
2591
|
+
if (!Array.isArray(value) || value.length !== 2)
|
|
2592
|
+
fail2(biome, field, "must be an array of 2 numbers");
|
|
2593
|
+
const [threshold = 0, span = 0] = value.map(
|
|
2594
|
+
(entry2, index) => share(entry2, biome, `${field}[${index}]`)
|
|
2595
|
+
);
|
|
2596
|
+
if (span === 0) fail2(biome, `${field}[1]`, "must be greater than 0");
|
|
2597
|
+
return [threshold, span];
|
|
2598
|
+
}
|
|
2599
|
+
function pair(value, biome, field, min = 0, max = Number.POSITIVE_INFINITY) {
|
|
2600
|
+
const [first = 0, second = 0] = intervalOf(value, biome, field, 2, min, max);
|
|
2601
|
+
return [first, second];
|
|
2602
|
+
}
|
|
2603
|
+
function pointOf(value, biome, field, size) {
|
|
2604
|
+
if (!Array.isArray(value) || value.length !== size)
|
|
2605
|
+
fail2(biome, field, `must be an array of ${size} numbers`);
|
|
2606
|
+
return value.map((entry2, index) => {
|
|
2607
|
+
if (typeof entry2 !== "number" || !Number.isFinite(entry2))
|
|
2608
|
+
fail2(biome, `${field}[${index}]`, "must be a finite number");
|
|
2609
|
+
return entry2 ?? 0;
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2612
|
+
function point2(value, biome, field) {
|
|
2613
|
+
const [x = 0, z = 0] = pointOf(value, biome, field, 2);
|
|
2614
|
+
return [x, z];
|
|
2615
|
+
}
|
|
2616
|
+
function point3(value, biome, field) {
|
|
2617
|
+
const [x = 0, y = 0, z = 0] = pointOf(value, biome, field, 3);
|
|
2618
|
+
return [x, y, z];
|
|
2619
|
+
}
|
|
2620
|
+
function far(value, biome, field) {
|
|
2621
|
+
if (value === null) return null;
|
|
2622
|
+
const far2 = closed(value, biome, field, FAR_FIELDS);
|
|
2623
|
+
return {
|
|
2624
|
+
cell: positive(far2.cell, biome, `${field}.cell`),
|
|
2625
|
+
spacing: pair(far2.spacing, biome, `${field}.spacing`),
|
|
2626
|
+
spacingAt: pair(far2.spacingAt, biome, `${field}.spacingAt`),
|
|
2627
|
+
slope: pair(far2.slope, biome, `${field}.slope`, 0, 90),
|
|
2628
|
+
meadowSlope: pair(far2.meadowSlope, biome, `${field}.meadowSlope`, 0, 90),
|
|
2629
|
+
reach: positive(far2.reach, biome, `${field}.reach`),
|
|
2630
|
+
treelineJitter: count(far2.treelineJitter, biome, `${field}.treelineJitter`),
|
|
2631
|
+
stand: pair(far2.stand, biome, `${field}.stand`, 0, 1),
|
|
2632
|
+
seed: whole(far2.seed, biome, `${field}.seed`),
|
|
2633
|
+
impostor: count(far2.impostor, biome, `${field}.impostor`)
|
|
2634
|
+
};
|
|
2635
|
+
}
|
|
2636
|
+
function frequencies(value, biome, field) {
|
|
2637
|
+
const [x = 0, z = 0] = pointOf(value, biome, field, 2);
|
|
2638
|
+
if (x <= 0 || z <= 0) fail2(biome, field, "must be two positive frequencies");
|
|
2639
|
+
return [x, z];
|
|
2640
|
+
}
|
|
2641
|
+
function driftRow(value, biome, field) {
|
|
2642
|
+
const row = closed(value, biome, field, DRIFT_FIELDS);
|
|
2643
|
+
return {
|
|
2644
|
+
field: oneOf(row.field, biome, `${field}.field`, DRIFT_FIELDS_NAMES),
|
|
2645
|
+
frequency: frequencies(row.frequency, biome, `${field}.frequency`),
|
|
2646
|
+
offset: share(row.offset, biome, `${field}.offset`),
|
|
2647
|
+
amplitude: share(row.amplitude, biome, `${field}.amplitude`),
|
|
2648
|
+
band: band(row.band, biome, `${field}.band`)
|
|
2649
|
+
};
|
|
2650
|
+
}
|
|
2651
|
+
function clearing(value, biome, field) {
|
|
2652
|
+
if (!Array.isArray(value) || value.length !== 3)
|
|
2653
|
+
fail2(biome, field, "must be an array of 3 numbers");
|
|
2654
|
+
const [x = 0, z = 0, radius = 0] = pointOf(value, biome, field, 3);
|
|
2655
|
+
if (radius <= 0) fail2(biome, `${field}[2]`, "must be greater than 0");
|
|
2656
|
+
return [x, z, radius];
|
|
2657
|
+
}
|
|
2658
|
+
function cover(value, biome) {
|
|
2659
|
+
const row = closed(value, biome, "cover", COVER_FIELDS);
|
|
2660
|
+
const clearings = row.clearings;
|
|
2661
|
+
if (!Array.isArray(clearings)) fail2(biome, "cover.clearings", "must be an array");
|
|
2662
|
+
return {
|
|
2663
|
+
ground: oneOf(row.ground, biome, "cover.ground", COVER_GROUNDS),
|
|
2664
|
+
seed: whole(row.seed, biome, "cover.seed"),
|
|
2665
|
+
attempts: whole(row.attempts, biome, "cover.attempts", 1),
|
|
2666
|
+
stoneRadius: positive(row.stoneRadius, biome, "cover.stoneRadius"),
|
|
2667
|
+
clearings: clearings.map((entry2, index) => clearing(entry2, biome, `cover.clearings[${index}]`))
|
|
2668
|
+
};
|
|
2669
|
+
}
|
|
2670
|
+
function foliage(value, biome, field) {
|
|
2671
|
+
const row = closed(value, biome, field, FOLIAGE_FIELDS);
|
|
2672
|
+
const height = row.height === null ? null : pair(row.height, biome, `${field}.height`);
|
|
2673
|
+
return {
|
|
2674
|
+
species: text(row.species, biome, `${field}.species`),
|
|
2675
|
+
density: count(row.density, biome, `${field}.density`),
|
|
2676
|
+
slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
|
|
2677
|
+
height,
|
|
2678
|
+
spacing: pair(row.spacing, biome, `${field}.spacing`),
|
|
2679
|
+
collision: oneOf(row.collision, biome, `${field}.collision`, COLLISION_CLASSES),
|
|
2680
|
+
stands: flag(row.stands, biome, `${field}.stands`),
|
|
2681
|
+
grassThreshold: share(row.grassThreshold, biome, `${field}.grassThreshold`),
|
|
2682
|
+
standThreshold: share(row.standThreshold, biome, `${field}.standThreshold`),
|
|
2683
|
+
far: far(row.far, biome, `${field}.far`)
|
|
2684
|
+
};
|
|
2685
|
+
}
|
|
2686
|
+
function grass(value, biome, field) {
|
|
2687
|
+
const row = closed(value, biome, field, GRASS_FIELDS);
|
|
2688
|
+
const density = count(row.density, biome, `${field}.density`);
|
|
2689
|
+
if (density > 1) fail2(biome, `${field}.density`, "must be at most 1");
|
|
2690
|
+
return {
|
|
2691
|
+
species: text(row.species, biome, `${field}.species`),
|
|
2692
|
+
density,
|
|
2693
|
+
slope: pair(row.slope, biome, `${field}.slope`, 0, 90),
|
|
2694
|
+
height: row.height === null ? null : pair(row.height, biome, `${field}.height`),
|
|
2695
|
+
spacing: positive(row.spacing, biome, `${field}.spacing`),
|
|
2696
|
+
slopeFalloff: count(row.slopeFalloff, biome, `${field}.slopeFalloff`),
|
|
2697
|
+
heightFalloff: count(row.heightFalloff, biome, `${field}.heightFalloff`),
|
|
2698
|
+
mats: row.mats === null ? null : band(row.mats, biome, `${field}.mats`),
|
|
2699
|
+
waterMargin: count(row.waterMargin, biome, `${field}.waterMargin`),
|
|
2700
|
+
beach: row.beach === null ? null : pair(row.beach, biome, `${field}.beach`),
|
|
2701
|
+
detailSpacing: positive(row.detailSpacing, biome, `${field}.detailSpacing`),
|
|
2702
|
+
drift: driftRow(row.drift, biome, `${field}.drift`),
|
|
2703
|
+
bladeScale: count(row.bladeScale, biome, `${field}.bladeScale`),
|
|
2704
|
+
bladeJitter: count(row.bladeJitter, biome, `${field}.bladeJitter`),
|
|
2705
|
+
scrubChance: share(row.scrubChance, biome, `${field}.scrubChance`),
|
|
2706
|
+
scrubScale: count(row.scrubScale, biome, `${field}.scrubScale`),
|
|
2707
|
+
scrubJitter: count(row.scrubJitter, biome, `${field}.scrubJitter`),
|
|
2708
|
+
scrubBush: flag(row.scrubBush, biome, `${field}.scrubBush`),
|
|
2709
|
+
shoreGround: flag(row.shoreGround, biome, `${field}.shoreGround`),
|
|
2710
|
+
cobbledBed: flag(row.cobbledBed, biome, `${field}.cobbledBed`)
|
|
2711
|
+
};
|
|
2712
|
+
}
|
|
2713
|
+
function layer(value, biome, field) {
|
|
2714
|
+
const row = closed(value, biome, field, LAYER_FIELDS, LAYER_REQUIRED);
|
|
2715
|
+
const from = count(row.from, biome, `${field}.from`);
|
|
2716
|
+
const to = count(row.to, biome, `${field}.to`);
|
|
2717
|
+
if (from >= to) fail2(biome, field, "must end above where it starts");
|
|
2718
|
+
const shedFrom = row.shedFrom === void 0 ? void 0 : count(row.shedFrom, biome, `${field}.shedFrom`, 0);
|
|
2719
|
+
const shedTo = row.shedTo === void 0 ? void 0 : count(row.shedTo, biome, `${field}.shedTo`, 0);
|
|
2720
|
+
for (const [key, entry2] of [
|
|
2721
|
+
["shedFrom", shedFrom],
|
|
2722
|
+
["shedTo", shedTo]
|
|
2723
|
+
])
|
|
2724
|
+
if (entry2 !== void 0 && entry2 > 1) fail2(biome, `${field}.${key}`, "must be at most 1");
|
|
2725
|
+
if (shedFrom !== void 0 && shedTo !== void 0 && shedFrom >= shedTo)
|
|
2726
|
+
fail2(biome, field, "must shed from a gentler slope than it sheds to");
|
|
2727
|
+
return {
|
|
2728
|
+
layer: text(row.layer, biome, `${field}.layer`),
|
|
2729
|
+
from,
|
|
2730
|
+
to,
|
|
2731
|
+
shedFrom,
|
|
2732
|
+
shedTo
|
|
2733
|
+
};
|
|
2734
|
+
}
|
|
2735
|
+
function water(value, biome, field) {
|
|
2736
|
+
const row = closed(value, biome, field, WATER_FIELDS, WATER_REQUIRED);
|
|
2737
|
+
const kind = oneOf(row.kind, biome, `${field}.kind`, WATER_KINDS);
|
|
2738
|
+
const width = row.width === void 0 ? void 0 : positive(row.width, biome, `${field}.width`);
|
|
2739
|
+
const radius = row.radius === void 0 ? void 0 : positive(row.radius, biome, `${field}.radius`);
|
|
2740
|
+
const depth = row.depth === void 0 ? void 0 : positive(row.depth, biome, `${field}.depth`);
|
|
2741
|
+
const level = row.level === void 0 ? void 0 : count(row.level, biome, `${field}.level`);
|
|
2742
|
+
if (kind === "river" && width === void 0) fail2(biome, `${field}.width`, "is missing");
|
|
2743
|
+
if (kind === "lake" && radius === void 0) fail2(biome, `${field}.radius`, "is missing");
|
|
2744
|
+
if (kind === "ocean" && level === void 0) fail2(biome, `${field}.level`, "is missing");
|
|
2745
|
+
return { kind, width, radius, depth, level };
|
|
2746
|
+
}
|
|
2747
|
+
function bake(value, biome) {
|
|
2748
|
+
const row = closed(value, biome, "bake", BAKE_FIELDS);
|
|
2749
|
+
return {
|
|
2750
|
+
file: text(row.file, biome, "bake.file"),
|
|
2751
|
+
key: row.key === null ? null : text(row.key, biome, "bake.key")
|
|
2752
|
+
};
|
|
2753
|
+
}
|
|
2754
|
+
function spawn2(value, biome) {
|
|
2755
|
+
const row = closed(value, biome, "spawn", SPAWN_FIELDS);
|
|
2756
|
+
return {
|
|
2757
|
+
at: point2(row.at, biome, "spawn.at"),
|
|
2758
|
+
cameraOffset: point3(row.cameraOffset, biome, "spawn.cameraOffset"),
|
|
2759
|
+
focus: point2(row.focus, biome, "spawn.focus")
|
|
2760
|
+
};
|
|
2761
|
+
}
|
|
2762
|
+
function species(value, biome) {
|
|
2763
|
+
if (!Array.isArray(value) || value.length === 0)
|
|
2764
|
+
fail2(biome, "species", "must be a non-empty array of asset ids");
|
|
2765
|
+
const names = value.map((name, index) => text(name, biome, `species[${index}]`));
|
|
2766
|
+
for (const [index, name] of names.entries())
|
|
2767
|
+
if (names.indexOf(name) !== index) fail2(biome, `species[${index}]`, `repeats '${name}'`);
|
|
2768
|
+
return names;
|
|
2769
|
+
}
|
|
2770
|
+
function validateBiome(spec, name) {
|
|
2771
|
+
if (typeof name !== "string" || name.trim() === "")
|
|
2772
|
+
throw new TypeError("validateBiome needs the biome's name");
|
|
2773
|
+
const biome = name;
|
|
2774
|
+
const root = closed(spec, biome, "", SPEC_FIELDS);
|
|
2775
|
+
const aliases = root.aliases;
|
|
2776
|
+
if (!Array.isArray(aliases) || aliases.length === 0)
|
|
2777
|
+
fail2(biome, "aliases", "must be a non-empty array of words");
|
|
2778
|
+
const rows = (value, field, one) => {
|
|
2779
|
+
if (!Array.isArray(value)) fail2(biome, field, "must be an array");
|
|
2780
|
+
return value.map((entry2, index) => one(entry2, `${field}[${index}]`));
|
|
2781
|
+
};
|
|
2782
|
+
return {
|
|
2783
|
+
look: text(root.look, biome, "look"),
|
|
2784
|
+
bake: bake(root.bake, biome),
|
|
2785
|
+
landform: oneOf(root.landform, biome, "landform", LANDFORM_KINDS),
|
|
2786
|
+
sizeMeters: positive(root.sizeMeters, biome, "sizeMeters"),
|
|
2787
|
+
seed: whole(root.seed, biome, "seed"),
|
|
2788
|
+
stream: oneOf(root.stream, biome, "stream", STREAMS),
|
|
2789
|
+
cover: cover(root.cover, biome),
|
|
2790
|
+
foliage: rows(root.foliage, "foliage", (entry2, at) => foliage(entry2, biome, at)),
|
|
2791
|
+
grass: rows(root.grass, "grass", (entry2, at) => grass(entry2, biome, at)),
|
|
2792
|
+
layers: rows(root.layers, "layers", (entry2, at) => layer(entry2, biome, at)),
|
|
2793
|
+
water: rows(root.water, "water", (entry2, at) => water(entry2, biome, at)),
|
|
2794
|
+
spawn: spawn2(root.spawn, biome),
|
|
2795
|
+
species: species(root.species, biome),
|
|
2796
|
+
aliases: aliases.map(
|
|
2797
|
+
(word, index) => text(word, biome, `aliases[${index}]`).toLowerCase()
|
|
2798
|
+
)
|
|
2799
|
+
};
|
|
2800
|
+
}
|
|
2801
|
+
|
|
2802
|
+
// src/mcp/tools.ts
|
|
2803
|
+
var PATCH_OPS = ["upsert", "update", "remove", "move", "toggle"];
|
|
2804
|
+
var TERRAIN_TOOLS = [
|
|
2805
|
+
{
|
|
2806
|
+
name: "terrain_generate",
|
|
2807
|
+
description: "Choose from a request, an explicit kit or a biome and cook one editable starter terrain kit (forest, coastal, alpine, desert or tundra) into a world.glb; `biome` names a starter or one of its alias words, or carries an inline IBiomeSpec whose own landform, size and seed build the ground; `landform` swaps the ground for one of the seven shape presets (alpine, temperateMountains, rollingHills, desertMesa, coastalCliffs, tundra, volcanic) and keeps the kit's surface and assets; `water` replaces the water bodies the biome declares and changes the cooked world: an ocean row floods to its level, a river or lake row re-shapes the recipe's own river or lake in order (width or radius), a recipe layer with no row is removed, and a river or lake row with no layer to take it fails. Returns the kit as recipe, the biome it bakes, the water bodies the cooked world floods, measured from the evaluated state as `water.json` records them, its band rows resolved against the cooked heights (`bands`), the world.glb, recipe.json and world.json paths, triangles, instances and draws measured from the produced GLB's default scene, and a ctx.assets.model load snippet. triangles counts every instance of the LOD0 default scene in full, before distance LOD and culling, instances sums the EXT_mesh_gpu_instancing instances, and draws counts primitives across instanced and non-instanced meshes, an instanced primitive counting once.",
|
|
2808
|
+
inputSchema: {
|
|
2809
|
+
type: "object",
|
|
2810
|
+
properties: {
|
|
2811
|
+
kit: { type: "string", enum: [...TERRAIN_KITS] },
|
|
2812
|
+
biome: {
|
|
2813
|
+
description: "A starter biome's name or alias word (forest, woods, beach, ...), or an inline IBiomeSpec object; a spec cooks with `kit`'s surface and assets, forest's when kit is absent.",
|
|
2814
|
+
anyOf: [{ type: "string", minLength: 1 }, { type: "object" }]
|
|
2815
|
+
},
|
|
2816
|
+
landform: { type: "string", enum: Object.keys(LANDFORMS) },
|
|
2817
|
+
request: { type: "string", minLength: 1 },
|
|
2818
|
+
sizeMeters: { type: "number", exclusiveMinimum: 0 },
|
|
2819
|
+
seed: { type: "integer" },
|
|
2820
|
+
water: {
|
|
2821
|
+
type: "array",
|
|
2822
|
+
items: { type: "object" },
|
|
2823
|
+
description: "IBiomeWaterBody rows that replace the biome's declared water: river (width), lake (radius), ocean (level)."
|
|
2824
|
+
},
|
|
2825
|
+
out: {
|
|
2826
|
+
type: "string",
|
|
2827
|
+
description: "Relative directory under the project's assets.source that must not exist yet; the default is assets.source/worlds/<kit>."
|
|
2828
|
+
}
|
|
2829
|
+
},
|
|
2830
|
+
anyOf: [{ required: ["request"] }, { required: ["kit"] }, { required: ["biome"] }],
|
|
2831
|
+
additionalProperties: false
|
|
2832
|
+
}
|
|
2833
|
+
},
|
|
2834
|
+
{
|
|
2835
|
+
name: "terrain_biome_new",
|
|
2836
|
+
description: "Make a new biome from a shipped one and cook it: copies the base biome's biome.data.json into <assets.source>/biomes/<name>/, applies the overrides, validates the file with validateBiome, then cooks it with the base kit's surface and assets and the biome's own landform preset. One call writes only under <assets.source>/biomes/<name>/, its cooked world included. Returns the same cook result as terrain_generate plus the biome file path and the biome's resolved `bands`. No code changes anywhere: the biome is data.",
|
|
2837
|
+
inputSchema: {
|
|
2838
|
+
type: "object",
|
|
2839
|
+
properties: {
|
|
2840
|
+
from: { type: "string", enum: [...TERRAIN_KITS] },
|
|
2841
|
+
name: {
|
|
2842
|
+
type: "string",
|
|
2843
|
+
pattern: "^[a-z][a-z0-9-]{0,31}$",
|
|
2844
|
+
description: "The new biome's folder and look name; lowercase, no spaces."
|
|
2845
|
+
},
|
|
2846
|
+
overrides: {
|
|
2847
|
+
type: "object",
|
|
2848
|
+
description: "IBiomeSpec fields to change on the base file (landform, foliage, grass, layers, water, spawn, species, aliases, bake). An unknown field fails."
|
|
2849
|
+
},
|
|
2850
|
+
out: {
|
|
2851
|
+
type: "string",
|
|
2852
|
+
description: "Relative directory under the project's assets.source that must not exist yet; the default is assets.source/biomes/<name>/world."
|
|
2853
|
+
}
|
|
2854
|
+
},
|
|
2855
|
+
required: ["from", "name"],
|
|
2856
|
+
additionalProperties: false
|
|
2857
|
+
}
|
|
2858
|
+
},
|
|
2859
|
+
{
|
|
2860
|
+
name: "terrain_patch",
|
|
2861
|
+
description: "Apply editor commands (upsert, update, remove, move, toggle) to a terrain recipe and return the edited recipe.",
|
|
2862
|
+
inputSchema: {
|
|
2863
|
+
type: "object",
|
|
2864
|
+
properties: {
|
|
2865
|
+
recipe: { type: "object" },
|
|
2866
|
+
commands: { type: "array", items: { type: "object" } }
|
|
2867
|
+
},
|
|
2868
|
+
required: ["recipe", "commands"],
|
|
2869
|
+
additionalProperties: false
|
|
2870
|
+
}
|
|
2871
|
+
}
|
|
2872
|
+
];
|
|
2873
|
+
function isRecord(value) {
|
|
2874
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2875
|
+
}
|
|
2876
|
+
function closedRecord(input, tool, fields) {
|
|
2877
|
+
if (!isRecord(input)) throw new TypeError(`${tool}: arguments must be an object.`);
|
|
2878
|
+
for (const key of Object.keys(input)) {
|
|
2879
|
+
if (!fields.includes(key)) throw new TypeError(`${tool}: unknown field '${key}'.`);
|
|
2880
|
+
}
|
|
2881
|
+
return input;
|
|
2882
|
+
}
|
|
2883
|
+
function relativeDirectory(out) {
|
|
2884
|
+
if (typeof out !== "string" || out.trim() === "" || isAbsolute(out) || out.split(/[\\/]/).includes("..")) {
|
|
2885
|
+
throw new TypeError("terrain_generate: out must be a relative directory inside the project.");
|
|
2886
|
+
}
|
|
2887
|
+
return out;
|
|
2888
|
+
}
|
|
2889
|
+
var GENERATE_FIELDS = [
|
|
2890
|
+
"request",
|
|
2891
|
+
"kit",
|
|
2892
|
+
"biome",
|
|
2893
|
+
"landform",
|
|
2894
|
+
"sizeMeters",
|
|
2895
|
+
"seed",
|
|
2896
|
+
"water",
|
|
2897
|
+
"out"
|
|
2898
|
+
];
|
|
2899
|
+
var BIOME_NEW_FIELDS = ["from", "name", "overrides", "out"];
|
|
2900
|
+
var LANDFORM_KINDS2 = Object.keys(LANDFORMS);
|
|
2901
|
+
function parseBiomeArgument(biome) {
|
|
2902
|
+
if (biome === void 0) return {};
|
|
2903
|
+
if (typeof biome === "string") {
|
|
2904
|
+
const word = biome.trim().toLowerCase();
|
|
2905
|
+
const kit = BIOME_WORD_ROWS.find(([, names]) => names.includes(word))?.[0];
|
|
2906
|
+
if (kit === void 0) {
|
|
2907
|
+
throw new TypeError(
|
|
2908
|
+
`terrain_generate: biome '${biome}' matches no biome. Try one of: ${biomeWordList()}.`
|
|
2909
|
+
);
|
|
2910
|
+
}
|
|
2911
|
+
return { kit };
|
|
2912
|
+
}
|
|
2913
|
+
if (isRecord(biome)) {
|
|
2914
|
+
const look = biome.look;
|
|
2915
|
+
return { spec: validateBiome(biome, typeof look === "string" ? look : "biome") };
|
|
2916
|
+
}
|
|
2917
|
+
throw new TypeError(
|
|
2918
|
+
"terrain_generate: biome must be a starter name, an alias word or a biome spec object."
|
|
2919
|
+
);
|
|
2920
|
+
}
|
|
2921
|
+
function parseWater(water2) {
|
|
2922
|
+
if (water2 === void 0) return void 0;
|
|
2923
|
+
if (!Array.isArray(water2) || water2.some((body) => !isRecord(body))) {
|
|
2924
|
+
throw new TypeError("terrain_generate: water must be an array of water body objects.");
|
|
2925
|
+
}
|
|
2926
|
+
return water2;
|
|
2927
|
+
}
|
|
2928
|
+
function parseGenerateInput(input) {
|
|
2929
|
+
const args = closedRecord(input, "terrain_generate", GENERATE_FIELDS);
|
|
2930
|
+
const { request, sizeMeters, seed, out } = args;
|
|
2931
|
+
if (request !== void 0 && (typeof request !== "string" || request.trim() === "")) {
|
|
2932
|
+
throw new TypeError("terrain_generate: request must be a non-empty string.");
|
|
2933
|
+
}
|
|
2934
|
+
const words = typeof request === "string" ? request.toLowerCase().split(/[^a-z]+/u) : [];
|
|
2935
|
+
const { kit: biomeKit, spec } = parseBiomeArgument(args.biome);
|
|
2936
|
+
const kit = args.kit ?? biomeKit ?? // A spec carries no appearance, so it cooks with the forest starter's surface and assets.
|
|
2937
|
+
(spec === void 0 ? TERRAIN_KITS[BIOME_WORD_ROWS.findIndex(([, names]) => names.some((name) => words.includes(name)))] : "forest");
|
|
2938
|
+
if (typeof kit !== "string" || !TERRAIN_KITS.includes(kit)) {
|
|
2939
|
+
throw new TypeError(
|
|
2940
|
+
request === void 0 ? `terrain_generate: kit must be one of ${TERRAIN_KITS.join(", ")}.` : `terrain_generate: request '${request}' matches no biome. Try one of: ${biomeWordList()}.`
|
|
2941
|
+
);
|
|
2942
|
+
}
|
|
2943
|
+
const parsed = { kit };
|
|
2944
|
+
if (spec !== void 0) parsed.spec = spec;
|
|
2945
|
+
if (args.landform !== void 0) {
|
|
2946
|
+
if (!LANDFORM_KINDS2.includes(args.landform))
|
|
2947
|
+
throw new TypeError(
|
|
2948
|
+
`terrain_generate: landform must be one of ${LANDFORM_KINDS2.join(", ")}.`
|
|
2949
|
+
);
|
|
2950
|
+
parsed.landform = args.landform;
|
|
2951
|
+
}
|
|
2952
|
+
if (sizeMeters !== void 0) {
|
|
2953
|
+
if (typeof sizeMeters !== "number" || !Number.isFinite(sizeMeters) || sizeMeters <= 0) {
|
|
2954
|
+
throw new TypeError("terrain_generate: sizeMeters must be a positive finite number.");
|
|
2955
|
+
}
|
|
2956
|
+
parsed.sizeMeters = sizeMeters;
|
|
2957
|
+
}
|
|
2958
|
+
if (seed !== void 0) {
|
|
2959
|
+
if (typeof seed !== "number" || !Number.isSafeInteger(seed)) {
|
|
2960
|
+
throw new TypeError("terrain_generate: seed must be a safe integer.");
|
|
2961
|
+
}
|
|
2962
|
+
parsed.seed = seed;
|
|
2963
|
+
}
|
|
2964
|
+
const water2 = parseWater(args.water);
|
|
2965
|
+
if (water2 !== void 0) parsed.water = water2;
|
|
2966
|
+
if (out !== void 0) parsed.out = relativeDirectory(out);
|
|
2967
|
+
return parsed;
|
|
2968
|
+
}
|
|
2969
|
+
function parseBiomeNewInput(input) {
|
|
2970
|
+
const args = closedRecord(input, "terrain_biome_new", BIOME_NEW_FIELDS);
|
|
2971
|
+
const from = args.from;
|
|
2972
|
+
if (typeof from !== "string" || !TERRAIN_KITS.includes(from))
|
|
2973
|
+
throw new TypeError(`terrain_biome_new: from must be one of ${TERRAIN_KITS.join(", ")}.`);
|
|
2974
|
+
const name = args.name;
|
|
2975
|
+
if (typeof name !== "string" || !/^[a-z][a-z0-9-]{0,31}$/u.test(name))
|
|
2976
|
+
throw new TypeError(
|
|
2977
|
+
"terrain_biome_new: name must be lowercase letters, digits and dashes, starting with a letter."
|
|
2978
|
+
);
|
|
2979
|
+
if (TERRAIN_KITS.includes(name))
|
|
2980
|
+
throw new TypeError(`terrain_biome_new: '${name}' is a shipped biome; choose a new name.`);
|
|
2981
|
+
const overrides = args.overrides;
|
|
2982
|
+
if (overrides !== void 0 && !isRecord(overrides))
|
|
2983
|
+
throw new TypeError("terrain_biome_new: overrides must be an object.");
|
|
2984
|
+
const parsed = { from, name };
|
|
2985
|
+
if (overrides !== void 0) parsed.overrides = { ...overrides };
|
|
2986
|
+
if (args.out !== void 0) parsed.out = relativeDirectory(args.out);
|
|
2987
|
+
return parsed;
|
|
2988
|
+
}
|
|
2989
|
+
function newBiomeSpec(base, name, overrides = {}) {
|
|
2990
|
+
return validateBiome(
|
|
2991
|
+
{
|
|
2992
|
+
...base,
|
|
2993
|
+
...overrides,
|
|
2994
|
+
aliases: overrides.aliases ?? [name],
|
|
2995
|
+
look: overrides.look ?? name
|
|
2996
|
+
},
|
|
2997
|
+
name
|
|
2998
|
+
);
|
|
2999
|
+
}
|
|
3000
|
+
async function resolveOutput(root, out, assetSource) {
|
|
3001
|
+
const realRoot = await realpath(root);
|
|
3002
|
+
let existing = resolve(realRoot, out);
|
|
3003
|
+
const tail = [];
|
|
3004
|
+
for (; ; ) {
|
|
3005
|
+
try {
|
|
3006
|
+
existing = await realpath(existing);
|
|
3007
|
+
break;
|
|
3008
|
+
} catch (error) {
|
|
3009
|
+
if (error.code !== "ENOENT") throw error;
|
|
3010
|
+
if (await lstat(existing).then(
|
|
3011
|
+
() => true,
|
|
3012
|
+
() => false
|
|
3013
|
+
)) {
|
|
3014
|
+
throw new Error(`terrain_generate: out '${out}' passes through a dangling symlink.`);
|
|
3015
|
+
}
|
|
3016
|
+
tail.unshift(basename(existing));
|
|
3017
|
+
existing = dirname(existing);
|
|
3018
|
+
}
|
|
3019
|
+
}
|
|
3020
|
+
const real = join(existing, ...tail);
|
|
3021
|
+
const inside = relative(realRoot, real);
|
|
3022
|
+
if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
|
|
3023
|
+
throw new Error(`terrain_generate: out '${out}' resolves outside the project.`);
|
|
3024
|
+
}
|
|
3025
|
+
if (assetSource !== void 0) {
|
|
3026
|
+
const under = relative(assetSource, real);
|
|
3027
|
+
if (under === "" || under === ".." || under.startsWith(`..${sep}`) || isAbsolute(under))
|
|
3028
|
+
throw new Error(
|
|
3029
|
+
`terrain_generate: out '${out}' must be under assets.source ('${relative(realRoot, assetSource)}') so the build lists the world in its manifest.`
|
|
3030
|
+
);
|
|
3031
|
+
}
|
|
3032
|
+
await assertOutputFree(real);
|
|
3033
|
+
return real;
|
|
3034
|
+
}
|
|
3035
|
+
async function assertOutputFree(dir) {
|
|
3036
|
+
const entries = await readdir(dir).catch((error) => {
|
|
3037
|
+
if (error.code === "ENOENT") return void 0;
|
|
3038
|
+
throw error;
|
|
3039
|
+
});
|
|
3040
|
+
if (entries !== void 0) {
|
|
3041
|
+
throw new Error(`terrain_generate: out '${dir}' already exists; choose a new directory.`);
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
function isTerrainDocument(input) {
|
|
3045
|
+
Terrain.fromJSON(JSON.stringify(input));
|
|
3046
|
+
return true;
|
|
3047
|
+
}
|
|
3048
|
+
function isLayer(input) {
|
|
3049
|
+
isTerrainDocument({ version: 1, config: new Terrain().config, layers: [input] });
|
|
3050
|
+
return true;
|
|
3051
|
+
}
|
|
3052
|
+
function isLayerPatch(patch) {
|
|
3053
|
+
if (patch.mask !== void 0 && patch.mask !== null) {
|
|
3054
|
+
isLayer({ id: "validation", type: "noise", params: {}, mask: patch.mask });
|
|
3055
|
+
}
|
|
3056
|
+
return (patch.type === void 0 || OPERATION_TYPES.some((type) => type === patch.type)) && (patch.name === void 0 || typeof patch.name === "string") && (patch.enabled === void 0 || typeof patch.enabled === "boolean") && (patch.opacity === void 0 || typeof patch.opacity === "number" && Number.isFinite(patch.opacity)) && (patch.params === void 0 || isRecord(patch.params));
|
|
3057
|
+
}
|
|
3058
|
+
function parseCommand(command, index) {
|
|
3059
|
+
if (!isRecord(command) || !PATCH_OPS.includes(command.op)) {
|
|
3060
|
+
throw new TypeError(
|
|
3061
|
+
`terrain_patch: command ${index} op must be one of ${PATCH_OPS.join(", ")}.`
|
|
3062
|
+
);
|
|
3063
|
+
}
|
|
3064
|
+
if (command.op === "upsert") {
|
|
3065
|
+
if (!isRecord(command.layer)) {
|
|
3066
|
+
throw new TypeError(`terrain_patch: command ${index} needs a layer object.`);
|
|
3067
|
+
}
|
|
3068
|
+
if (!isLayer(command.layer)) ;
|
|
3069
|
+
return { ...command, op: "upsert", layer: command.layer };
|
|
3070
|
+
}
|
|
3071
|
+
if (typeof command.id !== "string") {
|
|
3072
|
+
throw new TypeError(`terrain_patch: command ${index} needs a layer id.`);
|
|
3073
|
+
}
|
|
3074
|
+
const id = command.id;
|
|
3075
|
+
switch (command.op) {
|
|
3076
|
+
case "update": {
|
|
3077
|
+
if (!isRecord(command.patch) || !isLayerPatch(command.patch)) {
|
|
3078
|
+
throw new TypeError(`terrain_patch: command ${index} needs a valid patch object.`);
|
|
3079
|
+
}
|
|
3080
|
+
return { ...command, op: "update", id, patch: command.patch };
|
|
3081
|
+
}
|
|
3082
|
+
case "move":
|
|
3083
|
+
if (typeof command.index !== "number" || !Number.isInteger(command.index)) {
|
|
3084
|
+
throw new TypeError(`terrain_patch: command ${index} needs an integer index.`);
|
|
3085
|
+
}
|
|
3086
|
+
return { ...command, op: "move", id, index: command.index };
|
|
3087
|
+
case "toggle":
|
|
3088
|
+
if (command.enabled !== void 0 && typeof command.enabled !== "boolean") {
|
|
3089
|
+
throw new TypeError(`terrain_patch: command ${index} enabled must be a boolean.`);
|
|
3090
|
+
}
|
|
3091
|
+
return { ...command, op: "toggle", id };
|
|
3092
|
+
case "remove":
|
|
3093
|
+
return { ...command, op: "remove", id };
|
|
3094
|
+
default:
|
|
3095
|
+
throw new TypeError(`terrain_patch: command ${index} has an unknown op.`);
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
function parsePatchInput(input) {
|
|
3099
|
+
const args = closedRecord(input, "terrain_patch", ["recipe", "commands"]);
|
|
3100
|
+
if (!isRecord(args.recipe)) {
|
|
3101
|
+
throw new TypeError("terrain_patch: recipe must be a terrain document object.");
|
|
3102
|
+
}
|
|
3103
|
+
if (!Array.isArray(args.commands)) {
|
|
3104
|
+
throw new TypeError("terrain_patch: commands must be an array.");
|
|
3105
|
+
}
|
|
3106
|
+
if (!isTerrainDocument(args.recipe)) ;
|
|
3107
|
+
const commands = args.commands.map(parseCommand);
|
|
3108
|
+
patchRecipe(args.recipe, commands);
|
|
3109
|
+
return { recipe: args.recipe, commands };
|
|
3110
|
+
}
|
|
3111
|
+
function patchRecipe(recipe, commands) {
|
|
3112
|
+
return Terrain.fromJSON(recipe).applyPatch(commands).toJSON();
|
|
3113
|
+
}
|
|
3114
|
+
async function resolveAssetSource(projectRoot) {
|
|
3115
|
+
const configFile = join(projectRoot, "threenative.config.ts");
|
|
3116
|
+
const exists = await lstat(configFile).then(
|
|
3117
|
+
() => true,
|
|
3118
|
+
(error) => {
|
|
3119
|
+
if (error.code === "ENOENT") return false;
|
|
3120
|
+
throw error;
|
|
3121
|
+
}
|
|
3122
|
+
);
|
|
3123
|
+
let source = "assets";
|
|
3124
|
+
if (exists) {
|
|
3125
|
+
const { loadConfigFromFile } = await import('vite');
|
|
3126
|
+
const loaded = await loadConfigFromFile(
|
|
3127
|
+
{ command: "build", mode: "production" },
|
|
3128
|
+
configFile,
|
|
3129
|
+
projectRoot
|
|
3130
|
+
);
|
|
3131
|
+
const assets = loaded?.config?.assets;
|
|
3132
|
+
if (assets !== void 0) {
|
|
3133
|
+
if (!isRecord(assets)) throw new TypeError("terrain_generate: assets must be an object.");
|
|
3134
|
+
source = assets.source === void 0 ? "assets" : assets.source;
|
|
3135
|
+
}
|
|
3136
|
+
}
|
|
3137
|
+
if (typeof source !== "string" || source.trim() === "") {
|
|
3138
|
+
throw new TypeError("terrain_generate: assets.source must be a non-empty path.");
|
|
3139
|
+
}
|
|
3140
|
+
const configuredRoot = resolve(projectRoot, source);
|
|
3141
|
+
const sourceRoot = await realpath(configuredRoot).catch((error) => {
|
|
3142
|
+
if (error.code === "ENOENT") return configuredRoot;
|
|
3143
|
+
throw error;
|
|
3144
|
+
});
|
|
3145
|
+
const inside = relative(projectRoot, sourceRoot);
|
|
3146
|
+
if (inside === "" || inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside)) {
|
|
3147
|
+
throw new TypeError("terrain_generate: assets.source must be inside the project.");
|
|
3148
|
+
}
|
|
3149
|
+
return sourceRoot;
|
|
3150
|
+
}
|
|
3151
|
+
|
|
3152
|
+
// src/mcp/server.ts
|
|
3153
|
+
var SERVER_NAME = "threenative-terrain";
|
|
3154
|
+
var SERVER_VERSION = "0.1.2";
|
|
3155
|
+
var COOK_TIMEOUT_MS = 6e4;
|
|
3156
|
+
var COOK_CHILD = fileURLToPath(new URL("./cook-child.js", import.meta.url));
|
|
3157
|
+
function reply(id, result) {
|
|
3158
|
+
return JSON.stringify({ id, jsonrpc: "2.0", result });
|
|
3159
|
+
}
|
|
3160
|
+
function fail3(id, code, message) {
|
|
3161
|
+
return JSON.stringify({ id, jsonrpc: "2.0", error: { code, message } });
|
|
3162
|
+
}
|
|
3163
|
+
function toolResult(text2, isError = false) {
|
|
3164
|
+
return { content: [{ type: "text", text: text2 }], isError };
|
|
3165
|
+
}
|
|
3166
|
+
async function cookInChild(request, out) {
|
|
3167
|
+
const child = await runIsolated({
|
|
3168
|
+
command: process.execPath,
|
|
3169
|
+
// Inherits the parent's loader flags, so the same TypeScript runtime starts the child.
|
|
3170
|
+
args: [...childExecArgv(process.execArgv), COOK_CHILD, JSON.stringify(request)],
|
|
3171
|
+
timeoutMs: COOK_TIMEOUT_MS
|
|
3172
|
+
}).catch(async (error) => {
|
|
3173
|
+
if (error instanceof IsolatedKillError) await rm(out, { recursive: true, force: true });
|
|
3174
|
+
throw error;
|
|
3175
|
+
});
|
|
3176
|
+
return child.stdout.trim().split("\n").at(-1) ?? "";
|
|
3177
|
+
}
|
|
3178
|
+
async function callTool(name, args) {
|
|
3179
|
+
try {
|
|
3180
|
+
if (name === "terrain_generate") {
|
|
3181
|
+
const input = parseGenerateInput(args);
|
|
3182
|
+
const projectRoot = process.cwd();
|
|
3183
|
+
const assetSource = await resolveAssetSource(projectRoot);
|
|
3184
|
+
const out = await resolveOutput(
|
|
3185
|
+
projectRoot,
|
|
3186
|
+
input.out ?? relative(projectRoot, join(assetSource, "worlds", input.kit)),
|
|
3187
|
+
assetSource
|
|
3188
|
+
);
|
|
3189
|
+
return toolResult(await cookInChild({ ...input, out, projectRoot, assetSource }, out));
|
|
3190
|
+
}
|
|
3191
|
+
if (name === "terrain_biome_new") {
|
|
3192
|
+
const input = parseBiomeNewInput(args);
|
|
3193
|
+
const projectRoot = process.cwd();
|
|
3194
|
+
const assetSource = await resolveAssetSource(projectRoot);
|
|
3195
|
+
const base = JSON.parse(
|
|
3196
|
+
await readFile(
|
|
3197
|
+
new URL(`../../starter/${input.from}/biome.data.json`, import.meta.url),
|
|
3198
|
+
"utf8"
|
|
3199
|
+
)
|
|
3200
|
+
);
|
|
3201
|
+
const spec = newBiomeSpec(base, input.name, input.overrides);
|
|
3202
|
+
const biomeDir = await resolveOutput(
|
|
3203
|
+
projectRoot,
|
|
3204
|
+
relative(projectRoot, join(assetSource, "biomes", input.name)),
|
|
3205
|
+
assetSource
|
|
3206
|
+
);
|
|
3207
|
+
const out = await resolveOutput(
|
|
3208
|
+
projectRoot,
|
|
3209
|
+
input.out ?? relative(projectRoot, join(assetSource, "biomes", input.name, "world")),
|
|
3210
|
+
assetSource
|
|
3211
|
+
);
|
|
3212
|
+
await mkdir(biomeDir, { recursive: true });
|
|
3213
|
+
const biomeJson = join(biomeDir, "biome.data.json");
|
|
3214
|
+
await writeFile(biomeJson, `${JSON.stringify(spec, null, 2)}
|
|
3215
|
+
`);
|
|
3216
|
+
let text2;
|
|
3217
|
+
try {
|
|
3218
|
+
text2 = await cookInChild(
|
|
3219
|
+
{ assetSource, biome: input.name, kit: input.from, out, projectRoot, spec },
|
|
3220
|
+
out
|
|
3221
|
+
);
|
|
3222
|
+
} catch (error) {
|
|
3223
|
+
await rm(biomeDir, { recursive: true, force: true });
|
|
3224
|
+
throw error;
|
|
3225
|
+
}
|
|
3226
|
+
const shown = relative(projectRoot, biomeJson).split(sep).join("/");
|
|
3227
|
+
return toolResult(JSON.stringify({ ...JSON.parse(text2), biomeJson: shown }));
|
|
3228
|
+
}
|
|
3229
|
+
if (name === "terrain_patch") {
|
|
3230
|
+
const { recipe, commands } = parsePatchInput(args);
|
|
3231
|
+
return toolResult(JSON.stringify(patchRecipe(recipe, commands)));
|
|
3232
|
+
}
|
|
3233
|
+
throw new TypeError(`Unknown tool '${name}'.`);
|
|
3234
|
+
} catch (error) {
|
|
3235
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
3236
|
+
return toolResult(message.match(/^\w*Error: .*$/m)?.[0] ?? message, true);
|
|
3237
|
+
}
|
|
3238
|
+
}
|
|
3239
|
+
async function handleLine(line) {
|
|
3240
|
+
let request;
|
|
3241
|
+
try {
|
|
3242
|
+
request = JSON.parse(line);
|
|
3243
|
+
} catch {
|
|
3244
|
+
return fail3(null, -32700, "Parse error.");
|
|
3245
|
+
}
|
|
3246
|
+
const { id, method, params } = request;
|
|
3247
|
+
if (method === void 0) return fail3(id ?? null, -32600, "Invalid request: no method.");
|
|
3248
|
+
if (id === void 0) return void 0;
|
|
3249
|
+
if (method === "initialize") {
|
|
3250
|
+
return reply(id, {
|
|
3251
|
+
protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18",
|
|
3252
|
+
capabilities: { tools: {} },
|
|
3253
|
+
serverInfo: { name: SERVER_NAME, version: SERVER_VERSION }
|
|
3254
|
+
});
|
|
3255
|
+
}
|
|
3256
|
+
if (method === "tools/list") return reply(id, { tools: TERRAIN_TOOLS });
|
|
3257
|
+
if (method === "tools/call") {
|
|
3258
|
+
const name = params?.name;
|
|
3259
|
+
if (typeof name !== "string") return fail3(id, -32602, "tools/call needs a tool name.");
|
|
3260
|
+
return reply(id, await callTool(name, params?.arguments ?? {}));
|
|
3261
|
+
}
|
|
3262
|
+
return fail3(id, -32601, `Method not found: ${method}.`);
|
|
3263
|
+
}
|
|
3264
|
+
function runServer() {
|
|
3265
|
+
const lines = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });
|
|
3266
|
+
lines.on("line", (line) => {
|
|
3267
|
+
if (line.trim() === "") return;
|
|
3268
|
+
handleLine(line).then((response) => {
|
|
3269
|
+
if (response !== void 0) process.stdout.write(`${response}
|
|
3270
|
+
`);
|
|
3271
|
+
});
|
|
3272
|
+
});
|
|
3273
|
+
}
|
|
3274
|
+
var entry = process.argv[1];
|
|
3275
|
+
if (entry !== void 0 && realpathSync(resolve(entry)) === realpathSync(fileURLToPath(import.meta.url))) {
|
|
3276
|
+
runServer();
|
|
3277
|
+
}
|
|
3278
|
+
|
|
3279
|
+
export { handleLine, runServer };
|