forked from golang/geo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloop.go
1833 lines (1642 loc) · 65 KB
/
loop.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
// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package s2
import (
"fmt"
"io"
"math"
"github.com/golang/geo/r1"
"github.com/golang/geo/r3"
"github.com/golang/geo/s1"
)
// Loop represents a simple spherical polygon. It consists of a sequence
// of vertices where the first vertex is implicitly connected to the
// last. All loops are defined to have a CCW orientation, i.e. the interior of
// the loop is on the left side of the edges. This implies that a clockwise
// loop enclosing a small area is interpreted to be a CCW loop enclosing a
// very large area.
//
// Loops are not allowed to have any duplicate vertices (whether adjacent or
// not). Non-adjacent edges are not allowed to intersect, and furthermore edges
// of length 180 degrees are not allowed (i.e., adjacent vertices cannot be
// antipodal). Loops must have at least 3 vertices (except for the "empty" and
// "full" loops discussed below).
//
// There are two special loops: the "empty" loop contains no points and the
// "full" loop contains all points. These loops do not have any edges, but to
// preserve the invariant that every loop can be represented as a vertex
// chain, they are defined as having exactly one vertex each (see EmptyLoop
// and FullLoop).
type Loop struct {
vertices []Point
// originInside keeps a precomputed value whether this loop contains the origin
// versus computing from the set of vertices every time.
originInside bool
// depth is the nesting depth of this Loop if it is contained by a Polygon
// or other shape and is used to determine if this loop represents a hole
// or a filled in portion.
depth int
// bound is a conservative bound on all points contained by this loop.
// If l.ContainsPoint(P), then l.bound.ContainsPoint(P).
bound Rect
// Since bound is not exact, it is possible that a loop A contains
// another loop B whose bounds are slightly larger. subregionBound
// has been expanded sufficiently to account for this error, i.e.
// if A.Contains(B), then A.subregionBound.Contains(B.bound).
subregionBound Rect
// index is the spatial index for this Loop.
index *ShapeIndex
}
// LoopFromPoints constructs a loop from the given points.
func LoopFromPoints(pts []Point) *Loop {
l := &Loop{
vertices: pts,
index: NewShapeIndex(),
}
l.initOriginAndBound()
return l
}
// LoopFromCell constructs a loop corresponding to the given cell.
//
// Note that the loop and cell *do not* contain exactly the same set of
// points, because Loop and Cell have slightly different definitions of
// point containment. For example, a Cell vertex is contained by all
// four neighboring Cells, but it is contained by exactly one of four
// Loops constructed from those cells. As another example, the cell
// coverings of cell and LoopFromCell(cell) will be different, because the
// loop contains points on its boundary that actually belong to other cells
// (i.e., the covering will include a layer of neighboring cells).
func LoopFromCell(c Cell) *Loop {
l := &Loop{
vertices: []Point{
c.Vertex(0),
c.Vertex(1),
c.Vertex(2),
c.Vertex(3),
},
index: NewShapeIndex(),
}
l.initOriginAndBound()
return l
}
// These two points are used for the special Empty and Full loops.
var (
emptyLoopPoint = Point{r3.Vector{X: 0, Y: 0, Z: 1}}
fullLoopPoint = Point{r3.Vector{X: 0, Y: 0, Z: -1}}
)
// EmptyLoop returns a special "empty" loop.
func EmptyLoop() *Loop {
return LoopFromPoints([]Point{emptyLoopPoint})
}
// FullLoop returns a special "full" loop.
func FullLoop() *Loop {
return LoopFromPoints([]Point{fullLoopPoint})
}
// initOriginAndBound sets the origin containment for the given point and then calls
// the initialization for the bounds objects and the internal index.
func (l *Loop) initOriginAndBound() {
if len(l.vertices) < 3 {
// Check for the special "empty" and "full" loops (which have one vertex).
if !l.isEmptyOrFull() {
l.originInside = false
return
}
// This is the special empty or full loop, so the origin depends on if
// the vertex is in the southern hemisphere or not.
l.originInside = l.vertices[0].Z < 0
} else {
// Point containment testing is done by counting edge crossings starting
// at a fixed point on the sphere (OriginPoint). We need to know whether
// the reference point (OriginPoint) is inside or outside the loop before
// we can construct the ShapeIndex. We do this by first guessing that
// it is outside, and then seeing whether we get the correct containment
// result for vertex 1. If the result is incorrect, the origin must be
// inside the loop.
//
// A loop with consecutive vertices A,B,C contains vertex B if and only if
// the fixed vector R = B.Ortho is contained by the wedge ABC. The
// wedge is closed at A and open at C, i.e. the point B is inside the loop
// if A = R but not if C = R. This convention is required for compatibility
// with VertexCrossing. (Note that we can't use OriginPoint
// as the fixed vector because of the possibility that B == OriginPoint.)
l.originInside = false
v1Inside := OrderedCCW(Point{l.vertices[1].Ortho()}, l.vertices[0], l.vertices[2], l.vertices[1])
if v1Inside != l.ContainsPoint(l.vertices[1]) {
l.originInside = true
}
}
// We *must* call initBound before initializing the index, because
// initBound calls ContainsPoint which does a bounds check before using
// the index.
l.initBound()
// Create a new index and add us to it.
l.index = NewShapeIndex()
l.index.Add(l)
}
// initBound sets up the approximate bounding Rects for this loop.
func (l *Loop) initBound() {
if len(l.vertices) == 0 {
*l = *EmptyLoop()
return
}
// Check for the special "empty" and "full" loops.
if l.isEmptyOrFull() {
if l.IsEmpty() {
l.bound = EmptyRect()
} else {
l.bound = FullRect()
}
l.subregionBound = l.bound
return
}
// The bounding rectangle of a loop is not necessarily the same as the
// bounding rectangle of its vertices. First, the maximal latitude may be
// attained along the interior of an edge. Second, the loop may wrap
// entirely around the sphere (e.g. a loop that defines two revolutions of a
// candy-cane stripe). Third, the loop may include one or both poles.
// Note that a small clockwise loop near the equator contains both poles.
bounder := NewRectBounder()
for i := 0; i <= len(l.vertices); i++ { // add vertex 0 twice
bounder.AddPoint(l.Vertex(i))
}
b := bounder.RectBound()
if l.ContainsPoint(Point{r3.Vector{0, 0, 1}}) {
b = Rect{r1.Interval{b.Lat.Lo, math.Pi / 2}, s1.FullInterval()}
}
// If a loop contains the south pole, then either it wraps entirely
// around the sphere (full longitude range), or it also contains the
// north pole in which case b.Lng.IsFull() due to the test above.
// Either way, we only need to do the south pole containment test if
// b.Lng.IsFull().
if b.Lng.IsFull() && l.ContainsPoint(Point{r3.Vector{0, 0, -1}}) {
b.Lat.Lo = -math.Pi / 2
}
l.bound = b
l.subregionBound = ExpandForSubregions(l.bound)
}
// Validate checks whether this is a valid loop.
func (l *Loop) Validate() error {
if err := l.findValidationErrorNoIndex(); err != nil {
return err
}
// Check for intersections between non-adjacent edges (including at vertices)
// TODO(roberts): Once shapeutil gets findAnyCrossing uncomment this.
// return findAnyCrossing(l.index)
return nil
}
// findValidationErrorNoIndex reports whether this is not a valid loop, but
// skips checks that would require a ShapeIndex to be built for the loop. This
// is primarily used by Polygon to do validation so it doesn't trigger the
// creation of unneeded ShapeIndices.
func (l *Loop) findValidationErrorNoIndex() error {
// All vertices must be unit length.
for i, v := range l.vertices {
if !v.IsUnit() {
return fmt.Errorf("vertex %d is not unit length", i)
}
}
// Loops must have at least 3 vertices (except for empty and full).
if len(l.vertices) < 3 {
if l.isEmptyOrFull() {
return nil // Skip remaining tests.
}
return fmt.Errorf("non-empty, non-full loops must have at least 3 vertices")
}
// Loops are not allowed to have any duplicate vertices or edge crossings.
// We split this check into two parts. First we check that no edge is
// degenerate (identical endpoints). Then we check that there are no
// intersections between non-adjacent edges (including at vertices). The
// second check needs the ShapeIndex, so it does not fall within the scope
// of this method.
for i, v := range l.vertices {
if v == l.Vertex(i+1) {
return fmt.Errorf("edge %d is degenerate (duplicate vertex)", i)
}
// Antipodal vertices are not allowed.
if other := (Point{l.Vertex(i + 1).Mul(-1)}); v == other {
return fmt.Errorf("vertices %d and %d are antipodal", i,
(i+1)%len(l.vertices))
}
}
return nil
}
// Contains reports whether the region contained by this loop is a superset of the
// region contained by the given other loop.
func (l *Loop) Contains(o *Loop) bool {
// For a loop A to contain the loop B, all of the following must
// be true:
//
// (1) There are no edge crossings between A and B except at vertices.
//
// (2) At every vertex that is shared between A and B, the local edge
// ordering implies that A contains B.
//
// (3) If there are no shared vertices, then A must contain a vertex of B
// and B must not contain a vertex of A. (An arbitrary vertex may be
// chosen in each case.)
//
// The second part of (3) is necessary to detect the case of two loops whose
// union is the entire sphere, i.e. two loops that contains each other's
// boundaries but not each other's interiors.
if !l.subregionBound.Contains(o.bound) {
return false
}
// Special cases to handle either loop being empty or full.
if l.isEmptyOrFull() || o.isEmptyOrFull() {
return l.IsFull() || o.IsEmpty()
}
// Check whether there are any edge crossings, and also check the loop
// relationship at any shared vertices.
relation := &containsRelation{}
if hasCrossingRelation(l, o, relation) {
return false
}
// There are no crossings, and if there are any shared vertices then A
// contains B locally at each shared vertex.
if relation.foundSharedVertex {
return true
}
// Since there are no edge intersections or shared vertices, we just need to
// test condition (3) above. We can skip this test if we discovered that A
// contains at least one point of B while checking for edge crossings.
if !l.ContainsPoint(o.Vertex(0)) {
return false
}
// We still need to check whether (A union B) is the entire sphere.
// Normally this check is very cheap due to the bounding box precondition.
if (o.subregionBound.Contains(l.bound) || o.bound.Union(l.bound).IsFull()) &&
o.ContainsPoint(l.Vertex(0)) {
return false
}
return true
}
// Intersects reports whether the region contained by this loop intersects the region
// contained by the other loop.
func (l *Loop) Intersects(o *Loop) bool {
// Given two loops, A and B, A.Intersects(B) if and only if !A.Complement().Contains(B).
//
// This code is similar to Contains, but is optimized for the case
// where both loops enclose less than half of the sphere.
if !l.bound.Intersects(o.bound) {
return false
}
// Check whether there are any edge crossings, and also check the loop
// relationship at any shared vertices.
relation := &intersectsRelation{}
if hasCrossingRelation(l, o, relation) {
return true
}
if relation.foundSharedVertex {
return false
}
// Since there are no edge intersections or shared vertices, the loops
// intersect only if A contains B, B contains A, or the two loops contain
// each other's boundaries. These checks are usually cheap because of the
// bounding box preconditions. Note that neither loop is empty (because of
// the bounding box check above), so it is safe to access vertex(0).
// Check whether A contains B, or A and B contain each other's boundaries.
// (Note that A contains all the vertices of B in either case.)
if l.subregionBound.Contains(o.bound) || l.bound.Union(o.bound).IsFull() {
if l.ContainsPoint(o.Vertex(0)) {
return true
}
}
// Check whether B contains A.
if o.subregionBound.Contains(l.bound) {
if o.ContainsPoint(l.Vertex(0)) {
return true
}
}
return false
}
// Equal reports whether two loops have the same vertices in the same linear order
// (i.e., cyclic rotations are not allowed).
func (l *Loop) Equal(other *Loop) bool {
if len(l.vertices) != len(other.vertices) {
return false
}
for i, v := range l.vertices {
if v != other.Vertex(i) {
return false
}
}
return true
}
// BoundaryEqual reports whether the two loops have the same boundary. This is
// true if and only if the loops have the same vertices in the same cyclic order
// (i.e., the vertices may be cyclically rotated). The empty and full loops are
// considered to have different boundaries.
func (l *Loop) BoundaryEqual(o *Loop) bool {
if len(l.vertices) != len(o.vertices) {
return false
}
// Special case to handle empty or full loops. Since they have the same
// number of vertices, if one loop is empty/full then so is the other.
if l.isEmptyOrFull() {
return l.IsEmpty() == o.IsEmpty()
}
// Loop through the vertices to find the first of ours that matches the
// starting vertex of the other loop. Use that offset to then 'align' the
// vertices for comparison.
for offset, vertex := range l.vertices {
if vertex == o.Vertex(0) {
// There is at most one starting offset since loop vertices are unique.
for i := 0; i < len(l.vertices); i++ {
if l.Vertex(i+offset) != o.Vertex(i) {
return false
}
}
return true
}
}
return false
}
// compareBoundary returns +1 if this loop contains the boundary of the other loop,
// -1 if it excludes the boundary of the other, and 0 if the boundaries of the two
// loops cross. Shared edges are handled as follows:
//
// If XY is a shared edge, define Reversed(XY) to be true if XY
// appears in opposite directions in both loops.
// Then this loop contains XY if and only if Reversed(XY) == the other loop is a hole.
// (Intuitively, this checks whether this loop contains a vanishingly small region
// extending from the boundary of the other toward the interior of the polygon to
// which the other belongs.)
//
// This function is used for testing containment and intersection of
// multi-loop polygons. Note that this method is not symmetric, since the
// result depends on the direction of this loop but not on the direction of
// the other loop (in the absence of shared edges).
//
// This requires that neither loop is empty, and if other loop IsFull, then it must not
// be a hole.
func (l *Loop) compareBoundary(o *Loop) int {
// The bounds must intersect for containment or crossing.
if !l.bound.Intersects(o.bound) {
return -1
}
// Full loops are handled as though the loop surrounded the entire sphere.
if l.IsFull() {
return 1
}
if o.IsFull() {
return -1
}
// Check whether there are any edge crossings, and also check the loop
// relationship at any shared vertices.
relation := newCompareBoundaryRelation(o.IsHole())
if hasCrossingRelation(l, o, relation) {
return 0
}
if relation.foundSharedVertex {
if relation.containsEdge {
return 1
}
return -1
}
// There are no edge intersections or shared vertices, so we can check
// whether A contains an arbitrary vertex of B.
if l.ContainsPoint(o.Vertex(0)) {
return 1
}
return -1
}
// ContainsOrigin reports true if this loop contains s2.OriginPoint().
func (l *Loop) ContainsOrigin() bool {
return l.originInside
}
// ReferencePoint returns the reference point for this loop.
func (l *Loop) ReferencePoint() ReferencePoint {
return OriginReferencePoint(l.originInside)
}
// NumEdges returns the number of edges in this shape.
func (l *Loop) NumEdges() int {
if l.isEmptyOrFull() {
return 0
}
return len(l.vertices)
}
// Edge returns the endpoints for the given edge index.
func (l *Loop) Edge(i int) Edge {
return Edge{l.Vertex(i), l.Vertex(i + 1)}
}
// NumChains reports the number of contiguous edge chains in the Loop.
func (l *Loop) NumChains() int {
if l.IsEmpty() {
return 0
}
return 1
}
// Chain returns the i-th edge chain in the Shape.
func (l *Loop) Chain(chainID int) Chain {
return Chain{0, l.NumEdges()}
}
// ChainEdge returns the j-th edge of the i-th edge chain.
func (l *Loop) ChainEdge(chainID, offset int) Edge {
return Edge{l.Vertex(offset), l.Vertex(offset + 1)}
}
// ChainPosition returns a ChainPosition pair (i, j) such that edgeID is the
// j-th edge of the Loop.
func (l *Loop) ChainPosition(edgeID int) ChainPosition {
return ChainPosition{0, edgeID}
}
// Dimension returns the dimension of the geometry represented by this Loop.
func (l *Loop) Dimension() int { return 2 }
func (l *Loop) typeTag() typeTag { return typeTagNone }
func (l *Loop) privateInterface() {}
// IsEmpty reports true if this is the special empty loop that contains no points.
func (l *Loop) IsEmpty() bool {
return l.isEmptyOrFull() && !l.ContainsOrigin()
}
// IsFull reports true if this is the special full loop that contains all points.
func (l *Loop) IsFull() bool {
return l.isEmptyOrFull() && l.ContainsOrigin()
}
// isEmptyOrFull reports true if this loop is either the "empty" or "full" special loops.
func (l *Loop) isEmptyOrFull() bool {
return len(l.vertices) == 1
}
// Vertices returns the vertices in the loop.
func (l *Loop) Vertices() []Point {
return l.vertices
}
// RectBound returns a tight bounding rectangle. If the loop contains the point,
// the bound also contains it.
func (l *Loop) RectBound() Rect {
return l.bound
}
// CapBound returns a bounding cap that may have more padding than the corresponding
// RectBound. The bound is conservative such that if the loop contains a point P,
// the bound also contains it.
func (l *Loop) CapBound() Cap {
return l.bound.CapBound()
}
// Vertex returns the vertex for the given index. For convenience, the vertex indices
// wrap automatically for methods that do index math such as Edge.
// i.e., Vertex(NumEdges() + n) is the same as Vertex(n).
func (l *Loop) Vertex(i int) Point {
return l.vertices[i%len(l.vertices)]
}
// OrientedVertex returns the vertex in reverse order if the loop represents a polygon
// hole. For example, arguments 0, 1, 2 are mapped to vertices n-1, n-2, n-3, where
// n == len(vertices). This ensures that the interior of the polygon is always to
// the left of the vertex chain.
//
// This requires: 0 <= i < 2 * len(vertices)
func (l *Loop) OrientedVertex(i int) Point {
j := i - len(l.vertices)
if j < 0 {
j = i
}
if l.IsHole() {
j = len(l.vertices) - 1 - j
}
return l.Vertex(j)
}
// NumVertices returns the number of vertices in this loop.
func (l *Loop) NumVertices() int {
return len(l.vertices)
}
// bruteForceContainsPoint reports if the given point is contained by this loop.
// This method does not use the ShapeIndex, so it is only preferable below a certain
// size of loop.
func (l *Loop) bruteForceContainsPoint(p Point) bool {
origin := OriginPoint()
inside := l.originInside
crosser := NewChainEdgeCrosser(origin, p, l.Vertex(0))
for i := 1; i <= len(l.vertices); i++ { // add vertex 0 twice
inside = inside != crosser.EdgeOrVertexChainCrossing(l.Vertex(i))
}
return inside
}
// ContainsPoint returns true if the loop contains the point.
func (l *Loop) ContainsPoint(p Point) bool {
if !l.index.IsFresh() && !l.bound.ContainsPoint(p) {
return false
}
// For small loops it is faster to just check all the crossings. We also
// use this method during loop initialization because InitOriginAndBound()
// calls Contains() before InitIndex(). Otherwise, we keep track of the
// number of calls to Contains() and only build the index when enough calls
// have been made so that we think it is worth the effort. Note that the
// code below is structured so that if many calls are made in parallel only
// one thread builds the index, while the rest continue using brute force
// until the index is actually available.
const maxBruteForceVertices = 32
// TODO(roberts): add unindexed contains calls tracking
if len(l.index.shapes) == 0 || // Index has not been initialized yet.
len(l.vertices) <= maxBruteForceVertices {
return l.bruteForceContainsPoint(p)
}
// Otherwise, look up the point in the index.
it := l.index.Iterator()
if !it.LocatePoint(p) {
return false
}
return l.iteratorContainsPoint(it, p)
}
// ContainsCell reports whether the given Cell is contained by this Loop.
func (l *Loop) ContainsCell(target Cell) bool {
it := l.index.Iterator()
relation := it.LocateCellID(target.ID())
// If "target" is disjoint from all index cells, it is not contained.
// Similarly, if "target" is subdivided into one or more index cells then it
// is not contained, since index cells are subdivided only if they (nearly)
// intersect a sufficient number of edges. (But note that if "target" itself
// is an index cell then it may be contained, since it could be a cell with
// no edges in the loop interior.)
if relation != Indexed {
return false
}
// Otherwise check if any edges intersect "target".
if l.boundaryApproxIntersects(it, target) {
return false
}
// Otherwise check if the loop contains the center of "target".
return l.iteratorContainsPoint(it, target.Center())
}
// IntersectsCell reports whether this Loop intersects the given cell.
func (l *Loop) IntersectsCell(target Cell) bool {
it := l.index.Iterator()
relation := it.LocateCellID(target.ID())
// If target does not overlap any index cell, there is no intersection.
if relation == Disjoint {
return false
}
// If target is subdivided into one or more index cells, there is an
// intersection to within the ShapeIndex error bound (see Contains).
if relation == Subdivided {
return true
}
// If target is an index cell, there is an intersection because index cells
// are created only if they have at least one edge or they are entirely
// contained by the loop.
if it.CellID() == target.id {
return true
}
// Otherwise check if any edges intersect target.
if l.boundaryApproxIntersects(it, target) {
return true
}
// Otherwise check if the loop contains the center of target.
return l.iteratorContainsPoint(it, target.Center())
}
// CellUnionBound computes a covering of the Loop.
func (l *Loop) CellUnionBound() []CellID {
return l.CapBound().CellUnionBound()
}
// boundaryApproxIntersects reports if the loop's boundary intersects target.
// It may also return true when the loop boundary does not intersect target but
// some edge comes within the worst-case error tolerance.
//
// This requires that it.Locate(target) returned Indexed.
func (l *Loop) boundaryApproxIntersects(it *ShapeIndexIterator, target Cell) bool {
aClipped := it.IndexCell().findByShapeID(0)
// If there are no edges, there is no intersection.
if len(aClipped.edges) == 0 {
return false
}
// We can save some work if target is the index cell itself.
if it.CellID() == target.ID() {
return true
}
// Otherwise check whether any of the edges intersect target.
maxError := (faceClipErrorUVCoord + intersectsRectErrorUVDist)
bound := target.BoundUV().ExpandedByMargin(maxError)
for _, ai := range aClipped.edges {
v0, v1, ok := ClipToPaddedFace(l.Vertex(ai), l.Vertex(ai+1), target.Face(), maxError)
if ok && edgeIntersectsRect(v0, v1, bound) {
return true
}
}
return false
}
// iteratorContainsPoint reports if the iterator that is positioned at the ShapeIndexCell
// that may contain p, contains the point p.
func (l *Loop) iteratorContainsPoint(it *ShapeIndexIterator, p Point) bool {
// Test containment by drawing a line segment from the cell center to the
// given point and counting edge crossings.
aClipped := it.IndexCell().findByShapeID(0)
inside := aClipped.containsCenter
if len(aClipped.edges) > 0 {
center := it.Center()
crosser := NewEdgeCrosser(center, p)
aiPrev := -2
for _, ai := range aClipped.edges {
if ai != aiPrev+1 {
crosser.RestartAt(l.Vertex(ai))
}
aiPrev = ai
inside = inside != crosser.EdgeOrVertexChainCrossing(l.Vertex(ai+1))
}
}
return inside
}
// RegularLoop creates a loop with the given number of vertices, all
// located on a circle of the specified radius around the given center.
func RegularLoop(center Point, radius s1.Angle, numVertices int) *Loop {
return RegularLoopForFrame(getFrame(center), radius, numVertices)
}
// RegularLoopForFrame creates a loop centered around the z-axis of the given
// coordinate frame, with the first vertex in the direction of the positive x-axis.
func RegularLoopForFrame(frame matrix3x3, radius s1.Angle, numVertices int) *Loop {
return LoopFromPoints(regularPointsForFrame(frame, radius, numVertices))
}
// CanonicalFirstVertex returns a first index and a direction (either +1 or -1)
// such that the vertex sequence (first, first+dir, ..., first+(n-1)*dir) does
// not change when the loop vertex order is rotated or inverted. This allows the
// loop vertices to be traversed in a canonical order. The return values are
// chosen such that (first, ..., first+n*dir) are in the range [0, 2*n-1] as
// expected by the Vertex method.
func (l *Loop) CanonicalFirstVertex() (firstIdx, direction int) {
firstIdx = 0
n := len(l.vertices)
for i := 1; i < n; i++ {
if l.Vertex(i).Cmp(l.Vertex(firstIdx).Vector) == -1 {
firstIdx = i
}
}
// 0 <= firstIdx <= n-1, so (firstIdx+n*dir) <= 2*n-1.
if l.Vertex(firstIdx+1).Cmp(l.Vertex(firstIdx+n-1).Vector) == -1 {
return firstIdx, 1
}
// n <= firstIdx <= 2*n-1, so (firstIdx+n*dir) >= 0.
firstIdx += n
return firstIdx, -1
}
// TurningAngle returns the sum of the turning angles at each vertex. The return
// value is positive if the loop is counter-clockwise, negative if the loop is
// clockwise, and zero if the loop is a great circle. Degenerate and
// nearly-degenerate loops are handled consistently with Sign. So for example,
// if a loop has zero area (i.e., it is a very small CCW loop) then the turning
// angle will always be negative.
//
// This quantity is also called the "geodesic curvature" of the loop.
func (l *Loop) TurningAngle() float64 {
// For empty and full loops, we return the limit value as the loop area
// approaches 0 or 4*Pi respectively.
if l.isEmptyOrFull() {
if l.ContainsOrigin() {
return -2 * math.Pi
}
return 2 * math.Pi
}
// Don't crash even if the loop is not well-defined.
if len(l.vertices) < 3 {
return 0
}
// To ensure that we get the same result when the vertex order is rotated,
// and that the result is negated when the vertex order is reversed, we need
// to add up the individual turn angles in a consistent order. (In general,
// adding up a set of numbers in a different order can change the sum due to
// rounding errors.)
//
// Furthermore, if we just accumulate an ordinary sum then the worst-case
// error is quadratic in the number of vertices. (This can happen with
// spiral shapes, where the partial sum of the turning angles can be linear
// in the number of vertices.) To avoid this we use the Kahan summation
// algorithm (http://en.wikipedia.org/wiki/Kahan_summation_algorithm).
n := len(l.vertices)
i, dir := l.CanonicalFirstVertex()
sum := TurnAngle(l.Vertex((i+n-dir)%n), l.Vertex(i), l.Vertex((i+dir)%n))
compensation := s1.Angle(0)
for n-1 > 0 {
i += dir
angle := TurnAngle(l.Vertex(i-dir), l.Vertex(i), l.Vertex(i+dir))
oldSum := sum
angle += compensation
sum += angle
compensation = (oldSum - sum) + angle
n--
}
const maxCurvature = 2*math.Pi - 4*dblEpsilon
return math.Max(-maxCurvature, math.Min(maxCurvature, float64(dir)*float64(sum+compensation)))
}
// turningAngleMaxError return the maximum error in TurningAngle. The value is not
// constant; it depends on the loop.
func (l *Loop) turningAngleMaxError() float64 {
// The maximum error can be bounded as follows:
// 3.00 * dblEpsilon for RobustCrossProd(b, a)
// 3.00 * dblEpsilon for RobustCrossProd(c, b)
// 3.25 * dblEpsilon for Angle()
// 2.00 * dblEpsilon for each addition in the Kahan summation
// ------------------
// 11.25 * dblEpsilon
maxErrorPerVertex := 11.25 * dblEpsilon
return maxErrorPerVertex * float64(len(l.vertices))
}
// IsHole reports whether this loop represents a hole in its containing polygon.
func (l *Loop) IsHole() bool { return l.depth&1 != 0 }
// Sign returns -1 if this Loop represents a hole in its containing polygon, and +1 otherwise.
func (l *Loop) Sign() int {
if l.IsHole() {
return -1
}
return 1
}
// IsNormalized reports whether the loop area is at most 2*pi. Degenerate loops are
// handled consistently with Sign, i.e., if a loop can be
// expressed as the union of degenerate or nearly-degenerate CCW triangles,
// then it will always be considered normalized.
func (l *Loop) IsNormalized() bool {
// Optimization: if the longitude span is less than 180 degrees, then the
// loop covers less than half the sphere and is therefore normalized.
if l.bound.Lng.Length() < math.Pi {
return true
}
// We allow some error so that hemispheres are always considered normalized.
// TODO(roberts): This is no longer required by the Polygon implementation,
// so alternatively we could create the invariant that a loop is normalized
// if and only if its complement is not normalized.
return l.TurningAngle() >= -l.turningAngleMaxError()
}
// Normalize inverts the loop if necessary so that the area enclosed by the loop
// is at most 2*pi.
func (l *Loop) Normalize() {
if !l.IsNormalized() {
l.Invert()
}
}
// Invert reverses the order of the loop vertices, effectively complementing the
// region represented by the loop. For example, the loop ABCD (with edges
// AB, BC, CD, DA) becomes the loop DCBA (with edges DC, CB, BA, AD).
// Notice that the last edge is the same in both cases except that its
// direction has been reversed.
func (l *Loop) Invert() {
l.index.Reset()
if l.isEmptyOrFull() {
if l.IsFull() {
l.vertices[0] = emptyLoopPoint
} else {
l.vertices[0] = fullLoopPoint
}
} else {
// For non-special loops, reverse the slice of vertices.
for i := len(l.vertices)/2 - 1; i >= 0; i-- {
opp := len(l.vertices) - 1 - i
l.vertices[i], l.vertices[opp] = l.vertices[opp], l.vertices[i]
}
}
// originInside must be set correctly before building the ShapeIndex.
l.originInside = !l.originInside
if l.bound.Lat.Lo > -math.Pi/2 && l.bound.Lat.Hi < math.Pi/2 {
// The complement of this loop contains both poles.
l.bound = FullRect()
l.subregionBound = l.bound
} else {
l.initBound()
}
l.index.Add(l)
}
// findVertex returns the index of the vertex at the given Point in the range
// 1..numVertices, and a boolean indicating if a vertex was found.
func (l *Loop) findVertex(p Point) (index int, ok bool) {
const notFound = 0
if len(l.vertices) < 10 {
// Exhaustive search for loops below a small threshold.
for i := 1; i <= len(l.vertices); i++ {
if l.Vertex(i) == p {
return i, true
}
}
return notFound, false
}
it := l.index.Iterator()
if !it.LocatePoint(p) {
return notFound, false
}
aClipped := it.IndexCell().findByShapeID(0)
for i := aClipped.numEdges() - 1; i >= 0; i-- {
ai := aClipped.edges[i]
if l.Vertex(ai) == p {
if ai == 0 {
return len(l.vertices), true
}
return ai, true
}
if l.Vertex(ai+1) == p {
return ai + 1, true
}
}
return notFound, false
}
// ContainsNested reports whether the given loops is contained within this loop.
// This function does not test for edge intersections. The two loops must meet
// all of the Polygon requirements; for example this implies that their
// boundaries may not cross or have any shared edges (although they may have
// shared vertices).
func (l *Loop) ContainsNested(other *Loop) bool {
if !l.subregionBound.Contains(other.bound) {
return false
}
// Special cases to handle either loop being empty or full. Also bail out
// when B has no vertices to avoid heap overflow on the vertex(1) call
// below. (This method is called during polygon initialization before the
// client has an opportunity to call IsValid().)
if l.isEmptyOrFull() || other.NumVertices() < 2 {
return l.IsFull() || other.IsEmpty()
}
// We are given that A and B do not share any edges, and that either one
// loop contains the other or they do not intersect.
m, ok := l.findVertex(other.Vertex(1))
if !ok {
// Since other.vertex(1) is not shared, we can check whether A contains it.
return l.ContainsPoint(other.Vertex(1))
}
// Check whether the edge order around other.Vertex(1) is compatible with
// A containing B.
return WedgeContains(l.Vertex(m-1), l.Vertex(m), l.Vertex(m+1), other.Vertex(0), other.Vertex(2))
}
// surfaceIntegralFloat64 computes the oriented surface integral of some quantity f(x)
// over the loop interior, given a function f(A,B,C) that returns the
// corresponding integral over the spherical triangle ABC. Here "oriented
// surface integral" means:
//
// (1) f(A,B,C) must be the integral of f if ABC is counterclockwise,
// and the integral of -f if ABC is clockwise.
//
// (2) The result of this function is *either* the integral of f over the
// loop interior, or the integral of (-f) over the loop exterior.
//
// Note that there are at least two common situations where it easy to work
// around property (2) above:
//
// - If the integral of f over the entire sphere is zero, then it doesn't
// matter which case is returned because they are always equal.
//
// - If f is non-negative, then it is easy to detect when the integral over
// the loop exterior has been returned, and the integral over the loop
// interior can be obtained by adding the integral of f over the entire
// unit sphere (a constant) to the result.
//
// Any changes to this method may need corresponding changes to surfaceIntegralPoint as well.
func (l *Loop) surfaceIntegralFloat64(f func(a, b, c Point) float64) float64 {
// We sum f over a collection T of oriented triangles, possibly