bevy_flora 0.5.0

Parametric, stylized procedural trees for Bevy that grow over time: 15 presets, bent and forking branches, leaf styles, deterministic per seed.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
//! Leaf placement on the (aged) skeleton and leaf geometry.

use bevy::math::{Vec2, Vec3, Vec4};
use std::f32::consts::{PI, TAU};

use crate::growth::GrowthParams;
use crate::mesh::MeshData;
use crate::params::{FoliageParams, FoliagePlacement, LeafOrientation, LeafStyle, TrunkParams};
use crate::rng::SeededRng;
use crate::skeleton::{Node, NodeKind, Skeleton, trunk_depth};

/// Separate random stream for leaf tints, so adding them does not change any
/// existing draw (leaf positions, sizes and rotations stay as in 0.1).
const LEAF_TINT_SALT: i32 = 0x7135_1EAF;

/// Separate random stream for leaf hues, for the same reason.
const LEAF_HUE_SALT: i32 = 0x4E0E_1EAF;

/// One leaf: where it sits and how it is oriented.
#[derive(Clone, Debug, PartialEq)]
pub struct LeafPoint {
    /// World-space (tree-local) position of the leaf, in metres.
    pub position: Vec3,
    /// Primary orientation.
    pub direction: Vec3,
    /// Leaf size in metres (base-to-tip length for leaf-shaped cards).
    pub size: f32,
    /// Rotation around `direction`, radians.
    pub rotation: f32,
    /// Per-leaf colour draw in -1..1, scaled by [`FoliageParams::color_variation`].
    pub tint: f32,
    /// Per-leaf hue draw in −1..1, scaled by [`FoliageParams::hue_variation`].
    pub hue: f32,
}

/// Leaf points for every node of `skeleton`.
///
/// Each node draws from its own RNG stream (keyed by the node's id in the
/// full skeleton), so aging the tree never re-rolls other nodes' leaves.
pub fn collect_leaf_points(
    skeleton: &Skeleton,
    foliage: &FoliageParams,
    growth: &GrowthParams,
    trunk: &TrunkParams,
    seed: i32,
) -> Vec<LeafPoint> {
    let mut points = Vec::new();
    if !foliage.enabled {
        return points;
    }
    for i in 0..skeleton.nodes.len() {
        leaf_points_for_node(skeleton, i, foliage, growth, trunk, seed, &mut points);
    }
    points
}

/// Growth scale of `node`'s leaves: 0 until `progress` passes
/// [`GrowthParams::leaf_threshold`], 1 once the node is fully grown. Leaf size
/// (and a tip cluster's radius) is proportional to it.
pub(crate) fn node_leaf_scale(node: &Node, growth: &GrowthParams) -> f32 {
    if growth.leaf_threshold >= 1.0 {
        if node.progress >= 1.0 { 1.0 } else { 0.0 }
    } else {
        ((node.progress - growth.leaf_threshold) / (1.0 - growth.leaf_threshold)).clamp(0.0, 1.0)
    }
}

/// Leaves along a branch of `length` metres under
/// [`FoliagePlacement::AllBranches`]: at least one, more on longer wood.
pub(crate) fn distributed_leaf_count(foliage: &FoliageParams, length: f32, height_ratio: f32) -> i32 {
    let height_mod = height_modifier(height_ratio, foliage);
    ((foliage.density * length * height_mod) as i32).max(1)
}

/// Append the leaf points of node `i` to `points`.
#[allow(clippy::too_many_arguments)]
pub fn leaf_points_for_node(
    skeleton: &Skeleton,
    i: usize,
    foliage: &FoliageParams,
    growth: &GrowthParams,
    trunk: &TrunkParams,
    seed: i32,
    points: &mut Vec<LeafPoint>,
) {
    let node = &skeleton.nodes[i];
    // A sub-branch shortened to nothing by `keep_out_of_trunk` starts inside
    // the trunk: it has no wood to carry leaves.
    if node.kind == NodeKind::Trunk || node.length <= 0.0 {
        return;
    }

    let leaf_scale = node_leaf_scale(node, growth);
    if leaf_scale <= 0.0 {
        return;
    }

    // Threshold on the mature radius so the decision does not change with age.
    let full_tip_radius = if node.radius_progress > 0.0 {
        node.tip_radius / node.radius_progress
    } else {
        node.tip_radius
    };
    if trunk.radius > 0.0
        && full_tip_radius / trunk.radius > foliage.radius_threshold
        && foliage.placement != FoliagePlacement::AllBranches
    {
        return;
    }

    let mut rng = SeededRng::from_parts(seed, node.id);
    let first = points.len();
    let ctx = NodeCtx {
        wood: node,
        end: skeleton.end(i),
        direction: node.direction,
        length: node.length,
        height_ratio: node.height_ratio,
        trunk,
        seed,
        leaf_scale,
    };

    match foliage.placement {
        FoliagePlacement::TerminalBranches => {
            if skeleton.is_terminal(i) {
                add_terminal_leaves(points, &ctx, foliage, &mut rng);
            }
        }
        FoliagePlacement::AllBranches => add_distributed_leaves(points, &ctx, foliage, &mut rng),
        FoliagePlacement::TipClusters => {
            if skeleton.is_terminal(i) {
                add_cluster_leaves(points, &ctx, foliage, &mut rng);
            }
        }
    }

    // Tints come from their own stream, drawn in leaf order, so a node's
    // leaves keep their tints as the tree ages.
    let mut tint_rng = SeededRng::from_parts(seed ^ LEAF_TINT_SALT, node.id);
    for p in &mut points[first..] {
        p.tint = tint_rng.range(-1.0, 1.0);
    }

    let mut hue_rng = SeededRng::from_parts(seed ^ LEAF_HUE_SALT, node.id);
    for p in &mut points[first..] {
        p.hue = hue_rng.range(-1.0, 1.0);
    }

    if leaf_scale < 1.0 {
        for p in &mut points[first..] {
            p.size *= leaf_scale;
        }
    }
}

