webgpu-trees 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (330) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1547 -2
  3. package/assets/SOURCES.md +263 -0
  4. package/assets/bark/alder.albedo.avif +0 -0
  5. package/assets/bark/alder.normal.avif +0 -0
  6. package/assets/bark/aleppoPine.albedo.avif +0 -0
  7. package/assets/bark/aleppoPine.normal.avif +0 -0
  8. package/assets/bark/ash.albedo.avif +0 -0
  9. package/assets/bark/ash.normal.avif +0 -0
  10. package/assets/bark/aspen.albedo.avif +0 -0
  11. package/assets/bark/aspen.normal.avif +0 -0
  12. package/assets/bark/beech.albedo.avif +0 -0
  13. package/assets/bark/beech.normal.avif +0 -0
  14. package/assets/bark/birch.albedo.avif +0 -0
  15. package/assets/bark/birch.normal.avif +0 -0
  16. package/assets/bark/birchFoot.albedo.avif +0 -0
  17. package/assets/bark/birchFoot.normal.avif +0 -0
  18. package/assets/bark/corsicanPine.albedo.avif +0 -0
  19. package/assets/bark/corsicanPine.normal.avif +0 -0
  20. package/assets/bark/cypress.albedo.avif +0 -0
  21. package/assets/bark/cypress.normal.avif +0 -0
  22. package/assets/bark/douglas.albedo.avif +0 -0
  23. package/assets/bark/douglas.normal.avif +0 -0
  24. package/assets/bark/eucalyptus.albedo.avif +0 -0
  25. package/assets/bark/eucalyptus.normal.avif +0 -0
  26. package/assets/bark/eucalyptusUpper.albedo.avif +0 -0
  27. package/assets/bark/eucalyptusUpper.normal.avif +0 -0
  28. package/assets/bark/fibrous.albedo.avif +0 -0
  29. package/assets/bark/fibrous.normal.avif +0 -0
  30. package/assets/bark/hemlock.albedo.avif +0 -0
  31. package/assets/bark/hemlock.normal.avif +0 -0
  32. package/assets/bark/hornbeam.albedo.avif +0 -0
  33. package/assets/bark/hornbeam.normal.avif +0 -0
  34. package/assets/bark/larch.albedo.avif +0 -0
  35. package/assets/bark/larch.normal.avif +0 -0
  36. package/assets/bark/lime.albedo.avif +0 -0
  37. package/assets/bark/lime.normal.avif +0 -0
  38. package/assets/bark/liveOak.albedo.avif +0 -0
  39. package/assets/bark/liveOak.normal.avif +0 -0
  40. package/assets/bark/magnolia.albedo.avif +0 -0
  41. package/assets/bark/magnolia.normal.avif +0 -0
  42. package/assets/bark/maple.albedo.avif +0 -0
  43. package/assets/bark/maple.normal.avif +0 -0
  44. package/assets/bark/montereyPine.albedo.avif +0 -0
  45. package/assets/bark/montereyPine.normal.avif +0 -0
  46. package/assets/bark/norMaple.albedo.avif +0 -0
  47. package/assets/bark/norMaple.normal.avif +0 -0
  48. package/assets/bark/oak.albedo.avif +0 -0
  49. package/assets/bark/oak.normal.avif +0 -0
  50. package/assets/bark/palmLattice.albedo.avif +0 -0
  51. package/assets/bark/palmLattice.normal.avif +0 -0
  52. package/assets/bark/palmPineapple.albedo.avif +0 -0
  53. package/assets/bark/palmPineapple.normal.avif +0 -0
  54. package/assets/bark/palmRings.albedo.avif +0 -0
  55. package/assets/bark/palmRings.normal.avif +0 -0
  56. package/assets/bark/pine.albedo.avif +0 -0
  57. package/assets/bark/pine.normal.avif +0 -0
  58. package/assets/bark/pineFlakes.albedo.avif +0 -0
  59. package/assets/bark/pineFlakes.normal.avif +0 -0
  60. package/assets/bark/plane.albedo.avif +0 -0
  61. package/assets/bark/plane.normal.avif +0 -0
  62. package/assets/bark/poplar.albedo.avif +0 -0
  63. package/assets/bark/poplar.normal.avif +0 -0
  64. package/assets/bark/redAlder.albedo.avif +0 -0
  65. package/assets/bark/redAlder.normal.avif +0 -0
  66. package/assets/bark/redOak.albedo.avif +0 -0
  67. package/assets/bark/redOak.normal.avif +0 -0
  68. package/assets/bark/ridged.albedo.avif +0 -0
  69. package/assets/bark/ridged.normal.avif +0 -0
  70. package/assets/bark/sitkaSpruce.albedo.avif +0 -0
  71. package/assets/bark/sitkaSpruce.normal.avif +0 -0
  72. package/assets/bark/spruce.albedo.avif +0 -0
  73. package/assets/bark/spruce.normal.avif +0 -0
  74. package/assets/bark/stonePine.albedo.avif +0 -0
  75. package/assets/bark/stonePine.normal.avif +0 -0
  76. package/assets/bark/sweetgum.albedo.avif +0 -0
  77. package/assets/bark/sweetgum.normal.avif +0 -0
  78. package/assets/bark/sycMaple.albedo.avif +0 -0
  79. package/assets/bark/sycMaple.normal.avif +0 -0
  80. package/assets/bark/torreyPine.albedo.avif +0 -0
  81. package/assets/bark/torreyPine.normal.avif +0 -0
  82. package/assets/bark/whitePine.albedo.avif +0 -0
  83. package/assets/bark/whitePine.normal.avif +0 -0
  84. package/assets/bark/whiteSpruce.albedo.avif +0 -0
  85. package/assets/bark/whiteSpruce.normal.avif +0 -0
  86. package/assets/bark/whiteWillow.albedo.avif +0 -0
  87. package/assets/bark/whiteWillow.normal.avif +0 -0
  88. package/assets/bark/willow.albedo.avif +0 -0
  89. package/assets/bark/willow.normal.avif +0 -0
  90. package/assets/leaves/alder.albedo.avif +0 -0
  91. package/assets/leaves/alder.normal.avif +0 -0
  92. package/assets/leaves/ash.albedo.avif +0 -0
  93. package/assets/leaves/ash.normal.avif +0 -0
  94. package/assets/leaves/aspen.albedo.avif +0 -0
  95. package/assets/leaves/aspen.normal.avif +0 -0
  96. package/assets/leaves/beech.albedo.avif +0 -0
  97. package/assets/leaves/beech.normal.avif +0 -0
  98. package/assets/leaves/birch.albedo.avif +0 -0
  99. package/assets/leaves/birch.normal.avif +0 -0
  100. package/assets/leaves/blackthorn.albedo.avif +0 -0
  101. package/assets/leaves/blackthorn.normal.avif +0 -0
  102. package/assets/leaves/blade.albedo.avif +0 -0
  103. package/assets/leaves/blade.normal.avif +0 -0
  104. package/assets/leaves/broomSprig.albedo.avif +0 -0
  105. package/assets/leaves/broomSprig.normal.avif +0 -0
  106. package/assets/leaves/corsicanShoot.albedo.avif +0 -0
  107. package/assets/leaves/corsicanShoot.normal.avif +0 -0
  108. package/assets/leaves/cypress.albedo.avif +0 -0
  109. package/assets/leaves/cypress.normal.avif +0 -0
  110. package/assets/leaves/cypressPad.albedo.avif +0 -0
  111. package/assets/leaves/cypressPad.normal.avif +0 -0
  112. package/assets/leaves/deadFronds.albedo.avif +0 -0
  113. package/assets/leaves/deadFronds.normal.avif +0 -0
  114. package/assets/leaves/deltoid.albedo.avif +0 -0
  115. package/assets/leaves/deltoid.normal.avif +0 -0
  116. package/assets/leaves/douglasShoot.albedo.avif +0 -0
  117. package/assets/leaves/douglasShoot.normal.avif +0 -0
  118. package/assets/leaves/elderSprig.albedo.avif +0 -0
  119. package/assets/leaves/elderSprig.normal.avif +0 -0
  120. package/assets/leaves/elliptic.albedo.avif +0 -0
  121. package/assets/leaves/elliptic.normal.avif +0 -0
  122. package/assets/leaves/eucalyptus.albedo.avif +0 -0
  123. package/assets/leaves/eucalyptus.normal.avif +0 -0
  124. package/assets/leaves/fan.albedo.avif +0 -0
  125. package/assets/leaves/fan.normal.avif +0 -0
  126. package/assets/leaves/fanB.albedo.avif +0 -0
  127. package/assets/leaves/fanB.normal.avif +0 -0
  128. package/assets/leaves/fir.albedo.avif +0 -0
  129. package/assets/leaves/fir.normal.avif +0 -0
  130. package/assets/leaves/frond.albedo.avif +0 -0
  131. package/assets/leaves/frond.normal.avif +0 -0
  132. package/assets/leaves/gorse.albedo.avif +0 -0
  133. package/assets/leaves/gorse.normal.avif +0 -0
  134. package/assets/leaves/hawthorn.albedo.avif +0 -0
  135. package/assets/leaves/hawthorn.normal.avif +0 -0
  136. package/assets/leaves/hemlockShoot.albedo.avif +0 -0
  137. package/assets/leaves/hemlockShoot.normal.avif +0 -0
  138. package/assets/leaves/hornbeam.albedo.avif +0 -0
  139. package/assets/leaves/hornbeam.normal.avif +0 -0
  140. package/assets/leaves/lance.albedo.avif +0 -0
  141. package/assets/leaves/lance.normal.avif +0 -0
  142. package/assets/leaves/larchShoot.albedo.avif +0 -0
  143. package/assets/leaves/larchShoot.normal.avif +0 -0
  144. package/assets/leaves/lime.albedo.avif +0 -0
  145. package/assets/leaves/lime.normal.avif +0 -0
  146. package/assets/leaves/liveOak.albedo.avif +0 -0
  147. package/assets/leaves/liveOak.normal.avif +0 -0
  148. package/assets/leaves/londonPlane.albedo.avif +0 -0
  149. package/assets/leaves/londonPlane.normal.avif +0 -0
  150. package/assets/leaves/magnolia.albedo.avif +0 -0
  151. package/assets/leaves/magnolia.normal.avif +0 -0
  152. package/assets/leaves/maple.albedo.avif +0 -0
  153. package/assets/leaves/maple.normal.avif +0 -0
  154. package/assets/leaves/norMaple.albedo.avif +0 -0
  155. package/assets/leaves/norMaple.normal.avif +0 -0
  156. package/assets/leaves/oak.albedo.avif +0 -0
  157. package/assets/leaves/oak.normal.avif +0 -0
  158. package/assets/leaves/paintFan.albedo.avif +0 -0
  159. package/assets/leaves/paintFan.normal.avif +0 -0
  160. package/assets/leaves/paintFrond.albedo.avif +0 -0
  161. package/assets/leaves/paintFrond.normal.avif +0 -0
  162. package/assets/leaves/pine.albedo.avif +0 -0
  163. package/assets/leaves/pine.normal.avif +0 -0
  164. package/assets/leaves/pineClumpDark.albedo.avif +0 -0
  165. package/assets/leaves/pineClumpDark.normal.avif +0 -0
  166. package/assets/leaves/pineClumpLight.albedo.avif +0 -0
  167. package/assets/leaves/pineClumpLight.normal.avif +0 -0
  168. package/assets/leaves/poplar.albedo.avif +0 -0
  169. package/assets/leaves/poplar.normal.avif +0 -0
  170. package/assets/leaves/queenFrond.albedo.avif +0 -0
  171. package/assets/leaves/queenFrond.normal.avif +0 -0
  172. package/assets/leaves/redAlder.albedo.avif +0 -0
  173. package/assets/leaves/redAlder.normal.avif +0 -0
  174. package/assets/leaves/redOak.albedo.avif +0 -0
  175. package/assets/leaves/redOak.normal.avif +0 -0
  176. package/assets/leaves/round.albedo.avif +0 -0
  177. package/assets/leaves/round.normal.avif +0 -0
  178. package/assets/leaves/scale.albedo.avif +0 -0
  179. package/assets/leaves/scale.normal.avif +0 -0
  180. package/assets/leaves/scotsPineClump.albedo.avif +0 -0
  181. package/assets/leaves/scotsPineClump.normal.avif +0 -0
  182. package/assets/leaves/seaBuckthornSprig.albedo.avif +0 -0
  183. package/assets/leaves/seaBuckthornSprig.normal.avif +0 -0
  184. package/assets/leaves/serrate.albedo.avif +0 -0
  185. package/assets/leaves/serrate.normal.avif +0 -0
  186. package/assets/leaves/sitkaShoot.albedo.avif +0 -0
  187. package/assets/leaves/sitkaShoot.normal.avif +0 -0
  188. package/assets/leaves/stonePineCanopy.albedo.avif +0 -0
  189. package/assets/leaves/stonePineCanopy.normal.avif +0 -0
  190. package/assets/leaves/stonePineCushion.albedo.avif +0 -0
  191. package/assets/leaves/stonePineCushion.normal.avif +0 -0
  192. package/assets/leaves/sweetgum.albedo.avif +0 -0
  193. package/assets/leaves/sweetgum.normal.avif +0 -0
  194. package/assets/leaves/sycamore.albedo.avif +0 -0
  195. package/assets/leaves/sycamore.normal.avif +0 -0
  196. package/assets/leaves/torreyPine.albedo.avif +0 -0
  197. package/assets/leaves/torreyPine.normal.avif +0 -0
  198. package/assets/leaves/whitePine.albedo.avif +0 -0
  199. package/assets/leaves/whitePine.normal.avif +0 -0
  200. package/assets/leaves/whiteSpruceShoot.albedo.avif +0 -0
  201. package/assets/leaves/whiteSpruceShoot.normal.avif +0 -0
  202. package/assets/leaves/whiteWillow.albedo.avif +0 -0
  203. package/assets/leaves/whiteWillow.normal.avif +0 -0
  204. package/assets/leaves/willow.albedo.avif +0 -0
  205. package/assets/leaves/willow.normal.avif +0 -0
  206. package/assets/marks/marks.json +894 -0
  207. package/assets/marks/painterly.avif +0 -0
  208. package/assets/marks/sheets.avif +0 -0
  209. package/assets/scans.json +6406 -0
  210. package/lib/age.d.ts +36 -0
  211. package/lib/age.d.ts.map +1 -0
  212. package/lib/age.js +170 -0
  213. package/lib/age.js.map +1 -0
  214. package/lib/atmosphere.d.ts +64 -0
  215. package/lib/atmosphere.d.ts.map +1 -0
  216. package/lib/atmosphere.js +260 -0
  217. package/lib/atmosphere.js.map +1 -0
  218. package/lib/dabs.d.ts +4 -0
  219. package/lib/dabs.d.ts.map +1 -0
  220. package/lib/dabs.js +77 -0
  221. package/lib/dabs.js.map +1 -0
  222. package/lib/engine.d.ts +211 -0
  223. package/lib/engine.d.ts.map +1 -0
  224. package/lib/engine.js +3808 -0
  225. package/lib/engine.js.map +1 -0
  226. package/lib/genetics.d.ts +129 -0
  227. package/lib/genetics.d.ts.map +1 -0
  228. package/lib/genetics.js +721 -0
  229. package/lib/genetics.js.map +1 -0
  230. package/lib/geometry.d.ts +237 -0
  231. package/lib/geometry.d.ts.map +1 -0
  232. package/lib/geometry.js +1944 -0
  233. package/lib/geometry.js.map +1 -0
  234. package/lib/grow.d.ts +83 -0
  235. package/lib/grow.d.ts.map +1 -0
  236. package/lib/grow.js +3851 -0
  237. package/lib/grow.js.map +1 -0
  238. package/lib/hiz.d.ts +74 -0
  239. package/lib/hiz.d.ts.map +1 -0
  240. package/lib/hiz.js +161 -0
  241. package/lib/hiz.js.map +1 -0
  242. package/lib/impostor.d.ts +106 -0
  243. package/lib/impostor.d.ts.map +1 -0
  244. package/lib/impostor.js +450 -0
  245. package/lib/impostor.js.map +1 -0
  246. package/lib/index.d.ts +17 -0
  247. package/lib/index.d.ts.map +1 -0
  248. package/lib/index.js +16 -0
  249. package/lib/index.js.map +1 -0
  250. package/lib/leaves.d.ts +30 -0
  251. package/lib/leaves.d.ts.map +1 -0
  252. package/lib/leaves.js +829 -0
  253. package/lib/leaves.js.map +1 -0
  254. package/lib/light.d.ts +110 -0
  255. package/lib/light.d.ts.map +1 -0
  256. package/lib/light.js +430 -0
  257. package/lib/light.js.map +1 -0
  258. package/lib/lobes.d.ts +25 -0
  259. package/lib/lobes.d.ts.map +1 -0
  260. package/lib/lobes.js +151 -0
  261. package/lib/lobes.js.map +1 -0
  262. package/lib/marks.d.ts +63 -0
  263. package/lib/marks.d.ts.map +1 -0
  264. package/lib/marks.js +553 -0
  265. package/lib/marks.js.map +1 -0
  266. package/lib/mips.d.ts +42 -0
  267. package/lib/mips.d.ts.map +1 -0
  268. package/lib/mips.js +220 -0
  269. package/lib/mips.js.map +1 -0
  270. package/lib/paintedMarks.d.ts +21 -0
  271. package/lib/paintedMarks.d.ts.map +1 -0
  272. package/lib/paintedMarks.js +53 -0
  273. package/lib/paintedMarks.js.map +1 -0
  274. package/lib/palm.d.ts +162 -0
  275. package/lib/palm.d.ts.map +1 -0
  276. package/lib/palm.js +779 -0
  277. package/lib/palm.js.map +1 -0
  278. package/lib/palmAtlas.d.ts +79 -0
  279. package/lib/palmAtlas.d.ts.map +1 -0
  280. package/lib/palmAtlas.js +335 -0
  281. package/lib/palmAtlas.js.map +1 -0
  282. package/lib/palmGeometry.d.ts +41 -0
  283. package/lib/palmGeometry.d.ts.map +1 -0
  284. package/lib/palmGeometry.js +309 -0
  285. package/lib/palmGeometry.js.map +1 -0
  286. package/lib/phenology.d.ts +21 -0
  287. package/lib/phenology.d.ts.map +1 -0
  288. package/lib/phenology.js +168 -0
  289. package/lib/phenology.js.map +1 -0
  290. package/lib/random.d.ts +34 -0
  291. package/lib/random.d.ts.map +1 -0
  292. package/lib/random.js +92 -0
  293. package/lib/random.js.map +1 -0
  294. package/lib/scans.d.ts +232 -0
  295. package/lib/scans.d.ts.map +1 -0
  296. package/lib/scans.js +397 -0
  297. package/lib/scans.js.map +1 -0
  298. package/lib/scatter.d.ts +70 -0
  299. package/lib/scatter.d.ts.map +1 -0
  300. package/lib/scatter.js +186 -0
  301. package/lib/scatter.js.map +1 -0
  302. package/lib/species.d.ts +369 -0
  303. package/lib/species.d.ts.map +1 -0
  304. package/lib/species.js +2978 -0
  305. package/lib/species.js.map +1 -0
  306. package/lib/sprays.d.ts +112 -0
  307. package/lib/sprays.d.ts.map +1 -0
  308. package/lib/sprays.js +1137 -0
  309. package/lib/sprays.js.map +1 -0
  310. package/lib/stand.d.ts +52 -0
  311. package/lib/stand.d.ts.map +1 -0
  312. package/lib/stand.js +279 -0
  313. package/lib/stand.js.map +1 -0
  314. package/lib/styles.d.ts +135 -0
  315. package/lib/styles.d.ts.map +1 -0
  316. package/lib/styles.js +79 -0
  317. package/lib/styles.js.map +1 -0
  318. package/lib/tree.d.ts +134 -0
  319. package/lib/tree.d.ts.map +1 -0
  320. package/lib/tree.js +57 -0
  321. package/lib/tree.js.map +1 -0
  322. package/lib/variants.d.ts +157 -0
  323. package/lib/variants.d.ts.map +1 -0
  324. package/lib/variants.js +532 -0
  325. package/lib/variants.js.map +1 -0
  326. package/lib/visibility.d.ts +105 -0
  327. package/lib/visibility.d.ts.map +1 -0
  328. package/lib/visibility.js +242 -0
  329. package/lib/visibility.js.map +1 -0
  330. package/package.json +62 -3
