-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTriangulation.cs
More file actions
1626 lines (1430 loc) · 60.3 KB
/
Triangulation.cs
File metadata and controls
1626 lines (1430 loc) · 60.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
using System.Numerics;
using System.Runtime.CompilerServices;
using static CDT.CdtUtils;
namespace CDT;
/// <summary>
/// Errors thrown by the triangulation.
/// </summary>
public class TriangulationException : Exception
{
/// <inheritdoc/>
public TriangulationException(string message) : base(message) { }
}
/// <summary>Thrown when a duplicate vertex is detected during insertion.</summary>
public sealed class DuplicateVertexException : TriangulationException
{
/// <summary>First duplicate vertex index.</summary>
public int V1 { get; }
/// <summary>Second duplicate vertex index (same position as V1).</summary>
public int V2 { get; }
/// <inheritdoc/>
public DuplicateVertexException(int v1, int v2)
: base($"Duplicate vertex detected: #{v1} is a duplicate of #{v2}")
{
V1 = v1;
V2 = v2;
}
}
/// <summary>
/// Thrown when a mutating method is called after the triangulation has been finalized
/// (i.e., after any <c>Erase*</c> method has been called).
/// </summary>
public sealed class TriangulationFinalizedException : TriangulationException
{
/// <inheritdoc/>
public TriangulationFinalizedException()
: base("The triangulation has already been finalized. No further modifications are allowed after calling an Erase method.")
{ }
}
/// <summary>Thrown when intersecting constraint edges are detected and <see cref="IntersectingConstraintEdges.NotAllowed"/> is set.</summary>
public sealed class IntersectingConstraintsException : TriangulationException
{
/// <summary>First constraint edge.</summary>
public Edge E1 { get; }
/// <summary>Second constraint edge.</summary>
public Edge E2 { get; }
/// <inheritdoc/>
public IntersectingConstraintsException(Edge e1, Edge e2)
: base($"Intersecting constraint edges: ({e1.V1},{e1.V2}) ∩ ({e2.V1},{e2.V2})")
{
E1 = e1;
E2 = e2;
}
}
/// <summary>
/// 2D constrained Delaunay triangulation.
/// Supports both constrained and conforming modes.
/// </summary>
/// <typeparam name="T">Floating-point coordinate type (float or double).</typeparam>
public sealed class Triangulation<T>
where T : unmanaged, IFloatingPoint<T>, IMinMaxValue<T>, IRootFunctions<T>
{
// -------------------------------------------------------------------------
// Public state (read-only views)
// -------------------------------------------------------------------------
/// <summary>All vertices in the triangulation (including super-triangle vertices while not finalized).</summary>
public ReadOnlyMemory<V2d<T>> Vertices => new(_vertices, 0, _verticesCount);
/// <summary>All triangles in the triangulation.</summary>
public ReadOnlyMemory<Triangle> Triangles => new(_triangles, 0, _trianglesCount);
/// <summary>Set of constraint (fixed) edges.</summary>
public IReadOnlySet<Edge> FixedEdges => _fixedEdges;
/// <summary>
/// Stores count of overlapping boundaries for a fixed edge.
/// Only has entries for edges that represent overlapping boundaries.
/// </summary>
public IReadOnlyDictionary<Edge, ushort> OverlapCount => _overlapCount;
/// <summary>
/// Stores the list of original edges represented by a given fixed edge.
/// Only populated when edges were split or overlap.
/// </summary>
public IReadOnlyDictionary<Edge, IReadOnlyList<Edge>> PieceToOriginals => _pieceToOriginalsView;
// -------------------------------------------------------------------------
// Private fields
// -------------------------------------------------------------------------
private V2d<T>[] _vertices = [];
private int _verticesCount;
private Triangle[] _triangles = [];
private int _trianglesCount;
private readonly HashSet<Edge> _fixedEdges = new();
private readonly Dictionary<Edge, ushort> _overlapCount = new();
private readonly Dictionary<Edge, List<Edge>> _pieceToOriginals = new();
private readonly IReadOnlyDictionary<Edge, IReadOnlyList<Edge>> _pieceToOriginalsView;
private readonly VertexInsertionOrder _insertionOrder;
private readonly IntersectingConstraintEdges _intersectingEdgesStrategy;
private readonly T _minDistToConstraintEdge;
private readonly T _two;
private SuperGeometryType _superGeomType;
private int _nTargetVerts;
// For each vertex: one adjacent triangle index
private int[] _vertTris = [];
private int _vertTrisCount;
// KD-tree for nearest-point location
private KdTree<T>? _kdTree;
// -------------------------------------------------------------------------
// Construction
// -------------------------------------------------------------------------
/// <summary>
/// Creates a triangulation with default settings:
/// <see cref="VertexInsertionOrder.Auto"/>,
/// <see cref="IntersectingConstraintEdges.NotAllowed"/>,
/// zero minimum distance.
/// </summary>
public Triangulation()
: this(VertexInsertionOrder.Auto, IntersectingConstraintEdges.NotAllowed, T.Zero)
{ }
/// <summary>Creates a triangulation with the specified insertion order.</summary>
public Triangulation(VertexInsertionOrder insertionOrder)
: this(insertionOrder, IntersectingConstraintEdges.NotAllowed, T.Zero)
{ }
/// <summary>Creates a triangulation with explicit settings.</summary>
public Triangulation(
VertexInsertionOrder insertionOrder,
IntersectingConstraintEdges intersectingEdgesStrategy,
T minDistToConstraintEdge)
{
_insertionOrder = insertionOrder;
_intersectingEdgesStrategy = intersectingEdgesStrategy;
_minDistToConstraintEdge = minDistToConstraintEdge;
_two = T.One + T.One;
_superGeomType = SuperGeometryType.SuperTriangle;
_nTargetVerts = 0;
_pieceToOriginalsView = new CovariantReadOnlyDictionary<Edge, List<Edge>, IReadOnlyList<Edge>>(_pieceToOriginals);
}
// -------------------------------------------------------------------------
// Public API – vertex insertion
// -------------------------------------------------------------------------
/// <summary>Inserts a list of vertices into the triangulation.</summary>
public void InsertVertices(IReadOnlyList<V2d<T>> newVertices)
{
if (IsFinalized) throw new TriangulationFinalizedException();
if (newVertices.Count == 0) return;
bool isFirstInsertion = _kdTree == null && _verticesCount == 0;
// Pre-allocate backing arrays once we know the incoming vertex count.
// Euler's formula: a planar triangulation of N points has ~2N triangles.
if (isFirstInsertion)
{
int n = newVertices.Count;
ArrayEnsureCapacity(ref _vertices, n + Indices.SuperTriangleVertexCount);
ArrayEnsureCapacity(ref _vertTris, n + Indices.SuperTriangleVertexCount);
ArrayEnsureCapacity(ref _triangles, 2 * n + 4);
}
// Build bounding box of new vertices
var box = new Box2d<T>();
box.Envelop(newVertices);
if (isFirstInsertion)
{
AddSuperTriangle(box);
}
else if (_kdTree == null)
{
// Subsequent calls: initialize the KD tree with all existing vertices
InitKdTree();
}
int insertStart = _verticesCount;
foreach (var v in newVertices)
{
AddNewVertex(v, Indices.NoNeighbor);
}
if (_insertionOrder == VertexInsertionOrder.Auto && isFirstInsertion)
{
// Use BFS KD-tree ordering for the first bulk insertion
// Walk-start comes from the BFS parent, not the KD tree
InsertVertices_KDTreeBFS(insertStart, box);
}
else if (_insertionOrder == VertexInsertionOrder.Auto)
{
// Subsequent calls: randomized with KD-tree walk-start
InsertVertices_Randomized(insertStart);
}
else
{
// AsProvided: sequential order, KD-tree walk-start
var stack = new Stack<int>(4);
for (int iV = insertStart; iV < _verticesCount; iV++)
{
InsertVertex(iV, stack);
}
}
}
// -------------------------------------------------------------------------
// Public API – edge insertion (constrained DT)
// -------------------------------------------------------------------------
/// <summary>Inserts constraint edges (constrained Delaunay triangulation).</summary>
public void InsertEdges(IReadOnlyList<Edge> edges)
{
if (IsFinalized) throw new TriangulationFinalizedException();
var remaining = new List<Edge>(4);
var tppTasks = new List<TriangulatePseudoPolygonTask>(8);
var polyL = new List<int>(8);
var polyR = new List<int>(8);
var outerTris = new Dictionary<Edge, int>();
var intersected = new List<int>(8);
foreach (var e in edges)
{
remaining.Clear();
remaining.Add(new Edge(e.V1 + _nTargetVerts, e.V2 + _nTargetVerts));
while (remaining.Count > 0)
{
Edge edge = remaining[^1];
remaining.RemoveAt(remaining.Count - 1);
InsertEdgeIteration(edge, new Edge(e.V1 + _nTargetVerts, e.V2 + _nTargetVerts), remaining, tppTasks, polyL, polyR, outerTris, intersected);
}
}
}
// -------------------------------------------------------------------------
// Public API – conforming DT
// -------------------------------------------------------------------------
/// <summary>
/// Inserts constraint edges for a conforming Delaunay triangulation.
/// May add new vertices (midpoints) until edges are represented.
/// </summary>
public void ConformToEdges(IReadOnlyList<Edge> edges)
{
if (IsFinalized) throw new TriangulationFinalizedException();
var remaining = new List<ConformToEdgeTask>(8);
var flipStack = new Stack<int>(4);
var flippedFixed = new List<Edge>(8);
foreach (var e in edges)
{
var shifted = new Edge(e.V1 + _nTargetVerts, e.V2 + _nTargetVerts);
remaining.Clear();
remaining.Add(new ConformToEdgeTask(shifted, new List<Edge> { shifted }, 0));
while (remaining.Count > 0)
{
var task = remaining[^1];
remaining.RemoveAt(remaining.Count - 1);
ConformToEdgeIteration(task.Edge, task.Originals, task.Overlaps, remaining, flipStack, flippedFixed);
}
}
}
// -------------------------------------------------------------------------
// Public API – finalization
// -------------------------------------------------------------------------
/// <summary>Removes the super-triangle to produce a convex hull triangulation.</summary>
public void EraseSuperTriangle()
{
if (IsFinalized) throw new TriangulationFinalizedException();
if (_superGeomType != SuperGeometryType.SuperTriangle) return;
var toErase = new HashSet<int>();
for (int i = 0; i < _trianglesCount; i++)
{
if (CdtUtils.TouchesSuperTriangle(_triangles[i]))
toErase.Add(i);
}
FinalizeTriangulation(toErase);
}
/// <summary>Removes all outer triangles (flood-fill from super-triangle vertex until a constraint edge).</summary>
public void EraseOuterTriangles()
{
if (IsFinalized) throw new TriangulationFinalizedException();
if (_vertTris[0] == Indices.NoNeighbor)
throw new TriangulationException("No vertex triangle data – already finalized?");
var seeds = new Stack<int>();
seeds.Push(_vertTris[0]);
var toErase = GrowToBoundary(seeds);
FinalizeTriangulation(toErase);
}
/// <summary>
/// Removes outer triangles and automatically detects and removes holes
/// using even-odd depth rule.
/// </summary>
public void EraseOuterTrianglesAndHoles()
{
if (IsFinalized) throw new TriangulationFinalizedException();
var depths = CalculateTriangleDepths();
var toErase = new HashSet<int>();
for (int i = 0; i < _trianglesCount; i++)
{
if (depths[i] % 2 == 0) toErase.Add(i);
}
FinalizeTriangulation(toErase);
}
/// <summary>
/// Indicates whether the triangulation has been finalized (i.e., one of the
/// Erase methods was called). Further modification is not possible.
/// </summary>
public bool IsFinalized => _vertTrisCount == 0 && _verticesCount > 0;
// -------------------------------------------------------------------------
// Internal helpers – super-triangle setup
// -------------------------------------------------------------------------
private void AddSuperTriangle(Box2d<T> box)
{
_nTargetVerts = Indices.SuperTriangleVertexCount;
_superGeomType = SuperGeometryType.SuperTriangle;
T cx = (box.Min.X + box.Max.X) / _two;
T cy = (box.Min.Y + box.Max.Y) / _two;
T w = box.Max.X - box.Min.X;
T h = box.Max.Y - box.Min.Y;
T r = T.Max(w, h);
r = T.Max(_two * r, T.One);
// Guard against very large numbers
while (cy <= cy - r) r = _two * r;
T R = _two * r;
T cos30 = ParseT("0.8660254037844386");
T shiftX = R * cos30;
var v1 = new V2d<T>(cx - shiftX, cy - r);
var v2 = new V2d<T>(cx + shiftX, cy - r);
var v3 = new V2d<T>(cx, cy + R);
AddNewVertex(v1, 0);
AddNewVertex(v2, 0);
AddNewVertex(v3, 0);
AddTriangle(new Triangle(0, 1, 2, Indices.NoNeighbor, Indices.NoNeighbor, Indices.NoNeighbor));
if (_insertionOrder != VertexInsertionOrder.Auto)
{
InitKdTree();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void AddNewVertex(V2d<T> pos, int iTri)
{
ArrayAdd(ref _vertices, ref _verticesCount, pos);
ArrayAdd(ref _vertTris, ref _vertTrisCount, iTri);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int AddTriangle() => AddTriangle(new Triangle());
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int AddTriangle(Triangle t)
{
int idx = _trianglesCount;
ArrayAdd(ref _triangles, ref _trianglesCount, t);
return idx;
}
// -------------------------------------------------------------------------
// Low-level array-growth helpers
// -------------------------------------------------------------------------
// Maximum element count for which a temporary int[] is stackalloc'd instead of heap-allocated.
private const int StackAllocThreshold = 512;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ArrayAdd<TItem>(ref TItem[] arr, ref int count, TItem item)
{
if (count == arr.Length)
Array.Resize(ref arr, arr.Length == 0 ? 4 : arr.Length * 2);
arr[count++] = item;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ArrayEnsureCapacity<TItem>(ref TItem[] arr, int capacity)
{
if (arr.Length < capacity)
Array.Resize(ref arr, capacity);
}
// -------------------------------------------------------------------------
// Internal helpers – vertex insertion
// -------------------------------------------------------------------------
private void InsertVertex(int iVert, int walkStart, Stack<int> stack)
{
var (iT, iTopo) = WalkingSearchTrianglesAt(iVert, walkStart);
if (iTopo == Indices.NoNeighbor)
InsertVertexInsideTriangle(iVert, iT, stack);
else
InsertVertexOnEdge(iVert, iT, iTopo, handleFixedSplitEdge: true, stack);
EnsureDelaunayByEdgeFlips(iVert, stack);
TryAddVertexToLocator(iVert);
}
private void InsertVertex(int iVert, int walkStart)
{
var stack = new Stack<int>(4);
InsertVertex(iVert, walkStart, stack);
}
private void InsertVertex(int iVert, Stack<int> stack)
{
int near = _kdTree != null
? _kdTree.Nearest(_vertices[iVert].X, _vertices[iVert].Y, _vertices)
: 0;
InsertVertex(iVert, near, stack);
}
private void InsertVertex(int iVert)
{
// Walk-start from KD-tree nearest point, or vertex 0 as fallback
int near = _kdTree != null
? _kdTree.Nearest(_vertices[iVert].X, _vertices[iVert].Y, _vertices)
: 0;
InsertVertex(iVert, near);
}
private void InsertVertices_Randomized(int superGeomVertCount)
{
int count = _verticesCount - superGeomVertCount;
Span<int> indices = count <= StackAllocThreshold ? stackalloc int[count] : new int[count];
for (int i = 0; i < count; i++) { indices[i] = superGeomVertCount + i; }
for (int i = count - 1; i > 0; i--)
{
int j = Random.Shared.Next(i + 1);
(indices[i], indices[j]) = (indices[j], indices[i]);
}
var stack = new Stack<int>(4);
foreach (int iV in indices) { InsertVertex(iV, stack); }
}
private void InsertVertices_KDTreeBFS(int superGeomVertCount, Box2d<T> box)
{
int vertexCount = _verticesCount - superGeomVertCount;
if (vertexCount <= 0) { return; }
Span<int> indices = vertexCount <= StackAllocThreshold ? stackalloc int[vertexCount] : new int[vertexCount];
for (int i = 0; i < vertexCount; i++) { indices[i] = superGeomVertCount + i; }
var queue = new Queue<(int lo, int hi, T boxMinX, T boxMinY, T boxMaxX, T boxMaxY, int parent)>();
queue.Enqueue((0, vertexCount, box.Min.X, box.Min.Y, box.Max.X, box.Max.Y, 0));
var stack = new Stack<int>(4);
while (queue.Count > 0)
{
var (lo, hi, boxMinX, boxMinY, boxMaxX, boxMaxY, parent) = queue.Dequeue();
int len = hi - lo;
if (len == 0) { continue; }
if (len == 1) { InsertVertex(indices[lo], parent, stack); continue; }
int midPos = lo + len / 2;
if (T.CreateChecked(boxMaxX - boxMinX) >= T.CreateChecked(boxMaxY - boxMinY))
{
NthElement(indices, lo, midPos, hi, new VertexXComparer(_vertices));
T split = _vertices[indices[midPos]].X;
InsertVertex(indices[midPos], parent, stack);
if (lo < midPos) { queue.Enqueue((lo, midPos, boxMinX, boxMinY, split, boxMaxY, indices[midPos])); }
if (midPos + 1 < hi) { queue.Enqueue((midPos + 1, hi, split, boxMinY, boxMaxX, boxMaxY, indices[midPos])); }
}
else
{
NthElement(indices, lo, midPos, hi, new VertexYComparer(_vertices));
T split = _vertices[indices[midPos]].Y;
InsertVertex(indices[midPos], parent, stack);
if (lo < midPos) { queue.Enqueue((lo, midPos, boxMinX, boxMinY, boxMaxX, split, indices[midPos])); }
if (midPos + 1 < hi) { queue.Enqueue((midPos + 1, hi, boxMinX, split, boxMaxX, boxMaxY, indices[midPos])); }
}
}
}
// -------------------------------------------------------------------------
// nth_element — O(n) average quickselect for spatial BFS partitioning
// -------------------------------------------------------------------------
private readonly struct VertexXComparer : IComparer<int>
{
private readonly V2d<T>[] _vertices;
public VertexXComparer(V2d<T>[] vertices) => _vertices = vertices;
public int Compare(int a, int b) => _vertices[a].X.CompareTo(_vertices[b].X);
}
private readonly struct VertexYComparer : IComparer<int>
{
private readonly V2d<T>[] _vertices;
public VertexYComparer(V2d<T>[] vertices) => _vertices = vertices;
public int Compare(int a, int b) => _vertices[a].Y.CompareTo(_vertices[b].Y);
}
/// <summary>
/// Rearranges <paramref name="arr"/> in [<paramref name="lo"/>, <paramref name="hi"/>)
/// so the element at position <paramref name="nth"/> is the one that would be there
/// after a full sort; elements before it are ≤ it and elements after are ≥ it.
/// </summary>
private static void NthElement<TComparer>(Span<int> arr, int lo, int nth, int hi, TComparer cmp)
where TComparer : struct, IComparer<int>
{
while (lo < hi - 1)
{
// Pivot: middle element avoids worst-case on sorted input
int mid = lo + (hi - lo) / 2;
(arr[mid], arr[hi - 1]) = (arr[hi - 1], arr[mid]);
int store = lo;
for (int i = lo; i < hi - 1; i++)
{
if (cmp.Compare(arr[i], arr[hi - 1]) < 0)
{
(arr[store], arr[i]) = (arr[i], arr[store]);
store++;
}
}
(arr[store], arr[hi - 1]) = (arr[hi - 1], arr[store]);
if (store < nth) lo = store + 1;
else if (store > nth) hi = store;
else return;
}
}
private void InsertVertex_FlipFixedEdges(int iV, Stack<int> stack, List<Edge> flipped)
{
flipped.Clear();
// Use KD-tree if available, otherwise fall back to vertex 0 (first super-triangle vertex)
int near = _kdTree != null
? _kdTree.Nearest(_vertices[iV].X, _vertices[iV].Y, _vertices)
: 0;
var (iT, iTopo) = WalkingSearchTrianglesAt(iV, near);
if (iTopo == Indices.NoNeighbor)
InsertVertexInsideTriangle(iV, iT, stack);
else
InsertVertexOnEdge(iV, iT, iTopo, handleFixedSplitEdge: false, stack);
int _dbgFlipIter2 = 0;
while (stack.Count > 0)
{
if (++_dbgFlipIter2 > 1_000_000) throw new InvalidOperationException($"InsertVertex_FlipFixed infinite loop, iV={iV}");
int tri = stack.Pop();
EdgeFlipInfo(tri, iV,
out int itopo, out int iv2, out int iv3, out int iv4,
out int n1, out int n2, out int n3, out int n4);
if (itopo != Indices.NoNeighbor && IsFlipNeeded(iV, iv2, iv3, iv4))
{
var flippedEdge = new Edge(iv2, iv4);
if (_fixedEdges.Contains(flippedEdge))
flipped.Add(flippedEdge);
FlipEdge(tri, itopo, iV, iv2, iv3, iv4, n1, n2, n3, n4);
stack.Push(tri);
stack.Push(itopo);
}
}
TryAddVertexToLocator(iV);
}
private void EnsureDelaunayByEdgeFlips(int iV1, Stack<int> triStack)
{
int _dbgFlipIter = 0;
while (triStack.Count > 0)
{
if (++_dbgFlipIter > 1_000_000) throw new InvalidOperationException($"EnsureDelaunayByEdgeFlips infinite loop, iV1={iV1}, stack size={triStack.Count}");
int iT = triStack.Pop();
EdgeFlipInfo(iT, iV1,
out int iTopo, out int iV2, out int iV3, out int iV4,
out int n1, out int n2, out int n3, out int n4);
if (iTopo != Indices.NoNeighbor && IsFlipNeeded(iV1, iV2, iV3, iV4))
{
FlipEdge(iT, iTopo, iV1, iV2, iV3, iV4, n1, n2, n3, n4);
triStack.Push(iT);
triStack.Push(iTopo);
}
}
}
// -------------------------------------------------------------------------
// Locate triangle containing a vertex
// -------------------------------------------------------------------------
private (int iT, int iTopo) WalkingSearchTrianglesAt(int iVert, int startVertex)
{
var v = _vertices[iVert];
int iT = WalkTriangles(startVertex, v);
var t = _triangles[iT];
var loc = LocatePointTriangle(v, _vertices[t.V0], _vertices[t.V1], _vertices[t.V2]);
if (loc == PtTriLocation.Outside)
{
// Walk hit a degenerate cycle; fall back to brute-force linear scan
iT = FindTriangleLinear(v, out loc);
t = _triangles[iT];
}
if (loc == PtTriLocation.OnVertex)
{
int iDupe = _vertices[t.V0] == v ? t.V0 : _vertices[t.V1] == v ? t.V1 : t.V2;
throw new DuplicateVertexException(iVert - _nTargetVerts, iDupe - _nTargetVerts);
}
int iNeigh = CdtUtils.IsOnEdge(loc)
? t.GetNeighbor(CdtUtils.EdgeNeighborFromLocation(loc))
: Indices.NoNeighbor;
return (iT, iNeigh);
}
/// <summary>Brute-force O(n) fallback: scan all triangles to find the one containing <paramref name="pos"/>.</summary>
private int FindTriangleLinear(V2d<T> pos, out PtTriLocation loc)
{
for (int i = 0; i < _trianglesCount; i++)
{
var t = _triangles[i];
loc = LocatePointTriangle(pos, _vertices[t.V0], _vertices[t.V1], _vertices[t.V2]);
if (loc != PtTriLocation.Outside)
{
return i;
}
}
throw new TriangulationException($"No triangle found for point ({pos.X}, {pos.Y}).");
}
private int WalkTriangles(int startVertex, V2d<T> pos)
{
int currTri = _vertTris[startVertex];
for (int guard = 0; guard < 1_000_000; guard++)
{
var t = _triangles[currTri];
bool found = true;
int offset = guard % 3;
for (int i = 0; i < 3; i++)
{
int idx = (i + offset) % 3;
int vStart = t.GetVertex(idx);
int vEnd = t.GetVertex(CdtUtils.Ccw(idx));
var loc = LocatePointLine(pos, _vertices[vStart], _vertices[vEnd]);
int iN = t.GetNeighbor(idx);
if (loc == PtLineLocation.Right && iN != Indices.NoNeighbor)
{
currTri = iN;
found = false;
break;
}
}
if (found) { return currTri; }
}
// Walk did not converge (very degenerate triangulation) — let caller fall back.
return currTri;
}
// -------------------------------------------------------------------------
// Insert vertex inside triangle or on edge
// -------------------------------------------------------------------------
private void InsertVertexInsideTriangle(int v, int iT, Stack<int> stack)
{
int iNewT1 = AddTriangle();
int iNewT2 = AddTriangle();
var t = _triangles[iT];
int v1 = t.V0, v2 = t.V1, v3 = t.V2;
int n1 = t.N0, n2 = t.N1, n3 = t.N2;
_triangles[iNewT1] = new Triangle(v2, v3, v, n2, iNewT2, iT);
_triangles[iNewT2] = new Triangle(v3, v1, v, n3, iT, iNewT1);
_triangles[iT] = new Triangle(v1, v2, v, n1, iNewT1, iNewT2);
SetAdjacentTriangle(v, iT);
SetAdjacentTriangle(v3, iNewT1);
ChangeNeighbor(n2, iT, iNewT1);
ChangeNeighbor(n3, iT, iNewT2);
stack.Clear();
stack.Push(iT);
stack.Push(iNewT1);
stack.Push(iNewT2);
}
private void InsertVertexOnEdge(int v, int iT1, int iT2, bool handleFixedSplitEdge, Stack<int> stack)
{
int iTnew1 = AddTriangle();
int iTnew2 = AddTriangle();
var t1 = _triangles[iT1];
int i1 = CdtUtils.NeighborIndex(t1, iT2);
int v1 = t1.GetVertex(CdtUtils.OpposedVertexIndex(i1));
int v2 = t1.GetVertex(CdtUtils.Ccw(CdtUtils.OpposedVertexIndex(i1)));
int n1 = t1.GetNeighbor(CdtUtils.OpposedVertexIndex(i1));
int n4 = t1.GetNeighbor(CdtUtils.Cw(CdtUtils.OpposedVertexIndex(i1)));
var t2 = _triangles[iT2];
int i2 = CdtUtils.NeighborIndex(t2, iT1);
int v3 = t2.GetVertex(CdtUtils.OpposedVertexIndex(i2));
int v4 = t2.GetVertex(CdtUtils.Ccw(CdtUtils.OpposedVertexIndex(i2)));
int n3 = t2.GetNeighbor(CdtUtils.OpposedVertexIndex(i2));
int n2 = t2.GetNeighbor(CdtUtils.Cw(CdtUtils.OpposedVertexIndex(i2)));
_triangles[iT1] = new Triangle(v, v1, v2, iTnew1, n1, iT2);
_triangles[iT2] = new Triangle(v, v2, v3, iT1, n2, iTnew2);
_triangles[iTnew1] = new Triangle(v, v4, v1, iTnew2, n4, iT1);
_triangles[iTnew2] = new Triangle(v, v3, v4, iT2, n3, iTnew1);
SetAdjacentTriangle(v, iT1);
SetAdjacentTriangle(v4, iTnew1);
ChangeNeighbor(n4, iT1, iTnew1);
ChangeNeighbor(n3, iT2, iTnew2);
if (handleFixedSplitEdge)
{
var sharedEdge = new Edge(v2, v4);
if (_fixedEdges.Contains(sharedEdge))
SplitFixedEdge(sharedEdge, v);
}
stack.Clear();
stack.Push(iT1);
stack.Push(iTnew2);
stack.Push(iT2);
stack.Push(iTnew1);
}
// -------------------------------------------------------------------------
// Edge flip
// -------------------------------------------------------------------------
private void EdgeFlipInfo(
int iT, int iV1,
out int iTopo, out int iV2, out int iV3, out int iV4,
out int n1, out int n2, out int n3, out int n4)
{
var t = _triangles[iT];
if (t.V0 == iV1)
{
iV2 = t.V1; iV4 = t.V2;
n1 = t.N0; n3 = t.N2;
iTopo = t.N1;
}
else if (t.V1 == iV1)
{
iV2 = t.V2; iV4 = t.V0;
n1 = t.N1; n3 = t.N0;
iTopo = t.N2;
}
else
{
iV2 = t.V0; iV4 = t.V1;
n1 = t.N2; n3 = t.N1;
iTopo = t.N0;
}
n2 = Indices.NoNeighbor;
n4 = Indices.NoNeighbor;
iV3 = Indices.NoVertex;
if (iTopo == Indices.NoNeighbor) return;
var tOpo = _triangles[iTopo];
int oi = CdtUtils.NeighborIndex(tOpo, iT);
int ov = CdtUtils.OpposedVertexIndex(oi);
iV3 = tOpo.GetVertex(ov);
// n2 and n4 use the NEIGHBOR position (oi), not the vertex position (ov)
n2 = tOpo.GetNeighbor(CdtUtils.Ccw(oi));
n4 = tOpo.GetNeighbor(CdtUtils.Cw(oi));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool IsFlipNeeded(int iV1, int iV2, int iV3, int iV4)
{
// Skip HashSet lookup when there are no fixed edges (pure vertex-insertion path).
if (_fixedEdges.Count > 0 && _fixedEdges.Contains(new Edge(iV2, iV4))) return false;
var v1 = _vertices[iV1];
var v2 = _vertices[iV2];
var v3 = _vertices[iV3];
var v4 = _vertices[iV4];
if (_superGeomType == SuperGeometryType.SuperTriangle)
{
int st = Indices.SuperTriangleVertexCount;
if (iV1 < st)
{
if (iV2 < st)
return LocatePointLine(v2, v3, v4) == LocatePointLine(v1, v3, v4);
if (iV4 < st)
return LocatePointLine(v4, v2, v3) == LocatePointLine(v1, v2, v3);
return false;
}
if (iV3 < st)
{
if (iV2 < st)
return LocatePointLine(v2, v1, v4) == LocatePointLine(v3, v1, v4);
if (iV4 < st)
return LocatePointLine(v4, v2, v1) == LocatePointLine(v3, v2, v1);
return false;
}
if (iV2 < st)
return LocatePointLine(v2, v3, v4) == LocatePointLine(v1, v3, v4);
if (iV4 < st)
return LocatePointLine(v4, v2, v3) == LocatePointLine(v1, v2, v3);
}
return IsInCircumcircle(v1, v2, v3, v4);
}
private void FlipEdge(
int iT, int iTopo,
int v1, int v2, int v3, int v4,
int n1, int n2, int n3, int n4)
{
_triangles[iT] = new Triangle(v4, v1, v3, n3, iTopo, n4);
_triangles[iTopo] = new Triangle(v2, v3, v1, n2, iT, n1);
ChangeNeighbor(n1, iT, iTopo);
ChangeNeighbor(n4, iTopo, iT);
if (!IsFinalized)
{
SetAdjacentTriangle(v4, iT);
SetAdjacentTriangle(v2, iTopo);
}
}
// -------------------------------------------------------------------------
// Constraint edge insertion
// -------------------------------------------------------------------------
private void InsertEdgeIteration(
Edge edge, Edge originalEdge,
List<Edge> remaining,
List<TriangulatePseudoPolygonTask> tppIterations,
List<int> polyL,
List<int> polyR,
Dictionary<Edge, int> outerTris,
List<int> intersected)
{
int iA = edge.V1, iB = edge.V2;
if (iA == iB) return;
if (HasEdge(iA, iB))
{
FixEdge(edge, originalEdge);
return;
}
var a = _vertices[iA];
var b = _vertices[iB];
T distTol = _minDistToConstraintEdge == T.Zero
? T.Zero
: _minDistToConstraintEdge * CdtUtils.Distance(a, b);
var (iT, iVL, iVR) = IntersectedTriangle(iA, a, b, distTol);
if (iT == Indices.NoNeighbor)
{
var edgePart = new Edge(iA, iVL);
FixEdge(edgePart, originalEdge);
remaining.Add(new Edge(iVL, iB));
return;
}
polyL.Clear();
polyR.Clear();
outerTris.Clear();
intersected.Clear();
polyL.Add(iA); polyL.Add(iVL);
polyR.Add(iA); polyR.Add(iVR);
outerTris[new Edge(iA, iVL)] = CdtUtils.EdgeNeighbor(_triangles[iT], iA, iVL);
outerTris[new Edge(iA, iVR)] = CdtUtils.EdgeNeighbor(_triangles[iT], iA, iVR);
intersected.Add(iT);
int iV = iA;
var t = _triangles[iT];
while (!t.ContainsVertex(iB))
{
int iTopo = CdtUtils.OpposedTriangle(t, iV);
var tOpo = _triangles[iTopo];
int iVopo = CdtUtils.OpposedVertex(tOpo, iT);
HandleIntersectingEdgeStrategy(iVL, iVR, iA, iB, iT, iTopo, originalEdge, a, b, distTol, remaining, tppIterations, out bool @return);
if (@return) return;
var loc = LocatePointLine(_vertices[iVopo], a, b, distTol);
if (loc == PtLineLocation.Left)
{
var e = new Edge(polyL[^1], iVopo);
int outer = CdtUtils.EdgeNeighbor(tOpo, e.V1, e.V2);
if (!outerTris.TryAdd(e, outer)) outerTris[e] = Indices.NoNeighbor;
polyL.Add(iVopo);
iV = iVL;
iVL = iVopo;
}
else if (loc == PtLineLocation.Right)
{
var e = new Edge(polyR[^1], iVopo);
int outer = CdtUtils.EdgeNeighbor(tOpo, e.V1, e.V2);
if (!outerTris.TryAdd(e, outer)) outerTris[e] = Indices.NoNeighbor;
polyR.Add(iVopo);
iV = iVR;
iVR = iVopo;
}
else // on line
{
iB = iVopo;
}
intersected.Add(iTopo);
iT = iTopo;
t = _triangles[iT];
}
outerTris[new Edge(polyL[^1], iB)] = CdtUtils.EdgeNeighbor(t, polyL[^1], iB);
outerTris[new Edge(polyR[^1], iB)] = CdtUtils.EdgeNeighbor(t, polyR[^1], iB);
polyL.Add(iB);
polyR.Add(iB);
// Ensure start/end vertices have valid non-intersected triangle
if (_vertTris[iA] == intersected[0]) PivotVertexTriangleCW(iA);
if (_vertTris[iB] == intersected[^1]) PivotVertexTriangleCW(iB);
polyR.Reverse();
// Re-use intersected triangles
int iTL = intersected[^1]; intersected.RemoveAt(intersected.Count - 1);
int iTR = intersected[^1]; intersected.RemoveAt(intersected.Count - 1);
TriangulatePseudoPolygon(polyL, outerTris, iTL, iTR, intersected, tppIterations);
TriangulatePseudoPolygon(polyR, outerTris, iTR, iTL, intersected, tppIterations);
if (iB != edge.V2)
{
FixEdge(new Edge(iA, iB), originalEdge);
remaining.Add(new Edge(iB, edge.V2));
}
else
{
FixEdge(edge, originalEdge);
}
}
private void HandleIntersectingEdgeStrategy(
int iVL, int iVR, int iA, int iB, int iT, int iTopo,
Edge originalEdge, V2d<T> a, V2d<T> b, T distTol,
List<Edge> remaining, List<TriangulatePseudoPolygonTask> tppIterations,
out bool @return)
{
@return = false;
var edgeLR = new Edge(iVL, iVR);
switch (_intersectingEdgesStrategy)
{
case IntersectingConstraintEdges.NotAllowed:
if (_fixedEdges.Contains(edgeLR))
{
var e1 = originalEdge;
var e2 = edgeLR;
if (_pieceToOriginals.TryGetValue(e2, out var origE2) && origE2.Count > 0) e2 = origE2[0];
e1 = new Edge(e1.V1 - _nTargetVerts, e1.V2 - _nTargetVerts);
e2 = new Edge(e2.V1 - _nTargetVerts, e2.V2 - _nTargetVerts);
throw new IntersectingConstraintsException(e1, e2);
}
break;
case IntersectingConstraintEdges.TryResolve:
if (_fixedEdges.Contains(edgeLR))
{
var newV = IntersectionPosition(_vertices[iA], _vertices[iB], _vertices[iVL], _vertices[iVR]);
int iNewVert = SplitFixedEdgeAt(edgeLR, newV, iT, iTopo);
remaining.Add(new Edge(iA, iNewVert));
remaining.Add(new Edge(iNewVert, iB));
@return = true;
}
break;
}
}