struct NodeCtx<'a> {
    /// The node itself; leaves along it follow its (bent) axis.
    wood: &'a Node,
    /// Leaves around a tip must not end up inside the trunk.
    trunk: &'a TrunkParams,
    seed: i32,
    end: Vec3,
    direction: Vec3,
    length: f32,
    height_ratio: f32,
    /// Growth scale of this node's leaves (0..1); tip clusters shrink with it.
    leaf_scale: f32,
}

fn add_terminal_leaves(
    points: &mut Vec<LeafPoint>,
    node: &NodeCtx,
    foliage: &FoliageParams,
    rng: &mut SeededRng,
) {
    let height_mod = height_modifier(node.height_ratio, foliage);
    let count = ((foliage.density * height_mod) as i32).max(1);
    for _ in 0..count {
        let size = foliage.leaf_size
            * (1.0 + rng.range(-foliage.leaf_size_variation, foliage.leaf_size_variation));
        let direction = leaf_direction(node, foliage, rng);
        let offset = rng.range(0.0, node.length * 0.2);
        let along = if node.length > 0.0 { 1.0 - offset / node.length } else { 1.0 };
        points.push(LeafPoint {
            position: node.wood.point_at(along),
            direction,
            size,
            rotation: rng.range(0.0, TAU) * foliage.rotation_variation,
            tint: 0.0,
            hue: 0.0,
        });
    }
}

fn add_distributed_leaves(
    points: &mut Vec<LeafPoint>,
    node: &NodeCtx,
    foliage: &FoliageParams,
    rng: &mut SeededRng,
) {
    let count = distributed_leaf_count(foliage, node.length, node.height_ratio);
    for i in 0..count {
        let t = (i as f32 + rng.range(0.0, 1.0)) / count as f32;
        let biased_t = t * t;
        let position = node.wood.point_at(0.3 + biased_t * 0.7);
        let size = foliage.leaf_size
            * (1.0 + rng.range(-foliage.leaf_size_variation, foliage.leaf_size_variation));
        let direction = leaf_direction(node, foliage, rng);
        points.push(LeafPoint {
            position,
            direction,
            size,
            rotation: rng.range(0.0, TAU) * foliage.rotation_variation,
            tint: 0.0,
            hue: 0.0,
        });
    }
}

fn add_cluster_leaves(
    points: &mut Vec<LeafPoint>,
    node: &NodeCtx,
    foliage: &FoliageParams,
    rng: &mut SeededRng,
) {
    let height_mod = height_modifier(node.height_ratio, foliage);
    let count = ((foliage.cluster_size as f32 * height_mod) as i32).max(1);
    // Leaves fill a ball within 3/4 of a leaf of the tip, so each one
    // overlaps the twig end instead of floating on a shell around it. The
    // ball shrinks with the leaves while the node is young.
    let cluster_radius = foliage.leaf_size * 0.75 * node.leaf_scale;
    for _ in 0..count {
        let theta = rng.range(0.0, TAU);
        let phi = rng.range(0.0, PI);
        let r = cluster_radius * rng.range(0.0, 1.0);
        let mut offset = Vec3::new(
            r * phi.sin() * theta.cos(),
            r * phi.sin() * theta.sin(),
            r * phi.cos(),
        );
        // Twigs near the trunk would put part of the sphere inside it; the
        // mirrored point is outside (the tip is, and the trunk is convex).
        if trunk_depth(node.trunk, node.seed, node.end + offset) > 0.0 {
            offset = -offset;
        }
        let size = foliage.leaf_size
            * (1.0 + rng.range(-foliage.leaf_size_variation, foliage.leaf_size_variation));
        points.push(LeafPoint {
            position: node.end + offset,
            direction: offset.normalize_or_zero(),
            size,
            rotation: rng.range(0.0, TAU) * foliage.rotation_variation,
            tint: 0.0,
            hue: 0.0,
        });
    }
}

fn height_modifier(height_ratio: f32, foliage: &FoliageParams) -> f32 {
    if !foliage.use_crown_density {
        return 1.0;
    }
    let base = 1.0 - foliage.height_falloff;
    base + height_ratio * foliage.height_falloff
}

fn leaf_direction(node: &NodeCtx, foliage: &FoliageParams, rng: &mut SeededRng) -> Vec3 {
    let base_dir = match foliage.orientation {
        LeafOrientation::RadialOutward => {
            let horizontal = Vec3::new(node.end.x, 0.0, node.end.z);
            if horizontal.length_squared() > 0.001 {
                horizontal.normalize()
            } else {
                Vec3::X
            }
        }
        LeafOrientation::FollowBranch => node.direction,
        LeafOrientation::RandomUpward => Vec3::new(
            rng.range(-1.0, 1.0),
            rng.range(0.2, 1.0),
            rng.range(-1.0, 1.0),
        )
        .normalize_or_zero(),
        LeafOrientation::HorizontalSpread => {
            let angle = rng.range(0.0, TAU);
            Vec3::new(angle.cos(), 0.0, angle.sin())
        }
    };
    Vec3::new(base_dir.x, base_dir.y - foliage.droop, base_dir.z).normalize_or_zero()
}

