webgpu-biome 0.0.0-stage → 0.1.0

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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/lib/canopy.d.ts +75 -0
  4. package/lib/canopy.d.ts.map +1 -0
  5. package/lib/canopy.js +295 -0
  6. package/lib/canopy.js.map +1 -0
  7. package/lib/climate.d.ts +68 -0
  8. package/lib/climate.d.ts.map +1 -0
  9. package/lib/climate.js +105 -0
  10. package/lib/climate.js.map +1 -0
  11. package/lib/detail.d.ts +55 -0
  12. package/lib/detail.d.ts.map +1 -0
  13. package/lib/detail.js +225 -0
  14. package/lib/detail.js.map +1 -0
  15. package/lib/ecotone.d.ts +166 -0
  16. package/lib/ecotone.d.ts.map +1 -0
  17. package/lib/ecotone.js +1007 -0
  18. package/lib/ecotone.js.map +1 -0
  19. package/lib/engine.d.ts +102 -0
  20. package/lib/engine.d.ts.map +1 -0
  21. package/lib/engine.js +773 -0
  22. package/lib/engine.js.map +1 -0
  23. package/lib/epiphytes.d.ts +19 -0
  24. package/lib/epiphytes.d.ts.map +1 -0
  25. package/lib/epiphytes.js +180 -0
  26. package/lib/epiphytes.js.map +1 -0
  27. package/lib/ground.d.ts +43 -0
  28. package/lib/ground.d.ts.map +1 -0
  29. package/lib/ground.js +450 -0
  30. package/lib/ground.js.map +1 -0
  31. package/lib/horizon.d.ts +20 -0
  32. package/lib/horizon.d.ts.map +1 -0
  33. package/lib/horizon.js +625 -0
  34. package/lib/horizon.js.map +1 -0
  35. package/lib/index.d.ts +21 -0
  36. package/lib/index.d.ts.map +1 -0
  37. package/lib/index.js +18 -0
  38. package/lib/index.js.map +1 -0
  39. package/lib/particles.d.ts +12 -0
  40. package/lib/particles.d.ts.map +1 -0
  41. package/lib/particles.js +124 -0
  42. package/lib/particles.js.map +1 -0
  43. package/lib/post.d.ts +23 -0
  44. package/lib/post.d.ts.map +1 -0
  45. package/lib/post.js +225 -0
  46. package/lib/post.js.map +1 -0
  47. package/lib/recipe-specs.d.ts +51 -0
  48. package/lib/recipe-specs.d.ts.map +1 -0
  49. package/lib/recipe-specs.js +562 -0
  50. package/lib/recipe-specs.js.map +1 -0
  51. package/lib/recipes.d.ts +9 -0
  52. package/lib/recipes.d.ts.map +1 -0
  53. package/lib/recipes.js +279 -0
  54. package/lib/recipes.js.map +1 -0
  55. package/lib/sandbox.d.ts +183 -0
  56. package/lib/sandbox.d.ts.map +1 -0
  57. package/lib/sandbox.js +1060 -0
  58. package/lib/sandbox.js.map +1 -0
  59. package/lib/shadows.d.ts +71 -0
  60. package/lib/shadows.d.ts.map +1 -0
  61. package/lib/shadows.js +532 -0
  62. package/lib/shadows.js.map +1 -0
  63. package/lib/sky.d.ts +16 -0
  64. package/lib/sky.d.ts.map +1 -0
  65. package/lib/sky.js +132 -0
  66. package/lib/sky.js.map +1 -0
  67. package/lib/substrate.d.ts +124 -0
  68. package/lib/substrate.d.ts.map +1 -0
  69. package/lib/substrate.js +988 -0
  70. package/lib/substrate.js.map +1 -0
  71. package/lib/turf.d.ts +60 -0
  72. package/lib/turf.d.ts.map +1 -0
  73. package/lib/turf.js +278 -0
  74. package/lib/turf.js.map +1 -0
  75. package/lib/water.d.ts +41 -0
  76. package/lib/water.d.ts.map +1 -0
  77. package/lib/water.js +210 -0
  78. package/lib/water.js.map +1 -0
  79. package/package.json +63 -3
