@casmo/tree.js 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/README.md +106 -16
  2. package/dist/apply-CcodnAbs.js +250 -0
  3. package/dist/apply-CcodnAbs.js.map +1 -0
  4. package/dist/bake/index.d.ts +2 -2
  5. package/dist/bake/index.d.ts.map +1 -1
  6. package/dist/definition/crown-shape.d.ts +9 -0
  7. package/dist/definition/crown-shape.d.ts.map +1 -0
  8. package/dist/definition/defaults.d.ts +7 -1
  9. package/dist/definition/defaults.d.ts.map +1 -1
  10. package/dist/definition/index.d.ts +4 -3
  11. package/dist/definition/index.d.ts.map +1 -1
  12. package/dist/definition/migrations.d.ts +0 -8
  13. package/dist/definition/migrations.d.ts.map +1 -1
  14. package/dist/definition/schema.d.ts.map +1 -1
  15. package/dist/definition/types.d.ts +95 -6
  16. package/dist/definition/types.d.ts.map +1 -1
  17. package/dist/effects/mask.d.ts +3 -3
  18. package/dist/effects/mask.d.ts.map +1 -1
  19. package/dist/effects.js +3 -3
  20. package/dist/effects.js.map +1 -1
  21. package/dist/forest/Forest.d.ts +10 -1
  22. package/dist/forest/Forest.d.ts.map +1 -1
  23. package/dist/forest/nodes.d.ts +4 -1
  24. package/dist/forest/nodes.d.ts.map +1 -1
  25. package/dist/{forest-OX9WvAwh.js → forest-DTrD8puH.js} +695 -546
  26. package/dist/forest-DTrD8puH.js.map +1 -0
  27. package/dist/generator/branches.d.ts +2 -2
  28. package/dist/generator/branches.d.ts.map +1 -1
  29. package/dist/generator/fruit.d.ts +28 -0
  30. package/dist/generator/fruit.d.ts.map +1 -0
  31. package/dist/generator/growth.d.ts +1 -1
  32. package/dist/generator/growth.d.ts.map +1 -1
  33. package/dist/generator/index.d.ts +4 -4
  34. package/dist/generator/index.d.ts.map +1 -1
  35. package/dist/generator/leaf-shapes.d.ts +33 -1
  36. package/dist/generator/leaf-shapes.d.ts.map +1 -1
  37. package/dist/generator/trunk.d.ts +8 -2
  38. package/dist/generator/trunk.d.ts.map +1 -1
  39. package/dist/generator/types.d.ts +34 -5
  40. package/dist/generator/types.d.ts.map +1 -1
  41. package/dist/index.d.ts +4 -2
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +48 -4
  44. package/dist/index.js.map +1 -1
  45. package/dist/materials/index.d.ts +6 -0
  46. package/dist/materials/index.d.ts.map +1 -1
  47. package/dist/names-C6-wuJ29.js +589 -0
  48. package/dist/names-C6-wuJ29.js.map +1 -0
  49. package/dist/react/Tree.d.ts +5 -2
  50. package/dist/react/Tree.d.ts.map +1 -1
  51. package/dist/react.js +10 -6
  52. package/dist/react.js.map +1 -1
  53. package/dist/season/nodes.d.ts +16 -0
  54. package/dist/season/nodes.d.ts.map +1 -1
  55. package/dist/season/profile.d.ts +26 -0
  56. package/dist/season/profile.d.ts.map +1 -1
  57. package/dist/species/almond.js +213 -0
  58. package/dist/species/almond.js.map +1 -0
  59. package/dist/species/almond.json +201 -0
  60. package/dist/species/apple.js +220 -0
  61. package/dist/species/apple.js.map +1 -0
  62. package/dist/species/apple.json +211 -0
  63. package/dist/species/ash.js +177 -0
  64. package/dist/species/ash.js.map +1 -0
  65. package/dist/species/ash.json +168 -0
  66. package/dist/species/beech.js +164 -0
  67. package/dist/species/beech.js.map +1 -0
  68. package/dist/species/beech.json +158 -0
  69. package/dist/species/birch.js +160 -0
  70. package/dist/species/birch.js.map +1 -0
  71. package/dist/species/birch.json +154 -0
  72. package/dist/species/catalog.d.ts +61 -0
  73. package/dist/species/catalog.d.ts.map +1 -0
  74. package/dist/species/cedar.js +159 -0
  75. package/dist/species/cedar.js.map +1 -0
  76. package/dist/species/cedar.json +159 -0
  77. package/dist/species/cherry.js +227 -0
  78. package/dist/species/cherry.js.map +1 -0
  79. package/dist/species/cherry.json +215 -0
  80. package/dist/species/chestnut.js +220 -0
  81. package/dist/species/chestnut.js.map +1 -0
  82. package/dist/species/chestnut.json +211 -0
  83. package/dist/species/douglas-fir.js +164 -0
  84. package/dist/species/douglas-fir.js.map +1 -0
  85. package/dist/species/douglas-fir.json +161 -0
  86. package/dist/species/elm.js +163 -0
  87. package/dist/species/elm.js.map +1 -0
  88. package/dist/species/elm.json +154 -0
  89. package/dist/species/hemlock.js +165 -0
  90. package/dist/species/hemlock.js.map +1 -0
  91. package/dist/species/hemlock.json +162 -0
  92. package/dist/species/hickory.js +190 -0
  93. package/dist/species/hickory.js.map +1 -0
  94. package/dist/species/hickory.json +183 -0
  95. package/dist/species/index.d.ts +10 -0
  96. package/dist/species/index.d.ts.map +1 -0
  97. package/dist/species/juniper.js +148 -0
  98. package/dist/species/juniper.js.map +1 -0
  99. package/dist/species/juniper.json +145 -0
  100. package/dist/species/loaders.d.ts +7 -0
  101. package/dist/species/loaders.d.ts.map +1 -0
  102. package/dist/species/mahogany.js +191 -0
  103. package/dist/species/mahogany.js.map +1 -0
  104. package/dist/species/mahogany.json +187 -0
  105. package/dist/species/maple.js +167 -0
  106. package/dist/species/maple.js.map +1 -0
  107. package/dist/species/maple.json +162 -0
  108. package/dist/species/oak.js +210 -0
  109. package/dist/species/oak.js.map +1 -0
  110. package/dist/species/oak.json +203 -0
  111. package/dist/species/olive.js +179 -0
  112. package/dist/species/olive.js.map +1 -0
  113. package/dist/species/olive.json +172 -0
  114. package/dist/species/peach.js +213 -0
  115. package/dist/species/peach.js.map +1 -0
  116. package/dist/species/peach.json +201 -0
  117. package/dist/species/pear.js +203 -0
  118. package/dist/species/pear.js.map +1 -0
  119. package/dist/species/pear.json +191 -0
  120. package/dist/species/pine.js +153 -0
  121. package/dist/species/pine.js.map +1 -0
  122. package/dist/species/pine.json +153 -0
  123. package/dist/species/plum.js +227 -0
  124. package/dist/species/plum.js.map +1 -0
  125. package/dist/species/plum.json +215 -0
  126. package/dist/species/red-oak.js +210 -0
  127. package/dist/species/red-oak.js.map +1 -0
  128. package/dist/species/red-oak.json +203 -0
  129. package/dist/species/redwood.js +164 -0
  130. package/dist/species/redwood.js.map +1 -0
  131. package/dist/species/redwood.json +161 -0
  132. package/dist/species/sequoia.js +157 -0
  133. package/dist/species/sequoia.js.map +1 -0
  134. package/dist/species/sequoia.json +157 -0
  135. package/dist/species/spruce.js +160 -0
  136. package/dist/species/spruce.js.map +1 -0
  137. package/dist/species/spruce.json +157 -0
  138. package/dist/species/teak.js +156 -0
  139. package/dist/species/teak.js.map +1 -0
  140. package/dist/species/teak.json +148 -0
  141. package/dist/species/types.d.ts +61 -0
  142. package/dist/species/types.d.ts.map +1 -0
  143. package/dist/species/walnut.js +210 -0
  144. package/dist/species/walnut.js.map +1 -0
  145. package/dist/species/walnut.json +203 -0
  146. package/dist/species/white-oak.js +203 -0
  147. package/dist/species/white-oak.js.map +1 -0
  148. package/dist/species/white-oak.json +199 -0
  149. package/dist/species.js +160 -0
  150. package/dist/species.js.map +1 -0
  151. package/dist/styles/apply.d.ts +12 -0
  152. package/dist/styles/apply.d.ts.map +1 -0
  153. package/dist/styles/low-poly/index.d.ts +1 -1
  154. package/dist/styles/low-poly/index.d.ts.map +1 -1
  155. package/dist/styles/low-poly.js +9 -8
  156. package/dist/styles/low-poly.js.map +1 -1
  157. package/dist/styles/names.d.ts +28 -0
  158. package/dist/styles/names.d.ts.map +1 -0
  159. package/dist/styles/realistic/index.d.ts +3 -8
  160. package/dist/styles/realistic/index.d.ts.map +1 -1
  161. package/dist/styles/realistic/textures.d.ts +20 -0
  162. package/dist/styles/realistic/textures.d.ts.map +1 -0
  163. package/dist/styles/realistic.js +10 -16
  164. package/dist/styles/realistic.js.map +1 -1
  165. package/dist/styles/registry.d.ts +2 -13
  166. package/dist/styles/registry.d.ts.map +1 -1
  167. package/dist/styles/stylized/index.d.ts +1 -1
  168. package/dist/styles/stylized/index.d.ts.map +1 -1
  169. package/dist/styles/stylized.js +9 -8
  170. package/dist/styles/stylized.js.map +1 -1
  171. package/dist/styles/types.d.ts +16 -2
  172. package/dist/styles/types.d.ts.map +1 -1
  173. package/dist/textures/realistic/bark-fibrous-normal.png +0 -0
  174. package/dist/textures/realistic/bark-fibrous.png +0 -0
  175. package/dist/textures/realistic/bark-papery-normal.png +0 -0
  176. package/dist/textures/realistic/bark-papery.png +0 -0
  177. package/dist/textures/realistic/bark-plated-normal.png +0 -0
  178. package/dist/textures/realistic/bark-plated.png +0 -0
  179. package/dist/textures/realistic/bark-smooth-normal.png +0 -0
  180. package/dist/textures/realistic/bark-smooth.png +0 -0
  181. package/dist/textures/realistic/leaf-compound.png +0 -0
  182. package/dist/textures/realistic/leaf-lobed.png +0 -0
  183. package/dist/textures/realistic/leaf-palmate.png +0 -0
  184. package/dist/textures/realistic/scale.png +0 -0
  185. package/dist/tree/Tree.d.ts +6 -4
  186. package/dist/tree/Tree.d.ts.map +1 -1
  187. package/package.json +9 -2
  188. package/dist/forest-OX9WvAwh.js.map +0 -1
  189. package/dist/types-BZjHhNz7.js +0 -20
  190. package/dist/types-BZjHhNz7.js.map +0 -1