package/lib/grow.js ADDED
@@ -0,0 +1,3851 @@
1
+ // Growing a tree: a species says how its kind is built, a size says how big
2
+ // this one is, and a seed says which one of its kind it is. Out come its
3
+ // branches (a skeleton of nodes) and its leaves (clumps hung on the twigs).
4
+ //
5
+ // Three ways of building, by the species' architecture, each inside the
6
+ // crown's outline: its shape's profile (rounded as Weber and Penn's pruning
7
+ // envelope, upright where it is widest), turned round the trunk.
8
+ //
9
+ // - broadleaf and shrub: from buds, in the light (Palubicki et al. 2009, made
10
+ // light). The trunk rises bare to the crown's base; its great limbs (its
11
+ // scaffolds) leave the top of it, round it by the golden angle and up it one
12
+ // to a slot, the lowest leaving widest, each laid out to the crown's outline
13
+ // along a spine that turns by the species' bend and wanders by how crooked it
14
+ // is; the trunk goes on up the crown as its leader, all the way if it keeps
15
+ // the lead. Then, for eleven cycles: each bud is lit by how little the wood
16
+ // above shades its voxel; the light is gathered down to the foot and handed
17
+ // back up, at each fork more to the main axis (Borchert and Honda's model)
18
+ // and to a scaffold as much as to its trunk; each bud grows as many
19
+ // internodes as it is given, turned towards the least shadow and up or down
20
+ // by the bend, a lateral bud at every one; and a branch that gathers too
21
+ // little light for its wood is shed (Takenaka). A shrub's stems are its
22
+ // scaffolds, from feet spread within a third of the crown. Leaves hang on the
23
+ // lit shoots near their twigs' ends. Then the wood is smoothed (forks held),
24
+ // bowed by its weight (thin wood more), and its straight runs joined.
25
+ // - conifer: a leader to the top, with whorls of boughs along it, each as long
26
+ // as the crown is wide where it hangs (some missing, some broken short), and
27
+ // side shoots along each bough; smoothed and bowed as a broadleaf is. A
28
+ // conifer has one leader: its row's stems are not read.
29
+ // - palm: grown by palm.ts, as a palm: one stem from one tip, and a crown of
30
+ // fronds round its top by the golden angle, the young upright, the old
31
+ // hanging, kept as it is pruned.
32
+ //
33
+ // Where it stands among other trees (stand.ts) is light too: its neighbours'
34
+ // crowns hide the low sky on their side, as a shadow over the voxels where
35
+ // the sky they hide would have come in. So an edge tree's buds turn out to
36
+ // the open side and its shaded side's lower branches are shed, and a tree
37
+ // inside a wood keeps only its top: the shapes come out of the light, as the
38
+ // rest of the crown's do. An edge tree's great limbs swing a little to the
39
+ // open side, and those that would reach into the dark are never grown; a
40
+ // conifer's boughs on its dark side die back or are not there. The crown
41
+ // still keeps to its outline: what moves is within it.
42
+ //
43
+ // A broadleaf or a shrub that weeps (`weep`) then hangs whips from its outer
44
+ // twigs: a short arch out, then straight down towards the crown's base, leaved
45
+ // all along, in place of the leaves at those twigs' ends.
46
+ //
47
+ // Then the same for all: clumps that crowd each other are thinned, the twigs
48
+ // that thinning left bare are shed (no twig ends without leaves), the tree is
49
+ // fitted to its size (a survey measured it, and a ball meets it there), and the
50
+ // radii come from the pipe model: a branch carries the wood of all it bears,
51
+ // of the branches it has shed, and of the twigs it once bore. A bole under a
52
+ // high crown has its own taper (its growth over years, not its crown's
53
+ // twigs), and the crown's wood meets it; a species that keeps them has dead
54
+ // stubs along a long clean bole.
55
+ //
56
+ // Plain Math and no three, so growing runs anywhere: in a worker, in node.
57
+ import { habitAt } from "./age.js";
58
+ import { growPalm } from "./palm.js";
59
+ import { standShare } from "./stand.js";
60
+ import { crownProfile } from "./tree.js";
61
+ import { Random, hashSeed } from "./random.js";
62
+ const DEG = Math.PI / 180;
63
+ const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));
64
+ /** Under the 4000 nodes a host can count on, with room for a conifer's last bough. */
65
+ const MAX_NODES = 3900;
66
+ /** The length of a piece of trunk below the crown (m). */
67
+ const TRUNK_STEP = 0.8;
68
+ /** The thinnest shell a conifer keeps its needles in, as a share of the way in, whatever its foliage depth. */
69
+ const MIN_SHELL = 0.12;
70
+ // Broadleaves and shrubs: growing by buds in the light (Palubicki et al. 2009).
71
+ /** Growing cycles: years, as it were. */
72
+ const CYCLES = 11;
73
+ /**
74
+ * The crown's size (the cube root of radius² × depth) in internodes: an internode's length. Tied to the
75
+ * crown and not to metres, a big tree and a small one of a kind grow alike, with about as many nodes.
76
+ */
77
+ const INTERNODES = 20;
78
+ /** The most voxels the shadow grid may have: a long thin crown's internodes are lengthened to keep under it. */
79
+ const MAX_VOXELS = 80000;
80
+ /** The wood grown, at the most, before it is smoothed and its straight runs joined (less for a tree that weeps). */
81
+ const FINE_NODES = 6000;
82
+ /** Shadow (Palubicki's): a node shades the voxels in a pyramid under it by a·b^−q, q layers down, to SHADOW_DEPTH layers. */
83
+ const SHADOW_A = 1;
84
+ const SHADOW_B = 2;
85
+ const SHADOW_DEPTH = 5;
86
+ /** Full light, in shadow: a bud under this much is in the dark. More in an open crown, whose leaves let light by. */
87
+ const LIGHT_FULL = 8;
88
+ const LIGHT_OPEN = 3;
89
+ /** The resource at a stem's foot, for each unit of light its buds gather (Palubicki's α). */
90
+ const ALPHA = 3;
91
+ /** The most internodes a bud puts out in a cycle. */
92
+ const MAX_METAMERS = 4;
93
+ /**
94
+ * Borchert and Honda's λ, how much of the resource at a fork goes on along its main axis rather than to its
95
+ * lateral: at leader 0 (decurrent: an oak's crown of equal limbs) and at leader 1 (excurrent: one stem to the top).
96
+ */
97
+ const LAMBDA_LO = 0.47;
98
+ const LAMBDA_HI = 0.55;
99
+ /** How much a stem's own axis is favoured over its laterals in the crown: at leader 0, and more for each unit of leader. */
100
+ const STEM_FAVOUR = 0.6;
101
+ const STEM_FAVOUR_LEADER = 1.4;
102
+ /** How much a scaffold's own axis is favoured over the shoots it puts out. */
103
+ const SCAFFOLD_FAVOUR = 1.3;
104
+ /** How far a shoot turns towards the least shadow it sees (Palubicki's ξ), and up or down by its species' bend (η). */
105
+ const TO_LIGHT = 0.4;
106
+ const TROPISM = 0.22;
107
+ /** How hard a stem's shoots turn up, at leader 1. */
108
+ const LEADER_UP = 0.35;
109
+ /** How far a shoot wanders at random each internode, at crooked 1. */
110
+ const WANDER = 0.22;
111
+ /**
112
+ * How much of its last internode's turn (its wandering and its turning to the light) a shoot keeps into the
113
+ * next: a shoot bends gently, as it grows, through several internodes; turned afresh at each, it zigzags,
114
+ * and smoothing only rounds the zigzag off.
115
+ */
116
+ const BEND_KEEP = 0.4;
117
+ /** A bud sees the voxels within this angle of its way (the cosine), two voxels round. */
118
+ const PERCEIVE = Math.cos(60 * DEG);
119
+ /**
120
+ * The voxels a bud sees (`lookForLight`): every one two round it, as offsets and the unit way to each, in a fixed
121
+ * order; and, for each of a cube map's cells of the way a bud looks, those it may see from a way in that cell (within
122
+ * the cone and the cell's own spread), in the same order. Asked at every internode grown, it tests a third of them.
123
+ */
124
+ const SEEN = (() => {
125
+ const off = [];
126
+ for (let a = -2; a <= 2; a++)
127
+ for (let b = -2; b <= 2; b++)
128
+ for (let c = -2; c <= 2; c++) {
129
+ if (a === 0 && b === 0 && c === 0)
130
+ continue;
131
+ const k = Math.hypot(a, b, c);
132
+ off.push(a, b, c, a / k, b / k, c / k);
133
+ }
134
+ return off;
135
+ })();
136
+ const SEEN_N = SEEN.length / 6;
137
+ const SEEN_CELLS = 8;
138
+ /** The cube map's cell of a way (unit or not): its face (by its largest part and that part's sign) and its place on it. */
139
+ function seenCell(x, y, z) {
140
+ const ax = Math.abs(x);
141
+ const ay = Math.abs(y);
142
+ const az = Math.abs(z);
143
+ let face;
144
+ let u;
145
+ let v;
146
+ if (ax >= ay && ax >= az) {
147
+ face = x >= 0 ? 0 : 1;
148
+ u = y / ax;
149
+ v = z / ax;
150
+ }
151
+ else if (ay >= az) {
152
+ face = y >= 0 ? 2 : 3;
153
+ u = x / ay;
154
+ v = z / ay;
155
+ }
156
+ else {
157
+ face = z >= 0 ? 4 : 5;
158
+ u = x / az;
159
+ v = y / az;
160
+ }
161
+ const iu = Math.min(SEEN_CELLS - 1, Math.max(0, Math.floor(((u + 1) / 2) * SEEN_CELLS)));
162
+ const iv = Math.min(SEEN_CELLS - 1, Math.max(0, Math.floor(((v + 1) / 2) * SEEN_CELLS)));
163
+ return (face * SEEN_CELLS + iu) * SEEN_CELLS + iv;
164
+ }
165
+ const SEEN_BUCKETS = (() => {
166
+ const out = [];
167
+ const way = (face, u, v) => {
168
+ const w = face < 2 ? [face === 0 ? 1 : -1, u, v] : face < 4 ? [u, face === 2 ? 1 : -1, v] : [u, v, face === 4 ? 1 : -1];
169
+ const k = Math.hypot(w[0], w[1], w[2]);
170
+ return [w[0] / k, w[1] / k, w[2] / k];
171
+ };
172
+ for (let face = 0; face < 6; face++)
173
+ for (let iu = 0; iu < SEEN_CELLS; iu++)
174
+ for (let iv = 0; iv < SEEN_CELLS; iv++) {
175
+ const u0 = (iu / SEEN_CELLS) * 2 - 1;
176
+ const u1 = ((iu + 1) / SEEN_CELLS) * 2 - 1;
177
+ const v0 = (iv / SEEN_CELLS) * 2 - 1;
178
+ const v1 = ((iv + 1) / SEEN_CELLS) * 2 - 1;
179
+ const mid = way(face, 0.5 * (u0 + u1), 0.5 * (v0 + v1));
180
+ // (The cell's spread: the angle from its middle to its furthest corner, and a little more.)
181
+ let spread = 0;
182
+ for (const [cu, cv] of [[u0, v0], [u0, v1], [u1, v0], [u1, v1]]) {
183
+ const c = way(face, cu, cv);
184
+ spread = Math.max(spread, Math.acos(Math.min(1, mid[0] * c[0] + mid[1] * c[1] + mid[2] * c[2])));
185
+ }
186
+ const least = Math.cos(Math.min(Math.PI, 60 * DEG + spread + 0.01));
187
+ const list = [];
188
+ for (let k = 0; k < SEEN_N; k++)
189
+ if (SEEN[6 * k + 3] * mid[0] + SEEN[6 * k + 4] * mid[1] + SEEN[6 * k + 5] * mid[2] >= least)
190
+ list.push(k);
191
+ out.push(Int32Array.from(list));
192
+ }
193
+ return out;
194
+ })();
195
+ /** The light a branch must gather for each of its internodes to be kept, from `openness` and `branchiness`, when `shed` is not given. */
196
+ const SHED_BASE = 0.05;
197
+ const SHED_OPEN = 0.1;
198
+ const SHED_SPARSE = 0.15;
199
+ /** The scaffolds leave the trunk from just above the crown's base, up a share of the crown's depth: at leader 0, and more for each unit of leader. */
200
+ const SCAFFOLD_FROM = 0;
201
+ const SCAFFOLD_SPAN = 0.14;
202
+ const SCAFFOLD_SPAN_LEADER = 0.5;
203
+ /** A stem that forks below its crown (`fork`) puts out its limbs over this share of the way from its fork to its crown's base. */
204
+ const FORK_SPAN = 0.25;
205
+ /**
206
+ * A stem that divides at its fork into a few stems (`forkStems`), each dividing again in V-forks (`forkSplits`):
207
+ * the angles (from upright) its first stems rise at, and how much further out each division's arms lean;
208
+ * how long its first stems are, as a share of the way from the fork to the crown's base and a share of its
209
+ * depth (FORK_INTO), and how much shorter each division's arms; how far apart round the stem its arms swing (rad); and
210
+ * how far a crooked one's piece of fork wanders each internode, as LIMB_WANDER does a limb's.
211
+ */
212
+ const FORK_TILT = [28 * DEG, 40 * DEG];
213
+ const FORK_TILT_STEP = 13 * DEG;
214
+ /** How far into its crown a forked stem's arms rise before they are limbs: a share of its depth past its base. */
215
+ const FORK_INTO = 0.3;
216
+ /** How far out from its stem all its arms together may lean, a share of its crown's radius (a narrow crown's rise steeply). */
217
+ const FORK_REACH = 0.55;
218
+ const FORK_SHORTER = 0.72;
219
+ /** How far a crooked tree's leaning lean (`lean`) is kept under a narrow crown, at the least (a column's: 0 before). */
220
+ const LEAN_NARROW = 0.5;
221
+ /** How far aside a leaning kind's forked trunk's or clump's stem bows on its way up, out in the open, a share of its rise for each of its `crooked`, and of the crown's radius at most. */
222
+ const STEM_BOW = 0.06;
223
+ const STEM_BOW_ROOM = 0.15;
224
+ /** The least crown (m, and in its trunk's radii) a forked trunk's or a clump's stems have room in. */
225
+ const FORK_ROOM_R = 1.5;
226
+ const FORK_ROOM_TRUNKS = 4;
227
+ /** How far out a V-forked stem's arms reach and its stem sways, at most, as shares of the crown's inside (its radius less a clump's room). */
228
+ const FORK_ROOM = 0.7;
229
+ const FORK_SWAY_ROOM = 0.25;
230
+ const FORK_SWING = 0.5;
231
+ const FORK_WANDER = 0.16;
232
+ /** How far apart up the stem a third or fourth stem leaves it (m). */
233
+ const FORK_APART = 0.3;
234
+ /**
235
+ * A forked trunk's or a clump's stems (trunks of their own): how far out from the axis the middle of each one's
236
+ * share of the crown is, as a share of its radius, by how many share it; how far a stem may lean where it
237
+ * leaves (rad) at leader 1 and at leader 0; the most its lean eases as it rises (the power p of 1 - (1 - t)^p:
238
+ * 1 straight, more leaning out at first and then turning up); how far round from its way out its great limbs
239
+ * leave it, at the most, over all its stems (a share of a full turn); and how far into another's share a
240
+ * stem's wood may grow, a share of the crown's radius.
241
+ */
242
+ const TRUNK_SHARE = [0, 0, 0.42, 0.5, 0.55];
243
+ const TRUNK_TILT = [12 * DEG, 36 * DEG];
244
+ const TRUNK_CURVE = 2.6;
245
+ const TRUNK_COVER = 1.3;
246
+ const SHARE_OVERLAP = 0.08;
247
+ /**
248
+ * The first piece of such a stem, from where it leaves (m); and how far up it eases into its lean and steps
249
+ * aside to its own side of the trunk, in trunk radii, and at the least (m).
250
+ */
251
+ const STEM_FIRST = 0.2;
252
+ /** ... and at least this many of the trunk's radii: it narrows from the trunk to itself over that, a crotch's shoulder. */
253
+ const STEM_FIRST_RADII = 1.4;
254
+ const STEM_EASE = 2.0;
255
+ /** How much thicker such a stem is where it leaves the trunk, fused into it, and over how much of its first piece that falls by e. */
256
+ const STEM_JOIN = 0.2;
257
+ const STEM_JOIN_FALL = 0.35;
258
+ const STEM_EASE_LEAST = 0.55;
259
+ /** A trunk is not forked this close under breast height or over it (m): measured, it is one trunk or its stems. */
260
+ const FORK_CLEAR_BH = 0.3;
261
+ /** How a leaning trunk turns upright (`lean`): its slope falls as 1 - (its height over the height it is upright by) to this power, so the higher, the longer it holds its lean. */
262
+ const LEAN_HOLD = 2.5;
263
+ /** Salts a tree's seed for which way it leans. */
264
+ const LEAN_SALT = 0x6c65616e;
265
+ /** ... and goes aside by then no further than this share of its crown's radius. */
266
+ const LEAN_OUT = 0.3;
267
+ /** How far a forked stem sways, at crooked 1, as a share of its height to the fork: a sinuous or leaning stem. */
268
+ const STEM_SWAY = 0.2;
269
+ /** How much wider than the species' angle the lowest scaffold leaves (and narrower the highest). */
270
+ const SCAFFOLD_SWING = 40 * DEG;
271
+ /** How far a scaffold turns up over a crown radius of its length, at bend 1 (down at -1), and how far it arches over by its weight. */
272
+ const SCAFFOLD_CURVE = 35 * DEG;
273
+ const SCAFFOLD_ARCH = 20 * DEG;
274
+ /** A crown narrower than this for its depth (radius over depth) is a column: its limbs rise steeply and arch little. */
275
+ const NARROW = 0.35;
276
+ /** A crown at least this wide for its depth (radius over depth) is lifted as its species says (`canopyLift`); narrower, less. */
277
+ const LIFT_WIDE = 0.8;
278
+ /** Wood further than this share of the crown's depth below its base, or further out than this share of its radius, has strayed and is shed (`shedStrays`). */
279
+ const STRAY_BELOW = 0.12;
280
+ /** A crown narrower than this (radius, m) is lit through: leaves to its middle. */
281
+ const SMALL_CROWN = 2.5;
282
+ const STRAY_BEYOND = 1.15;
283
+ /** How far a scaffold's way wanders each internode at crooked 1 (radians, a deviate's spread), and how much of its wander it keeps from the last. */
284
+ const LIMB_WANDER = 0.09;
285
+ const LIMB_KEEP = 0.85;
286
+ /** How much a crooked tree's wood that runs straight between elbows (`zigzagRun`) turns at each, for each internode of its run, beside what it wanders an internode. */
287
+ const ELBOW = 0.8;
288
+ /** How far a scaffold sways side to side over its length, at crooked 1. */
289
+ const SCAFFOLD_SWAY = 28 * DEG;
290
+ /** How far a trunk goes on up its crown, from its scaffolds to the top, at leader 0 (and all the way at leader 1). */
291
+ const LEADER_REACH = 0.55;
292
+ /** How lumpy an outline is at lobes 1: how far it falls back between its bulges, and how many bulges. */
293
+ const LOBE_DEPTH = 0.3;
294
+ const LOBE_COUNT = 7;
295
+ /** Leaves: on shoots this light or lighter ... */
296
+ const LEAF_LIGHT = 0.1;
297
+ /** ... within this many internodes of a twig's end at foliage depth 0, and this many more at 1. */
298
+ const LEAF_REACH = 1;
299
+ const LEAF_REACH_DEPTH = 5;
300
+ /** A pad's leaves are those within this many clump radii of its top, at pads 1, and this many more at pads 0. */
301
+ const PAD_THIN = 0.9;
302
+ const PAD_THICK = 7;
303
+ /** The most a crown lit through (small or narrow) is in pads, whatever its species' `pads`. */
304
+ const PAD_LIT = 0.9;
305
+ /**
306
+ * ... and a column (radius under NARROW of its depth), whose sky comes from round it as much as from above: a Scots
307
+ * pine drawn up in a wood kept in shelves was a pagoda of balls up its stem, a Monterey cypress's a few shelves.
308
+ */
309
+ const PAD_COLUMN = 0.4;
310
+ /**
311
+ * Bunches (`clusters` 1): a branch's leaves only this share of its foliage depth's reach from its twigs' ends;
312
+ * this share of branches bare; each bunch's clump this much bigger, and hanging this many of its radii under
313
+ * its twig.
314
+ */
315
+ const CLUSTER_REACH = 0.8;
316
+ const CLUSTER_BARE = 0.3;
317
+ const CLUSTER_GROW = 0.6;
318
+ const CLUSTER_HANG = 0.15;
319
+ /**
320
+ * How far a small crown's leaves still gather into bunches, beside an open-grown one's (a crown a few metres across is
321
+ * many sprays all through it); and a narrow one's, of a tall tree (a column's radius under NARROW of its depth, its
322
+ * radius SMALL_CROWN or more). A blue gum 26 m tall on a crown 3 m round is drawn up, not young: its crown is open,
323
+ * a few heavy ascending limbs hung with bunches, sky between them; made of sprays all through, it was a mop on a pole.
324
+ */
325
+ const CLUSTER_SMALL = 0;
326
+ const CLUSTER_NARROW = 0.75;
327
+ // The wood, smoothed and simplified, then bowed by its weight.
328
+ /** Laplacian passes over the wood, forks held, each moving a node this share of the way to its neighbours' middle. */
329
+ const SMOOTH_PASSES = 2;
330
+ const SMOOTH = 0.5;
331
+ /** A node that bends its wood less than this is dropped, its neighbours joined straight. */
332
+ const SIMPLIFY = 4 * DEG;
333
+ /** The longest piece simplifying may make, in internodes. */
334
+ const SIMPLIFY_SPAN = 5;
335
+ /**
336
+ * Where an axis's tip died and the shoot below it took the lead (sympodial growth), the new leader turns
337
+ * part of the way back towards the way the axis ran: past this angle, by this share of the rest. Grown at
338
+ * its lateral's angle and left there, every such node is a corner, and a twig of them a zigzag.
339
+ */
340
+ const TAKE_LEAD_KEEP = 15 * DEG;
341
+ const TAKE_LEAD = 0.6;
342
+ /** ... and for a species whose twigs run straight on (`zigzag` 0: its terminal bud goes on, a maple's), nearly all of it. */
343
+ const TAKE_LEAD_STRAIGHT = 0.92;
344
+ /** A species' `zigzag` past this (degrees) is grown into its fine branches as a zigzag (`zigzagWood`), by what it is past it. */
345
+ const ZIGZAG_FROM = 8;
346
+ /** How far wood turns down under its weight per internode of length (Evergrove's sag), at the most each piece, and the radius (in twigs' pipes) at which it is half as pliant. */
347
+ const SAG = 0.06;
348
+ const SAG_MOST = 0.3;
349
+ const SAG_STIFF = 2.6;
350
+ // Conifers.
351
+ /** How far a bough bends over its length at bend ±1 ... */
352
+ const BOUGH_CURVE = 50 * DEG;
353
+ /** ... and further for a long one, as its weight tells (per crown radius of length). */
354
+ const BOUGH_WEIGHT = 40 * DEG;
355
+ /** How far the top boughs turn up when the leader gives up the lead (leader 0): a pine's flat top. */
356
+ const TOP_TURN = 25 * DEG;
357
+ /** How far short of the top a leader stops when it does not keep the lead (leader 0), as a share of the crown's depth. */
358
+ const LEADER_SHORT = 0.3;
359
+ /** The length of a piece of bough, as a share of the crown's radius. */
360
+ const BOUGH_STEP = 0.12;
361
+ const MAX_BOUGH_STEPS = 8;
362
+ /** A side shoot's length, as a share of its bough's, at the bough's foot (shorter towards its tip). */
363
+ const SHOOT_LENGTH = 0.45;
364
+ /** The angle a side shoot leaves its bough at. */
365
+ const SHOOT_ANGLE = 55 * DEG;
366
+ /** A spire (spruce, fir, cedar): the top of the leader clothed in needles all round, this share of the crown's depth at most, and no more than SPIRE_MOST m. */
367
+ const SPIRE = 0.18;
368
+ const SPIRE_MOST = 3;
369
+ /** Its needles' clumps every this many clump radii up the leader, the top one this share of a clump's radius below the tree's top, the finest this share of a clump. */
370
+ const SPIRE_STEP = 0.9;
371
+ const SPIRE_TIP = 0.35;
372
+ const SPIRE_FINE = 0.4;
373
+ const SPIRE_FULL = 1.1;
374
+ /** A pine's tufts along its bough's tip and its shoots' ends, as a share of its clump (the bough's own end has a full one). */
375
+ const TUFT = 1;
376
+ /** A pine's side shoots: from this share of the way out along its bough, this share as many as a fir's. */
377
+ const TUFT_FROM = 0.45;
378
+ const TUFT_SHOOTS = 0.75;
379
+ /** The share of boughs broken or shaded back, which stop short. */
380
+ const BOUGH_BROKEN = 0.2;
381
+ /** How far a conifer sags under its weight, as a share of what a broadleaf of its bend does. */
382
+ const CONIFER_SAG = 0.5;
383
+ /**
384
+ * The furthest apart a conifer's whorls are, as a share of its crown's radius: a crown grown narrow in a
385
+ * wood has short boughs, and between its whorls the interwhorl branches a forest fir or spruce carries
386
+ * fill it, where a year's whorls alone would leave it a few tufts on a pole.
387
+ */
388
+ const WHORL_OF_CROWN = 0.3;
389
+ // Whips.
390
+ /** The share of the node budget kept from the crown's growing for its whips, at weep 1. */
391
+ const WHIP_NODES = 0.45;
392
+ /** The share of the clumps a crown may keep that go to its whips, at weep 1 (and a fifth more whatever the weep). */
393
+ const WHIP_CLUMPS = 0.75;
394
+ /** The share of the leaves along a weeping tree's twigs that it does not bear, at weep 1: they are on its whips. */
395
+ const WEEP_TWIG_BARE = 0.4;
396
+ /** ... under this share of its crown's depth: over it, every leaf along its twigs is kept. */
397
+ const WEEP_TOP = 0.6;
398
+ /** A whip's clump, as a share of the species'. */
399
+ const WHIP_CLUMP = 0.7;
400
+ /** How far a whip turns down with each piece of its arch. */
401
+ const WHIP_TURN = 35 * DEG;
402
+ /** The steepest a whip leaves its twig upwards, and the lowest. */
403
+ const WHIP_RISE = 10 * DEG;
404
+ const WHIP_DIP = -20 * DEG;
405
+ /** How much shorter a whip may stop than the crown's base, as a share of the way down to it from its twig (squared draws: most reach far). */
406
+ const WHIP_STAGGER = 0.45;
407
+ /** Whips spring from the tops of a weeping tree's arching limbs as well as its twigs' ends, above this share of its crown's depth. */
408
+ const WHIP_ARCH_FROM = 0.5;
409
+ /** How far over a whip's arch its clumps are hung there, in their radii. */
410
+ const WHIP_ARCH_LIFT = 0.35;
411
+ /** A weeping crown's wood above this share of its depth has leaves over it (`clotheTop`): over this share of a clump's radius above it, a spray hung this share of one over it where not. */
412
+ const CLOTHE_FROM = 0.45;
413
+ const CLOTHE_COVER = 0.6;
414
+ const CLOTHE_LIFT = 0.45;
415
+ /** ... in a tree that weeps at least this much: a curtain of whips is its crown (a willow's; a birch's few whips hang from an open crown, its twigs seen through it). */
416
+ const CLOTHE_WEEP = 0.5;
417
+ // Clumps.
418
+ /** How far from a clump's centre (in its radii) the twigs it covers are: they bear its leaves, and are not shed as bare. */
419
+ const IN_SPRAY = 0.8;
420
+ /** A conifer drawn in sheets keeps a twig without a clump of its own only this close to another's centre (in its radii). */
421
+ const IN_SHEET = 0.45;
422
+ /** How far past a twig's end its clump's centre sits, in the clump's radii. */
423
+ const HANG = 0.3;
424
+ /** How far a clump is lifted out of the crown from its twig, in its radii. */
425
+ const HANG_OUT = 0.2;
426
+ /** How close two clumps may be, as a share of their radii summed, in a solid crown and in an open one. */
427
+ const THIN = 0.6;
428
+ const THIN_OPEN = 0.4;
429
+ /** Past this many clumps, the crown is thinned again, wider ... */
430
+ const MAX_CLUMPS = 240;
431
+ /** ... more for a tree that weeps, by its share of whips (at weep 1, twice as many: a curtain is leaves all the way down) ... */
432
+ const WEEP_CLUMPS = 1;
433
+ /** ... and for a palm, whose leaves are strung along its fronds, and may be closer (a frond's leaflets overlap). */
434
+ const PALM_CLUMPS = 1.25;
435
+ const PALM_THIN = 0.75;
436
+ /** How far one clump's size strays from the species' (as shares of it), at the most. */
437
+ const CLUMP_MIN = 0.55;
438
+ const CLUMP_MAX = 1.6;
439
+ /** The largest a clump's radius may be, as a share of the crown's radius: five clumps across it at the least. */
440
+ const CLUMP_OF_CROWN = 0.2;
441
+ /**
442
+ * ... and of its depth, a broadleaf's or a shrub's: three clumps and more deep. A blue gum fitted 10 m tall on a crown
443
+ * 2.6 m deep and 5.3 m round, its clumps as big as its height gives them, was a thin flat lid of them, a single sheet.
444
+ */
445
+ const CLUMP_OF_DEPTH = 0.15;
446
+ /** ... and of a column's (a crown narrower than NARROW of its depth): six across it. */
447
+ const CLUMP_OF_COLUMN = 0.17;
448
+ /**
449
+ * ... and, for a broadleaf or a shrub whose crown is narrower for its height than its specimen's, smaller by as much
450
+ * (to this power): as many of its sprays across its crown, and not its specimen's few big ones crowded in (a stone
451
+ * pine of 12 m on a crown half its specimen's width was a tower of four or five cushions stacked, its specimen's
452
+ * 3 m cushions on a crown 12 m across). A tree small all over keeps its clumps as its height has them: a pine's
453
+ * tufts are its needles' size, and do not shrink with its crown.
454
+ */
455
+ const CLUMP_NARROW = 1;
456
+ /** ... less by this share of its `clusters`: a blue gum's bunches are its habit, at any width; smaller, its crown is a mop of sprays. */
457
+ const CLUMP_BUNCHED = 1;
458
+ /**
459
+ * ... and less in an open crown, from none at the first openness to all at the second: a California sycamore's patchy
460
+ * masses with its pale limbs between them are its kind's at any width (open 0.7); in fine sprays all through, a sycamore
461
+ * 11 m tall on a crown 3.8 m round was a ball on a pole.
462
+ */
463
+ const CLUMP_OPEN = [0.45, 0.75];
464
+ /** ... down to this share of what its height gives them, at the least: a pine's tufts drawn up in a wood stay tufts, not beads. */
465
+ const CLUMP_NARROW_LEAST = 0.6;
466
+ /** An umbrella pine's crown (`umbrellaCap`): flatter-topped than this, and at most this many of its radii deep. */
467
+ const UMBRELLA_ROUND = 3;
468
+ const UMBRELLA_DEPTH = 1.5;
469
+ /**
470
+ * ... and never less deep than this share of its height, a forest-grown stone pine's crown being its top third or so;
471
+ * but never deeper than UMBRELLA_DEEPEST of its radius: a crown 1 m round kept to 5 m was a column of cushions still.
472
+ */
473
+ const UMBRELLA_SHARE = 0.3;
474
+ const UMBRELLA_DEEPEST = 1.8;
475
+ // Fitting to size.
476
+ /** How far the outermost clump reaches, as a share of the crown radius. */
477
+ const FIT_REACH = 0.985;
478
+ /** How high the highest leaf or twig is, as a share of the height. */
479
+ const FIT_TOP = 0.995;
480
+ /** How far over the crown's base the lowest leaf may be (a share of the crown's depth) before the fit moves it down to it, and how far under (hanging) before it moves it up. */
481
+ const FIT_LOW = 0.04;
482
+ const FIT_HANG = 0.06;
483
+ // Radii.
484
+ /** The pipe model's exponent (da Vinci's rule is 2; measured trees give 2.2 to 2.5). */
485
+ const PIPE = 2.4;
486
+ /**
487
+ * Disused pipes (Shinozaki et al. 1964): wood grows thicker than the twigs it now carries, by the twigs and
488
+ * leaves it once carried and lost. Each internode of wood carries this share more pipes than it hands on.
489
+ */
490
+ const DISUSED = 0.08;
491
+ /**
492
+ * A bole's taper: its radius goes as the length of stem above to this power (a cone is 1, a paraboloid 0.5;
493
+ * measured boles between the butt and the crown are near 0.5 to 0.7).
494
+ */
495
+ const BOLE_TAPER = 0.6;
496
+ /** How much thicker a stem is at the ground than its taper alone, where its roots flare out. */
497
+ const FLARE = 0.3;
498
+ /** How much more a buttressed foot (`buttress` 1) flares than an ordinary one. */
499
+ const FLARE_BUTTRESS = 1.2;
500
+ /** How far up the flare reaches (m, its e-folding height): this, and this much more for each metre of trunk radius. */
501
+ const FLARE_FROM = 0.15;
502
+ const FLARE_PER_RADIUS = 1.2;
503
+ /** Where a bole is cut near its foot, in flare heights, to draw the flare's curve. */
504
+ const FLARE_CUTS = [0.4, 1, 2];
505
+ /** The longest piece of bole above the flare (m). */
506
+ const BOLE_PIECE = 0.6;
507
+ // Stubs on a clean bole.
508
+ /** Stubs on a metre of bole, at boleStubs 1. */
509
+ const STUBS_PER_METRE = 1.1;
510
+ /** The lowest a stub is (m, or breast height if higher), and the highest, as a share of the crown's base. */
511
+ const STUB_FROM = 1;
512
+ const STUB_TOP = 0.96;
513
+ /** A stub's least radius, as a share of the trunk's at its foot: thin enough to be a stub, thick enough to be drawn close to. */
514
+ const STUB_THINNEST = 0.08;
515
+ /** The longest a stub is (m): what is left of a dead branch once the wind has had the rest. */
516
+ const STUB_LONGEST = 0.45;
517
+ /**
518
+ * How dark a voxel the stand hides all of its low sky from is to a bud, in the shadow a node of wood casts
519
+ * on the voxel under it: about as dark as under a few layers of its own crown.
520
+ */
521
+ const STAND_SHADE = 1.0;
522
+ /**
523
+ * In a stand, a crown lives only where it is lit at least this, for its best lit (or in the top
524
+ * `STAND_LIVE_LEAST` of the tree's height, which it keeps however closed its wood: a tree inside a wood has
525
+ * a live crown of nearly half its height or more: Assmann's yield tables, and every forester's eye).
526
+ */
527
+ const STAND_LIVE = 0.5;
528
+ const STAND_LIVE_LEAST = 0.45;
529
+ /** How far an edge tree's great limbs swing to the open side, for how lopsided it stands (radians). */
530
+ const STAND_SWING = 0.55;
531
+ /** How far its leader leans out to the open side, for how lopsided it stands (a share of its wander). */
532
+ const STAND_LEADER = 0.05;
533
+ /** A conifer's bough lit less than this is dead, and gone; one lit less than `STAND_BOUGH_FULL` is shorter. */
534
+ const STAND_BOUGH = 0.4;
535
+ const STAND_BOUGH_FULL = 0.8;
536
+ /** Dead stubs along a bole a wood has cleaned, for how enclosed it stands (as `boleStubs`). */
537
+ const STAND_STUBS = 0.6;
538
+ /** Where a trunk's radius is measured (m): breast height. */
539
+ export const BREAST_HEIGHT = 1.3;
540
+ /**
541
+ * Where this tree's trunk radius is measured: breast height, or a tenth of its height if it is under 13 m.
542
+ * A shrub's stems are measured near their foot, below where they divide: at breast height a shrub is all
543
+ * twigs.
544
+ */
545
+ export function breastHeight(size) {
546
+ return Math.min(BREAST_HEIGHT, 0.1 * size.height);
547
+ }
548
+ /** The seed's own stream for its form, apart from the one it grows by. */
549
+ const FORM_SALT = 0x2f6b1c3d;
550
+ /** In a closed wood (enclosure 1): this share fewer of its trees fork, or grow as clumps ... */
551
+ const WOOD_FEWER_FORKS = 0.6;
552
+ const WOOD_FEWER_CLUMPS = 0.35;
553
+ /** ... and those that fork do so this share of the way higher, towards the crown's base. */
554
+ const WOOD_HIGHER = 0.5;
555
+ /** Where a clump's stems part from their root plate, in flare heights. */
556
+ const CLUMP_JOIN = [1.6, 2.3];
557
+ /** A fork is never lower than this many flare heights (or half its crown's base): its root plate, under it. */
558
+ const ROOT_PLATE = 1.2;
559
+ /** A number 0..1 from a seed alone, which decides its form: below a species' shares, it forks or is a clump. */
560
+ export function formDraw(seed) {
561
+ return new Random(hashSeed(seed) ^ FORM_SALT).next();
562
+ }
563
+ /** The share of a species' trees whose trunk forks. */
564
+ export function forkShareOf(sp) {
565
+ if (sp.architecture !== "broadleaf")
566
+ return 0;
567
+ return Math.min(1, Math.max(0, sp.forkShare ?? (sp.fork !== undefined && sp.forkStems !== undefined ? 1 : 0)));
568
+ }
569
+ /** The share of a species' trees that grow as a clump of stems from one root plate. */
570
+ export function stemShareOf(sp) {
571
+ if (sp.architecture !== "broadleaf")
572
+ return 0;
573
+ return Math.min(1, Math.max(0, sp.stemShare ?? 0));
574
+ }
575
+ /** Whether a species' trees differ in their form at the foot, one from the next. */
576
+ export function formsVary(sp) {
577
+ const f = forkShareOf(sp);
578
+ return stemShareOf(sp) > 0 || (f > 0 && (f < 1 || (sp.forkSpread ?? 0) > 0 || (sp.forkStemsMost ?? 0) > (sp.forkStems ?? 0)));
579
+ }
580
+ /**
581
+ * A tree's form, from its own seed (and where it stands: in a closed wood fewer trees fork or grow as
582
+ * clumps, and those that fork do so higher). The same seed always gives the same form; over many seeds, a
583
+ * species' shares.
584
+ */
585
+ export function formOf(sp, seed, stand) {
586
+ const rng = new Random(hashSeed(seed) ^ FORM_SALT);
587
+ const u = rng.next();
588
+ const v = rng.next();
589
+ const w = rng.next();
590
+ const shut = Math.min(1, Math.max(0, stand?.enclosure ?? 0));
591
+ const clump = stemShareOf(sp) * (1 - WOOD_FEWER_CLUMPS * shut);
592
+ const forks = forkShareOf(sp) * (1 - WOOD_FEWER_FORKS * shut);
593
+ // (Fewer stems are likelier than more.)
594
+ const count = (lo, hi) => Math.min(hi, lo + Math.floor(v ** 1.3 * (hi - lo + 1)));
595
+ if (u < clump) {
596
+ const [lo, hi] = sp.stemRange ?? [2, 3];
597
+ return { stems: count(Math.max(2, lo), Math.min(4, hi)), fork: 0, clump: true, join: CLUMP_JOIN[0] + (CLUMP_JOIN[1] - CLUMP_JOIN[0]) * w };
598
+ }
599
+ if (u < clump + forks) {
600
+ const lo = Math.max(2, Math.min(4, Math.round(sp.forkStems ?? 2)));
601
+ const hi = Math.max(lo, Math.min(4, Math.round(sp.forkStemsMost ?? lo)));
602
+ let at = Math.min(1, Math.max(0, sp.fork ?? 0.6)) + (sp.forkSpread ?? 0) * (2 * w - 1);
603
+ at += shut * WOOD_HIGHER * (1 - at);
604
+ return { stems: count(lo, hi), fork: Math.min(1, Math.max(0.02, at)), clump: false, join: 0 };
605
+ }
606
+ return { stems: 1, fork: 1, clump: false, join: 0 };
607
+ }
608
+ /**
609
+ * Where a tree's stems part (m): a clump's a little over its root plate, a forked trunk's where its form says
610
+ * (but over its root plate: the stems of a trunk forked near the ground still rise from one), a stone pine's
611
+ * (V-forks) where its form says.
612
+ */
613
+ export function forkHeight(sp, size, form) {
614
+ if (form.stems <= 1)
615
+ return size.crownBase;
616
+ const hf = flareHeight(size, sp.buttress ?? 0);
617
+ const bh = breastHeight(size);
618
+ // (A stem's first piece, from the trunk's thickness to its own, ends under breast height or well over it.)
619
+ const under = Math.max(FORK_CLEAR_BH, stemFirst(size));
620
+ if (form.clump)
621
+ return Math.max(0.1, Math.min(hf * form.join, 0.6 * bh, bh - under, 0.6 * size.crownBase));
622
+ if (sp.forkSplits !== undefined)
623
+ return form.fork * size.crownBase;
624
+ const ceil = Math.max(size.crownBase, Math.min(bh + FORK_CLEAR_BH + 0.6, 0.45 * size.height));
625
+ const floorY = Math.min(Math.max(1.8 * hf, 0.12 * size.height), 0.45 * ceil);
626
+ const y = Math.max(form.fork * ceil, floorY);
627
+ // Clear breast height so survey trunk measurement is unambiguous; push above bh whenever the tree leaves room, unless `fork` explicitly asked for a basal split (< 0.22).
628
+ if (form.fork >= 0.22 && y < bh + FORK_CLEAR_BH && bh + FORK_CLEAR_BH <= 0.92 * ceil)
629
+ return bh + FORK_CLEAR_BH;
630
+ if (y > bh - under && y < bh + FORK_CLEAR_BH)
631
+ return bh + FORK_CLEAR_BH <= 0.92 * ceil ? bh + FORK_CLEAR_BH : Math.max(0.1, Math.min(y, bh - under));
632
+ return y;
633
+ }
634
+ /**
635
+ * The wood a grown tree has at a height (m): where each piece of it crosses that height (x, z from its foot)
636
+ * and how thick it is there, the thickest first, leaving out wood thinner than `least` of its trunk's
637
+ * radius. At 1 m, a forked or clumped tree's stems: what a ball meets of it low down (one circle for a tree
638
+ * of one stem).
639
+ */
640
+ export function stemsAt(tree, y, least = 0.15) {
641
+ const k = tree.skeleton;
642
+ const out = [];
643
+ for (let i = 0; i < k.count; i++) {
644
+ const p = k.parent[i];
645
+ if (p < 0 || k.y[p] > y || k.y[i] <= y)
646
+ continue;
647
+ const f = (y - k.y[p]) / Math.max(1e-9, k.y[i] - k.y[p]);
648
+ const r = k.radius[p] + (k.radius[i] - k.radius[p]) * f;
649
+ if (r < least * tree.size.trunkRadius)
650
+ continue;
651
+ out.push({ x: k.x[p] + (k.x[i] - k.x[p]) * f, z: k.z[p] + (k.z[i] - k.z[p]) * f, r });
652
+ }
653
+ return out.sort((a, b) => b.r - a.r);
654
+ }
655
+ /** How long the first piece of a forked trunk's or a clump's stem is (m). */
656
+ function stemFirst(size) {
657
+ // (No longer than leaves room for a fork just over the root plate to end under breast height: a short
658
+ // tree's stems may still part low.)
659
+ const room = breastHeight(size) - ROOT_PLATE * flareHeight(size) - 0.05;
660
+ return Math.max(STEM_FIRST, Math.min(STEM_FIRST_RADII * size.trunkRadius, room));
661
+ }
662
+ /** A branch's angle from its parent (radians): the species', varied by its spread, within two spreads. */
663
+ function branchAngle(sp, rng) {
664
+ const g = Math.max(-2, Math.min(2, rng.gauss()));
665
+ return Math.max(5 * DEG, Math.min(175 * DEG, (sp.branchAngle + sp.branchAngleSpread * g) * DEG));
666
+ }
667
+ /**
668
+ * Grow one tree of a species to a size. The same arguments give the same tree. A `stand` (in the tree's own
669
+ * frame: its open side along +x) grows it in the light its neighbours leave it; left out, it stands alone.
670
+ */
671
+ export function growTree(row, size, seed, stand) {
672
+ // (An umbrella pine's crown deep for its width is its top's: `umbrellaCap`. Grown so, it keeps the size it was
673
+ // asked for, as a crown its stand has lifted does: the fit stretches its trunk and its crown from that size's crown
674
+ // base, and its crown, kept to its top, stays at its top.)
675
+ const asked = soundSize(size);
676
+ const sz = umbrellaCap(row, asked);
677
+ // (Its row as a tree of its own size grows: a small or narrow one as a younger tree of its kind, age.ts.)
678
+ const species = habitAt(row, sz);
679
+ const rng = new Random(seed);
680
+ const wood = newWood();
681
+ // (Nothing round it is no stand: it grows exactly as one alone.)
682
+ const st = stand && (stand.enclosure > 0 || stand.lopsided > 0) && species.architecture !== "palm" ? stand : undefined;
683
+ // (Where its live crown starts: its base, unless its wood has lifted it.)
684
+ const lift = st ? liveBaseOf(species, sz, st) : sz.crownBase;
685
+ // The species' clump, scaled by the tree's height against the species' own (a younger tree's twigs
686
+ // are smaller, but less so than the tree). No more than a share of the crown's radius, though: a crown
687
+ // grown narrow in a wood is still a crown of many sprays, not two or three balls on a stick.
688
+ const budGrown = species.architecture === "broadleaf" || species.architecture === "shrub";
689
+ // And smaller in a crown narrower for its height than its specimen's (CLUMP_NARROW).
690
+ const narrower = (sz.crownRadius / Math.max(0.01, species.crownRadius)) / (sz.height / Math.max(0.01, species.height));
691
+ // (A crown of bunches, `clusters`, keeps its bunches' size, as many fewer across a narrower crown: CLUMP_BUNCHED.)
692
+ // (And an open crown keeps its masses' size, as far as it is open: CLUMP_OPEN.)
693
+ const opened = Math.min(1, Math.max(0, (species.openness - CLUMP_OPEN[0]) / (CLUMP_OPEN[1] - CLUMP_OPEN[0])));
694
+ const narrowing = CLUMP_NARROW * (1 - CLUMP_BUNCHED * Math.min(1, Math.max(0, species.clusters ?? 0))) * (1 - opened);
695
+ const own = 0.5 * species.clumpSize * Math.sqrt(sz.height / species.height) * (budGrown ? Math.max(CLUMP_NARROW_LEAST, Math.min(1, narrower) ** narrowing) : 1);
696
+ // (A broadleaf's column, narrower than NARROW of its depth, a little smaller again: its clumps are round its stem,
697
+ // CLUMP_OF_COLUMN. A conifer's boughs are laid whorl by whorl, as long as its crown is wide, whatever its shape.)
698
+ const ofCrown = budGrown && sz.crownRadius / Math.max(0.01, sz.height - sz.crownBase) < NARROW ? CLUMP_OF_COLUMN : CLUMP_OF_CROWN;
699
+ // (Nor more than CLUMP_OF_DEPTH of a broadleaf's crown's depth: a shallow crown is still leaves in layers, not one sheet of
700
+ // clumps as deep as it is.)
701
+ // (A flat-topped kind's, an umbrella's or a shelf's, `crownRound` over UMBRELLA_ROUND, is a shallow crown of its own:
702
+ // its cushions and pads keep their size.)
703
+ const layered = budGrown && !((row.crownRound ?? 0) > UMBRELLA_ROUND);
704
+ const clumpR = species.architecture === "palm" ? own : Math.min(own, ofCrown * sz.crownRadius, layered ? CLUMP_OF_DEPTH * (sz.height - sz.crownBase) : Infinity);
705
+ // (How fine that is beside its kind's clump at its height, as a crown of its kind's width would have them.)
706
+ const kinds = Math.min(0.5 * species.clumpSize * Math.sqrt(sz.height / species.height), CLUMP_OF_CROWN * sz.crownRadius);
707
+ const clumpShare = budGrown ? Math.min(1, clumpR / Math.max(1e-6, kinds)) : 1;
708
+ // (Its form at the foot, from its own seed: one stem, a forked trunk, or a clump of stems.)
709
+ // (Not where its crown has no room for its stems side by side: a crown under FORK_ROOM_R round, or under
710
+ // FORK_ROOM_TRUNKS of its trunk's radius, is one stem's. A blue gum's clump of two stems 24 m tall under a crown 1 m
711
+ // round leaned its stems out of it, and bore one clump of leaves.)
712
+ const roomy = sz.crownRadius >= FORK_ROOM_R && sz.crownRadius >= FORK_ROOM_TRUNKS * sz.trunkRadius;
713
+ const form = species.architecture === "broadleaf" && roomy ? formOf(species, seed, st) : { stems: 1, fork: 1, clump: false, join: 0 };
714
+ let hung;
715
+ switch (species.architecture) {
716
+ case "conifer":
717
+ hung = whorled(species, sz, rng.fork(), wood, clumpR, st, lift);
718
+ break;
719
+ case "broadleaf":
720
+ case "shrub":
721
+ hung = budGrow(species, sz, rng.fork(), wood, clumpR, st, lift, form, leanWay(seed));
722
+ break;
723
+ case "palm":
724
+ // (A palm is grown as a palm: palm.ts.)
725
+ return growPalm(species, sz, seed);
726
+ }
727
+ // (A stone pine's V-forks below its crown keep their limbs from there; a forked trunk's or a clump's
728
+ // stems are kept as trunks.)
729
+ const vForkY = form.stems > 1 && species.forkSplits !== undefined ? forkHeight(species, sz, form) : undefined;
730
+ // (A forked trunk's or a clump's: where its stems part and their first pieces are kept as grown by the fit.)
731
+ const keepBelow = form.stems > 1 && species.forkSplits === undefined ? forkHeight(species, sz, form) + stemFirst(sz) + 0.05 : 0;
732
+ const grown = boleStubs(species, finish(species, sz, wood, hung, st ? lift : undefined, vForkY, keepBelow), rng.fork(), st);
733
+ const tree = sz === asked ? grown : { ...grown, size: asked };
734
+ const habit = { sprayHang: species.sprayHang, pads: species.pads, clusters: species.clusters };
735
+ const said = Object.values(habit).some((v) => v !== undefined && v > 0);
736
+ const fine = clumpShare < 1 - 1e-6;
737
+ return species.buttress || said || fine ? { ...tree, ...(species.buttress ? { buttress: species.buttress } : {}), ...(said ? { habit } : {}), ...(fine ? { clumpShare } : {}) } : tree;
738
+ }
739
+ /**
740
+ * The crown an umbrella pine grows (a stone pine's: its flat top, `crownRound` over UMBRELLA_ROUND, on limbs that
741
+ * divide in V-forks, `forkSplits`): no deeper than UMBRELLA_DEPTH of its radius (or UMBRELLA_SHARE of its height,
742
+ * if that is more, up to UMBRELLA_DEEPEST of its radius), at the top of the tree, its stem
743
+ * clean under it. Open-grown, its crown is a wide flat dome some three times as wide as deep; drawn up in a wood or
744
+ * a planting, it is a short crown on a long clean stem (EUFORGEN: "in dense stands, the crown is small and
745
+ * confined to the top"), not a column of its cushions: a survey's crown base under such a crown is its neighbours',
746
+ * or its own few low shoots. Fitted 20 m tall on a crown from 3 m, its cushions stacked up the column were a tower
747
+ * of plates. Other kinds keep their size as asked.
748
+ */
749
+ export function umbrellaCap(sp, size) {
750
+ if (sp.architecture !== "broadleaf" || sp.forkSplits === undefined || !((sp.crownRound ?? 0) > UMBRELLA_ROUND))
751
+ return size;
752
+ const base = size.height - Math.max(UMBRELLA_DEPTH * size.crownRadius, Math.min(UMBRELLA_SHARE * size.height, UMBRELLA_DEEPEST * size.crownRadius));
753
+ return base > size.crownBase ? { ...size, crownBase: Math.min(base, 0.95 * size.height) } : size;
754
+ }
755
+ /** A size growing can use: positive, with its crown's base under its top. */
756
+ function soundSize(s) {
757
+ const height = Math.max(0.1, s.height);
758
+ const crownRadius = Math.max(0.05, s.crownRadius);
759
+ const crownBase = Math.min(Math.max(0, s.crownBase), 0.95 * height);
760
+ const trunkRadius = Math.max(0.001, s.trunkRadius);
761
+ return { height, crownRadius, crownBase, trunkRadius };
762
+ }
763
+ /**
764
+ * How much of a place's sky a tree's stand leaves it (stand.ts, `standShare`, its crown taken as the
765
+ * shaders take it), for the most it leaves anywhere in the crown: 1 where the crown is best off. So a tree
766
+ * in an even shade all over (a sapling under a wood's canopy) is grown as one in the open: what shapes a
767
+ * crown is where its light comes from, not how much of it there is.
768
+ */
769
+ function standLightOf(sp, stand, size) {
770
+ const k = 0.5 * (0.3 + (1 - sp.openness) * 1.1);
771
+ const depth = Math.max(0.01, size.height - size.crownBase);
772
+ const shell = Math.max(sp.foliageDepth, 0.15) * Math.min(size.crownRadius, 0.5 * depth);
773
+ const at = (x, y, z) => standShare(stand, size, k, shell, x, y, z);
774
+ // (The best: over the crown's ellipsoid, at a few heights, out from its axis to near its side.)
775
+ let best = 1e-3;
776
+ for (let i = 0; i <= 12; i++) {
777
+ const e = i / 6 - 1;
778
+ const y = size.crownBase + 0.5 * depth * (1 + e);
779
+ const r = size.crownRadius * Math.sqrt(Math.max(0, 1 - e * e));
780
+ for (const f of [0, 0.5, 0.9])
781
+ for (let j = 0; j < (f > 0 ? 8 : 1); j++)
782
+ best = Math.max(best, at(f * r * Math.cos((j * Math.PI) / 4), y, f * r * Math.sin((j * Math.PI) / 4)));
783
+ }
784
+ return (x, y, z) => Math.min(1, at(x, y, z) / best);
785
+ }
786
+ /**
787
+ * Where a crown in a stand lives from (m): the lowest height at which a place halfway out on its most open
788
+ * side is lit enough to keep its leaves (`STAND_LIVE`), and no higher than the top `STAND_LIVE_LEAST` of the
789
+ * tree. At a wood's edge that is its base (its open side keeps its leaves to the ground); inside a wood, high.
790
+ */
791
+ function liveBaseOf(sp, size, stand) {
792
+ const at = standLightOf(sp, stand, size);
793
+ const profile = profileOf(sp);
794
+ const depth = Math.max(0.01, size.height - size.crownBase);
795
+ const top = size.height * (1 - STAND_LIVE_LEAST);
796
+ for (let i = 0; i <= 40; i++) {
797
+ const y = size.crownBase + (i / 40) * depth;
798
+ if (y >= top)
799
+ return Math.max(size.crownBase, top);
800
+ if (at(0.5 * profile(i / 40) * size.crownRadius, y, 0) >= STAND_LIVE)
801
+ return y;
802
+ }
803
+ return Math.max(size.crownBase, top);
804
+ }
805
+ function newWood() {
806
+ return { x: [], y: [], z: [], parent: [], stem: [], cont: [], kids: [], stems: 0, radius: null, shed: null };
807
+ }
808
+ function addNode(w, x, y, z, parent, cont) {
809
+ const i = w.x.length;
810
+ w.x.push(x);
811
+ w.y.push(y);
812
+ w.z.push(z);
813
+ w.parent.push(parent);
814
+ w.stem.push(parent < 0 ? w.stems++ : w.stem[parent]);
815
+ w.cont.push(parent >= 0 && cont);
816
+ w.kids.push([]);
817
+ if (w.shed)
818
+ w.shed.push(0);
819
+ if (parent >= 0)
820
+ w.kids[parent].push(i);
821
+ return i;
822
+ }
823
+ function newHung() {
824
+ return { node: [], x: [], y: [], z: [], r: [], whip: [] };
825
+ }
826
+ function hang(h, node, x, y, z, r, whip = false) {
827
+ h.node.push(node);
828
+ h.x.push(x);
829
+ h.y.push(y);
830
+ h.z.push(z);
831
+ h.r.push(r);
832
+ h.whip.push(whip);
833
+ }
834
+ /** One clump's radius: the species' mean, varied by its clump spread. */
835
+ function clumpRadius(sp, mean, rng) {
836
+ const k = 1 + 0.5 * sp.clumpSpread * rng.gauss();
837
+ return mean * Math.min(CLUMP_MAX, Math.max(CLUMP_MIN, k));
838
+ }
839
+ // ---------------------------------------------------------------------------
840
+ // A species' crown profile, tabled: growing asks it at every step.
841
+ const PROFILE_STEPS = 512;
842
+ /** A species' `crownProfile` as a function of `t` (0 the crown's base, 1 its top), from a table of it. */
843
+ function profileOf(sp) {
844
+ const table = new Float64Array(PROFILE_STEPS + 1);
845
+ for (let i = 0; i <= PROFILE_STEPS; i++)
846
+ table[i] = crownProfile(sp.shape, i / PROFILE_STEPS, sp);
847
+ return (t) => {
848
+ if (!(t > 0))
849
+ return table[0];
850
+ if (t >= 1)
851
+ return table[PROFILE_STEPS];
852
+ const f = t * PROFILE_STEPS;
853
+ const i = Math.floor(f);
854
+ return table[i] + (table[i + 1] - table[i]) * (f - i);
855
+ };
856
+ }
857
+ /**
858
+ * How far a crown reaches from its axis at a height (m): its species' outline from its base to its top. A
859
+ * crown a wood has lifted (its live crown starting at `lift`, above its base: stand.ts) is a whole crown of
860
+ * its kind over what is left of the tree, its outline drawn from `lift` to the top, as wide as its own
861
+ * outline or that, whichever is wider, and never past the crown's ellipsoid: what a ball meets
862
+ * (`crownEllipsoid`). So a tree inside a wood keeps a full crown, high up and as wide as its neighbours let
863
+ * it be, not the top of an open-grown one.
864
+ */
865
+ function outlineOf(sp, size, lift = size.crownBase) {
866
+ const profile = profileOf(sp);
867
+ const base = size.crownBase;
868
+ const depth = Math.max(0.01, size.height - base);
869
+ const R = size.crownRadius;
870
+ const own = (y) => profile((y - base) / depth) * R;
871
+ if (!(lift > base + 0.02 * depth))
872
+ return own;
873
+ const live = Math.max(0.01, size.height - lift);
874
+ const ry = 0.5 * depth;
875
+ const cy = base + ry;
876
+ return (y) => {
877
+ const w = own(y);
878
+ if (y <= lift)
879
+ return w;
880
+ const e = (y - cy) / ry;
881
+ const ellipsoid = e >= 1 ? 0 : R * Math.sqrt(1 - e * e);
882
+ return Math.max(w, Math.min(ellipsoid, profile((y - lift) / live) * R));
883
+ };
884
+ }
885
+ // ---------------------------------------------------------------------------
886
+ // The crown's envelope: the solid of revolution its profile sweeps, from its
887
+ // base to its top. Every profile is concave in height, so the solid is convex:
888
+ // a ray from inside leaves it once, which is what lets its reach be bisected.
889
+ class Envelope {
890
+ outline;
891
+ depth;
892
+ radius;
893
+ side;
894
+ /** Its lowest and highest points, inside any margins. */
895
+ lo;
896
+ hi;
897
+ /** The height of its centroid, on the axis: where the crown's heart is. */
898
+ cy;
899
+ /** Its volume (m³). */
900
+ volume;
901
+ /**
902
+ * The crown's envelope, shrunk by margins (m) at its side, bottom and top: the space a clump's centre
903
+ * may take and keep the clump inside.
904
+ */
905
+ constructor(sp, size, side = 0, bottom = 0, top = 0, lift = size.crownBase) {
906
+ this.outline = outlineOf(sp, size, lift);
907
+ this.depth = Math.max(0.01, size.height - size.crownBase);
908
+ this.radius = size.crownRadius;
909
+ this.side = side;
910
+ this.lo = size.crownBase + Math.min(bottom, 0.4 * this.depth);
911
+ this.hi = Math.max(this.lo + 0.01, size.height - Math.min(top, 0.4 * this.depth));
912
+ // Slices for the volume and the centroid.
913
+ let v = 0;
914
+ let vy = 0;
915
+ const n = 64;
916
+ for (let i = 0; i < n; i++) {
917
+ const y = this.lo + ((i + 0.5) / n) * (this.hi - this.lo);
918
+ const w = Math.max(0, this.width(y));
919
+ v += w * w;
920
+ vy += w * w * y;
921
+ }
922
+ this.volume = (Math.PI * v * (this.hi - this.lo)) / n;
923
+ this.cy = v > 0 ? vy / v : 0.5 * (this.lo + this.hi);
924
+ }
925
+ /** How far it reaches from the axis at a height (m); below 0 where it does not reach at all. */
926
+ width(y) {
927
+ if (y < this.lo || y > this.hi)
928
+ return -1;
929
+ return this.outline(y) - this.side;
930
+ }
931
+ inside(x, y, z) {
932
+ const w = this.width(y);
933
+ return w >= 0 && x * x + z * z <= w * w;
934
+ }
935
+ /** How far it is from its heart (0, cy, 0) to its surface, along a unit direction. */
936
+ reach(dx, dy, dz) {
937
+ let lo = 0;
938
+ let hi = Math.hypot(this.radius, this.hi - this.lo) + 1;
939
+ for (let i = 0; i < 24; i++) {
940
+ const m = 0.5 * (lo + hi);
941
+ if (this.inside(dx * m, this.cy + dy * m, dz * m))
942
+ lo = m;
943
+ else
944
+ hi = m;
945
+ }
946
+ return lo;
947
+ }
948
+ /** The outward normal of its surface at a point on it (or near it): side, top or bottom, whichever is nearest. */
949
+ normal(x, y, z) {
950
+ const yc = Math.min(this.hi, Math.max(this.lo, y));
951
+ const d = Math.hypot(x, z);
952
+ const sideGap = Math.abs(this.width(yc) - d);
953
+ const topGap = Math.abs(this.hi - y);
954
+ const bottomGap = Math.abs(y - this.lo);
955
+ if (topGap <= sideGap && topGap <= bottomGap)
956
+ return [0, 1, 0];
957
+ if (bottomGap <= sideGap)
958
+ return [0, -1, 0];
959
+ const h = 0.01 * (this.hi - this.lo);
960
+ const slope = (this.width(Math.min(this.hi, yc + h)) - this.width(Math.max(this.lo, yc - h))) / (2 * h);
961
+ const ux = d > 1e-9 ? x / d : 1;
962
+ const uz = d > 1e-9 ? z / d : 0;
963
+ const k = 1 / Math.hypot(1, slope);
964
+ return [ux * k, -slope * k, uz * k];
965
+ }
966
+ /**
967
+ * How deep a sphere sits in it, 0 (touching its surface) to 1 (at its heart), and which way it faces out:
968
+ * the surface's normal near it, turned halfway to the way out from the heart.
969
+ */
970
+ place(x, y, z, r) {
971
+ const dy = y - this.cy;
972
+ const dist = Math.hypot(x, dy, z);
973
+ let ux = 0;
974
+ let uy = 1;
975
+ let uz = 0;
976
+ if (dist > 1e-9) {
977
+ ux = x / dist;
978
+ uy = dy / dist;
979
+ uz = z / dist;
980
+ }
981
+ const L = this.reach(ux, uy, uz);
982
+ const depth = L > 0 ? Math.min(1, Math.max(0, 1 - (dist + r) / L)) : 0;
983
+ const s = this.normal(ux * L, this.cy + uy * L, uz * L);
984
+ const nx = s[0] + ux;
985
+ const ny = s[1] + uy;
986
+ const nz = s[2] + uz;
987
+ const k = Math.hypot(nx, ny, nz);
988
+ return { depth, n: k > 1e-9 ? [nx / k, ny / k, nz / k] : [0, 1, 0] };
989
+ }
990
+ }
991
+ function norm(v) {
992
+ const k = Math.hypot(v[0], v[1], v[2]);
993
+ return k > 1e-12 ? [v[0] / k, v[1] / k, v[2] / k] : [0, 1, 0];
994
+ }
995
+ /** Some unit vector square to a unit vector. */
996
+ function perpendicular(a) {
997
+ const b = Math.abs(a[1]) < 0.9 ? [0, 1, 0] : [1, 0, 0];
998
+ return norm([a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]);
999
+ }
1000
+ /** A direction at an angle from an axis, turned round it by an azimuth (both radians). */
1001
+ function cone(axis, angle, azimuth) {
1002
+ const p = perpendicular(axis);
1003
+ const q = [axis[1] * p[2] - axis[2] * p[1], axis[2] * p[0] - axis[0] * p[2], axis[0] * p[1] - axis[1] * p[0]];
1004
+ const c = Math.cos(azimuth);
1005
+ const s = Math.sin(azimuth);
1006
+ const ca = Math.cos(angle);
1007
+ const sa = Math.sin(angle);
1008
+ return norm([
1009
+ axis[0] * ca + (p[0] * c + q[0] * s) * sa,
1010
+ axis[1] * ca + (p[1] * c + q[1] * s) * sa,
1011
+ axis[2] * ca + (p[2] * c + q[2] * s) * sa,
1012
+ ]);
1013
+ }
1014
+ // ---------------------------------------------------------------------------
1015
+ // Broadleaves and shrubs: growing by buds, in the light.
1016
+ /**
1017
+ * A leaning trunk (`lean`): as far as its species says, its own way round (`way`, `leanWay`), nearly all the way
1018
+ * up to `to` metres (its fork, or where its limbs leave it) and turning upright only near there, so a coastal
1019
+ * Torrey pine's or a sycamore's stem reads as leaning from the tee and its crown, grown upright from its top,
1020
+ * stands near over its foot: no further aside by then than LEAN_OUT of its crown's radius `R` (a tall bole under
1021
+ * a narrow crown leans less, and a column, under NARROW of its `depth` wide, not at all). Its slope (x, z per metre up) at a height, and how far it has gone aside by then.
1022
+ * Not in a stand (`inStand`), where its neighbours draw it up.
1023
+ */
1024
+ function leanOf(sp, inStand, way, to, R, depth) {
1025
+ const h = Math.max(0.01, to);
1026
+ const p = LEAN_HOLD;
1027
+ // (A crown narrow for its depth, a tree drawn up straight, leans less, as its canopy is lifted less; a column not at all.)
1028
+ // (Never less than LEAN_NARROW of it, out in the open: a California sycamore drawn up tall on a narrow crown still
1029
+ // leans, as its kind does; upright, it was a lollipop on a pole. Its crown stays over its foot as before.)
1030
+ const wide = LEAN_NARROW + (1 - LEAN_NARROW) * Math.min(1, Math.max(0, (R / Math.max(0.01, depth) - NARROW) / (LIFT_WIDE - NARROW)));
1031
+ // (Slope t·(1 - (y/h)^p): aside by h, t·h·p/(p + 1).)
1032
+ const t = (sp.lean ?? 0) > 0 && !inStand ? wide * Math.min(Math.tan(Math.min(35, sp.lean ?? 0) * DEG), (LEAN_OUT * R * (p + 1)) / (p * h)) : 0;
1033
+ if (t === 0)
1034
+ return { slope: () => [0, 0], at: () => [0, 0] };
1035
+ const a = way;
1036
+ return {
1037
+ slope: (y) => {
1038
+ const s = t * Math.max(0, 1 - Math.min(1, Math.max(0, y) / h) ** p);
1039
+ return [s * Math.cos(a), s * Math.sin(a)];
1040
+ },
1041
+ at: (y) => {
1042
+ const u = Math.min(1, Math.max(0, y) / h);
1043
+ const d = t * h * (u - u ** (p + 1) / (p + 1));
1044
+ return [d * Math.cos(a), d * Math.sin(a)];
1045
+ },
1046
+ };
1047
+ }
1048
+ /**
1049
+ * Which way a tree leans (`lean`), from its own seed alone, on its own stream: the rest of its growing draws
1050
+ * as it would upright, so a lean bends the tree it is and does not grow another.
1051
+ */
1052
+ function leanWay(seed) {
1053
+ return new Random(hashSeed(seed) ^ LEAN_SALT).next() * 2 * Math.PI;
1054
+ }
1055
+ /**
1056
+ * How many great limbs (scaffolds) a broadleaf's trunk carries into its crown: its row's `scaffolds`, or 4
1057
+ * and one more for every third of its leader. A shrub's (or a stool's) stems are its scaffolds: it has none
1058
+ * besides.
1059
+ */
1060
+ export function scaffoldCount(sp) {
1061
+ if (sp.architecture !== "broadleaf" && sp.architecture !== "shrub")
1062
+ return 0;
1063
+ if (Math.round(sp.stems) > 1)
1064
+ return 0;
1065
+ return Math.max(0, Math.round(sp.scaffolds ?? 4 + 3 * sp.leader));
1066
+ }
1067
+ /**
1068
+ * Bulges on a crown's outline: a few directions from its heart where it reaches all the way out, falling
1069
+ * back between them, by how lumpy the species is.
1070
+ */
1071
+ class Lobes {
1072
+ dirs;
1073
+ amount;
1074
+ constructor(amount, rng) {
1075
+ this.amount = Math.min(1, Math.max(0, amount)) * LOBE_DEPTH;
1076
+ this.dirs = new Float64Array(LOBE_COUNT * 3);
1077
+ for (let k = 0; k < LOBE_COUNT; k++)
1078
+ this.dirs.set(rng.onSphere(), 3 * k);
1079
+ }
1080
+ /** The share of the outline's reach in a direction from the heart (not unit: it is normalized here). */
1081
+ reach(ux, uy, uz) {
1082
+ if (this.amount <= 0)
1083
+ return 1;
1084
+ const k = Math.hypot(ux, uy, uz);
1085
+ if (k < 1e-9)
1086
+ return 1;
1087
+ let best = 0;
1088
+ for (let j = 0; j < LOBE_COUNT; j++) {
1089
+ const d = (ux * this.dirs[3 * j] + uy * this.dirs[3 * j + 1] + uz * this.dirs[3 * j + 2]) / k;
1090
+ if (d > 0)
1091
+ best = Math.max(best, d * d * d);
1092
+ }
1093
+ return 1 - this.amount * (1 - best);
1094
+ }
1095
+ }
1096
+ /**
1097
+ * A broadleaf or a shrub, grown from its buds (Palubicki et al. 2009, lightened). Its trunk rises bare to the
1098
+ * crown's base; its great limbs leave the top of it, set round it and up it as Weber and Penn set a tree's
1099
+ * first branches, each reaching out to the crown's outline. Then, cycle by cycle: every bud is lit by how
1100
+ * little the wood above shades it (shadow cast down through a grid of voxels); the light is gathered down to
1101
+ * the foot and handed back up as what to grow with, more to the main axis at each fork (Borchert and
1102
+ * Honda); each bud grows as many internodes as it is given, its way turned towards the least shadow and up
1103
+ * or down by the species' bend, with a lateral bud at every one (by the golden angle); and a branch that
1104
+ * gathers too little light for its wood is shed (Takenaka). Nothing grows out of the crown's outline.
1105
+ */
1106
+ function budGrow(sp, size, rng, w, clumpR, stand, liftTo = size.crownBase, form = { stems: 1, fork: 1, clump: false, join: 0 }, way = 0) {
1107
+ const { height: H, crownRadius: R, crownBase: base } = size;
1108
+ const depth = Math.max(0.01, H - base);
1109
+ const crown = Math.cbrt(R * R * depth);
1110
+ let L = crown / INTERNODES;
1111
+ // (The grid starts a few layers under the crown: shadow falls only downwards, and nothing on the bare
1112
+ // trunk below grows, so a tall clean bole costs it no voxels and its crown no fineness.)
1113
+ const under = (l) => Math.max(0, Math.floor(base / l) - 4);
1114
+ const voxels = (l) => (Math.ceil((2 * R) / l) + 7) ** 2 * (Math.ceil(H / l) + 6 - under(l));
1115
+ while (voxels(L) > MAX_VOXELS)
1116
+ L *= 1.08;
1117
+ /** How many internodes a run of a crooked tree's wood is between its elbows (`zigzagRun`), or 1. */
1118
+ const elbows = sp.zigzagRun ? Math.max(1, Math.round(sp.zigzagRun / L)) : 1;
1119
+ const weep = weepOf(sp);
1120
+ const target = Math.round(FINE_NODES * (1 - WHIP_NODES * weep));
1121
+ const cap = 2 * target + 600;
1122
+ // The crown its leaves keep to, its outline drawn in by a clump's room: its lobes, and the heights it spans.
1123
+ const lobes = new Lobes(sp.lobes ?? 0, rng);
1124
+ const side = 1.2 * clumpR;
1125
+ const lo = base + Math.min(0.25 * clumpR, 0.2 * depth);
1126
+ const hi = H - Math.min(1.05 * clumpR, 0.3 * depth);
1127
+ const mid = base + 0.5 * depth;
1128
+ const widthAt = outlineOf(sp, size, liftTo);
1129
+ // (In a stand, only where its neighbours leave it light enough to live: `liveAt`, below.)
1130
+ let liveAt = null;
1131
+ const inCrown = (x, y, z) => {
1132
+ if (y < lo || y > hi)
1133
+ return false;
1134
+ const wd = widthAt(y) * lobes.reach(x / R, (y - mid) / (0.5 * depth), z / R) - side;
1135
+ return wd > 0 && x * x + z * z <= wd * wd && (!liveAt || liveAt(x, y, z));
1136
+ };
1137
+ // The voxels: shadow in each, and whether each is in the crown.
1138
+ const vs = L;
1139
+ const nx = Math.ceil((2 * R) / vs) + 7;
1140
+ const nz = nx;
1141
+ const skip = under(vs);
1142
+ const ny = Math.ceil(H / vs) + 6 - skip;
1143
+ const ox = -0.5 * nx * vs;
1144
+ const oz = ox;
1145
+ const oy = (skip - 2) * vs;
1146
+ const shadow = new Float64Array(nx * ny * nz);
1147
+ const room = new Uint8Array(nx * ny * nz);
1148
+ const full = LIGHT_FULL + LIGHT_OPEN * sp.openness;
1149
+ // In a stand: its light in each voxel, as its own crown leaves it (standLightOf). Where it is too dark for
1150
+ // leaves to pay for themselves, the crown does not grow at all (its lower branches there died young and
1151
+ // were shed long ago: a wood cleans its trees' boles), except in the top of the tree, which a tree keeps
1152
+ // however closed its wood; and the rest is shaded by it, STAND_SHADE layers of the crown's own where its
1153
+ // neighbours hide all of the sky the place has, so its buds turn to the open side. It does
1154
+ // not move as the tree grows.
1155
+ const standAt = stand ? standLightOf(sp, stand, size) : null;
1156
+ const standShadow = new Float64Array(standAt ? nx * ny * nz : 0);
1157
+ const standAlive = new Uint8Array(standAt ? nx * ny * nz : 0);
1158
+ if (standAt) {
1159
+ const alive = standAlive;
1160
+ const keepTop = H * (1 - STAND_LIVE_LEAST);
1161
+ // (Worked out at every third voxel each way and shared by the 27 about it: it changes slowly.)
1162
+ const share = new Float32Array(nx * ny * nz);
1163
+ for (let iy = 0; iy < ny; iy += 3)
1164
+ for (let iz = 0; iz < nz; iz += 3)
1165
+ for (let ix = 0; ix < nx; ix += 3) {
1166
+ const l = standAt(ox + (ix + 1.5) * vs, oy + (iy + 1.5) * vs, oz + (iz + 1.5) * vs);
1167
+ for (let a = iy; a < Math.min(ny, iy + 3); a++)
1168
+ for (let b = iz; b < Math.min(nz, iz + 3); b++)
1169
+ for (let d = ix; d < Math.min(nx, ix + 3); d++) {
1170
+ const c = d + nx * (b + nz * a);
1171
+ share[c] = l;
1172
+ // (In its top it lives in half the light: but not on an edge's dark side, nor deep in the dark.)
1173
+ alive[c] = l >= STAND_LIVE || (oy + (a + 0.5) * vs >= keepTop && l >= 0.5 * STAND_LIVE) ? 1 : 0;
1174
+ }
1175
+ }
1176
+ // (The shadow is the stand's light beside the best lit at the same height: it turns buds to the open
1177
+ // side, and darkens nothing where the stand is even all round; the dark below is `alive`'s.)
1178
+ for (let iy = 0; iy < ny; iy++) {
1179
+ const layer = nx * nz * iy;
1180
+ let best = 1e-3;
1181
+ for (let c = layer; c < layer + nx * nz; c++)
1182
+ best = Math.max(best, share[c]);
1183
+ for (let c = layer; c < layer + nx * nz; c++)
1184
+ standShadow[c] = STAND_SHADE * full * (1 - share[c] / best);
1185
+ }
1186
+ const cellOf = (x, y, z) => {
1187
+ const ix = Math.min(nx - 1, Math.max(0, Math.floor((x - ox) / vs)));
1188
+ const iy = Math.min(ny - 1, Math.max(0, Math.floor((y - oy) / vs)));
1189
+ const iz = Math.min(nz - 1, Math.max(0, Math.floor((z - oz) / vs)));
1190
+ return ix + nx * (iz + nz * iy);
1191
+ };
1192
+ liveAt = (x, y, z) => alive[cellOf(x, y, z)] === 1;
1193
+ }
1194
+ for (let iy = 0; iy < ny; iy++) {
1195
+ const y = oy + (iy + 0.5) * vs;
1196
+ if (y < lo || y > hi)
1197
+ continue;
1198
+ for (let iz = 0; iz < nz; iz++)
1199
+ for (let ix = 0; ix < nx; ix++) {
1200
+ if (inCrown(ox + (ix + 0.5) * vs, y, oz + (iz + 0.5) * vs))
1201
+ room[ix + nx * (iz + nz * iy)] = 1;
1202
+ }
1203
+ }
1204
+ // (Where the live crown starts: its base, unless a stand has lifted it.)
1205
+ let liveLow = Infinity;
1206
+ for (let c = 0; c < room.length && liveAt; c++)
1207
+ if (room[c])
1208
+ liveLow = Math.min(liveLow, oy + (Math.floor(c / (nx * nz)) + 0.5) * vs);
1209
+ if (!Number.isFinite(liveLow))
1210
+ liveLow = lo;
1211
+ const fall = new Float64Array(SHADOW_DEPTH + 1);
1212
+ for (let q = 0; q <= SHADOW_DEPTH; q++)
1213
+ fall[q] = SHADOW_A * SHADOW_B ** -q;
1214
+ const voxel = (x, y, z) => {
1215
+ const ix = Math.floor((x - ox) / vs);
1216
+ const iy = Math.floor((y - oy) / vs);
1217
+ const iz = Math.floor((z - oz) / vs);
1218
+ if (ix < 0 || iy < 0 || iz < 0 || ix >= nx || iy >= ny || iz >= nz)
1219
+ return -1;
1220
+ return ix + nx * (iz + nz * iy);
1221
+ };
1222
+ const shade = (x, y, z, sign) => {
1223
+ const ix = Math.floor((x - ox) / vs);
1224
+ const iy = Math.floor((y - oy) / vs);
1225
+ const iz = Math.floor((z - oz) / vs);
1226
+ if (ix < 0 || iz < 0 || ix >= nx || iz >= nz || iy < 0 || iy >= ny)
1227
+ return;
1228
+ for (let q = 0; q <= SHADOW_DEPTH; q++) {
1229
+ const ly = iy - q;
1230
+ if (ly < 0)
1231
+ break;
1232
+ const amt = sign * fall[q];
1233
+ const x0 = Math.max(0, ix - q);
1234
+ const x1 = Math.min(nx - 1, ix + q);
1235
+ const z0 = Math.max(0, iz - q);
1236
+ const z1 = Math.min(nz - 1, iz + q);
1237
+ for (let zz = z0; zz <= z1; zz++) {
1238
+ const row = nx * (zz + nz * ly);
1239
+ for (let xx = x0; xx <= x1; xx++)
1240
+ shadow[row + xx] += amt;
1241
+ }
1242
+ }
1243
+ };
1244
+ const lightAt = (x, y, z) => {
1245
+ const c = voxel(x, y, z);
1246
+ // (In a stand, a bud where no crown lives is in the dark: it gets nothing, and gives its branch nothing.)
1247
+ if (standAt && c >= 0 && !standAlive[c])
1248
+ return 0;
1249
+ const s = c < 0 ? 0 : shadow[c] + (standAt ? standShadow[c] : 0);
1250
+ return Math.min(1, Math.max(0, (full - s + SHADOW_A) / full));
1251
+ };
1252
+ // What a bud sees: the voxels two round it, within its cone. The least shaded three of them in the crown
1253
+ // give the way to the light (straight on, where they are alike), as the mean of their directions.
1254
+ // (As typed arrays, each with its voxel offset: this is asked at every internode grown, and was a sixth of a
1255
+ // crown's growing. Only those its way's cell may see are tested: SEEN_BUCKETS.)
1256
+ const seenN = SEEN_N;
1257
+ const seenA = new Int32Array(seenN);
1258
+ const seenB = new Int32Array(seenN);
1259
+ const seenC = new Int32Array(seenN);
1260
+ const seenX = new Float64Array(seenN);
1261
+ const seenY = new Float64Array(seenN);
1262
+ const seenZ = new Float64Array(seenN);
1263
+ const seenAt = new Int32Array(seenN);
1264
+ for (let q = 0; q < seenN; q++) {
1265
+ seenA[q] = SEEN[6 * q];
1266
+ seenB[q] = SEEN[6 * q + 1];
1267
+ seenC[q] = SEEN[6 * q + 2];
1268
+ seenX[q] = SEEN[6 * q + 3];
1269
+ seenY[q] = SEEN[6 * q + 4];
1270
+ seenZ[q] = SEEN[6 * q + 5];
1271
+ seenAt[q] = seenA[q] + nx * (seenC[q] + nz * seenB[q]);
1272
+ }
1273
+ const toLight = [0, 0, 0];
1274
+ const best = new Float64Array(3);
1275
+ const bestAt = new Int32Array(3);
1276
+ const lean = 0.05 * SHADOW_A;
1277
+ const lookForLight = (x, y, z, d) => {
1278
+ const ix = Math.floor((x - ox) / vs);
1279
+ const iy = Math.floor((y - oy) / vs);
1280
+ const iz = Math.floor((z - oz) / vs);
1281
+ // (Two voxels clear of the grid's sides every way: none of what it sees is off the grid.)
1282
+ const inside = ix >= 2 && iy >= 2 && iz >= 2 && ix < nx - 2 && iy < ny - 2 && iz < nz - 2;
1283
+ const here = ix + nx * (iz + nz * iy);
1284
+ const d0 = d[0];
1285
+ const d1 = d[1];
1286
+ const d2 = d[2];
1287
+ let b0 = Infinity;
1288
+ let b1 = Infinity;
1289
+ let b2 = Infinity;
1290
+ let a0 = -1;
1291
+ let a1 = -1;
1292
+ let a2 = -1;
1293
+ const cands = SEEN_BUCKETS[seenCell(d0, d1, d2)];
1294
+ for (let q = 0; q < cands.length; q++) {
1295
+ const k = cands[q];
1296
+ const dot = seenX[k] * d0 + seenY[k] * d1 + seenZ[k] * d2;
1297
+ if (dot < PERCEIVE)
1298
+ continue;
1299
+ let c;
1300
+ if (inside)
1301
+ c = here + seenAt[k];
1302
+ else {
1303
+ const jx = ix + seenA[k];
1304
+ const jy = iy + seenB[k];
1305
+ const jz = iz + seenC[k];
1306
+ if (jx < 0 || jy < 0 || jz < 0 || jx >= nx || jy >= ny || jz >= nz)
1307
+ continue;
1308
+ c = jx + nx * (jz + nz * jy);
1309
+ }
1310
+ if (!room[c])
1311
+ continue;
1312
+ const score = shadow[c] + (standAt ? standShadow[c] : 0) - lean * dot;
1313
+ // (Kept in order, least first.)
1314
+ if (score >= b2)
1315
+ continue;
1316
+ if (score < b1) {
1317
+ b2 = b1;
1318
+ a2 = a1;
1319
+ if (score < b0) {
1320
+ b1 = b0;
1321
+ a1 = a0;
1322
+ b0 = score;
1323
+ a0 = k;
1324
+ }
1325
+ else {
1326
+ b1 = score;
1327
+ a1 = k;
1328
+ }
1329
+ }
1330
+ else {
1331
+ b2 = score;
1332
+ a2 = k;
1333
+ }
1334
+ }
1335
+ if (a0 < 0)
1336
+ return false;
1337
+ best[0] = b0;
1338
+ bestAt[0] = a0;
1339
+ bestAt[1] = a1;
1340
+ bestAt[2] = a2;
1341
+ let sx = 0;
1342
+ let sy = 0;
1343
+ let sz = 0;
1344
+ for (let j = 0; j < 3; j++) {
1345
+ const k = bestAt[j];
1346
+ if (k < 0)
1347
+ break;
1348
+ sx += seenX[k];
1349
+ sy += seenY[k];
1350
+ sz += seenZ[k];
1351
+ }
1352
+ const l = Math.hypot(sx, sy, sz);
1353
+ toLight[0] = sx / l;
1354
+ toLight[1] = sy / l;
1355
+ toLight[2] = sz / l;
1356
+ return true;
1357
+ };
1358
+ // The wood as it grows. Each node ends an internode, and bears a terminal bud (until it grows on or dies)
1359
+ // and a lateral bud (until it grows out or dies); its main child goes on its axis, its lateral child
1360
+ // starts a new one.
1361
+ const px = new Float64Array(cap);
1362
+ const py = new Float64Array(cap);
1363
+ const pz = new Float64Array(cap);
1364
+ const dx = new Float64Array(cap);
1365
+ const dy = new Float64Array(cap);
1366
+ const dz = new Float64Array(cap);
1367
+ /** Each node's turn as it grew (its wandering and its turning to the light), handed on to its next internode. */
1368
+ const tw = new Float64Array(cap * 3);
1369
+ const par = new Int32Array(cap);
1370
+ const main = new Int32Array(cap);
1371
+ const lat = new Int32Array(cap);
1372
+ /** 0 a stem, 1 a scaffold, 2 a shoot. */
1373
+ const kind = new Uint8Array(cap);
1374
+ const alive = new Uint8Array(cap);
1375
+ const tBud = new Uint8Array(cap);
1376
+ const lBud = new Uint8Array(cap);
1377
+ /** A V-fork (`forkStems`): its two arms share what it is given by the light each gathers, neither favoured. */
1378
+ const even = new Uint8Array(cap);
1379
+ const az = new Float64Array(cap);
1380
+ /** Which of a forked trunk's or a clump's stems a node is on (-1: the trunk under them, or a tree of one stem). */
1381
+ const owner = new Int8Array(cap).fill(-1);
1382
+ /** How many nodes along its axis a node is: which of its axis's buds it bears, for opposite or two-ranked buds. */
1383
+ const rank = new Int32Array(cap);
1384
+ const phyllo = sp.phyllotaxis ?? "spiral";
1385
+ const light = new Float64Array(cap);
1386
+ const gathered = new Float64Array(cap);
1387
+ const internodes = new Int32Array(cap);
1388
+ const pipes = new Float64Array(cap);
1389
+ const shedPipes = new Float64Array(cap);
1390
+ const vIn = new Float64Array(cap);
1391
+ const vT = new Float64Array(cap);
1392
+ const vL = new Float64Array(cap);
1393
+ let count = 0;
1394
+ let living = 0;
1395
+ const roots = [];
1396
+ const add = (x, y, z, parent, onAxis, k, d) => {
1397
+ const i = count++;
1398
+ px[i] = x;
1399
+ py[i] = y;
1400
+ pz[i] = z;
1401
+ dx[i] = d[0];
1402
+ dy[i] = d[1];
1403
+ dz[i] = d[2];
1404
+ par[i] = parent;
1405
+ owner[i] = parent >= 0 ? owner[parent] : -1;
1406
+ main[i] = -1;
1407
+ lat[i] = -1;
1408
+ kind[i] = k;
1409
+ alive[i] = 1;
1410
+ living++;
1411
+ tBud[i] = 0;
1412
+ lBud[i] = y >= base ? 1 : 0;
1413
+ if (parent >= 0) {
1414
+ if (onAxis)
1415
+ main[parent] = i;
1416
+ else
1417
+ lat[parent] = i;
1418
+ rank[i] = onAxis ? rank[parent] + 1 : 0;
1419
+ // (Round its axis: by the golden angle; opposite pairs crossed, one of each grown (a half turn, then a
1420
+ // quarter back); two ranks, a half turn each, starting square to the shoot's plane, so its laterals lie
1421
+ // in a flat fan either side of it.)
1422
+ az[i] = onAxis
1423
+ ? az[parent] + (phyllo === "opposite" ? (rank[i] % 2 === 1 ? Math.PI : -0.5 * Math.PI) : phyllo === "distichous" ? Math.PI : GOLDEN_ANGLE)
1424
+ : phyllo === "distichous"
1425
+ ? (rng.chance(0.5) ? 0 : Math.PI)
1426
+ : rng.range(0, 2 * Math.PI);
1427
+ }
1428
+ else
1429
+ roots.push(i);
1430
+ shade(x, y, z, 1);
1431
+ return i;
1432
+ };
1433
+ const dirOf = (i) => [dx[i], dy[i], dz[i]];
1434
+ /**
1435
+ * A spine laid out ahead of growing (a scaffold, a leader, a shrub's stem): from a node along a way that
1436
+ * turns as `way(s)` says (s, metres along it), an internode at a time, until it leaves the crown (once it
1437
+ * has been in it) or has gone `most` metres. Returns its nodes' places.
1438
+ */
1439
+ const spine = (from, way, most, keep) => {
1440
+ const pts = [];
1441
+ let x = px[from];
1442
+ let y = py[from];
1443
+ let z = pz[from];
1444
+ let entered = inCrown(x, y, z);
1445
+ for (let s = 0; s < most; s += L) {
1446
+ const d = way(s);
1447
+ const nx2 = x + d[0] * L;
1448
+ const ny2 = y + d[1] * L;
1449
+ const nz2 = z + d[2] * L;
1450
+ if (inCrown(nx2, ny2, nz2) && (!keep || keep(nx2, nz2)))
1451
+ entered = true;
1452
+ // (In a stand, a spine that has found no live crown by the crown's edge never will.)
1453
+ else if (entered || ny2 < 0 || (liveAt && nx2 * nx2 + nz2 * nz2 > R * R))
1454
+ break;
1455
+ x = nx2;
1456
+ y = ny2;
1457
+ z = nz2;
1458
+ pts.push(x, y, z);
1459
+ }
1460
+ return pts;
1461
+ };
1462
+ const lay = (from, pts, keep, k, onAxis) => {
1463
+ let at = from;
1464
+ for (let j = 0; j < keep; j++) {
1465
+ const x = pts[3 * j];
1466
+ const y = pts[3 * j + 1];
1467
+ const z = pts[3 * j + 2];
1468
+ const d = norm([x - px[at], y - py[at], z - pz[at]]);
1469
+ at = add(x, y, z, at, j > 0 || onAxis, k, d);
1470
+ }
1471
+ if (keep > 0)
1472
+ tBud[at] = 1;
1473
+ return at;
1474
+ };
1475
+ // The stems. One for a tree; for a shrub or a stool, several from feet spread within a third of the
1476
+ // crown, leaning out from it.
1477
+ const stems = Math.max(1, Math.round(sp.stems));
1478
+ const scaffolds = scaffoldCount(sp);
1479
+ // (A forked trunk's or a clump's stems share the crown: each the part of it nearer the middle of its own
1480
+ // share than of another's, by a little. Their middles, out from the axis, are laid with the stems.)
1481
+ const shareX = [];
1482
+ const shareZ = [];
1483
+ const overlap = SHARE_OVERLAP * R;
1484
+ const owns = (k, x, z) => {
1485
+ for (let j = 0; j < shareX.length; j++) {
1486
+ if (j === k)
1487
+ continue;
1488
+ const ux = shareX[k] - shareX[j];
1489
+ const uz = shareZ[k] - shareZ[j];
1490
+ const l = Math.hypot(ux, uz);
1491
+ if (l < 1e-6)
1492
+ continue;
1493
+ if (((x - 0.5 * (shareX[k] + shareX[j])) * ux + (z - 0.5 * (shareZ[k] + shareZ[j])) * uz) / l < -overlap)
1494
+ return false;
1495
+ }
1496
+ return true;
1497
+ };
1498
+ const turn = rng.range(0, 2 * Math.PI);
1499
+ for (let s = 0; s < stems; s++) {
1500
+ const azs = turn + s * GOLDEN_ANGLE + rng.range(-0.3, 0.3);
1501
+ if (stems > 1) {
1502
+ // A shrub's stem: from its foot, leaning out, turning up by its bend, through the crown to its edge.
1503
+ const rr = (R / 3) * Math.sqrt((s + 0.5) / stems);
1504
+ const lean = Math.min(0.5 * sp.branchAngle * DEG, Math.atan(Math.max(0, 0.6 * R - rr) / Math.max(L, 0.5 * depth)));
1505
+ const foot = add(rr * Math.cos(azs), 0, rr * Math.sin(azs), -1, true, 0, [0, 1, 0]);
1506
+ const e0 = 0.5 * Math.PI - lean * rng.range(0.6, 1.2);
1507
+ const sway = SCAFFOLD_SWAY * sp.crooked * rng.range(-1, 1);
1508
+ const pts = spine(foot, (u) => {
1509
+ const f = u / Math.max(L, R);
1510
+ const e = Math.min(0.5 * Math.PI, e0 + 0.5 * sp.bend * SCAFFOLD_CURVE * f);
1511
+ const a = azs + sway * Math.sin(Math.PI * Math.min(1, f));
1512
+ return [Math.cos(e) * Math.cos(a), Math.sin(e), Math.cos(e) * Math.sin(a)];
1513
+ }, 2 * (H + R));
1514
+ lay(foot, pts, Math.max(1, Math.round((pts.length / 3) * rng.range(0.75, 1))), 0, true);
1515
+ continue;
1516
+ }
1517
+ /** The scaffolds to lay: where each leaves, and (a forked stem's) which way and at what angle from upright. */
1518
+ const holds = [];
1519
+ // (A stone pine's stem divides in V-forks; a forked trunk's or a clump's stems are trunks of their own.)
1520
+ const vFork = form.stems > 1 && sp.forkSplits !== undefined;
1521
+ // (Not a crown grown narrow, in a wood: its stem's limbs leave it one by one, rising steeply, as any tree's.)
1522
+ if (vFork && !liveAt && R / depth >= NARROW) {
1523
+ // A stem that divides at its fork into a few stems, each dividing again in V-forks, rising and then
1524
+ // spreading, their last arms the limbs that reach out under the crown (a stone pine's): its fork a share
1525
+ // of the way to its crown's base, its stem sinuous or leaning a little on the way, as crooked as it is.
1526
+ const yF = forkHeight(sp, size, form);
1527
+ const lean = rng.range(0, 2 * Math.PI);
1528
+ // (No further aside than its crown leaves room for its arms: `reachOut`.)
1529
+ // (Its inside where its arms end, a share FORK_INTO into its crown: a domed crown is narrow at its foot.)
1530
+ const inner = Math.max(0.05, widthAt(Math.min(hi, base + FORK_INTO * depth)) * (1 - LOBE_DEPTH * Math.min(1, Math.max(0, sp.lobes ?? 0))) - side);
1531
+ const sway = Math.min(STEM_SWAY * sp.crooked * yF, FORK_SWAY_ROOM * inner) * rng.range(0.6, 1);
1532
+ const wave = rng.range(0.7, 1.1);
1533
+ const steps = Math.max(2, Math.ceil(yF / TRUNK_STEP));
1534
+ let at = add(0, 0, 0, -1, true, 0, [0, 1, 0]);
1535
+ lBud[at] = 0;
1536
+ const stemAt = (y) => {
1537
+ const o = sway * Math.sin(Math.PI * wave * (y / yF));
1538
+ return [o * Math.cos(lean), y, o * Math.sin(lean)];
1539
+ };
1540
+ // (Its stems leave it a little apart up it: a node has one stem to go on and one to put out, so a third
1541
+ // or fourth leaves a little below the others.)
1542
+ const n = form.stems;
1543
+ const below = [];
1544
+ for (let k = 1; k <= steps; k++) {
1545
+ const y = (yF * k) / steps;
1546
+ const q = stemAt(y);
1547
+ at = add(q[0], q[1], q[2], at, true, 0, norm([q[0] - px[at], q[1] - py[at], q[2] - pz[at]]));
1548
+ lBud[at] = 0;
1549
+ }
1550
+ for (let k = 2; k < n; k++) {
1551
+ below.push(at);
1552
+ const q = stemAt(yF);
1553
+ at = add(q[0], py[at] + FORK_APART, q[2], at, true, 0, [0, 1, 0]);
1554
+ lBud[at] = 0;
1555
+ }
1556
+ const top = at;
1557
+ even[top] = 1;
1558
+ for (const b of below)
1559
+ even[b] = 1;
1560
+ const az0 = rng.range(0, 2 * Math.PI);
1561
+ const splits = Math.max(0, Math.round(sp.forkSplits ?? 1));
1562
+ // (Its first arms as long as rise, with the arms after them, from its fork a little into its crown.)
1563
+ let levels = 0;
1564
+ for (let q = 0; q <= splits; q++)
1565
+ levels += FORK_SHORTER ** q;
1566
+ /** The most an arm `len` long may lean (from upright): its share of how far out they all may. */
1567
+ // (Its arms' ends within the crown's inside, where its limbs may grow: in a narrow crown, its reach out from
1568
+ // its stem's sway, within FORK_ROOM of the room a clump leaves at its side. Reaching its kind's share of the
1569
+ // crown's radius, a narrow crown's arms all ended outside it, and their limbs grew no leaves.)
1570
+ const reachOut = Math.min(FORK_REACH * R, Math.max(0.05, FORK_ROOM * inner - Math.abs(sway)));
1571
+ const most = (len) => Math.asin(Math.min(1, reachOut / (splits + 1) / Math.max(len, 1e-3)));
1572
+ // (How far they rise, each level as steep as it may lean: in a narrow crown its arms are held nearer upright
1573
+ // than their kind's lean, and reckoned at that lean they rose out of the top of a short crown on a tall stem,
1574
+ // its limbs all above it and not a leaf on them.)
1575
+ const rise = Math.max(0.5, base - yF) + FORK_INTO * depth;
1576
+ let first = rise / (levels * Math.cos(0.5 * (FORK_TILT[0] + FORK_TILT[1]) + FORK_TILT_STEP));
1577
+ for (let pass = 0; pass < 4; pass++) {
1578
+ let up = 0;
1579
+ for (let q = 0; q <= splits; q++) {
1580
+ const len = first * FORK_SHORTER ** q;
1581
+ up += len * Math.cos(Math.min(0.5 * (FORK_TILT[0] + FORK_TILT[1]) + q * FORK_TILT_STEP, most(len)) + 0.25 * FORK_TILT_STEP);
1582
+ }
1583
+ first *= rise / Math.max(1e-3, up);
1584
+ }
1585
+ let scaffold = 0;
1586
+ /** A piece of fork from `from`, `len` metres at `tilt` from upright round `a`, wandering; then its V-fork, or its limb. */
1587
+ const arm = (from, onAxis, a, lean, len, left) => {
1588
+ const tilt = Math.min(lean, most(len));
1589
+ const m = Math.max(2, Math.round(len / L));
1590
+ let node = from;
1591
+ let we = 0;
1592
+ let wa = 0;
1593
+ for (let j = 0; j < m; j++) {
1594
+ we = LIMB_KEEP * we + FORK_WANDER * sp.crooked * rng.gauss();
1595
+ wa = LIMB_KEEP * wa + FORK_WANDER * sp.crooked * rng.gauss();
1596
+ // (It rises, then leans out further along it: a V-fork's arms spread as they go.)
1597
+ const e = 0.5 * Math.PI - Math.max(4 * DEG, Math.min(80 * DEG, tilt + 0.5 * FORK_TILT_STEP * (j / m) + we));
1598
+ const d = [Math.cos(e) * Math.cos(a + wa), Math.sin(e), Math.cos(e) * Math.sin(a + wa)];
1599
+ // (Bare below its crown; in it, its buds put out shoots as a limb's do.)
1600
+ // (And however it wanders, no further out than its crown's inside leaves room for, FORK_ROOM of it: wandering
1601
+ // up a tall stem to a short crown, its arms ended outside the crown.)
1602
+ let ax = px[node] + d[0] * (len / m);
1603
+ let az = pz[node] + d[2] * (len / m);
1604
+ const out = Math.hypot(ax, az);
1605
+ if (out > FORK_ROOM * inner) {
1606
+ ax *= (FORK_ROOM * inner) / out;
1607
+ az *= (FORK_ROOM * inner) / out;
1608
+ }
1609
+ node = add(ax, py[node] + d[1] * (len / m), az, node, j > 0 || onAxis, 1, d);
1610
+ }
1611
+ const t = tilt + FORK_TILT_STEP;
1612
+ if (left <= 0) {
1613
+ holds.push({ node, scaffold: scaffold++, az: a + wa, angle: t + FORK_TILT_STEP });
1614
+ return;
1615
+ }
1616
+ // (A V-fork: the arm that goes on steeper, the other swung out wider and leaning further.)
1617
+ even[node] = 1;
1618
+ const swing = FORK_SWING * rng.range(0.7, 1.2) * (rng.chance(0.5) ? 1 : -1);
1619
+ arm(node, true, a + wa - 0.4 * swing, t - 0.7 * FORK_TILT_STEP, len * FORK_SHORTER * rng.range(0.85, 1.15), left - 1);
1620
+ arm(node, false, a + wa + 0.6 * swing, t + 0.5 * FORK_TILT_STEP, len * FORK_SHORTER * rng.range(0.85, 1.15), left - 1);
1621
+ };
1622
+ const nodes = [top, top, ...below];
1623
+ for (let k = 0; k < n; k++) {
1624
+ const a = az0 + (k * 2 * Math.PI) / n + rng.range(-0.3, 0.3);
1625
+ const tilt = rng.range(FORK_TILT[0], FORK_TILT[1]);
1626
+ // (Some stems divide once less: not every arm of an old pine forked as often.)
1627
+ const more = splits - (k > 0 && rng.chance(0.3) ? 1 : 0);
1628
+ arm(nodes[k], k === 0, a, tilt, first * rng.range(0.85, 1.15), more);
1629
+ }
1630
+ }
1631
+ else if (form.stems > 1 && !vFork) {
1632
+ // A trunk that forks into a few stems (`forkShare`; near the ground, its stems rising from one root
1633
+ // plate and leaning apart from it), or a clump of stems from one root plate (`stemShare`): each a tree's
1634
+ // stem of its own, leaning out from where they part and turning up, its leader in the middle of its own
1635
+ // share of the crown, its great limbs round it and out over its share (crowns that touch, not one
1636
+ // blob: Leonardo's tree is one crown however many its stems).
1637
+ const n = form.stems;
1638
+ const yF = forkHeight(sp, size, form);
1639
+ // (Its stems part a little apart: under breast height downwards from the fork, over it upwards, so a
1640
+ // trunk is measured there as one trunk or as its stems.)
1641
+ const apart = Math.min(FORK_APART, 0.12 * yF);
1642
+ const yLow = yF >= breastHeight(size) ? yF : yF - apart * (n - 2);
1643
+ let at = add(0, 0, 0, -1, true, 0, [0, 1, 0]);
1644
+ lBud[at] = 0;
1645
+ // (A leaning tree's trunk, `lean`, leans under its fork, easing upright to it.)
1646
+ const leaning = leanOf(sp, liveAt !== null, way, yLow, R, depth);
1647
+ const steps = Math.max(1, Math.ceil(yLow / TRUNK_STEP));
1648
+ for (let k = 1; k <= steps; k++) {
1649
+ const y = (yLow * k) / steps;
1650
+ const o = leaning.at(y);
1651
+ at = add(o[0], y, o[1], at, true, 0, norm([o[0] - px[at], y - py[at], o[1] - pz[at]]));
1652
+ lBud[at] = 0;
1653
+ }
1654
+ const below = [];
1655
+ for (let k = 2; k < n; k++) {
1656
+ below.push(at);
1657
+ at = add(0, py[at] + apart, 0, at, true, 0, [0, 1, 0]);
1658
+ lBud[at] = 0;
1659
+ }
1660
+ even[at] = 1;
1661
+ for (const b of below)
1662
+ even[b] = 1;
1663
+ const from = [at, at, ...below];
1664
+ const az0 = rng.range(0, 2 * Math.PI);
1665
+ // (Its share's middle: out from the axis, the further the more stems share the crown.)
1666
+ const out = TRUNK_SHARE[Math.min(4, n)] * R;
1667
+ const azOf = [];
1668
+ for (let k = 0; k < n; k++) {
1669
+ const a = az0 + (k * 2 * Math.PI) / n + rng.range(-0.25, 0.25);
1670
+ const d = out * rng.range(0.85, 1.15);
1671
+ azOf.push(a);
1672
+ shareX.push(d * Math.cos(a));
1673
+ shareZ.push(d * Math.sin(a));
1674
+ }
1675
+ // (How far a stem may lean where it leaves: an excurrent tree's stems rise nearly upright, a decurrent
1676
+ // one's lean out.)
1677
+ const tiltMost = TRUNK_TILT[0] + (TRUNK_TILT[1] - TRUNK_TILT[0]) * (1 - sp.leader);
1678
+ const span = Math.min(0.8, SCAFFOLD_SPAN + SCAFFOLD_SPAN_LEADER * sp.leader);
1679
+ const each = Math.max(2, Math.round(scaffolds / Math.sqrt(n)));
1680
+ const cover = Math.min(1, TRUNK_COVER / n);
1681
+ for (let k = 0; k < n; k++) {
1682
+ const a = azOf[k];
1683
+ const d = Math.hypot(shareX[k], shareZ[k]);
1684
+ const yLo = Math.max(base + SCAFFOLD_FROM * depth, liveAt ? liveLow : 0, yF + L);
1685
+ const yHi = liveAt ? Math.max(yLo + L, yLo + span * (H - yLo)) : Math.max(yLo + L, base + span * depth);
1686
+ const top = Math.max(yHi + L, yHi + Math.min(1, LEADER_REACH + (1 - LEADER_REACH) * sp.leader) * (hi - L - yHi));
1687
+ // Its way out: from where it leaves, out to its share's middle by its leader's top, leaning out most
1688
+ // at first and turning up (1 - (1 - t)^p), no more than it may lean where it leaves.
1689
+ const rise = Math.max(L, top - yF);
1690
+ const p = Math.min(TRUNK_CURVE, Math.max(1, (Math.tan(tiltMost) * rise) / Math.max(1e-3, d)));
1691
+ // (Eased in over its first few trunk radii, as are its stepping aside to its own side of the trunk and
1692
+ // the wandering it starts with: a trunk bent harder than its thickness folds over on itself.)
1693
+ const ramp = Math.max(STEM_EASE_LEAST, STEM_EASE * size.trunkRadius);
1694
+ // (Its step aside: out to where its outer side is the trunk's where they part (the trunk there its
1695
+ // stems' areas together, a stem its share), taken over its first piece.)
1696
+ const first0 = stemFirst(size);
1697
+ const trunkAt = (size.trunkRadius * boleShape(size, yF, sp.buttress ?? 0)) / boleShape(size, breastHeight(size), sp.buttress ?? 0);
1698
+ const aside = Math.max(0, trunkAt * (1 - 1 / Math.sqrt(n)));
1699
+ const slope = (y) => {
1700
+ const t = Math.min(1, Math.max(0, (y - yF) / rise));
1701
+ const u = Math.min(1, Math.max(0, (y - yF) / ramp));
1702
+ const s = (y - yF) / Math.max(first0, 1e-4);
1703
+ const stepOut = s > 0 && s < 1 ? (aside / Math.max(first0, 1e-4)) * 6 * s * (1 - s) : 0;
1704
+ return ((d * p * (1 - t) ** (p - 1)) / rise) * u * u * (3 - 2 * u) + stepOut;
1705
+ };
1706
+ const marks = [];
1707
+ for (let j = 0; j < each; j++)
1708
+ marks.push(yLo + ((j + rng.range(0.15, 0.85)) / each) * (yHi - yLo));
1709
+ const levels = [];
1710
+ // (A curved shoulder leaving the fork smoothly over `first0`, then pieces close enough to draw its easing out as a curve.)
1711
+ for (const y of [0.5 * first0, first0, ...[0.4, 0.7, 1].map((f) => f * ramp).filter((y) => y > first0 + 0.1)])
1712
+ if (yF + y < yLo - 0.1)
1713
+ levels.push({ y: yF + y, scaffold: y < first0 ? -2 : -1 });
1714
+ const from0 = levels.length > 0 ? levels[levels.length - 1].y : yF;
1715
+ const rest = Math.max(1, Math.ceil((yLo - from0) / TRUNK_STEP));
1716
+ for (let j = 1; j < rest; j++)
1717
+ levels.push({ y: from0 + ((yLo - from0) * j) / rest, scaffold: -1 });
1718
+ const section = marks.map((y, j) => ({ y, scaffold: j }));
1719
+ for (let y = yLo; y <= yHi + 1e-9; y += L)
1720
+ if (marks.every((m) => Math.abs(m - y) > 0.4 * L))
1721
+ section.push({ y, scaffold: -1 });
1722
+ section.sort((u, v) => u.y - v.y);
1723
+ levels.push(...section);
1724
+ let node = from[k];
1725
+ let wx = 0;
1726
+ let wz = 0;
1727
+ let first = true;
1728
+ const phase = rng.range(0, 2 * Math.PI);
1729
+ // (A leaning kind's, `lean`: its stems wander as its trunk leans.)
1730
+ const bowOut = (sp.lean ?? 0) > 0 && !liveAt ? Math.min(STEM_BOW * sp.crooked * (top - yF), STEM_BOW_ROOM * R) : 0;
1731
+ for (const lv of levels) {
1732
+ // (Its stems stand side by side in the trunk where they part, each stepping out from its middle to its
1733
+ // own side: so a stem's outer side runs on from the trunk's, and they part in a crotch between them.)
1734
+ const calm = Math.min(1, Math.max(0, (lv.y - yF) / ramp));
1735
+ if (lv.scaffold !== -2) {
1736
+ const j = rng.onSphere();
1737
+ wx = 0.6 * wx + 0.08 * sp.crooked * j[0] * calm;
1738
+ wz = 0.6 * wz + 0.08 * sp.crooked * j[2] * calm;
1739
+ }
1740
+ const sl = slope(0.5 * (py[node] + lv.y));
1741
+ // (And bows in a long sinuous bend, as crooked as its kind: STEM_BOW. Straight, a sycamore's two stems were poles.)
1742
+ const u = (0.5 * (py[node] + lv.y) - yF) / Math.max(L, top - yF);
1743
+ const bow = (bowOut * Math.PI * Math.cos(Math.PI * 1.5 * u) * 1.5) / Math.max(L, top - yF);
1744
+ const dir = norm([wx + sl * Math.cos(a) + bow * Math.cos(phase), 1, wz + sl * Math.sin(a) + bow * Math.sin(phase)]);
1745
+ const len = (lv.y - py[node]) / dir[1];
1746
+ node = add(px[node] + dir[0] * len, lv.y, pz[node] + dir[2] * len, node, first ? k === 0 : true, 0, dir);
1747
+ if (first)
1748
+ owner[node] = k;
1749
+ first = false;
1750
+ if (lv.scaffold >= 0) {
1751
+ lBud[node] = 0;
1752
+ // (Its great limbs round it and out over its share, few towards the others'.)
1753
+ const off = (((lv.scaffold * GOLDEN_ANGLE + phase) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
1754
+ holds.push({ node, scaffold: lv.scaffold, pos: each > 1 ? lv.scaffold / (each - 1) : 0.5, az: a + cover * (off - Math.PI) + rng.range(-0.2, 0.2), own: k });
1755
+ }
1756
+ else if (lv.y < yLo)
1757
+ lBud[node] = 0;
1758
+ }
1759
+ // Its leader, on up to its top.
1760
+ let lx = 0;
1761
+ let lz = 0;
1762
+ const y0 = py[node];
1763
+ const pts = spine(node, (u) => {
1764
+ const j = rng.onSphere();
1765
+ lx = 0.7 * lx + 0.06 * sp.crooked * j[0] + (stand ? STAND_LEADER * stand.lopsided : 0);
1766
+ lz = 0.7 * lz + 0.06 * sp.crooked * j[2];
1767
+ const sl = slope(y0 + u);
1768
+ return norm([lx + sl * Math.cos(a), 1, lz + sl * Math.sin(a)]);
1769
+ }, Math.max(0, top - y0), (x, z) => owns(k, x, z));
1770
+ node = lay(node, pts, pts.length / 3, 0, true);
1771
+ tBud[node] = 1;
1772
+ }
1773
+ }
1774
+ else {
1775
+ // A tree's trunk: bare to its crown's base, then through the scaffolds' span, one of them at each of
1776
+ // their heights (one in each of as many slots up it), its own lateral buds between.
1777
+ // (In a stand, from where its live crown starts, its wood's shade having lifted it.)
1778
+ // (Or lower, where the species' stem forks (`fork`): its limbs rise bare to its crown.)
1779
+ const vase = vFork ? forkHeight(sp, size, form) : undefined;
1780
+ const yLo = Math.max(vase !== undefined ? vase : base + SCAFFOLD_FROM * depth, liveAt ? liveLow : 0);
1781
+ const span = Math.min(0.8, SCAFFOLD_SPAN + SCAFFOLD_SPAN_LEADER * sp.leader);
1782
+ // (A forked stem's limbs leave it close together, in a vase: its V-forks.)
1783
+ const yHi = liveAt ? Math.max(yLo + L, yLo + span * (H - yLo)) : vase !== undefined ? Math.max(yLo + L, yLo + FORK_SPAN * (base - yLo)) : Math.max(yLo + L, base + span * depth);
1784
+ const levels = [];
1785
+ const below = Math.max(1, Math.ceil(yLo / TRUNK_STEP));
1786
+ for (let k = 1; k < below; k++)
1787
+ levels.push({ y: (yLo * k) / below, scaffold: -1 });
1788
+ const marks = [];
1789
+ for (let k = 0; k < scaffolds; k++)
1790
+ marks.push(yLo + ((k + rng.range(0.15, 0.85)) / scaffolds) * (yHi - yLo));
1791
+ const section = marks.map((y, k) => ({ y, scaffold: k }));
1792
+ for (let y = yLo; y <= yHi + 1e-9; y += L)
1793
+ if (marks.every((m) => Math.abs(m - y) > 0.4 * L))
1794
+ section.push({ y, scaffold: -1 });
1795
+ section.sort((a, b) => a.y - b.y);
1796
+ levels.push(...section);
1797
+ let at = add(0, 0, 0, -1, true, 0, [0, 1, 0]);
1798
+ lBud[at] = 0;
1799
+ let wx = 0;
1800
+ let wz = 0;
1801
+ // (A leaning stem, `lean`, easing upright by where its limbs leave it.)
1802
+ const leaning = leanOf(sp, liveAt !== null, way, Math.max(L, yLo), R, depth);
1803
+ for (const lv of levels) {
1804
+ const j = rng.onSphere();
1805
+ wx = 0.6 * wx + 0.08 * sp.crooked * j[0];
1806
+ wz = 0.6 * wz + 0.08 * sp.crooked * j[2];
1807
+ const sl = leaning.slope(0.5 * (py[at] + lv.y));
1808
+ const d = norm([wx + sl[0], 1, wz + sl[1]]);
1809
+ const len = (lv.y - py[at]) / d[1];
1810
+ at = add(px[at] + d[0] * len, lv.y, pz[at] + d[2] * len, at, true, 0, d);
1811
+ if (lv.scaffold >= 0) {
1812
+ lBud[at] = 0;
1813
+ holds.push({ node: at, scaffold: lv.scaffold });
1814
+ }
1815
+ }
1816
+ // The trunk goes on up the crown as its leader, all the way when it keeps the lead; otherwise part way,
1817
+ // and its bud grows on from there as one more limb.
1818
+ {
1819
+ const top = yHi + Math.min(1, LEADER_REACH + (1 - LEADER_REACH) * sp.leader) * (hi - L - yHi);
1820
+ let lx = 0;
1821
+ let lz = 0;
1822
+ const pts = spine(at, () => {
1823
+ const j = rng.onSphere();
1824
+ lx = 0.7 * lx + 0.06 * sp.crooked * j[0] + (stand ? STAND_LEADER * stand.lopsided : 0);
1825
+ lz = 0.7 * lz + 0.06 * sp.crooked * j[2];
1826
+ return norm([lx, 1, lz]);
1827
+ }, Math.max(0, top - py[at]));
1828
+ at = lay(at, pts, pts.length / 3, 0, true);
1829
+ }
1830
+ tBud[at] = 1;
1831
+ }
1832
+ // The scaffolds, round the trunk by the golden angle, the lowest leaving widest; each turns up (or down)
1833
+ // by the species' bend and arches over by its weight, sways a little, and reaches out to the crown's
1834
+ // outline (some stop a little short).
1835
+ /** A scaffold's turning, a share `f` of the crown's reach along it: the species' curve (and back), or its bend's turn up and its weight's arch over. */
1836
+ const limbTurn = (f) => {
1837
+ if (sp.limbCurve === undefined && sp.limbCurveBack === undefined)
1838
+ return sp.bend * SCAFFOLD_CURVE * f - SCAFFOLD_ARCH * f * f;
1839
+ const c = (sp.limbCurve ?? 0) * DEG;
1840
+ if (sp.limbCurveBack === undefined)
1841
+ return c * Math.min(f, 1.2);
1842
+ return 2 * c * Math.min(f, 0.5) + 2 * sp.limbCurveBack * DEG * Math.min(0.7, Math.max(0, f - 0.5));
1843
+ };
1844
+ for (const h of holds) {
1845
+ const { node, scaffold: k } = h;
1846
+ const pos = h.pos ?? (scaffolds > 1 ? k / (scaffolds - 1) : 0.5);
1847
+ const g = Math.max(-2, Math.min(2, rng.gauss()));
1848
+ // (No wider than the crown has room for: in a crown narrow for its depth (a tree grown in a wood, a
1849
+ // column), the limbs rise steeply, or they would reach its side at once and curl over into hooks.)
1850
+ // (A species that says its limbs' angles keeps them: an alder's short level limbs on its leader, in a
1851
+ // narrow cone, stop at its side.)
1852
+ const room = R / depth < NARROW && !sp.limbAngle ? Math.atan((2.4 * R) / depth) : Math.PI;
1853
+ // (The species' angle at its height in the crown, if it says; else its branch angle, swung wider low.)
1854
+ const want = h.angle !== undefined ? h.angle : sp.limbAngle ? limbAngleAt(sp, (py[node] - base) / depth) + 0.5 * sp.branchAngleSpread * g * DEG : (sp.branchAngle + 0.5 * sp.branchAngleSpread * g) * DEG + SCAFFOLD_SWING * (0.5 - pos);
1855
+ const angle = Math.min(110 * DEG, room, Math.max(8 * DEG, want));
1856
+ let a0 = h.az ?? azs + k * GOLDEN_ANGLE + rng.range(-0.3, 0.3);
1857
+ if (standAt && stand) {
1858
+ // (An edge tree's limbs swing out to the open side, along +x; one whose end would be in the dark has
1859
+ // died young and gone.)
1860
+ a0 -= STAND_SWING * stand.lopsided * Math.sin(a0);
1861
+ const reachY = Math.min(hi, py[node] + 0.25 * depth);
1862
+ const reachR = 0.8 * widthAt(reachY);
1863
+ if (!inCrown(reachR * Math.cos(a0), reachY, reachR * Math.sin(a0)))
1864
+ continue;
1865
+ }
1866
+ const e0 = 0.5 * Math.PI - angle;
1867
+ const sway = SCAFFOLD_SWAY * sp.crooked * rng.range(-1, 1);
1868
+ const phase = rng.range(0, Math.PI);
1869
+ // (And it wanders, up and down and side to side, a bend every few internodes: a crooked limb's elbows.)
1870
+ let we = 0;
1871
+ let wa = 0;
1872
+ const pts = spine(node, (u) => {
1873
+ // (Its arch over the crown, reckoned over the crown's reach: the larger of its radius and most of its
1874
+ // depth, so a long limb in a narrow crown rises rather than arching back down.)
1875
+ const f = u / (R / depth < NARROW ? Math.max(R, 0.6 * depth) : R);
1876
+ // (A tree whose wood runs straight between elbows, `zigzagRun`, turns only at them, by as much at once.)
1877
+ const kick = elbows > 1 ? ((Math.round(u / L) + 1) % elbows === 0 ? ELBOW * elbows : 0) : 1;
1878
+ const ge = rng.gauss();
1879
+ const ga = rng.gauss();
1880
+ if (kick > 0) {
1881
+ we = LIMB_KEEP ** elbows * we + kick * LIMB_WANDER * sp.crooked * ge;
1882
+ wa = LIMB_KEEP ** elbows * wa + kick * LIMB_WANDER * sp.crooked * ga;
1883
+ }
1884
+ const e = Math.max(-80 * DEG, Math.min(0.5 * Math.PI, e0 + limbTurn(f) + we));
1885
+ const a = a0 + sway * Math.sin(Math.PI * f + phase) + wa;
1886
+ return [Math.cos(e) * Math.cos(a), Math.sin(e), Math.cos(e) * Math.sin(a)];
1887
+ }, R + depth, h.own !== undefined ? (x, z) => owns(h.own, x, z) : undefined);
1888
+ const n = pts.length / 3;
1889
+ lay(node, pts, Math.max(Math.min(2, n), Math.round(n * rng.range(0.82, 1))), 1, false);
1890
+ }
1891
+ }
1892
+ // Light at every node, then gathered down to each foot: what each axis and branch collects, how many
1893
+ // internodes it is, and how many twigs' pipes it carries (the wood it sheds, too).
1894
+ const gather = () => {
1895
+ for (let i = count - 1; i >= 0; i--) {
1896
+ if (!alive[i])
1897
+ continue;
1898
+ let q = (tBud[i] ? light[i] : 0) + (lBud[i] ? light[i] : 0);
1899
+ let n = 1;
1900
+ let p = shedPipes[i];
1901
+ const m = main[i];
1902
+ const l = lat[i];
1903
+ if (m >= 0) {
1904
+ q += gathered[m];
1905
+ n += internodes[m];
1906
+ p += pipes[m];
1907
+ }
1908
+ if (l >= 0) {
1909
+ q += gathered[l];
1910
+ n += internodes[l];
1911
+ p += pipes[l];
1912
+ }
1913
+ if (m < 0 && l < 0)
1914
+ p += 1;
1915
+ gathered[i] = q;
1916
+ internodes[i] = n;
1917
+ pipes[i] = p;
1918
+ }
1919
+ };
1920
+ const cut = (c) => {
1921
+ const stack = [c];
1922
+ while (stack.length > 0) {
1923
+ const i = stack.pop();
1924
+ if (!alive[i])
1925
+ continue;
1926
+ alive[i] = 0;
1927
+ living--;
1928
+ shade(px[i], py[i], pz[i], -1);
1929
+ if (main[i] >= 0)
1930
+ stack.push(main[i]);
1931
+ if (lat[i] >= 0)
1932
+ stack.push(lat[i]);
1933
+ }
1934
+ };
1935
+ /** Shed every branch (a lateral off its axis, not a scaffold) that gathers too little light for its wood. */
1936
+ const shedThreshold = sp.shed ?? SHED_BASE + SHED_OPEN * sp.openness + SHED_SPARSE * (1 - sp.branchiness);
1937
+ const shedDark = () => {
1938
+ let any = false;
1939
+ for (let i = 0; i < count; i++) {
1940
+ const c = lat[i];
1941
+ if (!alive[i] || c < 0 || !alive[c] || kind[c] <= 1 || internodes[c] < 3)
1942
+ continue;
1943
+ if (gathered[c] / internodes[c] >= shedThreshold)
1944
+ continue;
1945
+ shedPipes[i] += pipes[c];
1946
+ cut(c);
1947
+ lat[i] = -1;
1948
+ lBud[i] = 0;
1949
+ any = true;
1950
+ }
1951
+ return any;
1952
+ };
1953
+ const lambda = LAMBDA_LO + (LAMBDA_HI - LAMBDA_LO) * sp.leader;
1954
+ const stemFavour = STEM_FAVOUR + STEM_FAVOUR_LEADER * sp.leader;
1955
+ const lift = TROPISM * sp.bend;
1956
+ const grow = (from, onAxis, n) => {
1957
+ let at = from;
1958
+ let d;
1959
+ if (onAxis)
1960
+ d = dirOf(from);
1961
+ else {
1962
+ lBud[from] = 0;
1963
+ d = cone(dirOf(from), branchAngle(sp, rng), az[from]);
1964
+ // (A shoot is not put out straight down: it leaves its axis's other side.)
1965
+ if (d[1] < -0.6)
1966
+ d = cone(dirOf(from), branchAngle(sp, rng), az[from] + Math.PI);
1967
+ }
1968
+ const k = onAxis ? kind[from] : 2;
1969
+ // (The turn it grows with: on along its axis, what its last internode turned by; a new shoot's afresh.)
1970
+ const turn = onAxis ? [tw[3 * from], tw[3 * from + 1], tw[3 * from + 2]] : [0, 0, 0];
1971
+ let first = !onAxis;
1972
+ for (let m = 0; m < n && count < cap; m++) {
1973
+ const j = rng.onSphere();
1974
+ const up = lift + (k === 0 ? LEADER_UP * sp.leader : 0);
1975
+ // (Wood that runs straight between elbows, `zigzagRun`, wanders all at once at each: as much as it would
1976
+ // have over the run, or more.)
1977
+ const wander = WANDER * sp.crooked * (elbows > 1 ? ((rank[at] + 1) % elbows === 0 ? ELBOW * elbows : 0) : 1);
1978
+ let wx = wander * j[0];
1979
+ let wy = wander * j[1];
1980
+ let wz = wander * j[2];
1981
+ // (Turned to the light as it grows; wood that runs straight between elbows, at them, by as much at once.)
1982
+ const elbow = elbows === 1 || (rank[at] + 1) % elbows === 0;
1983
+ if (elbow && lookForLight(px[at], py[at], pz[at], d)) {
1984
+ wx += elbows * TO_LIGHT * toLight[0];
1985
+ wy += elbows * TO_LIGHT * toLight[1];
1986
+ wz += elbows * TO_LIGHT * toLight[2];
1987
+ }
1988
+ const keep = first ? 0 : BEND_KEEP;
1989
+ first = false;
1990
+ turn[0] = keep * turn[0] + (1 - keep) * wx;
1991
+ turn[1] = keep * turn[1] + (1 - keep) * wy;
1992
+ turn[2] = keep * turn[2] + (1 - keep) * wz;
1993
+ d = norm([d[0] + turn[0], d[1] + up + turn[1], d[2] + turn[2]]);
1994
+ const x = px[at] + d[0] * L;
1995
+ const y = py[at] + d[1] * L;
1996
+ const z = pz[at] + d[2] * L;
1997
+ if (!inCrown(x, y, z) || (owner[at] >= 0 && !owns(owner[at], x, z))) {
1998
+ if (at !== from || onAxis)
1999
+ tBud[at] = 0;
2000
+ return;
2001
+ }
2002
+ if (at === from && onAxis)
2003
+ tBud[from] = 0;
2004
+ const i = add(x, y, z, at, at !== from || onAxis, k, d);
2005
+ tw[3 * i] = turn[0];
2006
+ tw[3 * i + 1] = turn[1];
2007
+ tw[3 * i + 2] = turn[2];
2008
+ if (at !== from)
2009
+ tBud[at] = 0;
2010
+ tBud[i] = 1;
2011
+ at = i;
2012
+ }
2013
+ };
2014
+ for (let cycle = 0; cycle < CYCLES && living < target; cycle++) {
2015
+ for (let i = 0; i < count; i++)
2016
+ if (alive[i])
2017
+ light[i] = lightAt(px[i], py[i], pz[i]);
2018
+ gather();
2019
+ if (cycle > 1 && shedDark())
2020
+ gather();
2021
+ // The resource, at each foot by the light its stem gathers, but no more than the wood left to grow
2022
+ // allows this cycle; handed up, at each node, between its main axis and its lateral.
2023
+ let total = 0;
2024
+ for (const r of roots)
2025
+ total += gathered[r];
2026
+ const budget = (target - living) / (CYCLES - cycle);
2027
+ vIn.fill(0, 0, count);
2028
+ for (const r of roots)
2029
+ vIn[r] = total > 0 ? Math.min(ALPHA * gathered[r], (budget * gathered[r]) / total) : 0;
2030
+ for (let i = 0; i < count; i++) {
2031
+ vT[i] = 0;
2032
+ vL[i] = 0;
2033
+ if (!alive[i])
2034
+ continue;
2035
+ const v = vIn[i];
2036
+ if (v <= 0)
2037
+ continue;
2038
+ const m = main[i];
2039
+ const l = lat[i];
2040
+ const qm = m >= 0 ? gathered[m] : tBud[i] ? light[i] : 0;
2041
+ const ql = l >= 0 ? gathered[l] : lBud[i] ? light[i] : 0;
2042
+ // (A scaffold has as much say as the trunk it leaves: the great limbs share by the light each gathers.)
2043
+ const wm = even[i] ? qm : lambda * (kind[i] === 0 ? stemFavour : kind[i] === 1 ? SCAFFOLD_FAVOUR : 1) * qm;
2044
+ const wl = even[i] ? ql : (l >= 0 && kind[l] === 1 ? lambda * stemFavour : 1 - lambda) * ql;
2045
+ if (wm + wl <= 0)
2046
+ continue;
2047
+ const vm = (v * wm) / (wm + wl);
2048
+ if (m >= 0)
2049
+ vIn[m] = vm;
2050
+ else
2051
+ vT[i] = vm;
2052
+ if (l >= 0)
2053
+ vIn[l] = v - vm;
2054
+ else
2055
+ vL[i] = v - vm;
2056
+ }
2057
+ const before = count;
2058
+ for (let i = 0; i < before; i++) {
2059
+ if (!alive[i])
2060
+ continue;
2061
+ if (tBud[i] && vT[i] >= 1)
2062
+ grow(i, true, Math.min(MAX_METAMERS, Math.floor(vT[i])));
2063
+ if (lBud[i] && vL[i] >= 1)
2064
+ grow(i, false, Math.min(MAX_METAMERS, Math.floor(vL[i])));
2065
+ }
2066
+ if (count === before)
2067
+ break;
2068
+ }
2069
+ // And a last reckoning of the light: what has grown into the dark is shed.
2070
+ for (let i = 0; i < count; i++)
2071
+ if (alive[i])
2072
+ light[i] = lightAt(px[i], py[i], pz[i]);
2073
+ gather();
2074
+ if (shedDark())
2075
+ gather();
2076
+ // Into the wood, the living nodes in order (a parent before its children), with what each sheds.
2077
+ const index = new Int32Array(count).fill(-1);
2078
+ const shed = [];
2079
+ for (let i = 0; i < count; i++) {
2080
+ if (!alive[i])
2081
+ continue;
2082
+ const p = par[i];
2083
+ index[i] = addNode(w, px[i], py[i], pz[i], p < 0 ? -1 : index[p], p >= 0 && main[p] === i);
2084
+ shed.push(shedPipes[i]);
2085
+ }
2086
+ w.shed = shed;
2087
+ // (A forked trunk's or a clump's stems are stems of their own, each with its own bole: `pipeRadii`.)
2088
+ const feet = w.stems;
2089
+ let lastOwner = -1;
2090
+ for (let i = 0; i < count; i++) {
2091
+ if (!alive[i] || owner[i] < 0)
2092
+ continue;
2093
+ w.stem[index[i]] = feet + owner[i];
2094
+ lastOwner = Math.max(lastOwner, owner[i]);
2095
+ }
2096
+ w.stems = feet + lastOwner + 1;
2097
+ // Leaves: on the lit shoots near their twigs' ends (further back the deeper the species keeps its leaves),
2098
+ // the lighter the bigger; each at its node, a little on along its twig and out of the crown.
2099
+ // (A small or narrow crown is lit through and full of leaves to its middle, along its leader too: kept to
2100
+ // a shell, a crown two or three metres across is a ring, which from afar reads as a hook.)
2101
+ // (A crown of bunches (`clusters`) wide enough for them keeps them, narrow or not, and its sky between them: CLUSTER_NARROW.)
2102
+ const bunched = (sp.clusters ?? 0) > 0 && R >= SMALL_CROWN;
2103
+ const lit = (R / depth < NARROW && !bunched) || R < SMALL_CROWN;
2104
+ const reach = lit ? LEAF_REACH + LEAF_REACH_DEPTH : LEAF_REACH + Math.round(LEAF_REACH_DEPTH * Math.min(1, Math.max(0, sp.foliageDepth)));
2105
+ const fromTip = new Int32Array(count).fill(1 << 20);
2106
+ for (let i = count - 1; i >= 0; i--) {
2107
+ if (!alive[i])
2108
+ continue;
2109
+ const m = main[i];
2110
+ const l = lat[i];
2111
+ if (m < 0 && l < 0)
2112
+ fromTip[i] = 0;
2113
+ const p = par[i];
2114
+ if (p >= 0)
2115
+ fromTip[p] = Math.min(fromTip[p], fromTip[i] + 1);
2116
+ }
2117
+ const h = newHung();
2118
+ const heart = base + 0.5 * depth;
2119
+ const bears = (i) => alive[i] && !(kind[i] === 0 && !lit) && fromTip[i] <= reach && light[i] >= (lit ? 0.5 * LEAF_LIGHT : LEAF_LIGHT) && py[i] >= base;
2120
+ // (Pads, `pads`: each branch off a great limb keeps only the leaves near its top, a shelf with air and bare
2121
+ // wood under it. A pad is a branch's shoots, by the branch that leaves the limb.)
2122
+ const padTop = new Map();
2123
+ const padOf = new Int32Array(count).fill(-1);
2124
+ // (Less in a crown lit through, a small or narrow one, `PAD_LIT` at most: a tree grown in shelter or in a wood
2125
+ // is not shaped into such thin shelves, and kept to their tops so small a crown is a few balls.)
2126
+ const padding = R / depth < NARROW ? Math.min(PAD_COLUMN, sp.pads ?? 0) : lit ? Math.min(PAD_LIT, sp.pads ?? 0) : (sp.pads ?? 0);
2127
+ // (Bunches only where the crown has room for them: a small or narrow crown, a tree grown in a wood, is many
2128
+ // sprays all through it, as below.)
2129
+ const clustering = Math.min(1, Math.max(0, sp.clusters ?? 0)) * (R < SMALL_CROWN ? CLUSTER_SMALL : R / depth < NARROW ? CLUSTER_NARROW : 1);
2130
+ if (padding > 0 || clustering > 0) {
2131
+ for (let i = 0; i < count; i++) {
2132
+ if (!alive[i])
2133
+ continue;
2134
+ const p = par[i];
2135
+ if (kind[i] === 0 || p < 0)
2136
+ padOf[i] = -1;
2137
+ else if (kind[p] <= 1 && kind[i] === 2)
2138
+ padOf[i] = i;
2139
+ else if (kind[i] === 1)
2140
+ padOf[i] = kind[p] === 0 ? count + i : padOf[p];
2141
+ else
2142
+ padOf[i] = padOf[p];
2143
+ if (padOf[i] >= 0 && bears(i))
2144
+ padTop.set(padOf[i], Math.max(padTop.get(padOf[i]) ?? -Infinity, py[i]));
2145
+ }
2146
+ }
2147
+ const padDepth = clumpR * (PAD_THIN + PAD_THICK * (1 - padding));
2148
+ // (Bunches, `clusters`: a branch bears only at its shoots' ends, or, a share of branches, not at all; which
2149
+ // is decided once a branch, in the order they are met.)
2150
+ const clusterReach = Math.max(1, Math.round(reach * (1 - CLUSTER_REACH * clustering)));
2151
+ const bareBranch = new Map();
2152
+ for (let i = 0; i < count; i++) {
2153
+ if (!bears(i))
2154
+ continue;
2155
+ if (padding > 0 && padOf[i] >= 0 && py[i] < (padTop.get(padOf[i]) ?? -Infinity) - padDepth)
2156
+ continue;
2157
+ if (clustering > 0 && padOf[i] >= 0) {
2158
+ if (fromTip[i] > clusterReach)
2159
+ continue;
2160
+ let bare = bareBranch.get(padOf[i]);
2161
+ if (bare === undefined)
2162
+ bareBranch.set(padOf[i], (bare = rng.chance(CLUSTER_BARE * clustering)));
2163
+ if (bare)
2164
+ continue;
2165
+ }
2166
+ const end = main[i] < 0 && lat[i] < 0;
2167
+ const t = end ? dirOf(i) : [0, 0, 0];
2168
+ const o = norm([px[i], py[i] - heart, pz[i]]);
2169
+ const r = clumpRadius(sp, clumpR, rng) * (0.8 + 0.3 * light[i]) * (1 + CLUSTER_GROW * clustering);
2170
+ // (A bunch hangs a little under its twig.)
2171
+ const drop = CLUSTER_HANG * clustering * r;
2172
+ hang(h, index[i], px[i] + (t[0] * HANG + o[0] * HANG_OUT) * r, py[i] + (t[1] * HANG + o[1] * HANG_OUT) * r - drop, pz[i] + (t[2] * HANG + o[2] * HANG_OUT) * r, r);
2173
+ }
2174
+ // Smoothed, bowed by its weight, and its straight runs joined; then a tree that weeps hangs its whips.
2175
+ const unit = L;
2176
+ straightenLeads(w, h, (sp.zigzag ?? TAKE_LEAD_KEEP / DEG) * DEG, sp.zigzag === 0 ? TAKE_LEAD_STRAIGHT : TAKE_LEAD);
2177
+ smoothWood(w, h);
2178
+ // (Wood that runs straight between elbows, `zigzagRun`, has zigzagged as it grew: not again, internode by
2179
+ // internode, which drawn as a curve through its nodes is a wavy line.)
2180
+ if ((sp.zigzag ?? 0) > ZIGZAG_FROM && elbows === 1)
2181
+ zigzagWood(w, h, ((sp.zigzag ?? 0) - ZIGZAG_FROM) * DEG);
2182
+ // (Less in a narrow crown: its wood rises steep and short-armed, and bowed it hooks.)
2183
+ sagWood(w, h, sagOf(sp) * (R / depth < NARROW ? Math.max(0.25, R / depth / NARROW) : 1), unit);
2184
+ const most = Math.round(MAX_NODES * (1 - WHIP_NODES * weep));
2185
+ const simple = simplifyWood(w, h, unit * SIMPLIFY_SPAN, most);
2186
+ if (weep <= 0)
2187
+ return h;
2188
+ const whips = hangWhips(sp, size, simple, clumpR, weep, rng, liveAt, liftTo);
2189
+ const out = newHung();
2190
+ for (let c = 0; c < h.node.length; c++) {
2191
+ if (whips.bears.has(h.node[c]))
2192
+ continue;
2193
+ // A tree that weeps bears most of its leaves on its whips, few along its twigs; but all of them over the
2194
+ // top of its crown, which they clothe over its arching limbs.
2195
+ if (simple.kids[h.node[c]].length > 0 && h.y[c] < base + WEEP_TOP * depth && rng.chance(WEEP_TWIG_BARE * weep))
2196
+ continue;
2197
+ hang(out, h.node[c], h.x[c], h.y[c], h.z[c], h.r[c]);
2198
+ }
2199
+ for (let c = 0; c < whips.h.node.length; c++)
2200
+ hang(out, whips.h.node[c], whips.h.x[c], whips.h.y[c], whips.h.z[c], whips.h.r[c], true);
2201
+ return out;
2202
+ }
2203
+ /** How far a species' wood sags under its weight, 0..1: more the more it bends down, little if it turns up. */
2204
+ function sagOf(sp) {
2205
+ return Math.min(1, Math.max(0.05, 0.35 - 0.65 * sp.bend));
2206
+ }
2207
+ // ---------------------------------------------------------------------------
2208
+ // The wood made good: smoothed, bowed, simplified. Each moves the clumps with the nodes they hang on.
2209
+ /** Laplacian smoothing (as Evergrove's): each node of a run moves part way to its neighbours' middle; forks, feet and ends stay. */
2210
+ function smoothWood(w, h, passes = SMOOTH_PASSES, k = SMOOTH) {
2211
+ const n = w.x.length;
2212
+ const x0 = Float64Array.from(w.x);
2213
+ const y0 = Float64Array.from(w.y);
2214
+ const z0 = Float64Array.from(w.z);
2215
+ const nx = new Float64Array(n);
2216
+ const ny = new Float64Array(n);
2217
+ const nz = new Float64Array(n);
2218
+ for (let pass = 0; pass < passes; pass++) {
2219
+ for (let i = 0; i < n; i++) {
2220
+ nx[i] = w.x[i];
2221
+ ny[i] = w.y[i];
2222
+ nz[i] = w.z[i];
2223
+ const p = w.parent[i];
2224
+ if (p < 0 || w.kids[i].length !== 1)
2225
+ continue;
2226
+ const c = w.kids[i][0];
2227
+ nx[i] += ((w.x[p] + w.x[c]) / 2 - w.x[i]) * k;
2228
+ ny[i] += ((w.y[p] + w.y[c]) / 2 - w.y[i]) * k;
2229
+ nz[i] += ((w.z[p] + w.z[c]) / 2 - w.z[i]) * k;
2230
+ }
2231
+ for (let i = 0; i < n; i++) {
2232
+ w.x[i] = nx[i];
2233
+ w.y[i] = ny[i];
2234
+ w.z[i] = nz[i];
2235
+ }
2236
+ }
2237
+ follow(w, h, x0, y0, z0);
2238
+ }
2239
+ /**
2240
+ * Each shoot that took the lead where its axis's tip died (its node's only child, starting an axis of its
2241
+ * own) turned back towards the way the axis ran, past TAKE_LEAD_KEEP by TAKE_LEAD of the rest, and all it
2242
+ * bears with it. Nodes come parents first.
2243
+ */
2244
+ function straightenLeads(w, h, keepTurn = TAKE_LEAD_KEEP, share = TAKE_LEAD) {
2245
+ const n = w.x.length;
2246
+ const x0 = Float64Array.from(w.x);
2247
+ const y0 = Float64Array.from(w.y);
2248
+ const z0 = Float64Array.from(w.z);
2249
+ const q = new Float64Array(n * 4);
2250
+ for (let i = 0; i < n; i++) {
2251
+ q[4 * i + 3] = 1;
2252
+ const p = w.parent[i];
2253
+ if (p < 0)
2254
+ continue;
2255
+ let qx = q[4 * p];
2256
+ let qy = q[4 * p + 1];
2257
+ let qz = q[4 * p + 2];
2258
+ let qw = q[4 * p + 3];
2259
+ const seg = [x0[i] - x0[p], y0[i] - y0[p], z0[i] - z0[p]];
2260
+ const g = w.parent[p];
2261
+ if (g >= 0 && !w.cont[i] && w.kids[p].length === 1) {
2262
+ const into = norm([w.x[p] - w.x[g], w.y[p] - w.y[g], w.z[p] - w.z[g]]);
2263
+ const out = norm(rotate(qx, qy, qz, qw, seg[0], seg[1], seg[2]));
2264
+ const turn = Math.acos(Math.min(1, Math.max(-1, into[0] * out[0] + into[1] * out[1] + into[2] * out[2])));
2265
+ // (About the axis square to both, turning `out` towards `into`.)
2266
+ const ax = [out[1] * into[2] - out[2] * into[1], out[2] * into[0] - out[0] * into[2], out[0] * into[1] - out[1] * into[0]];
2267
+ const al = Math.hypot(ax[0], ax[1], ax[2]);
2268
+ if (turn > keepTurn && al > 1e-6) {
2269
+ const angle = (turn - keepTurn) * share;
2270
+ const sn = Math.sin(angle / 2) / al;
2271
+ const bx = ax[0] * sn;
2272
+ const by = ax[1] * sn;
2273
+ const bz = ax[2] * sn;
2274
+ const bw = Math.cos(angle / 2);
2275
+ // b times the parent's turn.
2276
+ const nqx = bw * qx + bx * qw + by * qz - bz * qy;
2277
+ const nqy = bw * qy - bx * qz + by * qw + bz * qx;
2278
+ const nqz = bw * qz + bx * qy - by * qx + bz * qw;
2279
+ const nqw = bw * qw - bx * qx - by * qy - bz * qz;
2280
+ qx = nqx;
2281
+ qy = nqy;
2282
+ qz = nqz;
2283
+ qw = nqw;
2284
+ }
2285
+ }
2286
+ q[4 * i] = qx;
2287
+ q[4 * i + 1] = qy;
2288
+ q[4 * i + 2] = qz;
2289
+ q[4 * i + 3] = qw;
2290
+ const [rx, ry, rz] = rotate(qx, qy, qz, qw, seg[0], seg[1], seg[2]);
2291
+ w.x[i] = w.x[p] + rx;
2292
+ w.y[i] = w.y[p] + ry;
2293
+ w.z[i] = w.z[p] + rz;
2294
+ }
2295
+ follow(w, h, x0, y0, z0);
2296
+ }
2297
+ /**
2298
+ * A sympodial species' fine branches zigzag (`zigzag`): each shoot ended in a flower or a dead tip and the bud
2299
+ * under it took the lead, a little aside, the next time the other way. Each node on a branch's own axis (the
2300
+ * second order and finer) is set aside from its axis's line, alternately left and right, by the share of its
2301
+ * piece that turns it by `angle`; all beyond it moves with it. Grown so after smoothing, which would iron a
2302
+ * zigzag flat.
2303
+ */
2304
+ function zigzagWood(w, h, angle) {
2305
+ const n = w.x.length;
2306
+ const x0 = Float64Array.from(w.x);
2307
+ const y0 = Float64Array.from(w.y);
2308
+ const z0 = Float64Array.from(w.z);
2309
+ const order = new Uint8Array(n);
2310
+ const step = new Int32Array(n);
2311
+ const ox = new Float64Array(n);
2312
+ const oy = new Float64Array(n);
2313
+ const oz = new Float64Array(n);
2314
+ const k = Math.tan(0.5 * angle);
2315
+ for (let i = 0; i < n; i++) {
2316
+ const p = w.parent[i];
2317
+ if (p < 0)
2318
+ continue;
2319
+ order[i] = w.cont[i] ? order[p] : Math.min(255, order[p] + 1);
2320
+ step[i] = w.cont[i] ? step[p] + 1 : 0;
2321
+ ox[i] = ox[p];
2322
+ oy[i] = oy[p];
2323
+ oz[i] = oz[p];
2324
+ if (order[i] < 2 || !w.cont[i])
2325
+ continue;
2326
+ const sx = x0[i] - x0[p];
2327
+ const sy = y0[i] - y0[p];
2328
+ const sz = z0[i] - z0[p];
2329
+ const len = Math.hypot(sx, sy, sz);
2330
+ // (Aside square to the piece and level: a twig zigzags in its own plane, as it lies.)
2331
+ let ax = -sz;
2332
+ let az = sx;
2333
+ const al = Math.hypot(ax, az);
2334
+ if (al < 1e-6 || len < 1e-6)
2335
+ continue;
2336
+ ax /= al;
2337
+ az /= al;
2338
+ const by = (step[i] % 2 === 0 ? 1 : -1) * k * len;
2339
+ ox[i] += ax * by;
2340
+ oz[i] += az * by;
2341
+ }
2342
+ for (let i = 0; i < n; i++) {
2343
+ w.x[i] = x0[i] + ox[i];
2344
+ w.y[i] = y0[i] + oy[i];
2345
+ w.z[i] = z0[i] + oz[i];
2346
+ }
2347
+ follow(w, h, x0, y0, z0);
2348
+ }
2349
+ /** Each clump moved as its node has moved, from where it was. */
2350
+ function follow(w, h, x0, y0, z0) {
2351
+ for (let c = 0; c < h.node.length; c++) {
2352
+ const i = h.node[c];
2353
+ h.x[c] += w.x[i] - x0[i];
2354
+ h.y[c] += w.y[i] - y0[i];
2355
+ h.z[c] += w.z[i] - z0[i];
2356
+ }
2357
+ }
2358
+ /**
2359
+ * The wood bowed under its weight (as Evergrove's gravity): each piece turns towards straight down by an angle
2360
+ * that grows with its length and falls fast with its thickness (a beam's stiffness goes as its radius to
2361
+ * the fourth, its load slower), at most SAG_MOST, and all beyond it turns with it, so a limb's bends add up
2362
+ * along it and its twigs hang. `unit` is the length the sag is reckoned per.
2363
+ */
2364
+ function sagWood(w, h, amount, unit) {
2365
+ if (amount <= 0)
2366
+ return;
2367
+ const n = w.x.length;
2368
+ const r = pipeUnits(w, unit);
2369
+ const x0 = Float64Array.from(w.x);
2370
+ const y0 = Float64Array.from(w.y);
2371
+ const z0 = Float64Array.from(w.z);
2372
+ // Each node's turn, as a quaternion (x, y, z, w).
2373
+ const q = new Float64Array(n * 4);
2374
+ for (let i = 0; i < n; i++) {
2375
+ q[4 * i + 3] = 1;
2376
+ const p = w.parent[i];
2377
+ if (p < 0)
2378
+ continue;
2379
+ const sx = x0[i] - x0[p];
2380
+ const sy = y0[i] - y0[p];
2381
+ const sz = z0[i] - z0[p];
2382
+ const len = Math.hypot(sx, sy, sz);
2383
+ let qx = q[4 * p];
2384
+ let qy = q[4 * p + 1];
2385
+ let qz = q[4 * p + 2];
2386
+ let qw = q[4 * p + 3];
2387
+ if (len > 1e-9) {
2388
+ const [ex, ey, ez] = rotate(qx, qy, qz, qw, sx / len, sy / len, sz / len);
2389
+ // Its axis: square to it and to straight down (d × down = (ez, 0, -ex)).
2390
+ const ax = ez;
2391
+ const azv = -ex;
2392
+ const al = Math.hypot(ax, azv);
2393
+ if (al > 1e-6) {
2394
+ const toDown = Math.acos(Math.min(1, Math.max(-1, -ey)));
2395
+ const stiff = (r[i] / SAG_STIFF) ** 3;
2396
+ const angle = Math.min(toDown, SAG_MOST, (SAG * amount * len) / unit / (1 + stiff));
2397
+ const s = Math.sin(angle / 2) / al;
2398
+ const bx = ax * s;
2399
+ const bz = azv * s;
2400
+ const bw = Math.cos(angle / 2);
2401
+ // b (about the axis, which has no y) times the parent's turn.
2402
+ const nqx = bw * qx + bx * qw + 0 * qz - bz * qy;
2403
+ const nqy = bw * qy - bx * qz + 0 * qw + bz * qx;
2404
+ const nqz = bw * qz + bx * qy - 0 * qx + bz * qw;
2405
+ const nqw = bw * qw - bx * qx - 0 * qy - bz * qz;
2406
+ qx = nqx;
2407
+ qy = nqy;
2408
+ qz = nqz;
2409
+ qw = nqw;
2410
+ }
2411
+ }
2412
+ q[4 * i] = qx;
2413
+ q[4 * i + 1] = qy;
2414
+ q[4 * i + 2] = qz;
2415
+ q[4 * i + 3] = qw;
2416
+ const [rx, ry, rz] = rotate(qx, qy, qz, qw, sx, sy, sz);
2417
+ w.x[i] = w.x[p] + rx;
2418
+ w.y[i] = w.y[p] + ry;
2419
+ w.z[i] = w.z[p] + rz;
2420
+ }
2421
+ follow(w, h, x0, y0, z0);
2422
+ }
2423
+ /** A vector turned by a unit quaternion. */
2424
+ function rotate(qx, qy, qz, qw, vx, vy, vz) {
2425
+ // t = 2 q × v; v' = v + w t + q × t
2426
+ const tx = 2 * (qy * vz - qz * vy);
2427
+ const ty = 2 * (qz * vx - qx * vz);
2428
+ const tz = 2 * (qx * vy - qy * vx);
2429
+ return [vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx)];
2430
+ }
2431
+ /**
2432
+ * The wood with the nodes that hardly bend it dropped, their neighbours joined straight (as Evergrove's):
2433
+ * every foot, fork and end is kept, and no joined piece is longer than `longest`. If that leaves more nodes
2434
+ * than `most`, again with a wider angle. A clump on a dropped node goes to the nearer kept one along its
2435
+ * twig. Returns the new wood, which `w` now is.
2436
+ */
2437
+ function simplifyWood(w, h, longest, most) {
2438
+ let angle = SIMPLIFY;
2439
+ for (let tries = 0;; tries++) {
2440
+ const done = simplifyOnce(w, h, angle, longest);
2441
+ if (w.x.length <= most || tries >= 6 || !done)
2442
+ return w;
2443
+ angle *= 1.6;
2444
+ longest *= 1.3;
2445
+ }
2446
+ }
2447
+ function simplifyOnce(w, h, angle, longest) {
2448
+ const n = w.x.length;
2449
+ const parent = w.parent.slice();
2450
+ const kids = w.kids.map((k) => k.slice());
2451
+ const cont = w.cont.slice();
2452
+ const shed = w.shed ? w.shed.slice() : new Array(n).fill(0);
2453
+ const gone = new Uint8Array(n);
2454
+ const cos = Math.cos(angle);
2455
+ let dropped = 0;
2456
+ for (let i = 0; i < n; i++) {
2457
+ const p = parent[i];
2458
+ // (A stem leaving a forked trunk keeps its first node: its first piece is where it narrows to itself.)
2459
+ if (p < 0 || kids[i].length !== 1 || w.stem[i] !== w.stem[p])
2460
+ continue;
2461
+ const c = kids[i][0];
2462
+ if (!cont[c])
2463
+ continue;
2464
+ const ax = w.x[i] - w.x[p];
2465
+ const ay = w.y[i] - w.y[p];
2466
+ const az = w.z[i] - w.z[p];
2467
+ const bx = w.x[c] - w.x[i];
2468
+ const by = w.y[c] - w.y[i];
2469
+ const bz = w.z[c] - w.z[i];
2470
+ const la = Math.hypot(ax, ay, az);
2471
+ const lb = Math.hypot(bx, by, bz);
2472
+ if (la < 1e-9 || lb < 1e-9)
2473
+ continue;
2474
+ if ((ax * bx + ay * by + az * bz) / (la * lb) < cos)
2475
+ continue;
2476
+ if (Math.hypot(w.x[c] - w.x[p], w.y[c] - w.y[p], w.z[c] - w.z[p]) > longest)
2477
+ continue;
2478
+ parent[c] = p;
2479
+ kids[p][kids[p].indexOf(i)] = c;
2480
+ cont[c] = cont[i];
2481
+ shed[p] += shed[i];
2482
+ gone[i] = 1;
2483
+ dropped++;
2484
+ }
2485
+ if (dropped === 0)
2486
+ return false;
2487
+ const remap = new Int32Array(n).fill(-1);
2488
+ let m = 0;
2489
+ for (let i = 0; i < n; i++)
2490
+ if (!gone[i])
2491
+ remap[i] = m++;
2492
+ /** The kept node a dropped one's clumps go to: the nearer of the kept ones either side of it on its run. */
2493
+ const keptFor = (i, x, y, z) => {
2494
+ let up = i;
2495
+ while (gone[up])
2496
+ up = parent[up];
2497
+ let down = i;
2498
+ while (gone[down])
2499
+ down = kids[down][0];
2500
+ const du = Math.hypot(w.x[up] - x, w.y[up] - y, w.z[up] - z);
2501
+ const dd = Math.hypot(w.x[down] - x, w.y[down] - y, w.z[down] - z);
2502
+ return dd < du ? down : up;
2503
+ };
2504
+ for (let c = 0; c < h.node.length; c++) {
2505
+ const i = h.node[c];
2506
+ h.node[c] = remap[gone[i] ? keptFor(i, h.x[c], h.y[c], h.z[c]) : i];
2507
+ }
2508
+ const out = newWood();
2509
+ const outShed = [];
2510
+ for (let i = 0; i < n; i++) {
2511
+ if (gone[i])
2512
+ continue;
2513
+ const j = addNode(out, w.x[i], w.y[i], w.z[i], parent[i] < 0 ? -1 : remap[parent[i]], cont[i]);
2514
+ out.stem[j] = w.stem[i];
2515
+ outShed.push(shed[i]);
2516
+ }
2517
+ w.x = out.x;
2518
+ w.y = out.y;
2519
+ w.z = out.z;
2520
+ w.parent = out.parent;
2521
+ w.cont = out.cont;
2522
+ w.kids = out.kids;
2523
+ w.stem = out.stem;
2524
+ w.shed = outShed;
2525
+ return true;
2526
+ }
2527
+ /**
2528
+ * Whips, hung from a share `weep` of the crown's twig ends, its outer and upper ones first: each arches out
2529
+ * a little and then hangs straight down under its weight, to as low as the crown's base (some stop
2530
+ * short), kept inside the crown's outline, and leaved along all its length. Two whips do not hang where
2531
+ * their leaves would crowd each other. Returns the twigs they hang from and their clumps.
2532
+ */
2533
+ function hangWhips(sp, size, w, clumpR, weep, rng, alive, lift = size.crownBase) {
2534
+ const { crownBase: base, crownRadius: R, height: H } = size;
2535
+ const depth = Math.max(0.01, H - base);
2536
+ const rW = WHIP_CLUMP * clumpR;
2537
+ const thinK = thinGap(sp);
2538
+ const piece = 2.3 * thinK * rW;
2539
+ const gap = 2 * thinK * rW;
2540
+ const inner = new Envelope(sp, size, rW, 0.7 * rW, rW, lift);
2541
+ const ends = [];
2542
+ for (let i = 0; i < w.x.length; i++)
2543
+ if (w.kids[i].length === 0 && w.parent[i] >= 0 && w.y[i] > base)
2544
+ ends.push(i);
2545
+ // (And the tops of the arches its limbs make in its upper crown, where they turn over and down: a willow's
2546
+ // whips spring from all along the top of its arching limbs. Hung only from its twigs' ends, the arches were
2547
+ // bare wire looping over the crown.)
2548
+ for (let i = 0; i < w.x.length; i++) {
2549
+ const p = w.parent[i];
2550
+ if (p < 0 || w.kids[i].length === 0 || w.y[i] < base + WHIP_ARCH_FROM * depth || w.y[i] <= w.y[p])
2551
+ continue;
2552
+ if (w.kids[i].every((k) => w.y[k] < w.y[i]))
2553
+ ends.push(i);
2554
+ }
2555
+ const score = (i) => Math.hypot(w.x[i], w.z[i]) / R + (0.5 * (w.y[i] - base)) / depth;
2556
+ const order = ends.map((i) => ({ i, s: score(i) })).sort((a, b) => b.s - a.s || a.i - b.i);
2557
+ const chosen = order.slice(0, Math.round(weep * order.length));
2558
+ let nodesLeft = MAX_NODES - w.x.length - 8;
2559
+ let clumpsLeft = Math.round(clumpCap(sp) * Math.min(1, 0.2 + WHIP_CLUMPS * weep));
2560
+ const bears = new Set();
2561
+ const h = newHung();
2562
+ const lines = [];
2563
+ const path = [];
2564
+ for (const { i } of chosen) {
2565
+ if (nodesLeft < 4 || clumpsLeft < 2)
2566
+ break;
2567
+ const p = w.parent[i];
2568
+ const t = norm([w.x[i] - w.x[p], w.y[i] - w.y[p], w.z[i] - w.z[p]]);
2569
+ // Out from the crown's axis, and on the way the twig was going.
2570
+ const rho = Math.hypot(w.x[i], w.z[i]);
2571
+ const th = Math.hypot(t[0], t[2]);
2572
+ let hx = (th > 1e-6 ? t[0] / th : 0) + (rho > 1e-6 ? w.x[i] / rho : 0);
2573
+ let hz = (th > 1e-6 ? t[2] / th : 0) + (rho > 1e-6 ? w.z[i] / rho : 0);
2574
+ const hk = Math.hypot(hx, hz);
2575
+ if (hk < 1e-6) {
2576
+ const a = rng.range(0, 2 * Math.PI);
2577
+ hx = Math.cos(a);
2578
+ hz = Math.sin(a);
2579
+ }
2580
+ else {
2581
+ hx /= hk;
2582
+ hz /= hk;
2583
+ }
2584
+ const stop = base + 0.8 * rW + (w.y[i] - base) * WHIP_STAGGER * rng.next() ** 2;
2585
+ if (w.y[i] - stop < 2 * piece)
2586
+ continue;
2587
+ let e = Math.min(WHIP_RISE, Math.max(WHIP_DIP, Math.asin(Math.max(-1, Math.min(1, t[1])))));
2588
+ let x = w.x[i];
2589
+ let y = w.y[i];
2590
+ let z = w.z[i];
2591
+ let sx = 0;
2592
+ let sz = 0;
2593
+ let hangAt = -1;
2594
+ path.length = 0;
2595
+ for (let k = 0; k < 64 && path.length < 3 * nodesLeft; k++) {
2596
+ e = Math.max(-0.5 * Math.PI, e - WHIP_TURN);
2597
+ // It sways a little as it hangs, by how crooked the species is.
2598
+ const j = rng.onSphere();
2599
+ sx = 0.7 * sx + 0.12 * sp.crooked * j[0];
2600
+ sz = 0.7 * sz + 0.12 * sp.crooked * j[2];
2601
+ const c = Math.cos(e);
2602
+ const d = norm([c * hx + sx + 0.04 * hx, Math.sin(e), c * hz + sz + 0.04 * hz]);
2603
+ let nx = x + d[0] * piece;
2604
+ const ny = y + d[1] * piece;
2605
+ let nz = z + d[2] * piece;
2606
+ if (ny < stop)
2607
+ break;
2608
+ // (In a stand, no lower than its crown lives there: a whip hangs to the ground on the open side.)
2609
+ if (alive && !alive(nx, ny, nz))
2610
+ break;
2611
+ // Inside the crown's outline: drawn in to it (its arch, from a twig at the crown's edge, follows the
2612
+ // edge round), and ended where the outline narrows fast under it as it hangs.
2613
+ const wd = inner.width(ny);
2614
+ if (wd < 0)
2615
+ break;
2616
+ const r = Math.hypot(nx, nz);
2617
+ if (r > wd) {
2618
+ if (hangAt >= 0 && r - wd > 0.7 * piece)
2619
+ break;
2620
+ // (Past the outline, it goes no further out and turns down the sooner: drawn back in to the outline, a
2621
+ // whip arching up out of the crown's narrow top turned back on itself, and its wood was drawn as a loop
2622
+ // of wire over the crown.)
2623
+ const r0 = Math.hypot(x, z);
2624
+ if (r > r0 && r0 > 1e-6) {
2625
+ nx = x + (nx - x) - (x / r0) * (r - r0);
2626
+ nz = z + (nz - z) - (z / r0) * (r - r0);
2627
+ }
2628
+ e = Math.max(-0.5 * Math.PI, e - WHIP_TURN);
2629
+ }
2630
+ x = nx;
2631
+ y = ny;
2632
+ z = nz;
2633
+ path.push(x, y, z);
2634
+ if (hangAt < 0 && e <= -0.5 * Math.PI + 1e-6)
2635
+ hangAt = path.length - 3;
2636
+ }
2637
+ const pieces = path.length / 3;
2638
+ if (pieces < 2)
2639
+ continue;
2640
+ // Where it hangs, seen from above: not on another's line.
2641
+ const at = hangAt >= 0 ? hangAt : path.length - 3;
2642
+ const lx = path[at];
2643
+ const lz = path[at + 2];
2644
+ let free = true;
2645
+ for (let k = 0; k < lines.length && free; k += 2)
2646
+ if (Math.hypot(lines[k] - lx, lines[k + 1] - lz) < gap)
2647
+ free = false;
2648
+ if (!free)
2649
+ continue;
2650
+ lines.push(lx, lz);
2651
+ // (A twig's end gives its leaves to its whip; an arch's top keeps its own, over the wood.)
2652
+ if (w.kids[i].length === 0)
2653
+ bears.add(i);
2654
+ let q = i;
2655
+ const n = Math.min(pieces, nodesLeft, clumpsLeft);
2656
+ for (let k = 0; k < n; k++) {
2657
+ q = addNode(w, path[3 * k], path[3 * k + 1], path[3 * k + 2], q, true);
2658
+ const r = rW * Math.min(1.3, Math.max(0.75, 1 + 0.25 * sp.clumpSpread * rng.gauss()));
2659
+ // (Along its arch, over the wood, which its leaves hide: hung under it there, they left the arch a bare
2660
+ // wire over the crown's top. Hanging, a little under it.)
2661
+ const arch = hangAt >= 0 && 3 * k < hangAt;
2662
+ hang(h, q, w.x[q], w.y[q] + (arch ? WHIP_ARCH_LIFT : -0.15) * r, w.z[q], r);
2663
+ }
2664
+ nodesLeft -= n;
2665
+ clumpsLeft -= n;
2666
+ }
2667
+ return { bears, h };
2668
+ }
2669
+ // ---------------------------------------------------------------------------
2670
+ // Conifers: a leader, and whorls of boughs.
2671
+ /**
2672
+ * A bough's line, of unit length: from the horizontal at `rise`, bending by `curve` along it, in n pieces;
2673
+ * or, given `back`, by `curve` over its inner half and `back` over its outer (Weber and Penn's nCurve and
2674
+ * nCurveBack: a J-curved bough droops, then its tip turns up). Never past straight up or straight down.
2675
+ */
2676
+ function boughLine(rise, curve, n, back) {
2677
+ const h = [0];
2678
+ const v = [0];
2679
+ let e = rise;
2680
+ for (let k = 0; k < n; k++) {
2681
+ const s = (k + 0.5) / n;
2682
+ const turn = back === undefined ? curve / n : s < 0.5 ? (2 * curve) / n : (2 * back) / n;
2683
+ e = Math.max(-88 * DEG, Math.min(88 * DEG, e + turn));
2684
+ h.push(h[k] + Math.cos(e) / n);
2685
+ v.push(v[k] + Math.sin(e) / n);
2686
+ }
2687
+ return { h, v };
2688
+ }
2689
+ /**
2690
+ * The angle a first-order limb leaves its trunk at (radians from upright), at a share `t` of the way up the
2691
+ * crown: the species' `limbAngle` from its base to its top, or its `branchAngle`.
2692
+ */
2693
+ function limbAngleAt(sp, t) {
2694
+ if (!sp.limbAngle)
2695
+ return sp.branchAngle * DEG;
2696
+ const u = Math.min(1, Math.max(0, t));
2697
+ return (sp.limbAngle[1] + (sp.limbAngle[0] - sp.limbAngle[1]) * u) * DEG;
2698
+ }
2699
+ /** Whether a species carries its needles as a pine does: in tufts at its shoots' ends, the wood behind them bare. */
2700
+ function tufted(sp) {
2701
+ return sp.leafKind === "pine";
2702
+ }
2703
+ /**
2704
+ * Whether a conifer's top is a spire: its leader kept (excurrent) and clothed in needles all round over its
2705
+ * last few metres, with the short upswept boughs of its last whorls (a spruce's, a fir's, a cedar's).
2706
+ */
2707
+ function spired(sp) {
2708
+ return sp.architecture === "conifer" && sp.leader >= 0.8 && !tufted(sp);
2709
+ }
2710
+ function whorled(sp, size, rng, w, clumpR, stand, lift = size.crownBase) {
2711
+ const { height: H, crownRadius: R, crownBase: base } = size;
2712
+ const depth = Math.max(0.01, H - base);
2713
+ const standAt = stand ? standLightOf(sp, stand, size) : null;
2714
+ const profileAt = outlineOf(sp, size, lift);
2715
+ const spacing = Math.min(1 / Math.max(0.05, sp.whorlsPerMetre), WHORL_OF_CROWN * R);
2716
+ const top = H - 1.1 * clumpR;
2717
+ const segLen = Math.max(0.05, BOUGH_STEP * R);
2718
+ const h = newHung();
2719
+ const shed = [];
2720
+ w.shed = shed;
2721
+ const shell = Math.max(MIN_SHELL, Math.min(1, sp.foliageDepth));
2722
+ const tufts = tufted(sp);
2723
+ const spire = spired(sp);
2724
+ /** The top of the leader clothed in needles all round: its length (m). */
2725
+ const spireLen = spire ? Math.min(SPIRE_MOST, SPIRE * depth, 0.6 * depth) : 0;
2726
+ /** How far a bough's tip may reach from the axis at a height, its clump inside the crown. */
2727
+ const reachAt = (y) => Math.max(0.15 * clumpR, profileAt(Math.min(H, Math.max(base, y))) - 0.9 * clumpR);
2728
+ /** A bough's turning along it (radians): the species' curve (and back), or from its bend, more for a long one. */
2729
+ const curveOf = (full) => {
2730
+ if (sp.limbCurve === undefined && sp.limbCurveBack === undefined)
2731
+ return { curve: sp.bend * (BOUGH_CURVE + (BOUGH_WEIGHT * full) / R) };
2732
+ // (A long bough's weight bends it further than a short one's: the curve is a typical bough's, about the
2733
+ // crown's radius long.)
2734
+ const weight = 0.55 + 0.45 * Math.min(1.6, full / Math.max(0.01, 0.8 * R));
2735
+ return { curve: (sp.limbCurve ?? 0) * DEG * weight, back: sp.limbCurveBack === undefined ? undefined : sp.limbCurveBack * DEG };
2736
+ };
2737
+ /**
2738
+ * A bough's shape at a height: how it rises and bends, and the longest it can be with every node of it
2739
+ * in the crown, with room for a clump, and its tip under the crown's top. (Found by halving: the crown is
2740
+ * narrower where a rising bough's tip goes, and wider where a drooping one's does.)
2741
+ */
2742
+ const plan = (y, angle) => {
2743
+ const t = Math.min(1, Math.max(0, (y - base) / depth));
2744
+ const rise = 90 * DEG - angle + (1 - sp.leader) * t * TOP_TURN;
2745
+ const room = Math.max(0.05, top - y);
2746
+ const full = reachAt(y);
2747
+ const { curve, back } = curveOf(full);
2748
+ const n = Math.min(MAX_BOUGH_STEPS, Math.max(2, Math.round(full / segLen)));
2749
+ const line = boughLine(rise, curve, n, back);
2750
+ const fits = (len) => {
2751
+ if (line.v[n] * len > room)
2752
+ return false;
2753
+ for (let k = 1; k <= n; k++)
2754
+ if (line.h[k] * len > reachAt(y + line.v[k] * len))
2755
+ return false;
2756
+ return true;
2757
+ };
2758
+ let lo = 0;
2759
+ let hi = 3 * R + room;
2760
+ for (let i = 0; i < 30; i++) {
2761
+ const m = 0.5 * (lo + hi);
2762
+ if (fits(m))
2763
+ lo = m;
2764
+ else
2765
+ hi = m;
2766
+ }
2767
+ return { line, n, len: lo };
2768
+ };
2769
+ /** A bough's angle at a height: the species' there, varied by its spread. */
2770
+ const angleAt = (y) => {
2771
+ const g = Math.max(-2, Math.min(2, rng.gauss()));
2772
+ return Math.max(5 * DEG, Math.min(175 * DEG, limbAngleAt(sp, (y - base) / depth) + sp.branchAngleSpread * g * DEG));
2773
+ };
2774
+ // The lowest whorl is set so its boughs' leaves hang at the crown's base: above it when they droop,
2775
+ // below it when they rise (a pine's lowest live boughs leave the trunk under its crown and turn up into it).
2776
+ const low = plan(base, limbAngleAt(sp, 0));
2777
+ const lowLeaf = Math.min(low.n, Math.max(1, Math.ceil(low.n * (1 - shell))));
2778
+ const y0 = Math.max(0.5 * base, base + clumpR - Math.min(low.line.v[lowLeaf], low.line.v[low.n]) * low.len);
2779
+ // The leader's heights: the bare trunk in pieces, then a node at every whorl, then its top; over its spire,
2780
+ // a node every so often between, for the needles that clothe it.
2781
+ const levels = [];
2782
+ const trunkSteps = Math.max(1, Math.ceil(y0 / TRUNK_STEP));
2783
+ for (let k = 1; k < trunkSteps; k++)
2784
+ levels.push({ y: (y0 * k) / trunkSteps, whorl: false });
2785
+ // A leader that gives up the lead stops short of the top, and its last boughs, turned up, make the
2786
+ // crown's top round or flat: an old pine's.
2787
+ const lead = Math.max(y0 + spacing, top - (1 - sp.leader) * LEADER_SHORT * depth);
2788
+ const leaderTop = spire ? H - SPIRE_TIP * clumpR : Math.min(top, lead);
2789
+ const spireFrom = leaderTop - spireLen;
2790
+ const step = (y) => (spire && y >= spireFrom - 1e-9 ? Math.min(TRUNK_STEP, SPIRE_STEP * clumpR) : TRUNK_STEP);
2791
+ for (let y = y0; y < lead - 0.5 * spacing; y += spacing) {
2792
+ const yy = Math.min(lead - 0.25 * spacing, y + 0.15 * spacing * rng.range(-1, 1));
2793
+ const last = levels.length > 0 ? levels[levels.length - 1].y : 0;
2794
+ const fill = Math.floor((yy - last) / step(yy));
2795
+ for (let k = 1; k <= fill; k++)
2796
+ levels.push({ y: last + ((yy - last) * k) / (fill + 1), whorl: false });
2797
+ levels.push({ y: yy, whorl: true });
2798
+ }
2799
+ {
2800
+ const last = levels.length > 0 ? levels[levels.length - 1].y : 0;
2801
+ const fill = Math.floor((leaderTop - last) / step(leaderTop));
2802
+ for (let k = 1; k <= fill; k++)
2803
+ levels.push({ y: last + ((leaderTop - last) * k) / (fill + 1), whorl: false });
2804
+ }
2805
+ levels.push({ y: leaderTop, whorl: false });
2806
+ let i = addNode(w, 0, 0, 0, -1, false);
2807
+ let wx = 0;
2808
+ let wz = 0;
2809
+ let turn = rng.range(0, 2 * Math.PI);
2810
+ /** The leader's nodes over its spire, to clothe. */
2811
+ const spireNodes = [];
2812
+ for (const lv of levels) {
2813
+ const dy = lv.y - w.y[i];
2814
+ const j = rng.onSphere();
2815
+ wx = 0.85 * wx + 0.06 * sp.crooked * dy * j[0];
2816
+ wz = 0.85 * wz + 0.06 * sp.crooked * dy * j[2];
2817
+ i = addNode(w, wx, lv.y, wz, i, true);
2818
+ if (spire && lv.y >= spireFrom - 1e-9)
2819
+ spireNodes.push(i);
2820
+ if (!lv.whorl)
2821
+ continue;
2822
+ turn += GOLDEN_ANGLE;
2823
+ const per = Math.max(1, Math.round(sp.whorl));
2824
+ for (let b = 0; b < per; b++) {
2825
+ // An open tree has lost boughs from its whorls.
2826
+ if (!rng.chance(sp.branchiness) || w.x.length >= MAX_NODES - 40) {
2827
+ shed[i] += 1;
2828
+ continue;
2829
+ }
2830
+ const az = turn + (2 * Math.PI * b) / per + rng.range(-0.4, 0.4) * (2 * Math.PI) / per;
2831
+ const planned = plan(lv.y, angleAt(lv.y));
2832
+ const { line, n } = planned;
2833
+ // Not every bough is whole: some were broken or shaded back, and stop short.
2834
+ let len = planned.len * (rng.chance(BOUGH_BROKEN) ? rng.range(0.45, 0.8) : rng.range(0.85, 1));
2835
+ if (standAt) {
2836
+ // In a stand, a bough on the dark side is shorter, or dead and gone (its stub may stay: boleStubs).
2837
+ const lit = standAt(0.5 * len * Math.cos(az), lv.y, 0.5 * len * Math.sin(az));
2838
+ if (lit < STAND_BOUGH && lv.y < H * (1 - STAND_LIVE_LEAST)) {
2839
+ shed[i] += 0.5 * n;
2840
+ continue;
2841
+ }
2842
+ len *= 0.55 + 0.45 * Math.min(1, (lit - STAND_BOUGH) / (STAND_BOUGH_FULL - STAND_BOUGH));
2843
+ }
2844
+ // A bough whose leaves would hang below the crown's base is in the shade of those above: it has
2845
+ // died and fallen, as a forest tree's lower boughs do (the trunk keeps its wood).
2846
+ const leafFrom = Math.min(n, Math.max(1, Math.ceil(n * (1 - shell))));
2847
+ if (lv.y + Math.min(line.v[leafFrom], line.v[n]) * len - 1.25 * clumpR < base - 0.25 * clumpR) {
2848
+ shed[i] += 0.5 * n;
2849
+ continue;
2850
+ }
2851
+ // (Too short to carry a leaf past its spire's needles: not grown, the spire clothes the leader there.)
2852
+ if (spire && lv.y >= spireFrom && len < 0.8 * clumpR)
2853
+ continue;
2854
+ const ca = Math.cos(az);
2855
+ const sa = Math.sin(az);
2856
+ // Along the bough, a wander square to it, side to side and up and down, by how crooked the species is.
2857
+ let jitter = 0;
2858
+ let heave = 0;
2859
+ let prev = i;
2860
+ const bough = [];
2861
+ for (let k = 1; k <= n; k++) {
2862
+ jitter += (0.15 * sp.crooked * len * rng.gauss()) / n;
2863
+ heave += (0.1 * sp.crooked * len * rng.gauss()) / n;
2864
+ const hh = line.h[k] * len;
2865
+ const x = w.x[i] + hh * ca - jitter * sa;
2866
+ const z = w.z[i] + hh * sa + jitter * ca;
2867
+ prev = addNode(w, x, lv.y + line.v[k] * len + heave, z, prev, k > 1);
2868
+ bough.push(prev);
2869
+ }
2870
+ // Side shoots, left and right, longest near the bough's foot, on the part of it that is in leaf (as
2871
+ // deep as the species keeps its leaves, and a little more); then the leaves, on that part of the
2872
+ // bough and at every shoot's end. A pine's needles are at its shoots' ends only, in tufts.
2873
+ // (A pine's shoots are on its bough's outer part, fewer, each tufted at its end: the bough's inner part bare.)
2874
+ // (A narrow crown, grown in a wood, is short boughs tufted all along: there is no inner part to be bare.)
2875
+ const sparse = tufts && R >= SMALL_CROWN;
2876
+ const leafy = sparse ? TUFT_FROM : Math.max(0.15, 1 - shell - 0.15);
2877
+ // (How far the shoots hang from the bough: a comb's or a cedar's hang down, a fir's lie in its plane.)
2878
+ const hang = sp.sprayHang;
2879
+ for (let k = 1; k < n * 2; k++) {
2880
+ const f = Math.floor(k / 2) / n;
2881
+ const at = bough[Math.floor(k / 2) - 1];
2882
+ if (f < leafy || !rng.chance(Math.max(0.3, sp.branchiness) * (sparse ? TUFT_SHOOTS : 1)))
2883
+ continue;
2884
+ const nxt = bough[Math.floor(k / 2)];
2885
+ const bd = norm([w.x[nxt] - w.x[at], w.y[nxt] - w.y[at], w.z[nxt] - w.z[at]]);
2886
+ const side = k % 2 === 0 ? 1 : -1;
2887
+ const sideDir = norm([-bd[2] * side, 0, bd[0] * side]);
2888
+ const c = Math.cos(SHOOT_ANGLE);
2889
+ const s = Math.sin(SHOOT_ANGLE);
2890
+ const sd = hang === undefined ? norm([bd[0] * c + sideDir[0] * s, bd[1] * c + sp.bend * 0.3, bd[2] * c + sideDir[2] * s]) : norm([(bd[0] * c + sideDir[0] * s) * (1 - 0.75 * hang), bd[1] * c * (1 - hang) - 1.6 * hang, (bd[2] * c + sideDir[2] * s) * (1 - 0.75 * hang)]);
2891
+ let sl = len * SHOOT_LENGTH * (1 - 0.6 * f) * (hang === undefined ? 1 : 1 - 0.35 * hang);
2892
+ // Kept inside the crown, shortened if it would poke out.
2893
+ for (let tries = 0; tries < 4; tries++) {
2894
+ const tx = w.x[at] + sd[0] * sl;
2895
+ const ty = w.y[at] + sd[1] * sl;
2896
+ const tz = w.z[at] + sd[2] * sl;
2897
+ if (Math.hypot(tx, tz) <= profileAt(Math.max(base, ty)) - 0.5 * clumpR && ty <= top)
2898
+ break;
2899
+ sl *= 0.6;
2900
+ }
2901
+ const pieces = sl > 4 * segLen ? 2 : 1;
2902
+ let q = at;
2903
+ for (let m = 1; m <= pieces; m++) {
2904
+ const d = (sl * m) / pieces;
2905
+ q = addNode(w, w.x[at] + sd[0] * d, w.y[at] + sd[1] * d, w.z[at] + sd[2] * d, q, m > 1);
2906
+ }
2907
+ hangNeedles(h, w, q, sp, size, clumpR * (sparse ? TUFT : 1), rng);
2908
+ }
2909
+ for (let k = 1; k <= n; k++) {
2910
+ if (sparse ? k === n || (k === n - 1 && n > 2) : k === n || k / n >= 1 - shell)
2911
+ hangNeedles(h, w, bough[k - 1], sp, size, clumpR * (sparse && k < n ? TUFT : 1), rng);
2912
+ }
2913
+ }
2914
+ }
2915
+ if (spire) {
2916
+ // The spire: needles all round the leader over its last few metres, finer towards its tip, so its top is
2917
+ // a dense point and no bare stick (each kept before the boughs' when clumps are thinned).
2918
+ for (const node of spireNodes) {
2919
+ const u = Math.min(1, Math.max(0, (w.y[node] - spireFrom) / Math.max(1e-3, leaderTop - spireFrom)));
2920
+ const r = clumpR * (SPIRE_FINE + (SPIRE_FULL - SPIRE_FINE) * (1 - u) ** 0.7);
2921
+ hang(h, node, w.x[node], w.y[node] - 0.1 * r, w.z[node], r, true);
2922
+ }
2923
+ }
2924
+ else {
2925
+ // And a tuft at the leader's top.
2926
+ hangNeedles(h, w, i, sp, size, clumpR, rng);
2927
+ }
2928
+ // Smoothed, bowed a little by its weight (its boughs' droop is grown already), and its straight runs joined.
2929
+ smoothWood(w, h);
2930
+ sagWood(w, h, CONIFER_SAG * sagOf(sp), segLen);
2931
+ simplifyWood(w, h, 4 * segLen, MAX_NODES);
2932
+ return h;
2933
+ }
2934
+ /** A conifer's clump on a node: needles hang under their shoot, so its centre sits a little below. */
2935
+ function hangNeedles(h, w, node, sp, size, clumpR, rng) {
2936
+ const r = clumpRadius(sp, clumpR, rng);
2937
+ const y = w.y[node] - 0.25 * r;
2938
+ // None under the crown's base: down there it is too dark for needles.
2939
+ if (y - r < size.crownBase - 0.25 * r)
2940
+ return;
2941
+ hang(h, node, w.x[node], y, w.z[node], r);
2942
+ }
2943
+ // ---------------------------------------------------------------------------
2944
+ // For every tree: thin the clumps, fit to size, the radii, and the arrays.
2945
+ function finish(sp, size, w, hung, lift, forkY, keepBelow = 0) {
2946
+ const lifted = lift !== undefined;
2947
+ const env = new Envelope(sp, size, 0, 0, 0, lift);
2948
+ liftCanopy(sp, size, hung);
2949
+ let keep = thin(sp, env, hung);
2950
+ // (A conifer whose boughs are drawn as sheets keeps a twig only where its needles lie close over it: a sheet
2951
+ // lies along its bough, and a twig off it, inside a clump's ball but not under the sheet, pokes out bare.)
2952
+ if (sp.architecture !== "palm")
2953
+ keep = shedBare(w, hung, keep, sp.architecture === "conifer" && !tufted(sp) ? IN_SHEET : IN_SPRAY);
2954
+ if (clothed(sp))
2955
+ keep = clotheTop(size, w, hung, keep);
2956
+ fit(size, w, hung, keep, lifted, keepBelow);
2957
+ if (sp.architecture !== "palm")
2958
+ keepToOutline(env, w, hung);
2959
+ // (And again where drawing the crown in to its outline took its clothing off its wood.)
2960
+ if (clothed(sp))
2961
+ keep = clotheTop(size, w, hung, keep);
2962
+ if (!w.radius)
2963
+ refineBoles(size, w, hung, sp.buttress ?? 0);
2964
+ // A clump keeps to its twig: its centre within its radius of the node it hangs on.
2965
+ for (const c of keep) {
2966
+ const nd = hung.node[c];
2967
+ const dx = hung.x[c] - w.x[nd];
2968
+ const dy = hung.y[c] - w.y[nd];
2969
+ const dz = hung.z[c] - w.z[nd];
2970
+ const d = Math.hypot(dx, dy, dz);
2971
+ const most = 0.9 * hung.r[c];
2972
+ if (d > most) {
2973
+ hung.x[c] = w.x[nd] + (dx * most) / d;
2974
+ hung.y[c] = w.y[nd] + (dy * most) / d;
2975
+ hung.z[c] = w.z[nd] + (dz * most) / d;
2976
+ }
2977
+ }
2978
+ const n = w.x.length;
2979
+ const skeleton = {
2980
+ count: n,
2981
+ x: Float32Array.from(w.x),
2982
+ y: Float32Array.from(w.y),
2983
+ z: Float32Array.from(w.z),
2984
+ radius: new Float32Array(n),
2985
+ parent: Int32Array.from(w.parent),
2986
+ order: new Uint8Array(n),
2987
+ limb: new Int32Array(n),
2988
+ along: new Float32Array(n),
2989
+ };
2990
+ skeleton.radius.set(w.radius ?? pipeRadii(size, w, sp.buttress ?? 0));
2991
+ for (let i = 0; i < n; i++) {
2992
+ const p = w.parent[i];
2993
+ if (p < 0) {
2994
+ skeleton.order[i] = 0;
2995
+ skeleton.limb[i] = i;
2996
+ skeleton.along[i] = w.y[i];
2997
+ continue;
2998
+ }
2999
+ const o = w.cont[i] ? skeleton.order[p] : Math.min(255, skeleton.order[p] + 1);
3000
+ skeleton.order[i] = o;
3001
+ skeleton.limb[i] = o === 0 ? skeleton.limb[p] : o === 1 && skeleton.order[p] === 0 ? i : skeleton.limb[p];
3002
+ skeleton.along[i] = skeleton.along[p] + Math.hypot(w.x[i] - w.x[p], w.y[i] - w.y[p], w.z[i] - w.z[p]);
3003
+ }
3004
+ const m = keep.length;
3005
+ const clumps = {
3006
+ count: m,
3007
+ x: new Float32Array(m),
3008
+ y: new Float32Array(m),
3009
+ z: new Float32Array(m),
3010
+ radius: new Float32Array(m),
3011
+ nx: new Float32Array(m),
3012
+ ny: new Float32Array(m),
3013
+ nz: new Float32Array(m),
3014
+ node: new Int32Array(m),
3015
+ depth: new Float32Array(m),
3016
+ tx: new Float32Array(m),
3017
+ ty: new Float32Array(m),
3018
+ tz: new Float32Array(m),
3019
+ };
3020
+ for (let k = 0; k < m; k++) {
3021
+ const c = keep[k];
3022
+ clumps.x[k] = hung.x[c];
3023
+ clumps.y[k] = hung.y[c];
3024
+ clumps.z[k] = hung.z[c];
3025
+ clumps.radius[k] = hung.r[c];
3026
+ clumps.node[k] = hung.node[c];
3027
+ const at = env.place(hung.x[c], hung.y[c], hung.z[c], hung.r[c]);
3028
+ clumps.depth[k] = at.depth;
3029
+ clumps.nx[k] = at.n[0];
3030
+ clumps.ny[k] = at.n[1];
3031
+ clumps.nz[k] = at.n[2];
3032
+ // Its twig's way: from the node's parent to the node (a stem's foot, up).
3033
+ const nd = hung.node[c];
3034
+ const p = w.parent[nd];
3035
+ const t = p >= 0 ? norm([w.x[nd] - w.x[p], w.y[nd] - w.y[p], w.z[nd] - w.z[p]]) : [0, 1, 0];
3036
+ clumps.tx[k] = t[0];
3037
+ clumps.ty[k] = t[1];
3038
+ clumps.tz[k] = t[2];
3039
+ }
3040
+ if (sp.architecture === "palm")
3041
+ return { size, skeleton, clumps };
3042
+ // (A trunk's stems, a forked one's or a clump's, are not strays however low they leave it: each all the way up its
3043
+ // leader, past its first limb. Marked only to its first limb, a stem whose first limb the fit drew down under its
3044
+ // crown's base was shed from there as a stray, with all it bore: a Monterey cypress forked low was a bare stump.)
3045
+ const trunks = new Uint8Array(n);
3046
+ for (const start of stemStarts(w))
3047
+ for (const i of stemLeader(w, start))
3048
+ trunks[i] = 1;
3049
+ return shedStrays(size, skeleton, clumps, forkY, trunks);
3050
+ }
3051
+ /** Whether a species' crown is a weeping one whose top is clothed in leaves (`clotheTop`): its sprays are hung over its wood there. */
3052
+ export function clothed(sp) {
3053
+ return weepOf(sp) >= CLOTHE_WEEP;
3054
+ }
3055
+ /**
3056
+ * A weeping crown's top clothed: every piece of its upper wood with leaves over it. A willow's arching limbs
3057
+ * carry the springing bases of its whips and short leafy shoots all along their tops, so from any side its
3058
+ * top is a dome of leaves and no wood shows over it; grown, its arches' tops between the whips it hung were
3059
+ * bare wire over the crown. Wherever a piece of wood in the crown's upper part (CLOTHE_FROM of its depth) has
3060
+ * no clump's inner core (CLOTHE_COVER of its radius) over it, a whip's spray is hung over it, its centre
3061
+ * CLOTHE_LIFT of its radius above the wood, the highest wood first (one hung over it covers what is under
3062
+ * it). Kept as a whip's leaves are. Returns `keep` with the new clumps' indices.
3063
+ */
3064
+ function clotheTop(size, w, h, keep) {
3065
+ const base = size.crownBase;
3066
+ const depth = Math.max(0.01, size.height - base);
3067
+ const from = base + CLOTHE_FROM * depth;
3068
+ if (keep.length === 0)
3069
+ return keep;
3070
+ // (The size of the whips' sprays, or the crown's.)
3071
+ const own = keep.filter((c) => h.whip[c]).map((c) => h.r[c]);
3072
+ const rs = (own.length > 0 ? own : keep.map((c) => h.r[c])).sort((a, b) => a - b);
3073
+ const r = rs[rs.length >> 1];
3074
+ const list = keep.slice();
3075
+ const covered = (x, y, z) => {
3076
+ for (const c of list) {
3077
+ const rc = h.r[c];
3078
+ const dx = h.x[c] - x;
3079
+ const dz = h.z[c] - z;
3080
+ const d2 = dx * dx + dz * dz;
3081
+ if (d2 < rc * rc && h.y[c] + CLOTHE_COVER * Math.sqrt(rc * rc - d2) >= y)
3082
+ return true;
3083
+ }
3084
+ return false;
3085
+ };
3086
+ const samples = [];
3087
+ for (let i = 0; i < w.x.length; i++) {
3088
+ const p = w.parent[i];
3089
+ if (p < 0)
3090
+ continue;
3091
+ // (Along it, every half a spray's radius, each on the nearer of its ends.)
3092
+ const steps = Math.max(1, Math.ceil(Math.hypot(w.x[i] - w.x[p], w.y[i] - w.y[p], w.z[i] - w.z[p]) / (0.5 * r)));
3093
+ for (let k = 1; k <= steps; k++) {
3094
+ const t = k / steps;
3095
+ const y = w.y[p] + (w.y[i] - w.y[p]) * t;
3096
+ if (y >= from)
3097
+ samples.push({ node: t < 0.5 ? p : i, x: w.x[p] + (w.x[i] - w.x[p]) * t, y, z: w.z[p] + (w.z[i] - w.z[p]) * t });
3098
+ }
3099
+ }
3100
+ samples.sort((a, b) => b.y - a.y || a.node - b.node);
3101
+ const out = keep.slice();
3102
+ for (const s of samples) {
3103
+ if (covered(s.x, s.y, s.z))
3104
+ continue;
3105
+ hang(h, s.node, s.x, s.y + CLOTHE_LIFT * r, s.z, r, true);
3106
+ list.push(h.node.length - 1);
3107
+ out.push(h.node.length - 1);
3108
+ }
3109
+ return out;
3110
+ }
3111
+ /**
3112
+ * The crown's underside cleared (`canopyLift`), so its limbs show beneath it: no leaves under a bowl from
3113
+ * the lowest leaves at the crown's rim up to that share of the way to its heart at its middle. Reckoned on
3114
+ * the leaves as grown and bowed, from the lowest of them (the fit then sets those at the crown's base), and
3115
+ * marked by moving them out of the crown, below it, where thinning drops them. Only an open-grown crown is
3116
+ * lifted so: one narrower than it is deep (a tree grown in a wood or in shelter, as a survey may hand over)
3117
+ * keeps its leaves down its middle, the lift fading from a crown as wide as LIFT_WIDE of its depth to none
3118
+ * at a column's (NARROW); cleared, a narrow crown's bowl is most of it.
3119
+ */
3120
+ function liftCanopy(sp, size, h) {
3121
+ const wide = size.crownRadius / Math.max(0.01, size.height - size.crownBase);
3122
+ const L = (sp.canopyLift ?? 0) * Math.min(1, Math.max(0, (wide - NARROW) / (LIFT_WIDE - NARROW)));
3123
+ if (L <= 0 || h.node.length === 0)
3124
+ return;
3125
+ let low = Infinity;
3126
+ let top = -Infinity;
3127
+ for (let c = 0; c < h.node.length; c++) {
3128
+ low = Math.min(low, h.y[c] - h.r[c]);
3129
+ top = Math.max(top, h.y[c] + h.r[c]);
3130
+ }
3131
+ const heart = low + 0.5 * (top - low);
3132
+ for (let c = 0; c < h.node.length; c++) {
3133
+ const rho = Math.min(1, Math.hypot(h.x[c], h.z[c]) / size.crownRadius);
3134
+ if (h.y[c] < low + L * (heart - low) * (1 - rho * rho))
3135
+ h.y[c] = -1e6;
3136
+ }
3137
+ }
3138
+ /**
3139
+ * Which nodes bear leaves (1) or lead to wood that does: a node a clump hangs on, a node inside a clump
3140
+ * (within IN_SPRAY of its radii of its centre: a clump is a spray of leaves over the twigs there, not one
3141
+ * twig's), every node on the way down from one, and every stem's foot. Each clump is [node, x, y, z,
3142
+ * radius]; nodes not `alive` (if given) bear nothing.
3143
+ */
3144
+ function leafy(n, parent, x, y, z, clumps, alive, inSpray = IN_SPRAY) {
3145
+ const bears = new Uint8Array(n);
3146
+ for (const [node] of clumps)
3147
+ bears[node] = 1;
3148
+ // (A hashed grid of the clumps, by the largest's reach.)
3149
+ let most = 0;
3150
+ for (const c of clumps)
3151
+ most = Math.max(most, inSpray * c[4]);
3152
+ const cell = Math.max(1e-3, most);
3153
+ const size = 4096;
3154
+ const head = new Int32Array(size).fill(-1);
3155
+ const next = new Int32Array(clumps.length).fill(-1);
3156
+ const key = (ix, iy, iz) => (Math.imul(ix, 73856093) ^ Math.imul(iy, 19349663) ^ Math.imul(iz, 83492791)) & (size - 1);
3157
+ clumps.forEach((c, k) => {
3158
+ const h = key(Math.floor(c[1] / cell), Math.floor(c[2] / cell), Math.floor(c[3] / cell));
3159
+ next[k] = head[h];
3160
+ head[h] = k;
3161
+ });
3162
+ for (let i = 0; i < n; i++) {
3163
+ if (bears[i] || (alive && !alive[i]))
3164
+ continue;
3165
+ const ix = Math.floor(x[i] / cell);
3166
+ const iy = Math.floor(y[i] / cell);
3167
+ const iz = Math.floor(z[i] / cell);
3168
+ for (let a = -1; a <= 1 && !bears[i]; a++)
3169
+ for (let b = -1; b <= 1 && !bears[i]; b++)
3170
+ for (let d = -1; d <= 1 && !bears[i]; d++)
3171
+ for (let k = head[key(ix + a, iy + b, iz + d)]; k >= 0; k = next[k]) {
3172
+ const c = clumps[k];
3173
+ const reach = inSpray * c[4];
3174
+ if ((x[i] - c[1]) ** 2 + (y[i] - c[2]) ** 2 + (z[i] - c[3]) ** 2 < reach * reach) {
3175
+ bears[i] = 1;
3176
+ break;
3177
+ }
3178
+ }
3179
+ }
3180
+ for (let i = n - 1; i >= 0; i--) {
3181
+ const p = parent[i];
3182
+ if (alive && !alive[i])
3183
+ bears[i] = 0;
3184
+ if (p < 0)
3185
+ bears[i] = 1;
3186
+ else if (bears[i])
3187
+ bears[p] = 1;
3188
+ }
3189
+ return bears;
3190
+ }
3191
+ /**
3192
+ * Every twig that bears no leaves, nor leads to any, is shed, back to the wood that does: once the crown is
3193
+ * thinned, a twig whose clump went is a dead twig, and a tree drops those (they are what litters the ground
3194
+ * under it). Left on, they are bare forks poking out of the crown, and the leaves they no longer lead to
3195
+ * hang in the air between them. A stem's foot stays. (The pipe model is not told of these, as it is of the
3196
+ * branches shed in the dark: they are many and small, and a fork that kept their pipes would be far thicker
3197
+ * than Leonardo's rule has it.) Keeps only the kept clumps in `h`, and returns their indices, now 0, 1, ...
3198
+ */
3199
+ function shedBare(w, h, keep, inSpray = IN_SPRAY) {
3200
+ const n = w.x.length;
3201
+ if (keep.length === 0)
3202
+ return keep;
3203
+ const bears = leafy(n, w.parent, w.x, w.y, w.z, keep.map((c) => [h.node[c], h.x[c], h.y[c], h.z[c], h.r[c]]), undefined, inSpray);
3204
+ const to = new Int32Array(n).fill(-1);
3205
+ const out = newWood();
3206
+ const outShed = [];
3207
+ const outRadius = [];
3208
+ for (let i = 0; i < n; i++) {
3209
+ if (!bears[i])
3210
+ continue;
3211
+ const p = w.parent[i];
3212
+ to[i] = addNode(out, w.x[i], w.y[i], w.z[i], p < 0 ? -1 : to[p], w.cont[i]);
3213
+ out.stem[to[i]] = w.stem[i];
3214
+ outShed.push(w.shed ? w.shed[i] : 0);
3215
+ if (w.radius)
3216
+ outRadius.push(w.radius[i]);
3217
+ }
3218
+ w.x = out.x;
3219
+ w.y = out.y;
3220
+ w.z = out.z;
3221
+ w.parent = out.parent;
3222
+ w.cont = out.cont;
3223
+ w.kids = out.kids;
3224
+ w.stem = out.stem;
3225
+ w.shed = outShed;
3226
+ if (w.radius)
3227
+ w.radius = outRadius;
3228
+ const kept = newHung();
3229
+ for (const c of keep)
3230
+ hang(kept, to[h.node[c]], h.x[c], h.y[c], h.z[c], h.r[c], h.whip[c]);
3231
+ Object.assign(h, kept);
3232
+ return keep.map((_, k) => k);
3233
+ }
3234
+ /**
3235
+ * Wood that has strayed well out of the tree's own space is shed, from where it strays on: a long thin
3236
+ * branch bowed by its weight out below the crown's base or out past its reach (in a narrow crown, a hook
3237
+ * hanging from it), as a tree drops a limb it cannot hold up or light. Stems stay; a clump on shed wood
3238
+ * goes with it, and wood it leaves bare goes after it.
3239
+ */
3240
+ function shedStrays(size, sk, cl, forkY, trunks) {
3241
+ const depth = Math.max(0.01, size.height - size.crownBase);
3242
+ // (A stem that forks below its crown (`fork`) keeps its limbs from there.)
3243
+ const low = Math.min(size.crownBase - STRAY_BELOW * depth, forkY !== undefined ? forkY - 0.5 : Infinity);
3244
+ const far = STRAY_BEYOND * size.crownRadius;
3245
+ const keep = new Uint8Array(sk.count);
3246
+ for (let i = 0; i < sk.count; i++) {
3247
+ const p = sk.parent[i];
3248
+ // (Under its crown only going down: a limb leaving a stem low and rising into the crown is the limb its crown
3249
+ // hangs on, not a stray. Shed from where it left, a cypress forked low, its limbs leaving its stems under the
3250
+ // crown's base and rising to its shelves, was a bare stump.)
3251
+ const out = sk.order[i] > 0 && !trunks?.[i] && ((sk.y[i] < low && (p < 0 || sk.y[i] < sk.y[p])) || Math.hypot(sk.x[i], sk.z[i]) > far);
3252
+ keep[i] = (p < 0 || keep[p]) && !out ? 1 : 0;
3253
+ }
3254
+ // (What is left bare by that goes too: a twig whose leaves were all on the wood shed past it is dead.)
3255
+ const on = [];
3256
+ for (let c = 0; c < cl.count; c++)
3257
+ if (keep[cl.node[c]])
3258
+ on.push([cl.node[c], cl.x[c], cl.y[c], cl.z[c], cl.radius[c]]);
3259
+ const bears = leafy(sk.count, sk.parent, sk.x, sk.y, sk.z, on, keep);
3260
+ let shed = 0;
3261
+ for (let i = 0; i < sk.count; i++) {
3262
+ if (cl.count > 0 && !bears[i])
3263
+ keep[i] = 0;
3264
+ if (!keep[i])
3265
+ shed++;
3266
+ }
3267
+ if (shed === 0)
3268
+ return { size, skeleton: sk, clumps: cl };
3269
+ const to = new Int32Array(sk.count).fill(-1);
3270
+ let n = 0;
3271
+ for (let i = 0; i < sk.count; i++)
3272
+ if (keep[i])
3273
+ to[i] = n++;
3274
+ const pick = (a, make) => {
3275
+ const b = make(n);
3276
+ for (let i = 0; i < sk.count; i++)
3277
+ if (keep[i])
3278
+ b[to[i]] = a[i];
3279
+ return b;
3280
+ };
3281
+ const skeleton = {
3282
+ count: n,
3283
+ x: pick(sk.x, (k) => new Float32Array(k)),
3284
+ y: pick(sk.y, (k) => new Float32Array(k)),
3285
+ z: pick(sk.z, (k) => new Float32Array(k)),
3286
+ radius: pick(sk.radius, (k) => new Float32Array(k)),
3287
+ parent: new Int32Array(n),
3288
+ order: pick(sk.order, (k) => new Uint8Array(k)),
3289
+ limb: new Int32Array(n),
3290
+ along: pick(sk.along, (k) => new Float32Array(k)),
3291
+ };
3292
+ for (let i = 0; i < sk.count; i++) {
3293
+ if (!keep[i])
3294
+ continue;
3295
+ skeleton.parent[to[i]] = sk.parent[i] < 0 ? -1 : to[sk.parent[i]];
3296
+ skeleton.limb[to[i]] = to[sk.limb[i]];
3297
+ }
3298
+ const kept = [];
3299
+ for (let c = 0; c < cl.count; c++)
3300
+ if (keep[cl.node[c]])
3301
+ kept.push(c);
3302
+ const m = kept.length;
3303
+ const f = () => new Float32Array(m);
3304
+ const clumps = { count: m, x: f(), y: f(), z: f(), radius: f(), nx: f(), ny: f(), nz: f(), node: new Int32Array(m), depth: f(), tx: f(), ty: f(), tz: f() };
3305
+ kept.forEach((c, k) => {
3306
+ for (const key of ["x", "y", "z", "radius", "nx", "ny", "nz", "depth", "tx", "ty", "tz"])
3307
+ clumps[key][k] = cl[key][c];
3308
+ clumps.node[k] = to[cl.node[c]];
3309
+ });
3310
+ return { size, skeleton, clumps };
3311
+ }
3312
+ /**
3313
+ * Dead stubs on a long clean bole, as many as the species keeps (`boleStubs`): the lower branches a tree
3314
+ * grown in a wood once had, died back in the shade above and broken off short. More of them high on the
3315
+ * bole, under the crown, where they died last; the low ones have long since rotted off and healed over.
3316
+ * Wood only: no leaves below the crown's base. (No living shoots from dormant buds: a leafless one reads
3317
+ * as a bare twig.)
3318
+ */
3319
+ function boleStubs(sp, tree, rng, stand) {
3320
+ // (A tree in a wood keeps the stubs of the branches the wood's shade killed, whatever its kind: a
3321
+ // conifer's too, its dead boughs.)
3322
+ const amount = Math.min(1, Math.max(0, sp.boleStubs ?? 0, stand ? STAND_STUBS * stand.enclosure : 0));
3323
+ const sk = tree.skeleton;
3324
+ const kinds = sp.architecture === "broadleaf" || (stand && sp.architecture === "conifer");
3325
+ if (amount <= 0 || !kinds || Math.round(sp.stems) > 1)
3326
+ return tree;
3327
+ // The bole: the first stem's nodes from its foot to the first that bears a branch.
3328
+ const bole = [0];
3329
+ for (;;) {
3330
+ const at = bole[bole.length - 1];
3331
+ let next = -1;
3332
+ let kids = 0;
3333
+ for (let i = at + 1; i < sk.count; i++) {
3334
+ if (sk.parent[i] !== at)
3335
+ continue;
3336
+ kids++;
3337
+ if (sk.order[i] === 0)
3338
+ next = i;
3339
+ }
3340
+ if (next < 0 || kids > 1)
3341
+ break;
3342
+ bole.push(next);
3343
+ }
3344
+ const top = sk.y[bole[bole.length - 1]];
3345
+ const from = Math.max(STUB_FROM, breastHeight(tree.size));
3346
+ // (Up to the crown's base; in a wood, up to the first living limb, where the wood's shade lifted it.)
3347
+ const length = STUB_TOP * (stand ? top : Math.min(top, tree.size.crownBase)) - from;
3348
+ const room = MAX_NODES + 100 - sk.count;
3349
+ const count = Math.min(Math.floor(room / 2), Math.round(amount * STUBS_PER_METRE * length));
3350
+ if (count < 1)
3351
+ return tree;
3352
+ const foot = sk.radius[0];
3353
+ const x = [];
3354
+ const y = [];
3355
+ const z = [];
3356
+ const radius = [];
3357
+ const parent = [];
3358
+ for (let k = 0; k < count; k++) {
3359
+ // (Squared towards the top: most stubs are just under the crown.)
3360
+ const want = from + length * Math.sqrt(rng.next());
3361
+ let at = bole[0];
3362
+ for (const b of bole)
3363
+ if (Math.abs(sk.y[b] - want) < Math.abs(sk.y[at] - want))
3364
+ at = b;
3365
+ if (sk.y[at] < from - 0.3)
3366
+ continue;
3367
+ const rb = sk.radius[at];
3368
+ // (A dead branch's stub is a thin one's: the thick lower limbs of a tree grown in a wood were few, and
3369
+ // what they leave is a scar, not a peg.)
3370
+ const r0 = Math.min(0.3 * rb, Math.max(STUB_THINNEST * foot, rb * rng.range(0.1, 0.2)));
3371
+ const len = Math.min(STUB_LONGEST, r0 * rng.range(5, 12)) * (0.6 + 0.4 * ((sk.y[at] - from) / Math.max(0.01, length)));
3372
+ // Off at the species' angle and a little lower: a dead branch has stopped turning to the light.
3373
+ const angle = Math.min(100 * DEG, (sp.branchAngle + rng.range(5, 35)) * DEG);
3374
+ const d = cone([0, 1, 0], angle, rng.range(0, 2 * Math.PI));
3375
+ const ax = sk.x[at] + d[0] * len;
3376
+ const ay = sk.y[at] + d[1] * len;
3377
+ const az = sk.z[at] + d[2] * len;
3378
+ x.push(ax);
3379
+ y.push(ay);
3380
+ z.push(az);
3381
+ radius.push(r0);
3382
+ parent.push(at);
3383
+ // (Broken off, not sawn: its end narrows over a little more, ragged, so its tube does not end in an open
3384
+ // ring.)
3385
+ const tip = r0 * rng.range(1, 2);
3386
+ x.push(ax + d[0] * tip);
3387
+ y.push(ay + d[1] * tip);
3388
+ z.push(az + d[2] * tip);
3389
+ radius.push(r0 * 0.35);
3390
+ parent.push(-1 - (x.length - 2));
3391
+ }
3392
+ const m = x.length;
3393
+ if (m === 0)
3394
+ return tree;
3395
+ const grow = (a, make) => {
3396
+ const b = make(sk.count + m);
3397
+ b.set(a);
3398
+ return b;
3399
+ };
3400
+ const out = {
3401
+ count: sk.count + m,
3402
+ x: grow(sk.x, (k) => new Float32Array(k)),
3403
+ y: grow(sk.y, (k) => new Float32Array(k)),
3404
+ z: grow(sk.z, (k) => new Float32Array(k)),
3405
+ radius: grow(sk.radius, (k) => new Float32Array(k)),
3406
+ parent: grow(sk.parent, (k) => new Int32Array(k)),
3407
+ order: grow(sk.order, (k) => new Uint8Array(k)),
3408
+ limb: grow(sk.limb, (k) => new Int32Array(k)),
3409
+ along: grow(sk.along, (k) => new Float32Array(k)),
3410
+ };
3411
+ for (let k = 0; k < m; k++) {
3412
+ const i = sk.count + k;
3413
+ // (A negative parent is one of these new nodes: the stub a tip ends.)
3414
+ const p = parent[k] < 0 ? sk.count + (-1 - parent[k]) : parent[k];
3415
+ out.x[i] = x[k];
3416
+ out.y[i] = y[k];
3417
+ out.z[i] = z[k];
3418
+ out.radius[i] = radius[k];
3419
+ out.parent[i] = p;
3420
+ out.order[i] = 1;
3421
+ out.limb[i] = out.order[p] === 0 ? i : out.limb[p];
3422
+ out.along[i] = out.along[p] + Math.hypot(out.x[i] - out.x[p], out.y[i] - out.y[p], out.z[i] - out.z[p]);
3423
+ }
3424
+ return { size: tree.size, skeleton: out, clumps: tree.clumps };
3425
+ }
3426
+ /** How close two clumps may be, as a share of their radii summed. */
3427
+ function thinGap(sp) {
3428
+ return (THIN + THIN_OPEN * sp.openness) * (sp.architecture === "palm" ? PALM_THIN : 1);
3429
+ }
3430
+ /** How many clumps a tree of a species keeps, at most. */
3431
+ function clumpCap(sp) {
3432
+ if (sp.architecture === "palm")
3433
+ return Math.round(MAX_CLUMPS * PALM_CLUMPS);
3434
+ return Math.round(MAX_CLUMPS * (1 + WEEP_CLUMPS * weepOf(sp)));
3435
+ }
3436
+ /** A species' share of whips, 0..1 (none for a conifer or a palm, which do not grow them). */
3437
+ function weepOf(sp) {
3438
+ if (sp.architecture !== "broadleaf" && sp.architecture !== "shrub")
3439
+ return 0;
3440
+ return Math.min(1, Math.max(0, sp.weep ?? 0));
3441
+ }
3442
+ /**
3443
+ * Thin the clumps that crowd each other, the outermost kept first (they make the crown's outline), so
3444
+ * no two are closer than a share of their radii summed: nearer in a solid crown, further in an open one.
3445
+ * If that still leaves more than a host should draw, again, wider.
3446
+ */
3447
+ function thin(sp, env, h) {
3448
+ const count = h.node.length;
3449
+ const spire = spired(sp);
3450
+ const outer = new Float64Array(count);
3451
+ for (let c = 0; c < count; c++)
3452
+ outer[c] = env.place(h.x[c], h.y[c], h.z[c], h.r[c]).depth;
3453
+ // A clump whose centre is out of the crown's outline, or that hangs half out of its base (or by more than
3454
+ // a twentieth of the crown's depth), is out of the light the crown grows to: dropped.
3455
+ const within = (c) => Math.hypot(h.x[c], h.z[c]) <= env.width(Math.min(env.hi, Math.max(env.lo, h.y[c]))) &&
3456
+ h.y[c] - 0.5 * h.r[c] >= env.lo &&
3457
+ h.y[c] - h.r[c] >= env.lo - 0.05 * (env.hi - env.lo);
3458
+ // (A whip's leaves first: a weeping tree is its curtain.)
3459
+ const byOuter = Array.from({ length: count }, (_, c) => c)
3460
+ .filter(within)
3461
+ .sort((a, b) => Number(h.whip[b]) - Number(h.whip[a]) || outer[a] - outer[b] || a - b);
3462
+ let rMax = 0;
3463
+ for (let c = 0; c < count; c++)
3464
+ rMax = Math.max(rMax, h.r[c]);
3465
+ const pass = (k) => {
3466
+ const cell = Math.max(1e-3, 2 * rMax * k);
3467
+ // A hashed grid: each cell's clumps chained through `next`, its first in `head`.
3468
+ const size = 4096;
3469
+ const head = new Int32Array(size).fill(-1);
3470
+ const next = new Int32Array(count).fill(-1);
3471
+ const key = (ix, iy, iz) => (Math.imul(ix, 73856093) ^ Math.imul(iy, 19349663) ^ Math.imul(iz, 83492791)) & (size - 1);
3472
+ const kept = [];
3473
+ for (const c of byOuter) {
3474
+ const ix = Math.floor(h.x[c] / cell);
3475
+ const iy = Math.floor(h.y[c] / cell);
3476
+ const iz = Math.floor(h.z[c] / cell);
3477
+ // (A conifer's spire is kept whole: its needles clothe the leader, close together.)
3478
+ let free = true;
3479
+ if (spire && h.whip[c]) {
3480
+ kept.push(c);
3481
+ const kc = key(ix, iy, iz);
3482
+ next[c] = head[kc];
3483
+ head[kc] = c;
3484
+ continue;
3485
+ }
3486
+ for (let a = -1; a <= 1 && free; a++)
3487
+ for (let b = -1; b <= 1 && free; b++)
3488
+ for (let d = -1; d <= 1 && free; d++) {
3489
+ for (let o = head[key(ix + a, iy + b, iz + d)]; o >= 0; o = next[o]) {
3490
+ const gap = k * (h.r[c] + h.r[o]);
3491
+ const dx = h.x[c] - h.x[o];
3492
+ const dy = h.y[c] - h.y[o];
3493
+ const dz = h.z[c] - h.z[o];
3494
+ if (dx * dx + dy * dy + dz * dz < gap * gap) {
3495
+ free = false;
3496
+ break;
3497
+ }
3498
+ }
3499
+ }
3500
+ if (!free)
3501
+ continue;
3502
+ kept.push(c);
3503
+ const kc = key(ix, iy, iz);
3504
+ next[c] = head[kc];
3505
+ head[kc] = c;
3506
+ }
3507
+ return kept;
3508
+ };
3509
+ // Clumps fill a shell, so their count goes as the spacing's inverse square: each pass widens it by
3510
+ // that, and a little more, so few passes are needed.
3511
+ let k = thinGap(sp);
3512
+ const most = clumpCap(sp);
3513
+ let kept = pass(k);
3514
+ // A weeping tree keeps its whips' leaves as they are, and loses the deepest of the rest.
3515
+ if (weepOf(sp) > 0)
3516
+ return kept.slice(0, most).sort((a, b) => a - b);
3517
+ for (let tries = 0; tries < 4 && kept.length > most; tries++) {
3518
+ k *= 1.05 * Math.sqrt(kept.length / most);
3519
+ kept = pass(k);
3520
+ }
3521
+ return kept.sort((a, b) => a - b);
3522
+ }
3523
+ /**
3524
+ * What the fit and the wood's sag pushed out of the crown's outline is drawn back in to it, square to the
3525
+ * trunk, its clumps with it (and any clump still out, after it): a twig the shears would have taken.
3526
+ */
3527
+ function keepToOutline(env, w, h) {
3528
+ const n = w.x.length;
3529
+ const dx = new Float64Array(n);
3530
+ const dz = new Float64Array(n);
3531
+ for (let i = 0; i < n; i++) {
3532
+ if (w.parent[i] < 0)
3533
+ continue;
3534
+ const wd = env.width(Math.min(env.hi, Math.max(env.lo, w.y[i])));
3535
+ const d = Math.hypot(w.x[i], w.z[i]);
3536
+ if (wd <= 0 || d <= wd)
3537
+ continue;
3538
+ const k = wd / d;
3539
+ dx[i] = w.x[i] * (k - 1);
3540
+ dz[i] = w.z[i] * (k - 1);
3541
+ w.x[i] += dx[i];
3542
+ w.z[i] += dz[i];
3543
+ }
3544
+ for (let c = 0; c < h.node.length; c++) {
3545
+ h.x[c] += dx[h.node[c]];
3546
+ h.z[c] += dz[h.node[c]];
3547
+ const wd = env.width(Math.min(env.hi, Math.max(env.lo, h.y[c])));
3548
+ const d = Math.hypot(h.x[c], h.z[c]);
3549
+ if (wd > 0 && d > wd) {
3550
+ h.x[c] *= wd / d;
3551
+ h.z[c] *= wd / d;
3552
+ }
3553
+ }
3554
+ }
3555
+ /**
3556
+ * Fit the grown tree to its size: across, about its axis, so its outermost clump reaches the crown
3557
+ * radius; and up, so its highest leaf is at its height and (when the growing missed it by more than a
3558
+ * little) its lowest at its crown's base, stretching the crown and the trunk under it apart. The growing
3559
+ * aims at all three already; this takes up what it misses by.
3560
+ */
3561
+ function fit(size, w, h, keep, lifted = false, below = 0) {
3562
+ let reach = 0;
3563
+ let topY = 0;
3564
+ let lowY = Infinity;
3565
+ for (const c of keep) {
3566
+ reach = Math.max(reach, Math.hypot(h.x[c], h.z[c]) + h.r[c]);
3567
+ topY = Math.max(topY, h.y[c] + h.r[c]);
3568
+ lowY = Math.min(lowY, h.y[c] - h.r[c]);
3569
+ }
3570
+ for (let i = 0; i < w.y.length; i++)
3571
+ topY = Math.max(topY, w.y[i]);
3572
+ const across = reach > 0 ? (FIT_REACH * size.crownRadius) / reach : 1;
3573
+ const depth = Math.max(0.01, size.height - size.crownBase);
3574
+ // The pivot: the crown's base, or its lowest leaf if that is off the base and there is trunk under it to stretch.
3575
+ let from = size.crownBase;
3576
+ let to = size.crownBase;
3577
+ const off = lowY - size.crownBase;
3578
+ // (A crown its stand has lifted keeps its lowest leaves where they grew: down to the crown's base on its open
3579
+ // side, if it has one, and no lower; inside a wood, higher.)
3580
+ if (Number.isFinite(lowY) && ((off > FIT_LOW * depth && !lifted) || off < -FIT_HANG * depth) && lowY > 0.01 * size.height && size.crownBase > 0.03 * size.height) {
3581
+ from = lowY;
3582
+ to = size.crownBase + 0.5 * FIT_LOW * depth;
3583
+ }
3584
+ const upward = topY > from ? (FIT_TOP * size.height - to) / (topY - from) : 1;
3585
+ // (A trunk that forks or a clump's root plate keeps where its stems part, and their first pieces, as grown:
3586
+ // what is stretched is the trunk over them. So a fork kept clear of breast height stays clear of it.)
3587
+ const clear = breastHeight(size) + FORK_CLEAR_BH + 0.15;
3588
+ const keepTo = Math.min(Math.max(0.8 * to, Math.min(to - 0.1, clear)), Math.max(0.8 * from, Math.min(from - 0.1, clear)));
3589
+ const b = Math.max(0, Math.min(below, keepTo));
3590
+ const stretch = (y) => (y > from ? to + (y - from) * upward : from <= 0 ? y : y <= b ? y : b + ((y - b) * (to - b)) / (from - b));
3591
+ for (let i = 0; i < w.x.length; i++) {
3592
+ w.x[i] *= across;
3593
+ w.z[i] *= across;
3594
+ w.y[i] = stretch(w.y[i]);
3595
+ }
3596
+ for (let c = 0; c < h.node.length; c++) {
3597
+ h.x[c] *= across;
3598
+ h.z[c] *= across;
3599
+ h.y[c] = stretch(h.y[c]);
3600
+ }
3601
+ }
3602
+ /**
3603
+ * The pipe model (Shinozaki et al. 1964, after da Vinci), with a twig's end 1: a branch's cross-section,
3604
+ * r^PIPE, carries all the twigs beyond it, the pipes of the branches it has shed, and the disused pipes
3605
+ * its own length has gathered. `unit` is an internode's length.
3606
+ */
3607
+ function pipeUnits(w, unit) {
3608
+ const n = w.x.length;
3609
+ const pipes = new Float64Array(n);
3610
+ const r = new Float64Array(n);
3611
+ for (let i = n - 1; i >= 0; i--) {
3612
+ let a = w.shed ? w.shed[i] : 0;
3613
+ const kids = w.kids[i];
3614
+ if (kids.length === 0)
3615
+ a += 1;
3616
+ for (const c of kids) {
3617
+ const len = Math.hypot(w.x[c] - w.x[i], w.y[c] - w.y[i], w.z[c] - w.z[i]);
3618
+ a += pipes[c] * (1 + (DISUSED * len) / unit);
3619
+ }
3620
+ pipes[i] = a;
3621
+ r[i] = a ** (1 / PIPE);
3622
+ }
3623
+ return r;
3624
+ }
3625
+ /** An internode's length on a tree of a size: the crown's size over INTERNODES. */
3626
+ function unitOf(size) {
3627
+ return Math.cbrt(size.crownRadius * size.crownRadius * Math.max(0.01, size.height - size.crownBase)) / INTERNODES;
3628
+ }
3629
+ /**
3630
+ * A stem's bole: its nodes from its start (its foot, or where it leaves a trunk that forks) up its own axis
3631
+ * to the first that bears a branch of its own (the lowest live limb, where the crown starts), that node last.
3632
+ * A trunk that forks into stems (each a stem of its own: `Wood.stem`) runs on through the nodes they leave,
3633
+ * to the last of them.
3634
+ */
3635
+ function trunkBole(w, start) {
3636
+ const out = [start];
3637
+ const s = w.stem[start];
3638
+ let at = start;
3639
+ for (;;) {
3640
+ const kids = w.kids[at];
3641
+ const next = kids.find((c) => w.cont[c] && w.stem[c] === s);
3642
+ if (next === undefined || kids.some((c) => c !== next && w.stem[c] === s))
3643
+ return out;
3644
+ at = next;
3645
+ out.push(at);
3646
+ }
3647
+ }
3648
+ /** A stem's leader: from where it starts, on along it (its own stem's next node on its axis) to its top. */
3649
+ function stemLeader(w, start) {
3650
+ const out = [start];
3651
+ const s = w.stem[start];
3652
+ for (let at = start;;) {
3653
+ const next = w.kids[at].find((c) => w.cont[c] && w.stem[c] === s);
3654
+ if (next === undefined)
3655
+ return out;
3656
+ at = next;
3657
+ out.push(at);
3658
+ }
3659
+ }
3660
+ /** Where each stem starts: its foot, or where it leaves the trunk it forks from. Parents first. */
3661
+ function stemStarts(w) {
3662
+ const out = [];
3663
+ for (let i = 0; i < w.x.length; i++) {
3664
+ const p = w.parent[i];
3665
+ if (p < 0 || w.stem[p] !== w.stem[i])
3666
+ out.push(i);
3667
+ }
3668
+ return out;
3669
+ }
3670
+ /** The stems that leave a bole (a trunk forking, or a clump's root plate): their starts. */
3671
+ function stemsOff(w, bole) {
3672
+ const out = [];
3673
+ for (const b of bole)
3674
+ for (const c of w.kids[b])
3675
+ if (w.stem[c] !== w.stem[b])
3676
+ out.push(c);
3677
+ return out;
3678
+ }
3679
+ /** How far up a stem its root flare reaches (m): its e-folding height, more for a thicker trunk, under breast height. */
3680
+ export function flareHeight(size, buttress = 0) {
3681
+ const b = Math.min(1, Math.max(0, buttress));
3682
+ return Math.min((0.4 + 0.25 * b) * breastHeight(size), (FLARE_FROM + FLARE_PER_RADIUS * size.trunkRadius) * (1 + b));
3683
+ }
3684
+ /**
3685
+ * The shape of a bole's taper, as a radius at a height to be scaled: a power of the length of stem still
3686
+ * above (Behre's and Kozak's taper curves are near this between the butt and the crown), swollen at its
3687
+ * foot where the roots flare out.
3688
+ */
3689
+ function boleShape(size, y, buttress = 0) {
3690
+ const H = Math.max(0.1, size.height);
3691
+ const above = Math.max(0.02, (H - y) / H);
3692
+ return above ** BOLE_TAPER * (1 + FLARE * (1 + FLARE_BUTTRESS * buttress) * Math.exp(-Math.max(0, y) / flareHeight(size, buttress)));
3693
+ }
3694
+ /**
3695
+ * A bole's long bare pieces cut shorter, and more finely near its foot, where the root flare swells it: so
3696
+ * its taper is drawn as a smooth curve and not as cones stacked on cones. The new nodes lie on the pieces
3697
+ * they cut, so nothing moves; a clump keeps to its node.
3698
+ */
3699
+ function refineBoles(size, w, h, buttress = 0) {
3700
+ const n = w.x.length;
3701
+ const bh = breastHeight(size);
3702
+ const hf = flareHeight(size, buttress);
3703
+ /** For each node, the heights at which to cut the piece under it. */
3704
+ const cuts = new Map();
3705
+ for (const start of stemStarts(w)) {
3706
+ const bole = trunkBole(w, start);
3707
+ // (A stem's under breast height is a shrub's, of the pipe model: but not a root plate that stems leave.)
3708
+ if (w.y[bole[bole.length - 1]] <= bh && stemsOff(w, bole).length === 0)
3709
+ continue;
3710
+ // (A stem off a forked trunk from the piece under its start.)
3711
+ for (let k = w.parent[start] >= 0 ? 0 : 1; k < bole.length; k++) {
3712
+ const c = bole[k];
3713
+ const y0 = w.y[w.parent[c]];
3714
+ const y1 = w.y[c];
3715
+ const ys = [];
3716
+ // (Not the first piece of a stem leaving a forked trunk: it narrows from the trunk to itself along it,
3717
+ // and cut, it would narrow at the cut, a ledge.)
3718
+ if (k > 0 || w.parent[start] < 0)
3719
+ for (const f of FLARE_CUTS)
3720
+ if (f * hf > y0 + 0.05 && f * hf < y1 - 0.05)
3721
+ ys.push(f * hf);
3722
+ const from = ys.length > 0 ? ys[ys.length - 1] : y0;
3723
+ const pieces = Math.ceil((y1 - from) / BOLE_PIECE - 1e-9);
3724
+ for (let m = 1; m < pieces; m++)
3725
+ ys.push(from + ((y1 - from) * m) / pieces);
3726
+ if (ys.length > 0)
3727
+ cuts.set(c, ys);
3728
+ }
3729
+ }
3730
+ if (cuts.size === 0)
3731
+ return;
3732
+ const out = newWood();
3733
+ const shed = [];
3734
+ const remap = new Int32Array(n);
3735
+ for (let i = 0; i < n; i++) {
3736
+ const p = w.parent[i];
3737
+ let parent = p < 0 ? -1 : remap[p];
3738
+ const ys = cuts.get(i);
3739
+ // (The first piece cut keeps the node's place on its parent: a stem leaving a fork leaves it as it did.)
3740
+ let cont = w.cont[i];
3741
+ if (ys && p >= 0) {
3742
+ for (const y of ys) {
3743
+ const f = (y - w.y[p]) / Math.max(1e-9, w.y[i] - w.y[p]);
3744
+ parent = addNode(out, w.x[p] + (w.x[i] - w.x[p]) * f, y, w.z[p] + (w.z[i] - w.z[p]) * f, parent, cont);
3745
+ out.stem[parent] = w.stem[i];
3746
+ shed.push(0);
3747
+ cont = true;
3748
+ }
3749
+ }
3750
+ remap[i] = addNode(out, w.x[i], w.y[i], w.z[i], parent, cont);
3751
+ out.stem[remap[i]] = w.stem[i];
3752
+ shed.push(w.shed ? w.shed[i] : 0);
3753
+ }
3754
+ for (let c = 0; c < h.node.length; c++)
3755
+ h.node[c] = remap[h.node[c]];
3756
+ w.x = out.x;
3757
+ w.y = out.y;
3758
+ w.z = out.z;
3759
+ w.parent = out.parent;
3760
+ w.cont = out.cont;
3761
+ w.kids = out.kids;
3762
+ w.stem = out.stem;
3763
+ w.shed = shed;
3764
+ }
3765
+ /**
3766
+ * The radii (m). A stem whose crown starts above breast height has a bole: it is given its taper
3767
+ * (`boleShape`), scaled to the size's trunk radius at breast height, and its crown the pipe model's radii,
3768
+ * scaled to meet the bole where the crown starts. The pipe model alone would make the bole of the wood a
3769
+ * small crown has carried and lost: a long clean bole under a narrow crown, reckoned in that crown's short
3770
+ * internodes, swells to many times its top's thickness, a thread under the crown. A real bole's taper is
3771
+ * its own growth over years, not its crown's twigs. A stem whose crown starts low (a shrub's) is the pipe
3772
+ * model's, scaled so its radius at breast height is the trunk radius.
3773
+ */
3774
+ function pipeRadii(size, w, buttress = 0) {
3775
+ const n = w.x.length;
3776
+ const r = pipeUnits(w, unitOf(size));
3777
+ const bh = breastHeight(size);
3778
+ const scale = new Float64Array(w.stems).fill(1);
3779
+ const boleR = new Float64Array(n).fill(-1);
3780
+ const shape = (y) => boleShape(size, y, buttress);
3781
+ /** A stem's bole tapered as a bole does, from a radius at a height; its crown scaled to meet it where it starts. */
3782
+ const taper = (bole, r0, y0, swell = () => 1) => {
3783
+ for (const b of bole)
3784
+ boleR[b] = (r0 * shape(w.y[b]) * swell(w.y[b])) / (shape(y0) * swell(y0));
3785
+ const top = bole[bole.length - 1];
3786
+ scale[w.stem[top]] = boleR[top] / r[top];
3787
+ };
3788
+ for (let i = 0; i < n; i++) {
3789
+ if (w.parent[i] >= 0)
3790
+ continue;
3791
+ const bole = trunkBole(w, i);
3792
+ const top = bole[bole.length - 1];
3793
+ const stems = stemsOff(w, bole);
3794
+ if (stems.length > 0) {
3795
+ // A trunk that forks into stems, or a clump's root plate: its stems share its wood by their area (the
3796
+ // pipe model with Leonardo's 2), each tapering as a bole does to its own crown. Forked under breast
3797
+ // height, their areas there together are the trunk's (what a survey measures of a clump is its stems'
3798
+ // basal area); above it, the trunk is measured there, as one stem is.
3799
+ const boles = stems.map((c) => trunkBole(w, c));
3800
+ let total = 0;
3801
+ for (const c of stems)
3802
+ total += r[c] * r[c];
3803
+ const share = stems.map((c) => (r[c] * r[c]) / Math.max(1e-12, total));
3804
+ const yTop = w.y[top];
3805
+ // (Each stem swells a little into the trunk where it leaves it, as a limb's collar does: fused there.)
3806
+ const join = (y) => 1 + STEM_JOIN * Math.exp(-Math.max(0, y - yTop) / (STEM_JOIN_FALL * stemFirst(size)));
3807
+ if (yTop >= bh) {
3808
+ taper(bole, size.trunkRadius, bh);
3809
+ stems.forEach((c, k) => {
3810
+ const yP = w.y[w.parent[c]];
3811
+ taper(boles[k], boleR[w.parent[c]] * Math.sqrt(share[k]) * (shape(w.y[c]) / shape(yP)), w.y[c], join);
3812
+ });
3813
+ }
3814
+ else {
3815
+ let area = 0;
3816
+ stems.forEach((_, k) => {
3817
+ const rs = size.trunkRadius * Math.sqrt(share[k]);
3818
+ taper(boles[k], rs, bh, join);
3819
+ area += ((rs * shape(yTop)) / shape(bh)) ** 2;
3820
+ });
3821
+ taper(bole, Math.sqrt(area), yTop);
3822
+ }
3823
+ continue;
3824
+ }
3825
+ if (w.y[top] > bh) {
3826
+ taper(bole, size.trunkRadius, bh);
3827
+ continue;
3828
+ }
3829
+ // Each stem's radius at breast height, along its axis from its foot.
3830
+ let at = i;
3831
+ let measured = r[i];
3832
+ for (;;) {
3833
+ const next = w.kids[at].find((c) => w.cont[c]);
3834
+ if (next === undefined) {
3835
+ measured = r[at];
3836
+ break;
3837
+ }
3838
+ if (w.y[next] >= bh) {
3839
+ const f = (bh - w.y[at]) / Math.max(1e-9, w.y[next] - w.y[at]);
3840
+ measured = r[at] + (r[next] - r[at]) * Math.min(1, Math.max(0, f));
3841
+ break;
3842
+ }
3843
+ at = next;
3844
+ }
3845
+ scale[w.stem[i]] = size.trunkRadius / measured;
3846
+ }
3847
+ for (let i = 0; i < n; i++)
3848
+ r[i] = boleR[i] >= 0 ? boleR[i] : r[i] * scale[w.stem[i]];
3849
+ return r;
3850
+ }
3851
+ //# sourceMappingURL=grow.js.map