@casmo/tree.js 0.0.0-stage → 0.1.1

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 (153) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +485 -2
  3. package/dist/bake/index.d.ts +39 -0
  4. package/dist/bake/index.d.ts.map +1 -0
  5. package/dist/definition/defaults.d.ts +9 -0
  6. package/dist/definition/defaults.d.ts.map +1 -0
  7. package/dist/definition/index.d.ts +5 -0
  8. package/dist/definition/index.d.ts.map +1 -0
  9. package/dist/definition/migrations.d.ts +12 -0
  10. package/dist/definition/migrations.d.ts.map +1 -0
  11. package/dist/definition/parse.d.ts +30 -0
  12. package/dist/definition/parse.d.ts.map +1 -0
  13. package/dist/definition/schema.d.ts +13 -0
  14. package/dist/definition/schema.d.ts.map +1 -0
  15. package/dist/definition/types.d.ts +217 -0
  16. package/dist/definition/types.d.ts.map +1 -0
  17. package/dist/effects/effects.d.ts +46 -0
  18. package/dist/effects/effects.d.ts.map +1 -0
  19. package/dist/effects/glow.d.ts +19 -0
  20. package/dist/effects/glow.d.ts.map +1 -0
  21. package/dist/effects/grade.d.ts +19 -0
  22. package/dist/effects/grade.d.ts.map +1 -0
  23. package/dist/effects/index.d.ts +7 -0
  24. package/dist/effects/index.d.ts.map +1 -0
  25. package/dist/effects/mask.d.ts +44 -0
  26. package/dist/effects/mask.d.ts.map +1 -0
  27. package/dist/effects/outline.d.ts +18 -0
  28. package/dist/effects/outline.d.ts.map +1 -0
  29. package/dist/effects/suggested.d.ts +13 -0
  30. package/dist/effects/suggested.d.ts.map +1 -0
  31. package/dist/effects.js +249 -0
  32. package/dist/effects.js.map +1 -0
  33. package/dist/forest/Forest.d.ts +156 -0
  34. package/dist/forest/Forest.d.ts.map +1 -0
  35. package/dist/forest/index.d.ts +14 -0
  36. package/dist/forest/index.d.ts.map +1 -0
  37. package/dist/forest/nodes.d.ts +31 -0
  38. package/dist/forest/nodes.d.ts.map +1 -0
  39. package/dist/forest/placement.d.ts +52 -0
  40. package/dist/forest/placement.d.ts.map +1 -0
  41. package/dist/forest-OX9WvAwh.js +3057 -0
  42. package/dist/forest-OX9WvAwh.js.map +1 -0
  43. package/dist/generator/attributes.d.ts +20 -0
  44. package/dist/generator/attributes.d.ts.map +1 -0
  45. package/dist/generator/branches.d.ts +12 -0
  46. package/dist/generator/branches.d.ts.map +1 -0
  47. package/dist/generator/frames.d.ts +21 -0
  48. package/dist/generator/frames.d.ts.map +1 -0
  49. package/dist/generator/growth.d.ts +15 -0
  50. package/dist/generator/growth.d.ts.map +1 -0
  51. package/dist/generator/index.d.ts +22 -0
  52. package/dist/generator/index.d.ts.map +1 -0
  53. package/dist/generator/leaf-shapes.d.ts +10 -0
  54. package/dist/generator/leaf-shapes.d.ts.map +1 -0
  55. package/dist/generator/leaves.d.ts +14 -0
  56. package/dist/generator/leaves.d.ts.map +1 -0
  57. package/dist/generator/mesh.d.ts +11 -0
  58. package/dist/generator/mesh.d.ts.map +1 -0
  59. package/dist/generator/sculpt.d.ts +28 -0
  60. package/dist/generator/sculpt.d.ts.map +1 -0
  61. package/dist/generator/trunk.d.ts +6 -0
  62. package/dist/generator/trunk.d.ts.map +1 -0
  63. package/dist/generator/types.d.ts +126 -0
  64. package/dist/generator/types.d.ts.map +1 -0
  65. package/dist/generator/vec.d.ts +12 -0
  66. package/dist/generator/vec.d.ts.map +1 -0
  67. package/dist/generator/wind.d.ts +27 -0
  68. package/dist/generator/wind.d.ts.map +1 -0
  69. package/dist/growth/evaluate.d.ts +32 -0
  70. package/dist/growth/evaluate.d.ts.map +1 -0
  71. package/dist/growth/index.d.ts +3 -0
  72. package/dist/growth/index.d.ts.map +1 -0
  73. package/dist/growth/tsl.d.ts +12 -0
  74. package/dist/growth/tsl.d.ts.map +1 -0
  75. package/dist/index.d.ts +14 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +198 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/materials/index.d.ts +18 -0
  80. package/dist/materials/index.d.ts.map +1 -0
  81. package/dist/materials/maps.d.ts +23 -0
  82. package/dist/materials/maps.d.ts.map +1 -0
  83. package/dist/materials/shading.d.ts +18 -0
  84. package/dist/materials/shading.d.ts.map +1 -0
  85. package/dist/materials/toon.d.ts +12 -0
  86. package/dist/materials/toon.d.ts.map +1 -0
  87. package/dist/math/index.d.ts +23 -0
  88. package/dist/math/index.d.ts.map +1 -0
  89. package/dist/profiles-BAiyeFlh.js +113 -0
  90. package/dist/profiles-BAiyeFlh.js.map +1 -0
  91. package/dist/random/index.d.ts +37 -0
  92. package/dist/random/index.d.ts.map +1 -0
  93. package/dist/react/Forest.d.ts +54 -0
  94. package/dist/react/Forest.d.ts.map +1 -0
  95. package/dist/react/Tree.d.ts +41 -0
  96. package/dist/react/Tree.d.ts.map +1 -0
  97. package/dist/react/Wind.d.ts +17 -0
  98. package/dist/react/Wind.d.ts.map +1 -0
  99. package/dist/react/index.d.ts +6 -0
  100. package/dist/react/index.d.ts.map +1 -0
  101. package/dist/react/useTreeStyle.d.ts +15 -0
  102. package/dist/react/useTreeStyle.d.ts.map +1 -0
  103. package/dist/react.js +239 -0
  104. package/dist/react.js.map +1 -0
  105. package/dist/renderer/index.d.ts +7 -0
  106. package/dist/renderer/index.d.ts.map +1 -0
  107. package/dist/season/check.d.ts +3 -0
  108. package/dist/season/check.d.ts.map +1 -0
  109. package/dist/season/index.d.ts +4 -0
  110. package/dist/season/index.d.ts.map +1 -0
  111. package/dist/season/nodes.d.ts +32 -0
  112. package/dist/season/nodes.d.ts.map +1 -0
  113. package/dist/season/profile.d.ts +78 -0
  114. package/dist/season/profile.d.ts.map +1 -0
  115. package/dist/season/profiles.d.ts +40 -0
  116. package/dist/season/profiles.d.ts.map +1 -0
  117. package/dist/styles/low-poly/index.d.ts +16 -0
  118. package/dist/styles/low-poly/index.d.ts.map +1 -0
  119. package/dist/styles/low-poly.js +165 -0
  120. package/dist/styles/low-poly.js.map +1 -0
  121. package/dist/styles/realistic/index.d.ts +23 -0
  122. package/dist/styles/realistic/index.d.ts.map +1 -0
  123. package/dist/styles/realistic.js +206 -0
  124. package/dist/styles/realistic.js.map +1 -0
  125. package/dist/styles/registry.d.ts +17 -0
  126. package/dist/styles/registry.d.ts.map +1 -0
  127. package/dist/styles/stylized/index.d.ts +17 -0
  128. package/dist/styles/stylized/index.d.ts.map +1 -0
  129. package/dist/styles/stylized.js +266 -0
  130. package/dist/styles/stylized.js.map +1 -0
  131. package/dist/styles/types.d.ts +12 -0
  132. package/dist/styles/types.d.ts.map +1 -0
  133. package/dist/textures/index.d.ts +44 -0
  134. package/dist/textures/index.d.ts.map +1 -0
  135. package/dist/textures/realistic/bark-normal.png +0 -0
  136. package/dist/textures/realistic/bark.png +0 -0
  137. package/dist/textures/realistic/leaf.png +0 -0
  138. package/dist/textures/realistic/needles.png +0 -0
  139. package/dist/tree/Tree.d.ts +70 -0
  140. package/dist/tree/Tree.d.ts.map +1 -0
  141. package/dist/tree/index.d.ts +14 -0
  142. package/dist/tree/index.d.ts.map +1 -0
  143. package/dist/types-BZjHhNz7.js +20 -0
  144. package/dist/types-BZjHhNz7.js.map +1 -0
  145. package/dist/wind/Wind.d.ts +54 -0
  146. package/dist/wind/Wind.d.ts.map +1 -0
  147. package/dist/wind/index.d.ts +4 -0
  148. package/dist/wind/index.d.ts.map +1 -0
  149. package/dist/wind/node.d.ts +38 -0
  150. package/dist/wind/node.d.ts.map +1 -0
  151. package/dist/wind/response.d.ts +27 -0
  152. package/dist/wind/response.d.ts.map +1 -0
  153. package/package.json +107 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"forest-OX9WvAwh.js","names":["vec3","sin","dot","cross","dot","cross","DEG","sin","sin","cross","dot","sin","cross","dot","sin","sin","treeScale","thickness","partProgress"],"sources":["../src/definition/defaults.ts","../src/definition/migrations.ts","../src/definition/schema.ts","../src/definition/parse.ts","../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/growth.ts","../src/generator/wind.ts","../src/generator/attributes.ts","../src/generator/leaf-shapes.ts","../src/generator/leaves.ts","../src/generator/mesh.ts","../src/generator/sculpt.ts","../src/generator/trunk.ts","../src/generator/index.ts","../src/growth/evaluate.ts","../src/growth/tsl.ts","../src/textures/index.ts","../src/materials/maps.ts","../src/materials/toon.ts","../src/materials/shading.ts","../src/materials/index.ts","../src/renderer/index.ts","../src/season/nodes.ts","../src/season/check.ts","../src/wind/Wind.ts","../src/wind/response.ts","../src/wind/node.ts","../src/tree/Tree.ts","../src/tree/index.ts","../src/styles/registry.ts","../src/forest/nodes.ts","../src/forest/placement.ts","../src/forest/Forest.ts","../src/forest/index.ts"],"sourcesContent":["import { CURRENT_SCHEMA_VERSION, type BranchLevelDefinition, type TreeDefinition } from './types';\n\n/** Defaults for one branching level; fills fields missing from a partial `branches[i]`. */\nexport const DEFAULT_BRANCH_LEVEL: BranchLevelDefinition = {\n count: 6,\n start: 0.35,\n end: 0.95,\n angle: 45,\n angleVariation: 0.2,\n spiral: 137.5,\n length: 0.5,\n lengthVariation: 0.2,\n radius: 0.6,\n taper: 0.3,\n sides: 6,\n sections: 5,\n bend: 0.1,\n gravity: 0.1,\n};\n\n/**\n * The documented defaults: a small broadleaf tree with two branching levels.\n * Anything a Definition leaves out is taken from here.\n */\nexport const DEFAULT_DEFINITION: TreeDefinition = {\n schemaVersion: CURRENT_SCHEMA_VERSION,\n name: '',\n form: 'broadleaf',\n trunk: {\n length: 4,\n radius: 0.25,\n taper: 0.4,\n sides: 8,\n sections: 8,\n lengthVariation: 0.15,\n bend: 0.08,\n },\n branches: [\n { ...DEFAULT_BRANCH_LEVEL },\n { ...DEFAULT_BRANCH_LEVEL, count: 4, start: 0.2, angle: 40, length: 0.45, sides: 4, sections: 3 },\n ],\n leaves: {\n count: 8,\n shape: 'card',\n size: 0.25,\n sizeVariation: 0.2,\n start: 0.3,\n angle: 40,\n },\n materials: {\n shading: 'standard',\n bark: { color: '#6b4a2b', roughness: 0.9, map: null, normalMap: null },\n leaf: { roughness: 0.7, map: null, alphaTest: 0.5 },\n },\n season: {\n // Deciduous: fresh green in spring, deep green in summer, autumn colours, bare in winter.\n leafColor: [\n { t: 0, value: '#8bc34a' },\n { t: 0.25, value: '#3e7d2b' },\n { t: 0.5, value: '#3e7d2b' },\n { t: 0.62, value: '#d8892b' },\n { t: 0.72, value: '#a0401f' },\n ],\n leafCoverage: [\n { t: 0, value: 0.3 },\n { t: 0.1, value: 1 },\n { t: 0.62, value: 1 },\n { t: 0.75, value: 0 },\n { t: 0.97, value: 0 },\n { t: 1, value: 0.3 },\n ],\n blossom: [{ t: 0, value: 0 }],\n blossomColor: '#f7c6d9',\n },\n wind: { trunk: 0.2, branches: 0.5, leaves: 0.8, frequency: 1 },\n variation: { color: 0.1, growth: 0.1, season: 0.05 },\n sculpts: [],\n};\n","/**\n * Schema migrations. `MIGRATIONS[n]` turns a raw (unvalidated) schemaVersion `n` object into\n * a raw schemaVersion `n + 1` object. Migrations run in order before defaults and validation,\n * so they only need to move/rename what changed; missing fields are defaulted afterwards.\n *\n * To change the format: bump CURRENT_SCHEMA_VERSION, add `MIGRATIONS[old]`, and add a\n * fixture in test/fixtures/definition-v<old>.json with a test.\n */\ntype Raw = Record<string, unknown>;\n\nexport const MIGRATIONS: Record<number, (input: Raw) => Raw> = {\n /**\n * v1 -> v2: `bark` moved into `materials.bark`; branches, leaves, Season Profile, Wind,\n * variation and sculpts were added. A v1 tree was a bare trunk, so it keeps no branches\n * and no leaves (same tree as before).\n */\n 1: (input) => {\n const { bark, ...rest } = input;\n return {\n ...rest,\n schemaVersion: 2,\n branches: [],\n leaves: { count: 0 },\n ...(bark === undefined ? {} : { materials: { bark } }),\n };\n },\n};\n","import { DEFAULT_BRANCH_LEVEL, DEFAULT_DEFINITION } from './defaults';\nimport {\n CURRENT_SCHEMA_VERSION,\n MAX_BRANCH_LEVELS,\n type BranchLevelDefinition,\n type DeleteSculpt,\n type Keyframe,\n type LeavesSculpt,\n type MoveSculpt,\n type Sculpt,\n type TreeDefinition,\n} from './types';\n\n/** Thrown for an invalid Tree Definition; `field` is the path of the bad field, e.g. `branches[1].angle`. */\nexport class TreeDefinitionError extends Error {\n readonly field: string;\n constructor(field: string, message: string) {\n super(`Invalid Tree Definition: ${field} ${message}`);\n this.name = 'TreeDefinitionError';\n this.field = field;\n }\n}\n\n/**\n * A schema node: validates `value` at `path`, filling it from `fallback` (the default)\n * when it is undefined, and returns a fresh, complete value. Throws TreeDefinitionError.\n */\ntype Schema<T> = (value: unknown, fallback: T | undefined, path: string) => T;\n\nconst ROOT = '(root)';\nconst join = (path: string, key: string) => (path === ROOT ? key : `${path}.${key}`);\nconst show = (v: unknown) => (v === undefined ? 'undefined' : JSON.stringify(v));\n\nexport function isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\n/** Leaf schema from a predicate; `undefined` takes the fallback, or is reported missing. */\nfunction leaf<T>(expected: string, ok: (v: unknown) => boolean): Schema<T> {\n return (value, fallback, path) => {\n const v = value === undefined ? fallback : value;\n if (v === undefined) throw new TreeDefinitionError(path, 'is missing');\n if (!ok(v)) throw new TreeDefinitionError(path, `must be ${expected}, got ${show(v)}`);\n return (Array.isArray(v) ? [...v] : v) as T;\n };\n}\n\nconst isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);\nconst range = (min: number, max: number) => leaf<number>(`a number from ${min} to ${max}`, (v) => isNum(v) && v >= min && v <= max);\nconst unit = range(0, 1);\nconst positive = leaf<number>('a number > 0', (v) => isNum(v) && v > 0);\nconst finite = leaf<number>('a finite number', isNum);\nconst intAtLeast = (min: number) => leaf<number>(`an integer >= ${min}`, (v) => Number.isInteger(v) && (v as number) >= min);\nconst hexColor = leaf<string>('a colour like \"#6b4a2b\"', (v) => typeof v === 'string' && /^#[0-9a-f]{6}$/i.test(v));\nconst text = leaf<string>('a string', (v) => typeof v === 'string');\nconst url = leaf<string | null>('a URL string or null', (v) => v === null || (typeof v === 'string' && v.length > 0));\nconst vec3 = leaf<[number, number, number]>('[x, y, z] numbers', (v) => Array.isArray(v) && v.length === 3 && v.every(isNum));\nconst oneOf = <T extends string>(...values: T[]) =>\n leaf<T>(`one of ${values.map((x) => `\"${x}\"`).join(', ')}`, (v) => values.includes(v as T));\nconst literal = <T>(expected: T) => leaf<T>(String(expected), (v) => v === expected);\n\n/** Object with exactly these fields; unknown fields are rejected (catches typos). */\nfunction obj<T>(fields: { [K in keyof T]-?: Schema<T[K]> }): Schema<T> {\n return (value, fallback, path) => {\n if (value === undefined && fallback === undefined) throw new TreeDefinitionError(path, 'is missing');\n const given = value === undefined ? {} : value;\n if (!isObject(given)) throw new TreeDefinitionError(path, `must be an object, got ${show(given)}`);\n for (const key of Object.keys(given)) {\n if (!(key in fields)) throw new TreeDefinitionError(join(path, key), 'is not a known field');\n }\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(fields) as (keyof T & string)[]) {\n out[key] = fields[key](given[key], fallback?.[key], join(path, key));\n }\n return out as T;\n };\n}\n\n/** Array; a missing array takes the fallback array, each item is filled from `itemFallback`. */\nfunction arr<T>(item: Schema<T>, opts: { min?: number; max?: number; itemFallback?: T } = {}): Schema<T[]> {\n const { min = 0, max = Infinity, itemFallback } = opts;\n return (value, fallback, path) => {\n const v = value === undefined ? fallback : value;\n if (v === undefined) throw new TreeDefinitionError(path, 'is missing');\n if (!Array.isArray(v)) throw new TreeDefinitionError(path, `must be an array, got ${show(v)}`);\n if (v.length < min) throw new TreeDefinitionError(path, `must have at least ${min} entries`);\n if (v.length > max) throw new TreeDefinitionError(path, `must have at most ${max} entries`);\n return v.map((x, i) => item(x, itemFallback, `${path}[${i}]`));\n };\n}\n\n/** Adds a cross-field check; `check` returns [field, problem] or null. */\nfunction refine<T>(schema: Schema<T>, check: (v: T) => [string, string] | null): Schema<T> {\n return (value, fallback, path) => {\n const v = schema(value, fallback, path);\n const problem = check(v);\n if (problem) throw new TreeDefinitionError(join(path, problem[0]), problem[1]);\n return v;\n };\n}\n\n/** Union discriminated by `key`. */\nfunction tagged<T>(key: string, variants: Record<string, Schema<T>>): Schema<T> {\n const names = Object.keys(variants);\n return (value, fallback, path) => {\n if (!isObject(value)) throw new TreeDefinitionError(path, `must be an object, got ${show(value)}`);\n const variant = variants[value[key] as string];\n if (!variant) {\n throw new TreeDefinitionError(join(path, key), `must be one of ${names.map((n) => `\"${n}\"`).join(', ')}, got ${show(value[key])}`);\n }\n return variant(value, fallback, path);\n };\n}\n\n/** Keyframe track: at least one key, `t` in 0..1 and non-decreasing. */\nfunction track<V>(value: Schema<V>): Schema<Keyframe<V>[]> {\n const keys = arr(obj<Keyframe<V>>({ t: unit, value }), { min: 1 });\n return (v, fallback, path) => {\n const out = keys(v, fallback, path);\n for (let i = 1; i < out.length; i++) {\n if (out[i]!.t < out[i - 1]!.t) {\n throw new TreeDefinitionError(`${path}[${i}].t`, `must be >= the previous keyframe's t (${out[i - 1]!.t}), got ${out[i]!.t}`);\n }\n }\n return out;\n };\n}\n\nconst branchLevel = refine(\n obj<BranchLevelDefinition>({\n count: intAtLeast(0),\n start: unit,\n end: unit,\n angle: range(0, 180),\n angleVariation: unit,\n spiral: range(0, 360),\n length: positive,\n lengthVariation: unit,\n radius: unit,\n taper: unit,\n sides: intAtLeast(3),\n sections: intAtLeast(1),\n bend: unit,\n gravity: range(-1, 1),\n }),\n (b) => (b.end < b.start ? ['end', `must be >= start (${b.start}), got ${b.end}`] : null),\n);\n\nconst branchPath = leaf<string>('a branch path like \"0\" or \"0.3.1\"', (v) => typeof v === 'string' && /^0(\\.\\d+)*$/.test(v));\nconst sculpt = tagged<Sculpt>('action', {\n delete: obj<DeleteSculpt>({ action: literal('delete'), seed: finite, path: branchPath }) as Schema<Sculpt>,\n move: obj<MoveSculpt>({ action: literal('move'), seed: finite, path: branchPath, rotation: vec3, scale: positive }) as Schema<Sculpt>,\n leaves: obj<LeavesSculpt>({ action: literal('leaves'), seed: finite, path: branchPath, coverage: unit }) as Schema<Sculpt>,\n});\n\n/** The whole Tree Definition schema (current version). Mirrors the interfaces in types.ts. */\nconst treeDefinition = obj<TreeDefinition>({\n schemaVersion: literal(CURRENT_SCHEMA_VERSION),\n name: text,\n form: oneOf('broadleaf', 'conifer'),\n trunk: obj({\n length: positive,\n radius: positive,\n taper: unit,\n sides: intAtLeast(3),\n sections: intAtLeast(1),\n lengthVariation: unit,\n bend: unit,\n }),\n branches: arr(branchLevel, { max: MAX_BRANCH_LEVELS, itemFallback: DEFAULT_BRANCH_LEVEL }),\n leaves: obj({\n count: intAtLeast(0),\n shape: oneOf('card', 'clump', 'needle', 'puff'),\n size: positive,\n sizeVariation: unit,\n start: unit,\n angle: range(0, 180),\n }),\n materials: obj({\n shading: oneOf('standard', 'flat', 'toon'),\n bark: obj({ color: hexColor, roughness: unit, map: url, normalMap: url }),\n leaf: obj({ roughness: unit, map: url, alphaTest: unit }),\n }),\n season: obj({\n leafColor: track(hexColor),\n leafCoverage: track(unit),\n blossom: track(unit),\n blossomColor: hexColor,\n }),\n wind: obj({ trunk: unit, branches: unit, leaves: unit, frequency: positive }),\n variation: obj({ color: unit, growth: unit, season: unit }),\n sculpts: arr(sculpt),\n});\n\n/**\n * Validates a raw current-version Definition and fills every missing field from\n * {@link DEFAULT_DEFINITION}. Returns a fresh object (never aliases input or defaults).\n */\nexport function validateDefinition(raw: Record<string, unknown>): TreeDefinition {\n return treeDefinition(raw, DEFAULT_DEFINITION, ROOT);\n}\n","import { MIGRATIONS } from './migrations';\nimport { isObject, TreeDefinitionError, validateDefinition } from './schema';\nimport { CURRENT_SCHEMA_VERSION, type DeepPartial, type TreeDefinition, type TreeDefinitionInput } from './types';\n\nexport { TreeDefinitionError } from './schema';\n\n/**\n * Turns untrusted input into a complete, valid Tree Definition:\n * - `input` is a Definition object (e.g. parsed JSON) or a JSON string;\n * - older `schemaVersion`s are migrated to {@link CURRENT_SCHEMA_VERSION};\n * - missing fields are filled from {@link DEFAULT_DEFINITION} (missing fields of a\n * `branches[i]` entry from {@link DEFAULT_BRANCH_LEVEL});\n * - every field is validated; unknown fields are rejected.\n * Throws {@link TreeDefinitionError} naming the first bad field (`field`, e.g. `branches[1].angle`).\n * Never mutates `input`.\n */\nexport function parseDefinition(input: unknown): TreeDefinition {\n let raw = input;\n if (typeof raw === 'string') {\n try {\n raw = JSON.parse(raw);\n } catch (e) {\n throw new TreeDefinitionError('(root)', `is not valid JSON: ${(e as Error).message}`);\n }\n }\n if (!isObject(raw)) throw new TreeDefinitionError('(root)', 'must be an object');\n const version = raw.schemaVersion;\n if (version === undefined) throw new TreeDefinitionError('schemaVersion', 'is missing');\n if (!Number.isInteger(version) || (version as number) < 1) {\n throw new TreeDefinitionError('schemaVersion', `must be an integer >= 1, got ${JSON.stringify(version)}`);\n }\n if ((version as number) > CURRENT_SCHEMA_VERSION) {\n throw new TreeDefinitionError(\n 'schemaVersion',\n `is ${version}, newer than this version of @casmo/tree.js supports (${CURRENT_SCHEMA_VERSION}); upgrade the library`,\n );\n }\n for (let v = version as number; v < CURRENT_SCHEMA_VERSION; v++) raw = MIGRATIONS[v]!(raw as Record<string, unknown>);\n return validateDefinition(raw as Record<string, unknown>);\n}\n\n/** Changes to apply on top of a Definition: any subset of its fields (arrays replace as a whole). */\nexport type DefinitionPatch = DeepPartial<Omit<TreeDefinition, 'schemaVersion'>>;\n\n/**\n * Starts from a Definition (e.g. a built-in Style) and changes a few parameters:\n * objects are merged deeply, arrays and values replace. Returns a new, validated Definition.\n *\n * ```ts\n * const tall = extendDefinition(broadleaf, { trunk: { length: 7 }, wind: { leaves: 1 } });\n * ```\n */\nexport function extendDefinition(base: TreeDefinition | TreeDefinitionInput, patch: DefinitionPatch): TreeDefinition {\n const parsed = parseDefinition(base);\n if (!isObject(patch)) throw new TreeDefinitionError('(root)', 'patch must be an object');\n return parseDefinition({ ...merge(parsed as unknown as Record<string, unknown>, patch), schemaVersion: CURRENT_SCHEMA_VERSION });\n}\n\nfunction merge(base: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue;\n out[key] = isObject(value) && isObject(base[key]) ? merge(base[key], value) : value;\n }\n return out;\n}\n\n/**\n * Fetches a Tree Definition JSON file (e.g. a Tree Editor export) and parses it with\n * {@link parseDefinition}. Rejects with an Error for an HTTP error, or a TreeDefinitionError.\n */\nexport async function fetchDefinition(url: string | URL, init?: RequestInit): Promise<TreeDefinition> {\n const response = await fetch(url, init);\n if (!response.ok) throw new Error(`Could not load Tree Definition from ${String(url)}: HTTP ${response.status}`);\n return parseDefinition(await response.text());\n}\n","/**\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 { 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}\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 };\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/** `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","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 { 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 below the trunk, breadth first (level by level).\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, trunk: SkeletonBranch, random: Random): SkeletonBranch[] {\n const out: SkeletonBranch[] = [];\n const queue: SkeletonBranch[] = [trunk];\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, definition.form === 'conifer' && parent.level === 0);\n out.push(...children);\n queue.push(...children);\n }\n return out;\n}\n\n/** Shortest conifer trunk branch, as a fraction of the declared length (keeps the top from being bare). */\nconst MIN_CONE = 0.1;\n\n/**\n * `cone`: the conifer Form. Branches from the trunk shrink linearly from the declared length at\n * `start` towards the trunk tip, so the crown is a cone. A broadleaf keeps the declared length.\n */\nfunction growChildren(parent: SkeletonBranch, level: BranchLevelDefinition, random: Random, cone: boolean): 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 * (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 profile = cone ? Math.max(MIN_CONE, (1 - t) / Math.max(1 - level.start, 1e-6)) : 1;\n const length = parentLength * level.length * profile * (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 { 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): GrowthTiming {\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 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 } 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 */\ninterface 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. */\nfunction 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). */\nfunction 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 const template = TEMPLATES[shape];\n const n = template.positions.length;\n const positions = new Float32Array(leaves.length * n * 3);\n const normals = new Float32Array(leaves.length * n * 3);\n const uvs = new Float32Array(leaves.length * n * 2);\n const colors = new Float32Array(leaves.length * n * 3);\n const indices = new Uint32Array(leaves.length * template.triangles.length * 3);\n const attributes = createAttributes(leaves.length * n);\n leaves.forEach((leaf, l) => {\n const side = cross(leaf.normal, leaf.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(leaf.normal, y)), scale(leaf.direction, z));\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 < n; c++) {\n const v = l * n + c;\n const local = template.positions[c]!;\n positions.set(add(leaf.position, scale(toWorld(local), leaf.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(leaf.tint, v * 3);\n writePart(attributes, v, part, 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 { 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 type { PartSeason } from '../season/profile';\nimport { cos, sin } from '../math';\nimport { createAttributes, writePart, type PartInfo } from './attributes';\nimport { branchFrames, pathLength } from './frames';\nimport type { GeometryBuffers, GrowthWindow, SkeletonBranch } from './types';\nimport type { PartSway } from './wind';\nimport { add, normalize, scale } from './vec';\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.\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): GeometryBuffers {\n const pts = branch.points;\n const frames = branchFrames(branch);\n const rings = pts.length;\n const ringSize = sides + 1; // duplicated seam vertex for UVs\n const vertexCount = rings * 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 // Radius change per unit length tilts the normals of a tapered branch towards its tip.\n const slope = (pts[0]!.radius - pts[rings - 1]!.radius) / Math.max(pathLength(branch), 1e-6);\n\n let v = 0;\n for (let r = 0; r < rings; r++) {\n const { position, radius } = pts[r]!;\n const { tangent, normal, binormal } = frames[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 positions.set(add(position, scale(radial, radius)), v * 3);\n normals.set(normalize(add(radial, scale(tangent, slope))), v * 3);\n uvs.set([s / sides, r / (rings - 1)], v * 2);\n writePart(attributes, v, part, r / (rings - 1), radius);\n v++;\n }\n }\n for (let r = 0; r < rings - 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[rings - 1]!.position, tip * 3);\n normals.set(frames[rings - 1]!.tangent, tip * 3);\n uvs.set([0.5, 1], tip * 2);\n writePart(attributes, tip, part, 1);\n const lastRing = (rings - 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/** 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 { cos, sin } from '../math';\nimport type { Sculpt, TreeDefinition } from '../definition';\nimport { seedRandom } from '../random';\nimport type { SkeletonBranch, SkeletonLeaf, Vec3 } from './types';\nimport { add, scale, sub } from './vec';\n\n/**\n * The Sculpt pass (ADR 0003): hand edits stored in the Definition, applied after the procedural\n * skeleton is grown and before leaves, Growth timing, Wind weights and meshes are derived from it.\n * So a sculpted part still grows, changes with the Season and sways like any other.\n *\n * A Sculpt only applies on the Seed it was made on; every other Seed ignores it. Sculpts apply in\n * Definition order. A Sculpt whose path does not exist (any more) for this Seed is skipped.\n */\nexport function sculptsFor(definition: TreeDefinition, seed: number): Sculpt[] {\n return definition.sculpts.filter((s) => s.seed === seed);\n}\n\n/** True if `path` is `root` or grows from it (its descendants). */\nexport const inSubtree = (path: string, root: string): boolean => path === root || path.startsWith(`${root}.`);\n\n/**\n * Applies the branch Sculpts to the skeleton branches (returns a new array, paths unchanged):\n * - `delete` drops the branch and everything growing from it;\n * - `move` rotates (Euler XYZ, radians, three.js convention, in tree space) and scales the branch\n * and everything growing from it about the branch base. `scale` scales lengths; radii stay.\n */\nexport function sculptBranches(branches: SkeletonBranch[], sculpts: Sculpt[]): SkeletonBranch[] {\n let out = branches;\n for (const sculpt of sculpts) {\n if (sculpt.action === 'delete') {\n out = out.filter((b) => !inSubtree(b.path, sculpt.path));\n } else if (sculpt.action === 'move') {\n const root = out.find((b) => b.path === sculpt.path);\n if (!root) continue;\n const base = root.points[0]!.position;\n const rotate = eulerXYZ(sculpt.rotation);\n const move = (p: Vec3) => add(base, rotate(scale(sub(p, base), sculpt.scale)));\n out = out.map((b) =>\n inSubtree(b.path, sculpt.path)\n ? {\n ...b,\n direction: rotate(b.direction),\n points: b.points.map((p) => ({ position: move(p.position), radius: p.radius })),\n }\n : b,\n );\n }\n }\n return out;\n}\n\n/**\n * Applies the `leaves` Sculpts (painting): each sets the coverage (0..1) of a branch and everything\n * growing from it; a later Sculpt on a sub-branch overrides it there. A leaf is kept while its own\n * stable random number (from the Seed and leaf id) is below its coverage, so painting more coverage\n * only ever adds leaves. Season coverage then applies on top of the kept leaves as usual.\n */\nexport function sculptLeaves(leaves: SkeletonLeaf[], sculpts: Sculpt[], seed: number): SkeletonLeaf[] {\n const painted = sculpts.filter((s) => s.action === 'leaves');\n if (painted.length === 0) return leaves;\n return leaves.filter((leaf) => {\n let coverage = 1;\n for (const s of painted) if (inSubtree(leaf.branch, s.path)) coverage = s.coverage;\n return seedRandom(seed, `sculpt/${leaf.id}`) < coverage;\n });\n}\n\n/** The rotation of a three.js `Euler(x, y, z, 'XYZ')` (matrix Rx * Ry * Rz) as a function on vectors. */\nfunction eulerXYZ([x, y, z]: Vec3): (v: Vec3) => Vec3 {\n const [a, b, c, d, e, f] = [cos(x), sin(x), cos(y), sin(y), cos(z), sin(z)];\n const [ae, af, be, bf] = [a * e, a * f, b * e, b * f];\n const m = [c * e, -c * f, d, af + be * d, ae - bf * d, -b * c, bf - ae * d, be + af * d, a * c];\n return ([vx, vy, vz]) => [\n m[0]! * vx + m[1]! * vy + m[2]! * vz,\n m[3]! * vx + m[4]! * vy + m[5]! * vz,\n m[6]! * vx + m[7]! * vy + m[8]! * vz,\n ];\n}\n","import type { TreeDefinition } from '../definition';\nimport type { Random } from '../random';\nimport type { SkeletonBranch, SkeletonPoint } from './types';\n\n/** Builds the trunk centre line from the Definition, varied by the Seed within its ranges. */\nexport function buildTrunk(definition: TreeDefinition, random: Random): SkeletonBranch {\n const { trunk } = definition;\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 { path: '0', parent: null, level: 0, attach: 0, direction: [0, 1, 0], points };\n}\n","import type { TreeDefinition } from '../definition';\nimport { createRandom, hashBytes, seedRandom } from '../random';\nimport { woodSeasonAttribute } from '../season/profile';\nimport { buildBranches } from './branches';\nimport { growthTiming } from './growth';\nimport { solidLeafGeometry } from './leaf-shapes';\nimport { leafGeometry, placeLeaves } from './leaves';\nimport { mergeBuffers, sweepBranch } from './mesh';\nimport { sculptBranches, sculptLeaves, sculptsFor } from './sculpt';\nimport { buildTrunk } from './trunk';\nimport { branchSway, writeTrunkSway } from './wind';\nimport type { GeometryBuffers, TreeData, TreeSkeleton } from './types';\n\nexport { growthTiming } from './growth';\nexport type { GrowthTiming, GrowthWindow, GeometryBuffers, TreeAttributes, VertexAttribute, SkeletonBranch, 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 trunk = buildTrunk(definition, random.fork('trunk'));\n const sculpts = sculptsFor(definition, seed);\n const branches = sculptBranches([trunk, ...buildBranches(definition, trunk, 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 growth = growthTiming(definition, seed, branches, leaves);\n const sway = branchSway(branches, definition.branches.length);\n const wood = mergeBuffers(\n branches.map((b, i) =>\n sweepBranch(\n b,\n sidesOf(b.level),\n seedRandom(seed, b.path),\n woodSeasonAttribute(seed, definition.variation),\n growth.branches[i],\n sway.get(b.path),\n ),\n ),\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 skeleton = { branches, leaves };\n writeTrunkSway(wood, trunkHeight(skeleton));\n writeTrunkSway(leafBuffers, trunkHeight(skeleton));\n return { seed, skeleton, wood, leaves: leafBuffers, growth };\n}\n\n/**\n * Height of the (possibly Sculpted) trunk's tip: the scale of a tree's Wind sway. A Sculpt may\n * delete the trunk (an empty tree, nothing sways); the height is then 1.\n */\nexport function trunkHeight(skeleton: Pick<TreeSkeleton, 'branches'>): number {\n const trunk = skeleton.branches.find((b) => b.parent === null)?.points;\n return trunk ? trunk[trunk.length - 1]!.position[1] : 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 and leaves). */\nexport function hashTreeData(data: TreeData): string {\n return hex(hashBuffers(data.leaves, hashBuffers(data.wood)));\n}\n\nfunction hashBuffers(geometry: GeometryBuffers, h?: number): number {\n const arrays = [geometry.positions, geometry.normals, geometry.uvs, geometry.colors, geometry.indices];\n for (const name of Object.keys(geometry.attributes).sort()) {\n arrays.push(geometry.attributes[name]!.array);\n }\n for (const array of arrays) {\n if (array) h = hashBytes(new Uint8Array(array.buffer, array.byteOffset, array.byteLength), h);\n }\n return h!;\n}\n\nconst hex = (h: number) => h.toString(16).padStart(8, '0');\n","import type { GeometryBuffers } from '../generator';\n\n/**\n * The Growth model, one spec with two backends: `growPositions` (CPU, here) and `growthPosition`\n * (TSL, `./tsl.ts`). Keep them in step. Per vertex, at Growth `g`:\n *\n * 1. thicken: move the vertex towards its part's centre line, keeping `thickness(g)` of its radius\n * (`aGrowth.z`, along the vertex normal);\n * 2. sprout: scale the part about its base point (`aOrigin`) by `partProgress(g, start, end)`\n * (`aGrowth.xy`), so a part grows out of a point on its (already grown) parent;\n * 3. size: scale the whole tree about its base (local origin) by `treeScale(g)`.\n *\n * Every step is written as `x - offset * (1 - factor)`, so at Growth 1 the positions are exactly\n * the generated ones: a tree at Growth 1 is a normal static tree.\n */\n\n/** Size of the whole tree at Growth 0 (sapling), relative to fully grown. */\nexport const SAPLING_SCALE = 0.2;\n/** Branch thickness at Growth 0, relative to the size-scaled thickness when fully grown. */\nexport const SAPLING_THICKNESS = 0.4;\n/** Smallest window width, so parts with `start == end` (the trunk) are simply grown. */\nexport const MIN_WINDOW = 1e-5;\n\nexport const treeScale = (growth: number): number => SAPLING_SCALE + (1 - SAPLING_SCALE) * growth;\nexport const thickness = (growth: number): number => SAPLING_THICKNESS + (1 - SAPLING_THICKNESS) * growth;\n\n/** How far one part has sprouted (0 = not yet, 1 = full size), eased; 1 from `end` on. */\nexport function partProgress(growth: number, start: number, end: number): number {\n const p = Math.min(Math.max((growth - end) / Math.max(end - start, MIN_WINDOW) + 1, 0), 1);\n return p * p * (3 - 2 * p);\n}\n\n/** Clamps a Growth value to 0..1 (NaN becomes 1, fully grown). */\nexport function clampGrowth(growth: number): number {\n return Number.isNaN(growth) ? 1 : Math.min(Math.max(growth, 0), 1);\n}\n\n/**\n * Vertex positions of generated geometry at a given Growth, on the CPU (for baking a tree and\n * for tests; at runtime the same model runs in TSL). Returns a new array.\n */\nexport function growPositions(buffers: GeometryBuffers, growth: number): Float32Array {\n const g = clampGrowth(growth);\n const { positions, normals } = buffers;\n const { aOrigin, aGrowth } = buffers.attributes;\n const out = new Float32Array(positions.length);\n const scale = treeScale(g);\n const thin = 1 - thickness(g);\n for (let v = 0; v < positions.length / 3; v++) {\n const [start, end, radius] = [aGrowth.array[v * 3]!, aGrowth.array[v * 3 + 1]!, aGrowth.array[v * 3 + 2]!];\n const shrink = 1 - partProgress(g, start, end);\n for (let k = 0; k < 3; k++) {\n const i = v * 3 + k;\n const thick = positions[i]! - normals[i]! * radius * thin;\n const sprouted = thick - (thick - aOrigin.array[i]!) * shrink;\n out[i] = sprouted - sprouted * (1 - scale);\n }\n }\n return out;\n}\n","import { attribute, float, normalGeometry, positionLocal } from 'three/tsl';\nimport type { Node } from 'three/webgpu';\nimport { MIN_WINDOW, SAPLING_SCALE, SAPLING_THICKNESS } from './evaluate';\n\n// The TSL twins of the helpers in `./evaluate.ts`, step for step.\n\n/** Size of the whole tree at Growth `g` (twin of `treeScale`). */\nconst treeScale = (g: Node<'float'>): Node<'float'> => float(SAPLING_SCALE).add(float(1 - SAPLING_SCALE).mul(g));\n\n/** Branch thickness at Growth `g` (twin of `thickness`). */\nconst thickness = (g: Node<'float'>): Node<'float'> => float(SAPLING_THICKNESS).add(float(1 - SAPLING_THICKNESS).mul(g));\n\n/** How far one part has sprouted, eased (twin of `partProgress`). */\nfunction partProgress(g: Node<'float'>, start: Node<'float'>, end: Node<'float'>): Node<'float'> {\n const p = g.sub(end).div(end.sub(start).max(MIN_WINDOW)).add(1).clamp(0, 1);\n return p.mul(p).mul(float(3).sub(p.mul(2)));\n}\n\n/**\n * Growth in TSL: the vertex position of a tree part at Growth `growth` (a float node, usually the\n * tree's Growth uniform; a Forest can pass a per-instance attribute instead). Same model and steps\n * as `growPositions` (see `./evaluate.ts`), driven by the Generator's `aGrowth` and `aOrigin` attributes.\n *\n * `position` is the input position (default `positionLocal`). To compose with other vertex effects,\n * feed this node into them, e.g. `material.positionNode = windPosition(growthPosition(uGrowth))`:\n * Growth first, so the rest acts on the grown tree.\n */\nexport function growthPosition(growth: Node<'float'>, position: Node<'vec3'> = positionLocal): Node<'vec3'> {\n const g = float(growth).clamp(0, 1);\n const data = attribute<'vec3'>('aGrowth', 'vec3');\n const origin = attribute<'vec3'>('aOrigin', 'vec3');\n const [start, end, radius] = [data.x, data.y, data.z];\n\n const scale = treeScale(g);\n const thin = float(1).sub(thickness(g));\n const shrink = float(1).sub(partProgress(g, start, end));\n\n const thick = position.sub(normalGeometry.mul(radius).mul(thin));\n const sprouted = thick.sub(thick.sub(origin).mul(shrink));\n return sprouted.sub(sprouted.mul(float(1).sub(scale)));\n}\n","import { 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 {\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';\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 */\nclass SoftToonLightingModel extends LightingModel {\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 }\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 }\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 { DoubleSide, type MeshStandardNodeMaterial } from 'three/webgpu';\nimport { color, mix, uv, float } from 'three/tsl';\nimport type { TreeDefinition } from '../definition';\nimport type { TextureOptions } from '../textures';\nimport { applyBarkMaps, applyLeafMap } from './maps';\nimport { createShadedMaterial, isFlatShading } from './shading';\n\nexport { createShadedMaterial } from './shading';\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 */\nexport function createBarkMaterial(definition: TreeDefinition, textures?: TextureOptions): 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 material.colorNode = applyBarkMaps(material, definition.materials.bark, shaded, 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","/** Thrown when a tree is drawn by anything other than `WebGPURenderer` (ADR 0002). */\nexport class UnsupportedRendererError extends Error {\n constructor(what: string) {\n super(\n `tree.js requires WebGPURenderer (import { WebGPURenderer } from 'three/webgpu'), but the tree is being drawn by ${what}. ` +\n 'The classic WebGLRenderer is not supported because tree materials are TSL node materials. ' +\n 'WebGPURenderer runs on WebGPU and falls back to WebGL2 by itself, so switching renderers keeps WebGL2 support.',\n );\n this.name = 'UnsupportedRendererError';\n }\n}\n\ninterface RendererLike {\n isWebGPURenderer?: boolean;\n isWebGLRenderer?: boolean;\n}\n\n/** Throws {@link UnsupportedRendererError} unless `renderer` is a `WebGPURenderer` (either backend). */\nexport function assertWebGPURenderer(renderer: unknown): void {\n const r = renderer as RendererLike | null | undefined;\n if (r?.isWebGPURenderer === true) return;\n throw new UnsupportedRendererError(r?.isWebGLRenderer ? 'the classic WebGLRenderer' : 'an unknown renderer');\n}\n","import { Color, type Node as FloatNode, type NodeMaterial, type UniformNode } from 'three/webgpu';\nimport { attribute, float, fract, mix, select, uniform, varying, vec4 } from 'three/tsl';\nimport type { Keyframe, SeasonProfileDefinition } from '../definition';\nimport { KEYFRAME_EPSILON } from './profile';\n\n/** A float uniform (`.value` is the Season). */\nexport type SeasonUniform = UniformNode<'float', number>;\n\n// TSL node types are loosely typed in @types/three; keep our own alias.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Node = any;\n\n/**\n * Unrolls a keyframe track into a chain of mixes over uniforms (one per segment). Same maths\n * as `sampleTrack` in `./profile.ts`. Key times and values are uniforms, so editing a value\n * never recompiles; only a different key count does.\n */\nfunction keyframeNode<V>(s: Node, track: readonly Keyframe<V>[], toUniform: (v: V) => Node): Node {\n const ts: Node[] = track.map((k) => uniform(k.t));\n const vs: Node[] = track.map((k) => toUniform(k.value));\n let out: Node = vs[0];\n for (let i = 0; i < track.length - 1; i++) {\n const f = s.sub(ts[i]).div(ts[i + 1]!.sub(ts[i]).max(KEYFRAME_EPSILON)).clamp(0, 1);\n out = mix(out, vs[i + 1], f);\n }\n return out;\n}\n\n/** The Season nodes of one tree's leaves; `S` is the Season input node (a uniform by default). */\nexport interface SeasonNodes<S extends FloatNode<'float'> = SeasonUniform> {\n /** Season 0..1 (first day of spring .. last day of winter). For a uniform: write `.value`; nothing recompiles. */\n season: S;\n /** Leaf colour (vec3, linear) at this leaf's shifted Season, or the blossom colour for a blossom. */\n color: Node;\n /** True while the leaf is shown (coverage above its rank, or a blossom). For `maskNode`. */\n visible: Node;\n}\n\n/**\n * Builds the TSL nodes that evaluate a Season Profile per leaf, from the `aSeason` vertex\n * attribute (Seed timing shift, coverage rank, blossom rank). The TSL twin of `leafSeason`.\n * Evaluated in the vertex stage (constant per leaf) and passed on as varyings.\n *\n * `season` is the Season input: a new uniform by default, or any float node (a Forest passes its\n * per-instance Season attribute).\n */\nexport function createSeasonNodes(profile: SeasonProfileDefinition): SeasonNodes;\nexport function createSeasonNodes<S extends FloatNode<'float'>>(profile: SeasonProfileDefinition, season: S): SeasonNodes<S>;\nexport function createSeasonNodes(profile: SeasonProfileDefinition, season: FloatNode<'float'> = uniform(0)): SeasonNodes<FloatNode<'float'>> {\n const aSeason = attribute('aSeason', 'vec3');\n const shifted = season.add(aSeason.x);\n const s = select(shifted.greaterThan(1).or(shifted.lessThan(0)), fract(shifted), shifted);\n\n const leafColor = keyframeNode(s, profile.leafColor, (v) => uniform(new Color(v)));\n const coverage = keyframeNode(s, profile.leafCoverage, (v) => uniform(v));\n const blossom = keyframeNode(s, profile.blossom, (v) => uniform(v));\n const blossomColor = uniform(new Color(profile.blossomColor));\n\n const isBlossom = blossom.greaterThan(aSeason.z);\n const shown = isBlossom.or(coverage.greaterThan(aSeason.y));\n return {\n season,\n color: varying(select(isBlossom, blossomColor, leafColor)),\n visible: varying(select(shown, float(1), float(0))).greaterThan(0.5),\n };\n}\n\n/**\n * Hooks Season into a leaf material: `colorNode` (times the vertex-colour tint, and times the\n * material's existing `colorNode`, such as a leaf card texture with alpha) and `maskNode`, which\n * also cuts fallen leaves out of the shadow pass.\n */\nexport function applySeasonToLeafMaterial(material: NodeMaterial, nodes: Pick<SeasonNodes, 'color' | 'visible'>): void {\n material.colorNode = material.colorNode ? vec4(nodes.color, 1).mul(material.colorNode as Node) : nodes.color;\n material.maskNode = nodes.visible;\n}\n","import { wrapSeason } from './profile';\n\n/** A Season set by the app: must be finite (RangeError otherwise), then wrapped into 0..1. */\nexport function checkedSeason(value: number): number {\n if (!Number.isFinite(value)) throw new RangeError(`Season must be a finite number, got ${value}`);\n return wrapSeason(value);\n}\n","import { Vector3, type UniformNode } from 'three/webgpu';\nimport { uniform } from 'three/tsl';\n\nexport type WindDirection = Vector3 | readonly [number, number, number];\n\nexport interface WindOptions {\n /** World-space direction the wind blows towards (any length > 0; stored as a unit vector). Default +X. */\n direction?: WindDirection;\n /** 0 = calm (default), 1 = strong wind; larger values are allowed for storms. */\n strength?: number;\n}\n\n/**\n * Scene-wide Wind: a direction and a strength that every tree listening to it sways with.\n * Changing them only writes uniform values (no recompile). Trees use {@link sceneWind} unless\n * `createTree(..., { wind })` names another one. How much each tree moves is its Definition's\n * Wind response (`definition.wind`).\n */\nexport class Wind {\n /** The shared TSL uniforms tree materials read. Write through the setters, not here. */\n readonly uniforms: {\n readonly direction: UniformNode<'vec3', Vector3>;\n readonly strength: UniformNode<'float', number>;\n /** Seconds; follows the renderer clock unless {@link Wind.time} pins it. */\n readonly time: UniformNode<'float', number>;\n };\n private pinnedTime: number | null = null;\n\n constructor(options: WindOptions = {}) {\n this.uniforms = {\n direction: uniform(new Vector3(1, 0, 0)),\n strength: uniform(0),\n time: uniform(0).onRenderUpdate((frame) => this.pinnedTime ?? frame.time),\n };\n this.set(options);\n }\n\n /** Unit direction the wind blows towards (a copy: assign a new value to change it). */\n get direction(): Vector3 {\n return this.uniforms.direction.value.clone();\n }\n\n set direction(value: WindDirection) {\n const v = Array.isArray(value) ? new Vector3(...(value as [number, number, number])) : (value as Vector3).clone();\n const length = v.length();\n if (!Number.isFinite(length) || length === 0) {\n throw new RangeError(`Wind direction must be a finite, non-zero vector, got [${v.toArray().join(', ')}]`);\n }\n this.uniforms.direction.value.copy(v.divideScalar(length));\n }\n\n get strength(): number {\n return this.uniforms.strength.value;\n }\n\n set strength(value: number) {\n if (!Number.isFinite(value) || value < 0) throw new RangeError(`Wind strength must be a finite number >= 0, got ${value}`);\n this.uniforms.strength.value = value;\n }\n\n /**\n * Pins the Wind clock to a time in seconds (pause, deterministic screenshots), or `null`\n * (default) to follow the renderer's clock.\n */\n get time(): number | null {\n return this.pinnedTime;\n }\n\n set time(value: number | null) {\n this.pinnedTime = value;\n if (value !== null) this.uniforms.time.value = value;\n }\n\n /** Sets direction and/or strength; returns this. */\n set(options: WindOptions): this {\n if (options.direction !== undefined) this.direction = options.direction;\n if (options.strength !== undefined) this.strength = options.strength;\n return this;\n }\n}\n\n/** The scene-wide Wind every tree sways with by default. */\nexport const sceneWind = new Wind();\n\n/** The uniforms Wind nodes read: those of a {@link Wind}, or of a {@link WindBinding}. */\nexport type WindUniforms = Wind['uniforms'];\n\n/**\n * Per-object Wind uniforms that follow whichever Wind is bound to them, read once per render.\n * Trees and Forests build their Wind nodes on these, so switching to another Wind is one\n * assignment: no new nodes, no recompile, no regeneration.\n */\nexport class WindBinding {\n /** The bound Wind. */\n wind: Wind;\n readonly uniforms: WindUniforms;\n\n constructor(wind: Wind) {\n this.wind = wind;\n const direction = wind.uniforms.direction.value.clone();\n this.uniforms = {\n direction: uniform(direction).onRenderUpdate(() => direction.copy(this.wind.uniforms.direction.value)),\n strength: uniform(wind.strength).onRenderUpdate(() => this.wind.strength),\n time: uniform(0).onRenderUpdate((frame) => this.wind.time ?? frame.time),\n };\n }\n}\n","import type { UniformNode } from 'three/webgpu';\nimport { uniform } from 'three/tsl';\nimport type { WindResponseDefinition } from '../definition';\n\n/**\n * One tree's response to the Wind (from its Definition's `wind`), held in uniforms so the\n * Tree Editor can change it live. `height` (trunk height) and `phase` (from the Seed) shape the\n * motion: the sway scales with the tree, and trees of different Seeds move out of step.\n */\nexport class WindResponse {\n readonly uniforms: {\n readonly trunk: UniformNode<'float', number>;\n readonly branches: UniformNode<'float', number>;\n readonly leaves: UniformNode<'float', number>;\n readonly frequency: UniformNode<'float', number>;\n readonly height: UniformNode<'float', number>;\n /** Radians, 0..2π. */\n readonly phase: UniformNode<'float', number>;\n };\n\n constructor(response: WindResponseDefinition, shape: { height: number; phase: number }) {\n this.uniforms = {\n trunk: uniform(0),\n branches: uniform(0),\n leaves: uniform(0),\n frequency: uniform(1),\n height: uniform(shape.height),\n phase: uniform(shape.phase),\n };\n this.set(response);\n }\n\n /** The current response, as in the Definition's `wind`. */\n get values(): WindResponseDefinition {\n const u = this.uniforms;\n return { trunk: u.trunk.value, branches: u.branches.value, leaves: u.leaves.value, frequency: u.frequency.value };\n }\n\n /** Changes part of the response (uniform writes only). Weights are 0..1, frequency > 0. */\n set(response: Partial<WindResponseDefinition>): this {\n for (const key of ['trunk', 'branches', 'leaves'] as const) {\n const value = response[key];\n if (value === undefined) continue;\n if (!(value >= 0 && value <= 1)) throw new RangeError(`wind.${key} must be within 0..1, got ${value}`);\n this.uniforms[key].value = value;\n }\n if (response.frequency !== undefined) {\n if (!(response.frequency > 0 && Number.isFinite(response.frequency))) {\n throw new RangeError(`wind.frequency must be > 0, got ${response.frequency}`);\n }\n this.uniforms.frequency.value = response.frequency;\n }\n return this;\n }\n}\n","import type { Node, NodeMaterial } from 'three/webgpu';\nimport {\n attribute,\n cross,\n dot,\n modelWorldMatrixInverse,\n normalGeometry,\n positionGeometry,\n positionLocal,\n sin,\n vec3,\n vec4,\n} from 'three/tsl';\nimport type { WindUniforms } from './Wind';\nimport type { WindResponse } from './response';\n\n// Sway amplitudes at Wind strength 1 and response 1, as a fraction of the trunk height.\nconst TRUNK_AMPLITUDE = 0.15;\nconst BRANCH_AMPLITUDE = 0.1;\n// Leaf flutter, as a fraction of the distance from the leaf base.\nconst LEAF_AMPLITUDE = 0.2;\n\n/**\n * Overrides for trees that are not one object each (Forest instances): the Wind direction in\n * the tree's own space and the tree's phase (radians), e.g. from per-instance attributes.\n */\nexport interface WindFrame {\n direction?: Node<'vec3'>;\n phase?: Node<'float'>;\n}\n\n/** Anything holding Wind uniforms: a {@link Wind} or a {@link WindBinding} that follows one. */\nexport interface WindSource {\n readonly uniforms: WindUniforms;\n}\n\n/** The scene Wind direction in the rendered object's space (rotation only, normalized). */\nexport function objectWindDirection(wind: WindSource): Node<'vec3'> {\n return modelWorldMatrixInverse.mul(vec4(wind.uniforms.direction, 0)).xyz.normalize();\n}\n\n/**\n * TSL node: the Wind displacement (vec3, object space) of each vertex, from the per-vertex\n * `aWind` weights (trunk sway, branch sway, leaf flutter), the tree's Wind response and the\n * scene Wind. It only depends on geometry attributes and uniforms, so it adds onto any other\n * position node (Growth): `position = grown + windOffset(...)` (see {@link applyWind}).\n *\n * - trunk: leans with the wind and swings slowly, bending from the ground (weight = height²);\n * - branches: swing faster, with a phase that varies smoothly in space so joints stay attached,\n * plus a little cross-wind motion;\n * - leaves: flutter along their normal, more at the tip.\n * All of it is scaled by slow gusts. Wind direction is world space; it is turned into the tree's\n * object space (rotation only, so a scaled-up tree sways proportionally more). `frame` replaces\n * that direction and the response's phase (see {@link WindFrame}).\n */\nexport function windOffset(wind: WindSource, response: WindResponse, frame: WindFrame = {}): Node<'vec3'> {\n const weights = attribute('aWind', 'vec3');\n const random = attribute('aRandom', 'float');\n const origin = attribute('aOrigin', 'vec3');\n const r = response.uniforms;\n const strength = wind.uniforms.strength;\n\n const t = wind.uniforms.time.mul(r.frequency).add(frame.phase ?? r.phase);\n const direction = (frame.direction ?? objectWindDirection(wind)).normalize();\n const across = cross(direction, vec3(0, 1, 0));\n // 0.6 .. 1: two slow, incommensurate waves.\n const gust = sin(t.mul(0.37)).add(sin(t.mul(0.91).add(1.7))).mul(0.1).add(0.8);\n const scale = strength.mul(r.height).mul(gust);\n\n const trunkSwing = sin(t.mul(1.1)).mul(0.25).add(0.75); // 0.5 .. 1: lean plus swing\n const trunk = direction.mul(trunkSwing.mul(r.trunk).mul(weights.x).mul(scale).mul(TRUNK_AMPLITUDE));\n\n const spatialPhase = dot(positionGeometry, vec3(0.9, 0.4, 0.7));\n const branchSwing = sin(t.mul(2.3).add(spatialPhase)).mul(0.35).add(0.65); // 0.3 .. 1\n const branchCross = sin(t.mul(1.7).add(spatialPhase.mul(1.3))).mul(0.3);\n const branches = direction\n .mul(branchSwing)\n .add(across.mul(branchCross))\n .mul(r.branches.mul(weights.y).mul(scale).mul(BRANCH_AMPLITUDE));\n\n const leafLength = positionGeometry.sub(origin).length();\n const flutter = sin(t.mul(9).add(random.mul(6.2832)));\n const leaves = normalGeometry.mul(\n flutter.mul(r.leaves).mul(weights.z).mul(leafLength).mul(strength).mul(gust).mul(LEAF_AMPLITUDE),\n );\n\n return trunk.add(branches).add(leaves);\n}\n\n/**\n * Adds a Wind offset to a material's vertex position (its existing `positionNode`, or the plain\n * local position). The shadow pass reuses `positionNode`, so shadows sway along.\n */\nexport function applyWind(material: NodeMaterial, offset: Node<'vec3'>): void {\n material.positionNode = material.positionNode ? (material.positionNode as Node<'vec3'>).add(offset) : positionLocal.add(offset);\n material.needsUpdate = true;\n}\n","import {\n BufferAttribute,\n BufferGeometry,\n Group,\n InterleavedBuffer,\n InterleavedBufferAttribute,\n Mesh,\n type Material,\n type MeshStandardNodeMaterial,\n type NodeMaterial,\n type UniformNode,\n} from 'three/webgpu';\nimport { uniform } from 'three/tsl';\nimport type { TreeDefinition } from '../definition';\nimport { trunkHeight, type GeometryBuffers, type TreeData } from '../generator';\nimport { clampGrowth, growthPosition } from '../growth';\nimport { createBarkMaterial, createLeafMaterial } from '../materials';\nimport { assertWebGPURenderer } from '../renderer';\nimport { applySeasonToLeafMaterial, createSeasonNodes, type SeasonUniform } from '../season';\nimport { checkedSeason } from '../season/check';\nimport { textureReady, type TextureOptions } from '../textures';\nimport { seedRandom } from '../random';\nimport { applyWind, sceneWind, windOffset, Wind, WindBinding, WindResponse } from '../wind';\n\n/**\n * The Generator's per-vertex part attributes (`aLevel`, `aSeason`, `aWind`, ...) go into one\n * interleaved vertex buffer: WebGPU allows only 8 vertex buffers per draw by default, and a\n * textured leaf already reads position, normal, uv and colour besides Growth, Season and Wind.\n */\nfunction setPartAttributes(geometry: BufferGeometry, attributes: GeometryBuffers['attributes']): void {\n const entries = Object.entries(attributes);\n const stride = entries.reduce((sum, [, a]) => sum + a.itemSize, 0);\n const count = geometry.getAttribute('position').count;\n const data = new Float32Array(count * stride);\n let offset = 0;\n for (const [, { array, itemSize }] of entries) {\n for (let v = 0; v < count; v++) {\n for (let c = 0; c < itemSize; c++) data[v * stride + offset + c] = array[v * itemSize + c]!;\n }\n offset += itemSize;\n }\n const buffer = new InterleavedBuffer(data, stride);\n offset = 0;\n for (const [name, { itemSize }] of entries) {\n geometry.setAttribute(name, new InterleavedBufferAttribute(buffer, itemSize, offset));\n offset += itemSize;\n }\n}\n\nfunction toBufferGeometry(buffers: GeometryBuffers): BufferGeometry {\n const geometry = new BufferGeometry();\n geometry.setAttribute('position', new BufferAttribute(buffers.positions, 3));\n geometry.setAttribute('normal', new BufferAttribute(buffers.normals, 3));\n geometry.setAttribute('uv', new BufferAttribute(buffers.uvs, 2));\n if (buffers.colors) geometry.setAttribute('color', new BufferAttribute(buffers.colors, 3));\n setPartAttributes(geometry, buffers.attributes);\n geometry.setIndex(new BufferAttribute(buffers.indices, 1));\n geometry.computeBoundingBox();\n geometry.computeBoundingSphere();\n return geometry;\n}\n\nfunction treeMesh<M extends Material>(name: string, geometry: BufferGeometry, material: M): Mesh<BufferGeometry, M> {\n const mesh = new Mesh(geometry, material);\n mesh.name = name;\n mesh.castShadow = true;\n mesh.receiveShadow = true;\n mesh.onBeforeRender = (renderer) => assertWebGPURenderer(renderer);\n return mesh;\n}\n\n/** Per-tree state a Tree starts with. */\nexport interface TreeOptions {\n /** Growth, 0 (sapling) .. 1 (fully grown, default). */\n growth?: number;\n /** Season, 0 (first day of spring, default) .. 1 (last day of winter). */\n season?: number;\n /** The Wind this tree sways with. Default: the scene-wide {@link sceneWind}. */\n wind?: Wind;\n /**\n * Where this tree's textures load from (base path / per-URL overrides); takes precedence over\n * the app-wide `setTextureOptions`. Only Definitions with textures (e.g. the realistic Style) use it.\n */\n textures?: TextureOptions;\n}\n\n/**\n * A generated tree as a three.js object. Add it to a scene rendered by `WebGPURenderer`.\n * `growth`, `season` and the Wind only update uniforms: no regeneration, no recompile.\n */\nexport class Tree extends Group {\n readonly isTree = true;\n readonly definition: TreeDefinition;\n readonly seed: number;\n /** The generator output this object was built from (pure data). */\n readonly data: TreeData;\n /** Trunk and branches. */\n readonly wood: Mesh<BufferGeometry, Material>;\n /** Leaf cards (empty geometry for a bare tree). */\n readonly leaves: Mesh<BufferGeometry, MeshStandardNodeMaterial>;\n /** This tree's Growth uniform (read by the wood and leaf materials' `positionNode`). */\n readonly growthUniform: UniformNode<'float', number>;\n /** The Season uniform the leaf material reads (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\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);\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 this.add(this.wood, this.leaves);\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 this.season = options.season ?? 0;\n }\n\n /**\n * The Wind this tree sways with (shared with every other tree using it). Assigning another\n * Wind only rebinds uniforms: no regeneration, no recompile.\n */\n get wind(): Wind {\n return this.windBinding.wind;\n }\n\n set wind(value: Wind) {\n this.windBinding.wind = value;\n }\n\n /**\n * Season: 0 (first day of spring) .. 1 (last day of winter); sets leaf colour, leaf coverage\n * and blossom from the Definition's Season Profile. Values outside 0..1 wrap around the year.\n * Only updates a uniform, so it is cheap to animate.\n */\n get season(): number {\n return this.seasonUniform.value;\n }\n\n set season(value: number) {\n this.seasonUniform.value = checkedSeason(value);\n }\n\n /**\n * How far this tree has grown: 0 (sapling) .. 1 (fully grown); values outside are clamped.\n * Setting it only writes a uniform, so it is cheap to animate every frame.\n */\n get growth(): number {\n return this.growthUniform.value;\n }\n\n set growth(value: number) {\n this.growthUniform.value = clampGrowth(value);\n }\n\n /** Frees the GPU resources (geometries and materials) of this tree and removes it from its parent. */\n override dispose(): void {\n this.traverse((object) => {\n if (object instanceof Mesh) {\n object.geometry.dispose();\n const materials = Array.isArray(object.material) ? object.material : [object.material];\n for (const material of materials) material.dispose();\n }\n });\n this.removeFromParent();\n super.dispose();\n }\n}\n","import { parseDefinition, type TreeDefinition, type TreeDefinitionInput } from '../definition';\nimport { generateTree } from '../generator';\nimport { Tree, type TreeOptions } from './Tree';\n\nexport { Tree, type TreeOptions } from './Tree';\n\nexport interface CreateTreeOptions extends TreeOptions {\n /** Picks one individual tree within the Definition's ranges. Default 0. */\n seed?: number;\n}\n\n/**\n * Grows a tree from a Tree Definition (plain object or parsed JSON) and a Seed and\n * returns a three.js object to add to a scene rendered by `WebGPURenderer`.\n * Throws `TreeDefinitionError` for an invalid Definition.\n */\nexport function createTree(\n definition: TreeDefinitionInput | TreeDefinition,\n options: CreateTreeOptions = {},\n): Tree {\n const parsed = parseDefinition(definition);\n const seed = options.seed ?? 0;\n return new Tree(parsed, generateTree(parsed, seed), {\n growth: options.growth,\n wind: options.wind,\n season: options.season,\n textures: options.textures,\n });\n}\n","import type { TreeStyle } from './types';\n\n/**\n * The built-in Styles, each a lazily loaded chunk (`@casmo/tree.js/styles/<name>`).\n * To add a Style: one line here (plus its vite entry and package.json export).\n */\nexport const STYLE_LOADERS = {\n 'low-poly': () => import('./low-poly'),\n stylized: () => import('./stylized'),\n realistic: () => import('./realistic'),\n} satisfies Record<string, () => Promise<{ default: TreeStyle }>>;\n\n/** Name of a built-in Style, e.g. 'low-poly'. */\nexport type StyleName = keyof typeof STYLE_LOADERS;\n\n/** Names of all built-in Styles. */\nexport const STYLE_NAMES = Object.keys(STYLE_LOADERS) as StyleName[];\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 Record<string, (() => Promise<{ default: TreeStyle }>) | undefined>)[name];\n if (!load) throw new Error(`Unknown tree.js Style \"${name}\". Built-in Styles: ${STYLE_NAMES.join(', ')}.`);\n return (await load()).default;\n}\n","import type { Node } from 'three/webgpu';\nimport { attribute, cross, positionGeometry, positionLocal } from 'three/tsl';\nimport { growthPosition } from '../growth';\nimport { objectWindDirection, windOffset, type WindResponse, type WindSource } from '../wind';\n\n/**\n * Per-instance data of a Forest (one interleaved instanced buffer, 8 floats per tree):\n * `iRotation` = the tree's rotation as a quaternion (x, y, z, w);\n * `iState` = (scale, Growth, Season, Wind phase), Growth/Season already include the tree's offsets.\n */\nexport const INSTANCE_STRIDE = 8;\nexport const INSTANCE_ATTRIBUTES = { iRotation: 0, iState: 4 } as const;\n\n/** Per-tree values in the instanced Season/Growth/Wind slots. */\nexport function instanceState(): { scale: Node<'float'>; growth: Node<'float'>; season: Node<'float'>; windPhase: Node<'float'> } {\n const state = attribute<'vec4'>('iState', 'vec4');\n return { scale: state.x, growth: state.y, season: state.z, windPhase: state.w };\n}\n\n/** Rotates `v` by the instance quaternion (`inverse` = by its conjugate). */\nfunction rotate(v: Node<'vec3'>, inverse = false): Node<'vec3'> {\n const q = attribute<'vec4'>('iRotation', 'vec4');\n const u = inverse ? q.xyz.negate() : q.xyz;\n const t = cross(u, v).mul(2);\n return v.add(t.mul(q.w)).add(cross(u, t));\n}\n\n/**\n * The vertex position of a Forest tree (positionNode of an instanced Variant mesh).\n *\n * On an InstancedMesh, three.js applies the instance matrix to `positionLocal` before\n * `positionNode` runs, but Growth and Wind are defined in the tree's own space (about the\n * generated `aOrigin`s, relative to its trunk height). So both are computed from\n * `positionGeometry`, and only their displacement is turned into forest space with the\n * instance rotation and scale: M·(p + d) = M·p + R·s·d. The Wind direction goes the other way\n * (forest -> tree space) and each tree sways with its own phase.\n */\nexport function forestPosition(wind: WindSource, response: WindResponse): Node<'vec3'> {\n const { scale, growth, windPhase } = instanceState();\n const grown = growthPosition(growth, positionGeometry);\n const offset = windOffset(wind, response, { direction: rotate(objectWindDirection(wind), true), phase: windPhase });\n const displacement = grown.add(offset).sub(positionGeometry);\n return positionLocal.add(rotate(displacement).mul(scale));\n}\n","// Pure Forest bookkeeping (no three.js): tree keys and the per-tree hash.\nimport type { VariationDefinition } from '../definition';\nimport type { Vec3 } from '../generator';\nimport { createRandom, hashCombine, seedToUint32 } from '../random';\nimport { clampGrowth } from '../growth/evaluate';\nimport { wrapSeason } from '../season/profile';\n\n/** Where one tree of a Forest stands. */\nexport interface ForestPlacement {\n /** Position of the tree base, in the Forest's space. */\n position: Vec3 | { x: number; y: number; z: number };\n /** Radians: a number turns the tree about the vertical (Y) axis; [x, y, z] is an Euler rotation (XYZ order). Default 0. */\n rotation?: number | Vec3;\n /** Uniform scale. Default 1. */\n scale?: number;\n /**\n * A stable id. A tree's Variant and offsets come from it, so the tree keeps its look when it is\n * moved. Without an id they come from the position (rounded to 1 mm).\n */\n id?: string | number;\n}\n\n/** What the forest seed and a tree's key decide about that tree. */\nexport interface ForestTreeTraits {\n /** Which Variant (0 .. variants-1) the tree is drawn as. */\n variant: number;\n /** 0 .. `variation.growth`: how far behind the forest's Growth this tree grows. */\n growthDelay: number;\n /** Within ± `variation.season`: how far this tree's Season is shifted. */\n seasonShift: number;\n /** Radians, 0 .. 2π: so trees of one Variant do not sway in step. */\n windPhase: number;\n}\n\nexport function placementPosition(placement: ForestPlacement): Vec3 {\n const p = placement.position;\n const v: Vec3 = Array.isArray(p) ? [p[0], p[1], p[2]] : [(p as { x: number }).x, (p as { y: number }).y, (p as { z: number }).z];\n if (!v.every(Number.isFinite)) throw new RangeError(`Forest placement position must be finite, got [${v.join(', ')}]`);\n return v;\n}\n\n/**\n * The key a tree is known by: its id as a string (so ids 1 and \"1\" are the same tree), or\n * `@x,y,z` (position in millimetres) when it has no id.\n */\nexport function forestTreeKey(placement: ForestPlacement): string {\n if (placement.id !== undefined) return String(placement.id);\n const mm = placementPosition(placement).map((c) => Math.round(c * 1000) || 0); // `|| 0` folds -0 into 0\n return `@${mm.join(',')}`;\n}\n\n/** The Seed of Variant `index` of a forest. */\nexport function variantSeed(forestSeed: number, index: number): number {\n return hashCombine(seedToUint32(forestSeed), 0x7a71a7, index);\n}\n\n/**\n * A tree's Variant and offsets: a hash of the forest seed and the tree's key only, so they never\n * depend on the tree's index in the list or on which other trees exist.\n */\nexport function forestTreeTraits(\n forestSeed: number,\n key: string,\n variants: number,\n variation: Pick<VariationDefinition, 'growth' | 'season'>,\n): ForestTreeTraits {\n const random = createRandom(forestSeed).fork('forest').fork(key);\n return {\n variant: random.int(0, variants - 1),\n growthDelay: random.next() * variation.growth,\n seasonShift: (random.next() * 2 - 1) * variation.season,\n windPhase: random.next() * Math.PI * 2,\n };\n}\n\n/**\n * The Growth one tree is drawn at, for a Growth `growth` set on it: delayed by its `growthDelay`\n * but still exactly 0 at Growth 0 and 1 at Growth 1, so a fully grown forest is fully grown.\n */\nexport function delayedGrowth(growth: number, delay: number): number {\n const g = clampGrowth(growth);\n return delay > 0 ? clampGrowth((g - delay) / (1 - delay)) : g;\n}\n\n/** The Season one tree is drawn at: the Season set on it plus its shift, wrapped into 0..1. */\nexport function shiftedSeason(season: number, shift: number): number {\n return wrapSeason(season + shift);\n}\n","import {\n BufferAttribute,\n BufferGeometry,\n DynamicDrawUsage,\n Euler,\n Group,\n InstancedBufferAttribute,\n InstancedInterleavedBuffer,\n InstancedMesh,\n InterleavedBuffer,\n InterleavedBufferAttribute,\n Matrix4,\n Quaternion,\n Vector3,\n type MeshStandardNodeMaterial,\n} from 'three/webgpu';\nimport type { TreeDefinition } from '../definition';\nimport { generateTree, trunkHeight, type GeometryBuffers, type TreeData } from '../generator';\nimport { createBarkMaterial, createLeafMaterial } from '../materials';\nimport { assertWebGPURenderer } from '../renderer';\nimport { applySeasonToLeafMaterial, createSeasonNodes } from '../season';\nimport { checkedSeason } from '../season/check';\nimport { clampGrowth } from '../growth';\nimport { textureReady, type TextureOptions } from '../textures';\nimport { sceneWind, Wind, WindBinding, WindResponse, type WindSource } from '../wind';\nimport { INSTANCE_ATTRIBUTES, INSTANCE_STRIDE, forestPosition, instanceState } from './nodes';\nimport {\n delayedGrowth,\n forestTreeKey,\n forestTreeTraits,\n placementPosition,\n shiftedSeason,\n variantSeed,\n type ForestPlacement,\n type ForestTreeTraits,\n} from './placement';\n\n/** Options of {@link createForest}. */\nexport interface ForestOptions {\n /** How many Variants (distinct trees, each drawn instanced) the forest is made of. Default 4. */\n variants?: number;\n /** The forest seed: picks the Variants and every tree's Variant and offsets. Default 0. */\n seed?: number;\n /** Growth every tree starts at, 0..1. Default 1 (fully grown). */\n growth?: number;\n /** Season every tree starts at, 0..1. Default 0. */\n season?: number;\n /** The Wind the forest sways with. Default: the scene-wide `sceneWind`. */\n wind?: Wind;\n /** Where the Definition's textures load from (as `createTree(..., { textures })`). */\n textures?: TextureOptions;\n}\n\n/** What the GPU draws one tree with (after its offsets). */\nexport interface ForestInstanceState {\n growth: number;\n season: number;\n windPhase: number;\n}\n\nconst MIN_CAPACITY = 16;\n// Room for Wind sway in the instance bounding spheres (fraction of the trunk height).\nconst WIND_BOUNDS = 0.35;\n\n/**\n * One tree of a {@link Forest}. Its Variant and offsets come from the forest seed and its key\n * only. `growth` and `season` are what the app sets on this tree; the tree draws them with its\n * offsets applied (see {@link Forest.instanceState}).\n */\nexport class ForestTree implements ForestTreeTraits {\n /** The tree's id as a string, or `@x,y,z` (position in mm) when it was placed without an id. */\n readonly key: string;\n readonly placement: Readonly<ForestPlacement>;\n readonly variant: number;\n readonly growthDelay: number;\n readonly seasonShift: number;\n readonly windPhase: number;\n /** @internal Slot in the Variant's instance buffers. */\n slot = -1;\n private growthValue: number;\n private seasonValue: number;\n\n /** @internal Use {@link Forest.addTree}. */\n constructor(\n key: string,\n placement: ForestPlacement,\n traits: ForestTreeTraits,\n state: { growth: number; season: number },\n private readonly onChange: (tree: ForestTree) => void,\n ) {\n this.key = key;\n this.placement = placement;\n this.variant = traits.variant;\n this.growthDelay = traits.growthDelay;\n this.seasonShift = traits.seasonShift;\n this.windPhase = traits.windPhase;\n this.growthValue = clampGrowth(state.growth);\n this.seasonValue = checkedSeason(state.season);\n }\n\n /** Growth set on this tree, 0..1 (clamped). Only rewrites this tree's instance data. */\n get growth(): number {\n return this.growthValue;\n }\n\n set growth(value: number) {\n this.growthValue = clampGrowth(value);\n this.onChange(this);\n }\n\n /** Season set on this tree, 0..1 (wraps around the year). Only rewrites this tree's instance data. */\n get season(): number {\n return this.seasonValue;\n }\n\n set season(value: number) {\n this.seasonValue = checkedSeason(value);\n this.onChange(this);\n }\n}\n\n/** Packs generator buffers into one interleaved vertex buffer, so a Variant takes a single vertex buffer slot. */\nfunction interleavedGeometry(buffers: GeometryBuffers, boundsMargin: number): BufferGeometry {\n const parts: [string, Float32Array, number][] = [\n ['position', buffers.positions, 3],\n ['normal', buffers.normals, 3],\n ['uv', buffers.uvs, 2],\n ];\n if (buffers.colors) parts.push(['color', buffers.colors, 3]);\n for (const [name, { array, itemSize }] of Object.entries(buffers.attributes)) parts.push([name, array, itemSize]);\n\n const count = buffers.positions.length / 3;\n const stride = parts.reduce((sum, [, , size]) => sum + size, 0);\n const data = new Float32Array(count * stride);\n const interleaved = new InterleavedBuffer(data, stride);\n const geometry = new BufferGeometry();\n let offset = 0;\n for (const [name, array, size] of parts) {\n for (let v = 0; v < count; v++) {\n for (let c = 0; c < size; c++) data[v * stride + offset + c] = array[v * size + c]!;\n }\n geometry.setAttribute(name, new InterleavedBufferAttribute(interleaved, size, offset));\n offset += size;\n }\n geometry.setIndex(new BufferAttribute(buffers.indices, 1));\n geometry.computeBoundingBox();\n geometry.computeBoundingSphere();\n geometry.boundingSphere!.radius += boundsMargin;\n geometry.boundingBox!.expandByScalar(boundsMargin);\n return geometry;\n}\n\n/** Copies a geometry's attributes into a new geometry (shares the vertex data). */\nfunction shareGeometry(source: BufferGeometry): BufferGeometry {\n const geometry = new BufferGeometry();\n for (const [name, attribute] of Object.entries(source.attributes)) geometry.setAttribute(name, attribute);\n geometry.setIndex(source.getIndex());\n geometry.boundingBox = source.boundingBox!.clone();\n geometry.boundingSphere = source.boundingSphere!.clone();\n return geometry;\n}\n\n/**\n * One Variant of a Forest: one Seed's tree, drawn once per tree that uses it with an instanced\n * wood mesh and an instanced leaf mesh (one draw call per material).\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 /** 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 instanceData!: InstancedInterleavedBuffer;\n private readonly woodSource: BufferGeometry;\n private readonly leafSource: BufferGeometry;\n\n constructor(\n private readonly forest: Forest,\n definition: TreeDefinition,\n index: number,\n seed: number,\n wind: WindSource,\n capacity: number,\n textures?: TextureOptions,\n ) {\n this.index = index;\n this.seed = seed;\n this.data = generateTree(definition, seed);\n const height = trunkHeight(this.data.skeleton);\n this.windResponse = new WindResponse(definition.wind, { height, phase: 0 });\n\n const position = forestPosition(wind, this.windResponse);\n this.barkMaterial = createBarkMaterial(definition, textures);\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 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 get capacity(): number {\n return this.instanceData.count;\n }\n\n /** @internal */\n add(tree: ForestTree): void {\n if (this.trees.length === this.capacity) this.allocate(this.capacity * 2);\n tree.slot = this.trees.length;\n this.trees.push(tree);\n this.write(tree);\n this.setCount();\n }\n\n /** @internal Swap-removes a tree: the last tree takes its slot. */\n remove(tree: ForestTree): void {\n const last = this.trees.pop()!;\n if (last !== tree) {\n last.slot = tree.slot;\n this.trees[last.slot] = last;\n this.write(last);\n }\n tree.slot = -1;\n this.setCount();\n }\n\n /** @internal Writes one tree's transform and state into its instance slot. */\n write(tree: ForestTree): void {\n const i = tree.slot;\n const { placement } = tree;\n const position = new Vector3(...placementPosition(placement));\n const rotation = placement.rotation ?? 0;\n const quaternion = new Quaternion().setFromEuler(\n typeof rotation === 'number' ? new Euler(0, rotation, 0) : new Euler(rotation[0], rotation[1], rotation[2]),\n );\n const scale = placement.scale ?? 1;\n this.woodMesh.setMatrixAt(i, new Matrix4().compose(position, quaternion, new Vector3(scale, scale, scale)));\n this.woodMesh.instanceMatrix.needsUpdate = true;\n\n const array = this.instanceData.array as Float32Array;\n array.set(\n [\n quaternion.x,\n quaternion.y,\n quaternion.z,\n quaternion.w,\n scale,\n delayedGrowth(tree.growth, tree.growthDelay),\n shiftedSeason(tree.season, tree.seasonShift),\n tree.windPhase,\n ],\n i * INSTANCE_STRIDE,\n );\n this.instanceData.needsUpdate = true;\n this.woodMesh.boundingSphere = this.leafMesh.boundingSphere = null;\n this.woodMesh.boundingBox = this.leafMesh.boundingBox = null;\n }\n\n /** @internal */\n state(tree: ForestTree): ForestInstanceState {\n const o = tree.slot * INSTANCE_STRIDE;\n const array = this.instanceData.array as Float32Array;\n return { growth: array[o + 5]!, season: array[o + 6]!, windPhase: array[o + 7]! };\n }\n\n /** @internal Frees the GPU resources. */\n dispose(): void {\n this.disposeMeshes();\n this.woodSource.dispose();\n this.leafSource.dispose();\n this.barkMaterial.dispose();\n this.leafMaterial.dispose();\n }\n\n private setCount(): void {\n this.woodMesh.count = this.leafMesh.count = this.trees.length;\n }\n\n /**\n * (Re)builds the instanced meshes with room for `capacity` trees. An InstancedMesh cannot grow,\n * so a full Variant gets new meshes (same materials and vertex data) of twice the size.\n */\n private allocate(capacity: number): void {\n const instanceData = new InstancedInterleavedBuffer(new Float32Array(capacity * INSTANCE_STRIDE), INSTANCE_STRIDE, 1);\n instanceData.setUsage(DynamicDrawUsage);\n const matrices = new InstancedBufferAttribute(new Float32Array(capacity * 16), 16);\n matrices.setUsage(DynamicDrawUsage);\n if (this.woodMesh) {\n instanceData.array.set(this.instanceData.array);\n matrices.array.set(this.woodMesh.instanceMatrix.array);\n this.disposeMeshes();\n }\n this.instanceData = instanceData;\n\n const mesh = (name: string, source: BufferGeometry, material: MeshStandardNodeMaterial) => {\n const geometry = shareGeometry(source);\n for (const [attribute, offset] of Object.entries(INSTANCE_ATTRIBUTES)) {\n geometry.setAttribute(attribute, new InterleavedBufferAttribute(instanceData, 4, offset));\n }\n const instanced = new InstancedMesh(geometry, material, capacity);\n instanced.instanceMatrix = matrices; // wood and leaves share one matrix buffer\n instanced.name = `${name} ${this.index}`;\n instanced.castShadow = true;\n instanced.receiveShadow = true;\n instanced.onBeforeRender = (renderer) => assertWebGPURenderer(renderer);\n return instanced;\n };\n this.woodMesh = mesh('forest wood', this.woodSource, this.barkMaterial);\n this.leafMesh = mesh('forest leaves', this.leafSource, this.leafMaterial);\n this.setCount();\n this.forest.add(this.woodMesh, this.leafMesh);\n }\n\n private disposeMeshes(): void {\n for (const mesh of [this.woodMesh, this.leafMesh]) {\n mesh.removeFromParent();\n mesh.geometry.dispose();\n mesh.dispose();\n }\n }\n}\n\n/**\n * Many trees of one Tree Definition, drawn from a few shared Variants (one instanced mesh per\n * Variant and material). Each tree's Variant and its small Growth/Season offsets come from a\n * hash of the forest seed and the tree's id (or position), never from its index, so adding or\n * removing trees never changes the others. Growth and Season can be set per tree or for all.\n */\nexport class Forest extends Group {\n readonly isForest = true;\n readonly definition: TreeDefinition;\n /** The forest seed. */\n readonly seed: number;\n readonly variants: readonly ForestVariant[];\n /** Resolves once every texture has loaded (at once without textures); rejects if one fails. */\n readonly ready: Promise<void>;\n private readonly byKey = new Map<string, ForestTree>();\n private readonly windBinding: WindBinding;\n private growthValue: number;\n private seasonValue: number;\n\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 const textures = this.variants.flatMap((v) => [v.barkMaterial.map, v.barkMaterial.normalMap, v.leafMaterial.map]);\n this.ready = Promise.all(textures.filter((t) => t !== null).map(textureReady)).then(() => undefined);\n this.ready.catch(() => {}); // only reported to whoever awaits it\n for (const placement of placements) this.addTree(placement);\n }\n\n /**\n * The Wind every tree of this forest sways with. Assigning another Wind only rebinds uniforms:\n * no rebuild, no recompile.\n */\n get wind(): Wind {\n return this.windBinding.wind;\n }\n\n set wind(value: Wind) {\n this.windBinding.wind = value;\n }\n\n /** Every tree, in the order they were added. */\n get trees(): readonly ForestTree[] {\n return [...this.byKey.values()];\n }\n\n /** Number of trees. */\n get size(): number {\n return this.byKey.size;\n }\n\n /** The tree with this key (its id as a string, or `ForestTree.key`). */\n get(key: string | number): ForestTree | undefined {\n return this.byKey.get(String(key));\n }\n\n /**\n * Plants a tree. Throws if a tree with the same id (or, without ids, the same position) exists.\n * It starts at the forest's current Growth and Season.\n */\n addTree(placement: ForestPlacement): ForestTree {\n const key = forestTreeKey(placement);\n if (this.byKey.has(key)) {\n throw new Error(\n placement.id !== undefined\n ? `Forest already has a tree with id \"${placement.id}\"`\n : `Forest already has a tree at position ${key.slice(1)} (mm); give the trees an id to place them on the same spot`,\n );\n }\n const traits = forestTreeTraits(this.seed, key, this.variants.length, this.definition.variation);\n const frozen = {\n ...placement,\n position: placementPosition(placement),\n rotation: Array.isArray(placement.rotation) ? [...(placement.rotation as number[])] : placement.rotation,\n } as ForestPlacement;\n const tree = new ForestTree(key, Object.freeze(frozen), traits, { growth: this.growthValue, season: this.seasonValue }, (t) =>\n this.variants[t.variant]!.write(t),\n );\n this.byKey.set(key, tree);\n this.variants[tree.variant]!.add(tree);\n return tree;\n }\n\n /** Cuts a tree (by key or object). Returns false if it is not in this forest. Other trees keep their look. */\n removeTree(tree: ForestTree | string | number): boolean {\n const found = typeof tree === 'object' ? this.byKey.get(tree.key) : this.get(tree);\n if (!found || (typeof tree === 'object' && found !== tree)) return false;\n this.byKey.delete(found.key);\n this.variants[found.variant]!.remove(found);\n return true;\n }\n\n /** The tree drawn by instance `instanceId` of a Variant mesh, e.g. from a raycast intersection. */\n treeAt(intersection: { object: unknown; instanceId?: number }): ForestTree | undefined {\n const variant = this.variants.find((v) => v.wood === intersection.object || v.leaves === intersection.object);\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 /** Frees every Variant's geometries, materials and instance buffers, and removes the forest from its parent. */\n override dispose(): void {\n for (const variant of this.variants) variant.dispose();\n this.byKey.clear();\n this.removeFromParent();\n super.dispose();\n }\n}\n","import { parseDefinition, type TreeDefinition, type TreeDefinitionInput } from '../definition';\nimport { Forest, type ForestOptions } from './Forest';\nimport type { ForestPlacement } from './placement';\n\nexport { Forest, ForestTree, ForestVariant, type ForestOptions, type ForestInstanceState } from './Forest';\nexport type { ForestPlacement, ForestTreeTraits } from './placement';\n\n/**\n * Places many trees of one Tree Definition cheaply: `variants` Seeds are generated once and each\n * is drawn instanced. Each tree's Variant and small Growth/Season offsets come from a hash of\n * the forest `seed` and the tree's id (or position), so the same seed and placements always give\n * the same forest, and adding or removing a tree never changes the others.\n * Throws `TreeDefinitionError` for an invalid Definition.\n */\nexport function createForest(\n definition: TreeDefinitionInput | TreeDefinition,\n placements: readonly ForestPlacement[] = [],\n options: ForestOptions = {},\n): Forest {\n return new Forest(parseDefinition(definition), placements, options);\n}\n"],"mappings":";;;;;AAGA,IAAa,uBAA8C;CACzD,OAAO;CACP,OAAO;CACP,KAAK;CACL,OAAO;CACP,gBAAgB;CAChB,QAAQ;CACR,QAAQ;CACR,iBAAiB;CACjB,QAAQ;CACR,OAAO;CACP,OAAO;CACP,UAAU;CACV,MAAM;CACN,SAAS;AACX;;;;;AAMA,IAAa,qBAAqC;CAChD,eAAA;CACA,MAAM;CACN,MAAM;CACN,OAAO;EACL,QAAQ;EACR,QAAQ;EACR,OAAO;EACP,OAAO;EACP,UAAU;EACV,iBAAiB;EACjB,MAAM;CACR;CACA,UAAU,CACR,EAAE,GAAG,qBAAqB,GAC1B;EAAE,GAAG;EAAsB,OAAO;EAAG,OAAO;EAAK,OAAO;EAAI,QAAQ;EAAM,OAAO;EAAG,UAAU;CAAE,CAClG;CACA,QAAQ;EACN,OAAO;EACP,OAAO;EACP,MAAM;EACN,eAAe;EACf,OAAO;EACP,OAAO;CACT;CACA,WAAW;EACT,SAAS;EACT,MAAM;GAAE,OAAO;GAAW,WAAW;GAAK,KAAK;GAAM,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M,OAAO,GAAG,KAAK,SAAS,KAAK;CAC7D;;CAGA,IAAI,SAAiB;EACnB,OAAO,KAAK;CACd;CAEA,IAAI,OAAO,OAAe;EACxB,KAAK,cAAc,cAAc,KAAK;EACtC,KAAK,MAAM,QAAQ,KAAK,MAAM,OAAO,GAAG,KAAK,SAAS,KAAK;CAC7D;;CAGA,UAAyB;EACvB,KAAK,MAAM,WAAW,KAAK,UAAU,QAAQ,QAAQ;EACrD,KAAK,MAAM,MAAM;EACjB,KAAK,iBAAiB;EACtB,MAAM,QAAQ;CAChB;AACF;;;;;;;;;ACtdA,SAAgB,aACd,YACA,aAAyC,CAAC,GAC1C,UAAyB,CAAC,GAClB;CACR,OAAO,IAAI,OAAO,gBAAgB,UAAU,GAAG,YAAY,OAAO;AACpE"}