@@ -1,411 +1,6 @@
1
- import "./types-BZjHhNz7.js";
1
+ import { f as DEFAULT_FRUIT_AMOUNT, p as DEFAULT_FRUIT_COLOR, s as parseDefinition, t as STYLE_NAMES } from "./names-C6-wuJ29.js";
2
2
  import { BufferAttribute, BufferGeometry, Color, DoubleSide, DynamicDrawUsage, Euler, Group, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMesh, InterleavedBuffer, InterleavedBufferAttribute, LightingModel, Matrix4, Mesh, MeshStandardNodeMaterial, NoColorSpace, Quaternion, RepeatWrapping, SRGBColorSpace, Texture, TextureLoader, Vector3 } from "three/webgpu";
3
3
  import { BRDF_Lambert, attribute, color, cross, diffuseColor, dot, float, fract, mix, modelWorldMatrixInverse, normalGeometry, normalMap, normalView, positionGeometry, positionLocal, select, sin, smoothstep, texture, uniform, uv, varying, vec2, vec3, vec4 } from "three/tsl";
4
- // src/definition/defaults.ts
5
- /** Defaults for one branching level; fills fields missing from a partial `branches[i]`. */
6
- var DEFAULT_BRANCH_LEVEL = {
7
- count: 6,
8
- start: .35,
9
- end: .95,
10
- angle: 45,
11
- angleVariation: .2,
12
- spiral: 137.5,
13
- length: .5,
14
- lengthVariation: .2,
15
- radius: .6,
16
- taper: .3,
17
- sides: 6,
18
- sections: 5,
19
- bend: .1,
20
- gravity: .1
21
- };
22
- /**
23
- * The documented defaults: a small broadleaf tree with two branching levels.
24
- * Anything a Definition leaves out is taken from here.
25
- */
26
- var DEFAULT_DEFINITION = {
27
- schemaVersion: 2,
28
- name: "",
29
- form: "broadleaf",
30
- trunk: {
31
- length: 4,
32
- radius: .25,
33
- taper: .4,
34
- sides: 8,
35
- sections: 8,
36
- lengthVariation: .15,
37
- bend: .08
38
- },
39
- branches: [{ ...DEFAULT_BRANCH_LEVEL }, {
40
- ...DEFAULT_BRANCH_LEVEL,
41
- count: 4,
42
- start: .2,
43
- angle: 40,
44
- length: .45,
45
- sides: 4,
46
- sections: 3
47
- }],
48
- leaves: {
49
- count: 8,
50
- shape: "card",
51
- size: .25,
52
- sizeVariation: .2,
53
- start: .3,
54
- angle: 40
55
- },
56
- materials: {
57
- shading: "standard",
58
- bark: {
59
- color: "#6b4a2b",
60
- roughness: .9,
61
- map: null,
62
- normalMap: null
63
- },
64
- leaf: {
65
- roughness: .7,
66
- map: null,
67
- alphaTest: .5
68
- }
69
- },
70
- season: {
71
- leafColor: [
72
- {
73
- t: 0,
74
- value: "#8bc34a"
75
- },
76
- {
77
- t: .25,
78
- value: "#3e7d2b"
79
- },
80
- {
81
- t: .5,
82
- value: "#3e7d2b"
83
- },
84
- {
85
- t: .62,
86
- value: "#d8892b"
87
- },
88
- {
89
- t: .72,
90
- value: "#a0401f"
91
- }
92
- ],
93
- leafCoverage: [
94
- {
95
- t: 0,
96
- value: .3
97
- },
98
- {
99
- t: .1,
100
- value: 1
101
- },
102
- {
103
- t: .62,
104
- value: 1
105
- },
106
- {
107
- t: .75,
108
- value: 0
109
- },
110
- {
111
- t: .97,
112
- value: 0
113
- },
114
- {
115
- t: 1,
116
- value: .3
117
- }
118
- ],
119
- blossom: [{
120
- t: 0,
121
- value: 0
122
- }],
123
- blossomColor: "#f7c6d9"
124
- },
125
- wind: {
126
- trunk: .2,
127
- branches: .5,
128
- leaves: .8,
129
- frequency: 1
130
- },
131
- variation: {
132
- color: .1,
133
- growth: .1,
134
- season: .05
135
- },
136
- sculpts: []
137
- };
138
- // src/definition/migrations.ts
139
- var MIGRATIONS = {
140
- /**
141
- * v1 -> v2: `bark` moved into `materials.bark`; branches, leaves, Season Profile, Wind,
142
- * variation and sculpts were added. A v1 tree was a bare trunk, so it keeps no branches
143
- * and no leaves (same tree as before).
144
- */
145
- 1: (input) => {
146
- const { bark, ...rest } = input;
147
- return {
148
- ...rest,
149
- schemaVersion: 2,
150
- branches: [],
151
- leaves: { count: 0 },
152
- ...bark === void 0 ? {} : { materials: { bark } }
153
- };
154
- } };
155
- // src/definition/schema.ts
156
- /** Thrown for an invalid Tree Definition; `field` is the path of the bad field, e.g. `branches[1].angle`. */
157
- var TreeDefinitionError = class extends Error {
158
- field;
159
- constructor(field, message) {
160
- super(`Invalid Tree Definition: ${field} ${message}`);
161
- this.name = "TreeDefinitionError";
162
- this.field = field;
163
- }
164
- };
165
- var ROOT = "(root)";
166
- var join = (path, key) => path === ROOT ? key : `${path}.${key}`;
167
- var show = (v) => v === void 0 ? "undefined" : JSON.stringify(v);
168
- function isObject(v) {
169
- return typeof v === "object" && v !== null && !Array.isArray(v);
170
- }
171
- /** Leaf schema from a predicate; `undefined` takes the fallback, or is reported missing. */
172
- function leaf(expected, ok) {
173
- return (value, fallback, path) => {
174
- const v = value === void 0 ? fallback : value;
175
- if (v === void 0) throw new TreeDefinitionError(path, "is missing");
176
- if (!ok(v)) throw new TreeDefinitionError(path, `must be ${expected}, got ${show(v)}`);
177
- return Array.isArray(v) ? [...v] : v;
178
- };
179
- }
180
- var isNum = (v) => typeof v === "number" && Number.isFinite(v);
181
- var range = (min, max) => leaf(`a number from ${min} to ${max}`, (v) => isNum(v) && v >= min && v <= max);
182
- var unit = range(0, 1);
183
- var positive = leaf("a number > 0", (v) => isNum(v) && v > 0);
184
- var finite = leaf("a finite number", isNum);
185
- var intAtLeast = (min) => leaf(`an integer >= ${min}`, (v) => Number.isInteger(v) && v >= min);
186
- var hexColor = leaf("a colour like \"#6b4a2b\"", (v) => typeof v === "string" && /^#[0-9a-f]{6}$/i.test(v));
187
- var text = leaf("a string", (v) => typeof v === "string");
188
- var url = leaf("a URL string or null", (v) => v === null || typeof v === "string" && v.length > 0);
189
- var vec3$1 = leaf("[x, y, z] numbers", (v) => Array.isArray(v) && v.length === 3 && v.every(isNum));
190
- var oneOf = (...values) => leaf(`one of ${values.map((x) => `"${x}"`).join(", ")}`, (v) => values.includes(v));
191
- var literal = (expected) => leaf(String(expected), (v) => v === expected);
192
- /** Object with exactly these fields; unknown fields are rejected (catches typos). */
193
- function obj(fields) {
194
- return (value, fallback, path) => {
195
- if (value === void 0 && fallback === void 0) throw new TreeDefinitionError(path, "is missing");
196
- const given = value === void 0 ? {} : value;
197
- if (!isObject(given)) throw new TreeDefinitionError(path, `must be an object, got ${show(given)}`);
198
- for (const key of Object.keys(given)) if (!(key in fields)) throw new TreeDefinitionError(join(path, key), "is not a known field");
199
- const out = {};
200
- for (const key of Object.keys(fields)) out[key] = fields[key](given[key], fallback?.[key], join(path, key));
201
- return out;
202
- };
203
- }
204
- /** Array; a missing array takes the fallback array, each item is filled from `itemFallback`. */
205
- function arr(item, opts = {}) {
206
- const { min = 0, max = Infinity, itemFallback } = opts;
207
- return (value, fallback, path) => {
208
- const v = value === void 0 ? fallback : value;
209
- if (v === void 0) throw new TreeDefinitionError(path, "is missing");
210
- if (!Array.isArray(v)) throw new TreeDefinitionError(path, `must be an array, got ${show(v)}`);
211
- if (v.length < min) throw new TreeDefinitionError(path, `must have at least ${min} entries`);
212
- if (v.length > max) throw new TreeDefinitionError(path, `must have at most ${max} entries`);
213
- return v.map((x, i) => item(x, itemFallback, `${path}[${i}]`));
214
- };
215
- }
216
- /** Adds a cross-field check; `check` returns [field, problem] or null. */
217
- function refine(schema, check) {
218
- return (value, fallback, path) => {
219
- const v = schema(value, fallback, path);
220
- const problem = check(v);
221
- if (problem) throw new TreeDefinitionError(join(path, problem[0]), problem[1]);
222
- return v;
223
- };
224
- }
225
- /** Union discriminated by `key`. */
226
- function tagged(key, variants) {
227
- const names = Object.keys(variants);
228
- return (value, fallback, path) => {
229
- if (!isObject(value)) throw new TreeDefinitionError(path, `must be an object, got ${show(value)}`);
230
- const variant = variants[value[key]];
231
- if (!variant) throw new TreeDefinitionError(join(path, key), `must be one of ${names.map((n) => `"${n}"`).join(", ")}, got ${show(value[key])}`);
232
- return variant(value, fallback, path);
233
- };
234
- }
235
- /** Keyframe track: at least one key, `t` in 0..1 and non-decreasing. */
236
- function track(value) {
237
- const keys = arr(obj({
238
- t: unit,
239
- value
240
- }), { min: 1 });
241
- return (v, fallback, path) => {
242
- const out = keys(v, fallback, path);
243
- for (let i = 1; i < out.length; i++) if (out[i].t < out[i - 1].t) throw new TreeDefinitionError(`${path}[${i}].t`, `must be >= the previous keyframe's t (${out[i - 1].t}), got ${out[i].t}`);
244
- return out;
245
- };
246
- }
247
- var branchLevel = refine(obj({
248
- count: intAtLeast(0),
249
- start: unit,
250
- end: unit,
251
- angle: range(0, 180),
252
- angleVariation: unit,
253
- spiral: range(0, 360),
254
- length: positive,
255
- lengthVariation: unit,
256
- radius: unit,
257
- taper: unit,
258
- sides: intAtLeast(3),
259
- sections: intAtLeast(1),
260
- bend: unit,
261
- gravity: range(-1, 1)
262
- }), (b) => b.end < b.start ? ["end", `must be >= start (${b.start}), got ${b.end}`] : null);
263
- var branchPath = leaf("a branch path like \"0\" or \"0.3.1\"", (v) => typeof v === "string" && /^0(\.\d+)*$/.test(v));
264
- var sculpt = tagged("action", {
265
- delete: obj({
266
- action: literal("delete"),
267
- seed: finite,
268
- path: branchPath
269
- }),
270
- move: obj({
271
- action: literal("move"),
272
- seed: finite,
273
- path: branchPath,
274
- rotation: vec3$1,
275
- scale: positive
276
- }),
277
- leaves: obj({
278
- action: literal("leaves"),
279
- seed: finite,
280
- path: branchPath,
281
- coverage: unit
282
- })
283
- });
284
- /** The whole Tree Definition schema (current version). Mirrors the interfaces in types.ts. */
285
- var treeDefinition = obj({
286
- schemaVersion: literal(2),
287
- name: text,
288
- form: oneOf("broadleaf", "conifer"),
289
- trunk: obj({
290
- length: positive,
291
- radius: positive,
292
- taper: unit,
293
- sides: intAtLeast(3),
294
- sections: intAtLeast(1),
295
- lengthVariation: unit,
296
- bend: unit
297
- }),
298
- branches: arr(branchLevel, {
299
- max: 4,
300
- itemFallback: DEFAULT_BRANCH_LEVEL
301
- }),
302
- leaves: obj({
303
- count: intAtLeast(0),
304
- shape: oneOf("card", "clump", "needle", "puff"),
305
- size: positive,
306
- sizeVariation: unit,
307
- start: unit,
308
- angle: range(0, 180)
309
- }),
310
- materials: obj({
311
- shading: oneOf("standard", "flat", "toon"),
312
- bark: obj({
313
- color: hexColor,
314
- roughness: unit,
315
- map: url,
316
- normalMap: url
317
- }),
318
- leaf: obj({
319
- roughness: unit,
320
- map: url,
321
- alphaTest: unit
322
- })
323
- }),
324
- season: obj({
325
- leafColor: track(hexColor),
326
- leafCoverage: track(unit),
327
- blossom: track(unit),
328
- blossomColor: hexColor
329
- }),
330
- wind: obj({
331
- trunk: unit,
332
- branches: unit,
333
- leaves: unit,
334
- frequency: positive
335
- }),
336
- variation: obj({
337
- color: unit,
338
- growth: unit,
339
- season: unit
340
- }),
341
- sculpts: arr(sculpt)
342
- });
343
- /**
344
- * Validates a raw current-version Definition and fills every missing field from
345
- * {@link DEFAULT_DEFINITION}. Returns a fresh object (never aliases input or defaults).
346
- */
347
- function validateDefinition(raw) {
348
- return treeDefinition(raw, DEFAULT_DEFINITION, ROOT);
349
- }
350
- // src/definition/parse.ts
351
- /**
352
- * Turns untrusted input into a complete, valid Tree Definition:
353
- * - `input` is a Definition object (e.g. parsed JSON) or a JSON string;
354
- * - older `schemaVersion`s are migrated to {@link CURRENT_SCHEMA_VERSION};
355
- * - missing fields are filled from {@link DEFAULT_DEFINITION} (missing fields of a
356
- * `branches[i]` entry from {@link DEFAULT_BRANCH_LEVEL});
357
- * - every field is validated; unknown fields are rejected.
358
- * Throws {@link TreeDefinitionError} naming the first bad field (`field`, e.g. `branches[1].angle`).
359
- * Never mutates `input`.
360
- */
361
- function parseDefinition(input) {
362
- let raw = input;
363
- if (typeof raw === "string") try {
364
- raw = JSON.parse(raw);
365
- } catch (e) {
366
- throw new TreeDefinitionError("(root)", `is not valid JSON: ${e.message}`);
367
- }
368
- if (!isObject(raw)) throw new TreeDefinitionError("(root)", "must be an object");
369
- const version = raw.schemaVersion;
370
- if (version === void 0) throw new TreeDefinitionError("schemaVersion", "is missing");
371
- if (!Number.isInteger(version) || version < 1) throw new TreeDefinitionError("schemaVersion", `must be an integer >= 1, got ${JSON.stringify(version)}`);
372
- if (version > 2) throw new TreeDefinitionError("schemaVersion", `is ${version}, newer than this version of @casmo/tree.js supports (2); upgrade the library`);
373
- for (let v = version; v < 2; v++) raw = MIGRATIONS[v](raw);
374
- return validateDefinition(raw);
375
- }
376
- /**
377
- * Starts from a Definition (e.g. a built-in Style) and changes a few parameters:
378
- * objects are merged deeply, arrays and values replace. Returns a new, validated Definition.
379
- *
380
- * ```ts
381
- * const tall = extendDefinition(broadleaf, { trunk: { length: 7 }, wind: { leaves: 1 } });
382
- * ```
383
- */
384
- function extendDefinition(base, patch) {
385
- const parsed = parseDefinition(base);
386
- if (!isObject(patch)) throw new TreeDefinitionError("(root)", "patch must be an object");
387
- return parseDefinition({
388
- ...merge(parsed, patch),
389
- schemaVersion: 2
390
- });
391
- }
392
- function merge(base, patch) {
393
- const out = { ...base };
394
- for (const [key, value] of Object.entries(patch)) {
395
- if (value === void 0) continue;
396
- out[key] = isObject(value) && isObject(base[key]) ? merge(base[key], value) : value;
397
- }
398
- return out;
399
- }
400
- /**
401
- * Fetches a Tree Definition JSON file (e.g. a Tree Editor export) and parses it with
402
- * {@link parseDefinition}. Rejects with an Error for an HTTP error, or a TreeDefinitionError.
403
- */
404
- async function fetchDefinition(url, init) {
405
- const response = await fetch(url, init);
406
- if (!response.ok) throw new Error(`Could not load Tree Definition from ${String(url)}: HTTP ${response.status}`);
407
- return parseDefinition(await response.text());
408
- }
409
4
  // src/random/index.ts
410
5
  /**
411
6
  * Random: the only source of randomness in tree.js.
@@ -668,6 +263,13 @@ function hexToLinear(hex) {
668
263
  srgbToLinear((n & 255) / 255)
669
264
  ];
670
265
  }
266
+ /** A Season Profile's Fruit tracks, with the defaults for absent ones. */
267
+ function fruitTracks(profile) {
268
+ return {
269
+ fruit: profile.fruit ?? DEFAULT_FRUIT_AMOUNT,
270
+ fruitColor: profile.fruitColor ?? DEFAULT_FRUIT_COLOR
271
+ };
272
+ }
671
273
  /**
672
274
  * Evaluates the Season Profile at `season`, shifted by `shift` (a Seed's timing offset,
673
275
  * see {@link seasonShift}) and wrapped around the year.
@@ -682,7 +284,12 @@ function evaluateSeason(profile, season, shift = 0) {
682
284
  })), s),
683
285
  leafCoverage: sampleTrack(profile.leafCoverage, s),
684
286
  blossom: sampleTrack(profile.blossom, s),
685
- blossomColor: hexToLinear(profile.blossomColor)
287
+ blossomColor: hexToLinear(profile.blossomColor),
288
+ fruit: sampleTrack(fruitTracks(profile).fruit, s),
289
+ fruitColor: sampleTrack(fruitTracks(profile).fruitColor.map((k) => ({
290
+ t: k.t,
291
+ value: hexToLinear(k.value)
292
+ })), s)
686
293
  };
687
294
  }
688
295
  /** The {@link PartSeason} of vertex `vertex` in `aSeason` attribute data (3 floats per vertex). */
@@ -709,6 +316,15 @@ function leafSeasonAttribute(seed, variation, leafId) {
709
316
  blossomRank: seedRandom(seed, `${leafId}#blossom`)
710
317
  };
711
318
  }
