@casmo/tree.js 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/README.md +775 -4
  2. package/dist/effects/custom.d.ts +62 -0
  3. package/dist/effects/custom.d.ts.map +1 -0
  4. package/dist/effects/effects.d.ts +92 -6
  5. package/dist/effects/effects.d.ts.map +1 -1
  6. package/dist/effects/glow.d.ts +5 -0
  7. package/dist/effects/glow.d.ts.map +1 -1
  8. package/dist/effects/grade.d.ts +3 -0
  9. package/dist/effects/grade.d.ts.map +1 -1
  10. package/dist/effects/highlight.d.ts +35 -0
  11. package/dist/effects/highlight.d.ts.map +1 -0
  12. package/dist/effects/index.d.ts +7 -1
  13. package/dist/effects/index.d.ts.map +1 -1
  14. package/dist/effects/inner-lines.d.ts +39 -0
  15. package/dist/effects/inner-lines.d.ts.map +1 -0
  16. package/dist/effects/live.d.ts +12 -0
  17. package/dist/effects/live.d.ts.map +1 -0
  18. package/dist/effects/mask.d.ts +32 -12
  19. package/dist/effects/mask.d.ts.map +1 -1
  20. package/dist/effects/outline.d.ts +12 -0
  21. package/dist/effects/outline.d.ts.map +1 -1
  22. package/dist/effects/pass.d.ts +27 -0
  23. package/dist/effects/pass.d.ts.map +1 -0
  24. package/dist/effects/screen.d.ts +31 -0
  25. package/dist/effects/screen.d.ts.map +1 -0
  26. package/dist/effects/suggested.d.ts +5 -0
  27. package/dist/effects/suggested.d.ts.map +1 -1
  28. package/dist/effects/tree-id.d.ts +50 -0
  29. package/dist/effects/tree-id.d.ts.map +1 -0
  30. package/dist/effects-qHx_8Dlk.js +1052 -0
  31. package/dist/effects-qHx_8Dlk.js.map +1 -0
  32. package/dist/effects.js +3 -249
  33. package/dist/forest/Forest.d.ts +82 -4
  34. package/dist/forest/Forest.d.ts.map +1 -1
  35. package/dist/forest/forest-lod.d.ts +70 -0
  36. package/dist/forest/forest-lod.d.ts.map +1 -0
  37. package/dist/forest/impostor-material.d.ts +106 -0
  38. package/dist/forest/impostor-material.d.ts.map +1 -0
  39. package/dist/forest/impostor-season.d.ts +13 -0
  40. package/dist/forest/impostor-season.d.ts.map +1 -0
  41. package/dist/forest/impostor.d.ts +105 -0
  42. package/dist/forest/impostor.d.ts.map +1 -0
  43. package/dist/forest/index.d.ts +1 -0
  44. package/dist/forest/index.d.ts.map +1 -1
  45. package/dist/forest/levels.d.ts +144 -0
  46. package/dist/forest/levels.d.ts.map +1 -0
  47. package/dist/forest/lod.d.ts +106 -0
  48. package/dist/forest/lod.d.ts.map +1 -0
  49. package/dist/forest/nodes.d.ts +42 -1
  50. package/dist/forest/nodes.d.ts.map +1 -1
  51. package/dist/forest/octahedral.d.ts +33 -0
  52. package/dist/forest/octahedral.d.ts.map +1 -0
  53. package/dist/{forest-ChEaWJrf.js → forest-CM5DrklM.js} +1727 -340
  54. package/dist/forest-CM5DrklM.js.map +1 -0
  55. package/dist/generator/fruit.d.ts +2 -0
  56. package/dist/generator/fruit.d.ts.map +1 -1
  57. package/dist/generator/index.d.ts +1 -0
  58. package/dist/generator/index.d.ts.map +1 -1
  59. package/dist/generator/light.d.ts +36 -0
  60. package/dist/generator/light.d.ts.map +1 -0
  61. package/dist/index.d.ts +3 -2
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +5 -2
  64. package/dist/index.js.map +1 -1
  65. package/dist/materials/crown-nodes.d.ts +5 -0
  66. package/dist/materials/crown-nodes.d.ts.map +1 -1
  67. package/dist/materials/leaf-translucency-model.d.ts +6 -1
  68. package/dist/materials/leaf-translucency-model.d.ts.map +1 -1
  69. package/dist/materials/material-features.d.ts +12 -0
  70. package/dist/materials/material-features.d.ts.map +1 -1
  71. package/dist/materials/shader-hooks.d.ts +155 -0
  72. package/dist/materials/shader-hooks.d.ts.map +1 -0
  73. package/dist/motion-Qd7xjeZM.js +276 -0
  74. package/dist/motion-Qd7xjeZM.js.map +1 -0
  75. package/dist/nodes-DxgTyF9B.js +436 -0
  76. package/dist/nodes-DxgTyF9B.js.map +1 -0
  77. package/dist/react/Forest.d.ts +17 -3
  78. package/dist/react/Forest.d.ts.map +1 -1
  79. package/dist/react/ScenePipeline.d.ts +63 -0
  80. package/dist/react/ScenePipeline.d.ts.map +1 -0
  81. package/dist/react/SceneShaderHooks.d.ts +25 -0
  82. package/dist/react/SceneShaderHooks.d.ts.map +1 -0
  83. package/dist/react/Tree.d.ts +9 -2
  84. package/dist/react/Tree.d.ts.map +1 -1
  85. package/dist/react/Weather.d.ts +45 -0
  86. package/dist/react/Weather.d.ts.map +1 -0
  87. package/dist/react/Wind.d.ts +12 -1
  88. package/dist/react/Wind.d.ts.map +1 -1
  89. package/dist/react/index.d.ts +7 -1
  90. package/dist/react/index.d.ts.map +1 -1
  91. package/dist/react.js +347 -10
  92. package/dist/react.js.map +1 -1
  93. package/dist/renderer/index.d.ts +6 -0
  94. package/dist/renderer/index.d.ts.map +1 -1
  95. package/dist/scene/antialias.d.ts +35 -0
  96. package/dist/scene/antialias.d.ts.map +1 -0
  97. package/dist/scene/ao.d.ts +46 -0
  98. package/dist/scene/ao.d.ts.map +1 -0
  99. package/dist/scene/bloom.d.ts +19 -0
  100. package/dist/scene/bloom.d.ts.map +1 -0
  101. package/dist/scene/fog.d.ts +49 -0
  102. package/dist/scene/fog.d.ts.map +1 -0
  103. package/dist/scene/godrays.d.ts +37 -0
  104. package/dist/scene/godrays.d.ts.map +1 -0
  105. package/dist/scene/index.d.ts +14 -0
  106. package/dist/scene/index.d.ts.map +1 -0
  107. package/dist/scene/motion-blur.d.ts +23 -0
  108. package/dist/scene/motion-blur.d.ts.map +1 -0
  109. package/dist/scene/pipeline.d.ts +109 -0
  110. package/dist/scene/pipeline.d.ts.map +1 -0
  111. package/dist/scene/settings.d.ts +36 -0
  112. package/dist/scene/settings.d.ts.map +1 -0
  113. package/dist/scene/stack.d.ts +25 -0
  114. package/dist/scene/stack.d.ts.map +1 -0
  115. package/dist/scene/stage.d.ts +52 -0
  116. package/dist/scene/stage.d.ts.map +1 -0
  117. package/dist/scene/suggested.d.ts +12 -0
  118. package/dist/scene/suggested.d.ts.map +1 -0
  119. package/dist/scene/tone-mapping.d.ts +20 -0
  120. package/dist/scene/tone-mapping.d.ts.map +1 -0
  121. package/dist/scene/velocity.d.ts +34 -0
  122. package/dist/scene/velocity.d.ts.map +1 -0
  123. package/dist/scene.js +889 -0
  124. package/dist/scene.js.map +1 -0
  125. package/dist/season/nodes.d.ts +13 -0
  126. package/dist/season/nodes.d.ts.map +1 -1
  127. package/dist/shader-hooks-BFRtlWGI.js +275 -0
  128. package/dist/shader-hooks-BFRtlWGI.js.map +1 -0
  129. package/dist/tree/Tree.d.ts +8 -3
  130. package/dist/tree/Tree.d.ts.map +1 -1
  131. package/dist/tree/index.d.ts.map +1 -1
  132. package/dist/weather/index.d.ts +3 -0
  133. package/dist/weather/index.d.ts.map +1 -0
  134. package/dist/weather/shared.d.ts +43 -0
  135. package/dist/weather/shared.d.ts.map +1 -0
  136. package/dist/weather/snow.d.ts +87 -0
  137. package/dist/weather/snow.d.ts.map +1 -0
  138. package/dist/weather/wetness.d.ts +75 -0
  139. package/dist/weather/wetness.d.ts.map +1 -0
  140. package/dist/weather.js +288 -0
  141. package/dist/weather.js.map +1 -0
  142. package/dist/wind/Wind.d.ts +100 -5
  143. package/dist/wind/Wind.d.ts.map +1 -1
  144. package/dist/wind/burst.d.ts +28 -0
  145. package/dist/wind/burst.d.ts.map +1 -0
  146. package/dist/wind/index.d.ts +3 -2
  147. package/dist/wind/index.d.ts.map +1 -1
  148. package/dist/wind/motion.d.ts +30 -0
  149. package/dist/wind/motion.d.ts.map +1 -0
  150. package/dist/wind/node.d.ts +17 -3
  151. package/dist/wind/node.d.ts.map +1 -1
  152. package/package.json +9 -1
  153. package/dist/effects.js.map +0 -1
  154. package/dist/forest-ChEaWJrf.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"forest-CM5DrklM.js","names":["sin","cos","exp","dot","cross","length","normalize","normalize","dot","cross","length","DEG","cos","sin","normalize","normalize","cos","sin","cross","dot","DEG","cos","sin","normalize","length","cross","dot","DEG","cos","sin","normalize","cross","dot","DEG","cos","sin","cross","dot","cos","sin","normalize","length","cos","sin","cos","sin","shiftedSeason","normalize","cross","ramp"],"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/light.ts","../src/generator/index.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/response.ts","../src/tree/Tree.ts","../src/tree/index.ts","../src/styles/registry.ts","../src/forest/impostor-season.ts","../src/forest/impostor-material.ts","../src/forest/octahedral.ts","../src/forest/impostor.ts","../src/forest/lod.ts","../src/forest/levels.ts","../src/forest/forest-lod.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). */\nexport const 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 { extendDefinition, type DefinitionPatch, type TreeDefinition } from '../definition';\nimport { createRandom, seedRandom } from '../random';\nimport { woodSeasonAttribute } from '../season/profile';\nimport { buildBranches } from './branches';\nimport { crownVolume } from './crown';\nimport { COARSE_SIDES, emptyGeometry, fruitGeometry, fruitGrowth, placeFruit } from './fruit';\nimport { growthTiming } from './growth';\nimport { trunkHeight } from './index';\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 type { GrowthWindow, SkeletonBranch, TreeData } from './types';\nimport { branchSway, writeTrunkSway } from './wind';\n\n/** Fewest sides around a part of the Light level (a triangle). */\nconst MIN_SIDES = 3;\n/** Fewest sections along a part of the Light level. */\nconst MIN_SECTIONS = 1;\n\n/** Most the leaves of the Light level grow, as a multiple of their size, to fill the crown of a dropped branch level. */\nconst MAX_LEAF_GROWTH = 2.5;\n/** The share of the Full tree's Fruit the Light level keeps (each Fruit by its own stable random number). */\nconst LIGHT_FRUIT_SHARE = 0.5;\n\nconst halfSides = (sides: number) => Math.max(MIN_SIDES, Math.round(sides / 2));\nconst halfSections = (sections: number) => Math.max(MIN_SECTIONS, Math.round(sections / 2));\n\n/**\n * The Light Definition (ADR 0010): the Definition a Forest's Light Detail Level is generated from.\n * Fixed reductions of `definition`:\n * - about half the sides and sections of the trunk and every branch level (at least 3 sides, 1 section),\n * half the sides of the Roots and half the extra rings of the Root Flare;\n * - the deepest branch level dropped (when there are at least two and it has branches), and the leaves\n * then grow on the level above, larger by the square root of the dropped level's `count` (at most\n * {@link MAX_LEAF_GROWTH} times) to keep the crown filled;\n * - with a single branch level kept: half the leaves per branch, larger to keep the same leaf area;\n * - coarse Fruit: half the sides, at most {@link COARSE_SIDES} (at least 3).\n *\n * Then `override` is merged on top (like {@link extendDefinition}: objects deeply, arrays replace) and the\n * result is validated. Pure and deterministic; never mutates `definition`.\n */\nexport function lightDefinition(definition: TreeDefinition, override: DefinitionPatch = {}): TreeDefinition {\n const { trunk, branches, leaves, fruit, roots } = definition;\n const deepest = branches[branches.length - 1];\n const drop = branches.length >= 2 && deepest!.count > 0;\n const halved = drop ? leaves.count : Math.max(1, Math.round(leaves.count / 2));\n const growth = drop ? Math.min(Math.sqrt(deepest!.count), MAX_LEAF_GROWTH) : leaves.count > 0 ? Math.sqrt(leaves.count / halved) : 1;\n\n const derived: TreeDefinition = {\n ...definition,\n trunk: {\n ...trunk,\n sides: halfSides(trunk.sides),\n sections: halfSections(trunk.sections),\n ...(trunk.flare ? { flareSections: halfSections(trunk.flareSections ?? FLARE_SECTIONS) } : {}),\n },\n branches: (drop ? branches.slice(0, -1) : branches).map((level) => ({\n ...level,\n sides: halfSides(level.sides),\n sections: halfSections(level.sections),\n })),\n leaves: leaves.count > 0 ? { ...leaves, count: halved, size: leaves.size * growth } : leaves,\n ...(fruit ? { fruit: { ...fruit, sides: Math.min(halfSides(fruit.sides ?? 2 * COARSE_SIDES), COARSE_SIDES) } } : {}),\n ...(roots ? { roots: { ...roots, sides: halfSides(rootSides(definition)) } } : {}),\n };\n return extendDefinition(derived, override);\n}\n\n/**\n * The Light Detail Level of a Variant (ADR 0010): the tree of `definition` and `seed`, generated from its\n * {@link lightDefinition} (with `override`) so that it keeps every surviving branch in place:\n *\n * - the skeleton grows with the Full Definition's sections (branch paths fork their randomness, ADR 0003,\n * so every branch the Light level keeps lies exactly where it does in the Full tree); the wood mesh then\n * sweeps only every other skeleton point (the Light sections) with the Light sides;\n * - leaves grow on the outermost Light branches, and only where the Full tree has leaves on that branch\n * or the branches growing from it (Sculpts deleting branches or painting leaves carry over);\n * - about half the Full tree's Fruit (each kept or not by its own stable random number) hangs where it\n * hangs in Full, drawn coarse (a Fruit that is already coarse cannot get fewer faces otherwise).\n *\n * Growth, Wind and Season attributes are those of the Full tree: a surviving branch (and its Fruit) grows,\n * sways and changes with the Season exactly as in Full; a Light leaf grows from the first to the last Full\n * leaf on its branch. Leaves and Fruit keep the Full `aLevel`. With `materials.occlusion` the meshes carry\n * `aOcclusion` like Full, so the Light meshes can share the Variant's materials. Pure and deterministic.\n */\nexport function generateLightTree(definition: TreeDefinition, seed: number, override?: DefinitionPatch): TreeData {\n const light = lightDefinition(definition, override);\n const random = createRandom(seed);\n\n // The Full skeleton (no meshes): its Growth, Wind sway, leaf spans and Fruit.\n const fullSculpts = sculptsFor(definition, seed);\n const fullStems = buildStems(definition, random);\n const fullBranches = sculptBranches([...fullStems, ...buildBranches(definition, fullStems, random.fork('branches'))], fullSculpts);\n const fullLeaves = sculptLeaves(placeLeaves(definition, fullBranches, random.fork('leaves')), fullSculpts, seed);\n const fullTiming = growthTiming(definition, seed, fullBranches, fullLeaves);\n const fullGrowth = new Map(fullBranches.map((b, i) => [b.path, fullTiming.branches[i]!]));\n const fullFruit = placeFruit(definition, fullBranches, random.fork('fruit'));\n const fullFruitGrowth = fruitGrowth(seed, fullFruit, fullGrowth);\n const kept = fullFruit.map((f) => seedRandom(seed, `light/fruit/${f.id}`) < LIGHT_FRUIT_SHARE);\n const fruit = fullFruit.filter((_, i) => kept[i]);\n\n // Each branch's span of Full leaf Growth (over the leaves on it and on the branches growing from it).\n const leafSpan = new Map<string, GrowthWindow>();\n fullLeaves.forEach((leaf, l) => {\n const window = fullTiming.leaves[l]!;\n const parts = leaf.branch.split('.');\n for (let n = 1; n <= parts.length; n++) {\n const path = parts.slice(0, n).join('.');\n const span = leafSpan.get(path);\n leafSpan.set(path, span ? { start: Math.min(span.start, window.start), end: Math.max(span.end, window.end) } : window);\n }\n });\n\n // The Light skeleton: the Light shape grown on the Full sections.\n const shape: TreeDefinition = {\n ...light,\n trunk: { ...light.trunk, sections: definition.trunk.sections },\n branches: light.branches.map((level, i) => ({ ...level, sections: definition.branches[i]?.sections ?? level.sections })),\n };\n const sculpts = sculptsFor(shape, seed);\n const stems = buildStems(shape, random);\n const branches = sculptBranches([...stems, ...buildBranches(shape, stems, random.fork('branches'))], sculpts);\n const leaves = sculptLeaves(placeLeaves(light, branches, random.fork('leaves')), sculpts, seed).filter((leaf) => leafSpan.has(leaf.branch));\n const roots = growRoots(\n light,\n branches.filter((b) => b.parent === null),\n random,\n );\n\n // Growth and Wind of the Full tree; a branch only an override adds gets its own.\n const own = growthTiming(light, seed, branches, []);\n const growth = {\n branches: branches.map((b, i) => fullGrowth.get(b.path) ?? own.branches[i]!),\n leaves: leaves.map((leaf) => leafSpan.get(leaf.branch)!),\n fruit: fullFruitGrowth.filter((_, i) => kept[i]),\n roots: roots.map(() => ({ start: 0, end: 0 })),\n };\n const sway = new Map([...branchSway(branches, light.branches.length), ...branchSway(fullBranches, definition.branches.length)]);\n\n const sidesOf = (level: number) => (level === 0 ? light.trunk.sides : light.branches[level - 1]!.sides);\n const sectionsOf = (level: number) => (level === 0 ? light.trunk.sections : light.branches[level - 1]!.sections);\n const stemSweep = { flare: light.trunk.flare ?? 0, sections: light.trunk.flareSections ?? FLARE_SECTIONS };\n const woodSeason = woodSeasonAttribute(seed, definition.variation);\n const wood = mergeBuffers([\n ...branches.map((b, i) =>\n sweepBranch(\n coarsen(b, sectionsOf(b.level)),\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(light), seedRandom(seed, root.path), woodSeason, growth.roots[i])),\n ]);\n const leafLevel = definition.branches.length + 1;\n const leafBuffers =\n light.leaves.shape === 'card'\n ? leafGeometry(leaves, leafLevel, seed, definition.variation, growth.leaves, sway)\n : solidLeafGeometry(leaves, light.leaves.shape, leafLevel, seed, definition.variation, growth.leaves, sway);\n const fruitBuffers = light.fruit\n ? fruitGeometry(fruit, light.fruit, definition.branches.length + 2, seed, definition.variation, growth.fruit, sway)\n : emptyGeometry();\n const skeleton = { branches, leaves, fruit, roots };\n const height = trunkHeight(skeleton);\n for (const buffers of [wood, leafBuffers, fruitBuffers]) writeTrunkSway(buffers, height);\n const crown = crownVolume(leafBuffers.positions, branches);\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/** The branch with only `sections` + 1 of its skeleton points (evenly picked, both ends kept) to sweep. */\nfunction coarsen(branch: SkeletonBranch, sections: number): SkeletonBranch {\n const n = branch.points.length - 1;\n if (sections >= n) return branch;\n return { ...branch, points: Array.from({ length: sections + 1 }, (_, k) => branch.points[Math.round((k * n) / sections)]!) };\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 { generateLightTree, lightDefinition } from './light';\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 { 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 return crownAt(crown, grown.div(growthScale(float(growth).clamp(0, 1))));\n}\n\n/**\n * The Crown Volume measured at `point`, a position in the fully grown tree's own space (Growth 1, no\n * Wind). `crownNodes` uses it for a tree's vertices; an Impostor for the point its bake pictured.\n */\nexport function crownAt(crown: CrownVolume, point: Node<'vec3'>): CrownNodes {\n const local = point.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 applyLeafTranslucencyTerm(material, leafTranslucencyTerm(values, crown, growth));\n}\n\n/**\n * Gives `material` the translucent lighting model for a ready-made term (`applyLeafTranslucency` builds\n * it from a tree's vertices; an Impostor from its baked Crown Volume distance).\n */\nexport function applyLeafTranslucencyTerm(material: MeshStandardNodeMaterial, term: LeafTranslucencyTerm): void {\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 type { LeafTranslucencyValues } from './leaf-translucency';\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\n/**\n * The live values of the Material Features that are on, as the uniforms every target shares (null for\n * a feature that is off). For materials made after the features were applied (a Forest's Impostors).\n */\nexport interface MaterialFeatureNodes {\n crownNormals: Node<'float'> | null;\n translucency: LeafTranslucencyValues | null;\n occlusion: Node<'float'> | null;\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, as their shared uniforms (tuning them reaches every material that reads them). */\n get nodes(): MaterialFeatureNodes {\n return { crownNormals: this.crown, translucency: this.translucencyValues, occlusion: this.occlusion };\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","import type { Renderer } from 'three/webgpu';\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\n/**\n * @internal The renderer an `onBeforeRender` callback receives (typed as the classic renderer by\n * three's types), as the `WebGPURenderer` it must be. Throws {@link UnsupportedRendererError} otherwise.\n */\nexport function webgpuRenderer(renderer: unknown): Renderer {\n assertWebGPURenderer(renderer);\n return renderer as 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 return keyframeSampler(track, toUniform)(s);\n}\n\n/** As `keyframeNode`, with the uniforms made once: the returned function samples the track at any Season node. */\nfunction keyframeSampler<V>(track: readonly Keyframe<V>[], toUniform: (v: V) => Node): (s: Node) => Node {\n const ts: Node[] = track.map((k) => uniform(k.t));\n const vs: Node[] = track.map((k) => toUniform(k.value));\n return (s) => {\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\n/** One leaf at one Season (TSL): see {@link leafSeasonNode}. */\nexport interface LeafSeasonNode {\n /** Leaf colour (vec3, linear) at the 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). */\n shown: Node;\n}\n\n/**\n * The TSL twin of `leafSeason` for a Season Profile: returns a function that evaluates one leaf from\n * a Season node and its Season timing (vec3: shift, coverage rank, blossom rank, as `aSeason`). The\n * Profile's uniforms are made once, so it can be called for many leaves (an Impostor's frames).\n */\nexport function leafSeasonNode(profile: SeasonProfileDefinition): (season: FloatNode<'float'>, part: Node) => LeafSeasonNode {\n const leafColor = keyframeSampler(profile.leafColor, (v) => uniform(new Color(v)));\n const coverage = keyframeSampler(profile.leafCoverage, (v) => uniform(v));\n const blossom = keyframeSampler(profile.blossom, (v) => uniform(v));\n const blossomColor = uniform(new Color(profile.blossomColor));\n return (season, part) => {\n const s = shiftedSeason(season, part);\n const isBlossom = blossom(s).greaterThan(part.z);\n return { color: select(isBlossom, blossomColor, leafColor(s)), shown: isBlossom.or(coverage(s).greaterThan(part.y)) };\n };\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 { color, shown } = leafSeasonNode(profile)(season, attribute('aSeason', 'vec3'));\n return {\n season,\n color: varying(color),\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 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 {\n BufferAttribute,\n BufferGeometry,\n InterleavedBuffer,\n InterleavedBufferAttribute,\n Mesh,\n type Material,\n type MeshStandardNodeMaterial,\n type Node,\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 { LiveShaderHooks, partHookTarget, ShaderHookedGroup, type TreeShaderHooks } from '../materials/shader-hooks';\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';\nimport { setWindMotion } from '../wind/motion';\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 /** The Tree Shader Hook per tree part (see {@link Tree.shaderHooks}). Default: none. */\n shaderHooks?: TreeShaderHooks;\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 ShaderHookedGroup {\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 protected readonly hooks: LiveShaderHooks;\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 // Wind-aware velocity (ADR 0011): only read by a scene pass with a velocity channel.\n const motion = { source: this.windBinding, offset, shift: (previous: Node<'float'>) => windOffset(this.windBinding, this.windResponse, { time: previous }).sub(offset) };\n for (const material of [bark, leaf, fruit]) setWindMotion(material.positionNode as Node, motion);\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 const inputs = { season: this.seasonUniform, growth: this.growthUniform };\n this.hooks = new LiveShaderHooks(\n [\n partHookTarget('bark', bark, this.wood.geometry, inputs),\n partHookTarget('leaves', leaf, this.leaves.geometry, inputs),\n partHookTarget('fruit', fruit, this.fruit.geometry, inputs),\n ],\n definition.materials.shading,\n options.shaderHooks,\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 (except the one-time node-graph rebuild\n * when the tree first follows a Wind that has had a Wind Burst, see `Wind.burst`).\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.hooks.dispose();\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 shaderHooks: options.shaderHooks,\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","// The Impostor's Season atlas texel (ADR 0010), as pure maths: what the bake writes for a leaf and\n// how the Impostor shader reads it back (the TSL twins are in impostor.ts and impostor-material.ts).\n// No three.js at runtime.\nimport type { PartSeason } from '../season/profile';\n\n/** A texel: r = timing shift (−1..1 as 0..1), g = coverage rank, b = blossom rank, a = 1 on leaves. */\nexport type SeasonTexel = readonly [number, number, number, number];\n\n/** The leaf timing shift is within ±`variation.season` (at most 1); the atlas keeps it as `shift · SCALE + 0.5`. */\nexport const SEASON_SHIFT_SCALE = 0.5;\n\n/** The texel the bake writes for a leaf (`aSeason`), or for wood (`null`: empty). */\nexport function encodeSeasonTexel(part: PartSeason | null): SeasonTexel {\n if (!part) return [0, 0, 0, 0];\n return [part.shift * SEASON_SHIFT_SCALE + 0.5, part.coverageRank, part.blossomRank, 1];\n}\n\n/**\n * The leaf Season timing a (filtered, premultiplied) texel pictures: divided by its leaf share `a`\n * (mipmaps and frame blends mix texels with the empty background).\n */\nexport function decodeSeasonTexel(texel: SeasonTexel): PartSeason {\n const a = Math.max(texel[3], 1e-4);\n return { shift: (texel[0] / a - 0.5) / SEASON_SHIFT_SCALE, coverageRank: texel[1] / a, blossomRank: texel[2] / a };\n}\n","// The Impostor's draw side (ADR 0010): one card per tree turned to the camera, showing the baked\n// frames nearest the view, lit through the baked normals. The TSL twins of octahedral.ts live here.\nimport { DoubleSide, type MeshStandardNodeMaterial, type Node, type Texture } from 'three/webgpu';\nimport {\n abs,\n and,\n cameraPosition,\n cameraProjectionMatrix,\n cameraWorldMatrix,\n cross,\n dot,\n float,\n floor,\n max,\n min,\n mix,\n modelWorldMatrix,\n modelWorldMatrixInverse,\n positionGeometry,\n select,\n texture,\n transformNormalToView,\n varying,\n vec2,\n vec3,\n vec4,\n} from 'three/tsl';\nimport type { TreeDefinition } from '../definition';\nimport type { CrownVolume } from '../generator';\nimport { createShadedMaterial } from '../materials';\nimport { crownAt } from '../materials/crown-nodes';\nimport { applyLeafTranslucencyTerm } from '../materials/leaf-translucency-model';\nimport type { MaterialFeatureNodes } from '../materials/material-features';\nimport type { ShaderHookTarget } from '../materials/shader-hooks';\nimport { setTreeLeafMask } from '../effects/mask';\nimport { leafSeasonNode } from '../season';\nimport { objectWindDirection, treeSwayOffset, type WindResponse, type WindSource } from '../wind';\nimport { SEASON_SHIFT_SCALE } from './impostor-season';\nimport { setWindMotion } from '../wind/motion';\nimport { instanceBurstFrame, instanceRotate, instanceState, levelTreePosition, levelVisible } from './nodes';\nimport type { Vec3 } from './octahedral';\n\n/** Coverage (blended over the frames) from which an Impostor texel is drawn. */\nconst ALPHA_CUT = 0.5;\n/** The smallest coverage values are divided by. */\nconst MIN_COVERAGE = 1e-4;\n\n/** Where a Variant's frames are: the tree's centre and the half size of each frame (tree space, Growth 1). */\nexport interface ImpostorBounds {\n center: Vec3;\n /** Half the width of a frame's picture and of the card (the tree's bounding radius plus a margin). */\n half: number;\n}\n\n/** A Variant's baked atlases, one texture per channel (by name, see `ImpostorChannel`), frames × frames frames each. */\nexport interface ImpostorAtlases {\n frames: number;\n bounds: ImpostorBounds;\n textures: Readonly<Record<string, Texture>>;\n}\n\n/** Column `i` of a mat4 node. */\nfunction column(matrix: unknown, i: number): Node<'vec4'> {\n return (matrix as { element(i: number): Node<'vec4'> }).element(i);\n}\n\n/** TSL twin of `octahedralEncode`. */\nfunction encode(d: Node<'vec3'>): Node<'vec2'> {\n const y = max(d.y, 0);\n const s = abs(d.x).add(y).add(abs(d.z));\n const px = d.x.div(s);\n const pz = d.z.div(s);\n return vec2(px.add(pz).add(1), px.sub(pz).add(1)).mul(0.5);\n}\n\n/** TSL twin of `octahedralDecode`. */\nfunction decode(uv: Node<'vec2'>): Node<'vec3'> {\n const a = uv.x.mul(2).sub(1);\n const b = uv.y.mul(2).sub(1);\n const px = a.add(b).mul(0.5);\n const pz = a.sub(b).mul(0.5);\n return vec3(px, float(1).sub(abs(px)).sub(abs(pz)), pz).normalize();\n}\n\n/** TSL twin of `frameBasis` (right and up; forward is the input). */\nfunction basis(forward: Node<'vec3'>): { right: Node<'vec3'>; up: Node<'vec3'> } {\n const reference = select(abs(forward.y).greaterThan(0.999), vec3(0, 0, -1), vec3(0, 1, 0));\n const right = cross(reference, forward).normalize();\n return { right, up: cross(forward, right) };\n}\n\n/** TSL twin of `frameUv`. */\nfunction frameUv(point: Node<'vec3'>, view: Node<'vec3'>, forward: Node<'vec3'>, half: number): Node<'vec2'> {\n const t = dot(point, forward).div(max(dot(view, forward), 1e-3));\n const hit = point.sub(view.mul(t));\n const { right, up } = basis(forward);\n return vec2(dot(hit, right), dot(hit, up)).div(2 * half).add(0.5);\n}\n\n/** The (i, j) offsets of the four blended frames, in `blendFrames` order. */\nconst OFFSETS = [\n [0, 0],\n [1, 0],\n [0, 1],\n [1, 1],\n] as const;\n\n/** One of the (up to) four frames blended at a fragment. */\nexport interface ImpostorFrame {\n /** A channel's atlas texel in this frame, as baked (premultiplied by coverage; 0 outside the frame's picture). */\n sample(channel: string): Node<'vec4'>;\n}\n\n/**\n * The card of an Impostor tree and what it shows (built for a Detail Level mesh: the tree comes from\n * the level list). Everything here is per tree and per camera, so shadow passes see the card and\n * the frames turned to the light.\n */\nexport interface ImpostorView {\n /** The card's vertex in forest space (`positionNode`). */\n position: Node<'vec3'>;\n /** The Wind displacement of the card's vertex in forest space (null without Wind). */\n sway: Node<'vec3'> | null;\n /** The card pushed back from the viewer by its half size (`castShadowPositionNode`), so it does not shadow itself. */\n shadowPosition: Node<'vec3'>;\n /** Coverage of this fragment (0..1), blended over the frames. */\n coverage: Node<'float'>;\n /**\n * With `sway`: where the card's vertex was at Wind time `previous` relative to `position` (forest\n * space), for Wind-aware velocity (ADR 0011).\n */\n windShift?: (previous: Node<'float'>) => Node<'vec3'>;\n /**\n * Blends `perFrame` over the frames by their weights. Decode per frame what does not blend\n * linearly (a colour that depends on the leaf flag, Season ranks); `perFrame` gets premultiplied\n * samples and should return a premultiplied value.\n */\n blend(perFrame: (frame: ImpostorFrame) => Node<'vec4'>): Node<'vec4'>;\n /** A channel blended over the frames, divided by the coverage (for values that blend linearly). */\n value(channel: string): Node<'vec4'>;\n}\n\n/**\n * Builds the card and the frame blend. In the vertex stage: the direction to the camera (or, for\n * an orthographic camera such as a sun's shadow camera, its forward axis) in tree space, the card\n * across it, the four nearest frames and where each pictured the card's vertex (`frameUv`). In the\n * fragment stage: the atlases sampled in those frames and blended bilinearly.\n *\n * `sway`: a displacement (tree space) of a card point at its tree-space position (the Wind) at Wind\n * time `time` (default the Wind's clock); the pictures move with the card.\n */\nexport function impostorView(atlases: ImpostorAtlases, sway?: (point: Node<'vec3'>, time?: Node<'float'>) => Node<'vec3'>): ImpostorView {\n const { frames, bounds } = atlases;\n const { half } = bounds;\n const center = vec3(...bounds.center);\n const { scale } = instanceState();\n const base = levelTreePosition();\n const centerForest = base.add(instanceRotate(center).mul(scale));\n\n // The direction to the viewer, in forest (= the card's object) space, then in tree space.\n const eye = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;\n const axis = modelWorldMatrixInverse.mul(vec4(column(cameraWorldMatrix, 2).xyz, 0)).xyz;\n const orthographic = column(cameraProjectionMatrix, 3).w.greaterThan(0.5);\n const viewForest = select(orthographic, axis, eye.sub(centerForest)).normalize();\n const view = instanceRotate(viewForest, true).normalize();\n\n // The card, across the view (corners of positionGeometry at ±1).\n const card = basis(view);\n const point = card.right.mul(positionGeometry.x).add(card.up.mul(positionGeometry.y)).mul(half);\n const treePoint = center.add(point);\n const swayed = sway?.(treePoint);\n const position = base.add(instanceRotate(swayed ? treePoint.add(swayed) : treePoint).mul(scale));\n const swayForest = swayed ? instanceRotate(swayed).mul(scale) : null;\n const shadowPosition = position.sub(viewForest.mul(half).mul(scale));\n\n // The frames around the view (`blendFrames`) and where each one pictured this vertex.\n const g = encode(view).mul(frames).sub(0.5).clamp(0, frames - 1);\n const cell = min(floor(g), Math.max(frames - 2, 0));\n const blendVarying = varying(vec4(cell, g.sub(cell)));\n const frameOf = (k: number) => min(blendVarying.xy.add(vec2(...OFFSETS[k]!)), frames - 1);\n const vertexFrame = (k: number) => min(cell.add(vec2(...OFFSETS[k]!)), frames - 1);\n const local = OFFSETS.map((_, k) => frameUv(point, view, decode(vertexFrame(k).add(0.5).div(frames)), half));\n const locals = [varying(vec4(local[0]!, local[1]!)), varying(vec4(local[2]!, local[3]!))];\n const fx = blendVarying.z;\n const fy = blendVarying.w;\n const weights = [float(1).sub(fx).mul(float(1).sub(fy)), fx.mul(float(1).sub(fy)), float(1).sub(fx).mul(fy), fx.mul(fy)];\n\n const frameSamplers: ImpostorFrame[] = OFFSETS.map((_, k) => {\n const uv = k % 2 === 0 ? locals[k >> 1]!.xy : locals[k >> 1]!.zw;\n // Only inside the frame: the neighbouring frames' pictures are other directions.\n const inside = and(uv.greaterThanEqual(vec2(0)).all(), uv.lessThanEqual(vec2(1)).all());\n const atlasUv = frameOf(k).add(uv.clamp(0, 1)).div(frames);\n // three samples a render target top row first (v = 0 is the bake camera's top, y = 1).\n const flipped = vec2(atlasUv.x, float(1).sub(atlasUv.y));\n const samples = new Map<string, Node<'vec4'>>();\n return {\n sample(channel) {\n let value = samples.get(channel);\n if (!value) {\n const atlas = atlases.textures[channel];\n if (!atlas) throw new Error(`No Impostor atlas \"${channel}\"`);\n value = select(inside, texture(atlas, flipped), vec4(0));\n samples.set(channel, value);\n }\n return value;\n },\n };\n });\n const blend = (perFrame: (frame: ImpostorFrame) => Node<'vec4'>): Node<'vec4'> =>\n frameSamplers.reduce<Node<'vec4'>>((sum, frame, k) => sum.add(perFrame(frame).mul(weights[k]!)), vec4(0));\n const values = new Map<string, Node<'vec4'>>();\n const blended = (channel: string): Node<'vec4'> => {\n let value = values.get(channel);\n if (!value) {\n value = blend((frame) => frame.sample(channel));\n values.set(channel, value);\n }\n return value;\n };\n const coverage = blended(COLOR_CHANNEL).a;\n return {\n position,\n sway: swayForest,\n shadowPosition,\n coverage,\n ...(sway && swayed ? { windShift: (previous: Node<'float'>) => instanceRotate(sway(treePoint, previous).sub(swayed)).mul(scale) } : {}),\n blend,\n value: (channel) => blended(channel).div(max(coverage, MIN_COVERAGE)),\n };\n}\n\n/** The colour atlas: the MRT `output` (rgb = colour, a = coverage). */\nexport const COLOR_CHANNEL = 'output';\n/** The normal atlas: rgb = tree-space normal (encoded 0..1), a = 1 on leaves, 0 on wood. */\nexport const NORMAL_CHANNEL = 'normal';\n/** The Season atlas (`encodeSeasonTexel`): r = leaf timing shift, g = coverage rank, b = blossom rank, a = 1 on leaves. */\nexport const SEASON_CHANNEL = 'season';\n/** The wood layer's colour atlas: the wood alone (rgb = colour, a = coverage), shown where leaves have dropped. */\nexport const WOOD_COLOR_CHANNEL = 'woodOutput';\n/** The wood layer's normal atlas (as `NORMAL_CHANNEL`, a = 0). */\nexport const WOOD_NORMAL_CHANNEL = 'woodNormal';\n\n/**\n * The Material Feature atlas (only baked when a Material Feature is on, ADR 0008): rgb = the pictured\n * point in tree space (Growth 1, encoded over the frame's box, see `featureTexel`), from which the card\n * measures the Crown Volume (Crown Normals, Leaf Translucency); a = the raw Structural Occlusion\n * (`aOcclusion`, 0 when that feature is off).\n */\nexport const FEATURES_CHANNEL = 'features';\n\n/** The Material Feature atlas texel the bake writes for a tree-space `point` and raw `occlusion`. */\nexport function featureTexel(point: Node<'vec3'>, occlusion: Node<'float'>, bounds: ImpostorBounds): Node<'vec4'> {\n return vec4(point.sub(vec3(...bounds.center)).div(2 * bounds.half).add(0.5), occlusion);\n}\n\n/** Inverse of `featureTexel` for the point (a texel already divided by the coverage). */\nfunction featurePoint(texel: Node<'vec4'>, bounds: ImpostorBounds): Node<'vec3'> {\n return texel.xyz.sub(0.5).mul(2 * bounds.half).add(vec3(...bounds.center));\n}\n\n/** The Material Features an Impostor applies: the Forest's live values and the Variant's Crown Volume. */\nexport interface ImpostorFeatures {\n nodes: MaterialFeatureNodes;\n crown: CrownVolume;\n}\n\n/** Whether any Material Feature is on (then the Impostor bakes and reads `FEATURES_CHANNEL`). */\nexport function hasImpostorFeatures(features: ImpostorFeatures | null | undefined): features is ImpostorFeatures {\n const nodes = features?.nodes;\n return !!nodes && (nodes.crownNormals !== null || nodes.translucency !== null || nodes.occlusion !== null);\n}\n\n/**\n * The material of a Variant's Impostor cards: the Definition's shading (smooth: the baked normals\n * carry the shape), the baked colour with each leaf texel in the Season Profile at the tree's Season\n * plus the leaf's own timing shift (colour, blossom; a dropped leaf shows the wood layer behind it,\n * or nothing), the baked normal turned with the tree, bark or leaf roughness, cut out by the coverage\n * and the Detail Level cross-fade (in the shadow pass too, so the shadow is tree-shaped). With\n * `wind`, the card bends with height as the tree sways, in the tree's own Wind phase.\n */\nexport function createImpostorMaterial(\n definition: TreeDefinition,\n atlases: ImpostorAtlases,\n features: ImpostorFeatures | null = null,\n wind?: { source: WindSource; response: WindResponse },\n): MeshStandardNodeMaterial {\n const burst = wind && instanceBurstFrame();\n const sway = wind\n ? (point: Node<'vec3'>, time?: Node<'float'>) =>\n treeSwayOffset(wind.source, wind.response, point, {\n direction: instanceRotate(objectWindDirection(wind.source), true),\n phase: instanceState().windPhase,\n time,\n burst,\n })\n : undefined;\n const view = impostorView(atlases, sway);\n const material = createShadedMaterial(definition.materials.shading);\n material.name = 'tree.js impostor';\n material.flatShading = false;\n // The card always faces the camera; both sides so the shadow pass (which flips FrontSide) keeps it.\n material.side = DoubleSide;\n material.positionNode = view.position;\n // Wind-aware velocity (ADR 0011): the card's sway, bursts included, at the previous Wind time.\n if (wind && view.windShift) setWindMotion(view.position, { source: wind.source, shift: view.windShift });\n material.castShadowPositionNode = view.shadowPosition;\n\n // Per frame (frames blend wood and leaf texels, and leaves of different timing): each leaf texel at\n // its own Season. A dropped leaf gives way to the wood layer.\n const treeSeason = varying(instanceState().season) as Node<'float'>;\n const leafSeason = leafSeasonNode(definition.season);\n const maxShift = definition.variation.season;\n const frameStates = new Map<ImpostorFrame, { color: Node<'vec4'>; normal: Node<'vec4'> }>();\n const frameState = (frame: ImpostorFrame) => {\n let state = frameStates.get(frame);\n if (!state) {\n const texel = frame.sample(COLOR_CHANNEL);\n const normal = frame.sample(NORMAL_CHANNEL);\n const flag = normal.a.div(max(texel.a, MIN_COVERAGE)).clamp(0, 1);\n const season = frame.sample(SEASON_CHANNEL);\n const leaves = max(season.a, MIN_COVERAGE);\n // No leaf is shifted beyond the Definition's Season variation: that bounds the 8-bit error of\n // texels with little leaf in them (the shift is premultiplied by the leaf share).\n const shift = season.r.div(leaves).sub(0.5).div(SEASON_SHIFT_SCALE).clamp(-maxShift, maxShift);\n const part = vec3(shift, season.g.div(leaves).clamp(0, 1), season.b.div(leaves).clamp(0, 1));\n const leaf = leafSeason(treeSeason, part);\n // How much of the texel is leaves that are not shown now: that share is the wood layer's.\n const dropped = flag.mul(select(leaf.shown, float(0), float(1))).toVar();\n const shown = vec4(texel.rgb.mul(mix(vec3(1), leaf.color, flag)), texel.a);\n state = {\n color: mix(shown, frame.sample(WOOD_COLOR_CHANNEL), dropped),\n normal: mix(normal, frame.sample(WOOD_NORMAL_CHANNEL), dropped),\n };\n frameStates.set(frame, state);\n }\n return state;\n };\n const color = view.blend((frame) => frameState(frame).color);\n const normal = view.blend((frame) => frameState(frame).normal);\n const coverage = color.a;\n const covered = max(coverage, MIN_COVERAGE);\n material.colorNode = color.rgb.div(covered);\n const leaf = normal.a.div(covered).clamp(0, 1);\n const treeNormal = normal.rgb.div(covered).mul(2).sub(1).normalize();\n material.normalNode = transformNormalToView(instanceRotate(treeNormal)).normalize();\n material.roughnessNode = mix(float(definition.materials.bark.roughness), float(definition.materials.leaf.roughness), leaf);\n material.metalness = 0;\n material.maskNode = and(coverage.greaterThan(ALPHA_CUT), levelVisible());\n // Material Features: on a dropped leaf's texel the wood shows, and `leaf` (from the wood layer's flag) turns the leaf-only ones off there.\n if (hasImpostorFeatures(features)) applyImpostorFeatures(material, view, atlases.bounds, leaf, features);\n // Tree Effects: tree pixels, leaves where the (Season-aware) leaf flag says so (wood elsewhere).\n material.userData.treePart = 'leaves';\n setTreeLeafMask(material, leaf);\n hookTargets.set(material, {\n material,\n // No Fruit on an Impostor: its bark and leaf texels, by the (Season-aware) leaf flag.\n parts: ['bark', 'leaves'],\n partWeight: (part) => (part === 'leaves' ? leaf : float(1).sub(leaf)),\n vertexColors: false,\n season: treeSeason,\n growth: varying(instanceState().growth) as Node<'float'>,\n treePosition: varying(modelWorldMatrix.mul(vec4(levelTreePosition(), 1)).xyz) as Node<'vec3'>,\n sway: view.sway,\n });\n return material;\n}\n\nconst hookTargets = new WeakMap<MeshStandardNodeMaterial, ShaderHookTarget>();\n\n/**\n * What Tree Shader Hooks shade on an Impostor card (ADR 0012): its baked colour, leaf flag and normal at\n * draw time, so hooks follow live settings without a rebake.\n */\nexport function impostorHookTarget(material: MeshStandardNodeMaterial): ShaderHookTarget {\n const target = hookTargets.get(material);\n if (!target) throw new Error('Not an Impostor material');\n return target;\n}\n\n/**\n * Material Features on an Impostor card, as on the tree's own materials (same uniforms, so live tuning\n * needs no rebake): the Crown Volume is measured at the point each texel pictured. Crown Normals and\n * Leaf Translucency act on leaf texels only (by the baked leaf flag); Structural Occlusion on all.\n */\nfunction applyImpostorFeatures(\n material: MeshStandardNodeMaterial,\n view: ImpostorView,\n bounds: ImpostorBounds,\n leaf: Node<'float'>,\n features: ImpostorFeatures,\n): void {\n const { nodes } = features;\n const texel = view.value(FEATURES_CHANNEL);\n const crown = crownAt(features.crown, featurePoint(texel, bounds));\n if (nodes.crownNormals) {\n const own = material.normalNode as Node<'vec3'>;\n const crownView = transformNormalToView(instanceRotate(crown.normal)).normalize();\n const blend = mix(own, crownView, nodes.crownNormals.mul(leaf));\n material.normalNode = select(blend.length().greaterThan(1e-4), blend.normalize(), crownView);\n }\n if (nodes.translucency) {\n const { strength, edge, ambient } = nodes.translucency;\n applyLeafTranslucencyTerm(material, { strength: strength.mul(leaf), ambient: ambient.mul(leaf), edge, thinness: crown.distance.clamp(0, 1) });\n }\n if (nodes.occlusion) material.aoNode = mix(float(1), texel.w, nodes.occlusion);\n}\n","// The directions an Impostor is pictured from (ADR 0010), as pure maths: the CPU source of truth\n// that the bake (frame transforms) and the Impostor shader (TSL twins in impostor-material.ts) mirror.\n// No three.js at runtime.\n//\n// Directions are hemi-octahedral: the upper hemisphere (y >= 0, tree space) folded onto the unit\n// square, straight down from above in the centre and the horizon along the edges. The square is cut\n// into frames × frames frames; frame (i, j) pictures the tree from the direction at the centre of its\n// cell, ((i + 0.5) / frames, (j + 0.5) / frames). Frame (i, j) sits at column i, row j of the atlas.\n\nexport type Vec3 = readonly [number, number, number];\n\n/** A frame's camera: it looks along -forward, with `right` and `up` across its picture (right × up = forward). */\nexport interface FrameBasis {\n right: Vec3;\n up: Vec3;\n forward: Vec3;\n}\n\n/** The (up to) four frames a view blends, with their weights (they sum to 1). */\nexport interface FrameBlend {\n frames: [number, number][];\n weights: number[];\n}\n\n/** Below this |y|, a frame's up is world up; above it (seen from straight above) the frame's up is -z. */\nconst POLE = 0.999;\n\n// `+ 0` turns -0 into 0, so equal directions compare equal.\nconst vec = (x: number, y: number, z: number): Vec3 => [x + 0, y + 0, z + 0];\n\nfunction normalize(v: Vec3): Vec3 {\n const l = Math.hypot(v[0], v[1], v[2]);\n return vec(v[0] / l, v[1] / l, v[2] / l);\n}\n\nfunction cross(a: Vec3, b: Vec3): Vec3 {\n return vec(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]);\n}\n\nfunction dot(a: Vec3, b: Vec3): number {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\n/** A view direction (from the tree towards the viewer) on the unit square; views from below count as from the horizon. */\nexport function octahedralEncode(direction: Vec3): [number, number] {\n const [x, y, z] = [direction[0], Math.max(direction[1], 0), direction[2]];\n const s = Math.abs(x) + Math.abs(y) + Math.abs(z);\n const px = x / s;\n const pz = z / s;\n return [(px + pz + 1) / 2, (px - pz + 1) / 2];\n}\n\n/** The unit direction at a point of the unit square (inverse of `octahedralEncode`). */\nexport function octahedralDecode(u: number, v: number): Vec3 {\n const a = u * 2 - 1;\n const b = v * 2 - 1;\n const px = (a + b) / 2;\n const pz = (a - b) / 2;\n return normalize([px, 1 - Math.abs(px) - Math.abs(pz), pz]);\n}\n\n/** The direction frame (i, j) pictures the tree from. */\nexport function frameDirection(i: number, j: number, frames: number): Vec3 {\n return octahedralDecode((i + 0.5) / frames, (j + 0.5) / frames);\n}\n\n/** The camera basis of a frame looking at the tree from `forward`. */\nexport function frameBasis(forward: Vec3): FrameBasis {\n const reference: Vec3 = Math.abs(forward[1]) > POLE ? [0, 0, -1] : [0, 1, 0];\n const right = normalize(cross(reference, forward));\n return { right, up: cross(forward, right), forward: vec(...forward) };\n}\n\n/**\n * The four frames around a view direction and their bilinear weights, in the order (i, j), (i+1, j),\n * (i, j+1), (i+1, j+1). On the grid's edge (and with one frame) the frames are clamped to the grid.\n */\nexport function blendFrames(view: Vec3, frames: number): FrameBlend {\n const [u, v] = octahedralEncode(view);\n const cell = (t: number) => {\n const g = Math.min(Math.max(t * frames - 0.5, 0), frames - 1);\n const base = Math.min(Math.floor(g), Math.max(frames - 2, 0));\n return [base, g - base] as const;\n };\n const [i, fx] = cell(u);\n const [j, fy] = cell(v);\n const last = frames - 1;\n const at = (di: number, dj: number): [number, number] => [Math.min(i + di, last), Math.min(j + dj, last)];\n return {\n frames: [at(0, 0), at(1, 0), at(0, 1), at(1, 1)],\n weights: [(1 - fx) * (1 - fy), fx * (1 - fy), (1 - fx) * fy, fx * fy],\n };\n}\n\n/**\n * Where frame `forward` pictured what is seen through `point` of the card (tree space, relative to\n * the tree's centre) looking along `-view`: the line of sight meets the frame's plane (through the\n * centre, facing `forward`) and that spot is projected onto the frame. In 0..1 across the frame,\n * whose picture spans `2 · half` (the card's size).\n */\nexport function frameUv(point: Vec3, view: Vec3, forward: Vec3, half: number): [number, number] {\n const t = dot(point, forward) / Math.max(dot(view, forward), 1e-3);\n const hit = vec(point[0] - view[0] * t, point[1] - view[1] * t, point[2] - view[2] * t);\n const { right, up } = frameBasis(forward);\n return [dot(hit, right) / (2 * half) + 0.5, dot(hit, up) / (2 * half) + 0.5];\n}\n","// A Variant's Impostor (ADR 0010, GLOSSARY): the atlases baked from frames × frames directions at\n// Growth 1, and the card material that draws far trees with them. The directions are hemi-octahedral\n// (`octahedral.ts`): the upper hemisphere only, from the horizon to straight above; a view from below\n// uses the horizon frames.\n//\n// What is baked is a list of channels (one atlas each); the bake renders every channel of every\n// frame in one pass. Later features add channels (`impostorChannels`) and read them in the material\n// (`createImpostorMaterial`, through `ImpostorView.value`).\nimport {\n BufferAttribute,\n BufferGeometry,\n DoubleSide,\n InstancedMesh,\n LinearFilter,\n LinearMipmapLinearFilter,\n Matrix4,\n MeshBasicNodeMaterial,\n OrthographicCamera,\n RenderTarget,\n RendererUtils,\n Scene,\n UnsignedByteType,\n type Node,\n type Renderer,\n type Texture,\n} from 'three/webgpu';\nimport { attribute, float, frontFacing, mrt, normalGeometry, output, positionGeometry, select, texture, uv, vec4 } from 'three/tsl';\nimport type { TreeDefinition } from '../definition';\nimport type { GeometryBuffers } from '../generator';\nimport { createBarkMaterial, createLeafMaterial } from '../materials';\nimport type { TextureOptions } from '../textures';\nimport type { WindResponse, WindSource } from '../wind';\nimport {\n COLOR_CHANNEL,\n createImpostorMaterial,\n FEATURES_CHANNEL,\n featureTexel,\n hasImpostorFeatures,\n NORMAL_CHANNEL,\n SEASON_CHANNEL,\n WOOD_COLOR_CHANNEL,\n WOOD_NORMAL_CHANNEL,\n type ImpostorAtlases,\n type ImpostorBounds,\n type ImpostorFeatures,\n} from './impostor-material';\nimport { encodeSeasonTexel, SEASON_SHIFT_SCALE } from './impostor-season';\nimport type { LevelPart } from './levels';\nimport type { ImpostorAtlasOptions } from './lod';\nimport { frameBasis, frameDirection } from './octahedral';\n\n/** Room around the tree's bounding sphere in each frame, so mipmaps do not bleed in from the next frame. */\nconst FRAME_MARGIN = 1.04;\n\n/** One part of the tree as the bake draws it. */\nexport interface ImpostorBakePart {\n kind: 'wood' | 'leaves';\n /** The part's vertex data (tree space, Growth 1). */\n geometry: BufferGeometry;\n /** The unlit bake material of the part: its colour, alpha cut and the Definition's maps. */\n material: MeshBasicNodeMaterial;\n}\n\n/**\n * One atlas of an Impostor: what the bake writes per covered texel for each part. The background\n * stays 0, so every atlas is premultiplied by coverage (mipmaps and frame blends stay right; the\n * material divides by the coverage). `name` is the MRT output and texture name.\n */\nexport interface ImpostorChannel {\n name: string;\n bake(part: ImpostorBakePart): Node<'vec4'>;\n}\n\n/** Leaves are two-sided: the normal of the side the frame sees, encoded 0..1. */\nconst bakedNormal = () => select(frontFacing, normalGeometry, normalGeometry.negate()).normalize().mul(0.5).add(0.5);\n\n/**\n * The channels of the tree layer every Impostor bakes: colour (rgb, coverage in a), the tree-space\n * normal (a = leaf flag), the leaves' Season timing (`encodeSeasonTexel`: shift, coverage rank,\n * blossom rank, leaf flag; empty on wood), plus, only when a Material Feature is on, the features\n * atlas (`FEATURES_CHANNEL`: the pictured point and the raw Structural Occlusion).\n *\n * Each channel is one RGBA8 attachment of a single render pass: WebGPU's default limit\n * (`maxColorAttachmentBytesPerSample` 32, 8 per RGBA8) allows 4, which these use up. More inputs need\n * another layer (as the wood layer, `impostorWoodChannels`).\n */\nexport function impostorChannels(bounds: ImpostorBounds, features: ImpostorFeatures | null = null): ImpostorChannel[] {\n const channels: ImpostorChannel[] = [\n { name: COLOR_CHANNEL, bake: () => output },\n { name: NORMAL_CHANNEL, bake: (part) => vec4(bakedNormal(), float(part.kind === 'leaves' ? 1 : 0)) },\n {\n name: SEASON_CHANNEL,\n bake: (part) => {\n if (part.kind === 'wood') return vec4(...encodeSeasonTexel(null));\n const aSeason = attribute<'vec3'>('aSeason', 'vec3');\n return vec4(aSeason.x.mul(SEASON_SHIFT_SCALE).add(0.5), aSeason.y, aSeason.z, 1);\n },\n },\n ];\n if (hasImpostorFeatures(features)) {\n // aOcclusion is only generated when Structural Occlusion is on.\n const occlusion = features.nodes.occlusion ? attribute<'float'>('aOcclusion', 'float') : float(0);\n channels.push({ name: FEATURES_CHANNEL, bake: () => featureTexel(positionGeometry, occlusion, bounds) });\n }\n return channels;\n}\n\n/**\n * The channels of the wood layer: the wood alone (colour with coverage, normal), so an Impostor shows\n * bare branches where its leaves have dropped instead of holes.\n */\nexport function impostorWoodChannels(): ImpostorChannel[] {\n return [\n { name: WOOD_COLOR_CHANNEL, bake: () => output },\n { name: WOOD_NORMAL_CHANNEL, bake: () => vec4(bakedNormal(), 0) },\n ];\n}\n\n/** One render target of the bake: the parts drawn into it and the atlases (channels) it holds. */\ninterface ImpostorLayer {\n kinds: readonly ImpostorBakePart['kind'][];\n channels: readonly ImpostorChannel[];\n target: RenderTarget;\n}\n\n/** The tree's centre and the half size of a frame, from its wood and leaves (Fruit is not on Impostors). */\nexport function impostorBounds(parts: readonly GeometryBuffers[]): ImpostorBounds {\n const min = [Infinity, Infinity, Infinity];\n const max = [-Infinity, -Infinity, -Infinity];\n for (const { positions } of parts) {\n for (let i = 0; i < positions.length; i += 3) {\n for (let c = 0; c < 3; c++) {\n min[c] = Math.min(min[c]!, positions[i + c]!);\n max[c] = Math.max(max[c]!, positions[i + c]!);\n }\n }\n }\n if (min[0] === Infinity) return { center: [0, 0, 0], half: 1 };\n const center = [0, 1, 2].map((c) => (min[c]! + max[c]!) / 2) as [number, number, number];\n let radius = 0;\n for (const { positions } of parts) {\n for (let i = 0; i < positions.length; i += 3) {\n radius = Math.max(radius, Math.hypot(positions[i]! - center[0], positions[i + 1]! - center[1], positions[i + 2]! - center[2]));\n }\n }\n return { center, half: Math.max(radius, 1e-3) * FRAME_MARGIN };\n}\n\n/**\n * Where the bake draws the tree for frame (i, j): seen from the frame's direction (its basis turned\n * to the camera's axes), scaled so the frame spans 2·half, moved into its cell of the atlas. The bake\n * camera is orthographic over the atlas (0..1 in x and y), so one draw renders every frame.\n */\nexport function frameTransform(i: number, j: number, frames: number, bounds: ImpostorBounds): Matrix4 {\n const { right, up, forward } = frameBasis(frameDirection(i, j, frames));\n const s = 1 / (2 * bounds.half);\n const [cx, cy, cz] = bounds.center;\n const rows = [right, up, forward].map(([x, y, z]) => [x * s, y * s, z * s, -(x * cx + y * cy + z * cz) * s]);\n const m = new Matrix4().set(\n rows[0]![0]! / frames, rows[0]![1]! / frames, rows[0]![2]! / frames, (rows[0]![3]! + 0.5 + i) / frames,\n rows[1]![0]! / frames, rows[1]![1]! / frames, rows[1]![2]! / frames, (rows[1]![3]! + 0.5 + j) / frames,\n rows[2]![0]!, rows[2]![1]!, rows[2]![2]!, rows[2]![3]!,\n 0, 0, 0, 1,\n );\n return m;\n}\n\n/** The unlit bake materials of the wood and the leaves (Growth 1, no Wind, no Season mask). */\nfunction bakeMaterials(definition: TreeDefinition, textures?: TextureOptions): { wood: MeshBasicNodeMaterial; leaves: MeshBasicNodeMaterial } {\n const bark = createBarkMaterial(definition, textures, float(1));\n const wood = new MeshBasicNodeMaterial();\n wood.name = 'tree.js impostor bake wood';\n wood.colorNode = bark.colorNode;\n bark.dispose();\n\n const leaf = createLeafMaterial(definition, textures);\n const leaves = new MeshBasicNodeMaterial();\n leaves.name = 'tree.js impostor bake leaves';\n leaves.vertexColors = true; // the Seed's per-leaf tint; the Season colour is applied when drawn\n leaves.side = DoubleSide;\n if (leaf.map) {\n // Card texture: its colour, cut at alphaTest; covered texels stay fully opaque (coverage).\n const card = texture(leaf.map, uv());\n leaves.colorNode = vec4(card.rgb, 1);\n leaves.maskNode = card.a.greaterThanEqual(leaf.alphaTest);\n }\n leaf.dispose();\n return { wood, leaves };\n}\n\n/** Rows of the card: the Wind bends it with height, so it needs more than one row of quads. */\nconst CARD_ROWS = 4;\n\n/** The card: a square from (−1, −1) to (1, 1) in x and y, in `CARD_ROWS` rows. */\nfunction cardGeometry(): BufferGeometry {\n const positions: number[] = [];\n const uvs: number[] = [];\n const index: number[] = [];\n for (let row = 0; row <= CARD_ROWS; row++) {\n const v = row / CARD_ROWS;\n positions.push(-1, v * 2 - 1, 0, 1, v * 2 - 1, 0);\n uvs.push(0, v, 1, v);\n if (row < CARD_ROWS) {\n const a = row * 2;\n index.push(a, a + 1, a + 3, a, a + 3, a + 2);\n }\n }\n const geometry = new BufferGeometry();\n geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3));\n geometry.setAttribute('normal', new BufferAttribute(new Float32Array(positions.length).map((_, i) => (i % 3 === 2 ? 1 : 0)), 3));\n geometry.setAttribute('uv', new BufferAttribute(new Float32Array(uvs), 2));\n geometry.setIndex(index);\n return geometry;\n}\n\n/** A render target for one layer's atlases (one texture per channel, named after it). */\nfunction layerTarget(size: number, channels: readonly ImpostorChannel[]): RenderTarget {\n const target = new RenderTarget(size, size, {\n count: channels.length,\n type: UnsignedByteType,\n depthBuffer: true,\n generateMipmaps: true,\n minFilter: LinearMipmapLinearFilter,\n magFilter: LinearFilter,\n });\n channels.forEach((channel, i) => (target.textures[i]!.name = channel.name));\n return target;\n}\n\n/** What the Impostor of one Variant is made from. */\nexport interface VariantImpostorOptions {\n definition: TreeDefinition;\n /** The Variant's vertex data the bake draws (shared: never disposed by the Impostor). */\n sources: { wood: BufferGeometry; leaves: BufferGeometry };\n /** The tree's centre and the half size of a frame: `impostorBounds` of the wood and leaves. */\n bounds: ImpostorBounds;\n atlas: Required<ImpostorAtlasOptions>;\n /** Name of the card mesh. */\n name: string;\n /** Where the Definition's textures load from. */\n textures?: TextureOptions;\n /** The Forest's live Material Feature uniforms and the Variant's Crown Volume; null when none is on. */\n features?: ImpostorFeatures | null;\n /** The Wind the cards sway with and the Variant's response to it. */\n wind?: { source: WindSource; response: WindResponse };\n}\n\n/**\n * The Impostor of one Variant: the atlases (allocated at once, filled by `bake`), the card material\n * that samples them, and the card geometry. `part` is what the Variant's Impostor Detail Level draws.\n *\n * Two layers are baked: the tree (wood and leaves, with the leaves' Season timing) and the wood\n * alone, which shows where leaves have dropped.\n */\nexport class VariantImpostor {\n readonly frames: number;\n readonly bounds: ImpostorBounds;\n /** The channels of every layer (one atlas each). */\n readonly channels: readonly ImpostorChannel[];\n /** The Impostor level's single mesh: a card per tree. */\n readonly part: LevelPart;\n private readonly definition: TreeDefinition;\n private readonly sources: { wood: BufferGeometry; leaves: BufferGeometry };\n private readonly textures: TextureOptions | undefined;\n private readonly layers: readonly ImpostorLayer[];\n private baked = false;\n\n constructor({ definition, sources, bounds, atlas, name, textures, features = null, wind }: VariantImpostorOptions) {\n this.definition = definition;\n this.sources = sources;\n this.textures = textures;\n this.frames = atlas.frames;\n this.bounds = bounds;\n const layer = (kinds: ImpostorLayer['kinds'], channels: ImpostorChannel[]): ImpostorLayer => ({ kinds, channels, target: layerTarget(atlas.size, channels) });\n this.layers = [layer(['wood', 'leaves'], impostorChannels(this.bounds, features)), layer(['wood'], impostorWoodChannels())];\n this.channels = this.layers.flatMap((l) => l.channels);\n this.part = { name, geometry: cardGeometry(), material: createImpostorMaterial(definition, this.atlases, features, wind) };\n }\n\n /** The atlases by channel name. */\n get atlases(): ImpostorAtlases {\n const textures: Record<string, Texture> = {};\n for (const { channels, target } of this.layers) channels.forEach((channel, i) => (textures[channel.name] = target.textures[i]!));\n return { frames: this.frames, bounds: this.bounds, textures };\n }\n\n /** Whether `bake` has run. */\n get isBaked(): boolean {\n return this.baked;\n }\n\n /**\n * Renders every frame into the atlases with the app's renderer, one pass per layer, then restores\n * the renderer as it was. Deterministic: the same Definition and Variant Seed give the same atlases.\n */\n bake(renderer: Renderer): void {\n const frames = this.frames;\n const materials: MeshBasicNodeMaterial[] = [];\n const meshes: InstancedMesh[] = [];\n const scenes = this.layers.map(({ kinds, channels }) => {\n // Each layer has its own materials: their MRT outputs are the layer's channels.\n const layerMaterials = bakeMaterials(this.definition, this.textures);\n materials.push(layerMaterials.wood, layerMaterials.leaves);\n const scene = new Scene();\n for (const kind of kinds) {\n const source = this.sources[kind];\n if ((source.getIndex()?.count ?? 0) === 0) continue;\n const material = layerMaterials[kind];\n const part: ImpostorBakePart = { kind, geometry: source, material };\n material.mrtNode = mrt(Object.fromEntries(channels.map((c) => [c.name, c.bake(part)])));\n // Shares the Variant's vertex data (never disposed here: that would free the shared buffers).\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 const mesh = new InstancedMesh(geometry, material, frames * frames);\n for (let j = 0; j < frames; j++) {\n for (let i = 0; i < frames; i++) mesh.setMatrixAt(j * frames + i, frameTransform(i, j, frames, this.bounds));\n }\n mesh.frustumCulled = false;\n scene.add(mesh);\n meshes.push(mesh);\n }\n return scene;\n });\n const camera = new OrthographicCamera(0, 1, 1, 0, 0, 2);\n camera.position.set(0, 0, 1);\n camera.updateMatrixWorld();\n\n const state = RendererUtils.resetRendererState(renderer, {} as Parameters<typeof RendererUtils.resetRendererState>[1]);\n try {\n renderer.setClearColor(0x000000, 0);\n this.layers.forEach(({ target }, i) => {\n renderer.setRenderTarget(target);\n renderer.render(scenes[i]!, camera);\n });\n } finally {\n RendererUtils.restoreRendererState(renderer, state);\n for (const mesh of meshes) mesh.dispose();\n for (const material of materials) material.dispose();\n }\n this.baked = true;\n }\n\n /** Frees the atlases, the card geometry and its material (the level mesh's geometry belongs to the levels). */\n dispose(): void {\n for (const { target } of this.layers) target.dispose();\n this.part.geometry.dispose();\n this.part.material.dispose();\n }\n}\n","// Forest Detail Levels (ADR 0010): the options, their validation and defaults, and the pure\n// level selection that the GPU compute pass mirrors. No three.js at runtime.\nimport type { Camera } from 'three/webgpu';\nimport type { TreeDefinitionInput } from '../definition';\n\n/** A Forest tree's Detail Level (GLOSSARY): Full (as without Detail Levels), Light (fewer faces and leaves) or Impostor (one card). */\nexport const DetailLevel = { Full: 0, Light: 1, Impostor: 2 } as const;\nexport type DetailLevel = (typeof DetailLevel)[keyof typeof DetailLevel];\n\n/** Resolution of a Variant's Impostor atlases. */\nexport interface ImpostorAtlasOptions {\n /**\n * Directions per side (frames × frames pictures). They are hemi-octahedral: they cover the upper\n * hemisphere only, from the horizon to straight above (a view from below uses the horizon frames).\n * Default 12.\n */\n frames?: number;\n /** Atlas width and height in pixels. Default 2048. */\n size?: number;\n}\n\n/** The Detail Levels of a Forest (`ForestOptions.lod`). */\nexport interface ForestLodOptions {\n /** Camera distance (world units, divided by the tree's placement scale) from which a tree draws Light. */\n light: number;\n /** Camera distance (as `light`, at least `light`) from which a fully grown tree draws as an Impostor. */\n impostor: number;\n /** Width of the cross-fade band, as a fraction (0..1) of each switch distance, centred on it. Default 0.1. */\n fade?: number;\n /** Impostor atlas resolution. Default 12 × 12 directions at 2048². */\n impostorAtlas?: ImpostorAtlasOptions;\n /** Partial Definition merged over the automatic Light reduction of every Variant. */\n lightDefinition?: Omit<TreeDefinitionInput, 'schemaVersion'>;\n /** The camera whose distance picks every tree's level. Default: the first non-shadow camera that draws the Forest in a frame. */\n camera?: Camera | null;\n}\n\n/** A Forest's current Detail Level settings (`forest.lod`), every default filled in. */\nexport interface ForestLodSettings {\n light: number;\n impostor: number;\n fade: number;\n impostorAtlas: Required<ImpostorAtlasOptions>;\n lightDefinition: Omit<TreeDefinitionInput, 'schemaVersion'> | null;\n /** null: the first non-shadow camera that draws the Forest in a frame. */\n camera: Camera | null;\n}\n\n/** What `forest.lod = …` can change live (only uniforms are written: no rebuild, no recompile). */\nexport type ForestLodUpdate = Partial<Pick<ForestLodSettings, 'light' | 'impostor' | 'fade' | 'camera'>>;\n\n/** The distances the level selection needs. */\nexport type DetailLevelDistances = Pick<ForestLodSettings, 'light' | 'impostor' | 'fade'>;\n\n/** A tree's Detail Level and how far it has faded into the next one. */\nexport interface DetailLevelSelection {\n /** The nearer level the tree draws at. */\n level: DetailLevel;\n /**\n * 0..1: how far the tree is into the cross-fade towards `level + 1`. The tree draws at `level`\n * with amount `1 - fade` and, when `fade > 0`, also at `level + 1` with amount `fade`.\n */\n fade: number;\n}\n\nexport const DEFAULT_LOD_FADE = 0.1;\nexport const DEFAULT_IMPOSTOR_ATLAS: Required<ImpostorAtlasOptions> = { frames: 12, size: 2048 };\n/** `lod: true`: Light from this many trunk heights away, Impostor from … */\nexport const DEFAULT_LIGHT_HEIGHTS = 6;\n/** … this many trunk heights away. */\nexport const DEFAULT_IMPOSTOR_HEIGHTS = 20;\n/** Smallest placement scale the selection divides by (a scale of 0 must not divide by zero). */\nexport const MIN_LOD_SCALE = 1e-6;\n\n/** 0 below `start`, 1 from `end`, linear in between (a band of width 0 is a hard step at `end`). */\nfunction ramp(x: number, start: number, end: number): number {\n if (end <= start) return x >= end ? 1 : 0;\n return Math.min(Math.max((x - start) / (end - start), 0), 1);\n}\n\n/**\n * Picks a Forest tree's Detail Level. The single source of truth for level selection: the GPU\n * compute pass mirrors it line by line.\n *\n * - `t = distance / max(scale, 1e-6)`: a tree at placement scale 2 switches at twice the distance.\n * - Each switch distance `d` (`light`, `impostor`) has a cross-fade band from `d·(1 − fade/2)` to\n * `d·(1 + fade/2)`; inside it the tree fades linearly from the nearer level to the next one.\n * - A tree whose drawn Growth is below 1 is never an Impostor: it is capped at Light.\n * - The Impostor switch is checked first, so if the two bands overlap the farther one wins.\n *\n * @param distance distance from the camera that picks the levels to the tree's base, world units\n * @param scale the tree's placement scale\n * @param growth the tree's drawn Growth (after its Growth delay)\n */\nexport function selectDetailLevel(distance: number, scale: number, growth: number, settings: DetailLevelDistances): DetailLevelSelection {\n const t = distance / Math.max(scale, MIN_LOD_SCALE);\n const half = settings.fade / 2;\n if (growth >= 1) {\n const toImpostor = ramp(t, settings.impostor * (1 - half), settings.impostor * (1 + half));\n if (toImpostor >= 1) return { level: DetailLevel.Impostor, fade: 0 };\n if (toImpostor > 0) return { level: DetailLevel.Light, fade: toImpostor };\n }\n const toLight = ramp(t, settings.light * (1 - half), settings.light * (1 + half));\n if (toLight >= 1) return { level: DetailLevel.Light, fade: 0 };\n return { level: DetailLevel.Full, fade: toLight };\n}\n\nfunction checkDistance(name: string, value: number): void {\n if (!Number.isFinite(value) || value < 0) throw new RangeError(`Forest lod.${name} must be a finite distance >= 0, got ${value}`);\n}\n\n/** Throws a RangeError unless the distances and fade are valid. */\nexport function checkDetailLevelDistances({ light, impostor, fade }: DetailLevelDistances): void {\n checkDistance('light', light);\n checkDistance('impostor', impostor);\n if (impostor < light) throw new RangeError(`Forest lod.impostor (${impostor}) must be at least lod.light (${light})`);\n if (!(fade >= 0 && fade <= 1)) throw new RangeError(`Forest lod.fade must be within 0..1, got ${fade}`);\n}\n\nfunction checkAtlas(name: keyof ImpostorAtlasOptions, value: number): void {\n if (!Number.isInteger(value) || value < 1) throw new RangeError(`Forest lod.impostorAtlas.${name} must be an integer >= 1, got ${value}`);\n}\n\n/** The switch distances of `lod: true`, from the tallest Variant's trunk height. */\nexport function defaultDetailLevelDistances(trunkHeight: number): Pick<ForestLodSettings, 'light' | 'impostor'> {\n return { light: trunkHeight * DEFAULT_LIGHT_HEIGHTS, impostor: trunkHeight * DEFAULT_IMPOSTOR_HEIGHTS };\n}\n\n/**\n * The settings of `ForestOptions.lod` with every default filled in, or null when it is missing or\n * false. `trunkHeight` (the tallest Variant's) gives the distances of `lod: true`. Throws a RangeError\n * for invalid settings.\n */\nexport function resolveForestLod(lod: boolean | ForestLodOptions | undefined, trunkHeight: number): ForestLodSettings | null {\n if (lod === undefined || lod === false) return null;\n const options: ForestLodOptions = lod === true ? defaultDetailLevelDistances(trunkHeight) : lod;\n const settings: ForestLodSettings = {\n light: options.light,\n impostor: options.impostor,\n fade: options.fade ?? DEFAULT_LOD_FADE,\n impostorAtlas: { ...DEFAULT_IMPOSTOR_ATLAS, ...options.impostorAtlas },\n lightDefinition: options.lightDefinition ?? null,\n camera: options.camera ?? null,\n };\n checkDetailLevelDistances(settings);\n checkAtlas('frames', settings.impostorAtlas.frames);\n checkAtlas('size', settings.impostorAtlas.size);\n return settings;\n}\n\n/** Side of the ordered-dither (Bayer) matrix the cross-fade uses. */\nexport const DITHER_SIZE = 8;\n\n/**\n * The cross-fade threshold of screen pixel (x, y), in 0..1: an 8 × 8 Bayer matrix, the same in every\n * frame (no temporal noise), so a still frame is deterministic. The GPU mirrors it bit for bit.\n */\nexport function ditherThreshold(x: number, y: number): number {\n const px = Math.floor(x) & 7;\n const py = Math.floor(y) & 7;\n const v = px ^ py;\n const rank = ((v & 1) << 5) | ((py & 1) << 4) | ((v & 2) << 2) | ((py & 2) << 1) | ((v & 4) >> 1) | ((py & 4) >> 2);\n return (rank + 0.5) / (DITHER_SIZE * DITHER_SIZE);\n}\n\n/**\n * Whether a tree drawn at a level shows a pixel with dither `threshold`. A tree at `level` with\n * `fade` shows the nearer level where `threshold < 1 − fade` and the next level (`next`) everywhere\n * else, so the two levels together cover every pixel exactly once.\n */\nexport function showsPixel(fade: number, next: boolean, threshold: number): boolean {\n return next ? threshold >= 1 - fade : threshold < 1 - fade;\n}\n","// Forest Detail Levels on the GPU (ADR 0010): per Variant, a compute pass sorts the trees into one\n// list per Detail Level and fills the indirect draw arguments of the meshes that draw each level.\nimport {\n BufferGeometry,\n IndirectStorageBufferAttribute,\n Matrix4,\n Mesh,\n StorageBufferAttribute,\n Vector3,\n type Camera,\n type ComputeNode,\n type Material,\n type Node,\n type Object3D,\n type Renderer,\n type Scene,\n type StorageBufferNode,\n type UniformNode,\n} from 'three/webgpu';\nimport { atomicAdd, atomicLoad, atomicStore, float, Fn, If, instanceIndex, screenCoordinate, select, storage, uint, uniform, varying, vec4 } from 'three/tsl';\nimport { DetailLevel, DITHER_SIZE, MIN_LOD_SCALE } from './lod';\nimport { drawsDetailLevel, INSTANCE_STRIDE, type LevelInstance } from './nodes';\n\n/** Detail Levels a Variant can draw: Full, Light and Impostor. Lists and draw arguments have room for all three. */\nexport const LEVEL_COUNT = 3;\n/** Meshes (materials) one Detail Level draws at most: wood, leaves and Fruit. */\nexport const MAX_LEVEL_PARTS = 3;\n/** u32s per indexed indirect draw: indexCount, instanceCount, firstIndex, baseVertex, firstInstance. */\nconst ARGS_STRIDE = 5;\n/** vec4s per tree in the GPU tree data: rotation, state (as the instance data), position. */\nconst TREE_VEC4S = 3;\n\n/** The live values every Variant's level selection reads (one set per Forest). */\nexport interface DetailLevelUniforms {\n light: UniformNode<'float', number>;\n impostor: UniformNode<'float', number>;\n fade: UniformNode<'float', number>;\n /** World position of the camera that picks the levels this frame. */\n camera: UniformNode<'vec3', Vector3>;\n /** The Forest's world matrix (tree positions are in forest space). */\n forest: UniformNode<'mat4', Matrix4>;\n /**\n * The farthest Detail Level that can be drawn: Light until the Impostors are baked. Trees\n * beyond it draw at it, without a cross-fade into the level that is not there.\n */\n farthest: UniformNode<'uint', number>;\n}\n\n/** One mesh of a Detail Level: the geometry (shared vertex data) and the material it draws with. */\nexport interface LevelPart {\n name: string;\n geometry: BufferGeometry;\n material: Material;\n}\n\n/** The meshes of one Detail Level of a Variant. */\nexport interface LevelMeshes {\n level: DetailLevel;\n meshes: Mesh[];\n}\n\n/** The 8 × 8 Bayer threshold of this fragment (twin of `ditherThreshold`). */\nfunction ditherThresholdNode(): Node<'float'> {\n const x = uint(screenCoordinate.x).bitAnd(7);\n const y = uint(screenCoordinate.y).bitAnd(7);\n const v = x.bitXor(y);\n const rank = v\n .bitAnd(1)\n .shiftLeft(5)\n .bitOr(y.bitAnd(1).shiftLeft(4))\n .bitOr(v.bitAnd(2).shiftLeft(2))\n .bitOr(y.bitAnd(2).shiftLeft(1))\n .bitOr(v.bitAnd(4).shiftRight(1))\n .bitOr(y.bitAnd(4).shiftRight(2));\n return float(rank).add(0.5).div(DITHER_SIZE * DITHER_SIZE);\n}\n\n/** 0 below `start`, 1 from `end`, linear in between (twin of `ramp` in lod.ts). */\nfunction ramp(x: Node<'float'>, start: Node<'float'>, end: Node<'float'>): Node<'float'> {\n const step = select(x.greaterThanEqual(end), float(1), float(0));\n return select(end.lessThanEqual(start), step, x.sub(start).div(end.sub(start)).clamp(0, 1));\n}\n\n/**\n * The GPU side of one Variant's Detail Levels: the tree data by slot, one list of tree slots per\n * level (with each entry's cross-fade), the indirect draw arguments, the compute pass that fills\n * them, and the meshes of every level (they draw indirectly and read their trees by slot).\n *\n * - `setLevel(level, parts)` gives a level its meshes (Full and Light now; an Impostor card later).\n * - `write(slot, …)` / `count` mirror the Variant's instance data; `resize(capacity)` keeps them.\n * - `dispatches` run once per frame for the camera that picks the levels, before any of the meshes is drawn.\n */\nexport class VariantLevels {\n /** Every level's meshes, nearest level first. */\n readonly levels: LevelMeshes[] = [];\n private capacityValue: number;\n private treeData: StorageBufferAttribute;\n private lists: StorageBufferAttribute;\n private dithers: StorageBufferAttribute;\n private readonly counters = new StorageBufferAttribute(new Uint32Array(LEVEL_COUNT), 1);\n private readonly args = new IndirectStorageBufferAttribute(new Uint32Array(LEVEL_COUNT * MAX_LEVEL_PARTS * ARGS_STRIDE), 1);\n // The draw side reads the buffers through these nodes; resize() points them at the new buffers.\n private readonly treeNode: StorageBufferNode<'vec4'>;\n private readonly listNode: StorageBufferNode<'uint'>;\n private readonly ditherNode: StorageBufferNode<'float'>;\n private readonly countNode = uniform(0, 'uint');\n private readonly levelOf = new WeakMap<object, DetailLevel>();\n private computeNodes: ComputeNode[];\n /** Bumped whenever the trees change (data, count, capacity): the levels must be selected again. */\n version = 0;\n /** What the meshes read per tree (see `drawsDetailLevel`). */\n private readonly instance: LevelInstance;\n\n constructor(\n capacity: number,\n private readonly uniforms: DetailLevelUniforms,\n private readonly setupMesh: (mesh: Mesh) => void,\n ) {\n this.capacityValue = capacity;\n this.treeData = new StorageBufferAttribute(new Float32Array(capacity * TREE_VEC4S * 4), 4);\n this.lists = new StorageBufferAttribute(new Uint32Array(LEVEL_COUNT * capacity), 1);\n this.dithers = new StorageBufferAttribute(new Float32Array(LEVEL_COUNT * capacity), 1);\n this.treeNode = storage(this.treeData, 'vec4', capacity * TREE_VEC4S).toReadOnly();\n this.listNode = storage(this.lists, 'uint', LEVEL_COUNT * capacity).toReadOnly();\n this.ditherNode = storage(this.dithers, 'float', LEVEL_COUNT * capacity).toReadOnly();\n\n // The entry of the level list this instance draws: the level's base (per mesh) + instanceIndex.\n // A flat varying, so the fragment stage reads the same entry.\n const base = uniform(0, 'uint').onObjectUpdate(({ object }) => (this.levelOf.get(object as object) ?? 0) * this.capacityValue);\n const entry = varying(base.add(instanceIndex)) as unknown as Node<'uint'>;\n const slot = this.listNode.element(entry) as unknown as Node<'uint'>;\n const tree = (k: number) => this.treeNode.element(slot.mul(TREE_VEC4S).add(k)) as unknown as Node<'vec4'>;\n // dither >= 0: the nearer level of a cross-fade, drawn where threshold < dither; < 0: the next\n // level, drawn where threshold >= -dither (see `showsPixel`).\n const dither = this.ditherNode.element(entry) as unknown as Node<'float'>;\n const threshold = ditherThresholdNode();\n this.instance = {\n slot,\n rotation: tree(0),\n state: tree(1),\n position: tree(2).xyz,\n visible: select(dither.greaterThanEqual(0), threshold.lessThan(dither), threshold.greaterThanEqual(dither.negate())) as unknown as Node<'bool'>,\n };\n this.computeNodes = this.createDispatches();\n }\n\n get capacity(): number {\n return this.capacityValue;\n }\n\n /** Number of trees (slots 0..count-1 are in use). */\n get count(): number {\n return this.countNode.value;\n }\n\n set count(value: number) {\n this.countNode.value = value;\n this.version++;\n }\n\n /** The compute dispatches to run once per frame (reset, select, draw arguments). */\n get dispatches(): readonly ComputeNode[] {\n return this.computeNodes;\n }\n\n /** Every mesh of every level. */\n get meshes(): Mesh[] {\n return this.levels.flatMap((l) => l.meshes);\n }\n\n /**\n * The GPU buffers in use: the tree data by slot (`TREE_VEC4S` vec4 per slot), the level lists and\n * their cross-fades (`LEVEL_COUNT` × capacity), the level counters and the draw arguments. The first\n * three are replaced when the Variant grows; the counters and the draw arguments are kept.\n */\n get buffers(): {\n trees: StorageBufferAttribute;\n lists: StorageBufferAttribute;\n dithers: StorageBufferAttribute;\n counters: StorageBufferAttribute;\n args: IndirectStorageBufferAttribute;\n } {\n return { trees: this.treeData, lists: this.lists, dithers: this.dithers, counters: this.counters, args: this.args };\n }\n\n /** The indirect draw arguments, LEVEL_COUNT × MAX_LEVEL_PARTS draws of 5 u32 (for read-back). */\n get drawArguments(): IndirectStorageBufferAttribute {\n return this.args;\n }\n\n /**\n * How many trees each Detail Level drew in the last selection (indexed by DetailLevel; a tree in a\n * cross-fade counts at both levels), read back from the draw arguments on the GPU.\n */\n async drawnCounts(renderer: Renderer): Promise<number[]> {\n const args = new Uint32Array(await renderer.getArrayBufferAsync(this.args));\n return Array.from({ length: LEVEL_COUNT }, (_, level) => args[level * MAX_LEVEL_PARTS * ARGS_STRIDE + 1]!);\n }\n\n /**\n * Gives `level` its meshes (at most MAX_LEVEL_PARTS parts), one per part, each drawn\n * indirectly from the level's list. A part without indices (e.g. the leaves of a bare\n * Definition) gets no mesh: WebGPU would draw it with an index count of 0. Returns the meshes;\n * the caller adds them to the scene.\n */\n setLevel(level: DetailLevel, parts: readonly LevelPart[]): Mesh[] {\n if (parts.length > MAX_LEVEL_PARTS) throw new RangeError(`A Detail Level has at most ${MAX_LEVEL_PARTS} meshes`);\n if (this.levels.some((l) => l.level === level)) throw new Error(`Detail Level ${level} already has its meshes`);\n const array = this.args.array as Uint32Array;\n const drawn = parts.filter((part) => (part.geometry.getIndex()?.count ?? 0) > 0);\n const meshes = drawn.map((part, i) => {\n const draw = (level * MAX_LEVEL_PARTS + i) * ARGS_STRIDE;\n const geometry = new BufferGeometry();\n for (const [name, attribute] of Object.entries(part.geometry.attributes)) geometry.setAttribute(name, attribute);\n geometry.setIndex(part.geometry.getIndex());\n array[draw] = geometry.getIndex()!.count;\n geometry.setIndirect(this.args, draw * 4);\n const mesh = new Mesh(geometry, part.material);\n mesh.name = part.name;\n // The level lists span the whole forest: the compute pass decides what is drawn, not the CPU.\n mesh.frustumCulled = false;\n mesh.castShadow = true;\n mesh.receiveShadow = true;\n // Raycasting stays on the Variant's instanced meshes (one hit per tree, `instanceId` = slot).\n mesh.raycast = () => {};\n this.levelOf.set(mesh, level);\n drawsDetailLevel(mesh, this.instance);\n this.setupMesh(mesh);\n return mesh;\n });\n this.args.needsUpdate = true; // only before the first frame: later uploads would wipe the GPU's counts\n this.levels.push({ level, meshes });\n this.levels.sort((a, b) => a.level - b.level);\n return meshes;\n }\n\n /**\n * Writes one tree: `instance` = its INSTANCE_STRIDE floats of instance data (rotation, state),\n * `position` = its base in forest space.\n */\n write(slot: number, instance: ArrayLike<number>, position: readonly [number, number, number]): void {\n const array = this.treeData.array as Float32Array;\n const o = slot * TREE_VEC4S * 4;\n for (let i = 0; i < INSTANCE_STRIDE; i++) array[o + i] = instance[i]!;\n array[o + 8] = position[0];\n array[o + 9] = position[1];\n array[o + 10] = position[2];\n array[o + 11] = 0;\n this.treeData.needsUpdate = true;\n this.version++;\n }\n\n /** Room for `capacity` trees (the tree data is kept; the lists are refilled every frame). */\n resize(capacity: number): void {\n const treeData = new StorageBufferAttribute(new Float32Array(capacity * TREE_VEC4S * 4), 4);\n (treeData.array as Float32Array).set((this.treeData.array as Float32Array).subarray(0, Math.min(capacity, this.capacityValue) * TREE_VEC4S * 4));\n this.disposeBuffers();\n this.capacityValue = capacity;\n this.treeData = treeData;\n this.lists = new StorageBufferAttribute(new Uint32Array(LEVEL_COUNT * capacity), 1);\n this.dithers = new StorageBufferAttribute(new Float32Array(LEVEL_COUNT * capacity), 1);\n for (const [node, attribute, count] of [\n [this.treeNode, this.treeData, capacity * TREE_VEC4S],\n [this.listNode, this.lists, LEVEL_COUNT * capacity],\n [this.ditherNode, this.dithers, LEVEL_COUNT * capacity],\n ] as const) {\n node.value = attribute;\n node.bufferCount = count;\n }\n for (const node of this.computeNodes) node.dispose();\n this.computeNodes = this.createDispatches();\n this.version++;\n }\n\n /** Frees the meshes' geometry, the buffers and the compute pass (the materials belong to the Variant). */\n dispose(): void {\n for (const mesh of this.meshes) {\n mesh.removeFromParent();\n mesh.geometry.dispose();\n }\n this.levels.length = 0;\n this.disposeBuffers();\n this.counters.dispose();\n this.args.dispose();\n for (const node of this.computeNodes) node.dispose();\n }\n\n private disposeBuffers(): void {\n this.treeData.dispose();\n this.lists.dispose();\n this.dithers.dispose();\n }\n\n /**\n * The compute pass: reset the level counters; sort every tree into its level list (and, in a\n * cross-fade, the next level's too), mirroring `selectDetailLevel`; copy the counts into the draw\n * arguments of every level's meshes.\n */\n private createDispatches(): ComputeNode[] {\n const capacity = this.capacityValue;\n const { light, impostor, fade, camera, forest, farthest } = this.uniforms;\n const counters = storage(this.counters, 'uint', LEVEL_COUNT).toAtomic();\n const trees = storage(this.treeData, 'vec4', capacity * TREE_VEC4S).toReadOnly();\n const lists = storage(this.lists, 'uint', LEVEL_COUNT * capacity);\n const dithers = storage(this.dithers, 'float', LEVEL_COUNT * capacity);\n const args = storage(this.args, 'uint', LEVEL_COUNT * MAX_LEVEL_PARTS * ARGS_STRIDE);\n const count = this.countNode;\n\n const reset = Fn(() => {\n If(instanceIndex.lessThan(LEVEL_COUNT), () => {\n atomicStore(counters.element(instanceIndex), uint(0));\n });\n })().compute(LEVEL_COUNT);\n\n const append = (level: Node<'uint'>, i: Node<'uint'>, dither: Node<'float'>) => {\n const at = atomicAdd(counters.element(level), uint(1)).toVar();\n const entry = level.mul(uint(capacity)).add(at);\n lists.element(entry).assign(i);\n dithers.element(entry).assign(dither);\n };\n\n const select_ = Fn(() => {\n const i = instanceIndex;\n If(i.lessThan(count), () => {\n const state = trees.element(i.mul(TREE_VEC4S).add(1));\n const base = trees.element(i.mul(TREE_VEC4S).add(2)).xyz;\n const world = forest.mul(vec4(base, 1)).xyz;\n // selectDetailLevel, line by line.\n const t = world.distance(camera).div(state.x.max(MIN_LOD_SCALE));\n const half = fade.mul(0.5);\n const toImpostor = select(\n state.y.greaterThanEqual(1),\n ramp(t, impostor.mul(float(1).sub(half)), impostor.mul(float(1).add(half))),\n float(0),\n );\n const toLight = ramp(t, light.mul(float(1).sub(half)), light.mul(float(1).add(half)));\n const level = uint(DetailLevel.Full).toVar();\n const amount = toLight.toVar();\n If(toImpostor.greaterThanEqual(1), () => {\n level.assign(DetailLevel.Impostor);\n amount.assign(0);\n })\n .ElseIf(toImpostor.greaterThan(0), () => {\n level.assign(DetailLevel.Light);\n amount.assign(toImpostor);\n })\n .ElseIf(toLight.greaterThanEqual(1), () => {\n level.assign(DetailLevel.Light);\n amount.assign(0);\n });\n // Nothing beyond the farthest level that can be drawn (no Impostors yet: Light, not faded).\n If(level.greaterThanEqual(farthest), () => {\n level.assign(farthest);\n amount.assign(0);\n });\n const nearer = float(1).sub(amount);\n append(level, i, nearer);\n If(amount.greaterThan(0), () => {\n append(level.add(uint(1)), i, nearer.negate());\n });\n });\n })().compute(capacity);\n\n const draws = LEVEL_COUNT * MAX_LEVEL_PARTS;\n const copyCounts = Fn(() => {\n If(instanceIndex.lessThan(draws), () => {\n const level = instanceIndex.div(uint(MAX_LEVEL_PARTS));\n args.element(instanceIndex.mul(ARGS_STRIDE).add(1)).assign(atomicLoad(counters.element(level)));\n });\n })().compute(draws);\n\n return [reset, select_, copyCounts];\n }\n}\n\n/** Whether a render is a shadow pass (three draws shadow maps with a shadow override material). */\nfunction isShadowPass(scene: Scene | null): boolean {\n return (scene?.overrideMaterial as { isShadowPassMaterial?: boolean } | null | undefined)?.isShadowPassMaterial === true;\n}\n\n/**\n * Picks the level camera (the camera whose distance picks every tree's Detail Level) and runs every\n * Variant's level selection before a Detail Level mesh of the Forest is drawn: once per frame (`renderer.info.frame`), and again in the same frame only when\n * something it depends on changed (trees, settings, the level camera's or the Forest's position). So\n * every render of a frame (shadow passes, other cameras) draws the levels of the frame's level camera.\n */\nexport class LevelSelection {\n private frame: number | null = null;\n /** The level camera of the current frame. */\n private camera: Camera | null = null;\n /** The last non-shadow camera seen drawing the Forest (before the first selection). */\n private seen: Camera | null = null;\n /** What the last selection was made from (see `inputs`). */\n private last: number[] = [];\n private readonly position = new Vector3();\n\n constructor(private readonly uniforms: DetailLevelUniforms) {}\n\n /** Notes the camera of a render that draws the Forest, unless it is a shadow pass. */\n observe(scene: Scene | null, camera: Camera | null): void {\n if (camera && !isShadowPass(scene)) this.seen = camera;\n }\n\n /**\n * Called before a Detail Level mesh is drawn. The first call of a frame fixes the frame's level\n * camera: `explicit` (`lod.camera`) when set, otherwise the camera of this render. A shadow map can\n * be drawn before the camera's own render reaches the Forest: then it is the previous frame's level\n * camera (or, on the first frame, the last camera seen drawing the Forest).\n */\n prepare(renderer: Renderer, scene: Scene | null, camera: Camera | null, explicit: Camera | null, forest: Object3D, variants: readonly VariantLevels[]): void {\n this.observe(scene, camera);\n if (typeof renderer.compute !== 'function') return;\n const frame = (renderer.info as { frame?: number } | undefined)?.frame ?? null;\n if (frame === null || frame !== this.frame) {\n const lodCamera = explicit ?? (isShadowPass(scene) ? (this.camera ?? this.seen ?? camera) : camera);\n if (!lodCamera) return;\n this.frame = frame;\n this.camera = lodCamera;\n this.last = [];\n } else if (explicit) {\n this.camera = explicit;\n }\n const inputs = this.inputs(this.camera!, forest, variants);\n if (inputs.length === this.last.length && inputs.every((v, i) => v === this.last[i])) return;\n this.last = inputs;\n this.uniforms.camera.value.copy(this.position);\n this.uniforms.forest.value.copy(forest.matrixWorld);\n void renderer.compute(variants.flatMap((v) => v.dispatches));\n }\n\n /** Everything the selection reads (leaves the camera's world position in `this.position`). */\n private inputs(camera: Camera, forest: Object3D, variants: readonly VariantLevels[]): number[] {\n camera.updateMatrixWorld();\n camera.getWorldPosition(this.position);\n const { light, impostor, fade, farthest } = this.uniforms;\n return [\n ...this.position.toArray(),\n ...forest.matrixWorld.elements,\n light.value,\n impostor.value,\n fade.value,\n farthest.value,\n ...variants.map((v) => v.version),\n ];\n }\n}\n","// A Forest's Detail Levels (ADR 0010): what a lod Forest adds to a plain one. The settings and their\n// uniforms, the backend found on the first render, the Variants' Detail Level meshes, the Impostor\n// bake and `lodReady`. The Forest owns one when `lod` is set and forwards to it.\nimport { Matrix4, Vector3, type Camera, type Mesh, type Object3D, type Renderer, type Scene } from 'three/webgpu';\nimport { uniform } from 'three/tsl';\nimport type { MaterialFeatureNodes } from '../materials/material-features';\nimport { webgpuRenderer } from '../renderer';\nimport type { ForestVariant } from './Forest';\nimport { LevelSelection, type DetailLevelUniforms } from './levels';\nimport { checkDetailLevelDistances, DetailLevel, type DetailLevelDistances, type ForestLodSettings, type ForestLodUpdate } from './lod';\n\n/** What the Detail Levels need from their Forest. */\nexport interface ForestLodHost {\n /** The Forest: its world matrix places the trees, and the Detail Level meshes are added to it. */\n readonly object: Object3D;\n readonly variants: readonly ForestVariant[];\n /** Resolves once the Definition's textures have loaded (the Impostors are baked with them). */\n readonly texturesReady: Promise<void>;\n /** The Forest's live Material Feature uniforms (the Impostor cards use them too). */\n readonly features: MaterialFeatureNodes | null;\n}\n\n/**\n * The Detail Levels of one Forest. Which backend draws the Forest is only known on its first render\n * (three calls `onBeforeRender` with the renderer then, and not before), so:\n *\n * - On WebGPURenderer's WebGL2 fallback (`detect`): one console warning, `lod` is ignored and `ready`\n * resolves on that first render.\n * - On WebGPU: that first frame still draws every tree in full. Right after it, every Variant gets its\n * Detail Level meshes (they cannot join a frame whose render list is already made), the Impostors are\n * baked once the textures have loaded, and then `ready` resolves.\n */\nexport class ForestLod {\n /** The live values the GPU level selection reads. */\n readonly uniforms: DetailLevelUniforms;\n /** Resolves once the Impostors are baked; on the WebGL2 fallback on the first render; on dispose. */\n readonly ready: Promise<void>;\n private readonly settings: ForestLodSettings;\n private readonly selection: LevelSelection;\n private backend: 'unknown' | 'webgpu' | 'webgl' = 'unknown';\n private resolveReady: () => void = () => {};\n private disposed = false;\n\n constructor(\n settings: ForestLodSettings,\n private readonly host: ForestLodHost,\n ) {\n this.settings = settings;\n this.uniforms = {\n light: uniform(settings.light),\n impostor: uniform(settings.impostor),\n fade: uniform(settings.fade),\n camera: uniform(new Vector3()),\n forest: uniform(new Matrix4()),\n // Until the Impostors are baked, trees beyond the Impostor distance draw Light.\n farthest: uniform(DetailLevel.Light, 'uint'),\n };\n this.selection = new LevelSelection(this.uniforms);\n this.ready = new Promise((resolve) => (this.resolveReady = resolve));\n }\n\n /** The settings (a copy). */\n get values(): ForestLodSettings {\n return { ...this.settings, impostorAtlas: { ...this.settings.impostorAtlas } };\n }\n\n /** Sets distances, fade or camera (the others kept): only uniforms. Throws a RangeError for invalid values, keeping the old ones. */\n update(value: ForestLodUpdate): void {\n const { settings, uniforms } = this;\n const next: DetailLevelDistances = {\n light: value.light ?? settings.light,\n impostor: value.impostor ?? settings.impostor,\n fade: value.fade ?? settings.fade,\n };\n checkDetailLevelDistances(next);\n Object.assign(settings, next);\n if (value.camera !== undefined) settings.camera = value.camera;\n uniforms.light.value = next.light;\n uniforms.impostor.value = next.impostor;\n uniforms.fade.value = next.fade;\n }\n\n /** Whether the Detail Levels are drawn: the first render was on WebGPU (not the WebGL2 fallback). */\n get active(): boolean {\n return this.backend === 'webgpu';\n }\n\n /**\n * Called before each of the Forest's instanced meshes is drawn: notes the camera and, on the first\n * render, finds the backend (see the class).\n */\n detect(renderer: Renderer, scene: Scene | null, camera: Camera | null): void {\n this.selection.observe(scene, camera);\n if (this.backend !== 'unknown') return;\n const backend: object | undefined = renderer.backend;\n if (backend && 'isWebGLBackend' in backend && backend.isWebGLBackend === true) {\n this.backend = 'webgl';\n console.warn(\n 'tree.js: Forest Detail Levels (lod) need WebGPU; on WebGPURenderer\\'s WebGL2 fallback this Forest ignores lod and draws every tree in full.',\n );\n this.resolveReady();\n } else {\n this.backend = 'webgpu';\n queueMicrotask(() => {\n if (this.disposed) return this.resolveReady();\n this.enable();\n void this.bake(renderer);\n });\n }\n }\n\n /**\n * How many trees each Detail Level drew in the last frame (indexed by DetailLevel; a tree in a\n * cross-fade counts at both levels). All zero until the Detail Levels are drawn. Reads the GPU.\n */\n async counts(renderer: Renderer): Promise<number[]> {\n const counts = [0, 0, 0];\n for (const variant of this.host.variants) {\n if (!variant.levels) continue;\n const drawn = await variant.levels.drawnCounts(renderer);\n drawn.forEach((count, level) => (counts[level]! += count));\n }\n return counts;\n }\n\n /** Stops what is pending (the Detail Level meshes, the bake) and resolves `ready`: nothing is left to wait for. */\n dispose(): void {\n this.disposed = true;\n this.resolveReady();\n }\n\n /** Builds every Variant's Detail Level meshes and buffers. */\n private enable(): void {\n const setupMesh = (mesh: Mesh) => {\n mesh.onBeforeRender = (renderer, scene, camera) => this.select(webgpuRenderer(renderer), scene, camera);\n };\n for (const variant of this.host.variants) variant.enableDetailLevels(this.uniforms, this.settings, setupMesh, this.host.features);\n }\n\n /**\n * Bakes every Variant's Impostor with the app's renderer (after the textures have loaded), then lets\n * far trees draw as Impostors and resolves `ready`. Until then they draw Light. If the bake fails,\n * they keep drawing Light (one console error) and `ready` still resolves.\n */\n private async bake(renderer: Renderer): Promise<void> {\n try {\n await this.host.texturesReady.catch(() => {}); // a texture that failed to load bakes as without it\n if (this.disposed) return;\n for (const variant of this.host.variants) variant.impostor!.bake(renderer);\n this.uniforms.farthest.value = DetailLevel.Impostor;\n } catch (error) {\n console.error('tree.js: baking the Forest Impostors failed; far trees draw Light.', error);\n } finally {\n this.resolveReady();\n }\n }\n\n /**\n * Before a Detail Level mesh is drawn: the first time in a frame, picks every tree's level for the\n * camera that picks the levels, on the GPU (shadow passes and other cameras reuse that frame's levels).\n */\n private select(renderer: Renderer, scene: Scene | null, camera: Camera | null): void {\n const levels = this.host.variants.map((v) => v.levels!);\n this.selection.prepare(renderer, scene, camera, this.settings.camera, this.host.object, levels);\n }\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 InstancedBufferAttribute,\n InstancedInterleavedBuffer,\n InstancedMesh,\n InterleavedBuffer,\n InterleavedBufferAttribute,\n Matrix4,\n Quaternion,\n Vector3,\n type Camera,\n type Mesh,\n type MeshStandardNodeMaterial,\n type Node,\n type Renderer,\n type Scene,\n} from 'three/webgpu';\nimport { and, positionGeometry, varying } from 'three/tsl';\nimport type { MaterialFeatures, TranslucencyDefinition, TreeDefinition } from '../definition';\nimport { generateLightTree, generateTree, trunkHeight, type GeometryBuffers, type TreeData } from '../generator';\nimport { createBarkMaterial, createFruitMaterial, createLeafMaterial } from '../materials';\nimport { LiveMaterialFeatures, type MaterialFeatureNodes, type MaterialFeatureTarget } from '../materials/material-features';\nimport { LiveShaderHooks, partHookTarget, ShaderHookedGroup, type ShaderHookTarget, type TreeShaderHooks } from '../materials/shader-hooks';\nimport { webgpuRenderer } 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 { impostorBounds, VariantImpostor } from './impostor';\nimport { impostorHookTarget } from './impostor-material';\nimport { ForestLod } from './forest-lod';\nimport { VariantLevels, type DetailLevelUniforms, type LevelPart } from './levels';\nimport { DetailLevel, resolveForestLod, type ForestLodOptions, type ForestLodSettings, type ForestLodUpdate } from './lod';\nimport { INSTANCE_ATTRIBUTES, INSTANCE_STRIDE, forestPosition, instanceRotate, instanceState, instanceTreeBase, levelVisible } 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 * Detail Levels (ADR 0010): draw far trees Light and as Impostors, with a cross-fade. `true` derives\n * the switch distances from the tallest Variant's trunk height. Missing or false: the forest draws\n * every tree in full, exactly as without this option. WebGPU only: on WebGPURenderer's WebGL2\n * fallback it is ignored (one console warning). Switching it on or off needs a new Forest.\n */\n lod?: boolean | ForestLodOptions;\n /** The Tree Shader Hook per tree part (see {@link Forest.shaderHooks}). Default: none. */\n shaderHooks?: TreeShaderHooks;\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 /** @internal The Variant drawing this tree, null once it is removed. */\n owner: ForestVariant | null = null;\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 private readonly definition: TreeDefinition;\n /** @internal The Detail Levels this Variant draws its trees with; null until they are drawn (lod set, on WebGPU). */\n levels: VariantLevels | null = null;\n /** Vertex data of the Light level (null until Detail Levels are drawn). */\n private lightSources: BufferGeometry[] = [];\n /** @internal The Impostor of this Variant (atlases and card material); null until Detail Levels are drawn. */\n impostor: VariantImpostor | null = null;\n\n constructor(\n private readonly forest: Forest,\n definition: TreeDefinition,\n index: number,\n seed: number,\n private readonly wind: WindSource,\n capacity: number,\n private readonly textures?: TextureOptions,\n ) {\n this.index = index;\n this.seed = seed;\n this.definition = definition;\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 /**\n * @internal What Tree Shader Hooks shade on this Variant: its bark, leaf and Fruit materials (which draw\n * every Detail Level but Impostor), with each tree's own Season, Growth and position.\n */\n hookTargets(): ShaderHookTarget[] {\n const { season, growth } = instanceState();\n const inputs = () => ({ season: varying(season) as Node<'float'>, growth: varying(growth) as Node<'float'>, treeBase: instanceTreeBase() });\n const targets = [partHookTarget('bark', this.barkMaterial, this.woodSource, inputs()), partHookTarget('leaves', this.leafMaterial, this.leafSource, inputs())];\n if (this.fruitMaterial && this.fruitSource) targets.push(partHookTarget('fruit', this.fruitMaterial, this.fruitSource, inputs()));\n return targets;\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 tree.owner = this;\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 tree.owner = null;\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 this.levels?.write(i, array.subarray(i * INSTANCE_STRIDE, (i + 1) * INSTANCE_STRIDE), [position.x, position.y, position.z]);\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 /**\n * @internal Starts drawing this Variant's trees by Detail Level (ADR 0010): a Full and a Light mesh\n * set, drawn indirectly from the level lists, with the Variant's own materials (which get the\n * cross-fade dither). The instanced meshes stay, hidden, for raycasting and Tree IDs.\n */\n enableDetailLevels(\n uniforms: DetailLevelUniforms,\n settings: Pick<ForestLodSettings, 'lightDefinition' | 'impostorAtlas'>,\n setupMesh: (mesh: Mesh) => void,\n features: MaterialFeatureNodes | null = null,\n ): void {\n if (this.levels) return;\n const levels = new VariantLevels(this.capacity, uniforms, setupMesh);\n const parts = (level: string, wood: BufferGeometry, leaves: BufferGeometry, fruit: BufferGeometry | null): LevelPart[] => {\n const list: LevelPart[] = [\n { name: `forest wood ${this.index} ${level}`, geometry: wood, material: this.barkMaterial },\n { name: `forest leaves ${this.index} ${level}`, geometry: leaves, material: this.leafMaterial },\n ];\n if (fruit && this.fruitMaterial) {\n list.push({ name: `forest fruit ${this.index} ${level}`, geometry: fruit, material: this.fruitMaterial });\n }\n return list;\n };\n levels.setLevel(DetailLevel.Full, parts('full', this.woodSource, this.leafSource, this.fruitSource));\n\n const light = generateLightTree(this.definition, this.seed, settings.lightDefinition ?? undefined);\n const margin = trunkHeight(this.data.skeleton) * WIND_BOUNDS;\n this.lightSources = [light.wood, light.leaves, light.fruit].map((buffers) => interleavedGeometry(buffers, margin));\n const [wood, leaves, fruit] = this.lightSources as [BufferGeometry, BufferGeometry, BufferGeometry];\n levels.setLevel(DetailLevel.Light, parts('light', wood, leaves, this.fruitSource ? fruit : null));\n\n // The Impostor card is set up now (its draw arguments too), but only drawn once baked (`farthest`).\n this.impostor = new VariantImpostor({\n definition: this.definition,\n sources: { wood: this.woodSource, leaves: this.leafSource },\n bounds: impostorBounds([this.data.wood, this.data.leaves]),\n atlas: settings.impostorAtlas,\n name: `forest impostor ${this.index}`,\n textures: this.textures,\n features: features ? { nodes: features, crown: this.data.crown } : null,\n wind: { source: this.wind, response: this.windResponse },\n });\n levels.setLevel(DetailLevel.Impostor, [this.impostor.part]);\n this.forest.addShaderHookTargets([impostorHookTarget(this.impostor.part.material as MeshStandardNodeMaterial)]);\n\n // Every level draws only its share of a tree in a cross-fade.\n for (const material of [this.barkMaterial, this.leafMaterial, this.fruitMaterial]) {\n if (!material) continue;\n material.maskNode = material.maskNode ? and(material.maskNode as Node<'bool'>, levelVisible()) : levelVisible();\n material.needsUpdate = true;\n }\n this.levels = levels;\n for (const tree of this.trees) this.write(tree);\n levels.count = this.trees.length;\n for (const mesh of this.meshes) mesh.visible = false;\n this.forest.add(...levels.meshes);\n }\n\n /** @internal Frees the GPU resources. */\n dispose(): void {\n // Detail Levels: the level meshes' geometry, the GPU buffers and compute pass, then the Light vertex data.\n this.levels?.dispose();\n this.levels = null;\n this.impostor?.dispose();\n this.impostor = null;\n for (const source of this.lightSources) source.dispose();\n this.lightSources = [];\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 if (this.levels) this.levels.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 this.levels?.resize(capacity);\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 // Drawn by the Detail Level meshes instead once those are on (kept for raycasting and Tree IDs).\n instanced.visible = this.levels === null;\n instanced.onBeforeRender = (renderer, scene, camera) => this.forest.detectLodBackend(webgpuRenderer(renderer), scene, camera);\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 ShaderHookedGroup {\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 protected readonly hooks: LiveShaderHooks;\n /** The trunk height of the tallest Variant (the distances of `lod: true`). */\n private readonly tallestTrunk: number;\n /** The Detail Levels; null without lod. */\n private readonly detailLevels: ForestLod | null;\n /**\n * Resolves once every Impostor is baked (far trees draw Light until then); at once without lod; and\n * on dispose. The backend is only known on the first render (three hands the renderer to the\n * Forest's meshes then, not before), so on WebGPURenderer's WebGL2 fallback, where lod is ignored,\n * it resolves on that first render, not at once.\n */\n readonly lodReady: Promise<void>;\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 this.hooks = new LiveShaderHooks(\n this.variants.flatMap((v) => v.hookTargets()),\n definition.materials.shading,\n options.shaderHooks,\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\n this.tallestTrunk = Math.max(...this.variants.map((v) => trunkHeight(v.data.skeleton)));\n const lod = this.resolveLod(options.lod);\n this.detailLevels = lod\n ? new ForestLod(lod, { object: this, variants: this.variants, texturesReady: this.ready, features: this.features.nodes })\n : null;\n this.lodReady = this.detailLevels?.ready ?? Promise.resolve();\n\n for (const placement of placements) this.addTree(placement);\n }\n\n /**\n * The Detail Level settings (a copy), null without lod. Setting `light`, `impostor`, `fade` or\n * `camera` (the others kept) only writes uniforms: no rebuild, no recompile. Throws a RangeError for\n * invalid values (keeping the old ones), and on a forest without lod (switching it on needs a new Forest).\n */\n get lod(): ForestLodSettings | null {\n return this.detailLevels?.values ?? null;\n }\n\n set lod(value: ForestLodUpdate) {\n if (!this.detailLevels) throw new Error('This Forest has no Detail Levels: pass `lod` to createForest (switching them on needs a new Forest)');\n this.detailLevels.update(value);\n }\n\n /**\n * @internal The settings `lod` gives this Forest, every default filled in (`lod: true`: the distances\n * from its tallest Variant's trunk height), or null when it is missing or false. Throws a RangeError\n * for invalid settings.\n */\n resolveLod(lod: boolean | ForestLodOptions | undefined): ForestLodSettings | null {\n return resolveForestLod(lod, this.tallestTrunk);\n }\n\n /** @internal The live Detail Level settings as uniforms (null without lod), for the GPU level selection. */\n get lodUniforms(): DetailLevelUniforms | null {\n return this.detailLevels?.uniforms ?? null;\n }\n\n /** @internal Whether Detail Levels are drawn: lod is set and the first render was on WebGPU (not the WebGL2 fallback). */\n get lodActive(): boolean {\n return this.detailLevels?.active ?? false;\n }\n\n /**\n * @internal Called before each instanced mesh is drawn: on the first render of a lod Forest, finds the\n * backend (see `ForestLod`). Does nothing without lod.\n */\n detectLodBackend(renderer: Renderer, scene: Scene | null = null, camera: Camera | null = null): void {\n this.detailLevels?.detect(renderer, scene, camera);\n }\n\n /**\n * @internal How many trees each Detail Level drew in the last frame (indexed by DetailLevel; a tree\n * in a cross-fade counts at both levels). All zero until Detail Levels are drawn. Reads the GPU.\n */\n async detailLevelCounts(renderer: Renderer): Promise<number[]> {\n return this.detailLevels ? this.detailLevels.counts(renderer) : [0, 0, 0];\n }\n\n /**\n * The Wind every tree of this forest sways with. Assigning another Wind only rebinds uniforms:\n * no rebuild, no recompile (except the one-time node-graph rebuild when the Forest first follows a\n * Wind that has had a Wind Burst, see `Wind.burst`).\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 /** @internal Materials made later (the Impostor cards) that the hooks shade too. */\n addShaderHookTargets(targets: readonly ShaderHookTarget[]): void {\n this.hooks.addTargets(targets);\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 this.hooks.dispose();\n this.detailLevels?.dispose(); // nothing left to wait for\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';\nexport {\n DetailLevel,\n selectDetailLevel,\n type DetailLevelSelection,\n type ForestLodOptions,\n type ForestLodSettings,\n type ForestLodUpdate,\n type ImpostorAtlasOptions,\n} from './lod';\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(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