@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.
Files changed (127) hide show
  1. package/AGENT_GUIDE.md +19 -4
  2. package/dist/editor/index.d.ts +160 -5
  3. package/dist/editor/index.js +3783 -1406
  4. package/dist/editor/server.d.ts +2 -2
  5. package/dist/editor/server.js +555 -121
  6. package/dist/editor/worker.d.ts +33 -1
  7. package/dist/editor/worker.js +444 -110
  8. package/dist/export.d.ts +11 -9
  9. package/dist/export.js +22 -34
  10. package/dist/index.d.ts +727 -73
  11. package/dist/index.js +2434 -553
  12. package/dist/kit.d.ts +56 -0
  13. package/dist/kit.js +2524 -0
  14. package/dist/mcp/cook-child.d.ts +2 -0
  15. package/dist/mcp/cook-child.js +3705 -0
  16. package/dist/mcp/server.d.ts +7 -0
  17. package/dist/mcp/server.js +3279 -0
  18. package/dist/{server-ByM2hmYJ.d.ts → server-C8Ydr_IM.d.ts} +3 -2
  19. package/dist/starter.d.ts +143 -0
  20. package/dist/starter.js +1030 -0
  21. package/dist/{terrain-gPnkCU6S.d.ts → terrain-B3DkduPw.d.ts} +3 -2
  22. package/dist/three.d.ts +1 -1
  23. package/dist/{types-Ant8-Axc.d.ts → types-CPYAc9vo.d.ts} +13 -4
  24. package/dist/world-package-B7KGYIou.d.ts +94 -0
  25. package/package.json +28 -6
  26. package/starter/alpine/README.md +77 -1
  27. package/starter/alpine/bake.mjs +4 -116
  28. package/starter/alpine/biome.data.json +114 -0
  29. package/starter/alpine/heightmap.r16 +0 -0
  30. package/starter/alpine/recipe.json +3 -66051
  31. package/starter/alpine/world.ts +45 -293
  32. package/starter/coastal/README.md +77 -1
  33. package/starter/coastal/bake.mjs +4 -116
  34. package/starter/coastal/biome.data.json +135 -0
  35. package/starter/coastal/heightmap.r16 +0 -0
  36. package/starter/coastal/recipe.json +3 -66051
  37. package/starter/coastal/sea.ts +49 -16
  38. package/starter/coastal/world.ts +53 -318
  39. package/starter/desert/README.md +77 -1
  40. package/starter/desert/bake.mjs +4 -116
  41. package/starter/desert/biome.data.json +114 -0
  42. package/starter/desert/heightmap.r16 +0 -0
  43. package/starter/desert/recipe.json +3 -66051
  44. package/starter/desert/world.ts +45 -293
  45. package/starter/forest/README.md +84 -4
  46. package/starter/forest/assets.json +32 -0
  47. package/starter/forest/bake.mjs +6 -116
  48. package/starter/forest/biome.data.json +150 -0
  49. package/starter/forest/heightmap.r16 +0 -0
  50. package/starter/forest/recipe.json +192 -4428
  51. package/starter/forest/sky.ts +11 -0
  52. package/starter/forest/water.ts +30 -20
  53. package/starter/forest/world.ts +86 -322
  54. package/starter/tundra/README.md +77 -1
  55. package/starter/tundra/bake.mjs +4 -116
  56. package/starter/tundra/biome.data.json +131 -0
  57. package/starter/tundra/heightmap.r16 +0 -0
  58. package/starter/tundra/recipe.json +18 -66066
  59. package/starter/tundra/world.ts +65 -319
  60. package/starter-assets.json +6 -0
  61. package/{starter-assets/credits.json → starter-credits.json} +12 -105
  62. package/starter-assets/bark_brown_02/bark_brown_02_diff_1k.jpg +0 -0
  63. package/starter-assets/bark_brown_02/bark_brown_02_nor_gl_1k.jpg +0 -0
  64. package/starter-assets/bark_brown_02/bark_brown_02_rough_1k.jpg +0 -0
  65. package/starter-assets/boulder_01/boulder-mid.glb +0 -0
  66. package/starter-assets/boulder_01/boulder-near.glb +0 -0
  67. package/starter-assets/cliff_side/cliff_side_ao_1k.jpg +0 -0
  68. package/starter-assets/cliff_side/cliff_side_diff_1k.jpg +0 -0
  69. package/starter-assets/cliff_side/cliff_side_nor_gl_1k.jpg +0 -0
  70. package/starter-assets/cliff_side/cliff_side_rough_1k.jpg +0 -0
  71. package/starter-assets/fern_02/fern_02_alpha_512.png +0 -0
  72. package/starter-assets/fern_02/fern_02_diff_512.jpg +0 -0
  73. package/starter-assets/fern_02/fern_02_nor_gl_512.jpg +0 -0
  74. package/starter-assets/fir_tree_01/fir-b-lod1.glb +0 -0
  75. package/starter-assets/fir_tree_01/fir-b-lod2.glb +0 -0
  76. package/starter-assets/fir_tree_01/fir-c-lod1.glb +0 -0
  77. package/starter-assets/fir_tree_01/fir-c-lod2.glb +0 -0
  78. package/starter-assets/fir_tree_01/fir_tree_01_twig_arm_1k.jpg +0 -0
  79. package/starter-assets/fir_tree_01/fir_tree_01_twig_diff_1k.jpg +0 -0
  80. package/starter-assets/fir_tree_01/fir_tree_01_twig_nor_gl_1k.jpg +0 -0
  81. package/starter-assets/forest_ground_04/forest_ground_04_ao_1k.jpg +0 -0
  82. package/starter-assets/forest_ground_04/forest_ground_04_diff_1k.jpg +0 -0
  83. package/starter-assets/forest_ground_04/forest_ground_04_nor_gl_1k.jpg +0 -0
  84. package/starter-assets/forest_ground_04/forest_ground_04_rough_1k.jpg +0 -0
  85. package/starter-assets/forest_leaves_02/forest_leaves_02_arm_512.jpg +0 -0
  86. package/starter-assets/forest_leaves_02/forest_leaves_02_diff_512.jpg +0 -0
  87. package/starter-assets/forest_leaves_02/forest_leaves_02_nor_gl_512.jpg +0 -0
  88. package/starter-assets/grass_medium_02/grass_medium_02_alpha_512.png +0 -0
  89. package/starter-assets/grass_medium_02/grass_medium_02_diff_512.jpg +0 -0
  90. package/starter-assets/grass_medium_02/grass_medium_02_nor_gl_512.jpg +0 -0
  91. package/starter-assets/hdri/kloofendal_48d_partly_cloudy_1k.hdr +0 -0
  92. package/starter-assets/leafy_grass/leafy_grass_ao_1k.jpg +0 -0
  93. package/starter-assets/leafy_grass/leafy_grass_diff_1k.jpg +0 -0
  94. package/starter-assets/leafy_grass/leafy_grass_nor_gl_1k.jpg +0 -0
  95. package/starter-assets/leafy_grass/leafy_grass_rough_1k.jpg +0 -0
  96. package/starter-assets/lichen_rock/lichen_rock_arm_512.jpg +0 -0
  97. package/starter-assets/lichen_rock/lichen_rock_diff_512.jpg +0 -0
  98. package/starter-assets/lichen_rock/lichen_rock_nor_gl_512.jpg +0 -0
  99. package/starter-assets/mossy_rock/mossy_rock_ao_1k.jpg +0 -0
  100. package/starter-assets/mossy_rock/mossy_rock_diff_1k.jpg +0 -0
  101. package/starter-assets/mossy_rock/mossy_rock_nor_gl_1k.jpg +0 -0
  102. package/starter-assets/mossy_rock/mossy_rock_rough_1k.jpg +0 -0
  103. package/starter-assets/needle-atlas.png +0 -0
  104. package/starter-assets/needle-surface.png +0 -0
  105. package/starter-assets/river_small_rocks/river_small_rocks_arm_512.jpg +0 -0
  106. package/starter-assets/river_small_rocks/river_small_rocks_diff_512.jpg +0 -0
  107. package/starter-assets/river_small_rocks/river_small_rocks_nor_gl_512.jpg +0 -0
  108. package/starter-assets/rock_boulder_dry/rock_boulder_dry_arm_512.jpg +0 -0
  109. package/starter-assets/rock_boulder_dry/rock_boulder_dry_diff_512.jpg +0 -0
  110. package/starter-assets/rock_boulder_dry/rock_boulder_dry_nor_gl_512.jpg +0 -0
  111. package/starter-assets/rocks/boulder-mid.glb +0 -0
  112. package/starter-assets/rocks/boulder-near.glb +0 -0
  113. package/starter-assets/rocks/boulder-prep.json +0 -37
  114. package/starter-assets/rocks/rock01-mid.glb +0 -0
  115. package/starter-assets/rocks/rock01-near.glb +0 -0
  116. package/starter-assets/rocks/rock01-prep.json +0 -37
  117. package/starter-assets/rocks/rock04-mid.glb +0 -0
  118. package/starter-assets/rocks/rock04-near.glb +0 -0
  119. package/starter-assets/rocks/rock04-prep.json +0 -37
  120. package/starter-assets/sand_01/sand_01_ao_1k.jpg +0 -0
  121. package/starter-assets/sand_01/sand_01_diff_1k.jpg +0 -0
  122. package/starter-assets/sand_01/sand_01_nor_gl_1k.jpg +0 -0
  123. package/starter-assets/sand_01/sand_01_rough_1k.jpg +0 -0
  124. package/starter-assets/snow_02/snow_02_ao_1k.jpg +0 -0
  125. package/starter-assets/snow_02/snow_02_diff_1k.jpg +0 -0
  126. package/starter-assets/snow_02/snow_02_nor_gl_1k.jpg +0 -0
  127. package/starter-assets/snow_02/snow_02_rough_1k.jpg +0 -0
