Simpact Cyan
Population based event driven simulation using mNRM
polygon2d.h
1 #ifndef POLYGON2D_H
2 
3 #define POLYGON2D_H
4 
5 #include "booltype.h"
6 #include <algorithm>
7 #include <vector>
8 
10 class Polygon2D
11 {
12 public:
13  Polygon2D() { m_numCoords = 0; }
14  virtual ~Polygon2D() { }
15 
16  bool_t init(const std::vector<double> &xCoords, const std::vector<double> &yCoords);
17  bool_t init(const std::vector<std::pair<double, double> > &points);
18  bool_t init(const std::vector<Point2D> &points);
19  bool isInside(double x, double y) const;
20  int getNumberOfPoints() const { return m_numCoords; }
21 private:
22  std::vector<std::pair<double, double> > m_xyCoords;
23  int m_numCoords;
24 };
25 
26 inline bool_t Polygon2D::init(const std::vector<double> &xCoords, const std::vector<double> &yCoords)
27 {
28  if (xCoords.size() != yCoords.size())
29  return "Number of X and Y coordinates is not the same";
30 
31  std::vector<std::pair<double,double> > points(xCoords.size());
32 
33  for (int i = 0 ; i < xCoords.size() ; i++)
34  points[i] = std::pair<double, double>(xCoords[i], yCoords[i]);
35 
36  return init(points);
37 }
38 
39 inline bool_t Polygon2D::init(const std::vector<std::pair<double, double> > &points)
40 {
41  if (points.size() < 3)
42  return "Too few points to be a polygon";
43 
44  m_numCoords = points.size();
45  m_xyCoords.resize(m_numCoords+1);
46 
47  for (int i = 0 ; i < m_numCoords ; i++)
48  m_xyCoords[i] = points[i];
49 
50  m_xyCoords[m_numCoords] = points[0];
51 
52  return true;
53 }
54 
55 inline bool_t Polygon2D::init(const std::vector<Point2D> &points)
56 {
57  if (points.size() < 3)
58  return "Too few points to be a polygon";
59 
60  m_numCoords = points.size();
61  m_xyCoords.resize(m_numCoords+1);
62 
63  for (int i = 0 ; i < m_numCoords ; i++)
64  m_xyCoords[i] = std::pair<double, double>(points[i].x, points[i].y);
65 
66  m_xyCoords[m_numCoords] = std::pair<double, double>(points[0].x, points[0].y);
67 
68  return true;
69 }
70 
71 inline bool Polygon2D::isInside(double x, double y) const
72 {
73  int intersections = 0;
74 
75  for (int i = 0 ; i < m_numCoords ; i++)
76  {
77  double y1 = m_xyCoords[i].second;
78  double y2 = m_xyCoords[i+1].second;
79  double Y1 = y1;
80  double Y2 = y2;
81 
82  if (Y2 < Y1)
83  {
84  double tmp = Y1;
85  Y1 = Y2;
86  Y2 = tmp;
87  }
88 
89  if (Y1 < y && y <= Y2)
90  {
91  double x1 = m_xyCoords[i].first;
92  double x2 = m_xyCoords[i+1].first;
93 
94  if (x <= std::max(x1, x2))
95  {
96  if (x1 == x2)
97  intersections++;
98  else
99  {
100  double x0 = ((y - y1)*(x2 - x1))/(y2 - y1) + x1;
101 
102  if (x <= x0)
103  intersections++;
104  }
105  }
106  }
107  }
108  return (intersections&1)?true:false;
109 }
110 
111 #endif // GRALE_POLYGON2D_H
112 
Type to return true/false with error description.
Definition: booltype.h:25
This class can be used to represent a polygon.
Definition: polygon2d.h:10