-
Notifications
You must be signed in to change notification settings - Fork 183
Expand file tree
/
Copy pathflip_geodesics.cpp
More file actions
1858 lines (1472 loc) · 58.5 KB
/
flip_geodesics.cpp
File metadata and controls
1858 lines (1472 loc) · 58.5 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 "geometrycentral/surface/flip_geodesics.h"
#include "geometrycentral/surface/mesh_graph_algorithms.h"
#include "happly.h"
namespace geometrycentral {
namespace surface {
FlipEdgePath::FlipEdgePath(FlipEdgeNetwork& network_, std::vector<Halfedge> halfedges_, bool isClosed_)
: network(network_), isClosed(isClosed_) {
if (halfedges_.empty()) {
throw std::runtime_error("tried to create path from empty halfege list");
}
// Populate the list
SegmentID loopPrevID = INVALID_IND;
SegmentID firstID = INVALID_IND;
for (Halfedge newHe : halfedges_) {
// Get a new ID and entry
SegmentID newHeID = network.getNextUniquePathSegmentInd();
std::tuple<Halfedge, SegmentID, SegmentID> newEntry{newHe, loopPrevID, INVALID_IND};
pathHeInfo[newHeID] = newEntry;
// Try layering this path along the outside of the edge, on the side of the halfedge. Note that this MIGHT NOT be
// the right thing to do, but we cannot distinguish more complicated cases without adding more info to the
// constructor. Use other construction strategies to encode paths with interesting coincidence.
network.pushOutsideSegment(newHe, {this, newHeID});
// Track first
if (firstID == INVALID_IND) {
firstID = newHeID;
}
// Set the new ID as next on the previous entry
if (loopPrevID != INVALID_IND) {
std::get<2>(pathHeInfo[loopPrevID]) = newHeID;
}
// Add to the queue of wedge angles
network.addToWedgeAngleQueue({this, newHeID});
loopPrevID = newHeID;
}
SegmentID lastID = loopPrevID;
// Gather info about start and end of path
Halfedge firstHe = halfedges_.front();
Vertex firstVert = firstHe.vertex();
Halfedge lastHe = halfedges_.back();
Vertex lastVert = lastHe.twin().vertex();
if (isClosed) {
// Sanity check that input actually connects
if (lastHe.twin().vertex() != firstVert) {
throw std::runtime_error("tried to construct closed path, but input halfedges do not form a loop");
}
// Connect the back to the front
std::get<1>(pathHeInfo[firstID]) = lastID;
std::get<2>(pathHeInfo[lastID]) = firstID;
} else {
// Set marked vertex flags for endpoints
network.isMarkedVertex[firstVert] = true;
network.isMarkedVertex[lastVert] = true;
}
}
void FlipEdgePath::replacePathSegment(SegmentID nextID, SegmentAngleType angleType,
const std::vector<Halfedge>& newHalfedges) {
// We use the following halfedge names in order (note that some may be INVALID_IND)
// PrevPrev -> Prev -> Next -> NextNext
// ^^^^^^^^^^^^^^^^^
// straightening here
// Get the prev and nextnext info
Halfedge heNext, hePrev;
SegmentID prevID, nextNextID, prevPrevID, UNUSED;
std::tie(heNext, prevID, nextNextID) = pathHeInfo[nextID];
size_t sizeBefore = pathHeInfo.size();
if (prevID == INVALID_IND) {
throw std::runtime_error("tried to to replace segment with next as first halfedge in list");
}
// Get the prevprev info
std::tie(hePrev, prevPrevID, UNUSED) = pathHeInfo[prevID];
// == Part 1: remove the old edges from all structures
// Remove from the segment stacks on the edge (note that they MUST be on the outside or this whole method invalid)
if (angleType == SegmentAngleType::LeftTurn) {
network.popOutsideSegment(hePrev);
network.popOutsideSegment(heNext);
} else /* RightTurn */ {
network.popOutsideSegment(hePrev.twin());
network.popOutsideSegment(heNext.twin());
}
// Remove from this list
pathHeInfo.erase(prevID);
pathHeInfo.erase(nextID);
// These handle deletion when the path is a length-2 loop to start
bool replacedLength2Loop = false;
if (prevPrevID == nextID) {
replacedLength2Loop = true;
prevPrevID = INVALID_IND;
nextNextID = INVALID_IND;
}
// == Part 2: add the new edges to all structures
SegmentID loopPrevID = prevPrevID;
SegmentID firstAddedID = INVALID_IND;
for (Halfedge newHe : newHalfedges) {
// Get a new ID and entry
SegmentID newHeID = network.getNextUniquePathSegmentInd();
std::tuple<Halfedge, SegmentID, SegmentID> newEntry{newHe, loopPrevID, INVALID_IND};
pathHeInfo[newHeID] = newEntry;
// Add to edge stack
if (angleType == SegmentAngleType::LeftTurn) {
network.pushOutsideSegment(newHe.twin(), {this, newHeID});
} else /* RightTurn */ {
network.pushOutsideSegment(newHe, {this, newHeID});
}
// Set the new ID as next on the previous entry
if (loopPrevID != INVALID_IND) {
auto tupBefore = pathHeInfo[loopPrevID];
std::get<2>(pathHeInfo[loopPrevID]) = newHeID;
auto tupAfter = pathHeInfo[loopPrevID];
}
// add any new wedge angles to the list
network.addToWedgeAngleQueue({this, newHeID});
if (firstAddedID == INVALID_IND) {
firstAddedID = newHeID;
}
loopPrevID = newHeID;
}
// Set the pointers to/from the nextnext segment
if (loopPrevID != INVALID_IND) {
std::get<2>(pathHeInfo[loopPrevID]) = nextNextID;
}
if (nextNextID != INVALID_IND) {
std::get<1>(pathHeInfo[nextNextID]) = loopPrevID; // need to set prev ptr!
// probably changed the angle incoming to the next halfedge
network.addToWedgeAngleQueue({this, nextNextID});
}
// Connect the new front to new back
if (replacedLength2Loop) {
SegmentID lastAddedID = loopPrevID;
std::get<1>(pathHeInfo[firstAddedID]) = lastAddedID;
std::get<2>(pathHeInfo[lastAddedID]) = firstAddedID;
network.addToWedgeAngleQueue({this, firstAddedID});
}
// Reconsider any outside segments that share the edge, as they may have become unblocked by this move
if (angleType == SegmentAngleType::LeftTurn) {
network.addToWedgeAngleQueue(network.getOutsideSegment(heNext)); // auto-exits if null
network.addToWedgeAngleQueue(network.getOutsideSegment(hePrev));
} else /* RightTurn */ {
network.addToWedgeAngleQueue(network.getOutsideSegment(heNext.twin()));
network.addToWedgeAngleQueue(network.getOutsideSegment(hePrev.twin()));
}
}
size_t FlipEdgePath::size() { return pathHeInfo.size(); }
std::vector<Halfedge> FlipEdgePath::getHalfedgeList() {
// Find the last halfedge with `next` == INVALID_IND, if one exists
SegmentID lastID;
for (auto it : pathHeInfo) {
// Gather values
SegmentID currID = it.first;
SegmentID prevID, nextID;
Halfedge currHe;
std::tie(currHe, prevID, nextID) = it.second;
lastID = currID;
if (nextID == INVALID_IND) {
// since we break after setting, will be left with lastID == currID
break;
}
}
// Walk backwards along path to reconstruct
std::vector<Halfedge> result;
SegmentID walkID = lastID;
SegmentID firstID = walkID; // used to exit if a loop
while (walkID != INVALID_IND) {
SegmentID prevID, nextID;
Halfedge currHe;
std::tie(currHe, prevID, nextID) = pathHeInfo[walkID];
result.push_back(currHe);
walkID = prevID;
if (walkID == firstID) break; // test at end so we don't insta-out
}
std::reverse(result.begin(), result.end()); // flip to have expected direction
return result;
}
FlipEdgeNetwork::FlipEdgeNetwork(ManifoldSurfaceMesh& mesh_, IntrinsicGeometryInterface& inputGeom,
const std::vector<std::vector<Halfedge>>& hePaths, VertexData<bool> extraMarkedVerts)
: tri(std::unique_ptr<SignpostIntrinsicTriangulation>(new SignpostIntrinsicTriangulation(mesh_, inputGeom))),
mesh(*(tri->intrinsicMesh)), pathsAtEdge(mesh), isMarkedVertex(mesh, false) {
// Build initial paths from the vectors of edges (path constructor updates other structures of this class)
for (const std::vector<Halfedge>& hePath : hePaths) {
// Assumes that path is closed if it ends where it starts
// (this might be a problem as the default one day, but for now it is overwhelmingly likely to be what we want
Halfedge firstHe = hePath.front();
Halfedge lastHe = hePath.back();
bool isClosed = firstHe.vertex() == lastHe.twin().vertex();
// Convert to the corresponding intrinsic halfedges
std::vector<Halfedge> intPath(hePath.size());
for (size_t i = 0; i < hePath.size(); i++) {
intPath[i] = mesh.halfedge(hePath[i].getIndex());
}
paths.emplace_back(new FlipEdgePath(*this, intPath, isClosed));
}
// Mark any additional verts
if (extraMarkedVerts.size() > 0) {
for (Vertex v : mesh.vertices()) {
if (extraMarkedVerts[v.getIndex()]) {
isMarkedVertex[v] = true;
}
}
}
// Make sure everything is good to go
validate();
}
void FlipEdgeNetwork::addPath(const std::vector<Halfedge>& hePath) {
// Assumes that path is closed if it ends where it starts
// (this might be a problem as the default one day, but for now it is overwhelmingly likely to be what we want
Halfedge firstHe = hePath.front();
Halfedge lastHe = hePath.back();
bool isClosed = firstHe.vertex() == lastHe.twin().vertex();
paths.emplace_back(new FlipEdgePath(*this, hePath, isClosed));
}
std::unique_ptr<FlipEdgeNetwork> FlipEdgeNetwork::constructFromDijkstraPath(ManifoldSurfaceMesh& mesh_,
IntrinsicGeometryInterface& geom,
Vertex startVert, Vertex endVert) {
// Get the Dijkstra path
std::vector<Halfedge> dijkstraPath = shortestEdgePath(geom, startVert, endVert);
if (dijkstraPath.empty()) {
// Not connected, or same vertex
return std::unique_ptr<FlipEdgeNetwork>();
}
return std::unique_ptr<FlipEdgeNetwork>(new FlipEdgeNetwork(mesh_, geom, {dijkstraPath}));
}
std::unique_ptr<FlipEdgeNetwork> FlipEdgeNetwork::constructFromPiecewiseDijkstraPath(ManifoldSurfaceMesh& mesh_,
IntrinsicGeometryInterface& geom,
std::vector<Vertex> points,
bool closed, bool markInterior, bool removeOverlap) {
std::vector<Halfedge> halfedges;
VertexData<bool> extraMark(geom.mesh, false);
size_t end = closed ? points.size() : points.size() - 1;
for (size_t i = 0; i < end; i++) {
Vertex vA = points[i];
Vertex vB = points[(i + 1) % points.size()];
std::vector<Halfedge> dijkstraPath = shortestEdgePath(geom, vA, vB);
if (markInterior) {
extraMark[vA] = true;
extraMark[vB] = true;
}
if (dijkstraPath.empty()) {
// Not connected, or same vertex
return std::unique_ptr<FlipEdgeNetwork>();
}
halfedges.insert(halfedges.end(), dijkstraPath.begin(), dijkstraPath.end());
}
if(!removeOverlap || halfedges.size() == 0) {
return std::unique_ptr<FlipEdgeNetwork>(new FlipEdgeNetwork(mesh_, geom, {halfedges}, extraMark));
}
// 2 Adjacent Dijkstra paths may share edge(s)
// This creates a 'back-and-forth' that FlipOut cannot solve
std::vector<Halfedge> heClean;
Halfedge hePrev, heNext;
size_t i, behind;
behind = 1;
heClean.push_back(halfedges[0]);
for(i = 1; i < halfedges.size(); i++) {
hePrev = halfedges[i - behind];
heNext = halfedges[i];
heClean.push_back(halfedges[i]);
if(hePrev.edge() == heNext.twin().edge()) {
/* Backtrack in case >2 edges overlap */
behind = (behind >= i) ? 1 : behind + 2;
heClean.pop_back();
heClean.pop_back();
} else {
behind = 1;
}
}
return std::unique_ptr<FlipEdgeNetwork>(new FlipEdgeNetwork(mesh_, geom, {heClean}, extraMark));
}
std::unique_ptr<FlipEdgeNetwork> FlipEdgeNetwork::constructFromEdgeSet(ManifoldSurfaceMesh& mesh_,
IntrinsicGeometryInterface& geom,
const EdgeData<bool>& inPath,
const VertexData<bool>& extraMarkedVertices) {
ManifoldSurfaceMesh& mesh = mesh_;
std::vector<std::vector<Halfedge>> allHalfedges;
// Endpoint vertices will be those with != 2 incident path edges
VertexData<int> endpointCount(mesh, 0);
for (Edge e : mesh.edges()) {
if (inPath[e]) {
endpointCount[e.halfedge().vertex()]++;
endpointCount[e.halfedge().twin().vertex()]++;
}
}
VertexData<bool> isEndpoint(mesh, false);
for (Vertex v : mesh.vertices()) {
if (extraMarkedVertices[v] || (endpointCount[v] != 0 && endpointCount[v] != 2)) {
isEndpoint[v] = true;
}
}
// Walk paths between the endpoints
EdgeData<bool> walked(mesh, false);
for (Halfedge heStart : mesh.halfedges()) {
// Check if we should start a walk
if (!inPath[heStart.edge()] || walked[heStart.edge()] || !isEndpoint[heStart.vertex()]) continue;
// Start a new path
allHalfedges.emplace_back();
std::vector<Halfedge>& newPath = allHalfedges.back();
// Walk along the path until we reach an endpoint
Halfedge heCurr = heStart;
while (true) {
walked[heCurr.edge()] = true;
newPath.push_back(heCurr);
if (isEndpoint[heCurr.twin().vertex()]) break;
// find next edge
for (Halfedge heOther : heCurr.twin().vertex().outgoingHalfedges()) {
if (heOther.twin() != heCurr && inPath[heOther.edge()]) {
heCurr = heOther;
break;
}
}
}
}
// Any remaining paths are closed loops
for (Halfedge heStart : mesh.halfedges()) {
// Check if we should start a walk
if (!inPath[heStart.edge()] || walked[heStart.edge()]) continue;
// Start a new path
allHalfedges.emplace_back();
std::vector<Halfedge>& newPath = allHalfedges.back();
// Walk along the path until we reach an endpoint
Halfedge heCurr = heStart;
do {
walked[heCurr.edge()] = true;
newPath.push_back(heCurr);
// find next edge
for (Halfedge heOther : heCurr.twin().vertex().outgoingHalfedges()) {
if (heOther.twin() != heCurr && inPath[heOther.edge()]) {
heCurr = heOther;
break;
}
}
} while (heCurr != heStart);
}
return std::unique_ptr<FlipEdgeNetwork>(new FlipEdgeNetwork(mesh_, geom, allHalfedges));
}
double FlipEdgeNetwork::minWedgeAngle(const FlipPathSegment& pathSegment) {
FlipEdgePath& edgePath = *pathSegment.path;
SegmentID nextID = pathSegment.id;
SegmentID prevID, UNUSED;
Halfedge heNext;
std::tie(heNext, prevID, UNUSED) = edgePath.pathHeInfo[nextID];
if (prevID == INVALID_IND) {
// This is the first halfedge in a not-closed path
return M_PI;
}
Halfedge hePrev = std::get<0>(edgePath.pathHeInfo[prevID]);
return minWedgeAngle(hePrev, heNext);
}
double FlipEdgeNetwork::minWedgeAngle(Halfedge hePrev, Halfedge heNext) {
return std::get<1>(locallyShortestTestWithType(hePrev, heNext));
}
SegmentAngleType FlipEdgeNetwork::locallyShortestTest(Halfedge hePrev, Halfedge heNext) {
return std::get<0>(locallyShortestTestWithType(hePrev, heNext));
}
double FlipEdgeNetwork::minAngle() {
double minAngle = std::numeric_limits<double>::infinity();
for (auto& epPtr : paths) {
FlipEdgePath& path = *epPtr;
int prevInvalidCount = 0;
int nextInvalidCount = 0;
for (auto it : path.pathHeInfo) {
// Gather values
SegmentID currID = it.first;
SegmentID prevID, nextID;
Halfedge currHe;
std::tie(currHe, prevID, nextID) = it.second;
if (prevID == INVALID_IND) continue;
Halfedge prevHe = std::get<0>(path.pathHeInfo[prevID]);
double angle = minWedgeAngle(prevHe, currHe);
minAngle = std::fmin(minAngle, angle);
}
}
return minAngle;
}
double FlipEdgeNetwork::minAngleIsotopy() {
double minAngle = std::numeric_limits<double>::infinity();
for (auto& epPtr : paths) {
FlipEdgePath& path = *epPtr;
int prevInvalidCount = 0;
int nextInvalidCount = 0;
for (auto it : path.pathHeInfo) {
// Gather values
SegmentID currID = it.first;
SegmentID prevID, nextID;
Halfedge currHe;
std::tie(currHe, prevID, nextID) = it.second;
if (prevID == INVALID_IND) continue;
Halfedge prevHe = std::get<0>(path.pathHeInfo[prevID]);
ShortestReturnBoth result = locallyShortestTestWithBoth(prevHe, currHe);
// Skip if the wedge if blocked
FlipPathSegment seg{epPtr.get(), currID};
if (result.minType != SegmentAngleType::Shortest && !wedgeIsClearEndpointsOnly(seg, result.minType)) {
continue;
}
// Skip if the vertex is marked and not straightening
if (!straightenAroundMarkedVertices && isMarkedVertex[currHe.twin().vertex()]) continue;
minAngle = std::fmin(minAngle, result.minAngle);
}
}
return minAngle;
}
std::tuple<double, double> FlipEdgeNetwork::measureSideAngles(Halfedge hePrev, Halfedge heNext) {
Vertex v = heNext.vertex();
double s = tri->vertexAngleSums[v];
double angleIn = tri->signpostAngle[hePrev.twin()];
double angleOut = tri->signpostAngle[heNext];
bool isBoundary = v.isBoundary();
// Compute right angle
double rightAngle;
if (angleIn < angleOut) {
rightAngle = angleOut - angleIn;
} else {
if (isBoundary) {
rightAngle = std::numeric_limits<double>::infinity();
} else {
rightAngle = (s - angleIn) + angleOut;
}
}
// Compute left angle
double leftAngle;
if (angleOut < angleIn) {
leftAngle = angleIn - angleOut;
} else {
if (isBoundary) {
leftAngle = std::numeric_limits<double>::infinity();
} else {
leftAngle = (s - angleOut) + angleIn;
}
}
return std::tuple<double, double>{leftAngle, rightAngle};
}
std::tuple<SegmentAngleType, double> FlipEdgeNetwork::locallyShortestTestWithType(Halfedge hePrev, Halfedge heNext) {
if (hePrev == Halfedge()) return std::make_tuple(SegmentAngleType::Shortest, std::numeric_limits<double>::infinity());
double leftAngle, rightAngle;
std::tie(leftAngle, rightAngle) = measureSideAngles(hePrev, heNext);
double minAngle = std::fmin(leftAngle, rightAngle);
// Classify
if (leftAngle < rightAngle) {
if (leftAngle > (M_PI - EPS_ANGLE)) {
return std::make_tuple(SegmentAngleType::Shortest, minAngle);
}
return std::make_tuple(SegmentAngleType::LeftTurn, minAngle);
} else {
if (rightAngle > (M_PI - EPS_ANGLE)) {
return std::make_tuple(SegmentAngleType::Shortest, minAngle);
}
return std::make_tuple(SegmentAngleType::RightTurn, minAngle);
}
}
FlipEdgeNetwork::ShortestReturnBoth FlipEdgeNetwork::locallyShortestTestWithBoth(Halfedge hePrev, Halfedge heNext) {
ShortestReturnBoth result{SegmentAngleType::Shortest, std::numeric_limits<double>::infinity(),
SegmentAngleType::Shortest, std::numeric_limits<double>::infinity()};
if (hePrev == Halfedge()) return result;
double leftAngle, rightAngle;
std::tie(leftAngle, rightAngle) = measureSideAngles(hePrev, heNext);
double minAngle = std::fmin(leftAngle, rightAngle);
// Classify
if (leftAngle < rightAngle) {
result.minAngle = leftAngle;
result.maxAngle = rightAngle;
if (leftAngle > (M_PI - EPS_ANGLE)) {
result.minType = SegmentAngleType::Shortest;
} else {
result.minType = SegmentAngleType::LeftTurn;
}
if (rightAngle > (M_PI - EPS_ANGLE)) {
result.maxType = SegmentAngleType::Shortest;
} else {
result.maxType = SegmentAngleType::RightTurn;
}
} else {
result.minAngle = rightAngle;
result.maxAngle = leftAngle;
if (rightAngle > (M_PI - EPS_ANGLE)) {
result.minType = SegmentAngleType::Shortest;
} else {
result.minType = SegmentAngleType::RightTurn;
}
if (leftAngle > (M_PI - EPS_ANGLE)) {
result.maxType = SegmentAngleType::Shortest;
} else {
result.maxType = SegmentAngleType::LeftTurn;
}
}
return result;
}
bool FlipEdgeNetwork::wedgeIsClear(const FlipPathSegment& pathSegmentNext, SegmentAngleType type) {
// WARNING code duplications with endpoints only version
// TODO handle checks in case where the path lollipops out and back along a single edge
// Gather values
FlipEdgePath& edgePath = *pathSegmentNext.path;
SegmentID nextID = pathSegmentNext.id;
SegmentID prevID, UNUSED;
Halfedge heNext;
std::tie(heNext, prevID, UNUSED) = edgePath.pathHeInfo[nextID];
if (prevID == INVALID_IND) {
// This is the first halfedge in a not-closed path
throw std::runtime_error("called wedgeIsClear() beginning of openPath");
}
Halfedge hePrev = std::get<0>(edgePath.pathHeInfo[prevID]);
FlipPathSegment pathSegmentPrev{&edgePath, prevID};
// Gather values
Vertex prevVert = hePrev.vertex();
Vertex middleVert = heNext.vertex();
Vertex nextVert = heNext.twin().vertex();
// Used to disable straightening around certain vertices, but usually this isn't what you want: the algorithm should
// still be able to straighten if a path touches and endpoint vertex but is not obstructed.
if (!straightenAroundMarkedVertices && isMarkedVertex[middleVert]) {
return false;
}
// Split to cases based on which side the wedge faces. Either way, we're iterating around the wedge making sure there
// are no path edges in the way.
switch (type) {
case SegmentAngleType::Shortest: {
throw std::runtime_error("checked wedgeIsClear() with straight wedge, which doesn't make sense");
break;
}
case SegmentAngleType::LeftTurn: {
// Check bounding edges
if (getOutsideSegment(hePrev) != pathSegmentPrev) return false;
if (getOutsideSegment(heNext) != pathSegmentNext) return false;
// Orbit incident edges in wedge, each must have no path edges
Halfedge heCurr = hePrev.next();
while (heCurr != heNext) {
if (edgeInPath(heCurr.edge())) return false;
heCurr = heCurr.twin().next();
}
break;
}
case SegmentAngleType::RightTurn: {
// Check bounding edges
if (getOutsideSegment(hePrev.twin()) != pathSegmentPrev) return false;
if (getOutsideSegment(heNext.twin()) != pathSegmentNext) return false;
// Orbit incident edges in wedge, each must have no path edges
Halfedge heCurr = hePrev.twin().next().next().twin();
while (heCurr != heNext) {
if (edgeInPath(heCurr.edge())) return false;
heCurr = heCurr.next().next().twin();
}
break;
}
}
return true;
}
// Like wedgeIsClear(), but only returns true if block by a path endpoint, rather than an interior portion of hte path.
// Useful for testing isotopy classes.
bool FlipEdgeNetwork::wedgeIsClearEndpointsOnly(const FlipPathSegment& pathSegmentNext, SegmentAngleType type) {
// WARNING code duplications with endpoints only version
// Gather values
FlipEdgePath& edgePath = *pathSegmentNext.path;
SegmentID nextID = pathSegmentNext.id;
SegmentID prevID, UNUSED;
Halfedge heNext;
std::tie(heNext, prevID, UNUSED) = edgePath.pathHeInfo[nextID];
if (prevID == INVALID_IND) {
// This is the first halfedge in a not-closed path
throw std::runtime_error("called wedgeIsClear() beginning of openPath");
}
Halfedge hePrev = std::get<0>(edgePath.pathHeInfo[prevID]);
FlipPathSegment pathSegmentPrev{&edgePath, prevID};
// Gather values
Vertex prevVert = hePrev.vertex();
Vertex middleVert = heNext.vertex();
Vertex nextVert = heNext.twin().vertex();
// Split to cases based on which side the wedge faces. Either way, we're iterating around the wedge making sure there
// are no path edges in the way.
switch (type) {
case SegmentAngleType::Shortest: {
throw std::runtime_error("checked wedgeIsClear() with straight wedge, which doesn't make sense");
break;
}
case SegmentAngleType::LeftTurn: {
// Check bounding edges
if (getOutsideSegment(hePrev) != pathSegmentPrev && getOutsideSegment(hePrev).isEndpoint()) return false;
if (getOutsideSegment(heNext) != pathSegmentNext && getOutsideSegment(heNext).isEndpoint()) return false;
// Orbit incident edges in wedge, each must have no path edges
Halfedge heCurr = hePrev.next();
while (heCurr != heNext) {
for (FlipPathSegment& p : pathsAtEdge[heCurr.edge()]) {
if (p.isEndpoint()) return false;
}
heCurr = heCurr.twin().next();
}
break;
}
case SegmentAngleType::RightTurn: {
// Check bounding edges
if (getOutsideSegment(hePrev.twin()) != pathSegmentPrev && getOutsideSegment(hePrev.twin()).isEndpoint())
return false;
if (getOutsideSegment(heNext.twin()) != pathSegmentNext && getOutsideSegment(heNext.twin()).isEndpoint())
return false;
// Orbit incident edges in wedge, each must have no path edges
Halfedge heCurr = hePrev.twin().next().next().twin();
while (heCurr != heNext) {
for (FlipPathSegment& p : pathsAtEdge[heCurr.edge()]) {
if (p.isEndpoint()) return false;
}
heCurr = heCurr.next().next().twin();
}
break;
}
}
return true;
}
void FlipEdgeNetwork::locallyShortenAt(FlipPathSegment& pathSegment, SegmentAngleType angleType) {
// Gather values
FlipEdgePath& edgePath = *pathSegment.path;
SegmentID nextID = pathSegment.id;
SegmentID prevID, UNUSED;
Halfedge heNext;
std::tie(heNext, prevID, UNUSED) = edgePath.pathHeInfo[nextID];
if (prevID == INVALID_IND) {
// This is the first halfedge in a not-closed path
return;
}
Halfedge hePrev = std::get<0>(edgePath.pathHeInfo[prevID]);
// Gather values
Vertex prevVert = hePrev.vertex();
Vertex middleVert = heNext.vertex();
Vertex nextVert = heNext.twin().vertex();
if (angleType == SegmentAngleType::Shortest) {
// nothing to do here
return;
}
nShortenIters++;
// Special case for loop consisting of a single self-edge
if (prevID == nextID) {
processSingleEdgeLoop(pathSegment, angleType);
return;
}
// Compute the initial path length
double initPathLength = tri->edgeLengths[hePrev.edge()] + tri->edgeLengths[heNext.edge()];
// The straightening logic below always walks CW, so flip the ordering if this is a right turn
Halfedge sPrev, sNext;
bool reversed;
if (angleType == SegmentAngleType::LeftTurn) {
sPrev = hePrev;
sNext = heNext;
reversed = false;
} else {
sPrev = heNext.twin();
sNext = hePrev.twin();
reversed = true;
}
{ // == Main logic: flip until a shorter path exists
Halfedge sCurr = sPrev.next();
Halfedge sPrevTwin = sPrev.twin();
while (sCurr != sNext) {
// Don't want to flip the first edge of the wedge
if (sCurr == sPrevTwin) {
sCurr = sCurr.twin().next(); // advance to next edge
continue;
}
// Gather values for the edge to be flipped
Edge currEdge = sCurr.edge();
double oldLen = tri->edgeLengths[currEdge]; // old values are used for rewinding
double oldAngleA = tri->signpostAngle[currEdge.halfedge()];
double oldAngleB = tri->signpostAngle[currEdge.halfedge().twin()];
bool oldIsOrig = tri->edgeIsOriginal[currEdge];
// Try to flip the edge. Note that flipping will only be possible iff \beta < \pi as in the formal algorithm
// statement
bool flipped = tri->flipEdgeIfPossible(currEdge);
if (flipped) {
nFlips++;
// track data to support rewinding
if (supportRewinding) {
rewindRecord.emplace_back(currEdge, oldLen, oldAngleA, oldAngleB, oldIsOrig);
}
// Flip happened! Update data and continue processing
// Re-check previous edge
sCurr = sCurr.twin().next().twin();
} else {
sCurr = sCurr.twin().next(); // advance to next edge
}
}
}
// Build the list of edges representing the new path
// measure the length of the new path along the boundary
double newPathLength = 0.;
std::vector<Halfedge> newPath;
{
Halfedge sCurr = sPrev.next();
while (true) {
newPath.push_back(sCurr.next().twin());
newPathLength += tri->edgeLengths[sCurr.next().edge()];
if (sCurr == sNext) break;
sCurr = sCurr.twin().next();
}
}
// Make sure the new path is actually shorter (this would never happen in the Reals, but can rarely happen if an edge
// is numerically unflippable for floating point reasons)
if (newPathLength > initPathLength) return;
// Make sure the new path orientation matches the orientation of the input edges
if (reversed) {
std::reverse(newPath.begin(), newPath.end());
for (Halfedge& he : newPath) {
he = he.twin();
}
}
// Replace the path segment with the new path
// (most of the bookkeeping to update data structures happens in here)
edgePath.replacePathSegment(nextID, angleType, newPath);
}
void FlipEdgeNetwork::processSingleEdgeLoop(FlipPathSegment& pathSegment, SegmentAngleType angleType) {
// That annoying special case we need to handle for loops consisting of a single edge
FlipEdgePath& edgePath = *pathSegment.path;
SegmentID id = pathSegment.id;
SegmentID UNUSED1, UNUSED2;
Halfedge he;
std::tie(he, UNUSED1, UNUSED2) = edgePath.pathHeInfo[id];
// == Replace the old segment with the two opposite edges of the triangle
switch (angleType) {
case SegmentAngleType::Shortest: {
// nothing to do, probably shouldn't even be here
return;
break;
}
case SegmentAngleType::LeftTurn: {
Halfedge heFirst = he.next().next().twin();
Halfedge heSecond = he.next().twin();
SegmentID firstID = getNextUniquePathSegmentInd();
SegmentID secondID = getNextUniquePathSegmentInd();
edgePath.pathHeInfo.erase(id);
popOutsideSegment(he);
edgePath.pathHeInfo[firstID] = std::make_tuple(heFirst, secondID, secondID);
edgePath.pathHeInfo[secondID] = std::make_tuple(heSecond, firstID, firstID);
pushOutsideSegment(heFirst.twin(), FlipPathSegment{&edgePath, firstID});
pushOutsideSegment(heSecond.twin(), FlipPathSegment{&edgePath, secondID});
addToWedgeAngleQueue(FlipPathSegment{&edgePath, firstID});
addToWedgeAngleQueue(FlipPathSegment{&edgePath, secondID});
break;
}
case SegmentAngleType::RightTurn: {
Halfedge heFirst = he.twin().next();
Halfedge heSecond = he.twin().next().next();
SegmentID firstID = getNextUniquePathSegmentInd();
SegmentID secondID = getNextUniquePathSegmentInd();
edgePath.pathHeInfo.erase(id);
popOutsideSegment(he.twin());
edgePath.pathHeInfo[firstID] = std::make_tuple(heFirst, secondID, secondID);
edgePath.pathHeInfo[secondID] = std::make_tuple(heSecond, firstID, firstID);
pushOutsideSegment(heFirst, FlipPathSegment{&edgePath, firstID});
pushOutsideSegment(heSecond, FlipPathSegment{&edgePath, secondID});
addToWedgeAngleQueue(FlipPathSegment{&edgePath, firstID});
addToWedgeAngleQueue(FlipPathSegment{&edgePath, secondID});
break;
}
}
}
void FlipEdgeNetwork::iterativeShorten(size_t maxIterations, double maxRelativeLengthDecrease) {
bool checkLength = maxRelativeLengthDecrease != 0;
double initLength = -777;
if (checkLength) {
initLength = length();
}
size_t nIterations = 0;
while (!wedgeAngleQueue.empty() && (maxIterations == INVALID_IND || nIterations < maxIterations)) {
// Get the smallest angle
double minAngle = std::get<0>(wedgeAngleQueue.top());
SegmentAngleType angleType = std::get<1>(wedgeAngleQueue.top());
FlipPathSegment pathSegment = std::get<2>(wedgeAngleQueue.top());
wedgeAngleQueue.pop();
// Check if its a stale entry
FlipEdgePath& path = *pathSegment.path;
if (path.pathHeInfo.find(pathSegment.id) == path.pathHeInfo.end()) {
continue; // segment no longer exists
}
double currAngle = minWedgeAngle(pathSegment);
if (currAngle != minAngle) {
continue; // angle has changed
}
// Make sure the wedge is clear
// TODO I think we _might_ be able to argue that this check isn't necessary, and the wedge will always be clear as
// long as we check it before inserting in to the queue
if (!wedgeIsClear(pathSegment, angleType)) {
continue;
}
// Shorten about that wedge
locallyShortenAt(pathSegment, angleType);
// validate();
nIterations++;
// Periodically purge the queue, since we can't remove from it and thus accumulate stale entries
size_t purgeInterval = 1000; // note: basically does nothing; our queues pretty much never get this big
if (nIterations % purgeInterval == 0) {
purgeStaleQueueEntries();
}
// Quit if we pass the length threshold
if (checkLength) {
double currLength = length();
if (currLength < maxRelativeLengthDecrease * initLength) {
break;
}
}
}
}