@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.
- package/LICENSE +21 -0
- package/README.md +485 -2
- package/dist/bake/index.d.ts +39 -0
- package/dist/bake/index.d.ts.map +1 -0
- package/dist/definition/defaults.d.ts +9 -0
- package/dist/definition/defaults.d.ts.map +1 -0
- package/dist/definition/index.d.ts +5 -0
- package/dist/definition/index.d.ts.map +1 -0
- package/dist/definition/migrations.d.ts +12 -0
- package/dist/definition/migrations.d.ts.map +1 -0
- package/dist/definition/parse.d.ts +30 -0
- package/dist/definition/parse.d.ts.map +1 -0
- package/dist/definition/schema.d.ts +13 -0
- package/dist/definition/schema.d.ts.map +1 -0
- package/dist/definition/types.d.ts +217 -0
- package/dist/definition/types.d.ts.map +1 -0
- package/dist/effects/effects.d.ts +46 -0
- package/dist/effects/effects.d.ts.map +1 -0
- package/dist/effects/glow.d.ts +19 -0
- package/dist/effects/glow.d.ts.map +1 -0
- package/dist/effects/grade.d.ts +19 -0
- package/dist/effects/grade.d.ts.map +1 -0
- package/dist/effects/index.d.ts +7 -0
- package/dist/effects/index.d.ts.map +1 -0
- package/dist/effects/mask.d.ts +44 -0
- package/dist/effects/mask.d.ts.map +1 -0
- package/dist/effects/outline.d.ts +18 -0
- package/dist/effects/outline.d.ts.map +1 -0
- package/dist/effects/suggested.d.ts +13 -0
- package/dist/effects/suggested.d.ts.map +1 -0
- package/dist/effects.js +249 -0
- package/dist/effects.js.map +1 -0
- package/dist/forest/Forest.d.ts +156 -0
- package/dist/forest/Forest.d.ts.map +1 -0
- package/dist/forest/index.d.ts +14 -0
- package/dist/forest/index.d.ts.map +1 -0
- package/dist/forest/nodes.d.ts +31 -0
- package/dist/forest/nodes.d.ts.map +1 -0
- package/dist/forest/placement.d.ts +52 -0
- package/dist/forest/placement.d.ts.map +1 -0
- package/dist/forest-OX9WvAwh.js +3057 -0
- package/dist/forest-OX9WvAwh.js.map +1 -0
- package/dist/generator/attributes.d.ts +20 -0
- package/dist/generator/attributes.d.ts.map +1 -0
- package/dist/generator/branches.d.ts +12 -0
- package/dist/generator/branches.d.ts.map +1 -0
- package/dist/generator/frames.d.ts +21 -0
- package/dist/generator/frames.d.ts.map +1 -0
- package/dist/generator/growth.d.ts +15 -0
- package/dist/generator/growth.d.ts.map +1 -0
- package/dist/generator/index.d.ts +22 -0
- package/dist/generator/index.d.ts.map +1 -0
- package/dist/generator/leaf-shapes.d.ts +10 -0
- package/dist/generator/leaf-shapes.d.ts.map +1 -0
- package/dist/generator/leaves.d.ts +14 -0
- package/dist/generator/leaves.d.ts.map +1 -0
- package/dist/generator/mesh.d.ts +11 -0
- package/dist/generator/mesh.d.ts.map +1 -0
- package/dist/generator/sculpt.d.ts +28 -0
- package/dist/generator/sculpt.d.ts.map +1 -0
- package/dist/generator/trunk.d.ts +6 -0
- package/dist/generator/trunk.d.ts.map +1 -0
- package/dist/generator/types.d.ts +126 -0
- package/dist/generator/types.d.ts.map +1 -0
- package/dist/generator/vec.d.ts +12 -0
- package/dist/generator/vec.d.ts.map +1 -0
- package/dist/generator/wind.d.ts +27 -0
- package/dist/generator/wind.d.ts.map +1 -0
- package/dist/growth/evaluate.d.ts +32 -0
- package/dist/growth/evaluate.d.ts.map +1 -0
- package/dist/growth/index.d.ts +3 -0
- package/dist/growth/index.d.ts.map +1 -0
- package/dist/growth/tsl.d.ts +12 -0
- package/dist/growth/tsl.d.ts.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +198 -0
- package/dist/index.js.map +1 -0
- package/dist/materials/index.d.ts +18 -0
- package/dist/materials/index.d.ts.map +1 -0
- package/dist/materials/maps.d.ts +23 -0
- package/dist/materials/maps.d.ts.map +1 -0
- package/dist/materials/shading.d.ts +18 -0
- package/dist/materials/shading.d.ts.map +1 -0
- package/dist/materials/toon.d.ts +12 -0
- package/dist/materials/toon.d.ts.map +1 -0
- package/dist/math/index.d.ts +23 -0
- package/dist/math/index.d.ts.map +1 -0
- package/dist/profiles-BAiyeFlh.js +113 -0
- package/dist/profiles-BAiyeFlh.js.map +1 -0
- package/dist/random/index.d.ts +37 -0
- package/dist/random/index.d.ts.map +1 -0
- package/dist/react/Forest.d.ts +54 -0
- package/dist/react/Forest.d.ts.map +1 -0
- package/dist/react/Tree.d.ts +41 -0
- package/dist/react/Tree.d.ts.map +1 -0
- package/dist/react/Wind.d.ts +17 -0
- package/dist/react/Wind.d.ts.map +1 -0
- package/dist/react/index.d.ts +6 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/useTreeStyle.d.ts +15 -0
- package/dist/react/useTreeStyle.d.ts.map +1 -0
- package/dist/react.js +239 -0
- package/dist/react.js.map +1 -0
- package/dist/renderer/index.d.ts +7 -0
- package/dist/renderer/index.d.ts.map +1 -0
- package/dist/season/check.d.ts +3 -0
- package/dist/season/check.d.ts.map +1 -0
- package/dist/season/index.d.ts +4 -0
- package/dist/season/index.d.ts.map +1 -0
- package/dist/season/nodes.d.ts +32 -0
- package/dist/season/nodes.d.ts.map +1 -0
- package/dist/season/profile.d.ts +78 -0
- package/dist/season/profile.d.ts.map +1 -0
- package/dist/season/profiles.d.ts +40 -0
- package/dist/season/profiles.d.ts.map +1 -0
- package/dist/styles/low-poly/index.d.ts +16 -0
- package/dist/styles/low-poly/index.d.ts.map +1 -0
- package/dist/styles/low-poly.js +165 -0
- package/dist/styles/low-poly.js.map +1 -0
- package/dist/styles/realistic/index.d.ts +23 -0
- package/dist/styles/realistic/index.d.ts.map +1 -0
- package/dist/styles/realistic.js +206 -0
- package/dist/styles/realistic.js.map +1 -0
- package/dist/styles/registry.d.ts +17 -0
- package/dist/styles/registry.d.ts.map +1 -0
- package/dist/styles/stylized/index.d.ts +17 -0
- package/dist/styles/stylized/index.d.ts.map +1 -0
- package/dist/styles/stylized.js +266 -0
- package/dist/styles/stylized.js.map +1 -0
- package/dist/styles/types.d.ts +12 -0
- package/dist/styles/types.d.ts.map +1 -0
- package/dist/textures/index.d.ts +44 -0
- package/dist/textures/index.d.ts.map +1 -0
- package/dist/textures/realistic/bark-normal.png +0 -0
- package/dist/textures/realistic/bark.png +0 -0
- package/dist/textures/realistic/leaf.png +0 -0
- package/dist/textures/realistic/needles.png +0 -0
- package/dist/tree/Tree.d.ts +70 -0
- package/dist/tree/Tree.d.ts.map +1 -0
- package/dist/tree/index.d.ts +14 -0
- package/dist/tree/index.d.ts.map +1 -0
- package/dist/types-BZjHhNz7.js +20 -0
- package/dist/types-BZjHhNz7.js.map +1 -0
- package/dist/wind/Wind.d.ts +54 -0
- package/dist/wind/Wind.d.ts.map +1 -0
- package/dist/wind/index.d.ts +4 -0
- package/dist/wind/index.d.ts.map +1 -0
- package/dist/wind/node.d.ts +38 -0
- package/dist/wind/node.d.ts.map +1 -0
- package/dist/wind/response.d.ts +27 -0
- package/dist/wind/response.d.ts.map +1 -0
- package/package.json +107 -4
|
@@ -0,0 +1,3057 @@
|
|
|
1
|
+
import "./types-BZjHhNz7.js";
|
|
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
|
+
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
|
+
// src/random/index.ts
|
|
410
|
+
/**
|
|
411
|
+
* Random: the only source of randomness in tree.js.
|
|
412
|
+
*
|
|
413
|
+
* Determinism contract: the same Seed gives the same numbers on every machine
|
|
414
|
+
* and across releases within a major version. `Math.random` is never used
|
|
415
|
+
* (enforced by ESLint). Everything here is plain 32-bit integer math.
|
|
416
|
+
*/
|
|
417
|
+
var FNV_OFFSET = 2166136261;
|
|
418
|
+
var FNV_PRIME = 16777619;
|
|
419
|
+
/** FNV-1a 32-bit hash of a string (UTF-16 code units, low byte then high byte). */
|
|
420
|
+
function hashString(input) {
|
|
421
|
+
let h = FNV_OFFSET;
|
|
422
|
+
for (let i = 0; i < input.length; i++) {
|
|
423
|
+
const c = input.charCodeAt(i);
|
|
424
|
+
h ^= c & 255;
|
|
425
|
+
h = Math.imul(h, FNV_PRIME);
|
|
426
|
+
if (c > 255) {
|
|
427
|
+
h ^= c >>> 8;
|
|
428
|
+
h = Math.imul(h, FNV_PRIME);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return h >>> 0;
|
|
432
|
+
}
|
|
433
|
+
/** FNV-1a 32-bit hash over raw bytes; `h` continues a previous hash. */
|
|
434
|
+
function hashBytes(bytes, h = FNV_OFFSET) {
|
|
435
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
436
|
+
h ^= bytes[i];
|
|
437
|
+
h = Math.imul(h, FNV_PRIME);
|
|
438
|
+
}
|
|
439
|
+
return h >>> 0;
|
|
440
|
+
}
|
|
441
|
+
/** Mixes any number of 32-bit values into one well-distributed 32-bit hash. */
|
|
442
|
+
function hashCombine(...values) {
|
|
443
|
+
let h = FNV_OFFSET;
|
|
444
|
+
for (const v of values) {
|
|
445
|
+
h = Math.imul(h ^ v >>> 0, FNV_PRIME);
|
|
446
|
+
h = fmix32(h);
|
|
447
|
+
}
|
|
448
|
+
return h >>> 0;
|
|
449
|
+
}
|
|
450
|
+
/** Converts any finite number (including fractions and negatives) to a 32-bit seed. */
|
|
451
|
+
function seedToUint32(seed) {
|
|
452
|
+
if (!Number.isFinite(seed)) throw new TypeError(`Seed must be a finite number, got ${seed}`);
|
|
453
|
+
const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
|
|
454
|
+
view.setFloat64(0, seed, true);
|
|
455
|
+
return hashCombine(view.getUint32(0, true), view.getUint32(4, true));
|
|
456
|
+
}
|
|
457
|
+
function fmix32(h) {
|
|
458
|
+
h ^= h >>> 16;
|
|
459
|
+
h = Math.imul(h, 2246822507);
|
|
460
|
+
h ^= h >>> 13;
|
|
461
|
+
h = Math.imul(h, 3266489909);
|
|
462
|
+
h ^= h >>> 16;
|
|
463
|
+
return h >>> 0;
|
|
464
|
+
}
|
|
465
|
+
/** Seeded PRNG (mulberry32). */
|
|
466
|
+
function createRandom(seed) {
|
|
467
|
+
return fromState(seedToUint32(seed));
|
|
468
|
+
}
|
|
469
|
+
function fromState(origin) {
|
|
470
|
+
let state = origin;
|
|
471
|
+
const next = () => {
|
|
472
|
+
state = state + 1831565813 >>> 0;
|
|
473
|
+
let t = state;
|
|
474
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
475
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
476
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
477
|
+
};
|
|
478
|
+
return {
|
|
479
|
+
next,
|
|
480
|
+
range: (min, max) => min + (max - min) * next(),
|
|
481
|
+
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
|
|
482
|
+
fork: (key) => fromState(hashCombine(origin, typeof key === "number" ? seedToUint32(key) : hashString(key)))
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* A stable 0..1 (exclusive) number from a Seed and a key (a branch path, leaf id, purpose...).
|
|
487
|
+
* It makes no stream draws (ADR 0003), so it never shifts or is shifted by other random numbers.
|
|
488
|
+
*/
|
|
489
|
+
function seedRandom(seed, key) {
|
|
490
|
+
return hashCombine(seedToUint32(seed), hashString(key)) / 4294967296;
|
|
491
|
+
}
|
|
492
|
+
// src/math/index.ts
|
|
493
|
+
/**
|
|
494
|
+
* Deterministic maths: the same bits on every machine and JavaScript engine.
|
|
495
|
+
*
|
|
496
|
+
* ECMAScript leaves `Math.sin`, `Math.cos`, `Math.exp`, `Math.log`, `Math.pow`, `Math.hypot`, `**`
|
|
497
|
+
* and friends "implementation-approximated", so engines (and engine versions) may differ in the
|
|
498
|
+
* last bit, which would change a Seed's tree. Everything here is built from `+ - * /`,
|
|
499
|
+
* `Math.sqrt`, `Math.round`/`Math.floor` and exact bit manipulation, which IEEE 754 and the spec
|
|
500
|
+
* pin down exactly. The algorithms are those of fdlibm (sun.com, 1993), accurate to about 1 ulp.
|
|
501
|
+
* ESLint forbids the platform functions in the code that feeds generated geometry and hashes.
|
|
502
|
+
*/
|
|
503
|
+
var bits = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));
|
|
504
|
+
/** 2^k as an exact double, for -1022 <= k <= 1023. */
|
|
505
|
+
function powerOfTwo(k) {
|
|
506
|
+
bits.setUint32(0, k + 1023 << 20);
|
|
507
|
+
bits.setUint32(4, 0);
|
|
508
|
+
return bits.getFloat64(0);
|
|
509
|
+
}
|
|
510
|
+
var PIO2_1 = 1.5707963267341256;
|
|
511
|
+
var PIO2_2 = 6077100506303966e-26;
|
|
512
|
+
var PIO2_3 = 20222662487111665e-37;
|
|
513
|
+
var INV_PIO2 = .6366197723675814;
|
|
514
|
+
var S1 = -.16666666666666632;
|
|
515
|
+
var S2 = .00833333333332249;
|
|
516
|
+
var S3 = -.0001984126982985795;
|
|
517
|
+
var S4 = 27557313707070068e-22;
|
|
518
|
+
var S5 = -2.5050760253406863e-8;
|
|
519
|
+
var S6 = 158969099521155e-24;
|
|
520
|
+
var C1 = .0416666666666666;
|
|
521
|
+
var C2 = -.001388888888887411;
|
|
522
|
+
var C3 = 2480158728947673e-20;
|
|
523
|
+
var C4 = -2.7557314351390663e-7;
|
|
524
|
+
var C5 = 2.087572321298175e-9;
|
|
525
|
+
var C6 = -11359647557788195e-27;
|
|
526
|
+
/** sin on |x| <= π/4. */
|
|
527
|
+
function kernelSin(x) {
|
|
528
|
+
const z = x * x;
|
|
529
|
+
const r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6)));
|
|
530
|
+
return x + z * x * (S1 + z * r);
|
|
531
|
+
}
|
|
532
|
+
/** cos on |x| <= π/4. */
|
|
533
|
+
function kernelCos(x) {
|
|
534
|
+
const z = x * x;
|
|
535
|
+
const r = z * (C1 + z * (C2 + z * (C3 + z * (C4 + z * (C5 + z * C6)))));
|
|
536
|
+
const hz = .5 * z;
|
|
537
|
+
const w = 1 - hz;
|
|
538
|
+
return w + (1 - w - hz + z * r);
|
|
539
|
+
}
|
|
540
|
+
/** `x` reduced to |r| <= ~π/4, and the quadrant (0..3) it came from. Accurate for |x| < 2^20 · π/2. */
|
|
541
|
+
function reduce(x) {
|
|
542
|
+
if (Math.abs(x) <= Math.PI / 4) return [x, 0];
|
|
543
|
+
const n = Math.round(x * INV_PIO2);
|
|
544
|
+
return [x - n * PIO2_1 - n * PIO2_2 - n * PIO2_3, (n % 4 + 4) % 4];
|
|
545
|
+
}
|
|
546
|
+
/** Deterministic `Math.sin`. */
|
|
547
|
+
function sin$1(x) {
|
|
548
|
+
if (!Number.isFinite(x)) return NaN;
|
|
549
|
+
if (x === 0) return x;
|
|
550
|
+
const [r, q] = reduce(x);
|
|
551
|
+
return q === 0 ? kernelSin(r) : q === 1 ? kernelCos(r) : q === 2 ? -kernelSin(r) : -kernelCos(r);
|
|
552
|
+
}
|
|
553
|
+
/** Deterministic `Math.cos`. */
|
|
554
|
+
function cos(x) {
|
|
555
|
+
if (!Number.isFinite(x)) return NaN;
|
|
556
|
+
const [r, q] = reduce(x);
|
|
557
|
+
return q === 0 ? kernelCos(r) : q === 1 ? -kernelSin(r) : q === 2 ? -kernelCos(r) : kernelSin(r);
|
|
558
|
+
}
|
|
559
|
+
var LN2_HI = .6931471803691238;
|
|
560
|
+
var LN2_LO = 19082149292705877e-26;
|
|
561
|
+
var INV_LN2 = 1.4426950408889634;
|
|
562
|
+
var P1 = .16666666666666602;
|
|
563
|
+
var P2 = -.0027777777777015593;
|
|
564
|
+
var P3 = 6613756321437934e-20;
|
|
565
|
+
var P4 = -16533902205465252e-22;
|
|
566
|
+
var P5 = 4.1381367970572385e-8;
|
|
567
|
+
/** Deterministic `Math.exp`. */
|
|
568
|
+
function exp(x) {
|
|
569
|
+
if (Number.isNaN(x)) return NaN;
|
|
570
|
+
if (x > 709.782712893384) return Number.POSITIVE_INFINITY;
|
|
571
|
+
if (x < -745.1332191019411) return 0;
|
|
572
|
+
if (x === 0) return 1;
|
|
573
|
+
const k = Math.round(x * INV_LN2);
|
|
574
|
+
const hi = x - k * LN2_HI;
|
|
575
|
+
const lo = k * LN2_LO;
|
|
576
|
+
const r = hi - lo;
|
|
577
|
+
const t = r * r;
|
|
578
|
+
const c = r - t * (P1 + t * (P2 + t * (P3 + t * (P4 + t * P5))));
|
|
579
|
+
const y = 1 - (lo - r * c / (2 - c) - hi);
|
|
580
|
+
if (k >= -1021) return k === 1024 ? y * 2 * powerOfTwo(1023) : y * powerOfTwo(k);
|
|
581
|
+
return y * powerOfTwo(k + 1e3) * powerOfTwo(-1e3);
|
|
582
|
+
}
|
|
583
|
+
var LG1 = .6666666666666735;
|
|
584
|
+
var LG2 = .3999999999940942;
|
|
585
|
+
var LG3 = .2857142874366239;
|
|
586
|
+
var LG4 = .22222198432149784;
|
|
587
|
+
var LG5 = .1818357216161805;
|
|
588
|
+
var LG6 = .15313837699209373;
|
|
589
|
+
var LG7 = .14798198605116586;
|
|
590
|
+
var TWO54 = 0x40000000000000;
|
|
591
|
+
/** Deterministic `Math.log` (natural logarithm). */
|
|
592
|
+
function log(x) {
|
|
593
|
+
if (Number.isNaN(x) || x < 0) return NaN;
|
|
594
|
+
if (x === 0) return Number.NEGATIVE_INFINITY;
|
|
595
|
+
if (x === Number.POSITIVE_INFINITY) return x;
|
|
596
|
+
let k = 0;
|
|
597
|
+
if (x < 22250738585072014e-324) {
|
|
598
|
+
x *= TWO54;
|
|
599
|
+
k = -54;
|
|
600
|
+
}
|
|
601
|
+
bits.setFloat64(0, x);
|
|
602
|
+
let high = bits.getUint32(0);
|
|
603
|
+
k += (high >>> 20) - 1023;
|
|
604
|
+
high &= 1048575;
|
|
605
|
+
const i = high + 614244 & 1048576;
|
|
606
|
+
bits.setUint32(0, high | i ^ 1072693248);
|
|
607
|
+
k += i >>> 20;
|
|
608
|
+
const f = bits.getFloat64(0) - 1;
|
|
609
|
+
const s = f / (2 + f);
|
|
610
|
+
const z = s * s;
|
|
611
|
+
const w = z * z;
|
|
612
|
+
const r = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7))) + w * (LG2 + w * (LG4 + w * LG6));
|
|
613
|
+
const hfsq = .5 * f * f;
|
|
614
|
+
return k * LN2_HI - (hfsq - (s * (hfsq + r) + k * LN2_LO) - f);
|
|
615
|
+
}
|
|
616
|
+
/** Deterministic `Math.pow` (`x ** y`), for the finite values the library uses. */
|
|
617
|
+
function pow(x, y) {
|
|
618
|
+
if (y === 0) return 1;
|
|
619
|
+
if (Number.isNaN(x) || Number.isNaN(y)) return NaN;
|
|
620
|
+
if (x === 1) return 1;
|
|
621
|
+
if (x === 0) return y > 0 ? 0 : Number.POSITIVE_INFINITY;
|
|
622
|
+
if (x < 0) {
|
|
623
|
+
if (!Number.isInteger(y)) return NaN;
|
|
624
|
+
const p = exp(y * log(-x));
|
|
625
|
+
return y % 2 === 0 ? p : -p;
|
|
626
|
+
}
|
|
627
|
+
return exp(y * log(x));
|
|
628
|
+
}
|
|
629
|
+
/** Deterministic `Math.hypot` of a 3-vector. */
|
|
630
|
+
function hypot3(x, y, z) {
|
|
631
|
+
return Math.sqrt(x * x + y * y + z * z);
|
|
632
|
+
}
|
|
633
|
+
// src/season/profile.ts
|
|
634
|
+
/** Smallest keyframe span used as a divisor (two keys at the same `t` make a step). */
|
|
635
|
+
var KEYFRAME_EPSILON = 1e-5;
|
|
636
|
+
/** Interpolation weight of the segment `t0..t1` at `s` (0 before, 1 after). */
|
|
637
|
+
function segmentWeight(s, t0, t1) {
|
|
638
|
+
return Math.min(Math.max((s - t0) / Math.max(t1 - t0, KEYFRAME_EPSILON), 0), 1);
|
|
639
|
+
}
|
|
640
|
+
function mixValue(a, b, f) {
|
|
641
|
+
if (typeof a === "number") return a + (b - a) * f;
|
|
642
|
+
return a.map((x, i) => x + (b[i] - x) * f);
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Samples a keyframe track at Season `s`: linear between keys, holding the first value
|
|
646
|
+
* before the first key and the last value after the last one. Computed as a chain of
|
|
647
|
+
* mixes (one per segment), the same chain the shader runs.
|
|
648
|
+
*/
|
|
649
|
+
function sampleTrack(track, s) {
|
|
650
|
+
let out = track[0].value;
|
|
651
|
+
for (let i = 0; i < track.length - 1; i++) out = mixValue(out, track[i + 1].value, segmentWeight(s, track[i].t, track[i + 1].t));
|
|
652
|
+
return out;
|
|
653
|
+
}
|
|
654
|
+
/** Brings any Season into 0..1: values inside 0..1 (including 1, the last day of winter) are kept, others wrap around the year. */
|
|
655
|
+
function wrapSeason(s) {
|
|
656
|
+
return s >= 0 && s <= 1 ? s : s - Math.floor(s);
|
|
657
|
+
}
|
|
658
|
+
/** sRGB transfer curve -> linear, per channel (as three.js `SRGBToLinear`). */
|
|
659
|
+
function srgbToLinear(c) {
|
|
660
|
+
return c < .04045 ? c * .0773993808 : pow(c * .9478672986 + .0521327014, 2.4);
|
|
661
|
+
}
|
|
662
|
+
/** `#rrggbb` -> linear RGB. */
|
|
663
|
+
function hexToLinear(hex) {
|
|
664
|
+
const n = parseInt(hex.slice(1), 16);
|
|
665
|
+
return [
|
|
666
|
+
srgbToLinear((n >> 16 & 255) / 255),
|
|
667
|
+
srgbToLinear((n >> 8 & 255) / 255),
|
|
668
|
+
srgbToLinear((n & 255) / 255)
|
|
669
|
+
];
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Evaluates the Season Profile at `season`, shifted by `shift` (a Seed's timing offset,
|
|
673
|
+
* see {@link seasonShift}) and wrapped around the year.
|
|
674
|
+
*/
|
|
675
|
+
function evaluateSeason(profile, season, shift = 0) {
|
|
676
|
+
const s = wrapSeason(season + shift);
|
|
677
|
+
return {
|
|
678
|
+
season: s,
|
|
679
|
+
leafColor: sampleTrack(profile.leafColor.map((k) => ({
|
|
680
|
+
t: k.t,
|
|
681
|
+
value: hexToLinear(k.value)
|
|
682
|
+
})), s),
|
|
683
|
+
leafCoverage: sampleTrack(profile.leafCoverage, s),
|
|
684
|
+
blossom: sampleTrack(profile.blossom, s),
|
|
685
|
+
blossomColor: hexToLinear(profile.blossomColor)
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
/** The {@link PartSeason} of vertex `vertex` in `aSeason` attribute data (3 floats per vertex). */
|
|
689
|
+
function partSeasonAt(aSeason, vertex) {
|
|
690
|
+
return {
|
|
691
|
+
shift: aSeason[vertex * 3],
|
|
692
|
+
coverageRank: aSeason[vertex * 3 + 1],
|
|
693
|
+
blossomRank: aSeason[vertex * 3 + 2]
|
|
694
|
+
};
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* A Seed's Season timing shift for the whole tree: within ± half of `variation.season`.
|
|
698
|
+
* Per-leaf jitter ({@link leafSeasonAttribute}) takes the other half, so a leaf stays within the range.
|
|
699
|
+
*/
|
|
700
|
+
function seasonShift(seed, variation) {
|
|
701
|
+
return (seedRandom(seed, "season") * 2 - 1) * (variation.season / 2);
|
|
702
|
+
}
|
|
703
|
+
/** The Season timing (`aSeason` attribute) of one leaf; see {@link PartSeason}. */
|
|
704
|
+
function leafSeasonAttribute(seed, variation, leafId) {
|
|
705
|
+
const jitter = (seedRandom(seed, `${leafId}#season`) * 2 - 1) * (variation.season / 2);
|
|
706
|
+
return {
|
|
707
|
+
shift: seasonShift(seed, variation) + jitter,
|
|
708
|
+
coverageRank: seedRandom(seed, `${leafId}#coverage`),
|
|
709
|
+
blossomRank: seedRandom(seed, `${leafId}#blossom`)
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
/** `aSeason` for wood vertices: the tree's timing shift, no ranks. */
|
|
713
|
+
function woodSeasonAttribute(seed, variation) {
|
|
714
|
+
return {
|
|
715
|
+
shift: seasonShift(seed, variation),
|
|
716
|
+
coverageRank: 0,
|
|
717
|
+
blossomRank: 0
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Evaluates one leaf from its Season timing (`aSeason` attribute, see {@link partSeasonAt}): the
|
|
722
|
+
* exact CPU twin of the leaf shader (see `createSeasonNodes`). Use it to bake a tree at a Season.
|
|
723
|
+
*/
|
|
724
|
+
function leafSeason(profile, season, part) {
|
|
725
|
+
const state = evaluateSeason(profile, season, part.shift);
|
|
726
|
+
const blossom = state.blossom > part.blossomRank;
|
|
727
|
+
return {
|
|
728
|
+
visible: blossom || state.leafCoverage > part.coverageRank,
|
|
729
|
+
blossom,
|
|
730
|
+
color: blossom ? state.blossomColor : state.leafColor
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
// src/generator/vec.ts
|
|
734
|
+
var add = (a, b) => [
|
|
735
|
+
a[0] + b[0],
|
|
736
|
+
a[1] + b[1],
|
|
737
|
+
a[2] + b[2]
|
|
738
|
+
];
|
|
739
|
+
var sub = (a, b) => [
|
|
740
|
+
a[0] - b[0],
|
|
741
|
+
a[1] - b[1],
|
|
742
|
+
a[2] - b[2]
|
|
743
|
+
];
|
|
744
|
+
var scale = (a, s) => [
|
|
745
|
+
a[0] * s,
|
|
746
|
+
a[1] * s,
|
|
747
|
+
a[2] * s
|
|
748
|
+
];
|
|
749
|
+
var dot$1 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
750
|
+
var cross$1 = (a, b) => [
|
|
751
|
+
a[1] * b[2] - a[2] * b[1],
|
|
752
|
+
a[2] * b[0] - a[0] * b[2],
|
|
753
|
+
a[0] * b[1] - a[1] * b[0]
|
|
754
|
+
];
|
|
755
|
+
var length = (a) => hypot3(a[0], a[1], a[2]);
|
|
756
|
+
function normalize(a) {
|
|
757
|
+
const l = length(a);
|
|
758
|
+
return l > 1e-12 ? scale(a, 1 / l) : [
|
|
759
|
+
0,
|
|
760
|
+
1,
|
|
761
|
+
0
|
|
762
|
+
];
|
|
763
|
+
}
|
|
764
|
+
var lerp = (a, b, t) => [
|
|
765
|
+
a[0] + (b[0] - a[0]) * t,
|
|
766
|
+
a[1] + (b[1] - a[1]) * t,
|
|
767
|
+
a[2] + (b[2] - a[2]) * t
|
|
768
|
+
];
|
|
769
|
+
/** Any unit vector perpendicular to the unit vector `v`. */
|
|
770
|
+
function perpendicular(v) {
|
|
771
|
+
return normalize(cross$1(Math.abs(v[1]) < .9 ? [
|
|
772
|
+
0,
|
|
773
|
+
1,
|
|
774
|
+
0
|
|
775
|
+
] : [
|
|
776
|
+
1,
|
|
777
|
+
0,
|
|
778
|
+
0
|
|
779
|
+
], v));
|
|
780
|
+
}
|
|
781
|
+
// src/generator/frames.ts
|
|
782
|
+
/**
|
|
783
|
+
* Parallel-transport frames, one per skeleton point: the cross-section does not twist
|
|
784
|
+
* as the branch bends, so swept rings stay even for branches in any direction.
|
|
785
|
+
*/
|
|
786
|
+
function branchFrames(branch) {
|
|
787
|
+
const pts = branch.points.map((p) => p.position);
|
|
788
|
+
const n = pts.length;
|
|
789
|
+
const segment = (i) => normalize(sub(pts[Math.min(i + 1, n - 1)], pts[Math.min(i, n - 2)]));
|
|
790
|
+
const frames = [];
|
|
791
|
+
for (let i = 0; i < n; i++) {
|
|
792
|
+
const tangent = i === 0 && branch.parent === null ? [
|
|
793
|
+
0,
|
|
794
|
+
1,
|
|
795
|
+
0
|
|
796
|
+
] : i === 0 || i === n - 1 ? segment(Math.min(i, n - 2)) : normalize(add(segment(i - 1), segment(i)));
|
|
797
|
+
let normal;
|
|
798
|
+
if (i === 0) normal = perpendicular(tangent);
|
|
799
|
+
else {
|
|
800
|
+
const previous = frames[i - 1].normal;
|
|
801
|
+
normal = normalize(sub(previous, scale(tangent, dot$1(previous, tangent))));
|
|
802
|
+
}
|
|
803
|
+
frames.push({
|
|
804
|
+
tangent,
|
|
805
|
+
normal,
|
|
806
|
+
binormal: cross$1(tangent, normal)
|
|
807
|
+
});
|
|
808
|
+
}
|
|
809
|
+
return frames;
|
|
810
|
+
}
|
|
811
|
+
/** Total length of a branch's centre line. */
|
|
812
|
+
function pathLength(branch) {
|
|
813
|
+
let total = 0;
|
|
814
|
+
for (let i = 1; i < branch.points.length; i++) total += length(sub(branch.points[i].position, branch.points[i - 1].position));
|
|
815
|
+
return total;
|
|
816
|
+
}
|
|
817
|
+
/** The point, frame and radius at fraction `t` (0..1) of a branch's length. */
|
|
818
|
+
function sampleBranch(branch, frames, t) {
|
|
819
|
+
const pts = branch.points;
|
|
820
|
+
const target = Math.min(Math.max(t, 0), 1) * pathLength(branch);
|
|
821
|
+
let walked = 0;
|
|
822
|
+
for (let i = 1; i < pts.length; i++) {
|
|
823
|
+
const a = pts[i - 1];
|
|
824
|
+
const b = pts[i];
|
|
825
|
+
const segment = length(sub(b.position, a.position));
|
|
826
|
+
if (walked + segment >= target || i === pts.length - 1) {
|
|
827
|
+
const f = segment > 0 ? Math.min(Math.max((target - walked) / segment, 0), 1) : 0;
|
|
828
|
+
const tangent = normalize(sub(b.position, a.position));
|
|
829
|
+
const normal = normalize(sub(frames[i - 1].normal, scale(tangent, dot$1(frames[i - 1].normal, tangent))));
|
|
830
|
+
return {
|
|
831
|
+
position: lerp(a.position, b.position, f),
|
|
832
|
+
radius: a.radius + (b.radius - a.radius) * f,
|
|
833
|
+
tangent,
|
|
834
|
+
normal,
|
|
835
|
+
binormal: cross$1(tangent, normal)
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
walked += segment;
|
|
839
|
+
}
|
|
840
|
+
const last = pts[pts.length - 1];
|
|
841
|
+
return {
|
|
842
|
+
position: last.position,
|
|
843
|
+
radius: last.radius,
|
|
844
|
+
...frames[frames.length - 1]
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
// src/generator/branches.ts
|
|
848
|
+
var DEG$1 = Math.PI / 180;
|
|
849
|
+
/** How far `gravity` = ±1 turns a branch over its whole length (sum of per-section pulls). */
|
|
850
|
+
var GRAVITY_PER_BRANCH = 1.5;
|
|
851
|
+
/**
|
|
852
|
+
* Grows all branching levels below the trunk, breadth first (level by level).
|
|
853
|
+
*
|
|
854
|
+
* Branch path stability (ADR 0003): a parent's spiral phase comes from `random.fork(parentPath)`
|
|
855
|
+
* and each child's shape from `random.fork(childPath)`. So a branch depends only on its
|
|
856
|
+
* ancestors and its own path, never on its siblings' subtrees, on deeper levels or on leaves.
|
|
857
|
+
*/
|
|
858
|
+
function buildBranches(definition, trunk, random) {
|
|
859
|
+
const out = [];
|
|
860
|
+
const queue = [trunk];
|
|
861
|
+
for (let q = 0; q < queue.length; q++) {
|
|
862
|
+
const parent = queue[q];
|
|
863
|
+
const level = definition.branches[parent.level];
|
|
864
|
+
if (!level) continue;
|
|
865
|
+
const children = growChildren(parent, level, random, definition.form === "conifer" && parent.level === 0);
|
|
866
|
+
out.push(...children);
|
|
867
|
+
queue.push(...children);
|
|
868
|
+
}
|
|
869
|
+
return out;
|
|
870
|
+
}
|
|
871
|
+
/** Shortest conifer trunk branch, as a fraction of the declared length (keeps the top from being bare). */
|
|
872
|
+
var MIN_CONE = .1;
|
|
873
|
+
/**
|
|
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.
|
|
876
|
+
*/
|
|
877
|
+
function growChildren(parent, level, random, cone) {
|
|
878
|
+
const count = level.count;
|
|
879
|
+
const azimuth0 = random.fork(parent.path).range(0, Math.PI * 2);
|
|
880
|
+
const frames = branchFrames(parent);
|
|
881
|
+
const parentLength = pathLength(parent);
|
|
882
|
+
const children = [];
|
|
883
|
+
for (let i = 0; i < count; i++) {
|
|
884
|
+
const path = `${parent.path}.${i}`;
|
|
885
|
+
const r = random.fork(path);
|
|
886
|
+
const t = level.start + (level.end - level.start) * (i + r.range(.15, .85)) / count;
|
|
887
|
+
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;
|
|
890
|
+
const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin$1(azimuth)));
|
|
891
|
+
const start = normalize(add(scale(at.tangent, cos(angle)), scale(across, sin$1(angle))));
|
|
892
|
+
const pull = [
|
|
893
|
+
0,
|
|
894
|
+
level.gravity * GRAVITY_PER_BRANCH / level.sections,
|
|
895
|
+
0
|
|
896
|
+
];
|
|
897
|
+
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;
|
|
900
|
+
const baseRadius = at.radius * level.radius;
|
|
901
|
+
const points = [];
|
|
902
|
+
let position = at.position;
|
|
903
|
+
for (let s = 0; s <= level.sections; s++) {
|
|
904
|
+
points.push({
|
|
905
|
+
position,
|
|
906
|
+
radius: baseRadius * (1 + (level.taper - 1) * (s / level.sections))
|
|
907
|
+
});
|
|
908
|
+
if (s === level.sections) break;
|
|
909
|
+
const wander = [
|
|
910
|
+
r.range(-1, 1),
|
|
911
|
+
r.range(-1, 1),
|
|
912
|
+
r.range(-1, 1)
|
|
913
|
+
];
|
|
914
|
+
direction = normalize(add(add(direction, scale(wander, level.bend)), pull));
|
|
915
|
+
position = add(position, scale(direction, step));
|
|
916
|
+
}
|
|
917
|
+
children.push({
|
|
918
|
+
path,
|
|
919
|
+
parent: parent.path,
|
|
920
|
+
level: parent.level + 1,
|
|
921
|
+
attach: t,
|
|
922
|
+
direction: start,
|
|
923
|
+
points
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
return children;
|
|
927
|
+
}
|
|
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
|
+
// src/generator/wind.ts
|
|
991
|
+
var NO_SWAY = {
|
|
992
|
+
base: 0,
|
|
993
|
+
gain: 0,
|
|
994
|
+
flutter: false
|
|
995
|
+
};
|
|
996
|
+
/** Branch sway of every branch (by path). `branches` must be ordered parents first (the skeleton is). */
|
|
997
|
+
function branchSway(branches, levels) {
|
|
998
|
+
const gain = levels > 0 ? 1 / levels : 0;
|
|
999
|
+
const out = /* @__PURE__ */ new Map();
|
|
1000
|
+
for (const branch of branches) {
|
|
1001
|
+
if (branch.parent === null) {
|
|
1002
|
+
out.set(branch.path, NO_SWAY);
|
|
1003
|
+
continue;
|
|
1004
|
+
}
|
|
1005
|
+
const parent = out.get(branch.parent);
|
|
1006
|
+
out.set(branch.path, {
|
|
1007
|
+
base: parent.base + parent.gain * branch.attach,
|
|
1008
|
+
gain,
|
|
1009
|
+
flutter: false
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
return out;
|
|
1013
|
+
}
|
|
1014
|
+
/** The sway of a leaf: its branch's sway at the attach point, plus flutter. */
|
|
1015
|
+
function leafSway(branch, attach) {
|
|
1016
|
+
return {
|
|
1017
|
+
base: branch.base + branch.gain * attach,
|
|
1018
|
+
gain: 0,
|
|
1019
|
+
flutter: true
|
|
1020
|
+
};
|
|
1021
|
+
}
|
|
1022
|
+
/** Fills the trunk-sway channel (x of `aWind`) from each vertex's height. */
|
|
1023
|
+
function writeTrunkSway(buffers, trunkHeight) {
|
|
1024
|
+
const aWind = buffers.attributes.aWind.array;
|
|
1025
|
+
const count = buffers.positions.length / 3;
|
|
1026
|
+
for (let v = 0; v < count; v++) {
|
|
1027
|
+
const h = Math.min(Math.max(buffers.positions[v * 3 + 1] / Math.max(trunkHeight, 1e-6), 0), 1);
|
|
1028
|
+
aWind[v * 3] = h * h;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
// src/generator/attributes.ts
|
|
1032
|
+
/** Allocates the per-vertex attributes for `vertexCount` vertices. */
|
|
1033
|
+
function createAttributes(vertexCount) {
|
|
1034
|
+
const scalar = () => ({
|
|
1035
|
+
array: new Float32Array(vertexCount),
|
|
1036
|
+
itemSize: 1
|
|
1037
|
+
});
|
|
1038
|
+
return {
|
|
1039
|
+
aLevel: scalar(),
|
|
1040
|
+
aAlong: scalar(),
|
|
1041
|
+
aAttach: scalar(),
|
|
1042
|
+
aRandom: scalar(),
|
|
1043
|
+
aOrigin: {
|
|
1044
|
+
array: new Float32Array(vertexCount * 3),
|
|
1045
|
+
itemSize: 3
|
|
1046
|
+
},
|
|
1047
|
+
aGrowth: {
|
|
1048
|
+
array: new Float32Array(vertexCount * 3),
|
|
1049
|
+
itemSize: 3
|
|
1050
|
+
},
|
|
1051
|
+
aSeason: {
|
|
1052
|
+
array: new Float32Array(vertexCount * 3),
|
|
1053
|
+
itemSize: 3
|
|
1054
|
+
},
|
|
1055
|
+
aWind: {
|
|
1056
|
+
array: new Float32Array(vertexCount * 3),
|
|
1057
|
+
itemSize: 3
|
|
1058
|
+
}
|
|
1059
|
+
};
|
|
1060
|
+
}
|
|
1061
|
+
/** Writes one vertex's attributes; `radius` = its distance from the part's centre line. */
|
|
1062
|
+
function writePart(attributes, v, part, along, radius = 0) {
|
|
1063
|
+
attributes.aLevel.array[v] = part.level;
|
|
1064
|
+
attributes.aAlong.array[v] = along;
|
|
1065
|
+
attributes.aAttach.array[v] = part.attach;
|
|
1066
|
+
attributes.aRandom.array[v] = part.random;
|
|
1067
|
+
attributes.aOrigin.array.set(part.origin, v * 3);
|
|
1068
|
+
attributes.aGrowth.array.set([
|
|
1069
|
+
part.growth.start,
|
|
1070
|
+
part.growth.end,
|
|
1071
|
+
radius
|
|
1072
|
+
], v * 3);
|
|
1073
|
+
attributes.aSeason.array.set([
|
|
1074
|
+
part.season.shift,
|
|
1075
|
+
part.season.coverageRank,
|
|
1076
|
+
part.season.blossomRank
|
|
1077
|
+
], v * 3);
|
|
1078
|
+
const sway = part.sway ?? NO_SWAY;
|
|
1079
|
+
attributes.aWind.array[v * 3 + 1] = Math.min(sway.base + sway.gain * along, 1);
|
|
1080
|
+
attributes.aWind.array[v * 3 + 2] = sway.flutter ? along : 0;
|
|
1081
|
+
}
|
|
1082
|
+
// src/generator/leaf-shapes.ts
|
|
1083
|
+
var GOLDEN = (1 + Math.sqrt(5)) / 2;
|
|
1084
|
+
/** Low-poly foliage ball: an icosahedron of diameter 1, from the attachment point out along the leaf. */
|
|
1085
|
+
function clumpTemplate() {
|
|
1086
|
+
const normals = [
|
|
1087
|
+
[
|
|
1088
|
+
-1,
|
|
1089
|
+
GOLDEN,
|
|
1090
|
+
0
|
|
1091
|
+
],
|
|
1092
|
+
[
|
|
1093
|
+
1,
|
|
1094
|
+
GOLDEN,
|
|
1095
|
+
0
|
|
1096
|
+
],
|
|
1097
|
+
[
|
|
1098
|
+
-1,
|
|
1099
|
+
-GOLDEN,
|
|
1100
|
+
0
|
|
1101
|
+
],
|
|
1102
|
+
[
|
|
1103
|
+
1,
|
|
1104
|
+
-GOLDEN,
|
|
1105
|
+
0
|
|
1106
|
+
],
|
|
1107
|
+
[
|
|
1108
|
+
0,
|
|
1109
|
+
-1,
|
|
1110
|
+
GOLDEN
|
|
1111
|
+
],
|
|
1112
|
+
[
|
|
1113
|
+
0,
|
|
1114
|
+
1,
|
|
1115
|
+
GOLDEN
|
|
1116
|
+
],
|
|
1117
|
+
[
|
|
1118
|
+
0,
|
|
1119
|
+
-1,
|
|
1120
|
+
-GOLDEN
|
|
1121
|
+
],
|
|
1122
|
+
[
|
|
1123
|
+
0,
|
|
1124
|
+
1,
|
|
1125
|
+
-GOLDEN
|
|
1126
|
+
],
|
|
1127
|
+
[
|
|
1128
|
+
GOLDEN,
|
|
1129
|
+
0,
|
|
1130
|
+
-1
|
|
1131
|
+
],
|
|
1132
|
+
[
|
|
1133
|
+
GOLDEN,
|
|
1134
|
+
0,
|
|
1135
|
+
1
|
|
1136
|
+
],
|
|
1137
|
+
[
|
|
1138
|
+
-GOLDEN,
|
|
1139
|
+
0,
|
|
1140
|
+
-1
|
|
1141
|
+
],
|
|
1142
|
+
[
|
|
1143
|
+
-GOLDEN,
|
|
1144
|
+
0,
|
|
1145
|
+
1
|
|
1146
|
+
]
|
|
1147
|
+
].map((v) => normalize(v));
|
|
1148
|
+
const centre = [
|
|
1149
|
+
0,
|
|
1150
|
+
0,
|
|
1151
|
+
.5
|
|
1152
|
+
];
|
|
1153
|
+
return {
|
|
1154
|
+
positions: normals.map((n) => add(centre, scale(n, .5))),
|
|
1155
|
+
normals,
|
|
1156
|
+
triangles: [
|
|
1157
|
+
[
|
|
1158
|
+
0,
|
|
1159
|
+
11,
|
|
1160
|
+
5
|
|
1161
|
+
],
|
|
1162
|
+
[
|
|
1163
|
+
0,
|
|
1164
|
+
5,
|
|
1165
|
+
1
|
|
1166
|
+
],
|
|
1167
|
+
[
|
|
1168
|
+
0,
|
|
1169
|
+
1,
|
|
1170
|
+
7
|
|
1171
|
+
],
|
|
1172
|
+
[
|
|
1173
|
+
0,
|
|
1174
|
+
7,
|
|
1175
|
+
10
|
|
1176
|
+
],
|
|
1177
|
+
[
|
|
1178
|
+
0,
|
|
1179
|
+
10,
|
|
1180
|
+
11
|
|
1181
|
+
],
|
|
1182
|
+
[
|
|
1183
|
+
1,
|
|
1184
|
+
5,
|
|
1185
|
+
9
|
|
1186
|
+
],
|
|
1187
|
+
[
|
|
1188
|
+
5,
|
|
1189
|
+
11,
|
|
1190
|
+
4
|
|
1191
|
+
],
|
|
1192
|
+
[
|
|
1193
|
+
11,
|
|
1194
|
+
10,
|
|
1195
|
+
2
|
|
1196
|
+
],
|
|
1197
|
+
[
|
|
1198
|
+
10,
|
|
1199
|
+
7,
|
|
1200
|
+
6
|
|
1201
|
+
],
|
|
1202
|
+
[
|
|
1203
|
+
7,
|
|
1204
|
+
1,
|
|
1205
|
+
8
|
|
1206
|
+
],
|
|
1207
|
+
[
|
|
1208
|
+
3,
|
|
1209
|
+
9,
|
|
1210
|
+
4
|
|
1211
|
+
],
|
|
1212
|
+
[
|
|
1213
|
+
3,
|
|
1214
|
+
4,
|
|
1215
|
+
2
|
|
1216
|
+
],
|
|
1217
|
+
[
|
|
1218
|
+
3,
|
|
1219
|
+
2,
|
|
1220
|
+
6
|
|
1221
|
+
],
|
|
1222
|
+
[
|
|
1223
|
+
3,
|
|
1224
|
+
6,
|
|
1225
|
+
8
|
|
1226
|
+
],
|
|
1227
|
+
[
|
|
1228
|
+
3,
|
|
1229
|
+
8,
|
|
1230
|
+
9
|
|
1231
|
+
],
|
|
1232
|
+
[
|
|
1233
|
+
4,
|
|
1234
|
+
9,
|
|
1235
|
+
5
|
|
1236
|
+
],
|
|
1237
|
+
[
|
|
1238
|
+
2,
|
|
1239
|
+
4,
|
|
1240
|
+
11
|
|
1241
|
+
],
|
|
1242
|
+
[
|
|
1243
|
+
6,
|
|
1244
|
+
2,
|
|
1245
|
+
10
|
|
1246
|
+
],
|
|
1247
|
+
[
|
|
1248
|
+
8,
|
|
1249
|
+
6,
|
|
1250
|
+
7
|
|
1251
|
+
],
|
|
1252
|
+
[
|
|
1253
|
+
9,
|
|
1254
|
+
8,
|
|
1255
|
+
1
|
|
1256
|
+
]
|
|
1257
|
+
]
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Stylized foliage puff: an icosphere (the clump's icosahedron with every triangle split in
|
|
1262
|
+
* four, new vertices pushed onto the sphere), diameter 1, from the attachment point outward.
|
|
1263
|
+
* Smooth radial normals, so toon shading makes it read as a soft round ball.
|
|
1264
|
+
*/
|
|
1265
|
+
function puffTemplate() {
|
|
1266
|
+
const ico = clumpTemplate();
|
|
1267
|
+
const centre = [
|
|
1268
|
+
0,
|
|
1269
|
+
0,
|
|
1270
|
+
.5
|
|
1271
|
+
];
|
|
1272
|
+
const normals = [...ico.normals];
|
|
1273
|
+
const midpoints = /* @__PURE__ */ new Map();
|
|
1274
|
+
const midpoint = (a, b) => {
|
|
1275
|
+
const key = a < b ? `${a}-${b}` : `${b}-${a}`;
|
|
1276
|
+
let index = midpoints.get(key);
|
|
1277
|
+
if (index === void 0) {
|
|
1278
|
+
index = normals.push(normalize(add(normals[a], normals[b]))) - 1;
|
|
1279
|
+
midpoints.set(key, index);
|
|
1280
|
+
}
|
|
1281
|
+
return index;
|
|
1282
|
+
};
|
|
1283
|
+
const triangles = ico.triangles.flatMap(([a, b, c]) => {
|
|
1284
|
+
const [ab, bc, ca] = [
|
|
1285
|
+
midpoint(a, b),
|
|
1286
|
+
midpoint(b, c),
|
|
1287
|
+
midpoint(c, a)
|
|
1288
|
+
];
|
|
1289
|
+
return [
|
|
1290
|
+
[
|
|
1291
|
+
a,
|
|
1292
|
+
ab,
|
|
1293
|
+
ca
|
|
1294
|
+
],
|
|
1295
|
+
[
|
|
1296
|
+
b,
|
|
1297
|
+
bc,
|
|
1298
|
+
ab
|
|
1299
|
+
],
|
|
1300
|
+
[
|
|
1301
|
+
c,
|
|
1302
|
+
ca,
|
|
1303
|
+
bc
|
|
1304
|
+
],
|
|
1305
|
+
[
|
|
1306
|
+
ab,
|
|
1307
|
+
bc,
|
|
1308
|
+
ca
|
|
1309
|
+
]
|
|
1310
|
+
];
|
|
1311
|
+
});
|
|
1312
|
+
return {
|
|
1313
|
+
positions: normals.map((n) => add(centre, scale(n, .5))),
|
|
1314
|
+
normals,
|
|
1315
|
+
triangles
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
/** Needle tuft: a slim five-sided spindle from the attachment point (z = 0) to the tip (z = 1). */
|
|
1319
|
+
var NEEDLE_SIDES = 5;
|
|
1320
|
+
var NEEDLE_RADIUS = .28;
|
|
1321
|
+
var NEEDLE_WAIST = .25;
|
|
1322
|
+
function needleTemplate() {
|
|
1323
|
+
const positions = [[
|
|
1324
|
+
0,
|
|
1325
|
+
0,
|
|
1326
|
+
0
|
|
1327
|
+
], [
|
|
1328
|
+
0,
|
|
1329
|
+
0,
|
|
1330
|
+
1
|
|
1331
|
+
]];
|
|
1332
|
+
const normals = [[
|
|
1333
|
+
0,
|
|
1334
|
+
0,
|
|
1335
|
+
-1
|
|
1336
|
+
], [
|
|
1337
|
+
0,
|
|
1338
|
+
0,
|
|
1339
|
+
1
|
|
1340
|
+
]];
|
|
1341
|
+
const triangles = [];
|
|
1342
|
+
for (let s = 0; s < NEEDLE_SIDES; s++) {
|
|
1343
|
+
const angle = s / NEEDLE_SIDES * Math.PI * 2;
|
|
1344
|
+
const radial = [
|
|
1345
|
+
cos(angle),
|
|
1346
|
+
sin$1(angle),
|
|
1347
|
+
0
|
|
1348
|
+
];
|
|
1349
|
+
positions.push([
|
|
1350
|
+
radial[0] * NEEDLE_RADIUS,
|
|
1351
|
+
radial[1] * NEEDLE_RADIUS,
|
|
1352
|
+
NEEDLE_WAIST
|
|
1353
|
+
]);
|
|
1354
|
+
normals.push(radial);
|
|
1355
|
+
const a = 2 + s;
|
|
1356
|
+
const b = 2 + (s + 1) % NEEDLE_SIDES;
|
|
1357
|
+
triangles.push([
|
|
1358
|
+
a,
|
|
1359
|
+
b,
|
|
1360
|
+
1
|
|
1361
|
+
], [
|
|
1362
|
+
b,
|
|
1363
|
+
a,
|
|
1364
|
+
0
|
|
1365
|
+
]);
|
|
1366
|
+
}
|
|
1367
|
+
return {
|
|
1368
|
+
positions,
|
|
1369
|
+
normals,
|
|
1370
|
+
triangles
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
var TEMPLATES = {
|
|
1374
|
+
clump: orient(clumpTemplate()),
|
|
1375
|
+
needle: orient(needleTemplate()),
|
|
1376
|
+
puff: orient(puffTemplate())
|
|
1377
|
+
};
|
|
1378
|
+
/** Fixes each triangle's winding so its front face points along its vertex normals (CCW = front). */
|
|
1379
|
+
function orient(template) {
|
|
1380
|
+
const { positions: p, normals: n } = template;
|
|
1381
|
+
const triangles = template.triangles.map(([a, b, c]) => {
|
|
1382
|
+
return dot$1(cross$1(sub(p[b], p[a]), sub(p[c], p[a])), add(add(n[a], n[b]), n[c])) >= 0 ? [
|
|
1383
|
+
a,
|
|
1384
|
+
b,
|
|
1385
|
+
c
|
|
1386
|
+
] : [
|
|
1387
|
+
a,
|
|
1388
|
+
c,
|
|
1389
|
+
b
|
|
1390
|
+
];
|
|
1391
|
+
});
|
|
1392
|
+
return {
|
|
1393
|
+
...template,
|
|
1394
|
+
triangles
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
/**
|
|
1398
|
+
* Leaf geometry for the solid shapes ('clump', 'needle', 'puff'): one small closed mesh per leaf,
|
|
1399
|
+
* placed in the leaf's frame (across, normal, direction) and scaled by its size. Like cards,
|
|
1400
|
+
* every vertex carries the leaf's tint as its colour and the leaf's part attributes.
|
|
1401
|
+
*/
|
|
1402
|
+
function solidLeafGeometry(leaves, shape, level, seed, variation = { season: 0 }, growth = [], branchSway = /* @__PURE__ */ new Map()) {
|
|
1403
|
+
const template = TEMPLATES[shape];
|
|
1404
|
+
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
|
+
};
|
|
1426
|
+
for (let c = 0; c < n; c++) {
|
|
1427
|
+
const v = l * n + c;
|
|
1428
|
+
const local = template.positions[c];
|
|
1429
|
+
positions.set(add(leaf.position, scale(toWorld(local), leaf.size)), v * 3);
|
|
1430
|
+
normals.set(normalize(toWorld(template.normals[c])), v * 3);
|
|
1431
|
+
const along = Math.min(Math.max(local[2], 0), 1);
|
|
1432
|
+
uvs.set([local[0] + .5, along], v * 2);
|
|
1433
|
+
colors.set(leaf.tint, v * 3);
|
|
1434
|
+
writePart(attributes, v, part, along);
|
|
1435
|
+
}
|
|
1436
|
+
template.triangles.forEach((triangle, t) => {
|
|
1437
|
+
indices.set(triangle.map((i) => l * n + i), (l * template.triangles.length + t) * 3);
|
|
1438
|
+
});
|
|
1439
|
+
});
|
|
1440
|
+
return {
|
|
1441
|
+
positions,
|
|
1442
|
+
normals,
|
|
1443
|
+
uvs,
|
|
1444
|
+
colors,
|
|
1445
|
+
indices,
|
|
1446
|
+
attributes
|
|
1447
|
+
};
|
|
1448
|
+
}
|
|
1449
|
+
// src/generator/leaves.ts
|
|
1450
|
+
var DEG = Math.PI / 180;
|
|
1451
|
+
/** Leaf card width as a fraction of its length. */
|
|
1452
|
+
var LEAF_WIDTH = .5;
|
|
1453
|
+
/**
|
|
1454
|
+
* Places leaves on the outermost branches (the trunk if there are no branch levels).
|
|
1455
|
+
* Each leaf draws from `random.fork(leafId)`, so leaves never shift the branches and
|
|
1456
|
+
* one leaf never shifts another. The colour tint shared by the whole tree comes from
|
|
1457
|
+
* `random.fork('tint')`. The shape ('card' here, 'clump'/'needle'/'puff' in `leaf-shapes.ts`) only affects the mesh.
|
|
1458
|
+
*/
|
|
1459
|
+
function placeLeaves(definition, branches, random) {
|
|
1460
|
+
const { leaves } = definition;
|
|
1461
|
+
if (leaves.count === 0) return [];
|
|
1462
|
+
const outermost = definition.branches.length;
|
|
1463
|
+
const half = definition.variation.color / 2;
|
|
1464
|
+
const tintRandom = random.fork("tint");
|
|
1465
|
+
const treeTint = [
|
|
1466
|
+
0,
|
|
1467
|
+
1,
|
|
1468
|
+
2
|
|
1469
|
+
].map(() => tintRandom.range(-half, half));
|
|
1470
|
+
const tilt = Math.min(leaves.angle, 180) * DEG;
|
|
1471
|
+
const out = [];
|
|
1472
|
+
for (const branch of branches) {
|
|
1473
|
+
if (branch.level !== outermost) continue;
|
|
1474
|
+
const frames = branchFrames(branch);
|
|
1475
|
+
for (let i = 0; i < leaves.count; i++) {
|
|
1476
|
+
const id = `${branch.path}/${i}`;
|
|
1477
|
+
const r = random.fork(id);
|
|
1478
|
+
const t = leaves.start + (1 - leaves.start) * (i + r.range(.1, .9)) / leaves.count;
|
|
1479
|
+
const at = sampleBranch(branch, frames, t);
|
|
1480
|
+
const azimuth = r.range(0, Math.PI * 2);
|
|
1481
|
+
const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin$1(azimuth)));
|
|
1482
|
+
const direction = normalize(add(scale(at.tangent, cos(tilt)), scale(across, sin$1(tilt))));
|
|
1483
|
+
const side0 = cross$1(direction, [
|
|
1484
|
+
0,
|
|
1485
|
+
1,
|
|
1486
|
+
0
|
|
1487
|
+
]);
|
|
1488
|
+
const side = dot$1(side0, side0) > 1e-6 ? normalize(side0) : perpendicular(direction);
|
|
1489
|
+
const roll = r.range(-.4, .4);
|
|
1490
|
+
const normal = normalize(add(scale(cross$1(side, direction), cos(roll)), scale(side, sin$1(roll))));
|
|
1491
|
+
const size = leaves.size * (1 + r.range(-leaves.sizeVariation, leaves.sizeVariation));
|
|
1492
|
+
const brightness = r.range(-half, half);
|
|
1493
|
+
const tint = treeTint.map((c) => 1 + c + brightness);
|
|
1494
|
+
out.push({
|
|
1495
|
+
id,
|
|
1496
|
+
branch: branch.path,
|
|
1497
|
+
index: i,
|
|
1498
|
+
attach: t,
|
|
1499
|
+
position: at.position,
|
|
1500
|
+
direction,
|
|
1501
|
+
normal,
|
|
1502
|
+
size,
|
|
1503
|
+
tint
|
|
1504
|
+
});
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
return out;
|
|
1508
|
+
}
|
|
1509
|
+
/** One diamond-shaped card per leaf (4 vertices, 2 triangles); vertex colours carry the leaf's tint. */
|
|
1510
|
+
function leafGeometry(leaves, level, seed, variation = { season: 0 }, growth = [], branchSway = /* @__PURE__ */ new Map()) {
|
|
1511
|
+
const positions = new Float32Array(leaves.length * 4 * 3);
|
|
1512
|
+
const normals = new Float32Array(leaves.length * 4 * 3);
|
|
1513
|
+
const uvs = new Float32Array(leaves.length * 4 * 2);
|
|
1514
|
+
const colors = new Float32Array(leaves.length * 4 * 3);
|
|
1515
|
+
const indices = new Uint32Array(leaves.length * 6);
|
|
1516
|
+
const attributes = createAttributes(leaves.length * 4);
|
|
1517
|
+
leaves.forEach((leaf, l) => {
|
|
1518
|
+
const side = cross$1(leaf.direction, leaf.normal);
|
|
1519
|
+
const halfWidth = leaf.size * LEAF_WIDTH / 2;
|
|
1520
|
+
const mid = add(leaf.position, scale(leaf.direction, leaf.size * .4));
|
|
1521
|
+
const corners = [
|
|
1522
|
+
leaf.position,
|
|
1523
|
+
add(mid, scale(side, halfWidth)),
|
|
1524
|
+
add(leaf.position, scale(leaf.direction, leaf.size)),
|
|
1525
|
+
add(mid, scale(side, -halfWidth))
|
|
1526
|
+
];
|
|
1527
|
+
const cornerUvs = [
|
|
1528
|
+
.5,
|
|
1529
|
+
0,
|
|
1530
|
+
1,
|
|
1531
|
+
.4,
|
|
1532
|
+
.5,
|
|
1533
|
+
1,
|
|
1534
|
+
0,
|
|
1535
|
+
.4
|
|
1536
|
+
];
|
|
1537
|
+
const part = {
|
|
1538
|
+
level,
|
|
1539
|
+
attach: leaf.attach,
|
|
1540
|
+
random: seedRandom(seed, leaf.id),
|
|
1541
|
+
origin: leaf.position,
|
|
1542
|
+
season: leafSeasonAttribute(seed, variation, leaf.id),
|
|
1543
|
+
growth: growth[l] ?? {
|
|
1544
|
+
start: 0,
|
|
1545
|
+
end: 0
|
|
1546
|
+
},
|
|
1547
|
+
sway: leafSway(branchSway.get(leaf.branch) ?? NO_SWAY, leaf.attach)
|
|
1548
|
+
};
|
|
1549
|
+
for (let c = 0; c < 4; c++) {
|
|
1550
|
+
const v = l * 4 + c;
|
|
1551
|
+
positions.set(corners[c], v * 3);
|
|
1552
|
+
normals.set(leaf.normal, v * 3);
|
|
1553
|
+
uvs.set([cornerUvs[c * 2], cornerUvs[c * 2 + 1]], v * 2);
|
|
1554
|
+
colors.set(leaf.tint, v * 3);
|
|
1555
|
+
writePart(attributes, v, part, cornerUvs[c * 2 + 1]);
|
|
1556
|
+
}
|
|
1557
|
+
const v0 = l * 4;
|
|
1558
|
+
indices.set([
|
|
1559
|
+
v0,
|
|
1560
|
+
v0 + 1,
|
|
1561
|
+
v0 + 2,
|
|
1562
|
+
v0,
|
|
1563
|
+
v0 + 2,
|
|
1564
|
+
v0 + 3
|
|
1565
|
+
], l * 6);
|
|
1566
|
+
});
|
|
1567
|
+
return {
|
|
1568
|
+
positions,
|
|
1569
|
+
normals,
|
|
1570
|
+
uvs,
|
|
1571
|
+
colors,
|
|
1572
|
+
indices,
|
|
1573
|
+
attributes
|
|
1574
|
+
};
|
|
1575
|
+
}
|
|
1576
|
+
// src/generator/mesh.ts
|
|
1577
|
+
/**
|
|
1578
|
+
* Sweeps a ring of `sides` vertices along a branch's points, using parallel-transport
|
|
1579
|
+
* frames so branches in any direction get even rings, and caps the tip.
|
|
1580
|
+
*/
|
|
1581
|
+
function sweepBranch(branch, sides, random, season = {
|
|
1582
|
+
shift: 0,
|
|
1583
|
+
coverageRank: 0,
|
|
1584
|
+
blossomRank: 0
|
|
1585
|
+
}, growth = {
|
|
1586
|
+
start: 0,
|
|
1587
|
+
end: 0
|
|
1588
|
+
}, sway) {
|
|
1589
|
+
const pts = branch.points;
|
|
1590
|
+
const frames = branchFrames(branch);
|
|
1591
|
+
const rings = pts.length;
|
|
1592
|
+
const ringSize = sides + 1;
|
|
1593
|
+
const vertexCount = rings * ringSize + 1;
|
|
1594
|
+
const positions = new Float32Array(vertexCount * 3);
|
|
1595
|
+
const normals = new Float32Array(vertexCount * 3);
|
|
1596
|
+
const uvs = new Float32Array(vertexCount * 2);
|
|
1597
|
+
const indices = [];
|
|
1598
|
+
const attributes = createAttributes(vertexCount);
|
|
1599
|
+
const part = {
|
|
1600
|
+
level: branch.level,
|
|
1601
|
+
attach: branch.attach,
|
|
1602
|
+
random,
|
|
1603
|
+
origin: pts[0].position,
|
|
1604
|
+
season,
|
|
1605
|
+
growth,
|
|
1606
|
+
sway
|
|
1607
|
+
};
|
|
1608
|
+
const slope = (pts[0].radius - pts[rings - 1].radius) / Math.max(pathLength(branch), 1e-6);
|
|
1609
|
+
let v = 0;
|
|
1610
|
+
for (let r = 0; r < rings; r++) {
|
|
1611
|
+
const { position, radius } = pts[r];
|
|
1612
|
+
const { tangent, normal, binormal } = frames[r];
|
|
1613
|
+
for (let s = 0; s <= sides; s++) {
|
|
1614
|
+
const angle = s % sides / sides * Math.PI * 2;
|
|
1615
|
+
const radial = add(scale(normal, cos(angle)), scale(binormal, sin$1(angle)));
|
|
1616
|
+
positions.set(add(position, scale(radial, radius)), v * 3);
|
|
1617
|
+
normals.set(normalize(add(radial, scale(tangent, slope))), v * 3);
|
|
1618
|
+
uvs.set([s / sides, r / (rings - 1)], v * 2);
|
|
1619
|
+
writePart(attributes, v, part, r / (rings - 1), radius);
|
|
1620
|
+
v++;
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
for (let r = 0; r < rings - 1; r++) for (let s = 0; s < sides; s++) {
|
|
1624
|
+
const a = r * ringSize + s;
|
|
1625
|
+
const b = a + 1;
|
|
1626
|
+
const c = a + ringSize;
|
|
1627
|
+
const d = c + 1;
|
|
1628
|
+
indices.push(a, b, c, b, d, c);
|
|
1629
|
+
}
|
|
1630
|
+
const tip = v;
|
|
1631
|
+
positions.set(pts[rings - 1].position, tip * 3);
|
|
1632
|
+
normals.set(frames[rings - 1].tangent, tip * 3);
|
|
1633
|
+
uvs.set([.5, 1], tip * 2);
|
|
1634
|
+
writePart(attributes, tip, part, 1);
|
|
1635
|
+
const lastRing = (rings - 1) * ringSize;
|
|
1636
|
+
for (let s = 0; s < sides; s++) indices.push(lastRing + s, lastRing + s + 1, tip);
|
|
1637
|
+
return {
|
|
1638
|
+
positions,
|
|
1639
|
+
normals,
|
|
1640
|
+
uvs,
|
|
1641
|
+
indices: Uint32Array.from(indices),
|
|
1642
|
+
attributes
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
/** Concatenates geometry buffers into one (indices are offset). */
|
|
1646
|
+
function mergeBuffers(parts) {
|
|
1647
|
+
const vertexCount = parts.reduce((n, p) => n + p.positions.length / 3, 0);
|
|
1648
|
+
const indexCount = parts.reduce((n, p) => n + p.indices.length, 0);
|
|
1649
|
+
const out = {
|
|
1650
|
+
positions: new Float32Array(vertexCount * 3),
|
|
1651
|
+
normals: new Float32Array(vertexCount * 3),
|
|
1652
|
+
uvs: new Float32Array(vertexCount * 2),
|
|
1653
|
+
indices: new Uint32Array(indexCount),
|
|
1654
|
+
attributes: createAttributes(vertexCount)
|
|
1655
|
+
};
|
|
1656
|
+
let v = 0;
|
|
1657
|
+
let i = 0;
|
|
1658
|
+
for (const part of parts) {
|
|
1659
|
+
out.positions.set(part.positions, v * 3);
|
|
1660
|
+
out.normals.set(part.normals, v * 3);
|
|
1661
|
+
out.uvs.set(part.uvs, v * 2);
|
|
1662
|
+
for (const [name, attribute] of Object.entries(out.attributes)) attribute.array.set(part.attributes[name].array, v * attribute.itemSize);
|
|
1663
|
+
for (let k = 0; k < part.indices.length; k++) out.indices[i + k] = part.indices[k] + v;
|
|
1664
|
+
v += part.positions.length / 3;
|
|
1665
|
+
i += part.indices.length;
|
|
1666
|
+
}
|
|
1667
|
+
return out;
|
|
1668
|
+
}
|
|
1669
|
+
// src/generator/sculpt.ts
|
|
1670
|
+
/**
|
|
1671
|
+
* The Sculpt pass (ADR 0003): hand edits stored in the Definition, applied after the procedural
|
|
1672
|
+
* skeleton is grown and before leaves, Growth timing, Wind weights and meshes are derived from it.
|
|
1673
|
+
* So a sculpted part still grows, changes with the Season and sways like any other.
|
|
1674
|
+
*
|
|
1675
|
+
* A Sculpt only applies on the Seed it was made on; every other Seed ignores it. Sculpts apply in
|
|
1676
|
+
* Definition order. A Sculpt whose path does not exist (any more) for this Seed is skipped.
|
|
1677
|
+
*/
|
|
1678
|
+
function sculptsFor(definition, seed) {
|
|
1679
|
+
return definition.sculpts.filter((s) => s.seed === seed);
|
|
1680
|
+
}
|
|
1681
|
+
/** True if `path` is `root` or grows from it (its descendants). */
|
|
1682
|
+
var inSubtree = (path, root) => path === root || path.startsWith(`${root}.`);
|
|
1683
|
+
/**
|
|
1684
|
+
* Applies the branch Sculpts to the skeleton branches (returns a new array, paths unchanged):
|
|
1685
|
+
* - `delete` drops the branch and everything growing from it;
|
|
1686
|
+
* - `move` rotates (Euler XYZ, radians, three.js convention, in tree space) and scales the branch
|
|
1687
|
+
* and everything growing from it about the branch base. `scale` scales lengths; radii stay.
|
|
1688
|
+
*/
|
|
1689
|
+
function sculptBranches(branches, sculpts) {
|
|
1690
|
+
let out = branches;
|
|
1691
|
+
for (const sculpt of sculpts) if (sculpt.action === "delete") out = out.filter((b) => !inSubtree(b.path, sculpt.path));
|
|
1692
|
+
else if (sculpt.action === "move") {
|
|
1693
|
+
const root = out.find((b) => b.path === sculpt.path);
|
|
1694
|
+
if (!root) continue;
|
|
1695
|
+
const base = root.points[0].position;
|
|
1696
|
+
const rotate = eulerXYZ(sculpt.rotation);
|
|
1697
|
+
const move = (p) => add(base, rotate(scale(sub(p, base), sculpt.scale)));
|
|
1698
|
+
out = out.map((b) => inSubtree(b.path, sculpt.path) ? {
|
|
1699
|
+
...b,
|
|
1700
|
+
direction: rotate(b.direction),
|
|
1701
|
+
points: b.points.map((p) => ({
|
|
1702
|
+
position: move(p.position),
|
|
1703
|
+
radius: p.radius
|
|
1704
|
+
}))
|
|
1705
|
+
} : b);
|
|
1706
|
+
}
|
|
1707
|
+
return out;
|
|
1708
|
+
}
|
|
1709
|
+
/**
|
|
1710
|
+
* Applies the `leaves` Sculpts (painting): each sets the coverage (0..1) of a branch and everything
|
|
1711
|
+
* growing from it; a later Sculpt on a sub-branch overrides it there. A leaf is kept while its own
|
|
1712
|
+
* stable random number (from the Seed and leaf id) is below its coverage, so painting more coverage
|
|
1713
|
+
* only ever adds leaves. Season coverage then applies on top of the kept leaves as usual.
|
|
1714
|
+
*/
|
|
1715
|
+
function sculptLeaves(leaves, sculpts, seed) {
|
|
1716
|
+
const painted = sculpts.filter((s) => s.action === "leaves");
|
|
1717
|
+
if (painted.length === 0) return leaves;
|
|
1718
|
+
return leaves.filter((leaf) => {
|
|
1719
|
+
let coverage = 1;
|
|
1720
|
+
for (const s of painted) if (inSubtree(leaf.branch, s.path)) coverage = s.coverage;
|
|
1721
|
+
return seedRandom(seed, `sculpt/${leaf.id}`) < coverage;
|
|
1722
|
+
});
|
|
1723
|
+
}
|
|
1724
|
+
/** The rotation of a three.js `Euler(x, y, z, 'XYZ')` (matrix Rx * Ry * Rz) as a function on vectors. */
|
|
1725
|
+
function eulerXYZ([x, y, z]) {
|
|
1726
|
+
const [a, b, c, d, e, f] = [
|
|
1727
|
+
cos(x),
|
|
1728
|
+
sin$1(x),
|
|
1729
|
+
cos(y),
|
|
1730
|
+
sin$1(y),
|
|
1731
|
+
cos(z),
|
|
1732
|
+
sin$1(z)
|
|
1733
|
+
];
|
|
1734
|
+
const [ae, af, be, bf] = [
|
|
1735
|
+
a * e,
|
|
1736
|
+
a * f,
|
|
1737
|
+
b * e,
|
|
1738
|
+
b * f
|
|
1739
|
+
];
|
|
1740
|
+
const m = [
|
|
1741
|
+
c * e,
|
|
1742
|
+
-c * f,
|
|
1743
|
+
d,
|
|
1744
|
+
af + be * d,
|
|
1745
|
+
ae - bf * d,
|
|
1746
|
+
-b * c,
|
|
1747
|
+
bf - ae * d,
|
|
1748
|
+
be + af * d,
|
|
1749
|
+
a * c
|
|
1750
|
+
];
|
|
1751
|
+
return ([vx, vy, vz]) => [
|
|
1752
|
+
m[0] * vx + m[1] * vy + m[2] * vz,
|
|
1753
|
+
m[3] * vx + m[4] * vy + m[5] * vz,
|
|
1754
|
+
m[6] * vx + m[7] * vy + m[8] * vz
|
|
1755
|
+
];
|
|
1756
|
+
}
|
|
1757
|
+
// 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) {
|
|
1760
|
+
const { trunk } = definition;
|
|
1761
|
+
const length = trunk.length * (1 + random.range(-trunk.lengthVariation, trunk.lengthVariation));
|
|
1762
|
+
const sectionLength = length / trunk.sections;
|
|
1763
|
+
const maxDrift = trunk.bend * sectionLength;
|
|
1764
|
+
const points = [];
|
|
1765
|
+
let x = 0;
|
|
1766
|
+
let z = 0;
|
|
1767
|
+
for (let i = 0; i <= trunk.sections; i++) {
|
|
1768
|
+
const t = i / trunk.sections;
|
|
1769
|
+
if (i > 0) {
|
|
1770
|
+
x += random.range(-maxDrift, maxDrift);
|
|
1771
|
+
z += random.range(-maxDrift, maxDrift);
|
|
1772
|
+
}
|
|
1773
|
+
points.push({
|
|
1774
|
+
position: [
|
|
1775
|
+
x,
|
|
1776
|
+
t * length,
|
|
1777
|
+
z
|
|
1778
|
+
],
|
|
1779
|
+
radius: trunk.radius * (1 + (trunk.taper - 1) * t)
|
|
1780
|
+
});
|
|
1781
|
+
}
|
|
1782
|
+
return {
|
|
1783
|
+
path: "0",
|
|
1784
|
+
parent: null,
|
|
1785
|
+
level: 0,
|
|
1786
|
+
attach: 0,
|
|
1787
|
+
direction: [
|
|
1788
|
+
0,
|
|
1789
|
+
1,
|
|
1790
|
+
0
|
|
1791
|
+
],
|
|
1792
|
+
points
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
// src/generator/index.ts
|
|
1796
|
+
/**
|
|
1797
|
+
* The Generator: a pure function from a (parsed) Tree Definition and a Seed to tree data.
|
|
1798
|
+
* No three.js, no GPU, no globals; runs in Node. Same input, same output, on every machine.
|
|
1799
|
+
*
|
|
1800
|
+
* Each part of the tree draws from its own `random.fork(<part>)` stream so that adding
|
|
1801
|
+
* a new part never shifts the numbers of an existing one.
|
|
1802
|
+
*/
|
|
1803
|
+
function generateTree(definition, seed) {
|
|
1804
|
+
const random = createRandom(seed);
|
|
1805
|
+
const trunk = buildTrunk(definition, random.fork("trunk"));
|
|
1806
|
+
const sculpts = sculptsFor(definition, seed);
|
|
1807
|
+
const branches = sculptBranches([trunk, ...buildBranches(definition, trunk, random.fork("branches"))], sculpts);
|
|
1808
|
+
const sidesOf = (level) => level === 0 ? definition.trunk.sides : definition.branches[level - 1].sides;
|
|
1809
|
+
const leaves = sculptLeaves(placeLeaves(definition, branches, random.fork("leaves")), sculpts, seed);
|
|
1810
|
+
const growth = growthTiming(definition, seed, branches, leaves);
|
|
1811
|
+
const sway = branchSway(branches, definition.branches.length);
|
|
1812
|
+
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
|
+
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);
|
|
1814
|
+
const skeleton = {
|
|
1815
|
+
branches,
|
|
1816
|
+
leaves
|
|
1817
|
+
};
|
|
1818
|
+
writeTrunkSway(wood, trunkHeight(skeleton));
|
|
1819
|
+
writeTrunkSway(leafBuffers, trunkHeight(skeleton));
|
|
1820
|
+
return {
|
|
1821
|
+
seed,
|
|
1822
|
+
skeleton,
|
|
1823
|
+
wood,
|
|
1824
|
+
leaves: leafBuffers,
|
|
1825
|
+
growth
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1828
|
+
/**
|
|
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.
|
|
1831
|
+
*/
|
|
1832
|
+
function trunkHeight(skeleton) {
|
|
1833
|
+
const trunk = skeleton.branches.find((b) => b.parent === null)?.points;
|
|
1834
|
+
return trunk ? trunk[trunk.length - 1].position[1] : 1;
|
|
1835
|
+
}
|
|
1836
|
+
/** Stable 32-bit hash (hex) of the generated geometry buffers, for determinism checks. */
|
|
1837
|
+
function hashGeometry(geometry) {
|
|
1838
|
+
return hex(hashBuffers(geometry));
|
|
1839
|
+
}
|
|
1840
|
+
/** Stable hash of a tree's generated geometry (wood and leaves). */
|
|
1841
|
+
function hashTreeData(data) {
|
|
1842
|
+
return hex(hashBuffers(data.leaves, hashBuffers(data.wood)));
|
|
1843
|
+
}
|
|
1844
|
+
function hashBuffers(geometry, h) {
|
|
1845
|
+
const arrays = [
|
|
1846
|
+
geometry.positions,
|
|
1847
|
+
geometry.normals,
|
|
1848
|
+
geometry.uvs,
|
|
1849
|
+
geometry.colors,
|
|
1850
|
+
geometry.indices
|
|
1851
|
+
];
|
|
1852
|
+
for (const name of Object.keys(geometry.attributes).sort()) arrays.push(geometry.attributes[name].array);
|
|
1853
|
+
for (const array of arrays) if (array) h = hashBytes(new Uint8Array(array.buffer, array.byteOffset, array.byteLength), h);
|
|
1854
|
+
return h;
|
|
1855
|
+
}
|
|
1856
|
+
var hex = (h) => h.toString(16).padStart(8, "0");
|
|
1857
|
+
// src/growth/evaluate.ts
|
|
1858
|
+
/**
|
|
1859
|
+
* The Growth model, one spec with two backends: `growPositions` (CPU, here) and `growthPosition`
|
|
1860
|
+
* (TSL, `./tsl.ts`). Keep them in step. Per vertex, at Growth `g`:
|
|
1861
|
+
*
|
|
1862
|
+
* 1. thicken: move the vertex towards its part's centre line, keeping `thickness(g)` of its radius
|
|
1863
|
+
* (`aGrowth.z`, along the vertex normal);
|
|
1864
|
+
* 2. sprout: scale the part about its base point (`aOrigin`) by `partProgress(g, start, end)`
|
|
1865
|
+
* (`aGrowth.xy`), so a part grows out of a point on its (already grown) parent;
|
|
1866
|
+
* 3. size: scale the whole tree about its base (local origin) by `treeScale(g)`.
|
|
1867
|
+
*
|
|
1868
|
+
* Every step is written as `x - offset * (1 - factor)`, so at Growth 1 the positions are exactly
|
|
1869
|
+
* the generated ones: a tree at Growth 1 is a normal static tree.
|
|
1870
|
+
*/
|
|
1871
|
+
/** Size of the whole tree at Growth 0 (sapling), relative to fully grown. */
|
|
1872
|
+
var SAPLING_SCALE = .2;
|
|
1873
|
+
/** Branch thickness at Growth 0, relative to the size-scaled thickness when fully grown. */
|
|
1874
|
+
var SAPLING_THICKNESS = .4;
|
|
1875
|
+
/** Smallest window width, so parts with `start == end` (the trunk) are simply grown. */
|
|
1876
|
+
var MIN_WINDOW = 1e-5;
|
|
1877
|
+
var treeScale$1 = (growth) => SAPLING_SCALE + .8 * growth;
|
|
1878
|
+
var thickness$1 = (growth) => SAPLING_THICKNESS + .6 * growth;
|
|
1879
|
+
/** How far one part has sprouted (0 = not yet, 1 = full size), eased; 1 from `end` on. */
|
|
1880
|
+
function partProgress$1(growth, start, end) {
|
|
1881
|
+
const p = Math.min(Math.max((growth - end) / Math.max(end - start, MIN_WINDOW) + 1, 0), 1);
|
|
1882
|
+
return p * p * (3 - 2 * p);
|
|
1883
|
+
}
|
|
1884
|
+
/** Clamps a Growth value to 0..1 (NaN becomes 1, fully grown). */
|
|
1885
|
+
function clampGrowth(growth) {
|
|
1886
|
+
return Number.isNaN(growth) ? 1 : Math.min(Math.max(growth, 0), 1);
|
|
1887
|
+
}
|
|
1888
|
+
/**
|
|
1889
|
+
* Vertex positions of generated geometry at a given Growth, on the CPU (for baking a tree and
|
|
1890
|
+
* for tests; at runtime the same model runs in TSL). Returns a new array.
|
|
1891
|
+
*/
|
|
1892
|
+
function growPositions(buffers, growth) {
|
|
1893
|
+
const g = clampGrowth(growth);
|
|
1894
|
+
const { positions, normals } = buffers;
|
|
1895
|
+
const { aOrigin, aGrowth } = buffers.attributes;
|
|
1896
|
+
const out = new Float32Array(positions.length);
|
|
1897
|
+
const scale = treeScale$1(g);
|
|
1898
|
+
const thin = 1 - thickness$1(g);
|
|
1899
|
+
for (let v = 0; v < positions.length / 3; v++) {
|
|
1900
|
+
const [start, end, radius] = [
|
|
1901
|
+
aGrowth.array[v * 3],
|
|
1902
|
+
aGrowth.array[v * 3 + 1],
|
|
1903
|
+
aGrowth.array[v * 3 + 2]
|
|
1904
|
+
];
|
|
1905
|
+
const shrink = 1 - partProgress$1(g, start, end);
|
|
1906
|
+
for (let k = 0; k < 3; k++) {
|
|
1907
|
+
const i = v * 3 + k;
|
|
1908
|
+
const thick = positions[i] - normals[i] * radius * thin;
|
|
1909
|
+
const sprouted = thick - (thick - aOrigin.array[i]) * shrink;
|
|
1910
|
+
out[i] = sprouted - sprouted * (1 - scale);
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
return out;
|
|
1914
|
+
}
|
|
1915
|
+
// src/growth/tsl.ts
|
|
1916
|
+
/** Size of the whole tree at Growth `g` (twin of `treeScale`). */
|
|
1917
|
+
var treeScale = (g) => float(SAPLING_SCALE).add(float(1 - SAPLING_SCALE).mul(g));
|
|
1918
|
+
/** Branch thickness at Growth `g` (twin of `thickness`). */
|
|
1919
|
+
var thickness = (g) => float(SAPLING_THICKNESS).add(float(1 - SAPLING_THICKNESS).mul(g));
|
|
1920
|
+
/** How far one part has sprouted, eased (twin of `partProgress`). */
|
|
1921
|
+
function partProgress(g, start, end) {
|
|
1922
|
+
const p = g.sub(end).div(end.sub(start).max(MIN_WINDOW)).add(1).clamp(0, 1);
|
|
1923
|
+
return p.mul(p).mul(float(3).sub(p.mul(2)));
|
|
1924
|
+
}
|
|
1925
|
+
/**
|
|
1926
|
+
* Growth in TSL: the vertex position of a tree part at Growth `growth` (a float node, usually the
|
|
1927
|
+
* tree's Growth uniform; a Forest can pass a per-instance attribute instead). Same model and steps
|
|
1928
|
+
* as `growPositions` (see `./evaluate.ts`), driven by the Generator's `aGrowth` and `aOrigin` attributes.
|
|
1929
|
+
*
|
|
1930
|
+
* `position` is the input position (default `positionLocal`). To compose with other vertex effects,
|
|
1931
|
+
* feed this node into them, e.g. `material.positionNode = windPosition(growthPosition(uGrowth))`:
|
|
1932
|
+
* Growth first, so the rest acts on the grown tree.
|
|
1933
|
+
*/
|
|
1934
|
+
function growthPosition(growth, position = positionLocal) {
|
|
1935
|
+
const g = float(growth).clamp(0, 1);
|
|
1936
|
+
const data = attribute("aGrowth", "vec3");
|
|
1937
|
+
const origin = attribute("aOrigin", "vec3");
|
|
1938
|
+
const [start, end, radius] = [
|
|
1939
|
+
data.x,
|
|
1940
|
+
data.y,
|
|
1941
|
+
data.z
|
|
1942
|
+
];
|
|
1943
|
+
const scale = treeScale(g);
|
|
1944
|
+
const thin = float(1).sub(thickness(g));
|
|
1945
|
+
const shrink = float(1).sub(partProgress(g, start, end));
|
|
1946
|
+
const thick = position.sub(normalGeometry.mul(radius).mul(thin));
|
|
1947
|
+
const sprouted = thick.sub(thick.sub(origin).mul(shrink));
|
|
1948
|
+
return sprouted.sub(sprouted.mul(float(1).sub(scale)));
|
|
1949
|
+
}
|
|
1950
|
+
// src/textures/index.ts
|
|
1951
|
+
var TEXTURES_DIR = "./textures/";
|
|
1952
|
+
var MODULE_URL = import.meta.url;
|
|
1953
|
+
/**
|
|
1954
|
+
* The URL of the package's bundled textures (the realistic Style's bark and leaf cards), as
|
|
1955
|
+
* shipped in `dist/textures/`. Relative texture URLs in a Definition resolve against it unless
|
|
1956
|
+
* the app sets its own `basePath`.
|
|
1957
|
+
*/
|
|
1958
|
+
var DEFAULT_TEXTURE_BASE_PATH = new URL(TEXTURES_DIR, MODULE_URL).href;
|
|
1959
|
+
var globalOptions = {};
|
|
1960
|
+
/**
|
|
1961
|
+
* Sets the app-wide texture options (base path / URL overrides) used by every tree created
|
|
1962
|
+
* afterwards. Options passed to `createTree(…, { textures })` take precedence.
|
|
1963
|
+
*/
|
|
1964
|
+
function setTextureOptions(options) {
|
|
1965
|
+
globalOptions = {
|
|
1966
|
+
...options,
|
|
1967
|
+
urls: { ...options.urls }
|
|
1968
|
+
};
|
|
1969
|
+
}
|
|
1970
|
+
/** The app-wide texture options set with `setTextureOptions`. */
|
|
1971
|
+
function getTextureOptions() {
|
|
1972
|
+
return {
|
|
1973
|
+
...globalOptions,
|
|
1974
|
+
urls: { ...globalOptions.urls }
|
|
1975
|
+
};
|
|
1976
|
+
}
|
|
1977
|
+
var ABSOLUTE = /^([a-z][a-z\d+.-]*:|\/)/i;
|
|
1978
|
+
/** The URL a Definition's texture URL is loaded from, after URL overrides and the base path. */
|
|
1979
|
+
function resolveTextureUrl(url, options = {}) {
|
|
1980
|
+
const override = options.urls?.[url] ?? globalOptions.urls?.[url];
|
|
1981
|
+
if (override !== void 0) return override;
|
|
1982
|
+
if (ABSOLUTE.test(url)) return url;
|
|
1983
|
+
const base = options.basePath ?? globalOptions.basePath ?? DEFAULT_TEXTURE_BASE_PATH;
|
|
1984
|
+
return (base === "" || base.endsWith("/") ? base : `${base}/`) + url.replace(/^\.\//, "");
|
|
1985
|
+
}
|
|
1986
|
+
var cache = /* @__PURE__ */ new Map();
|
|
1987
|
+
var pending = /* @__PURE__ */ new WeakMap();
|
|
1988
|
+
/**
|
|
1989
|
+
* Loads a texture from an already resolved URL. Textures are shared: the same URL and kind
|
|
1990
|
+
* give the same `Texture` (trees don't dispose them). `texture.name` is the URL. The image
|
|
1991
|
+
* loads asynchronously; `textureReady(texture)` resolves once it is there. Outside a browser
|
|
1992
|
+
* (no DOM, e.g. Node tests) the texture is created without an image.
|
|
1993
|
+
*/
|
|
1994
|
+
function loadTexture(url, kind) {
|
|
1995
|
+
const key = `${kind} ${url}`;
|
|
1996
|
+
const cached = cache.get(key);
|
|
1997
|
+
if (cached) return cached;
|
|
1998
|
+
let texture;
|
|
1999
|
+
let ready;
|
|
2000
|
+
if (typeof document === "undefined") {
|
|
2001
|
+
texture = new Texture();
|
|
2002
|
+
ready = Promise.resolve();
|
|
2003
|
+
} else {
|
|
2004
|
+
let resolve;
|
|
2005
|
+
let reject;
|
|
2006
|
+
ready = new Promise((res, rej) => (resolve = res, reject = rej));
|
|
2007
|
+
texture = new TextureLoader().load(url, () => resolve(), void 0, () => {
|
|
2008
|
+
cache.delete(key);
|
|
2009
|
+
reject(/* @__PURE__ */ new Error(`tree.js: could not load texture ${url}`));
|
|
2010
|
+
});
|
|
2011
|
+
ready.catch(() => {});
|
|
2012
|
+
}
|
|
2013
|
+
texture.name = url;
|
|
2014
|
+
texture.colorSpace = kind === "color" ? SRGBColorSpace : NoColorSpace;
|
|
2015
|
+
texture.wrapS = texture.wrapT = RepeatWrapping;
|
|
2016
|
+
texture.anisotropy = 4;
|
|
2017
|
+
cache.set(key, texture);
|
|
2018
|
+
pending.set(texture, ready);
|
|
2019
|
+
return texture;
|
|
2020
|
+
}
|
|
2021
|
+
/** Resolves when a texture from `loadTexture` has its image (rejects if it failed to load). */
|
|
2022
|
+
function textureReady(texture) {
|
|
2023
|
+
return pending.get(texture) ?? Promise.resolve();
|
|
2024
|
+
}
|
|
2025
|
+
// src/materials/maps.ts
|
|
2026
|
+
/**
|
|
2027
|
+
* How often the bark texture repeats around (u) and along (v) a branch. Bark UVs run 0..1
|
|
2028
|
+
* around and 0..1 along each branch, so this keeps the bark from stretching along long parts.
|
|
2029
|
+
*/
|
|
2030
|
+
var BARK_REPEAT = [2, 6];
|
|
2031
|
+
/**
|
|
2032
|
+
* Textured bark: `color × map` (the glTF base colour convention) and a tangent-space normal map,
|
|
2033
|
+
* both tiled by `BARK_REPEAT`. Returns the colour node to use, or `base` when there is no map.
|
|
2034
|
+
* `.map` / `.normalMap` are also set, for exporters and so `tree.ready` can wait for them.
|
|
2035
|
+
*/
|
|
2036
|
+
function applyBarkMaps(material, bark, base, textures) {
|
|
2037
|
+
const tiled = uv().mul(vec2(...BARK_REPEAT));
|
|
2038
|
+
if (bark.normalMap) {
|
|
2039
|
+
material.normalMap = load(bark.normalMap, "data", textures);
|
|
2040
|
+
material.normalNode = normalMap(texture(material.normalMap, tiled));
|
|
2041
|
+
}
|
|
2042
|
+
if (!bark.map) return base;
|
|
2043
|
+
material.map = load(bark.map, "color", textures);
|
|
2044
|
+
return base.mul(texture(material.map, tiled).rgb);
|
|
2045
|
+
}
|
|
2046
|
+
/**
|
|
2047
|
+
* Alpha-cut leaf cards: `colorNode` = the card texture (rgba, card UVs), cut at `alphaTest`.
|
|
2048
|
+
* The Season colour is multiplied in later (`applySeasonToLeafMaterial`). `.map` is set too, so
|
|
2049
|
+
* the shadow pass cuts the same shape out of the leaf shadows.
|
|
2050
|
+
*/
|
|
2051
|
+
function applyLeafMap(material, leaf, textures) {
|
|
2052
|
+
if (!leaf.map) return;
|
|
2053
|
+
material.map = load(leaf.map, "color", textures);
|
|
2054
|
+
material.colorNode = texture(material.map);
|
|
2055
|
+
material.alphaTest = leaf.alphaTest;
|
|
2056
|
+
}
|
|
2057
|
+
var load = (url, kind, textures) => loadTexture(resolveTextureUrl(url, textures), kind);
|
|
2058
|
+
// src/materials/toon.ts
|
|
2059
|
+
/** Brightness of the shaded side, relative to the lit side (the toon "shadow tone"). */
|
|
2060
|
+
var SHADE = .5;
|
|
2061
|
+
/** The soft band between shade and light, in N·L (a hard toon edge would be 0 wide). */
|
|
2062
|
+
var BAND_START = 0;
|
|
2063
|
+
var BAND_END = .2;
|
|
2064
|
+
/**
|
|
2065
|
+
* Soft toon lighting: two tones (lit and shaded) per light with a smooth band in between,
|
|
2066
|
+
* plus plain diffuse ambient/hemisphere light. No specular or environment reflections. Built
|
|
2067
|
+
* in TSL from the light direction only, so it needs no gradient texture (no image files).
|
|
2068
|
+
*/
|
|
2069
|
+
var SoftToonLightingModel = class extends LightingModel {
|
|
2070
|
+
direct({ lightDirection, lightColor, reflectedLight }) {
|
|
2071
|
+
const dotNL = normalView.dot(lightDirection);
|
|
2072
|
+
const tone = mix(float(SHADE), float(1), smoothstep(BAND_START, BAND_END, dotNL));
|
|
2073
|
+
const irradiance = lightColor.mul(tone);
|
|
2074
|
+
reflectedLight.directDiffuse.addAssign(irradiance.mul(BRDF_Lambert({ diffuseColor: diffuseColor.rgb })));
|
|
2075
|
+
}
|
|
2076
|
+
indirect(builder) {
|
|
2077
|
+
const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
|
|
2078
|
+
reflectedLight.indirectDiffuse.addAssign(irradiance.mul(BRDF_Lambert({ diffuseColor })));
|
|
2079
|
+
reflectedLight.indirectDiffuse.mulAssign(ambientOcclusion);
|
|
2080
|
+
}
|
|
2081
|
+
};
|
|
2082
|
+
/**
|
|
2083
|
+
* The stylized Style's material (`materials.shading: 'toon'`): a `MeshStandardNodeMaterial`
|
|
2084
|
+
* lit by the soft toon model. Staying a standard material keeps every part node (Season
|
|
2085
|
+
* colour, Growth/Wind `positionNode`) and exporters (they see a plain PBR material) working
|
|
2086
|
+
* the same as for the other Styles.
|
|
2087
|
+
*/
|
|
2088
|
+
var SoftToonNodeMaterial = class extends MeshStandardNodeMaterial {
|
|
2089
|
+
isSoftToonMaterial = true;
|
|
2090
|
+
setupLightingModel() {
|
|
2091
|
+
return new SoftToonLightingModel();
|
|
2092
|
+
}
|
|
2093
|
+
};
|
|
2094
|
+
// src/materials/shading.ts
|
|
2095
|
+
/**
|
|
2096
|
+
* The Style layer of the tree materials: the base node material for a Definition's
|
|
2097
|
+
* `materials.shading`. `createBarkMaterial` / `createLeafMaterial` start from it and then set
|
|
2098
|
+
* their part-specific nodes (bark colour, Season colour, Growth/Wind `positionNode`), so those
|
|
2099
|
+
* shared nodes work the same in every Style.
|
|
2100
|
+
*
|
|
2101
|
+
* - `flat` (low-poly): faceted lighting from the screen-space face normal (`flatShading`), so
|
|
2102
|
+
* facets stay correct when Growth or Wind move vertices in `positionNode`. Rough, no gloss.
|
|
2103
|
+
* - `standard` (realistic): smooth PBR shading.
|
|
2104
|
+
* - `toon` (stylized): soft two-tone toon lighting (`SoftToonNodeMaterial`, still a standard
|
|
2105
|
+
* node material underneath), smooth normals so leaf clumps read as rounded.
|
|
2106
|
+
*/
|
|
2107
|
+
function createShadedMaterial(shading) {
|
|
2108
|
+
const material = shading === "toon" ? new SoftToonNodeMaterial() : new MeshStandardNodeMaterial();
|
|
2109
|
+
material.flatShading = shading === "flat";
|
|
2110
|
+
return material;
|
|
2111
|
+
}
|
|
2112
|
+
/** Whether a shading model wants solid (flat) colours rather than smooth colour gradients. */
|
|
2113
|
+
var isFlatShading = (shading) => shading === "flat";
|
|
2114
|
+
// src/materials/index.ts
|
|
2115
|
+
/**
|
|
2116
|
+
* Bark material: a TSL node material (ADR 0002). Growth/Season/Wind uniforms and
|
|
2117
|
+
* per-Style variants hook in here in later tickets (#5-#10). `materials.bark.map` / `.normalMap`
|
|
2118
|
+
* load through `textures` (base path / URL overrides, see `TextureOptions`).
|
|
2119
|
+
*/
|
|
2120
|
+
function createBarkMaterial(definition, textures) {
|
|
2121
|
+
const material = createShadedMaterial(definition.materials.shading);
|
|
2122
|
+
material.name = "tree.js bark";
|
|
2123
|
+
material.userData.treePart = "bark";
|
|
2124
|
+
const base = color(definition.materials.bark.color);
|
|
2125
|
+
const shaded = isFlatShading(definition.materials.shading) ? base : mix(base.mul(.75), base, uv().y.clamp(0, 1).pow(float(.5)));
|
|
2126
|
+
material.colorNode = applyBarkMaps(material, definition.materials.bark, shaded, textures);
|
|
2127
|
+
material.roughness = definition.materials.bark.roughness;
|
|
2128
|
+
material.metalness = 0;
|
|
2129
|
+
return material;
|
|
2130
|
+
}
|
|
2131
|
+
/**
|
|
2132
|
+
* Leaf material: a TSL node material lit from both sides. `.color` is the Season Profile's
|
|
2133
|
+
* leaf colour at Season 0 (what exporters see); `Tree` adds the Season nodes
|
|
2134
|
+
* (`applySeasonToLeafMaterial`), whose colour is multiplied by the per-leaf vertex colours (the Seed's tint)
|
|
2135
|
+
* and by the leaf card texture (`materials.leaf.map`, alpha cut at `alphaTest`), if any.
|
|
2136
|
+
*/
|
|
2137
|
+
function createLeafMaterial(definition, textures) {
|
|
2138
|
+
const material = createShadedMaterial(definition.materials.shading);
|
|
2139
|
+
material.name = "tree.js leaves";
|
|
2140
|
+
material.userData.treePart = "leaves";
|
|
2141
|
+
material.color.set(definition.season.leafColor[0].value);
|
|
2142
|
+
material.vertexColors = true;
|
|
2143
|
+
material.side = DoubleSide;
|
|
2144
|
+
material.roughness = definition.materials.leaf.roughness;
|
|
2145
|
+
material.metalness = 0;
|
|
2146
|
+
applyLeafMap(material, definition.materials.leaf, textures);
|
|
2147
|
+
return material;
|
|
2148
|
+
}
|
|
2149
|
+
// src/renderer/index.ts
|
|
2150
|
+
/** Thrown when a tree is drawn by anything other than `WebGPURenderer` (ADR 0002). */
|
|
2151
|
+
var UnsupportedRendererError = class extends Error {
|
|
2152
|
+
constructor(what) {
|
|
2153
|
+
super(`tree.js requires WebGPURenderer (import { WebGPURenderer } from 'three/webgpu'), but the tree is being drawn by ${what}. The classic WebGLRenderer is not supported because tree materials are TSL node materials. WebGPURenderer runs on WebGPU and falls back to WebGL2 by itself, so switching renderers keeps WebGL2 support.`);
|
|
2154
|
+
this.name = "UnsupportedRendererError";
|
|
2155
|
+
}
|
|
2156
|
+
};
|
|
2157
|
+
/** Throws {@link UnsupportedRendererError} unless `renderer` is a `WebGPURenderer` (either backend). */
|
|
2158
|
+
function assertWebGPURenderer(renderer) {
|
|
2159
|
+
const r = renderer;
|
|
2160
|
+
if (r?.isWebGPURenderer === true) return;
|
|
2161
|
+
throw new UnsupportedRendererError(r?.isWebGLRenderer ? "the classic WebGLRenderer" : "an unknown renderer");
|
|
2162
|
+
}
|
|
2163
|
+
// src/season/nodes.ts
|
|
2164
|
+
/**
|
|
2165
|
+
* Unrolls a keyframe track into a chain of mixes over uniforms (one per segment). Same maths
|
|
2166
|
+
* as `sampleTrack` in `./profile.ts`. Key times and values are uniforms, so editing a value
|
|
2167
|
+
* never recompiles; only a different key count does.
|
|
2168
|
+
*/
|
|
2169
|
+
function keyframeNode(s, track, toUniform) {
|
|
2170
|
+
const ts = track.map((k) => uniform(k.t));
|
|
2171
|
+
const vs = track.map((k) => toUniform(k.value));
|
|
2172
|
+
let out = vs[0];
|
|
2173
|
+
for (let i = 0; i < track.length - 1; i++) {
|
|
2174
|
+
const f = s.sub(ts[i]).div(ts[i + 1].sub(ts[i]).max(KEYFRAME_EPSILON)).clamp(0, 1);
|
|
2175
|
+
out = mix(out, vs[i + 1], f);
|
|
2176
|
+
}
|
|
2177
|
+
return out;
|
|
2178
|
+
}
|
|
2179
|
+
function createSeasonNodes(profile, season = uniform(0)) {
|
|
2180
|
+
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);
|
|
2183
|
+
const leafColor = keyframeNode(s, profile.leafColor, (v) => uniform(new Color(v)));
|
|
2184
|
+
const coverage = keyframeNode(s, profile.leafCoverage, (v) => uniform(v));
|
|
2185
|
+
const blossom = keyframeNode(s, profile.blossom, (v) => uniform(v));
|
|
2186
|
+
const blossomColor = uniform(new Color(profile.blossomColor));
|
|
2187
|
+
const isBlossom = blossom.greaterThan(aSeason.z);
|
|
2188
|
+
const shown = isBlossom.or(coverage.greaterThan(aSeason.y));
|
|
2189
|
+
return {
|
|
2190
|
+
season,
|
|
2191
|
+
color: varying(select(isBlossom, blossomColor, leafColor)),
|
|
2192
|
+
visible: varying(select(shown, float(1), float(0))).greaterThan(.5)
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
/**
|
|
2196
|
+
* Hooks Season into a leaf material: `colorNode` (times the vertex-colour tint, and times the
|
|
2197
|
+
* material's existing `colorNode`, such as a leaf card texture with alpha) and `maskNode`, which
|
|
2198
|
+
* also cuts fallen leaves out of the shadow pass.
|
|
2199
|
+
*/
|
|
2200
|
+
function applySeasonToLeafMaterial(material, nodes) {
|
|
2201
|
+
material.colorNode = material.colorNode ? vec4(nodes.color, 1).mul(material.colorNode) : nodes.color;
|
|
2202
|
+
material.maskNode = nodes.visible;
|
|
2203
|
+
}
|
|
2204
|
+
// src/season/check.ts
|
|
2205
|
+
/** A Season set by the app: must be finite (RangeError otherwise), then wrapped into 0..1. */
|
|
2206
|
+
function checkedSeason(value) {
|
|
2207
|
+
if (!Number.isFinite(value)) throw new RangeError(`Season must be a finite number, got ${value}`);
|
|
2208
|
+
return wrapSeason(value);
|
|
2209
|
+
}
|
|
2210
|
+
// src/wind/Wind.ts
|
|
2211
|
+
/**
|
|
2212
|
+
* Scene-wide Wind: a direction and a strength that every tree listening to it sways with.
|
|
2213
|
+
* Changing them only writes uniform values (no recompile). Trees use {@link sceneWind} unless
|
|
2214
|
+
* `createTree(..., { wind })` names another one. How much each tree moves is its Definition's
|
|
2215
|
+
* Wind response (`definition.wind`).
|
|
2216
|
+
*/
|
|
2217
|
+
var Wind = class {
|
|
2218
|
+
/** The shared TSL uniforms tree materials read. Write through the setters, not here. */
|
|
2219
|
+
uniforms;
|
|
2220
|
+
pinnedTime = null;
|
|
2221
|
+
constructor(options = {}) {
|
|
2222
|
+
this.uniforms = {
|
|
2223
|
+
direction: uniform(new Vector3(1, 0, 0)),
|
|
2224
|
+
strength: uniform(0),
|
|
2225
|
+
time: uniform(0).onRenderUpdate((frame) => this.pinnedTime ?? frame.time)
|
|
2226
|
+
};
|
|
2227
|
+
this.set(options);
|
|
2228
|
+
}
|
|
2229
|
+
/** Unit direction the wind blows towards (a copy: assign a new value to change it). */
|
|
2230
|
+
get direction() {
|
|
2231
|
+
return this.uniforms.direction.value.clone();
|
|
2232
|
+
}
|
|
2233
|
+
set direction(value) {
|
|
2234
|
+
const v = Array.isArray(value) ? new Vector3(...value) : value.clone();
|
|
2235
|
+
const length = v.length();
|
|
2236
|
+
if (!Number.isFinite(length) || length === 0) throw new RangeError(`Wind direction must be a finite, non-zero vector, got [${v.toArray().join(", ")}]`);
|
|
2237
|
+
this.uniforms.direction.value.copy(v.divideScalar(length));
|
|
2238
|
+
}
|
|
2239
|
+
get strength() {
|
|
2240
|
+
return this.uniforms.strength.value;
|
|
2241
|
+
}
|
|
2242
|
+
set strength(value) {
|
|
2243
|
+
if (!Number.isFinite(value) || value < 0) throw new RangeError(`Wind strength must be a finite number >= 0, got ${value}`);
|
|
2244
|
+
this.uniforms.strength.value = value;
|
|
2245
|
+
}
|
|
2246
|
+
/**
|
|
2247
|
+
* Pins the Wind clock to a time in seconds (pause, deterministic screenshots), or `null`
|
|
2248
|
+
* (default) to follow the renderer's clock.
|
|
2249
|
+
*/
|
|
2250
|
+
get time() {
|
|
2251
|
+
return this.pinnedTime;
|
|
2252
|
+
}
|
|
2253
|
+
set time(value) {
|
|
2254
|
+
this.pinnedTime = value;
|
|
2255
|
+
if (value !== null) this.uniforms.time.value = value;
|
|
2256
|
+
}
|
|
2257
|
+
/** Sets direction and/or strength; returns this. */
|
|
2258
|
+
set(options) {
|
|
2259
|
+
if (options.direction !== void 0) this.direction = options.direction;
|
|
2260
|
+
if (options.strength !== void 0) this.strength = options.strength;
|
|
2261
|
+
return this;
|
|
2262
|
+
}
|
|
2263
|
+
};
|
|
2264
|
+
/** The scene-wide Wind every tree sways with by default. */
|
|
2265
|
+
var sceneWind = new Wind();
|
|
2266
|
+
/**
|
|
2267
|
+
* Per-object Wind uniforms that follow whichever Wind is bound to them, read once per render.
|
|
2268
|
+
* Trees and Forests build their Wind nodes on these, so switching to another Wind is one
|
|
2269
|
+
* assignment: no new nodes, no recompile, no regeneration.
|
|
2270
|
+
*/
|
|
2271
|
+
var WindBinding = class {
|
|
2272
|
+
/** The bound Wind. */
|
|
2273
|
+
wind;
|
|
2274
|
+
uniforms;
|
|
2275
|
+
constructor(wind) {
|
|
2276
|
+
this.wind = wind;
|
|
2277
|
+
const direction = wind.uniforms.direction.value.clone();
|
|
2278
|
+
this.uniforms = {
|
|
2279
|
+
direction: uniform(direction).onRenderUpdate(() => direction.copy(this.wind.uniforms.direction.value)),
|
|
2280
|
+
strength: uniform(wind.strength).onRenderUpdate(() => this.wind.strength),
|
|
2281
|
+
time: uniform(0).onRenderUpdate((frame) => this.wind.time ?? frame.time)
|
|
2282
|
+
};
|
|
2283
|
+
}
|
|
2284
|
+
};
|
|
2285
|
+
// src/wind/response.ts
|
|
2286
|
+
/**
|
|
2287
|
+
* One tree's response to the Wind (from its Definition's `wind`), held in uniforms so the
|
|
2288
|
+
* Tree Editor can change it live. `height` (trunk height) and `phase` (from the Seed) shape the
|
|
2289
|
+
* motion: the sway scales with the tree, and trees of different Seeds move out of step.
|
|
2290
|
+
*/
|
|
2291
|
+
var WindResponse = class {
|
|
2292
|
+
uniforms;
|
|
2293
|
+
constructor(response, shape) {
|
|
2294
|
+
this.uniforms = {
|
|
2295
|
+
trunk: uniform(0),
|
|
2296
|
+
branches: uniform(0),
|
|
2297
|
+
leaves: uniform(0),
|
|
2298
|
+
frequency: uniform(1),
|
|
2299
|
+
height: uniform(shape.height),
|
|
2300
|
+
phase: uniform(shape.phase)
|
|
2301
|
+
};
|
|
2302
|
+
this.set(response);
|
|
2303
|
+
}
|
|
2304
|
+
/** The current response, as in the Definition's `wind`. */
|
|
2305
|
+
get values() {
|
|
2306
|
+
const u = this.uniforms;
|
|
2307
|
+
return {
|
|
2308
|
+
trunk: u.trunk.value,
|
|
2309
|
+
branches: u.branches.value,
|
|
2310
|
+
leaves: u.leaves.value,
|
|
2311
|
+
frequency: u.frequency.value
|
|
2312
|
+
};
|
|
2313
|
+
}
|
|
2314
|
+
/** Changes part of the response (uniform writes only). Weights are 0..1, frequency > 0. */
|
|
2315
|
+
set(response) {
|
|
2316
|
+
for (const key of [
|
|
2317
|
+
"trunk",
|
|
2318
|
+
"branches",
|
|
2319
|
+
"leaves"
|
|
2320
|
+
]) {
|
|
2321
|
+
const value = response[key];
|
|
2322
|
+
if (value === void 0) continue;
|
|
2323
|
+
if (!(value >= 0 && value <= 1)) throw new RangeError(`wind.${key} must be within 0..1, got ${value}`);
|
|
2324
|
+
this.uniforms[key].value = value;
|
|
2325
|
+
}
|
|
2326
|
+
if (response.frequency !== void 0) {
|
|
2327
|
+
if (!(response.frequency > 0 && Number.isFinite(response.frequency))) throw new RangeError(`wind.frequency must be > 0, got ${response.frequency}`);
|
|
2328
|
+
this.uniforms.frequency.value = response.frequency;
|
|
2329
|
+
}
|
|
2330
|
+
return this;
|
|
2331
|
+
}
|
|
2332
|
+
};
|
|
2333
|
+
// src/wind/node.ts
|
|
2334
|
+
var TRUNK_AMPLITUDE = .15;
|
|
2335
|
+
var BRANCH_AMPLITUDE = .1;
|
|
2336
|
+
var LEAF_AMPLITUDE = .2;
|
|
2337
|
+
/** The scene Wind direction in the rendered object's space (rotation only, normalized). */
|
|
2338
|
+
function objectWindDirection(wind) {
|
|
2339
|
+
return modelWorldMatrixInverse.mul(vec4(wind.uniforms.direction, 0)).xyz.normalize();
|
|
2340
|
+
}
|
|
2341
|
+
/**
|
|
2342
|
+
* TSL node: the Wind displacement (vec3, object space) of each vertex, from the per-vertex
|
|
2343
|
+
* `aWind` weights (trunk sway, branch sway, leaf flutter), the tree's Wind response and the
|
|
2344
|
+
* scene Wind. It only depends on geometry attributes and uniforms, so it adds onto any other
|
|
2345
|
+
* position node (Growth): `position = grown + windOffset(...)` (see {@link applyWind}).
|
|
2346
|
+
*
|
|
2347
|
+
* - trunk: leans with the wind and swings slowly, bending from the ground (weight = height²);
|
|
2348
|
+
* - branches: swing faster, with a phase that varies smoothly in space so joints stay attached,
|
|
2349
|
+
* plus a little cross-wind motion;
|
|
2350
|
+
* - leaves: flutter along their normal, more at the tip.
|
|
2351
|
+
* All of it is scaled by slow gusts. Wind direction is world space; it is turned into the tree's
|
|
2352
|
+
* object space (rotation only, so a scaled-up tree sways proportionally more). `frame` replaces
|
|
2353
|
+
* that direction and the response's phase (see {@link WindFrame}).
|
|
2354
|
+
*/
|
|
2355
|
+
function windOffset(wind, response, frame = {}) {
|
|
2356
|
+
const weights = attribute("aWind", "vec3");
|
|
2357
|
+
const random = attribute("aRandom", "float");
|
|
2358
|
+
const origin = attribute("aOrigin", "vec3");
|
|
2359
|
+
const r = response.uniforms;
|
|
2360
|
+
const strength = wind.uniforms.strength;
|
|
2361
|
+
const t = wind.uniforms.time.mul(r.frequency).add(frame.phase ?? r.phase);
|
|
2362
|
+
const direction = (frame.direction ?? objectWindDirection(wind)).normalize();
|
|
2363
|
+
const across = cross(direction, vec3(0, 1, 0));
|
|
2364
|
+
const gust = sin(t.mul(.37)).add(sin(t.mul(.91).add(1.7))).mul(.1).add(.8);
|
|
2365
|
+
const scale = strength.mul(r.height).mul(gust);
|
|
2366
|
+
const trunkSwing = sin(t.mul(1.1)).mul(.25).add(.75);
|
|
2367
|
+
const trunk = direction.mul(trunkSwing.mul(r.trunk).mul(weights.x).mul(scale).mul(TRUNK_AMPLITUDE));
|
|
2368
|
+
const spatialPhase = dot(positionGeometry, vec3(.9, .4, .7));
|
|
2369
|
+
const branchSwing = sin(t.mul(2.3).add(spatialPhase)).mul(.35).add(.65);
|
|
2370
|
+
const branchCross = sin(t.mul(1.7).add(spatialPhase.mul(1.3))).mul(.3);
|
|
2371
|
+
const branches = direction.mul(branchSwing).add(across.mul(branchCross)).mul(r.branches.mul(weights.y).mul(scale).mul(BRANCH_AMPLITUDE));
|
|
2372
|
+
const leafLength = positionGeometry.sub(origin).length();
|
|
2373
|
+
const flutter = sin(t.mul(9).add(random.mul(6.2832)));
|
|
2374
|
+
const leaves = normalGeometry.mul(flutter.mul(r.leaves).mul(weights.z).mul(leafLength).mul(strength).mul(gust).mul(LEAF_AMPLITUDE));
|
|
2375
|
+
return trunk.add(branches).add(leaves);
|
|
2376
|
+
}
|
|
2377
|
+
/**
|
|
2378
|
+
* Adds a Wind offset to a material's vertex position (its existing `positionNode`, or the plain
|
|
2379
|
+
* local position). The shadow pass reuses `positionNode`, so shadows sway along.
|
|
2380
|
+
*/
|
|
2381
|
+
function applyWind(material, offset) {
|
|
2382
|
+
material.positionNode = material.positionNode ? material.positionNode.add(offset) : positionLocal.add(offset);
|
|
2383
|
+
material.needsUpdate = true;
|
|
2384
|
+
}
|
|
2385
|
+
// src/tree/Tree.ts
|
|
2386
|
+
/**
|
|
2387
|
+
* The Generator's per-vertex part attributes (`aLevel`, `aSeason`, `aWind`, ...) go into one
|
|
2388
|
+
* interleaved vertex buffer: WebGPU allows only 8 vertex buffers per draw by default, and a
|
|
2389
|
+
* textured leaf already reads position, normal, uv and colour besides Growth, Season and Wind.
|
|
2390
|
+
*/
|
|
2391
|
+
function setPartAttributes(geometry, attributes) {
|
|
2392
|
+
const entries = Object.entries(attributes);
|
|
2393
|
+
const stride = entries.reduce((sum, [, a]) => sum + a.itemSize, 0);
|
|
2394
|
+
const count = geometry.getAttribute("position").count;
|
|
2395
|
+
const data = new Float32Array(count * stride);
|
|
2396
|
+
let offset = 0;
|
|
2397
|
+
for (const [, { array, itemSize }] of entries) {
|
|
2398
|
+
for (let v = 0; v < count; v++) for (let c = 0; c < itemSize; c++) data[v * stride + offset + c] = array[v * itemSize + c];
|
|
2399
|
+
offset += itemSize;
|
|
2400
|
+
}
|
|
2401
|
+
const buffer = new InterleavedBuffer(data, stride);
|
|
2402
|
+
offset = 0;
|
|
2403
|
+
for (const [name, { itemSize }] of entries) {
|
|
2404
|
+
geometry.setAttribute(name, new InterleavedBufferAttribute(buffer, itemSize, offset));
|
|
2405
|
+
offset += itemSize;
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
function toBufferGeometry(buffers) {
|
|
2409
|
+
const geometry = new BufferGeometry();
|
|
2410
|
+
geometry.setAttribute("position", new BufferAttribute(buffers.positions, 3));
|
|
2411
|
+
geometry.setAttribute("normal", new BufferAttribute(buffers.normals, 3));
|
|
2412
|
+
geometry.setAttribute("uv", new BufferAttribute(buffers.uvs, 2));
|
|
2413
|
+
if (buffers.colors) geometry.setAttribute("color", new BufferAttribute(buffers.colors, 3));
|
|
2414
|
+
setPartAttributes(geometry, buffers.attributes);
|
|
2415
|
+
geometry.setIndex(new BufferAttribute(buffers.indices, 1));
|
|
2416
|
+
geometry.computeBoundingBox();
|
|
2417
|
+
geometry.computeBoundingSphere();
|
|
2418
|
+
return geometry;
|
|
2419
|
+
}
|
|
2420
|
+
function treeMesh(name, geometry, material) {
|
|
2421
|
+
const mesh = new Mesh(geometry, material);
|
|
2422
|
+
mesh.name = name;
|
|
2423
|
+
mesh.castShadow = true;
|
|
2424
|
+
mesh.receiveShadow = true;
|
|
2425
|
+
mesh.onBeforeRender = (renderer) => assertWebGPURenderer(renderer);
|
|
2426
|
+
return mesh;
|
|
2427
|
+
}
|
|
2428
|
+
/**
|
|
2429
|
+
* A generated tree as a three.js object. Add it to a scene rendered by `WebGPURenderer`.
|
|
2430
|
+
* `growth`, `season` and the Wind only update uniforms: no regeneration, no recompile.
|
|
2431
|
+
*/
|
|
2432
|
+
var Tree = class extends Group {
|
|
2433
|
+
isTree = true;
|
|
2434
|
+
definition;
|
|
2435
|
+
seed;
|
|
2436
|
+
/** The generator output this object was built from (pure data). */
|
|
2437
|
+
data;
|
|
2438
|
+
/** Trunk and branches. */
|
|
2439
|
+
wood;
|
|
2440
|
+
/** Leaf cards (empty geometry for a bare tree). */
|
|
2441
|
+
leaves;
|
|
2442
|
+
/** This tree's Growth uniform (read by the wood and leaf materials' `positionNode`). */
|
|
2443
|
+
growthUniform;
|
|
2444
|
+
/** The Season uniform the leaf material reads (shared nodes may reference it). */
|
|
2445
|
+
seasonUniform;
|
|
2446
|
+
/** This tree's response to the Wind, from `definition.wind`; `windResponse.set(...)` changes it live. */
|
|
2447
|
+
windResponse;
|
|
2448
|
+
windBinding;
|
|
2449
|
+
/**
|
|
2450
|
+
* Resolves once every texture of this tree has loaded (at once for a tree without textures);
|
|
2451
|
+
* rejects if one fails. Await it before a first render that must show the textures.
|
|
2452
|
+
*/
|
|
2453
|
+
ready;
|
|
2454
|
+
constructor(definition, data, options = {}) {
|
|
2455
|
+
super();
|
|
2456
|
+
this.name = "Tree";
|
|
2457
|
+
this.definition = definition;
|
|
2458
|
+
this.seed = data.seed;
|
|
2459
|
+
this.data = data;
|
|
2460
|
+
this.growthUniform = uniform(clampGrowth(options.growth ?? 1));
|
|
2461
|
+
const bark = createBarkMaterial(definition, options.textures);
|
|
2462
|
+
const leaf = createLeafMaterial(definition, options.textures);
|
|
2463
|
+
bark.positionNode = growthPosition(this.growthUniform);
|
|
2464
|
+
leaf.positionNode = growthPosition(this.growthUniform);
|
|
2465
|
+
this.wood = treeMesh("wood", toBufferGeometry(data.wood), bark);
|
|
2466
|
+
this.leaves = treeMesh("leaves", toBufferGeometry(data.leaves), leaf);
|
|
2467
|
+
const textures = [
|
|
2468
|
+
bark.map,
|
|
2469
|
+
bark.normalMap,
|
|
2470
|
+
leaf.map
|
|
2471
|
+
].filter((t) => t !== null);
|
|
2472
|
+
this.ready = Promise.all(textures.map(textureReady)).then(() => void 0);
|
|
2473
|
+
this.ready.catch(() => {});
|
|
2474
|
+
this.add(this.wood, this.leaves);
|
|
2475
|
+
this.windBinding = new WindBinding(options.wind ?? sceneWind);
|
|
2476
|
+
this.windResponse = new WindResponse(definition.wind, {
|
|
2477
|
+
height: trunkHeight(data.skeleton),
|
|
2478
|
+
phase: seedRandom(data.seed, "wind") * Math.PI * 2
|
|
2479
|
+
});
|
|
2480
|
+
const offset = windOffset(this.windBinding, this.windResponse);
|
|
2481
|
+
applyWind(this.wood.material, offset);
|
|
2482
|
+
applyWind(this.leaves.material, offset);
|
|
2483
|
+
const season = createSeasonNodes(definition.season);
|
|
2484
|
+
applySeasonToLeafMaterial(this.leaves.material, season);
|
|
2485
|
+
this.seasonUniform = season.season;
|
|
2486
|
+
this.season = options.season ?? 0;
|
|
2487
|
+
}
|
|
2488
|
+
/**
|
|
2489
|
+
* The Wind this tree sways with (shared with every other tree using it). Assigning another
|
|
2490
|
+
* Wind only rebinds uniforms: no regeneration, no recompile.
|
|
2491
|
+
*/
|
|
2492
|
+
get wind() {
|
|
2493
|
+
return this.windBinding.wind;
|
|
2494
|
+
}
|
|
2495
|
+
set wind(value) {
|
|
2496
|
+
this.windBinding.wind = value;
|
|
2497
|
+
}
|
|
2498
|
+
/**
|
|
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.
|
|
2501
|
+
* Only updates a uniform, so it is cheap to animate.
|
|
2502
|
+
*/
|
|
2503
|
+
get season() {
|
|
2504
|
+
return this.seasonUniform.value;
|
|
2505
|
+
}
|
|
2506
|
+
set season(value) {
|
|
2507
|
+
this.seasonUniform.value = checkedSeason(value);
|
|
2508
|
+
}
|
|
2509
|
+
/**
|
|
2510
|
+
* How far this tree has grown: 0 (sapling) .. 1 (fully grown); values outside are clamped.
|
|
2511
|
+
* Setting it only writes a uniform, so it is cheap to animate every frame.
|
|
2512
|
+
*/
|
|
2513
|
+
get growth() {
|
|
2514
|
+
return this.growthUniform.value;
|
|
2515
|
+
}
|
|
2516
|
+
set growth(value) {
|
|
2517
|
+
this.growthUniform.value = clampGrowth(value);
|
|
2518
|
+
}
|
|
2519
|
+
/** Frees the GPU resources (geometries and materials) of this tree and removes it from its parent. */
|
|
2520
|
+
dispose() {
|
|
2521
|
+
this.traverse((object) => {
|
|
2522
|
+
if (object instanceof Mesh) {
|
|
2523
|
+
object.geometry.dispose();
|
|
2524
|
+
const materials = Array.isArray(object.material) ? object.material : [object.material];
|
|
2525
|
+
for (const material of materials) material.dispose();
|
|
2526
|
+
}
|
|
2527
|
+
});
|
|
2528
|
+
this.removeFromParent();
|
|
2529
|
+
super.dispose();
|
|
2530
|
+
}
|
|
2531
|
+
};
|
|
2532
|
+
// src/tree/index.ts
|
|
2533
|
+
/**
|
|
2534
|
+
* Grows a tree from a Tree Definition (plain object or parsed JSON) and a Seed and
|
|
2535
|
+
* returns a three.js object to add to a scene rendered by `WebGPURenderer`.
|
|
2536
|
+
* Throws `TreeDefinitionError` for an invalid Definition.
|
|
2537
|
+
*/
|
|
2538
|
+
function createTree(definition, options = {}) {
|
|
2539
|
+
const parsed = parseDefinition(definition);
|
|
2540
|
+
return new Tree(parsed, generateTree(parsed, options.seed ?? 0), {
|
|
2541
|
+
growth: options.growth,
|
|
2542
|
+
wind: options.wind,
|
|
2543
|
+
season: options.season,
|
|
2544
|
+
textures: options.textures
|
|
2545
|
+
});
|
|
2546
|
+
}
|
|
2547
|
+
// src/styles/registry.ts
|
|
2548
|
+
/**
|
|
2549
|
+
* 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).
|
|
2551
|
+
*/
|
|
2552
|
+
var STYLE_LOADERS = {
|
|
2553
|
+
"low-poly": () => import("./styles/low-poly.js"),
|
|
2554
|
+
stylized: () => import("./styles/stylized.js"),
|
|
2555
|
+
realistic: () => import("./styles/realistic.js")
|
|
2556
|
+
};
|
|
2557
|
+
/** Names of all built-in Styles. */
|
|
2558
|
+
var STYLE_NAMES = Object.keys(STYLE_LOADERS);
|
|
2559
|
+
/** Downloads a built-in Style (dynamic import) and resolves to it. Rejects for an unknown name. */
|
|
2560
|
+
async function loadStyle(name) {
|
|
2561
|
+
const load = STYLE_LOADERS[name];
|
|
2562
|
+
if (!load) throw new Error(`Unknown tree.js Style "${name}". Built-in Styles: ${STYLE_NAMES.join(", ")}.`);
|
|
2563
|
+
return (await load()).default;
|
|
2564
|
+
}
|
|
2565
|
+
// src/forest/nodes.ts
|
|
2566
|
+
var INSTANCE_ATTRIBUTES = {
|
|
2567
|
+
iRotation: 0,
|
|
2568
|
+
iState: 4
|
|
2569
|
+
};
|
|
2570
|
+
/** Per-tree values in the instanced Season/Growth/Wind slots. */
|
|
2571
|
+
function instanceState() {
|
|
2572
|
+
const state = attribute("iState", "vec4");
|
|
2573
|
+
return {
|
|
2574
|
+
scale: state.x,
|
|
2575
|
+
growth: state.y,
|
|
2576
|
+
season: state.z,
|
|
2577
|
+
windPhase: state.w
|
|
2578
|
+
};
|
|
2579
|
+
}
|
|
2580
|
+
/** Rotates `v` by the instance quaternion (`inverse` = by its conjugate). */
|
|
2581
|
+
function rotate(v, inverse = false) {
|
|
2582
|
+
const q = attribute("iRotation", "vec4");
|
|
2583
|
+
const u = inverse ? q.xyz.negate() : q.xyz;
|
|
2584
|
+
const t = cross(u, v).mul(2);
|
|
2585
|
+
return v.add(t.mul(q.w)).add(cross(u, t));
|
|
2586
|
+
}
|
|
2587
|
+
/**
|
|
2588
|
+
* The vertex position of a Forest tree (positionNode of an instanced Variant mesh).
|
|
2589
|
+
*
|
|
2590
|
+
* On an InstancedMesh, three.js applies the instance matrix to `positionLocal` before
|
|
2591
|
+
* `positionNode` runs, but Growth and Wind are defined in the tree's own space (about the
|
|
2592
|
+
* generated `aOrigin`s, relative to its trunk height). So both are computed from
|
|
2593
|
+
* `positionGeometry`, and only their displacement is turned into forest space with the
|
|
2594
|
+
* instance rotation and scale: M·(p + d) = M·p + R·s·d. The Wind direction goes the other way
|
|
2595
|
+
* (forest -> tree space) and each tree sways with its own phase.
|
|
2596
|
+
*/
|
|
2597
|
+
function forestPosition(wind, response) {
|
|
2598
|
+
const { scale, growth, windPhase } = instanceState();
|
|
2599
|
+
const grown = growthPosition(growth, positionGeometry);
|
|
2600
|
+
const offset = windOffset(wind, response, {
|
|
2601
|
+
direction: rotate(objectWindDirection(wind), true),
|
|
2602
|
+
phase: windPhase
|
|
2603
|
+
});
|
|
2604
|
+
const displacement = grown.add(offset).sub(positionGeometry);
|
|
2605
|
+
return positionLocal.add(rotate(displacement).mul(scale));
|
|
2606
|
+
}
|
|
2607
|
+
// src/forest/placement.ts
|
|
2608
|
+
function placementPosition(placement) {
|
|
2609
|
+
const p = placement.position;
|
|
2610
|
+
const v = Array.isArray(p) ? [
|
|
2611
|
+
p[0],
|
|
2612
|
+
p[1],
|
|
2613
|
+
p[2]
|
|
2614
|
+
] : [
|
|
2615
|
+
p.x,
|
|
2616
|
+
p.y,
|
|
2617
|
+
p.z
|
|
2618
|
+
];
|
|
2619
|
+
if (!v.every(Number.isFinite)) throw new RangeError(`Forest placement position must be finite, got [${v.join(", ")}]`);
|
|
2620
|
+
return v;
|
|
2621
|
+
}
|
|
2622
|
+
/**
|
|
2623
|
+
* The key a tree is known by: its id as a string (so ids 1 and "1" are the same tree), or
|
|
2624
|
+
* `@x,y,z` (position in millimetres) when it has no id.
|
|
2625
|
+
*/
|
|
2626
|
+
function forestTreeKey(placement) {
|
|
2627
|
+
if (placement.id !== void 0) return String(placement.id);
|
|
2628
|
+
return `@${placementPosition(placement).map((c) => Math.round(c * 1e3) || 0).join(",")}`;
|
|
2629
|
+
}
|
|
2630
|
+
/** The Seed of Variant `index` of a forest. */
|
|
2631
|
+
function variantSeed(forestSeed, index) {
|
|
2632
|
+
return hashCombine(seedToUint32(forestSeed), 8024487, index);
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* A tree's Variant and offsets: a hash of the forest seed and the tree's key only, so they never
|
|
2636
|
+
* depend on the tree's index in the list or on which other trees exist.
|
|
2637
|
+
*/
|
|
2638
|
+
function forestTreeTraits(forestSeed, key, variants, variation) {
|
|
2639
|
+
const random = createRandom(forestSeed).fork("forest").fork(key);
|
|
2640
|
+
return {
|
|
2641
|
+
variant: random.int(0, variants - 1),
|
|
2642
|
+
growthDelay: random.next() * variation.growth,
|
|
2643
|
+
seasonShift: (random.next() * 2 - 1) * variation.season,
|
|
2644
|
+
windPhase: random.next() * Math.PI * 2
|
|
2645
|
+
};
|
|
2646
|
+
}
|
|
2647
|
+
/**
|
|
2648
|
+
* The Growth one tree is drawn at, for a Growth `growth` set on it: delayed by its `growthDelay`
|
|
2649
|
+
* but still exactly 0 at Growth 0 and 1 at Growth 1, so a fully grown forest is fully grown.
|
|
2650
|
+
*/
|
|
2651
|
+
function delayedGrowth(growth, delay) {
|
|
2652
|
+
const g = clampGrowth(growth);
|
|
2653
|
+
return delay > 0 ? clampGrowth((g - delay) / (1 - delay)) : g;
|
|
2654
|
+
}
|
|
2655
|
+
/** The Season one tree is drawn at: the Season set on it plus its shift, wrapped into 0..1. */
|
|
2656
|
+
function shiftedSeason(season, shift) {
|
|
2657
|
+
return wrapSeason(season + shift);
|
|
2658
|
+
}
|
|
2659
|
+
// src/forest/Forest.ts
|
|
2660
|
+
var MIN_CAPACITY = 16;
|
|
2661
|
+
var WIND_BOUNDS = .35;
|
|
2662
|
+
/**
|
|
2663
|
+
* One tree of a {@link Forest}. Its Variant and offsets come from the forest seed and its key
|
|
2664
|
+
* only. `growth` and `season` are what the app sets on this tree; the tree draws them with its
|
|
2665
|
+
* offsets applied (see {@link Forest.instanceState}).
|
|
2666
|
+
*/
|
|
2667
|
+
var ForestTree = class {
|
|
2668
|
+
onChange;
|
|
2669
|
+
/** The tree's id as a string, or `@x,y,z` (position in mm) when it was placed without an id. */
|
|
2670
|
+
key;
|
|
2671
|
+
placement;
|
|
2672
|
+
variant;
|
|
2673
|
+
growthDelay;
|
|
2674
|
+
seasonShift;
|
|
2675
|
+
windPhase;
|
|
2676
|
+
/** @internal Slot in the Variant's instance buffers. */
|
|
2677
|
+
slot = -1;
|
|
2678
|
+
growthValue;
|
|
2679
|
+
seasonValue;
|
|
2680
|
+
/** @internal Use {@link Forest.addTree}. */
|
|
2681
|
+
constructor(key, placement, traits, state, onChange) {
|
|
2682
|
+
this.onChange = onChange;
|
|
2683
|
+
this.key = key;
|
|
2684
|
+
this.placement = placement;
|
|
2685
|
+
this.variant = traits.variant;
|
|
2686
|
+
this.growthDelay = traits.growthDelay;
|
|
2687
|
+
this.seasonShift = traits.seasonShift;
|
|
2688
|
+
this.windPhase = traits.windPhase;
|
|
2689
|
+
this.growthValue = clampGrowth(state.growth);
|
|
2690
|
+
this.seasonValue = checkedSeason(state.season);
|
|
2691
|
+
}
|
|
2692
|
+
/** Growth set on this tree, 0..1 (clamped). Only rewrites this tree's instance data. */
|
|
2693
|
+
get growth() {
|
|
2694
|
+
return this.growthValue;
|
|
2695
|
+
}
|
|
2696
|
+
set growth(value) {
|
|
2697
|
+
this.growthValue = clampGrowth(value);
|
|
2698
|
+
this.onChange(this);
|
|
2699
|
+
}
|
|
2700
|
+
/** Season set on this tree, 0..1 (wraps around the year). Only rewrites this tree's instance data. */
|
|
2701
|
+
get season() {
|
|
2702
|
+
return this.seasonValue;
|
|
2703
|
+
}
|
|
2704
|
+
set season(value) {
|
|
2705
|
+
this.seasonValue = checkedSeason(value);
|
|
2706
|
+
this.onChange(this);
|
|
2707
|
+
}
|
|
2708
|
+
};
|
|
2709
|
+
/** Packs generator buffers into one interleaved vertex buffer, so a Variant takes a single vertex buffer slot. */
|
|
2710
|
+
function interleavedGeometry(buffers, boundsMargin) {
|
|
2711
|
+
const parts = [
|
|
2712
|
+
[
|
|
2713
|
+
"position",
|
|
2714
|
+
buffers.positions,
|
|
2715
|
+
3
|
|
2716
|
+
],
|
|
2717
|
+
[
|
|
2718
|
+
"normal",
|
|
2719
|
+
buffers.normals,
|
|
2720
|
+
3
|
|
2721
|
+
],
|
|
2722
|
+
[
|
|
2723
|
+
"uv",
|
|
2724
|
+
buffers.uvs,
|
|
2725
|
+
2
|
|
2726
|
+
]
|
|
2727
|
+
];
|
|
2728
|
+
if (buffers.colors) parts.push([
|
|
2729
|
+
"color",
|
|
2730
|
+
buffers.colors,
|
|
2731
|
+
3
|
|
2732
|
+
]);
|
|
2733
|
+
for (const [name, { array, itemSize }] of Object.entries(buffers.attributes)) parts.push([
|
|
2734
|
+
name,
|
|
2735
|
+
array,
|
|
2736
|
+
itemSize
|
|
2737
|
+
]);
|
|
2738
|
+
const count = buffers.positions.length / 3;
|
|
2739
|
+
const stride = parts.reduce((sum, [, , size]) => sum + size, 0);
|
|
2740
|
+
const data = new Float32Array(count * stride);
|
|
2741
|
+
const interleaved = new InterleavedBuffer(data, stride);
|
|
2742
|
+
const geometry = new BufferGeometry();
|
|
2743
|
+
let offset = 0;
|
|
2744
|
+
for (const [name, array, size] of parts) {
|
|
2745
|
+
for (let v = 0; v < count; v++) for (let c = 0; c < size; c++) data[v * stride + offset + c] = array[v * size + c];
|
|
2746
|
+
geometry.setAttribute(name, new InterleavedBufferAttribute(interleaved, size, offset));
|
|
2747
|
+
offset += size;
|
|
2748
|
+
}
|
|
2749
|
+
geometry.setIndex(new BufferAttribute(buffers.indices, 1));
|
|
2750
|
+
geometry.computeBoundingBox();
|
|
2751
|
+
geometry.computeBoundingSphere();
|
|
2752
|
+
geometry.boundingSphere.radius += boundsMargin;
|
|
2753
|
+
geometry.boundingBox.expandByScalar(boundsMargin);
|
|
2754
|
+
return geometry;
|
|
2755
|
+
}
|
|
2756
|
+
/** Copies a geometry's attributes into a new geometry (shares the vertex data). */
|
|
2757
|
+
function shareGeometry(source) {
|
|
2758
|
+
const geometry = new BufferGeometry();
|
|
2759
|
+
for (const [name, attribute] of Object.entries(source.attributes)) geometry.setAttribute(name, attribute);
|
|
2760
|
+
geometry.setIndex(source.getIndex());
|
|
2761
|
+
geometry.boundingBox = source.boundingBox.clone();
|
|
2762
|
+
geometry.boundingSphere = source.boundingSphere.clone();
|
|
2763
|
+
return geometry;
|
|
2764
|
+
}
|
|
2765
|
+
/**
|
|
2766
|
+
* 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).
|
|
2768
|
+
*/
|
|
2769
|
+
var ForestVariant = class {
|
|
2770
|
+
forest;
|
|
2771
|
+
index;
|
|
2772
|
+
seed;
|
|
2773
|
+
data;
|
|
2774
|
+
/** This Variant's response to the Wind (trunk height from its Seed; each tree has its own phase). */
|
|
2775
|
+
windResponse;
|
|
2776
|
+
barkMaterial;
|
|
2777
|
+
leafMaterial;
|
|
2778
|
+
/** The trees drawn as this Variant, in instance order. */
|
|
2779
|
+
trees = [];
|
|
2780
|
+
woodMesh;
|
|
2781
|
+
leafMesh;
|
|
2782
|
+
instanceData;
|
|
2783
|
+
woodSource;
|
|
2784
|
+
leafSource;
|
|
2785
|
+
constructor(forest, definition, index, seed, wind, capacity, textures) {
|
|
2786
|
+
this.forest = forest;
|
|
2787
|
+
this.index = index;
|
|
2788
|
+
this.seed = seed;
|
|
2789
|
+
this.data = generateTree(definition, seed);
|
|
2790
|
+
const height = trunkHeight(this.data.skeleton);
|
|
2791
|
+
this.windResponse = new WindResponse(definition.wind, {
|
|
2792
|
+
height,
|
|
2793
|
+
phase: 0
|
|
2794
|
+
});
|
|
2795
|
+
const position = forestPosition(wind, this.windResponse);
|
|
2796
|
+
this.barkMaterial = createBarkMaterial(definition, textures);
|
|
2797
|
+
this.barkMaterial.positionNode = position;
|
|
2798
|
+
this.leafMaterial = createLeafMaterial(definition, textures);
|
|
2799
|
+
this.leafMaterial.positionNode = position;
|
|
2800
|
+
applySeasonToLeafMaterial(this.leafMaterial, createSeasonNodes(definition.season, instanceState().season));
|
|
2801
|
+
this.woodSource = interleavedGeometry(this.data.wood, height * WIND_BOUNDS);
|
|
2802
|
+
this.leafSource = interleavedGeometry(this.data.leaves, height * WIND_BOUNDS);
|
|
2803
|
+
this.allocate(capacity);
|
|
2804
|
+
}
|
|
2805
|
+
/** Instanced mesh of trunks and branches. Replaced (not resized) when the Variant outgrows its capacity. */
|
|
2806
|
+
get wood() {
|
|
2807
|
+
return this.woodMesh;
|
|
2808
|
+
}
|
|
2809
|
+
/** Instanced mesh of the leaves. Replaced along with {@link wood}. */
|
|
2810
|
+
get leaves() {
|
|
2811
|
+
return this.leafMesh;
|
|
2812
|
+
}
|
|
2813
|
+
get capacity() {
|
|
2814
|
+
return this.instanceData.count;
|
|
2815
|
+
}
|
|
2816
|
+
/** @internal */
|
|
2817
|
+
add(tree) {
|
|
2818
|
+
if (this.trees.length === this.capacity) this.allocate(this.capacity * 2);
|
|
2819
|
+
tree.slot = this.trees.length;
|
|
2820
|
+
this.trees.push(tree);
|
|
2821
|
+
this.write(tree);
|
|
2822
|
+
this.setCount();
|
|
2823
|
+
}
|
|
2824
|
+
/** @internal Swap-removes a tree: the last tree takes its slot. */
|
|
2825
|
+
remove(tree) {
|
|
2826
|
+
const last = this.trees.pop();
|
|
2827
|
+
if (last !== tree) {
|
|
2828
|
+
last.slot = tree.slot;
|
|
2829
|
+
this.trees[last.slot] = last;
|
|
2830
|
+
this.write(last);
|
|
2831
|
+
}
|
|
2832
|
+
tree.slot = -1;
|
|
2833
|
+
this.setCount();
|
|
2834
|
+
}
|
|
2835
|
+
/** @internal Writes one tree's transform and state into its instance slot. */
|
|
2836
|
+
write(tree) {
|
|
2837
|
+
const i = tree.slot;
|
|
2838
|
+
const { placement } = tree;
|
|
2839
|
+
const position = new Vector3(...placementPosition(placement));
|
|
2840
|
+
const rotation = placement.rotation ?? 0;
|
|
2841
|
+
const quaternion = new Quaternion().setFromEuler(typeof rotation === "number" ? new Euler(0, rotation, 0) : new Euler(rotation[0], rotation[1], rotation[2]));
|
|
2842
|
+
const scale = placement.scale ?? 1;
|
|
2843
|
+
this.woodMesh.setMatrixAt(i, new Matrix4().compose(position, quaternion, new Vector3(scale, scale, scale)));
|
|
2844
|
+
this.woodMesh.instanceMatrix.needsUpdate = true;
|
|
2845
|
+
this.instanceData.array.set([
|
|
2846
|
+
quaternion.x,
|
|
2847
|
+
quaternion.y,
|
|
2848
|
+
quaternion.z,
|
|
2849
|
+
quaternion.w,
|
|
2850
|
+
scale,
|
|
2851
|
+
delayedGrowth(tree.growth, tree.growthDelay),
|
|
2852
|
+
shiftedSeason(tree.season, tree.seasonShift),
|
|
2853
|
+
tree.windPhase
|
|
2854
|
+
], i * 8);
|
|
2855
|
+
this.instanceData.needsUpdate = true;
|
|
2856
|
+
this.woodMesh.boundingSphere = this.leafMesh.boundingSphere = null;
|
|
2857
|
+
this.woodMesh.boundingBox = this.leafMesh.boundingBox = null;
|
|
2858
|
+
}
|
|
2859
|
+
/** @internal */
|
|
2860
|
+
state(tree) {
|
|
2861
|
+
const o = tree.slot * 8;
|
|
2862
|
+
const array = this.instanceData.array;
|
|
2863
|
+
return {
|
|
2864
|
+
growth: array[o + 5],
|
|
2865
|
+
season: array[o + 6],
|
|
2866
|
+
windPhase: array[o + 7]
|
|
2867
|
+
};
|
|
2868
|
+
}
|
|
2869
|
+
/** @internal Frees the GPU resources. */
|
|
2870
|
+
dispose() {
|
|
2871
|
+
this.disposeMeshes();
|
|
2872
|
+
this.woodSource.dispose();
|
|
2873
|
+
this.leafSource.dispose();
|
|
2874
|
+
this.barkMaterial.dispose();
|
|
2875
|
+
this.leafMaterial.dispose();
|
|
2876
|
+
}
|
|
2877
|
+
setCount() {
|
|
2878
|
+
this.woodMesh.count = this.leafMesh.count = this.trees.length;
|
|
2879
|
+
}
|
|
2880
|
+
/**
|
|
2881
|
+
* (Re)builds the instanced meshes with room for `capacity` trees. An InstancedMesh cannot grow,
|
|
2882
|
+
* so a full Variant gets new meshes (same materials and vertex data) of twice the size.
|
|
2883
|
+
*/
|
|
2884
|
+
allocate(capacity) {
|
|
2885
|
+
const instanceData = new InstancedInterleavedBuffer(new Float32Array(capacity * 8), 8, 1);
|
|
2886
|
+
instanceData.setUsage(DynamicDrawUsage);
|
|
2887
|
+
const matrices = new InstancedBufferAttribute(new Float32Array(capacity * 16), 16);
|
|
2888
|
+
matrices.setUsage(DynamicDrawUsage);
|
|
2889
|
+
if (this.woodMesh) {
|
|
2890
|
+
instanceData.array.set(this.instanceData.array);
|
|
2891
|
+
matrices.array.set(this.woodMesh.instanceMatrix.array);
|
|
2892
|
+
this.disposeMeshes();
|
|
2893
|
+
}
|
|
2894
|
+
this.instanceData = instanceData;
|
|
2895
|
+
const mesh = (name, source, material) => {
|
|
2896
|
+
const geometry = shareGeometry(source);
|
|
2897
|
+
for (const [attribute, offset] of Object.entries(INSTANCE_ATTRIBUTES)) geometry.setAttribute(attribute, new InterleavedBufferAttribute(instanceData, 4, offset));
|
|
2898
|
+
const instanced = new InstancedMesh(geometry, material, capacity);
|
|
2899
|
+
instanced.instanceMatrix = matrices;
|
|
2900
|
+
instanced.name = `${name} ${this.index}`;
|
|
2901
|
+
instanced.castShadow = true;
|
|
2902
|
+
instanced.receiveShadow = true;
|
|
2903
|
+
instanced.onBeforeRender = (renderer) => assertWebGPURenderer(renderer);
|
|
2904
|
+
return instanced;
|
|
2905
|
+
};
|
|
2906
|
+
this.woodMesh = mesh("forest wood", this.woodSource, this.barkMaterial);
|
|
2907
|
+
this.leafMesh = mesh("forest leaves", this.leafSource, this.leafMaterial);
|
|
2908
|
+
this.setCount();
|
|
2909
|
+
this.forest.add(this.woodMesh, this.leafMesh);
|
|
2910
|
+
}
|
|
2911
|
+
disposeMeshes() {
|
|
2912
|
+
for (const mesh of [this.woodMesh, this.leafMesh]) {
|
|
2913
|
+
mesh.removeFromParent();
|
|
2914
|
+
mesh.geometry.dispose();
|
|
2915
|
+
mesh.dispose();
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
};
|
|
2919
|
+
/**
|
|
2920
|
+
* Many trees of one Tree Definition, drawn from a few shared Variants (one instanced mesh per
|
|
2921
|
+
* Variant and material). Each tree's Variant and its small Growth/Season offsets come from a
|
|
2922
|
+
* hash of the forest seed and the tree's id (or position), never from its index, so adding or
|
|
2923
|
+
* removing trees never changes the others. Growth and Season can be set per tree or for all.
|
|
2924
|
+
*/
|
|
2925
|
+
var Forest = class extends Group {
|
|
2926
|
+
isForest = true;
|
|
2927
|
+
definition;
|
|
2928
|
+
/** The forest seed. */
|
|
2929
|
+
seed;
|
|
2930
|
+
variants;
|
|
2931
|
+
/** Resolves once every texture has loaded (at once without textures); rejects if one fails. */
|
|
2932
|
+
ready;
|
|
2933
|
+
byKey = /* @__PURE__ */ new Map();
|
|
2934
|
+
windBinding;
|
|
2935
|
+
growthValue;
|
|
2936
|
+
seasonValue;
|
|
2937
|
+
constructor(definition, placements = [], options = {}) {
|
|
2938
|
+
super();
|
|
2939
|
+
const count = options.variants ?? 4;
|
|
2940
|
+
if (!Number.isInteger(count) || count < 1) throw new RangeError(`Forest variants must be an integer >= 1, got ${count}`);
|
|
2941
|
+
this.name = "Forest";
|
|
2942
|
+
this.definition = definition;
|
|
2943
|
+
this.seed = options.seed ?? 0;
|
|
2944
|
+
this.windBinding = new WindBinding(options.wind ?? sceneWind);
|
|
2945
|
+
this.growthValue = clampGrowth(options.growth ?? 1);
|
|
2946
|
+
this.seasonValue = checkedSeason(options.season ?? 0);
|
|
2947
|
+
const capacity = Math.max(MIN_CAPACITY, 2 ** Math.ceil(Math.log2(Math.max(1, placements.length / count * 1.25))));
|
|
2948
|
+
this.variants = Array.from({ length: count }, (_, i) => new ForestVariant(this, definition, i, variantSeed(this.seed, i), this.windBinding, capacity, options.textures));
|
|
2949
|
+
const textures = this.variants.flatMap((v) => [
|
|
2950
|
+
v.barkMaterial.map,
|
|
2951
|
+
v.barkMaterial.normalMap,
|
|
2952
|
+
v.leafMaterial.map
|
|
2953
|
+
]);
|
|
2954
|
+
this.ready = Promise.all(textures.filter((t) => t !== null).map(textureReady)).then(() => void 0);
|
|
2955
|
+
this.ready.catch(() => {});
|
|
2956
|
+
for (const placement of placements) this.addTree(placement);
|
|
2957
|
+
}
|
|
2958
|
+
/**
|
|
2959
|
+
* The Wind every tree of this forest sways with. Assigning another Wind only rebinds uniforms:
|
|
2960
|
+
* no rebuild, no recompile.
|
|
2961
|
+
*/
|
|
2962
|
+
get wind() {
|
|
2963
|
+
return this.windBinding.wind;
|
|
2964
|
+
}
|
|
2965
|
+
set wind(value) {
|
|
2966
|
+
this.windBinding.wind = value;
|
|
2967
|
+
}
|
|
2968
|
+
/** Every tree, in the order they were added. */
|
|
2969
|
+
get trees() {
|
|
2970
|
+
return [...this.byKey.values()];
|
|
2971
|
+
}
|
|
2972
|
+
/** Number of trees. */
|
|
2973
|
+
get size() {
|
|
2974
|
+
return this.byKey.size;
|
|
2975
|
+
}
|
|
2976
|
+
/** The tree with this key (its id as a string, or `ForestTree.key`). */
|
|
2977
|
+
get(key) {
|
|
2978
|
+
return this.byKey.get(String(key));
|
|
2979
|
+
}
|
|
2980
|
+
/**
|
|
2981
|
+
* Plants a tree. Throws if a tree with the same id (or, without ids, the same position) exists.
|
|
2982
|
+
* It starts at the forest's current Growth and Season.
|
|
2983
|
+
*/
|
|
2984
|
+
addTree(placement) {
|
|
2985
|
+
const key = forestTreeKey(placement);
|
|
2986
|
+
if (this.byKey.has(key)) throw new Error(placement.id !== void 0 ? `Forest already has a tree with id "${placement.id}"` : `Forest already has a tree at position ${key.slice(1)} (mm); give the trees an id to place them on the same spot`);
|
|
2987
|
+
const traits = forestTreeTraits(this.seed, key, this.variants.length, this.definition.variation);
|
|
2988
|
+
const frozen = {
|
|
2989
|
+
...placement,
|
|
2990
|
+
position: placementPosition(placement),
|
|
2991
|
+
rotation: Array.isArray(placement.rotation) ? [...placement.rotation] : placement.rotation
|
|
2992
|
+
};
|
|
2993
|
+
const tree = new ForestTree(key, Object.freeze(frozen), traits, {
|
|
2994
|
+
growth: this.growthValue,
|
|
2995
|
+
season: this.seasonValue
|
|
2996
|
+
}, (t) => this.variants[t.variant].write(t));
|
|
2997
|
+
this.byKey.set(key, tree);
|
|
2998
|
+
this.variants[tree.variant].add(tree);
|
|
2999
|
+
return tree;
|
|
3000
|
+
}
|
|
3001
|
+
/** Cuts a tree (by key or object). Returns false if it is not in this forest. Other trees keep their look. */
|
|
3002
|
+
removeTree(tree) {
|
|
3003
|
+
const found = typeof tree === "object" ? this.byKey.get(tree.key) : this.get(tree);
|
|
3004
|
+
if (!found || typeof tree === "object" && found !== tree) return false;
|
|
3005
|
+
this.byKey.delete(found.key);
|
|
3006
|
+
this.variants[found.variant].remove(found);
|
|
3007
|
+
return true;
|
|
3008
|
+
}
|
|
3009
|
+
/** The tree drawn by instance `instanceId` of a Variant mesh, e.g. from a raycast intersection. */
|
|
3010
|
+
treeAt(intersection) {
|
|
3011
|
+
const variant = this.variants.find((v) => v.wood === intersection.object || v.leaves === intersection.object);
|
|
3012
|
+
return variant && intersection.instanceId !== void 0 ? variant.trees[intersection.instanceId] : void 0;
|
|
3013
|
+
}
|
|
3014
|
+
/** What the GPU draws a tree with: its Growth and Season after its offsets, and its Wind phase. */
|
|
3015
|
+
instanceState(tree) {
|
|
3016
|
+
const found = typeof tree === "object" ? tree : this.get(tree);
|
|
3017
|
+
if (!found || found.slot < 0) throw new Error(`No tree "${String(typeof tree === "object" ? tree.key : tree)}" in this Forest`);
|
|
3018
|
+
return this.variants[found.variant].state(found);
|
|
3019
|
+
}
|
|
3020
|
+
/** Growth of the whole forest: setting it sets every tree's Growth (and that of trees planted later). */
|
|
3021
|
+
get growth() {
|
|
3022
|
+
return this.growthValue;
|
|
3023
|
+
}
|
|
3024
|
+
set growth(value) {
|
|
3025
|
+
this.growthValue = clampGrowth(value);
|
|
3026
|
+
for (const tree of this.byKey.values()) tree.growth = this.growthValue;
|
|
3027
|
+
}
|
|
3028
|
+
/** Season of the whole forest: setting it sets every tree's Season (and that of trees planted later). */
|
|
3029
|
+
get season() {
|
|
3030
|
+
return this.seasonValue;
|
|
3031
|
+
}
|
|
3032
|
+
set season(value) {
|
|
3033
|
+
this.seasonValue = checkedSeason(value);
|
|
3034
|
+
for (const tree of this.byKey.values()) tree.season = this.seasonValue;
|
|
3035
|
+
}
|
|
3036
|
+
/** Frees every Variant's geometries, materials and instance buffers, and removes the forest from its parent. */
|
|
3037
|
+
dispose() {
|
|
3038
|
+
for (const variant of this.variants) variant.dispose();
|
|
3039
|
+
this.byKey.clear();
|
|
3040
|
+
this.removeFromParent();
|
|
3041
|
+
super.dispose();
|
|
3042
|
+
}
|
|
3043
|
+
};
|
|
3044
|
+
// src/forest/index.ts
|
|
3045
|
+
/**
|
|
3046
|
+
* Places many trees of one Tree Definition cheaply: `variants` Seeds are generated once and each
|
|
3047
|
+
* is drawn instanced. Each tree's Variant and small Growth/Season offsets come from a hash of
|
|
3048
|
+
* the forest `seed` and the tree's id (or position), so the same seed and placements always give
|
|
3049
|
+
* the same forest, and adding or removing a tree never changes the others.
|
|
3050
|
+
* Throws `TreeDefinitionError` for an invalid Definition.
|
|
3051
|
+
*/
|
|
3052
|
+
function createForest(definition, placements = [], options = {}) {
|
|
3053
|
+
return new Forest(parseDefinition(definition), placements, options);
|
|
3054
|
+
}
|
|
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 };
|
|
3056
|
+
|
|
3057
|
+
//# sourceMappingURL=forest-OX9WvAwh.js.map
|