/// Geometry for all `points` in `foliage.style`.
///
/// Each leaf gets a vertex colour (its tint scaled by
/// [`FoliageParams::color_variation`], its hue by [`FoliageParams::hue_variation`]), every
/// normal is bent toward pointing out of the crown by [`FoliageParams::normal_bend`], and the
/// leaf shader's inputs are baked in: `uv1.x` flags the upper side of each card, `uv1.y` is the
/// crown visibility ([`FoliageParams::occlusion`]) and `sway` is the flutter vector.
pub fn foliage_mesh(points: &[LeafPoint], foliage: &FoliageParams) -> MeshData {
    foliage_mesh_with(points, foliage, None)
}

/// [`foliage_mesh`] that also records, when `firsts` is given, the index of
/// each leaf's first vertex (one entry per point, in order).
pub(crate) fn foliage_mesh_with(
    points: &[LeafPoint],
    foliage: &FoliageParams,
    mut firsts: Option<&mut Vec<u32>>,
) -> MeshData {
    let mut mesh = MeshData::default();
    if points.is_empty() {
        return mesh;
    }
    let variation = foliage.color_variation.clamp(0.0, 0.5);
    let hue_span = foliage.hue_variation.clamp(0.0, 0.5);
    let mut ranges = Vec::with_capacity(points.len());
    for point in points {
        let first = mesh.positions.len();
        if let Some(firsts) = firsts.as_deref_mut() {
            firsts.push(first as u32);
        }
        match foliage.style {
            LeafStyle::CrossedPlanes => crossed_planes(&mut mesh, point),
            LeafStyle::SingleQuad => single_quad(&mut mesh, point),
            LeafStyle::ClusterSphere => cluster_sphere(&mut mesh, point),
            LeafStyle::StarBurst => star_burst(&mut mesh, point),
            LeafStyle::NeedleCluster => needle_cluster(&mut mesh, point),
        }
        let end = mesh.positions.len();
        ranges.push((first, end));

        // Normals are still the cards' own here, which is what tells the sides apart.
        let factor = 1.0 + point.tint * variation;
        let hue = point.hue * hue_span;
        mesh.colors.resize(
            end,
            Vec4::new(
                factor * (1.0 + 0.6 * hue),
                factor * (1.0 + 0.1 * hue),
                factor * (1.0 - 0.6 * hue),
                1.0,
            ),
        );
        mesh.uv1.extend(
            mesh.normals[first..end]
                .iter()
                .map(|&n| Vec2::new(if is_upper(n) { 1.0 } else { 0.0 }, 1.0)),
        );

        // One flutter direction and phase per leaf; both faces and both crossed cards share them.
        let (_, _, forward) = build_basis(point.direction, point.rotation);
        let phase = (point.position.dot(Vec3::new(12.9898, 78.233, 37.719)).sin() * 43_758.547)
            .fract()
            .abs();
        let rigid = foliage.style == LeafStyle::ClusterSphere;
        for &vertex in &mesh.positions[first..end] {
            let lever = if rigid { point.size * 0.4 } else { (vertex - point.position).length() };
            mesh.sway.push((forward * lever).extend(phase));
        }
    }

    let center = points.iter().map(|p| p.position).sum::<Vec3>() / points.len() as f32;

    // Leaves deep in the crown see less sky.
    if points.len() >= 2 {
        let occlusion = foliage.occlusion.clamp(0.0, 1.0);
        let extent = points
            .iter()
            .fold(Vec3::ZERO, |m, p| m.max((p.position - center).abs()))
            .max(Vec3::splat(1e-3));
        for (point, &(first, end)) in points.iter().zip(&ranges) {
            let rel = (point.position - center) / extent;
            let d = rel.length().min(1.0);
            let up = rel.y.clamp(-1.0, 1.0);
            let openness = (0.8 * d + 0.2 * (0.5 * up + 0.5)).clamp(0.0, 1.0);
            let visibility = 1.0 - occlusion * (1.0 - openness);
            for uv in &mut mesh.uv1[first..end] {
                uv.y = visibility;
            }
        }
    }

    let bend = foliage.normal_bend.clamp(0.0, 1.0);
    if bend > 0.0 {
        for (normal, &position) in mesh.normals.iter_mut().zip(&mesh.positions) {
            let out = (position - center).normalize_or(Vec3::Y);
            *normal = normal.lerp(out, bend).normalize_or(out);
        }
    }
    mesh
}

/// Two leaf cards at 90° sharing `up`. Their bases meet at the leaf point and
/// the tips reach one `size` along `up`, so the leaf grows out of its stem
/// instead of being threaded on it.
fn crossed_planes(mesh: &mut MeshData, point: &LeafPoint) {
    let half = point.size * 0.5;
    let (right, up, forward) = build_basis(point.direction, point.rotation);
    let center = point.position + up * half;
    add_double_sided_leaf(mesh, center, right * half, up * half);
    add_double_sided_leaf(mesh, center, forward * half, up * half);
}

/// One leaf card, base at the leaf point and tip one `size` along `up`.
fn single_quad(mesh: &mut MeshData, point: &LeafPoint) {
    let half = point.size * 0.5;
    let (right, up, _) = build_basis(point.direction, point.rotation);
    add_double_sided_leaf(mesh, point.position + up * half, right * half, up * half);
}

/// Octahedron.
fn cluster_sphere(mesh: &mut MeshData, point: &LeafPoint) {
    let size = point.size * 0.4;
    let c = point.position;
    let top = c + Vec3::Y * size;
    let bottom = c - Vec3::Y * size;
    let front = c + Vec3::NEG_Z * size;
    let back = c + Vec3::Z * size;
    let left = c + Vec3::NEG_X * size;
    let right = c + Vec3::X * size;

    add_triangle_outward(mesh, c, top, front, right);
    add_triangle_outward(mesh, c, top, right, back);
    add_triangle_outward(mesh, c, top, back, left);
    add_triangle_outward(mesh, c, top, left, front);
    add_triangle_outward(mesh, c, bottom, right, front);
    add_triangle_outward(mesh, c, bottom, back, right);
    add_triangle_outward(mesh, c, bottom, left, back);
    add_triangle_outward(mesh, c, bottom, front, left);
}