@@ -0,0 +1,20 @@
1
+ import type { PartSeason } from '../season/profile';
2
+ import type { GrowthWindow, TreeAttributes, Vec3 } from './types';
3
+ import { type PartSway } from './wind';
4
+ /** The facts shared by every vertex of one part (branch or leaf). */
5
+ export interface PartInfo {
6
+ level: number;
7
+ attach: number;
8
+ random: number;
9
+ origin: Vec3;
10
+ growth: GrowthWindow;
11
+ /** Season timing, written as `aSeason` (vec3: shift, coverage rank, blossom rank). */
12
+ season: PartSeason;
13
+ /** Wind weights of the part (branch sway, leaf flutter); trunk sway is filled in from heights. */
14
+ sway?: PartSway;
15
+ }
16
+ /** Allocates the per-vertex attributes for `vertexCount` vertices. */
17
+ export declare function createAttributes(vertexCount: number): TreeAttributes;
18
+ /** Writes one vertex's attributes; `radius` = its distance from the part's centre line. */
19
+ export declare function writePart(attributes: TreeAttributes, v: number, part: PartInfo, along: number, radius?: number): void;
20
+ //# sourceMappingURL=attributes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attributes.d.ts","sourceRoot":"","sources":["../../src/generator/attributes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAW,KAAK,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAEhD,qEAAqE;AACrE,MAAM,WAAW,QAAQ;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,IAAI,CAAC;IACb,MAAM,EAAE,YAAY,CAAC;IACrB,sFAAsF;IACtF,MAAM,EAAE,UAAU,CAAC;IACnB,kGAAkG;IAClG,IAAI,CAAC,EAAE,QAAQ,CAAC;CACjB;AAED,sEAAsE;AACtE,wBAAgB,gBAAgB,CAAC,WAAW,EAAE,MAAM,GAAG,cAAc,CAYpE;AAED,2FAA2F;AAC3F,wBAAgB,SAAS,CAAC,UAAU,EAAE,cAAc,EAAE,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,SAAI,GAAG,IAAI,CAWhH"}
@@ -0,0 +1,12 @@
1
+ import type { TreeDefinition } from '../definition';
2
+ import type { Random } from '../random';
3
+ import type { SkeletonBranch } from './types';
4
+ /**
5
+ * Grows all branching levels below the trunk, breadth first (level by level).
6
+ *
7
+ * Branch path stability (ADR 0003): a parent's spiral phase comes from `random.fork(parentPath)`
8
+ * and each child's shape from `random.fork(childPath)`. So a branch depends only on its
9
+ * ancestors and its own path, never on its siblings' subtrees, on deeper levels or on leaves.
10
+ */
11
+ export declare function buildBranches(definition: TreeDefinition, trunk: SkeletonBranch, random: Random): SkeletonBranch[];
12
+ //# sourceMappingURL=branches.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"branches.d.ts","sourceRoot":"","sources":["../../src/generator/branches.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAyB,cAAc,EAAE,MAAM,eAAe,CAAC;AAC3E,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAExC,OAAO,KAAK,EAAE,cAAc,EAAuB,MAAM,SAAS,CAAC;AAOnE;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,UAAU,EAAE,cAAc,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,GAAG,cAAc,EAAE,CAYjH"}
@@ -0,0 +1,21 @@
1
+ import type { SkeletonBranch, Vec3 } from './types';
2
+ /** An orthonormal frame on a branch's centre line: `tangent` along the branch, `normal`/`binormal` across it. */
3
+ export interface Frame {
4
+ tangent: Vec3;
5
+ normal: Vec3;
6
+ binormal: Vec3;
7
+ }
8
+ /**
9
+ * Parallel-transport frames, one per skeleton point: the cross-section does not twist
10
+ * as the branch bends, so swept rings stay even for branches in any direction.
11
+ */
12
+ export declare function branchFrames(branch: SkeletonBranch): Frame[];
13
+ /** Total length of a branch's centre line. */
14
+ export declare function pathLength(branch: SkeletonBranch): number;
15
+ export interface BranchSample extends Frame {
16
+ position: Vec3;
17
+ radius: number;
18
+ }
19
+ /** The point, frame and radius at fraction `t` (0..1) of a branch's length. */
20
+ export declare function sampleBranch(branch: SkeletonBranch, frames: Frame[], t: number): BranchSample;
21
+ //# sourceMappingURL=frames.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frames.d.ts","sourceRoot":"","sources":["../../src/generator/frames.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAGpD,iHAAiH;AACjH,MAAM,WAAW,KAAK;IACpB,OAAO,EAAE,IAAI,CAAC;IACd,MAAM,EAAE,IAAI,CAAC;IACb,QAAQ,EAAE,IAAI,CAAC;CAChB;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,cAAc,GAAG,KAAK,EAAE,CAuB5D;AAED,8CAA8C;AAC9C,wBAAgB,UAAU,CAAC,MAAM,EAAE,cAAc,GAAG,MAAM,CAMzD;AAED,MAAM,WAAW,YAAa,SAAQ,KAAK;IACzC,QAAQ,EAAE,IAAI,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,+EAA+E;AAC/E,wBAAgB,YAAY,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,YAAY,CAyB7F"}
@@ -0,0 +1,15 @@
1
+ import type { TreeDefinition } from '../definition';
2
+ import type { GrowthTiming, SkeletonBranch, SkeletonLeaf } from './types';
3
+ /**
4
+ * When each part grows, as Growth windows (0..1) parallel to the skeleton arrays.
5
+ *
6
+ * Order: the trunk is there from Growth 0 (it only scales with the whole tree); a branch sprouts
7
+ * once its parent is fully grown, lower branches first; leaves come after their branch. So a part
8
+ * always sprouts from a fully-grown parent and never floats. The last part finishes at Growth 1.
9
+ *
10
+ * Seed (within `variation.growth` = v): each part's start is delayed by up to v/2 of its own window
11
+ * (its end stays put, so the order above holds), and the whole timeline is warped by `t^k`,
12
+ * k in 1 ± v (a monotone map that keeps 0 and 1). Together a window moves by less than v.
13
+ */
14
+ export declare function growthTiming(definition: TreeDefinition, seed: number, branches: SkeletonBranch[], leaves: SkeletonLeaf[]): GrowthTiming;
15
+ //# sourceMappingURL=growth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"growth.d.ts","sourceRoot":"","sources":["../../src/generator/growth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAgB,cAAc,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAcxF;;;;;;;;;;GAUG;AACH,wBAAgB,YAAY,CAC1B,UAAU,EAAE,cAAc,EAC1B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,cAAc,EAAE,EAC1B,MAAM,EAAE,YAAY,EAAE,GACrB,YAAY,CA4Bd"}