Debian Codegraph @

src/atlas/util/SphericalPolygon.cc

raw
1 /*
2 * (C) Copyright 2013 ECMWF.
3 *
4 * This software is licensed under the terms of the Apache Licence Version 2.0
5 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
6 * In applying this licence, ECMWF does not waive the privileges and immunities
7 * granted to it by virtue of its status as an intergovernmental organisation
8 * nor does it submit to any jurisdiction.
9 */
10
11 #include <algorithm>
12 #include <cmath>
13 #include <iostream>
14 #include <limits>
15
16 #include "eckit/types/FloatCompare.h"
17
18 #include "atlas/runtime/Exception.h"
19 #include "atlas/util/CoordinateEnums.h"
20 #include "atlas/util/SphericalPolygon.h"
21
22 namespace atlas {
23 namespace util {
24
25 //------------------------------------------------------------------------------------------------------
26
27 SphericalPolygon::SphericalPolygon(const PartitionPolygon& partition_polygon):
28 PolygonCoordinates(partition_polygon.xy(), false) {}
29
30 SphericalPolygon::SphericalPolygon(const std::vector<PointLonLat>& points): PolygonCoordinates(points) {}
31
32 bool SphericalPolygon::contains(const Point2& P) const {
33 using eckit::types::is_approximately_equal;
34
35 ATLAS_ASSERT(coordinates_.size() >= 2);
36
37 // check first bounding box
38 if (coordinatesMax_[LON] <= P[LON] || P[LON] < coordinatesMin_[LON]) {
39 return false;
40 }
41
42 // winding number
43 int wn = 0;
44
45 // loop on polygon edges
46 for (size_t i = 1; i < coordinates_.size(); ++i) {
47 const Point2& A = coordinates_[i - 1];
48 const Point2& B = coordinates_[i];
49
50 // test if P is on/above/below of a great circle containing A,B
51 const bool APB = (A[LON] <= P[LON] && P[LON] < B[LON]);
52 const bool BPA = (B[LON] <= P[LON] && P[LON] < A[LON]);
53
54 if (APB != BPA) {
55 const double lat = is_approximately_equal(A[LAT], B[LAT]) && is_approximately_equal(std::abs(A[LAT]), 90.)
56 ? A[LAT]
57 : util::Earth::greatCircleLatitudeGivenLongitude(A, B, P[LON]);
58
59 ATLAS_ASSERT(!std::isnan(lat));
60 if (is_approximately_equal(P[LAT], lat)) {
61 return true;
62 }
63
64 wn += (P[LAT] > lat ? -1 : 1) * (APB ? -1 : 1);
65 }
66 }
67
68 // wn == 0 only when P is outside
69 return wn != 0;
70 }
71
72 //------------------------------------------------------------------------------------------------------
73
74 } // namespace util
75 } // namespace atlas