Go to the documentation of this file.00001
00007 #ifndef __GEOMETRY_UTILS_H
00008 #define __GEOMETRY_UTILS_H
00009
00010 #include <vector>
00011 #include <cmath>
00012
00013
00014 #define EQ_DOUBLE(a, b) \
00015 (std::abs((a) - (b)) < 0.0001)
00016
00020 struct Rectangle {
00021
00023 Rectangle() : Rectangle(0, 0, 0, 0) {}
00024
00033 Rectangle(double b, double t, double l, double r) :
00034 bot(b), top(t), left(l), right(r) {}
00035
00041 bool does_contain(double x, double y) const {
00042 return ((bot < y) && (y < top)) && ((left < x) && (x < right));
00043 }
00044
00049 double area() const {
00050 return (top - bot)*(right - left);
00051 }
00052
00053 double bot,
00054 top,
00055 left,
00056 right;
00057 };
00058
00062 struct DiscretePoint2D {
00063 public:
00064
00069 DiscretePoint2D(int x_coord, int y_coord):
00070 x{x_coord}, y{y_coord} {}
00071
00072 int x, y;
00073
00075 DiscretePoint2D operator+(const DiscretePoint2D &p) const {
00076 return DiscretePoint2D(x + p.x, y + p.y);
00077 }
00078
00080 DiscretePoint2D operator-() const {
00081 return DiscretePoint2D(-x, -y);
00082 }
00083
00089 double dist_sq(const DiscretePoint2D &pt) const {
00090 return std::pow(x - pt.x, 2) + std::pow(y - pt.y, 2);
00091 }
00092 };
00093
00097 class DiscreteLine2D {
00098 using Point = DiscretePoint2D;
00099 public:
00100
00106 DiscreteLine2D(const Point &start, const Point &end) {
00107 generatePointsWithBresenham(start.x, start.y, end.x, end.y);
00108 }
00110 const std::vector<Point>& points() const { return _points; }
00111 private:
00112
00121 void generatePointsWithBresenham(int x1, int y1, int x2, int y2) {
00122
00123
00124
00125
00126 int delta_x(x2 - x1);
00127
00128 signed char const ix((delta_x > 0) - (delta_x < 0));
00129 delta_x = std::abs(delta_x) * 2;
00130
00131 int delta_y(y2 - y1);
00132
00133 signed char const iy((delta_y > 0) - (delta_y < 0));
00134 delta_y = std::abs(delta_y) * 2;
00135
00136 _points.push_back(Point(x1, y1));
00137
00138 if (delta_x >= delta_y) {
00139
00140 int error(delta_y - (delta_x >> 1));
00141 while (x1 != x2) {
00142 if ((0 <= error) && (error || (0 < ix))) {
00143 error -= delta_x;
00144 y1 += iy;
00145 }
00146
00147 error += delta_y;
00148 x1 += ix;
00149 _points.push_back(Point(x1, y1));
00150 }
00151 }
00152 else {
00153
00154 int error(delta_x - (delta_y >> 1));
00155
00156 while (y1 != y2) {
00157 if ((0 <= error) && (error || (0 < iy))) {
00158 error -= delta_y;
00159 x1 += ix;
00160 }
00161
00162 error += delta_x;
00163 y1 += iy;
00164 _points.push_back(Point(x1, y1));
00165 }
00166 }
00167 }
00168 private:
00169 std::vector<Point> _points;
00170 };
00171
00172 #endif