forked from annayudovin/PDN-ScrollGeneratorPlugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpiralTree.cs
1220 lines (1017 loc) · 50.6 KB
/
SpiralTree.cs
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
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace ScrollGeneratorEffect
{
public class SpiralTree
{
private List<SpiralNode> Nodes { get; set; } = new List<SpiralNode>();
private readonly Polygon _container;
private readonly Random _rnd;
private string _treeLog = "";
public SpiralNode this[int i]
{
get => Nodes[i];
set => Nodes[i] = value;
}
public int Count => Nodes.Count;
public SpiralTree()
{
_rnd = new Random();
}
public SpiralTree(Polygon container, float initRad = 0)
{
_rnd = new Random();
Configs.InitAll(_rnd);
_container = container;
initRad = initRad == 0f ? Configs.initRadius : initRad;
if (Configs.RANDANG) { Configs.rootAngle = Configs.Random(0f, (float)Math.Tau, _rnd); }
float initAngl = Configs.rootAngle;
if (Configs.TWIN)
{
GrowTwins(_container.Centroid, initRad, initAngl, Configs.twinRatio);
}
else
{
SpiralNode root = new(_container.Centroid, initRad, initAngl);
Nodes.Add(root);
_ = CheckEdgeFit(root); //initialize edge data
float angl = 2f * (float)Math.Tau;
float x = root.SprlCtr.X + (root.Rad * 0.099f * angl * (float)Math.Cos(angl + root.StrtAngl));
float y = root.SprlCtr.Y + (root.Rad * 0.099f * angl * (float)Math.Sin(angl + root.StrtAngl));
root.StrtPt = new PointF(x, y);
}
}
public void CreateLog()
{
if (!Configs.LOG) { return; }
string dName = AppDirectoryPath();
if (dName == "") { return; }
string fName = "treeLog.txt";
string fPath = Path.Combine(dName, fName);
if (!File.Exists(fPath))
{
// Create a file to write to.
using StreamWriter sw = File.CreateText(fPath);
sw.Write(Configs.LogProperties());
sw.Write(_container.PrintPolygon());
}
else
{
using StreamWriter sw = new(fPath, true);
sw.Write(Configs.LogProperties());
sw.Write(_container.PrintPolygon());
}
}
public void AddToLog(string lgString)
{
_treeLog += lgString;
}
public void WriteLog()
{
if (!Configs.LOG) { return; }
string dName = AppDirectoryPath();
if (dName == "") { return; }
string fName = "treeLog.txt";
string fPath = Path.Combine(dName, fName);
if (!File.Exists(fPath))
{
// Create a file to write to.
using StreamWriter sw = File.CreateText(fPath);
sw.Write(_treeLog);
}
else
{
using StreamWriter sw = new(fPath, true);
sw.Write(_treeLog);
}
}
public List<PointF[]> PlotSpiralTreePoints()
{
List<PointF[]> spiralFlPtsLst = new();
foreach (SpiralNode node in Nodes)
{
PointF[] spiralFlPts = node.PlotSpiralPoints();
spiralFlPtsLst.Add(spiralFlPts);
}
return spiralFlPtsLst;
}
//produces complement Hue and Value, at the same Saturation
public List<int[]> GetRGBRandomComplement()
{
int H = _rnd.Next(0, 100);
int S = _rnd.Next(0, 100);
int V = _rnd.Next(0, 100);
//increase value contrast
if (Math.Abs(V - 50) <= 20) { V = V > 50? V + 15 : V - 15; }
int[] color = HsvToRgb(H, S, V);
int[] colorHSV = { H, S, V }; //for debugging only
H = (H + 50) % 100;
V = (V + 50) % 100;
//increase value contrast
if (Math.Abs(V - 50) <= 20) { V = V > 50 ? V + 15 : V - 15; }
int[] complement = HsvToRgb(H, S, V);
int[] complementHSV = { H, S, V }; //for debugging only
return new List<int[]> { color, complement, colorHSV, complementHSV };
}
//ranges for each of h, s, and v is 0-100
//translation from javascript function found at https://gist.github.com/mjackson/5311256
private int[] HsvToRgb(int _h, int _s, int _v)
{
float h = _h / 100f;
float s = _s / 100f;
float v = _v / 100f;
float r = 0;
float g = 0;
float b = 0;
float i = (float)Math.Floor(h * 6);
float f = h * 6 - i;
float p = v * (1 - s);
float q = v * (1 - f * s);
float t = v * (1 - (1 - f) * s);
switch (i % 6)
{
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
r *= 255;
g *= 255;
b *= 255;
int[] _rgb = { (int)r, (int)g, (int)b };
return _rgb;
}
public List<PointF[]> PlotTreeEnvelopePoints()
{
List<PointF[]> outerFlPtsLst = new();
foreach (SpiralNode node in Nodes)
{
PointF[] outerFlPts = node.PlotNodeEnvelopePoints();
outerFlPtsLst.Add(outerFlPts);
}
return outerFlPtsLst;
}
//let the app make sure we have/can create a MyDocuments
//directory to put files into - and produce appropriate error messages
public static string AppDirectoryPath()
{
string myDocsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string appFolderName = "ScrollGenerator";
string dirPath = Path.Combine(myDocsPath, appFolderName);
return !Directory.Exists(dirPath) ? "" : dirPath;
}
//this overload uses cached points list to avoid recalculating everything again
public static void WriteSVG(List<PointF[]> spiralPtsLst, int boxWidth, int boxHeight, string scrollColor, int strokeWidth)
{
string dName = AppDirectoryPath();
if (dName == "") { return; }
string timeStmp = DateTime.Now.ToString("s").Replace(':', '-').Replace('T', '-');
string fName = $"scroll-{timeStmp}.svg";
string fPath = Path.Combine(dName, fName);
if (!File.Exists(fPath))
{
using StreamWriter sw = File.CreateText(fPath);
sw.Write(buildSVG(spiralPtsLst, boxWidth, boxHeight, scrollColor, strokeWidth));
}
static string buildSVG(List<PointF[]> spiralPtsLst, int boxWidth, int boxHeight, string scrollColor, int strokeWidth)
{
string svgFileString = $"<svg width=\"{boxWidth}\" height=\"{boxHeight}\" " +
$"viewBox=\"0 0 {boxWidth} {boxHeight}\">\n";
string sprlStrtString = $" <path style=\"fill:none; stroke:{scrollColor}; stroke-width:{strokeWidth}\"\n d=\"";
string sprlEndString = $"\">\n </path>\n";
string sprlPtsString = "";
foreach (PointF[] arry in spiralPtsLst)
{
sprlPtsString += sprlStrtString;
sprlPtsString += $"M {arry[0].X},{arry[0].Y} ";
sprlPtsString += $"C {arry[0].X},{arry[0].Y}";
foreach (PointF pt in arry[1..]) { sprlPtsString += $" {pt.X},{pt.Y}"; }
sprlPtsString += sprlEndString;
}
svgFileString += sprlPtsString;
svgFileString += "</svg>";
return svgFileString;
}
}
public void WriteSVG(int boxWidth, int boxHeight, string scrollColor, int strokeWidth)
{
string dName = AppDirectoryPath();
if (dName == "") { return; }
string timeStmp = DateTime.Now.ToString("s").Replace(':', '-').Replace('T', '-');
string fName = $"scroll-{timeStmp}.svg";
string fPath = Path.Combine(dName, fName);
if (!File.Exists(fPath))
{
using StreamWriter sw = File.CreateText(fPath);
sw.Write(buildSVG(boxWidth, boxHeight, scrollColor, strokeWidth));
}
string buildSVG(int boxWidth, int boxHeight, string scrollColor, int strokeWidth)
{
string svgFileString = $"<svg width=\"{boxWidth}\" height=\"{boxHeight}\" " +
$"viewBox=\"0 0 {boxWidth} {boxHeight}\">\n";
string sprlStrtString = $" <path style=\"fill:none; stroke:{scrollColor}; stroke-width:{strokeWidth}\"\n d=\"";
string sprlEndString = $"\">\n </path>\n";
string sprlPtsString = "";
foreach (SpiralNode node in Nodes)
{
PointF[] spiralPts = node.PlotSpiralPoints();
sprlPtsString += sprlStrtString;
sprlPtsString += $"M {spiralPts[0].X},{spiralPts[0].Y} ";
sprlPtsString += $"C {spiralPts[0].X},{spiralPts[0].Y}";
foreach (PointF pt in spiralPts[1..]) { sprlPtsString += $" {pt.X},{pt.Y}"; }
sprlPtsString += sprlEndString;
}
svgFileString += sprlPtsString;
svgFileString += "</svg>";
return svgFileString;
}
}
private static List<PointF> CenterPair(PointF initCtr, float strtAngl, float rad1, float twinScale)
{
float rad2 = rad1 * twinScale;
float shiftAngl = 0.05f;
float halfDist = 0.5f * Configs.rootBuffer;
float ctr1X = initCtr.X + ((float)Math.Cos(strtAngl - shiftAngl) * (rad1 + halfDist));
float ctr1Y = initCtr.Y + ((float)Math.Sin(strtAngl - shiftAngl) * (rad1 + halfDist));
float ctr2X = initCtr.X + ((float)Math.Cos(Trig.ComplementAngle(strtAngl + shiftAngl)) *
(rad2 + halfDist * twinScale));
float ctr2Y = initCtr.Y + ((float)Math.Sin(Trig.ComplementAngle(strtAngl + shiftAngl)) *
(rad2 + halfDist * twinScale));
float ctrYavg = Math.Abs(Math.Abs(initCtr.Y - ctr1Y) - Math.Abs(initCtr.Y - ctr2Y)) / 2;
ctr2Y -= ctrYavg;
ctr1Y -= ctrYavg;
return new List<PointF>() { new PointF(ctr1X, ctr1Y), new PointF(ctr2X, ctr2Y) };
}
public void GrowTwins(PointF initCtr, float rad, float strtAngl, float twinScale = 1)
{
if (!Configs.TWIN) { return; }
if (twinScale > 1) { twinScale = 1f; }
if (twinScale < 0.6) { twinScale = 0.6f; }
List<PointF> ctrLst = CenterPair(initCtr, strtAngl, rad, twinScale);
PointF ctr1 = ctrLst[1];
PointF ctr2 = ctrLst[0];
SpiralNode root = new(ctr1, rad, strtAngl);
Nodes.Add(root);
_ = CheckEdgeFit(root);
SpiralNode twin = new(ctr2, rad * twinScale, Trig.ComplementAngle(strtAngl), true);
if (CheckEdgeFit(twin)) { Nodes.Add(twin); }
//average the two roots' start points, for solid transition
float avgX = (root.StrtPt.X + twin.StrtPt.X) / 2;
float avgY = (root.StrtPt.Y + twin.StrtPt.Y) / 2;
root.StrtPt = new PointF(avgX, avgY);
twin.StrtPt = new PointF(avgX, avgY);
}
public float FirstOpenAngl(int idx) //returns absolute angle
{
SpiralNode idxNode = Nodes[idx];
//first leaf on a root node
if (!idxNode.HasLeaves && idxNode.PrntIdx == -1)
{
float rootDist = 0;
if (Configs.TWIN)
{ rootDist = Trig.PointDist(Nodes[0].Ctr, Nodes[1].Ctr); }
return idxNode.RootBaseAngle(idx, rootDist); //returns absolute angle
}
float firstOpen;
if (!idxNode.HasLeaves) //first leaf on index node
{
SpiralNode prntNode = Nodes[idxNode.PrntIdx];
int problemSibIdx = prntNode.ObstructingSibIdx(idx);
if (problemSibIdx != -1)
{ //index node's parent has an obstructing sibling
SpiralNode problemSibNode = Nodes[problemSibIdx];
float problemSibAngle = SpiralNode.SibConflictAngle(idxNode, problemSibNode); //returns absolute angle
return problemSibAngle != -100 ? problemSibAngle : idxNode.BaseAngle(prntNode.Rad);//sibling too far away to obstruct leaves
}
else //index node has no obstructing siblings
{ return idxNode.BaseAngle(prntNode.Rad); } //returns absolute angle
}
else
{
int prevLeafIdx = idxNode.LastLeafIdx();
float prevLeafAngl = idxNode.LastLeafAngle(); //returns absolute angle
float prevLeafRad = Nodes[prevLeafIdx].Rad;
float prevLeafArc = Trig.CalcLeafArcSpan(idxNode.Rad, prevLeafRad);
firstOpen = prevLeafAngl - (idxNode.Clock * (Configs.nodeHalo + prevLeafArc));
}
return Trig.Mod2PI(firstOpen);
}
public bool CheckFit(SpiralNode newLeaf)
{
bool fitsNhbrs = CheckNhbrFit(newLeaf);
bool fitsEdges = CheckEdgeFit(newLeaf);
return fitsNhbrs && fitsEdges;
}
public bool CheckNhbrFit(SpiralNode newLeaf)
{
int leafPrntIdx = newLeaf.PrntIdx;
//for testing fit check:
//newLeaf.TmpNhbrIdxs.Clear();
//newLeaf.TmpNhbrDists.Clear();
//scan for nodes that collide with leaf
for (int idx = 0; idx < Nodes.Count; idx++)
{
if (leafPrntIdx == idx) { continue; }//parent isn't a neighbor
SpiralNode curr = Nodes[idx];
float skinDistToLeaf = SpiralNode.GetSurfaceDist(newLeaf, curr);
float cutoff = Configs.nodeBuffer;
//collision cutoff is smaller for sibling
if (leafPrntIdx == curr.PrntIdx) { cutoff = 0.65f * Configs.nodeBuffer; }
//if (skinDistToLeaf < 10) //for testing fit check
//{
// newLeaf.TmpNhbrIdxs.Add(idx);
// newLeaf.TmpNhbrDists.Add(skinDistToLeaf);
//}
if (skinDistToLeaf < cutoff) //collision check
{
newLeaf.NhbrIdxs.Add(idx);
newLeaf.NhbrDists.Add(skinDistToLeaf);
}
}
//leaf won't fit as is, needs further adjustment
return newLeaf.NhbrIdxs.Count <= 0;
}
public bool CheckEdgeFit(SpiralNode newLeaf)
{
PointF closestPt;
List<float> edgeDists = new();
List<PointF> edgePoints = new();
List<float> prntEdgeDists = new();
PointF prntCtr = new(0, 0);
float maxLeafFitDist = 0f;
if (newLeaf.PrntIdx != -1)
{
SpiralNode prntNode = Nodes[newLeaf.PrntIdx];
float prntRad = prntNode.Rad;
prntCtr = prntNode.Ctr;
prntEdgeDists.AddRange(prntNode.EdgeDists);
maxLeafFitDist = prntRad + (2 * newLeaf.Rad) + newLeaf.Lift + Configs.nodeBuffer;
}
for (int idx = 0; idx < _container.Edges.Count; idx++)
{
Polygon.FlEdge edge = _container.Edges[idx];
bool jumpedEdge = false;
if (newLeaf.PrntIdx != -1) //root nodes have no parent: can't do this check
{
if (Math.Abs(prntEdgeDists[idx]) < maxLeafFitDist) //parent is close enough to edge to warrant checking
{
jumpedEdge = edge.CrossEdge(prntCtr, newLeaf.Ctr);
}
}
Tuple<float, PointF> result = edge.DistanceToEdge(newLeaf.Ctr);
float edgeDist = result.Item1;
closestPt = result.Item2;
float skinEdgeDist = SpiralNode.GetSkinDistToPt(newLeaf, closestPt);
//found a deal breaker
if (jumpedEdge || skinEdgeDist < Configs.nodeBuffer / 2) { edgeDist = 0; }
edgeDists.Add(Math.Abs(edgeDist));
edgePoints.Add(closestPt);
}
//at this point edgeDists/edgePoints contains [corrected] copy of leaf's parent's data
//overwrite existing [inherited] data from leaf with updated data
newLeaf.EdgeDists = edgeDists;
newLeaf.EdgePoints = edgePoints;
return !newLeaf.EdgeDists.Contains(0);
}
public bool TryAdjustToEdges(ref SpiralNode newLeaf, SpiralNode prntNode, bool limited = false)
{
List<float> edgeFitAngls = new();
float initStartAngl = FirstOpenAngl(newLeaf.PrntIdx);
int edgeIdx = 0;
int problemEdgeCount = newLeaf.EdgeDists.Count(x => x == 0);
//get idx of either the closest (to leaf) edge or, most likely case: the only one with conflict
if (problemEdgeCount == 1) { edgeIdx = newLeaf.EdgeDists.FindIndex(x => x == 0); }
if (problemEdgeCount > 1) //case of multiple conflicting edges
{
PointF leafCtr = newLeaf.Ctr;
IEnumerable<(int idx, float dist)> edgePtDistFltr =
newLeaf.EdgePoints.Select((x, i) => (i, Trig.PointDist(x, leafCtr)));
List<(int idx, float dist)> edgePtDists = edgePtDistFltr.ToList();
edgePtDists.Sort((a, b) => a.dist > b.dist ? 1 : a.dist < b.dist ? -1 : 0); //ascending by dist
(int idx, float dist) = edgePtDists[0];
edgeIdx = idx; //index of edge closest to leaf
}
float edgeArc = Trig.EdgeFitArc(prntNode.EdgePoints[edgeIdx], prntNode.Ctr, prntNode.Rad, newLeaf.Rad, newLeaf.Lift);
if (edgeArc == -100) { return false; }
float anglFromPrnt = Trig.AngleToPoint(prntNode.Ctr, prntNode.EdgePoints[edgeIdx]);
//check BOTH possible angles around leaf tangent
//The option going in the direction of leaf growth (decreasing angles for positive Clock)
//needs to be tried first. If both options are valid (and both work potentially fit),
//the option tried first will be kept. To grow maximum number of leaves, we want
//*this* leaf to fit before the edge, and the next one (if any), AFTER it
List<float> tmpLst = new() { anglFromPrnt + edgeArc, anglFromPrnt - edgeArc };
if (prntNode.Clock < 0) { tmpLst.Sort(); }
float angleToFit1 = Trig.Mod2PI(tmpLst[0]);
float angleToFit2 = Trig.Mod2PI(tmpLst[1]);
string edgLg = "";
if (Configs.LOG)
{
edgLg = $"angle from leaf's parent to edge#{edgeIdx}: {anglFromPrnt:F3}, distance: " +
$"{prntNode.EdgeDists[edgeIdx]:F3}; edge fit arc: {edgeArc:F3} produced fit angles: ";
}
bool inRange1 = limited ? prntNode.AngleInSproutRange(angleToFit1) : prntNode.AngleInGrowthRange(initStartAngl, angleToFit1);
if (Configs.LOG) { edgLg += $"{angleToFit1:F3} " + (inRange1 ? "" : "(out of range) "); }
bool inRange2 = limited ? prntNode.AngleInSproutRange(angleToFit2) : prntNode.AngleInGrowthRange(initStartAngl, angleToFit2);
if (Configs.LOG) { edgLg += $" and {angleToFit2:F3} " + (inRange2 ? "" : "(out of range) \n"); }
if (!inRange1 && !inRange2) { return false; } //no valid resolutions exist, bail
float origStrt = newLeaf.StrtAngl;
int origSlot = newLeaf.Slot;
bool fitsAll;
int newSlot;
if (inRange1)
{
newSlot = prntNode.CorrectedSlot(angleToFit1, origSlot);
if (Configs.GRAD && Configs.SMTOLG) { newLeaf.Slot = newSlot; }
newLeaf.AdjustLeaf(prntNode, angleToFit1, newSlot, _rnd);
fitsAll = CheckFit(newLeaf);
if (Configs.LOG)
{
edgLg += $"adjusting leaf's start angle to {angleToFit1:F3} ";
edgLg += (fitsAll ? "resolved " : "did not resolve ") + "all existing conflicts";
AddToLog(edgLg + "\n");
}
if (fitsAll || !inRange2) { return fitsAll; }
else if (inRange2 && !newLeaf.EdgeDists.Contains(0) && newLeaf.NhbrIdxs.Count > 0)
{
//if both solutions are in range, attempt to resolve neighbor conflicts for the first
//attempted before moving on to the second
fitsAll = TryAdjustToNhbrs(ref newLeaf, prntNode, false, limited);
if (fitsAll) { return true; }
}
}
if (inRange2)
{
newSlot = prntNode.CorrectedSlot(angleToFit2, origSlot);
if (Configs.GRAD && Configs.SMTOLG) { newLeaf.Slot = newSlot; }
newLeaf.AdjustLeaf(prntNode, angleToFit2, newSlot, _rnd);
fitsAll = CheckFit(newLeaf);
if (Configs.LOG)
{
edgLg += $"adjusting leaf's start angle to {angleToFit2:F3} ";
edgLg += (fitsAll ? "resolved " : "did not resolve ") + "all existing conflicts";
AddToLog(edgLg + "\n");
}
return fitsAll; //caller will check neighbors on this one
}
return false;
}
public bool TryMinAdjustment(ref SpiralNode newLeaf, SpiralNode prntNode)
{
float minNhbrDist = newLeaf.NhbrDists.Min();
float initStartAngl = Trig.ComplementAngle(newLeaf.StrtAngl);
int nhbrIdx = newLeaf.ClosestNhbrIdx();
if (nhbrIdx < 0) { return false; }
SpiralNode nhbrNode = Nodes[nhbrIdx];
float ratioMult = Trig.RadRatioMult(newLeaf.Rad, nhbrNode.Rad);
ratioMult = Math.Max(ratioMult, 2f);
for (int i = 0; i < 2; i++)
{
int direction = -1 + 2 * i;
float tryAngle = Trig.Mod2PI(initStartAngl + direction * ratioMult * Configs.nodeHalo);
if (Configs.LOG)
{
string dirStr = direction > 0 ? "+" : "-";
string minLg = $"attempt minimal adjustment angle {tryAngle:F3} (from {initStartAngl:F3}, " +
$"at curr rad {newLeaf.Rad}) in {dirStr} direction for neighbor {nhbrIdx} " +
$"(minNhbrDist={minNhbrDist:F3}, rad={nhbrNode.Rad:F3} " +
$"anglFromPrnt={Trig.AngleToPoint(prntNode.Ctr, nhbrNode.Ctr)})\n";
AddToLog(minLg);
}
SpiralNode copy = new(newLeaf);
copy.AdjustLeaf(prntNode, tryAngle, newLeaf.Slot, _rnd);
bool startFits = CheckFit(copy);
if (startFits || newLeaf.NhbrIdxs.Count == 0)
{
newLeaf = copy;
if (Configs.LOG) { AddToLog($"minimal adjustment worked for idx: {Nodes.Count}\n"); }
return startFits;
}
}
return false;
}
public bool TryAdjustToNhbrs(ref SpiralNode newLeaf, SpiralNode prntNode, bool aftrRslt = false, bool limited = false)
{
int origSlot = newLeaf.Slot;
int maxTries = Configs.useSlots.Count;
int prevConflictCount = newLeaf.NhbrIdxs.Count;
List<float> alreadyTried = new();
bool startFits = false; //that's why we are here
while (!startFits && newLeaf.NhbrIdxs.Count > 0 && maxTries > 0)
{
maxTries--; //convenient limit counter
//only edge conflicts
if (newLeaf.NhbrIdxs.Count == 0 && newLeaf.EdgeDists.Contains(0)) { return false; }
float prevDistSum = newLeaf.NhbrDists.Sum();
//special case: very minor conflict
float minNhbrDist = newLeaf.NhbrDists.Min();
if (minNhbrDist > Configs.nodeBuffer * 0.2) //a VERY small problem
{
startFits = TryMinAdjustment(ref newLeaf, prntNode);
//either worked completely, of it's no longer neighbor problems
if (startFits || newLeaf.NhbrIdxs.Count == 0) { return startFits; }
}
//special case: nearest sibling collision
if (newLeaf.NhbrIdxs.Count == 1 && newLeaf.NhbrIdxs[0] == Nodes.Count - 1 && Nodes[^1].PrntIdx == newLeaf.PrntIdx)
{
float firstOpenAngl = FirstOpenAngl(newLeaf.PrntIdx);
float leafArc = Trig.CalcLeafArcSpan(prntNode.Rad, newLeaf.Rad);
float nextLeafAngl = Trig.Mod2PI(firstOpenAngl - (prntNode.Clock * (Configs.nodeHalo + leafArc)));
newLeaf.AdjustLeaf(prntNode, nextLeafAngl, newLeaf.Slot, _rnd);
startFits = CheckFit(newLeaf);
if (startFits)
{
if (Configs.LOG) { AddToLog($"sibling adjustment worked for idx: {Nodes.Count}\n"); }
return true;
}
else if (newLeaf.NhbrIdxs.Count == 0) { return false; } //it's no longer neighbor problems
}
float nhbrFitAngl = GetNeighborFitAngle(newLeaf, prntNode, aftrRslt);
if (limited && !aftrRslt)
{
if (!prntNode.AngleInSproutRange(nhbrFitAngl))
{
if (Configs.LOG) { AddToLog($"maximum adjustment for resprouted leaf exceeded. Gave up.\n"); }
return false;
}
}
//no [new] resolutions offered, bail
if (nhbrFitAngl != -100) //returned a valid angle we tried before
{
if (alreadyTried.Contains(nhbrFitAngl))
{
if (Configs.LOG) { AddToLog($"no new solutions found, giving up.\n"); }
return false;
}
}
else //returned -100
{
if (Configs.LOG) { AddToLog($"no good alternatives found, giving up.\n"); }
return false;
}
int newSlot = prntNode.CorrectedSlot(nhbrFitAngl, origSlot);
if (Math.Abs(newLeaf.Slot - newSlot) > 2)
{
if (Configs.LOG)
{
string sltLog = $"at this angle, leaf slot should be {newSlot}, current slot {newLeaf.Slot}\n";
sltLog += "unsuitable adjustment scale, giving up. ";
AddToLog(sltLog);
}
return false;
}
alreadyTried.Add(nhbrFitAngl);
if (!aftrRslt)
{
newLeaf.AdjustLeaf(prntNode, nhbrFitAngl, newSlot, _rnd);
startFits = CheckFit(newLeaf); //leaf has been re-centered, check fit again
}
else
{// try backing up, but if it doesn't work, ditch the copy and
//start over like it never happened
aftrRslt = false; //after the first pass, this will become a problem if true
SpiralNode copy1 = new(newLeaf);
if (Configs.GRAD && !Configs.SMTOLG) { copy1.Slot = newSlot; }
copy1.AdjustLeaf(prntNode, nhbrFitAngl, newSlot, _rnd);
startFits = CheckFit(copy1); //leaf has been re-centered, check fit again
if (startFits)
{
newLeaf = copy1;
if (Configs.LOG) { AddToLog($"adjustment worked for idx: {Nodes.Count}\n"); }
return true;
}
else if (Configs.LOG) { AddToLog("didn't work:\n" + newLeaf.PrintNodeNhbrData()); }
}
if (startFits)
{
if (Configs.LOG) { AddToLog($"adjustment worked for idx: {Nodes.Count}\n"); }
return true;
}
else if (alreadyTried.Count > 3 && newLeaf.NhbrDists.Sum() < prevDistSum &&
prevConflictCount > newLeaf.NhbrIdxs.Count)
{
if (Configs.LOG) { AddToLog($"adjustment attempts causing more problems, giving up.\n"); }
return false;
} //attempts are making things worse
}
if (Configs.LOG) { AddToLog($"after exhausting maximum attempts, giving up.\n"); }
return false;
}
public float GetNeighborFitAngle(SpiralNode newLeaf, SpiralNode prntNode, bool aftrRslt = false)
{
float firstOpenAngl = FirstOpenAngl(newLeaf.PrntIdx); //in case there are no leaves yet
int nhbrIdx;
float leafArc = Trig.CalcLeafArcSpan(prntNode.Rad, newLeaf.Rad);
if (newLeaf.NhbrIdxs.Count == 1) { nhbrIdx = newLeaf.NhbrIdxs[0]; }
else { nhbrIdx = newLeaf.ClosestNhbrIdx(); } //or find worst conflict
SpiralNode nhbrNode = Nodes[nhbrIdx];
if (Configs.LOG)
{
string confLog = "conflicting neighbors:\n";
confLog += newLeaf.PrintNodeNhbrData();
confLog += $"adjust to neighbor idx: {nhbrIdx}\n";
AddToLog(confLog);
}
float fitArc = Trig.ClosestFitAngle(prntNode, newLeaf, nhbrNode);
if (fitArc == -100f) { return -100f; }
else
{
bool inRange;
float initStart = Trig.ComplementAngle(newLeaf.StrtAngl);
float prntToNhbrAngl = Trig.AngleToPoint(prntNode.Ctr, nhbrNode.Ctr);
if (aftrRslt)
{
//first try backing up the leaf rather than moving it forward as usual
float angl0 = Trig.Mod2PI(prntToNhbrAngl + (prntNode.Clock * fitArc));
inRange = prntNode.AngleInGrowthRange(firstOpenAngl, angl0);
if (inRange)
{
string bkpLg = $" current start (parent-to-leaf angle):{initStart}, " +
$"parent-to-neighbor angle: {prntToNhbrAngl}; attempt backing up to start angle: {angl0:F3}\n";
if (Configs.LOG) { AddToLog(bkpLg); }
return angl0;
}
}
//proceed as usual
float angl1 = Trig.Mod2PI(prntToNhbrAngl - (prntNode.Clock * fitArc));
float remainingArc = Trig.Mod2PI(prntNode.Clock * (fitArc - prntNode.EndAngl));
inRange = prntNode.AngleInGrowthRange(firstOpenAngl, angl1);
if (inRange && remainingArc >= 0.5 * leafArc)
{
if (Configs.LOG) { AddToLog($"attempt new start angle: {angl1:F3}\n"); }
return angl1;
}
}
return -100;
}
public bool TryAdjust(ref SpiralNode newLeaf, SpiralNode prntNode, bool canBackUp, bool limited = false)
{
bool adjustSuccess;
//first see if there's an edge problem
if (newLeaf.EdgeDists.Contains(0) && newLeaf.NhbrIdxs.Count == 0)
{
adjustSuccess = TryAdjustToEdges(ref newLeaf, prntNode, limited);
if (adjustSuccess) { return true; }
if (!adjustSuccess && newLeaf.EdgeDists.Contains(0)) { return false; }
//else: still doesn't fit, but edge problems solved - neighbors
//may be pacified by the next block
}
if (newLeaf.NhbrIdxs.Count > 0)
{
adjustSuccess = TryAdjustToNhbrs(ref newLeaf, prntNode, canBackUp, limited);
if (adjustSuccess) { return true; }
}
return false;
}
// make a copy, try adjusting copy - if doesn't work, discard copy,
// make a fresh copy, reslot copy, if still problems, make second copy - adjust second copy (of reslotted copy), if doesn't work, discard second copy,
// reslot first copy, if still problems, make second copy - adjust second copy, if doesn't work, discard
public bool TryToFit(ref SpiralNode newLeaf, SpiralNode prntNode, bool noRslt = false)
{
//try going up a slot (at a new slot angle) a few times to see if it fixes the problem
SpiralNode copy1 = new(newLeaf);
(int slt, float rad, float angl) oldConditions = (newLeaf.Slot, newLeaf.Rad, newLeaf.StrtAngl);
(int slt, float rad, float angl) newConditions = (0, 0f, -100f);
float initStartAngl = Trig.ComplementAngle(newLeaf.StrtAngl);
//ADJUST HERE
bool canBackUp = Configs.maxLeaves <= 3;
bool adjustSuccess = TryAdjust(ref copy1, prntNode, canBackUp, noRslt);
if (adjustSuccess)
{
newLeaf = copy1;
return true;
}
else
{
copy1 = new SpiralNode(newLeaf);
if (noRslt) { return false; }
}
float newStart = initStartAngl;
List<int> slotLst = Configs.useSlots;
int sltIdx = slotLst.FindIndex(x => x == copy1.Slot);
for (int i = sltIdx + 1; i < slotLst.Count; i++)
{
int slt = slotLst[i];
newStart = prntNode.ReslotAngl(slt, false); //stops reslotAngl decrementing by one
if (newStart == -100) //can't reslot, bail
{
newConditions = (slt, 0f, -100f);
LogReslot(false, 2, oldConditions, newConditions);
return false;
}
//RESLOT HERE
if (prntNode.AngleInGrowthRange(initStartAngl, newStart))
{
copy1.AdjustLeaf(prntNode, newStart, slt, _rnd);
if (Configs.GRAD && !Configs.SMTOLG &&
Configs.RadTooSmall(copy1.Rad)) { return false; }
bool reslotSuccess = CheckFit(copy1);
newConditions = (copy1.Slot, copy1.Rad, copy1.StrtAngl);
LogReslot(reslotSuccess, 2, oldConditions, newConditions);
if (reslotSuccess)
{
newLeaf = copy1;
return true;
}
else //opt for minor adjustments over reslotting if possible
{
SpiralNode copy2 = new(copy1);
//ADJUST HERE
adjustSuccess = TryAdjust(ref copy2, prntNode, true);
newConditions = (copy2.Slot, copy2.Rad, copy2.StrtAngl);
if (!adjustSuccess) { copy2 = new SpiralNode(copy1); }
else
{
newLeaf = copy2;
return true;
}
}
}
}
return false;
}
public void LogReslot(bool startFits, int rsltCause,
(int slt, float rad, float angl) oldConditions,
(int slt, float rad, float angl) newConditions)
{
if (!Configs.LOG) { return; }
string lg = "";
int oldSlot = oldConditions.slt;
float oldRad = oldConditions.rad;
float oldAngle = oldConditions.angl;
int newSlot = newConditions.slt;
float newRad = newConditions.rad;
float newAngle = newConditions.angl;
if (rsltCause == 2) //TryToFit
{
lg += $"Having failed to resolve conflicts by adjusting leaf angle, trying to fix " +
$"problem(s) by changing leaf slot from {oldSlot} to {newSlot};\n";
if (startFits)
{
lg += $"reslot effort successful, producing leaf radius {newRad:F3} at (new) angle {newAngle:F3}\n";
}
else
{
lg += $"reslot effort failed";
if (newAngle != -100)
{
lg += $", producing leaf radius {newRad:F3} at (new) angle {newAngle:F3}";
}
lg += ".\n";
}
}
if (rsltCause == 3) //attempt to increase leafRad to sufficient size for growing
{
lg += $"Leaf radius {oldRad:F3} too small; changed leaf slot " +
$"from {oldSlot} to {newSlot} to get radius={newRad:F3} " +
$"(start angle also changed from {oldAngle:F3} to {newAngle:F3})\n";
}
AddToLog(lg);
}
public bool GrowLeaf(SpiralNode prntNode, int prntIdx, float leafRad, float startAngle, int leafSlot, bool noRslt = false)
{
//if leaves get progressively smaller and the current leaf is already too small, don't bother growing any
if (!Configs.BigEnoughToGrow(leafRad))
{
prntNode.Full = true;
return false;
}
float lift = prntNode.CalcNodeLift(leafRad, startAngle);
float leafCtrX = prntNode.Ctr.X + ((float)Math.Cos(startAngle) * (prntNode.Rad + leafRad + lift));
float leafCtrY = prntNode.Ctr.Y + ((float)Math.Sin(startAngle) * (prntNode.Rad + leafRad + lift));
SpiralNode newLeaf = new(prntIdx, prntNode.Clock, leafCtrX, leafCtrY,
leafRad, Trig.ComplementAngle(startAngle), leafSlot, lift);
//inherit parent's edge data
newLeaf.EdgeDists.AddRange(prntNode.EdgeDists);
newLeaf.EdgePoints.AddRange(prntNode.EdgePoints);
bool startFits = CheckFit(newLeaf);
if (!startFits) //result 1 - failed, retrying
{
LogLeaf(newLeaf, prntNode, 1, noRslt);
startFits = noRslt ? TryToFit(ref newLeaf, prntNode, true) : TryToFit(ref newLeaf, prntNode);
}
if (startFits && !Configs.RadTooSmall(newLeaf.Rad)) //result 2, worked - either immediately, or after retry
{
Nodes.Add(newLeaf);
int lastIdx = Nodes.Count - 1;
prntNode.MarkParent(newLeaf, lastIdx);
LogLeaf(newLeaf, prntNode, 2, noRslt);
return true;
}
else //result 3, failed after retry
{
LogLeaf(newLeaf, prntNode, 3, noRslt);
return false;
}
}
public void LogLeaf(SpiralNode newLeaf, SpiralNode prntNode, int result, bool resprouted = false)
{
if (!Configs.LOG) { return; }
string lfLog = "";
string mod = resprouted ? "resprouted " : "";
if (result == 1)
{
lfLog += $"\ngrowLeaf had a problem fitting {mod}leaf idx {Nodes.Count} (rad={newLeaf.Rad:F3}" +
$", slot={newLeaf.Slot}) at angle: {Trig.ComplementAngle(newLeaf.StrtAngl):F3} " +
$"on parent idx {newLeaf.PrntIdx}, (clock: {prntNode.Clock}, strtAngl: {prntNode.StrtAngl:F3})\n";
if (newLeaf.NhbrIdxs.Count > 0)
{
lfLog += "found neighbor conflicts:\n";
lfLog += newLeaf.PrintNodeNhbrData();
}
if (newLeaf.EdgeDists.Contains(0))
{
lfLog += "found edge conflicts: ";
lfLog += newLeaf.PrintNodeEdgeData(true);
}
}