@@ -155,6 +155,10 @@ function splinePoints(points, step = 3, smooth = true) {
155
155
 
156
156
  // src/core/erosion.ts
157
157
  function thermal(height, n, size, { iterations = 20, talus = 32, rate = 0.22 } = {}, observations) {
158
+ if (!Number.isInteger(n) || n < 2)
159
+ throw RangeError("Thermal erosion requires grid resolution n >= 2");
160
+ if (!Number.isInteger(iterations) || iterations < 0 || iterations > 200)
161
+ throw RangeError("Thermal erosion iterations must be between 0 and 200");
158
162
  const h = height.slice();
159
163
  const delta = new Float64Array(h.length);
160
164
  const limit = Math.tan(talus * Math.PI / 180) * (size / (n - 1));
@@ -163,18 +167,24 @@ function thermal(height, n, size, { iterations = 20, talus = 32, rate = 0.22 } =
163
167
  for (let z = 0; z < n; z += 1) {
164
168
  for (let x = 0; x < n; x += 1) {
165
169
  const i = z * n + x;
170
+ const here = h[i];
166
171
  let best = -1;
167
172
  let diff = limit;
168
- for (const j of [
169
- x > 0 ? i - 1 : -1,
170
- x < n - 1 ? i + 1 : -1,
171
- z > 0 ? i - n : -1,
172
- z < n - 1 ? i + n : -1
173
- ]) {
174
- if (j >= 0 && h[i] - h[j] > diff) {
175
- diff = h[i] - h[j];
176
- best = j;
177
- }
173
+ if (x > 0 && here - h[i - 1] > diff) {
174
+ diff = here - h[i - 1];
175
+ best = i - 1;
176
+ }
177
+ if (x < n - 1 && here - h[i + 1] > diff) {
178
+ diff = here - h[i + 1];
179
+ best = i + 1;
180
+ }
181
+ if (z > 0 && here - h[i - n] > diff) {
182
+ diff = here - h[i - n];
183
+ best = i - n;
184
+ }
185
+ if (z < n - 1 && here - h[i + n] > diff) {
186
+ diff = here - h[i + n];
187
+ best = i + n;
178
188
  }
179
189
  if (best >= 0) {
180
190
  const transfer = (diff - limit) * rate;
@@ -193,92 +203,177 @@ var brushes = /* @__PURE__ */ new Map();
193
203
  function brush(radius) {
194
204
  let cells = brushes.get(radius);
195
205
  if (!cells) {
196
- cells = [];
206
+ const dx = [];
207
+ const dz = [];
208
+ const raw = [];
197
209
  let total = 0;
198
- for (let dz = -radius; dz <= radius; dz += 1) {
199
- for (let dx = -radius; dx <= radius; dx += 1) {
200
- const d = Math.hypot(dx, dz);
210
+ for (let z = -radius; z <= radius; z += 1) {
211
+ for (let x = -radius; x <= radius; x += 1) {
212
+ const d = Math.hypot(x, z);
201
213
  if (d > radius) continue;
202
- const weight = 1 - d / (radius + 1);
203
- cells.push({ dx, dz, weight });
204
- total += weight;
214
+ const weight2 = 1 - d / (radius + 1);
215
+ dx.push(x);
216
+ dz.push(z);
217
+ raw.push(weight2);
218
+ total += weight2;
205
219
  }
206
220
  }
207
- for (const c of cells) c.weight /= total;
221
+ const weight = Float64Array.from(raw, (w) => w / total);
222
+ let full = 0;
223
+ for (let k = 0; k < weight.length; k += 1) full += weight[k];
224
+ cells = { dx: Int32Array.from(dx), dz: Int32Array.from(dz), full, radius, weight };
208
225
  brushes.set(radius, cells);
209
226
  }
210
227
  return cells;
211
228
  }
212
- function hydraulic(height, n, size, {
213
- // Roughly one droplet per cell. Incision saturates near here: more droplets keep cutting the
214
- // same drainage lines over, which deepens nothing and spends the bake time.
215
- droplets = n * n,
216
- // A droplet has to be able to cross the world, so its step budget scales with the grid: a
217
- // fixed 40 barely leaves a 257 world while a 65 world would walk off it in a few steps.
218
- maxSteps = Math.round(Math.min(64, Math.max(24, n / 4))),
219
- inertia = 0.2,
220
- capacity = 4,
221
- // Each step takes a small bite of the sediment the droplet can carry. A big bite carves
222
- // fewer, deeper dimples that stand proud of their neighbours as spikes; many shallow bites
223
- // over the same lines incise the same drainage with a smooth surface.
224
- erosion = 0.03,
225
- deposition = 0.3,
226
- evaporation = 0.025,
227
- seed = 1,
228
- brushRadius = 3
229
- } = {}, observations) {
229
+ var MAX_AUTOMATIC_DROPLETS = 1025 * 1025;
230
+ var MAX_EXPLICIT_DROPLETS = 2e5;
231
+ function hydraulic(height, n, size, options = {}, observations) {
232
+ const {
233
+ droplets: requestedDroplets,
234
+ // A droplet has to be able to cross the world, so its step budget scales with the grid: a
235
+ // fixed 40 barely leaves a 257 world while a 65 world would walk off it in a few steps.
236
+ maxSteps = Math.round(Math.min(64, Math.max(24, n / 4))),
237
+ inertia = 0.2,
238
+ capacity = 4,
239
+ // Each step takes a small bite of the sediment the droplet can carry. A big bite carves
240
+ // fewer, deeper dimples that stand proud of their neighbours as spikes; many shallow bites
241
+ // over the same lines incise the same drainage with a smooth surface.
242
+ erosion = 0.03,
243
+ deposition = 0.3,
244
+ evaporation = 0.025,
245
+ seed = 1,
246
+ brushRadius = 3
247
+ } = options;
248
+ if (!Number.isInteger(n) || n < 2)
249
+ throw RangeError("Hydraulic erosion requires grid resolution n >= 2");
250
+ const droplets = requestedDroplets === void 0 ? Math.min(n * n, MAX_AUTOMATIC_DROPLETS) : requestedDroplets;
251
+ if (!Number.isSafeInteger(droplets) || droplets < 0)
252
+ throw RangeError("Hydraulic erosion droplets must be a non-negative integer");
253
+ if (requestedDroplets !== void 0 && droplets > MAX_EXPLICIT_DROPLETS)
254
+ throw RangeError(`Hydraulic erosion droplets must not exceed ${String(MAX_EXPLICIT_DROPLETS)}`);
255
+ if (!Number.isInteger(maxSteps) || maxSteps < 1 || maxSteps > 128)
256
+ throw RangeError("Hydraulic erosion maxSteps must be between 1 and 128");
230
257
  const h = Float64Array.from(height);
231
258
  const rnd = random(seed);
232
259
  const cell = size / (n - 1);
233
- const cells = brush(brushRadius);
260
+ const minSlope = 5e-3 * cell;
261
+ const oneMinusInertia = 1 - inertia;
262
+ const oneMinusEvaporation = 1 - evaporation;
263
+ const brushCells = brush(brushRadius);
264
+ const brushDx = brushCells.dx;
265
+ const brushDz = brushCells.dz;
266
+ const brushWeight = brushCells.weight;
267
+ const brushCount = brushDx.length;
268
+ const brushFull = brushCells.full;
269
+ const brushEdge = brushCells.radius;
270
+ const brushOffset = new Int32Array(brushCount);
271
+ for (let k = 0; k < brushCount; k += 1)
272
+ brushOffset[k] = brushDz[k] * n + brushDx[k];
273
+ const obsFlow = observations?.flow;
274
+ const obsSediment = observations?.sediment;
275
+ const obsDeposition = observations?.deposition;
234
276
  const spread = (x, z, amount, floor = Number.NEGATIVE_INFINITY) => {
277
+ if (amount === 0) return 0;
278
+ const interior = x >= brushEdge && x < n - brushEdge && z >= brushEdge && z < n - brushEdge;
279
+ if (interior) {
280
+ const total2 = brushFull;
281
+ if (total2 <= 0) return 0;
282
+ const base = z * n + x;
283
+ if (amount < 0) {
284
+ let moved = 0;
285
+ for (let k = 0; k < brushCount; k += 1) {
286
+ const i = base + brushOffset[k];
287
+ const share = amount * brushWeight[k] / total2;
288
+ const avail = h[i] - floor;
289
+ const change = avail <= 0 ? -0 : -share < avail ? share : -avail;
290
+ h[i] = h[i] + change;
291
+ moved += change;
292
+ }
293
+ return moved;
294
+ }
295
+ if (obsDeposition !== void 0) {
296
+ for (let k = 0; k < brushCount; k += 1) {
297
+ const i = base + brushOffset[k];
298
+ const share = amount * brushWeight[k] / total2;
299
+ h[i] = h[i] + share;
300
+ obsDeposition[i] = obsDeposition[i] + share;
301
+ }
302
+ } else {
303
+ for (let k = 0; k < brushCount; k += 1) {
304
+ const i = base + brushOffset[k];
305
+ const share = amount * brushWeight[k] / total2;
306
+ h[i] = h[i] + share;
307
+ }
308
+ }
309
+ return amount;
310
+ }
235
311
  let total = 0;
236
- for (const c of cells) {
237
- const ix = x + c.dx;
238
- const iz = z + c.dz;
239
- if (ix >= 0 && ix < n && iz >= 0 && iz < n) total += c.weight;
312
+ for (let k = 0; k < brushCount; k += 1) {
313
+ const ix = x + brushDx[k];
314
+ const iz = z + brushDz[k];
315
+ if (ix >= 0 && ix < n && iz >= 0 && iz < n) total += brushWeight[k];
240
316
  }
241
317
  if (total <= 0) return 0;
242
- let moved = 0;
243
- for (const c of cells) {
244
- const ix = x + c.dx;
245
- const iz = z + c.dz;
246
- if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
247
- const i = iz * n + ix;
248
- const share = amount * c.weight / total;
249
- const change = amount < 0 ? -Math.min(-share, Math.max(0, h[i] - floor)) : share;
250
- h[i] = h[i] + change;
251
- moved += change;
252
- if (observations && amount > 0)
253
- observations.deposition[i] = observations.deposition[i] + amount * c.weight / total;
318
+ if (amount < 0) {
319
+ let moved = 0;
320
+ for (let k = 0; k < brushCount; k += 1) {
321
+ const ix = x + brushDx[k];
322
+ const iz = z + brushDz[k];
323
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
324
+ const i = iz * n + ix;
325
+ const share = amount * brushWeight[k] / total;
326
+ const avail = h[i] - floor;
327
+ const change = avail <= 0 ? -0 : -share < avail ? share : -avail;
328
+ h[i] = h[i] + change;
329
+ moved += change;
330
+ }
331
+ return moved;
254
332
  }
255
- return moved;
333
+ if (obsDeposition !== void 0) {
334
+ for (let k = 0; k < brushCount; k += 1) {
335
+ const ix = x + brushDx[k];
336
+ const iz = z + brushDz[k];
337
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
338
+ const i = iz * n + ix;
339
+ const share = amount * brushWeight[k] / total;
340
+ h[i] = h[i] + share;
341
+ obsDeposition[i] = obsDeposition[i] + share;
342
+ }
343
+ } else {
344
+ for (let k = 0; k < brushCount; k += 1) {
345
+ const ix = x + brushDx[k];
346
+ const iz = z + brushDz[k];
347
+ if (ix < 0 || ix >= n || iz < 0 || iz >= n) continue;
348
+ const i = iz * n + ix;
349
+ const share = amount * brushWeight[k] / total;
350
+ h[i] = h[i] + share;
351
+ }
352
+ }
353
+ return amount;
256
354
  };
257
- const get = (x, z) => {
355
+ const probeOld = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
356
+ const probeNext = { value: 0, dx: 0, dz: 0, ix: 0, iz: 0 };
357
+ const get = (x, z, out) => {
258
358
  const ix = Math.min(n - 2, Math.floor(x));
259
359
  const iz = Math.min(n - 2, Math.floor(z));
260
360
  const tx = x - ix;
261
361
  const tz = z - iz;
262
362
  const i = iz * n + ix;
263
- return {
264
- value: lerp(
265
- lerp(h[i], h[i + 1], tx),
266
- lerp(h[i + n], h[i + n + 1], tx),
267
- tz
268
- ),
269
- dx: lerp(
270
- h[i + 1] - h[i],
271
- h[i + n + 1] - h[i + n],
272
- tz
273
- ) / cell,
274
- dz: lerp(
275
- h[i + n] - h[i],
276
- h[i + n + 1] - h[i + 1],
277
- tx
278
- ) / cell,
279
- ix,
280
- iz
281
- };
363
+ const h00 = h[i];
364
+ const h10 = h[i + 1];
365
+ const h01 = h[i + n];
366
+ const h11 = h[i + n + 1];
367
+ const g10 = h10 - h00;
368
+ const g01 = h01 - h00;
369
+ const v0 = h00 + g10 * tx;
370
+ const v1 = h01 + (h11 - h01) * tx;
371
+ out.value = v0 + (v1 - v0) * tz;
372
+ out.dx = (g10 + (h11 - h01 - g10) * tz) / cell;
373
+ out.dz = (g01 + (h11 - h10 - g01) * tx) / cell;
374
+ out.ix = ix;
375
+ out.iz = iz;
376
+ return out;
282
377
  };
283
378
  for (let k = 0; k < droplets; k += 1) {
284
379
  let x = rnd() * (n - 1 - 1e-3);
@@ -289,23 +384,30 @@ function hydraulic(height, n, size, {
289
384
  let speed = 1;
290
385
  let sediment = 0;
291
386
  for (let step = 0; step < maxSteps; step += 1) {
292
- const old = get(x, z);
293
- if (observations) {
387
+ const old = get(x, z, probeOld);
388
+ if (obsFlow !== void 0 && obsSediment !== void 0) {
294
389
  const tx = x - old.ix;
295
390
  const tz = z - old.iz;
296
391
  const i = old.iz * n + old.ix;
297
- for (let oz = 0; oz < 2; oz++) {
298
- for (let ox = 0; ox < 2; ox++) {
299
- const index = i + oz * n + ox;
300
- const weight = (ox ? tx : 1 - tx) * (oz ? tz : 1 - tz);
301
- observations.flow[index] = observations.flow[index] + water * weight;
302
- observations.sediment[index] = observations.sediment[index] + sediment * weight;
303
- }
304
- }
392
+ const w00 = (1 - tx) * (1 - tz);
393
+ const w10 = tx * (1 - tz);
394
+ const w01 = (1 - tx) * tz;
395
+ const w11 = tx * tz;
396
+ obsFlow[i] = obsFlow[i] + water * w00;
397
+ obsSediment[i] = obsSediment[i] + sediment * w00;
398
+ obsFlow[i + 1] = obsFlow[i + 1] + water * w10;
399
+ obsSediment[i + 1] = obsSediment[i + 1] + sediment * w10;
400
+ obsFlow[i + n] = obsFlow[i + n] + water * w01;
401
+ obsSediment[i + n] = obsSediment[i + n] + sediment * w01;
402
+ obsFlow[i + n + 1] = obsFlow[i + n + 1] + water * w11;
403
+ obsSediment[i + n + 1] = obsSediment[i + n + 1] + sediment * w11;
305
404
  }
306
- dx = dx * inertia - old.dx * (1 - inertia);
307
- dz = dz * inertia - old.dz * (1 - inertia);
308
- let length = Math.hypot(dx, dz);
405
+ dx = dx * inertia - old.dx * oneMinusInertia;
406
+ dz = dz * inertia - old.dz * oneMinusInertia;
407
+ const largest = Math.max(Math.abs(dx), Math.abs(dz));
408
+ const scaledX = Math.abs(dx) / largest;
409
+ const scaledZ = Math.abs(dz) / largest;
410
+ let length = largest === 0 || largest === Number.POSITIVE_INFINITY ? largest : Math.sqrt(scaledX * scaledX + scaledZ * scaledZ) * largest;
309
411
  if (length < 1e-9) {
310
412
  const angle = rnd() * Math.PI * 2;
311
413
  dx = Math.cos(angle);
@@ -320,31 +422,223 @@ function hydraulic(height, n, size, {
320
422
  sediment = 0;
321
423
  break;
322
424
  }
323
- const next = get(nx, nz);
425
+ const next = get(nx, nz, probeNext);
324
426
  const dh = next.value - old.value;
325
- const cap = Math.max(-dh, 5e-3 * cell) * speed * water * capacity;
427
+ const slope = -dh;
428
+ const cap = (slope > minSlope ? slope : minSlope) * speed * water * capacity;
326
429
  if (dh > 0 || sediment > cap) {
327
- const amount = dh > 0 ? Math.min(dh, sediment) : (sediment - cap) * deposition;
430
+ const amount = dh > 0 ? dh < sediment ? dh : sediment : (sediment - cap) * deposition;
328
431
  spread(old.ix, old.iz, amount);
329
432
  sediment -= amount;
330
433
  } else {
331
- const amount = Math.max(0, Math.min((cap - sediment) * erosion, -dh));
434
+ const bite = (cap - sediment) * erosion;
435
+ const amount = bite < slope ? bite : slope;
332
436
  sediment -= spread(old.ix, old.iz, -amount, next.value);
333
437
  }
334
- speed = Math.sqrt(Math.max(0.01, speed * speed - dh * 3));
335
- water *= 1 - evaporation;
438
+ const sq = speed * speed - dh * 3;
439
+ speed = Math.sqrt(sq > 0.01 ? sq : 0.01);
440
+ water *= oneMinusEvaporation;
336
441
  x = nx;
337
442
  z = nz;
338
443
  if (water < 0.02) break;
339
444
  }
340
445
  if (sediment > 0 && water < 0.02) {
341
- const end = get(clamp(x, 0, n - 1.001), clamp(z, 0, n - 1.001));
446
+ const end = get(clamp(x, 0, n - 1.001), clamp(z, 0, n - 1.001), probeOld);
342
447
  spread(end.ix, end.iz, sediment);
343
448
  }
344
449
  }
345
450
  return Float32Array.from(h);
346
451
  }
347
452
 
453
+ // src/core/fluvial.ts
454
+ var DX = Int8Array.of(-1, 0, 1, -1, 1, -1, 0, 1);
455
+ var DZ = Int8Array.of(-1, -1, -1, 0, 0, 1, 1, 1);
456
+ var DIST = Float64Array.from(DX, (dx, k) => Math.hypot(dx, DZ[k]));
457
+ var FILL_SLOPE = Math.tan(0.06 * Math.PI / 180);
458
+ var EPSILON = 1e-3;
459
+ function fillDepressions(h, n, epsilon = EPSILON) {
460
+ const total = n * n;
461
+ const keys = new Float64Array(total);
462
+ const cells = new Int32Array(total);
463
+ const closed = new Uint8Array(total);
464
+ let size = 0;
465
+ const push = (key, cell) => {
466
+ let k = size++;
467
+ while (k > 0) {
468
+ const parent = k - 1 >> 1;
469
+ if (keys[parent] <= key) break;
470
+ keys[k] = keys[parent];
471
+ cells[k] = cells[parent];
472
+ k = parent;
473
+ }
474
+ keys[k] = key;
475
+ cells[k] = cell;
476
+ };
477
+ const pop = () => {
478
+ const top = cells[0];
479
+ size -= 1;
480
+ const key = keys[size];
481
+ const cell = cells[size];
482
+ let k = 0;
483
+ for (; ; ) {
484
+ let child = 2 * k + 1;
485
+ if (child >= size) break;
486
+ if (child + 1 < size && keys[child + 1] < keys[child]) child += 1;
487
+ if (keys[child] >= key) break;
488
+ keys[k] = keys[child];
489
+ cells[k] = cells[child];
490
+ k = child;
491
+ }
492
+ keys[k] = key;
493
+ cells[k] = cell;
494
+ return top;
495
+ };
496
+ for (let z = 0; z < n; z += 1) {
497
+ for (let x = 0; x < n; x += 1) {
498
+ if (x > 0 && x < n - 1 && z > 0 && z < n - 1) continue;
499
+ const i = z * n + x;
500
+ closed[i] = 1;
501
+ push(h[i], i);
502
+ }
503
+ }
504
+ while (size > 0) {
505
+ const c = pop();
506
+ const cx = c % n;
507
+ const cz = (c - cx) / n;
508
+ const level = h[c];
509
+ for (let k = 0; k < 8; k += 1) {
510
+ const x = cx + DX[k];
511
+ const z = cz + DZ[k];
512
+ if (x < 0 || z < 0 || x >= n || z >= n) continue;
513
+ const j = z * n + x;
514
+ if (closed[j]) continue;
515
+ closed[j] = 1;
516
+ if (h[j] <= level) h[j] = level + epsilon;
517
+ push(h[j], j);
518
+ }
519
+ }
520
+ }
521
+ function createFlow(n) {
522
+ const total = n * n;
523
+ return {
524
+ receiver: new Int32Array(total),
525
+ order: new Int32Array(total),
526
+ cells: new Float64Array(total)
527
+ };
528
+ }
529
+ function routeFlow(h, n, flow) {
530
+ const { receiver, order, cells } = flow;
531
+ const total = n * n;
532
+ const head = new Int32Array(total).fill(-1);
533
+ const next = new Int32Array(total);
534
+ let roots = 0;
535
+ for (let z = 0; z < n; z += 1) {
536
+ for (let x = 0; x < n; x += 1) {
537
+ const i = z * n + x;
538
+ let best = -1;
539
+ if (x > 0 && x < n - 1 && z > 0 && z < n - 1) {
540
+ const here = h[i];
541
+ let bestSlope = 0;
542
+ for (let k = 0; k < 8; k += 1) {
543
+ const j = i + DZ[k] * n + DX[k];
544
+ const slope = (here - h[j]) / DIST[k];
545
+ if (slope > bestSlope) {
546
+ bestSlope = slope;
547
+ best = j;
548
+ }
549
+ }
550
+ }
551
+ receiver[i] = best;
552
+ if (best < 0) order[roots++] = i;
553
+ else {
554
+ next[i] = head[best];
555
+ head[best] = i;
556
+ }
557
+ }
558
+ }
559
+ for (let k = 0; k < total; k += 1) {
560
+ const i = order[k];
561
+ for (let d = head[i]; d >= 0; d = next[d]) order[roots++] = d;
562
+ }
563
+ cells.fill(1);
564
+ for (let k = total - 1; k >= 0; k -= 1) {
565
+ const i = order[k];
566
+ const r = receiver[i];
567
+ if (r >= 0) cells[r] = cells[r] + cells[i];
568
+ }
569
+ }
570
+ function fluvial(height, n, size, {
571
+ iterations = 40,
572
+ uplift = 1e-3,
573
+ erodibility = 5e-6,
574
+ timeStep = 2e4,
575
+ concavity = 0.45,
576
+ talus = 35,
577
+ relief
578
+ } = {}) {
579
+ const total = n * n;
580
+ const spacing = size / (n - 1);
581
+ const h = Float64Array.from(height);
582
+ const band = Math.min(4, n - 1);
583
+ for (let a = 0; a < n; a += 1)
584
+ for (let d = 1; d <= band; d += 1) {
585
+ h[a] = Math.min(h[a], h[d * n + a]);
586
+ h[(n - 1) * n + a] = Math.min(h[(n - 1) * n + a], h[(n - 1 - d) * n + a]);
587
+ h[a * n] = Math.min(h[a * n], h[a * n + d]);
588
+ h[a * n + n - 1] = Math.min(h[a * n + n - 1], h[a * n + n - 1 - d]);
589
+ }
590
+ fillDepressions(h, n, FILL_SLOPE * spacing);
591
+ let low = Number.POSITIVE_INFINITY;
592
+ let high = Number.NEGATIVE_INFINITY;
593
+ for (let i = 0; i < total; i += 1) {
594
+ low = Math.min(low, h[i]);
595
+ high = Math.max(high, h[i]);
596
+ }
597
+ const range2 = high - low || 1;
598
+ const rise = Float64Array.from(h, (v) => uplift * timeStep * (v - low) / range2);
599
+ const flow = createFlow(n);
600
+ const kdt = erodibility * timeStep;
601
+ const maxRise = Math.tan(talus * Math.PI / 180) * spacing;
602
+ const power = Float64Array.from(
603
+ { length: total + 1 },
604
+ (_, c) => (c * spacing * spacing) ** concavity
605
+ );
606
+ for (let step = 0; step < iterations; step += 1) {
607
+ routeFlow(h, n, flow);
608
+ const { order, receiver, cells } = flow;
609
+ for (let k = 0; k < total; k += 1) {
610
+ const i = order[k];
611
+ const r = receiver[i];
612
+ if (r < 0) continue;
613
+ const delta = Math.abs(r - i);
614
+ const run = delta === 1 || delta === n ? 1 : Math.SQRT2;
615
+ const factor = kdt * power[cells[i]] / (spacing * run);
616
+ const below = h[r];
617
+ const solved = (h[i] + rise[i] + factor * below) / (1 + factor);
618
+ h[i] = Math.max(Math.min(solved, below + maxRise * run), below + EPSILON);
619
+ }
620
+ }
621
+ for (let a = 0; a < n; a += 1) {
622
+ h[a] = h[n + a];
623
+ h[(n - 1) * n + a] = h[(n - 2) * n + a];
624
+ }
625
+ for (let a = 0; a < n; a += 1) {
626
+ h[a * n] = h[a * n + 1];
627
+ h[a * n + n - 1] = h[a * n + n - 2];
628
+ }
629
+ if (relief !== void 0) {
630
+ let lo = Number.POSITIVE_INFINITY;
631
+ let hi = Number.NEGATIVE_INFINITY;
632
+ for (const v of h) {
633
+ lo = Math.min(lo, v);
634
+ hi = Math.max(hi, v);
635
+ }
636
+ const gain = relief / (hi - lo || 1);
637
+ for (let i = 0; i < total; i += 1) h[i] = lo + (h[i] - lo) * gain;
638
+ }
639
+ return Float32Array.from(h);
640
+ }
641
+
348
642
  // src/core/masks.ts
349
643
  var MATERIAL_IDS = Object.freeze([
350
644
  "grass",
@@ -863,7 +1157,7 @@ function applyOperation(s, layer) {
863
1157
  talus: new Float32Array(s.height.length)
864
1158
  };
865
1159
  s.erosion ??= structuredClone(observations);
866
- const eroded = p.method === "hydraulic" ? hydraulic(
1160
+ const eroded = p.method === "fluvial" ? fluvial(s.height, n, s.size, p) : p.method === "hydraulic" ? hydraulic(
867
1161
  s.height,
868
1162
  n,
869
1163
  s.size,
@@ -1104,7 +1398,7 @@ function finalizeState(s) {
1104
1398
  accepted.push({
1105
1399
  id: `${rule.id}:candidate:${seed}:${attempt}`,
1106
1400
  layer: rule.id,
1107
- asset: rule.asset ?? "pine",
1401
+ asset: rule.asset,
1108
1402
  position: [x, h + (rule.offsetY ?? 0), z],
1109
1403
  rotation: yaw,
1110
1404
  scale: itemScale,
@@ -1116,7 +1410,7 @@ function finalizeState(s) {
1116
1410
  bucket.push(index);
1117
1411
  buckets.set(key, bucket);
1118
1412
  }
1119
- s.instances.push(...accepted);
1413
+ for (const instance of accepted) s.instances.push(instance);
1120
1414
  if (accepted.length < count)
1121
1415
  s.diagnostics.push(
1122
1416
  `Scatter '${rule.id}': placed ${accepted.length}/${count}; masks or spacing exhausted the attempt budget.`
@@ -1191,6 +1485,10 @@ var PARAMS = Object.freeze({
1191
1485
  "method",
1192
1486
  "iterations",
1193
1487
  "talus",
1488
+ "uplift",
1489
+ "erodibility",
1490
+ "timeStep",
1491
+ "relief",
1194
1492
  "rate",
1195
1493
  "droplets",
1196
1494
  "maxSteps",
@@ -1240,14 +1538,23 @@ function fail(message) {
1240
1538
  }
1241
1539
  function finiteTree(value, path = "value", depth = 0) {
1242
1540
  if (depth > 32) fail(`${path}: nesting is too deep`);
1243
- if (typeof value === "number" && !Number.isFinite(value)) fail(`${path} must be finite`);
1541
+ if (typeof value === "number") {
1542
+ if (!Number.isFinite(value)) fail(`${path} must be finite`);
1543
+ return;
1544
+ }
1244
1545
  if (value === void 0 || typeof value === "function" || typeof value === "bigint" || typeof value === "symbol")
1245
1546
  fail(`${path} is not JSON-serializable`);
1246
1547
  if (value && typeof value === "object") {
1247
1548
  if (ArrayBuffer.isView(value)) fail(`${path}: use a plain array in recipes`);
1248
- for (const [key, entry] of Object.entries(value)) {
1249
- if (["__proto__", "prototype", "constructor"].includes(key))
1549
+ for (const key of Object.keys(value)) {
1550
+ if (key === "__proto__" || key === "prototype" || key === "constructor")
1250
1551
  fail(`${path}: unsafe object key`);
1552
+ const entry = value[key];
1553
+ if (typeof entry === "number") {
1554
+ if (depth + 1 > 32) fail(`${path}.${key}: nesting is too deep`);
1555
+ if (!Number.isFinite(entry)) fail(`${path}.${key} must be finite`);
1556
+ continue;
1557
+ }
1251
1558
  finiteTree(entry, `${path}.${key}`, depth + 1);
1252
1559
  }
1253
1560
  }
@@ -1528,6 +1835,13 @@ function validateLayer(layer) {
1528
1835
  if (params[key] !== void 0) num(params[key], key, key === "count" ? 0 : 1, max, true);
1529
1836
  if (params.persistence !== void 0) num(params.persistence, "persistence", 0.01, 1);
1530
1837
  if (params.lacunarity !== void 0) num(params.lacunarity, "lacunarity", 1, 4);
1838
+ for (const [key, min, max] of [
1839
+ ["uplift", 1e-9, 1],
1840
+ ["erodibility", 1e-9, 1],
1841
+ ["timeStep", 1, 1e7],
1842
+ ["relief", 1, 1e5]
1843
+ ])
1844
+ if (params[key] !== void 0) num(params[key], key, min, max);
1531
1845
  for (const key of ["minSlope", "maxSlope", "talus"])
1532
1846
  if (params[key] !== void 0) num(params[key], key, 0, key === "talus" ? 89.9 : 90);
1533
1847
  if (params.minHeight !== void 0 && params.maxHeight !== void 0 && params.minHeight > params.maxHeight)
@@ -1545,7 +1859,8 @@ function validateLayer(layer) {
1545
1859
  if (rule.strength !== void 0) num(rule.strength, "rule.strength", 0, 1);
1546
1860
  }
1547
1861
  }
1548
- if (params.method !== void 0) enumeration(params.method, "method", ["thermal", "hydraulic"]);
1862
+ if (params.method !== void 0)
1863
+ enumeration(params.method, "method", ["thermal", "hydraulic", "fluvial"]);
1549
1864
  if (params.mode !== void 0) enumeration(params.mode, "mode", ["fbm", "ridged", "billow"]);
1550
1865
  if (params.shape !== void 0)
1551
1866
  enumeration(
@@ -1573,6 +1888,10 @@ function validateLayer(layer) {
1573
1888
  }
1574
1889
  if (params.name !== void 0) identifier(params.name, "name");
1575
1890
  if (params.asset !== void 0) identifier(params.asset, "asset");
1891
+ if (layer.type === "scatter" && typeof params.asset !== "string")
1892
+ fail(
1893
+ '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'
1894
+ );
1576
1895
  if (["heightmap", "paste"].includes(layer.type) && !params.data)
1577
1896
  fail(`${layer.type} requires heightmap data`);
1578
1897
  const data = params.data;
@@ -1624,8 +1943,8 @@ var TerrainEvaluator = class {
1624
1943
  validateDocument(doc);
1625
1944
  validateConfig({ ...doc.config, resolution });
1626
1945
  const keys = [];
1627
- let key = JSON.stringify({ ...doc.config, resolution });
1628
- for (const layer of doc.layers) {
1946
+ let key = this.limit > 0 ? JSON.stringify({ ...doc.config, resolution }) : "";
1947
+ for (const layer of this.limit > 0 ? doc.layers : []) {
1629
1948
  key += `|${JSON.stringify(layer)}`;
1630
1949
  keys.push(key);
1631
1950
  }
@@ -1978,7 +2297,7 @@ function encodeGLB(input) {
1978
2297
  }
1979
2298
  const binary = join(chunks);
1980
2299
  const doc = {
1981
- asset: { version: "2.0", generator: "Strata Terrain 0.1.0" },
2300
+ asset: { version: "2.0", generator: "@threenative/terrain 0.1.8" },
1982
2301
  scene: 0,
1983
2302
  scenes: [{ nodes: meshes.map((_, i) => i) }],
1984
2303
  nodes: meshes.map((m, i) => ({ mesh: i, name: m.name ?? `Terrain ${i}` })),
@@ -2089,6 +2408,7 @@ async function makeExport(state, recipe, kind) {
2089
2408
  });
2090
2409
  if (kind === "project")
2091
2410
  return result("terrain-recipe.json", "application/json", json("", recipe).bytes);
2411
+ if (!state) throw new Error("Wait for initial build");
2092
2412
  if (kind === "png")
2093
2413
  return result("terrain-height16.png", "image/png", await encodeHeightPNG(state));
2094
2414
  if (kind === "glb") return result("terrain.glb", "model/gltf-binary", encodeGLB(bakeMesh(state)));
@@ -2187,23 +2507,37 @@ async function makeExport(state, recipe, kind) {
2187
2507
  return result("terrain-runtime.zip", "application/zip", encodeZIP(files));
2188
2508
  }
2189
2509
 
2190
- // src/editor/worker.js
2510
+ // src/editor/worker.ts
2511
+ var worker = globalThis;
2191
2512
  var evaluator = new TerrainEvaluator({ cacheMB: 48 });
2192
- self.onmessage = async ({ data }) => {
2513
+ worker.onmessage = async ({ data }) => {
2193
2514
  const { id, type, recipe, resolution, kind } = data;
2194
2515
  try {
2195
2516
  validateDocument(recipe);
2196
2517
  const start = performance.now();
2197
2518
  const state = evaluator.evaluate(recipe, {
2198
2519
  resolution,
2199
- onProgress: (p) => self.postMessage({ id, type: "progress", progress: p })
2520
+ onProgress: (p) => worker.postMessage({ id, type: "progress", progress: p })
2200
2521
  });
2201
2522
  if (type === "export") {
2523
+ if (!kind) throw new Error("Missing export kind");
2202
2524
  const output = await makeExport(state, recipe, kind);
2203
- self.postMessage({ id, type: "exported", output }, [output.bytes.buffer]);
2204
- } else self.postMessage({ id, type: "evaluated", state, ms: performance.now() - start });
2525
+ if (!(output.bytes.buffer instanceof ArrayBuffer))
2526
+ throw Error("Export buffer is not transferable");
2527
+ worker.postMessage({ id, type: "exported", output }, [output.bytes.buffer]);
2528
+ } else {
2529
+ const normal = bakeMesh(state).normals;
2530
+ const transfer = [state.height, normal, state.splat].map(({ buffer }) => {
2531
+ if (!(buffer instanceof ArrayBuffer)) throw Error("Terrain buffer is not transferable");
2532
+ return buffer;
2533
+ });
2534
+ worker.postMessage(
2535
+ { id, type: "evaluated", state, normal, ms: performance.now() - start },
2536
+ transfer
2537
+ );
2538
+ }
2205
2539
  } catch (error) {
2206
- self.postMessage({
2540
+ worker.postMessage({
2207
2541
  id,
2208
2542
  type: "error",
2209
2543
  error: error instanceof Error ? error.message : String(error)