|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include "cg/primitives/point.h" |
| 4 | +#include <boost/numeric/interval.hpp> |
| 5 | +#include <gmpxx.h> |
| 6 | + |
| 7 | +#include <boost/optional.hpp> |
| 8 | + |
| 9 | +namespace cg |
| 10 | +{ |
| 11 | + enum orientation_t |
| 12 | + { |
| 13 | + CG_RIGHT = -1, |
| 14 | + CG_COLLINEAR = 0, |
| 15 | + CG_LEFT = 1 |
| 16 | + }; |
| 17 | + |
| 18 | + struct orientation_d |
| 19 | + { |
| 20 | + boost::optional<orientation_t> operator() (point_2 const & a, point_2 const & b, point_2 const & c) const |
| 21 | + { |
| 22 | + double l = (b.x - a.x) * (c.y - a.y); |
| 23 | + double r = (b.y - a.y) * (c.x - a.x); |
| 24 | + double res = l - r; |
| 25 | + double eps = (fabs(l) + fabs(r)) * 8 * std::numeric_limits<double>::epsilon(); |
| 26 | + |
| 27 | + if (res > eps) |
| 28 | + return CG_LEFT; |
| 29 | + |
| 30 | + if (res < -eps) |
| 31 | + return CG_RIGHT; |
| 32 | + |
| 33 | + return boost::none; |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + struct orientation_i |
| 38 | + { |
| 39 | + boost::optional<orientation_t> operator() (point_2 const & a, point_2 const & b, point_2 const & c) const |
| 40 | + { |
| 41 | + typedef boost::numeric::interval_lib::unprotect<boost::numeric::interval<double> >::type interval; |
| 42 | + |
| 43 | + boost::numeric::interval<double>::traits_type::rounding _; |
| 44 | + interval res = (interval(b.x) - a.x) * (interval(c.y) - a.y) |
| 45 | + - (interval(b.y) - a.y) * (interval(c.x) - a.x); |
| 46 | + |
| 47 | + if (res.lower() > 0) |
| 48 | + return CG_LEFT; |
| 49 | + |
| 50 | + if (res.upper() < 0) |
| 51 | + return CG_RIGHT; |
| 52 | + |
| 53 | + if (res.upper() == res.lower()) |
| 54 | + return CG_COLLINEAR; |
| 55 | + |
| 56 | + return boost::none; |
| 57 | + } |
| 58 | + }; |
| 59 | + |
| 60 | + struct orientation_r |
| 61 | + { |
| 62 | + boost::optional<orientation_t> operator() (point_2 const & a, point_2 const & b, point_2 const & c) const |
| 63 | + { |
| 64 | + mpq_class res = (mpq_class(b.x) - a.x) * (mpq_class(c.y) - a.y) |
| 65 | + - (mpq_class(b.y) - a.y) * (mpq_class(c.x) - a.x); |
| 66 | + |
| 67 | + int cres = cmp(res, 0); |
| 68 | + |
| 69 | + if (cres > 0) |
| 70 | + return CG_LEFT; |
| 71 | + |
| 72 | + if (cres < 0) |
| 73 | + return CG_RIGHT; |
| 74 | + |
| 75 | + return CG_COLLINEAR; |
| 76 | + } |
| 77 | + }; |
| 78 | + |
| 79 | + inline orientation_t orientation(point_2 const & a, point_2 const & b, point_2 const & c) |
| 80 | + { |
| 81 | + if (boost::optional<orientation_t> v = orientation_d()(a, b, c)) |
| 82 | + return *v; |
| 83 | + |
| 84 | + if (boost::optional<orientation_t> v = orientation_i()(a, b, c)) |
| 85 | + return *v; |
| 86 | + |
| 87 | + return *orientation_r()(a, b, c); |
| 88 | + } |
| 89 | +} |
0 commit comments