-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
path_intersection.go
1382 lines (1255 loc) · 35.9 KB
/
path_intersection.go
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
package canvas
import (
"fmt"
"io"
"math"
"slices"
"sort"
"strings"
"sync"
)
// RayIntersections returns the intersections of a path with a ray starting at (x,y) to (∞,y).
// An intersection is tangent only when it is at (x,y), i.e. the start of the ray. Intersections
// are sorted along the ray. This function runs in O(n) with n the number of path segments.
func (p *Path) RayIntersections(x, y float64) []Intersection {
var start, end Point
var zs []Intersection
for i := 0; i < len(p.d); {
cmd := p.d[i]
switch cmd {
case MoveToCmd:
end = Point{p.d[i+1], p.d[i+2]}
case LineToCmd, CloseCmd:
end = Point{p.d[i+1], p.d[i+2]}
ymin := math.Min(start.Y, end.Y)
ymax := math.Max(start.Y, end.Y)
xmax := math.Max(start.X, end.X)
if Interval(y, ymin, ymax) && x <= xmax+Epsilon {
zs = intersectionLineLine(zs, Point{x, y}, Point{xmax + 1.0, y}, start, end)
}
case QuadToCmd:
cp := Point{p.d[i+1], p.d[i+2]}
end = Point{p.d[i+3], p.d[i+4]}
ymin := math.Min(math.Min(start.Y, end.Y), cp.Y)
ymax := math.Max(math.Max(start.Y, end.Y), cp.Y)
xmax := math.Max(math.Max(start.X, end.X), cp.X)
if Interval(y, ymin, ymax) && x <= xmax+Epsilon {
zs = intersectionLineQuad(zs, Point{x, y}, Point{xmax + 1.0, y}, start, cp, end)
}
case CubeToCmd:
cp1 := Point{p.d[i+1], p.d[i+2]}
cp2 := Point{p.d[i+3], p.d[i+4]}
end = Point{p.d[i+5], p.d[i+6]}
ymin := math.Min(math.Min(start.Y, end.Y), math.Min(cp1.Y, cp2.Y))
ymax := math.Max(math.Max(start.Y, end.Y), math.Max(cp1.Y, cp2.Y))
xmax := math.Max(math.Max(start.X, end.X), math.Max(cp1.X, cp2.X))
if Interval(y, ymin, ymax) && x <= xmax+Epsilon {
zs = intersectionLineCube(zs, Point{x, y}, Point{xmax + 1.0, y}, start, cp1, cp2, end)
}
case ArcToCmd:
rx, ry, phi := p.d[i+1], p.d[i+2], p.d[i+3]
large, sweep := toArcFlags(p.d[i+4])
end = Point{p.d[i+5], p.d[i+6]}
cx, cy, theta0, theta1 := ellipseToCenter(start.X, start.Y, rx, ry, phi, large, sweep, end.X, end.Y)
if Interval(y, cy-math.Max(rx, ry), cy+math.Max(rx, ry)) && x <= cx+math.Max(rx, ry)+Epsilon {
zs = intersectionLineEllipse(zs, Point{x, y}, Point{cx + rx + 1.0, y}, Point{cx, cy}, Point{rx, ry}, phi, theta0, theta1)
}
}
i += cmdLen(cmd)
start = end
}
for i := range zs {
if zs[i].T[0] != 0.0 {
zs[i].T[0] = math.NaN()
}
}
sort.SliceStable(zs, func(i, j int) bool {
if Equal(zs[i].X, zs[j].X) {
return false
}
return zs[i].X < zs[j].X
})
return zs
}
type pathOp int
const (
opSettle pathOp = iota
opAND
opOR
opNOT
opXOR
)
var boPointPool *sync.Pool
var boNodePool *sync.Pool
var boInitPoolsOnce = sync.OnceFunc(func() {
boPointPool = &sync.Pool{New: func() any { return &SweepPoint{} }}
boNodePool = &sync.Pool{New: func() any { return &SweepNode{} }}
})
// Settle returns the "settled" path. It removes all self-intersections, orients all filling paths
// CCW and all holes CW, and tries to split into subpaths if possible. Note that path p is
// flattened unless q is already flat. Path q is implicitly closed. It runs in O((n + k) log n),
// with n the sum of the number of segments, and k the number of intersections.
func (p *Path) Settle(fillRule FillRule) *Path {
return bentleyOttmann(p.Split(), nil, opSettle, fillRule)
}
func (ps Paths) Settle(fillRule FillRule) *Path {
return bentleyOttmann(ps, nil, opSettle, fillRule)
}
// And returns the boolean path operation of path p AND q, i.e. the intersection of both. It
// removes all self-intersections, orients all filling paths CCW and all holes CW, and tries to
// split into subpaths if possible. Note that path p is flattened unless q is already flat. Path
// q is implicitly closed. It runs in O((n + k) log n), with n the sum of the number of segments,
// and k the number of intersections.
func (p *Path) And(q *Path) *Path {
return bentleyOttmann(p.Split(), q.Split(), opAND, NonZero)
}
func (ps Paths) And(qs Paths) *Path {
return bentleyOttmann(ps, qs, opAND, NonZero)
}
// Or returns the boolean path operation of path p OR q, i.e. the union of both. It
// removes all self-intersections, orients all filling paths CCW and all holes CW, and tries to
// split into subpaths if possible. Note that path p is flattened unless q is already flat. Path
// q is implicitly closed. It runs in O((n + k) log n), with n the sum of the number of segments,
// and k the number of intersections.
func (p *Path) Or(q *Path) *Path {
return bentleyOttmann(p.Split(), q.Split(), opOR, NonZero)
}
// Xor returns the boolean path operation of path p XOR q, i.e. the symmetric difference of both.
// It removes all self-intersections, orients all filling paths CCW and all holes CW, and tries to
// split into subpaths if possible. Note that path p is flattened unless q is already flat. Path
// q is implicitly closed. It runs in O((n + k) log n), with n the sum of the number of segments,
// and k the number of intersections.
func (p *Path) Xor(q *Path) *Path {
return bentleyOttmann(p.Split(), q.Split(), opXOR, NonZero)
}
// Not returns the boolean path operation of path p NOT q, i.e. the difference of both.
// It removes all self-intersections, orients all filling paths CCW and all holes CW, and tries to
// split into subpaths if possible. Note that path p is flattened unless q is already flat. Path
// q is implicitly closed. It runs in O((n + k) log n), with n the sum of the number of segments,
// and k the number of intersections.
func (p *Path) Not(q *Path) *Path {
return bentleyOttmann(p.Split(), q.Split(), opNOT, NonZero)
}
type SweepPoint struct {
// initial data
Point // position of this endpoint
other *SweepPoint // pointer to the other endpoint of the segment
clipping bool // is clipping polygon (otherwise is subject polygon)
segment int // segment index to distinguish self-overlapping segments
left bool // point is left-end of segment
selfWindings int // positive if segment goes left-right (or bottom-top when vertical)
vertical bool // segment is vertical
// processing the queue
node *SweepNode // used for fast accessing btree node in O(1) (instead of Find in O(log n))
otherSelfWindings int // used when merging overlapping segments
// computing sweep fields
windings int // windings of the same polygon (excluding this segment)
otherWindings int // windings of the other polygon
inResult bool // in the final result polygon
prevInResult *SweepPoint // previous (downwards) segment that is in the final result polygon
// building the polygon
index int // index into result array
processed bool
resultWindings int // windings of the resulting polygon
}
func (s SweepPoint) Increasing() bool {
return 0 < s.selfWindings
}
func (s SweepPoint) Left() Point {
if s.left {
return s.Point
}
return s.other.Point
}
func (s SweepPoint) Right() Point {
if s.left {
return s.other.Point
}
return s.Point
}
func (s SweepPoint) Start() Point {
if s.left == s.Increasing() {
return s.Point
}
return s.other.Point
}
func (s SweepPoint) End() Point {
if s.left == s.Increasing() {
return s.other.Point
}
return s.Point
}
func (s SweepPoint) String() string {
path := "P"
if s.clipping {
path = "Q"
}
return fmt.Sprintf("%s(%v−%v)", path, s.Point, s.other.Point)
}
// SweepEvents is a heap priority queue of sweep events.
type SweepEvents []*SweepPoint
func (q SweepEvents) Less(i, j int) bool {
return q[i].LessH(q[j])
}
func (q SweepEvents) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
}
func (q *SweepEvents) AddPathEndpoints(p *Path, seg int, clipping bool) int {
// TODO: change this if we allow non-flat paths
// allocate all memory at once to prevent multiple allocations/memmoves below
n := len(p.d) / 4
if cap(*q) < len(*q)+n {
q2 := make(SweepEvents, len(*q), len(*q)+n)
copy(q2, *q)
*q = q2
}
for i := 4; i < len(p.d); {
if p.d[i] != LineToCmd && p.d[i] != CloseCmd {
panic("non-flat paths not supported")
}
n := cmdLen(p.d[i])
start := Point{p.d[i-3], p.d[i-2]}
end := Point{p.d[i+n-3], p.d[i+n-2]}
i += n
seg++
if start.Equals(end) {
// skip zero-length lineTo or close command
continue
}
vertical := Equal(start.X, end.X)
increasing := start.X < end.X
if vertical {
increasing = start.Y < end.Y
}
selfWindings := 1
if !increasing {
selfWindings = -1
}
a := boPointPool.Get().(*SweepPoint)
b := boPointPool.Get().(*SweepPoint)
*a = SweepPoint{
Point: start,
clipping: clipping,
segment: seg,
left: increasing,
selfWindings: selfWindings,
vertical: vertical,
}
*b = SweepPoint{
Point: end,
clipping: clipping,
segment: seg,
left: !increasing,
selfWindings: selfWindings,
vertical: vertical,
}
a.other = b
b.other = a
*q = append(*q, a, b)
}
return seg
}
func (q SweepEvents) Init() {
n := len(q)
for i := n/2 - 1; 0 <= i; i-- {
q.down(i, n)
}
}
func (q *SweepEvents) Push(item *SweepPoint) {
*q = append(*q, item)
q.up(len(*q) - 1)
}
func (q *SweepEvents) Top() *SweepPoint {
return (*q)[0]
}
func (q *SweepEvents) Pop() *SweepPoint {
n := len(*q) - 1
q.Swap(0, n)
q.down(0, n)
items := (*q)[n]
*q = (*q)[:n]
return items
}
func (q *SweepEvents) Remove(item *SweepPoint) {
// TODO: make O(log n)
index := -1
for i := range *q {
if (*q)[i] == item {
index = i
break
}
}
n := len(*q) - 1
if index == -1 {
panic("Item not in queue")
} else if index < n {
q.Swap(index, n)
q.down(index, n)
}
*q = (*q)[:n]
}
// from container/heap
func (q SweepEvents) up(j int) {
for {
i := (j - 1) / 2 // parent
if i == j || !q.Less(j, i) {
break
}
q.Swap(i, j)
j = i
}
}
func (q SweepEvents) down(i0, n int) {
i := i0
for {
j1 := 2*i + 1
if n <= j1 || j1 < 0 { // j1 < 0 after int overflow
break
}
j := j1 // left child
if j2 := j1 + 1; j2 < n && q.Less(j2, j1) {
j = j2 // = 2*i + 2 // right child
}
if !q.Less(j, i) {
break
}
q.Swap(i, j)
i = j
}
}
func (q SweepEvents) Print(w io.Writer) {
q2 := make(SweepEvents, len(q))
copy(q2, q)
q = q2
n := len(q) - 1
for 0 < n {
q.Swap(0, n)
q.down(0, n)
n--
}
for k := len(q) - 1; 0 <= k; k-- {
fmt.Fprintln(w, len(q)-1-k, q[k])
}
return
}
func (q SweepEvents) String() string {
sb := strings.Builder{}
q.Print(&sb)
str := sb.String()
if 0 < len(str) {
str = str[:len(str)-1]
}
return str
}
type SweepNode struct {
parent, left, right *SweepNode
height int
*SweepPoint
}
func (n *SweepNode) Prev() *SweepNode {
// go left
if n.left != nil {
n = n.left
for n.right != nil {
n = n.right // find the right-most of current subtree
}
return n
}
for n.parent != nil && n.parent.left == n {
n = n.parent // find first parent for which we're right
}
return n.parent // can be nil
}
func (n *SweepNode) Next() *SweepNode {
// go right
if n.right != nil {
n = n.right
for n.left != nil {
n = n.left // find the left-most of current subtree
}
return n
}
for n.parent != nil && n.parent.right == n {
n = n.parent // find first parent for which we're left
}
return n.parent // can be nil
}
func (n *SweepNode) balance() int {
r := 0
if n.left != nil {
r -= n.left.height
}
if n.right != nil {
r += n.right.height
}
return r
}
func (n *SweepNode) updateHeight() {
n.height = 0
if n.left != nil {
n.height = n.left.height
}
if n.right != nil && n.height < n.right.height {
n.height = n.right.height
}
n.height++
}
func (n *SweepNode) swapChild(a, b *SweepNode) {
if n.right == a {
n.right = b
} else {
n.left = b
}
if b != nil {
b.parent = n
}
}
func (a *SweepNode) rotateLeft() *SweepNode {
b := a.right
if a.parent != nil {
a.parent.swapChild(a, b)
} else {
b.parent = nil
}
a.parent = b
if a.right = b.left; a.right != nil {
a.right.parent = a
}
b.left = a
return b
}
func (a *SweepNode) rotateRight() *SweepNode {
b := a.left
if a.parent != nil {
a.parent.swapChild(a, b)
} else {
b.parent = nil
}
a.parent = b
if a.left = b.right; a.left != nil {
a.left.parent = a
}
b.right = a
return b
}
func (n *SweepNode) Print(w io.Writer, indent int) {
if n.right != nil {
n.right.Print(w, indent+1)
} else if n.left != nil {
fmt.Fprintf(w, "%vnil\n", strings.Repeat(" ", indent+1))
}
fmt.Fprintf(w, "%v%v\n", strings.Repeat(" ", indent), n.SweepPoint)
if n.left != nil {
n.left.Print(w, indent+1)
} else if n.right != nil {
fmt.Fprintf(w, "%vnil\n", strings.Repeat(" ", indent+1))
}
}
// TODO: use AB tree with A=2 and B=16 instead of AVL, according to LEDA (S. Naber. Comparison of search-tree data structures in LEDA. Personal communication.) this was faster.
type SweepStatus struct {
root *SweepNode
}
func (s *SweepStatus) newNode(item *SweepPoint) *SweepNode {
n := boNodePool.Get().(*SweepNode)
n.parent = nil
n.left = nil
n.right = nil
n.height = 1
n.SweepPoint = item
n.SweepPoint.node = n
return n
}
func (s *SweepStatus) returnNode(n *SweepNode) {
n.SweepPoint.node = nil
n.SweepPoint = nil // help the GC
boNodePool.Put(n)
}
func (s *SweepStatus) find(item *SweepPoint) (*SweepNode, int) {
n := s.root
for n != nil {
cmp := item.CompareV(n.SweepPoint)
if cmp < 0 {
if n.left == nil {
return n, -1
}
n = n.left
} else if 0 < cmp {
if n.right == nil {
return n, 1
}
n = n.right
} else {
break
}
}
return n, 0
}
func (s *SweepStatus) rebalance(n *SweepNode) {
for {
oheight := n.height
if balance := n.balance(); balance == 2 {
// Tree is excessively right-heavy, rotate it to the left.
if n.right != nil && n.right.balance() < 0 {
// Right tree is left-heavy, which would cause the next rotation to result in
// overall left-heaviness. Rotate the right tree to the right to counteract this.
n.right = n.right.rotateRight()
n.right.right.updateHeight()
}
n = n.rotateLeft()
n.left.updateHeight()
} else if balance == -2 {
// Tree is excessively left-heavy, rotate it to the right
if n.left != nil && n.left.balance() > 0 {
// The left tree is right-heavy, which would cause the next rotation to result in
// overall right-heaviness. Rotate the left tree to the left to compensate.
n.left = n.left.rotateLeft()
n.left.left.updateHeight()
}
n = n.rotateRight()
n.right.updateHeight()
} else if balance < -2 || 2 < balance {
panic("Tree too far out of shape!")
}
n.updateHeight()
if n.parent == nil {
s.root = n
return
}
if oheight == n.height {
return
}
n = n.parent
}
}
func (s *SweepStatus) String() string {
if s.root == nil {
return "nil"
}
sb := strings.Builder{}
s.root.Print(&sb, 0)
str := sb.String()
if 0 < len(str) {
str = str[:len(str)-1]
}
return str
}
func (s *SweepStatus) First() *SweepNode {
if s.root == nil {
return nil
}
n := s.root
for n.left != nil {
n = n.left
}
return n
}
func (s *SweepStatus) Last() *SweepNode {
if s.root == nil {
return nil
}
n := s.root
for n.right != nil {
n = n.right
}
return n
}
// Find returns the node equal to item. May return nil.
func (s *SweepStatus) Find(item *SweepPoint) *SweepNode {
n, cmp := s.find(item)
if cmp == 0 {
return n
}
return nil
}
func (s *SweepStatus) FindPrevNext(item *SweepPoint) (*SweepNode, *SweepNode) {
if s.root == nil {
return nil, nil
}
n, cmp := s.find(item)
if cmp < 0 {
return n.Prev(), n
} else if 0 < cmp {
return n, n.Next()
} else {
return n.Prev(), n.Next()
}
}
func (s *SweepStatus) Insert(item *SweepPoint) *SweepNode {
if s.root == nil {
s.root = s.newNode(item)
return s.root
}
rebalance := false
n, cmp := s.find(item)
if cmp < 0 {
// lower
n.left = s.newNode(item)
n.left.parent = n
rebalance = n.right == nil
n = n.left
} else if 0 < cmp {
// higher
n.right = s.newNode(item)
n.right.parent = n
rebalance = n.left == nil
n = n.right
} else {
// equal, replace
n.SweepPoint.node = nil
n.SweepPoint = item
n.SweepPoint.node = n
return n
}
if rebalance {
n.height++
if n.parent != nil {
s.rebalance(n.parent)
}
}
return n
}
func (s *SweepStatus) InsertAfter(n *SweepNode, item *SweepPoint) *SweepNode {
rebalance := false
if n == nil {
if s.root == nil {
s.root = s.newNode(item)
return s.root
}
// insert as left-most node in tree
n = s.root
for n.left != nil {
n = n.left
}
n.left = s.newNode(item)
n.left.parent = n
rebalance = n.right == nil
n = n.left
} else if n.right == nil {
// insert directly to the right of n
n.right = s.newNode(item)
n.right.parent = n
rebalance = n.left == nil
n = n.right
} else {
// insert next to n at a deeper level
n = n.right
for n.left != nil {
n = n.left
}
n.left = s.newNode(item)
n.left.parent = n
rebalance = n.right == nil
n = n.left
}
if rebalance {
n.height++
if n.parent != nil {
s.rebalance(n.parent)
}
}
return n
}
func (s *SweepStatus) Remove(n *SweepNode) {
var o *SweepNode
for {
if n.height == 1 {
o = n.parent
if o != nil {
o.swapChild(n, nil)
s.rebalance(o)
} else {
s.root = nil
}
s.returnNode(n)
return
} else if n.right != nil {
o = n.right
for o.left != nil {
o = o.left
}
} else if n.left != nil {
o = n.left
for o.right != nil {
o = o.right
}
} else {
panic("Impossible")
}
n.SweepPoint, o.SweepPoint = o.SweepPoint, n.SweepPoint
n.SweepPoint.node, o.SweepPoint.node = n, o
n = o
}
}
func (s *SweepStatus) Clear() {
n := s.First()
for n != nil {
cur := n
n = n.Next()
boNodePool.Put(cur)
}
s.root = nil
}
func (a *SweepPoint) LessH(b *SweepPoint) bool {
// used for sweep queue
if !Equal(a.X, b.X) {
return a.X < b.X // sort left to right
} else if !Equal(a.Y, b.Y) {
return a.Y < b.Y // then bottom to top
} else if a.left != b.left {
return b.left // handle right-endpoints before left-endpoints
} else if a.compareTangentsV(b) < 0 {
return true // sort upwards, this ensures CCW orientation order of result
}
return false
}
func (a *SweepPoint) compareOverlapsV(b *SweepPoint) int {
// compare segments vertically that overlap (ie. are the same)
if a.clipping != b.clipping {
// for equal segments, clipping path is virtually to the top-right of subject path
if b.clipping {
return -1
} else {
return 1
}
}
// equal segment on same path, sort by segment index
if a.segment < b.segment {
return -1
} else {
return 1
}
}
func (a *SweepPoint) compareTangentsV(b *SweepPoint) int {
// compare segments vertically at a.X, b.X <= a.X, and a and b coincide at (a.X,a.Y)
// note that a.left==b.left, we may be comparing right-endpoints
if a.vertical {
// a is vertical
if b.vertical {
// a and b are vertical
if Equal(a.Y, b.Y) {
return a.compareOverlapsV(b)
} else if a.Y < b.Y {
return -1
} else {
return 1
}
}
return 1
} else if b.vertical {
// b is vertical
return -1
}
sign := 1
if !a.left {
sign = -1
}
if a.left && a.other.X < b.other.X || !a.left && b.other.X < a.other.X {
t := (a.other.X - b.X) / (b.other.X - b.X)
by := b.Interpolate(b.other.Point, t).Y // b's y at a's other
if Equal(a.other.Y, by) {
return sign * a.compareOverlapsV(b)
} else if a.other.Y < by {
return sign * -1
} else {
return sign * 1
}
} else {
t := (b.other.X - a.X) / (a.other.X - a.X)
ay := a.Interpolate(a.other.Point, t).Y // a's y at b's other
if Equal(ay, b.other.Y) {
return sign * a.compareOverlapsV(b)
} else if ay < b.other.Y {
return sign * -1
} else {
return sign * 1
}
}
}
func (a *SweepPoint) compareV(b *SweepPoint) int {
// compare segments vertically at a.X and b.X <= a.X
bRight := b.Right()
t := (a.X - b.X) / (bRight.X - b.X)
by := b.Point.Interpolate(bRight, t).Y // b's y at a's left
if Equal(a.Y, by) {
return a.compareTangentsV(b)
} else if a.Y < by {
return -1
} else {
return 1
}
}
func (a *SweepPoint) CompareV(b *SweepPoint) int {
// used for sweep status, a is the point to be inserted / found
if Equal(a.X, b.X) {
// left-point at same X
if Equal(a.Y, b.Y) {
// left-point the same
return a.compareTangentsV(b)
} else if a.Y < b.Y {
return -1
} else {
return 1
}
} else if a.X < b.X {
// a starts to the left of b
return -b.compareV(a)
} else {
// a starts to the right of b
return a.compareV(b)
}
}
type SweepPointPair [2]*SweepPoint
func compareIntersections(a, b Intersection) int {
if Equal(a.X, b.X) {
if Equal(a.Y, b.Y) {
return 0
} else if a.Y < b.Y {
return -1
} else {
return 1
}
} else if a.X < b.X {
return -1
} else {
return 1
}
}
func addIntersections(queue *SweepEvents, handled map[SweepPointPair]struct{}, zs Intersections, a, b *SweepPoint) bool {
// a and b are always left-endpoints and a is below b
if _, ok := handled[SweepPointPair{a, b}]; ok {
return false
} else if _, ok := handled[SweepPointPair{b, a}]; ok {
return false
}
// find all intersections between segment pair
// this returns either no intersections, or one or more secant/tangent intersections,
// or exactly two "same" intersections which occurs when the segments overlap.
zs = intersectionLineLine(zs[:0], a.Start(), a.End(), b.Start(), b.End())
// clean up intersections outside one of the segments, this may happen for nearly parallel
// lines for example
for i := 0; i < len(zs); i++ {
zs[i].Point = zs[i].Point.Gridsnap(2.0 * Epsilon) // prevent numerical issues
if z := zs[i]; !a.vertical && !Interval(z.X, a.X, a.other.X) || a.vertical && !Interval(z.Y, a.Y, a.other.Y) || !b.vertical && !Interval(z.X, b.X, b.other.X) || b.vertical && !Interval(z.Y, b.Y, b.other.Y) { //z.X < a.X || z.X < b.X || a.other.X < z.X || b.other.X < z.X {
fmt.Println("WARNING: removing intersection", zs[i], "between", a, b)
zs = append(zs[:i], zs[i+1:]...)
i--
}
}
// no (valid) intersections
if len(zs) == 0 {
handled[SweepPointPair{a, b}] = struct{}{}
return false
}
// sort intersections from left to right
slices.SortFunc(zs, compareIntersections)
// handle a
aLefts := []*SweepPoint{a}
aPrevLeft, aLastRight := a, a.other
for i, z := range zs {
if z.T[0] == 0.0 || z.T[0] == 1.0 {
// ignore tangent intersections at the endpoints
continue
} else if aPrevLeft.Point.Equals(z.Point) || i == len(zs)-1 && z.Point.Equals(aLastRight.Point) {
// ignore tangent intersections at the endpoints
continue
}
// split segment at intersection
aRight, aLeft := *a.other, *a
aRight.Point = z.Point
aLeft.Point = z.Point
// update references
aPrevLeft.other, aRight.other = &aRight, aPrevLeft
// add to queue
queue.Push(&aRight)
aLefts = append(aLefts, &aLeft)
aPrevLeft = &aLeft
}
aPrevLeft.other, aLastRight.other = aLastRight, aPrevLeft
for _, aLeft := range aLefts[1:] {
// add to queue
queue.Push(aLeft)
}
// handle b
bLefts := []*SweepPoint{b}
bPrevLeft, bLastRight := b, b.other
for i, z := range zs {
if z.T[1] == 0.0 || z.T[1] == 1.0 {
// ignore tangent intersections at the endpoints
continue
} else if bPrevLeft.Point.Equals(z.Point) || i == len(zs)-1 && z.Point.Equals(bLastRight.Point) {
// ignore tangent intersections at the endpoints
continue
}
// split segment at intersection
bRight, bLeft := *b.other, *b
bRight.Point = z.Point
bLeft.Point = z.Point
// update references
bPrevLeft.other, bRight.other = &bRight, bPrevLeft
// add to queue
queue.Push(&bRight)
bLefts = append(bLefts, &bLeft)
bPrevLeft = &bLeft
}
bPrevLeft.other, bLastRight.other = bLastRight, bPrevLeft
for _, bLeft := range bLefts[1:] {
// add to queue
queue.Push(bLeft)
}
if zs[0].Same {
// Handle overlapping paths. Since we just split both segments above, we first find the
// segments that overlap. We then transfer all selfWindings and otherSelfWindings to the
// segment above and remove the segment below from the result.