1 // Copyright 2005 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 
16 // Author: ericv@google.com (Eric Veach)
17 
18 #ifndef S2_S2POLYGON_H_
19 #define S2_S2POLYGON_H_
20 
21 #include <atomic>
22 #include <cstddef>
23 #include <map>
24 #include <vector>
25 
26 #include "s2/base/integral_types.h"
27 #include "s2/third_party/absl/base/macros.h"
28 #include "s2/_fp_contract_off.h"
29 #include "s2/mutable_s2shape_index.h"
30 #include "s2/s1angle.h"
31 #include "s2/s2boolean_operation.h"
32 #include "s2/s2builder.h"
33 #include "s2/s2cell_id.h"
34 #include "s2/s2debug.h"
35 #include "s2/s2latlng_rect.h"
36 #include "s2/s2loop.h"
37 #include "s2/s2polyline.h"
38 #include "s2/s2region.h"
39 #include "s2/s2shape_index.h"
40 
41 class Decoder;
42 class Encoder;
43 class S1Angle;
44 class S2Cap;
45 class S2Cell;
46 class S2CellUnion;
47 class S2Error;
48 class S2Loop;
49 class S2PolygonBuilder;
50 class S2Polyline;
51 struct S2XYZFaceSiTi;
52 
53 // An S2Polygon is an S2Region object that represents a polygon.  A polygon is
54 // defined by zero or more loops; recall that the interior of a loop is
55 // defined to be its left-hand side (see S2Loop).  There are two different
56 // conventions for creating an S2Polygon:
57 //
58 //   - InitNested() expects the input loops to be nested hierarchically.  The
59 //     polygon interior then consists of the set of points contained by an odd
60 //     number of loops.  So for example, a circular region with a hole in it
61 //     would be defined as two CCW loops, with one loop containing the other.
62 //     The loops can be provided in any order.
63 //
64 //     When the orientation of the input loops is unknown, the nesting
65 //     requirement is typically met by calling S2Loop::Normalize() on each
66 //     loop (which inverts the loop if necessary so that it encloses at most
67 //     half the sphere).  But in fact any set of loops can be used as long as
68 //     (1) there is no pair of loops that cross, and (2) there is no pair of
69 //     loops whose union is the entire sphere.
70 //
71 //   - InitOriented() expects the input loops to be oriented such that the
72 //     polygon interior is on the left-hand side of every loop.  So for
73 //     example, a circular region with a hole in it would be defined using a
74 //     CCW outer loop and a CW inner loop.  The loop orientations must all be
75 //     consistent; for example, it is not valid to have one CCW loop nested
76 //     inside another CCW loop, because the region between the two loops is on
77 //     the left-hand side of one loop and the right-hand side of the other.
78 //
79 // Most clients will not call these methods directly; instead they should use
80 // S2Builder, which has better support for dealing with imperfect data.
81 //
82 // When the polygon is initialized, the given loops are automatically
83 // converted into a canonical form consisting of "shells" and "holes".  Shells
84 // and holes are both oriented CCW, and are nested hierarchically.  The loops
85 // are reordered to correspond to a preorder traversal of the nesting
86 // hierarchy; InitOriented may also invert some loops. The set of input S2Loop
87 // pointers is always preserved; the caller can use this to determine how the
88 // loops were reordered if desired.
89 //
90 // Polygons may represent any region of the sphere with a polygonal boundary,
91 // including the entire sphere (known as the "full" polygon).  The full
92 // polygon consists of a single full loop (see S2Loop), whereas the empty
93 // polygon has no loops at all.
94 //
95 // Polygons have the following restrictions:
96 //
97 //  - Loops may not cross, i.e. the boundary of a loop may not intersect
98 //    both the interior and exterior of any other loop.
99 //
100 //  - Loops may not share edges, i.e. if a loop contains an edge AB, then
101 //    no other loop may contain AB or BA.
102 //
103 //  - Loops may share vertices, however no vertex may appear twice in a
104 //    single loop (see S2Loop).
105 //
106 //  - No loop may be empty.  The full loop may appear only in the full polygon.
107 
108 class S2Polygon final : public S2Region {
109  public:
110   // The default constructor creates an empty polygon.  It can be made
111   // non-empty by calling Init(), Decode(), etc.
112   S2Polygon();
113 
114   // Hide these overloads from SWIG to prevent compilation errors.
115   // TODO(user): Fix the SWIG wrapping in a better way.
116 #ifndef SWIG
117   // Convenience constructor that calls InitNested() with the given loops.
118   //
119   // When called with override == S2Debug::ALLOW, the automatic validity
120   // checking is controlled by --s2debug (which is true by default in
121   // non-optimized builds).  When this flag is enabled, a fatal error is
122   // generated whenever an invalid polygon is constructed.
123   //
124   // With override == S2Debug::DISABLE, the automatic validity checking
125   // is disabled.  The main reason to do this is if you intend to call
126   // IsValid() explicitly.  (See set_s2debug_override() for details.)
127   // Example:
128   //
129   //   std::vector<std::unique_ptr<S2Loop>> loops;
130   //   // ... set up loops ...
131   //   S2Polygon* polygon = new S2Polygon(std::move(loops), S2Debug::DISABLE);
132   //
133   // This is equivalent to:
134   //
135   //   S2Polygon* polygon = new S2Polygon;
136   //   polygon->set_s2debug_override(S2Debug::DISABLE);
137   //   polygon->InitNested(std::move(loops));
138   explicit S2Polygon(std::vector<std::unique_ptr<S2Loop> > loops,
139                      S2Debug override = S2Debug::ALLOW);
140 #endif
141 
142   // Convenience constructor that creates a polygon with a single loop
143   // corresponding to the given cell.
144   explicit S2Polygon(const S2Cell& cell);
145 
146 #ifndef SWIG
147   // Convenience constructor that calls Init(S2Loop*).  Note that this method
148   // automatically converts the special empty loop (see S2Loop) into an empty
149   // polygon, unlike the vector-of-loops constructor which does not allow
150   // empty loops at all.
151   explicit S2Polygon(std::unique_ptr<S2Loop> loop,
152                      S2Debug override = S2Debug::ALLOW);
153 
154   // Create a polygon from a set of hierarchically nested loops.  The polygon
155   // interior consists of the points contained by an odd number of loops.
156   // (Recall that a loop contains the set of points on its left-hand side.)
157   //
158   // This method figures out the loop nesting hierarchy and assigns every
159   // loop a depth.  Shells have even depths, and holes have odd depths.  Note
160   // that the loops are reordered so the hierarchy can be traversed more
161   // easily (see GetParent(), GetLastDescendant(), and S2Loop::depth()).
162   //
163   // This method may be called more than once, in which case any existing
164   // loops are deleted before being replaced by the input loops.
165   void InitNested(std::vector<std::unique_ptr<S2Loop> > loops);
166 
167   // Like InitNested(), but expects loops to be oriented such that the polygon
168   // interior is on the left-hand side of all loops.  This implies that shells
169   // and holes should have opposite orientations in the input to this method.
170   // (During initialization, loops representing holes will automatically be
171   // inverted.)
172   void InitOriented(std::vector<std::unique_ptr<S2Loop> > loops);
173 
174   // Initialize a polygon from a single loop.  Note that this method
175   // automatically converts the special empty loop (see S2Loop) into an empty
176   // polygon, unlike the vector-of-loops InitNested() method which does not
177   // allow empty loops at all.
178   void Init(std::unique_ptr<S2Loop> loop);
179 #endif  // !defined(SWIG)
180 
181   // Releases ownership of and returns the loops of this polygon, and resets
182   // the polygon to be empty.
183   std::vector<std::unique_ptr<S2Loop> > Release();
184 
185   // Makes a deep copy of the given source polygon.  The destination polygon
186   // will be cleared if necessary.
187   void Copy(const S2Polygon* src);
188 
189   // Destroys the polygon and frees its loops.
190   ~S2Polygon() override;
191 
192   // Allows overriding the automatic validity checks controlled by
193   // --s2debug (which is true by default in non-optimized builds).
194   // When this flag is enabled, a fatal error is generated whenever
195   // an invalid polygon is constructed.  The main reason to disable
196   // this flag is if you intend to call IsValid() explicitly, like this:
197   //
198   //   S2Polygon polygon;
199   //   polygon.set_s2debug_override(S2Debug::DISABLE);
200   //   polygon.Init(...);
201   //   if (!polygon.IsValid()) { ... }
202   //
203   // This setting is preserved across calls to Init() and Decode().
204   void set_s2debug_override(S2Debug override);
205   S2Debug s2debug_override() const;
206 
207   // Returns true if this is a valid polygon (including checking whether all
208   // the loops are themselves valid).  Note that validity is checked
209   // automatically during initialization when --s2debug is enabled (true by
210   // default in debug binaries).
211   bool IsValid() const;
212 
213   // Returns true if this is *not* a valid polygon and sets "error"
214   // appropriately.  Otherwise returns false and leaves "error" unchanged.
215   //
216   // Note that in error messages, loops that represent holes have their edges
217   // numbered in reverse order, starting from the last vertex of the loop.
218   //
219   // REQUIRES: error != nullptr
220   bool FindValidationError(S2Error* error) const;
221 
222   // Return true if this is the empty polygon (consisting of no loops).
is_empty()223   bool is_empty() const { return loops_.empty(); }
224 
225   // Return true if this is the full polygon (consisting of a single loop that
226   // encompasses the entire sphere).
is_full()227   bool is_full() const { return num_loops() == 1 && loop(0)->is_full(); }
228 
229   // Return the number of loops in this polygon.
num_loops()230   int num_loops() const { return static_cast<int>(loops_.size()); }
231 
232   // Total number of vertices in all loops.
num_vertices()233   int num_vertices() const { return num_vertices_; }
234 
235   // Return the loop at the given index.  Note that during initialization, the
236   // given loops are reordered according to a preorder traversal of the loop
237   // nesting hierarchy.  This implies that every loop is immediately followed
238   // by its descendants.  This hierarchy can be traversed using the methods
239   // GetParent(), GetLastDescendant(), and S2Loop::depth().
loop(int k)240   const S2Loop* loop(int k) const { return loops_[k].get(); }
loop(int k)241   S2Loop* loop(int k) { return loops_[k].get(); }
242 
243   // Return the index of the parent of loop k, or -1 if it has no parent.
244   int GetParent(int k) const;
245 
246   // Return the index of the last loop that is contained within loop k.
247   // Returns num_loops() - 1 if k < 0.  Note that loops are indexed according
248   // to a preorder traversal of the nesting hierarchy, so the immediate
249   // children of loop k can be found by iterating over loops
250   // (k+1)..GetLastDescendant(k) and selecting those whose depth is equal to
251   // (loop(k)->depth() + 1).
252   int GetLastDescendant(int k) const;
253 
254   // Return the area of the polygon interior, i.e. the region on the left side
255   // of an odd number of loops.  The return value is between 0 and 4*Pi.
256   double GetArea() const;
257 
258   // Return the true centroid of the polygon multiplied by the area of the
259   // polygon (see s2centroids.h for details on centroids).  The result is not
260   // unit length, so you may want to normalize it.  Also note that in general,
261   // the centroid may not be contained by the polygon.
262   //
263   // We prescale by the polygon area for two reasons: (1) it is cheaper to
264   // compute this way, and (2) it makes it easier to compute the centroid of
265   // more complicated shapes (by splitting them into disjoint regions and
266   // adding their centroids).
267   S2Point GetCentroid() const;
268 
269   // If all of the polygon's vertices happen to be the centers of S2Cells at
270   // some level, then return that level, otherwise return -1.  See also
271   // InitToSnapped() and s2builderutil::S2CellIdSnapFunction.
272   // Returns -1 if the polygon has no vertices.
273   int GetSnapLevel() const;
274 
275   // Return the distance from the given point to the polygon interior.  If the
276   // polygon is empty, return S1Angle::Infinity().  "x" should be unit length.
277   S1Angle GetDistance(const S2Point& x) const;
278 
279   // Return the distance from the given point to the polygon boundary.  If the
280   // polygon is empty or full, return S1Angle::Infinity() (since the polygon
281   // has no boundary).  "x" should be unit length.
282   S1Angle GetDistanceToBoundary(const S2Point& x) const;
283 
284   // Return the overlap fractions between two polygons, i.e. the ratios of the
285   // area of intersection to the area of each polygon.
286   static std::pair<double, double> GetOverlapFractions(const S2Polygon* a,
287                                                        const S2Polygon* b);
288 
289   // If the given point is contained by the polygon, return it.  Otherwise
290   // return the closest point on the polygon boundary.  If the polygon is
291   // empty, return the input argument.  Note that the result may or may not be
292   // contained by the polygon.  "x" should be unit length.
293   S2Point Project(const S2Point& x) const;
294 
295   // Return the closest point on the polygon boundary to the given point.  If
296   // the polygon is empty or full, return the input argument (since the
297   // polygon has no boundary).  "x" should be unit length.
298   S2Point ProjectToBoundary(const S2Point& x) const;
299 
300   // Return true if this polygon contains the given other polygon, i.e.
301   // if polygon A contains all points contained by polygon B.
302   bool Contains(const S2Polygon* b) const;
303 
304   // Returns true if this polgyon (A) approximately contains the given other
305   // polygon (B). This is true if it is possible to move the vertices of B
306   // no further than "tolerance" such that A contains the modified B.
307   //
308   // For example, the empty polygon will contain any polygon whose maximum
309   // width is no more than "tolerance".
310   bool ApproxContains(const S2Polygon* b, S1Angle tolerance) const;
311 
312   // Return true if this polygon intersects the given other polygon, i.e.
313   // if there is a point that is contained by both polygons.
314   bool Intersects(const S2Polygon* b) const;
315 
316   // Returns true if this polgyon (A) and the given polygon (B) are
317   // approximately disjoint.  This is true if it is possible to ensure that A
318   // and B do not intersect by moving their vertices no further than
319   // "tolerance".  This implies that in borderline cases where A and B overlap
320   // slightly, this method returns true (A and B are approximately disjoint).
321   //
322   // For example, any polygon is approximately disjoint from a polygon whose
323   // maximum width is no more than "tolerance".
324   bool ApproxDisjoint(const S2Polygon* b, S1Angle tolerance) const;
325 
326   // Initialize this polygon to the intersection, union, difference (A - B),
327   // or symmetric difference (XOR) of the given two polygons.
328   //
329   // "snap_function" allows you to specify a minimum spacing between output
330   // vertices, and/or that the vertices should be snapped to a discrete set of
331   // points (e.g. S2CellId centers or E7 lat/lng coordinates).  Any snap
332   // function can be used, including the IdentitySnapFunction with a
333   // snap_radius of zero (which preserves the input vertices exactly).
334   //
335   // The boundary of the output polygon before snapping is guaranteed to be
336   // accurate to within S2::kIntersectionError of the exact result.
337   // Snapping can move the boundary by an additional distance that depends on
338   // the snap function.  Finally, any degenerate portions of the output
339   // polygon are automatically removed (i.e., regions that do not contain any
340   // points) since S2Polygon does not allow such regions.
341   //
342   // See S2Builder and s2builderutil for more details on snap functions.  For
343   // example, you can snap to E7 coordinates by setting "snap_function" to
344   // s2builderutil::IntLatLngSnapFunction(7).
345   //
346   // The default snap function is the IdentitySnapFunction with a snap radius
347   // of S2::kIntersectionMergeRadius (equal to about 1.8e-15 radians
348   // or 11 nanometers on the Earth's surface).  This means that vertices may
349   // be positioned arbitrarily, but vertices that are extremely close together
350   // can be merged together.  The reason for a non-zero default snap radius is
351   // that it helps to eliminate narrow cracks and slivers when T-vertices are
352   // present.  For example, adjacent S2Cells at different levels do not share
353   // exactly the same boundary, so there can be a narrow crack between them.
354   // If a polygon is intersected with those cells and the pieces are unioned
355   // together, the result would have a narrow crack unless the snap radius is
356   // set to a non-zero value.
357   //
358   // Note that if you want to encode the vertices in a lower-precision
359   // representation (such as S2CellIds or E7), it is much better to use a
360   // suitable SnapFunction rather than rounding the vertices yourself, because
361   // this will create self-intersections unless you ensure that the vertices
362   // and edges are sufficiently well-separated first.  In particular you need
363   // to use a snap function whose min_edge_vertex_separation() is at least
364   // twice the maximum distance that a vertex can move when rounded.
365   //
366   // The versions of these functions with an S2Error argument return true on
367   // success and set "error" appropriately otherwise.  However note that these
368   // functions should never return an error provided that both input polygons
369   // are valid (i.e., IsValid() returns true).
370   void InitToIntersection(const S2Polygon* a, const S2Polygon* b);
371   void InitToIntersection(const S2Polygon& a, const S2Polygon& b,
372                           const S2Builder::SnapFunction& snap_function);
373   bool InitToIntersection(const S2Polygon& a, const S2Polygon& b,
374                           const S2Builder::SnapFunction& snap_function,
375                           S2Error *error);
376 
377   void InitToUnion(const S2Polygon* a, const S2Polygon* b);
378   void InitToUnion(const S2Polygon& a, const S2Polygon& b,
379                    const S2Builder::SnapFunction& snap_function);
380   bool InitToUnion(const S2Polygon& a, const S2Polygon& b,
381                    const S2Builder::SnapFunction& snap_function,
382                    S2Error *error);
383 
384   void InitToDifference(const S2Polygon* a, const S2Polygon* b);
385   void InitToDifference(const S2Polygon& a, const S2Polygon& b,
386                         const S2Builder::SnapFunction& snap_function);
387   bool InitToDifference(const S2Polygon& a, const S2Polygon& b,
388                         const S2Builder::SnapFunction& snap_function,
389                         S2Error *error);
390 
391   void InitToSymmetricDifference(const S2Polygon* a, const S2Polygon* b);
392   void InitToSymmetricDifference(const S2Polygon& a, const S2Polygon& b,
393                                  const S2Builder::SnapFunction& snap_function);
394   bool InitToSymmetricDifference(const S2Polygon& a, const S2Polygon& b,
395                                  const S2Builder::SnapFunction& snap_function,
396                                  S2Error *error);
397 
398   // Convenience functions that use the IdentitySnapFunction with the given
399   // snap radius.  TODO(ericv): Consider deprecating these and require the
400   // snap function to be specified explcitly?
401   void InitToApproxIntersection(const S2Polygon* a, const S2Polygon* b,
402                                 S1Angle snap_radius);
403   void InitToApproxUnion(const S2Polygon* a, const S2Polygon* b,
404                          S1Angle snap_radius);
405   void InitToApproxDifference(const S2Polygon* a, const S2Polygon* b,
406                               S1Angle snap_radius);
407   void InitToApproxSymmetricDifference(const S2Polygon* a, const S2Polygon* b,
408                                        S1Angle snap_radius);
409 
410   // Snaps the vertices of the given polygon using the given SnapFunction
411   // (e.g., s2builderutil::IntLatLngSnapFunction(6) snaps to E6 coordinates).
412   // This can change the polygon topology (merging loops, for example), but
413   // the resulting polygon is guaranteed to be valid, and no vertex will move
414   // by more than snap_function.snap_radius().  See S2Builder for other
415   // guarantees (e.g., minimum edge-vertex separation).
416   //
417   // Note that this method is a thin wrapper over S2Builder, so if you are
418   // starting with data that is not in S2Polygon format (e.g., integer E7
419   // coordinates) then it is faster to just use S2Builder directly.
420   void InitToSnapped(const S2Polygon& polygon,
421                      const S2Builder::SnapFunction& snap_function);
422 
423   // Convenience function that snaps the vertices to S2CellId centers at the
424   // given level (default level 30, which has S2CellId centers spaced about 1
425   // centimeter apart).  Polygons can be efficiently encoded by Encode() after
426   // they have been snapped.
427   void InitToSnapped(const S2Polygon* polygon,
428                      int snap_level = S2CellId::kMaxLevel);
429 
430   // Snaps the input polygon according to the given "snap_function" and
431   // reduces the number of vertices if possible, while ensuring that no vertex
432   // moves further than snap_function.snap_radius().
433   //
434   // Simplification works by replacing nearly straight chains of short edges
435   // with longer edges, in a way that preserves the topology of the input
436   // polygon up to the creation of degeneracies.  This means that loops or
437   // portions of loops may become degenerate, in which case they are removed.
438   // For example, if there is a very small island in the original polygon, it
439   // may disappear completely.  (Even if there are dense islands, they could
440   // all be removed rather than being replaced by a larger simplified island
441   // if more area is covered by water than land.)
442   void InitToSimplified(const S2Polygon& a,
443                         const S2Builder::SnapFunction& snap_function);
444 
445   // Like InitToSimplified, except that any vertices or edges on the boundary
446   // of the given S2Cell are preserved if possible.  This method requires that
447   // the polygon has already been clipped so that it does not extend outside
448   // the cell by more than "boundary_tolerance".  In other words, it operates
449   // on polygons that have already been intersected with a cell.
450   //
451   // Typically this method is used in geometry-processing pipelines that
452   // intersect polygons with a collection of S2Cells and then process those
453   // cells in parallel, where each cell generates some geometry that needs to
454   // be simplified.  In contrast, if you just need to simplify the *input*
455   // geometry then it is easier and faster to do the simplification before
456   // computing the intersection with any S2Cells.
457   //
458   // "boundary_tolerance" specifies how close a vertex must be to the cell
459   // boundary to be kept.  The default tolerance is large enough to handle any
460   // reasonable way of interpolating points along the cell boundary, such as
461   // S2::GetIntersection(), S2::Interpolate(), or direct (u,v)
462   // interpolation using S2::FaceUVtoXYZ().  However, if the vertices have
463   // been snapped to a lower-precision representation (e.g., S2CellId centers
464   // or E7 coordinates) then you will need to set this tolerance explicitly.
465   // For example, if the vertices were snapped to E7 coordinates then
466   // "boundary_tolerance" should be set to
467   //
468   //   s2builderutil::IntLatLngSnapFunction::MinSnapRadiusForExponent(7)
469   //
470   // Degenerate portions of loops are always removed, so if a vertex on the
471   // cell boundary belongs only to degenerate regions then it will not be
472   // kept.  For example, if the input polygon is a narrow strip of width less
473   // than "snap_radius" along one side of the cell, then the entire loop may
474   // become degenerate and be removed.
475   //
476   // REQUIRES: all vertices of "a" are within "boundary_tolerance" of "cell".
477   void InitToSimplifiedInCell(
478       const S2Polygon* a, const S2Cell& cell, S1Angle snap_radius,
479       S1Angle boundary_tolerance = S1Angle::Radians(1e-15));
480 
481   // Initialize this polygon to the complement of the given polygon.
482   void InitToComplement(const S2Polygon* a);
483 
484   // Invert the polygon (replace it by its complement).
485   void Invert();
486 
487   // Return true if this polygon contains the given polyline.  This method
488   // returns an exact result, according to the following model:
489   //
490   //  - All edges are geodesics (of course).
491   //
492   //  - Vertices are ignored for the purposes of defining containment.
493   //    (This is because polygons often do not contain their vertices, in
494   //    order to that when a set of polygons tiles the sphere then every point
495   //    is contained by exactly one polygon.)
496   //
497   //  - Points that lie exactly on geodesic edges are resolved using symbolic
498   //    perturbations (i.e., they are considered to be infinitesmally offset
499   //    from the edge).
500   //
501   //  - If the polygon and polyline share an edge, it is handled as follows.
502   //    First, the polygon edges are oriented so that the interior is always
503   //    on the left.  Then the shared polyline edge is contained if and only
504   //    if it is in the same direction as the corresponding polygon edge.
505   //    (This model ensures that when a polyline is intersected with a polygon
506   //    and its complement, the edge only appears in one of the two results.)
507   //
508   // TODO(ericv): Update the implementation to correspond to the model above.
509   bool Contains(const S2Polyline& b) const;
510 
511   // Returns true if this polgyon approximately contains the given polyline
512   // This is true if it is possible to move the polyline vertices no further
513   // than "tolerance" such that the polyline is now contained.
514   bool ApproxContains(const S2Polyline& b, S1Angle tolerance) const;
515 
516   // Return true if this polygon intersects the given polyline.  This method
517   // returns an exact result; see Contains(S2Polyline) for details.
518   bool Intersects(const S2Polyline& b) const;
519 
520   // Returns true if this polgyon is approximately disjoint from the given
521   // polyline.  This is true if it is possible to avoid intersection by moving
522   // their vertices no further than "tolerance".
523   //
524   // This implies that in borderline cases where there is a small overlap,
525   // this method returns true (i.e., they are approximately disjoint).
526   bool ApproxDisjoint(const S2Polyline& b, S1Angle tolerance) const;
527 
528 #ifndef SWIG
529   // Intersect this polygon with the polyline "in" and return the resulting
530   // zero or more polylines.  The polylines are returned in the order they
531   // would be encountered by traversing "in" from beginning to end.
532   // Note that the output may include polylines with only one vertex,
533   // but there will not be any zero-vertex polylines.
534   //
535   // This is equivalent to calling ApproxIntersectWithPolyline() with the
536   // "snap_radius" set to S2::kIntersectionMergeRadius.
537   std::vector<std::unique_ptr<S2Polyline> > IntersectWithPolyline(
538       const S2Polyline& in) const;
539 
540   // Similar to IntersectWithPolyline(), except that vertices will be
541   // dropped as necessary to ensure that all adjacent vertices in the
542   // sequence obtained by concatenating the output polylines will be
543   // farther than "snap_radius" apart.  Note that this can change
544   // the number of output polylines and/or yield single-vertex polylines.
545   std::vector<std::unique_ptr<S2Polyline> > ApproxIntersectWithPolyline(
546       const S2Polyline& in, S1Angle snap_radius) const;
547 
548   // TODO(ericv): Update documentation.
549   std::vector<std::unique_ptr<S2Polyline>> IntersectWithPolyline(
550       const S2Polyline& in, const S2Builder::SnapFunction& snap_function) const;
551 
552   // Same as IntersectWithPolyline, but subtracts this polygon from
553   // the given polyline.
554   std::vector<std::unique_ptr<S2Polyline> > SubtractFromPolyline(
555       const S2Polyline& in) const;
556 
557   // Same as ApproxIntersectWithPolyline, but subtracts this polygon
558   // from the given polyline.
559   std::vector<std::unique_ptr<S2Polyline> > ApproxSubtractFromPolyline(
560       const S2Polyline& in, S1Angle snap_radius) const;
561 
562   std::vector<std::unique_ptr<S2Polyline>> SubtractFromPolyline(
563       const S2Polyline& in, const S2Builder::SnapFunction& snap_function) const;
564 
565   // Return a polygon which is the union of the given polygons.
566   static std::unique_ptr<S2Polygon> DestructiveUnion(
567       std::vector<std::unique_ptr<S2Polygon> > polygons);
568   static std::unique_ptr<S2Polygon> DestructiveApproxUnion(
569       std::vector<std::unique_ptr<S2Polygon> > polygons,
570       S1Angle snap_radius);
571 #endif  // !defined(SWIG)
572 
573   // Initialize this polygon to the outline of the given cell union.
574   // In principle this polygon should exactly contain the cell union and
575   // this polygon's inverse should not intersect the cell union, but rounding
576   // issues may cause this not to be the case.
577   void InitToCellUnionBorder(const S2CellUnion& cells);
578 
579   // Return true if every loop of this polygon shares at most one vertex with
580   // its parent loop.  Every polygon has a unique normalized form.  A polygon
581   // can be normalized by passing it through S2Builder (with no snapping) in
582   // order to reconstruct the polygon from its edges.
583   //
584   // Generally there is no reason to convert polygons to normalized form.  It
585   // is mainly useful for testing in order to compare whether two polygons
586   // have exactly the same interior, even when they have a different loop
587   // structure.  For example, a diamond nested within a square (touching at
588   // four points) could be represented as a square with a diamond-shaped hole,
589   // or as four triangles.  Methods such as BoundaryApproxEquals() will report
590   // these polygons as being different (because they have different
591   // boundaries) even though they contain the same points.  However if they
592   // are both converted to normalized form (the "four triangles" version) then
593   // they can be compared more easily.
594   //
595   // Also see ApproxEquals(), which can determine whether two polygons contain
596   // approximately the same set of points without any need for normalization.
597   bool IsNormalized() const;
598 
599   // Return true if two polygons have exactly the same loops.  The loops must
600   // appear in the same order, and corresponding loops must have the same
601   // linear vertex ordering (i.e., cyclic rotations are not allowed).
602   bool Equals(const S2Polygon* b) const;
603 
604   // Return true if two polygons are approximately equal to within the given
605   // tolerance.  This is true if it is possible to move the vertices of the
606   // two polygons so that they contain the same set of points.
607   //
608   // Note that according to this model, small regions less than "tolerance" in
609   // width do not need to be considered, since these regions can be collapsed
610   // into degenerate loops (which contain no points) by moving their vertices.
611   //
612   // This model is not as strict as using the Hausdorff distance would be, and
613   // it is also not as strict as BoundaryNear (defined below).  However, it is
614   // a good choice for comparing polygons that have been snapped, simplified,
615   // unioned, etc, since these operations use a model similar to this one
616   // (i.e., degenerate loops or portions of loops are automatically removed).
617   bool ApproxEquals(const S2Polygon* b, S1Angle tolerance) const;
618 
619   // Returns true if two polygons have the same boundary.  More precisely,
620   // this method requires that both polygons have loops with the same cyclic
621   // vertex order and the same nesting hierarchy.  (This implies that vertices
622   // may be cyclically rotated between corresponding loops, and the loop
623   // ordering may be different between the two polygons as long as the nesting
624   // hierarchy is the same.)
625   bool BoundaryEquals(const S2Polygon* b) const;
626 
627   // Return true if two polygons have the same boundary except for vertex
628   // perturbations.  Both polygons must have loops with the same cyclic vertex
629   // order and the same nesting hierarchy, but the vertex locations are
630   // allowed to differ by up to "max_error".
631   bool BoundaryApproxEquals(const S2Polygon& b,
632                             S1Angle max_error = S1Angle::Radians(1e-15)) const;
633 
634   // Return true if two polygons have boundaries that are within "max_error"
635   // of each other along their entire lengths.  More precisely, there must be
636   // a bijection between the two sets of loops such that for each pair of
637   // loops, "a_loop->BoundaryNear(b_loop)" is true.
638   bool BoundaryNear(const S2Polygon& b,
639                     S1Angle max_error = S1Angle::Radians(1e-15)) const;
640 
641   // Returns the total number of bytes used by the polygon.
642   size_t SpaceUsed() const;
643 
644   ////////////////////////////////////////////////////////////////////////
645   // S2Region interface (see s2region.h for details):
646 
647   // GetRectBound() returns essentially tight results, while GetCapBound()
648   // might have a lot of extra padding.  Both bounds are conservative in that
649   // if the loop contains a point P, then the bound contains P also.
650   S2Polygon* Clone() const override;
651   S2Cap GetCapBound() const override;  // Cap surrounding rect bound.
GetRectBound()652   S2LatLngRect GetRectBound() const override { return bound_; }
653   void GetCellUnionBound(std::vector<S2CellId> *cell_ids) const override;
654 
655   bool Contains(const S2Cell& cell) const override;
656   bool MayIntersect(const S2Cell& cell) const override;
657 
658   // The point 'p' does not need to be normalized.
659   bool Contains(const S2Point& p) const override;
660 
661   // Appends a serialized representation of the S2Polygon to "encoder".
662   //
663   // The encoding uses about 4 bytes per vertex for typical polygons in
664   // Google's geographic repository, assuming that most vertices have been
665   // snapped to the centers of S2Cells at some fixed level (typically using
666   // InitToSnapped). The remaining vertices are stored using 24 bytes.
667   // Decoding a polygon encoded this way always returns the original polygon,
668   // without any loss of precision.
669   //
670   // The snap level is chosen to be the one that has the most vertices snapped
671   // to S2Cells at that level.  If most vertices need 24 bytes, then all
672   // vertices are encoded this way (this method automatically chooses the
673   // encoding that has the best chance of giving the smaller output size).
674   //
675   // REQUIRES: "encoder" uses the default constructor, so that its buffer
676   //           can be enlarged as necessary by calling Ensure(int).
677   void Encode(Encoder* const encoder) const;
678 
679   // Encodes the polygon's S2Points directly as three doubles using
680   // (40 + 43 * num_loops + 24 * num_vertices) bytes.
681   //
682   // REQUIRES: "encoder" uses the default constructor, so that its buffer
683   //           can be enlarged as necessary by calling Ensure(int).
684   void EncodeUncompressed(Encoder* encoder) const;
685 
686   // Decodes a polygon encoded with Encode().  Returns true on success.
687   bool Decode(Decoder* const decoder);
688 
689   // Decodes a polygon by pointing the S2Loop vertices directly into the
690   // decoder's memory buffer (which needs to persist for the lifetime of the
691   // decoded S2Polygon).  It is much faster than Decode(), but requires that
692   // all the polygon vertices were encoded exactly using 24 bytes per vertex.
693   // This essentially requires that the polygon was not snapped beforehand to
694   // a given S2Cell level; otherwise this method falls back to Decode().
695   //
696   // Returns true on success.
697   bool DecodeWithinScope(Decoder* const decoder);
698 
699 #ifndef SWIG
700   // Wrapper class for indexing a polygon (see S2ShapeIndex).  Once this
701   // object is inserted into an S2ShapeIndex it is owned by that index, and
702   // will be automatically deleted when no longer needed by the index.  Note
703   // that this class does not take ownership of the polygon itself (see
704   // OwningShape below).  You can also subtype this class to store additional
705   // data (see S2Shape for details).
706   //
707   // Note that unlike S2Polygon, the edges of S2Polygon::Shape are directed
708   // such that the polygon interior is always on the left.
709   class Shape : public S2Shape {
710    public:
711     static constexpr TypeTag kTypeTag = 1;
712 
Shape()713     Shape() : polygon_(nullptr), cumulative_edges_(nullptr) {}
714     ~Shape() override;
715 
716     // Initialization.  Does not take ownership of "polygon".  May be called
717     // more than once.
718     // TODO(ericv/jrosenstock): Make "polygon" a const reference.
719     explicit Shape(const S2Polygon* polygon);
720     void Init(const S2Polygon* polygon);
721 
polygon()722     const S2Polygon* polygon() const { return polygon_; }
723 
724     // Encodes the polygon using S2Polygon::Encode().
Encode(Encoder * encoder)725     void Encode(Encoder* encoder) const {
726       polygon_->Encode(encoder);
727     }
728 
729     // Encodes the polygon using S2Polygon::EncodeUncompressed().
EncodeUncompressed(Encoder * encoder)730     void EncodeUncompressed(Encoder* encoder) const {
731       polygon_->EncodeUncompressed(encoder);
732     }
733 
734     // Decoding is defined only for S2Polyline::OwningShape below.
735 
736     // S2Shape interface:
num_edges()737     int num_edges() const final { return num_edges_; }
738     Edge edge(int e) const final;
dimension()739     int dimension() const final { return 2; }
740     ReferencePoint GetReferencePoint() const final;
741     int num_chains() const final;
742     Chain chain(int i) const final;
743     Edge chain_edge(int i, int j) const final;
744     ChainPosition chain_position(int e) const final;
type_tag()745     TypeTag type_tag() const override { return kTypeTag; }
746 
747    private:
748     // The total number of edges in the polygon.  This is the same as
749     // polygon_->num_vertices() except in one case (polygon_->is_full()).  On
750     // the other hand this field doesn't take up any extra space due to field
751     // packing with S2Shape::id_.
752     //
753     // TODO(ericv): Consider using this field instead as an atomic<int> hint to
754     // speed up edge location when there are a large number of loops.  Also
755     // consider changing S2Polygon::num_vertices to num_edges instead.
756     int num_edges_;
757 
758     const S2Polygon* polygon_;
759 
760     // An array where element "i" is the total number of edges in loops 0..i-1.
761     // This field is only used for polygons that have a large number of loops.
762     int* cumulative_edges_;
763   };
764 
765   // Like Shape, except that the S2Polygon is automatically deleted when this
766   // object is deleted by the S2ShapeIndex.  This is useful when an S2Polygon
767   // is constructed solely for the purpose of indexing it.
768   class OwningShape : public Shape {
769    public:
OwningShape()770     OwningShape() {}  // Must call Init().
771 
OwningShape(std::unique_ptr<const S2Polygon> polygon)772     explicit OwningShape(std::unique_ptr<const S2Polygon> polygon)
773         : Shape(polygon.get()), owned_polygon_(std::move(polygon)) {}
774 
Init(std::unique_ptr<const S2Polygon> polygon)775     void Init(std::unique_ptr<const S2Polygon> polygon) {
776       Shape::Init(polygon.get());
777       owned_polygon_ = std::move(polygon);
778     }
779 
Init(Decoder * decoder)780     bool Init(Decoder* decoder) {
781       auto polygon = absl::make_unique<S2Polygon>();
782       if (!polygon->Decode(decoder)) return false;
783       Shape::Init(polygon.get());
784       owned_polygon_ = std::move(polygon);
785       return true;
786     }
787 
788     std::unique_ptr<const S2Polygon> owned_polygon_;
789   };
790 #endif  // SWIG
791 
792   // Returns the built-in S2ShapeIndex associated with every S2Polygon.  This
793   // can be used in conjunction with the various S2ShapeIndex query classes
794   // (S2ClosestEdgeQuery, S2BooleanOperation, etc) to do things beyond what is
795   // possible with S2Polygon built-in convenience methods.
796   //
797   // For example, to measure the distance from one S2Polygon to another, you
798   // can write:
799   //   S2ClosestEdgeQuery query(&polygon1.index());
800   //   S2ClosestEdgeQuery::ShapeIndexTarget target(&polygon2.index());
801   //   S1ChordAngle distance = query.GetDistance(&target);
802   //
803   // The index contains a single S2Polygon::Shape object.
index()804   const MutableS2ShapeIndex& index() const { return index_; }
805 
806  private:
807   friend class S2Stats;
808   friend class PolygonOperation;
809 
810   // Given that loops_ contains a single loop, initialize all other fields.
811   void InitOneLoop();
812 
813   // Compute num_vertices_, bound_, subregion_bound_.
814   void InitLoopProperties();
815 
816   // Deletes the contents of the loops_ vector and resets the polygon state.
817   void ClearLoops();
818 
819   // Return true if there is an error in the loop nesting hierarchy.
820   bool FindLoopNestingError(S2Error* error) const;
821 
822   // A map from each loop to its immediate children with respect to nesting.
823   // This map is built during initialization of multi-loop polygons to
824   // determine which are shells and which are holes, and then discarded.
825   typedef std::map<S2Loop*, std::vector<S2Loop*> > LoopMap;
826 
827   void InsertLoop(S2Loop* new_loop, S2Loop* parent, LoopMap* loop_map);
828   void InitLoops(LoopMap* loop_map);
829 
830   // Add the polygon's loops to the S2ShapeIndex.  (The actual work of
831   // building the index only happens when the index is first used.)
832   void InitIndex();
833 
834   // When the loop is modified (Invert(), or Init() called again) then the
835   // indexing structures need to be cleared since they become invalid.
836   void ClearIndex();
837 
838   // Initializes the polygon to the result of the given boolean operation,
839   // returning an error on failure.
840   bool InitToOperation(S2BooleanOperation::OpType op_type,
841                        const S2Builder::SnapFunction& snap_function,
842                        const S2Polygon& a, const S2Polygon& b, S2Error* error);
843 
844   // Initializes the polygon to the result of the given boolean operation,
845   // logging an error on failure (fatal in debug builds).
846   void InitToOperation(S2BooleanOperation::OpType op_type,
847                        const S2Builder::SnapFunction& snap_function,
848                        const S2Polygon& a, const S2Polygon& b);
849 
850   // Initializes the polygon from input polygon "a" using the given S2Builder.
851   // If the result has an empty boundary (no loops), also decides whether the
852   // result should be the full polygon rather than the empty one based on the
853   // area of the input polygon.  (See comments in InitToApproxIntersection.)
854   void InitFromBuilder(const S2Polygon& a, S2Builder* builder);
855 
856   std::vector<std::unique_ptr<S2Polyline> > OperationWithPolyline(
857       S2BooleanOperation::OpType op_type,
858       const S2Builder::SnapFunction& snap_function,
859       const S2Polyline& a) const;
860 
861   // Decode a polygon encoded with EncodeUncompressed().  Used by the Decode
862   // and DecodeWithinScope methods above.  The within_scope parameter
863   // specifies whether to call DecodeWithinScope on the loops.
864   bool DecodeUncompressed(Decoder* const decoder, bool within_scope);
865 
866   // Encode the polygon's vertices using about 4 bytes / vertex plus 24 bytes /
867   // unsnapped vertex. All the loop vertices must be converted first to the
868   // S2XYZFaceSiTi format using S2Loop::GetXYZFaceSiTiVertices, and concatenated
869   // in the all_vertices array.
870   //
871   // REQUIRES: snap_level >= 0.
872   void EncodeCompressed(Encoder* encoder, const S2XYZFaceSiTi* all_vertices,
873                         int snap_level) const;
874 
875   // Decode a polygon encoded with EncodeCompressed().
876   bool DecodeCompressed(Decoder* decoder);
877 
878   static std::vector<std::unique_ptr<S2Polyline> > SimplifyEdgesInCell(
879       const S2Polygon& a, const S2Cell& cell,
880       double tolerance_uv, S1Angle snap_radius);
881 
882   // Internal implementation of intersect/subtract polyline functions above.
883   std::vector<std::unique_ptr<S2Polyline> > InternalClipPolyline(
884       bool invert, const S2Polyline& a, S1Angle snap_radius) const;
885 
886   // Defines a total ordering on S2Loops that does not depend on the cyclic
887   // order of loop vertices.  This function is used to choose which loop to
888   // invert in the case where several loops have exactly the same area.
889   static int CompareLoops(const S2Loop* a, const S2Loop* b);
890 
891   std::vector<std::unique_ptr<S2Loop> > loops_;
892 
893   // Allows overriding the automatic validity checking controlled by the
894   // --s2debug flag.
895   S2Debug s2debug_override_;
896 
897   // True if InitOriented() was called and the given loops had inconsistent
898   // orientations (i.e., it is not possible to construct a polygon such that
899   // the interior is on the left-hand side of all loops).  We need to remember
900   // this error so that it can be returned later by FindValidationError(),
901   // since it is not possible to detect this error once the polygon has been
902   // initialized.  This field is not preserved by Encode/Decode.
903   uint8 error_inconsistent_loop_orientations_;
904 
905   // Cache for num_vertices().
906   int num_vertices_;
907 
908   // In general we build the index the first time it is needed, but we make an
909   // exception for Contains(S2Point) because this method has a simple brute
910   // force implementation that is also relatively cheap.  For this one method
911   // we keep track of the number of calls made and only build the index once
912   // enough calls have been made that we think an index would be worthwhile.
913   mutable std::atomic<int32> unindexed_contains_calls_;
914 
915   // "bound_" is a conservative bound on all points contained by this polygon:
916   // if A.Contains(P), then A.bound_.Contains(S2LatLng(P)).
917   S2LatLngRect bound_;
918 
919   // Since "bound_" is not exact, it is possible that a polygon A contains
920   // another polygon B whose bounds are slightly larger.  "subregion_bound_"
921   // has been expanded sufficiently to account for this error, i.e.
922   // if A.Contains(B), then A.subregion_bound_.Contains(B.bound_).
923   S2LatLngRect subregion_bound_;
924 
925   // Spatial index containing this polygon.
926   MutableS2ShapeIndex index_;
927 
928 #ifndef SWIG
929   S2Polygon(const S2Polygon&) = delete;
930   void operator=(const S2Polygon&) = delete;
931 #endif
932 };
933 
934 #endif  // S2_S2POLYGON_H_
935