Repository navigation
Expand file tree
/
Copy pathTreeGenerator.cpp
More file actions
1975 lines (1885 loc) · 81.4 KB
/
Copy pathTreeGenerator.cpp
File metadata and controls
1975 lines (1885 loc) · 81.4 KB
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
#include "TreeGenerator.h"
#include <deki/LogSystem.h>
#include <deki/providers/Memory.h>
#include <algorithm>
#include <cmath>
namespace DekiTrees
{
namespace
{
using Deki::Vector3;
using Deki3D::VertexPNTC;
constexpr float kPi = 3.14159265f;
constexpr float kTwoPi = 6.2831853f;
constexpr float kDegrees = kPi / 180.0f;
// What a tree may be made of at most, whatever its numbers ask for.
constexpr int kMaxLevels = 3;
constexpr int kMaxBranches = 120;
constexpr int kMaxCurveRes = 12;
constexpr int kMaxLeaves = 12;
constexpr int kMaxStems = 3000;
// The far leaves, which stand in for the others on a tree small on the
// screen: this share of their number, each this much larger. The crown's
// masses are behind them, so they cover half the screen the leaves do.
constexpr float kFarLeafShare = 0.22f;
constexpr float kFarLeafSize = 1.45f;
// The crown's hull is measured in this many slices of the crown's height and
// sectors round its upright, and is this dark beside the leaves over it.
constexpr int kHullRings = 6;
constexpr int kHullSides = 8;
constexpr float kHullShade = 0.74f;
// A crown of leaf masses: at most this many, each drawn as this many slices
// and sectors; a leaf card is kept where it is at least kEdgeFrom of the
// way out of its mass, and set on the mass's surface.
constexpr int kMaxMasses = 16;
constexpr int kMassRings = 6;
constexpr int kMassSides = 10;
constexpr float kEdgeFrom = 0.5f;
constexpr float kMassBelow = 0.7f; // a mass is this flat underneath
float Smooth(float from, float to, float x)
{
const float t = std::clamp((x - from) / (to - from), 0.0f, 1.0f);
return t * t * (3.0f - 2.0f * t);
}
/// A number from 0 up to 1 for three whole numbers, the same every time.
float Roll(int a, int b, int c)
{
uint32_t h = static_cast<uint32_t>(a) * 374761393u + static_cast<uint32_t>(b) * 668265263u +
static_cast<uint32_t>(c) * 2246822519u;
h = (h ^ (h >> 13)) * 1274126177u;
h ^= h >> 16;
return static_cast<float>(h & 0xFFFFFF) / 16777216.0f;
}
/// The tree's own run of chance: the same numbers in the same order for the
/// same seed, so growing a tree twice grows it the same.
class Chance
{
public:
explicit Chance(int32_t seed)
: m_State(static_cast<uint32_t>(seed) * 2654435761u + 0x9E3779B9u)
{
}
/// From 0 up to 1.
float Next()
{
m_State = m_State * 1664525u + 1013904223u;
return static_cast<float>((m_State >> 8) & 0xFFFFFF) / 16777216.0f;
}
/// From -amount to amount.
float Vary(float amount) { return (Next() * 2.0f - 1.0f) * amount; }
private:
uint32_t m_State;
};
/// 0xAABBGGRR, as a vertex keeps its colour: `color` at `shade` of its brightness.
uint32_t Shaded(const TreeColor& color, float shade)
{
const auto channel = [shade](uint8_t value)
{ return static_cast<uint32_t>(std::clamp(static_cast<float>(value) * shade, 0.0f, 255.0f)); };
return 0xFF000000u | (channel(color.b) << 16) | (channel(color.g) << 8) | channel(color.r);
}
TreeColor Mix(const TreeColor& a, const TreeColor& b, float t)
{
const auto channel = [t](uint8_t from, uint8_t to)
{
return static_cast<uint8_t>(static_cast<float>(from) + (static_cast<float>(to) - static_cast<float>(from)) * t);
};
return TreeColor{ channel(a.r, b.r), channel(a.g, b.g), channel(a.b, b.b) };
}
/// `v` turned about `axis` (unit) by `radians`.
Vector3 Turned(const Vector3& v, const Vector3& axis, float radians)
{
const float c = std::cos(radians);
const float s = std::sin(radians);
return v * c + axis.Cross(v) * s + axis * (axis.Dot(v) * (1.0f - c));
}
/// Where a stem is and how it lies: `z` runs along it, `x` and `y` across.
struct Frame
{
Vector3 origin;
Vector3 x = Vector3(1.0f, 0.0f, 0.0f);
Vector3 y = Vector3(0.0f, 0.0f, -1.0f);
Vector3 z = Vector3(0.0f, 1.0f, 0.0f);
void TurnAboutX(float radians)
{
y = Turned(y, x, radians);
z = Turned(z, x, radians);
}
void TurnAboutZ(float radians)
{
x = Turned(x, z, radians);
y = Turned(y, z, radians);
}
void TurnAbout(const Vector3& axis, float radians)
{
x = Turned(x, axis, radians);
y = Turned(y, axis, radians);
z = Turned(z, axis, radians);
}
};
/// The paper's ShapeRatio: how long a branch is, of the longest, `ratio` of
/// the way from the crown's top (0) to its foot (1).
float ShapeRatio(CrownShape shape, float ratio)
{
ratio = std::clamp(ratio, 0.0f, 1.0f);
switch (shape)
{
case CrownShape::Conical: return 0.2f + 0.8f * ratio;
case CrownShape::Spherical: return 0.2f + 0.8f * std::sin(kPi * ratio);
case CrownShape::Hemispherical: return 0.2f + 0.8f * std::sin(0.5f * kPi * ratio);
case CrownShape::Cylindrical: return 1.0f;
case CrownShape::TaperedCylindrical: return 0.5f + 0.5f * ratio;
case CrownShape::Flame: return ratio <= 0.7f ? ratio / 0.7f : (1.0f - ratio) / 0.3f;
case CrownShape::InverseConical: return 1.0f - 0.8f * ratio;
case CrownShape::TendFlame:
return ratio <= 0.7f ? 0.5f + 0.5f * ratio / 0.7f : 0.5f + 0.5f * (1.0f - ratio) / 0.3f;
}
return 1.0f;
}
/// Takes the tree's corners and triangles. With no buffers it only counts
/// them, which is how GrowTree learns what to allocate before a second
/// growing fills it.
class Builder
{
public:
Builder() = default;
Builder(VertexPNTC* vertices, uint16_t* indices)
: m_Vertices(vertices),
m_Indices(indices)
{
}
uint16_t Corner(const Vector3& position, const Vector3& normal, float u, float v, uint32_t color)
{
if (m_Vertices)
{
VertexPNTC& vertex = m_Vertices[m_VertexCount];
vertex.position = position;
vertex.normal = normal;
vertex.u = u;
vertex.v = v;
vertex.color = color;
}
m_Min = Vector3(std::min(m_Min.x, position.x), std::min(m_Min.y, position.y), std::min(m_Min.z, position.z));
m_Max = Vector3(std::max(m_Max.x, position.x), std::max(m_Max.y, position.y), std::max(m_Max.z, position.z));
return static_cast<uint16_t>(m_VertexCount++);
}
void Triangle(uint16_t a, uint16_t b, uint16_t c)
{
if (m_Indices)
{
m_Indices[m_IndexCount] = a;
m_Indices[m_IndexCount + 1] = b;
m_Indices[m_IndexCount + 2] = c;
}
m_IndexCount += 3;
}
uint32_t VertexCount() const { return m_VertexCount; }
uint32_t IndexCount() const { return m_IndexCount; }
const Vector3& Min() const { return m_Min; }
const Vector3& Max() const { return m_Max; }
private:
VertexPNTC* m_Vertices = nullptr;
uint16_t* m_Indices = nullptr;
uint32_t m_VertexCount = 0;
uint32_t m_IndexCount = 0;
Vector3 m_Min = Vector3(1e9f, 1e9f, 1e9f);
Vector3 m_Max = Vector3(-1e9f, -1e9f, -1e9f);
};
/// One mass of leaves: a lumpy ellipsoid about `middle`, `reach` along each
/// axis (less underneath).
struct Mass
{
Vector3 middle;
Vector3 reach;
};
/// Where a place is among the masses: in which, how far out of its middle
/// (1 on its surface), and the mass's normal there.
struct MassPlace
{
int mass = -1;
float distance = 1e9f;
Vector3 normal;
};
/// The crown: the box round the tree's leaves, how far the leaves reach from
/// its upright in each slice of its height and each sector round it, and the
/// masses of leaves it is made of. A leaf card takes its normal and its
/// colour from where it is in the box; the hull is drawn from the reaches.
struct Crown
{
Vector3 low = Vector3(1e9f, 1e9f, 1e9f);
Vector3 high = Vector3(-1e9f, -1e9f, -1e9f);
float reach[kHullRings][kHullSides] = {};
Mass masses[kMaxMasses];
int massCount = 0;
MassPlace MassAt(const Vector3& place) const
{
MassPlace found;
for (int i = 0; i < massCount; ++i)
{
const Mass& mass = masses[i];
const Vector3 from = place - mass.middle;
const float reachY = from.y < 0.0f ? mass.reach.y * kMassBelow : mass.reach.y;
const Vector3 unit(from.x / mass.reach.x, from.y / reachY, from.z / mass.reach.z);
const float distance = unit.Length();
if (distance < found.distance)
{
found.mass = i;
found.distance = distance;
const Vector3 slope(unit.x / mass.reach.x, unit.y / reachY, unit.z / mass.reach.z);
found.normal = slope.LengthSquared() > 1e-8f ? slope.Normalized() : Vector3(0.0f, 1.0f, 0.0f);
}
}
return found;
}
bool Known() const { return high.y > low.y; }
void Take(const Vector3& place)
{
low = Vector3(std::min(low.x, place.x), std::min(low.y, place.y), std::min(low.z, place.z));
high = Vector3(std::max(high.x, place.x), std::max(high.y, place.y), std::max(high.z, place.z));
}
/// Notes a leaf at `place` in the reaches, measured in `box`: the crown
/// as an earlier growing found it.
void Reach(const Vector3& place, const Crown& box)
{
const Vector3 middle = box.Middle();
const float height = std::max(box.high.y - box.low.y, 0.01f);
const int ring = std::clamp(static_cast<int>((place.y - box.low.y) / height * kHullRings), 0, kHullRings - 1);
const float x = place.x - middle.x;
const float z = place.z - middle.z;
// Round the upright the way a stem's ring goes: from x towards -z.
const float angle = std::atan2(-z, x) + kPi;
const int side = std::clamp(static_cast<int>(angle / kTwoPi * kHullSides), 0, kHullSides - 1);
reach[ring][side] = std::max(reach[ring][side], std::sqrt(x * x + z * z));
}
/// Makes the reaches fit to draw a hull from: a sector with no leaf takes
/// its slice's reach, a slice with none its neighbour's, and each sector
/// leans to the two beside it, so one long twig is not a spike.
void Settle()
{
float mean[kHullRings];
for (int ring = 0; ring < kHullRings; ++ring)
{
float sum = 0.0f;
int found = 0;
for (const float value : reach[ring])
{
sum += value;
found += value > 0.0f ? 1 : 0;
}
mean[ring] = found > 0 ? sum / static_cast<float>(found) : 0.0f;
}
for (int ring = 0; ring < kHullRings; ++ring)
{
// An empty slice: half the nearest slice that has leaves.
for (int away = 1; mean[ring] == 0.0f && away < kHullRings; ++away)
{
const float below = ring - away >= 0 ? mean[ring - away] : 0.0f;
const float above = ring + away < kHullRings ? mean[ring + away] : 0.0f;
mean[ring] = std::max(below, above) * 0.5f;
}
float filled[kHullSides];
for (int side = 0; side < kHullSides; ++side)
{
filled[side] = reach[ring][side] > 0.0f ? reach[ring][side] : mean[ring] * 0.7f;
}
for (int side = 0; side < kHullSides; ++side)
{
reach[ring][side] = 0.5f * filled[side] + 0.25f * filled[(side + 1) % kHullSides] +
0.25f * filled[(side + kHullSides - 1) % kHullSides];
}
}
}
Vector3 Middle() const { return (low + high) * 0.5f; }
/// `place` from the crown's middle, 1 at its box's faces.
Vector3 Within(const Vector3& place) const
{
const Vector3 half = (high - low) * 0.5f;
const Vector3 from = place - Middle();
return Vector3(from.x / std::max(half.x, 0.01f), from.y / std::max(half.y, 0.01f),
from.z / std::max(half.z, 0.01f));
}
};
/// How a leaf at one place in the crown looks: lit by `normal`, `color` at
/// `shade` of its brightness.
struct LeafLook
{
Vector3 normal;
TreeColor color;
float shade = 1.0f;
};
/// Out and up in the crown is bright, in and under is dark, and the normal
/// is the crown's own there, not a card's.
LeafLook LookAt(const TreeSpec& spec, const Crown& crown, const Vector3& place)
{
const Vector3 within = crown.Known() ? crown.Within(place) : Vector3(0.0f, 0.5f, 0.0f);
const float outward = std::min(within.Length(), 1.2f);
LeafLook look;
look.normal = Vector3(within.x, within.y * 0.8f + 0.35f, within.z);
look.normal = look.normal.LengthSquared() > 1e-6f ? look.normal.Normalized() : Vector3(0.0f, 1.0f, 0.0f);
const float height = within.y * 0.5f + 0.5f;
const float rise = spec.leafLay == LeafLay::Fronds ? 0.25f : 0.55f;
const float light = std::clamp(0.1f + rise * height + 0.3f * Smooth(0.4f, 1.0f, outward), 0.0f, 1.0f);
look.color = Mix(spec.leafDark, spec.leafLight, light);
look.shade = (0.55f + 0.45f * Smooth(0.25f, 0.95f, outward)) * (0.8f + 0.2f * (look.normal.y * 0.5f + 0.5f));
return look;
}
/// How the surface of a mass, or a card on it, looks at `place`. All of it
/// is lit by the crown's one normal, so the crown shades as one round thing
/// and no mass is a ball of its own: light and dark go across the whole
/// crown in one smooth sweep. A mass is only a little darker where it faces
/// into the crown or down, as leaves are there.
LeafLook MassLook(const TreeSpec& spec, const Crown& crown, const Vector3& place, const Vector3& massNormal)
{
LeafLook look = LookAt(spec, crown, place);
const Vector3 within = crown.Known() ? crown.Within(place) : Vector3(0.0f, 0.5f, 0.0f);
const float outward = std::min(within.Length(), 1.2f);
Vector3 away = place - crown.Middle();
away = away.LengthSquared() > 1e-6f ? away.Normalized() : Vector3(0.0f, 1.0f, 0.0f);
look.shade = (0.8f + 0.2f * Smooth(0.2f, 1.0f, outward)) * (0.88f + 0.12f * (look.normal.y * 0.5f + 0.5f)) *
(0.9f + 0.1f * Smooth(-0.5f, 0.6f, massNormal.Dot(away)));
return look;
}
/// The masses of leaves into `crown`: `count` groups of the leaf places, as
/// k-means finds them, each as large as its leaves are spread.
void FindMasses(Crown& crown, const Vector3* places, int placeCount, int count, float leafSize)
{
crown.massCount = 0;
count = std::min(count, kMaxMasses);
if (count <= 0 || placeCount < count * 3)
{
return;
}
// Seeds as far apart as can be, from the highest leaf.
Vector3 middles[kMaxMasses];
int top = 0;
for (int i = 1; i < placeCount; ++i)
{
top = places[i].y > places[top].y ? i : top;
}
middles[0] = places[top];
for (int k = 1; k < count; ++k)
{
int farthest = 0;
float farthestAway = -1.0f;
for (int i = 0; i < placeCount; ++i)
{
float nearest = 1e9f;
for (int j = 0; j < k; ++j)
{
nearest = std::min(nearest, (places[i] - middles[j]).LengthSquared());
}
if (nearest > farthestAway)
{
farthestAway = nearest;
farthest = i;
}
}
middles[k] = places[farthest];
}
const auto nearestOf = [&](const Vector3& place)
{
int best = 0;
for (int j = 1; j < count; ++j)
{
best = (place - middles[j]).LengthSquared() < (place - middles[best]).LengthSquared() ? j : best;
}
return best;
};
int members[kMaxMasses] = {};
for (int pass = 0; pass < 10; ++pass)
{
Vector3 sums[kMaxMasses];
for (int k = 0; k < count; ++k)
{
sums[k] = Vector3(0.0f, 0.0f, 0.0f);
members[k] = 0;
}
for (int i = 0; i < placeCount; ++i)
{
const int k = nearestOf(places[i]);
sums[k] = sums[k] + places[i];
++members[k];
}
for (int k = 0; k < count; ++k)
{
if (members[k] > 0)
{
middles[k] = sums[k] * (1.0f / static_cast<float>(members[k]));
}
}
}
// Each as large as its leaves are spread, and no flatter than half a cluster.
Vector3 spread[kMaxMasses];
for (int k = 0; k < count; ++k)
{
spread[k] = Vector3(0.0f, 0.0f, 0.0f);
}
for (int i = 0; i < placeCount; ++i)
{
const int k = nearestOf(places[i]);
const Vector3 from = places[i] - middles[k];
spread[k] = spread[k] + Vector3(from.x * from.x, from.y * from.y, from.z * from.z);
}
for (int k = 0; k < count; ++k)
{
if (members[k] < 3)
{
continue;
}
const float share = 1.0f / static_cast<float>(members[k]);
const auto across = [&](float sum) { return std::max(1.05f * std::sqrt(sum * share), leafSize * 0.45f); };
Mass& mass = crown.masses[crown.massCount++];
mass.middle = middles[k];
mass.reach = Vector3(across(spread[k].x), across(spread[k].y), across(spread[k].z));
}
}
/// The crown's masses of leaves into `builder`: lumpy ellipsoids, flatter
/// underneath, each a little its own way.
void GrowMasses(const TreeSpec& spec, const Crown& crown, Builder& builder)
{
for (int i = 0; i < crown.massCount; ++i)
{
const Mass& mass = crown.masses[i];
const float twist = Roll(i, spec.seed, 1301) * kTwoPi;
const float lumps = 2.0f + std::floor(Roll(i, spec.seed, 1302) * 3.0f);
uint16_t first = 0;
for (int ring = 0; ring <= kMassRings; ++ring)
{
const float latitude = kPi * (static_cast<float>(ring) / kMassRings - 0.5f); // from the foot up
for (int side = 0; side <= kMassSides; ++side)
{
const float longitude = kTwoPi * static_cast<float>(side % kMassSides) / kMassSides;
Vector3 unit(std::cos(latitude) * std::cos(longitude), std::sin(latitude),
std::cos(latitude) * std::sin(longitude));
// Lumps round it, so its outline is never an ellipse.
const float lump = 1.0f + 0.14f * std::sin(lumps * longitude + twist) * std::cos(latitude) +
0.08f * std::sin(2.0f * latitude + twist * 0.7f);
const float reachY = unit.y < 0.0f ? mass.reach.y * kMassBelow : mass.reach.y;
const Vector3 place =
mass.middle + Vector3(unit.x * mass.reach.x, unit.y * reachY, unit.z * mass.reach.z) * lump;
Vector3 slope(unit.x / mass.reach.x, unit.y / reachY, unit.z / mass.reach.z);
slope = slope.LengthSquared() > 1e-8f ? slope.Normalized() : Vector3(0.0f, 1.0f, 0.0f);
const LeafLook look = MassLook(spec, crown, place, slope);
const uint16_t corner =
builder.Corner(place, look.normal, static_cast<float>(side) / kMassSides,
static_cast<float>(ring) / kMassRings, Shaded(look.color, look.shade));
if (ring == 0 && side == 0)
{
first = corner;
}
}
}
for (int ring = 0; ring < kMassRings; ++ring)
{
for (int side = 0; side < kMassSides; ++side)
{
const uint16_t a = static_cast<uint16_t>(first + ring * (kMassSides + 1) + side);
const uint16_t c = static_cast<uint16_t>(a + kMassSides + 1);
builder.Triangle(a, c, static_cast<uint16_t>(a + 1));
builder.Triangle(static_cast<uint16_t>(a + 1), c, static_cast<uint16_t>(c + 1));
}
}
}
}
/// The crown's hull into `builder`: a closed shape inside the leaves, drawn
/// from how far they reach in each slice and sector, the colour of leaves in
/// shade. It fills the crown where cards alone leave it thin, and hides the
/// wood inside it.
void GrowHull(const TreeSpec& spec, const Crown& crown, Builder& builder)
{
// A crown of masses needs none: the masses fill it, and a hull inside them is drawn over.
if (spec.hull <= 0.0f || !crown.Known() || crown.massCount > 0)
{
return;
}
const Vector3 middle = crown.Middle();
const float height = crown.high.y - crown.low.y;
const auto corner = [&](const Vector3& place)
{
const LeafLook look = LookAt(spec, crown, place);
return builder.Corner(place, look.normal, 0.0f, 0.0f, Shaded(look.color, look.shade * kHullShade));
};
uint16_t rings[kHullRings + 1];
for (int ring = 0; ring <= kHullRings; ++ring)
{
// From above the lowest leaves to a little under the highest, and
// drawn in at its foot and its top, where it closes. A broadleaf
// tree's starts higher: one walks under it and looks up into it.
const float foot = spec.leafLay == LeafLay::Fronds ? 0.06f : 0.24f;
const float y = crown.low.y + height * (foot + (0.9f - foot) * static_cast<float>(ring) / kHullRings);
float closing = 1.0f;
if (ring == 0)
{
closing = 0.4f;
}
else if (ring == 1 || ring == kHullRings - 1)
{
closing = 0.85f;
}
else if (ring == kHullRings)
{
closing = 0.42f;
}
for (int side = 0; side <= kHullSides; ++side)
{
const int sector = side % kHullSides;
const float below = crown.reach[std::max(ring - 1, 0)][sector];
const float above = crown.reach[std::min(ring, kHullRings - 1)][sector];
const float radius = (below + above) * 0.5f * spec.hull * closing;
const float angle = (static_cast<float>(sector) + 0.5f) * kTwoPi / kHullSides - kPi;
const uint16_t at =
corner(Vector3(middle.x + std::cos(angle) * radius, y, middle.z - std::sin(angle) * radius));
if (side == 0)
{
rings[ring] = at;
}
}
}
for (int ring = 0; ring < kHullRings; ++ring)
{
for (int side = 0; side < kHullSides; ++side)
{
const uint16_t a = static_cast<uint16_t>(rings[ring] + side);
const uint16_t c = static_cast<uint16_t>(rings[ring + 1] + side);
builder.Triangle(a, static_cast<uint16_t>(a + 1), c);
builder.Triangle(static_cast<uint16_t>(a + 1), static_cast<uint16_t>(c + 1), c);
}
}
const uint16_t foot =
corner(Vector3(middle.x, crown.low.y + height * (spec.leafLay == LeafLay::Fronds ? 0.02f : 0.2f), middle.z));
const uint16_t top = corner(Vector3(middle.x, crown.low.y + height * 0.95f, middle.z));
for (int side = 0; side < kHullSides; ++side)
{
const uint16_t low = static_cast<uint16_t>(rings[0] + side);
const uint16_t high = static_cast<uint16_t>(rings[kHullRings] + side);
builder.Triangle(foot, static_cast<uint16_t>(low + 1), low);
builder.Triangle(high, static_cast<uint16_t>(high + 1), top);
}
}
/// What one growing of the tree puts into the builder: the model is grown
/// the same every time, and each part of the mesh is one growing that keeps
/// only its own.
enum class Part
{
Survey, // nothing: the growing only finds the crown
Limbs, // the trunk and the branches
Twigs, // the stems of the top level, where there are three levels
Leaves,
FarLeaves,
};
/// One growing of a tree into a Builder.
class Growth
{
public:
Growth(const TreeSpec& spec, Builder& builder, Part part, const Crown& crown)
: m_Spec(spec),
m_Builder(builder),
m_Part(part),
m_Crown(crown),
m_Chance(spec.seed)
{
}
void Grow()
{
const StemLevel& trunk = m_Spec.level[0];
m_Scale = m_Spec.scale + m_Chance.Vary(m_Spec.scaleV);
const float length = std::max((trunk.length + m_Chance.Vary(trunk.lengthV)) * m_Scale, 0.1f);
const float radius = length * m_Spec.ratio;
Stem stem;
stem.level = 0;
stem.length = length;
stem.radius = radius;
stem.bare = m_Spec.baseSize * length;
PlanChildren(stem, length, 0.0f, 1.0f);
Frame frame;
frame.origin = Vector3(0.0f, -0.02f * length, 0.0f); // its foot a little into the ground
Segments(stem, frame, 0, 0.0f, false, 1.0f);
}
/// The box round the leaf cards' middles, as the growing found them.
const Crown& Found() const { return m_Found; }
/// How many leaf clusters the tree has, kept or not.
int Clusters() const { return m_Cards; }
/// A survey also writes each cluster's place into `places`, one for each
/// of Clusters().
void Collect(Vector3* places) { m_Places = places; }
private:
/// A stem as the model sees it, shared by the forks it splits into.
struct Stem
{
int level = 0;
float length = 1.0f;
float radius = 0.1f;
float bare = 0.0f; // from its foot, the length that carries nothing
int children = 0; // stems of the next level it carries
float childSpacing = 1.0f;
float lengthChildMax = 1.0f;
float turned = 0.0f; // how far round it the last child was put, radians
float side = 1.0f; // which side the next child goes, when they alternate
float splitDebt = 0.0f; // of forks owed: a fork is whole, the number asked for is not
float childDebt = 0.0f;
float offsetOnParent = 0.0f;
float parentLength = 1.0f;
};
const StemLevel& Level(int level) const { return m_Spec.level[std::min(level, kMaxLevels - 1)]; }
bool TopLevel(int level) const { return level >= m_Spec.levels - 1; }
/// Whether this growing keeps the wood of a stem of `level`.
bool KeepsWood(int level) const
{
const bool twig = m_Spec.levels >= 3 && TopLevel(level);
return m_Part == (twig ? Part::Twigs : Part::Limbs);
}
/// A stem's radius `along` it (0 its foot, 1 its tip): the paper's taper.
float RadiusAt(const Stem& stem, float along) const
{
const float taper = Level(stem.level).taper;
const float unit = taper < 1.0f ? taper : (taper < 2.0f ? 2.0f - taper : 0.0f);
const float tapered = stem.radius * (1.0f - unit * along);
float radius = tapered;
if (taper >= 1.0f)
{
// A tip rounded off, or a stem of beads.
const float fromTip = (1.0f - along) * stem.length;
const float depth = (taper < 2.0f || fromTip < tapered) ? 1.0f : taper - 2.0f;
const float inBead =
taper < 2.0f ? fromTip
: std::fabs(fromTip - 2.0f * tapered * std::floor(fromTip / (2.0f * tapered) + 0.5f));
if (!(taper < 2.0f && inBead >= tapered))
{
const float under = tapered * tapered - (inBead - tapered) * (inBead - tapered);
radius = (1.0f - depth) * tapered + depth * std::sqrt(std::max(under, 0.0f));
}
}
if (stem.level == 0)
{
// The trunk widens where it meets the ground.
const float y = std::max(1.0f - 8.0f * along, 0.0f);
radius *= m_Spec.flare * (std::pow(100.0f, y) - 1.0f) / 100.0f + 1.0f;
}
return std::max(radius, stem.length * 0.0004f);
}
/// How many stems of the next level `stem` carries and how far apart.
void PlanChildren(Stem& stem, float parentLength, float offsetOnParent, float lengthChildMaxOfIt)
{
stem.parentLength = parentLength;
stem.offsetOnParent = offsetOnParent;
stem.children = 0;
if (TopLevel(stem.level))
{
return;
}
const StemLevel& next = Level(stem.level + 1);
float count = static_cast<float>(next.branches);
if (stem.level == 1)
{
// Fewer on a short branch.
count *= 0.2f + 0.8f * (stem.length / parentLength) / std::max(lengthChildMaxOfIt, 0.01f);
}
else if (stem.level > 1)
{
count *= 1.0f - 0.5f * offsetOnParent / parentLength;
}
stem.children = std::clamp(static_cast<int>(count + 0.5f), 0, kMaxBranches);
stem.childSpacing = (stem.length - stem.bare) / static_cast<float>(std::max(stem.children, 1));
}
/// A ring of a stem's surface at `frame`. Returns its first corner.
uint16_t Ring(const Frame& frame, float radius, int sides, uint32_t color)
{
uint16_t first = 0;
for (int i = 0; i <= sides; ++i)
{
const float angle = static_cast<float>(i) * kTwoPi / static_cast<float>(sides);
const Vector3 normal = frame.x * std::cos(angle) + frame.y * std::sin(angle);
const uint16_t corner = m_Builder.Corner(frame.origin + normal * radius, normal,
static_cast<float>(i) / static_cast<float>(sides), 0.0f, color);
if (i == 0)
{
first = corner;
}
}
return first;
}
void Join(uint16_t lower, uint16_t upper, int sides)
{
for (int i = 0; i < sides; ++i)
{
const uint16_t a = static_cast<uint16_t>(lower + i);
const uint16_t b = static_cast<uint16_t>(a + 1);
const uint16_t c = static_cast<uint16_t>(upper + i);
const uint16_t d = static_cast<uint16_t>(c + 1);
m_Builder.Triangle(a, b, c);
m_Builder.Triangle(b, d, c);
}
}
uint32_t BarkAt(const Stem& stem, float along) const
{
// Darker at the trunk's foot and in under the crown.
const float shade = stem.level == 0 ? 0.62f + 0.3f * Smooth(0.0f, 0.5f, along) : 0.8f - 0.08f * stem.level;
return Shaded(m_Spec.bark, shade);
}
/// Grows a stem's segments from `first` on, from `frame`: its surface,
/// the stems and leaves it carries, and its forks. `straighten` is turned
/// back each segment, the way a fork straightens after it has leaned
/// away; `share` is how much of the stem's children this fork carries.
void Segments(Stem& stem, Frame frame, int first, float straighten, bool fork, float share)
{
const StemLevel& level = Level(stem.level);
const int segments = std::clamp(level.curveRes, 1, kMaxCurveRes);
const float segmentLength = stem.length / static_cast<float>(segments);
const int sides = stem.level == 0 ? 8 : (stem.level == 1 ? 4 : 3);
const bool wood = KeepsWood(stem.level);
// A twig is drawn as one straight piece from its foot to its tip: it
// is thin and half hidden, and there are many.
const bool onePiece = stem.level >= 2 && level.segSplits == 0.0f;
uint16_t ring = 0;
if (wood)
{
const float along = static_cast<float>(first) / static_cast<float>(segments);
ring = Ring(frame, RadiusAt(stem, along), sides, BarkAt(stem, along));
}
for (int s = first; s < segments; ++s)
{
// The bend at this segment's start.
if (s > 0 || fork)
{
float bend = level.curveBack == 0.0f ? level.curve / static_cast<float>(segments)
: (s < (segments + 1) / 2 ? level.curve : level.curveBack) /
(static_cast<float>(segments) * 0.5f);
bend += m_Chance.Vary(std::fabs(level.curveV)) / static_cast<float>(segments);
frame.TurnAboutX(bend * kDegrees);
if (straighten != 0.0f)
{
frame.TurnAboutX(straighten);
}
if (stem.level >= 2 && m_Spec.attractionUp != 0.0f)
{
// A twig turns upward by how far it leans and how it lies.
const float declination = std::acos(std::clamp(frame.z.y, -1.0f, 1.0f));
const float orientation = std::acos(std::clamp(frame.y.y, -1.0f, 1.0f));
frame.TurnAboutX(-m_Spec.attractionUp * declination * std::cos(orientation) /
static_cast<float>(segments));
}
}
// What it carries along this segment.
const float from = static_cast<float>(s) * segmentLength;
if (stem.children > 0)
{
for (int k = 0; k < stem.children; ++k)
{
const float offset = stem.bare + (static_cast<float>(k) + 0.5f) * stem.childSpacing;
if (offset < from || offset >= from + segmentLength)
{
continue;
}
// A fork carries its share of the stem's children.
stem.childDebt += share;
const bool carried = stem.childDebt >= 0.999f;
if (carried)
{
stem.childDebt -= 1.0f;
}
Child(stem, frame, offset, offset - from, carried);
}
}
if (TopLevel(stem.level))
{
Leaves(stem, frame, from, segmentLength);
}
frame.origin = frame.origin + frame.z * segmentLength;
if (wood && (!onePiece || s + 1 == segments))
{
const float along = static_cast<float>(s + 1) / static_cast<float>(segments);
const uint16_t next = Ring(frame, RadiusAt(stem, along), sides, BarkAt(stem, along));
Join(ring, next, sides);
ring = next;
}
// Forks at this segment's end.
if (s + 1 >= segments)
{
continue;
}
int forks = 0;
if (stem.level == 0 && s == 0 && m_Spec.baseSplits > 0)
{
forks = m_Spec.baseSplits;
}
else
{
const float owed = level.segSplits + stem.splitDebt;
forks = static_cast<int>(owed + 0.5f);
stem.splitDebt = owed - static_cast<float>(forks);
}
if (forks <= 0 || m_Stems >= kMaxStems)
{
continue;
}
const float left = static_cast<float>(segments - s - 1);
const float declination = std::acos(std::clamp(frame.z.y, -1.0f, 1.0f)) / kDegrees;
const float each = share / static_cast<float>(forks + 1);
for (int f = 0; f <= forks; ++f)
{
// Each fork leans away, less the more the stem leans already,
// and goes its own way round the tree's upright.
const float lean =
std::max(level.splitAngle + m_Chance.Vary(level.splitAngleV) - declination, 0.0f) * kDegrees;
const float chance = m_Chance.Next();
float round = (20.0f + 0.75f * (30.0f + std::fabs(declination - 90.0f)) * chance * chance) * kDegrees;
if (m_Chance.Next() < 0.5f)
{
round = -round;
}
Frame away = frame;
away.TurnAboutX(lean);
away.TurnAbout(Vector3(0.0f, 1.0f, 0.0f), round + static_cast<float>(f) * kTwoPi / (forks + 1));
if (f == forks)
{
// The stem itself is the last of them and goes on here.
frame = away;
straighten = -lean / left;
share = each;
fork = true;
if (wood)
{
const float along = static_cast<float>(s + 1) / static_cast<float>(segments);
ring = Ring(frame, RadiusAt(stem, along), sides, BarkAt(stem, along));
}
break;
}
++m_Stems;
Segments(stem, away, s + 1, -lean / left, true, each);
}
}
}
/// A stem of the next level, `offset` along `stem` and `into` the
/// segment `frame` starts. Not `carried`: its chance is still taken, so
/// the tree grows the same, and nothing of it is grown.
void Child(Stem& stem, const Frame& frame, float offset, float into, bool carried)
{
const StemLevel& level = Level(stem.level + 1);
const float lengthChildMax = level.length + m_Chance.Vary(level.lengthV);
Stem child;
child.level = stem.level + 1;
const float grows = std::max(stem.length - stem.bare, 0.001f);
if (stem.level == 0)
{
child.length = stem.length * lengthChildMax * ShapeRatio(m_Spec.shape, (stem.length - offset) / grows);
}
else
{
child.length = lengthChildMax * (stem.length - 0.6f * offset);
}
child.length = std::max(child.length, stem.length * 0.02f);
// As thick as its length says, and no thicker than the stem it leaves.
child.radius = std::min(stem.radius * std::pow(child.length / stem.length, m_Spec.ratioPower),
RadiusAt(stem, offset / stem.length));
float down = level.downAngle;
if (level.downAngleV >= 0.0f)
{
down += m_Chance.Vary(level.downAngleV);
}
else
{
// More low on its parent, less high on it.
m_Chance.Next();
down += level.downAngleV * (1.0f - 2.0f * ShapeRatio(CrownShape::Conical, (stem.length - offset) / grows));
}
float round = 0.0f;
if (level.rotate >= 0.0f)
{
stem.turned += (level.rotate + m_Chance.Vary(level.rotateV)) * kDegrees;
round = stem.turned;
}
else
{
// To one side, then the other.
stem.side = -stem.side;
round = stem.side * (180.0f + level.rotate + m_Chance.Vary(level.rotateV)) * kDegrees;
}
if (!carried || m_Stems >= kMaxStems)
{
return;
}
++m_Stems;
Frame at = frame;
at.origin = frame.origin + frame.z * into;
at.TurnAboutZ(round);
at.TurnAboutX(down * kDegrees);
PlanChildren(child, stem.length, offset, lengthChildMax);
Segments(child, at, 0, 0.0f, false, 1.0f);
}
/// A leaf card: `across` and `up` are its half width and its height from
/// `foot`, `normal` what it is lit by.
void Card(const Vector3& foot, const Vector3& across, const Vector3& up, const Vector3& normal, uint32_t footColor,
uint32_t topColor)
{
const uint16_t a = m_Builder.Corner(foot - across, normal, 0.0f, 0.0f, footColor);
const uint16_t b = m_Builder.Corner(foot + across, normal, 1.0f, 0.0f, footColor);
const uint16_t c = m_Builder.Corner(foot + across + up, normal, 1.0f, 1.0f, topColor);
const uint16_t d = m_Builder.Corner(foot - across + up, normal, 0.0f, 1.0f, topColor);
m_Builder.Triangle(a, b, c);
m_Builder.Triangle(a, c, d);
}
/// The leaves a stem of the top level carries along the segment `frame`
/// starts, `from` along the stem.
void Leaves(const Stem& stem, const Frame& frame, float from, float segmentLength)
{
const int leaves = std::clamp(m_Spec.leaves, 0, kMaxLeaves);
const float detail = std::clamp(m_Spec.detail, 0.05f, 1.0f);
const bool far = m_Part == Part::FarLeaves;
const bool kept = m_Part == Part::Leaves || far;
// Fewer cards are each larger, so the crown stays covered.
const float grown = std::pow(detail, -0.35f) * (far ? kFarLeafSize : 1.0f);
for (int i = 0; i < leaves; ++i)
{
// Along its outer part: a twig is bare where it leaves its branch.
const float bare = m_Spec.leafLay == LeafLay::Fronds ? 0.1f : 0.25f;
const float offset =
stem.length * (bare + (1.0f - bare) * (static_cast<float>(i) + 0.5f) / static_cast<float>(leaves));
if (offset < from || offset >= from + segmentLength)
{
continue;
}
const int card = m_Cards++;
const float size = m_Spec.leafSize * (0.8f + 0.4f * m_Chance.Next());