@casmo/tree.js 0.1.1 → 0.3.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.
- package/README.md +312 -16
- package/dist/apply-Cio2t7CZ.js +285 -0
- package/dist/apply-Cio2t7CZ.js.map +1 -0
- package/dist/bake/index.d.ts +44 -5
- package/dist/bake/index.d.ts.map +1 -1
- package/dist/definition/crown-shape.d.ts +9 -0
- package/dist/definition/crown-shape.d.ts.map +1 -0
- package/dist/definition/defaults.d.ts +15 -1
- package/dist/definition/defaults.d.ts.map +1 -1
- package/dist/definition/index.d.ts +4 -3
- package/dist/definition/index.d.ts.map +1 -1
- package/dist/definition/migrations.d.ts +0 -8
- package/dist/definition/migrations.d.ts.map +1 -1
- package/dist/definition/schema.d.ts.map +1 -1
- package/dist/definition/types.d.ts +181 -6
- package/dist/definition/types.d.ts.map +1 -1
- package/dist/effects/mask.d.ts +3 -3
- package/dist/effects/mask.d.ts.map +1 -1
- package/dist/effects.js +3 -3
- package/dist/effects.js.map +1 -1
- package/dist/forest/Forest.d.ts +37 -2
- package/dist/forest/Forest.d.ts.map +1 -1
- package/dist/forest/nodes.d.ts +6 -1
- package/dist/forest/nodes.d.ts.map +1 -1
- package/dist/{forest-OX9WvAwh.js → forest-ChEaWJrf.js} +1763 -684
- package/dist/forest-ChEaWJrf.js.map +1 -0
- package/dist/generator/branches.d.ts +2 -2
- package/dist/generator/branches.d.ts.map +1 -1
- package/dist/generator/crown.d.ts +28 -0
- package/dist/generator/crown.d.ts.map +1 -0
- package/dist/generator/fruit.d.ts +28 -0
- package/dist/generator/fruit.d.ts.map +1 -0
- package/dist/generator/growth.d.ts +1 -1
- package/dist/generator/growth.d.ts.map +1 -1
- package/dist/generator/index.d.ts +5 -4
- package/dist/generator/index.d.ts.map +1 -1
- package/dist/generator/leaf-shapes.d.ts +33 -1
- package/dist/generator/leaf-shapes.d.ts.map +1 -1
- package/dist/generator/mesh.d.ts +10 -2
- package/dist/generator/mesh.d.ts.map +1 -1
- package/dist/generator/occlusion.d.ts +8 -0
- package/dist/generator/occlusion.d.ts.map +1 -0
- package/dist/generator/roots.d.ts +16 -0
- package/dist/generator/roots.d.ts.map +1 -0
- package/dist/generator/trunk.d.ts +16 -2
- package/dist/generator/trunk.d.ts.map +1 -1
- package/dist/generator/types.d.ts +61 -6
- package/dist/generator/types.d.ts.map +1 -1
- package/dist/growth/index.d.ts +1 -1
- package/dist/growth/index.d.ts.map +1 -1
- package/dist/growth/tsl.d.ts +2 -0
- package/dist/growth/tsl.d.ts.map +1 -1
- package/dist/index.d.ts +6 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +274 -24
- package/dist/index.js.map +1 -1
- package/dist/materials/crown-nodes.d.ts +20 -0
- package/dist/materials/crown-nodes.d.ts.map +1 -0
- package/dist/materials/crown-normals.d.ts +17 -0
- package/dist/materials/crown-normals.d.ts.map +1 -0
- package/dist/materials/ground-tint.d.ts +13 -0
- package/dist/materials/ground-tint.d.ts.map +1 -0
- package/dist/materials/index.d.ts +13 -1
- package/dist/materials/index.d.ts.map +1 -1
- package/dist/materials/leaf-translucency-model.d.ts +14 -0
- package/dist/materials/leaf-translucency-model.d.ts.map +1 -0
- package/dist/materials/leaf-translucency.d.ts +73 -0
- package/dist/materials/leaf-translucency.d.ts.map +1 -0
- package/dist/materials/material-features.d.ts +43 -0
- package/dist/materials/material-features.d.ts.map +1 -0
- package/dist/materials/occlusion.d.ts +10 -0
- package/dist/materials/occlusion.d.ts.map +1 -0
- package/dist/materials/toon.d.ts +18 -1
- package/dist/materials/toon.d.ts.map +1 -1
- package/dist/names-BE9he6CS.js +713 -0
- package/dist/names-BE9he6CS.js.map +1 -0
- package/dist/react/Tree.d.ts +5 -2
- package/dist/react/Tree.d.ts.map +1 -1
- package/dist/react.js +10 -6
- package/dist/react.js.map +1 -1
- package/dist/season/nodes.d.ts +16 -0
- package/dist/season/nodes.d.ts.map +1 -1
- package/dist/season/profile.d.ts +26 -0
- package/dist/season/profile.d.ts.map +1 -1
- package/dist/species/almond.js +223 -0
- package/dist/species/almond.js.map +1 -0
- package/dist/species/almond.json +210 -0
- package/dist/species/apple.js +230 -0
- package/dist/species/apple.js.map +1 -0
- package/dist/species/apple.json +220 -0
- package/dist/species/ash.js +187 -0
- package/dist/species/ash.js.map +1 -0
- package/dist/species/ash.json +177 -0
- package/dist/species/beech.js +174 -0
- package/dist/species/beech.js.map +1 -0
- package/dist/species/beech.json +167 -0
- package/dist/species/birch.js +170 -0
- package/dist/species/birch.js.map +1 -0
- package/dist/species/birch.json +163 -0
- package/dist/species/catalog.d.ts +61 -0
- package/dist/species/catalog.d.ts.map +1 -0
- package/dist/species/cedar.js +169 -0
- package/dist/species/cedar.js.map +1 -0
- package/dist/species/cedar.json +168 -0
- package/dist/species/cherry.js +237 -0
- package/dist/species/cherry.js.map +1 -0
- package/dist/species/cherry.json +224 -0
- package/dist/species/chestnut.js +230 -0
- package/dist/species/chestnut.js.map +1 -0
- package/dist/species/chestnut.json +220 -0
- package/dist/species/douglas-fir.js +174 -0
- package/dist/species/douglas-fir.js.map +1 -0
- package/dist/species/douglas-fir.json +170 -0
- package/dist/species/elm.js +173 -0
- package/dist/species/elm.js.map +1 -0
- package/dist/species/elm.json +163 -0
- package/dist/species/hemlock.js +175 -0
- package/dist/species/hemlock.js.map +1 -0
- package/dist/species/hemlock.json +171 -0
- package/dist/species/hickory.js +200 -0
- package/dist/species/hickory.js.map +1 -0
- package/dist/species/hickory.json +192 -0
- package/dist/species/index.d.ts +10 -0
- package/dist/species/index.d.ts.map +1 -0
- package/dist/species/juniper.js +158 -0
- package/dist/species/juniper.js.map +1 -0
- package/dist/species/juniper.json +154 -0
- package/dist/species/loaders.d.ts +7 -0
- package/dist/species/loaders.d.ts.map +1 -0
- package/dist/species/mahogany.js +201 -0
- package/dist/species/mahogany.js.map +1 -0
- package/dist/species/mahogany.json +196 -0
- package/dist/species/maple.js +177 -0
- package/dist/species/maple.js.map +1 -0
- package/dist/species/maple.json +171 -0
- package/dist/species/oak.js +220 -0
- package/dist/species/oak.js.map +1 -0
- package/dist/species/oak.json +212 -0
- package/dist/species/olive.js +189 -0
- package/dist/species/olive.js.map +1 -0
- package/dist/species/olive.json +181 -0
- package/dist/species/peach.js +223 -0
- package/dist/species/peach.js.map +1 -0
- package/dist/species/peach.json +210 -0
- package/dist/species/pear.js +213 -0
- package/dist/species/pear.js.map +1 -0
- package/dist/species/pear.json +200 -0
- package/dist/species/pine.js +163 -0
- package/dist/species/pine.js.map +1 -0
- package/dist/species/pine.json +162 -0
- package/dist/species/plum.js +237 -0
- package/dist/species/plum.js.map +1 -0
- package/dist/species/plum.json +224 -0
- package/dist/species/red-oak.js +220 -0
- package/dist/species/red-oak.js.map +1 -0
- package/dist/species/red-oak.json +212 -0
- package/dist/species/redwood.js +174 -0
- package/dist/species/redwood.js.map +1 -0
- package/dist/species/redwood.json +170 -0
- package/dist/species/sequoia.js +167 -0
- package/dist/species/sequoia.js.map +1 -0
- package/dist/species/sequoia.json +166 -0
- package/dist/species/spruce.js +170 -0
- package/dist/species/spruce.js.map +1 -0
- package/dist/species/spruce.json +166 -0
- package/dist/species/teak.js +166 -0
- package/dist/species/teak.js.map +1 -0
- package/dist/species/teak.json +157 -0
- package/dist/species/types.d.ts +65 -0
- package/dist/species/types.d.ts.map +1 -0
- package/dist/species/walnut.js +220 -0
- package/dist/species/walnut.js.map +1 -0
- package/dist/species/walnut.json +212 -0
- package/dist/species/white-oak.js +213 -0
- package/dist/species/white-oak.js.map +1 -0
- package/dist/species/white-oak.json +208 -0
- package/dist/species.js +160 -0
- package/dist/species.js.map +1 -0
- package/dist/styles/apply.d.ts +12 -0
- package/dist/styles/apply.d.ts.map +1 -0
- package/dist/styles/low-poly/index.d.ts +1 -1
- package/dist/styles/low-poly/index.d.ts.map +1 -1
- package/dist/styles/low-poly.js +13 -10
- package/dist/styles/low-poly.js.map +1 -1
- package/dist/styles/material-features.d.ts +27 -0
- package/dist/styles/material-features.d.ts.map +1 -0
- package/dist/styles/names.d.ts +28 -0
- package/dist/styles/names.d.ts.map +1 -0
- package/dist/styles/realistic/index.d.ts +3 -8
- package/dist/styles/realistic/index.d.ts.map +1 -1
- package/dist/styles/realistic/textures.d.ts +20 -0
- package/dist/styles/realistic/textures.d.ts.map +1 -0
- package/dist/styles/realistic.js +14 -18
- package/dist/styles/realistic.js.map +1 -1
- package/dist/styles/registry.d.ts +2 -13
- package/dist/styles/registry.d.ts.map +1 -1
- package/dist/styles/stylized/index.d.ts +1 -1
- package/dist/styles/stylized/index.d.ts.map +1 -1
- package/dist/styles/stylized.js +13 -10
- package/dist/styles/stylized.js.map +1 -1
- package/dist/styles/types.d.ts +16 -2
- package/dist/styles/types.d.ts.map +1 -1
- package/dist/textures/realistic/bark-fibrous-normal.png +0 -0
- package/dist/textures/realistic/bark-fibrous.png +0 -0
- package/dist/textures/realistic/bark-papery-normal.png +0 -0
- package/dist/textures/realistic/bark-papery.png +0 -0
- package/dist/textures/realistic/bark-plated-normal.png +0 -0
- package/dist/textures/realistic/bark-plated.png +0 -0
- package/dist/textures/realistic/bark-smooth-normal.png +0 -0
- package/dist/textures/realistic/bark-smooth.png +0 -0
- package/dist/textures/realistic/leaf-compound.png +0 -0
- package/dist/textures/realistic/leaf-lobed.png +0 -0
- package/dist/textures/realistic/leaf-palmate.png +0 -0
- package/dist/textures/realistic/scale.png +0 -0
- package/dist/tree/Tree.d.ts +34 -5
- package/dist/tree/Tree.d.ts.map +1 -1
- package/package.json +9 -2
- package/dist/forest-OX9WvAwh.js.map +0 -1
- package/dist/types-BZjHhNz7.js +0 -20
- package/dist/types-BZjHhNz7.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"forest-ChEaWJrf.js","names":["sin","dot","cross","length","normalize","normalize","dot","cross","length","DEG","sin","normalize","normalize","sin","cross","dot","DEG","sin","normalize","length","cross","dot","DEG","sin","normalize","cross","dot","DEG","sin","cross","dot","sin","normalize","length","sin","sin","thickness","partProgress","shiftedSeason"],"sources":["../src/random/index.ts","../src/math/index.ts","../src/season/profile.ts","../src/generator/vec.ts","../src/generator/frames.ts","../src/generator/branches.ts","../src/generator/crown.ts","../src/generator/wind.ts","../src/generator/attributes.ts","../src/generator/leaf-shapes.ts","../src/generator/fruit.ts","../src/generator/growth.ts","../src/generator/leaves.ts","../src/generator/trunk.ts","../src/generator/mesh.ts","../src/generator/occlusion.ts","../src/generator/roots.ts","../src/generator/sculpt.ts","../src/generator/index.ts","../src/growth/evaluate.ts","../src/growth/tsl.ts","../src/materials/ground-tint.ts","../src/textures/index.ts","../src/materials/maps.ts","../src/materials/crown-nodes.ts","../src/materials/leaf-translucency.ts","../src/materials/toon.ts","../src/materials/shading.ts","../src/materials/crown-normals.ts","../src/materials/index.ts","../src/materials/leaf-translucency-model.ts","../src/materials/occlusion.ts","../src/materials/material-features.ts","../src/renderer/index.ts","../src/season/nodes.ts","../src/season/check.ts","../src/wind/Wind.ts","../src/wind/response.ts","../src/wind/node.ts","../src/tree/Tree.ts","../src/tree/index.ts","../src/styles/registry.ts","../src/forest/nodes.ts","../src/forest/placement.ts","../src/forest/Forest.ts","../src/forest/index.ts"],"sourcesContent":["/**\n * Random: the only source of randomness in tree.js.\n *\n * Determinism contract: the same Seed gives the same numbers on every machine\n * and across releases within a major version. `Math.random` is never used\n * (enforced by ESLint). Everything here is plain 32-bit integer math.\n */\n\nconst FNV_OFFSET = 0x811c9dc5;\nconst FNV_PRIME = 0x01000193;\n\n/** FNV-1a 32-bit hash of a string (UTF-16 code units, low byte then high byte). */\nexport function hashString(input: string): number {\n let h = FNV_OFFSET;\n for (let i = 0; i < input.length; i++) {\n const c = input.charCodeAt(i);\n h ^= c & 0xff;\n h = Math.imul(h, FNV_PRIME);\n if (c > 0xff) {\n h ^= c >>> 8;\n h = Math.imul(h, FNV_PRIME);\n }\n }\n return h >>> 0;\n}\n\n/** FNV-1a 32-bit hash over raw bytes; `h` continues a previous hash. */\nexport function hashBytes(bytes: Uint8Array, h: number = FNV_OFFSET): number {\n for (let i = 0; i < bytes.length; i++) {\n h ^= bytes[i]!;\n h = Math.imul(h, FNV_PRIME);\n }\n return h >>> 0;\n}\n\n/** Mixes any number of 32-bit values into one well-distributed 32-bit hash. */\nexport function hashCombine(...values: number[]): number {\n let h = FNV_OFFSET;\n for (const v of values) {\n h = Math.imul(h ^ (v >>> 0), FNV_PRIME);\n h = fmix32(h);\n }\n return h >>> 0;\n}\n\n/** Converts any finite number (including fractions and negatives) to a 32-bit seed. */\nexport function seedToUint32(seed: number): number {\n if (!Number.isFinite(seed)) throw new TypeError(`Seed must be a finite number, got ${seed}`);\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, seed, true);\n return hashCombine(view.getUint32(0, true), view.getUint32(4, true));\n}\n\nfunction fmix32(h: number): number {\n h ^= h >>> 16;\n h = Math.imul(h, 0x85ebca6b);\n h ^= h >>> 13;\n h = Math.imul(h, 0xc2b2ae35);\n h ^= h >>> 16;\n return h >>> 0;\n}\n\nexport interface Random {\n /** Uniform float in [0, 1). */\n next(): number;\n /** Uniform float in [min, max). */\n range(min: number, max: number): number;\n /** Uniform integer in [min, max] (inclusive). */\n int(min: number, max: number): number;\n /**\n * An independent stream derived from this stream's seed and `key`.\n * It does not depend on how many numbers this stream has produced, so\n * adding a draw in one part of the generator never shifts another part.\n */\n fork(key: string | number): Random;\n}\n\n/** Seeded PRNG (mulberry32). */\nexport function createRandom(seed: number): Random {\n return fromState(seedToUint32(seed));\n}\n\nfunction fromState(origin: number): Random {\n let state = origin;\n const next = (): number => {\n state = (state + 0x6d2b79f5) >>> 0;\n let t = state;\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n return {\n next,\n range: (min, max) => min + (max - min) * next(),\n int: (min, max) => min + Math.floor(next() * (max - min + 1)),\n fork: (key) =>\n fromState(hashCombine(origin, typeof key === 'number' ? seedToUint32(key) : hashString(key))),\n };\n}\n\n/**\n * A stable 0..1 (exclusive) number from a Seed and a key (a branch path, leaf id, purpose...).\n * It makes no stream draws (ADR 0003), so it never shifts or is shifted by other random numbers.\n */\nexport function seedRandom(seed: number, key: string): number {\n return hashCombine(seedToUint32(seed), hashString(key)) / 4294967296;\n}\n","/**\n * Deterministic maths: the same bits on every machine and JavaScript engine.\n *\n * ECMAScript leaves `Math.sin`, `Math.cos`, `Math.exp`, `Math.log`, `Math.pow`, `Math.hypot`, `**`\n * and friends \"implementation-approximated\", so engines (and engine versions) may differ in the\n * last bit, which would change a Seed's tree. Everything here is built from `+ - * /`,\n * `Math.sqrt`, `Math.round`/`Math.floor` and exact bit manipulation, which IEEE 754 and the spec\n * pin down exactly. The algorithms are those of fdlibm (sun.com, 1993), accurate to about 1 ulp.\n * ESLint forbids the platform functions in the code that feeds generated geometry and hashes.\n */\n\nconst bits = new DataView(new ArrayBuffer(8));\n\n/** 2^k as an exact double, for -1022 <= k <= 1023. */\nfunction powerOfTwo(k: number): number {\n bits.setUint32(0, (k + 1023) << 20);\n bits.setUint32(4, 0);\n return bits.getFloat64(0);\n}\n\n// π/2 split into parts with trailing zero bits, so `n * part` is exact (Cody & Waite).\nconst PIO2_1 = 1.5707963267341256e0; // first 33 bits of π/2\nconst PIO2_2 = 6.077100506303966e-11; // next 33 bits\nconst PIO2_3 = 2.0222662487111665e-21; // the rest\nconst INV_PIO2 = 6.366197723675814e-1;\n\nconst S1 = -1.66666666666666324348e-1;\nconst S2 = 8.33333333332248946124e-3;\nconst S3 = -1.98412698298579493134e-4;\nconst S4 = 2.75573137070700676789e-6;\nconst S5 = -2.50507602534068634195e-8;\nconst S6 = 1.58969099521155010221e-10;\n\nconst C1 = 4.16666666666666019037e-2;\nconst C2 = -1.38888888888741095749e-3;\nconst C3 = 2.48015872894767294178e-5;\nconst C4 = -2.75573143513906633035e-7;\nconst C5 = 2.08757232129817482790e-9;\nconst C6 = -1.13596475577881948265e-11;\n\n/** sin on |x| <= π/4. */\nfunction kernelSin(x: number): number {\n const z = x * x;\n const r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6)));\n return x + z * x * (S1 + z * r);\n}\n\n/** cos on |x| <= π/4. */\nfunction kernelCos(x: number): number {\n const z = x * x;\n const r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6)))));\n const hz = 0.5 * z;\n const w = 1 - hz;\n return w + (1 - w - hz + z * r);\n}\n\n/** `x` reduced to |r| <= ~π/4, and the quadrant (0..3) it came from. Accurate for |x| < 2^20 · π/2. */\nfunction reduce(x: number): [r: number, quadrant: number] {\n if (Math.abs(x) <= Math.PI / 4) return [x, 0];\n const n = Math.round(x * INV_PIO2);\n const r = x - n * PIO2_1 - n * PIO2_2 - n * PIO2_3;\n return [r, ((n % 4) + 4) % 4];\n}\n\n/** Deterministic `Math.sin`. */\nexport function sin(x: number): number {\n if (!Number.isFinite(x)) return Number.NaN;\n if (x === 0) return x; // keeps -0\n const [r, q] = reduce(x);\n return q === 0 ? kernelSin(r) : q === 1 ? kernelCos(r) : q === 2 ? -kernelSin(r) : -kernelCos(r);\n}\n\n/** Deterministic `Math.cos`. */\nexport function cos(x: number): number {\n if (!Number.isFinite(x)) return Number.NaN;\n const [r, q] = reduce(x);\n return q === 0 ? kernelCos(r) : q === 1 ? -kernelSin(r) : q === 2 ? -kernelCos(r) : kernelSin(r);\n}\n\nconst LN2_HI = 6.93147180369123816490e-1;\nconst LN2_LO = 1.90821492927058770002e-10;\nconst INV_LN2 = 1.44269504088896338700e0;\nconst P1 = 1.66666666666666019037e-1;\nconst P2 = -2.77777777770155933842e-3;\nconst P3 = 6.61375632143793436117e-5;\nconst P4 = -1.65339022054652515390e-6;\nconst P5 = 4.13813679705723846039e-8;\n\n/** Deterministic `Math.exp`. */\nexport function exp(x: number): number {\n if (Number.isNaN(x)) return Number.NaN;\n if (x > 709.782712893384) return Number.POSITIVE_INFINITY;\n if (x < -745.1332191019411) return 0;\n if (x === 0) return 1;\n const k = Math.round(x * INV_LN2);\n const hi = x - k * LN2_HI;\n const lo = k * LN2_LO;\n const r = hi - lo;\n const t = r * r;\n const c = r - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5))));\n const y = 1 - (lo - (r * c) / (2 - c) - hi);\n if (k >= -1021) return k === 1024 ? y * 2 * powerOfTwo(1023) : y * powerOfTwo(k);\n return y * powerOfTwo(k + 1000) * powerOfTwo(-1000); // subnormal result\n}\n\nconst LG1 = 6.666666666666735130e-1;\nconst LG2 = 3.999999999940941908e-1;\nconst LG3 = 2.857142874366239149e-1;\nconst LG4 = 2.222219843214978396e-1;\nconst LG5 = 1.818357216161805012e-1;\nconst LG6 = 1.531383769920937332e-1;\nconst LG7 = 1.479819860511658591e-1;\nconst TWO54 = 18014398509481984;\n\n/** Deterministic `Math.log` (natural logarithm). */\nexport function log(x: number): number {\n if (Number.isNaN(x) || x < 0) return Number.NaN;\n if (x === 0) return Number.NEGATIVE_INFINITY;\n if (x === Number.POSITIVE_INFINITY) return x;\n let k = 0;\n if (x < 2.2250738585072014e-308) {\n x *= TWO54; // subnormal: scale up so the exponent bits are meaningful\n k = -54;\n }\n bits.setFloat64(0, x);\n let high = bits.getUint32(0);\n k += (high >>> 20) - 1023;\n high &= 0x000fffff;\n // Normalise the mantissa m into [√2/2, √2): x = 2^k · m.\n const i = (high + 0x95f64) & 0x100000;\n bits.setUint32(0, high | (i ^ 0x3ff00000));\n k += i >>> 20;\n const f = bits.getFloat64(0) - 1;\n const s = f / (2 + f);\n const z = s * s;\n const w = z * z;\n const r = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7))) + w * (LG2 + w * (LG4 + w * LG6));\n const hfsq = 0.5 * f * f;\n return k * LN2_HI - (hfsq - (s * (hfsq + r) + k * LN2_LO) - f);\n}\n\n/** Deterministic `Math.pow` (`x ** y`), for the finite values the library uses. */\nexport function pow(x: number, y: number): number {\n if (y === 0) return 1;\n if (Number.isNaN(x) || Number.isNaN(y)) return Number.NaN;\n if (x === 1) return 1;\n if (x === 0) return y > 0 ? 0 : Number.POSITIVE_INFINITY;\n if (x < 0) {\n if (!Number.isInteger(y)) return Number.NaN;\n const p = exp(y * log(-x));\n return y % 2 === 0 ? p : -p;\n }\n return exp(y * log(x));\n}\n\n/** Deterministic `Math.hypot` of a 3-vector. */\nexport function hypot3(x: number, y: number, z: number): number {\n return Math.sqrt(x * x + y * y + z * z);\n}\n","import type { HexColor, Keyframe, SeasonProfileDefinition, VariationDefinition } from '../definition';\nimport { DEFAULT_FRUIT_AMOUNT, DEFAULT_FRUIT_COLOR } from '../definition/defaults';\nimport { seedRandom } from '../random';\nimport { pow } from '../math';\n\n/**\n * Pure JS evaluator of the Season Profile: the CPU twin of the TSL nodes in `./nodes.ts`.\n * No three.js, Node-safe. The Baked Tree export uses it to bake Season into geometry and\n * colours; the shader evaluates exactly the same maths per leaf.\n */\n\n/** Linear RGB, 0..1 per channel. */\nexport type RGB = [number, number, number];\n\n/** Smallest keyframe span used as a divisor (two keys at the same `t` make a step). */\nexport const KEYFRAME_EPSILON = 1e-5;\n\n/** Interpolation weight of the segment `t0..t1` at `s` (0 before, 1 after). */\nexport function segmentWeight(s: number, t0: number, t1: number): number {\n return Math.min(Math.max((s - t0) / Math.max(t1 - t0, KEYFRAME_EPSILON), 0), 1);\n}\n\nfunction mixValue<V extends number | number[]>(a: V, b: V, f: number): V {\n if (typeof a === 'number') return (a + ((b as number) - a) * f) as V;\n return a.map((x, i) => x + ((b as number[])[i]! - x) * f) as V;\n}\n\n/**\n * Samples a keyframe track at Season `s`: linear between keys, holding the first value\n * before the first key and the last value after the last one. Computed as a chain of\n * mixes (one per segment), the same chain the shader runs.\n */\nexport function sampleTrack<V extends number | number[]>(track: readonly Keyframe<V>[], s: number): V {\n let out = track[0]!.value;\n for (let i = 0; i < track.length - 1; i++) {\n out = mixValue(out, track[i + 1]!.value, segmentWeight(s, track[i]!.t, track[i + 1]!.t));\n }\n return out;\n}\n\n/** Brings any Season into 0..1: values inside 0..1 (including 1, the last day of winter) are kept, others wrap around the year. */\nexport function wrapSeason(s: number): number {\n return s >= 0 && s <= 1 ? s : s - Math.floor(s);\n}\n\n/** sRGB transfer curve -> linear, per channel (as three.js `SRGBToLinear`). */\nexport function srgbToLinear(c: number): number {\n return c < 0.04045 ? c * 0.0773993808 : pow(c * 0.9478672986 + 0.0521327014, 2.4);\n}\n\n/** `#rrggbb` -> linear RGB. */\nexport function hexToLinear(hex: HexColor): RGB {\n const n = parseInt(hex.slice(1), 16);\n return [srgbToLinear(((n >> 16) & 255) / 255), srgbToLinear(((n >> 8) & 255) / 255), srgbToLinear((n & 255) / 255)];\n}\n\n/** The Season Profile's values at one Season. Colours are linear RGB. */\nexport interface SeasonState {\n /** The Season the tracks were sampled at (after shift and wrap). */\n season: number;\n leafColor: RGB;\n /** 0 = bare .. 1 = full. */\n leafCoverage: number;\n /** 0 = none .. 1 = full bloom. */\n blossom: number;\n blossomColor: RGB;\n /** Fruit amount: 0 = none .. 1 = all Fruit at full size (1 without a `fruit` track). */\n fruit: number;\n /** Fruit colour (the default red without a `fruitColor` track). */\n fruitColor: RGB;\n}\n\n/** A Season Profile's Fruit tracks, with the defaults for absent ones. */\nexport function fruitTracks(profile: SeasonProfileDefinition): { fruit: Keyframe<number>[]; fruitColor: Keyframe<HexColor>[] } {\n return { fruit: profile.fruit ?? DEFAULT_FRUIT_AMOUNT, fruitColor: profile.fruitColor ?? DEFAULT_FRUIT_COLOR };\n}\n\n/**\n * Evaluates the Season Profile at `season`, shifted by `shift` (a Seed's timing offset,\n * see {@link seasonShift}) and wrapped around the year.\n */\nexport function evaluateSeason(profile: SeasonProfileDefinition, season: number, shift = 0): SeasonState {\n const s = wrapSeason(season + shift);\n return {\n season: s,\n leafColor: sampleTrack(\n profile.leafColor.map((k) => ({ t: k.t, value: hexToLinear(k.value) })),\n s,\n ),\n leafCoverage: sampleTrack(profile.leafCoverage, s),\n blossom: sampleTrack(profile.blossom, s),\n blossomColor: hexToLinear(profile.blossomColor),\n fruit: sampleTrack(fruitTracks(profile).fruit, s),\n fruitColor: sampleTrack(\n fruitTracks(profile).fruitColor.map((k) => ({ t: k.t, value: hexToLinear(k.value) })),\n s,\n ),\n };\n}\n\n/**\n * One part's Season timing: the `aSeason` vertex attribute (vec3: x, y, z) with names.\n * Wood has the tree's shift and zero ranks.\n */\nexport interface PartSeason {\n /** Timing shift (Season units) from the Seed: tree shift + per-leaf jitter, within ± `variation.season`. */\n shift: number;\n /** 0..1: the leaf shows while leaf coverage > this. */\n coverageRank: number;\n /** 0..1: the leaf is a blossom while blossom > this. */\n blossomRank: number;\n}\n\n/** The {@link PartSeason} of vertex `vertex` in `aSeason` attribute data (3 floats per vertex). */\nexport function partSeasonAt(aSeason: ArrayLike<number>, vertex: number): PartSeason {\n return { shift: aSeason[vertex * 3]!, coverageRank: aSeason[vertex * 3 + 1]!, blossomRank: aSeason[vertex * 3 + 2]! };\n}\n\n/**\n * A Seed's Season timing shift for the whole tree: within ± half of `variation.season`.\n * Per-leaf jitter ({@link leafSeasonAttribute}) takes the other half, so a leaf stays within the range.\n */\nexport function seasonShift(seed: number, variation: Pick<VariationDefinition, 'season'>): number {\n return (seedRandom(seed, 'season') * 2 - 1) * (variation.season / 2);\n}\n\n/** The Season timing (`aSeason` attribute) of one leaf; see {@link PartSeason}. */\nexport function leafSeasonAttribute(\n seed: number,\n variation: Pick<VariationDefinition, 'season'>,\n leafId: string,\n): PartSeason {\n const jitter = (seedRandom(seed, `${leafId}#season`) * 2 - 1) * (variation.season / 2);\n return {\n shift: seasonShift(seed, variation) + jitter,\n coverageRank: seedRandom(seed, `${leafId}#coverage`),\n blossomRank: seedRandom(seed, `${leafId}#blossom`),\n };\n}\n\n/** The Season timing (`aSeason` attribute) of one Fruit: like a leaf's, with the Fruit's rank as `coverageRank`. */\nexport function fruitSeasonAttribute(\n seed: number,\n variation: Pick<VariationDefinition, 'season'>,\n fruitId: string,\n): PartSeason {\n const jitter = (seedRandom(seed, `fruit/${fruitId}#season`) * 2 - 1) * (variation.season / 2);\n return { shift: seasonShift(seed, variation) + jitter, coverageRank: seedRandom(seed, `fruit/${fruitId}#rank`), blossomRank: 0 };\n}\n\n/** `aSeason` for wood vertices: the tree's timing shift, no ranks. */\nexport function woodSeasonAttribute(seed: number, variation: Pick<VariationDefinition, 'season'>): PartSeason {\n return { shift: seasonShift(seed, variation), coverageRank: 0, blossomRank: 0 };\n}\n\n/** One leaf at one Season. */\nexport interface LeafSeasonState {\n /** False when the leaf has fallen (or not yet grown) and is not a blossom. */\n visible: boolean;\n /** True when the leaf shows as a blossom. */\n blossom: boolean;\n /** Linear RGB before the Seed's per-leaf tint (vertex colour) is multiplied in. */\n color: RGB;\n}\n\n/**\n * Evaluates one leaf from its Season timing (`aSeason` attribute, see {@link partSeasonAt}): the\n * exact CPU twin of the leaf shader (see `createSeasonNodes`). Use it to bake a tree at a Season.\n */\nexport function leafSeason(profile: SeasonProfileDefinition, season: number, part: PartSeason): LeafSeasonState {\n const state = evaluateSeason(profile, season, part.shift);\n const blossom = state.blossom > part.blossomRank;\n return {\n visible: blossom || state.leafCoverage > part.coverageRank,\n blossom,\n color: blossom ? state.blossomColor : state.leafColor,\n };\n}\n\n/** One Fruit at one Season. */\nexport interface FruitSeasonState {\n /** False when the Fruit has not set yet or has dropped (the Fruit amount is not above its rank). */\n visible: boolean;\n /** Size of the Fruit relative to full size (0 when not visible): it swells with the Fruit amount. */\n scale: number;\n /** Linear RGB before the Seed's per-Fruit tint (vertex colour) is multiplied in. */\n color: RGB;\n}\n\n/**\n * Evaluates one Fruit from its Season timing (`aSeason` of the fruit mesh: shift, the Fruit's\n * rank as `coverageRank`): the exact CPU twin of the Fruit shader (see `createFruitSeasonNodes`).\n * A Fruit shows while the Fruit amount is above its rank, scaled about its attachment point by the amount.\n */\nexport function fruitSeason(profile: SeasonProfileDefinition, season: number, part: PartSeason): FruitSeasonState {\n const state = evaluateSeason(profile, season, part.shift);\n const visible = state.fruit > part.coverageRank;\n return { visible, scale: visible ? state.fruit : 0, color: state.fruitColor };\n}\n","import { hypot3 } from '../math';\nimport type { Vec3 } from './types';\n\nexport const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];\nexport const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];\nexport const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s];\nexport const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\nexport const cross = (a: Vec3, b: Vec3): Vec3 => [\n a[1] * b[2] - a[2] * b[1],\n a[2] * b[0] - a[0] * b[2],\n a[0] * b[1] - a[1] * b[0],\n];\nexport const length = (a: Vec3): number => hypot3(a[0], a[1], a[2]);\nexport function normalize(a: Vec3): Vec3 {\n const l = length(a);\n return l > 1e-12 ? scale(a, 1 / l) : [0, 1, 0];\n}\nexport const lerp = (a: Vec3, b: Vec3, t: number): Vec3 => [\n a[0] + (b[0] - a[0]) * t,\n a[1] + (b[1] - a[1]) * t,\n a[2] + (b[2] - a[2]) * t,\n];\n/** Any unit vector perpendicular to the unit vector `v`. */\nexport function perpendicular(v: Vec3): Vec3 {\n const helper: Vec3 = Math.abs(v[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];\n return normalize(cross(helper, v));\n}\n","import type { SkeletonBranch, Vec3 } from './types';\nimport { add, cross, dot, length, lerp, normalize, perpendicular, scale, sub } from './vec';\n\n/** An orthonormal frame on a branch's centre line: `tangent` along the branch, `normal`/`binormal` across it. */\nexport interface Frame {\n tangent: Vec3;\n normal: Vec3;\n binormal: Vec3;\n}\n\n/**\n * Parallel-transport frames, one per skeleton point: the cross-section does not twist\n * as the branch bends, so swept rings stay even for branches in any direction.\n */\nexport function branchFrames(branch: SkeletonBranch): Frame[] {\n const pts = branch.points.map((p) => p.position);\n const n = pts.length;\n const segment = (i: number): Vec3 => normalize(sub(pts[Math.min(i + 1, n - 1)]!, pts[Math.min(i, n - 2)]!));\n const frames: Frame[] = [];\n for (let i = 0; i < n; i++) {\n // The trunk stands flat on the ground: its base ring is horizontal.\n const tangent: Vec3 =\n i === 0 && branch.parent === null\n ? [0, 1, 0]\n : i === 0 || i === n - 1\n ? segment(Math.min(i, n - 2))\n : normalize(add(segment(i - 1), segment(i)));\n let normal: Vec3;\n if (i === 0) {\n normal = perpendicular(tangent);\n } else {\n const previous = frames[i - 1]!.normal;\n normal = normalize(sub(previous, scale(tangent, dot(previous, tangent))));\n }\n frames.push({ tangent, normal, binormal: cross(tangent, normal) });\n }\n return frames;\n}\n\n/** Total length of a branch's centre line. */\nexport function pathLength(branch: SkeletonBranch): number {\n let total = 0;\n for (let i = 1; i < branch.points.length; i++) {\n total += length(sub(branch.points[i]!.position, branch.points[i - 1]!.position));\n }\n return total;\n}\n\nexport interface BranchSample extends Frame {\n position: Vec3;\n radius: number;\n}\n\n/** The point, frame and radius at fraction `t` (0..1) of a branch's length. */\nexport function sampleBranch(branch: SkeletonBranch, frames: Frame[], t: number): BranchSample {\n const pts = branch.points;\n const target = Math.min(Math.max(t, 0), 1) * pathLength(branch);\n let walked = 0;\n for (let i = 1; i < pts.length; i++) {\n const a = pts[i - 1]!;\n const b = pts[i]!;\n const segment = length(sub(b.position, a.position));\n if (walked + segment >= target || i === pts.length - 1) {\n const f = segment > 0 ? Math.min(Math.max((target - walked) / segment, 0), 1) : 0;\n // The direction of the centre-line segment itself, so children leave at exactly their declared angle.\n const tangent = normalize(sub(b.position, a.position));\n const normal = normalize(sub(frames[i - 1]!.normal, scale(tangent, dot(frames[i - 1]!.normal, tangent))));\n return {\n position: lerp(a.position, b.position, f),\n radius: a.radius + (b.radius - a.radius) * f,\n tangent,\n normal,\n binormal: cross(tangent, normal),\n };\n }\n walked += segment;\n }\n const last = pts[pts.length - 1]!;\n return { position: last.position, radius: last.radius, ...frames[frames.length - 1]! };\n}\n","import { cos, sin } from '../math';\nimport type { BranchLevelDefinition, TreeDefinition } from '../definition';\nimport type { Random } from '../random';\nimport { sampleTrack } from '../season/profile';\nimport { branchFrames, pathLength, sampleBranch } from './frames';\nimport type { SkeletonBranch, SkeletonPoint, Vec3 } from './types';\nimport { add, normalize, scale } from './vec';\n\nconst DEG = Math.PI / 180;\n/** How far `gravity` = ±1 turns a branch over its whole length (sum of per-section pulls). */\nconst GRAVITY_PER_BRANCH = 1.5;\n\n/**\n * Grows all branching levels on every Stem, breadth first (level by level, over all Stems).\n *\n * Branch path stability (ADR 0003): a parent's spiral phase comes from `random.fork(parentPath)`\n * and each child's shape from `random.fork(childPath)`. So a branch depends only on its\n * ancestors and its own path, never on its siblings' subtrees, on deeper levels or on leaves.\n */\nexport function buildBranches(definition: TreeDefinition, stems: SkeletonBranch[], random: Random): SkeletonBranch[] {\n const out: SkeletonBranch[] = [];\n const queue: SkeletonBranch[] = [...stems];\n for (let q = 0; q < queue.length; q++) {\n const parent = queue[q]!;\n const level = definition.branches[parent.level];\n if (!level) continue;\n const children = growChildren(parent, level, random);\n out.push(...children);\n queue.push(...children);\n }\n return out;\n}\n\n/** A Crown Shape curve's multiplier at attach position `t`; an absent curve is flat (1). */\nconst crownShape = (curve: BranchLevelDefinition['lengthProfile'], t: number) => (curve ? sampleTrack(curve, t) : 1);\n\n/**\n * Grows one parent's children. The Crown Shape curves (`lengthProfile`, `angleProfile`) scale each\n * child's length and angle by where it sits on the parent (ADR 0004).\n */\nfunction growChildren(parent: SkeletonBranch, level: BranchLevelDefinition, random: Random): SkeletonBranch[] {\n const count = level.count;\n const azimuth0 = random.fork(parent.path).range(0, Math.PI * 2);\n const frames = branchFrames(parent);\n const parentLength = pathLength(parent);\n\n const children: SkeletonBranch[] = [];\n for (let i = 0; i < count; i++) {\n const path = `${parent.path}.${i}`;\n const r = random.fork(path);\n const t = level.start + ((level.end - level.start) * (i + r.range(0.15, 0.85))) / count;\n const at = sampleBranch(parent, frames, t);\n\n const angle = Math.min(level.angle * crownShape(level.angleProfile, t) * (1 + r.range(-level.angleVariation, level.angleVariation)), 180) * DEG;\n const azimuth = azimuth0 + i * level.spiral * DEG;\n const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin(azimuth)));\n const start = normalize(add(scale(at.tangent, cos(angle)), scale(across, sin(angle))));\n // Gravity bends the branch up (+) or down (-) a little more with every section.\n const pull: Vec3 = [0, (level.gravity * GRAVITY_PER_BRANCH) / level.sections, 0];\n let direction = start;\n\n const length = parentLength * level.length * crownShape(level.lengthProfile, t) * (1 + r.range(-level.lengthVariation, level.lengthVariation));\n const step = length / level.sections;\n const baseRadius = at.radius * level.radius;\n\n const points: SkeletonPoint[] = [];\n let position: Vec3 = at.position;\n for (let s = 0; s <= level.sections; s++) {\n points.push({ position, radius: baseRadius * (1 + (level.taper - 1) * (s / level.sections)) });\n if (s === level.sections) break;\n const wander: Vec3 = [r.range(-1, 1), r.range(-1, 1), r.range(-1, 1)];\n direction = normalize(add(add(direction, scale(wander, level.bend)), pull));\n position = add(position, scale(direction, step));\n }\n children.push({ path, parent: parent.path, level: parent.level + 1, attach: t, direction: start, points });\n }\n return children;\n}\n","import type { SkeletonBranch, Vec3 } from './types';\n\n/**\n * The Crown Volume (GLOSSARY): one smooth, axis-aligned ellipsoid around all leaves of the fully grown\n * tree, in tree space (before Growth and Wind). Plain numbers, so it can go into glTF extras unchanged.\n * A point `p` is inside when `crownDistance(crown, p) <= 1`.\n */\nexport interface CrownVolume {\n /** Centre of the ellipsoid, tree space (metres). */\n center: Vec3;\n /** Half axes along x, y and z (metres, > 0). */\n radii: Vec3;\n}\n\n/** Axes of the ellipsoid. */\nconst D = 3;\n/** Stop when no point is further out than (1 + TOLERANCE) x the ellipsoid of the current weights. */\nconst TOLERANCE = 1e-2;\nconst MAX_STEPS = 400;\n/** No axis is flatter than this fraction of the largest one (a single flat leaf card still has a volume). */\nconst MIN_FLATNESS = 1e-3;\n/** The Volume of a tree with no leaves and no branches (every Stem Sculpted away). */\nconst EMPTY: CrownVolume = { center: [0, 0, 0], radii: [1, 1, 1] };\n\n/**\n * How far `p` sits from the Crown Volume's centre, in units of the ellipsoid:\n * 0 at the centre, 1 on the shell, > 1 outside. (`1 - crownDistance` is how deep a point is in the crown.)\n */\nexport function crownDistance({ center, radii }: CrownVolume, p: Readonly<Vec3>): number {\n const x = (p[0] - center[0]) / radii[0];\n const y = (p[1] - center[1]) / radii[1];\n const z = (p[2] - center[2]) / radii[2];\n return Math.sqrt(x * x + y * y + z * z);\n}\n\n/**\n * The unit outward normal at `p` of the Crown Volume's ellipsoid through `p` (the shell scaled to pass\n * through it), i.e. the normalized gradient `(p - center) / radii²`. At the centre itself: straight up.\n */\nexport function crownNormal({ center, radii }: CrownVolume, p: Readonly<Vec3>): Vec3 {\n const x = (p[0] - center[0]) / (radii[0] * radii[0]);\n const y = (p[1] - center[1]) / (radii[1] * radii[1]);\n const z = (p[2] - center[2]) / (radii[2] * radii[2]);\n const length = Math.sqrt(x * x + y * y + z * z);\n return length > 0 ? [x / length, y / length, z / length] : [0, 1, 0];\n}\n\n/**\n * Fits the Crown Volume to the leaf vertex positions of the fully grown tree. A tree without leaves gets\n * a Volume around its branches (centre lines, Roots excluded).\n */\nexport function crownVolume(leafPositions: Float32Array, branches: readonly SkeletonBranch[]): CrownVolume {\n if (leafPositions.length > 0) return fitEllipsoid(leafPositions);\n const points = branches.flatMap((b) => b.points.map((p) => p.position));\n return points.length > 0 ? fitEllipsoid(Float64Array.from(points.flat())) : { center: [...EMPTY.center], radii: [...EMPTY.radii] };\n}\n\n/**\n * The smallest axis-aligned ellipsoid around `positions` (x, y, z triples), close to minimum volume.\n *\n * Frank-Wolfe on the dual (as in Khachiyan's algorithm, restricted to axis-aligned ellipsoids): weights\n * on the points give a weighted mean `m` and per-axis variance `v`, and the ellipsoid `sum (p - m)² / (3v)\n * <= 1`. Each step moves weight to the point furthest outside, or off the weighted point furthest inside\n * (an away step), by an exact line search on `sum log v`.\n * Converged, the furthest point lies on the shell; the ellipsoid is then scaled to contain every point\n * exactly. Only + - * / and sqrt, no randomness: the same numbers on every machine.\n */\nfunction fitEllipsoid(positions: ArrayLike<number>): CrownVolume {\n const n = positions.length / D;\n // Start from the outermost point along each axis (a core set); the steps add the points that matter.\n const u = new Float64Array(n);\n const core = new Set<number>();\n for (let i = 0; i < D; i++) {\n let lo = 0;\n let hi = 0;\n for (let j = 1; j < n; j++) {\n if (positions[j * D + i]! < positions[lo * D + i]!) lo = j;\n if (positions[j * D + i]! > positions[hi * D + i]!) hi = j;\n }\n core.add(lo).add(hi);\n }\n for (const j of core) u[j] = 1 / core.size;\n const m = [0, 0, 0];\n const q = [0, 0, 0]; // weighted mean of p²\n const v = [0, 0, 0];\n const p = [0, 0, 0];\n const at = (j: number) => {\n p[0] = positions[j * D]!;\n p[1] = positions[j * D + 1]!;\n p[2] = positions[j * D + 2]!;\n return p;\n };\n for (const j of core) {\n at(j);\n for (let i = 0; i < D; i++) {\n m[i]! += u[j]! * p[i]!;\n q[i]! += u[j]! * p[i]! * p[i]!;\n }\n }\n // A floor on each axis's variance, relative to the largest, keeps a flat point set fittable.\n const floorOf = () => MIN_FLATNESS * MIN_FLATNESS * Math.max(q[0]! - m[0]! * m[0]!, q[1]! - m[1]! * m[1]!, q[2]! - m[2]! * m[2]!, 1e-12);\n let floor = floorOf();\n const variances = () => {\n for (let i = 0; i < D; i++) v[i] = Math.max(q[i]! - m[i]! * m[i]!, floor);\n };\n /**\n * Scores every point (its squared distance in units of sqrt(v) per axis): the furthest point of all,\n * and the nearest point that carries weight. Returns [furthest, its score, nearest, its score].\n */\n const extremes = (): [number, number, number, number] => {\n const [m0, m1, m2] = m as [number, number, number];\n const w0 = 1 / v[0]!;\n const w1 = 1 / v[1]!;\n const w2 = 1 / v[2]!;\n let far = 0;\n let farScore = -1;\n let near = -1;\n let nearScore = Infinity;\n for (let j = 0, o = 0; j < n; j++, o += D) {\n const x = positions[o]! - m0;\n const y = positions[o + 1]! - m1;\n const z = positions[o + 2]! - m2;\n const score = x * x * w0 + y * y * w1 + z * z * w2;\n if (score > farScore) {\n farScore = score;\n far = j;\n }\n if (score < nearScore && u[j]! > 0) {\n nearScore = score;\n near = j;\n }\n }\n return [far, farScore, near, nearScore];\n };\n\n variances();\n let [far, score, near, nearScore] = extremes();\n for (let step = 0; step < MAX_STEPS && score > D * (1 + TOLERANCE); step++) {\n // Towards the furthest point, or (an away step) weight off the nearest weighted point, whichever is\n // further from optimal: away steps drop inner points and make the fit converge fast.\n const away = D - nearScore > score - D && u[near]! < 1;\n const j = away ? near : far;\n at(j);\n // The furthest an away step can go: all of the point's weight.\n const drop = -u[j]! / (1 - u[j]!);\n const a = away ? lineSearch(m, q, p, floor, drop, 0) : lineSearch(m, q, p, floor, 0, 1);\n const weight = a === drop ? 0 : (1 - a) * u[j]! + a;\n for (let k = 0; k < n; k++) u[k]! *= 1 - a;\n u[j] = weight;\n for (let i = 0; i < D; i++) {\n m[i] = (1 - a) * m[i]! + a * p[i]!;\n q[i] = (1 - a) * q[i]! + a * p[i]! * p[i]!;\n }\n floor = floorOf();\n variances();\n [far, score, near, nearScore] = extremes();\n }\n // Scale so the furthest point lies exactly on the shell: every point is inside.\n return {\n center: [m[0]!, m[1]!, m[2]!],\n radii: [Math.sqrt(v[0]! * score), Math.sqrt(v[1]! * score), Math.sqrt(v[2]! * score)],\n };\n}\n\n/**\n * The step `a` in `lo..hi` towards point `p` (away from it when negative) that maximizes `sum log v(a)`,\n * where moving weight `a` to `p` gives `v(a) = (1-a) q + a p² - ((1-a) m + a p)²`. Concave in `a`, so its\n * derivative `sum v'(a) / v(a)` falls through 0 at most once: bisect for it.\n */\nfunction lineSearch(m: number[], q: number[], p: number[], floor: number, lo: number, hi: number): number {\n const slope = (a: number) => {\n let s = 0;\n for (let i = 0; i < D; i++) {\n const mean = (1 - a) * m[i]! + a * p[i]!;\n const variance = Math.max((1 - a) * q[i]! + a * p[i]! * p[i]! - mean * mean, floor);\n s += (p[i]! * p[i]! - q[i]! - 2 * mean * (p[i]! - m[i]!)) / variance;\n }\n return s;\n };\n if (slope(lo) <= 0) return lo;\n if (slope(hi) >= 0) return hi;\n for (let k = 0; k < 40; k++) {\n const mid = (lo + hi) / 2;\n if (slope(mid) > 0) lo = mid;\n else hi = mid;\n }\n return (lo + hi) / 2;\n}\n","import type { GeometryBuffers, SkeletonBranch } from './types';\n\n/**\n * Wind weights (ticket #8). Every vertex carries `aWind` = (trunk sway, branch sway, leaf flutter),\n * each 0..1, which the Wind TSL node scales by the Definition's Wind response and the scene Wind.\n *\n * - trunk sway: (height / trunk height)², clamped: the trunk bends from the ground and carries\n * everything above it.\n * - branch sway: 0 on the trunk; along a branch of level L it rises by 1/levels from the value its\n * parent has at the attach point, so joints never tear and the outermost twigs reach up to 1.\n * - leaf flutter: 0 on wood; along a leaf from 0 at its base to 1 at its tip.\n */\nexport interface PartSway {\n /** Branch sway at the base of the part. */\n base: number;\n /** Branch sway gained from the base (along = 0) to the tip (along = 1). */\n gain: number;\n /** True for leaves: leaf flutter = along. */\n flutter: boolean;\n}\n\nexport const NO_SWAY: PartSway = { base: 0, gain: 0, flutter: false };\n\n/** Branch sway of every branch (by path). `branches` must be ordered parents first (the skeleton is). */\nexport function branchSway(branches: SkeletonBranch[], levels: number): Map<string, PartSway> {\n const gain = levels > 0 ? 1 / levels : 0;\n const out = new Map<string, PartSway>();\n for (const branch of branches) {\n if (branch.parent === null) {\n out.set(branch.path, NO_SWAY);\n continue;\n }\n const parent = out.get(branch.parent)!;\n out.set(branch.path, { base: parent.base + parent.gain * branch.attach, gain, flutter: false });\n }\n return out;\n}\n\n/** The sway of a leaf: its branch's sway at the attach point, plus flutter. */\nexport function leafSway(branch: PartSway, attach: number): PartSway {\n return { base: branch.base + branch.gain * attach, gain: 0, flutter: true };\n}\n\n/** Fills the trunk-sway channel (x of `aWind`) from each vertex's height. */\nexport function writeTrunkSway(buffers: GeometryBuffers, trunkHeight: number): void {\n const aWind = buffers.attributes.aWind.array;\n const count = buffers.positions.length / 3;\n for (let v = 0; v < count; v++) {\n const h = Math.min(Math.max(buffers.positions[v * 3 + 1]! / Math.max(trunkHeight, 1e-6), 0), 1);\n aWind[v * 3] = h * h;\n }\n}\n","import type { PartSeason } from '../season/profile';\nimport type { GrowthWindow, TreeAttributes, Vec3 } from './types';\nimport { NO_SWAY, type PartSway } from './wind';\n\n/** The facts shared by every vertex of one part (branch or leaf). */\nexport interface PartInfo {\n level: number;\n attach: number;\n random: number;\n origin: Vec3;\n growth: GrowthWindow;\n /** Season timing, written as `aSeason` (vec3: shift, coverage rank, blossom rank). */\n season: PartSeason;\n /** Wind weights of the part (branch sway, leaf flutter); trunk sway is filled in from heights. */\n sway?: PartSway;\n}\n\n/** Allocates the per-vertex attributes for `vertexCount` vertices. */\nexport function createAttributes(vertexCount: number): TreeAttributes {\n const scalar = () => ({ array: new Float32Array(vertexCount), itemSize: 1 });\n return {\n aLevel: scalar(),\n aAlong: scalar(),\n aAttach: scalar(),\n aRandom: scalar(),\n aOrigin: { array: new Float32Array(vertexCount * 3), itemSize: 3 },\n aGrowth: { array: new Float32Array(vertexCount * 3), itemSize: 3 },\n aSeason: { array: new Float32Array(vertexCount * 3), itemSize: 3 },\n aWind: { array: new Float32Array(vertexCount * 3), itemSize: 3 },\n };\n}\n\n/** Writes one vertex's attributes; `radius` = its distance from the part's centre line. */\nexport function writePart(attributes: TreeAttributes, v: number, part: PartInfo, along: number, radius = 0): void {\n attributes.aLevel.array[v] = part.level;\n attributes.aAlong.array[v] = along;\n attributes.aAttach.array[v] = part.attach;\n attributes.aRandom.array[v] = part.random;\n attributes.aOrigin.array.set(part.origin, v * 3);\n attributes.aGrowth.array.set([part.growth.start, part.growth.end, radius], v * 3);\n attributes.aSeason.array.set([part.season.shift, part.season.coverageRank, part.season.blossomRank], v * 3);\n const sway = part.sway ?? NO_SWAY;\n attributes.aWind.array[v * 3 + 1] = Math.min(sway.base + sway.gain * along, 1);\n attributes.aWind.array[v * 3 + 2] = sway.flutter ? along : 0;\n}\n","import { cos, sin } from '../math';\nimport type { LeafShape, VariationDefinition } from '../definition';\nimport { leafSeasonAttribute } from '../season/profile';\nimport { seedRandom } from '../random';\nimport { createAttributes, writePart, type PartInfo } from './attributes';\nimport type { GeometryBuffers, GrowthWindow, SkeletonLeaf, Vec3 } from './types';\nimport { leafSway, NO_SWAY, type PartSway } from './wind';\nimport { add, cross, dot, normalize, scale, sub } from './vec';\n\n/**\n * A closed solid leaf shape in a leaf's local frame, in units of the leaf size:\n * x = across (side), y = the leaf normal, z = along the leaf direction (0 = attachment, 1 = tip).\n * `normals` are outward unit normals (smooth; a flat-shaded material makes them faceted).\n */\nexport interface SolidTemplate {\n positions: Vec3[];\n normals: Vec3[];\n triangles: [number, number, number][];\n}\n\nconst GOLDEN = (1 + Math.sqrt(5)) / 2;\n\n/** Low-poly foliage ball: an icosahedron of diameter 1, from the attachment point out along the leaf. */\nexport function clumpTemplate(): SolidTemplate {\n const raw: Vec3[] = [\n [-1, GOLDEN, 0], [1, GOLDEN, 0], [-1, -GOLDEN, 0], [1, -GOLDEN, 0],\n [0, -1, GOLDEN], [0, 1, GOLDEN], [0, -1, -GOLDEN], [0, 1, -GOLDEN],\n [GOLDEN, 0, -1], [GOLDEN, 0, 1], [-GOLDEN, 0, -1], [-GOLDEN, 0, 1],\n ];\n const normals = raw.map((v) => normalize(v));\n const centre: Vec3 = [0, 0, 0.5];\n const triangles: [number, number, number][] = [\n [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11],\n [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8],\n [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9],\n [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1],\n ];\n return { positions: normals.map((n) => add(centre, scale(n, 0.5))), normals, triangles };\n}\n\n/**\n * Stylized foliage puff: an icosphere (the clump's icosahedron with every triangle split in\n * four, new vertices pushed onto the sphere), diameter 1, from the attachment point outward.\n * Smooth radial normals, so toon shading makes it read as a soft round ball.\n */\nfunction puffTemplate(): SolidTemplate {\n const ico = clumpTemplate();\n const centre: Vec3 = [0, 0, 0.5];\n const normals = [...ico.normals];\n const midpoints = new Map<string, number>();\n const midpoint = (a: number, b: number): number => {\n const key = a < b ? `${a}-${b}` : `${b}-${a}`;\n let index = midpoints.get(key);\n if (index === undefined) {\n index = normals.push(normalize(add(normals[a]!, normals[b]!))) - 1;\n midpoints.set(key, index);\n }\n return index;\n };\n const triangles: [number, number, number][] = ico.triangles.flatMap(([a, b, c]) => {\n const [ab, bc, ca] = [midpoint(a, b), midpoint(b, c), midpoint(c, a)];\n return [[a, ab, ca], [b, bc, ab], [c, ca, bc], [ab, bc, ca]] as [number, number, number][];\n });\n return { positions: normals.map((n) => add(centre, scale(n, 0.5))), normals, triangles };\n}\n\n/** Needle tuft: a slim five-sided spindle from the attachment point (z = 0) to the tip (z = 1). */\nconst NEEDLE_SIDES = 5;\nconst NEEDLE_RADIUS = 0.28;\nconst NEEDLE_WAIST = 0.25;\nfunction needleTemplate(): SolidTemplate {\n const positions: Vec3[] = [[0, 0, 0], [0, 0, 1]];\n const normals: Vec3[] = [[0, 0, -1], [0, 0, 1]];\n const triangles: [number, number, number][] = [];\n for (let s = 0; s < NEEDLE_SIDES; s++) {\n const angle = (s / NEEDLE_SIDES) * Math.PI * 2;\n const radial: Vec3 = [cos(angle), sin(angle), 0];\n positions.push([radial[0] * NEEDLE_RADIUS, radial[1] * NEEDLE_RADIUS, NEEDLE_WAIST]);\n normals.push(radial);\n const a = 2 + s;\n const b = 2 + ((s + 1) % NEEDLE_SIDES);\n triangles.push([a, b, 1], [b, a, 0]);\n }\n return { positions, normals, triangles };\n}\n\nconst TEMPLATES: Record<Exclude<LeafShape, 'card'>, SolidTemplate> = {\n clump: orient(clumpTemplate()),\n needle: orient(needleTemplate()),\n puff: orient(puffTemplate()),\n};\n\n/** Fixes each triangle's winding so its front face points along its vertex normals (CCW = front). */\nexport function orient(template: SolidTemplate): SolidTemplate {\n const { positions: p, normals: n } = template;\n const triangles = template.triangles.map(([a, b, c]): [number, number, number] => {\n const face = cross(sub(p[b]!, p[a]!), sub(p[c]!, p[a]!));\n return dot(face, add(add(n[a]!, n[b]!), n[c]!)) >= 0 ? [a, b, c] : [a, c, b];\n });\n return { ...template, triangles };\n}\n\n/**\n * Leaf geometry for the solid shapes ('clump', 'needle', 'puff'): one small closed mesh per leaf,\n * placed in the leaf's frame (across, normal, direction) and scaled by its size. Like cards,\n * every vertex carries the leaf's tint as its colour and the leaf's part attributes.\n */\nexport function solidLeafGeometry(\n leaves: SkeletonLeaf[],\n shape: Exclude<LeafShape, 'card'>,\n level: number,\n seed: number,\n variation: Pick<VariationDefinition, 'season'> = { season: 0 },\n growth: GrowthWindow[] = [],\n branchSway: ReadonlyMap<string, PartSway> = new Map(),\n): GeometryBuffers {\n return solidGeometry(TEMPLATES[shape], leaves, (leaf, l) => ({\n level,\n attach: leaf.attach,\n random: seedRandom(seed, leaf.id),\n origin: leaf.position,\n season: leafSeasonAttribute(seed, variation, leaf.id),\n growth: growth[l] ?? { start: 0, end: 0 },\n sway: leafSway(branchSway.get(leaf.branch) ?? NO_SWAY, leaf.attach),\n }));\n}\n\n/** One placed copy of a solid template: its base point, frame (direction, normal), size and tint. */\nexport interface SolidPlacement {\n position: Vec3;\n /** Unit vector from the base point to the far end (template z). */\n direction: Vec3;\n /** Unit vector across it (template y), perpendicular to `direction`. */\n normal: Vec3;\n size: number;\n /** Vertex colour (RGB multiplier). */\n tint: Vec3;\n}\n\n/**\n * One small closed mesh per placement: the template in the placement's frame\n * (across, normal, direction), scaled by its size, every vertex carrying the placement's tint\n * as its colour and its part attributes (`part`).\n */\nexport function solidGeometry<P extends SolidPlacement>(\n template: SolidTemplate,\n placements: readonly P[],\n part: (placement: P, index: number) => PartInfo,\n): GeometryBuffers {\n const n = template.positions.length;\n const positions = new Float32Array(placements.length * n * 3);\n const normals = new Float32Array(placements.length * n * 3);\n const uvs = new Float32Array(placements.length * n * 2);\n const colors = new Float32Array(placements.length * n * 3);\n const indices = new Uint32Array(placements.length * template.triangles.length * 3);\n const attributes = createAttributes(placements.length * n);\n placements.forEach((placement, l) => {\n const side = cross(placement.normal, placement.direction); // (side, normal, direction) is right-handed, so winding is kept\n const toWorld = ([x, y, z]: Vec3): Vec3 =>\n add(add(scale(side, x), scale(placement.normal, y)), scale(placement.direction, z));\n const info = part(placement, l);\n for (let c = 0; c < n; c++) {\n const v = l * n + c;\n const local = template.positions[c]!;\n positions.set(add(placement.position, scale(toWorld(local), placement.size)), v * 3);\n normals.set(normalize(toWorld(template.normals[c]!)), v * 3);\n const along = Math.min(Math.max(local[2], 0), 1);\n uvs.set([local[0] + 0.5, along], v * 2);\n colors.set(placement.tint, v * 3);\n writePart(attributes, v, info, along);\n }\n template.triangles.forEach((triangle, t) => {\n indices.set(triangle.map((i) => l * n + i), (l * template.triangles.length + t) * 3);\n });\n });\n return { positions, normals, uvs, colors, indices, attributes };\n}\n","import { cos, sin } from '../math';\nimport type { FruitType, TreeDefinition, VariationDefinition } from '../definition';\nimport { fruitSeasonAttribute } from '../season/profile';\nimport type { Random } from '../random';\nimport { seedRandom } from '../random';\nimport { createAttributes } from './attributes';\nimport { branchFrames, sampleBranch } from './frames';\nimport { clumpTemplate, orient, solidGeometry, type SolidTemplate } from './leaf-shapes';\nimport type { GeometryBuffers, GrowthWindow, SkeletonBranch, SkeletonFruit, Vec3 } from './types';\nimport { NO_SWAY, type PartSway } from './wind';\nimport { add, cross, dot, length, lerp, normalize, perpendicular, scale } from './vec';\n\nconst DEG = Math.PI / 180;\n/** Angle between twig and Fruit when it does not hang (`hang` 0), degrees. */\nconst FRUIT_TILT = 60;\n/** Fruit sits on the outer part of its twig: from this fraction of the twig length to its tip. */\nconst FRUIT_START = 0.3;\n/** Fruit starts to grow no earlier than this Growth (it only shows on a fully grown tree) ... */\nconst FRUIT_GROWTH_START = 0.9;\n/** ... plus up to this much per Fruit (from the Seed). */\nconst FRUIT_GROWTH_JITTER = 0.05;\n\n/**\n * Places Fruit on the outermost branches (the trunk if there are no branch levels), `fruit.count`\n * per branch (a fraction = a chance of one more). `random` is the Generator's `fork('fruit')`: each Fruit draws from its own\n * `random.fork(fruitId)`, so Fruit never shifts the branches or leaves (ADR 0006).\n */\nexport function placeFruit(definition: TreeDefinition, branches: SkeletonBranch[], random: Random): SkeletonFruit[] {\n const { fruit } = definition;\n if (!fruit || fruit.count === 0) return [];\n const outermost = definition.branches.length;\n const half = definition.variation.color / 2;\n const tintRandom = random.fork('tint');\n const treeTint = [0, 1, 2].map(() => tintRandom.range(-half, half));\n const tilt = FRUIT_TILT * DEG;\n const down: Vec3 = [0, -1, 0];\n\n // A fractional count is a chance of one more Fruit per twig, drawn from the twig's own fork (so a\n // higher chance keeps the Fruit a lower one had, and whole counts draw nothing extra).\n const whole = Math.floor(fruit.count);\n const chance = fruit.count - whole;\n const out: SkeletonFruit[] = [];\n for (const branch of branches) {\n if (branch.level !== outermost) continue;\n const count = whole + (chance > 0 && random.fork(`${branch.path}/chance`).next() < chance ? 1 : 0);\n if (count === 0) continue;\n const frames = branchFrames(branch);\n for (let i = 0; i < count; i++) {\n const id = `${branch.path}/${i}`;\n const r = random.fork(id);\n const t = FRUIT_START + ((1 - FRUIT_START) * (i + r.range(0.1, 0.9))) / count;\n const at = sampleBranch(branch, frames, t);\n const azimuth = r.range(0, Math.PI * 2);\n const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin(azimuth)));\n const outward = normalize(add(scale(at.tangent, cos(tilt)), scale(across, sin(tilt))));\n const hanging = lerp(outward, down, fruit.hang);\n const direction = length(hanging) > 1e-3 ? normalize(hanging) : across;\n const side0 = cross(direction, [0, 1, 0]);\n const normal = dot(side0, side0) > 1e-6 ? normalize(cross(normalize(side0), direction)) : perpendicular(direction);\n const size = fruit.size * (1 + r.range(-fruit.sizeVariation, fruit.sizeVariation));\n const brightness = r.range(-half, half);\n const tint = treeTint.map((c) => 1 + c + brightness) as Vec3;\n out.push({ id, branch: branch.path, index: i, attach: t, position: at.position, direction, normal, size, tint });\n }\n }\n return out;\n}\n\n/**\n * When each Fruit grows: only at the very end of Growth (from about {@link FRUIT_GROWTH_START},\n * never before its twig is fully grown), so a sapling bears none. Computed apart from the other\n * parts' timing, so Fruit never shifts the Growth of wood or leaves.\n */\nexport function fruitGrowth(seed: number, fruit: SkeletonFruit[], twigGrowth: ReadonlyMap<string, GrowthWindow>): GrowthWindow[] {\n return fruit.map((f) => {\n const from = FRUIT_GROWTH_START + seedRandom(seed, `growth/fruit/${f.id}`) * FRUIT_GROWTH_JITTER;\n return { start: Math.min(Math.max(from, twigGrowth.get(f.branch)?.end ?? 0), 1), end: 1 };\n });\n}\n\n/**\n * Fruit geometry: one small solid per Fruit from its Fruit Type's template, hanging from its\n * attachment point. Vertex colours carry the Seed's tint; `aSeason` = (timing shift, fruit rank, 0);\n * it sways with its twig at the attachment point (no leaf flutter).\n */\nexport function fruitGeometry(\n fruit: SkeletonFruit[],\n { type, sides }: { type: FruitType; sides?: number | undefined },\n level: number,\n seed: number,\n variation: Pick<VariationDefinition, 'season'>,\n growth: GrowthWindow[],\n branchSway: ReadonlyMap<string, PartSway>,\n): GeometryBuffers {\n if (fruit.length === 0) return emptyGeometry();\n return solidGeometry(fruitTemplate(type, sides), fruit, (f, i) => {\n const twig = branchSway.get(f.branch) ?? NO_SWAY;\n return {\n level,\n attach: f.attach,\n random: seedRandom(seed, `fruit/${f.id}`),\n origin: f.position,\n season: fruitSeasonAttribute(seed, variation, f.id),\n growth: growth[i] ?? { start: 0, end: 0 },\n sway: { base: twig.base + twig.gain * f.attach, gain: 0, flutter: false },\n };\n });\n}\n\n/** Empty geometry buffers (a tree without Fruit). */\nexport function emptyGeometry(): GeometryBuffers {\n return {\n positions: new Float32Array(0),\n normals: new Float32Array(0),\n uvs: new Float32Array(0),\n colors: new Float32Array(0),\n indices: new Uint32Array(0),\n attributes: createAttributes(0),\n };\n}\n\n// --- Fruit Type templates: closed solids in units of the Fruit size, z = 0 at the twig .. 1 at the far end.\n\n/** A solid of revolution around z: rings of `sides` vertices at (z, radius), closed by a point at each end. */\nfunction lathe(profile: [number, number][], sides: number, ends: [number, number], twist = 0): SolidTemplate {\n const positions: Vec3[] = [[0, 0, ends[0]], [0, 0, ends[1]]];\n const normals: Vec3[] = [[0, 0, -1], [0, 0, 1]];\n const triangles: [number, number, number][] = [];\n profile.forEach(([z, r], ring) => {\n for (let s = 0; s < sides; s++) {\n const angle = ((s + ring * twist) / sides) * Math.PI * 2;\n const radial: Vec3 = [cos(angle), sin(angle), 0];\n positions.push([radial[0] * r, radial[1] * r, z]);\n normals.push(radial);\n }\n });\n const at = (ring: number, s: number) => 2 + ring * sides + (s % sides);\n for (let s = 0; s < sides; s++) {\n triangles.push([0, at(0, s), at(0, s + 1)]);\n for (let ring = 0; ring < profile.length - 1; ring++) {\n triangles.push([at(ring, s), at(ring + 1, s), at(ring + 1, s + 1)], [at(ring, s), at(ring + 1, s + 1), at(ring, s + 1)]);\n }\n triangles.push([1, at(profile.length - 1, s + 1), at(profile.length - 1, s)]);\n }\n return orient({ positions, normals, triangles });\n}\n\n/** Chestnut husk: a ball (icosphere, diameter 0.8) with a spike at each of the icosahedron's 12 corners. */\nfunction nutTemplate(): SolidTemplate {\n const ico = clumpTemplate();\n const centre: Vec3 = [0, 0, 0.5];\n const directions = ico.positions.map((p) => normalize([p[0], p[1], p[2] - 0.5]));\n const midpoints = new Map<string, number>();\n const midpoint = (a: number, b: number): number => {\n const key = a < b ? `${a}-${b}` : `${b}-${a}`;\n let index = midpoints.get(key);\n if (index === undefined) {\n index = directions.push(normalize(add(directions[a]!, directions[b]!))) - 1;\n midpoints.set(key, index);\n }\n return index;\n };\n const triangles: [number, number, number][] = ico.triangles.flatMap(([a, b, c]) => {\n const [ab, bc, ca] = [midpoint(a, b), midpoint(b, c), midpoint(c, a)];\n return [[a, ab, ca], [b, bc, ab], [c, ca, bc], [ab, bc, ca]] as [number, number, number][];\n });\n // The first 12 directions are the icosahedron corners: the spikes.\n const positions = directions.map((d, i) => add(centre, scale(d, i < 12 ? 0.5 : 0.36)));\n return orient({ positions, normals: directions, triangles });\n}\n\n/** Each Fruit Type's smooth profile (z, radius) along its axis, and its end points. */\nconst PROFILES: Record<Exclude<FruitType, 'nut'>, { rings: [number, number][]; ends: [number, number]; twist?: number }> = {\n round: { rings: [[0.04, 0.22], [0.2, 0.44], [0.45, 0.5], [0.7, 0.45], [0.9, 0.28]], ends: [0.1, 1] },\n pear: { rings: [[0.08, 0.1], [0.25, 0.18], [0.45, 0.3], [0.65, 0.4], [0.82, 0.38], [0.95, 0.2]], ends: [0, 1] },\n // Staggered rings (half a side per ring) give the cone its scales.\n cone: { rings: [[0.08, 0.2], [0.22, 0.32], [0.38, 0.36], [0.54, 0.34], [0.7, 0.28], [0.86, 0.18]], ends: [0, 1], twist: 0.5 },\n berry: { rings: [[0.15, 0.36], [0.5, 0.5], [0.85, 0.36]], ends: [0, 1] },\n};\n\n/** Coarse profiles (low detail): two rings (berry one), a few flat facets. */\nconst COARSE: Record<Exclude<FruitType, 'nut'>, [number, number][]> = {\n round: [[0.28, 0.48], [0.72, 0.42]],\n pear: [[0.3, 0.2], [0.75, 0.4]],\n cone: [[0.25, 0.32], [0.65, 0.28]],\n berry: [[0.5, 0.5]],\n};\n\n/** At or below this many sides, Fruit uses the coarse profiles (and the nut a plain icosahedron). */\nconst COARSE_SIDES = 5;\n\n/** The default templates: each Fruit Type's own sides (Definitions without `fruit.sides`). */\nconst DEFAULT_SIDES: Record<Exclude<FruitType, 'nut'>, number> = { round: 8, pear: 8, cone: 7, berry: 6 };\n\nconst templates = new Map<string, SolidTemplate>();\n\n/** The template of a Fruit Type drawn with `sides` faces around (absent = the Type's own detail), cached. */\nfunction fruitTemplate(type: FruitType, sides?: number): SolidTemplate {\n const key = `${type}/${sides ?? ''}`;\n let template = templates.get(key);\n if (!template) {\n const coarse = sides !== undefined && sides <= COARSE_SIDES;\n if (type === 'nut') template = coarse ? coarseNutTemplate() : nutTemplate();\n else {\n const { rings, ends, twist } = PROFILES[type];\n template = lathe(coarse ? COARSE[type] : rings, sides ?? DEFAULT_SIDES[type], ends, twist);\n }\n templates.set(key, template);\n }\n return template;\n}\n\n/** Low-detail chestnut husk: an icosahedron (its corners are the spikes). */\nfunction coarseNutTemplate(): SolidTemplate {\n const ico = clumpTemplate();\n const directions = ico.positions.map((p) => normalize([p[0], p[1], p[2] - 0.5]));\n return orient({ positions: directions.map((d) => add([0, 0, 0.5], scale(d, 0.45))), normals: directions, triangles: ico.triangles });\n}\n","import { pow } from '../math';\nimport type { TreeDefinition } from '../definition';\nimport { seedRandom } from '../random';\nimport type { GrowthTiming, GrowthWindow, SkeletonBranch, SkeletonLeaf } from './types';\n\n// Raw timeline units (normalised to 0..1 afterwards, so only their ratios matter).\n/** Delay of a branch after its parent is grown, per unit of `attach` (lower branches sprout first). */\nconst BRANCH_STAGGER = 0.6;\n/** Time a branch takes from sprouting to full size. */\nconst BRANCH_DURATION = 1;\n/** Leaves wait this long after their branch is grown ... */\nconst LEAF_DELAY = 0.3;\n/** ... plus this much per unit of `attach` (leaves near the base first) ... */\nconst LEAF_STAGGER = 0.5;\n/** ... and take this long to unfold. */\nconst LEAF_DURATION = 0.6;\n\n/**\n * When each part grows, as Growth windows (0..1) parallel to the skeleton arrays.\n *\n * Order: the trunk is there from Growth 0 (it only scales with the whole tree); a branch sprouts\n * once its parent is fully grown, lower branches first; leaves come after their branch. So a part\n * always sprouts from a fully-grown parent and never floats. The last part finishes at Growth 1.\n *\n * Seed (within `variation.growth` = v): each part's start is delayed by up to v/2 of its own window\n * (its end stays put, so the order above holds), and the whole timeline is warped by `t^k`,\n * k in 1 ± v (a monotone map that keeps 0 and 1). Together a window moves by less than v.\n */\nexport function growthTiming(\n definition: TreeDefinition,\n seed: number,\n branches: SkeletonBranch[],\n leaves: SkeletonLeaf[],\n): Omit<GrowthTiming, 'fruit' | 'roots'> {\n const raw = new Map<string, GrowthWindow>();\n const branchWindows = branches.map((branch) => {\n let window: GrowthWindow = { start: 0, end: 0 };\n if (branch.parent !== null) {\n const start = raw.get(branch.parent)!.end + branch.attach * BRANCH_STAGGER;\n window = { start, end: start + BRANCH_DURATION };\n }\n raw.set(branch.path, window); // breadth first: parents come before children\n return window;\n });\n const leafWindows = leaves.map((leaf) => {\n const start = raw.get(leaf.branch)!.end + LEAF_DELAY + leaf.attach * LEAF_STAGGER;\n return { start, end: start + LEAF_DURATION };\n });\n\n const total = Math.max(0, ...branchWindows.map((w) => w.end), ...leafWindows.map((w) => w.end));\n const v = definition.variation.growth;\n const k = 1 + (2 * seedRandom(seed, 'growth') - 1) * v;\n const warp = (t: number) => (total > 0 ? pow(Math.min(1, t / total), k) : 0);\n const finish = (w: GrowthWindow, key: string): GrowthWindow => {\n const delay = seedRandom(seed, `growth/${key}`) * (v / 2) * (w.end - w.start);\n return { start: warp(w.start + delay), end: warp(w.end) };\n };\n return {\n branches: branchWindows.map((w, i) => finish(w, branches[i]!.path)),\n leaves: leafWindows.map((w, i) => finish(w, leaves[i]!.id)),\n };\n}\n","import { cos, sin } from '../math';\nimport type { TreeDefinition, VariationDefinition } from '../definition';\nimport { leafSeasonAttribute } from '../season/profile';\nimport type { Random } from '../random';\nimport { seedRandom } from '../random';\nimport { createAttributes, writePart } from './attributes';\nimport { branchFrames, sampleBranch } from './frames';\nimport type { GeometryBuffers, GrowthWindow, SkeletonBranch, SkeletonLeaf, Vec3 } from './types';\nimport { leafSway, NO_SWAY, type PartSway } from './wind';\nimport { add, cross, dot, normalize, perpendicular, scale } from './vec';\n\nconst DEG = Math.PI / 180;\n/** Leaf card width as a fraction of its length. */\nconst LEAF_WIDTH = 0.5;\n\n/**\n * Places leaves on the outermost branches (the trunk if there are no branch levels).\n * Each leaf draws from `random.fork(leafId)`, so leaves never shift the branches and\n * one leaf never shifts another. The colour tint shared by the whole tree comes from\n * `random.fork('tint')`. The shape ('card' here, 'clump'/'needle'/'puff' in `leaf-shapes.ts`) only affects the mesh.\n */\nexport function placeLeaves(definition: TreeDefinition, branches: SkeletonBranch[], random: Random): SkeletonLeaf[] {\n const { leaves } = definition;\n if (leaves.count === 0) return [];\n const outermost = definition.branches.length;\n // Per-tree tint and per-leaf brightness each take half the colour range, so together they stay within it.\n const half = definition.variation.color / 2;\n const tintRandom = random.fork('tint');\n const treeTint = [0, 1, 2].map(() => tintRandom.range(-half, half));\n const tilt = Math.min(leaves.angle, 180) * DEG;\n\n const out: SkeletonLeaf[] = [];\n for (const branch of branches) {\n if (branch.level !== outermost) continue;\n const frames = branchFrames(branch);\n for (let i = 0; i < leaves.count; i++) {\n const id = `${branch.path}/${i}`;\n const r = random.fork(id);\n const t = leaves.start + ((1 - leaves.start) * (i + r.range(0.1, 0.9))) / leaves.count;\n const at = sampleBranch(branch, frames, t);\n const azimuth = r.range(0, Math.PI * 2);\n const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin(azimuth)));\n const direction = normalize(add(scale(at.tangent, cos(tilt)), scale(across, sin(tilt))));\n // Card plane faces up as much as possible (sunlit side), with some random roll.\n const side0 = cross(direction, [0, 1, 0]);\n const side = dot(side0, side0) > 1e-6 ? normalize(side0) : perpendicular(direction);\n const roll = r.range(-0.4, 0.4);\n const up = cross(side, direction);\n const normal = normalize(add(scale(up, cos(roll)), scale(side, sin(roll))));\n const size = leaves.size * (1 + r.range(-leaves.sizeVariation, leaves.sizeVariation));\n const brightness = r.range(-half, half);\n const tint = treeTint.map((c) => 1 + c + brightness) as Vec3;\n out.push({ id, branch: branch.path, index: i, attach: t, position: at.position, direction, normal, size, tint });\n }\n }\n return out;\n}\n\n/** One diamond-shaped card per leaf (4 vertices, 2 triangles); vertex colours carry the leaf's tint. */\nexport function leafGeometry(\n leaves: SkeletonLeaf[],\n level: number,\n seed: number,\n variation: Pick<VariationDefinition, 'season'> = { season: 0 },\n growth: GrowthWindow[] = [],\n branchSway: ReadonlyMap<string, PartSway> = new Map(),\n): GeometryBuffers {\n const positions = new Float32Array(leaves.length * 4 * 3);\n const normals = new Float32Array(leaves.length * 4 * 3);\n const uvs = new Float32Array(leaves.length * 4 * 2);\n const colors = new Float32Array(leaves.length * 4 * 3);\n const indices = new Uint32Array(leaves.length * 6);\n const attributes = createAttributes(leaves.length * 4);\n leaves.forEach((leaf, l) => {\n const side = cross(leaf.direction, leaf.normal); // right-handed: direction x normal points to the card's right\n const halfWidth = (leaf.size * LEAF_WIDTH) / 2;\n const mid = add(leaf.position, scale(leaf.direction, leaf.size * 0.4));\n const corners: Vec3[] = [\n leaf.position,\n add(mid, scale(side, halfWidth)),\n add(leaf.position, scale(leaf.direction, leaf.size)),\n add(mid, scale(side, -halfWidth)),\n ];\n const cornerUvs = [0.5, 0, 1, 0.4, 0.5, 1, 0, 0.4];\n const part = {\n level,\n attach: leaf.attach,\n random: seedRandom(seed, leaf.id),\n origin: leaf.position,\n season: leafSeasonAttribute(seed, variation, leaf.id),\n growth: growth[l] ?? { start: 0, end: 0 },\n sway: leafSway(branchSway.get(leaf.branch) ?? NO_SWAY, leaf.attach),\n };\n for (let c = 0; c < 4; c++) {\n const v = l * 4 + c;\n positions.set(corners[c]!, v * 3);\n normals.set(leaf.normal, v * 3);\n uvs.set([cornerUvs[c * 2]!, cornerUvs[c * 2 + 1]!], v * 2);\n colors.set(leaf.tint, v * 3);\n writePart(attributes, v, part, cornerUvs[c * 2 + 1]!);\n }\n const v0 = l * 4;\n indices.set([v0, v0 + 1, v0 + 2, v0, v0 + 2, v0 + 3], l * 6);\n });\n return { positions, normals, uvs, colors, indices, attributes };\n}\n","import { cos, sin } from '../math';\nimport type { TreeDefinition, TrunkDefinition } from '../definition';\nimport type { Random } from '../random';\nimport type { SkeletonBranch, SkeletonPoint, Vec3 } from './types';\nimport { add, cross, dot, scale, sub } from './vec';\n\nconst DEG = Math.PI / 180;\n/** The leader: the part of a Stem above this fraction of its length is what trunk gravity bends. */\nconst LEADER_START = 2 / 3;\n/** How far trunk `gravity` = ±1 turns the leader over its length, degrees. */\nconst LEADER_BEND = 120;\n/** Seed range of each Stem's lean: ± this fraction of `spread`. */\nconst SPREAD_VARIATION = 0.3;\n/** Seed range of each Stem's place around the ring: ± this fraction of the gap between Stems. */\nconst RING_JITTER = 0.25;\n/** Radius of the ring the Stems stand in, as a fraction of the trunk radius (several Stems only). */\nconst RING_RADIUS = 1;\n/** How far a Stem's base ring sinks straight down below the ground, as a fraction of the trunk radius (no seam on uneven terrain). */\nexport const BASE_SINK = 0.1;\n/** Root Flare zone: the bottom fraction of a Stem's length (measured along it, after Sculpts) that widens. */\nexport const FLARE_ZONE = 0.12;\n/** Root Flare width: at `flare` = 1 the base ring is (1 + this) × the trunk radius. */\nexport const FLARE_WIDTH = 0.8;\n/** Extra rings the trunk sweep puts in the Root Flare zone while `trunk.flareSections` is absent (the low-poly Style sets 2). */\nexport const FLARE_SECTIONS = 3;\n\n/**\n * Builds the Stems: `trunk.stems` full trunks standing in a small ring at the base, paths \"0\", \"1\", ...\n *\n * Path stability (ADR 0003): Stem 0's centre line draws from `random.fork('trunk')` exactly as a\n * single trunk always did, Stem i > 0 from `random.fork('trunk/<i>')`; the ring and the leans come\n * from `random.fork('stems')`. So a single upright Stem without gravity is today's trunk, bit for bit.\n */\nexport function buildStems(definition: TreeDefinition, random: Random): SkeletonBranch[] {\n const { trunk } = definition;\n const { stems: count = 1, spread = 0, gravity = 0 } = trunk;\n const ring = random.fork('stems');\n const turn = ring.range(0, Math.PI * 2);\n const stems: SkeletonBranch[] = [];\n for (let i = 0; i < count; i++) {\n const r = ring.fork(i);\n const azimuth = turn + ((i + r.range(-RING_JITTER, RING_JITTER)) / count) * Math.PI * 2;\n const tilt = Math.min(spread * (1 + r.range(-SPREAD_VARIATION, SPREAD_VARIATION)), 90) * DEG;\n const offset = count > 1 ? trunk.radius * RING_RADIUS : 0;\n const line = centreLine(trunk, random.fork(i === 0 ? 'trunk' : `trunk/${i}`));\n stems.push(placeStem(String(i), line, gravity, azimuth, tilt, offset));\n }\n return stems;\n}\n\n/** One upright, unbent Stem's centre line at the origin, varied by the Seed within the trunk's ranges. */\nfunction centreLine(trunk: TrunkDefinition, random: Random): SkeletonPoint[] {\n const length = trunk.length * (1 + random.range(-trunk.lengthVariation, trunk.lengthVariation));\n const sectionLength = length / trunk.sections;\n const maxDrift = trunk.bend * sectionLength;\n\n const points: SkeletonPoint[] = [];\n let x = 0;\n let z = 0;\n for (let i = 0; i <= trunk.sections; i++) {\n const t = i / trunk.sections;\n if (i > 0) {\n x += random.range(-maxDrift, maxDrift);\n z += random.range(-maxDrift, maxDrift);\n }\n points.push({ position: [x, t * length, z], radius: trunk.radius * (1 + (trunk.taper - 1) * t) });\n }\n return points;\n}\n\n/**\n * Bends the leader by `gravity`, leans the Stem `tilt` radians out towards `azimuth` and moves its\n * base `offset` out along the ring. All bending happens in the vertical plane towards `azimuth`.\n */\nfunction placeStem(path: string, line: SkeletonPoint[], gravity: number, azimuth: number, tilt: number, offset: number): SkeletonBranch {\n const out: Vec3 = [cos(azimuth), 0, sin(azimuth)];\n const axis = cross([0, 1, 0], out); // rotating about it by a positive angle turns up towards `out`\n let points = line;\n\n if (gravity !== 0) {\n const sections = line.length - 1;\n const first = Math.min(sections - 1, Math.ceil(LEADER_START * sections));\n const step = (-gravity * LEADER_BEND * DEG) / (sections - first);\n // The leader turns a little more at every section; never back past vertical, never upside down.\n let bend = 0;\n points = line.slice(0, first + 1);\n for (let k = first; k < sections; k++) {\n bend = Math.min(Math.max(bend + step, -tilt), Math.PI - tilt);\n const segment = sub(line[k + 1]!.position, line[k]!.position);\n points.push({ position: add(points[k]!.position, rotate(segment, axis, bend)), radius: line[k + 1]!.radius });\n }\n }\n if (tilt !== 0) points = points.map((p) => ({ position: rotate(p.position, axis, tilt), radius: p.radius }));\n if (offset !== 0) points = points.map((p) => ({ position: add(p.position, scale(out, offset)), radius: p.radius }));\n\n return { path, parent: null, level: 0, attach: 0, direction: rotate([0, 1, 0], axis, tilt), points };\n}\n\n/** Rotates `v` about the unit `axis` by `angle` radians (Rodrigues). */\nfunction rotate(v: Vec3, axis: Vec3, angle: number): Vec3 {\n if (angle === 0) return v;\n const c = cos(angle);\n const s = sin(angle);\n return add(add(scale(v, c), scale(cross(axis, v), s)), scale(axis, dot(axis, v) * (1 - c)));\n}\n","import type { PartSeason } from '../season/profile';\nimport { cos, sin } from '../math';\nimport { createAttributes, writePart, type PartInfo } from './attributes';\nimport { branchFrames, pathLength, type Frame } from './frames';\nimport type { GeometryBuffers, GrowthWindow, SkeletonBranch, Vec3 } from './types';\nimport { BASE_SINK, FLARE_WIDTH, FLARE_ZONE } from './trunk';\nimport type { PartSway } from './wind';\nimport { add, length, lerp, normalize, scale, sub } from './vec';\n\n/** How a Stem is swept (ADR 0007): its base ring sinks below the ground, and widens by its Root Flare. */\nexport interface StemSweep {\n /** `trunk.flare` (0..1); 0 = no flare and no extra rings. */\n flare: number;\n /** Extra rings in the flare zone (`trunk.flareSections`). */\n sections: number;\n}\n\n/** One ring of a sweep: where it sits, its radius and frame, `along` (0..1, for UVs and aAlong) and the radius slope for its normals. */\ninterface Ring extends Frame {\n position: Vec3;\n radius: number;\n along: number;\n slope: number;\n}\n\n/**\n * Sweeps a ring of `sides` vertices along a branch's points, using parallel-transport\n * frames so branches in any direction get even rings, and caps the tip. A Stem (`stem` given)\n * sinks its base ring below the ground and widens by its Root Flare; its skeleton is never changed.\n */\nexport function sweepBranch(\n branch: SkeletonBranch,\n sides: number,\n random: number,\n season: PartSeason = { shift: 0, coverageRank: 0, blossomRank: 0 },\n growth: GrowthWindow = { start: 0, end: 0 },\n sway?: PartSway,\n stem?: StemSweep,\n): GeometryBuffers {\n const pts = branch.points;\n const rings = stem && stem.flare > 0 ? flaredRings(branch, stem) : plainRings(branch);\n const ringSize = sides + 1; // duplicated seam vertex for UVs\n const vertexCount = rings.length * ringSize + 1; // + tip cap centre\n const positions = new Float32Array(vertexCount * 3);\n const normals = new Float32Array(vertexCount * 3);\n const uvs = new Float32Array(vertexCount * 2);\n const indices: number[] = [];\n const attributes = createAttributes(vertexCount);\n const part: PartInfo = { level: branch.level, attach: branch.attach, random, origin: pts[0]!.position, season, growth, sway };\n\n let v = 0;\n rings.forEach(({ position, radius, tangent, normal, binormal, along, slope }, r) => {\n for (let s = 0; s <= sides; s++) {\n const angle = ((s % sides) / sides) * Math.PI * 2;\n const radial = add(scale(normal, cos(angle)), scale(binormal, sin(angle)));\n const vertex = add(position, scale(radial, radius));\n if (stem && r === 0) vertex[1] -= BASE_SINK * pts[0]!.radius;\n positions.set(vertex, v * 3);\n normals.set(normalize(add(radial, scale(tangent, slope))), v * 3);\n uvs.set([s / sides, along], v * 2);\n writePart(attributes, v, part, along, radius);\n v++;\n }\n });\n for (let r = 0; r < rings.length - 1; r++) {\n for (let s = 0; s < sides; s++) {\n const a = r * ringSize + s;\n const b = a + 1;\n const c = a + ringSize;\n const d = c + 1;\n indices.push(a, b, c, b, d, c);\n }\n }\n // Tip cap: fan around a centre vertex.\n const tip = v;\n positions.set(pts[pts.length - 1]!.position, tip * 3);\n normals.set(rings[rings.length - 1]!.tangent, tip * 3);\n uvs.set([0.5, 1], tip * 2);\n writePart(attributes, tip, part, 1);\n const lastRing = (rings.length - 1) * ringSize;\n for (let s = 0; s < sides; s++) indices.push(lastRing + s, lastRing + s + 1, tip);\n\n return { positions, normals, uvs, indices: Uint32Array.from(indices), attributes };\n}\n\n/** A ring at every skeleton point. Radius change per unit length tilts the normals of a tapered branch towards its tip. */\nfunction plainRings(branch: SkeletonBranch): Ring[] {\n const pts = branch.points;\n const frames = branchFrames(branch);\n const slope = (pts[0]!.radius - pts[pts.length - 1]!.radius) / Math.max(pathLength(branch), 1e-6);\n return pts.map(({ position, radius }, r) => ({ position, radius, ...frames[r]!, along: r / (pts.length - 1), slope }));\n}\n\n/**\n * A Stem's rings with its Root Flare: `sections` extra rings in the bottom {@link FLARE_ZONE} of its\n * length, closer together towards the base, and every ring in that zone widened by a multiplier that\n * eases from 1 at the top of the zone to 1 + {@link FLARE_WIDTH} × flare at the base (quadratic, so\n * the flare leaves the trunk without a crease). Normals follow the flared surface.\n */\nfunction flaredRings(branch: SkeletonBranch, { flare, sections }: StemSweep): Ring[] {\n const pts = branch.points;\n const total = Math.max(pathLength(branch), 1e-6);\n const zone = FLARE_ZONE * total;\n const slope = (pts[0]!.radius - pts[pts.length - 1]!.radius) / total;\n\n // The skeleton points plus the extra rings, each with its distance from the base.\n const extra = Array.from({ length: sections }, (_, k) => zone * ((k + 1) / sections) * ((k + 1) / sections));\n const points: { position: Vec3; radius: number; along: number; distance: number }[] = [];\n let walked = 0;\n for (let i = 0; i < pts.length; i++) {\n const a = pts[i]!;\n points.push({ ...a, along: i / (pts.length - 1), distance: walked });\n if (i === pts.length - 1) break;\n const b = pts[i + 1]!;\n const segment = length(sub(b.position, a.position));\n const gap = 1e-6 * total; // an extra ring on (or next to) a skeleton point is left out\n for (const d of extra) {\n if (d > walked + gap && d < walked + segment - gap) {\n const f = (d - walked) / segment;\n points.push({\n position: lerp(a.position, b.position, f),\n radius: a.radius + (b.radius - a.radius) * f,\n along: (i + f) / (pts.length - 1),\n distance: d,\n });\n }\n }\n walked += segment;\n }\n\n const frames = branchFrames({ ...branch, points });\n const width = FLARE_WIDTH * flare;\n return points.map(({ position, radius, along, distance }, r) => {\n const u = Math.max(1 - distance / zone, 0); // 1 at the base, 0 from the top of the zone up\n const multiplier = 1 + width * u * u;\n // d(radius × multiplier) / d(distance), negated: the trunk's taper plus the flare's own widening.\n return { position, radius: radius * multiplier, ...frames[r]!, along, slope: slope * multiplier + (radius * 2 * width * u) / zone };\n });\n}\n\n/** Concatenates geometry buffers into one (indices are offset). */\nexport function mergeBuffers(parts: GeometryBuffers[]): GeometryBuffers {\n const vertexCount = parts.reduce((n, p) => n + p.positions.length / 3, 0);\n const indexCount = parts.reduce((n, p) => n + p.indices.length, 0);\n const out: GeometryBuffers = {\n positions: new Float32Array(vertexCount * 3),\n normals: new Float32Array(vertexCount * 3),\n uvs: new Float32Array(vertexCount * 2),\n indices: new Uint32Array(indexCount),\n attributes: createAttributes(vertexCount),\n };\n let v = 0;\n let i = 0;\n for (const part of parts) {\n out.positions.set(part.positions, v * 3);\n out.normals.set(part.normals, v * 3);\n out.uvs.set(part.uvs, v * 2);\n for (const [name, attribute] of Object.entries(out.attributes)) {\n attribute.array.set(part.attributes[name]!.array, v * attribute.itemSize);\n }\n for (let k = 0; k < part.indices.length; k++) out.indices[i + k] = part.indices[k]! + v;\n v += part.positions.length / 3;\n i += part.indices.length;\n }\n return out;\n}\n","import { crownDistance, type CrownVolume } from './crown';\nimport type { GeometryBuffers } from './types';\n\n/**\n * Structural Occlusion (GLOSSARY): how open each vertex is to the sky, from the tree's own shape.\n * 0 = fully occluded, 1 = open. A deterministic mix (a product) of two terms, both measured on the fully\n * grown tree with every leaf on it (so it is the same in every Season and at every Growth):\n *\n * - crown depth: how deep the vertex sits inside the Crown Volume (`1 - crownDistance`, 0 at the shell);\n * - leaf cover above: the leaf area above the vertex, from a coarse voxel grid of leaf area, summed\n * upwards (as a leaf area index) and turned into openness, which falls from 1 towards FLOOR as it grows.\n *\n * No randomness and no ray tracing; only + - * / and sqrt, so the same numbers on every machine.\n * The Definition's `strength` is not used here: the material mixes it in (`aoNode`).\n */\n\n/** Grid cells along the largest extent of the leaves. */\nconst CELLS = 12;\n/** Empty cells around the leaves, so the grid's edge (and the horizontal blur's spill) reads as open sky. */\nconst PAD = 2;\n/** How fast the cover above darkens: openness `FLOOR + (1 - FLOOR) / (1 + COVER × leaf area per ground area above)`. */\nconst COVER = 0.3;\n/** The openness under an endless canopy: light still bounces in from the sides and the ground. */\nconst FLOOR = 0.3;\n/** How much darker the very centre of the Crown Volume is than its shell (before the cover above). */\nconst DEPTH = 0.4;\n\n/**\n * Adds `aOcclusion` (1 float per vertex) to each of `parts` (wood, leaves, Fruit). A tree without leaves\n * has no crown to hide under: every vertex is open (1).\n */\nexport function bakeOcclusion(parts: readonly GeometryBuffers[], leaves: GeometryBuffers, crown: CrownVolume): void {\n const cover = leaves.indices.length > 0 ? coverAbove(leaves) : null;\n for (const part of parts) {\n const p = part.positions;\n const array = new Float32Array(p.length / 3);\n if (cover) {\n const point: [number, number, number] = [0, 0, 0];\n for (let v = 0; v < array.length; v++) {\n point[0] = p[v * 3]!;\n point[1] = p[v * 3 + 1]!;\n point[2] = p[v * 3 + 2]!;\n const depth = Math.max(0, 1 - crownDistance(crown, point));\n array[v] = (1 - DEPTH * depth) * (FLOOR + (1 - FLOOR) / (1 + COVER * cover(point)));\n }\n } else {\n array.fill(1);\n }\n part.attributes.aOcclusion = { array, itemSize: 1 };\n }\n}\n\n/**\n * The leaf area above a point per unit of ground area (a leaf area index, 0 above the crown), as a\n * function. Leaf triangles are binned by centroid into a grid of cubes, blurred a little sideways (the\n * sky is a hemisphere, not a point overhead), summed from the top down and sampled trilinearly.\n */\nfunction coverAbove(leaves: GeometryBuffers): (p: readonly number[]) => number {\n const p = leaves.positions;\n const min = [Infinity, Infinity, Infinity];\n const max = [-Infinity, -Infinity, -Infinity];\n for (let o = 0; o < p.length; o += 3) {\n for (let i = 0; i < 3; i++) {\n min[i] = Math.min(min[i]!, p[o + i]!);\n max[i] = Math.max(max[i]!, p[o + i]!);\n }\n }\n const size = Math.max(max[0]! - min[0]!, max[1]! - min[1]!, max[2]! - min[2]!, 1e-6) / CELLS;\n const origin = min.map((m) => m - PAD * size);\n const [nx, ny, nz] = [0, 1, 2].map((i) => Math.ceil((max[i]! - min[i]!) / size) + 1 + 2 * PAD) as [number, number, number];\n const at = (x: number, y: number, z: number) => (y * nz + z) * nx + x;\n const cell = (value: number, i: number, n: number) => Math.min(n - 1, Math.max(0, Math.floor((value - origin[i]!) / size)));\n\n // Leaf area per cell, in units of a cell's ground area (so a sum over a column is a leaf area index).\n let area = new Float64Array(nx * ny * nz);\n const idx = leaves.indices;\n for (let t = 0; t < idx.length; t += 3) {\n const a = idx[t]! * 3;\n const b = idx[t + 1]! * 3;\n const c = idx[t + 2]! * 3;\n const u = [p[b]! - p[a]!, p[b + 1]! - p[a + 1]!, p[b + 2]! - p[a + 2]!];\n const w = [p[c]! - p[a]!, p[c + 1]! - p[a + 1]!, p[c + 2]! - p[a + 2]!];\n const cx = u[1]! * w[2]! - u[2]! * w[1]!;\n const cy = u[2]! * w[0]! - u[0]! * w[2]!;\n const cz = u[0]! * w[1]! - u[1]! * w[0]!;\n const triangle = Math.sqrt(cx * cx + cy * cy + cz * cz) / 2;\n const centre = [0, 1, 2].map((i) => (p[a + i]! + p[b + i]! + p[c + i]!) / 3);\n area[at(cell(centre[0]!, 0, nx), cell(centre[1]!, 1, ny), cell(centre[2]!, 2, nz))]! += triangle / (size * size);\n }\n // Blur sideways (1 2 1 along x, then along z).\n for (const [dx, dz] of [\n [1, 0],\n [0, 1],\n ] as const) {\n const blurred = new Float64Array(area.length);\n for (let y = 0; y < ny; y++) {\n for (let z = 0; z < nz; z++) {\n for (let x = 0; x < nx; x++) {\n const here = area[at(x, y, z)]!;\n const before = x - dx >= 0 && z - dz >= 0 ? area[at(x - dx, y, z - dz)]! : 0;\n const after = x + dx < nx && z + dz < nz ? area[at(x + dx, y, z + dz)]! : 0;\n blurred[at(x, y, z)] = (before + 2 * here + after) / 4;\n }\n }\n }\n area = blurred;\n }\n // Cover at each cell centre: everything above it plus half of its own cell.\n const above = new Float64Array(area.length);\n for (let z = 0; z < nz; z++) {\n for (let x = 0; x < nx; x++) {\n let sum = 0;\n for (let y = ny - 1; y >= 0; y--) {\n const own = area[at(x, y, z)]!;\n above[at(x, y, z)] = sum + own / 2;\n sum += own;\n }\n }\n }\n // Trilinear between cell centres; clamped at the grid's edges (below the grid: the whole column above).\n return (q) => {\n const f = [0, 1, 2].map((i) => (q[i]! - origin[i]!) / size - 0.5);\n const n = [nx, ny, nz];\n const lo: number[] = [];\n const t: number[] = [];\n for (let i = 0; i < 3; i++) {\n const g = Math.min(n[i]! - 1, Math.max(0, f[i]!));\n lo[i] = Math.min(n[i]! - 2, Math.floor(g));\n t[i] = g - lo[i]!;\n }\n let value = 0;\n for (let k = 0; k < 8; k++) {\n const x = lo[0]! + (k & 1);\n const y = lo[1]! + ((k >> 1) & 1);\n const z = lo[2]! + ((k >> 2) & 1);\n const weight = (k & 1 ? t[0]! : 1 - t[0]!) * ((k >> 1) & 1 ? t[1]! : 1 - t[1]!) * ((k >> 2) & 1 ? t[2]! : 1 - t[2]!);\n value += weight * above[at(x, y, z)]!;\n }\n return value;\n };\n}\n","import { cos, hypot3, pow, sin } from '../math';\nimport type { RootsDefinition, TreeDefinition } from '../definition';\nimport type { Random } from '../random';\nimport { pathLength } from './frames';\nimport type { SkeletonBranch, SkeletonRoot, Vec3 } from './types';\n\nconst DEG = Math.PI / 180;\n/** Sections along a Root while `roots.sections` is absent. */\nexport const ROOT_SECTIONS = 4;\n/** Seed range of each Root's place around its Stem: ± this fraction of the gap between Roots. */\nconst ROOT_JITTER = 0.25;\n/** Where a Root starts: this fraction of the trunk radius out from the Stem's centre, inside the Root Flare. */\nconst ROOT_START_OUT = 0.5;\n/** ... and this many of the Root's own radii above the ground (it sits on the ground there), so its top blends into the flare. */\nconst ROOT_START_UP = 1;\n/** How far `bend` = 1 turns a Root sideways per section (at most), radians. */\nconst ROOT_BEND_TURN = 0.5;\n/** A Root tapers as (1 − t)^this along its length (t = 0 base .. 1 tip): below 1 it stays thick longer, then comes to a point. */\nconst ROOT_TAPER = 0.6;\n/** A Root's tip ends at least this many of its base radii below the ground (it curves down to get there). */\nconst ROOT_TIP_DEPTH = 1;\n\n/** Sides around a Root while `roots.sides` is absent: about two thirds of the trunk's. */\nexport const rootSides = (definition: TreeDefinition): number =>\n definition.roots?.sides ?? Math.max(3, Math.round((definition.trunk.sides * 2) / 3));\n\n/** Where around a Stem its Roots go (see `rootArc`). */\ninterface RootArc {\n out: readonly [number, number];\n from: number;\n width: number;\n}\n\n/**\n * The part of the circle around a Stem its Roots are spread evenly over: azimuths `from` .. `from` +\n * `width` radians, measured from the horizontal unit vector `out` ([x, z]) round towards +z. A single\n * Stem's Roots go all the way round, starting at the Seed's `turn`. Of several Stems (standing in a\n * ring round the origin), each one's Roots cover only the half-circle facing `out`, away from the ring\n * centre, so they don't pile up between the Stems.\n */\nfunction rootArc(definition: TreeDefinition, stem: SkeletonBranch, turn: number): RootArc {\n const [x, , z] = stem.points[0]!.position;\n const away = hypot3(x, 0, z);\n if ((definition.trunk.stems ?? 1) <= 1 || away === 0) return { out: [1, 0], from: turn, width: Math.PI * 2 };\n return { out: [x / away, z / away], from: -Math.PI / 2, width: Math.PI };\n}\n\n/** The horizontal unit vector ([x, z]) at `azimuth` in `arc`. */\nfunction toward(arc: RootArc, azimuth: number): [number, number] {\n const [c, s] = [cos(azimuth), sin(azimuth)];\n const [ox, oz] = arc.out;\n return [ox * c - oz * s, oz * c + ox * s];\n}\n\n/**\n * Grows the Roots (ADR 0007) of every Stem in `stems` (the Stems left after the Sculpt pass, as\n * they are after it: a deleted Stem has none, a moved one keeps them at its base, a scaled one\n * scales them with its length). Stem `<p>`'s Roots are `<p>/r0`, `<p>/r1`, ...; Root i draws only\n * from `random.fork('roots/<p>/<i>')` and the Stem's turn from `random.fork('roots/<p>')`, so Roots\n * never change the wood, leaves or Fruit, and one Stem's Sculpts never change another's Roots.\n */\nexport function growRoots(definition: TreeDefinition, stems: SkeletonBranch[], random: Random): SkeletonRoot[] {\n const roots = definition.roots;\n if (!roots) return [];\n return stems.flatMap((stem) => {\n const turn = random.fork(`roots/${stem.path}`).range(0, Math.PI * 2);\n const arc = rootArc(definition, stem, turn);\n return Array.from({ length: roots.count }, (_, i) => {\n const r = random.fork(`roots/${stem.path}/${i}`);\n const azimuth = arc.from + ((i + 0.5 + r.range(-ROOT_JITTER, ROOT_JITTER)) / roots.count) * arc.width;\n return growRoot(`${stem.path}/r${i}`, stem, roots, arc, azimuth, r);\n });\n });\n}\n\n/**\n * One Root: from just inside the Stem's Root Flare, slightly above the Stem's base (the ground), it runs out towards\n * `azimuth` (in `arc`) and down at `angle`, turns sideways by up to `bend` per section, and tapers to a point.\n * If the dive alone would not take its tip below the ground, it curves down (more towards the tip) until it does.\n */\nfunction growRoot(path: string, stem: SkeletonBranch, roots: RootsDefinition, arc: RootArc, azimuth: number, r: Random): SkeletonRoot {\n const base = stem.points[0]!;\n const sections = roots.sections ?? ROOT_SECTIONS;\n const length = pathLength(stem) * roots.length * (1 + r.range(-roots.lengthVariation, roots.lengthVariation));\n const radius = base.radius * roots.radius;\n const step = length / sections;\n const pitch = roots.angle * DEG;\n\n const [outX, outZ] = toward(arc, azimuth);\n let heading = azimuth;\n let position: Vec3 = [\n base.position[0] + outX * base.radius * ROOT_START_OUT,\n base.position[1] + radius * ROOT_START_UP,\n base.position[2] + outZ * base.radius * ROOT_START_OUT,\n ];\n const positions: Vec3[] = [position];\n for (let s = 0; s < sections; s++) {\n const [x, z] = toward(arc, heading);\n position = [position[0] + step * cos(pitch) * x, position[1] - step * sin(pitch), position[2] + step * cos(pitch) * z];\n positions.push(position);\n heading += r.range(-1, 1) * roots.bend * ROOT_BEND_TURN;\n }\n\n const drop = Math.max(0, positions[sections]![1] + ROOT_TIP_DEPTH * radius);\n const points = positions.map(([x, y, z], s) => {\n const t = s / sections;\n return { position: [x, y - drop * t * t, z] as Vec3, radius: radius * pow(1 - t, ROOT_TAPER) };\n });\n const direction: Vec3 = [cos(pitch) * outX, -sin(pitch), cos(pitch) * outZ];\n return { path, parent: stem.path, level: 0, attach: 0, direction, points };\n}\n","import { cos, sin } from '../math';\nimport type { Sculpt, TreeDefinition } from '../definition';\nimport { seedRandom } from '../random';\nimport type { SkeletonBranch, SkeletonLeaf, Vec3 } from './types';\nimport { add, scale, sub } from './vec';\n\n/**\n * The Sculpt pass (ADR 0003): hand edits stored in the Definition, applied after the procedural\n * skeleton is grown and before leaves, Growth timing, Wind weights and meshes are derived from it.\n * So a sculpted part still grows, changes with the Season and sways like any other.\n *\n * A Sculpt only applies on the Seed it was made on; every other Seed ignores it. Sculpts apply in\n * Definition order. A Sculpt whose path does not exist (any more) for this Seed is skipped.\n */\nexport function sculptsFor(definition: TreeDefinition, seed: number): Sculpt[] {\n return definition.sculpts.filter((s) => s.seed === seed);\n}\n\n/** True if `path` is `root` or grows from it (its descendants). */\nexport const inSubtree = (path: string, root: string): boolean => path === root || path.startsWith(`${root}.`);\n\n/**\n * Applies the branch Sculpts to the skeleton branches (returns a new array, paths unchanged):\n * - `delete` drops the branch and everything growing from it;\n * - `move` rotates (Euler XYZ, radians, three.js convention, in tree space) and scales the branch\n * and everything growing from it about the branch base. `scale` scales lengths; radii stay.\n */\nexport function sculptBranches(branches: SkeletonBranch[], sculpts: Sculpt[]): SkeletonBranch[] {\n let out = branches;\n for (const sculpt of sculpts) {\n if (sculpt.action === 'delete') {\n out = out.filter((b) => !inSubtree(b.path, sculpt.path));\n } else if (sculpt.action === 'move') {\n const root = out.find((b) => b.path === sculpt.path);\n if (!root) continue;\n const base = root.points[0]!.position;\n const rotate = eulerXYZ(sculpt.rotation);\n const move = (p: Vec3) => add(base, rotate(scale(sub(p, base), sculpt.scale)));\n out = out.map((b) =>\n inSubtree(b.path, sculpt.path)\n ? {\n ...b,\n direction: rotate(b.direction),\n points: b.points.map((p) => ({ position: move(p.position), radius: p.radius })),\n }\n : b,\n );\n }\n }\n return out;\n}\n\n/**\n * Applies the `leaves` Sculpts (painting): each sets the coverage (0..1) of a branch and everything\n * growing from it; a later Sculpt on a sub-branch overrides it there. A leaf is kept while its own\n * stable random number (from the Seed and leaf id) is below its coverage, so painting more coverage\n * only ever adds leaves. Season coverage then applies on top of the kept leaves as usual.\n */\nexport function sculptLeaves(leaves: SkeletonLeaf[], sculpts: Sculpt[], seed: number): SkeletonLeaf[] {\n const painted = sculpts.filter((s) => s.action === 'leaves');\n if (painted.length === 0) return leaves;\n return leaves.filter((leaf) => {\n let coverage = 1;\n for (const s of painted) if (inSubtree(leaf.branch, s.path)) coverage = s.coverage;\n return seedRandom(seed, `sculpt/${leaf.id}`) < coverage;\n });\n}\n\n/** The rotation of a three.js `Euler(x, y, z, 'XYZ')` (matrix Rx * Ry * Rz) as a function on vectors. */\nfunction eulerXYZ([x, y, z]: Vec3): (v: Vec3) => Vec3 {\n const [a, b, c, d, e, f] = [cos(x), sin(x), cos(y), sin(y), cos(z), sin(z)];\n const [ae, af, be, bf] = [a * e, a * f, b * e, b * f];\n const m = [c * e, -c * f, d, af + be * d, ae - bf * d, -b * c, bf - ae * d, be + af * d, a * c];\n return ([vx, vy, vz]) => [\n m[0]! * vx + m[1]! * vy + m[2]! * vz,\n m[3]! * vx + m[4]! * vy + m[5]! * vz,\n m[6]! * vx + m[7]! * vy + m[8]! * vz,\n ];\n}\n","import type { TreeDefinition } from '../definition';\nimport { createRandom, hashBytes, seedRandom } from '../random';\nimport { woodSeasonAttribute } from '../season/profile';\nimport { buildBranches } from './branches';\nimport { crownVolume } from './crown';\nimport { fruitGeometry, fruitGrowth, placeFruit } from './fruit';\nimport { growthTiming } from './growth';\nimport { solidLeafGeometry } from './leaf-shapes';\nimport { leafGeometry, placeLeaves } from './leaves';\nimport { mergeBuffers, sweepBranch } from './mesh';\nimport { bakeOcclusion } from './occlusion';\nimport { growRoots, rootSides } from './roots';\nimport { sculptBranches, sculptLeaves, sculptsFor } from './sculpt';\nimport { buildStems, FLARE_SECTIONS } from './trunk';\nimport { branchSway, writeTrunkSway } from './wind';\nimport type { GeometryBuffers, TreeData, TreeSkeleton } from './types';\n\nexport { growthTiming } from './growth';\nexport { crownDistance, crownNormal, type CrownVolume } from './crown';\nexport type { GrowthTiming, GrowthWindow, GeometryBuffers, TreeAttributes, VertexAttribute, SkeletonBranch, SkeletonFruit, SkeletonRoot, SkeletonLeaf, SkeletonPoint, TreeData, TreeSkeleton, Vec3 } from './types';\n\n/**\n * The Generator: a pure function from a (parsed) Tree Definition and a Seed to tree data.\n * No three.js, no GPU, no globals; runs in Node. Same input, same output, on every machine.\n *\n * Each part of the tree draws from its own `random.fork(<part>)` stream so that adding\n * a new part never shifts the numbers of an existing one.\n */\nexport function generateTree(definition: TreeDefinition, seed: number): TreeData {\n const random = createRandom(seed);\n const stems = buildStems(definition, random);\n const sculpts = sculptsFor(definition, seed);\n const branches = sculptBranches([...stems, ...buildBranches(definition, stems, random.fork('branches'))], sculpts);\n const sidesOf = (level: number) => (level === 0 ? definition.trunk.sides : definition.branches[level - 1]!.sides);\n const leaves = sculptLeaves(placeLeaves(definition, branches, random.fork('leaves')), sculpts, seed);\n const fruit = placeFruit(definition, branches, random.fork('fruit'));\n // Roots grow from the Stems the Sculpt pass left, as it left them (ADR 0007).\n const roots = growRoots(\n definition,\n branches.filter((b) => b.parent === null),\n random,\n );\n const partGrowth = growthTiming(definition, seed, branches, leaves);\n const growth = {\n ...partGrowth,\n fruit: fruitGrowth(seed, fruit, new Map(branches.map((b, i) => [b.path, partGrowth.branches[i]!]))),\n // Like the trunk: there from Growth 0, scaled with the whole tree.\n roots: roots.map(() => ({ start: 0, end: 0 })),\n };\n const stemSweep = { flare: definition.trunk.flare ?? 0, sections: definition.trunk.flareSections ?? FLARE_SECTIONS };\n const sway = branchSway(branches, definition.branches.length);\n const woodSeason = woodSeasonAttribute(seed, definition.variation);\n // Roots come after every branch, so the rest of the wood buffer is the same with or without them.\n // They get no branch sway and no flutter.\n const wood = mergeBuffers([\n ...branches.map((b, i) =>\n sweepBranch(\n b,\n sidesOf(b.level),\n seedRandom(seed, b.path),\n woodSeason,\n growth.branches[i],\n sway.get(b.path),\n b.parent === null ? stemSweep : undefined,\n ),\n ),\n ...roots.map((root, i) => sweepBranch(root, rootSides(definition), seedRandom(seed, root.path), woodSeason, growth.roots[i])),\n ]);\n const leafBuffers =\n definition.leaves.shape === 'card'\n ? leafGeometry(leaves, definition.branches.length + 1, seed, definition.variation, growth.leaves, sway)\n : solidLeafGeometry(leaves, definition.leaves.shape, definition.branches.length + 1, seed, definition.variation, growth.leaves, sway);\n const fruitBuffers = fruitGeometry(\n fruit,\n definition.fruit ?? { type: 'round' },\n definition.branches.length + 2,\n seed,\n definition.variation,\n growth.fruit,\n sway,\n );\n const skeleton = { branches, leaves, fruit, roots };\n writeTrunkSway(wood, trunkHeight(skeleton));\n writeTrunkSway(leafBuffers, trunkHeight(skeleton));\n writeTrunkSway(fruitBuffers, trunkHeight(skeleton));\n // The Crown Volume sits next to the geometry, not in it: the buffers and their hash are unchanged.\n const crown = crownVolume(leafBuffers.positions, branches);\n // Structural Occlusion (ADR 0008): only with `materials.occlusion`, so without it the buffers are as before.\n if (definition.materials.occlusion) bakeOcclusion([wood, leafBuffers, fruitBuffers], leafBuffers, crown);\n return { seed, skeleton, wood, leaves: leafBuffers, fruit: fruitBuffers, growth, crown };\n}\n\n/**\n * Height of the tallest (possibly Sculpted) Stem: the scale of a tree's Wind sway. For an upright\n * trunk that is its tip. A Sculpt may delete every Stem (an empty tree, nothing sways); it is then 1.\n */\nexport function trunkHeight(skeleton: Pick<TreeSkeleton, 'branches'>): number {\n const stems = skeleton.branches.filter((b) => b.parent === null);\n if (stems.length === 0) return 1;\n return Math.max(...stems.flatMap((stem) => stem.points.map((p) => p.position[1])));\n}\n\n/** Stable 32-bit hash (hex) of the generated geometry buffers, for determinism checks. */\nexport function hashGeometry(geometry: GeometryBuffers): string {\n return hex(hashBuffers(geometry));\n}\n\n/** Stable hash of a tree's generated geometry (wood, leaves and, if any, Fruit). */\nexport function hashTreeData(data: TreeData): string {\n const h = hashBuffers(data.leaves, hashBuffers(data.wood));\n // A tree without Fruit hashes as before Fruit existed.\n return hex(data.fruit.positions.length > 0 ? hashBuffers(data.fruit, h) : h);\n}\n\nfunction hashBuffers(geometry: GeometryBuffers, h?: number): number {\n const arrays = [geometry.positions, geometry.normals, geometry.uvs, geometry.colors, geometry.indices];\n for (const name of Object.keys(geometry.attributes).sort()) {\n arrays.push(geometry.attributes[name]!.array);\n }\n for (const array of arrays) {\n if (array) h = hashBytes(new Uint8Array(array.buffer, array.byteOffset, array.byteLength), h);\n }\n return h!;\n}\n\nconst hex = (h: number) => h.toString(16).padStart(8, '0');\n","import type { GeometryBuffers } from '../generator';\n\n/**\n * The Growth model, one spec with two backends: `growPositions` (CPU, here) and `growthPosition`\n * (TSL, `./tsl.ts`). Keep them in step. Per vertex, at Growth `g`:\n *\n * 1. thicken: move the vertex towards its part's centre line, keeping `thickness(g)` of its radius\n * (`aGrowth.z`, along the vertex normal);\n * 2. sprout: scale the part about its base point (`aOrigin`) by `partProgress(g, start, end)`\n * (`aGrowth.xy`), so a part grows out of a point on its (already grown) parent;\n * 3. size: scale the whole tree about its base (local origin) by `treeScale(g)`.\n *\n * Every step is written as `x - offset * (1 - factor)`, so at Growth 1 the positions are exactly\n * the generated ones: a tree at Growth 1 is a normal static tree.\n */\n\n/** Size of the whole tree at Growth 0 (sapling), relative to fully grown. */\nexport const SAPLING_SCALE = 0.2;\n/** Branch thickness at Growth 0, relative to the size-scaled thickness when fully grown. */\nexport const SAPLING_THICKNESS = 0.4;\n/** Smallest window width, so parts with `start == end` (the trunk) are simply grown. */\nexport const MIN_WINDOW = 1e-5;\n\nexport const treeScale = (growth: number): number => SAPLING_SCALE + (1 - SAPLING_SCALE) * growth;\nexport const thickness = (growth: number): number => SAPLING_THICKNESS + (1 - SAPLING_THICKNESS) * growth;\n\n/** How far one part has sprouted (0 = not yet, 1 = full size), eased; 1 from `end` on. */\nexport function partProgress(growth: number, start: number, end: number): number {\n const p = Math.min(Math.max((growth - end) / Math.max(end - start, MIN_WINDOW) + 1, 0), 1);\n return p * p * (3 - 2 * p);\n}\n\n/** Clamps a Growth value to 0..1 (NaN becomes 1, fully grown). */\nexport function clampGrowth(growth: number): number {\n return Number.isNaN(growth) ? 1 : Math.min(Math.max(growth, 0), 1);\n}\n\n/**\n * Vertex positions of generated geometry at a given Growth, on the CPU (for baking a tree and\n * for tests; at runtime the same model runs in TSL). Returns a new array.\n */\nexport function growPositions(buffers: GeometryBuffers, growth: number): Float32Array {\n const g = clampGrowth(growth);\n const { positions, normals } = buffers;\n const { aOrigin, aGrowth } = buffers.attributes;\n const out = new Float32Array(positions.length);\n const scale = treeScale(g);\n const thin = 1 - thickness(g);\n for (let v = 0; v < positions.length / 3; v++) {\n const [start, end, radius] = [aGrowth.array[v * 3]!, aGrowth.array[v * 3 + 1]!, aGrowth.array[v * 3 + 2]!];\n const shrink = 1 - partProgress(g, start, end);\n for (let k = 0; k < 3; k++) {\n const i = v * 3 + k;\n const thick = positions[i]! - normals[i]! * radius * thin;\n const sprouted = thick - (thick - aOrigin.array[i]!) * shrink;\n out[i] = sprouted - sprouted * (1 - scale);\n }\n }\n return out;\n}\n","import { attribute, float, normalGeometry, positionLocal } from 'three/tsl';\nimport type { Node } from 'three/webgpu';\nimport { MIN_WINDOW, SAPLING_SCALE, SAPLING_THICKNESS } from './evaluate';\n\n// The TSL twins of the helpers in `./evaluate.ts`, step for step.\n\n/** Size of the whole tree at Growth `g` (twin of `treeScale`): the scale `growthPosition` gives the tree. */\nexport const growthScale = (g: Node<'float'>): Node<'float'> => float(SAPLING_SCALE).add(float(1 - SAPLING_SCALE).mul(g));\n\n/** Branch thickness at Growth `g` (twin of `thickness`). */\nconst thickness = (g: Node<'float'>): Node<'float'> => float(SAPLING_THICKNESS).add(float(1 - SAPLING_THICKNESS).mul(g));\n\n/** How far one part has sprouted, eased (twin of `partProgress`). */\nfunction partProgress(g: Node<'float'>, start: Node<'float'>, end: Node<'float'>): Node<'float'> {\n const p = g.sub(end).div(end.sub(start).max(MIN_WINDOW)).add(1).clamp(0, 1);\n return p.mul(p).mul(float(3).sub(p.mul(2)));\n}\n\n/**\n * Growth in TSL: the vertex position of a tree part at Growth `growth` (a float node, usually the\n * tree's Growth uniform; a Forest can pass a per-instance attribute instead). Same model and steps\n * as `growPositions` (see `./evaluate.ts`), driven by the Generator's `aGrowth` and `aOrigin` attributes.\n *\n * `position` is the input position (default `positionLocal`). To compose with other vertex effects,\n * feed this node into them, e.g. `material.positionNode = windPosition(growthPosition(uGrowth))`:\n * Growth first, so the rest acts on the grown tree.\n */\nexport function growthPosition(growth: Node<'float'>, position: Node<'vec3'> = positionLocal): Node<'vec3'> {\n const g = float(growth).clamp(0, 1);\n const data = attribute<'vec3'>('aGrowth', 'vec3');\n const origin = attribute<'vec3'>('aOrigin', 'vec3');\n const [start, end, radius] = [data.x, data.y, data.z];\n\n const scale = growthScale(g);\n const thin = float(1).sub(thickness(g));\n const shrink = float(1).sub(partProgress(g, start, end));\n\n const thick = position.sub(normalGeometry.mul(radius).mul(thin));\n const sprouted = thick.sub(thick.sub(origin).mul(shrink));\n return sprouted.sub(sprouted.mul(float(1).sub(scale)));\n}\n","import { color, float, mix, positionGeometry, smoothstep, varying } from 'three/tsl';\nimport type { Node } from 'three/webgpu';\nimport type { GroundTintDefinition } from '../definition';\nimport { growthPosition } from '../growth';\n\n/**\n * Ground Tint (GLOSSARY): how far the bark blends towards `tint.color` at tree-space height `y`\n * (on the grown tree): `strength` at and below the ground, easing (smoothstep) to 0 at `height`.\n */\nexport function groundTintAmount(tint: GroundTintDefinition, y: number): number {\n const t = Math.min(Math.max(y / tint.height, 0), 1);\n return tint.strength * (1 - t * t * (3 - 2 * t));\n}\n\n/**\n * The TSL twin of {@link groundTintAmount}, applied to a bark colour node: `mix(bark, tint, amount)`.\n * The height is the grown tree-space position (Growth `growth`, before Wind), from the vertex stage.\n */\nexport function applyGroundTint(bark: Node<'vec3'> | Node<'color'>, tint: GroundTintDefinition, growth: Node<'float'>): Node<'vec3'> {\n const y = varying(growthPosition(growth, positionGeometry).y);\n const amount = float(1).sub(smoothstep(0, tint.height, y)).mul(tint.strength);\n return mix(bark, color(tint.color), amount);\n}\n","import { NoColorSpace, RepeatWrapping, SRGBColorSpace, Texture, TextureLoader } from 'three/webgpu';\n\n/**\n * Where the package's own textures live, relative to this module: `./textures/` next to the\n * built `dist/index.js` (copied from `assets/` by the build), `../../assets/textures/` from\n * `src/textures/` in dev and tests. Set by `define` in vite.config.ts.\n */\ndeclare const __TREE_TEXTURES_DIR__: string;\n// Unbundled (e.g. Playwright specs importing the sources in Node) there is no define: the source layout.\nconst TEXTURES_DIR: string = typeof __TREE_TEXTURES_DIR__ === 'string' ? __TREE_TEXTURES_DIR__ : '../../assets/textures/';\n// Not written as `new URL('<literal>', import.meta.url)` on purpose: app bundlers (Vite, webpack)\n// rewrite that pattern as an asset import, but this is a directory the app may host elsewhere.\nconst MODULE_URL: string = import.meta.url;\n\n/**\n * The URL of the package's bundled textures (the realistic Style's bark and leaf cards), as\n * shipped in `dist/textures/`. Relative texture URLs in a Definition resolve against it unless\n * the app sets its own `basePath`.\n */\nexport const DEFAULT_TEXTURE_BASE_PATH: string = new URL(TEXTURES_DIR, MODULE_URL).href;\n\n/**\n * Where tree textures are loaded from. Texture URLs in a Tree Definition (`materials.bark.map`,\n * `materials.bark.normalMap`, `materials.leaf.map`) are either absolute (`https://…`, `/…`,\n * `data:`, `blob:`), used as they are, or relative (`realistic/bark.png`), resolved against\n * `basePath`.\n */\nexport interface TextureOptions {\n /**\n * Base path or URL for relative texture URLs, e.g. `'https://cdn.example.com/tree-textures/'`\n * after copying `node_modules/@casmo/tree.js/dist/textures/` there. Default: the package's own\n * `dist/textures/` (`DEFAULT_TEXTURE_BASE_PATH`).\n */\n basePath?: string;\n /** Per-texture overrides, keyed by the URL as written in the Definition (e.g. `'realistic/bark.png'`). */\n urls?: Record<string, string>;\n}\n\nlet globalOptions: TextureOptions = {};\n\n/**\n * Sets the app-wide texture options (base path / URL overrides) used by every tree created\n * afterwards. Options passed to `createTree(…, { textures })` take precedence.\n */\nexport function setTextureOptions(options: TextureOptions): void {\n globalOptions = { ...options, urls: { ...options.urls } };\n}\n\n/** The app-wide texture options set with `setTextureOptions`. */\nexport function getTextureOptions(): TextureOptions {\n return { ...globalOptions, urls: { ...globalOptions.urls } };\n}\n\nconst ABSOLUTE = /^([a-z][a-z\\d+.-]*:|\\/)/i;\n\n/** The URL a Definition's texture URL is loaded from, after URL overrides and the base path. */\nexport function resolveTextureUrl(url: string, options: TextureOptions = {}): string {\n const override = options.urls?.[url] ?? globalOptions.urls?.[url];\n if (override !== undefined) return override;\n if (ABSOLUTE.test(url)) return url;\n const base = options.basePath ?? globalOptions.basePath ?? DEFAULT_TEXTURE_BASE_PATH;\n return (base === '' || base.endsWith('/') ? base : `${base}/`) + url.replace(/^\\.\\//, '');\n}\n\n/** What a texture holds: colour (sRGB) or data such as a normal map (linear). */\nexport type TextureKind = 'color' | 'data';\n\nconst cache = new Map<string, Texture>();\nconst pending = new WeakMap<Texture, Promise<void>>();\n\n/**\n * Loads a texture from an already resolved URL. Textures are shared: the same URL and kind\n * give the same `Texture` (trees don't dispose them). `texture.name` is the URL. The image\n * loads asynchronously; `textureReady(texture)` resolves once it is there. Outside a browser\n * (no DOM, e.g. Node tests) the texture is created without an image.\n */\nexport function loadTexture(url: string, kind: TextureKind): Texture {\n const key = `${kind} ${url}`;\n const cached = cache.get(key);\n if (cached) return cached;\n\n let texture: Texture;\n let ready: Promise<void>;\n if (typeof document === 'undefined') {\n texture = new Texture();\n ready = Promise.resolve();\n } else {\n let resolve!: () => void;\n let reject!: (error: unknown) => void;\n ready = new Promise<void>((res, rej) => ((resolve = res), (reject = rej)));\n texture = new TextureLoader().load(url, () => resolve(), undefined, () => {\n cache.delete(key);\n reject(new Error(`tree.js: could not load texture ${url}`));\n });\n ready.catch(() => {}); // reported through `textureReady` / `tree.ready`, not as unhandled\n }\n texture.name = url;\n texture.colorSpace = kind === 'color' ? SRGBColorSpace : NoColorSpace;\n texture.wrapS = texture.wrapT = RepeatWrapping;\n texture.anisotropy = 4;\n cache.set(key, texture);\n pending.set(texture, ready);\n return texture;\n}\n\n/** Resolves when a texture from `loadTexture` has its image (rejects if it failed to load). */\nexport function textureReady(texture: Texture): Promise<void> {\n return pending.get(texture) ?? Promise.resolve();\n}\n","import type { MeshStandardNodeMaterial, Texture } from 'three/webgpu';\nimport { normalMap, texture, uv, vec2 } from 'three/tsl';\nimport type { BarkMaterialDefinition, LeafMaterialDefinition } from '../definition';\nimport { loadTexture, resolveTextureUrl, type TextureOptions } from '../textures';\n\n// TSL node types are loosely typed in @types/three; keep our own alias.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Node = any;\n\n/**\n * How often the bark texture repeats around (u) and along (v) a branch. Bark UVs run 0..1\n * around and 0..1 along each branch, so this keeps the bark from stretching along long parts.\n */\nexport const BARK_REPEAT: readonly [number, number] = [2, 6];\n\n/**\n * Textured bark: `color × map` (the glTF base colour convention) and a tangent-space normal map,\n * both tiled by `BARK_REPEAT`. Returns the colour node to use, or `base` when there is no map.\n * `.map` / `.normalMap` are also set, for exporters and so `tree.ready` can wait for them.\n */\nexport function applyBarkMaps(\n material: MeshStandardNodeMaterial,\n bark: BarkMaterialDefinition,\n base: Node,\n textures?: TextureOptions,\n): Node {\n const tiled = uv().mul(vec2(...BARK_REPEAT));\n if (bark.normalMap) {\n material.normalMap = load(bark.normalMap, 'data', textures);\n material.normalNode = normalMap(texture(material.normalMap, tiled));\n }\n if (!bark.map) return base;\n material.map = load(bark.map, 'color', textures);\n return base.mul(texture(material.map, tiled).rgb);\n}\n\n/**\n * Alpha-cut leaf cards: `colorNode` = the card texture (rgba, card UVs), cut at `alphaTest`.\n * The Season colour is multiplied in later (`applySeasonToLeafMaterial`). `.map` is set too, so\n * the shadow pass cuts the same shape out of the leaf shadows.\n */\nexport function applyLeafMap(material: MeshStandardNodeMaterial, leaf: LeafMaterialDefinition, textures?: TextureOptions): void {\n if (!leaf.map) return;\n material.map = load(leaf.map, 'color', textures);\n material.colorNode = texture(material.map);\n material.alphaTest = leaf.alphaTest;\n}\n\nconst load = (url: string, kind: 'color' | 'data', textures?: TextureOptions): Texture =>\n loadTexture(resolveTextureUrl(url, textures), kind);\n","import { float, length, normalize, positionGeometry, select, varying, vec3 } from 'three/tsl';\nimport type { Node } from 'three/webgpu';\nimport type { CrownVolume } from '../generator';\nimport { growthPosition, growthScale } from '../growth';\n\n/** The Crown Volume measured at a point of the tree, in TSL (fragment stage). */\nexport interface CrownNodes {\n /**\n * Unit outward normal of the Volume's ellipsoid through the point, in tree space (twin of `crownNormal`).\n * Straight up at the centre. Turn it into view space with `transformNormalToView` (a Forest first\n * rotates it by the instance).\n */\n normal: Node<'vec3'>;\n /** How far the point sits from the centre in units of the ellipsoid: 0 centre, 1 shell (twin of `crownDistance`). */\n distance: Node<'float'>;\n}\n\n/**\n * The Crown Volume (GLOSSARY) measured at the grown tree-space position (Growth `growth`, before Wind,\n * so Wind doesn't make it flicker). The Volume scales with the tree's Growth scale, as the vertices do,\n * so a sapling is measured against its own, smaller crown. Shared by the Material Features.\n */\nexport function crownNodes(crown: CrownVolume, growth: Node<'float'>): CrownNodes {\n const grown = varying(growthPosition(growth, positionGeometry), 'vCrownPosition');\n // Grown position back in the fully grown tree's frame: the Volume itself scaled by the Growth scale.\n const local = grown.div(growthScale(float(growth).clamp(0, 1))).sub(vec3(...crown.center));\n const radii = vec3(...crown.radii);\n const unit = local.div(radii);\n const gradient = unit.div(radii);\n const normal = select(length(gradient).greaterThan(1e-6), normalize(gradient), vec3(0, 1, 0));\n return { normal, distance: length(unit) };\n}\n","import type { LightingModelDirectInput, Node, NodeBuilder } from 'three/webgpu';\nimport { BRDF_Lambert, diffuseColor, float, mix, positionViewDirection } from 'three/tsl';\nimport type { CrownVolume } from '../generator';\nimport { crownNodes } from './crown-nodes';\n\n/*\n * @types/three leaves the lighting model's inputs untyped (`builder.context` is `unknown`, the light's\n * nodes and the reflected light are plain `Node`s). These name the fields the translucent models use,\n * with the node types three gives them.\n */\n\n/** The diffuse parts of the reflected light a lighting model adds to (RGB). */\nexport interface DiffuseLight {\n directDiffuse: Node<'vec3'>;\n indirectDiffuse: Node<'vec3'>;\n}\n\n/** The part of three's lighting context (`builder.context` in a lighting model) the terms read and write. */\nexport interface LightingContext {\n irradiance: Node<'vec3'>;\n ambientOcclusion: Node<'float'>;\n reflectedLight: DiffuseLight;\n}\n\n/** One direct light as a lighting model's `direct` gets it: view-space direction, colour (with shadow). */\nexport interface DirectLight {\n lightDirection: Node<'vec3'>;\n lightColor: Node<'vec3'>;\n reflectedLight: DiffuseLight;\n}\n\n/** The lighting context of a lighting model's builder, typed (see {@link LightingContext}). */\nexport const lightingContext = (builder: NodeBuilder): LightingContext => builder.context as LightingContext;\n\n/** A lighting model's `direct` input, typed (see {@link DirectLight}). */\nexport const directLight = (input: LightingModelDirectInput): DirectLight => input as unknown as DirectLight;\n\n/**\n * How narrow the Leaf Translucency lobe (light from behind the leaf) is: `back = saturate(dot(V, -L))^BACK_POWER`. Higher = only when\n * looking almost straight into the light through the leaf.\n */\nconst BACK_POWER = 3;\n\n/**\n * Leaf Translucency (GLOSSARY) as one shared TSL term, used by both leaf lighting models: the physical\n * one (`TranslucentLightingModel`, flat and standard shading) and `SoftToonLightingModel` (toon).\n * Build it with {@link leafTranslucencyTerm}; the values are uniforms, so changing them needs no recompile.\n */\nexport interface LeafTranslucencyTerm extends LeafTranslucencyValues {\n /** How thin the crown is at this fragment: 1 on (or outside) the Crown Volume's shell, towards 0 at its centre. */\n readonly thinness: Node<'float'>;\n}\n\n/** The settings of `materials.leaf.translucency` as nodes (uniforms, shared by every leaf material of a Tree or Forest). */\nexport interface LeafTranslucencyValues {\n /** Direct glow per light (0..1). */\n readonly strength: Node<'float'>;\n /** Indirect (sky) glow (0..1). */\n readonly ambient: Node<'float'>;\n /** Extra glow at the thin edge of the Crown Volume (0..1). */\n readonly edge: Node<'float'>;\n}\n\n/**\n * The term for a leaf material: `values` the settings of `materials.leaf.translucency`, `crown` the tree's\n * Crown Volume (`TreeData.crown`, tree space, fully grown) and `growth` the Growth node the material\n * grows with (the Tree's uniform, or a Forest's per-instance Growth).\n *\n * Thinness is the Crown Volume distance (`crownNodes`): measured in the tree's own space on the grown\n * position before Wind (so Wind doesn't make it flicker), against the Volume scaled by the same Growth scale\n * the vertices get. Being in tree space, it is the same for every Forest instance whatever its rotation and\n * scale. It needs no vertex attribute.\n */\nexport function leafTranslucencyTerm(values: LeafTranslucencyValues, crown: CrownVolume, growth: Node<'float'>): LeafTranslucencyTerm {\n return {\n strength: values.strength,\n ambient: values.ambient,\n edge: values.edge,\n thinness: crownNodes(crown, growth).distance.clamp(0, 1),\n };\n}\n\n/** `mix(1, thinness, edge)`: 1 everywhere at edge 0, only the crown's thin edge glows at edge 1. */\nconst edgeBoost = (term: LeafTranslucencyTerm): Node<'float'> => mix(float(1), term.thinness, term.edge);\n\n/**\n * Direct light shining through the leaf towards the viewer, for one light (add it to `directDiffuse`):\n * `lightColor × leaf diffuse × strength × back × edgeBoost`, where `back` is a smooth power of\n * dot(view direction, -light direction). `lightColor` already carries the light's shadow, so shadowed\n * leaves don't glow. The leaf diffuse is its Season colour (Season Profile x the Seed's tint x leaf map).\n * Unlike the lit side it has no Lambert 1/pi: like a real leaf against the sun, a strongly translucent leaf\n * glows brighter than one lit from the front.\n */\nexport function translucencyDirect(term: LeafTranslucencyTerm, lightDirection: Node<'vec3'>, lightColor: Node<'vec3'>): Node<'vec3'> {\n const back = positionViewDirection.dot(lightDirection.negate()).clamp(0, 1).pow(BACK_POWER);\n return lightColor\n .mul(diffuseColor.rgb)\n .mul(term.strength)\n .mul(back)\n .mul(edgeBoost(term));\n}\n\n/**\n * Indirect light shining through the leaf (add it to `indirectDiffuse` after the model's own AO step):\n * `irradiance × leaf diffuse × ambient × edgeBoost × ambient occlusion`, the leaf diffuse through the\n * Lambert BRDF like the rest of the indirect light.\n *\n * The irradiance from behind would be the irradiance sampled along the flipped normal; three's public\n * lighting-model API only exposes the irradiance already gathered along the normal (`context.irradiance`),\n * so that stands in for it. It is exact for ambient light and light probes' constant part; under a\n * hemisphere light it reads the side facing the viewer.\n */\nexport function translucencyIndirect(term: LeafTranslucencyTerm, builder: NodeBuilder): Node<'vec3'> {\n const { ambientOcclusion, irradiance } = lightingContext(builder);\n return irradiance\n // BRDF_Lambert is declared as an untyped OperatorNode; it is the RGB diffuse / pi.\n .mul(BRDF_Lambert({ diffuseColor: diffuseColor.rgb }) as unknown as Node<'vec3'>)\n .mul(term.ambient)\n .mul(edgeBoost(term))\n .mul(ambientOcclusion);\n}\n","import {\n LightingModel,\n MeshStandardNodeMaterial,\n type LightingModelDirectInput,\n type NodeBuilder,\n type PhysicalLightingModel,\n} from 'three/webgpu';\nimport { BRDF_Lambert, diffuseColor, float, mix, normalView, smoothstep } from 'three/tsl';\nimport { translucencyDirect, translucencyIndirect, type LeafTranslucencyTerm } from './leaf-translucency';\n\n// TSL node types are loosely typed in @types/three; keep our own alias.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Node = any;\n\n/** Brightness of the shaded side, relative to the lit side (the toon \"shadow tone\"). */\nconst SHADE = 0.5;\n/** The soft band between shade and light, in N·L (a hard toon edge would be 0 wide). */\nconst BAND_START = 0;\nconst BAND_END = 0.2;\n\n/**\n * Soft toon lighting: two tones (lit and shaded) per light with a smooth band in between,\n * plus plain diffuse ambient/hemisphere light. No specular or environment reflections. Built\n * in TSL from the light direction only, so it needs no gradient texture (no image files).\n *\n * With a Leaf Translucency term (leaf material only, `applyLeafTranslucency`), leaves with light behind them also glow:\n * the same shared term the physical leaf model adds.\n */\nexport class SoftToonLightingModel extends LightingModel {\n constructor(private readonly translucency: LeafTranslucencyTerm | null = null) {\n super();\n }\n\n /** Whether this model adds Leaf Translucency. */\n get isLeafTranslucencyModel(): boolean {\n return this.translucency !== null;\n }\n\n override direct({ lightDirection, lightColor, reflectedLight }: LightingModelDirectInput): void {\n const dotNL: Node = normalView.dot(lightDirection as Node);\n const tone = mix(float(SHADE), float(1), smoothstep(BAND_START, BAND_END, dotNL));\n const irradiance = (lightColor as Node).mul(tone);\n (reflectedLight.directDiffuse as Node).addAssign(irradiance.mul(BRDF_Lambert({ diffuseColor: diffuseColor.rgb })));\n if (this.translucency) (reflectedLight.directDiffuse as Node).addAssign(translucencyDirect(this.translucency, lightDirection as Node, lightColor as Node));\n }\n\n override indirect(builder: NodeBuilder): void {\n const { ambientOcclusion, irradiance, reflectedLight } = (builder as Node).context;\n reflectedLight.indirectDiffuse.addAssign(irradiance.mul(BRDF_Lambert({ diffuseColor })));\n reflectedLight.indirectDiffuse.mulAssign(ambientOcclusion);\n if (this.translucency) reflectedLight.indirectDiffuse.addAssign(translucencyIndirect(this.translucency, builder));\n }\n}\n\n/**\n * The stylized Style's material (`materials.shading: 'toon'`): a `MeshStandardNodeMaterial`\n * lit by the soft toon model. Staying a standard material keeps every part node (Season\n * colour, Growth/Wind `positionNode`) and exporters (they see a plain PBR material) working\n * the same as for the other Styles.\n */\nexport class SoftToonNodeMaterial extends MeshStandardNodeMaterial {\n readonly isSoftToonMaterial = true;\n\n override setupLightingModel(): PhysicalLightingModel {\n // The declared return type is the physical model; the renderer only uses the LightingModel interface.\n return new SoftToonLightingModel() as unknown as PhysicalLightingModel;\n }\n}\n","import { MeshStandardNodeMaterial } from 'three/webgpu';\nimport type { Shading } from '../definition';\nimport { SoftToonNodeMaterial } from './toon';\n\n/**\n * The Style layer of the tree materials: the base node material for a Definition's\n * `materials.shading`. `createBarkMaterial` / `createLeafMaterial` start from it and then set\n * their part-specific nodes (bark colour, Season colour, Growth/Wind `positionNode`), so those\n * shared nodes work the same in every Style.\n *\n * - `flat` (low-poly): faceted lighting from the screen-space face normal (`flatShading`), so\n * facets stay correct when Growth or Wind move vertices in `positionNode`. Rough, no gloss.\n * - `standard` (realistic): smooth PBR shading.\n * - `toon` (stylized): soft two-tone toon lighting (`SoftToonNodeMaterial`, still a standard\n * node material underneath), smooth normals so leaf clumps read as rounded.\n */\nexport function createShadedMaterial(shading: Shading): MeshStandardNodeMaterial {\n const material = shading === 'toon' ? new SoftToonNodeMaterial() : new MeshStandardNodeMaterial();\n material.flatShading = shading === 'flat';\n return material;\n}\n\n/** Whether a shading model wants solid (flat) colours rather than smooth colour gradients. */\nexport const isFlatShading = (shading: Shading): boolean => shading === 'flat';\n","import { length, mix, normalView, select, transformNormalToView } from 'three/tsl';\nimport type { MeshStandardNodeMaterial, Node } from 'three/webgpu';\nimport type { CrownVolume } from '../generator';\nimport { crownNodes } from './crown-nodes';\n\n/**\n * Crown Normals (GLOSSARY): blends the leaf material's normal from the leaf's own normal towards the\n * Crown Volume's normal at that point, by `amount` (0..1, a uniform: Definitions that differ only in it\n * share one shader, and a Tree tunes it live). Only call it when the feature is on (amount > 0); without\n * it the material keeps its own normal.\n *\n * - `growth`: the Growth node of the material's `positionNode` (the Volume scales with it).\n * - `toObject`: turns a tree-space normal into the mesh's own space (a Forest rotates it by the\n * instance, as it does the Growth and Wind displacement); default: tree space is object space.\n *\n * The leaf normal is the material's view-space normal: the screen-space facet normal under flat\n * shading (so facets stay visible below 1), the smooth one facing the viewer otherwise.\n */\nexport function applyCrownNormals(\n material: MeshStandardNodeMaterial,\n amount: Node<'float'>,\n crown: CrownVolume,\n growth: Node<'float'>,\n toObject: (normal: Node<'vec3'>) => Node<'vec3'> = (normal) => normal,\n): void {\n const crownView = transformNormalToView(toObject(crownNodes(crown, growth).normal)).normalize();\n const blend = mix(normalView, crownView, amount);\n // A leaf normal facing exactly away from the crown's cancels out half way: fall back to the crown's.\n material.normalNode = select(length(blend).greaterThan(1e-4), blend.normalize(), crownView);\n}\n","import { DoubleSide, type MeshStandardNodeMaterial } from 'three/webgpu';\nimport { color, mix, uv, float } from 'three/tsl';\nimport type { Node } from 'three/webgpu';\nimport type { TreeDefinition } from '../definition';\nimport { fruitTracks } from '../season/profile';\nimport type { TextureOptions } from '../textures';\nimport { applyGroundTint } from './ground-tint';\nimport { applyBarkMaps, applyLeafMap } from './maps';\nimport { createShadedMaterial, isFlatShading } from './shading';\n\nexport { createShadedMaterial } from './shading';\nexport { applyCrownNormals } from './crown-normals';\nexport { crownNodes, type CrownNodes } from './crown-nodes';\n\n/**\n * Bark material: a TSL node material (ADR 0002). Growth/Season/Wind uniforms and\n * per-Style variants hook in here in later tickets (#5-#10). `materials.bark.map` / `.normalMap`\n * load through `textures` (base path / URL overrides, see `TextureOptions`).\n *\n * `growth`: the Growth node the material's `positionNode` grows the tree with (default: fully grown).\n * A Ground Tint (`materials.bark.groundTint`) is measured on that grown position; without one it is unused.\n */\nexport function createBarkMaterial(\n definition: TreeDefinition,\n textures?: TextureOptions,\n growth: Node<'float'> = float(1),\n): MeshStandardNodeMaterial {\n const material = createShadedMaterial(definition.materials.shading);\n material.name = 'tree.js bark';\n material.userData.treePart = 'bark'; // Tree Effects (`/effects`) find tree pixels by it\n const base = color(definition.materials.bark.color);\n // Slightly darker towards the base for a little depth, purely in TSL (flat colour for flat shading).\n const shaded = isFlatShading(definition.materials.shading)\n ? base\n : mix(base.mul(0.75), base, uv().y.clamp(0, 1).pow(float(0.5)));\n const { groundTint } = definition.materials.bark;\n const tinted = groundTint ? applyGroundTint(shaded, groundTint, growth) : shaded;\n material.colorNode = applyBarkMaps(material, definition.materials.bark, tinted, textures);\n material.roughness = definition.materials.bark.roughness;\n material.metalness = 0;\n return material;\n}\n\n/**\n * Leaf material: a TSL node material lit from both sides. `.color` is the Season Profile's\n * leaf colour at Season 0 (what exporters see); `Tree` adds the Season nodes\n * (`applySeasonToLeafMaterial`), whose colour is multiplied by the per-leaf vertex colours (the Seed's tint)\n * and by the leaf card texture (`materials.leaf.map`, alpha cut at `alphaTest`), if any.\n */\nexport function createLeafMaterial(definition: TreeDefinition, textures?: TextureOptions): MeshStandardNodeMaterial {\n const material = createShadedMaterial(definition.materials.shading);\n material.name = 'tree.js leaves';\n material.userData.treePart = 'leaves';\n material.color.set(definition.season.leafColor[0]!.value);\n material.vertexColors = true;\n material.side = DoubleSide;\n material.roughness = definition.materials.leaf.roughness;\n material.metalness = 0;\n applyLeafMap(material, definition.materials.leaf, textures);\n return material;\n}\n\n/**\n * Fruit material: the Definition's shading (flat facets in low-poly, smooth toon in stylized,\n * smooth PBR in realistic), no textures. `.color` is the Fruit colour at Season 0; `Tree` sets the\n * Season colour (`createFruitSeasonNodes`), multiplied by the per-Fruit vertex colours (the Seed's tint).\n */\nexport function createFruitMaterial(definition: TreeDefinition): MeshStandardNodeMaterial {\n const material = createShadedMaterial(definition.materials.shading);\n material.name = 'tree.js fruit';\n material.userData.treePart = 'fruit';\n material.color.set(fruitTracks(definition.season).fruitColor[0]!.value);\n material.vertexColors = true;\n material.roughness = FRUIT_ROUGHNESS;\n material.metalness = 0;\n return material;\n}\n\n/** Fruit skin is a little glossier than leaves. */\nconst FRUIT_ROUGHNESS = 0.45;\n","import {\n PhysicalLightingModel,\n type LightingModelDirectInput,\n type MeshStandardNodeMaterial,\n type Node,\n type NodeBuilder,\n} from 'three/webgpu';\nimport type { CrownVolume } from '../generator';\nimport {\n directLight,\n leafTranslucencyTerm,\n lightingContext,\n translucencyDirect,\n translucencyIndirect,\n type LeafTranslucencyTerm,\n type LeafTranslucencyValues,\n} from './leaf-translucency';\nimport { SoftToonLightingModel, SoftToonNodeMaterial } from './toon';\n\n/**\n * three's physical lighting model plus Leaf Translucency (flat and standard leaf materials): everything\n * the physical model does, and per light and for the indirect light the shared translucency term.\n * Only the public `direct` / `indirect` entry points are extended.\n */\nclass TranslucentLightingModel extends PhysicalLightingModel {\n readonly isLeafTranslucencyModel = true;\n\n constructor(private readonly translucency: LeafTranslucencyTerm) {\n super();\n }\n\n override direct(input: LightingModelDirectInput, builder: NodeBuilder): void {\n super.direct(input, builder);\n const { lightDirection, lightColor, reflectedLight } = directLight(input);\n reflectedLight.directDiffuse.addAssign(translucencyDirect(this.translucency, lightDirection, lightColor));\n }\n\n override indirect(builder: NodeBuilder): void {\n // The physical model's own AO step has run by now; the term multiplies in the AO itself.\n super.indirect(builder);\n lightingContext(builder).reflectedLight.indirectDiffuse.addAssign(translucencyIndirect(this.translucency, builder));\n }\n}\n\n/**\n * Gives a leaf material Leaf Translucency (`materials.leaf.translucency` as uniforms, a Material Feature, ADR 0008):\n * its lighting model becomes the translucent one (the physical model with the term for flat and standard\n * shading, the soft toon model with the same term for toon). The material keeps its class and every node.\n * Only call it when the feature is set: without it the leaf material keeps today's lighting model.\n *\n * `crown` is the tree's Crown Volume (`TreeData.crown`); `growth` the Growth node the material's\n * `positionNode` grows with (a Tree's Growth uniform, or a Forest's per-instance Growth).\n */\nexport function applyLeafTranslucency(\n material: MeshStandardNodeMaterial,\n values: LeafTranslucencyValues,\n crown: CrownVolume,\n growth: Node<'float'>,\n): void {\n const term = leafTranslucencyTerm(values, crown, growth);\n const toon = material instanceof SoftToonNodeMaterial;\n // The declared return type is the physical model; the renderer only uses the LightingModel interface.\n material.setupLightingModel = () =>\n (toon ? new SoftToonLightingModel(term) : new TranslucentLightingModel(term)) as unknown as PhysicalLightingModel;\n material.needsUpdate = true;\n}\n","import { attribute, float, mix } from 'three/tsl';\nimport type { Node, NodeMaterial } from 'three/webgpu';\n\n/**\n * Structural Occlusion (GLOSSARY, ADR 0008) on a tree's own materials: each material's `aoNode` becomes\n * `mix(1, aOcclusion, strength)`, from the Generator's baked `aOcclusion` (only generated when\n * `materials.occlusion` is set). three applies it as it does the material's built-in AO (multiplied with an\n * app's SSAO/GTAO through `context.getAO`), so it only darkens ambient and indirect light; the toon model's\n * indirect light multiplies by it too. `strength` is a uniform, so tuning it needs no recompile.\n */\nexport function applyStructuralOcclusion(materials: readonly (NodeMaterial | null)[], strength: Node<'float'>): void {\n const ao = mix(float(1), attribute<'float'>('aOcclusion', 'float'), strength);\n for (const material of materials) if (material) material.aoNode = ao;\n}\n","import { uniform } from 'three/tsl';\nimport type { MeshStandardNodeMaterial, Node, NodeMaterial, UniformNode } from 'three/webgpu';\nimport type { MaterialFeatures, TranslucencyDefinition, TreeDefinition } from '../definition';\nimport type { CrownVolume } from '../generator';\nimport { materialFeaturesOf } from '../styles/material-features';\nimport { applyCrownNormals } from './crown-normals';\nimport { applyLeafTranslucency } from './leaf-translucency-model';\nimport { applyStructuralOcclusion } from './occlusion';\n\ntype FloatUniform = UniformNode<'float', number>;\n\n/** One tree's materials to give the Material Features (a Tree's, or one Forest Variant's). */\nexport interface MaterialFeatureTarget {\n /** The leaf material (Crown Normals, Leaf Translucency). */\n leaf: MeshStandardNodeMaterial;\n /** Every material of the tree: bark, leaf and Fruit (Structural Occlusion). */\n materials: readonly (NodeMaterial | null)[];\n /** The tree's Crown Volume (`TreeData.crown`). */\n crown: CrownVolume;\n /** The Growth node the materials' `positionNode` grows with. */\n growth: Node<'float'>;\n /** Turns a tree-space normal into the mesh's own space (a Forest rotates it by the instance). Default: as is. */\n toObject?: (normal: Node<'vec3'>) => Node<'vec3'>;\n}\n\nconst clamp01 = (value: number): number => Math.min(Math.max(value, 0), 1);\n\n/**\n * The Material Features (GLOSSARY, ADR 0008) of a Tree or Forest: applies those the Definition sets to\n * the materials of each target and owns their values as uniforms, shared by all targets, so a feature\n * that is on can be tuned live (no regeneration, no recompile). A feature that is off leaves the\n * materials exactly as they are and cannot be tuned (switching one on needs a new Tree or Forest).\n */\nexport class LiveMaterialFeatures {\n private readonly crown: FloatUniform | null;\n private readonly translucencyValues: { strength: FloatUniform; edge: FloatUniform; ambient: FloatUniform } | null;\n private readonly occlusion: FloatUniform | null;\n\n constructor(definition: TreeDefinition, targets: readonly MaterialFeatureTarget[]) {\n const { crownNormals, translucency, occlusion } = materialFeaturesOf(definition);\n this.crown = crownNormals ? uniform(crownNormals) : null;\n this.translucencyValues = translucency\n ? { strength: uniform(translucency.strength), edge: uniform(translucency.edge), ambient: uniform(translucency.ambient) }\n : null;\n this.occlusion = occlusion ? uniform(occlusion.strength) : null;\n for (const { leaf, materials, crown, growth, toObject } of targets) {\n if (this.crown) applyCrownNormals(leaf, this.crown, crown, growth, toObject);\n if (this.translucencyValues) applyLeafTranslucency(leaf, this.translucencyValues, crown, growth);\n if (this.occlusion) applyStructuralOcclusion(materials, this.occlusion);\n }\n }\n\n /** The features that are on, with their current values (same shape as `materialFeaturesOf`). */\n get values(): MaterialFeatures {\n return {\n ...(this.crown ? { crownNormals: this.crown.value } : {}),\n ...(this.translucencyValues\n ? {\n translucency: {\n strength: this.translucencyValues.strength.value,\n edge: this.translucencyValues.edge.value,\n ambient: this.translucencyValues.ambient.value,\n },\n }\n : {}),\n ...(this.occlusion ? { occlusion: { strength: this.occlusion.value } } : {}),\n };\n }\n\n /** Crown Normals amount, null when off. */\n get crownNormals(): number | null {\n return this.crown?.value ?? null;\n }\n\n /** Sets the Crown Normals amount (clamped to 0..1); throws when the feature is off. */\n set crownNormals(value: number) {\n if (!this.crown) {\n throw new Error('This tree has no Crown Normals: set `materials.leaf.crownNormals` in its Tree Definition to tune the amount');\n }\n this.crown.value = clamp01(value);\n }\n\n /** Leaf Translucency settings (a copy), null when off. */\n get translucency(): TranslucencyDefinition | null {\n return this.values.translucency ?? null;\n }\n\n /** Sets any of the Leaf Translucency settings (each clamped to 0..1; the others kept); throws when the feature is off. */\n set translucency(value: Partial<TranslucencyDefinition>) {\n if (!this.translucencyValues) {\n throw new Error('This tree has no Leaf Translucency: set `materials.leaf.translucency` in its Tree Definition to tune it');\n }\n for (const key of ['strength', 'edge', 'ambient'] as const) {\n const v = value[key];\n if (v !== undefined) this.translucencyValues[key].value = clamp01(v);\n }\n }\n\n /** Structural Occlusion strength, null when off. */\n get occlusionStrength(): number | null {\n return this.occlusion?.value ?? null;\n }\n\n /** Sets the Structural Occlusion strength (clamped to 0..1); throws when the feature is off. */\n set occlusionStrength(value: number) {\n if (!this.occlusion) {\n throw new Error('This tree has no Structural Occlusion: set `materials.occlusion` in its Tree Definition to tune its strength');\n }\n this.occlusion.value = clamp01(value);\n }\n}\n","/** Thrown when a tree is drawn by anything other than `WebGPURenderer` (ADR 0002). */\nexport class UnsupportedRendererError extends Error {\n constructor(what: string) {\n super(\n `tree.js requires WebGPURenderer (import { WebGPURenderer } from 'three/webgpu'), but the tree is being drawn by ${what}. ` +\n 'The classic WebGLRenderer is not supported because tree materials are TSL node materials. ' +\n 'WebGPURenderer runs on WebGPU and falls back to WebGL2 by itself, so switching renderers keeps WebGL2 support.',\n );\n this.name = 'UnsupportedRendererError';\n }\n}\n\ninterface RendererLike {\n isWebGPURenderer?: boolean;\n isWebGLRenderer?: boolean;\n}\n\n/** Throws {@link UnsupportedRendererError} unless `renderer` is a `WebGPURenderer` (either backend). */\nexport function assertWebGPURenderer(renderer: unknown): void {\n const r = renderer as RendererLike | null | undefined;\n if (r?.isWebGPURenderer === true) return;\n throw new UnsupportedRendererError(r?.isWebGLRenderer ? 'the classic WebGLRenderer' : 'an unknown renderer');\n}\n","import { Color, type Node as FloatNode, type NodeMaterial, type UniformNode } from 'three/webgpu';\nimport { attribute, float, fract, mix, positionLocal, select, uniform, varying, vec4 } from 'three/tsl';\nimport type { Keyframe, SeasonProfileDefinition } from '../definition';\nimport { fruitTracks, KEYFRAME_EPSILON } from './profile';\n\n/** A float uniform (`.value` is the Season). */\nexport type SeasonUniform = UniformNode<'float', number>;\n\n// TSL node types are loosely typed in @types/three; keep our own alias.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Node = any;\n\n/**\n * Unrolls a keyframe track into a chain of mixes over uniforms (one per segment). Same maths\n * as `sampleTrack` in `./profile.ts`. Key times and values are uniforms, so editing a value\n * never recompiles; only a different key count does.\n */\nfunction keyframeNode<V>(s: Node, track: readonly Keyframe<V>[], toUniform: (v: V) => Node): Node {\n const ts: Node[] = track.map((k) => uniform(k.t));\n const vs: Node[] = track.map((k) => toUniform(k.value));\n let out: Node = vs[0];\n for (let i = 0; i < track.length - 1; i++) {\n const f = s.sub(ts[i]).div(ts[i + 1]!.sub(ts[i]).max(KEYFRAME_EPSILON)).clamp(0, 1);\n out = mix(out, vs[i + 1], f);\n }\n return out;\n}\n\n/** The Season nodes of one tree's leaves; `S` is the Season input node (a uniform by default). */\nexport interface SeasonNodes<S extends FloatNode<'float'> = SeasonUniform> {\n /** Season 0..1 (first day of spring .. last day of winter). For a uniform: write `.value`; nothing recompiles. */\n season: S;\n /** Leaf colour (vec3, linear) at this leaf's shifted Season, or the blossom colour for a blossom. */\n color: Node;\n /** True while the leaf is shown (coverage above its rank, or a blossom). For `maskNode`. */\n visible: Node;\n}\n\n/**\n * Builds the TSL nodes that evaluate a Season Profile per leaf, from the `aSeason` vertex\n * attribute (Seed timing shift, coverage rank, blossom rank). The TSL twin of `leafSeason`.\n * Evaluated in the vertex stage (constant per leaf) and passed on as varyings.\n *\n * `season` is the Season input: a new uniform by default, or any float node (a Forest passes its\n * per-instance Season attribute).\n */\nexport function createSeasonNodes(profile: SeasonProfileDefinition): SeasonNodes;\nexport function createSeasonNodes<S extends FloatNode<'float'>>(profile: SeasonProfileDefinition, season: S): SeasonNodes<S>;\nexport function createSeasonNodes(profile: SeasonProfileDefinition, season: FloatNode<'float'> = uniform(0)): SeasonNodes<FloatNode<'float'>> {\n const aSeason = attribute('aSeason', 'vec3');\n const s = shiftedSeason(season, aSeason);\n\n const leafColor = keyframeNode(s, profile.leafColor, (v) => uniform(new Color(v)));\n const coverage = keyframeNode(s, profile.leafCoverage, (v) => uniform(v));\n const blossom = keyframeNode(s, profile.blossom, (v) => uniform(v));\n const blossomColor = uniform(new Color(profile.blossomColor));\n\n const isBlossom = blossom.greaterThan(aSeason.z);\n const shown = isBlossom.or(coverage.greaterThan(aSeason.y));\n return {\n season,\n color: varying(select(isBlossom, blossomColor, leafColor)),\n visible: varying(select(shown, float(1), float(0))).greaterThan(0.5),\n };\n}\n\n/** The part's own Season: the Season input plus the `aSeason.x` timing shift, wrapped around the year (as `wrapSeason`). */\nfunction shiftedSeason(season: Node, aSeason: Node): Node {\n const shifted = season.add(aSeason.x);\n return select(shifted.greaterThan(1).or(shifted.lessThan(0)), fract(shifted), shifted);\n}\n\n/** The Season nodes of one tree's Fruit. */\nexport interface FruitSeasonNodes {\n /** Fruit colour (vec3, linear) at this Fruit's shifted Season. */\n color: Node;\n /** Size of the Fruit (0 = not set or dropped .. 1 = full size). */\n scale: Node;\n /** The vertex position (default `positionLocal`) scaled about the Fruit's attachment point (`aOrigin`) by `scale`. */\n position: Node;\n}\n\n/**\n * Builds the TSL nodes that evaluate the Season Profile's Fruit tracks per Fruit, from the fruit\n * mesh's `aSeason` (timing shift, Fruit rank). The TSL twin of `fruitSeason`: a Fruit shows while\n * the Fruit amount is above its rank and swells with the amount. `season` is the Season input\n * (share the leaves' uniform so one write drives both).\n */\nexport function createFruitSeasonNodes(\n profile: SeasonProfileDefinition,\n season: FloatNode<'float'>,\n position: Node = positionLocal,\n): FruitSeasonNodes {\n const aSeason = attribute('aSeason', 'vec3');\n const origin = attribute('aOrigin', 'vec3');\n const s = shiftedSeason(season, aSeason);\n const tracks = fruitTracks(profile);\n const amount = keyframeNode(s, tracks.fruit, (v) => uniform(v));\n const scale = select(amount.greaterThan(aSeason.y), amount, float(0));\n return {\n color: varying(keyframeNode(s, tracks.fruitColor, (v) => uniform(new Color(v)))),\n scale,\n position: origin.add(position.sub(origin).mul(scale)),\n };\n}\n\n/**\n * Hooks Season into a leaf material: `colorNode` (times the vertex-colour tint, and times the\n * material's existing `colorNode`, such as a leaf card texture with alpha) and `maskNode`, which\n * also cuts fallen leaves out of the shadow pass.\n */\nexport function applySeasonToLeafMaterial(material: NodeMaterial, nodes: Pick<SeasonNodes, 'color' | 'visible'>): void {\n material.colorNode = material.colorNode ? vec4(nodes.color, 1).mul(material.colorNode as Node) : nodes.color;\n material.maskNode = nodes.visible;\n}\n","import { wrapSeason } from './profile';\n\n/** A Season set by the app: must be finite (RangeError otherwise), then wrapped into 0..1. */\nexport function checkedSeason(value: number): number {\n if (!Number.isFinite(value)) throw new RangeError(`Season must be a finite number, got ${value}`);\n return wrapSeason(value);\n}\n","import { Vector3, type UniformNode } from 'three/webgpu';\nimport { uniform } from 'three/tsl';\n\nexport type WindDirection = Vector3 | readonly [number, number, number];\n\nexport interface WindOptions {\n /** World-space direction the wind blows towards (any length > 0; stored as a unit vector). Default +X. */\n direction?: WindDirection;\n /** 0 = calm (default), 1 = strong wind; larger values are allowed for storms. */\n strength?: number;\n}\n\n/**\n * Scene-wide Wind: a direction and a strength that every tree listening to it sways with.\n * Changing them only writes uniform values (no recompile). Trees use {@link sceneWind} unless\n * `createTree(..., { wind })` names another one. How much each tree moves is its Definition's\n * Wind response (`definition.wind`).\n */\nexport class Wind {\n /** The shared TSL uniforms tree materials read. Write through the setters, not here. */\n readonly uniforms: {\n readonly direction: UniformNode<'vec3', Vector3>;\n readonly strength: UniformNode<'float', number>;\n /** Seconds; follows the renderer clock unless {@link Wind.time} pins it. */\n readonly time: UniformNode<'float', number>;\n };\n private pinnedTime: number | null = null;\n\n constructor(options: WindOptions = {}) {\n this.uniforms = {\n direction: uniform(new Vector3(1, 0, 0)),\n strength: uniform(0),\n time: uniform(0).onRenderUpdate((frame) => this.pinnedTime ?? frame.time),\n };\n this.set(options);\n }\n\n /** Unit direction the wind blows towards (a copy: assign a new value to change it). */\n get direction(): Vector3 {\n return this.uniforms.direction.value.clone();\n }\n\n set direction(value: WindDirection) {\n const v = Array.isArray(value) ? new Vector3(...(value as [number, number, number])) : (value as Vector3).clone();\n const length = v.length();\n if (!Number.isFinite(length) || length === 0) {\n throw new RangeError(`Wind direction must be a finite, non-zero vector, got [${v.toArray().join(', ')}]`);\n }\n this.uniforms.direction.value.copy(v.divideScalar(length));\n }\n\n get strength(): number {\n return this.uniforms.strength.value;\n }\n\n set strength(value: number) {\n if (!Number.isFinite(value) || value < 0) throw new RangeError(`Wind strength must be a finite number >= 0, got ${value}`);\n this.uniforms.strength.value = value;\n }\n\n /**\n * Pins the Wind clock to a time in seconds (pause, deterministic screenshots), or `null`\n * (default) to follow the renderer's clock.\n */\n get time(): number | null {\n return this.pinnedTime;\n }\n\n set time(value: number | null) {\n this.pinnedTime = value;\n if (value !== null) this.uniforms.time.value = value;\n }\n\n /** Sets direction and/or strength; returns this. */\n set(options: WindOptions): this {\n if (options.direction !== undefined) this.direction = options.direction;\n if (options.strength !== undefined) this.strength = options.strength;\n return this;\n }\n}\n\n/** The scene-wide Wind every tree sways with by default. */\nexport const sceneWind = new Wind();\n\n/** The uniforms Wind nodes read: those of a {@link Wind}, or of a {@link WindBinding}. */\nexport type WindUniforms = Wind['uniforms'];\n\n/**\n * Per-object Wind uniforms that follow whichever Wind is bound to them, read once per render.\n * Trees and Forests build their Wind nodes on these, so switching to another Wind is one\n * assignment: no new nodes, no recompile, no regeneration.\n */\nexport class WindBinding {\n /** The bound Wind. */\n wind: Wind;\n readonly uniforms: WindUniforms;\n\n constructor(wind: Wind) {\n this.wind = wind;\n const direction = wind.uniforms.direction.value.clone();\n this.uniforms = {\n direction: uniform(direction).onRenderUpdate(() => direction.copy(this.wind.uniforms.direction.value)),\n strength: uniform(wind.strength).onRenderUpdate(() => this.wind.strength),\n time: uniform(0).onRenderUpdate((frame) => this.wind.time ?? frame.time),\n };\n }\n}\n","import type { UniformNode } from 'three/webgpu';\nimport { uniform } from 'three/tsl';\nimport type { WindResponseDefinition } from '../definition';\n\n/**\n * One tree's response to the Wind (from its Definition's `wind`), held in uniforms so the\n * Tree Editor can change it live. `height` (trunk height) and `phase` (from the Seed) shape the\n * motion: the sway scales with the tree, and trees of different Seeds move out of step.\n */\nexport class WindResponse {\n readonly uniforms: {\n readonly trunk: UniformNode<'float', number>;\n readonly branches: UniformNode<'float', number>;\n readonly leaves: UniformNode<'float', number>;\n readonly frequency: UniformNode<'float', number>;\n readonly height: UniformNode<'float', number>;\n /** Radians, 0..2π. */\n readonly phase: UniformNode<'float', number>;\n };\n\n constructor(response: WindResponseDefinition, shape: { height: number; phase: number }) {\n this.uniforms = {\n trunk: uniform(0),\n branches: uniform(0),\n leaves: uniform(0),\n frequency: uniform(1),\n height: uniform(shape.height),\n phase: uniform(shape.phase),\n };\n this.set(response);\n }\n\n /** The current response, as in the Definition's `wind`. */\n get values(): WindResponseDefinition {\n const u = this.uniforms;\n return { trunk: u.trunk.value, branches: u.branches.value, leaves: u.leaves.value, frequency: u.frequency.value };\n }\n\n /** Changes part of the response (uniform writes only). Weights are 0..1, frequency > 0. */\n set(response: Partial<WindResponseDefinition>): this {\n for (const key of ['trunk', 'branches', 'leaves'] as const) {\n const value = response[key];\n if (value === undefined) continue;\n if (!(value >= 0 && value <= 1)) throw new RangeError(`wind.${key} must be within 0..1, got ${value}`);\n this.uniforms[key].value = value;\n }\n if (response.frequency !== undefined) {\n if (!(response.frequency > 0 && Number.isFinite(response.frequency))) {\n throw new RangeError(`wind.frequency must be > 0, got ${response.frequency}`);\n }\n this.uniforms.frequency.value = response.frequency;\n }\n return this;\n }\n}\n","import type { Node, NodeMaterial } from 'three/webgpu';\nimport {\n attribute,\n cross,\n dot,\n modelWorldMatrixInverse,\n normalGeometry,\n positionGeometry,\n positionLocal,\n sin,\n vec3,\n vec4,\n} from 'three/tsl';\nimport type { WindUniforms } from './Wind';\nimport type { WindResponse } from './response';\n\n// Sway amplitudes at Wind strength 1 and response 1, as a fraction of the trunk height.\nconst TRUNK_AMPLITUDE = 0.15;\nconst BRANCH_AMPLITUDE = 0.1;\n// Leaf flutter, as a fraction of the distance from the leaf base.\nconst LEAF_AMPLITUDE = 0.2;\n\n/**\n * Overrides for trees that are not one object each (Forest instances): the Wind direction in\n * the tree's own space and the tree's phase (radians), e.g. from per-instance attributes.\n */\nexport interface WindFrame {\n direction?: Node<'vec3'>;\n phase?: Node<'float'>;\n}\n\n/** Anything holding Wind uniforms: a {@link Wind} or a {@link WindBinding} that follows one. */\nexport interface WindSource {\n readonly uniforms: WindUniforms;\n}\n\n/** The scene Wind direction in the rendered object's space (rotation only, normalized). */\nexport function objectWindDirection(wind: WindSource): Node<'vec3'> {\n return modelWorldMatrixInverse.mul(vec4(wind.uniforms.direction, 0)).xyz.normalize();\n}\n\n/**\n * TSL node: the Wind displacement (vec3, object space) of each vertex, from the per-vertex\n * `aWind` weights (trunk sway, branch sway, leaf flutter), the tree's Wind response and the\n * scene Wind. It only depends on geometry attributes and uniforms, so it adds onto any other\n * position node (Growth): `position = grown + windOffset(...)` (see {@link applyWind}).\n *\n * - trunk: leans with the wind and swings slowly, bending from the ground (weight = height²);\n * - branches: swing faster, with a phase that varies smoothly in space so joints stay attached,\n * plus a little cross-wind motion;\n * - leaves: flutter along their normal, more at the tip.\n * All of it is scaled by slow gusts. Wind direction is world space; it is turned into the tree's\n * object space (rotation only, so a scaled-up tree sways proportionally more). `frame` replaces\n * that direction and the response's phase (see {@link WindFrame}).\n */\nexport function windOffset(wind: WindSource, response: WindResponse, frame: WindFrame = {}): Node<'vec3'> {\n const weights = attribute('aWind', 'vec3');\n const random = attribute('aRandom', 'float');\n const origin = attribute('aOrigin', 'vec3');\n const r = response.uniforms;\n const strength = wind.uniforms.strength;\n\n const t = wind.uniforms.time.mul(r.frequency).add(frame.phase ?? r.phase);\n const direction = (frame.direction ?? objectWindDirection(wind)).normalize();\n const across = cross(direction, vec3(0, 1, 0));\n // 0.6 .. 1: two slow, incommensurate waves.\n const gust = sin(t.mul(0.37)).add(sin(t.mul(0.91).add(1.7))).mul(0.1).add(0.8);\n const scale = strength.mul(r.height).mul(gust);\n\n const trunkSwing = sin(t.mul(1.1)).mul(0.25).add(0.75); // 0.5 .. 1: lean plus swing\n const trunk = direction.mul(trunkSwing.mul(r.trunk).mul(weights.x).mul(scale).mul(TRUNK_AMPLITUDE));\n\n const spatialPhase = dot(positionGeometry, vec3(0.9, 0.4, 0.7));\n const branchSwing = sin(t.mul(2.3).add(spatialPhase)).mul(0.35).add(0.65); // 0.3 .. 1\n const branchCross = sin(t.mul(1.7).add(spatialPhase.mul(1.3))).mul(0.3);\n const branches = direction\n .mul(branchSwing)\n .add(across.mul(branchCross))\n .mul(r.branches.mul(weights.y).mul(scale).mul(BRANCH_AMPLITUDE));\n\n const leafLength = positionGeometry.sub(origin).length();\n const flutter = sin(t.mul(9).add(random.mul(6.2832)));\n const leaves = normalGeometry.mul(\n flutter.mul(r.leaves).mul(weights.z).mul(leafLength).mul(strength).mul(gust).mul(LEAF_AMPLITUDE),\n );\n\n return trunk.add(branches).add(leaves);\n}\n\n/**\n * Adds a Wind offset to a material's vertex position (its existing `positionNode`, or the plain\n * local position). The shadow pass reuses `positionNode`, so shadows sway along.\n */\nexport function applyWind(material: NodeMaterial, offset: Node<'vec3'>): void {\n material.positionNode = material.positionNode ? (material.positionNode as Node<'vec3'>).add(offset) : positionLocal.add(offset);\n material.needsUpdate = true;\n}\n","import {\n BufferAttribute,\n BufferGeometry,\n Group,\n InterleavedBuffer,\n InterleavedBufferAttribute,\n Mesh,\n type Material,\n type MeshStandardNodeMaterial,\n type NodeMaterial,\n type UniformNode,\n} from 'three/webgpu';\nimport { uniform } from 'three/tsl';\nimport type { MaterialFeatures, TranslucencyDefinition, TreeDefinition } from '../definition';\nimport { trunkHeight, type GeometryBuffers, type TreeData } from '../generator';\nimport { clampGrowth, growthPosition } from '../growth';\nimport { createBarkMaterial, createFruitMaterial, createLeafMaterial } from '../materials';\nimport { LiveMaterialFeatures } from '../materials/material-features';\nimport { assertWebGPURenderer } from '../renderer';\nimport { applySeasonToLeafMaterial, createFruitSeasonNodes, createSeasonNodes, type SeasonUniform } from '../season';\nimport { checkedSeason } from '../season/check';\nimport { textureReady, type TextureOptions } from '../textures';\nimport { seedRandom } from '../random';\nimport { applyWind, sceneWind, windOffset, Wind, WindBinding, WindResponse } from '../wind';\n\n/**\n * The Generator's per-vertex part attributes (`aLevel`, `aSeason`, `aWind`, ...) go into one\n * interleaved vertex buffer: WebGPU allows only 8 vertex buffers per draw by default, and a\n * textured leaf already reads position, normal, uv and colour besides Growth, Season and Wind.\n */\nfunction setPartAttributes(geometry: BufferGeometry, attributes: GeometryBuffers['attributes']): void {\n const entries = Object.entries(attributes);\n const stride = entries.reduce((sum, [, a]) => sum + a.itemSize, 0);\n const count = geometry.getAttribute('position').count;\n const data = new Float32Array(count * stride);\n let offset = 0;\n for (const [, { array, itemSize }] of entries) {\n for (let v = 0; v < count; v++) {\n for (let c = 0; c < itemSize; c++) data[v * stride + offset + c] = array[v * itemSize + c]!;\n }\n offset += itemSize;\n }\n const buffer = new InterleavedBuffer(data, stride);\n offset = 0;\n for (const [name, { itemSize }] of entries) {\n geometry.setAttribute(name, new InterleavedBufferAttribute(buffer, itemSize, offset));\n offset += itemSize;\n }\n}\n\nfunction toBufferGeometry(buffers: GeometryBuffers): BufferGeometry {\n const geometry = new BufferGeometry();\n geometry.setAttribute('position', new BufferAttribute(buffers.positions, 3));\n geometry.setAttribute('normal', new BufferAttribute(buffers.normals, 3));\n geometry.setAttribute('uv', new BufferAttribute(buffers.uvs, 2));\n if (buffers.colors) geometry.setAttribute('color', new BufferAttribute(buffers.colors, 3));\n setPartAttributes(geometry, buffers.attributes);\n geometry.setIndex(new BufferAttribute(buffers.indices, 1));\n geometry.computeBoundingBox();\n geometry.computeBoundingSphere();\n return geometry;\n}\n\nfunction treeMesh<M extends Material>(name: string, geometry: BufferGeometry, material: M): Mesh<BufferGeometry, M> {\n const mesh = new Mesh(geometry, material);\n mesh.name = name;\n mesh.castShadow = true;\n mesh.receiveShadow = true;\n mesh.onBeforeRender = (renderer) => assertWebGPURenderer(renderer);\n return mesh;\n}\n\n/** Per-tree state a Tree starts with. */\nexport interface TreeOptions {\n /** Growth, 0 (sapling) .. 1 (fully grown, default). */\n growth?: number;\n /** Season, 0 (first day of spring, default) .. 1 (last day of winter). */\n season?: number;\n /** The Wind this tree sways with. Default: the scene-wide {@link sceneWind}. */\n wind?: Wind;\n /**\n * Where this tree's textures load from (base path / per-URL overrides); takes precedence over\n * the app-wide `setTextureOptions`. Only Definitions with textures (e.g. the realistic Style) use it.\n */\n textures?: TextureOptions;\n}\n\n/**\n * A generated tree as a three.js object. Add it to a scene rendered by `WebGPURenderer`.\n * `growth`, `season` and the Wind only update uniforms: no regeneration, no recompile.\n */\nexport class Tree extends Group {\n readonly isTree = true;\n readonly definition: TreeDefinition;\n readonly seed: number;\n /** The generator output this object was built from (pure data). */\n readonly data: TreeData;\n /** Trunk and branches. */\n readonly wood: Mesh<BufferGeometry, Material>;\n /** Leaf cards (empty geometry for a bare tree). */\n readonly leaves: Mesh<BufferGeometry, MeshStandardNodeMaterial>;\n /** Fruit (empty geometry when the Definition has no Fruit). */\n readonly fruit: Mesh<BufferGeometry, MeshStandardNodeMaterial>;\n /** This tree's Growth uniform (read by the wood, leaf and Fruit materials' `positionNode`). */\n readonly growthUniform: UniformNode<'float', number>;\n /** The Season uniform the leaf and Fruit materials read (shared nodes may reference it). */\n readonly seasonUniform: SeasonUniform;\n /** This tree's response to the Wind, from `definition.wind`; `windResponse.set(...)` changes it live. */\n readonly windResponse: WindResponse;\n private readonly windBinding: WindBinding;\n private readonly features: LiveMaterialFeatures;\n\n /**\n * Resolves once every texture of this tree has loaded (at once for a tree without textures);\n * rejects if one fails. Await it before a first render that must show the textures.\n */\n readonly ready: Promise<void>;\n\n constructor(definition: TreeDefinition, data: TreeData, options: TreeOptions = {}) {\n super();\n this.name = 'Tree';\n this.definition = definition;\n this.seed = data.seed;\n this.data = data;\n\n this.growthUniform = uniform(clampGrowth(options.growth ?? 1));\n const bark = createBarkMaterial(definition, options.textures, this.growthUniform);\n const leaf = createLeafMaterial(definition, options.textures);\n bark.positionNode = growthPosition(this.growthUniform);\n leaf.positionNode = growthPosition(this.growthUniform);\n this.wood = treeMesh('wood', toBufferGeometry(data.wood), bark);\n this.leaves = treeMesh('leaves', toBufferGeometry(data.leaves), leaf);\n const textures = [bark.map, bark.normalMap, leaf.map].filter((t) => t !== null);\n this.ready = Promise.all(textures.map(textureReady)).then(() => undefined);\n this.ready.catch(() => {}); // only reported to whoever awaits it\n const fruit = createFruitMaterial(definition);\n this.fruit = treeMesh('fruit', toBufferGeometry(data.fruit), fruit);\n this.add(this.wood, this.leaves, this.fruit);\n\n this.windBinding = new WindBinding(options.wind ?? sceneWind);\n this.windResponse = new WindResponse(definition.wind, {\n height: trunkHeight(data.skeleton),\n phase: seedRandom(data.seed, 'wind') * Math.PI * 2,\n });\n const offset = windOffset(this.windBinding, this.windResponse);\n applyWind(this.wood.material as NodeMaterial, offset);\n applyWind(this.leaves.material, offset);\n\n const season = createSeasonNodes(definition.season);\n applySeasonToLeafMaterial(this.leaves.material, season);\n this.seasonUniform = season.season;\n // Fruit: Season scales it about its attachment point, then Growth, then Wind (with its twig).\n const fruitSeason = createFruitSeasonNodes(definition.season, this.seasonUniform);\n fruit.colorNode = fruitSeason.color;\n fruit.positionNode = growthPosition(this.growthUniform, fruitSeason.position);\n applyWind(fruit, offset);\n this.season = options.season ?? 0;\n this.features = new LiveMaterialFeatures(definition, [\n { leaf, materials: [bark, leaf, fruit], crown: data.crown, growth: this.growthUniform },\n ]);\n }\n\n /**\n * Crown Normals amount (0..1), from the Definition's `materials.leaf.crownNormals`; null when it is off.\n * Setting it (clamped to 0..1) only writes a uniform: no regeneration, no recompile. Throws on a\n * tree without Crown Normals (switching the feature on needs a new tree).\n */\n get crownNormals(): number | null {\n return this.features.crownNormals;\n }\n\n set crownNormals(value: number) {\n this.features.crownNormals = value;\n }\n\n /**\n * Leaf Translucency settings (a copy), from the Definition's `materials.leaf.translucency`; null when it\n * is off. Setting any of them (each clamped to 0..1, the others kept) only writes uniforms: no\n * regeneration, no recompile. Throws on a tree without Leaf Translucency.\n */\n get translucency(): TranslucencyDefinition | null {\n return this.features.translucency;\n }\n\n set translucency(value: Partial<TranslucencyDefinition>) {\n this.features.translucency = value;\n }\n\n /**\n * The Material Features this tree shows, with their current (possibly live-tuned) values: the\n * Definition's (see `materialFeaturesOf`), except that Crown Normals at 0 count as off.\n */\n get materialFeatures(): MaterialFeatures {\n return this.features.values;\n }\n\n /**\n * Structural Occlusion strength (0..1), from the Definition's `materials.occlusion`; null when it has none.\n * Setting it (clamped to 0..1) only writes a uniform: no regeneration, no recompile. Throws on a tree\n * without Structural Occlusion (there is no baked occlusion to show).\n */\n get occlusionStrength(): number | null {\n return this.features.occlusionStrength;\n }\n\n set occlusionStrength(value: number) {\n this.features.occlusionStrength = value;\n }\n\n /**\n * The Wind this tree sways with (shared with every other tree using it). Assigning another\n * Wind only rebinds uniforms: no regeneration, no recompile.\n */\n get wind(): Wind {\n return this.windBinding.wind;\n }\n\n set wind(value: Wind) {\n this.windBinding.wind = value;\n }\n\n /**\n * Season: 0 (first day of spring) .. 1 (last day of winter); sets leaf colour, leaf coverage,\n * blossom and Fruit (amount, size, colour) from the Definition's Season Profile. Values outside 0..1 wrap around the year.\n * Only updates a uniform, so it is cheap to animate.\n */\n get season(): number {\n return this.seasonUniform.value;\n }\n\n set season(value: number) {\n this.seasonUniform.value = checkedSeason(value);\n }\n\n /**\n * How far this tree has grown: 0 (sapling) .. 1 (fully grown); values outside are clamped.\n * Setting it only writes a uniform, so it is cheap to animate every frame.\n */\n get growth(): number {\n return this.growthUniform.value;\n }\n\n set growth(value: number) {\n this.growthUniform.value = clampGrowth(value);\n }\n\n /** Frees the GPU resources (geometries and materials) of this tree and removes it from its parent. */\n override dispose(): void {\n this.traverse((object) => {\n if (object instanceof Mesh) {\n object.geometry.dispose();\n const materials = Array.isArray(object.material) ? object.material : [object.material];\n for (const material of materials) material.dispose();\n }\n });\n this.removeFromParent();\n super.dispose();\n }\n}\n","import { parseDefinition, type TreeDefinition, type TreeDefinitionInput } from '../definition';\nimport { generateTree } from '../generator';\nimport { Tree, type TreeOptions } from './Tree';\n\nexport { Tree, type TreeOptions } from './Tree';\n\nexport interface CreateTreeOptions extends TreeOptions {\n /** Picks one individual tree within the Definition's ranges. Default 0. */\n seed?: number;\n}\n\n/**\n * Grows a tree from a Tree Definition (plain object or parsed JSON) and a Seed and\n * returns a three.js object to add to a scene rendered by `WebGPURenderer`.\n * Throws `TreeDefinitionError` for an invalid Definition.\n */\nexport function createTree(\n definition: TreeDefinitionInput | TreeDefinition,\n options: CreateTreeOptions = {},\n): Tree {\n const parsed = parseDefinition(definition);\n const seed = options.seed ?? 0;\n return new Tree(parsed, generateTree(parsed, seed), {\n growth: options.growth,\n wind: options.wind,\n season: options.season,\n textures: options.textures,\n });\n}\n","import { STYLE_NAMES, type StyleName } from './names';\nimport type { TreeStyle } from './types';\n\nexport { STYLE_NAMES, styleLabel, styleOfShading, styleShading, type StyleName } from './names';\n\n/**\n * The built-in Styles, each a lazily loaded chunk (`@casmo/tree.js/styles/<name>`).\n * To add a Style: its name, label and shading in names.ts, its loader here, its look in apply.ts\n * (plus its vite entry and package.json export). The editor and the scripts read these lists.\n */\nconst STYLE_LOADERS: Record<StyleName, () => Promise<{ default: TreeStyle }>> = {\n 'low-poly': () => import('./low-poly'),\n stylized: () => import('./stylized'),\n realistic: () => import('./realistic'),\n};\n\n/** Downloads a built-in Style (dynamic import) and resolves to it. Rejects for an unknown name. */\nexport async function loadStyle(name: StyleName): Promise<TreeStyle> {\n const load = (STYLE_LOADERS as Partial<Record<string, () => Promise<{ default: TreeStyle }>>>)[name];\n if (!load) throw new Error(`Unknown tree.js Style \"${name}\". Built-in Styles: ${STYLE_NAMES.join(', ')}.`);\n return (await load()).default;\n}\n","import type { Node } from 'three/webgpu';\nimport { attribute, cross, positionGeometry, positionLocal } from 'three/tsl';\nimport { growthPosition } from '../growth';\nimport { objectWindDirection, windOffset, type WindResponse, type WindSource } from '../wind';\n\n/**\n * Per-instance data of a Forest (one interleaved instanced buffer, 8 floats per tree):\n * `iRotation` = the tree's rotation as a quaternion (x, y, z, w);\n * `iState` = (scale, Growth, Season, Wind phase), Growth/Season already include the tree's offsets.\n */\nexport const INSTANCE_STRIDE = 8;\nexport const INSTANCE_ATTRIBUTES = { iRotation: 0, iState: 4 } as const;\n\n/** Per-tree values in the instanced Season/Growth/Wind slots. */\nexport function instanceState(): { scale: Node<'float'>; growth: Node<'float'>; season: Node<'float'>; windPhase: Node<'float'> } {\n const state = attribute<'vec4'>('iState', 'vec4');\n return { scale: state.x, growth: state.y, season: state.z, windPhase: state.w };\n}\n\n/** Rotates `v` by the instance quaternion (`inverse` = by its conjugate): tree space to forest space. */\nexport function instanceRotate(v: Node<'vec3'>, inverse = false): Node<'vec3'> {\n const q = attribute<'vec4'>('iRotation', 'vec4');\n const u = inverse ? q.xyz.negate() : q.xyz;\n const t = cross(u, v).mul(2);\n return v.add(t.mul(q.w)).add(cross(u, t));\n}\n\n/**\n * The vertex position of a Forest tree (positionNode of an instanced Variant mesh).\n *\n * On an InstancedMesh, three.js applies the instance matrix to `positionLocal` before\n * `positionNode` runs, but Growth and Wind are defined in the tree's own space (about the\n * generated `aOrigin`s, relative to its trunk height). So both are computed from\n * `positionGeometry`, and only their displacement is turned into forest space with the\n * instance rotation and scale: M·(p + d) = M·p + R·s·d. The Wind direction goes the other way\n * (forest -> tree space) and each tree sways with its own phase.\n *\n * `base`: the tree-space position Growth starts from (default `positionGeometry`); Fruit passes\n * its Season-scaled position here.\n */\nexport function forestPosition(wind: WindSource, response: WindResponse, base: Node<'vec3'> = positionGeometry): Node<'vec3'> {\n const { scale, growth, windPhase } = instanceState();\n const grown = growthPosition(growth, base);\n const offset = windOffset(wind, response, { direction: instanceRotate(objectWindDirection(wind), true), phase: windPhase });\n const displacement = grown.add(offset).sub(positionGeometry);\n return positionLocal.add(instanceRotate(displacement).mul(scale));\n}\n","// Pure Forest bookkeeping (no three.js): tree keys and the per-tree hash.\nimport type { VariationDefinition } from '../definition';\nimport type { Vec3 } from '../generator';\nimport { createRandom, hashCombine, seedToUint32 } from '../random';\nimport { clampGrowth } from '../growth/evaluate';\nimport { wrapSeason } from '../season/profile';\n\n/** Where one tree of a Forest stands. */\nexport interface ForestPlacement {\n /** Position of the tree base, in the Forest's space. */\n position: Vec3 | { x: number; y: number; z: number };\n /** Radians: a number turns the tree about the vertical (Y) axis; [x, y, z] is an Euler rotation (XYZ order). Default 0. */\n rotation?: number | Vec3;\n /** Uniform scale. Default 1. */\n scale?: number;\n /**\n * A stable id. A tree's Variant and offsets come from it, so the tree keeps its look when it is\n * moved. Without an id they come from the position (rounded to 1 mm).\n */\n id?: string | number;\n}\n\n/** What the forest seed and a tree's key decide about that tree. */\nexport interface ForestTreeTraits {\n /** Which Variant (0 .. variants-1) the tree is drawn as. */\n variant: number;\n /** 0 .. `variation.growth`: how far behind the forest's Growth this tree grows. */\n growthDelay: number;\n /** Within ± `variation.season`: how far this tree's Season is shifted. */\n seasonShift: number;\n /** Radians, 0 .. 2π: so trees of one Variant do not sway in step. */\n windPhase: number;\n}\n\nexport function placementPosition(placement: ForestPlacement): Vec3 {\n const p = placement.position;\n const v: Vec3 = Array.isArray(p) ? [p[0], p[1], p[2]] : [(p as { x: number }).x, (p as { y: number }).y, (p as { z: number }).z];\n if (!v.every(Number.isFinite)) throw new RangeError(`Forest placement position must be finite, got [${v.join(', ')}]`);\n return v;\n}\n\n/**\n * The key a tree is known by: its id as a string (so ids 1 and \"1\" are the same tree), or\n * `@x,y,z` (position in millimetres) when it has no id.\n */\nexport function forestTreeKey(placement: ForestPlacement): string {\n if (placement.id !== undefined) return String(placement.id);\n const mm = placementPosition(placement).map((c) => Math.round(c * 1000) || 0); // `|| 0` folds -0 into 0\n return `@${mm.join(',')}`;\n}\n\n/** The Seed of Variant `index` of a forest. */\nexport function variantSeed(forestSeed: number, index: number): number {\n return hashCombine(seedToUint32(forestSeed), 0x7a71a7, index);\n}\n\n/**\n * A tree's Variant and offsets: a hash of the forest seed and the tree's key only, so they never\n * depend on the tree's index in the list or on which other trees exist.\n */\nexport function forestTreeTraits(\n forestSeed: number,\n key: string,\n variants: number,\n variation: Pick<VariationDefinition, 'growth' | 'season'>,\n): ForestTreeTraits {\n const random = createRandom(forestSeed).fork('forest').fork(key);\n return {\n variant: random.int(0, variants - 1),\n growthDelay: random.next() * variation.growth,\n seasonShift: (random.next() * 2 - 1) * variation.season,\n windPhase: random.next() * Math.PI * 2,\n };\n}\n\n/**\n * The Growth one tree is drawn at, for a Growth `growth` set on it: delayed by its `growthDelay`\n * but still exactly 0 at Growth 0 and 1 at Growth 1, so a fully grown forest is fully grown.\n */\nexport function delayedGrowth(growth: number, delay: number): number {\n const g = clampGrowth(growth);\n return delay > 0 ? clampGrowth((g - delay) / (1 - delay)) : g;\n}\n\n/** The Season one tree is drawn at: the Season set on it plus its shift, wrapped into 0..1. */\nexport function shiftedSeason(season: number, shift: number): number {\n return wrapSeason(season + shift);\n}\n","import {\n BufferAttribute,\n BufferGeometry,\n DynamicDrawUsage,\n Euler,\n Group,\n InstancedBufferAttribute,\n InstancedInterleavedBuffer,\n InstancedMesh,\n InterleavedBuffer,\n InterleavedBufferAttribute,\n Matrix4,\n Quaternion,\n Vector3,\n type MeshStandardNodeMaterial,\n} from 'three/webgpu';\nimport { positionGeometry } from 'three/tsl';\nimport type { MaterialFeatures, TranslucencyDefinition, TreeDefinition } from '../definition';\nimport { generateTree, trunkHeight, type GeometryBuffers, type TreeData } from '../generator';\nimport { createBarkMaterial, createFruitMaterial, createLeafMaterial } from '../materials';\nimport { LiveMaterialFeatures, type MaterialFeatureTarget } from '../materials/material-features';\nimport { assertWebGPURenderer } from '../renderer';\nimport { applySeasonToLeafMaterial, createFruitSeasonNodes, createSeasonNodes } from '../season';\nimport { checkedSeason } from '../season/check';\nimport { clampGrowth } from '../growth';\nimport { textureReady, type TextureOptions } from '../textures';\nimport { sceneWind, Wind, WindBinding, WindResponse, type WindSource } from '../wind';\nimport { INSTANCE_ATTRIBUTES, INSTANCE_STRIDE, forestPosition, instanceRotate, instanceState } from './nodes';\nimport {\n delayedGrowth,\n forestTreeKey,\n forestTreeTraits,\n placementPosition,\n shiftedSeason,\n variantSeed,\n type ForestPlacement,\n type ForestTreeTraits,\n} from './placement';\n\n/** Options of {@link createForest}. */\nexport interface ForestOptions {\n /** How many Variants (distinct trees, each drawn instanced) the forest is made of. Default 4. */\n variants?: number;\n /** The forest seed: picks the Variants and every tree's Variant and offsets. Default 0. */\n seed?: number;\n /** Growth every tree starts at, 0..1. Default 1 (fully grown). */\n growth?: number;\n /** Season every tree starts at, 0..1. Default 0. */\n season?: number;\n /** The Wind the forest sways with. Default: the scene-wide `sceneWind`. */\n wind?: Wind;\n /** Where the Definition's textures load from (as `createTree(..., { textures })`). */\n textures?: TextureOptions;\n}\n\n/** What the GPU draws one tree with (after its offsets). */\nexport interface ForestInstanceState {\n growth: number;\n season: number;\n windPhase: number;\n}\n\nconst MIN_CAPACITY = 16;\n// Room for Wind sway in the instance bounding spheres (fraction of the trunk height).\nconst WIND_BOUNDS = 0.35;\n\n/**\n * One tree of a {@link Forest}. Its Variant and offsets come from the forest seed and its key\n * only. `growth` and `season` are what the app sets on this tree; the tree draws them with its\n * offsets applied (see {@link Forest.instanceState}).\n */\nexport class ForestTree implements ForestTreeTraits {\n /** The tree's id as a string, or `@x,y,z` (position in mm) when it was placed without an id. */\n readonly key: string;\n readonly placement: Readonly<ForestPlacement>;\n readonly variant: number;\n readonly growthDelay: number;\n readonly seasonShift: number;\n readonly windPhase: number;\n /** @internal Slot in the Variant's instance buffers. */\n slot = -1;\n private growthValue: number;\n private seasonValue: number;\n\n /** @internal Use {@link Forest.addTree}. */\n constructor(\n key: string,\n placement: ForestPlacement,\n traits: ForestTreeTraits,\n state: { growth: number; season: number },\n private readonly onChange: (tree: ForestTree) => void,\n ) {\n this.key = key;\n this.placement = placement;\n this.variant = traits.variant;\n this.growthDelay = traits.growthDelay;\n this.seasonShift = traits.seasonShift;\n this.windPhase = traits.windPhase;\n this.growthValue = clampGrowth(state.growth);\n this.seasonValue = checkedSeason(state.season);\n }\n\n /** Growth set on this tree, 0..1 (clamped). Only rewrites this tree's instance data. */\n get growth(): number {\n return this.growthValue;\n }\n\n set growth(value: number) {\n this.growthValue = clampGrowth(value);\n this.onChange(this);\n }\n\n /** Season set on this tree, 0..1 (wraps around the year). Only rewrites this tree's instance data. */\n get season(): number {\n return this.seasonValue;\n }\n\n set season(value: number) {\n this.seasonValue = checkedSeason(value);\n this.onChange(this);\n }\n}\n\n/** Packs generator buffers into one interleaved vertex buffer, so a Variant takes a single vertex buffer slot. */\nfunction interleavedGeometry(buffers: GeometryBuffers, boundsMargin: number): BufferGeometry {\n const parts: [string, Float32Array, number][] = [\n ['position', buffers.positions, 3],\n ['normal', buffers.normals, 3],\n ['uv', buffers.uvs, 2],\n ];\n if (buffers.colors) parts.push(['color', buffers.colors, 3]);\n for (const [name, { array, itemSize }] of Object.entries(buffers.attributes)) parts.push([name, array, itemSize]);\n\n const count = buffers.positions.length / 3;\n const stride = parts.reduce((sum, [, , size]) => sum + size, 0);\n const data = new Float32Array(count * stride);\n const interleaved = new InterleavedBuffer(data, stride);\n const geometry = new BufferGeometry();\n let offset = 0;\n for (const [name, array, size] of parts) {\n for (let v = 0; v < count; v++) {\n for (let c = 0; c < size; c++) data[v * stride + offset + c] = array[v * size + c]!;\n }\n geometry.setAttribute(name, new InterleavedBufferAttribute(interleaved, size, offset));\n offset += size;\n }\n geometry.setIndex(new BufferAttribute(buffers.indices, 1));\n geometry.computeBoundingBox();\n geometry.computeBoundingSphere();\n geometry.boundingSphere!.radius += boundsMargin;\n geometry.boundingBox!.expandByScalar(boundsMargin);\n return geometry;\n}\n\n/** Copies a geometry's attributes into a new geometry (shares the vertex data). */\nfunction shareGeometry(source: BufferGeometry): BufferGeometry {\n const geometry = new BufferGeometry();\n for (const [name, attribute] of Object.entries(source.attributes)) geometry.setAttribute(name, attribute);\n geometry.setIndex(source.getIndex());\n geometry.boundingBox = source.boundingBox!.clone();\n geometry.boundingSphere = source.boundingSphere!.clone();\n return geometry;\n}\n\n/**\n * One Variant of a Forest: one Seed's tree, drawn once per tree that uses it with an instanced\n * wood mesh, an instanced leaf mesh and, when the Definition has Fruit, an instanced fruit mesh\n * (one draw call per material). All three share one instance matrix buffer.\n */\nexport class ForestVariant {\n readonly index: number;\n readonly seed: number;\n readonly data: TreeData;\n /** This Variant's response to the Wind (trunk height from its Seed; each tree has its own phase). */\n readonly windResponse: WindResponse;\n readonly barkMaterial: MeshStandardNodeMaterial;\n readonly leafMaterial: MeshStandardNodeMaterial;\n /** Fruit material, null when the Definition has no Fruit. */\n readonly fruitMaterial: MeshStandardNodeMaterial | null;\n /** The trees drawn as this Variant, in instance order. */\n readonly trees: ForestTree[] = [];\n private woodMesh!: InstancedMesh<BufferGeometry, MeshStandardNodeMaterial>;\n private leafMesh!: InstancedMesh<BufferGeometry, MeshStandardNodeMaterial>;\n private fruitMesh: InstancedMesh<BufferGeometry, MeshStandardNodeMaterial> | null = null;\n private instanceData!: InstancedInterleavedBuffer;\n private readonly woodSource: BufferGeometry;\n private readonly leafSource: BufferGeometry;\n private readonly fruitSource: BufferGeometry | null;\n\n constructor(\n private readonly forest: Forest,\n definition: TreeDefinition,\n index: number,\n seed: number,\n wind: WindSource,\n capacity: number,\n textures?: TextureOptions,\n ) {\n this.index = index;\n this.seed = seed;\n this.data = generateTree(definition, seed);\n const height = trunkHeight(this.data.skeleton);\n this.windResponse = new WindResponse(definition.wind, { height, phase: 0 });\n\n const position = forestPosition(wind, this.windResponse);\n this.barkMaterial = createBarkMaterial(definition, textures, instanceState().growth);\n this.barkMaterial.positionNode = position;\n this.leafMaterial = createLeafMaterial(definition, textures);\n this.leafMaterial.positionNode = position;\n applySeasonToLeafMaterial(this.leafMaterial, createSeasonNodes(definition.season, instanceState().season));\n\n this.woodSource = interleavedGeometry(this.data.wood, height * WIND_BOUNDS);\n this.leafSource = interleavedGeometry(this.data.leaves, height * WIND_BOUNDS);\n\n if (this.data.fruit.indices.length > 0) {\n // As on a Tree: Season scales each Fruit about its attachment point, then Growth and Wind.\n const fruitSeason = createFruitSeasonNodes(definition.season, instanceState().season, positionGeometry);\n this.fruitMaterial = createFruitMaterial(definition);\n this.fruitMaterial.colorNode = fruitSeason.color;\n this.fruitMaterial.positionNode = forestPosition(wind, this.windResponse, fruitSeason.position);\n this.fruitSource = interleavedGeometry(this.data.fruit, height * WIND_BOUNDS);\n } else {\n this.fruitMaterial = null;\n this.fruitSource = null;\n }\n this.allocate(capacity);\n }\n\n /** Instanced mesh of trunks and branches. Replaced (not resized) when the Variant outgrows its capacity. */\n get wood(): InstancedMesh<BufferGeometry, MeshStandardNodeMaterial> {\n return this.woodMesh;\n }\n\n /** Instanced mesh of the leaves. Replaced along with {@link wood}. */\n get leaves(): InstancedMesh<BufferGeometry, MeshStandardNodeMaterial> {\n return this.leafMesh;\n }\n\n /** Instanced mesh of the Fruit (null when the Definition has no Fruit). Replaced along with {@link wood}. */\n get fruit(): InstancedMesh<BufferGeometry, MeshStandardNodeMaterial> | null {\n return this.fruitMesh;\n }\n\n /** The Variant's meshes: wood, leaves and (with Fruit) fruit. */\n get meshes(): InstancedMesh<BufferGeometry, MeshStandardNodeMaterial>[] {\n return this.fruitMesh ? [this.woodMesh, this.leafMesh, this.fruitMesh] : [this.woodMesh, this.leafMesh];\n }\n\n get capacity(): number {\n return this.instanceData.count;\n }\n\n /** @internal */\n add(tree: ForestTree): void {\n if (this.trees.length === this.capacity) this.allocate(this.capacity * 2);\n tree.slot = this.trees.length;\n this.trees.push(tree);\n this.write(tree);\n this.setCount();\n }\n\n /** @internal Swap-removes a tree: the last tree takes its slot. */\n remove(tree: ForestTree): void {\n const last = this.trees.pop()!;\n if (last !== tree) {\n last.slot = tree.slot;\n this.trees[last.slot] = last;\n this.write(last);\n }\n tree.slot = -1;\n this.setCount();\n }\n\n /** @internal Writes one tree's transform and state into its instance slot. */\n write(tree: ForestTree): void {\n const i = tree.slot;\n const { placement } = tree;\n const position = new Vector3(...placementPosition(placement));\n const rotation = placement.rotation ?? 0;\n const quaternion = new Quaternion().setFromEuler(\n typeof rotation === 'number' ? new Euler(0, rotation, 0) : new Euler(rotation[0], rotation[1], rotation[2]),\n );\n const scale = placement.scale ?? 1;\n this.woodMesh.setMatrixAt(i, new Matrix4().compose(position, quaternion, new Vector3(scale, scale, scale)));\n this.woodMesh.instanceMatrix.needsUpdate = true;\n\n const array = this.instanceData.array as Float32Array;\n array.set(\n [\n quaternion.x,\n quaternion.y,\n quaternion.z,\n quaternion.w,\n scale,\n delayedGrowth(tree.growth, tree.growthDelay),\n shiftedSeason(tree.season, tree.seasonShift),\n tree.windPhase,\n ],\n i * INSTANCE_STRIDE,\n );\n this.instanceData.needsUpdate = true;\n for (const mesh of this.meshes) mesh.boundingSphere = mesh.boundingBox = null;\n }\n\n /** @internal */\n state(tree: ForestTree): ForestInstanceState {\n const o = tree.slot * INSTANCE_STRIDE;\n const array = this.instanceData.array as Float32Array;\n return { growth: array[o + 5]!, season: array[o + 6]!, windPhase: array[o + 7]! };\n }\n\n /** @internal Frees the GPU resources. */\n dispose(): void {\n this.disposeMeshes();\n this.woodSource.dispose();\n this.leafSource.dispose();\n this.fruitSource?.dispose();\n this.barkMaterial.dispose();\n this.leafMaterial.dispose();\n this.fruitMaterial?.dispose();\n }\n\n private setCount(): void {\n for (const mesh of this.meshes) mesh.count = this.trees.length;\n }\n\n /**\n * (Re)builds the instanced meshes with room for `capacity` trees. An InstancedMesh cannot grow,\n * so a full Variant gets new meshes (same materials and vertex data) of twice the size.\n */\n private allocate(capacity: number): void {\n const instanceData = new InstancedInterleavedBuffer(new Float32Array(capacity * INSTANCE_STRIDE), INSTANCE_STRIDE, 1);\n instanceData.setUsage(DynamicDrawUsage);\n const matrices = new InstancedBufferAttribute(new Float32Array(capacity * 16), 16);\n matrices.setUsage(DynamicDrawUsage);\n if (this.woodMesh) {\n instanceData.array.set(this.instanceData.array);\n matrices.array.set(this.woodMesh.instanceMatrix.array);\n this.disposeMeshes();\n }\n this.instanceData = instanceData;\n\n const mesh = (name: string, source: BufferGeometry, material: MeshStandardNodeMaterial) => {\n const geometry = shareGeometry(source);\n for (const [attribute, offset] of Object.entries(INSTANCE_ATTRIBUTES)) {\n geometry.setAttribute(attribute, new InterleavedBufferAttribute(instanceData, 4, offset));\n }\n const instanced = new InstancedMesh(geometry, material, capacity);\n instanced.instanceMatrix = matrices; // wood, leaves and fruit share one matrix buffer\n instanced.name = `${name} ${this.index}`;\n instanced.castShadow = true;\n instanced.receiveShadow = true;\n instanced.onBeforeRender = (renderer) => assertWebGPURenderer(renderer);\n return instanced;\n };\n this.woodMesh = mesh('forest wood', this.woodSource, this.barkMaterial);\n this.leafMesh = mesh('forest leaves', this.leafSource, this.leafMaterial);\n if (this.fruitSource && this.fruitMaterial) this.fruitMesh = mesh('forest fruit', this.fruitSource, this.fruitMaterial);\n this.setCount();\n this.forest.add(...this.meshes);\n }\n\n private disposeMeshes(): void {\n for (const mesh of this.meshes) {\n mesh.removeFromParent();\n mesh.geometry.dispose();\n mesh.dispose();\n }\n }\n}\n\n/**\n * Many trees of one Tree Definition, drawn from a few shared Variants (one instanced mesh per\n * Variant and material). Each tree's Variant and its small Growth/Season offsets come from a\n * hash of the forest seed and the tree's id (or position), never from its index, so adding or\n * removing trees never changes the others. Growth and Season can be set per tree or for all.\n */\nexport class Forest extends Group {\n readonly isForest = true;\n readonly definition: TreeDefinition;\n /** The forest seed. */\n readonly seed: number;\n readonly variants: readonly ForestVariant[];\n /** Resolves once every texture has loaded (at once without textures); rejects if one fails. */\n readonly ready: Promise<void>;\n private readonly byKey = new Map<string, ForestTree>();\n private readonly windBinding: WindBinding;\n private growthValue: number;\n private seasonValue: number;\n private readonly features: LiveMaterialFeatures;\n\n constructor(definition: TreeDefinition, placements: readonly ForestPlacement[] = [], options: ForestOptions = {}) {\n super();\n const count = options.variants ?? 4;\n if (!Number.isInteger(count) || count < 1) throw new RangeError(`Forest variants must be an integer >= 1, got ${count}`);\n this.name = 'Forest';\n this.definition = definition;\n this.seed = options.seed ?? 0;\n this.windBinding = new WindBinding(options.wind ?? sceneWind);\n this.growthValue = clampGrowth(options.growth ?? 1);\n this.seasonValue = checkedSeason(options.season ?? 0);\n\n const capacity = Math.max(MIN_CAPACITY, 2 ** Math.ceil(Math.log2(Math.max(1, (placements.length / count) * 1.25))));\n this.variants = Array.from(\n { length: count },\n (_, i) => new ForestVariant(this, definition, i, variantSeed(this.seed, i), this.windBinding, capacity, options.textures),\n );\n // Material Features: one set of values for the whole forest; each Variant has its own Crown Volume and\n // baked `aOcclusion`. The Crown Volume is in tree space: its normal turns with the instance (uniform\n // scale: rotation only).\n this.features = new LiveMaterialFeatures(\n definition,\n this.variants.map((v): MaterialFeatureTarget => ({\n leaf: v.leafMaterial,\n materials: [v.barkMaterial, v.leafMaterial, v.fruitMaterial],\n crown: v.data.crown,\n growth: instanceState().growth,\n toObject: (normal) => instanceRotate(normal),\n })),\n );\n const textures = this.variants.flatMap((v) => [v.barkMaterial.map, v.barkMaterial.normalMap, v.leafMaterial.map]);\n this.ready = Promise.all(textures.filter((t) => t !== null).map(textureReady)).then(() => undefined);\n this.ready.catch(() => {}); // only reported to whoever awaits it\n for (const placement of placements) this.addTree(placement);\n }\n\n /**\n * The Wind every tree of this forest sways with. Assigning another Wind only rebinds uniforms:\n * no rebuild, no recompile.\n */\n get wind(): Wind {\n return this.windBinding.wind;\n }\n\n set wind(value: Wind) {\n this.windBinding.wind = value;\n }\n\n /** Every tree, in the order they were added. */\n get trees(): readonly ForestTree[] {\n return [...this.byKey.values()];\n }\n\n /** Number of trees. */\n get size(): number {\n return this.byKey.size;\n }\n\n /** The tree with this key (its id as a string, or `ForestTree.key`). */\n get(key: string | number): ForestTree | undefined {\n return this.byKey.get(String(key));\n }\n\n /**\n * Plants a tree. Throws if a tree with the same id (or, without ids, the same position) exists.\n * It starts at the forest's current Growth and Season.\n */\n addTree(placement: ForestPlacement): ForestTree {\n const key = forestTreeKey(placement);\n if (this.byKey.has(key)) {\n throw new Error(\n placement.id !== undefined\n ? `Forest already has a tree with id \"${placement.id}\"`\n : `Forest already has a tree at position ${key.slice(1)} (mm); give the trees an id to place them on the same spot`,\n );\n }\n const traits = forestTreeTraits(this.seed, key, this.variants.length, this.definition.variation);\n const frozen = {\n ...placement,\n position: placementPosition(placement),\n rotation: Array.isArray(placement.rotation) ? [...(placement.rotation as number[])] : placement.rotation,\n } as ForestPlacement;\n const tree = new ForestTree(key, Object.freeze(frozen), traits, { growth: this.growthValue, season: this.seasonValue }, (t) =>\n this.variants[t.variant]!.write(t),\n );\n this.byKey.set(key, tree);\n this.variants[tree.variant]!.add(tree);\n return tree;\n }\n\n /** Cuts a tree (by key or object). Returns false if it is not in this forest. Other trees keep their look. */\n removeTree(tree: ForestTree | string | number): boolean {\n const found = typeof tree === 'object' ? this.byKey.get(tree.key) : this.get(tree);\n if (!found || (typeof tree === 'object' && found !== tree)) return false;\n this.byKey.delete(found.key);\n this.variants[found.variant]!.remove(found);\n return true;\n }\n\n /** The tree drawn by instance `instanceId` of a Variant mesh, e.g. from a raycast intersection. */\n treeAt(intersection: { object: unknown; instanceId?: number }): ForestTree | undefined {\n const variant = this.variants.find((v) => v.meshes.includes(intersection.object as InstancedMesh<BufferGeometry, MeshStandardNodeMaterial>));\n return variant && intersection.instanceId !== undefined ? variant.trees[intersection.instanceId] : undefined;\n }\n\n /** What the GPU draws a tree with: its Growth and Season after its offsets, and its Wind phase. */\n instanceState(tree: ForestTree | string | number): ForestInstanceState {\n const found = typeof tree === 'object' ? tree : this.get(tree);\n if (!found || found.slot < 0) throw new Error(`No tree \"${String(typeof tree === 'object' ? tree.key : tree)}\" in this Forest`);\n return this.variants[found.variant]!.state(found);\n }\n\n /** Growth of the whole forest: setting it sets every tree's Growth (and that of trees planted later). */\n get growth(): number {\n return this.growthValue;\n }\n\n set growth(value: number) {\n this.growthValue = clampGrowth(value);\n for (const tree of this.byKey.values()) tree.growth = this.growthValue;\n }\n\n /** Season of the whole forest: setting it sets every tree's Season (and that of trees planted later). */\n get season(): number {\n return this.seasonValue;\n }\n\n set season(value: number) {\n this.seasonValue = checkedSeason(value);\n for (const tree of this.byKey.values()) tree.season = this.seasonValue;\n }\n\n /**\n * Crown Normals amount (0..1), from the Definition's `materials.leaf.crownNormals`; null when it is off.\n * Setting it (clamped to 0..1) only writes a uniform: no regeneration, no recompile. Throws on a\n * forest without Crown Normals (switching the feature on needs a new forest).\n */\n get crownNormals(): number | null {\n return this.features.crownNormals;\n }\n\n set crownNormals(value: number) {\n this.features.crownNormals = value;\n }\n\n /**\n * Leaf Translucency settings (a copy), from the Definition's `materials.leaf.translucency`; null when it\n * is off. Setting any of them (each clamped to 0..1, the others kept) only writes uniforms: no\n * regeneration, no recompile. Throws on a forest without Leaf Translucency.\n */\n get translucency(): TranslucencyDefinition | null {\n return this.features.translucency;\n }\n\n set translucency(value: Partial<TranslucencyDefinition>) {\n this.features.translucency = value;\n }\n\n /**\n * The Material Features this forest shows, with their current (possibly live-tuned) values: the\n * Definition's (see `materialFeaturesOf`), except that Crown Normals at 0 count as off.\n */\n get materialFeatures(): MaterialFeatures {\n return this.features.values;\n }\n\n /**\n * Structural Occlusion strength (0..1) of every tree, from the Definition's `materials.occlusion`; null\n * when it has none. Setting it (clamped to 0..1) only writes a uniform. Throws without Structural Occlusion.\n */\n get occlusionStrength(): number | null {\n return this.features.occlusionStrength;\n }\n\n set occlusionStrength(value: number) {\n this.features.occlusionStrength = value;\n }\n\n /** Frees every Variant's geometries, materials and instance buffers, and removes the forest from its parent. */\n override dispose(): void {\n for (const variant of this.variants) variant.dispose();\n this.byKey.clear();\n this.removeFromParent();\n super.dispose();\n }\n}\n","import { parseDefinition, type TreeDefinition, type TreeDefinitionInput } from '../definition';\nimport { Forest, type ForestOptions } from './Forest';\nimport type { ForestPlacement } from './placement';\n\nexport { Forest, ForestTree, ForestVariant, type ForestOptions, type ForestInstanceState } from './Forest';\nexport type { ForestPlacement, ForestTreeTraits } from './placement';\n\n/**\n * Places many trees of one Tree Definition cheaply: `variants` Seeds are generated once and each\n * is drawn instanced. Each tree's Variant and small Growth/Season offsets come from a hash of\n * the forest `seed` and the tree's id (or position), so the same seed and placements always give\n * the same forest, and adding or removing a tree never changes the others.\n * Throws `TreeDefinitionError` for an invalid Definition.\n */\nexport function createForest(\n definition: TreeDefinitionInput | TreeDefinition,\n placements: readonly ForestPlacement[] = [],\n options: ForestOptions = {},\n): Forest {\n return new Forest(parseDefinition(definition), placements, options);\n}\n"],"mappings":";;;;;;;;;;;AAQA,IAAM,aAAa;AACnB,IAAM,YAAY;;AAGlB,SAAgB,WAAW,OAAuB;CAChD,IAAI,IAAI;CACR,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,IAAI,MAAM,WAAW,CAAC;EAC5B,KAAK,IAAI;EACT,IAAI,KAAK,KAAK,GAAG,SAAS;EAC1B,IAAI,IAAI,KAAM;GACZ,KAAK,MAAM;GACX,IAAI,KAAK,KAAK,GAAG,SAAS;EAC5B;CACF;CACA,OAAO,MAAM;AACf;;AAGA,SAAg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