/// Three quads at 60°.
fn star_burst(mesh: &mut MeshData, point: &LeafPoint) {
    let half = point.size * 0.5;
    let (_, up, _) = build_basis(point.direction, point.rotation);
    for i in 0..3 {
        let angle = (i as f32 / 3.0) * TAU + point.rotation;
        let right = Vec3::new(angle.cos(), 0.0, angle.sin());
        add_double_sided_leaf(mesh, point.position, right * half, up * half);
    }
}

/// Six thin radiating quads.
fn needle_cluster(mesh: &mut MeshData, point: &LeafPoint) {
    let length = point.size;
    let width = point.size * 0.1;
    let (_, _, forward) = build_basis(point.direction, point.rotation);
    for i in 0..6 {
        let angle = (i as f32 / 6.0) * TAU + point.rotation;
        let needle_dir = Vec3::new(angle.cos(), 0.3, angle.sin()).normalize();
        let needle_right = forward.cross(needle_dir).normalize_or_zero();
        add_double_sided_quad(
            mesh,
            point.position + needle_dir * length * 0.5,
            needle_right * width,
            needle_dir * length * 0.5,
        );
    }
}

/// Orthonormal `(right, up, forward)` with `forward = direction`, rotated by
/// `rotation` around `direction`.
fn build_basis(direction: Vec3, rotation: f32) -> (Vec3, Vec3, Vec3) {
    let world_up = if direction.y.abs() > 0.9 { Vec3::NEG_Z } else { Vec3::Y };
    let right = direction.cross(world_up).normalize_or_zero();
    let up = right.cross(direction).normalize_or_zero();
    let (sin_r, cos_r) = rotation.sin_cos();
    (right * cos_r + up * sin_r, up * cos_r - right * sin_r, direction)
}

/// Whether a card face with normal `n` is the leaf's upper side. Decided on the first of
/// `y, x, z` that is not zero, so exactly one of a double-sided card's two copies is the
/// upper one, even for a vertical card.
fn is_upper(n: Vec3) -> bool {
    [n.y, n.x, n.z].into_iter().find(|c| c.abs() > 1e-4).is_none_or(|c| c > 0.0)
}

/// Quad spanned by `half_right`/`half_up` around `center`, emitted twice with
/// opposite windings; each side's normal is derived from its winding.
fn add_double_sided_quad(mesh: &mut MeshData, center: Vec3, half_right: Vec3, half_up: Vec3) {
    let v0 = center - half_right - half_up;
    let v1 = center + half_right - half_up;
    let v2 = center + half_right + half_up;
    let v3 = center - half_right + half_up;
    let normal = half_right.cross(half_up).normalize_or_zero();
    let uvs = [
        Vec2::new(0.0, 0.0),
        Vec2::new(1.0, 0.0),
        Vec2::new(1.0, 1.0),
        Vec2::new(0.0, 1.0),
    ];

    let front = mesh.positions.len() as u32;
    mesh.positions.extend_from_slice(&[v0, v1, v2, v3]);
    mesh.normals.extend_from_slice(&[normal; 4]);
    mesh.uvs.extend_from_slice(&uvs);
    mesh.indices
        .extend_from_slice(&[front, front + 1, front + 2, front, front + 2, front + 3]);

    let back = mesh.positions.len() as u32;
    mesh.positions.extend_from_slice(&[v0, v1, v2, v3]);
    mesh.normals.extend_from_slice(&[-normal; 4]);
    mesh.uvs.extend_from_slice(&uvs);
    mesh.indices
        .extend_from_slice(&[back, back + 2, back + 1, back, back + 3, back + 2]);
}

/// Pointed oval, base to tip, about half the card's area. Units are
/// half-extents: x along `half_right`, y along `half_up`, base at y = -1, tip
/// at y = 1. Counter-clockwise seen from the front (`half_right × half_up`).
const LEAF_OUTLINE: [Vec2; 8] = [
    Vec2::new(0.0, -1.0),
    Vec2::new(0.55, -0.6),
    Vec2::new(0.8, -0.05),
    Vec2::new(0.6, 0.5),
    Vec2::new(0.0, 1.0),
    Vec2::new(-0.6, 0.5),
    Vec2::new(-0.8, -0.05),
    Vec2::new(-0.55, -0.6),
];

/// Leaf-shaped card spanned by `half_right`/`half_up` around `center`: a fan
/// over [`LEAF_OUTLINE`], emitted twice with opposite windings; each side's
/// normal is derived from its winding.
fn add_double_sided_leaf(mesh: &mut MeshData, center: Vec3, half_right: Vec3, half_up: Vec3) {
    let normal = half_right.cross(half_up).normalize_or_zero();
    let n = LEAF_OUTLINE.len() as u32;
    for (side_normal, front) in [(normal, true), (-normal, false)] {
        let base = mesh.positions.len() as u32;
        mesh.positions.push(center);
        mesh.uvs.push(Vec2::splat(0.5));
        for p in LEAF_OUTLINE {
            mesh.positions.push(center + half_right * p.x + half_up * p.y);
            mesh.uvs.push((p + Vec2::ONE) * 0.5);
        }
        mesh.normals
            .extend(std::iter::repeat_n(side_normal, n as usize + 1));
        for i in 0..n {
            let a = base + 1 + i;
            let b = base + 1 + (i + 1) % n;
            if front {
                mesh.indices.extend_from_slice(&[base, a, b]);
            } else {
                mesh.indices.extend_from_slice(&[base, b, a]);
            }
        }
    }
}

