@casmo/tree.js 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/README.md +590 -4
  2. package/dist/effects/custom.d.ts +62 -0
  3. package/dist/effects/custom.d.ts.map +1 -0
  4. package/dist/effects/effects.d.ts +42 -1
  5. package/dist/effects/effects.d.ts.map +1 -1
  6. package/dist/effects/index.d.ts +2 -0
  7. package/dist/effects/index.d.ts.map +1 -1
  8. package/dist/effects/mask.d.ts +9 -1
  9. package/dist/effects/mask.d.ts.map +1 -1
  10. package/dist/effects/tree-id.d.ts.map +1 -1
  11. package/dist/effects-qHx_8Dlk.js +1052 -0
  12. package/dist/effects-qHx_8Dlk.js.map +1 -0
  13. package/dist/effects.js +2 -963
  14. package/dist/forest/Forest.d.ts +80 -4
  15. package/dist/forest/Forest.d.ts.map +1 -1
  16. package/dist/forest/forest-lod.d.ts +70 -0
  17. package/dist/forest/forest-lod.d.ts.map +1 -0
  18. package/dist/forest/impostor-material.d.ts +106 -0
  19. package/dist/forest/impostor-material.d.ts.map +1 -0
  20. package/dist/forest/impostor-season.d.ts +13 -0
  21. package/dist/forest/impostor-season.d.ts.map +1 -0
  22. package/dist/forest/impostor.d.ts +105 -0
  23. package/dist/forest/impostor.d.ts.map +1 -0
  24. package/dist/forest/index.d.ts +1 -0
  25. package/dist/forest/index.d.ts.map +1 -1
  26. package/dist/forest/levels.d.ts +144 -0
  27. package/dist/forest/levels.d.ts.map +1 -0
  28. package/dist/forest/lod.d.ts +106 -0
  29. package/dist/forest/lod.d.ts.map +1 -0
  30. package/dist/forest/nodes.d.ts +42 -1
  31. package/dist/forest/nodes.d.ts.map +1 -1
  32. package/dist/forest/octahedral.d.ts +33 -0
  33. package/dist/forest/octahedral.d.ts.map +1 -0
  34. package/dist/{forest-lg61rhKM.js → forest-CM5DrklM.js} +1723 -340
  35. package/dist/forest-CM5DrklM.js.map +1 -0
  36. package/dist/generator/fruit.d.ts +2 -0
  37. package/dist/generator/fruit.d.ts.map +1 -1
  38. package/dist/generator/index.d.ts +1 -0
  39. package/dist/generator/index.d.ts.map +1 -1
  40. package/dist/generator/light.d.ts +36 -0
  41. package/dist/generator/light.d.ts.map +1 -0
  42. package/dist/index.d.ts +3 -2
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +5 -2
  45. package/dist/index.js.map +1 -1
  46. package/dist/materials/crown-nodes.d.ts +5 -0
  47. package/dist/materials/crown-nodes.d.ts.map +1 -1
  48. package/dist/materials/leaf-translucency-model.d.ts +6 -1
  49. package/dist/materials/leaf-translucency-model.d.ts.map +1 -1
  50. package/dist/materials/material-features.d.ts +12 -0
  51. package/dist/materials/material-features.d.ts.map +1 -1
  52. package/dist/materials/shader-hooks.d.ts +155 -0
  53. package/dist/materials/shader-hooks.d.ts.map +1 -0
  54. package/dist/motion-Qd7xjeZM.js +276 -0
  55. package/dist/motion-Qd7xjeZM.js.map +1 -0
  56. package/dist/nodes-DxgTyF9B.js +436 -0
  57. package/dist/nodes-DxgTyF9B.js.map +1 -0
  58. package/dist/react/Forest.d.ts +17 -3
  59. package/dist/react/Forest.d.ts.map +1 -1
  60. package/dist/react/ScenePipeline.d.ts +63 -0
  61. package/dist/react/ScenePipeline.d.ts.map +1 -0
  62. package/dist/react/SceneShaderHooks.d.ts +25 -0
  63. package/dist/react/SceneShaderHooks.d.ts.map +1 -0
  64. package/dist/react/Tree.d.ts +9 -2
  65. package/dist/react/Tree.d.ts.map +1 -1
  66. package/dist/react/Weather.d.ts +45 -0
  67. package/dist/react/Weather.d.ts.map +1 -0
  68. package/dist/react/Wind.d.ts +12 -1
  69. package/dist/react/Wind.d.ts.map +1 -1
  70. package/dist/react/index.d.ts +7 -1
  71. package/dist/react/index.d.ts.map +1 -1
  72. package/dist/react.js +347 -10
  73. package/dist/react.js.map +1 -1
  74. package/dist/renderer/index.d.ts +6 -0
  75. package/dist/renderer/index.d.ts.map +1 -1
  76. package/dist/scene/antialias.d.ts +35 -0
  77. package/dist/scene/antialias.d.ts.map +1 -0
  78. package/dist/scene/ao.d.ts +46 -0
  79. package/dist/scene/ao.d.ts.map +1 -0
  80. package/dist/scene/bloom.d.ts +19 -0
  81. package/dist/scene/bloom.d.ts.map +1 -0
  82. package/dist/scene/fog.d.ts +49 -0
  83. package/dist/scene/fog.d.ts.map +1 -0
  84. package/dist/scene/godrays.d.ts +37 -0
  85. package/dist/scene/godrays.d.ts.map +1 -0
  86. package/dist/scene/index.d.ts +14 -0
  87. package/dist/scene/index.d.ts.map +1 -0
  88. package/dist/scene/motion-blur.d.ts +23 -0
  89. package/dist/scene/motion-blur.d.ts.map +1 -0
  90. package/dist/scene/pipeline.d.ts +109 -0
  91. package/dist/scene/pipeline.d.ts.map +1 -0
  92. package/dist/scene/settings.d.ts +36 -0
  93. package/dist/scene/settings.d.ts.map +1 -0
  94. package/dist/scene/stack.d.ts +25 -0
  95. package/dist/scene/stack.d.ts.map +1 -0
  96. package/dist/scene/stage.d.ts +52 -0
  97. package/dist/scene/stage.d.ts.map +1 -0
  98. package/dist/scene/suggested.d.ts +12 -0
  99. package/dist/scene/suggested.d.ts.map +1 -0
  100. package/dist/scene/tone-mapping.d.ts +20 -0
  101. package/dist/scene/tone-mapping.d.ts.map +1 -0
  102. package/dist/scene/velocity.d.ts +34 -0
  103. package/dist/scene/velocity.d.ts.map +1 -0
  104. package/dist/scene.js +889 -0
  105. package/dist/scene.js.map +1 -0
  106. package/dist/season/nodes.d.ts +13 -0
  107. package/dist/season/nodes.d.ts.map +1 -1
  108. package/dist/shader-hooks-BFRtlWGI.js +275 -0
  109. package/dist/shader-hooks-BFRtlWGI.js.map +1 -0
  110. package/dist/tree/Tree.d.ts +8 -3
  111. package/dist/tree/Tree.d.ts.map +1 -1
  112. package/dist/tree/index.d.ts.map +1 -1
  113. package/dist/weather/index.d.ts +3 -0
  114. package/dist/weather/index.d.ts.map +1 -0
  115. package/dist/weather/shared.d.ts +43 -0
  116. package/dist/weather/shared.d.ts.map +1 -0
  117. package/dist/weather/snow.d.ts +87 -0
  118. package/dist/weather/snow.d.ts.map +1 -0
  119. package/dist/weather/wetness.d.ts +75 -0
  120. package/dist/weather/wetness.d.ts.map +1 -0
  121. package/dist/weather.js +288 -0
  122. package/dist/weather.js.map +1 -0
  123. package/dist/wind/Wind.d.ts +100 -5
  124. package/dist/wind/Wind.d.ts.map +1 -1
  125. package/dist/wind/burst.d.ts +28 -0
  126. package/dist/wind/burst.d.ts.map +1 -0
  127. package/dist/wind/index.d.ts +3 -2
  128. package/dist/wind/index.d.ts.map +1 -1
  129. package/dist/wind/motion.d.ts +30 -0
  130. package/dist/wind/motion.d.ts.map +1 -0
  131. package/dist/wind/node.d.ts +17 -3
  132. package/dist/wind/node.d.ts.map +1 -1
  133. package/package.json +9 -1
  134. package/dist/effects.js.map +0 -1
  135. package/dist/forest-lg61rhKM.js.map +0 -1
@@ -1,6 +1,9 @@
1
- import { g as DEFAULT_FRUIT_COLOR, h as DEFAULT_FRUIT_AMOUNT, o as materialFeaturesOf, t as STYLE_NAMES, u as parseDefinition } from "./names-BE9he6CS.js";
2
- import { BufferAttribute, BufferGeometry, Color, DoubleSide, DynamicDrawUsage, Euler, Group, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMesh, InterleavedBuffer, InterleavedBufferAttribute, LightingModel, Matrix4, Mesh, MeshStandardNodeMaterial, NoColorSpace, PhysicalLightingModel, Quaternion, RepeatWrapping, SRGBColorSpace, Texture, TextureLoader, Vector3 } from "three/webgpu";
3
- import { BRDF_Lambert, attribute, color, cross, diffuseColor, dot, float, fract, length, mix, modelWorldMatrixInverse, normalGeometry, normalMap, normalView, normalize, positionGeometry, positionLocal, positionViewDirection, select, sin, smoothstep, texture, transformNormalToView, uniform, uv, varying, vec2, vec3, vec4 } from "three/tsl";
1
+ import { c as extendDefinition, g as DEFAULT_FRUIT_COLOR, h as DEFAULT_FRUIT_AMOUNT, o as materialFeaturesOf, t as STYLE_NAMES, u as parseDefinition } from "./names-BE9he6CS.js";
2
+ import { _ as clampGrowth, a as instanceRotate, c as instanceTreeBase, d as applyWind, f as objectWindDirection, g as growthScale, h as growthPosition, i as instanceBurstFrame, l as levelTreePosition, m as windOffset, n as drawsDetailLevel, p as treeSwayOffset, r as forestPosition, s as instanceState, t as INSTANCE_ATTRIBUTES, u as levelVisible } from "./nodes-DxgTyF9B.js";
3
+ import { c as WindBinding, l as sceneWind, p as setTreeLeafMask, t as setWindMotion } from "./motion-Qd7xjeZM.js";
4
+ import { i as partHookTarget, n as ShaderHookedGroup, t as LiveShaderHooks } from "./shader-hooks-BFRtlWGI.js";
5
+ import { BufferAttribute, BufferGeometry, Color, DoubleSide, DynamicDrawUsage, Euler, IndirectStorageBufferAttribute, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMesh, InterleavedBuffer, InterleavedBufferAttribute, LightingModel, LinearFilter, LinearMipmapLinearFilter, Matrix4, Mesh, MeshBasicNodeMaterial, MeshStandardNodeMaterial, NoColorSpace, OrthographicCamera, PhysicalLightingModel, Quaternion, RenderTarget, RendererUtils, RepeatWrapping, SRGBColorSpace, Scene, StorageBufferAttribute, Texture, TextureLoader, UnsignedByteType, Vector3 } from "three/webgpu";
6
+ import { BRDF_Lambert, Fn, If, abs, and, atomicAdd, atomicLoad, atomicStore, attribute, cameraPosition, cameraProjectionMatrix, cameraWorldMatrix, color, cross, diffuseColor, dot, float, floor, fract, frontFacing, instanceIndex, length, max, min, mix, modelWorldMatrix, modelWorldMatrixInverse, mrt, normalGeometry, normalMap, normalView, normalize, output, positionGeometry, positionLocal, positionViewDirection, screenCoordinate, select, smoothstep, storage, texture, transformNormalToView, uint, uniform, uv, varying, vec2, vec3, vec4 } from "three/tsl";
4
7
  // src/random/index.ts
5
8
  /**
6
9
  * Random: the only source of randomness in tree.js.
@@ -146,7 +149,7 @@ function sin$1(x) {
146
149
  return q === 0 ? kernelSin(r) : q === 1 ? kernelCos(r) : q === 2 ? -kernelSin(r) : -kernelCos(r);
147
150
  }
148
151
  /** Deterministic `Math.cos`. */