package/lib/sandbox.js ADDED
@@ -0,0 +1,1060 @@
1
+ // Living 3D Forest & Garden Sandbox (`Phase 6`).
2
+ // Pure TypeScript + `webgpu-trees` math so both browser WebGPU (`src/engine.ts`)
3
+ // and Node headless MCP/tests (`mcp/studio.ts`, `node --test`) share one engine.
4
+ import { ALL_SPECIES, TREE_STRIDE, checkSpecies, cloneSpecies, crossoverGenomes, decodeDna, encodeDna, genomeToSpecies, lifeStageSizes, mutateGenome, speciesToGenome, } from "webgpu-trees";
5
+ import { bakeCanopyCpu, sampleCanopyCpu } from "./canopy.js";
6
+ import { computeTreeEdaphicTints } from "./ecotone.js";
7
+ import { ALL_FLORA_SPECIES, FLORA_STRIDE } from "webgpu-flora";
8
+ import { buildTurfSuppression, classifyTurf, createShrubHaloField } from "./turf.js";
9
+ import { placeEpiphytes } from "./epiphytes.js";
10
+ import { deriveLitterSoil, sampleSubstrateCpu } from "./substrate.js";
11
+ // Keep total species (`52 base + wild`) within WebGPU default `maxTextureDimension2D` (`8192 / 128 = 64` rows).
12
+ const MAX_WILD_CULTIVARS = 10;
13
+ function evalWildFitness(sp, shelter, exposure, moisture) {
14
+ const light = 1 - shelter;
15
+ const crRatio = sp.crownRadius / Math.max(0.8, sp.height);
16
+ const openness = sp.openness;
17
+ const canopyLift = sp.canopyLift ?? 0;
18
+ // Sunlit gap favors broad vigorous crown reach; shaded forest floor favors shade-tolerant high canopy lift / open foliage.
19
+ const lightFit = light > 0.65
20
+ ? (1 - Math.abs(openness - 0.38)) * 0.8 + Math.min(1, crRatio * 1.4) * 0.7
21
+ : (1 - Math.abs(openness - 0.56)) * 0.8 + Math.min(1, canopyLift * 1.5 + 0.25) * 0.6;
22
+ // Wind exposure favors stiffer, compact, thicker trunks.
23
+ const windFit = exposure > 0.5 ? sp.stiffness * 0.9 + (1 - Math.min(1, crRatio * 1.1)) * 0.6 : 0.45;
24
+ // Wet sites slightly boost spreading riparian/humid vigour; dry sites reward high stiffness & compact crowns.
25
+ const moistFit = moisture > 0.58 ? Math.min(1, sp.clumpSize * 0.5 + 0.3) : sp.stiffness * 0.45 + 0.3;
26
+ return lightFit * 0.48 + windFit * 0.32 + moistFit * 0.2;
27
+ }
28
+ function clamp01(v) {
29
+ return v < 0 ? 0 : v > 1 ? 1 : v;
30
+ }
31
+ function hash01(index, seed) {
32
+ let h = Math.imul(index ^ seed, 0x9e3779b1) >>> 0;
33
+ h ^= h >>> 16;
34
+ h = Math.imul(h, 0x7feb352d) >>> 0;
35
+ h ^= h >>> 15;
36
+ h = Math.imul(h, 0x846ca68b) >>> 0;
37
+ h ^= h >>> 16;
38
+ return (h >>> 0) / 4294967296;
39
+ }
40
+ function floraIndexMap() {
41
+ const map = new Map();
42
+ for (let i = 0; i < ALL_FLORA_SPECIES.length; i++)
43
+ map.set(ALL_FLORA_SPECIES[i].id, i);
44
+ return map;
45
+ }
46
+ function parseTreeRecords(trees, speciesList, speciesDnaCache, leans, collars) {
47
+ const count = Math.floor(trees.length / TREE_STRIDE);
48
+ const out = [];
49
+ for (let i = 0; i < count; i++) {
50
+ const o = i * TREE_STRIDE;
51
+ const spIdx = Math.round(trees[o + 3]);
52
+ const sp = speciesList[spIdx] ?? speciesList[0];
53
+ const h = Number.isFinite(trees[o + 4]) ? trees[o + 4] : sp.height;
54
+ const hFrac = h / Math.max(1, sp.height);
55
+ const recSeed = Number.isFinite(trees[o + 9]) ? Math.round(trees[o + 9]) : 101 + i;
56
+ let dna = speciesDnaCache?.[spIdx];
57
+ if (!dna) {
58
+ dna = encodeDna(speciesToGenome(sp, 101 + spIdx));
59
+ if (speciesDnaCache)
60
+ speciesDnaCache[spIdx] = dna;
61
+ }
62
+ out.push({
63
+ x: trees[o],
64
+ y: trees[o + 1],
65
+ z: trees[o + 2],
66
+ speciesIndex: spIdx,
67
+ height: h,
68
+ crownRadius: Number.isFinite(trees[o + 5]) ? trees[o + 5] : sp.crownRadius,
69
+ crownBase: Number.isFinite(trees[o + 6]) ? trees[o + 6] : sp.crownBase,
70
+ trunkRadius: Number.isFinite(trees[o + 7]) ? trees[o + 7] : sp.trunkRadius,
71
+ yaw: trees[o + 8],
72
+ seed: recSeed,
73
+ ageYears: Math.max(2, Math.round(Math.min(1.15, Math.max(0.12, hFrac)) * 45)),
74
+ coppiced: false,
75
+ dna,
76
+ generation: 1,
77
+ leanX: leans?.[i * 2] ?? 0,
78
+ leanZ: leans?.[i * 2 + 1] ?? 0,
79
+ collar: collars?.[i] === 1,
80
+ });
81
+ }
82
+ return out;
83
+ }
84
+ function packTreeRecords(records) {
85
+ const out = new Float32Array(records.length * TREE_STRIDE);
86
+ for (let i = 0; i < records.length; i++) {
87
+ const r = records[i];
88
+ const o = i * TREE_STRIDE;
89
+ out[o] = r.x;
90
+ out[o + 1] = r.y;
91
+ out[o + 2] = r.z;
92
+ out[o + 3] = r.speciesIndex;
93
+ out[o + 4] = r.height;
94
+ out[o + 5] = r.crownRadius;
95
+ out[o + 6] = r.crownBase;
96
+ out[o + 7] = r.trunkRadius;
97
+ out[o + 8] = r.yaw;
98
+ out[o + 9] = r.seed;
99
+ }
100
+ return out;
101
+ }
102
+ /**
103
+ * Create a stateful ecological forest & garden sandbox synced with terrain, canopy, soil,
104
+ * epiphytes, and continuous turf cover.
105
+ */
106
+ export function createBiomeSandbox(opts) {
107
+ const { baseSubstrate, rules, initialSolved } = opts;
108
+ const canopyCell = Math.max(0.5, opts.canopyCell ?? 2);
109
+ const mapCell = Math.max(0.25, opts.mapCell ?? initialSolved.grassMap.cell ?? 0.5);
110
+ const seed = opts.seed ?? 1337;
111
+ let foliageRetention = opts.foliageRetention ?? 1;
112
+ let onChange = opts.onChange;
113
+ const subscribers = new Set();
114
+ const floraIdxById = floraIndexMap();
115
+ // The solve's own rock cover (webgpu-rocks); rocks never change in the sandbox.
116
+ const rockCover = initialSolved.rockCover;
117
+ const rockCovered = (x, z) => {
118
+ if (!rockCover)
119
+ return false;
120
+ const ri = Math.min(rockCover.nx - 1, Math.max(0, Math.floor((x - baseSubstrate.x0) / rockCover.cell)));
121
+ const rj = Math.min(rockCover.nz - 1, Math.max(0, Math.floor((z - baseSubstrate.z0) / rockCover.cell)));
122
+ return rockCover.grid[rj * rockCover.nx + ri] === 1;
123
+ };
124
+ // Shrub-mantle guilds give the ground round their stems a collar, as in the initial solve.
125
+ const mantleSpecies = new Set(rules.overstory.filter((g) => g.role === "mantle").map((g) => g.speciesName));
126
+ // Where a version 1 snapshot (no per-tree lean or collar) stands a tree of the initial solve.
127
+ const initialTreeAt = new Map();
128
+ for (let t = 0; t < initialSolved.treeCount; t++) {
129
+ const o = t * TREE_STRIDE;
130
+ initialTreeAt.set(`${initialSolved.trees[o]},${initialSolved.trees[o + 2]},${initialSolved.trees[o + 9]}`, t);
131
+ }
132
+ const initialGroundFlora = initialSolved.flora.slice(0, initialSolved.groundFloraCount * FLORA_STRIDE);
133
+ const suppressMap = new Map();
134
+ for (const fg of rules.flora ?? []) {
135
+ const idx = floraIdxById.get(fg.speciesId);
136
+ if (idx !== undefined)
137
+ suppressMap.set(idx, Boolean(fg.suppressesTurf));
138
+ }
139
+ let year = 0;
140
+ let actionSeq = 0;
141
+ const baseSpeciesCount = (opts.treeSpecies ?? ALL_SPECIES).length;
142
+ let speciesList = (opts.treeSpecies ?? ALL_SPECIES).map((s) => cloneSpecies(s));
143
+ const baseDnaCache = [];
144
+ let trees = parseTreeRecords(initialSolved.trees, speciesList, baseDnaCache, initialSolved.treeLeans, initialSolved.treeCollars);
145
+ let manualFlora = [];
146
+ let mycoPatches = [];
147
+ let solved = initialSolved;
148
+ const genomeCache = new Map();
149
+ let wildSeq = 0;
150
+ const currentMaxGeneration = () => {
151
+ let m = 1;
152
+ for (const t of trees)
153
+ if (t.generation > m)
154
+ m = t.generation;
155
+ return m;
156
+ };
157
+ const currentWildHybrids = () => {
158
+ let c = 0;
159
+ for (const t of trees)
160
+ if (t.generation > 1)
161
+ c++;
162
+ return c;
163
+ };
164
+ const failResult = (action, note) => ({
165
+ ok: false,
166
+ action,
167
+ year,
168
+ note,
169
+ changedTrees: false,
170
+ changedFlora: false,
171
+ treeCount: solved.treeCount,
172
+ floraCount: solved.floraCount,
173
+ meanShelter: solved.meanShelter,
174
+ maxGeneration: currentMaxGeneration(),
175
+ wildHybridCount: currentWildHybrids(),
176
+ });
177
+ const genomeForTree = (rec) => {
178
+ let g = genomeCache.get(rec.dna);
179
+ if (!g) {
180
+ try {
181
+ g = decodeDna(rec.dna);
182
+ }
183
+ catch {
184
+ g = speciesToGenome(speciesList[rec.speciesIndex] ?? speciesList[0], rec.seed);
185
+ }
186
+ genomeCache.set(rec.dna, g);
187
+ }
188
+ return g;
189
+ };
190
+ const wildSlotIndices = [];
191
+ const registerWildCultivar = (species) => {
192
+ const existing = speciesList.findIndex((s) => s.name.toLowerCase() === species.name.toLowerCase());
193
+ if (existing >= 0) {
194
+ speciesList[existing] = cloneSpecies(species);
195
+ return existing;
196
+ }
197
+ if (wildSlotIndices.length < MAX_WILD_CULTIVARS) {
198
+ speciesList.push(cloneSpecies(species));
199
+ const idx = speciesList.length - 1;
200
+ wildSlotIndices.push(idx);
201
+ return idx;
202
+ }
203
+ // Reuse an unused wild slot, or fallback to oldest wild slot of same architecture to keep speciesList bounded.
204
+ const used = new Set(trees.map((t) => t.speciesIndex));
205
+ const freeIdx = wildSlotIndices.find((idx) => !used.has(idx));
206
+ if (freeIdx !== undefined) {
207
+ speciesList[freeIdx] = cloneSpecies(species);
208
+ return freeIdx;
209
+ }
210
+ const sameArchIdx = wildSlotIndices.find((idx) => speciesList[idx]?.architecture === species.architecture);
211
+ return sameArchIdx ?? wildSlotIndices[wildSeq % wildSlotIndices.length];
212
+ };
213
+ const insideBounds = (x, z) => x >= baseSubstrate.x0 + 1 &&
214
+ x <= baseSubstrate.x0 + baseSubstrate.width - 1 &&
215
+ z >= baseSubstrate.z0 + 1 &&
216
+ z <= baseSubstrate.z0 + baseSubstrate.depth - 1;
217
+ const registerCultivar = (species) => {
218
+ const errs = checkSpecies(species);
219
+ if (errs.length > 0)
220
+ throw new Error(`Invalid TreeSpecies cultivar "${species.name}": ${errs.join("; ")}`);
221
+ const existing = speciesList.findIndex((s) => s.name.toLowerCase() === species.name.toLowerCase());
222
+ if (existing >= 0) {
223
+ speciesList[existing] = cloneSpecies(species);
224
+ return existing;
225
+ }
226
+ speciesList.push(cloneSpecies(species));
227
+ return speciesList.length - 1;
228
+ };
229
+ const resolveTreeSpeciesIndex = (spec) => {
230
+ if (typeof spec === "number" && Number.isInteger(spec) && spec >= 0 && spec < speciesList.length) {
231
+ return spec;
232
+ }
233
+ if (typeof spec === "string" && spec.trim().length > 0) {
234
+ const q = spec.trim().toLowerCase();
235
+ const idx = speciesList.findIndex((s) => s.name.toLowerCase() === q);
236
+ if (idx >= 0)
237
+ return idx;
238
+ }
239
+ const defName = rules.overstory[0]?.speciesName ?? "Oak";
240
+ const defIdx = speciesList.findIndex((s) => s.name.toLowerCase() === defName.toLowerCase());
241
+ return defIdx >= 0 ? defIdx : 0;
242
+ };
243
+ const recompute = (changedTrees, changedFlora) => {
244
+ const packedTrees = packTreeRecords(trees);
245
+ const treeCount = trees.length;
246
+ const mycorrhizaBoosts = mycoPatches.map((p) => ({
247
+ x: p.x,
248
+ z: p.z,
249
+ radius: p.radius,
250
+ strength: p.strength,
251
+ }));
252
+ const canopy = bakeCanopyCpu({
253
+ bounds: { x0: baseSubstrate.x0, z0: baseSubstrate.z0, width: baseSubstrate.width, depth: baseSubstrate.depth },
254
+ cell: canopyCell,
255
+ trees: packedTrees,
256
+ species: speciesList,
257
+ foliageRetention,
258
+ mycorrhizaBoosts,
259
+ });
260
+ const soil = deriveLitterSoil(baseSubstrate, canopy.litter, canopy.coniferShare, canopy.nx, canopy.nz);
261
+ // Nurse logs from felled trees slowly enrich surrounding humus fertility as years pass.
262
+ for (const mf of manualFlora) {
263
+ if (!mf.isDeadwood)
264
+ continue;
265
+ const decayAge = Math.max(0, year - mf.birthYear);
266
+ const boost = Math.min(0.28, decayAge * 0.012);
267
+ if (boost <= 0.005)
268
+ continue;
269
+ const r = Math.max(2.5, mf.radius * 2.4);
270
+ const i0 = Math.max(0, Math.floor((mf.x - r - baseSubstrate.x0) / baseSubstrate.cell));
271
+ const i1 = Math.min(baseSubstrate.nx - 1, Math.ceil((mf.x + r - baseSubstrate.x0) / baseSubstrate.cell));
272
+ const j0 = Math.max(0, Math.floor((mf.z - r - baseSubstrate.z0) / baseSubstrate.cell));
273
+ const j1 = Math.min(baseSubstrate.nz - 1, Math.ceil((mf.z + r - baseSubstrate.z0) / baseSubstrate.cell));
274
+ for (let j = j0; j <= j1; j++) {
275
+ const gz = baseSubstrate.z0 + j * baseSubstrate.cell;
276
+ for (let i = i0; i <= i1; i++) {
277
+ const gx = baseSubstrate.x0 + i * baseSubstrate.cell;
278
+ const d = Math.hypot(gx - mf.x, gz - mf.z);
279
+ if (d < r) {
280
+ const k = j * baseSubstrate.nx + i;
281
+ soil.fertility[k] = clamp01(soil.fertility[k] + boost * (1 - d / r));
282
+ }
283
+ }
284
+ }
285
+ }
286
+ const effectiveSubstrate = {
287
+ ...baseSubstrate,
288
+ soilPh: soil.soilPh,
289
+ fertility: soil.fertility,
290
+ };
291
+ let shelterSum = 0;
292
+ for (let k = 0; k < canopy.shelter.length; k++)
293
+ shelterSum += canopy.shelter[k];
294
+ const meanShelter = canopy.shelter.length > 0 ? shelterSum / canopy.shelter.length : 0;
295
+ // Ground flora: keep ecologically compatible baseline ground flora + active manual/recruited flora.
296
+ const keptGround = [];
297
+ const keptSuppresses = [];
298
+ const baseCount = Math.floor(initialGroundFlora.length / FLORA_STRIDE);
299
+ for (let i = 0; i < baseCount; i++) {
300
+ const o = i * FLORA_STRIDE;
301
+ const fx = initialGroundFlora[o];
302
+ const fz = initialGroundFlora[o + 2];
303
+ const spIdx = Math.round(initialGroundFlora[o + 3]);
304
+ const sp = ALL_FLORA_SPECIES[spIdx];
305
+ if (sp) {
306
+ const can = sampleCanopyCpu(canopy, fx, fz);
307
+ // Sun-loving dwarf shrubs (`heather`, `cistusScrub`) thin out under newly closed deep canopy.
308
+ if ((sp.id === "heather" || sp.id === "cistusScrub") && can.shelter > 0.72)
309
+ continue;
310
+ }
311
+ for (let c = 0; c < FLORA_STRIDE; c++)
312
+ keptGround.push(initialGroundFlora[o + c]);
313
+ keptSuppresses.push(initialSolved.groundFloraSuppressesTurf[i] ?? 0);
314
+ }
315
+ for (const mf of manualFlora) {
316
+ keptGround.push(mf.x, mf.y, mf.z, mf.speciesIndex, mf.height, mf.radius, mf.yaw, mf.seed);
317
+ keptSuppresses.push(mf.suppressesTurf ? 1 : 0);
318
+ }
319
+ const groundFloraCount = Math.floor(keptGround.length / FLORA_STRIDE);
320
+ // Each tree's lean and collar travel with its record, whatever was felled or reordered.
321
+ const nextLeans = new Float32Array(treeCount * 2);
322
+ const treeCollars = new Uint8Array(treeCount);
323
+ for (let t = 0; t < treeCount; t++) {
324
+ nextLeans[t * 2] = trees[t].leanX;
325
+ nextLeans[t * 2 + 1] = trees[t].leanZ;
326
+ treeCollars[t] = trees[t].collar ? 1 : 0;
327
+ }
328
+ // Tree-hosted epiphytes, placed as the initial solve places them (epiphytes.ts).
329
+ const epiRaw = placeEpiphytes({
330
+ rules,
331
+ trees: packedTrees,
332
+ treeCount,
333
+ treeLeans: nextLeans,
334
+ treeSpecies: speciesList,
335
+ substrate: effectiveSubstrate,
336
+ canopy,
337
+ seed,
338
+ });
339
+ const epiphyteCount = Math.floor(epiRaw.length / FLORA_STRIDE);
340
+ const flora = new Float32Array(keptGround.length + epiRaw.length);
341
+ flora.set(keptGround, 0);
342
+ flora.set(epiRaw, keptGround.length);
343
+ const floraCount = groundFloraCount + epiphyteCount;
344
+ // Re-solve the turf with the initial solve's own classification (turf.ts) under the current stand.
345
+ const groundFloraSuppressesTurf = Uint8Array.from(keptSuppresses);
346
+ const shrubHalo = createShrubHaloField(baseSubstrate);
347
+ for (const rec of trees)
348
+ if (rec.collar)
349
+ shrubHalo.stamp(Math.fround(rec.x), Math.fround(rec.z), Math.fround(rec.crownRadius));
350
+ const layout = {
351
+ nx: initialSolved.grassMap.nx,
352
+ nz: initialSolved.grassMap.nz,
353
+ x0: initialSolved.grassMap.x0,
354
+ z0: initialSolved.grassMap.z0,
355
+ cell: mapCell,
356
+ };
357
+ const ids = classifyTurf({
358
+ substrate: effectiveSubstrate,
359
+ rules,
360
+ canopy,
361
+ layout,
362
+ rockCover,
363
+ flora,
364
+ groundFloraCount,
365
+ suppression: buildTurfSuppression(baseSubstrate, flora, groundFloraCount, groundFloraSuppressesTurf),
366
+ shrubHalo,
367
+ });
368
+ const nextTints = computeTreeEdaphicTints(packedTrees, treeCount, effectiveSubstrate);
369
+ solved = {
370
+ rocks: initialSolved.rocks,
371
+ rockCount: initialSolved.rockCount,
372
+ trees: packedTrees,
373
+ treeCount,
374
+ treeLeans: nextLeans,
375
+ treeTints: nextTints,
376
+ canopy,
377
+ meanShelter,
378
+ soil,
379
+ flora,
380
+ groundFloraCount,
381
+ epiphyteCount,
382
+ floraCount,
383
+ grassMap: { ids, ...layout },
384
+ treeCollars,
385
+ rockCover,
386
+ groundFloraSuppressesTurf,
387
+ };
388
+ void changedTrees;
389
+ void changedFlora;
390
+ };
391
+ const emitResult = (res) => {
392
+ if (res.ok) {
393
+ for (const listener of [...subscribers])
394
+ listener(res, solved);
395
+ if (onChange)
396
+ onChange(res, solved);
397
+ }
398
+ return res;
399
+ };
400
+ const addManualFloraCluster = (speciesId, cx, cz, count, colonyRadius, localSeed, suppressesTurf = false, scaleMult = 1) => {
401
+ const spIdx = floraIdxById.get(speciesId);
402
+ if (spIdx === undefined)
403
+ return 0;
404
+ const sp = ALL_FLORA_SPECIES[spIdx];
405
+ let added = 0;
406
+ for (let i = 0; i < count; i++) {
407
+ const ang = hash01(i * 13 + 3, localSeed) * Math.PI * 2;
408
+ const rad = count === 1 ? 0 : Math.sqrt(hash01(i * 29 + 7, localSeed)) * colonyRadius;
409
+ const px = cx + Math.cos(ang) * rad;
410
+ const pz = cz + Math.sin(ang) * rad;
411
+ if (!insideBounds(px, pz))
412
+ continue;
413
+ const sub = sampleSubstrateCpu(baseSubstrate, px, pz);
414
+ if (rules.waterLevel !== undefined && sub.height < rules.waterLevel + 0.04)
415
+ continue;
416
+ const scale = scaleMult * (0.82 + 0.36 * hash01(i * 41 + 11, localSeed));
417
+ manualFlora.push({
418
+ x: px,
419
+ y: sub.height,
420
+ z: pz,
421
+ speciesIndex: spIdx,
422
+ height: sp.height * scale,
423
+ radius: sp.radius * scale,
424
+ yaw: hash01(i * 53 + 19, localSeed) * Math.PI * 2,
425
+ seed: Math.floor(hash01(i * 67 + 23, localSeed) * 1_000_000),
426
+ birthYear: year,
427
+ suppressesTurf: suppressesTurf || sp.archetype === "cushion" || sp.archetype === "deadwood",
428
+ isDeadwood: sp.archetype === "deadwood",
429
+ });
430
+ added++;
431
+ }
432
+ return added;
433
+ };
434
+ const findNearestTreeIndex = (x, z, radius, preferBroadleaf) => {
435
+ let bestIdx = -1;
436
+ let bestDist = Infinity;
437
+ let bestFallbackIdx = -1;
438
+ let bestFallbackDist = Infinity;
439
+ for (let i = 0; i < trees.length; i++) {
440
+ const d = Math.hypot(trees[i].x - x, trees[i].z - z);
441
+ if (d > radius)
442
+ continue;
443
+ const sp = speciesList[trees[i].speciesIndex];
444
+ const isBroad = sp && (sp.architecture === "broadleaf" || sp.architecture === "shrub");
445
+ if (preferBroadleaf && isBroad) {
446
+ if (d < bestDist) {
447
+ bestDist = d;
448
+ bestIdx = i;
449
+ }
450
+ }
451
+ else if (d < bestFallbackDist) {
452
+ bestFallbackDist = d;
453
+ bestFallbackIdx = i;
454
+ }
455
+ }
456
+ return bestIdx >= 0 ? bestIdx : bestFallbackIdx;
457
+ };
458
+ return {
459
+ get year() {
460
+ return year;
461
+ },
462
+ get species() {
463
+ return speciesList;
464
+ },
465
+ get solved() {
466
+ return solved;
467
+ },
468
+ get maxGeneration() {
469
+ return currentMaxGeneration();
470
+ },
471
+ get wildHybridCount() {
472
+ return currentWildHybrids();
473
+ },
474
+ setFoliageRetention(retention) {
475
+ foliageRetention = clamp01(retention);
476
+ },
477
+ subscribe(listener) {
478
+ subscribers.add(listener);
479
+ return () => {
480
+ subscribers.delete(listener);
481
+ };
482
+ },
483
+ setOnChange(handler) {
484
+ onChange = handler;
485
+ },
486
+ registerCultivar,
487
+ plantTree(pOpts) {
488
+ actionSeq++;
489
+ const { x, z } = pOpts;
490
+ if (!insideBounds(x, z)) {
491
+ return failResult("plantTree", `Position (${x.toFixed(1)}, ${z.toFixed(1)}) is outside plot bounds.`);
492
+ }
493
+ const sub = sampleSubstrateCpu(baseSubstrate, x, z);
494
+ if (rules.waterLevel !== undefined && sub.height < rules.waterLevel + 0.06) {
495
+ return failResult("plantTree", `Cannot plant below water table (${sub.height.toFixed(2)} m < ${rules.waterLevel.toFixed(2)} m).`);
496
+ }
497
+ if (sub.slopeDeg > rules.rockSlopeDeg + 8) {
498
+ return failResult("plantTree", `Cliff slope (${sub.slopeDeg.toFixed(1)} deg) is too steep for planting.`);
499
+ }
500
+ let dnaSpecies;
501
+ let decodedGenome;
502
+ if (pOpts.dna && pOpts.dna.trim().length > 0) {
503
+ try {
504
+ decodedGenome = decodeDna(pOpts.dna);
505
+ const cname = pOpts.cultivarName?.trim() || `Cultivar ${pOpts.dna.trim().slice(5, 11)}`;
506
+ dnaSpecies = genomeToSpecies(decodedGenome, cname);
507
+ }
508
+ catch (err) {
509
+ return failResult("plantTree", `Invalid DNA string: ${err instanceof Error ? err.message : String(err)}`);
510
+ }
511
+ }
512
+ const spIdx = pOpts.customSpecies
513
+ ? registerCultivar(pOpts.customSpecies)
514
+ : dnaSpecies
515
+ ? registerCultivar(dnaSpecies)
516
+ : resolveTreeSpeciesIndex(pOpts.species);
517
+ const sp = speciesList[spIdx];
518
+ const stage = pOpts.stage ?? "young";
519
+ const stages = lifeStageSizes(sp);
520
+ const st = stages.find((s) => s.key === stage) ?? stages[1];
521
+ const ageMap = { sapling: 3, young: 10, mid: 24, mature: 48 };
522
+ const tSeed = pOpts.seed ?? Math.floor(hash01(actionSeq * 101, seed + 17) * 1_000_000);
523
+ const yaw = pOpts.yaw ?? hash01(actionSeq * 37, seed + 53) * Math.PI * 2;
524
+ const treeDna = decodedGenome ? pOpts.dna.trim() : encodeDna(speciesToGenome(sp, tSeed));
525
+ const treeGen = decodedGenome ? Math.max(1, decodedGenome.generation) : 1;
526
+ trees.push({
527
+ x,
528
+ y: sub.height,
529
+ z,
530
+ speciesIndex: spIdx,
531
+ height: st.size.height,
532
+ crownRadius: st.size.crownRadius,
533
+ crownBase: st.size.crownBase,
534
+ trunkRadius: st.size.trunkRadius,
535
+ yaw,
536
+ seed: tSeed,
537
+ ageYears: ageMap[stage],
538
+ coppiced: false,
539
+ dna: treeDna,
540
+ generation: treeGen,
541
+ leanX: 0,
542
+ leanZ: 0,
543
+ collar: stage === "sapling" || mantleSpecies.has(sp.name),
544
+ });
545
+ recompute(true, true);
546
+ const localShelter = sampleCanopyCpu(solved.canopy, x, z).shelter;
547
+ return emitResult({
548
+ ok: true,
549
+ action: "plantTree",
550
+ year,
551
+ note: `Planted ${stage} ${sp.name} (F${treeGen}) at (${x.toFixed(1)}, ${z.toFixed(1)}).`,
552
+ changedTrees: true,
553
+ changedFlora: true,
554
+ treeCount: solved.treeCount,
555
+ floraCount: solved.floraCount,
556
+ meanShelter: solved.meanShelter,
557
+ maxGeneration: currentMaxGeneration(),
558
+ wildHybridCount: currentWildHybrids(),
559
+ localShelter,
560
+ });
561
+ },
562
+ plantFlora(fOpts) {
563
+ actionSeq++;
564
+ const { x, z, speciesId } = fOpts;
565
+ if (!floraIdxById.has(speciesId)) {
566
+ return failResult("plantFlora", `Unknown flora species "${speciesId}".`);
567
+ }
568
+ if (!insideBounds(x, z)) {
569
+ return failResult("plantFlora", `Position (${x.toFixed(1)}, ${z.toFixed(1)}) is outside plot bounds.`);
570
+ }
571
+ const sp = ALL_FLORA_SPECIES[floraIdxById.get(speciesId)];
572
+ const count = fOpts.count ?? (sp.archetype === "deadwood" ? 1 : 9);
573
+ const radius = fOpts.colonyRadius ?? (sp.archetype === "deadwood" ? 0.5 : 2.8);
574
+ const added = addManualFloraCluster(speciesId, x, z, count, radius, fOpts.seed ?? seed + actionSeq * 89);
575
+ recompute(false, added > 0);
576
+ return emitResult({
577
+ ok: added > 0,
578
+ action: "plantFlora",
579
+ year,
580
+ note: added > 0 ? `Planted ${added}× ${sp.name} near (${x.toFixed(1)}, ${z.toFixed(1)}).` : "No suitable terrestrial cell found.",
581
+ changedTrees: false,
582
+ changedFlora: added > 0,
583
+ treeCount: solved.treeCount,
584
+ floraCount: solved.floraCount,
585
+ meanShelter: solved.meanShelter,
586
+ maxGeneration: currentMaxGeneration(),
587
+ wildHybridCount: currentWildHybrids(),
588
+ localShelter: sampleCanopyCpu(solved.canopy, x, z).shelter,
589
+ });
590
+ },
591
+ inoculateMycorrhiza(mOpts) {
592
+ actionSeq++;
593
+ const { x, z } = mOpts;
594
+ if (!insideBounds(x, z)) {
595
+ return failResult("inoculateMycorrhiza", `Position (${x.toFixed(1)}, ${z.toFixed(1)}) is outside plot bounds.`);
596
+ }
597
+ const radius = mOpts.radius ?? 9.5;
598
+ const strength = clamp01(mOpts.strength ?? 0.92);
599
+ mycoPatches.push({ x, z, radius, strength });
600
+ const sub = sampleSubstrateCpu(baseSubstrate, x, z);
601
+ const fungiId = sub.soilPh < 0.45 ? "flyAgaric" : sub.moisture > 0.56 ? "chanterelle" : "boletus";
602
+ const fruited = addManualFloraCluster(fungiId, x, z, 8, radius * 0.65, mOpts.seed ?? seed + actionSeq * 131);
603
+ recompute(false, fruited > 0);
604
+ return emitResult({
605
+ ok: true,
606
+ action: "inoculateMycorrhiza",
607
+ year,
608
+ note: `Inoculated ectomycorrhizal root zone (${radius.toFixed(1)} m) and fruited ${fruited} ${fungiId} mushrooms.`,
609
+ changedTrees: false,
610
+ changedFlora: true,
611
+ treeCount: solved.treeCount,
612
+ floraCount: solved.floraCount,
613
+ meanShelter: solved.meanShelter,
614
+ maxGeneration: currentMaxGeneration(),
615
+ wildHybridCount: currentWildHybrids(),
616
+ localShelter: sampleCanopyCpu(solved.canopy, x, z).shelter,
617
+ });
618
+ },
619
+ coppiceTree(tOpts) {
620
+ actionSeq++;
621
+ const idx = findNearestTreeIndex(tOpts.x, tOpts.z, tOpts.radius ?? 10, true);
622
+ if (idx < 0) {
623
+ return failResult("coppiceTree", `No tree found within ${(tOpts.radius ?? 10).toFixed(0)} m of (${tOpts.x.toFixed(1)}, ${tOpts.z.toFixed(1)}).`);
624
+ }
625
+ const rec = trees[idx];
626
+ const sp = speciesList[rec.speciesIndex];
627
+ rec.height = Math.max(1.4, sp.height * 0.25);
628
+ rec.crownRadius = Math.max(0.8, sp.crownRadius * 0.36);
629
+ rec.crownBase = Math.min(0.4, sp.crownBase * 0.22);
630
+ rec.trunkRadius = Math.max(0.06, rec.trunkRadius * 0.65);
631
+ rec.ageYears = 3;
632
+ rec.coppiced = true;
633
+ // Sunlit coppice stools flush the clearing edge with woodland forbs.
634
+ addManualFloraCluster("foxglove", rec.x, rec.z, 5, Math.max(2.2, rec.crownRadius * 1.6), seed + actionSeq * 173);
635
+ addManualFloraCluster("woodSorrel", rec.x, rec.z, 4, Math.max(1.8, rec.crownRadius * 1.3), seed + actionSeq * 197);
636
+ recompute(true, true);
637
+ const localShelter = sampleCanopyCpu(solved.canopy, rec.x, rec.z).shelter;
638
+ return emitResult({
639
+ ok: true,
640
+ action: "coppiceTree",
641
+ year,
642
+ note: `Coppiced ${sp.name} stool -> multi-stem regrowth & sunlit glade.`,
643
+ changedTrees: true,
644
+ changedFlora: true,
645
+ treeCount: solved.treeCount,
646
+ floraCount: solved.floraCount,
647
+ meanShelter: solved.meanShelter,
648
+ maxGeneration: currentMaxGeneration(),
649
+ wildHybridCount: currentWildHybrids(),
650
+ localShelter,
651
+ });
652
+ },
653
+ fellTree(tOpts) {
654
+ actionSeq++;
655
+ const idx = findNearestTreeIndex(tOpts.x, tOpts.z, tOpts.radius ?? 10, false);
656
+ if (idx < 0) {
657
+ return failResult("fellTree", `No tree found within ${(tOpts.radius ?? 10).toFixed(0)} m of (${tOpts.x.toFixed(1)}, ${tOpts.z.toFixed(1)}).`);
658
+ }
659
+ const removed = trees.splice(idx, 1)[0];
660
+ const sp = speciesList[removed.speciesIndex];
661
+ const scaleMult = Math.min(1.6, Math.max(0.75, removed.height / 14));
662
+ addManualFloraCluster("nurseLog", removed.x, removed.z, 1, 0.2, seed + actionSeq * 211, true, scaleMult);
663
+ addManualFloraCluster("turkeyTail", removed.x, removed.z, 3, 1.4, seed + actionSeq * 223);
664
+ addManualFloraCluster("foxglove", removed.x, removed.z, 6, Math.max(3.2, removed.crownRadius * 0.9), seed + actionSeq * 239);
665
+ recompute(true, true);
666
+ const localShelter = sampleCanopyCpu(solved.canopy, removed.x, removed.z).shelter;
667
+ return emitResult({
668
+ ok: true,
669
+ action: "fellTree",
670
+ year,
671
+ note: `Felled ${sp.name} -> nurse log, bracket fungi & canopy light gap.`,
672
+ changedTrees: true,
673
+ changedFlora: true,
674
+ treeCount: solved.treeCount,
675
+ floraCount: solved.floraCount,
676
+ meanShelter: solved.meanShelter,
677
+ maxGeneration: currentMaxGeneration(),
678
+ wildHybridCount: currentWildHybrids(),
679
+ localShelter,
680
+ });
681
+ },
682
+ stepSuccession(yearsRaw) {
683
+ actionSeq++;
684
+ const years = Math.max(1, Math.min(100, Math.round(yearsRaw)));
685
+ year += years;
686
+ // 1. Allometric growth along species life stages, modulated by light & coppice vigour.
687
+ for (const rec of trees) {
688
+ const sp = speciesList[rec.speciesIndex];
689
+ if (!sp)
690
+ continue;
691
+ const can = sampleCanopyCpu(solved.canopy, rec.x, rec.z);
692
+ const lightFactor = 0.65 + 0.55 * (1 - can.shelter * 0.6);
693
+ const coppiceBoost = rec.coppiced ? 1.35 : 1.0;
694
+ const rate = 0.038 * lightFactor * coppiceBoost;
695
+ const tAdvance = 1 - Math.exp(-rate * years);
696
+ rec.ageYears += years;
697
+ const targetH = sp.height * 1.05;
698
+ const targetCr = sp.crownRadius * 1.05;
699
+ const targetCb = Math.min(targetH * 0.68, sp.crownBase * 1.04);
700
+ const targetTr = sp.trunkRadius * 1.08;
701
+ rec.height = Math.max(rec.height, rec.height + (targetH - rec.height) * tAdvance);
702
+ rec.crownRadius = Math.max(rec.crownRadius, rec.crownRadius + (targetCr - rec.crownRadius) * tAdvance * (rec.coppiced ? 1.15 : 1));
703
+ rec.crownBase = Math.min(rec.height * 0.7, rec.crownBase + (targetCb - rec.crownBase) * tAdvance * 0.8);
704
+ rec.trunkRadius = Math.max(rec.trunkRadius, rec.trunkRadius + (targetTr - rec.trunkRadius) * tAdvance);
705
+ }
706
+ // 2. Pioneer recruitment in sunlit canopy gaps & shade-tolerant regeneration under closing woods.
707
+ const pioneerGuild = rules.overstory.find((g) => g.role === "pioneer") ??
708
+ rules.overstory.find((g) => g.speciesName === "Silver birch" || g.speciesName === "Rowan" || g.speciesName === "Scots pine") ??
709
+ rules.overstory[rules.overstory.length - 1];
710
+ const climaxGuild = rules.overstory.find((g) => g.role === "canopy") ?? rules.overstory[0];
711
+ let recruitedTrees = 0;
712
+ const maxRecruitTrees = Math.min(18, Math.max(1, Math.round(years * 0.75)));
713
+ const sampleProbes = Math.min(120, Math.max(16, Math.round(years * 6)));
714
+ const maxTreesLimit = (rules.maxTrees ?? 600) + 120;
715
+ for (let p = 0; p < sampleProbes && trees.length < maxTreesLimit; p++) {
716
+ const px = baseSubstrate.x0 + 6 + hash01(p * 31 + actionSeq * 7, seed + 811) * Math.max(4, baseSubstrate.width - 12);
717
+ const pz = baseSubstrate.z0 + 6 + hash01(p * 47 + actionSeq * 11, seed + 823) * Math.max(4, baseSubstrate.depth - 12);
718
+ if (rules.pathFn && rules.pathFn(px, pz) !== null)
719
+ continue;
720
+ const sub = sampleSubstrateCpu(baseSubstrate, px, pz);
721
+ if (rules.waterLevel !== undefined && sub.height < rules.waterLevel + 0.1)
722
+ continue;
723
+ if (sub.slopeDeg > rules.rockSlopeDeg)
724
+ continue;
725
+ if (rockCovered(px, pz))
726
+ continue;
727
+ const can = sampleCanopyCpu(solved.canopy, px, pz);
728
+ // Check spacing against existing trunks.
729
+ let crowded = false;
730
+ for (const t of trees) {
731
+ if (Math.hypot(t.x - px, t.z - pz) < Math.max(3.4, t.crownRadius * 0.75)) {
732
+ crowded = true;
733
+ break;
734
+ }
735
+ }
736
+ if (crowded)
737
+ continue;
738
+ const pickParentArchs = () => {
739
+ const fallbackArch = pioneerGuild
740
+ ? speciesList[resolveTreeSpeciesIndex(pioneerGuild.speciesName)]?.architecture
741
+ : climaxGuild
742
+ ? speciesList[resolveTreeSpeciesIndex(climaxGuild.speciesName)]?.architecture
743
+ : "broadleaf";
744
+ return fallbackArch ? [fallbackArch, "broadleaf", "conifer", "shrub"] : ["broadleaf", "conifer", "shrub"];
745
+ };
746
+ const recruitFromParents = (fallbackSpeciesName, ageY, useYoungStage) => {
747
+ const nearby = [];
748
+ for (const t of trees) {
749
+ if (t.ageYears < 12)
750
+ continue;
751
+ const d = Math.hypot(t.x - px, t.z - pz);
752
+ if (d > 48)
753
+ continue;
754
+ const tsp = speciesList[t.speciesIndex];
755
+ if (tsp)
756
+ nearby.push({ rec: t, arch: tsp.architecture, dist: d });
757
+ }
758
+ let chosenArch = null;
759
+ for (const a of pickParentArchs()) {
760
+ if (nearby.filter((n) => n.arch === a).length >= 2) {
761
+ chosenArch = a;
762
+ break;
763
+ }
764
+ }
765
+ if (chosenArch) {
766
+ const pool = nearby.filter((n) => n.arch === chosenArch).sort((a, b) => a.dist - b.dist);
767
+ const pA = pool[0].rec;
768
+ const pB = pool[1 + Math.floor(hash01(p * 13 + actionSeq, seed + 919) * Math.min(4, pool.length - 1))].rec;
769
+ const gA = genomeForTree(pA);
770
+ const gB = genomeForTree(pB);
771
+ let bestFitness = -Infinity;
772
+ let bestGenome = null;
773
+ let bestSp = null;
774
+ for (let c = 0; c < 4; c++) {
775
+ const cSeed = ((seed ^ (actionSeq * 977) ^ (p * 131) ^ (c * 59)) >>> 0) + 1;
776
+ const mut = mutateGenome(crossoverGenomes(gA, gB, { seed: cSeed }), {
777
+ rate: 0.2,
778
+ strength: 0.12,
779
+ seed: cSeed + 17,
780
+ });
781
+ const candSp = genomeToSpecies(mut, `cand_${c}`);
782
+ const fit = evalWildFitness(candSp, can.shelter, sub.exposure, sub.moisture);
783
+ if (fit > bestFitness) {
784
+ bestFitness = fit;
785
+ bestGenome = mut;
786
+ bestSp = candSp;
787
+ }
788
+ }
789
+ if (bestGenome && bestSp) {
790
+ wildSeq++;
791
+ const gen = Math.max(pA.generation, pB.generation) + 1;
792
+ const slotNum = ((wildSeq - 1) % MAX_WILD_CULTIVARS) + 1;
793
+ const namedSp = { ...bestSp, name: `Wild ${chosenArch} F${gen} #${slotNum}` };
794
+ const spIdx = registerWildCultivar(namedSp);
795
+ const sp = speciesList[spIdx];
796
+ const stages = lifeStageSizes(sp);
797
+ const st = useYoungStage ? stages[1] : stages[0];
798
+ const dna = encodeDna(bestGenome);
799
+ genomeCache.set(dna, bestGenome);
800
+ trees.push({
801
+ x: px,
802
+ y: sub.height,
803
+ z: pz,
804
+ speciesIndex: spIdx,
805
+ height: st.size.height,
806
+ crownRadius: st.size.crownRadius,
807
+ crownBase: st.size.crownBase,
808
+ trunkRadius: st.size.trunkRadius,
809
+ yaw: hash01(p * 59, seed + 839) * Math.PI * 2,
810
+ seed: Math.floor(hash01(p * 67, seed + 853) * 1_000_000),
811
+ ageYears: ageY,
812
+ coppiced: false,
813
+ dna,
814
+ generation: gen,
815
+ leanX: 0,
816
+ leanZ: 0,
817
+ collar: !useYoungStage,
818
+ });
819
+ return;
820
+ }
821
+ }
822
+ const spIdx = resolveTreeSpeciesIndex(fallbackSpeciesName);
823
+ const sp = speciesList[spIdx];
824
+ const stages = lifeStageSizes(sp);
825
+ const initSt = useYoungStage ? stages[1] : stages[0];
826
+ const rSeed = Math.floor(hash01(p * 67, seed + 853) * 1_000_000);
827
+ let dna = baseDnaCache[spIdx];
828
+ if (!dna) {
829
+ dna = encodeDna(speciesToGenome(sp, 101 + spIdx));
830
+ baseDnaCache[spIdx] = dna;
831
+ }
832
+ trees.push({
833
+ x: px,
834
+ y: sub.height,
835
+ z: pz,
836
+ speciesIndex: spIdx,
837
+ height: initSt.size.height,
838
+ crownRadius: initSt.size.crownRadius,
839
+ crownBase: initSt.size.crownBase,
840
+ trunkRadius: initSt.size.trunkRadius,
841
+ yaw: hash01(p * 59, seed + 839) * Math.PI * 2,
842
+ seed: rSeed,
843
+ ageYears: ageY,
844
+ coppiced: false,
845
+ dna,
846
+ generation: 1,
847
+ leanX: 0,
848
+ leanZ: 0,
849
+ collar: !useYoungStage || mantleSpecies.has(sp.name),
850
+ });
851
+ };
852
+ if (can.shelter < 0.34 && recruitedTrees < maxRecruitTrees && pioneerGuild) {
853
+ recruitFromParents(pioneerGuild.speciesName, years >= 15 ? 8 : 3, years >= 15);
854
+ recruitedTrees++;
855
+ addManualFloraCluster("foxglove", px, pz, 3, 2.4, seed + actionSeq * 307 + p);
856
+ }
857
+ else if (can.shelter > 0.56 && can.litter > 0.25) {
858
+ if (climaxGuild && recruitedTrees < maxRecruitTrees && hash01(p * 73, seed + 863) < 0.22) {
859
+ recruitFromParents(climaxGuild.speciesName, 3, false);
860
+ recruitedTrees++;
861
+ }
862
+ if (hash01(p * 97, seed + 887) < 0.45) {
863
+ const shadeId = can.mycorrhiza > 0.48 && hash01(p * 103, seed + 907) < 0.4 ? "chanterelle" : "ladyFern";
864
+ addManualFloraCluster(shadeId, px, pz, 2, 1.8, seed + actionSeq * 331 + p);
865
+ }
866
+ }
867
+ }
868
+ // Decay manual pioneer annuals slowly & fade >40yr nurse logs.
869
+ manualFlora = manualFlora.filter((mf) => !(mf.isDeadwood && year - mf.birthYear > 45));
870
+ recompute(true, true);
871
+ const maxGen = currentMaxGeneration();
872
+ const wildHyb = currentWildHybrids();
873
+ return emitResult({
874
+ ok: true,
875
+ action: "stepSuccession",
876
+ year,
877
+ note: `Year ${year} (+${years} yr): ${recruitedTrees} saplings recruited, ${solved.treeCount} trees, F${maxGen} (${wildHyb} wild hybrids), mean shelter ${(solved.meanShelter * 100).toFixed(1)}%.`,
878
+ changedTrees: true,
879
+ changedFlora: true,
880
+ treeCount: solved.treeCount,
881
+ floraCount: solved.floraCount,
882
+ meanShelter: solved.meanShelter,
883
+ maxGeneration: maxGen,
884
+ wildHybridCount: wildHyb,
885
+ });
886
+ },
887
+ exportSnapshot(recipeId) {
888
+ const cultivars = [];
889
+ for (let i = baseSpeciesCount; i < speciesList.length; i++) {
890
+ cultivars.push({ index: i, species: cloneSpecies(speciesList[i]) });
891
+ }
892
+ return {
893
+ version: 2,
894
+ ...(recipeId ? { recipeId } : {}),
895
+ year,
896
+ actionSeq,
897
+ seed,
898
+ foliageRetention,
899
+ cultivars,
900
+ trees: trees.map((t) => ({ ...t })),
901
+ manualFlora: manualFlora.map((mf) => ({ ...mf })),
902
+ mycoPatches: mycoPatches.map((mp) => ({ ...mp })),
903
+ };
904
+ },
905
+ inspectTree(editOpts) {
906
+ const idx = findNearestTreeIndex(editOpts.x, editOpts.z, editOpts.radius ?? 14, false);
907
+ if (idx < 0)
908
+ return null;
909
+ const rec = trees[idx];
910
+ const sp = speciesList[rec.speciesIndex] ?? speciesList[0];
911
+ const sub = sampleSubstrateCpu(baseSubstrate, rec.x, rec.z);
912
+ const can = sampleCanopyCpu(solved.canopy, rec.x, rec.z);
913
+ const fitness = evalWildFitness(sp, can.shelter, sub.exposure, sub.moisture);
914
+ return {
915
+ index: idx,
916
+ record: { ...rec },
917
+ species: cloneSpecies(sp),
918
+ fitness,
919
+ site: {
920
+ shelter: can.shelter,
921
+ moisture: sub.moisture,
922
+ soilPh: sub.soilPh,
923
+ exposure: sub.exposure,
924
+ },
925
+ };
926
+ },
927
+ importSnapshot(snapshot) {
928
+ if (!snapshot || typeof snapshot !== "object" || (snapshot.version !== 1 && snapshot.version !== 2) || !Array.isArray(snapshot.trees)) {
929
+ return failResult("importSnapshot", "Invalid BiomeSandboxSnapshot (expected version 1 or 2 with trees array).");
930
+ }
931
+ const nextSpecies = (opts.treeSpecies ?? ALL_SPECIES).map((s) => cloneSpecies(s));
932
+ const nextWildSlots = [];
933
+ if (Array.isArray(snapshot.cultivars)) {
934
+ const sorted = [...snapshot.cultivars].sort((a, b) => a.index - b.index);
935
+ for (const cv of sorted) {
936
+ const errs = checkSpecies(cv.species);
937
+ if (errs.length > 0) {
938
+ return failResult("importSnapshot", `Invalid cultivar "${cv.species?.name}": ${errs.join("; ")}`);
939
+ }
940
+ const clone = cloneSpecies(cv.species);
941
+ if (cv.index >= nextSpecies.length) {
942
+ nextSpecies[cv.index] = clone;
943
+ if (clone.name.startsWith("Wild "))
944
+ nextWildSlots.push(cv.index);
945
+ }
946
+ else if (cv.index >= baseSpeciesCount) {
947
+ nextSpecies[cv.index] = clone;
948
+ if (clone.name.startsWith("Wild "))
949
+ nextWildSlots.push(cv.index);
950
+ }
951
+ }
952
+ }
953
+ const nextTrees = [];
954
+ for (const raw of snapshot.trees) {
955
+ if (!Number.isFinite(raw.x) || !Number.isFinite(raw.z))
956
+ continue;
957
+ const spIdx = Math.max(0, Math.min(nextSpecies.length - 1, Math.round(raw.speciesIndex)));
958
+ const sp = nextSpecies[spIdx] ?? nextSpecies[0];
959
+ const tSeed = Number.isFinite(raw.seed) ? Math.round(raw.seed) : 101;
960
+ // Version 1 kept no lean or collar: take the initial solve's for a tree that stands where one of its trees stands.
961
+ const fromInitial = initialTreeAt.get(`${raw.x},${raw.z},${tSeed}`);
962
+ const leanX = Number.isFinite(raw.leanX) ? raw.leanX : fromInitial !== undefined ? initialSolved.treeLeans[fromInitial * 2] : 0;
963
+ const leanZ = Number.isFinite(raw.leanZ) ? raw.leanZ : fromInitial !== undefined ? initialSolved.treeLeans[fromInitial * 2 + 1] : 0;
964
+ const collar = typeof raw.collar === "boolean" ? raw.collar : fromInitial !== undefined && initialSolved.treeCollars[fromInitial] === 1;
965
+ nextTrees.push({
966
+ x: raw.x,
967
+ y: Number.isFinite(raw.y) ? raw.y : sampleSubstrateCpu(baseSubstrate, raw.x, raw.z).height,
968
+ z: raw.z,
969
+ speciesIndex: spIdx,
970
+ height: Number.isFinite(raw.height) ? raw.height : sp.height,
971
+ crownRadius: Number.isFinite(raw.crownRadius) ? raw.crownRadius : sp.crownRadius,
972
+ crownBase: Number.isFinite(raw.crownBase) ? raw.crownBase : sp.crownBase,
973
+ trunkRadius: Number.isFinite(raw.trunkRadius) ? raw.trunkRadius : sp.trunkRadius,
974
+ yaw: Number.isFinite(raw.yaw) ? raw.yaw : 0,
975
+ seed: tSeed,
976
+ ageYears: Number.isFinite(raw.ageYears) ? Math.max(1, Math.round(raw.ageYears)) : 10,
977
+ coppiced: Boolean(raw.coppiced),
978
+ dna: typeof raw.dna === "string" && raw.dna.startsWith("DNA1-") ? raw.dna : encodeDna(speciesToGenome(sp, tSeed)),
979
+ generation: Number.isFinite(raw.generation) ? Math.max(1, Math.round(raw.generation)) : 1,
980
+ leanX,
981
+ leanZ,
982
+ collar,
983
+ });
984
+ }
985
+ speciesList = nextSpecies;
986
+ wildSlotIndices.length = 0;
987
+ wildSlotIndices.push(...nextWildSlots);
988
+ wildSeq = nextWildSlots.length;
989
+ year = Math.max(0, Math.round(Number(snapshot.year) || 0));
990
+ actionSeq = Math.max(0, Math.round(Number(snapshot.actionSeq) || 0));
991
+ if (Number.isFinite(snapshot.foliageRetention))
992
+ foliageRetention = clamp01(snapshot.foliageRetention);
993
+ trees = nextTrees;
994
+ manualFlora = Array.isArray(snapshot.manualFlora) ? snapshot.manualFlora.map((mf) => ({ ...mf })) : [];
995
+ mycoPatches = Array.isArray(snapshot.mycoPatches) ? snapshot.mycoPatches.map((mp) => ({ ...mp })) : [];
996
+ recompute(true, true);
997
+ const maxGen = currentMaxGeneration();
998
+ const wildHyb = currentWildHybrids();
999
+ return emitResult({
1000
+ ok: true,
1001
+ action: "importSnapshot",
1002
+ year,
1003
+ note: `Imported snapshot (yr ${year}, ${solved.treeCount} trees, F${maxGen}, ${wildHyb} wild hybrids).`,
1004
+ changedTrees: true,
1005
+ changedFlora: true,
1006
+ treeCount: solved.treeCount,
1007
+ floraCount: solved.floraCount,
1008
+ meanShelter: solved.meanShelter,
1009
+ maxGeneration: maxGen,
1010
+ wildHybridCount: wildHyb,
1011
+ });
1012
+ },
1013
+ reset() {
1014
+ year = 0;
1015
+ actionSeq = 0;
1016
+ wildSeq = 0;
1017
+ wildSlotIndices.length = 0;
1018
+ speciesList = (opts.treeSpecies ?? ALL_SPECIES).map((s) => cloneSpecies(s));
1019
+ trees = parseTreeRecords(initialSolved.trees, speciesList, baseDnaCache, initialSolved.treeLeans, initialSolved.treeCollars);
1020
+ manualFlora = [];
1021
+ mycoPatches = [];
1022
+ solved = initialSolved;
1023
+ return emitResult({
1024
+ ok: true,
1025
+ action: "reset",
1026
+ year: 0,
1027
+ note: `Reset stand to Year 0 (${solved.treeCount} trees, ${solved.floraCount} flora).`,
1028
+ changedTrees: true,
1029
+ changedFlora: true,
1030
+ treeCount: solved.treeCount,
1031
+ floraCount: solved.floraCount,
1032
+ meanShelter: solved.meanShelter,
1033
+ maxGeneration: 1,
1034
+ wildHybridCount: 0,
1035
+ });
1036
+ },
1037
+ };
1038
+ }
1039
+ /** Apply one `SandboxCommand` to a sandbox. Unknown or incomplete commands do nothing and return `null`. */
1040
+ export function applySandboxCommand(sandbox, act) {
1041
+ switch (act.action) {
1042
+ case "plantTree":
1043
+ return sandbox.plantTree({ x: act.x ?? 0, z: act.z ?? 0, species: act.species, dna: act.dna, stage: act.stage });
1044
+ case "plantFlora":
1045
+ return act.speciesId ? sandbox.plantFlora({ x: act.x ?? 0, z: act.z ?? 0, speciesId: act.speciesId, count: act.count }) : null;
1046
+ case "inoculateMycorrhiza":
1047
+ return sandbox.inoculateMycorrhiza({ x: act.x ?? 0, z: act.z ?? 0, radius: act.radius });
1048
+ case "coppiceTree":
1049
+ return sandbox.coppiceTree({ x: act.x ?? 0, z: act.z ?? 0, radius: act.radius });
1050
+ case "fellTree":
1051
+ return sandbox.fellTree({ x: act.x ?? 0, z: act.z ?? 0, radius: act.radius });
1052
+ case "stepSuccession":
1053
+ return sandbox.stepSuccession(act.years ?? 5);
1054
+ case "reset":
1055
+ return sandbox.reset();
1056
+ default:
1057
+ return null;
1058
+ }
1059
+ }
1060
+ //# sourceMappingURL=sandbox.js.map