/// Triangle wound so its face points away from `center`.
fn add_triangle_outward(mesh: &mut MeshData, center: Vec3, a: Vec3, b: Vec3, c: Vec3) {
    let geometric = (b - a).cross(c - a);
    let outward = (a + b + c) / 3.0 - center;
    let (v1, v2) = if geometric.dot(outward) >= 0.0 { (b, c) } else { (c, b) };
    let normal = (v1 - a).cross(v2 - a).normalize_or_zero();
    let base = mesh.positions.len() as u32;
    mesh.positions.extend_from_slice(&[a, v1, v2]);
    mesh.normals.extend_from_slice(&[normal; 3]);
    mesh.uvs.extend_from_slice(&[
        Vec2::new(0.0, 0.0),
        Vec2::new(1.0, 0.0),
        Vec2::new(0.5, 1.0),
    ]);
    mesh.indices.extend_from_slice(&[base, base + 1, base + 2]);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mesh::rings::tests::{assert_faces_outward, assert_indices_valid};
    use crate::params::TreeParams;
    use crate::presets::TreePreset;
    use crate::skeleton::generate_skeleton;

    fn point() -> LeafPoint {
        LeafPoint {
            position: Vec3::ZERO,
            direction: Vec3::Y,
            size: 1.0,
            rotation: 0.0,
            tint: 0.0,
            hue: 0.0,
        }
    }

    /// Foliage settings with flat per-card normals and uniform colour.
    fn flat(style: LeafStyle) -> FoliageParams {
        FoliageParams {
            style,
            normal_bend: 0.0,
            color_variation: 0.0,
            hue_variation: 0.0,
            ..FoliageParams::default()
        }
    }

    #[test]
    fn build_basis_produces_orthonormal() {
        for dir in [Vec3::Y, Vec3::X, Vec3::new(0.3, 0.9, 0.1).normalize()] {
            let (right, up, forward) = build_basis(dir, 0.7);
            assert!((right.length() - 1.0).abs() < 1e-5);
            assert!((up.length() - 1.0).abs() < 1e-5);
            assert!(right.dot(up).abs() < 1e-5);
            assert!(right.dot(forward).abs() < 1e-5);
            assert!(up.dot(forward).abs() < 1e-5);
        }
    }

    #[test]
    fn leaf_vertex_counts() {
        let p = point();
        let count = |style| foliage_mesh(std::slice::from_ref(&p), &flat(style)).positions.len();
        assert_eq!(count(LeafStyle::CrossedPlanes), 36);
        assert_eq!(count(LeafStyle::SingleQuad), 18);
        assert_eq!(count(LeafStyle::ClusterSphere), 24);
        assert_eq!(count(LeafStyle::StarBurst), 54);
        assert_eq!(count(LeafStyle::NeedleCluster), 48);
    }

    #[test]
    fn leaf_meshes_face_outward() {
        // Flat normals: bent normals deliberately disagree with the winding.
        let p = LeafPoint {
            position: Vec3::new(1.0, 2.0, -0.5),
            direction: Vec3::new(0.4, -0.3, 0.7).normalize(),
            size: 0.8,
            rotation: 1.1,
            tint: 0.0,
            hue: 0.0,
        };
        for style in [
            LeafStyle::CrossedPlanes,
            LeafStyle::SingleQuad,
            LeafStyle::ClusterSphere,
            LeafStyle::StarBurst,
            LeafStyle::NeedleCluster,
        ] {
            let mesh = foliage_mesh(std::slice::from_ref(&p), &flat(style));
            assert_indices_valid(&mesh, &format!("{style:?}"));
            assert_faces_outward(&mesh, &format!("{style:?}"));
        }
    }

    #[test]
    fn leaf_cards_grow_out_of_their_attachment_point() {
        // D-045: cards centred on the leaf point were threaded on their twig
        // and read as green rings around thick limbs.
        let p = LeafPoint {
            position: Vec3::new(1.0, 2.0, -0.5),
            direction: Vec3::new(0.4, -0.3, 0.7).normalize(),
            size: 0.8,
            rotation: 1.1,
            tint: 0.0,
            hue: 0.0,
        };
        let (_, up, _) = build_basis(p.direction, p.rotation);
        for style in [LeafStyle::CrossedPlanes, LeafStyle::SingleQuad] {
            let mesh = foliage_mesh(std::slice::from_ref(&p), &flat(style));
            let (min, max) = mesh
                .positions
                .iter()
                .map(|v| (*v - p.position).dot(up))
                .fold((f32::MAX, f32::MIN), |(lo, hi), a| (lo.min(a), hi.max(a)));
            assert!(min > -1e-5, "{style:?}: card reaches {min} m behind the leaf point");
            assert!((max - p.size).abs() < 1e-5, "{style:?}: tip {max} m out, leaf size {}", p.size);
        }
    }

    fn oak_leaf_points(placement: FoliagePlacement, age: f32) -> (TreeParams, Vec<LeafPoint>) {
        let mut params = TreePreset::Oak.params();
        params.foliage.placement = placement;
        let skeleton = generate_skeleton(&params).aged(age, &params.growth);
        let points = collect_leaf_points(&skeleton, &params.foliage, &params.growth, &params.trunk, params.seed);
        (params, points)
    }

    #[test]
    fn bent_normals_point_out_of_the_crown() {
        let (params, points) = oak_leaf_points(FoliagePlacement::AllBranches, f32::INFINITY);
        assert!(!points.is_empty());
        let center = points.iter().map(|p| p.position).sum::<Vec3>() / points.len() as f32;
        for normal_bend in [params.foliage.normal_bend, 1.0] {
            let foliage = FoliageParams { normal_bend, ..params.foliage.clone() };
            let mesh = foliage_mesh(&points, &foliage);
            assert_indices_valid(&mesh, "oak");
            for (position, normal) in mesh.positions.iter().zip(&mesh.normals) {
                assert!((normal.length() - 1.0).abs() < 1e-4, "bend {normal_bend}: non-unit normal {normal:?}");
                assert!(
                    normal.dot(*position - center) > 0.0,
                    "bend {normal_bend}: normal {normal:?} at {position:?} points into the crown"
                );
            }
        }
    }

    #[test]
    fn leaf_colors_vary_per_leaf_within_bounds() {
        let (params, points) = oak_leaf_points(FoliagePlacement::AllBranches, f32::INFINITY);
        assert_eq!(params.foliage.style, LeafStyle::CrossedPlanes);
        let leaf_vertices = 36;

        let varied = FoliageParams { color_variation: 0.2, hue_variation: 0.0, ..params.foliage.clone() };
        let mesh = foliage_mesh(&points, &varied);
        assert_eq!(mesh.colors.len(), mesh.positions.len());
        assert_eq!(mesh.colors.len(), points.len() * leaf_vertices);
        let mut distinct = std::collections::BTreeSet::new();
        for leaf in mesh.colors.chunks(leaf_vertices) {
            assert!(leaf.iter().all(|c| *c == leaf[0]), "one leaf, several colours");
            let c = leaf[0];
            assert!((0.8 - 1e-5..=1.2 + 1e-5).contains(&c.x), "factor {} out of bounds", c.x);
            assert!(c.x == c.y && c.y == c.z && c.w == 1.0, "tint must be grey and opaque: {c:?}");
            distinct.insert(c.x.to_bits());
        }
        assert!(distinct.len() > 1, "all leaves share one colour");

        let plain = FoliageParams { color_variation: 0.0, hue_variation: 0.0, ..params.foliage.clone() };
        let mesh = foliage_mesh(&points, &plain);
        assert!(mesh.colors.iter().all(|c| *c == Vec4::ONE));
    }

    #[test]
    fn leaf_hues_vary_per_leaf() {
        let (params, points) = oak_leaf_points(FoliagePlacement::AllBranches, f32::INFINITY);
        let foliage = FoliageParams { hue_variation: 0.5, color_variation: 0.0, ..params.foliage.clone() };
        let mesh = foliage_mesh(&points, &foliage);
        let leaf_vertices = 36;
        let (mut warm, mut cool) = (false, false);
        for leaf in mesh.colors.chunks(leaf_vertices) {
            assert!(leaf.iter().all(|c| *c == leaf[0]), "one leaf, several colours");
            let c = leaf[0];
            assert!((c.x - 1.0).abs() <= 0.3 + 1e-5, "red {} out of bounds", c.x);
            warm |= c.x > c.z;
            cool |= c.x < c.z;
        }
        assert!(warm && cool, "hues do not lean both ways");
    }

    #[test]
    fn upper_flag_marks_the_face_that_looks_up() {
        let tilted = LeafPoint {
            position: Vec3::new(1.0, 2.0, -0.5),
            direction: Vec3::new(0.4, -0.3, 0.7).normalize(),
            size: 0.8,
            rotation: 1.1,
            ..point()
        };
        let sideways = LeafPoint { direction: Vec3::X, ..point() };
        for style in [
            LeafStyle::CrossedPlanes,
            LeafStyle::SingleQuad,
            LeafStyle::ClusterSphere,
            LeafStyle::StarBurst,
            LeafStyle::NeedleCluster,
        ] {
            for p in [point(), tilted.clone(), sideways.clone()] {
                let mesh = foliage_mesh(std::slice::from_ref(&p), &flat(style));
                assert_eq!(mesh.uv1.len(), mesh.positions.len());
                for (uv, &normal) in mesh.uv1.iter().zip(&mesh.normals) {
                    assert!(uv.x == 0.0 || uv.x == 1.0, "{style:?}: flag {}", uv.x);
                    assert_eq!(uv.x == 1.0, is_upper(normal), "{style:?}: flag against normal {normal:?}");
                }
                // A card is emitted twice, back to back; exactly one copy is the upper side.
                let face = match style {
                    LeafStyle::ClusterSphere => continue,
                    LeafStyle::NeedleCluster => 4,
                    _ => 9,
                };
                for card in mesh.uv1.chunks(2 * face) {
                    assert!(
                        card[..face].iter().all(|uv| uv.x != card[face].x)
                            && card[..face].iter().all(|uv| uv.x == card[0].x)
                            && card[face..].iter().all(|uv| uv.x == card[face].x),
                        "{style:?}: a card's two faces share a side"
                    );
                }
            }
        }
    }

    #[test]
    fn crown_occlusion_is_darkest_inside() {
        let (params, points) = oak_leaf_points(FoliagePlacement::AllBranches, f32::INFINITY);
        let leaf_vertices = 36;
        let center = points.iter().map(|p| p.position).sum::<Vec3>() / points.len() as f32;
        let by_distance = |a: &&(usize, &LeafPoint), b: &&(usize, &LeafPoint)| {
            (a.1.position - center).length().total_cmp(&(b.1.position - center).length())
        };
        let indexed: Vec<_> = points.iter().enumerate().collect();
        let nearest = indexed.iter().min_by(by_distance).unwrap().0;
        let farthest = indexed.iter().max_by(by_distance).unwrap().0;

        let dark = FoliageParams { occlusion: 0.6, ..params.foliage.clone() };
        let mesh = foliage_mesh(&points, &dark);
        assert!(mesh.uv1.iter().all(|uv| (0.4 - 1e-5..=1.0).contains(&uv.y)), "visibility out of [0.4, 1]");
        assert!(
            mesh.uv1[nearest * leaf_vertices].y < mesh.uv1[farthest * leaf_vertices].y,
            "the leaf at the crown's heart is not darker than the outermost one"
        );

        let open = FoliageParams { occlusion: 0.0, ..params.foliage.clone() };
        assert!(foliage_mesh(&points, &open).uv1.iter().all(|uv| uv.y == 1.0));
    }

    #[test]
    fn leaf_sway_is_one_motion_per_leaf() {
        let a = LeafPoint {
            position: Vec3::new(1.0, 2.0, -0.5),
            direction: Vec3::new(0.4, -0.3, 0.7).normalize(),
            size: 0.8,
            rotation: 1.1,
            ..point()
        };
        let b = LeafPoint { position: Vec3::new(-2.0, 3.0, 1.0), ..a.clone() };
        for style in [
            LeafStyle::CrossedPlanes,
            LeafStyle::SingleQuad,
            LeafStyle::ClusterSphere,
            LeafStyle::StarBurst,
            LeafStyle::NeedleCluster,
        ] {
            let points = [a.clone(), b.clone()];
            let mesh = foliage_mesh(&points, &flat(style));
            assert_eq!(mesh.sway.len(), mesh.positions.len());
            let per_leaf = mesh.positions.len() / 2;
            let mut phases = Vec::new();
            for (i, p) in points.iter().enumerate() {
                let range = i * per_leaf..(i + 1) * per_leaf;
                let (_, _, forward) = build_basis(p.direction, p.rotation);
                let phase = mesh.sway[range.start].w;
                assert!((0.0..1.0).contains(&phase), "{style:?}: phase {phase}");
                phases.push(phase);
                for (sway, &vertex) in mesh.sway[range.clone()].iter().zip(&mesh.positions[range]) {
                    assert_eq!(sway.w, phase, "{style:?}: a leaf with two phases");
                    let offset = sway.truncate();
                    assert!(offset.cross(forward).length() < 1e-4, "{style:?}: flutter not along the leaf's direction");
                    match style {
                        LeafStyle::CrossedPlanes | LeafStyle::SingleQuad => {
                            assert!((offset.length() - (vertex - p.position).length()).abs() < 1e-5, "{style:?}: lever");
                        }
                        LeafStyle::ClusterSphere => {
                            assert!((offset.length() - p.size * 0.4).abs() < 1e-5, "{style:?}: a cluster must move as one");
                        }
                        _ => {}
                    }
                }
            }
            assert_ne!(phases[0], phases[1], "{style:?}: two leaves flutter in step");
        }
    }

    #[test]
    fn branches_shortened_into_the_trunk_carry_no_leaves() {
        // A cypress on a wobbly trunk has sub-branches whose parent runs inside
        // the trunk; they are shortened to nothing, and their leaves sat
        // inside the trunk.
        let mut params = crate::presets::TreePreset::Cypress.params();
        params.seed = 1;
        params.trunk.randomness = 0.5;
        params.trunk.twist = 180.0;
        params.branches.twist = 90.0;
        let s = crate::skeleton::generate_skeleton(&params);
        let points = collect_leaf_points(&s, &params.foliage, &params.growth, &params.trunk, params.seed);
        for p in &points {
            let depth = trunk_depth(&params.trunk, params.seed, p.position);
            assert!(depth <= p.size * 0.5, "leaf {depth} m inside the trunk at {:?}", p.position);
        }
    }

    #[test]
    fn leaf_tints_never_reroll_as_the_tree_ages() {
        let tints = |age: f32| -> std::collections::BTreeSet<u32> {
            let (_, points) = oak_leaf_points(FoliagePlacement::TerminalBranches, age);
            points.iter().map(|p| p.tint.to_bits()).collect()
        };
        let young = tints(10.0);
        let mature = tints(f32::INFINITY);
        assert!(young.len() > 1, "no tints drawn at age 10");
        assert!(young.is_subset(&mature), "a leaf's tint changed while the tree aged");
    }

    #[test]
    fn collect_leaf_points_disabled() {
        let params = TreePreset::Oak.params();
        let skeleton = generate_skeleton(&params);
        let foliage = FoliageParams {
            enabled: false,
            ..params.foliage.clone()
        };
        let points = collect_leaf_points(&skeleton, &foliage, &params.growth, &params.trunk, 42);
        assert!(points.is_empty());
    }

    #[test]
    fn leaves_scale_with_age() {
        let params = TreePreset::Oak.params();
        let full = generate_skeleton(&params);
        let leaves_at = |age: f32| {
            let aged = full.aged(age, &params.growth);
            collect_leaf_points(&aged, &params.foliage, &params.growth, &params.trunk, params.seed)
        };
        let young = leaves_at(2.0);
        let mid = leaves_at(params.growth.maturity_age * 0.3);
        let mature = leaves_at(f32::INFINITY);
        assert!(!mature.is_empty());
        assert!(young.len() < mature.len(), "{} vs {}", young.len(), mature.len());
        let max_size = |pts: &[LeafPoint]| pts.iter().map(|p| p.size).fold(0.0, f32::max);
        assert!(max_size(&mid) < max_size(&mature));
    }

    #[test]
    fn leaf_points_stable_under_aging() {
        let mut params = TreePreset::Oak.params();
        params.foliage.placement = FoliagePlacement::AllBranches;
        params.foliage.orientation = LeafOrientation::FollowBranch;
        let full = generate_skeleton(&params);
        let (idx, primary) = full
            .nodes
            .iter()
            .enumerate()
            .find(|(_, n)| n.kind == NodeKind::Primary)
            .unwrap();
        let id = primary.id;
        let relative_leaves = |age: f32| {
            let aged = full.aged(age, &params.growth);
            let i = aged.nodes.iter().position(|n| n.id == id).expect("primary alive");
            let mut pts = Vec::new();
            leaf_points_for_node(&aged, i, &params.foliage, &params.growth, &params.trunk, params.seed, &mut pts);
            let end = aged.end(i);
            pts.into_iter()
                .map(|p| (p.position - end, p.direction, p.size, p.rotation))
                .collect::<Vec<_>>()
        };
        let a = relative_leaves(primary.birth + primary.duration);
        let b = relative_leaves(f32::INFINITY);
        assert!(!a.is_empty(), "node {idx} should have leaves");
        assert_eq!(a.len(), b.len());
        for (x, y) in a.iter().zip(&b) {
            assert!(x.0.distance(y.0) < 1e-4);
            assert_eq!(x.1, y.1);
            assert_eq!(x.2, y.2);
            assert_eq!(x.3, y.3);
        }
    }

    #[test]
    fn leaves_sit_on_bent_wood() {
        let mut params = TreePreset::Oak.params();
        params.branches.gravity_strength = 0.8;
        params.branches.stiffness = 0.1;
        let skeleton = generate_skeleton(&params);
        let axes: Vec<Vec<Vec3>> = skeleton
            .nodes
            .iter()
            .skip(1)
            .map(|n| n.axis(n.axis_points()).into_iter().map(|(c, _)| c).collect())
            .collect();
        let off_wood = |p: Vec3| {
            axes.iter()
                .flat_map(|axis| axis.windows(2))
                .map(|w| {
                    let ab = w[1] - w[0];
                    let t = ((p - w[0]).dot(ab) / ab.length_squared().max(f32::MIN_POSITIVE)).clamp(0.0, 1.0);
                    p.distance(w[0] + ab * t)
                })
                .fold(f32::MAX, f32::min)
        };
        for placement in [FoliagePlacement::AllBranches, FoliagePlacement::TerminalBranches] {
            params.foliage.placement = placement;
            let points = collect_leaf_points(&skeleton, &params.foliage, &params.growth, &params.trunk, params.seed);
            assert!(!points.is_empty());
            for p in &points {
                let d = off_wood(p.position);
                assert!(d < 1e-4, "{placement:?}: leaf at {:?} is {d} off the bent wood", p.position);
            }
        }
    }

    #[test]
    fn no_leaf_inside_the_trunk() {
        // Cypress twigs hug the trunk, so its tip clusters reach toward it.
        for preset in [TreePreset::Cypress, TreePreset::Poplar, TreePreset::Oak] {
            for placement in [FoliagePlacement::TipClusters, FoliagePlacement::TerminalBranches, FoliagePlacement::AllBranches] {
                let mut params = preset.params();
                params.foliage.placement = placement;
                let skeleton = generate_skeleton(&params);
                let points = collect_leaf_points(&skeleton, &params.foliage, &params.growth, &params.trunk, params.seed);
                for p in &points {
                    let depth = trunk_depth(&params.trunk, params.seed, p.position);
                    assert!(depth <= 0.0, "{} {placement:?}: leaf {depth} m inside the trunk", preset.name());
                }
            }
        }
    }

    #[test]
    fn young_tip_clusters_stay_on_their_tips() {
        // D-037: the cluster ball must shrink with its leaves while the tree
        // is young, or a 1 cm leaf floats tens of cm off its twig.
        for preset in [TreePreset::DragonTree, TreePreset::Oak, TreePreset::Cypress] {
            let mut params = preset.params();
            params.foliage.placement = FoliagePlacement::TipClusters;
            let mature = generate_skeleton(&params);
            for age in [4.0, 6.0, 9.0, 12.0] {
                let skeleton = mature.aged(age, &params.growth);
                let tips: Vec<Vec3> = (0..skeleton.nodes.len())
                    .filter(|&i| skeleton.nodes[i].kind != NodeKind::Trunk && skeleton.is_terminal(i))
                    .map(|i| skeleton.end(i))
                    .collect();
                let points = collect_leaf_points(&skeleton, &params.foliage, &params.growth, &params.trunk, params.seed);
                let max_ratio = 0.75 / (1.0 - params.foliage.leaf_size_variation) + 1e-3;
                for p in &points {
                    let d = tips.iter().map(|t| t.distance(p.position)).fold(f32::MAX, f32::min);
                    assert!(
                        d <= p.size * max_ratio + 1e-5,
                        "{} age {age}: leaf of size {} sits {d} m from the nearest tip",
                        preset.name(),
                        p.size
                    );
                }
            }
        }
    }

    #[test]
    fn leaves_never_disappear_as_a_tree_ages() {
        // D-039: tip placements must not drop a branch's leaves when its
        // first (still leafless) twigs are born; baobab went from 80 leaves
        // at age 6 to none at age 8.
        for preset in TreePreset::ALL {
            for placement in [FoliagePlacement::TerminalBranches, FoliagePlacement::TipClusters] {
                let mut params = preset.params();
                params.foliage.placement = placement;
                let mature = generate_skeleton(&params);
                let mut previous = 0;
                for step in 0..=40 {
                    let age = step as f32 * 0.5;
                    let skeleton = mature.aged(age, &params.growth);
                    let count = collect_leaf_points(&skeleton, &params.foliage, &params.growth, &params.trunk, params.seed).len();
                    assert!(
                        count >= previous,
                        "{} {placement:?}: {previous} leaves before age {age}, {count} at it",
                        preset.name()
                    );
                    previous = count;
                }
            }
        }
    }
}