319
+ /** The Season timing (`aSeason` attribute) of one Fruit: like a leaf's, with the Fruit's rank as `coverageRank`. */
320
+ function fruitSeasonAttribute(seed, variation, fruitId) {
321
+ const jitter = (seedRandom(seed, `fruit/${fruitId}#season`) * 2 - 1) * (variation.season / 2);
322
+ return {
323
+ shift: seasonShift(seed, variation) + jitter,
324
+ coverageRank: seedRandom(seed, `fruit/${fruitId}#rank`),
325
+ blossomRank: 0
326
+ };
327
+ }
712
328
  /** `aSeason` for wood vertices: the tree's timing shift, no ranks. */
713
329
  function woodSeasonAttribute(seed, variation) {
714
330
  return {
@@ -730,6 +346,20 @@ function leafSeason(profile, season, part) {
730
346
  color: blossom ? state.blossomColor : state.leafColor
731
347
  };
732
348
  }
349
+ /**
350
+ * Evaluates one Fruit from its Season timing (`aSeason` of the fruit mesh: shift, the Fruit's
351
+ * rank as `coverageRank`): the exact CPU twin of the Fruit shader (see `createFruitSeasonNodes`).
352
+ * A Fruit shows while the Fruit amount is above its rank, scaled about its attachment point by the amount.
353
+ */
354
+ function fruitSeason(profile, season, part) {
355
+ const state = evaluateSeason(profile, season, part.shift);
356
+ const visible = state.fruit > part.coverageRank;
357
+ return {
358
+ visible,
359
+ scale: visible ? state.fruit : 0,
360
+ color: state.fruitColor
361
+ };
362
+ }
733
363
  // src/generator/vec.ts
734
364
  var add = (a, b) => [
735
365
  a[0] + b[0],
@@ -845,36 +475,36 @@ function sampleBranch(branch, frames, t) {
845
475
  };
846
476
  }
847
477
  // src/generator/branches.ts
848
- var DEG$1 = Math.PI / 180;
478
+ var DEG$3 = Math.PI / 180;
849
479
  /** How far `gravity` = ±1 turns a branch over its whole length (sum of per-section pulls). */
850
480
  var GRAVITY_PER_BRANCH = 1.5;
851
481
  /**
852
- * Grows all branching levels below the trunk, breadth first (level by level).
482
+ * Grows all branching levels on every Stem, breadth first (level by level, over all Stems).
853
483
  *
854
484
  * Branch path stability (ADR 0003): a parent's spiral phase comes from `random.fork(parentPath)`
855
485
  * and each child's shape from `random.fork(childPath)`. So a branch depends only on its
856
486
  * ancestors and its own path, never on its siblings' subtrees, on deeper levels or on leaves.
857
487
  */
858
- function buildBranches(definition, trunk, random) {
488
+ function buildBranches(definition, stems, random) {
859
489
  const out = [];
860
- const queue = [trunk];
490
+ const queue = [...stems];
861
491
  for (let q = 0; q < queue.length; q++) {
862
492
  const parent = queue[q];
863
493
  const level = definition.branches[parent.level];
864
494
  if (!level) continue;
865
- const children = growChildren(parent, level, random, definition.form === "conifer" && parent.level === 0);
495
+ const children = growChildren(parent, level, random);
866
496
  out.push(...children);
867
497
  queue.push(...children);
868
498
  }
869
499
  return out;
870
500
  }
871
- /** Shortest conifer trunk branch, as a fraction of the declared length (keeps the top from being bare). */
872
- var MIN_CONE = .1;
501
+ /** A Crown Shape curve's multiplier at attach position `t`; an absent curve is flat (1). */
502
+ var crownShape = (curve, t) => curve ? sampleTrack(curve, t) : 1;
873
503
  /**
874
- * `cone`: the conifer Form. Branches from the trunk shrink linearly from the declared length at
875
- * `start` towards the trunk tip, so the crown is a cone. A broadleaf keeps the declared length.
504
+ * Grows one parent's children. The Crown Shape curves (`lengthProfile`, `angleProfile`) scale each
505
+ * child's length and angle by where it sits on the parent (ADR 0004).
876
506
  */
877
- function growChildren(parent, level, random, cone) {
507
+ function growChildren(parent, level, random) {
878
508
  const count = level.count;
879
509
  const azimuth0 = random.fork(parent.path).range(0, Math.PI * 2);
880
510
  const frames = branchFrames(parent);
@@ -885,8 +515,8 @@ function growChildren(parent, level, random, cone) {
885
515
  const r = random.fork(path);
886
516
  const t = level.start + (level.end - level.start) * (i + r.range(.15, .85)) / count;
887
517
  const at = sampleBranch(parent, frames, t);
888
- const angle = Math.min(level.angle * (1 + r.range(-level.angleVariation, level.angleVariation)), 180) * DEG$1;
889
- const azimuth = azimuth0 + i * level.spiral * DEG$1;
518
+ const angle = Math.min(level.angle * crownShape(level.angleProfile, t) * (1 + r.range(-level.angleVariation, level.angleVariation)), 180) * DEG$3;
519
+ const azimuth = azimuth0 + i * level.spiral * DEG$3;
890
520
  const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin$1(azimuth)));
891
521
  const start = normalize(add(scale(at.tangent, cos(angle)), scale(across, sin$1(angle))));
892
522
  const pull = [
@@ -895,8 +525,7 @@ function growChildren(parent, level, random, cone) {
895
525
  0
896
526
  ];
897
527
  let direction = start;
898
- const profile = cone ? Math.max(MIN_CONE, (1 - t) / Math.max(1 - level.start, 1e-6)) : 1;
899
- const step = parentLength * level.length * profile * (1 + r.range(-level.lengthVariation, level.lengthVariation)) / level.sections;
528
+ const step = parentLength * level.length * crownShape(level.lengthProfile, t) * (1 + r.range(-level.lengthVariation, level.lengthVariation)) / level.sections;
900
529
  const baseRadius = at.radius * level.radius;
901
530
  const points = [];
902
531
  let position = at.position;
@@ -925,68 +554,6 @@ function growChildren(parent, level, random, cone) {
925
554
  }
926
555
  return children;
927
556
  }
928
- // src/generator/growth.ts
929
- /** Delay of a branch after its parent is grown, per unit of `attach` (lower branches sprout first). */
930
- var BRANCH_STAGGER = .6;
931
- /** Time a branch takes from sprouting to full size. */
932
- var BRANCH_DURATION = 1;
933
- /** Leaves wait this long after their branch is grown ... */
934
- var LEAF_DELAY = .3;
935
- /** ... plus this much per unit of `attach` (leaves near the base first) ... */
936
- var LEAF_STAGGER = .5;
937
- /** ... and take this long to unfold. */
938
- var LEAF_DURATION = .6;
939
- /**
940
- * When each part grows, as Growth windows (0..1) parallel to the skeleton arrays.
941
- *
942
- * Order: the trunk is there from Growth 0 (it only scales with the whole tree); a branch sprouts
943
- * once its parent is fully grown, lower branches first; leaves come after their branch. So a part
944
- * always sprouts from a fully-grown parent and never floats. The last part finishes at Growth 1.
945
- *
946
- * Seed (within `variation.growth` = v): each part's start is delayed by up to v/2 of its own window
947
- * (its end stays put, so the order above holds), and the whole timeline is warped by `t^k`,
948
- * k in 1 ± v (a monotone map that keeps 0 and 1). Together a window moves by less than v.
949
- */
950
- function growthTiming(definition, seed, branches, leaves) {
951
- const raw = /* @__PURE__ */ new Map();
952
- const branchWindows = branches.map((branch) => {
953
- let window = {
954
- start: 0,
955
- end: 0
956
- };
957
- if (branch.parent !== null) {
958
- const start = raw.get(branch.parent).end + branch.attach * BRANCH_STAGGER;
959
- window = {
960
- start,
961
- end: start + BRANCH_DURATION
962
- };
963
- }
964
- raw.set(branch.path, window);
965
- return window;
966
- });
967
- const leafWindows = leaves.map((leaf) => {
968
- const start = raw.get(leaf.branch).end + LEAF_DELAY + leaf.attach * LEAF_STAGGER;
969
- return {
970
- start,
971
- end: start + LEAF_DURATION
972
- };
973
- });
974
- const total = Math.max(0, ...branchWindows.map((w) => w.end), ...leafWindows.map((w) => w.end));
975
- const v = definition.variation.growth;
976
- const k = 1 + (2 * seedRandom(seed, "growth") - 1) * v;
977
- const warp = (t) => total > 0 ? pow(Math.min(1, t / total), k) : 0;
978
- const finish = (w, key) => {
979
- const delay = seedRandom(seed, `growth/${key}`) * (v / 2) * (w.end - w.start);
980
- return {
981
- start: warp(w.start + delay),
982
- end: warp(w.end)
983
- };
984
- };
985
- return {
986
- branches: branchWindows.map((w, i) => finish(w, branches[i].path)),
987
- leaves: leafWindows.map((w, i) => finish(w, leaves[i].id))
988
- };
989
- }
990
557
  // src/generator/wind.ts
991
558
  var NO_SWAY = {
992
559
  base: 0,
@@ -1400,38 +967,45 @@ function orient(template) {
1400
967
  * every vertex carries the leaf's tint as its colour and the leaf's part attributes.
1401
968
  */
1402
969
  function solidLeafGeometry(leaves, shape, level, seed, variation = { season: 0 }, growth = [], branchSway = /* @__PURE__ */ new Map()) {
1403
- const template = TEMPLATES[shape];
970
+ return solidGeometry(TEMPLATES[shape], leaves, (leaf, l) => ({
971
+ level,
972
+ attach: leaf.attach,
973
+ random: seedRandom(seed, leaf.id),
974
+ origin: leaf.position,
975
+ season: leafSeasonAttribute(seed, variation, leaf.id),
976
+ growth: growth[l] ?? {
977
+ start: 0,
978
+ end: 0
979
+ },
980
+ sway: leafSway(branchSway.get(leaf.branch) ?? NO_SWAY, leaf.attach)
981
+ }));
982
+ }
983
+ /**
984
+ * One small closed mesh per placement: the template in the placement's frame
985
+ * (across, normal, direction), scaled by its size, every vertex carrying the placement's tint
986
+ * as its colour and its part attributes (`part`).
987
+ */
988
+ function solidGeometry(template, placements, part) {
1404
989
  const n = template.positions.length;
1405
- const positions = new Float32Array(leaves.length * n * 3);
1406
- const normals = new Float32Array(leaves.length * n * 3);
1407
- const uvs = new Float32Array(leaves.length * n * 2);
1408
- const colors = new Float32Array(leaves.length * n * 3);
1409
- const indices = new Uint32Array(leaves.length * template.triangles.length * 3);
1410
- const attributes = createAttributes(leaves.length * n);
1411
- leaves.forEach((leaf, l) => {
1412
- const side = cross$1(leaf.normal, leaf.direction);
1413
- const toWorld = ([x, y, z]) => add(add(scale(side, x), scale(leaf.normal, y)), scale(leaf.direction, z));
1414
- const part = {
1415
- level,
1416
- attach: leaf.attach,
1417
- random: seedRandom(seed, leaf.id),
1418
- origin: leaf.position,
1419
- season: leafSeasonAttribute(seed, variation, leaf.id),
1420
- growth: growth[l] ?? {
1421
- start: 0,
1422
- end: 0
1423
- },
1424
- sway: leafSway(branchSway.get(leaf.branch) ?? NO_SWAY, leaf.attach)
1425
- };
990
+ const positions = new Float32Array(placements.length * n * 3);
991
+ const normals = new Float32Array(placements.length * n * 3);
992
+ const uvs = new Float32Array(placements.length * n * 2);
993
+ const colors = new Float32Array(placements.length * n * 3);
994
+ const indices = new Uint32Array(placements.length * template.triangles.length * 3);
995
+ const attributes = createAttributes(placements.length * n);
996
+ placements.forEach((placement, l) => {
997
+ const side = cross$1(placement.normal, placement.direction);
998
+ const toWorld = ([x, y, z]) => add(add(scale(side, x), scale(placement.normal, y)), scale(placement.direction, z));
999
+ const info = part(placement, l);
1426
1000
  for (let c = 0; c < n; c++) {
1427
1001
  const v = l * n + c;
1428
1002
  const local = template.positions[c];
1429
- positions.set(add(leaf.position, scale(toWorld(local), leaf.size)), v * 3);
1003
+ positions.set(add(placement.position, scale(toWorld(local), placement.size)), v * 3);
1430
1004
  normals.set(normalize(toWorld(template.normals[c])), v * 3);
1431
1005
  const along = Math.min(Math.max(local[2], 0), 1);
1432
1006
  uvs.set([local[0] + .5, along], v * 2);
1433
- colors.set(leaf.tint, v * 3);
1434
- writePart(attributes, v, part, along);
1007
+ colors.set(placement.tint, v * 3);
1008
+ writePart(attributes, v, info, along);
1435
1009
  }
1436
1010
  template.triangles.forEach((triangle, t) => {
1437
1011
  indices.set(triangle.map((i) => l * n + i), (l * template.triangles.length + t) * 3);
@@ -1446,8 +1020,412 @@ function solidLeafGeometry(leaves, shape, level, seed, variation = { season: 0 }
1446
1020
  attributes
1447
1021
  };
1448
1022
  }
1023
+ // src/generator/fruit.ts
1024
+ var DEG$2 = Math.PI / 180;
1025
+ /** Angle between twig and Fruit when it does not hang (`hang` 0), degrees. */
1026
+ var FRUIT_TILT = 60;
1027
+ /** Fruit sits on the outer part of its twig: from this fraction of the twig length to its tip. */
1028
+ var FRUIT_START = .3;
1029
+ /** Fruit starts to grow no earlier than this Growth (it only shows on a fully grown tree) ... */
1030
+ var FRUIT_GROWTH_START = .9;
1031
+ /** ... plus up to this much per Fruit (from the Seed). */
1032
+ var FRUIT_GROWTH_JITTER = .05;
1033
+ /**
1034
+ * Places Fruit on the outermost branches (the trunk if there are no branch levels), `fruit.count`
1035
+ * per branch (a fraction = a chance of one more). `random` is the Generator's `fork('fruit')`: each Fruit draws from its own
1036
+ * `random.fork(fruitId)`, so Fruit never shifts the branches or leaves (ADR 0006).
1037
+ */
1038
+ function placeFruit(definition, branches, random) {
1039
+ const { fruit } = definition;
1040
+ if (!fruit || fruit.count === 0) return [];
1041
+ const outermost = definition.branches.length;
1042
+ const half = definition.variation.color / 2;
1043
+ const tintRandom = random.fork("tint");
1044
+ const treeTint = [
1045
+ 0,
1046
+ 1,
1047
+ 2
1048
+ ].map(() => tintRandom.range(-half, half));
1049
+ const tilt = FRUIT_TILT * DEG$2;
1050
+ const down = [
1051
+ 0,
1052
+ -1,
1053
+ 0
1054
+ ];
1055
+ const whole = Math.floor(fruit.count);
1056
+ const chance = fruit.count - whole;
1057
+ const out = [];
1058
+ for (const branch of branches) {
1059
+ if (branch.level !== outermost) continue;
1060
+ const count = whole + (chance > 0 && random.fork(`${branch.path}/chance`).next() < chance ? 1 : 0);
1061
+ if (count === 0) continue;
1062
+ const frames = branchFrames(branch);
1063
+ for (let i = 0; i < count; i++) {
1064
+ const id = `${branch.path}/${i}`;
1065
+ const r = random.fork(id);
1066
+ const t = FRUIT_START + .7 * (i + r.range(.1, .9)) / count;
1067
+ const at = sampleBranch(branch, frames, t);
1068
+ const azimuth = r.range(0, Math.PI * 2);
1069
+ const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin$1(azimuth)));
1070
+ const hanging = lerp(normalize(add(scale(at.tangent, cos(tilt)), scale(across, sin$1(tilt)))), down, fruit.hang);
1071
+ const direction = length(hanging) > .001 ? normalize(hanging) : across;
1072
+ const side0 = cross$1(direction, [
1073
+ 0,
1074
+ 1,
1075
+ 0
1076
+ ]);
1077
+ const normal = dot$1(side0, side0) > 1e-6 ? normalize(cross$1(normalize(side0), direction)) : perpendicular(direction);
1078
+ const size = fruit.size * (1 + r.range(-fruit.sizeVariation, fruit.sizeVariation));
1079
+ const brightness = r.range(-half, half);
1080
+ const tint = treeTint.map((c) => 1 + c + brightness);
1081
+ out.push({
1082
+ id,
1083
+ branch: branch.path,
1084
+ index: i,
1085
+ attach: t,
1086
+ position: at.position,
1087
+ direction,
1088
+ normal,
1089
+ size,
1090
+ tint
1091
+ });
1092
+ }
1093
+ }
1094
+ return out;
1095
+ }
1096
+ /**
1097
+ * When each Fruit grows: only at the very end of Growth (from about {@link FRUIT_GROWTH_START},
1098
+ * never before its twig is fully grown), so a sapling bears none. Computed apart from the other
1099
+ * parts' timing, so Fruit never shifts the Growth of wood or leaves.
1100
+ */
1101
+ function fruitGrowth(seed, fruit, twigGrowth) {
1102
+ return fruit.map((f) => {
1103
+ const from = FRUIT_GROWTH_START + seedRandom(seed, `growth/fruit/${f.id}`) * FRUIT_GROWTH_JITTER;
1104
+ return {
1105
+ start: Math.min(Math.max(from, twigGrowth.get(f.branch)?.end ?? 0), 1),
1106
+ end: 1
1107
+ };
1108
+ });
1109
+ }
1110
+ /**
1111
+ * Fruit geometry: one small solid per Fruit from its Fruit Type's template, hanging from its
1112
+ * attachment point. Vertex colours carry the Seed's tint; `aSeason` = (timing shift, fruit rank, 0);
1113
+ * it sways with its twig at the attachment point (no leaf flutter).
1114
+ */
1115
+ function fruitGeometry(fruit, { type, sides }, level, seed, variation, growth, branchSway) {
1116
+ if (fruit.length === 0) return emptyGeometry();
1117
+ return solidGeometry(fruitTemplate(type, sides), fruit, (f, i) => {
1118
+ const twig = branchSway.get(f.branch) ?? NO_SWAY;
1119
+ return {
1120
+ level,
1121
+ attach: f.attach,
1122
+ random: seedRandom(seed, `fruit/${f.id}`),
1123
+ origin: f.position,
1124
+ season: fruitSeasonAttribute(seed, variation, f.id),
1125
+ growth: growth[i] ?? {
1126
+ start: 0,
1127
+ end: 0
1128
+ },
1129
+ sway: {
1130
+ base: twig.base + twig.gain * f.attach,
1131
+ gain: 0,
1132
+ flutter: false
1133
+ }
1134
+ };
1135
+ });
1136
+ }
1137
+ /** Empty geometry buffers (a tree without Fruit). */
1138
+ function emptyGeometry() {
1139
+ return {
1140
+ positions: /* @__PURE__ */ new Float32Array(0),
1141
+ normals: /* @__PURE__ */ new Float32Array(0),
1142
+ uvs: /* @__PURE__ */ new Float32Array(0),
1143
+ colors: /* @__PURE__ */ new Float32Array(0),
1144
+ indices: /* @__PURE__ */ new Uint32Array(0),
1145
+ attributes: createAttributes(0)
1146
+ };
1147
+ }
1148
+ /** A solid of revolution around z: rings of `sides` vertices at (z, radius), closed by a point at each end. */
1149
+ function lathe(profile, sides, ends, twist = 0) {
1150
+ const positions = [[
1151
+ 0,
1152
+ 0,
1153
+ ends[0]
1154
+ ], [
1155
+ 0,
1156
+ 0,
1157
+ ends[1]
1158
+ ]];
1159
+ const normals = [[
1160
+ 0,
1161
+ 0,
1162
+ -1
1163
+ ], [
1164
+ 0,
1165
+ 0,
1166
+ 1
1167
+ ]];
1168
+ const triangles = [];
1169
+ profile.forEach(([z, r], ring) => {
1170
+ for (let s = 0; s < sides; s++) {
1171
+ const angle = (s + ring * twist) / sides * Math.PI * 2;
1172
+ const radial = [
1173
+ cos(angle),
1174
+ sin$1(angle),
1175
+ 0
1176
+ ];
1177
+ positions.push([
1178
+ radial[0] * r,
1179
+ radial[1] * r,
1180
+ z
1181
+ ]);
1182
+ normals.push(radial);
1183
+ }
1184
+ });
1185
+ const at = (ring, s) => 2 + ring * sides + s % sides;
1186
+ for (let s = 0; s < sides; s++) {
1187
+ triangles.push([
1188
+ 0,
1189
+ at(0, s),
1190
+ at(0, s + 1)
1191
+ ]);
1192
+ for (let ring = 0; ring < profile.length - 1; ring++) triangles.push([
1193
+ at(ring, s),
1194
+ at(ring + 1, s),
1195
+ at(ring + 1, s + 1)
1196
+ ], [
1197
+ at(ring, s),
1198
+ at(ring + 1, s + 1),
1199
+ at(ring, s + 1)
1200
+ ]);
1201
+ triangles.push([
1202
+ 1,
1203
+ at(profile.length - 1, s + 1),
1204
+ at(profile.length - 1, s)
1205
+ ]);
1206
+ }
1207
+ return orient({
1208
+ positions,
1209
+ normals,
1210
+ triangles
1211
+ });
1212
+ }
1213
+ /** Chestnut husk: a ball (icosphere, diameter 0.8) with a spike at each of the icosahedron's 12 corners. */
1214
+ function nutTemplate() {
1215
+ const ico = clumpTemplate();
1216
+ const centre = [
1217
+ 0,
1218
+ 0,
1219
+ .5
1220
+ ];
1221
+ const directions = ico.positions.map((p) => normalize([
1222
+ p[0],
1223
+ p[1],
1224
+ p[2] - .5
1225
+ ]));
1226
+ const midpoints = /* @__PURE__ */ new Map();
1227
+ const midpoint = (a, b) => {
1228
+ const key = a < b ? `${a}-${b}` : `${b}-${a}`;
1229
+ let index = midpoints.get(key);
1230
+ if (index === void 0) {
1231
+ index = directions.push(normalize(add(directions[a], directions[b]))) - 1;
1232
+ midpoints.set(key, index);
1233
+ }
1234
+ return index;
1235
+ };
1236
+ const triangles = ico.triangles.flatMap(([a, b, c]) => {
1237
+ const [ab, bc, ca] = [
1238
+ midpoint(a, b),
1239
+ midpoint(b, c),
1240
+ midpoint(c, a)
1241
+ ];
1242
+ return [
1243
+ [
1244
+ a,
1245
+ ab,
1246
+ ca
1247
+ ],
1248
+ [
1249
+ b,
1250
+ bc,
1251
+ ab
1252
+ ],
1253
+ [
1254
+ c,
1255
+ ca,
1256
+ bc
1257
+ ],
1258
+ [
1259
+ ab,
1260
+ bc,
1261
+ ca
1262
+ ]
1263
+ ];
1264
+ });
1265
+ return orient({
1266
+ positions: directions.map((d, i) => add(centre, scale(d, i < 12 ? .5 : .36))),
1267
+ normals: directions,
1268
+ triangles
1269
+ });
1270
+ }
1271
+ /** Each Fruit Type's smooth profile (z, radius) along its axis, and its end points. */
1272
+ var PROFILES = {
1273
+ round: {
1274
+ rings: [
1275
+ [.04, .22],
1276
+ [.2, .44],
1277
+ [.45, .5],
1278
+ [.7, .45],
1279
+ [.9, .28]
1280
+ ],
1281
+ ends: [.1, 1]
1282
+ },
1283
+ pear: {
1284
+ rings: [
1285
+ [.08, .1],
1286
+ [.25, .18],
1287
+ [.45, .3],
1288
+ [.65, .4],
1289
+ [.82, .38],
1290
+ [.95, .2]
1291
+ ],
1292
+ ends: [0, 1]
1293
+ },
1294
+ cone: {
1295
+ rings: [
1296
+ [.08, .2],
1297
+ [.22, .32],
1298
+ [.38, .36],
1299
+ [.54, .34],
1300
+ [.7, .28],
1301
+ [.86, .18]
1302
+ ],
1303
+ ends: [0, 1],
1304
+ twist: .5
1305
+ },
1306
+ berry: {
1307
+ rings: [
1308
+ [.15, .36],
1309
+ [.5, .5],
1310
+ [.85, .36]
1311
+ ],
1312
+ ends: [0, 1]
1313
+ }
1314
+ };
1315
+ /** Coarse profiles (low detail): two rings (berry one), a few flat facets. */
1316
+ var COARSE = {
1317
+ round: [[.28, .48], [.72, .42]],
1318
+ pear: [[.3, .2], [.75, .4]],
1319
+ cone: [[.25, .32], [.65, .28]],
1320
+ berry: [[.5, .5]]
1321
+ };
1322
+ /** At or below this many sides, Fruit uses the coarse profiles (and the nut a plain icosahedron). */
1323
+ var COARSE_SIDES = 5;
1324
+ /** The default templates: each Fruit Type's own sides (Definitions without `fruit.sides`). */
1325
+ var DEFAULT_SIDES = {
1326
+ round: 8,
1327
+ pear: 8,
1328
+ cone: 7,
1329
+ berry: 6
1330
+ };
1331
+ var templates = /* @__PURE__ */ new Map();
1332
+ /** The template of a Fruit Type drawn with `sides` faces around (absent = the Type's own detail), cached. */
1333
+ function fruitTemplate(type, sides) {
1334
+ const key = `${type}/${sides ?? ""}`;
1335
+ let template = templates.get(key);
1336
+ if (!template) {
1337
+ const coarse = sides !== void 0 && sides <= COARSE_SIDES;
1338
+ if (type === "nut") template = coarse ? coarseNutTemplate() : nutTemplate();
1339
+ else {
1340
+ const { rings, ends, twist } = PROFILES[type];
1341
+ template = lathe(coarse ? COARSE[type] : rings, sides ?? DEFAULT_SIDES[type], ends, twist);
1342
+ }
1343
+ templates.set(key, template);
1344
+ }
1345
+ return template;
1346
+ }
1347
+ /** Low-detail chestnut husk: an icosahedron (its corners are the spikes). */
1348
+ function coarseNutTemplate() {
1349
+ const ico = clumpTemplate();
1350
+ const directions = ico.positions.map((p) => normalize([
1351
+ p[0],
1352
+ p[1],
1353
+ p[2] - .5
1354
+ ]));
1355
+ return orient({
1356
+ positions: directions.map((d) => add([
1357
+ 0,
1358
+ 0,
1359
+ .5
1360
+ ], scale(d, .45))),
1361
+ normals: directions,
1362
+ triangles: ico.triangles
1363
+ });
1364
+ }
1365
+ // src/generator/growth.ts
1366
+ /** Delay of a branch after its parent is grown, per unit of `attach` (lower branches sprout first). */
1367
+ var BRANCH_STAGGER = .6;
1368
+ /** Time a branch takes from sprouting to full size. */
1369
+ var BRANCH_DURATION = 1;
1370
+ /** Leaves wait this long after their branch is grown ... */
1371
+ var LEAF_DELAY = .3;
1372
+ /** ... plus this much per unit of `attach` (leaves near the base first) ... */
1373
+ var LEAF_STAGGER = .5;
1374
+ /** ... and take this long to unfold. */
1375
+ var LEAF_DURATION = .6;
1376
+ /**
1377
+ * When each part grows, as Growth windows (0..1) parallel to the skeleton arrays.
1378
+ *
1379
+ * Order: the trunk is there from Growth 0 (it only scales with the whole tree); a branch sprouts
1380
+ * once its parent is fully grown, lower branches first; leaves come after their branch. So a part
1381
+ * always sprouts from a fully-grown parent and never floats. The last part finishes at Growth 1.
1382
+ *
1383
+ * Seed (within `variation.growth` = v): each part's start is delayed by up to v/2 of its own window
1384
+ * (its end stays put, so the order above holds), and the whole timeline is warped by `t^k`,
1385
+ * k in 1 ± v (a monotone map that keeps 0 and 1). Together a window moves by less than v.
1386
+ */
1387
+ function growthTiming(definition, seed, branches, leaves) {
1388
+ const raw = /* @__PURE__ */ new Map();
1389
+ const branchWindows = branches.map((branch) => {
1390
+ let window = {
1391
+ start: 0,
1392
+ end: 0
1393
+ };
1394
+ if (branch.parent !== null) {
1395
+ const start = raw.get(branch.parent).end + branch.attach * BRANCH_STAGGER;
1396
+ window = {
1397
+ start,
1398
+ end: start + BRANCH_DURATION
1399
+ };
1400
+ }
1401
+ raw.set(branch.path, window);
1402
+ return window;
1403
+ });
1404
+ const leafWindows = leaves.map((leaf) => {
1405
+ const start = raw.get(leaf.branch).end + LEAF_DELAY + leaf.attach * LEAF_STAGGER;
1406
+ return {
1407
+ start,
1408
+ end: start + LEAF_DURATION
1409
+ };
1410
+ });
1411
+ const total = Math.max(0, ...branchWindows.map((w) => w.end), ...leafWindows.map((w) => w.end));
1412
+ const v = definition.variation.growth;
1413
+ const k = 1 + (2 * seedRandom(seed, "growth") - 1) * v;
1414
+ const warp = (t) => total > 0 ? pow(Math.min(1, t / total), k) : 0;
1415
+ const finish = (w, key) => {
1416
+ const delay = seedRandom(seed, `growth/${key}`) * (v / 2) * (w.end - w.start);
1417
+ return {
1418
+ start: warp(w.start + delay),
1419
+ end: warp(w.end)
1420
+ };
1421
+ };
1422
+ return {
1423
+ branches: branchWindows.map((w, i) => finish(w, branches[i].path)),
1424
+ leaves: leafWindows.map((w, i) => finish(w, leaves[i].id))
1425
+ };
1426
+ }
1449
1427
  // src/generator/leaves.ts
1450
- var DEG = Math.PI / 180;
1428
+ var DEG$1 = Math.PI / 180;
1451
1429
  /** Leaf card width as a fraction of its length. */
1452
1430
  var LEAF_WIDTH = .5;
1453
1431
  /**
@@ -1467,7 +1445,7 @@ function placeLeaves(definition, branches, random) {
1467
1445
  1,
1468
1446
  2
1469
1447
  ].map(() => tintRandom.range(-half, half));
1470
- const tilt = Math.min(leaves.angle, 180) * DEG;
1448
+ const tilt = Math.min(leaves.angle, 180) * DEG$1;
1471
1449
  const out = [];
1472
1450
  for (const branch of branches) {
1473
1451
  if (branch.level !== outermost) continue;
@@ -1755,9 +1733,42 @@ function eulerXYZ([x, y, z]) {
1755
1733
  ];
1756
1734
  }
1757
1735
  // src/generator/trunk.ts
1758
- /** Builds the trunk centre line from the Definition, varied by the Seed within its ranges. */
1759
- function buildTrunk(definition, random) {
1736
+ var DEG = Math.PI / 180;
1737
+ /** The leader: the part of a Stem above this fraction of its length is what trunk gravity bends. */
1738
+ var LEADER_START = 2 / 3;
1739
+ /** How far trunk `gravity` = ±1 turns the leader over its length, degrees. */
1740
+ var LEADER_BEND = 120;
1741
+ /** Seed range of each Stem's lean: ± this fraction of `spread`. */
1742
+ var SPREAD_VARIATION = .3;
1743
+ /** Seed range of each Stem's place around the ring: ± this fraction of the gap between Stems. */
1744
+ var RING_JITTER = .25;
1745
+ /** Radius of the ring the Stems stand in, as a fraction of the trunk radius (several Stems only). */
1746
+ var RING_RADIUS = 1;
1747
+ /**
1748
+ * Builds the Stems: `trunk.stems` full trunks standing in a small ring at the base, paths "0", "1", ...
1749
+ *
1750
+ * Path stability (ADR 0003): Stem 0's centre line draws from `random.fork('trunk')` exactly as a
1751
+ * single trunk always did, Stem i > 0 from `random.fork('trunk/<i>')`; the ring and the leans come
1752
+ * from `random.fork('stems')`. So a single upright Stem without gravity is today's trunk, bit for bit.
1753
+ */
1754
+ function buildStems(definition, random) {
1760
1755
  const { trunk } = definition;
1756
+ const { stems: count = 1, spread = 0, gravity = 0 } = trunk;
1757
+ const ring = random.fork("stems");
1758
+ const turn = ring.range(0, Math.PI * 2);
1759
+ const stems = [];
1760
+ for (let i = 0; i < count; i++) {
1761
+ const r = ring.fork(i);
1762
+ const azimuth = turn + (i + r.range(-.25, RING_JITTER)) / count * Math.PI * 2;
1763
+ const tilt = Math.min(spread * (1 + r.range(-.3, SPREAD_VARIATION)), 90) * DEG;
1764
+ const offset = count > 1 ? trunk.radius * RING_RADIUS : 0;
1765
+ const line = centreLine(trunk, random.fork(i === 0 ? "trunk" : `trunk/${i}`));
1766
+ stems.push(placeStem(String(i), line, gravity, azimuth, tilt, offset));
1767
+ }
1768
+ return stems;
1769
+ }
1770
+ /** One upright, unbent Stem's centre line at the origin, varied by the Seed within the trunk's ranges. */
1771
+ function centreLine(trunk, random) {
1761
1772
  const length = trunk.length * (1 + random.range(-trunk.lengthVariation, trunk.lengthVariation));
1762
1773
  const sectionLength = length / trunk.sections;
1763
1774
  const maxDrift = trunk.bend * sectionLength;
@@ -1779,19 +1790,67 @@ function buildTrunk(definition, random) {
1779
1790
  radius: trunk.radius * (1 + (trunk.taper - 1) * t)
1780
1791
  });
1781
1792
  }
1793
+ return points;
1794
+ }
1795
+ /**
1796
+ * Bends the leader by `gravity`, leans the Stem `tilt` radians out towards `azimuth` and moves its
1797
+ * base `offset` out along the ring. All bending happens in the vertical plane towards `azimuth`.
1798
+ */
1799
+ function placeStem(path, line, gravity, azimuth, tilt, offset) {
1800
+ const out = [
1801
+ cos(azimuth),
1802
+ 0,
1803
+ sin$1(azimuth)
1804
+ ];
1805
+ const axis = cross$1([
1806
+ 0,
1807
+ 1,
1808
+ 0
1809
+ ], out);
1810
+ let points = line;
1811
+ if (gravity !== 0) {
1812
+ const sections = line.length - 1;
1813
+ const first = Math.min(sections - 1, Math.ceil(LEADER_START * sections));
1814
+ const step = -gravity * LEADER_BEND * DEG / (sections - first);
1815
+ let bend = 0;
1816
+ points = line.slice(0, first + 1);
1817
+ for (let k = first; k < sections; k++) {
1818
+ bend = Math.min(Math.max(bend + step, -tilt), Math.PI - tilt);
1819
+ const segment = sub(line[k + 1].position, line[k].position);
1820
+ points.push({
1821
+ position: add(points[k].position, rotate$1(segment, axis, bend)),
1822
+ radius: line[k + 1].radius
1823
+ });
1824
+ }
1825
+ }
1826
+ if (tilt !== 0) points = points.map((p) => ({
1827
+ position: rotate$1(p.position, axis, tilt),
1828
+ radius: p.radius
1829
+ }));
1830
+ if (offset !== 0) points = points.map((p) => ({
1831
+ position: add(p.position, scale(out, offset)),
1832
+ radius: p.radius
1833
+ }));
1782
1834
  return {
1783
- path: "0",
1835
+ path,
1784
1836
  parent: null,
1785
1837
  level: 0,
1786
1838
  attach: 0,
1787
- direction: [
1839
+ direction: rotate$1([
1788
1840
  0,
1789
1841
  1,
1790
1842
  0
1791
- ],
1843
+ ], axis, tilt),
1792
1844
  points
1793
1845
  };
1794
1846
  }
1847
+ /** Rotates `v` about the unit `axis` by `angle` radians (Rodrigues). */
1848
+ function rotate$1(v, axis, angle) {
1849
+ if (angle === 0) return v;
1850
+ const c = cos(angle);
1851
+ const s = sin$1(angle);
1852
+ return add(add(scale(v, c), scale(cross$1(axis, v), s)), scale(axis, dot$1(axis, v) * (1 - c)));
1853
+ }
1795
1854
  // src/generator/index.ts
1796
1855
  /**
1797
1856
  * The Generator: a pure function from a (parsed) Tree Definition and a Seed to tree data.
@@ -1802,44 +1861,55 @@ function buildTrunk(definition, random) {
1802
1861
  */
1803
1862
  function generateTree(definition, seed) {
1804
1863
  const random = createRandom(seed);
1805
- const trunk = buildTrunk(definition, random.fork("trunk"));
1864
+ const stems = buildStems(definition, random);
1806
1865
  const sculpts = sculptsFor(definition, seed);
1807
- const branches = sculptBranches([trunk, ...buildBranches(definition, trunk, random.fork("branches"))], sculpts);
1866
+ const branches = sculptBranches([...stems, ...buildBranches(definition, stems, random.fork("branches"))], sculpts);
1808
1867
  const sidesOf = (level) => level === 0 ? definition.trunk.sides : definition.branches[level - 1].sides;
1809
1868
  const leaves = sculptLeaves(placeLeaves(definition, branches, random.fork("leaves")), sculpts, seed);
1810
- const growth = growthTiming(definition, seed, branches, leaves);
1869
+ const fruit = placeFruit(definition, branches, random.fork("fruit"));
1870
+ const partGrowth = growthTiming(definition, seed, branches, leaves);
1871
+ const growth = {
1872
+ ...partGrowth,
1873
+ fruit: fruitGrowth(seed, fruit, new Map(branches.map((b, i) => [b.path, partGrowth.branches[i]])))
1874
+ };
1811
1875
  const sway = branchSway(branches, definition.branches.length);
1812
1876
  const wood = mergeBuffers(branches.map((b, i) => sweepBranch(b, sidesOf(b.level), seedRandom(seed, b.path), woodSeasonAttribute(seed, definition.variation), growth.branches[i], sway.get(b.path))));
1813
1877
  const leafBuffers = definition.leaves.shape === "card" ? leafGeometry(leaves, definition.branches.length + 1, seed, definition.variation, growth.leaves, sway) : solidLeafGeometry(leaves, definition.leaves.shape, definition.branches.length + 1, seed, definition.variation, growth.leaves, sway);
1878
+ const fruitBuffers = fruitGeometry(fruit, definition.fruit ?? { type: "round" }, definition.branches.length + 2, seed, definition.variation, growth.fruit, sway);
1814
1879
  const skeleton = {
1815
1880
  branches,
1816
- leaves
1881
+ leaves,
1882
+ fruit
1817
1883
  };
1818
1884
  writeTrunkSway(wood, trunkHeight(skeleton));
1819
1885
  writeTrunkSway(leafBuffers, trunkHeight(skeleton));
1886
+ writeTrunkSway(fruitBuffers, trunkHeight(skeleton));
1820
1887
  return {
1821
1888
  seed,
1822
1889
  skeleton,
1823
1890
  wood,
1824
1891
  leaves: leafBuffers,
1892
+ fruit: fruitBuffers,
1825
1893
  growth
1826
1894
  };
1827
1895
  }
1828
1896
  /**
1829
- * Height of the (possibly Sculpted) trunk's tip: the scale of a tree's Wind sway. A Sculpt may
1830
- * delete the trunk (an empty tree, nothing sways); the height is then 1.
1897
+ * Height of the tallest (possibly Sculpted) Stem: the scale of a tree's Wind sway. For an upright
1898
+ * trunk that is its tip. A Sculpt may delete every Stem (an empty tree, nothing sways); it is then 1.
1831
1899
  */
1832
1900
  function trunkHeight(skeleton) {
1833
- const trunk = skeleton.branches.find((b) => b.parent === null)?.points;
1834
- return trunk ? trunk[trunk.length - 1].position[1] : 1;
1901
+ const stems = skeleton.branches.filter((b) => b.parent === null);
1902
+ if (stems.length === 0) return 1;
1903
+ return Math.max(...stems.flatMap((stem) => stem.points.map((p) => p.position[1])));
1835
1904
  }
1836
1905
  /** Stable 32-bit hash (hex) of the generated geometry buffers, for determinism checks. */
1837
1906
  function hashGeometry(geometry) {
1838
1907
  return hex(hashBuffers(geometry));
1839
1908
  }
1840
- /** Stable hash of a tree's generated geometry (wood and leaves). */
1909
+ /** Stable hash of a tree's generated geometry (wood, leaves and, if any, Fruit). */
1841
1910
  function hashTreeData(data) {
1842
- return hex(hashBuffers(data.leaves, hashBuffers(data.wood)));
1911
+ const h = hashBuffers(data.leaves, hashBuffers(data.wood));
1912
+ return hex(data.fruit.positions.length > 0 ? hashBuffers(data.fruit, h) : h);
1843
1913
  }
1844
1914
  function hashBuffers(geometry, h) {
1845
1915
  const arrays = [
@@ -2146,6 +2216,23 @@ function createLeafMaterial(definition, textures) {
2146
2216
  applyLeafMap(material, definition.materials.leaf, textures);
2147
2217
  return material;
2148
2218
  }
2219
+ /**
2220
+ * Fruit material: the Definition's shading (flat facets in low-poly, smooth toon in stylized,
2221
+ * smooth PBR in realistic), no textures. `.color` is the Fruit colour at Season 0; `Tree` sets the
2222
+ * Season colour (`createFruitSeasonNodes`), multiplied by the per-Fruit vertex colours (the Seed's tint).
2223
+ */
2224
+ function createFruitMaterial(definition) {
2225
+ const material = createShadedMaterial(definition.materials.shading);
2226
+ material.name = "tree.js fruit";
2227
+ material.userData.treePart = "fruit";
2228
+ material.color.set(fruitTracks(definition.season).fruitColor[0].value);
2229
+ material.vertexColors = true;
2230
+ material.roughness = FRUIT_ROUGHNESS;
2231
+ material.metalness = 0;
2232
+ return material;
2233
+ }
2234
+ /** Fruit skin is a little glossier than leaves. */
2235
+ var FRUIT_ROUGHNESS = .45;
2149
2236
  // src/renderer/index.ts
2150
2237
  /** Thrown when a tree is drawn by anything other than `WebGPURenderer` (ADR 0002). */
2151
2238
  var UnsupportedRendererError = class extends Error {
@@ -2178,8 +2265,7 @@ function keyframeNode(s, track, toUniform) {
2178
2265
  }
2179
2266
  function createSeasonNodes(profile, season = uniform(0)) {
2180
2267
  const aSeason = attribute("aSeason", "vec3");
2181
- const shifted = season.add(aSeason.x);
2182
- const s = select(shifted.greaterThan(1).or(shifted.lessThan(0)), fract(shifted), shifted);
2268
+ const s = shiftedSeason$1(season, aSeason);
2183
2269
  const leafColor = keyframeNode(s, profile.leafColor, (v) => uniform(new Color(v)));
2184
2270
  const coverage = keyframeNode(s, profile.leafCoverage, (v) => uniform(v));
2185
2271
  const blossom = keyframeNode(s, profile.blossom, (v) => uniform(v));
@@ -2192,6 +2278,30 @@ function createSeasonNodes(profile, season = uniform(0)) {
2192
2278
  visible: varying(select(shown, float(1), float(0))).greaterThan(.5)
2193
2279
  };
2194
2280
  }
2281
+ /** The part's own Season: the Season input plus the `aSeason.x` timing shift, wrapped around the year (as `wrapSeason`). */
2282
+ function shiftedSeason$1(season, aSeason) {
2283
+ const shifted = season.add(aSeason.x);
2284
+ return select(shifted.greaterThan(1).or(shifted.lessThan(0)), fract(shifted), shifted);
2285
+ }
2286
+ /**
2287
+ * Builds the TSL nodes that evaluate the Season Profile's Fruit tracks per Fruit, from the fruit
2288
+ * mesh's `aSeason` (timing shift, Fruit rank). The TSL twin of `fruitSeason`: a Fruit shows while
2289
+ * the Fruit amount is above its rank and swells with the amount. `season` is the Season input
2290
+ * (share the leaves' uniform so one write drives both).
2291
+ */
2292
+ function createFruitSeasonNodes(profile, season, position = positionLocal) {
2293
+ const aSeason = attribute("aSeason", "vec3");
2294
+ const origin = attribute("aOrigin", "vec3");
2295
+ const s = shiftedSeason$1(season, aSeason);
2296
+ const tracks = fruitTracks(profile);
2297
+ const amount = keyframeNode(s, tracks.fruit, (v) => uniform(v));
2298
+ const scale = select(amount.greaterThan(aSeason.y), amount, float(0));
2299
+ return {
2300
+ color: varying(keyframeNode(s, tracks.fruitColor, (v) => uniform(new Color(v)))),
2301
+ scale,
2302
+ position: origin.add(position.sub(origin).mul(scale))
2303
+ };
2304
+ }
2195
2305
  /**
2196
2306
  * Hooks Season into a leaf material: `colorNode` (times the vertex-colour tint, and times the
2197
2307
  * material's existing `colorNode`, such as a leaf card texture with alpha) and `maskNode`, which
@@ -2439,9 +2549,11 @@ var Tree = class extends Group {
2439
2549
  wood;
2440
2550
  /** Leaf cards (empty geometry for a bare tree). */
2441
2551
  leaves;
2442
- /** This tree's Growth uniform (read by the wood and leaf materials' `positionNode`). */
2552
+ /** Fruit (empty geometry when the Definition has no Fruit). */
2553
+ fruit;
2554
+ /** This tree's Growth uniform (read by the wood, leaf and Fruit materials' `positionNode`). */
2443
2555
  growthUniform;
2444
- /** The Season uniform the leaf material reads (shared nodes may reference it). */
2556
+ /** The Season uniform the leaf and Fruit materials read (shared nodes may reference it). */
2445
2557
  seasonUniform;
2446
2558
  /** This tree's response to the Wind, from `definition.wind`; `windResponse.set(...)` changes it live. */
2447
2559
  windResponse;
@@ -2471,7 +2583,9 @@ var Tree = class extends Group {
2471
2583
  ].filter((t) => t !== null);
2472
2584
  this.ready = Promise.all(textures.map(textureReady)).then(() => void 0);
2473
2585
  this.ready.catch(() => {});
2474
- this.add(this.wood, this.leaves);
2586
+ const fruit = createFruitMaterial(definition);
2587
+ this.fruit = treeMesh("fruit", toBufferGeometry(data.fruit), fruit);
2588
+ this.add(this.wood, this.leaves, this.fruit);
2475
2589
  this.windBinding = new WindBinding(options.wind ?? sceneWind);
2476
2590
  this.windResponse = new WindResponse(definition.wind, {
2477
2591
  height: trunkHeight(data.skeleton),
@@ -2483,6 +2597,10 @@ var Tree = class extends Group {
2483
2597
  const season = createSeasonNodes(definition.season);
2484
2598
  applySeasonToLeafMaterial(this.leaves.material, season);
2485
2599
  this.seasonUniform = season.season;
2600
+ const fruitSeason = createFruitSeasonNodes(definition.season, this.seasonUniform);
2601
+ fruit.colorNode = fruitSeason.color;
2602
+ fruit.positionNode = growthPosition(this.growthUniform, fruitSeason.position);
2603
+ applyWind(fruit, offset);
2486
2604
  this.season = options.season ?? 0;
2487
2605
  }
2488
2606
  /**
@@ -2496,8 +2614,8 @@ var Tree = class extends Group {
2496
2614
  this.windBinding.wind = value;
2497
2615
  }
2498
2616
  /**
2499
- * Season: 0 (first day of spring) .. 1 (last day of winter); sets leaf colour, leaf coverage
2500
- * and blossom from the Definition's Season Profile. Values outside 0..1 wrap around the year.
2617
+ * Season: 0 (first day of spring) .. 1 (last day of winter); sets leaf colour, leaf coverage,
2618
+ * blossom and Fruit (amount, size, colour) from the Definition's Season Profile. Values outside 0..1 wrap around the year.
2501
2619
  * Only updates a uniform, so it is cheap to animate.
2502
2620
  */
2503
2621
  get season() {
@@ -2547,15 +2665,14 @@ function createTree(definition, options = {}) {
2547
2665
  // src/styles/registry.ts
2548
2666
  /**
2549
2667
  * The built-in Styles, each a lazily loaded chunk (`@casmo/tree.js/styles/<name>`).
2550
- * To add a Style: one line here (plus its vite entry and package.json export).
2668
+ * To add a Style: its name, label and shading in names.ts, its loader here, its look in apply.ts
2669
+ * (plus its vite entry and package.json export). The editor and the scripts read these lists.
2551
2670
  */
2552
2671
  var STYLE_LOADERS = {
2553
2672
  "low-poly": () => import("./styles/low-poly.js"),
2554
2673
  stylized: () => import("./styles/stylized.js"),
2555
2674
  realistic: () => import("./styles/realistic.js")
2556
2675
  };
2557
- /** Names of all built-in Styles. */
2558
- var STYLE_NAMES = Object.keys(STYLE_LOADERS);
2559
2676
  /** Downloads a built-in Style (dynamic import) and resolves to it. Rejects for an unknown name. */
2560
2677
  async function loadStyle(name) {
2561
2678
  const load = STYLE_LOADERS[name];
@@ -2593,10 +2710,13 @@ function rotate(v, inverse = false) {
2593
2710
  * `positionGeometry`, and only their displacement is turned into forest space with the
2594
2711
  * instance rotation and scale: M·(p + d) = M·p + R·s·d. The Wind direction goes the other way
2595
2712
  * (forest -> tree space) and each tree sways with its own phase.
2713
+ *
2714
+ * `base`: the tree-space position Growth starts from (default `positionGeometry`); Fruit passes
2715
+ * its Season-scaled position here.
2596
2716
  */
2597
- function forestPosition(wind, response) {
2717
+ function forestPosition(wind, response, base = positionGeometry) {
2598
2718
  const { scale, growth, windPhase } = instanceState();
2599
- const grown = growthPosition(growth, positionGeometry);
2719
+ const grown = growthPosition(growth, base);
2600
2720
  const offset = windOffset(wind, response, {
2601
2721
  direction: rotate(objectWindDirection(wind), true),
2602
2722
  phase: windPhase
@@ -2764,7 +2884,8 @@ function shareGeometry(source) {
2764
2884
  }
2765
2885
  /**
2766
2886
  * One Variant of a Forest: one Seed's tree, drawn once per tree that uses it with an instanced
2767
- * wood mesh and an instanced leaf mesh (one draw call per material).
2887
+ * wood mesh, an instanced leaf mesh and, when the Definition has Fruit, an instanced fruit mesh
2888
+ * (one draw call per material). All three share one instance matrix buffer.
2768
2889
  */
2769
2890
  var ForestVariant = class {
2770
2891
  forest;
@@ -2775,13 +2896,17 @@ var ForestVariant = class {
2775
2896
  windResponse;
2776
2897
  barkMaterial;
2777
2898
  leafMaterial;
2899
+ /** Fruit material, null when the Definition has no Fruit. */
2900
+ fruitMaterial;
2778
2901
  /** The trees drawn as this Variant, in instance order. */
2779
2902
  trees = [];
2780
2903
  woodMesh;
2781
2904
  leafMesh;
2905
+ fruitMesh = null;
2782
2906
  instanceData;
2783
2907
  woodSource;
2784
2908
  leafSource;
2909
+ fruitSource;
2785
2910
  constructor(forest, definition, index, seed, wind, capacity, textures) {
2786
2911
  this.forest = forest;
2787
2912
  this.index = index;
@@ -2800,6 +2925,16 @@ var ForestVariant = class {
2800
2925
  applySeasonToLeafMaterial(this.leafMaterial, createSeasonNodes(definition.season, instanceState().season));
2801
2926
  this.woodSource = interleavedGeometry(this.data.wood, height * WIND_BOUNDS);
2802
2927
  this.leafSource = interleavedGeometry(this.data.leaves, height * WIND_BOUNDS);
2928
+ if (this.data.fruit.indices.length > 0) {
2929
+ const fruitSeason = createFruitSeasonNodes(definition.season, instanceState().season, positionGeometry);
2930
+ this.fruitMaterial = createFruitMaterial(definition);
2931
+ this.fruitMaterial.colorNode = fruitSeason.color;
2932
+ this.fruitMaterial.positionNode = forestPosition(wind, this.windResponse, fruitSeason.position);
2933
+ this.fruitSource = interleavedGeometry(this.data.fruit, height * WIND_BOUNDS);
2934
+ } else {
2935
+ this.fruitMaterial = null;
2936
+ this.fruitSource = null;
2937
+ }
2803
2938
  this.allocate(capacity);
2804
2939
  }
2805
2940
  /** Instanced mesh of trunks and branches. Replaced (not resized) when the Variant outgrows its capacity. */
@@ -2810,6 +2945,18 @@ var ForestVariant = class {
2810
2945
  get leaves() {
2811
2946
  return this.leafMesh;
2812
2947
  }
2948
+ /** Instanced mesh of the Fruit (null when the Definition has no Fruit). Replaced along with {@link wood}. */
2949
+ get fruit() {
2950
+ return this.fruitMesh;
2951
+ }
2952
+ /** The Variant's meshes: wood, leaves and (with Fruit) fruit. */
2953
+ get meshes() {
2954
+ return this.fruitMesh ? [
2955
+ this.woodMesh,
2956
+ this.leafMesh,
2957
+ this.fruitMesh
2958
+ ] : [this.woodMesh, this.leafMesh];
2959
+ }
2813
2960
  get capacity() {
2814
2961
  return this.instanceData.count;
2815
2962
  }
@@ -2853,8 +3000,7 @@ var ForestVariant = class {
2853
3000
  tree.windPhase
2854
3001
  ], i * 8);
2855
3002
  this.instanceData.needsUpdate = true;
2856
- this.woodMesh.boundingSphere = this.leafMesh.boundingSphere = null;
2857
- this.woodMesh.boundingBox = this.leafMesh.boundingBox = null;
3003
+ for (const mesh of this.meshes) mesh.boundingSphere = mesh.boundingBox = null;
2858
3004
  }
2859
3005
  /** @internal */
2860
3006
  state(tree) {
@@ -2871,11 +3017,13 @@ var ForestVariant = class {
2871
3017
  this.disposeMeshes();
2872
3018
  this.woodSource.dispose();
2873
3019
  this.leafSource.dispose();
3020
+ this.fruitSource?.dispose();
2874
3021
  this.barkMaterial.dispose();
2875
3022
  this.leafMaterial.dispose();
3023
+ this.fruitMaterial?.dispose();
2876
3024
  }
2877
3025
  setCount() {
2878
- this.woodMesh.count = this.leafMesh.count = this.trees.length;
3026
+ for (const mesh of this.meshes) mesh.count = this.trees.length;
2879
3027
  }
2880
3028
  /**
2881
3029
  * (Re)builds the instanced meshes with room for `capacity` trees. An InstancedMesh cannot grow,
@@ -2905,11 +3053,12 @@ var ForestVariant = class {
2905
3053
  };
2906
3054
  this.woodMesh = mesh("forest wood", this.woodSource, this.barkMaterial);
2907
3055
  this.leafMesh = mesh("forest leaves", this.leafSource, this.leafMaterial);
3056
+ if (this.fruitSource && this.fruitMaterial) this.fruitMesh = mesh("forest fruit", this.fruitSource, this.fruitMaterial);
2908
3057
  this.setCount();
2909
- this.forest.add(this.woodMesh, this.leafMesh);
3058
+ this.forest.add(...this.meshes);
2910
3059
  }
2911
3060
  disposeMeshes() {
2912
- for (const mesh of [this.woodMesh, this.leafMesh]) {
3061
+ for (const mesh of this.meshes) {
2913
3062
  mesh.removeFromParent();
2914
3063
  mesh.geometry.dispose();
2915
3064
  mesh.dispose();
@@ -3008,7 +3157,7 @@ var Forest = class extends Group {
3008
3157
  }
3009
3158
  /** The tree drawn by instance `instanceId` of a Variant mesh, e.g. from a raycast intersection. */
3010
3159
  treeAt(intersection) {
3011
- const variant = this.variants.find((v) => v.wood === intersection.object || v.leaves === intersection.object);
3160
+ const variant = this.variants.find((v) => v.meshes.includes(intersection.object));
3012
3161
  return variant && intersection.instanceId !== void 0 ? variant.trees[intersection.instanceId] : void 0;
3013
3162
  }
3014
3163
  /** What the GPU draws a tree with: its Growth and Season after its offsets, and its Wind phase. */
@@ -3052,6 +3201,6 @@ var Forest = class extends Group {
3052
3201
  function createForest(definition, placements = [], options = {}) {
3053
3202
  return new Forest(parseDefinition(definition), placements, options);
3054
3203
  }
3055
- export { hashTreeData as A, srgbToLinear as B, loadTexture as C, clampGrowth as D, textureReady as E, leafSeasonAttribute as F, fetchDefinition as G, wrapSeason as H, partSeasonAt as I, DEFAULT_BRANCH_LEVEL as J, parseDefinition as K, sampleTrack as L, evaluateSeason as M, hexToLinear as N, growPositions as O, leafSeason as P, seasonShift as R, getTextureOptions as S, setTextureOptions as T, createRandom as U, woodSeasonAttribute as V, extendDefinition as W, DEFAULT_DEFINITION as Y, createBarkMaterial as _, forestTreeKey as a, BARK_REPEAT as b, createTree as c, Wind as d, sceneWind as f, assertWebGPURenderer as g, UnsupportedRendererError as h, ForestVariant as i, KEYFRAME_EPSILON as j, hashGeometry as k, Tree as l, createSeasonNodes as m, Forest as n, STYLE_NAMES as o, applySeasonToLeafMaterial as p, TreeDefinitionError as q, ForestTree as r, loadStyle as s, createForest as t, WindResponse as u, createLeafMaterial as v, resolveTextureUrl as w, DEFAULT_TEXTURE_BASE_PATH as x, isFlatShading as y, segmentWeight as z };
3204
+ export { hashTreeData as A, sampleTrack as B, loadTexture as C, clampGrowth as D, textureReady as E, fruitTracks as F, wrapSeason as G, segmentWeight as H, hexToLinear as I, createRandom as K, leafSeason as L, evaluateSeason as M, fruitSeason as N, growPositions as O, fruitSeasonAttribute as P, leafSeasonAttribute as R, getTextureOptions as S, setTextureOptions as T, srgbToLinear as U, seasonShift as V, woodSeasonAttribute as W, createBarkMaterial as _, forestTreeKey as a, BARK_REPEAT as b, Tree as c, sceneWind as d, applySeasonToLeafMaterial as f, assertWebGPURenderer as g, UnsupportedRendererError as h, ForestVariant as i, KEYFRAME_EPSILON as j, hashGeometry as k, WindResponse as l, createSeasonNodes as m, Forest as n, loadStyle as o, createFruitSeasonNodes as p, ForestTree as r, createTree as s, createForest as t, Wind as u, createLeafMaterial as v, resolveTextureUrl as w, DEFAULT_TEXTURE_BASE_PATH as x, isFlatShading as y, partSeasonAt as z };
3056
3205
 
3057
- //# sourceMappingURL=forest-OX9WvAwh.js.map
3206
+ //# sourceMappingURL=forest-DTrD8puH.js.map