149
- function cos(x) {
152
+ function cos$1(x) {
150
153
  if (!Number.isFinite(x)) return NaN;
151
154
  const [r, q] = reduce(x);
152
155
  return q === 0 ? kernelCos(r) : q === 1 ? -kernelSin(r) : q === 2 ? -kernelCos(r) : kernelSin(r);
@@ -160,7 +163,7 @@ var P3 = 6613756321437934e-20;
160
163
  var P4 = -16533902205465252e-22;
161
164
  var P5 = 4.1381367970572385e-8;
162
165
  /** Deterministic `Math.exp`. */
163
- function exp(x) {
166
+ function exp$1(x) {
164
167
  if (Number.isNaN(x)) return NaN;
165
168
  if (x > 709.782712893384) return Number.POSITIVE_INFINITY;
166
169
  if (x < -745.1332191019411) return 0;
@@ -216,10 +219,10 @@ function pow(x, y) {
216
219
  if (x === 0) return y > 0 ? 0 : Number.POSITIVE_INFINITY;
217
220
  if (x < 0) {
218
221
  if (!Number.isInteger(y)) return NaN;
219
- const p = exp(y * log(-x));
222
+ const p = exp$1(y * log(-x));
220
223
  return y % 2 === 0 ? p : -p;
221
224
  }
222
- return exp(y * log(x));
225
+ return exp$1(y * log(x));
223
226
  }
224
227
  /** Deterministic `Math.hypot` of a 3-vector. */
225
228
  function hypot3(x, y, z) {
@@ -377,13 +380,13 @@ var scale = (a, s) => [
377
380
  a[2] * s
378
381
  ];
379
382
  var dot$1 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
380
- var cross$1 = (a, b) => [
383
+ var cross$2 = (a, b) => [
381
384
  a[1] * b[2] - a[2] * b[1],
382
385
  a[2] * b[0] - a[0] * b[2],
383
386
  a[0] * b[1] - a[1] * b[0]
384
387
  ];
385
388
  var length$1 = (a) => hypot3(a[0], a[1], a[2]);
386
- function normalize$1(a) {
389
+ function normalize$2(a) {
387
390
  const l = length$1(a);
388
391
  return l > 1e-12 ? scale(a, 1 / l) : [
389
392
  0,
@@ -398,7 +401,7 @@ var lerp = (a, b, t) => [
398
401
  ];
399
402
  /** Any unit vector perpendicular to the unit vector `v`. */
400
403
  function perpendicular(v) {
401
- return normalize$1(cross$1(Math.abs(v[1]) < .9 ? [
404
+ return normalize$2(cross$2(Math.abs(v[1]) < .9 ? [
402
405
  0,
403
406
  1,
404
407
  0
@@ -416,24 +419,24 @@ function perpendicular(v) {
416
419
  function branchFrames(branch) {
417
420
  const pts = branch.points.map((p) => p.position);
418
421
  const n = pts.length;
419
- const segment = (i) => normalize$1(sub(pts[Math.min(i + 1, n - 1)], pts[Math.min(i, n - 2)]));
422
+ const segment = (i) => normalize$2(sub(pts[Math.min(i + 1, n - 1)], pts[Math.min(i, n - 2)]));
420
423
  const frames = [];
421
424
  for (let i = 0; i < n; i++) {
422
425
  const tangent = i === 0 && branch.parent === null ? [
423
426
  0,
424
427
  1,
425
428
  0
426
- ] : i === 0 || i === n - 1 ? segment(Math.min(i, n - 2)) : normalize$1(add(segment(i - 1), segment(i)));
429
+ ] : i === 0 || i === n - 1 ? segment(Math.min(i, n - 2)) : normalize$2(add(segment(i - 1), segment(i)));
427
430
  let normal;
428
431
  if (i === 0) normal = perpendicular(tangent);
429
432
  else {
430
433
  const previous = frames[i - 1].normal;
431
- normal = normalize$1(sub(previous, scale(tangent, dot$1(previous, tangent))));
434
+ normal = normalize$2(sub(previous, scale(tangent, dot$1(previous, tangent))));
432
435
  }
433
436
  frames.push({
434
437
  tangent,
435
438
  normal,
436
- binormal: cross$1(tangent, normal)
439
+ binormal: cross$2(tangent, normal)
437
440
  });
438
441
  }
439
442
  return frames;
@@ -455,14 +458,14 @@ function sampleBranch(branch, frames, t) {
455
458
  const segment = length$1(sub(b.position, a.position));
456
459
  if (walked + segment >= target || i === pts.length - 1) {
457
460
  const f = segment > 0 ? Math.min(Math.max((target - walked) / segment, 0), 1) : 0;
458
- const tangent = normalize$1(sub(b.position, a.position));
459
- const normal = normalize$1(sub(frames[i - 1].normal, scale(tangent, dot$1(frames[i - 1].normal, tangent))));
461
+ const tangent = normalize$2(sub(b.position, a.position));
462
+ const normal = normalize$2(sub(frames[i - 1].normal, scale(tangent, dot$1(frames[i - 1].normal, tangent))));
460
463
  return {
461
464
  position: lerp(a.position, b.position, f),
462
465
  radius: a.radius + (b.radius - a.radius) * f,
463
466
  tangent,
464
467
  normal,
465
- binormal: cross$1(tangent, normal)
468
+ binormal: cross$2(tangent, normal)
466
469
  };
467
470
  }
468
471
  walked += segment;
@@ -517,8 +520,8 @@ function growChildren(parent, level, random) {
517
520
  const at = sampleBranch(parent, frames, t);
518
521
  const angle = Math.min(level.angle * crownShape(level.angleProfile, t) * (1 + r.range(-level.angleVariation, level.angleVariation)), 180) * DEG$4;
519
522
  const azimuth = azimuth0 + i * level.spiral * DEG$4;
520
- const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin$1(azimuth)));
521
- const start = normalize$1(add(scale(at.tangent, cos(angle)), scale(across, sin$1(angle))));
523
+ const across = add(scale(at.normal, cos$1(azimuth)), scale(at.binormal, sin$1(azimuth)));
524
+ const start = normalize$2(add(scale(at.tangent, cos$1(angle)), scale(across, sin$1(angle))));
522
525
  const pull = [
523
526
  0,
524
527
  level.gravity * GRAVITY_PER_BRANCH / level.sections,
@@ -540,7 +543,7 @@ function growChildren(parent, level, random) {
540
543
  r.range(-1, 1),
541
544
  r.range(-1, 1)
542
545
  ];
543
- direction = normalize$1(add(add(direction, scale(wander, level.bend)), pull));
546
+ direction = normalize$2(add(add(direction, scale(wander, level.bend)), pull));
544
547
  position = add(position, scale(direction, step));
545
548
  }
546
549
  children.push({
@@ -923,7 +926,7 @@ function clumpTemplate() {
923
926
  0,
924
927
  1
925
928
  ]
926
- ].map((v) => normalize$1(v));
929
+ ].map((v) => normalize$2(v));
927
930
  const centre = [
928
931
  0,
929
932
  0,
@@ -1054,7 +1057,7 @@ function puffTemplate() {
1054
1057
  const key = a < b ? `${a}-${b}` : `${b}-${a}`;
1055
1058
  let index = midpoints.get(key);
1056
1059
  if (index === void 0) {
1057
- index = normals.push(normalize$1(add(normals[a], normals[b]))) - 1;
1060
+ index = normals.push(normalize$2(add(normals[a], normals[b]))) - 1;
1058
1061
  midpoints.set(key, index);
1059
1062
  }
1060
1063
  return index;
@@ -1121,7 +1124,7 @@ function needleTemplate() {
1121
1124
  for (let s = 0; s < NEEDLE_SIDES; s++) {
1122
1125
  const angle = s / NEEDLE_SIDES * Math.PI * 2;
1123
1126
  const radial = [
1124
- cos(angle),
1127
+ cos$1(angle),
1125
1128
  sin$1(angle),
1126
1129
  0
1127
1130
  ];
@@ -1158,7 +1161,7 @@ var TEMPLATES = {
1158
1161
  function orient(template) {
1159
1162
  const { positions: p, normals: n } = template;
1160
1163
  const triangles = template.triangles.map(([a, b, c]) => {
1161
- return dot$1(cross$1(sub(p[b], p[a]), sub(p[c], p[a])), add(add(n[a], n[b]), n[c])) >= 0 ? [
1164
+ return dot$1(cross$2(sub(p[b], p[a]), sub(p[c], p[a])), add(add(n[a], n[b]), n[c])) >= 0 ? [
1162
1165
  a,
1163
1166
  b,
1164
1167
  c
@@ -1206,14 +1209,14 @@ function solidGeometry(template, placements, part) {
1206
1209
  const indices = new Uint32Array(placements.length * template.triangles.length * 3);
1207
1210
  const attributes = createAttributes(placements.length * n);
1208
1211
  placements.forEach((placement, l) => {
1209
- const side = cross$1(placement.normal, placement.direction);
1212
+ const side = cross$2(placement.normal, placement.direction);
1210
1213
  const toWorld = ([x, y, z]) => add(add(scale(side, x), scale(placement.normal, y)), scale(placement.direction, z));
1211
1214
  const info = part(placement, l);
1212
1215
  for (let c = 0; c < n; c++) {
1213
1216
  const v = l * n + c;
1214
1217
  const local = template.positions[c];
1215
1218
  positions.set(add(placement.position, scale(toWorld(local), placement.size)), v * 3);
1216
- normals.set(normalize$1(toWorld(template.normals[c])), v * 3);
1219
+ normals.set(normalize$2(toWorld(template.normals[c])), v * 3);
1217
1220
  const along = Math.min(Math.max(local[2], 0), 1);
1218
1221
  uvs.set([local[0] + .5, along], v * 2);
1219
1222
  colors.set(placement.tint, v * 3);
@@ -1278,15 +1281,15 @@ function placeFruit(definition, branches, random) {
1278
1281
  const t = FRUIT_START + .7 * (i + r.range(.1, .9)) / count;
1279
1282
  const at = sampleBranch(branch, frames, t);
1280
1283
  const azimuth = r.range(0, Math.PI * 2);
1281
- const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin$1(azimuth)));
1282
- const hanging = lerp(normalize$1(add(scale(at.tangent, cos(tilt)), scale(across, sin$1(tilt)))), down, fruit.hang);
1283
- const direction = length$1(hanging) > .001 ? normalize$1(hanging) : across;
1284
- const side0 = cross$1(direction, [
1284
+ const across = add(scale(at.normal, cos$1(azimuth)), scale(at.binormal, sin$1(azimuth)));
1285
+ const hanging = lerp(normalize$2(add(scale(at.tangent, cos$1(tilt)), scale(across, sin$1(tilt)))), down, fruit.hang);
1286
+ const direction = length$1(hanging) > .001 ? normalize$2(hanging) : across;
1287
+ const side0 = cross$2(direction, [
1285
1288
  0,
1286
1289
  1,
1287
1290
  0
1288
1291
  ]);
1289
- const normal = dot$1(side0, side0) > 1e-6 ? normalize$1(cross$1(normalize$1(side0), direction)) : perpendicular(direction);
1292
+ const normal = dot$1(side0, side0) > 1e-6 ? normalize$2(cross$2(normalize$2(side0), direction)) : perpendicular(direction);
1290
1293
  const size = fruit.size * (1 + r.range(-fruit.sizeVariation, fruit.sizeVariation));
1291
1294
  const brightness = r.range(-half, half);
1292
1295
  const tint = treeTint.map((c) => 1 + c + brightness);
@@ -1382,7 +1385,7 @@ function lathe(profile, sides, ends, twist = 0) {
1382
1385
  for (let s = 0; s < sides; s++) {
1383
1386
  const angle = (s + ring * twist) / sides * Math.PI * 2;
1384
1387
  const radial = [
1385
- cos(angle),
1388
+ cos$1(angle),
1386
1389
  sin$1(angle),
1387
1390
  0
1388
1391
  ];
@@ -1430,7 +1433,7 @@ function nutTemplate() {
1430
1433
  0,
1431
1434
  .5
1432
1435
  ];
1433
- const directions = ico.positions.map((p) => normalize$1([
1436
+ const directions = ico.positions.map((p) => normalize$2([
1434
1437
  p[0],
1435
1438
  p[1],
1436
1439
  p[2] - .5
@@ -1440,7 +1443,7 @@ function nutTemplate() {
1440
1443
  const key = a < b ? `${a}-${b}` : `${b}-${a}`;
1441
1444
  let index = midpoints.get(key);
1442
1445
  if (index === void 0) {
1443
- index = directions.push(normalize$1(add(directions[a], directions[b]))) - 1;
1446
+ index = directions.push(normalize$2(add(directions[a], directions[b]))) - 1;
1444
1447
  midpoints.set(key, index);
1445
1448
  }
1446
1449
  return index;
@@ -1531,8 +1534,6 @@ var COARSE = {
1531
1534
  cone: [[.25, .32], [.65, .28]],
1532
1535
  berry: [[.5, .5]]
1533
1536
  };
1534
- /** At or below this many sides, Fruit uses the coarse profiles (and the nut a plain icosahedron). */
1535
- var COARSE_SIDES = 5;
1536
1537
  /** The default templates: each Fruit Type's own sides (Definitions without `fruit.sides`). */
1537
1538
  var DEFAULT_SIDES = {
1538
1539
  round: 8,
@@ -1546,7 +1547,7 @@ function fruitTemplate(type, sides) {
1546
1547
  const key = `${type}/${sides ?? ""}`;
1547
1548
  let template = templates.get(key);
1548
1549
  if (!template) {
1549
- const coarse = sides !== void 0 && sides <= COARSE_SIDES;
1550
+ const coarse = sides !== void 0 && sides <= 5;
1550
1551
  if (type === "nut") template = coarse ? coarseNutTemplate() : nutTemplate();
1551
1552
  else {
1552
1553
  const { rings, ends, twist } = PROFILES[type];
@@ -1559,7 +1560,7 @@ function fruitTemplate(type, sides) {
1559
1560
  /** Low-detail chestnut husk: an icosahedron (its corners are the spikes). */
1560
1561
  function coarseNutTemplate() {
1561
1562
  const ico = clumpTemplate();
1562
- const directions = ico.positions.map((p) => normalize$1([
1563
+ const directions = ico.positions.map((p) => normalize$2([
1563
1564
  p[0],
1564
1565
  p[1],
1565
1566
  p[2] - .5
@@ -1668,16 +1669,16 @@ function placeLeaves(definition, branches, random) {
1668
1669
  const t = leaves.start + (1 - leaves.start) * (i + r.range(.1, .9)) / leaves.count;
1669
1670
  const at = sampleBranch(branch, frames, t);
1670
1671
  const azimuth = r.range(0, Math.PI * 2);
1671
- const across = add(scale(at.normal, cos(azimuth)), scale(at.binormal, sin$1(azimuth)));
1672
- const direction = normalize$1(add(scale(at.tangent, cos(tilt)), scale(across, sin$1(tilt))));
1673
- const side0 = cross$1(direction, [
1672
+ const across = add(scale(at.normal, cos$1(azimuth)), scale(at.binormal, sin$1(azimuth)));
1673
+ const direction = normalize$2(add(scale(at.tangent, cos$1(tilt)), scale(across, sin$1(tilt))));
1674
+ const side0 = cross$2(direction, [
1674
1675
  0,
1675
1676
  1,
1676
1677
  0
1677
1678
  ]);
1678
- const side = dot$1(side0, side0) > 1e-6 ? normalize$1(side0) : perpendicular(direction);
1679
+ const side = dot$1(side0, side0) > 1e-6 ? normalize$2(side0) : perpendicular(direction);
1679
1680
  const roll = r.range(-.4, .4);
1680
- const normal = normalize$1(add(scale(cross$1(side, direction), cos(roll)), scale(side, sin$1(roll))));
1681
+ const normal = normalize$2(add(scale(cross$2(side, direction), cos$1(roll)), scale(side, sin$1(roll))));
1681
1682
  const size = leaves.size * (1 + r.range(-leaves.sizeVariation, leaves.sizeVariation));
1682
1683
  const brightness = r.range(-half, half);
1683
1684
  const tint = treeTint.map((c) => 1 + c + brightness);
@@ -1705,7 +1706,7 @@ function leafGeometry(leaves, level, seed, variation = { season: 0 }, growth = [
1705
1706
  const indices = new Uint32Array(leaves.length * 6);
1706
1707
  const attributes = createAttributes(leaves.length * 4);
1707
1708
  leaves.forEach((leaf, l) => {
1708
- const side = cross$1(leaf.direction, leaf.normal);
1709
+ const side = cross$2(leaf.direction, leaf.normal);
1709
1710
  const halfWidth = leaf.size * LEAF_WIDTH / 2;
1710
1711
  const mid = add(leaf.position, scale(leaf.direction, leaf.size * .4));
1711
1712
  const corners = [
@@ -1835,11 +1836,11 @@ function centreLine(trunk, random) {
1835
1836
  */
1836
1837
  function placeStem(path, line, gravity, azimuth, tilt, offset) {
1837
1838
  const out = [
1838
- cos(azimuth),
1839
+ cos$1(azimuth),
1839
1840
  0,
1840
1841
  sin$1(azimuth)
1841
1842
  ];
1842
- const axis = cross$1([
1843
+ const axis = cross$2([
1843
1844
  0,
1844
1845
  1,
1845
1846
  0
@@ -1884,9 +1885,9 @@ function placeStem(path, line, gravity, azimuth, tilt, offset) {
1884
1885
  /** Rotates `v` about the unit `axis` by `angle` radians (Rodrigues). */
1885
1886
  function rotate(v, axis, angle) {
1886
1887
  if (angle === 0) return v;
1887
- const c = cos(angle);
1888
+ const c = cos$1(angle);
1888
1889
  const s = sin$1(angle);
1889
- return add(add(scale(v, c), scale(cross$1(axis, v), s)), scale(axis, dot$1(axis, v) * (1 - c)));
1890
+ return add(add(scale(v, c), scale(cross$2(axis, v), s)), scale(axis, dot$1(axis, v) * (1 - c)));
1890
1891
  }
1891
1892
  // src/generator/mesh.ts
1892
1893
  /**
@@ -1924,11 +1925,11 @@ function sweepBranch(branch, sides, random, season = {
1924
1925
  rings.forEach(({ position, radius, tangent, normal, binormal, along, slope }, r) => {
1925
1926
  for (let s = 0; s <= sides; s++) {
1926
1927
  const angle = s % sides / sides * Math.PI * 2;
1927
- const radial = add(scale(normal, cos(angle)), scale(binormal, sin$1(angle)));
1928
+ const radial = add(scale(normal, cos$1(angle)), scale(binormal, sin$1(angle)));
1928
1929
  const vertex = add(position, scale(radial, radius));
1929
1930
  if (stem && r === 0) vertex[1] -= BASE_SINK * pts[0].radius;
1930
1931
  positions.set(vertex, v * 3);
1931
- normals.set(normalize$1(add(radial, scale(tangent, slope))), v * 3);
1932
+ normals.set(normalize$2(add(radial, scale(tangent, slope))), v * 3);
1932
1933
  uvs.set([s / sides, along], v * 2);
1933
1934
  writePart(attributes, v, part, along, radius);
1934
1935
  v++;
@@ -2242,7 +2243,7 @@ function rootArc(definition, stem, turn) {
2242
2243
  }
2243
2244
  /** The horizontal unit vector ([x, z]) at `azimuth` in `arc`. */
2244
2245
  function toward(arc, azimuth) {
2245
- const [c, s] = [cos(azimuth), sin$1(azimuth)];
2246
+ const [c, s] = [cos$1(azimuth), sin$1(azimuth)];
2246
2247
  const [ox, oz] = arc.out;
2247
2248
  return [ox * c - oz * s, oz * c + ox * s];
2248
2249
  }
@@ -2288,9 +2289,9 @@ function growRoot(path, stem, roots, arc, azimuth, r) {
2288
2289
  for (let s = 0; s < sections; s++) {
2289
2290
  const [x, z] = toward(arc, heading);
2290
2291
  position = [
2291
- position[0] + step * cos(pitch) * x,
2292
+ position[0] + step * cos$1(pitch) * x,
2292
2293
  position[1] - step * sin$1(pitch),
2293
- position[2] + step * cos(pitch) * z
2294
+ position[2] + step * cos$1(pitch) * z
2294
2295
  ];
2295
2296
  positions.push(position);
2296
2297
  heading += r.range(-1, 1) * roots.bend * ROOT_BEND_TURN;
@@ -2308,9 +2309,9 @@ function growRoot(path, stem, roots, arc, azimuth, r) {
2308
2309
  };
2309
2310
  });
2310
2311
  const direction = [
2311
- cos(pitch) * outX,
2312
+ cos$1(pitch) * outX,
2312
2313
  -sin$1(pitch),
2313
- cos(pitch) * outZ
2314
+ cos$1(pitch) * outZ
2314
2315
  ];
2315
2316
  return {
2316
2317
  path,
@@ -2379,11 +2380,11 @@ function sculptLeaves(leaves, sculpts, seed) {
2379
2380
  /** The rotation of a three.js `Euler(x, y, z, 'XYZ')` (matrix Rx * Ry * Rz) as a function on vectors. */
2380
2381
  function eulerXYZ([x, y, z]) {
2381
2382
  const [a, b, c, d, e, f] = [
2382
- cos(x),
2383
+ cos$1(x),
2383
2384
  sin$1(x),
2384
- cos(y),
2385
+ cos$1(y),
2385
2386
  sin$1(y),
2386
- cos(z),
2387
+ cos$1(z),
2387
2388
  sin$1(z)
2388
2389
  ];
2389
2390
  const [ae, af, be, bf] = [
@@ -2409,6 +2410,184 @@ function eulerXYZ([x, y, z]) {
2409
2410
  m[6] * vx + m[7] * vy + m[8] * vz
2410
2411
  ];
2411
2412
  }
2413
+ // src/generator/light.ts
2414
+ /** Fewest sides around a part of the Light level (a triangle). */
2415
+ var MIN_SIDES = 3;
2416
+ /** Fewest sections along a part of the Light level. */
2417
+ var MIN_SECTIONS = 1;
2418
+ /** Most the leaves of the Light level grow, as a multiple of their size, to fill the crown of a dropped branch level. */
2419
+ var MAX_LEAF_GROWTH = 2.5;
2420
+ /** The share of the Full tree's Fruit the Light level keeps (each Fruit by its own stable random number). */
2421
+ var LIGHT_FRUIT_SHARE = .5;
2422
+ var halfSides = (sides) => Math.max(MIN_SIDES, Math.round(sides / 2));
2423
+ var halfSections = (sections) => Math.max(MIN_SECTIONS, Math.round(sections / 2));
2424
+ /**
2425
+ * The Light Definition (ADR 0010): the Definition a Forest's Light Detail Level is generated from.
2426
+ * Fixed reductions of `definition`:
2427
+ * - about half the sides and sections of the trunk and every branch level (at least 3 sides, 1 section),
2428
+ * half the sides of the Roots and half the extra rings of the Root Flare;
2429
+ * - the deepest branch level dropped (when there are at least two and it has branches), and the leaves
2430
+ * then grow on the level above, larger by the square root of the dropped level's `count` (at most
2431
+ * {@link MAX_LEAF_GROWTH} times) to keep the crown filled;
2432
+ * - with a single branch level kept: half the leaves per branch, larger to keep the same leaf area;
2433
+ * - coarse Fruit: half the sides, at most {@link COARSE_SIDES} (at least 3).
2434
+ *
2435
+ * Then `override` is merged on top (like {@link extendDefinition}: objects deeply, arrays replace) and the
2436
+ * result is validated. Pure and deterministic; never mutates `definition`.
2437
+ */
2438
+ function lightDefinition(definition, override = {}) {
2439
+ const { trunk, branches, leaves, fruit, roots } = definition;
2440
+ const deepest = branches[branches.length - 1];
2441
+ const drop = branches.length >= 2 && deepest.count > 0;
2442
+ const halved = drop ? leaves.count : Math.max(1, Math.round(leaves.count / 2));
2443
+ const growth = drop ? Math.min(Math.sqrt(deepest.count), MAX_LEAF_GROWTH) : leaves.count > 0 ? Math.sqrt(leaves.count / halved) : 1;
2444
+ const derived = {
2445
+ ...definition,
2446
+ trunk: {
2447
+ ...trunk,
2448
+ sides: halfSides(trunk.sides),
2449
+ sections: halfSections(trunk.sections),
2450
+ ...trunk.flare ? { flareSections: halfSections(trunk.flareSections ?? 3) } : {}
2451
+ },
2452
+ branches: (drop ? branches.slice(0, -1) : branches).map((level) => ({
2453
+ ...level,
2454
+ sides: halfSides(level.sides),
2455
+ sections: halfSections(level.sections)
2456
+ })),
2457
+ leaves: leaves.count > 0 ? {
2458
+ ...leaves,
2459
+ count: halved,
2460
+ size: leaves.size * growth
2461
+ } : leaves,
2462
+ ...fruit ? { fruit: {
2463
+ ...fruit,
2464
+ sides: Math.min(halfSides(fruit.sides ?? 10), 5)
2465
+ } } : {},
2466
+ ...roots ? { roots: {
2467
+ ...roots,
2468
+ sides: halfSides(rootSides(definition))
2469
+ } } : {}
2470
+ };
2471
+ return extendDefinition(derived, override);
2472
+ }
2473
+ /**
2474
+ * The Light Detail Level of a Variant (ADR 0010): the tree of `definition` and `seed`, generated from its
2475
+ * {@link lightDefinition} (with `override`) so that it keeps every surviving branch in place:
2476
+ *
2477
+ * - the skeleton grows with the Full Definition's sections (branch paths fork their randomness, ADR 0003,
2478
+ * so every branch the Light level keeps lies exactly where it does in the Full tree); the wood mesh then
2479
+ * sweeps only every other skeleton point (the Light sections) with the Light sides;
2480
+ * - leaves grow on the outermost Light branches, and only where the Full tree has leaves on that branch
2481
+ * or the branches growing from it (Sculpts deleting branches or painting leaves carry over);
2482
+ * - about half the Full tree's Fruit (each kept or not by its own stable random number) hangs where it
2483
+ * hangs in Full, drawn coarse (a Fruit that is already coarse cannot get fewer faces otherwise).
2484
+ *
2485
+ * Growth, Wind and Season attributes are those of the Full tree: a surviving branch (and its Fruit) grows,
2486
+ * sways and changes with the Season exactly as in Full; a Light leaf grows from the first to the last Full
2487
+ * leaf on its branch. Leaves and Fruit keep the Full `aLevel`. With `materials.occlusion` the meshes carry
2488
+ * `aOcclusion` like Full, so the Light meshes can share the Variant's materials. Pure and deterministic.
2489
+ */
2490
+ function generateLightTree(definition, seed, override) {
2491
+ const light = lightDefinition(definition, override);
2492
+ const random = createRandom(seed);
2493
+ const fullSculpts = sculptsFor(definition, seed);
2494
+ const fullStems = buildStems(definition, random);
2495
+ const fullBranches = sculptBranches([...fullStems, ...buildBranches(definition, fullStems, random.fork("branches"))], fullSculpts);
2496
+ const fullLeaves = sculptLeaves(placeLeaves(definition, fullBranches, random.fork("leaves")), fullSculpts, seed);
2497
+ const fullTiming = growthTiming(definition, seed, fullBranches, fullLeaves);
2498
+ const fullGrowth = new Map(fullBranches.map((b, i) => [b.path, fullTiming.branches[i]]));
2499
+ const fullFruit = placeFruit(definition, fullBranches, random.fork("fruit"));
2500
+ const fullFruitGrowth = fruitGrowth(seed, fullFruit, fullGrowth);
2501
+ const kept = fullFruit.map((f) => seedRandom(seed, `light/fruit/${f.id}`) < LIGHT_FRUIT_SHARE);
2502
+ const fruit = fullFruit.filter((_, i) => kept[i]);
2503
+ const leafSpan = /* @__PURE__ */ new Map();
2504
+ fullLeaves.forEach((leaf, l) => {
2505
+ const window = fullTiming.leaves[l];
2506
+ const parts = leaf.branch.split(".");
2507
+ for (let n = 1; n <= parts.length; n++) {
2508
+ const path = parts.slice(0, n).join(".");
2509
+ const span = leafSpan.get(path);
2510
+ leafSpan.set(path, span ? {
2511
+ start: Math.min(span.start, window.start),
2512
+ end: Math.max(span.end, window.end)
2513
+ } : window);
2514
+ }
2515
+ });
2516
+ const shape = {
2517
+ ...light,
2518
+ trunk: {
2519
+ ...light.trunk,
2520
+ sections: definition.trunk.sections
2521
+ },
2522
+ branches: light.branches.map((level, i) => ({
2523
+ ...level,
2524
+ sections: definition.branches[i]?.sections ?? level.sections
2525
+ }))
2526
+ };
2527
+ const sculpts = sculptsFor(shape, seed);
2528
+ const stems = buildStems(shape, random);
2529
+ const branches = sculptBranches([...stems, ...buildBranches(shape, stems, random.fork("branches"))], sculpts);
2530
+ const leaves = sculptLeaves(placeLeaves(light, branches, random.fork("leaves")), sculpts, seed).filter((leaf) => leafSpan.has(leaf.branch));
2531
+ const roots = growRoots(light, branches.filter((b) => b.parent === null), random);
2532
+ const own = growthTiming(light, seed, branches, []);
2533
+ const growth = {
2534
+ branches: branches.map((b, i) => fullGrowth.get(b.path) ?? own.branches[i]),
2535
+ leaves: leaves.map((leaf) => leafSpan.get(leaf.branch)),
2536
+ fruit: fullFruitGrowth.filter((_, i) => kept[i]),
2537
+ roots: roots.map(() => ({
2538
+ start: 0,
2539
+ end: 0
2540
+ }))
2541
+ };
2542
+ const sway = new Map([...branchSway(branches, light.branches.length), ...branchSway(fullBranches, definition.branches.length)]);
2543
+ const sidesOf = (level) => level === 0 ? light.trunk.sides : light.branches[level - 1].sides;
2544
+ const sectionsOf = (level) => level === 0 ? light.trunk.sections : light.branches[level - 1].sections;
2545
+ const stemSweep = {
2546
+ flare: light.trunk.flare ?? 0,
2547
+ sections: light.trunk.flareSections ?? 3
2548
+ };
2549
+ const woodSeason = woodSeasonAttribute(seed, definition.variation);
2550
+ const wood = mergeBuffers([...branches.map((b, i) => sweepBranch(coarsen(b, sectionsOf(b.level)), sidesOf(b.level), seedRandom(seed, b.path), woodSeason, growth.branches[i], sway.get(b.path), b.parent === null ? stemSweep : void 0)), ...roots.map((root, i) => sweepBranch(root, rootSides(light), seedRandom(seed, root.path), woodSeason, growth.roots[i]))]);
2551
+ const leafLevel = definition.branches.length + 1;
2552
+ const leafBuffers = light.leaves.shape === "card" ? leafGeometry(leaves, leafLevel, seed, definition.variation, growth.leaves, sway) : solidLeafGeometry(leaves, light.leaves.shape, leafLevel, seed, definition.variation, growth.leaves, sway);
2553
+ const fruitBuffers = light.fruit ? fruitGeometry(fruit, light.fruit, definition.branches.length + 2, seed, definition.variation, growth.fruit, sway) : emptyGeometry();
2554
+ const skeleton = {
2555
+ branches,
2556
+ leaves,
2557
+ fruit,
2558
+ roots
2559
+ };
2560
+ const height = trunkHeight(skeleton);
2561
+ for (const buffers of [
2562
+ wood,
2563
+ leafBuffers,
2564
+ fruitBuffers
2565
+ ]) writeTrunkSway(buffers, height);
2566
+ const crown = crownVolume(leafBuffers.positions, branches);
2567
+ if (definition.materials.occlusion) bakeOcclusion([
2568
+ wood,
2569
+ leafBuffers,
2570
+ fruitBuffers
2571
+ ], leafBuffers, crown);
2572
+ return {
2573
+ seed,
2574
+ skeleton,
2575
+ wood,
2576
+ leaves: leafBuffers,
2577
+ fruit: fruitBuffers,
2578
+ growth,
2579
+ crown
2580
+ };
2581
+ }
2582
+ /** The branch with only `sections` + 1 of its skeleton points (evenly picked, both ends kept) to sweep. */
2583
+ function coarsen(branch, sections) {
2584
+ const n = branch.points.length - 1;
2585
+ if (sections >= n) return branch;
2586
+ return {
2587
+ ...branch,
2588
+ points: Array.from({ length: sections + 1 }, (_, k) => branch.points[Math.round(k * n / sections)])
2589
+ };
2590
+ }
2412
2591
  // src/generator/index.ts
2413
2592
  /**
2414
2593
  * The Generator: a pure function from a (parsed) Tree Definition and a Seed to tree data.
@@ -2500,99 +2679,6 @@ function hashBuffers(geometry, h) {
2500
2679
  return h;
2501
2680
  }
2502
2681
  var hex = (h) => h.toString(16).padStart(8, "0");
2503
- // src/growth/evaluate.ts
2504
- /**
2505
- * The Growth model, one spec with two backends: `growPositions` (CPU, here) and `growthPosition`
2506
- * (TSL, `./tsl.ts`). Keep them in step. Per vertex, at Growth `g`:
2507
- *
2508
- * 1. thicken: move the vertex towards its part's centre line, keeping `thickness(g)` of its radius
2509
- * (`aGrowth.z`, along the vertex normal);
2510
- * 2. sprout: scale the part about its base point (`aOrigin`) by `partProgress(g, start, end)`
2511
- * (`aGrowth.xy`), so a part grows out of a point on its (already grown) parent;
2512
- * 3. size: scale the whole tree about its base (local origin) by `treeScale(g)`.
2513
- *
2514
- * Every step is written as `x - offset * (1 - factor)`, so at Growth 1 the positions are exactly
2515
- * the generated ones: a tree at Growth 1 is a normal static tree.
2516
- */
2517
- /** Size of the whole tree at Growth 0 (sapling), relative to fully grown. */
2518
- var SAPLING_SCALE = .2;
2519
- /** Branch thickness at Growth 0, relative to the size-scaled thickness when fully grown. */
2520
- var SAPLING_THICKNESS = .4;
2521
- /** Smallest window width, so parts with `start == end` (the trunk) are simply grown. */
2522
- var MIN_WINDOW = 1e-5;
2523
- var treeScale = (growth) => SAPLING_SCALE + .8 * growth;
2524
- var thickness$1 = (growth) => SAPLING_THICKNESS + .6 * growth;
2525
- /** How far one part has sprouted (0 = not yet, 1 = full size), eased; 1 from `end` on. */
2526
- function partProgress$1(growth, start, end) {
2527
- const p = Math.min(Math.max((growth - end) / Math.max(end - start, MIN_WINDOW) + 1, 0), 1);
2528
- return p * p * (3 - 2 * p);
2529
- }
2530
- /** Clamps a Growth value to 0..1 (NaN becomes 1, fully grown). */
2531
- function clampGrowth(growth) {
2532
- return Number.isNaN(growth) ? 1 : Math.min(Math.max(growth, 0), 1);
2533
- }
2534
- /**
2535
- * Vertex positions of generated geometry at a given Growth, on the CPU (for baking a tree and
2536
- * for tests; at runtime the same model runs in TSL). Returns a new array.
2537
- */
2538
- function growPositions(buffers, growth) {
2539
- const g = clampGrowth(growth);
2540
- const { positions, normals } = buffers;
2541
- const { aOrigin, aGrowth } = buffers.attributes;
2542
- const out = new Float32Array(positions.length);
2543
- const scale = treeScale(g);
2544
- const thin = 1 - thickness$1(g);
2545
- for (let v = 0; v < positions.length / 3; v++) {
2546
- const [start, end, radius] = [
2547
- aGrowth.array[v * 3],
2548
- aGrowth.array[v * 3 + 1],
2549
- aGrowth.array[v * 3 + 2]
2550
- ];
2551
- const shrink = 1 - partProgress$1(g, start, end);
2552
- for (let k = 0; k < 3; k++) {
2553
- const i = v * 3 + k;
2554
- const thick = positions[i] - normals[i] * radius * thin;
2555
- const sprouted = thick - (thick - aOrigin.array[i]) * shrink;
2556
- out[i] = sprouted - sprouted * (1 - scale);
2557
- }
2558
- }
2559
- return out;
2560
- }
2561
- // src/growth/tsl.ts
2562
- /** Size of the whole tree at Growth `g` (twin of `treeScale`): the scale `growthPosition` gives the tree. */
2563
- var growthScale = (g) => float(SAPLING_SCALE).add(float(1 - SAPLING_SCALE).mul(g));
2564
- /** Branch thickness at Growth `g` (twin of `thickness`). */
2565
- var thickness = (g) => float(SAPLING_THICKNESS).add(float(1 - SAPLING_THICKNESS).mul(g));
2566
- /** How far one part has sprouted, eased (twin of `partProgress`). */
2567
- function partProgress(g, start, end) {
2568
- const p = g.sub(end).div(end.sub(start).max(MIN_WINDOW)).add(1).clamp(0, 1);
2569
- return p.mul(p).mul(float(3).sub(p.mul(2)));
2570
- }
2571
- /**
2572
- * Growth in TSL: the vertex position of a tree part at Growth `growth` (a float node, usually the
2573
- * tree's Growth uniform; a Forest can pass a per-instance attribute instead). Same model and steps
2574
- * as `growPositions` (see `./evaluate.ts`), driven by the Generator's `aGrowth` and `aOrigin` attributes.
2575
- *
2576
- * `position` is the input position (default `positionLocal`). To compose with other vertex effects,
2577
- * feed this node into them, e.g. `material.positionNode = windPosition(growthPosition(uGrowth))`:
2578
- * Growth first, so the rest acts on the grown tree.
2579
- */
2580
- function growthPosition(growth, position = positionLocal) {
2581
- const g = float(growth).clamp(0, 1);
2582
- const data = attribute("aGrowth", "vec3");
2583
- const origin = attribute("aOrigin", "vec3");
2584
- const [start, end, radius] = [
2585
- data.x,
2586
- data.y,
2587
- data.z
2588
- ];
2589
- const scale = growthScale(g);
2590
- const thin = float(1).sub(thickness(g));
2591
- const shrink = float(1).sub(partProgress(g, start, end));
2592
- const thick = position.sub(normalGeometry.mul(radius).mul(thin));
2593
- const sprouted = thick.sub(thick.sub(origin).mul(shrink));
2594
- return sprouted.sub(sprouted.mul(float(1).sub(scale)));
2595
- }
2596
2682
  // src/materials/ground-tint.ts
2597
2683
  /**
2598
2684
  * Ground Tint (GLOSSARY): how far the bark blends towards `tint.color` at tree-space height `y`
@@ -2726,7 +2812,14 @@ var load = (url, kind, textures) => loadTexture(resolveTextureUrl(url, textures)
2726
2812
  * so a sapling is measured against its own, smaller crown. Shared by the Material Features.
2727
2813
  */
2728
2814
  function crownNodes(crown, growth) {
2729
- const local = varying(growthPosition(growth, positionGeometry), "vCrownPosition").div(growthScale(float(growth).clamp(0, 1))).sub(vec3(...crown.center));
2815
+ return crownAt(crown, varying(growthPosition(growth, positionGeometry), "vCrownPosition").div(growthScale(float(growth).clamp(0, 1))));
2816
+ }
2817
+ /**
2818
+ * The Crown Volume measured at `point`, a position in the fully grown tree's own space (Growth 1, no
2819
+ * Wind). `crownNodes` uses it for a tree's vertices; an Impostor for the point its bake pictured.
2820
+ */
2821
+ function crownAt(crown, point) {
2822
+ const local = point.sub(vec3(...crown.center));
2730
2823
  const radii = vec3(...crown.radii);
2731
2824
  const unit = local.div(radii);
2732
2825
  const gradient = unit.div(radii);
@@ -2970,7 +3063,13 @@ var TranslucentLightingModel = class extends PhysicalLightingModel {
2970
3063
  * `positionNode` grows with (a Tree's Growth uniform, or a Forest's per-instance Growth).
2971
3064
  */
2972
3065
  function applyLeafTranslucency(material, values, crown, growth) {
2973
- const term = leafTranslucencyTerm(values, crown, growth);
3066
+ applyLeafTranslucencyTerm(material, leafTranslucencyTerm(values, crown, growth));
3067
+ }
3068
+ /**
3069
+ * Gives `material` the translucent lighting model for a ready-made term (`applyLeafTranslucency` builds
3070
+ * it from a tree's vertices; an Impostor from its baked Crown Volume distance).
3071
+ */
3072
+ function applyLeafTranslucencyTerm(material, term) {
2974
3073
  const toon = material instanceof SoftToonNodeMaterial;
2975
3074
  material.setupLightingModel = () => toon ? new SoftToonLightingModel(term) : new TranslucentLightingModel(term);
2976
3075
  material.needsUpdate = true;
@@ -3014,6 +3113,14 @@ var LiveMaterialFeatures = class {
3014
3113
  if (this.occlusion) applyStructuralOcclusion(materials, this.occlusion);
3015
3114
  }
3016
3115
  }
3116
+ /** The features that are on, as their shared uniforms (tuning them reaches every material that reads them). */
3117
+ get nodes() {
3118
+ return {
3119
+ crownNormals: this.crown,
3120
+ translucency: this.translucencyValues,
3121
+ occlusion: this.occlusion
3122
+ };
3123
+ }
3017
3124
  /** The features that are on, with their current values (same shape as `materialFeaturesOf`). */
3018
3125
  get values() {
3019
3126
  return {
@@ -3075,6 +3182,14 @@ function assertWebGPURenderer(renderer) {
3075
3182
  if (r?.isWebGPURenderer === true) return;
3076
3183
  throw new UnsupportedRendererError(r?.isWebGLRenderer ? "the classic WebGLRenderer" : "an unknown renderer");
3077
3184
  }
3185
+ /**
3186
+ * @internal The renderer an `onBeforeRender` callback receives (typed as the classic renderer by
3187
+ * three's types), as the `WebGPURenderer` it must be. Throws {@link UnsupportedRendererError} otherwise.
3188
+ */
3189
+ function webgpuRenderer(renderer) {
3190
+ assertWebGPURenderer(renderer);
3191
+ return renderer;
3192
+ }
3078
3193
  // src/season/nodes.ts
3079
3194
  /**
3080
3195
  * Unrolls a keyframe track into a chain of mixes over uniforms (one per segment). Same maths
@@ -3082,27 +3197,45 @@ function assertWebGPURenderer(renderer) {
3082
3197
  * never recompiles; only a different key count does.
3083
3198
  */
3084
3199
  function keyframeNode(s, track, toUniform) {
3200
+ return keyframeSampler(track, toUniform)(s);
3201
+ }
3202
+ /** As `keyframeNode`, with the uniforms made once: the returned function samples the track at any Season node. */
3203
+ function keyframeSampler(track, toUniform) {
3085
3204
  const ts = track.map((k) => uniform(k.t));
3086
3205
  const vs = track.map((k) => toUniform(k.value));
3087
- let out = vs[0];
3088
- for (let i = 0; i < track.length - 1; i++) {
3089
- const f = s.sub(ts[i]).div(ts[i + 1].sub(ts[i]).max(KEYFRAME_EPSILON)).clamp(0, 1);
3090
- out = mix(out, vs[i + 1], f);
3091
- }
3092
- return out;
3206
+ return (s) => {
3207
+ let out = vs[0];
3208
+ for (let i = 0; i < track.length - 1; i++) {
3209
+ const f = s.sub(ts[i]).div(ts[i + 1].sub(ts[i]).max(KEYFRAME_EPSILON)).clamp(0, 1);
3210
+ out = mix(out, vs[i + 1], f);
3211
+ }
3212
+ return out;
3213
+ };
3093
3214
  }
3094
- function createSeasonNodes(profile, season = uniform(0)) {
3095
- const aSeason = attribute("aSeason", "vec3");
3096
- const s = shiftedSeason$1(season, aSeason);
3097
- const leafColor = keyframeNode(s, profile.leafColor, (v) => uniform(new Color(v)));
3098
- const coverage = keyframeNode(s, profile.leafCoverage, (v) => uniform(v));
3099
- const blossom = keyframeNode(s, profile.blossom, (v) => uniform(v));
3215
+ /**
3216
+ * The TSL twin of `leafSeason` for a Season Profile: returns a function that evaluates one leaf from
3217
+ * a Season node and its Season timing (vec3: shift, coverage rank, blossom rank, as `aSeason`). The
3218
+ * Profile's uniforms are made once, so it can be called for many leaves (an Impostor's frames).
3219
+ */
3220
+ function leafSeasonNode(profile) {
3221
+ const leafColor = keyframeSampler(profile.leafColor, (v) => uniform(new Color(v)));
3222
+ const coverage = keyframeSampler(profile.leafCoverage, (v) => uniform(v));
3223
+ const blossom = keyframeSampler(profile.blossom, (v) => uniform(v));
3100
3224
  const blossomColor = uniform(new Color(profile.blossomColor));
3101
- const isBlossom = blossom.greaterThan(aSeason.z);
3102
- const shown = isBlossom.or(coverage.greaterThan(aSeason.y));
3225
+ return (season, part) => {
3226
+ const s = shiftedSeason$1(season, part);
3227
+ const isBlossom = blossom(s).greaterThan(part.z);
3228
+ return {
3229
+ color: select(isBlossom, blossomColor, leafColor(s)),
3230
+ shown: isBlossom.or(coverage(s).greaterThan(part.y))
3231
+ };
3232
+ };
3233
+ }
3234
+ function createSeasonNodes(profile, season = uniform(0)) {
3235
+ const { color, shown } = leafSeasonNode(profile)(season, attribute("aSeason", "vec3"));
3103
3236
  return {
3104
3237
  season,
3105
- color: varying(select(isBlossom, blossomColor, leafColor)),
3238
+ color: varying(color),
3106
3239
  visible: varying(select(shown, float(1), float(0))).greaterThan(.5)
3107
3240
  };
3108
3241
  }
@@ -3145,81 +3278,6 @@ function checkedSeason(value) {
3145
3278
  if (!Number.isFinite(value)) throw new RangeError(`Season must be a finite number, got ${value}`);
3146
3279
  return wrapSeason(value);
3147
3280
  }
3148
- // src/wind/Wind.ts
3149
- /**
3150
- * Scene-wide Wind: a direction and a strength that every tree listening to it sways with.
3151
- * Changing them only writes uniform values (no recompile). Trees use {@link sceneWind} unless
3152
- * `createTree(..., { wind })` names another one. How much each tree moves is its Definition's
3153
- * Wind response (`definition.wind`).
3154
- */
3155
- var Wind = class {
3156
- /** The shared TSL uniforms tree materials read. Write through the setters, not here. */
3157
- uniforms;
3158
- pinnedTime = null;
3159
- constructor(options = {}) {
3160
- this.uniforms = {
3161
- direction: uniform(new Vector3(1, 0, 0)),
3162
- strength: uniform(0),
3163
- time: uniform(0).onRenderUpdate((frame) => this.pinnedTime ?? frame.time)
3164
- };
3165
- this.set(options);
3166
- }
3167
- /** Unit direction the wind blows towards (a copy: assign a new value to change it). */
3168
- get direction() {
3169
- return this.uniforms.direction.value.clone();
3170
- }
3171
- set direction(value) {
3172
- const v = Array.isArray(value) ? new Vector3(...value) : value.clone();
3173
- const length = v.length();
3174
- if (!Number.isFinite(length) || length === 0) throw new RangeError(`Wind direction must be a finite, non-zero vector, got [${v.toArray().join(", ")}]`);
3175
- this.uniforms.direction.value.copy(v.divideScalar(length));
3176
- }
3177
- get strength() {
3178
- return this.uniforms.strength.value;
3179
- }
3180
- set strength(value) {
3181
- if (!Number.isFinite(value) || value < 0) throw new RangeError(`Wind strength must be a finite number >= 0, got ${value}`);
3182
- this.uniforms.strength.value = value;
3183
- }
3184
- /**
3185
- * Pins the Wind clock to a time in seconds (pause, deterministic screenshots), or `null`
3186
- * (default) to follow the renderer's clock.
3187
- */
3188
- get time() {
3189
- return this.pinnedTime;
3190
- }
3191
- set time(value) {
3192
- this.pinnedTime = value;
3193
- if (value !== null) this.uniforms.time.value = value;
3194
- }
3195
- /** Sets direction and/or strength; returns this. */
3196
- set(options) {
3197
- if (options.direction !== void 0) this.direction = options.direction;
3198
- if (options.strength !== void 0) this.strength = options.strength;
3199
- return this;
3200
- }
3201
- };
3202
- /** The scene-wide Wind every tree sways with by default. */
3203
- var sceneWind = new Wind();
3204
- /**
3205
- * Per-object Wind uniforms that follow whichever Wind is bound to them, read once per render.
3206
- * Trees and Forests build their Wind nodes on these, so switching to another Wind is one
3207
- * assignment: no new nodes, no recompile, no regeneration.
3208
- */
3209
- var WindBinding = class {
3210
- /** The bound Wind. */
3211
- wind;
3212
- uniforms;
3213
- constructor(wind) {
3214
- this.wind = wind;
3215
- const direction = wind.uniforms.direction.value.clone();
3216
- this.uniforms = {
3217
- direction: uniform(direction).onRenderUpdate(() => direction.copy(this.wind.uniforms.direction.value)),
3218
- strength: uniform(wind.strength).onRenderUpdate(() => this.wind.strength),
3219
- time: uniform(0).onRenderUpdate((frame) => this.wind.time ?? frame.time)
3220
- };
3221
- }
3222
- };
3223
3281
  // src/wind/response.ts
3224
3282
  /**
3225
3283
  * One tree's response to the Wind (from its Definition's `wind`), held in uniforms so the
@@ -3268,58 +3326,6 @@ var WindResponse = class {
3268
3326
  return this;
3269
3327
  }
3270
3328
  };
3271
- // src/wind/node.ts
3272
- var TRUNK_AMPLITUDE = .15;
3273
- var BRANCH_AMPLITUDE = .1;
3274
- var LEAF_AMPLITUDE = .2;
3275
- /** The scene Wind direction in the rendered object's space (rotation only, normalized). */
3276
- function objectWindDirection(wind) {
3277
- return modelWorldMatrixInverse.mul(vec4(wind.uniforms.direction, 0)).xyz.normalize();
3278
- }
3279
- /**
3280
- * TSL node: the Wind displacement (vec3, object space) of each vertex, from the per-vertex
3281
- * `aWind` weights (trunk sway, branch sway, leaf flutter), the tree's Wind response and the
3282
- * scene Wind. It only depends on geometry attributes and uniforms, so it adds onto any other
3283
- * position node (Growth): `position = grown + windOffset(...)` (see {@link applyWind}).
3284
- *
3285
- * - trunk: leans with the wind and swings slowly, bending from the ground (weight = height²);
3286
- * - branches: swing faster, with a phase that varies smoothly in space so joints stay attached,
3287
- * plus a little cross-wind motion;
3288
- * - leaves: flutter along their normal, more at the tip.
3289
- * All of it is scaled by slow gusts. Wind direction is world space; it is turned into the tree's
3290
- * object space (rotation only, so a scaled-up tree sways proportionally more). `frame` replaces
3291
- * that direction and the response's phase (see {@link WindFrame}).
3292
- */
3293
- function windOffset(wind, response, frame = {}) {
3294
- const weights = attribute("aWind", "vec3");
3295
- const random = attribute("aRandom", "float");
3296
- const origin = attribute("aOrigin", "vec3");
3297
- const r = response.uniforms;
3298
- const strength = wind.uniforms.strength;
3299
- const t = wind.uniforms.time.mul(r.frequency).add(frame.phase ?? r.phase);
3300
- const direction = (frame.direction ?? objectWindDirection(wind)).normalize();
3301
- const across = cross(direction, vec3(0, 1, 0));
3302
- const gust = sin(t.mul(.37)).add(sin(t.mul(.91).add(1.7))).mul(.1).add(.8);
3303
- const scale = strength.mul(r.height).mul(gust);
3304
- const trunkSwing = sin(t.mul(1.1)).mul(.25).add(.75);
3305
- const trunk = direction.mul(trunkSwing.mul(r.trunk).mul(weights.x).mul(scale).mul(TRUNK_AMPLITUDE));
3306
- const spatialPhase = dot(positionGeometry, vec3(.9, .4, .7));
3307
- const branchSwing = sin(t.mul(2.3).add(spatialPhase)).mul(.35).add(.65);
3308
- const branchCross = sin(t.mul(1.7).add(spatialPhase.mul(1.3))).mul(.3);
3309
- const branches = direction.mul(branchSwing).add(across.mul(branchCross)).mul(r.branches.mul(weights.y).mul(scale).mul(BRANCH_AMPLITUDE));
3310
- const leafLength = positionGeometry.sub(origin).length();
3311
- const flutter = sin(t.mul(9).add(random.mul(6.2832)));
3312
- const leaves = normalGeometry.mul(flutter.mul(r.leaves).mul(weights.z).mul(leafLength).mul(strength).mul(gust).mul(LEAF_AMPLITUDE));
3313
- return trunk.add(branches).add(leaves);
3314
- }
3315
- /**
3316
- * Adds a Wind offset to a material's vertex position (its existing `positionNode`, or the plain
3317
- * local position). The shadow pass reuses `positionNode`, so shadows sway along.
3318
- */
3319
- function applyWind(material, offset) {
3320
- material.positionNode = material.positionNode ? material.positionNode.add(offset) : positionLocal.add(offset);
3321
- material.needsUpdate = true;
3322
- }
3323
3329
  // src/tree/Tree.ts
3324
3330
  /**
3325
3331
  * The Generator's per-vertex part attributes (`aLevel`, `aSeason`, `aWind`, ...) go into one
@@ -3367,7 +3373,7 @@ function treeMesh(name, geometry, material) {
3367
3373
  * A generated tree as a three.js object. Add it to a scene rendered by `WebGPURenderer`.
3368
3374
  * `growth`, `season` and the Wind only update uniforms: no regeneration, no recompile.
3369
3375
  */
3370
- var Tree = class extends Group {
3376
+ var Tree = class extends ShaderHookedGroup {
3371
3377
  isTree = true;
3372
3378
  definition;
3373
3379
  seed;
@@ -3387,6 +3393,7 @@ var Tree = class extends Group {
3387
3393
  windResponse;
3388
3394
  windBinding;
3389
3395
  features;
3396
+ hooks;
3390
3397
  /**
3391
3398
  * Resolves once every texture of this tree has loaded (at once for a tree without textures);
3392
3399
  * rejects if one fails. Await it before a first render that must show the textures.
@@ -3430,6 +3437,16 @@ var Tree = class extends Group {
3430
3437
  fruit.colorNode = fruitSeason.color;
3431
3438
  fruit.positionNode = growthPosition(this.growthUniform, fruitSeason.position);
3432
3439
  applyWind(fruit, offset);
3440
+ const motion = {
3441
+ source: this.windBinding,
3442
+ offset,
3443
+ shift: (previous) => windOffset(this.windBinding, this.windResponse, { time: previous }).sub(offset)
3444
+ };
3445
+ for (const material of [
3446
+ bark,
3447
+ leaf,
3448
+ fruit
3449
+ ]) setWindMotion(material.positionNode, motion);
3433
3450
  this.season = options.season ?? 0;
3434
3451
  this.features = new LiveMaterialFeatures(definition, [{
3435
3452
  leaf,
@@ -3441,6 +3458,15 @@ var Tree = class extends Group {
3441
3458
  crown: data.crown,
3442
3459
  growth: this.growthUniform
3443
3460
  }]);
3461
+ const inputs = {
3462
+ season: this.seasonUniform,
3463
+ growth: this.growthUniform
3464
+ };
3465
+ this.hooks = new LiveShaderHooks([
3466
+ partHookTarget("bark", bark, this.wood.geometry, inputs),
3467
+ partHookTarget("leaves", leaf, this.leaves.geometry, inputs),
3468
+ partHookTarget("fruit", fruit, this.fruit.geometry, inputs)
3469
+ ], definition.materials.shading, options.shaderHooks);
3444
3470
  }
3445
3471
  /**
3446
3472
  * Crown Normals amount (0..1), from the Definition's `materials.leaf.crownNormals`; null when it is off.
@@ -3484,7 +3510,8 @@ var Tree = class extends Group {
3484
3510
  }
3485
3511
  /**
3486
3512
  * The Wind this tree sways with (shared with every other tree using it). Assigning another
3487
- * Wind only rebinds uniforms: no regeneration, no recompile.
3513
+ * Wind only rebinds uniforms: no regeneration, no recompile (except the one-time node-graph rebuild
3514
+ * when the tree first follows a Wind that has had a Wind Burst, see `Wind.burst`).
3488
3515
  */
3489
3516
  get wind() {
3490
3517
  return this.windBinding.wind;
@@ -3515,6 +3542,7 @@ var Tree = class extends Group {
3515
3542
  }
3516
3543
  /** Frees the GPU resources (geometries and materials) of this tree and removes it from its parent. */
3517
3544
  dispose() {
3545
+ this.hooks.dispose();
3518
3546
  this.traverse((object) => {
3519
3547
  if (object instanceof Mesh) {
3520
3548
  object.geometry.dispose();
@@ -3538,7 +3566,8 @@ function createTree(definition, options = {}) {
3538
3566
  growth: options.growth,
3539
3567
  wind: options.wind,
3540
3568
  season: options.season,
3541
- textures: options.textures
3569
+ textures: options.textures,
3570
+ shaderHooks: options.shaderHooks
3542
3571
  });
3543
3572
  }
3544
3573
  // src/styles/registry.ts
@@ -3558,51 +3587,1217 @@ async function loadStyle(name) {
3558
3587
  if (!load) throw new Error(`Unknown tree.js Style "${name}". Built-in Styles: ${STYLE_NAMES.join(", ")}.`);
3559
3588
  return (await load()).default;
3560
3589
  }
3561
- // src/forest/nodes.ts
3562
- var INSTANCE_ATTRIBUTES = {
3563
- iRotation: 0,
3564
- iState: 4
3565
- };
3566
- /** Per-tree values in the instanced Season/Growth/Wind slots. */
3567
- function instanceState() {
3568
- const state = attribute("iState", "vec4");
3590
+ // src/forest/impostor-season.ts
3591
+ /** The leaf timing shift is within ±`variation.season` (at most 1); the atlas keeps it as `shift · SCALE + 0.5`. */
3592
+ var SEASON_SHIFT_SCALE = .5;
3593
+ /** The texel the bake writes for a leaf (`aSeason`), or for wood (`null`: empty). */
3594
+ function encodeSeasonTexel(part) {
3595
+ if (!part) return [
3596
+ 0,
3597
+ 0,
3598
+ 0,
3599
+ 0
3600
+ ];
3601
+ return [
3602
+ part.shift * SEASON_SHIFT_SCALE + .5,
3603
+ part.coverageRank,
3604
+ part.blossomRank,
3605
+ 1
3606
+ ];
3607
+ }
3608
+ // src/forest/impostor-material.ts
3609
+ /** Coverage (blended over the frames) from which an Impostor texel is drawn. */
3610
+ var ALPHA_CUT = .5;
3611
+ /** The smallest coverage values are divided by. */
3612
+ var MIN_COVERAGE = 1e-4;
3613
+ /** Column `i` of a mat4 node. */
3614
+ function column(matrix, i) {
3615
+ return matrix.element(i);
3616
+ }
3617
+ /** TSL twin of `octahedralEncode`. */
3618
+ function encode(d) {
3619
+ const y = max(d.y, 0);
3620
+ const s = abs(d.x).add(y).add(abs(d.z));
3621
+ const px = d.x.div(s);
3622
+ const pz = d.z.div(s);
3623
+ return vec2(px.add(pz).add(1), px.sub(pz).add(1)).mul(.5);
3624
+ }
3625
+ /** TSL twin of `octahedralDecode`. */
3626
+ function decode(uv) {
3627
+ const a = uv.x.mul(2).sub(1);
3628
+ const b = uv.y.mul(2).sub(1);
3629
+ const px = a.add(b).mul(.5);
3630
+ const pz = a.sub(b).mul(.5);
3631
+ return vec3(px, float(1).sub(abs(px)).sub(abs(pz)), pz).normalize();
3632
+ }
3633
+ /** TSL twin of `frameBasis` (right and up; forward is the input). */
3634
+ function basis(forward) {
3635
+ const reference = select(abs(forward.y).greaterThan(.999), vec3(0, 0, -1), vec3(0, 1, 0));
3636
+ const right = cross(reference, forward).normalize();
3569
3637
  return {
3570
- scale: state.x,
3571
- growth: state.y,
3572
- season: state.z,
3573
- windPhase: state.w
3638
+ right,
3639
+ up: cross(forward, right)
3574
3640
  };
3575
3641
  }
3576
- /** Rotates `v` by the instance quaternion (`inverse` = by its conjugate): tree space to forest space. */
3577
- function instanceRotate(v, inverse = false) {
3578
- const q = attribute("iRotation", "vec4");
3579
- const u = inverse ? q.xyz.negate() : q.xyz;
3580
- const t = cross(u, v).mul(2);
3581
- return v.add(t.mul(q.w)).add(cross(u, t));
3582
- }
3642
+ /** TSL twin of `frameUv`. */
3643
+ function frameUv(point, view, forward, half) {
3644
+ const t = dot(point, forward).div(max(dot(view, forward), .001));
3645
+ const hit = point.sub(view.mul(t));
3646
+ const { right, up } = basis(forward);
3647
+ return vec2(dot(hit, right), dot(hit, up)).div(2 * half).add(.5);
3648
+ }
3649
+ /** The (i, j) offsets of the four blended frames, in `blendFrames` order. */
3650
+ var OFFSETS = [
3651
+ [0, 0],
3652
+ [1, 0],
3653
+ [0, 1],
3654
+ [1, 1]
3655
+ ];
3583
3656
  /**
3584
- * The vertex position of a Forest tree (positionNode of an instanced Variant mesh).
3657
+ * Builds the card and the frame blend. In the vertex stage: the direction to the camera (or, for
3658
+ * an orthographic camera such as a sun's shadow camera, its forward axis) in tree space, the card
3659
+ * across it, the four nearest frames and where each pictured the card's vertex (`frameUv`). In the
3660
+ * fragment stage: the atlases sampled in those frames and blended bilinearly.
3585
3661
  *
3586
- * On an InstancedMesh, three.js applies the instance matrix to `positionLocal` before
3587
- * `positionNode` runs, but Growth and Wind are defined in the tree's own space (about the
3588
- * generated `aOrigin`s, relative to its trunk height). So both are computed from
3589
- * `positionGeometry`, and only their displacement is turned into forest space with the
3590
- * instance rotation and scale: M·(p + d) = M·p + R·s·d. The Wind direction goes the other way
3591
- * (forest -> tree space) and each tree sways with its own phase.
3662
+ * `sway`: a displacement (tree space) of a card point at its tree-space position (the Wind) at Wind
3663
+ * time `time` (default the Wind's clock); the pictures move with the card.
3664
+ */
3665
+ function impostorView(atlases, sway) {
3666
+ const { frames, bounds } = atlases;
3667
+ const { half } = bounds;
3668
+ const center = vec3(...bounds.center);
3669
+ const { scale } = instanceState();
3670
+ const base = levelTreePosition();
3671
+ const centerForest = base.add(instanceRotate(center).mul(scale));
3672
+ const eye = modelWorldMatrixInverse.mul(vec4(cameraPosition, 1)).xyz;
3673
+ const axis = modelWorldMatrixInverse.mul(vec4(column(cameraWorldMatrix, 2).xyz, 0)).xyz;
3674
+ const orthographic = column(cameraProjectionMatrix, 3).w.greaterThan(.5);
3675
+ const viewForest = select(orthographic, axis, eye.sub(centerForest)).normalize();
3676
+ const view = instanceRotate(viewForest, true).normalize();
3677
+ const card = basis(view);
3678
+ const point = card.right.mul(positionGeometry.x).add(card.up.mul(positionGeometry.y)).mul(half);
3679
+ const treePoint = center.add(point);
3680
+ const swayed = sway?.(treePoint);
3681
+ const position = base.add(instanceRotate(swayed ? treePoint.add(swayed) : treePoint).mul(scale));
3682
+ const swayForest = swayed ? instanceRotate(swayed).mul(scale) : null;
3683
+ const shadowPosition = position.sub(viewForest.mul(half).mul(scale));
3684
+ const g = encode(view).mul(frames).sub(.5).clamp(0, frames - 1);
3685
+ const cell = min(floor(g), Math.max(frames - 2, 0));
3686
+ const blendVarying = varying(vec4(cell, g.sub(cell)));
3687
+ const frameOf = (k) => min(blendVarying.xy.add(vec2(...OFFSETS[k])), frames - 1);
3688
+ const vertexFrame = (k) => min(cell.add(vec2(...OFFSETS[k])), frames - 1);
3689
+ const local = OFFSETS.map((_, k) => frameUv(point, view, decode(vertexFrame(k).add(.5).div(frames)), half));
3690
+ const locals = [varying(vec4(local[0], local[1])), varying(vec4(local[2], local[3]))];
3691
+ const fx = blendVarying.z;
3692
+ const fy = blendVarying.w;
3693
+ const weights = [
3694
+ float(1).sub(fx).mul(float(1).sub(fy)),
3695
+ fx.mul(float(1).sub(fy)),
3696
+ float(1).sub(fx).mul(fy),
3697
+ fx.mul(fy)
3698
+ ];
3699
+ const frameSamplers = OFFSETS.map((_, k) => {
3700
+ const uv = k % 2 === 0 ? locals[k >> 1].xy : locals[k >> 1].zw;
3701
+ const inside = and(uv.greaterThanEqual(vec2(0)).all(), uv.lessThanEqual(vec2(1)).all());
3702
+ const atlasUv = frameOf(k).add(uv.clamp(0, 1)).div(frames);
3703
+ const flipped = vec2(atlasUv.x, float(1).sub(atlasUv.y));
3704
+ const samples = /* @__PURE__ */ new Map();
3705
+ return { sample(channel) {
3706
+ let value = samples.get(channel);
3707
+ if (!value) {
3708
+ const atlas = atlases.textures[channel];
3709
+ if (!atlas) throw new Error(`No Impostor atlas "${channel}"`);
3710
+ value = select(inside, texture(atlas, flipped), vec4(0));
3711
+ samples.set(channel, value);
3712
+ }
3713
+ return value;
3714
+ } };
3715
+ });
3716
+ const blend = (perFrame) => frameSamplers.reduce((sum, frame, k) => sum.add(perFrame(frame).mul(weights[k])), vec4(0));
3717
+ const values = /* @__PURE__ */ new Map();
3718
+ const blended = (channel) => {
3719
+ let value = values.get(channel);
3720
+ if (!value) {
3721
+ value = blend((frame) => frame.sample(channel));
3722
+ values.set(channel, value);
3723
+ }
3724
+ return value;
3725
+ };
3726
+ const coverage = blended(COLOR_CHANNEL).a;
3727
+ return {
3728
+ position,
3729
+ sway: swayForest,
3730
+ shadowPosition,
3731
+ coverage,
3732
+ ...sway && swayed ? { windShift: (previous) => instanceRotate(sway(treePoint, previous).sub(swayed)).mul(scale) } : {},
3733
+ blend,
3734
+ value: (channel) => blended(channel).div(max(coverage, MIN_COVERAGE))
3735
+ };
3736
+ }
3737
+ /** The colour atlas: the MRT `output` (rgb = colour, a = coverage). */
3738
+ var COLOR_CHANNEL = "output";
3739
+ /** The normal atlas: rgb = tree-space normal (encoded 0..1), a = 1 on leaves, 0 on wood. */
3740
+ var NORMAL_CHANNEL = "normal";
3741
+ /** The Season atlas (`encodeSeasonTexel`): r = leaf timing shift, g = coverage rank, b = blossom rank, a = 1 on leaves. */
3742
+ var SEASON_CHANNEL = "season";
3743
+ /** The wood layer's colour atlas: the wood alone (rgb = colour, a = coverage), shown where leaves have dropped. */
3744
+ var WOOD_COLOR_CHANNEL = "woodOutput";
3745
+ /** The wood layer's normal atlas (as `NORMAL_CHANNEL`, a = 0). */
3746
+ var WOOD_NORMAL_CHANNEL = "woodNormal";
3747
+ /**
3748
+ * The Material Feature atlas (only baked when a Material Feature is on, ADR 0008): rgb = the pictured
3749
+ * point in tree space (Growth 1, encoded over the frame's box, see `featureTexel`), from which the card
3750
+ * measures the Crown Volume (Crown Normals, Leaf Translucency); a = the raw Structural Occlusion
3751
+ * (`aOcclusion`, 0 when that feature is off).
3752
+ */
3753
+ var FEATURES_CHANNEL = "features";
3754
+ /** The Material Feature atlas texel the bake writes for a tree-space `point` and raw `occlusion`. */
3755
+ function featureTexel(point, occlusion, bounds) {
3756
+ return vec4(point.sub(vec3(...bounds.center)).div(2 * bounds.half).add(.5), occlusion);
3757
+ }
3758
+ /** Inverse of `featureTexel` for the point (a texel already divided by the coverage). */
3759
+ function featurePoint(texel, bounds) {
3760
+ return texel.xyz.sub(.5).mul(2 * bounds.half).add(vec3(...bounds.center));
3761
+ }
3762
+ /** Whether any Material Feature is on (then the Impostor bakes and reads `FEATURES_CHANNEL`). */
3763
+ function hasImpostorFeatures(features) {
3764
+ const nodes = features?.nodes;
3765
+ return !!nodes && (nodes.crownNormals !== null || nodes.translucency !== null || nodes.occlusion !== null);
3766
+ }
3767
+ /**
3768
+ * The material of a Variant's Impostor cards: the Definition's shading (smooth: the baked normals
3769
+ * carry the shape), the baked colour with each leaf texel in the Season Profile at the tree's Season
3770
+ * plus the leaf's own timing shift (colour, blossom; a dropped leaf shows the wood layer behind it,
3771
+ * or nothing), the baked normal turned with the tree, bark or leaf roughness, cut out by the coverage
3772
+ * and the Detail Level cross-fade (in the shadow pass too, so the shadow is tree-shaped). With
3773
+ * `wind`, the card bends with height as the tree sways, in the tree's own Wind phase.
3774
+ */
3775
+ function createImpostorMaterial(definition, atlases, features = null, wind) {
3776
+ const burst = wind && instanceBurstFrame();
3777
+ const view = impostorView(atlases, wind ? (point, time) => treeSwayOffset(wind.source, wind.response, point, {
3778
+ direction: instanceRotate(objectWindDirection(wind.source), true),
3779
+ phase: instanceState().windPhase,
3780
+ time,
3781
+ burst
3782
+ }) : void 0);
3783
+ const material = createShadedMaterial(definition.materials.shading);
3784
+ material.name = "tree.js impostor";
3785
+ material.flatShading = false;
3786
+ material.side = DoubleSide;
3787
+ material.positionNode = view.position;
3788
+ if (wind && view.windShift) setWindMotion(view.position, {
3789
+ source: wind.source,
3790
+ shift: view.windShift
3791
+ });
3792
+ material.castShadowPositionNode = view.shadowPosition;
3793
+ const treeSeason = varying(instanceState().season);
3794
+ const leafSeason = leafSeasonNode(definition.season);
3795
+ const maxShift = definition.variation.season;
3796
+ const frameStates = /* @__PURE__ */ new Map();
3797
+ const frameState = (frame) => {
3798
+ let state = frameStates.get(frame);
3799
+ if (!state) {
3800
+ const texel = frame.sample(COLOR_CHANNEL);
3801
+ const normal = frame.sample(NORMAL_CHANNEL);
3802
+ const flag = normal.a.div(max(texel.a, MIN_COVERAGE)).clamp(0, 1);
3803
+ const season = frame.sample(SEASON_CHANNEL);
3804
+ const leaves = max(season.a, MIN_COVERAGE);
3805
+ const shift = season.r.div(leaves).sub(.5).div(SEASON_SHIFT_SCALE).clamp(-maxShift, maxShift);
3806
+ const part = vec3(shift, season.g.div(leaves).clamp(0, 1), season.b.div(leaves).clamp(0, 1));
3807
+ const leaf = leafSeason(treeSeason, part);
3808
+ const dropped = flag.mul(select(leaf.shown, float(0), float(1))).toVar();
3809
+ const shown = vec4(texel.rgb.mul(mix(vec3(1), leaf.color, flag)), texel.a);
3810
+ state = {
3811
+ color: mix(shown, frame.sample(WOOD_COLOR_CHANNEL), dropped),
3812
+ normal: mix(normal, frame.sample(WOOD_NORMAL_CHANNEL), dropped)
3813
+ };
3814
+ frameStates.set(frame, state);
3815
+ }
3816
+ return state;
3817
+ };
3818
+ const color = view.blend((frame) => frameState(frame).color);
3819
+ const normal = view.blend((frame) => frameState(frame).normal);
3820
+ const coverage = color.a;
3821
+ const covered = max(coverage, MIN_COVERAGE);
3822
+ material.colorNode = color.rgb.div(covered);
3823
+ const leaf = normal.a.div(covered).clamp(0, 1);
3824
+ const treeNormal = normal.rgb.div(covered).mul(2).sub(1).normalize();
3825
+ material.normalNode = transformNormalToView(instanceRotate(treeNormal)).normalize();
3826
+ material.roughnessNode = mix(float(definition.materials.bark.roughness), float(definition.materials.leaf.roughness), leaf);
3827
+ material.metalness = 0;
3828
+ material.maskNode = and(coverage.greaterThan(ALPHA_CUT), levelVisible());
3829
+ if (hasImpostorFeatures(features)) applyImpostorFeatures(material, view, atlases.bounds, leaf, features);
3830
+ material.userData.treePart = "leaves";
3831
+ setTreeLeafMask(material, leaf);
3832
+ hookTargets.set(material, {
3833
+ material,
3834
+ parts: ["bark", "leaves"],
3835
+ partWeight: (part) => part === "leaves" ? leaf : float(1).sub(leaf),
3836
+ vertexColors: false,
3837
+ season: treeSeason,
3838
+ growth: varying(instanceState().growth),
3839
+ treePosition: varying(modelWorldMatrix.mul(vec4(levelTreePosition(), 1)).xyz),
3840
+ sway: view.sway
3841
+ });
3842
+ return material;
3843
+ }
3844
+ var hookTargets = /* @__PURE__ */ new WeakMap();
3845
+ /**
3846
+ * What Tree Shader Hooks shade on an Impostor card (ADR 0012): its baked colour, leaf flag and normal at
3847
+ * draw time, so hooks follow live settings without a rebake.
3848
+ */
3849
+ function impostorHookTarget(material) {
3850
+ const target = hookTargets.get(material);
3851
+ if (!target) throw new Error("Not an Impostor material");
3852
+ return target;
3853
+ }
3854
+ /**
3855
+ * Material Features on an Impostor card, as on the tree's own materials (same uniforms, so live tuning
3856
+ * needs no rebake): the Crown Volume is measured at the point each texel pictured. Crown Normals and
3857
+ * Leaf Translucency act on leaf texels only (by the baked leaf flag); Structural Occlusion on all.
3858
+ */
3859
+ function applyImpostorFeatures(material, view, bounds, leaf, features) {
3860
+ const { nodes } = features;
3861
+ const texel = view.value(FEATURES_CHANNEL);
3862
+ const crown = crownAt(features.crown, featurePoint(texel, bounds));
3863
+ if (nodes.crownNormals) {
3864
+ const own = material.normalNode;
3865
+ const crownView = transformNormalToView(instanceRotate(crown.normal)).normalize();
3866
+ const blend = mix(own, crownView, nodes.crownNormals.mul(leaf));
3867
+ material.normalNode = select(blend.length().greaterThan(1e-4), blend.normalize(), crownView);
3868
+ }
3869
+ if (nodes.translucency) {
3870
+ const { strength, edge, ambient } = nodes.translucency;
3871
+ applyLeafTranslucencyTerm(material, {
3872
+ strength: strength.mul(leaf),
3873
+ ambient: ambient.mul(leaf),
3874
+ edge,
3875
+ thinness: crown.distance.clamp(0, 1)
3876
+ });
3877
+ }
3878
+ if (nodes.occlusion) material.aoNode = mix(float(1), texel.w, nodes.occlusion);
3879
+ }
3880
+ // src/forest/octahedral.ts
3881
+ /** Below this |y|, a frame's up is world up; above it (seen from straight above) the frame's up is -z. */
3882
+ var POLE = .999;
3883
+ var vec = (x, y, z) => [
3884
+ x + 0,
3885
+ y + 0,
3886
+ z + 0
3887
+ ];
3888
+ function normalize$1(v) {
3889
+ const l = Math.hypot(v[0], v[1], v[2]);
3890
+ return vec(v[0] / l, v[1] / l, v[2] / l);
3891
+ }
3892
+ function cross$1(a, b) {
3893
+ return vec(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]);
3894
+ }
3895
+ /** The unit direction at a point of the unit square (inverse of `octahedralEncode`). */
3896
+ function octahedralDecode(u, v) {
3897
+ const a = u * 2 - 1;
3898
+ const b = v * 2 - 1;
3899
+ const px = (a + b) / 2;
3900
+ const pz = (a - b) / 2;
3901
+ return normalize$1([
3902
+ px,
3903
+ 1 - Math.abs(px) - Math.abs(pz),
3904
+ pz
3905
+ ]);
3906
+ }
3907
+ /** The direction frame (i, j) pictures the tree from. */
3908
+ function frameDirection(i, j, frames) {
3909
+ return octahedralDecode((i + .5) / frames, (j + .5) / frames);
3910
+ }
3911
+ /** The camera basis of a frame looking at the tree from `forward`. */
3912
+ function frameBasis(forward) {
3913
+ const right = normalize$1(cross$1(Math.abs(forward[1]) > POLE ? [
3914
+ 0,
3915
+ 0,
3916
+ -1
3917
+ ] : [
3918
+ 0,
3919
+ 1,
3920
+ 0
3921
+ ], forward));
3922
+ return {
3923
+ right,
3924
+ up: cross$1(forward, right),
3925
+ forward: vec(...forward)
3926
+ };
3927
+ }
3928
+ // src/forest/impostor.ts
3929
+ /** Room around the tree's bounding sphere in each frame, so mipmaps do not bleed in from the next frame. */
3930
+ var FRAME_MARGIN = 1.04;
3931
+ /** Leaves are two-sided: the normal of the side the frame sees, encoded 0..1. */
3932
+ var bakedNormal = () => select(frontFacing, normalGeometry, normalGeometry.negate()).normalize().mul(.5).add(.5);
3933
+ /**
3934
+ * The channels of the tree layer every Impostor bakes: colour (rgb, coverage in a), the tree-space
3935
+ * normal (a = leaf flag), the leaves' Season timing (`encodeSeasonTexel`: shift, coverage rank,
3936
+ * blossom rank, leaf flag; empty on wood), plus, only when a Material Feature is on, the features
3937
+ * atlas (`FEATURES_CHANNEL`: the pictured point and the raw Structural Occlusion).
3592
3938
  *
3593
- * `base`: the tree-space position Growth starts from (default `positionGeometry`); Fruit passes
3594
- * its Season-scaled position here.
3939
+ * Each channel is one RGBA8 attachment of a single render pass: WebGPU's default limit
3940
+ * (`maxColorAttachmentBytesPerSample` 32, 8 per RGBA8) allows 4, which these use up. More inputs need
3941
+ * another layer (as the wood layer, `impostorWoodChannels`).
3942
+ */
3943
+ function impostorChannels(bounds, features = null) {
3944
+ const channels = [
3945
+ {
3946
+ name: COLOR_CHANNEL,
3947
+ bake: () => output
3948
+ },
3949
+ {
3950
+ name: NORMAL_CHANNEL,
3951
+ bake: (part) => vec4(bakedNormal(), float(part.kind === "leaves" ? 1 : 0))
3952
+ },
3953
+ {
3954
+ name: SEASON_CHANNEL,
3955
+ bake: (part) => {
3956
+ if (part.kind === "wood") return vec4(...encodeSeasonTexel(null));
3957
+ const aSeason = attribute("aSeason", "vec3");
3958
+ return vec4(aSeason.x.mul(SEASON_SHIFT_SCALE).add(.5), aSeason.y, aSeason.z, 1);
3959
+ }
3960
+ }
3961
+ ];
3962
+ if (hasImpostorFeatures(features)) {
3963
+ const occlusion = features.nodes.occlusion ? attribute("aOcclusion", "float") : float(0);
3964
+ channels.push({
3965
+ name: FEATURES_CHANNEL,
3966
+ bake: () => featureTexel(positionGeometry, occlusion, bounds)
3967
+ });
3968
+ }
3969
+ return channels;
3970
+ }
3971
+ /**
3972
+ * The channels of the wood layer: the wood alone (colour with coverage, normal), so an Impostor shows
3973
+ * bare branches where its leaves have dropped instead of holes.
3974
+ */
3975
+ function impostorWoodChannels() {
3976
+ return [{
3977
+ name: WOOD_COLOR_CHANNEL,
3978
+ bake: () => output
3979
+ }, {
3980
+ name: WOOD_NORMAL_CHANNEL,
3981
+ bake: () => vec4(bakedNormal(), 0)
3982
+ }];
3983
+ }
3984
+ /** The tree's centre and the half size of a frame, from its wood and leaves (Fruit is not on Impostors). */
3985
+ function impostorBounds(parts) {
3986
+ const min = [
3987
+ Infinity,
3988
+ Infinity,
3989
+ Infinity
3990
+ ];
3991
+ const max = [
3992
+ -Infinity,
3993
+ -Infinity,
3994
+ -Infinity
3995
+ ];
3996
+ for (const { positions } of parts) for (let i = 0; i < positions.length; i += 3) for (let c = 0; c < 3; c++) {
3997
+ min[c] = Math.min(min[c], positions[i + c]);
3998
+ max[c] = Math.max(max[c], positions[i + c]);
3999
+ }
4000
+ if (min[0] === Infinity) return {
4001
+ center: [
4002
+ 0,
4003
+ 0,
4004
+ 0
4005
+ ],
4006
+ half: 1
4007
+ };
4008
+ const center = [
4009
+ 0,
4010
+ 1,
4011
+ 2
4012
+ ].map((c) => (min[c] + max[c]) / 2);
4013
+ let radius = 0;
4014
+ for (const { positions } of parts) for (let i = 0; i < positions.length; i += 3) radius = Math.max(radius, Math.hypot(positions[i] - center[0], positions[i + 1] - center[1], positions[i + 2] - center[2]));
4015
+ return {
4016
+ center,
4017
+ half: Math.max(radius, .001) * FRAME_MARGIN
4018
+ };
4019
+ }
4020
+ /**
4021
+ * Where the bake draws the tree for frame (i, j): seen from the frame's direction (its basis turned
4022
+ * to the camera's axes), scaled so the frame spans 2·half, moved into its cell of the atlas. The bake
4023
+ * camera is orthographic over the atlas (0..1 in x and y), so one draw renders every frame.
3595
4024
  */
3596
- function forestPosition(wind, response, base = positionGeometry) {
3597
- const { scale, growth, windPhase } = instanceState();
3598
- const grown = growthPosition(growth, base);
3599
- const offset = windOffset(wind, response, {
3600
- direction: instanceRotate(objectWindDirection(wind), true),
3601
- phase: windPhase
4025
+ function frameTransform(i, j, frames, bounds) {
4026
+ const { right, up, forward } = frameBasis(frameDirection(i, j, frames));
4027
+ const s = 1 / (2 * bounds.half);
4028
+ const [cx, cy, cz] = bounds.center;
4029
+ const rows = [
4030
+ right,
4031
+ up,
4032
+ forward
4033
+ ].map(([x, y, z]) => [
4034
+ x * s,
4035
+ y * s,
4036
+ z * s,
4037
+ -(x * cx + y * cy + z * cz) * s
4038
+ ]);
4039
+ return new Matrix4().set(rows[0][0] / frames, rows[0][1] / frames, rows[0][2] / frames, (rows[0][3] + .5 + i) / frames, rows[1][0] / frames, rows[1][1] / frames, rows[1][2] / frames, (rows[1][3] + .5 + j) / frames, rows[2][0], rows[2][1], rows[2][2], rows[2][3], 0, 0, 0, 1);
4040
+ }
4041
+ /** The unlit bake materials of the wood and the leaves (Growth 1, no Wind, no Season mask). */
4042
+ function bakeMaterials(definition, textures) {
4043
+ const bark = createBarkMaterial(definition, textures, float(1));
4044
+ const wood = new MeshBasicNodeMaterial();
4045
+ wood.name = "tree.js impostor bake wood";
4046
+ wood.colorNode = bark.colorNode;
4047
+ bark.dispose();
4048
+ const leaf = createLeafMaterial(definition, textures);
4049
+ const leaves = new MeshBasicNodeMaterial();
4050
+ leaves.name = "tree.js impostor bake leaves";
4051
+ leaves.vertexColors = true;
4052
+ leaves.side = DoubleSide;
4053
+ if (leaf.map) {
4054
+ const card = texture(leaf.map, uv());
4055
+ leaves.colorNode = vec4(card.rgb, 1);
4056
+ leaves.maskNode = card.a.greaterThanEqual(leaf.alphaTest);
4057
+ }
4058
+ leaf.dispose();
4059
+ return {
4060
+ wood,
4061
+ leaves
4062
+ };
4063
+ }
4064
+ /** Rows of the card: the Wind bends it with height, so it needs more than one row of quads. */
4065
+ var CARD_ROWS = 4;
4066
+ /** The card: a square from (−1, −1) to (1, 1) in x and y, in `CARD_ROWS` rows. */
4067
+ function cardGeometry() {
4068
+ const positions = [];
4069
+ const uvs = [];
4070
+ const index = [];
4071
+ for (let row = 0; row <= CARD_ROWS; row++) {
4072
+ const v = row / CARD_ROWS;
4073
+ positions.push(-1, v * 2 - 1, 0, 1, v * 2 - 1, 0);
4074
+ uvs.push(0, v, 1, v);
4075
+ if (row < CARD_ROWS) {
4076
+ const a = row * 2;
4077
+ index.push(a, a + 1, a + 3, a, a + 3, a + 2);
4078
+ }
4079
+ }
4080
+ const geometry = new BufferGeometry();
4081
+ geometry.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));
4082
+ geometry.setAttribute("normal", new BufferAttribute(new Float32Array(positions.length).map((_, i) => i % 3 === 2 ? 1 : 0), 3));
4083
+ geometry.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2));
4084
+ geometry.setIndex(index);
4085
+ return geometry;
4086
+ }
4087
+ /** A render target for one layer's atlases (one texture per channel, named after it). */
4088
+ function layerTarget(size, channels) {
4089
+ const target = new RenderTarget(size, size, {
4090
+ count: channels.length,
4091
+ type: UnsignedByteType,
4092
+ depthBuffer: true,
4093
+ generateMipmaps: true,
4094
+ minFilter: LinearMipmapLinearFilter,
4095
+ magFilter: LinearFilter
3602
4096
  });
3603
- const displacement = grown.add(offset).sub(positionGeometry);
3604
- return positionLocal.add(instanceRotate(displacement).mul(scale));
4097
+ channels.forEach((channel, i) => target.textures[i].name = channel.name);
4098
+ return target;
3605
4099
  }
4100
+ /**
4101
+ * The Impostor of one Variant: the atlases (allocated at once, filled by `bake`), the card material
4102
+ * that samples them, and the card geometry. `part` is what the Variant's Impostor Detail Level draws.
4103
+ *
4104
+ * Two layers are baked: the tree (wood and leaves, with the leaves' Season timing) and the wood
4105
+ * alone, which shows where leaves have dropped.
4106
+ */
4107
+ var VariantImpostor = class {
4108
+ frames;
4109
+ bounds;
4110
+ /** The channels of every layer (one atlas each). */
4111
+ channels;
4112
+ /** The Impostor level's single mesh: a card per tree. */
4113
+ part;
4114
+ definition;
4115
+ sources;
4116
+ textures;
4117
+ layers;
4118
+ baked = false;
4119
+ constructor({ definition, sources, bounds, atlas, name, textures, features = null, wind }) {
4120
+ this.definition = definition;
4121
+ this.sources = sources;
4122
+ this.textures = textures;
4123
+ this.frames = atlas.frames;
4124
+ this.bounds = bounds;
4125
+ const layer = (kinds, channels) => ({
4126
+ kinds,
4127
+ channels,
4128
+ target: layerTarget(atlas.size, channels)
4129
+ });
4130
+ this.layers = [layer(["wood", "leaves"], impostorChannels(this.bounds, features)), layer(["wood"], impostorWoodChannels())];
4131
+ this.channels = this.layers.flatMap((l) => l.channels);
4132
+ this.part = {
4133
+ name,
4134
+ geometry: cardGeometry(),
4135
+ material: createImpostorMaterial(definition, this.atlases, features, wind)
4136
+ };
4137
+ }
4138
+ /** The atlases by channel name. */
4139
+ get atlases() {
4140
+ const textures = {};
4141
+ for (const { channels, target } of this.layers) channels.forEach((channel, i) => textures[channel.name] = target.textures[i]);
4142
+ return {
4143
+ frames: this.frames,
4144
+ bounds: this.bounds,
4145
+ textures
4146
+ };
4147
+ }
4148
+ /** Whether `bake` has run. */
4149
+ get isBaked() {
4150
+ return this.baked;
4151
+ }
4152
+ /**
4153
+ * Renders every frame into the atlases with the app's renderer, one pass per layer, then restores
4154
+ * the renderer as it was. Deterministic: the same Definition and Variant Seed give the same atlases.
4155
+ */
4156
+ bake(renderer) {
4157
+ const frames = this.frames;
4158
+ const materials = [];
4159
+ const meshes = [];
4160
+ const scenes = this.layers.map(({ kinds, channels }) => {
4161
+ const layerMaterials = bakeMaterials(this.definition, this.textures);
4162
+ materials.push(layerMaterials.wood, layerMaterials.leaves);
4163
+ const scene = new Scene();
4164
+ for (const kind of kinds) {
4165
+ const source = this.sources[kind];
4166
+ if ((source.getIndex()?.count ?? 0) === 0) continue;
4167
+ const material = layerMaterials[kind];
4168
+ const part = {
4169
+ kind,
4170
+ geometry: source,
4171
+ material
4172
+ };
4173
+ material.mrtNode = mrt(Object.fromEntries(channels.map((c) => [c.name, c.bake(part)])));
4174
+ const geometry = new BufferGeometry();
4175
+ for (const [name, attribute] of Object.entries(source.attributes)) geometry.setAttribute(name, attribute);
4176
+ geometry.setIndex(source.getIndex());
4177
+ const mesh = new InstancedMesh(geometry, material, frames * frames);
4178
+ for (let j = 0; j < frames; j++) for (let i = 0; i < frames; i++) mesh.setMatrixAt(j * frames + i, frameTransform(i, j, frames, this.bounds));
4179
+ mesh.frustumCulled = false;
4180
+ scene.add(mesh);
4181
+ meshes.push(mesh);
4182
+ }
4183
+ return scene;
4184
+ });
4185
+ const camera = new OrthographicCamera(0, 1, 1, 0, 0, 2);
4186
+ camera.position.set(0, 0, 1);
4187
+ camera.updateMatrixWorld();
4188
+ const state = RendererUtils.resetRendererState(renderer, {});
4189
+ try {
4190
+ renderer.setClearColor(0, 0);
4191
+ this.layers.forEach(({ target }, i) => {
4192
+ renderer.setRenderTarget(target);
4193
+ renderer.render(scenes[i], camera);
4194
+ });
4195
+ } finally {
4196
+ RendererUtils.restoreRendererState(renderer, state);
4197
+ for (const mesh of meshes) mesh.dispose();
4198
+ for (const material of materials) material.dispose();
4199
+ }
4200
+ this.baked = true;
4201
+ }
4202
+ /** Frees the atlases, the card geometry and its material (the level mesh's geometry belongs to the levels). */
4203
+ dispose() {
4204
+ for (const { target } of this.layers) target.dispose();
4205
+ this.part.geometry.dispose();
4206
+ this.part.material.dispose();
4207
+ }
4208
+ };
4209
+ // src/forest/lod.ts
4210
+ /** A Forest tree's Detail Level (GLOSSARY): Full (as without Detail Levels), Light (fewer faces and leaves) or Impostor (one card). */
4211
+ var DetailLevel = {
4212
+ Full: 0,
4213
+ Light: 1,
4214
+ Impostor: 2
4215
+ };
4216
+ var DEFAULT_IMPOSTOR_ATLAS = {
4217
+ frames: 12,
4218
+ size: 2048
4219
+ };
4220
+ /** Smallest placement scale the selection divides by (a scale of 0 must not divide by zero). */
4221
+ var MIN_LOD_SCALE = 1e-6;
4222
+ /** 0 below `start`, 1 from `end`, linear in between (a band of width 0 is a hard step at `end`). */
4223
+ function ramp$1(x, start, end) {
4224
+ if (end <= start) return x >= end ? 1 : 0;
4225
+ return Math.min(Math.max((x - start) / (end - start), 0), 1);
4226
+ }
4227
+ /**
4228
+ * Picks a Forest tree's Detail Level. The single source of truth for level selection: the GPU
4229
+ * compute pass mirrors it line by line.
4230
+ *
4231
+ * - `t = distance / max(scale, 1e-6)`: a tree at placement scale 2 switches at twice the distance.
4232
+ * - Each switch distance `d` (`light`, `impostor`) has a cross-fade band from `d·(1 − fade/2)` to
4233
+ * `d·(1 + fade/2)`; inside it the tree fades linearly from the nearer level to the next one.
4234
+ * - A tree whose drawn Growth is below 1 is never an Impostor: it is capped at Light.
4235
+ * - The Impostor switch is checked first, so if the two bands overlap the farther one wins.
4236
+ *
4237
+ * @param distance distance from the camera that picks the levels to the tree's base, world units
4238
+ * @param scale the tree's placement scale
4239
+ * @param growth the tree's drawn Growth (after its Growth delay)
4240
+ */
4241
+ function selectDetailLevel(distance, scale, growth, settings) {
4242
+ const t = distance / Math.max(scale, MIN_LOD_SCALE);
4243
+ const half = settings.fade / 2;
4244
+ if (growth >= 1) {
4245
+ const toImpostor = ramp$1(t, settings.impostor * (1 - half), settings.impostor * (1 + half));
4246
+ if (toImpostor >= 1) return {
4247
+ level: DetailLevel.Impostor,
4248
+ fade: 0
4249
+ };
4250
+ if (toImpostor > 0) return {
4251
+ level: DetailLevel.Light,
4252
+ fade: toImpostor
4253
+ };
4254
+ }
4255
+ const toLight = ramp$1(t, settings.light * (1 - half), settings.light * (1 + half));
4256
+ if (toLight >= 1) return {
4257
+ level: DetailLevel.Light,
4258
+ fade: 0
4259
+ };
4260
+ return {
4261
+ level: DetailLevel.Full,
4262
+ fade: toLight
4263
+ };
4264
+ }
4265
+ function checkDistance(name, value) {
4266
+ if (!Number.isFinite(value) || value < 0) throw new RangeError(`Forest lod.${name} must be a finite distance >= 0, got ${value}`);
4267
+ }
4268
+ /** Throws a RangeError unless the distances and fade are valid. */
4269
+ function checkDetailLevelDistances({ light, impostor, fade }) {
4270
+ checkDistance("light", light);
4271
+ checkDistance("impostor", impostor);
4272
+ if (impostor < light) throw new RangeError(`Forest lod.impostor (${impostor}) must be at least lod.light (${light})`);
4273
+ if (!(fade >= 0 && fade <= 1)) throw new RangeError(`Forest lod.fade must be within 0..1, got ${fade}`);
4274
+ }
4275
+ function checkAtlas(name, value) {
4276
+ if (!Number.isInteger(value) || value < 1) throw new RangeError(`Forest lod.impostorAtlas.${name} must be an integer >= 1, got ${value}`);
4277
+ }
4278
+ /** The switch distances of `lod: true`, from the tallest Variant's trunk height. */
4279
+ function defaultDetailLevelDistances(trunkHeight) {
4280
+ return {
4281
+ light: trunkHeight * 6,
4282
+ impostor: trunkHeight * 20
4283
+ };
4284
+ }
4285
+ /**
4286
+ * The settings of `ForestOptions.lod` with every default filled in, or null when it is missing or
4287
+ * false. `trunkHeight` (the tallest Variant's) gives the distances of `lod: true`. Throws a RangeError
4288
+ * for invalid settings.
4289
+ */
4290
+ function resolveForestLod(lod, trunkHeight) {
4291
+ if (lod === void 0 || lod === false) return null;
4292
+ const options = lod === true ? defaultDetailLevelDistances(trunkHeight) : lod;
4293
+ const settings = {
4294
+ light: options.light,
4295
+ impostor: options.impostor,
4296
+ fade: options.fade ?? .1,
4297
+ impostorAtlas: {
4298
+ ...DEFAULT_IMPOSTOR_ATLAS,
4299
+ ...options.impostorAtlas
4300
+ },
4301
+ lightDefinition: options.lightDefinition ?? null,
4302
+ camera: options.camera ?? null
4303
+ };
4304
+ checkDetailLevelDistances(settings);
4305
+ checkAtlas("frames", settings.impostorAtlas.frames);
4306
+ checkAtlas("size", settings.impostorAtlas.size);
4307
+ return settings;
4308
+ }
4309
+ /** u32s per indexed indirect draw: indexCount, instanceCount, firstIndex, baseVertex, firstInstance. */
4310
+ var ARGS_STRIDE = 5;
4311
+ /** vec4s per tree in the GPU tree data: rotation, state (as the instance data), position. */
4312
+ var TREE_VEC4S = 3;
4313
+ /** The 8 × 8 Bayer threshold of this fragment (twin of `ditherThreshold`). */
4314
+ function ditherThresholdNode() {
4315
+ const x = uint(screenCoordinate.x).bitAnd(7);
4316
+ const y = uint(screenCoordinate.y).bitAnd(7);
4317
+ const v = x.bitXor(y);
4318
+ const rank = v.bitAnd(1).shiftLeft(5).bitOr(y.bitAnd(1).shiftLeft(4)).bitOr(v.bitAnd(2).shiftLeft(2)).bitOr(y.bitAnd(2).shiftLeft(1)).bitOr(v.bitAnd(4).shiftRight(1)).bitOr(y.bitAnd(4).shiftRight(2));
4319
+ return float(rank).add(.5).div(64);
4320
+ }
4321
+ /** 0 below `start`, 1 from `end`, linear in between (twin of `ramp` in lod.ts). */
4322
+ function ramp(x, start, end) {
4323
+ const step = select(x.greaterThanEqual(end), float(1), float(0));
4324
+ return select(end.lessThanEqual(start), step, x.sub(start).div(end.sub(start)).clamp(0, 1));
4325
+ }
4326
+ /**
4327
+ * The GPU side of one Variant's Detail Levels: the tree data by slot, one list of tree slots per
4328
+ * level (with each entry's cross-fade), the indirect draw arguments, the compute pass that fills
4329
+ * them, and the meshes of every level (they draw indirectly and read their trees by slot).
4330
+ *
4331
+ * - `setLevel(level, parts)` gives a level its meshes (Full and Light now; an Impostor card later).
4332
+ * - `write(slot, …)` / `count` mirror the Variant's instance data; `resize(capacity)` keeps them.
4333
+ * - `dispatches` run once per frame for the camera that picks the levels, before any of the meshes is drawn.
4334
+ */
4335
+ var VariantLevels = class {
4336
+ uniforms;
4337
+ setupMesh;
4338
+ /** Every level's meshes, nearest level first. */
4339
+ levels = [];
4340
+ capacityValue;
4341
+ treeData;
4342
+ lists;
4343
+ dithers;
4344
+ counters = new StorageBufferAttribute(/* @__PURE__ */ new Uint32Array(3), 1);
4345
+ args = new IndirectStorageBufferAttribute(/* @__PURE__ */ new Uint32Array(45), 1);
4346
+ treeNode;
4347
+ listNode;
4348
+ ditherNode;
4349
+ countNode = uniform(0, "uint");
4350
+ levelOf = /* @__PURE__ */ new WeakMap();
4351
+ computeNodes;
4352
+ /** Bumped whenever the trees change (data, count, capacity): the levels must be selected again. */
4353
+ version = 0;
4354
+ /** What the meshes read per tree (see `drawsDetailLevel`). */
4355
+ instance;
4356
+ constructor(capacity, uniforms, setupMesh) {
4357
+ this.uniforms = uniforms;
4358
+ this.setupMesh = setupMesh;
4359
+ this.capacityValue = capacity;
4360
+ this.treeData = new StorageBufferAttribute(new Float32Array(capacity * TREE_VEC4S * 4), 4);
4361
+ this.lists = new StorageBufferAttribute(new Uint32Array(3 * capacity), 1);
4362
+ this.dithers = new StorageBufferAttribute(new Float32Array(3 * capacity), 1);
4363
+ this.treeNode = storage(this.treeData, "vec4", capacity * TREE_VEC4S).toReadOnly();
4364
+ this.listNode = storage(this.lists, "uint", 3 * capacity).toReadOnly();
4365
+ this.ditherNode = storage(this.dithers, "float", 3 * capacity).toReadOnly();
4366
+ const base = uniform(0, "uint").onObjectUpdate(({ object }) => (this.levelOf.get(object) ?? 0) * this.capacityValue);
4367
+ const entry = varying(base.add(instanceIndex));
4368
+ const slot = this.listNode.element(entry);
4369
+ const tree = (k) => this.treeNode.element(slot.mul(TREE_VEC4S).add(k));
4370
+ const dither = this.ditherNode.element(entry);
4371
+ const threshold = ditherThresholdNode();
4372
+ this.instance = {
4373
+ slot,
4374
+ rotation: tree(0),
4375
+ state: tree(1),
4376
+ position: tree(2).xyz,
4377
+ visible: select(dither.greaterThanEqual(0), threshold.lessThan(dither), threshold.greaterThanEqual(dither.negate()))
4378
+ };
4379
+ this.computeNodes = this.createDispatches();
4380
+ }
4381
+ get capacity() {
4382
+ return this.capacityValue;
4383
+ }
4384
+ /** Number of trees (slots 0..count-1 are in use). */
4385
+ get count() {
4386
+ return this.countNode.value;
4387
+ }
4388
+ set count(value) {
4389
+ this.countNode.value = value;
4390
+ this.version++;
4391
+ }
4392
+ /** The compute dispatches to run once per frame (reset, select, draw arguments). */
4393
+ get dispatches() {
4394
+ return this.computeNodes;
4395
+ }
4396
+ /** Every mesh of every level. */
4397
+ get meshes() {
4398
+ return this.levels.flatMap((l) => l.meshes);
4399
+ }
4400
+ /**
4401
+ * The GPU buffers in use: the tree data by slot (`TREE_VEC4S` vec4 per slot), the level lists and
4402
+ * their cross-fades (`LEVEL_COUNT` × capacity), the level counters and the draw arguments. The first
4403
+ * three are replaced when the Variant grows; the counters and the draw arguments are kept.
4404
+ */
4405
+ get buffers() {
4406
+ return {
4407
+ trees: this.treeData,
4408
+ lists: this.lists,
4409
+ dithers: this.dithers,
4410
+ counters: this.counters,
4411
+ args: this.args
4412
+ };
4413
+ }
4414
+ /** The indirect draw arguments, LEVEL_COUNT × MAX_LEVEL_PARTS draws of 5 u32 (for read-back). */
4415
+ get drawArguments() {
4416
+ return this.args;
4417
+ }
4418
+ /**
4419
+ * How many trees each Detail Level drew in the last selection (indexed by DetailLevel; a tree in a
4420
+ * cross-fade counts at both levels), read back from the draw arguments on the GPU.
4421
+ */
4422
+ async drawnCounts(renderer) {
4423
+ const args = new Uint32Array(await renderer.getArrayBufferAsync(this.args));
4424
+ return Array.from({ length: 3 }, (_, level) => args[level * 3 * ARGS_STRIDE + 1]);
4425
+ }
4426
+ /**
4427
+ * Gives `level` its meshes (at most MAX_LEVEL_PARTS parts), one per part, each drawn
4428
+ * indirectly from the level's list. A part without indices (e.g. the leaves of a bare
4429
+ * Definition) gets no mesh: WebGPU would draw it with an index count of 0. Returns the meshes;
4430
+ * the caller adds them to the scene.
4431
+ */
4432
+ setLevel(level, parts) {
4433
+ if (parts.length > 3) throw new RangeError(`A Detail Level has at most 3 meshes`);
4434
+ if (this.levels.some((l) => l.level === level)) throw new Error(`Detail Level ${level} already has its meshes`);
4435
+ const array = this.args.array;
4436
+ const meshes = parts.filter((part) => (part.geometry.getIndex()?.count ?? 0) > 0).map((part, i) => {
4437
+ const draw = (level * 3 + i) * ARGS_STRIDE;
4438
+ const geometry = new BufferGeometry();
4439
+ for (const [name, attribute] of Object.entries(part.geometry.attributes)) geometry.setAttribute(name, attribute);
4440
+ geometry.setIndex(part.geometry.getIndex());
4441
+ array[draw] = geometry.getIndex().count;
4442
+ geometry.setIndirect(this.args, draw * 4);
4443
+ const mesh = new Mesh(geometry, part.material);
4444
+ mesh.name = part.name;
4445
+ mesh.frustumCulled = false;
4446
+ mesh.castShadow = true;
4447
+ mesh.receiveShadow = true;
4448
+ mesh.raycast = () => {};
4449
+ this.levelOf.set(mesh, level);
4450
+ drawsDetailLevel(mesh, this.instance);
4451
+ this.setupMesh(mesh);
4452
+ return mesh;
4453
+ });
4454
+ this.args.needsUpdate = true;
4455
+ this.levels.push({
4456
+ level,
4457
+ meshes
4458
+ });
4459
+ this.levels.sort((a, b) => a.level - b.level);
4460
+ return meshes;
4461
+ }
4462
+ /**
4463
+ * Writes one tree: `instance` = its INSTANCE_STRIDE floats of instance data (rotation, state),
4464
+ * `position` = its base in forest space.
4465
+ */
4466
+ write(slot, instance, position) {
4467
+ const array = this.treeData.array;
4468
+ const o = slot * TREE_VEC4S * 4;
4469
+ for (let i = 0; i < 8; i++) array[o + i] = instance[i];
4470
+ array[o + 8] = position[0];
4471
+ array[o + 9] = position[1];
4472
+ array[o + 10] = position[2];
4473
+ array[o + 11] = 0;
4474
+ this.treeData.needsUpdate = true;
4475
+ this.version++;
4476
+ }
4477
+ /** Room for `capacity` trees (the tree data is kept; the lists are refilled every frame). */
4478
+ resize(capacity) {
4479
+ const treeData = new StorageBufferAttribute(new Float32Array(capacity * TREE_VEC4S * 4), 4);
4480
+ treeData.array.set(this.treeData.array.subarray(0, Math.min(capacity, this.capacityValue) * TREE_VEC4S * 4));
4481
+ this.disposeBuffers();
4482
+ this.capacityValue = capacity;
4483
+ this.treeData = treeData;
4484
+ this.lists = new StorageBufferAttribute(new Uint32Array(3 * capacity), 1);
4485
+ this.dithers = new StorageBufferAttribute(new Float32Array(3 * capacity), 1);
4486
+ for (const [node, attribute, count] of [
4487
+ [
4488
+ this.treeNode,
4489
+ this.treeData,
4490
+ capacity * TREE_VEC4S
4491
+ ],
4492
+ [
4493
+ this.listNode,
4494
+ this.lists,
4495
+ 3 * capacity
4496
+ ],
4497
+ [
4498
+ this.ditherNode,
4499
+ this.dithers,
4500
+ 3 * capacity
4501
+ ]
4502
+ ]) {
4503
+ node.value = attribute;
4504
+ node.bufferCount = count;
4505
+ }
4506
+ for (const node of this.computeNodes) node.dispose();
4507
+ this.computeNodes = this.createDispatches();
4508
+ this.version++;
4509
+ }
4510
+ /** Frees the meshes' geometry, the buffers and the compute pass (the materials belong to the Variant). */
4511
+ dispose() {
4512
+ for (const mesh of this.meshes) {
4513
+ mesh.removeFromParent();
4514
+ mesh.geometry.dispose();
4515
+ }
4516
+ this.levels.length = 0;
4517
+ this.disposeBuffers();
4518
+ this.counters.dispose();
4519
+ this.args.dispose();
4520
+ for (const node of this.computeNodes) node.dispose();
4521
+ }
4522
+ disposeBuffers() {
4523
+ this.treeData.dispose();
4524
+ this.lists.dispose();
4525
+ this.dithers.dispose();
4526
+ }
4527
+ /**
4528
+ * The compute pass: reset the level counters; sort every tree into its level list (and, in a
4529
+ * cross-fade, the next level's too), mirroring `selectDetailLevel`; copy the counts into the draw
4530
+ * arguments of every level's meshes.
4531
+ */
4532
+ createDispatches() {
4533
+ const capacity = this.capacityValue;
4534
+ const { light, impostor, fade, camera, forest, farthest } = this.uniforms;
4535
+ const counters = storage(this.counters, "uint", 3).toAtomic();
4536
+ const trees = storage(this.treeData, "vec4", capacity * TREE_VEC4S).toReadOnly();
4537
+ const lists = storage(this.lists, "uint", 3 * capacity);
4538
+ const dithers = storage(this.dithers, "float", 3 * capacity);
4539
+ const args = storage(this.args, "uint", 45);
4540
+ const count = this.countNode;
4541
+ const reset = Fn(() => {
4542
+ If(instanceIndex.lessThan(3), () => {
4543
+ atomicStore(counters.element(instanceIndex), uint(0));
4544
+ });
4545
+ })().compute(3);
4546
+ const append = (level, i, dither) => {
4547
+ const at = atomicAdd(counters.element(level), uint(1)).toVar();
4548
+ const entry = level.mul(uint(capacity)).add(at);
4549
+ lists.element(entry).assign(i);
4550
+ dithers.element(entry).assign(dither);
4551
+ };
4552
+ const select_ = Fn(() => {
4553
+ const i = instanceIndex;
4554
+ If(i.lessThan(count), () => {
4555
+ const state = trees.element(i.mul(TREE_VEC4S).add(1));
4556
+ const base = trees.element(i.mul(TREE_VEC4S).add(2)).xyz;
4557
+ const t = forest.mul(vec4(base, 1)).xyz.distance(camera).div(state.x.max(MIN_LOD_SCALE));
4558
+ const half = fade.mul(.5);
4559
+ const toImpostor = select(state.y.greaterThanEqual(1), ramp(t, impostor.mul(float(1).sub(half)), impostor.mul(float(1).add(half))), float(0));
4560
+ const toLight = ramp(t, light.mul(float(1).sub(half)), light.mul(float(1).add(half)));
4561
+ const level = uint(DetailLevel.Full).toVar();
4562
+ const amount = toLight.toVar();
4563
+ If(toImpostor.greaterThanEqual(1), () => {
4564
+ level.assign(DetailLevel.Impostor);
4565
+ amount.assign(0);
4566
+ }).ElseIf(toImpostor.greaterThan(0), () => {
4567
+ level.assign(DetailLevel.Light);
4568
+ amount.assign(toImpostor);
4569
+ }).ElseIf(toLight.greaterThanEqual(1), () => {
4570
+ level.assign(DetailLevel.Light);
4571
+ amount.assign(0);
4572
+ });
4573
+ If(level.greaterThanEqual(farthest), () => {
4574
+ level.assign(farthest);
4575
+ amount.assign(0);
4576
+ });
4577
+ const nearer = float(1).sub(amount);
4578
+ append(level, i, nearer);
4579
+ If(amount.greaterThan(0), () => {
4580
+ append(level.add(uint(1)), i, nearer.negate());
4581
+ });
4582
+ });
4583
+ })().compute(capacity);
4584
+ const draws = 9;
4585
+ return [
4586
+ reset,
4587
+ select_,
4588
+ Fn(() => {
4589
+ If(instanceIndex.lessThan(draws), () => {
4590
+ const level = instanceIndex.div(uint(3));
4591
+ args.element(instanceIndex.mul(ARGS_STRIDE).add(1)).assign(atomicLoad(counters.element(level)));
4592
+ });
4593
+ })().compute(draws)
4594
+ ];
4595
+ }
4596
+ };
4597
+ /** Whether a render is a shadow pass (three draws shadow maps with a shadow override material). */
4598
+ function isShadowPass(scene) {
4599
+ return (scene?.overrideMaterial)?.isShadowPassMaterial === true;
4600
+ }
4601
+ /**
4602
+ * Picks the level camera (the camera whose distance picks every tree's Detail Level) and runs every
4603
+ * Variant's level selection before a Detail Level mesh of the Forest is drawn: once per frame (`renderer.info.frame`), and again in the same frame only when
4604
+ * something it depends on changed (trees, settings, the level camera's or the Forest's position). So
4605
+ * every render of a frame (shadow passes, other cameras) draws the levels of the frame's level camera.
4606
+ */
4607
+ var LevelSelection = class {
4608
+ uniforms;
4609
+ frame = null;
4610
+ /** The level camera of the current frame. */
4611
+ camera = null;
4612
+ /** The last non-shadow camera seen drawing the Forest (before the first selection). */
4613
+ seen = null;
4614
+ /** What the last selection was made from (see `inputs`). */
4615
+ last = [];
4616
+ position = new Vector3();
4617
+ constructor(uniforms) {
4618
+ this.uniforms = uniforms;
4619
+ }
4620
+ /** Notes the camera of a render that draws the Forest, unless it is a shadow pass. */
4621
+ observe(scene, camera) {
4622
+ if (camera && !isShadowPass(scene)) this.seen = camera;
4623
+ }
4624
+ /**
4625
+ * Called before a Detail Level mesh is drawn. The first call of a frame fixes the frame's level
4626
+ * camera: `explicit` (`lod.camera`) when set, otherwise the camera of this render. A shadow map can
4627
+ * be drawn before the camera's own render reaches the Forest: then it is the previous frame's level
4628
+ * camera (or, on the first frame, the last camera seen drawing the Forest).
4629
+ */
4630
+ prepare(renderer, scene, camera, explicit, forest, variants) {
4631
+ this.observe(scene, camera);
4632
+ if (typeof renderer.compute !== "function") return;
4633
+ const frame = renderer.info?.frame ?? null;
4634
+ if (frame === null || frame !== this.frame) {
4635
+ const lodCamera = explicit ?? (isShadowPass(scene) ? this.camera ?? this.seen ?? camera : camera);
4636
+ if (!lodCamera) return;
4637
+ this.frame = frame;
4638
+ this.camera = lodCamera;
4639
+ this.last = [];
4640
+ } else if (explicit) this.camera = explicit;
4641
+ const inputs = this.inputs(this.camera, forest, variants);
4642
+ if (inputs.length === this.last.length && inputs.every((v, i) => v === this.last[i])) return;
4643
+ this.last = inputs;
4644
+ this.uniforms.camera.value.copy(this.position);
4645
+ this.uniforms.forest.value.copy(forest.matrixWorld);
4646
+ renderer.compute(variants.flatMap((v) => v.dispatches));
4647
+ }
4648
+ /** Everything the selection reads (leaves the camera's world position in `this.position`). */
4649
+ inputs(camera, forest, variants) {
4650
+ camera.updateMatrixWorld();
4651
+ camera.getWorldPosition(this.position);
4652
+ const { light, impostor, fade, farthest } = this.uniforms;
4653
+ return [
4654
+ ...this.position.toArray(),
4655
+ ...forest.matrixWorld.elements,
4656
+ light.value,
4657
+ impostor.value,
4658
+ fade.value,
4659
+ farthest.value,
4660
+ ...variants.map((v) => v.version)
4661
+ ];
4662
+ }
4663
+ };
4664
+ // src/forest/forest-lod.ts
4665
+ /**
4666
+ * The Detail Levels of one Forest. Which backend draws the Forest is only known on its first render
4667
+ * (three calls `onBeforeRender` with the renderer then, and not before), so:
4668
+ *
4669
+ * - On WebGPURenderer's WebGL2 fallback (`detect`): one console warning, `lod` is ignored and `ready`
4670
+ * resolves on that first render.
4671
+ * - On WebGPU: that first frame still draws every tree in full. Right after it, every Variant gets its
4672
+ * Detail Level meshes (they cannot join a frame whose render list is already made), the Impostors are
4673
+ * baked once the textures have loaded, and then `ready` resolves.
4674
+ */
4675
+ var ForestLod = class {
4676
+ host;
4677
+ /** The live values the GPU level selection reads. */
4678
+ uniforms;
4679
+ /** Resolves once the Impostors are baked; on the WebGL2 fallback on the first render; on dispose. */
4680
+ ready;
4681
+ settings;
4682
+ selection;
4683
+ backend = "unknown";
4684
+ resolveReady = () => {};
4685
+ disposed = false;
4686
+ constructor(settings, host) {
4687
+ this.host = host;
4688
+ this.settings = settings;
4689
+ this.uniforms = {
4690
+ light: uniform(settings.light),
4691
+ impostor: uniform(settings.impostor),
4692
+ fade: uniform(settings.fade),
4693
+ camera: uniform(new Vector3()),
4694
+ forest: uniform(new Matrix4()),
4695
+ farthest: uniform(DetailLevel.Light, "uint")
4696
+ };
4697
+ this.selection = new LevelSelection(this.uniforms);
4698
+ this.ready = new Promise((resolve) => this.resolveReady = resolve);
4699
+ }
4700
+ /** The settings (a copy). */
4701
+ get values() {
4702
+ return {
4703
+ ...this.settings,
4704
+ impostorAtlas: { ...this.settings.impostorAtlas }
4705
+ };
4706
+ }
4707
+ /** Sets distances, fade or camera (the others kept): only uniforms. Throws a RangeError for invalid values, keeping the old ones. */
4708
+ update(value) {
4709
+ const { settings, uniforms } = this;
4710
+ const next = {
4711
+ light: value.light ?? settings.light,
4712
+ impostor: value.impostor ?? settings.impostor,
4713
+ fade: value.fade ?? settings.fade
4714
+ };
4715
+ checkDetailLevelDistances(next);
4716
+ Object.assign(settings, next);
4717
+ if (value.camera !== void 0) settings.camera = value.camera;
4718
+ uniforms.light.value = next.light;
4719
+ uniforms.impostor.value = next.impostor;
4720
+ uniforms.fade.value = next.fade;
4721
+ }
4722
+ /** Whether the Detail Levels are drawn: the first render was on WebGPU (not the WebGL2 fallback). */
4723
+ get active() {
4724
+ return this.backend === "webgpu";
4725
+ }
4726
+ /**
4727
+ * Called before each of the Forest's instanced meshes is drawn: notes the camera and, on the first
4728
+ * render, finds the backend (see the class).
4729
+ */
4730
+ detect(renderer, scene, camera) {
4731
+ this.selection.observe(scene, camera);
4732
+ if (this.backend !== "unknown") return;
4733
+ const backend = renderer.backend;
4734
+ if (backend && "isWebGLBackend" in backend && backend.isWebGLBackend === true) {
4735
+ this.backend = "webgl";
4736
+ console.warn("tree.js: Forest Detail Levels (lod) need WebGPU; on WebGPURenderer's WebGL2 fallback this Forest ignores lod and draws every tree in full.");
4737
+ this.resolveReady();
4738
+ } else {
4739
+ this.backend = "webgpu";
4740
+ queueMicrotask(() => {
4741
+ if (this.disposed) return this.resolveReady();
4742
+ this.enable();
4743
+ this.bake(renderer);
4744
+ });
4745
+ }
4746
+ }
4747
+ /**
4748
+ * How many trees each Detail Level drew in the last frame (indexed by DetailLevel; a tree in a
4749
+ * cross-fade counts at both levels). All zero until the Detail Levels are drawn. Reads the GPU.
4750
+ */
4751
+ async counts(renderer) {
4752
+ const counts = [
4753
+ 0,
4754
+ 0,
4755
+ 0
4756
+ ];
4757
+ for (const variant of this.host.variants) {
4758
+ if (!variant.levels) continue;
4759
+ (await variant.levels.drawnCounts(renderer)).forEach((count, level) => counts[level] += count);
4760
+ }
4761
+ return counts;
4762
+ }
4763
+ /** Stops what is pending (the Detail Level meshes, the bake) and resolves `ready`: nothing is left to wait for. */
4764
+ dispose() {
4765
+ this.disposed = true;
4766
+ this.resolveReady();
4767
+ }
4768
+ /** Builds every Variant's Detail Level meshes and buffers. */
4769
+ enable() {
4770
+ const setupMesh = (mesh) => {
4771
+ mesh.onBeforeRender = (renderer, scene, camera) => this.select(webgpuRenderer(renderer), scene, camera);
4772
+ };
4773
+ for (const variant of this.host.variants) variant.enableDetailLevels(this.uniforms, this.settings, setupMesh, this.host.features);
4774
+ }
4775
+ /**
4776
+ * Bakes every Variant's Impostor with the app's renderer (after the textures have loaded), then lets
4777
+ * far trees draw as Impostors and resolves `ready`. Until then they draw Light. If the bake fails,
4778
+ * they keep drawing Light (one console error) and `ready` still resolves.
4779
+ */
4780
+ async bake(renderer) {
4781
+ try {
4782
+ await this.host.texturesReady.catch(() => {});
4783
+ if (this.disposed) return;
4784
+ for (const variant of this.host.variants) variant.impostor.bake(renderer);
4785
+ this.uniforms.farthest.value = DetailLevel.Impostor;
4786
+ } catch (error) {
4787
+ console.error("tree.js: baking the Forest Impostors failed; far trees draw Light.", error);
4788
+ } finally {
4789
+ this.resolveReady();
4790
+ }
4791
+ }
4792
+ /**
4793
+ * Before a Detail Level mesh is drawn: the first time in a frame, picks every tree's level for the
4794
+ * camera that picks the levels, on the GPU (shadow passes and other cameras reuse that frame's levels).
4795
+ */
4796
+ select(renderer, scene, camera) {
4797
+ const levels = this.host.variants.map((v) => v.levels);
4798
+ this.selection.prepare(renderer, scene, camera, this.settings.camera, this.host.object, levels);
4799
+ }
4800
+ };
3606
4801
  // src/forest/placement.ts
3607
4802
  function placementPosition(placement) {
3608
4803
  const p = placement.position;
@@ -3770,6 +4965,8 @@ function shareGeometry(source) {
3770
4965
  */
3771
4966
  var ForestVariant = class {
3772
4967
  forest;
4968
+ wind;
4969
+ textures;
3773
4970
  index;
3774
4971
  seed;
3775
4972
  data;
@@ -3788,10 +4985,20 @@ var ForestVariant = class {
3788
4985
  woodSource;
3789
4986
  leafSource;
3790
4987
  fruitSource;
4988
+ definition;
4989
+ /** @internal The Detail Levels this Variant draws its trees with; null until they are drawn (lod set, on WebGPU). */
4990
+ levels = null;
4991
+ /** Vertex data of the Light level (null until Detail Levels are drawn). */
4992
+ lightSources = [];
4993
+ /** @internal The Impostor of this Variant (atlases and card material); null until Detail Levels are drawn. */
4994
+ impostor = null;
3791
4995
  constructor(forest, definition, index, seed, wind, capacity, textures) {
3792
4996
  this.forest = forest;
4997
+ this.wind = wind;
4998
+ this.textures = textures;
3793
4999
  this.index = index;
3794
5000
  this.seed = seed;
5001
+ this.definition = definition;
3795
5002
  this.data = generateTree(definition, seed);
3796
5003
  const height = trunkHeight(this.data.skeleton);
3797
5004
  this.windResponse = new WindResponse(definition.wind, {
@@ -3841,6 +5048,21 @@ var ForestVariant = class {
3841
5048
  get capacity() {
3842
5049
  return this.instanceData.count;
3843
5050
  }
5051
+ /**
5052
+ * @internal What Tree Shader Hooks shade on this Variant: its bark, leaf and Fruit materials (which draw
5053
+ * every Detail Level but Impostor), with each tree's own Season, Growth and position.
5054
+ */
5055
+ hookTargets() {
5056
+ const { season, growth } = instanceState();
5057
+ const inputs = () => ({
5058
+ season: varying(season),
5059
+ growth: varying(growth),
5060
+ treeBase: instanceTreeBase()
5061
+ });
5062
+ const targets = [partHookTarget("bark", this.barkMaterial, this.woodSource, inputs()), partHookTarget("leaves", this.leafMaterial, this.leafSource, inputs())];
5063
+ if (this.fruitMaterial && this.fruitSource) targets.push(partHookTarget("fruit", this.fruitMaterial, this.fruitSource, inputs()));
5064
+ return targets;
5065
+ }
3844
5066
  /** @internal */
3845
5067
  add(tree) {
3846
5068
  if (this.trees.length === this.capacity) this.allocate(this.capacity * 2);
@@ -3872,7 +5094,8 @@ var ForestVariant = class {
3872
5094
  const scale = placement.scale ?? 1;
3873
5095
  this.woodMesh.setMatrixAt(i, new Matrix4().compose(position, quaternion, new Vector3(scale, scale, scale)));
3874
5096
  this.woodMesh.instanceMatrix.needsUpdate = true;
3875
- this.instanceData.array.set([
5097
+ const array = this.instanceData.array;
5098
+ array.set([
3876
5099
  quaternion.x,
3877
5100
  quaternion.y,
3878
5101
  quaternion.z,
@@ -3883,6 +5106,11 @@ var ForestVariant = class {
3883
5106
  tree.windPhase
3884
5107
  ], i * 8);
3885
5108
  this.instanceData.needsUpdate = true;
5109
+ this.levels?.write(i, array.subarray(i * 8, (i + 1) * 8), [
5110
+ position.x,
5111
+ position.y,
5112
+ position.z
5113
+ ]);
3886
5114
  for (const mesh of this.meshes) mesh.boundingSphere = mesh.boundingBox = null;
3887
5115
  }
3888
5116
  /** @internal */
@@ -3895,8 +5123,85 @@ var ForestVariant = class {
3895
5123
  windPhase: array[o + 7]
3896
5124
  };
3897
5125
  }
5126
+ /**
5127
+ * @internal Starts drawing this Variant's trees by Detail Level (ADR 0010): a Full and a Light mesh
5128
+ * set, drawn indirectly from the level lists, with the Variant's own materials (which get the
5129
+ * cross-fade dither). The instanced meshes stay, hidden, for raycasting and Tree IDs.
5130
+ */
5131
+ enableDetailLevels(uniforms, settings, setupMesh, features = null) {
5132
+ if (this.levels) return;
5133
+ const levels = new VariantLevels(this.capacity, uniforms, setupMesh);
5134
+ const parts = (level, wood, leaves, fruit) => {
5135
+ const list = [{
5136
+ name: `forest wood ${this.index} ${level}`,
5137
+ geometry: wood,
5138
+ material: this.barkMaterial
5139
+ }, {
5140
+ name: `forest leaves ${this.index} ${level}`,
5141
+ geometry: leaves,
5142
+ material: this.leafMaterial
5143
+ }];
5144
+ if (fruit && this.fruitMaterial) list.push({
5145
+ name: `forest fruit ${this.index} ${level}`,
5146
+ geometry: fruit,
5147
+ material: this.fruitMaterial
5148
+ });
5149
+ return list;
5150
+ };
5151
+ levels.setLevel(DetailLevel.Full, parts("full", this.woodSource, this.leafSource, this.fruitSource));
5152
+ const light = generateLightTree(this.definition, this.seed, settings.lightDefinition ?? void 0);
5153
+ const margin = trunkHeight(this.data.skeleton) * WIND_BOUNDS;
5154
+ this.lightSources = [
5155
+ light.wood,
5156
+ light.leaves,
5157
+ light.fruit
5158
+ ].map((buffers) => interleavedGeometry(buffers, margin));
5159
+ const [wood, leaves, fruit] = this.lightSources;
5160
+ levels.setLevel(DetailLevel.Light, parts("light", wood, leaves, this.fruitSource ? fruit : null));
5161
+ this.impostor = new VariantImpostor({
5162
+ definition: this.definition,
5163
+ sources: {
5164
+ wood: this.woodSource,
5165
+ leaves: this.leafSource
5166
+ },
5167
+ bounds: impostorBounds([this.data.wood, this.data.leaves]),
5168
+ atlas: settings.impostorAtlas,
5169
+ name: `forest impostor ${this.index}`,
5170
+ textures: this.textures,
5171
+ features: features ? {
5172
+ nodes: features,
5173
+ crown: this.data.crown
5174
+ } : null,
5175
+ wind: {
5176
+ source: this.wind,
5177
+ response: this.windResponse
5178
+ }
5179
+ });
5180
+ levels.setLevel(DetailLevel.Impostor, [this.impostor.part]);
5181
+ this.forest.addShaderHookTargets([impostorHookTarget(this.impostor.part.material)]);
5182
+ for (const material of [
5183
+ this.barkMaterial,
5184
+ this.leafMaterial,
5185
+ this.fruitMaterial
5186
+ ]) {
5187
+ if (!material) continue;
5188
+ material.maskNode = material.maskNode ? and(material.maskNode, levelVisible()) : levelVisible();
5189
+ material.needsUpdate = true;
5190
+ }
5191
+ this.levels = levels;
5192
+ for (const tree of this.trees) this.write(tree);
5193
+ levels.count = this.trees.length;
5194
+ for (const mesh of this.meshes) mesh.visible = false;
5195
+ this.forest.add(...levels.meshes);
5196
+ }
3898
5197
  /** @internal Frees the GPU resources. */
3899
5198
  dispose() {
5199
+ this.levels?.dispose();
5200
+ this.levels = null;
5201
+ this.impostor?.dispose();
5202
+ this.impostor = null;
5203
+ for (const source of this.lightSources) source.dispose();
5204
+ this.lightSources = [];
3900
5205
  this.disposeMeshes();
3901
5206
  this.woodSource.dispose();
3902
5207
  this.leafSource.dispose();
@@ -3907,6 +5212,7 @@ var ForestVariant = class {
3907
5212
  }
3908
5213
  setCount() {
3909
5214
  for (const mesh of this.meshes) mesh.count = this.trees.length;
5215
+ if (this.levels) this.levels.count = this.trees.length;
3910
5216
  }
3911
5217
  /**
3912
5218
  * (Re)builds the instanced meshes with room for `capacity` trees. An InstancedMesh cannot grow,
@@ -3923,6 +5229,7 @@ var ForestVariant = class {
3923
5229
  this.disposeMeshes();
3924
5230
  }
3925
5231
  this.instanceData = instanceData;
5232
+ this.levels?.resize(capacity);
3926
5233
  const mesh = (name, source, material) => {
3927
5234
  const geometry = shareGeometry(source);
3928
5235
  for (const [attribute, offset] of Object.entries(INSTANCE_ATTRIBUTES)) geometry.setAttribute(attribute, new InterleavedBufferAttribute(instanceData, 4, offset));
@@ -3931,7 +5238,8 @@ var ForestVariant = class {
3931
5238
  instanced.name = `${name} ${this.index}`;
3932
5239
  instanced.castShadow = true;
3933
5240
  instanced.receiveShadow = true;
3934
- instanced.onBeforeRender = (renderer) => assertWebGPURenderer(renderer);
5241
+ instanced.visible = this.levels === null;
5242
+ instanced.onBeforeRender = (renderer, scene, camera) => this.forest.detectLodBackend(webgpuRenderer(renderer), scene, camera);
3935
5243
  return instanced;
3936
5244
  };
3937
5245
  this.woodMesh = mesh("forest wood", this.woodSource, this.barkMaterial);
@@ -3954,7 +5262,7 @@ var ForestVariant = class {
3954
5262
  * hash of the forest seed and the tree's id (or position), never from its index, so adding or
3955
5263
  * removing trees never changes the others. Growth and Season can be set per tree or for all.
3956
5264
  */
3957
- var Forest = class extends Group {
5265
+ var Forest = class extends ShaderHookedGroup {
3958
5266
  isForest = true;
3959
5267
  definition;
3960
5268
  /** The forest seed. */
@@ -3967,6 +5275,18 @@ var Forest = class extends Group {
3967
5275
  growthValue;
3968
5276
  seasonValue;
3969
5277
  features;
5278
+ hooks;
5279
+ /** The trunk height of the tallest Variant (the distances of `lod: true`). */
5280
+ tallestTrunk;
5281
+ /** The Detail Levels; null without lod. */
5282
+ detailLevels;
5283
+ /**
5284
+ * Resolves once every Impostor is baked (far trees draw Light until then); at once without lod; and
5285
+ * on dispose. The backend is only known on the first render (three hands the renderer to the
5286
+ * Forest's meshes then, not before), so on WebGPURenderer's WebGL2 fallback, where lod is ignored,
5287
+ * it resolves on that first render, not at once.
5288
+ */
5289
+ lodReady;
3970
5290
  constructor(definition, placements = [], options = {}) {
3971
5291
  super();
3972
5292
  const count = options.variants ?? 4;
@@ -3990,6 +5310,7 @@ var Forest = class extends Group {
3990
5310
  growth: instanceState().growth,
3991
5311
  toObject: (normal) => instanceRotate(normal)
3992
5312
  })));
5313
+ this.hooks = new LiveShaderHooks(this.variants.flatMap((v) => v.hookTargets()), definition.materials.shading, options.shaderHooks);
3993
5314
  const textures = this.variants.flatMap((v) => [
3994
5315
  v.barkMaterial.map,
3995
5316
  v.barkMaterial.normalMap,
@@ -3997,11 +5318,67 @@ var Forest = class extends Group {
3997
5318
  ]);
3998
5319
  this.ready = Promise.all(textures.filter((t) => t !== null).map(textureReady)).then(() => void 0);
3999
5320
  this.ready.catch(() => {});
5321
+ this.tallestTrunk = Math.max(...this.variants.map((v) => trunkHeight(v.data.skeleton)));
5322
+ const lod = this.resolveLod(options.lod);
5323
+ this.detailLevels = lod ? new ForestLod(lod, {
5324
+ object: this,
5325
+ variants: this.variants,
5326
+ texturesReady: this.ready,
5327
+ features: this.features.nodes
5328
+ }) : null;
5329
+ this.lodReady = this.detailLevels?.ready ?? Promise.resolve();
4000
5330
  for (const placement of placements) this.addTree(placement);
4001
5331
  }
4002
5332
  /**
5333
+ * The Detail Level settings (a copy), null without lod. Setting `light`, `impostor`, `fade` or
5334
+ * `camera` (the others kept) only writes uniforms: no rebuild, no recompile. Throws a RangeError for
5335
+ * invalid values (keeping the old ones), and on a forest without lod (switching it on needs a new Forest).
5336
+ */
5337
+ get lod() {
5338
+ return this.detailLevels?.values ?? null;
5339
+ }
5340
+ set lod(value) {
5341
+ if (!this.detailLevels) throw new Error("This Forest has no Detail Levels: pass `lod` to createForest (switching them on needs a new Forest)");
5342
+ this.detailLevels.update(value);
5343
+ }
5344
+ /**
5345
+ * @internal The settings `lod` gives this Forest, every default filled in (`lod: true`: the distances
5346
+ * from its tallest Variant's trunk height), or null when it is missing or false. Throws a RangeError
5347
+ * for invalid settings.
5348
+ */
5349
+ resolveLod(lod) {
5350
+ return resolveForestLod(lod, this.tallestTrunk);
5351
+ }
5352
+ /** @internal The live Detail Level settings as uniforms (null without lod), for the GPU level selection. */
5353
+ get lodUniforms() {
5354
+ return this.detailLevels?.uniforms ?? null;
5355
+ }
5356
+ /** @internal Whether Detail Levels are drawn: lod is set and the first render was on WebGPU (not the WebGL2 fallback). */
5357
+ get lodActive() {
5358
+ return this.detailLevels?.active ?? false;
5359
+ }
5360
+ /**
5361
+ * @internal Called before each instanced mesh is drawn: on the first render of a lod Forest, finds the
5362
+ * backend (see `ForestLod`). Does nothing without lod.
5363
+ */
5364
+ detectLodBackend(renderer, scene = null, camera = null) {
5365
+ this.detailLevels?.detect(renderer, scene, camera);
5366
+ }
5367
+ /**
5368
+ * @internal How many trees each Detail Level drew in the last frame (indexed by DetailLevel; a tree
5369
+ * in a cross-fade counts at both levels). All zero until Detail Levels are drawn. Reads the GPU.
5370
+ */
5371
+ async detailLevelCounts(renderer) {
5372
+ return this.detailLevels ? this.detailLevels.counts(renderer) : [
5373
+ 0,
5374
+ 0,
5375
+ 0
5376
+ ];
5377
+ }
5378
+ /**
4003
5379
  * The Wind every tree of this forest sways with. Assigning another Wind only rebinds uniforms:
4004
- * no rebuild, no recompile.
5380
+ * no rebuild, no recompile (except the one-time node-graph rebuild when the Forest first follows a
5381
+ * Wind that has had a Wind Burst, see `Wind.burst`).
4005
5382
  */
4006
5383
  get wind() {
4007
5384
  return this.windBinding.wind;
@@ -4077,6 +5454,10 @@ var Forest = class extends Group {
4077
5454
  this.seasonValue = checkedSeason(value);
4078
5455
  for (const tree of this.byKey.values()) tree.season = this.seasonValue;
4079
5456
  }
5457
+ /** @internal Materials made later (the Impostor cards) that the hooks shade too. */
5458
+ addShaderHookTargets(targets) {
5459
+ this.hooks.addTargets(targets);
5460
+ }
4080
5461
  /**
4081
5462
  * Crown Normals amount (0..1), from the Definition's `materials.leaf.crownNormals`; null when it is off.
4082
5463
  * Setting it (clamped to 0..1) only writes a uniform: no regeneration, no recompile. Throws on a
@@ -4118,6 +5499,8 @@ var Forest = class extends Group {
4118
5499
  }
4119
5500
  /** Frees every Variant's geometries, materials and instance buffers, and removes the forest from its parent. */
4120
5501
  dispose() {
5502
+ this.hooks.dispose();
5503
+ this.detailLevels?.dispose();
4121
5504
  for (const variant of this.variants) variant.dispose();
4122
5505
  this.byKey.clear();
4123
5506
  this.removeFromParent();
@@ -4135,6 +5518,6 @@ var Forest = class extends Group {
4135
5518
  function createForest(definition, placements = [], options = {}) {
4136
5519
  return new Forest(parseDefinition(definition), placements, options);
4137
5520
  }
4138
- export { treeScale as A, hexToLinear as B, loadTexture as C, groundTintAmount as D, textureReady as E, KEYFRAME_EPSILON as F, seasonShift as G, leafSeasonAttribute as H, evaluateSeason as I, woodSeasonAttribute as J, segmentWeight as K, fruitSeason as L, hashTreeData as M, crownDistance as N, clampGrowth as O, crownNormal as P, fruitSeasonAttribute as R, getTextureOptions as S, setTextureOptions as T, partSeasonAt as U, leafSeason as V, sampleTrack as W, createRandom as X, wrapSeason as Y, createBarkMaterial as _, forestTreeKey as a, BARK_REPEAT as b, Tree as c, sceneWind as d, applySeasonToLeafMaterial as f, assertWebGPURenderer as g, UnsupportedRendererError as h, ForestVariant as i, hashGeometry as j, growPositions as k, WindResponse as l, createSeasonNodes as m, Forest as n, loadStyle as o, createFruitSeasonNodes as p, srgbToLinear as q, ForestTree as r, createTree as s, createForest as t, Wind as u, createLeafMaterial as v, resolveTextureUrl as w, DEFAULT_TEXTURE_BASE_PATH as x, isFlatShading as y, fruitTracks as z };
5521
+ export { hashTreeData as A, leafSeasonAttribute as B, getTextureOptions as C, textureReady as D, setTextureOptions as E, fruitSeason as F, srgbToLinear as G, sampleTrack as H, fruitSeasonAttribute as I, createRandom as J, woodSeasonAttribute as K, fruitTracks as L, crownNormal as M, KEYFRAME_EPSILON as N, groundTintAmount as O, evaluateSeason as P, hexToLinear as R, DEFAULT_TEXTURE_BASE_PATH as S, resolveTextureUrl as T, seasonShift as U, partSeasonAt as V, segmentWeight as W, assertWebGPURenderer as _, forestTreeKey as a, isFlatShading as b, loadStyle as c, WindResponse as d, applySeasonToLeafMaterial as f, UnsupportedRendererError as g, leafSeasonNode as h, ForestVariant as i, crownDistance as j, hashGeometry as k, createTree as l, createSeasonNodes as m, Forest as n, DetailLevel as o, createFruitSeasonNodes as p, wrapSeason as q, ForestTree as r, selectDetailLevel as s, createForest as t, Tree as u, createBarkMaterial as v, loadTexture as w, BARK_REPEAT as x, createLeafMaterial as y, leafSeason as z };
4139
5522
 
4140
- //# sourceMappingURL=forest-lg61rhKM.js.map
5523
+ //# sourceMappingURL=forest-CM5DrklM.js.map