forked from AngusJohnson/Clipper2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclipper.triangulation.cpp
More file actions
1219 lines (1082 loc) · 37.3 KB
/
clipper.triangulation.cpp
File metadata and controls
1219 lines (1082 loc) · 37.3 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
/*******************************************************************************
* Author : Angus Johnson *
* Date : 13 December 2025 *
* Release : BETA RELEASE *
* Website : https://www.angusj.com *
* Copyright : Angus Johnson 2010-2025 *
* Purpose : Constrained Delaunay Triangulation *
* License : https://www.boost.org/LICENSE_1_0.txt *
*******************************************************************************/
#include "clipper2/clipper.h"
#include "clipper2/clipper.triangulation.h"
namespace Clipper2Lib
{
enum class EdgeKind { loose, ascend, descend }; // ascend & descend are 'fixed' edges
enum class IntersectKind { none, collinear, intersect };
enum class EdgeContainsResult { neither, left, right };
//forward definitions
class Vertex2;
class Edge;
class Triangle;
typedef std::vector<Vertex2*> VertexList;
typedef std::vector<Edge*> EdgeList;
class Vertex2 {
public:
Point64 pt;
EdgeList edges;
bool innerLM = false;
Vertex2(const Point64& p64) : pt(p64) { edges.reserve(2); };
};
class Edge {
public:
Vertex2* vL = nullptr;
Vertex2* vR = nullptr;
Vertex2* vB = nullptr;
Vertex2* vT = nullptr;
EdgeKind kind = EdgeKind::loose;
Triangle* triA = nullptr;
Triangle* triB = nullptr;
bool isActive = false;
Edge* nextE = nullptr;
Edge* prevE = nullptr;
};
class Triangle {
public:
Edge* edges[3];
Triangle(Edge* e1, Edge* e2, Edge* e3)
{
edges[0] = e1;
edges[1] = e2;
edges[2] = e3;
}
};
/////////////////////////////////////////////////////////////////////////////
// Delaunay class declaration
/////////////////////////////////////////////////////////////////////////////
class Delaunay {
private:
VertexList allVertices;
EdgeList allEdges;
std::vector<Triangle*> allTriangles;
std::stack<Edge*> pendingDelaunayStack;
std::stack<Edge*> horzEdgeStack;
std::stack<Vertex2*> locMinStack;
bool useDelaunay = true;
Vertex2* lowermostVertex = nullptr;
Edge* firstActive = nullptr;
void AddPath(const Path64& path);
bool AddPaths(const Paths64& paths);
void CleanUp();
bool FixupEdgeIntersects();
void MergeDupOrCollinearVertices();
void SplitEdge(Edge* longE, Edge* shortE);
bool RemoveIntersection(Edge* e1, Edge* e2);
Edge* CreateEdge(Vertex2* v1, Vertex2* v2, EdgeKind k);
Triangle* CreateTriangle(Edge* e1, Edge* e2, Edge* e3);
Edge* CreateInnerLocMinLooseEdge(Vertex2* vAbove);
Edge* HorizontalBetween(Vertex2* v1, Vertex2* v2);
void DoTriangulateLeft(Edge* edge, Vertex2* pivot, int64_t minY);
void DoTriangulateRight(Edge* edge, Vertex2* pivot, int64_t minY);
void AddEdgeToActives(Edge* edge);
void RemoveEdgeFromActives(Edge* edge);
void ForceLegal(Edge* edge);
public:
explicit Delaunay(bool delaunay = true) : useDelaunay(delaunay) {};
~Delaunay() { CleanUp(); };
Paths64 Execute(const Paths64& paths, TriangulateResult& triResult);
};
/////////////////////////////////////////////////////////////////////////////
// Miscellaneous functions
/////////////////////////////////////////////////////////////////////////////
static bool VertexListSort(const Vertex2* a, const Vertex2* b)
{
return (a->pt.y == b->pt.y) ? (a->pt.x < b->pt.x) : (a->pt.y > b->pt.y);
}
static bool EdgeListSort(const Edge* a, const Edge* b)
{
return (a->vL->pt.x < b->vL->pt.x);
}
static bool IsLooseEdge(const Edge& e)
{
return e.kind == EdgeKind::loose;
}
static bool IsLeftEdge(const Edge& e)
{
// left edge (bound) of a fill region
// ie fills on the **right** side of the edge
// precondition - e is never a 'loose' edge
return e.kind == EdgeKind::ascend;
}
static bool IsRightEdge(const Edge& e)
{
// right edge (bound) of a fill region
// but still fills on the **right** side of the edge
// precondition - e is never a 'loose' edge
return e.kind == EdgeKind::descend;
}
static bool IsHorizontal(const Edge& e)
{
return e.vB->pt.y == e.vT->pt.y;
}
static bool LeftTurning(const Point64& p1, const Point64& p2, const Point64& p3)
{
return CrossProductSign(p1, p2, p3) < 0;
}
static bool RightTurning(const Point64& p1, const Point64& p2, const Point64& p3)
{
return CrossProductSign(p1, p2, p3) > 0;
}
static bool EdgeCompleted(Edge* edge)
{
if (!edge->triA) return false;
if (edge->triB) return true;
return edge->kind != EdgeKind::loose;
}
static EdgeContainsResult EdgeContains(const Edge* edge, const Vertex2* v)
{
if (edge->vL == v) return EdgeContainsResult::left;
else if (edge->vR == v) return EdgeContainsResult::right;
else return EdgeContainsResult::neither;
}
static double GetAngle(const Point64& a, const Point64& b, const Point64& c)
{
//https://stackoverflow.com/a/3487062/359538
double abx = static_cast<double>(b.x - a.x);
double aby = static_cast<double>(b.y - a.y);
double bcx = static_cast<double>(b.x - c.x);
double bcy = static_cast<double>(b.y - c.y);
double dp = (abx * bcx + aby * bcy);
double cp = (abx * bcy - aby * bcx);
return std::atan2(cp, dp); //range between -Pi and Pi
}
static double GetLocMinAngle(Vertex2* v)
{
// todo - recheck the result's sign compared to left vs right turning
// (currently assumes left turning => positive values)
// precondition - this function is called before processing locMin.
//Assert(v->edges.size() == 2);
int asc, des;
if (v->edges[0]->kind == EdgeKind::ascend)
{
asc = 0;
des = 1;
}
else
{
des = 0;
asc = 1;
}
// winding direction - descending to ascending
return GetAngle(v->edges[des]->vT->pt, v->pt, v->edges[asc]->vT->pt);
}
static void RemoveEdgeFromVertex(Vertex2* vert, Edge* edge)
{
auto it = std::find(vert->edges.begin(), vert->edges.end(), edge);
if (it == vert->edges.end()) throw "oops!";
vert->edges.erase(it);
}
static bool FindLocMinIdx(const Path64& path, size_t len, size_t& idx)
{
if (len < 3) return false;
size_t i0 = idx, n = (idx + 1) % len;
while (path[n].y <= path[idx].y)
{
idx = n; n = (n + 1) % len;
if (idx == i0) return false; // fails if the path is completely horizontal
}
while (path[n].y >= path[idx].y)
{
idx = n; n = (n + 1) % len;
}
return true;
}
static size_t Prev(size_t& idx, size_t len)
{
if (idx == 0) return len - 1; else return idx - 1;
}
static size_t Next(size_t& idx, size_t len)
{
return (idx + 1) % len;
}
static Edge* FindLinkingEdge(const Vertex2* vert1, const Vertex2* vert2, bool preferAscending)
{
Edge* res = nullptr;
for (auto e : vert1->edges)
{
if (e->vL == vert2 || e->vR == vert2)
{
if (e->kind == EdgeKind::loose ||
((e->kind == EdgeKind::ascend) == preferAscending)) return e;
res = e;
}
}
return res;
}
static Path64 PathFromTriangle(Triangle tri)
{
Path64 res;
res.reserve(3);
res.push_back(tri.edges[0]->vL->pt);
res.push_back(tri.edges[0]->vR->pt);
const Edge& e = *tri.edges[1];
if (e.vL->pt == res[0] || e.vL->pt == res[1])
res.push_back(e.vR->pt);
else
res.push_back(e.vL->pt);
return res;
}
static double InCircleTest(const Point64& ptA, const Point64& ptB,
const Point64& ptC, const Point64& ptD)
{
// Return the determinant value of 3 x 3 matrix ...
// | ax-dx ay-dy Sqr(ax-dx)+Sqr(ay-dy) |
// | bx-dx by-dy Sqr(bx-dx)+Sqr(by-dy) |
// | cx-dx cy-dy Sqr(cx-dx)+Sqr(cy-dy) |
// The *sign* of the return value is determined by
// the orientation (CW vs CCW) of ptA, ptB & ptC.
// precondition - ptA, ptB & ptC make a *non-empty* triangle
double m00 = static_cast<double>(ptA.x - ptD.x);
double m01 = static_cast<double>(ptA.y - ptD.y);
double m02 = (Sqr(m00) + Sqr(m01));
double m10 = static_cast<double>(ptB.x - ptD.x);
double m11 = static_cast<double>(ptB.y - ptD.y);
double m12 = (Sqr(m10) + Sqr(m11));
double m20 = static_cast<double>(ptC.x - ptD.x);
double m21 = static_cast<double>(ptC.y - ptD.y);
double m22 = (Sqr(m20) + Sqr(m21));
return m00 * (m11 * m22 - m21 * m12) -
m10 * (m01 * m22 - m21 * m02) +
m20 * (m01 * m12 - m11 * m02);
}
static double ShortestDistFromSegment(const Point64& pt, const Point64& segPt1, const Point64& segPt2)
{
// precondition: segPt1 <> segPt2
double dx = static_cast<double>(segPt2.x - segPt1.x);
double dy = static_cast<double>(segPt2.y - segPt1.y);
//Assert((dx < > 0) or (dy < > 0)); // ie segPt1 <> segPt2
double ax = static_cast<double>(pt.x - segPt1.x);
double ay = static_cast<double>(pt.y - segPt1.y);
//q = (ax * dx + ay * dy) / (dx * dx + dy * dy);
double qNum = ax * dx + ay * dy;
if (qNum < 0) // pt is closest to seq1
return DistanceSqr(pt, segPt1);
else if (qNum > (Sqr(dx) + Sqr(dy))) // pt is closest to seq2
return DistanceSqr(pt, segPt2);
else
return Sqr(ax * dy - dx * ay) / (dx * dx + dy * dy);
}
static IntersectKind SegsIntersect(const Point64 s1a, const Point64 s1b,
const Point64 s2a, const Point64 s2b)
{
double dy1 = static_cast<double>(s1b.y - s1a.y);
double dx1 = static_cast<double>(s1b.x - s1a.x);
double dy2 = static_cast<double>(s2b.y - s2a.y);
double dx2 = static_cast<double>(s2b.x - s2a.x);
double cp = dy1 * dx2 - dy2 * dx1;
if (cp == 0) return IntersectKind::collinear;
double t = (static_cast<double>(s1a.x - s2a.x) * dy2 -
static_cast<double>(s1a.y - s2a.y) * dx2);
//ignore segments that 'intersect' at an end-point
if (t == 0) return IntersectKind::none;
if (t > 0)
{
if (cp < 0 || t >= cp) return IntersectKind::none;
}
else
{
if (cp > 0 || t <= cp) return IntersectKind::none;
}
// so far, the *segment* 's1' intersects the *line* through 's2',
// but now make sure it also intersects the *segment* 's2'
t = ((s1a.x - s2a.x) * dy1 - (s1a.y - s2a.y) * dx1);
if (t == 0) return IntersectKind::none;
if (t > 0)
{
if (cp > 0 && t < cp) return IntersectKind::intersect;
}
else
{
if (cp < 0 && t > cp) return IntersectKind::intersect;
}
return IntersectKind::none;
}
/////////////////////////////////////////////////////////////////////////////
// Delaunay class definitions
/////////////////////////////////////////////////////////////////////////////
void Delaunay::CleanUp()
{
for (auto v : allVertices) delete v;
allVertices.resize(0);
for (auto e : allEdges) delete e;
allEdges.resize(0);
for (auto t : allTriangles) delete t;
allTriangles.resize(0);
firstActive = nullptr;
lowermostVertex = nullptr;
}
void Delaunay::ForceLegal(Edge* edge)
{
// don't try to make empty triangles legal
if (!edge->triA || !edge->triB) return;
// vertA will be assigned the vertex in edge's triangleA
// that is NOT an end vertex of edge
// Likewise, vertB will be assigned the vertex in edge's
// triangleB that is NOT an end vertex of edge
// If edge is rotated, vertA & vertB will become its end vertices.
Vertex2* vertA = nullptr;
Vertex2* vertB = nullptr;
// Excluding 'edge', edgesA will contain two edges (one from
// triangleA and one from triangleB) that touch edge.vL.
// And edgesB will contain the two edges that touch edge.vR.
Edge* edgesA[3] = { nullptr, nullptr, nullptr };
Edge* edgesB[3] = { nullptr, nullptr, nullptr };
for (int i = 0; i < 3; ++i)
{
if (edge->triA->edges[i] == edge) continue;
switch (EdgeContains(edge->triA->edges[i], edge->vL))
{
case EdgeContainsResult::left:
edgesA[1] = edge->triA->edges[i];
vertA = edge->triA->edges[i]->vR;
break;
case EdgeContainsResult::right:
edgesA[1] = edge->triA->edges[i];
vertA = edge->triA->edges[i]->vL;
break;
default:
edgesB[1] = edge->triA->edges[i];
}
}
for (int i = 0; i < 3; ++i)
{
if (edge->triB->edges[i] == edge) continue;
switch (EdgeContains(edge->triB->edges[i], edge->vL))
{
case EdgeContainsResult::left:
edgesA[2] = edge->triB->edges[i];
vertB = edge->triB->edges[i]->vR;
break;
case EdgeContainsResult::right:
edgesA[2] = edge->triB->edges[i];
vertB = edge->triB->edges[i]->vL;
break;
default:
edgesB[2] = edge->triB->edges[i];
}
}
// InCircleTest reqires edge.triangleA to be a valid triangle
// if IsEmptyTriangle(edge.triangleA) then Exit; // slower
if (CrossProductSign(vertA->pt, edge->vL->pt, edge->vR->pt) == 0) return;
// ictResult - result sign is dependant on triangleA's orientation
double ictResult = InCircleTest(vertA->pt, edge->vL->pt, edge->vR->pt, vertB->pt);
if (ictResult == 0 || // if on or out of circle then exit
(RightTurning(vertA->pt, edge->vL->pt, edge->vR->pt) == (ictResult < 0))) return;
// TRIANGLES HERE ARE **NOT** DELAUNAY COMPLIANT, SO MAKE THEM SO.
// NOTE: ONCE WE BEGIN DELAUNAY COMPLIANCE, vL & vR WILL
// NO LONGER REPRESENT LEFT AND RIGHT VERTEX ORIENTATION.
// THIS IS MINOR PERFORMANCE EFFICIENCY IS SAFE AS LONG AS
// THE TRIANGULATE() METHOD IS CALLED ONCE ONLY ON A GIVEN
// SET OF PATHS
edge->vL = vertA;
edge->vR = vertB;
edge->triA->edges[0] = edge;
for (int i = 1; i < 3; ++i)
{
edge->triA->edges[i] = edgesA[i];
if (!edgesA[i]) throw "oops"; // stops compiler warnings
if (IsLooseEdge(*edgesA[i]))
pendingDelaunayStack.push(edgesA[i]);
// since each edge has its own triangleA and triangleB, we have to be careful
// to update the correct one ...
if (edgesA[i]->triA == edge->triA || edgesA[i]->triB == edge->triA) continue;
if (edgesA[i]->triA == edge->triB)
edgesA[i]->triA = edge->triA;
else if (edgesA[i]->triB == edge->triB)
edgesA[i]->triB = edge->triA;
else throw "oops";
}
edge->triB->edges[0] = edge;
for (int i = 1; i < 3; ++i)
{
edge->triB->edges[i] = edgesB[i];
if (!edgesB[i]) throw "oops"; // stops compiler warnings
if (IsLooseEdge(*edgesB[i]))
pendingDelaunayStack.push(edgesB[i]);
// since each edge has its own triangleA and triangleB, we have to be careful
// to update the correct one ...
if (edgesB[i]->triA == edge->triB || edgesB[i]->triB == edge->triB) continue;
if (edgesB[i]->triA == edge->triA)
edgesB[i]->triA = edge->triB;
else if (edgesB[i]->triB == edge->triA)
edgesB[i]->triB = edge->triB;
else throw "oops";
}
}
Edge* Delaunay::CreateEdge(Vertex2* v1, Vertex2* v2, EdgeKind k)
{
Edge* res = allEdges.emplace_back(new Edge());
if (v1->pt.y == v2->pt.y)
{
res->vB = v1; res->vT = v2;
}
else if (v1->pt.y < v2->pt.y)
{
res->vB = v2; res->vT = v1;
}
else
{
res->vB = v1; res->vT = v2;
}
if (v1->pt.x <= v2->pt.x)
{
res->vL = v1; res->vR = v2;
}
else
{
res->vL = v2; res->vR = v1;
}
res->kind = k;
v1->edges.push_back(res);
v2->edges.push_back(res);
if (k == EdgeKind::loose)
{
pendingDelaunayStack.push(res);
AddEdgeToActives(res);
}
return res;
}
Triangle* Delaunay::CreateTriangle(Edge* e1, Edge* e2, Edge* e3)
{
Triangle* res = allTriangles.emplace_back(new Triangle(e1, e2, e3));
// nb: only expire loose edges when both sides of these edges have triangles.
for (int i = 0; i < 3; ++i)
if (res->edges[i]->triA)
{
res->edges[i]->triB = res;
// this is the edge's second triangle hence no longer active
RemoveEdgeFromActives(res->edges[i]);
}
else
{
res->edges[i]->triA = res;
// this is the edge's first triangle, so only remove
// this edge from actives if it's a fixed edge.
if (!IsLooseEdge(*res->edges[i]))
RemoveEdgeFromActives(res->edges[i]);
}
return res;
}
bool Delaunay::RemoveIntersection(Edge* e1, Edge* e2)
{
// find which vertex is closest to the other segment
// (ie not the vertex closest to the intersection point) ...
Vertex2* v = e1->vL;
Edge* tmpE = e2;
double d = ShortestDistFromSegment(e1->vL->pt, e2->vL->pt, e2->vR->pt);
double d2 = ShortestDistFromSegment(e1->vR->pt, e2->vL->pt, e2->vR->pt);
if (d2 < d) { d = d2; v = e1->vR; }
d2 = ShortestDistFromSegment(e2->vL->pt, e1->vL->pt, e1->vR->pt);
if (d2 < d) { d = d2; tmpE = e1; v = e2->vL; }
d2 = ShortestDistFromSegment(e2->vR->pt, e1->vL->pt, e1->vR->pt);
if (d2 < d) { d = d2; tmpE = e1; v = e2->vR; }
if (d > 1.000)
return false; // Oops - this is not just a simple 'rounding' intersection
// split 'tmpE' into 2 edges at 'v'
Vertex2* v2 = tmpE->vT;
RemoveEdgeFromVertex(v2, tmpE);
// replace v2 in tmpE with v
if (tmpE->vL == v2) tmpE->vL = v;
else tmpE->vR = v;
tmpE->vT = v;
v->edges.push_back(tmpE);
v->innerLM = false; // #47
// left turning is angle positive
if (tmpE->vB->innerLM && GetLocMinAngle(tmpE->vB) <= 0)
tmpE->vB->innerLM = false; // #44, 52
// finally create a new edge between v and v2 ...
CreateEdge(v, v2, tmpE->kind);
return true;
}
bool Delaunay::FixupEdgeIntersects()
{
// precondition - edgeList must be sorted - ascending on edge.vL.pt.x
for (size_t i1 = 0; i1 < allEdges.size(); ++i1)
{
Edge* e1 = allEdges[i1];
// nb: we can safely ignore edges newly created inside this for loop
for (size_t i2 = i1 + 1; i2 < allEdges.size(); ++i2)
{
Edge* e2 = allEdges[i2];
if (e2->vL->pt.x >= e1->vR->pt.x)
break; // all 'e' from now on are too far right
// 'e2' is inside e1's horizontal region. If 'e2' is also inside
// e1's vertical region, only then check for an intersection ...
if (e2->vT->pt.y < e1->vB->pt.y && e2->vB->pt.y > e1->vT->pt.y &&
(SegsIntersect(e2->vL->pt, e2->vR->pt,
e1->vL->pt, e1->vR->pt) == IntersectKind::intersect))
{
if (!RemoveIntersection(e2, e1))
return false; // oops!!
}
// nb: collinear edges are managed in MergeDupOrCollinearVertices below
}
}
return true;
}
void Delaunay::SplitEdge(Edge* longE, Edge* shortE)
{
auto oldT = longE->vT, newT = shortE->vT;
// remove longEdge from longEdge.vT.edges
RemoveEdgeFromVertex(oldT, longE);
// shorten longEdge
longE->vT = newT;
if (longE->vL == oldT) longE->vL = newT;
else longE->vR = newT;
// add shortened longEdge to newT.edges
newT->edges.push_back(longE);
// and create a new edge betweem newV, oldT
CreateEdge(newT, oldT, longE->kind);
}
void Delaunay::MergeDupOrCollinearVertices()
{
// note: this procedure may add new edges and change the
// number of edges connected with a given vertex, but it
// won't add or delete vertices (so it's safe to use iterators)
auto vIter1 = allVertices.begin();
for (auto vIter2 = allVertices.begin() + 1; vIter2 != allVertices.end(); ++vIter2)
{
if ((*vIter1)->pt != (*vIter2)->pt)
{
vIter1 = vIter2;
continue;
}
// merge v1 & v2
Vertex2* v1 = *vIter1, * v2 = *vIter2;
if (!v1->innerLM || !v2->innerLM)
v1->innerLM = false;
// in all of v2's edges, replace links to v2 with links to v1
for (auto e : v2->edges)
{
if (e->vB == v2) e->vB = v1;
else e->vT = v1;
if (e->vL == v2) e->vL = v1;
else e->vR = v1;
}
// move all of v2's edges to v1
std::copy(v2->edges.begin(), v2->edges.end(), back_inserter(v1->edges));
v2->edges.resize(0);
// excluding horizontals, if pv.edges contains two edges
// that are *collinear* and share the same bottom coords
// but have different lengths, split the longer edge at
// the top of the shorter edge ...
for (auto itE = v1->edges.begin(); itE != v1->edges.end(); ++itE)
{
if (IsHorizontal(*(*itE)) || (*itE)->vB != v1) continue;
for (auto itE2 = itE + 1; itE2 != v1->edges.end(); ++itE2)
{
auto e1 = *itE, e2 = *itE2;
if (e2->vB != v1 || e1->vT->pt.y == e2->vT->pt.y ||
(CrossProductSign(e1->vT->pt, v1->pt, e2->vT->pt) != 0)) continue;
// we have parallel edges, both heading up from v1.pt.
// split the longer edge at the top of the shorter edge.
if (e1->vT->pt.y < e2->vT->pt.y) SplitEdge(e1, e2);
else SplitEdge(e2, e1);
break; // because only two edges can be collinear
}
}
}
}
Edge* Delaunay::CreateInnerLocMinLooseEdge(Vertex2* vAbove)
{
if (!firstActive) return nullptr; // oops!!
int64_t xAbove = vAbove->pt.x;
int64_t yAbove = vAbove->pt.y;
// find the closest 'active' edge with a vertex that's not above vAbove
Edge* e = firstActive, *eBelow = nullptr;
double bestD = -1.0;
while (e)
{
if (e->vL->pt.x <= xAbove && e->vR->pt.x >= xAbove &&
e->vB->pt.y >= yAbove && e->vB != vAbove && e->vT != vAbove &&
!LeftTurning(e->vL->pt, vAbove->pt, e->vR->pt))
{
double d = ShortestDistFromSegment(vAbove->pt, e->vL->pt, e->vR->pt);
if (!eBelow || d < bestD) // compare e with eBelow
{
eBelow = e;
bestD = d;
}
}
e = e->nextE;
}
if (!eBelow) return nullptr; // oops!!
// get the best vertex from 'eBelow'
Vertex2* vBest = (eBelow->vT->pt.y <= yAbove) ? eBelow->vB : eBelow->vT;
int64_t xBest = vBest->pt.x;
int64_t yBest = vBest->pt.y;
// make sure no edges intersect 'vAbove' and 'vBest' ...
// todo: fActives is currently *unsorted* but consider making it
// a tree structure based on each edge's left and right bounds
e = firstActive;
if (xBest < xAbove)
{
while (e)
{
if (e->vR->pt.x > xBest && e->vL->pt.x < xAbove &&
e->vB->pt.y > yAbove && e->vT->pt.y < yBest &&
(SegsIntersect(e->vB->pt, e->vT->pt,
vBest->pt, vAbove->pt) == IntersectKind::intersect))
{
vBest = (e->vT->pt.y > yAbove) ? e->vT : e->vB;
xBest = vBest->pt.x;
yBest = vBest->pt.y;
}
e = e->nextE;
}
}
else
{
while (e)
{
if (e->vR->pt.x < xBest && e->vL->pt.x > xAbove &&
e->vB->pt.y > yAbove && e->vT->pt.y < yBest &&
(SegsIntersect(e->vB->pt, e->vT->pt,
vBest->pt, vAbove->pt) == IntersectKind::intersect))
{
vBest = e->vT->pt.y > yAbove ? e->vT : e->vB;
xBest = vBest->pt.x;
yBest = vBest->pt.y;
}
e = e->nextE;
}
}
return CreateEdge(vBest, vAbove, EdgeKind::loose);
}
Edge* Delaunay::HorizontalBetween(Vertex2* v1, Vertex2* v2)
{
int64_t y = v1->pt.y, l, r;
if (v1->pt.x > v2->pt.x)
{
l = v2->pt.x;
r = v1->pt.x;
}
else
{
l = v1->pt.x;
r = v2->pt.x;
}
Edge* res = firstActive;
while (res)
{
if (res->vL->pt.y == y && res->vR->pt.y == y &&
res->vL->pt.x >= l && res->vR->pt.x <= r &&
(res->vL->pt.x != l || res->vL->pt.x != r)) break;
res = res->nextE;
}
return res;
}
void Delaunay::DoTriangulateLeft(Edge* edge, Vertex2* pivot, int64_t minY)
{
// precondition - pivot must be one end of edge (Usually .vB)
//Assert(!EdgeCompleted(edge));
Vertex2* vAlt = nullptr;
Edge* eAlt = nullptr;
Vertex2* v = (edge->vB == pivot) ? edge->vT : edge->vB;
for (auto e : pivot->edges)
{
if (e == edge || !e->isActive) continue;
Vertex2* vX = e->vT == pivot ? e->vB : e->vT;
if (vX == v) continue;
int cps = CrossProductSign(v->pt, pivot->pt, vX->pt);
if (cps == 0) //collinear paths
{
// if pivot is between v and vX then continue;
// nb: this is important for both horiz and non-horiz collinear
if ((v->pt.x > pivot->pt.x) == (pivot->pt.x > vX->pt.x)) continue;
}
// else if right-turning or not the best edge, then continue
else if (cps > 0 || (vAlt && !LeftTurning(vX->pt, pivot->pt, vAlt->pt)))
continue;
vAlt = vX;
eAlt = e;
}
if (!vAlt || vAlt->pt.y < minY) return;
// Don't triangulate **across** fixed edges
if (vAlt->pt.y < pivot->pt.y)
{
if (IsLeftEdge(*eAlt)) return;
}
else if (vAlt->pt.y > pivot->pt.y)
{
if (IsRightEdge(*eAlt)) return;
}
Edge* eX = FindLinkingEdge(vAlt, v, (vAlt->pt.y < v->pt.y));
if (!eX)
{
// be very careful creating loose horizontals at minY
if (vAlt->pt.y == v->pt.y && v->pt.y == minY &&
HorizontalBetween(vAlt, v)) return;
eX = CreateEdge(vAlt, v, EdgeKind::loose);
}
CreateTriangle(edge, eAlt, eX);
if (!EdgeCompleted(eX))
DoTriangulateLeft(eX, vAlt, minY);
}
void Delaunay::DoTriangulateRight(Edge* edge, Vertex2* pivot, int64_t minY)
{
// precondition - pivot must be one end of edge (Usually .vB)
//Assert(!EdgeCompleted(edge));
Vertex2* vAlt = nullptr;
Edge* eAlt = nullptr;
Vertex2* v = (edge->vB == pivot) ? edge->vT : edge->vB;
for (auto e : pivot->edges)
{
if (e == edge || !e->isActive) continue;
Vertex2* vX = e->vT == pivot ? e->vB : e->vT;
if (vX == v) continue;
int cps = CrossProductSign(v->pt, pivot->pt, vX->pt);
if (cps == 0) //collinear paths
{
// if pivot is between v and vX then continue;
// nb: this is important for both horiz and non-horiz collinear
if ((v->pt.x > pivot->pt.x) == (pivot->pt.x > vX->pt.x)) continue;
}
// else if right-turning or not the best edge, then continue
else if (cps < 0 || (vAlt && !RightTurning(vX->pt, pivot->pt, vAlt->pt)))
continue;
vAlt = vX;
eAlt = e;
}
if (!vAlt || vAlt->pt.y < minY) return;
// Don't triangulate **across** fixed edges
if (vAlt->pt.y < pivot->pt.y)
{
if (IsRightEdge(*eAlt)) return;
}
else if (vAlt->pt.y > pivot->pt.y)
{
if (IsLeftEdge(*eAlt)) return;
}
Edge* eX = FindLinkingEdge(vAlt, v, (vAlt->pt.y > v->pt.y));
if (!eX)
{
// be very careful creating loose horizontals at minY
if (vAlt->pt.y == v->pt.y && v->pt.y == minY &&
HorizontalBetween(vAlt, v)) return;
eX = CreateEdge(vAlt, v, EdgeKind::loose);
}
CreateTriangle(edge, eX, eAlt);
if (!EdgeCompleted(eX))
DoTriangulateRight(eX, vAlt, minY);
}
void Delaunay::AddEdgeToActives(Edge* edge)
{
// nb: on occassions this method can get called twice for a given edge
// This is because, in the Triangulate() method where vertex 'edges'
// arrays are being parsed, edges can can be removed from the array
// which changes the index of following edges.
if (edge->isActive) return;
edge->prevE = nullptr;
edge->nextE = firstActive;
edge->isActive = true;
if (firstActive)
firstActive->prevE = edge;
firstActive = edge;
}
void Delaunay::RemoveEdgeFromActives(Edge* edge)
{
// first, remove the edge from its vertices
RemoveEdgeFromVertex(edge->vB, edge);
RemoveEdgeFromVertex(edge->vT, edge);
// now remove the edge from double linked list (AEL)
Edge* prev = edge->prevE;
Edge* next = edge->nextE;
if (next) next->prevE = prev;
if (prev) prev->nextE = next;
edge->isActive = false;
if (firstActive == edge) firstActive = next;
}
Paths64 Delaunay::Execute(const Paths64& paths, TriangulateResult& triResult)
{
if (!AddPaths(paths))
{
triResult = TriangulateResult::no_polygons;
return Paths64(); // oops!
}
// if necessary fix path orientation because the algorithm
// expects clockwise outer paths and counter-clockwise inner paths
if (lowermostVertex->innerLM)
{
// the orientation of added paths must be wrong, so
// 1. reverse innerLM flags ...
Vertex2* lm;
while (!locMinStack.empty())
{
lm = locMinStack.top();
lm->innerLM = !lm->innerLM;
locMinStack.pop();
}
// 2. swap edge kinds
for (Edge* e : allEdges)
if (e->kind == EdgeKind::ascend)
e->kind = EdgeKind::descend;
else
e->kind = EdgeKind::ascend;
}
else
{
// path orientation is fine so ...
while (!locMinStack.empty())
locMinStack.pop();
}
std::sort(allEdges.begin(), allEdges.end(), EdgeListSort);
if (!FixupEdgeIntersects())
{
CleanUp();
triResult = TriangulateResult::paths_intersect;
return Paths64(); // oops!
}
std::sort(allVertices.begin(), allVertices.end(), VertexListSort);
MergeDupOrCollinearVertices();
int64_t currY = allVertices[0]->pt.y;
for (auto vIt = allVertices.begin(); vIt != allVertices.end(); ++vIt)
{
Vertex2* v = *vIt;
if (v->edges.empty()) continue;
if (v->pt.y != currY)
{
// JOIN AN INNER LOCMIN WITH A SUITABLE EDGE BELOW
while (!locMinStack.empty())
{
Vertex2* lm = locMinStack.top();
locMinStack.pop();
Edge* e = CreateInnerLocMinLooseEdge(lm);
if (!e)
{
CleanUp();
triResult = TriangulateResult::fail;
return Paths64(); // oops!
}
if (IsHorizontal(*e))
{
if (e->vL == e->vB)
DoTriangulateLeft(e, e->vB, currY); else
DoTriangulateRight(e, e->vB, currY);
}
else
{
DoTriangulateLeft(e, e->vB, currY);
if (!EdgeCompleted(e))
DoTriangulateRight(e, e->vB, currY);
}
// and because adding locMin edges to Actives was delayed ..
AddEdgeToActives(lm->edges[0]);
AddEdgeToActives(lm->edges[1]);
}
while (!horzEdgeStack.empty())
{
Edge* e = horzEdgeStack.top();
horzEdgeStack.pop();
if (EdgeCompleted(e)) continue;
if (e->vB == e->vL) // #45
{
if (IsLeftEdge(*e))
DoTriangulateLeft(e, e->vB, currY);
}
else
if (IsRightEdge(*e))
DoTriangulateRight(e, e->vB, currY);
}
currY = v->pt.y;
}
for (int i = static_cast<int>(v->edges.size()) - 1; i >= 0; --i)