From 00a42f3d852184e34a4372b95b2339ba2bccaf26 Mon Sep 17 00:00:00 2001 From: Giulio Camuffo Date: Wed, 9 Jan 2013 18:27:07 +0100 Subject: [PATCH] MATH: Fix Line2d intersection functions. Fix #682 --- math/line2d.cpp | 28 ++++++++++++++-------------- math/rect2d.cpp | 12 ++++++++++-- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/math/line2d.cpp b/math/line2d.cpp index 89151149ea4..fcc875a9f38 100644 --- a/math/line2d.cpp +++ b/math/line2d.cpp @@ -32,8 +32,13 @@ Line2d::Line2d() : Line2d::Line2d(const Vector2d &direction, const Vector2d &point) { Vector2d d = direction; - _a = d.getY() / d.getX(); - _b = -1; + if (fabsf(d.getX()) > 0.0001f) { + _a = d.getY() / d.getX(); + _b = -1; + } else { + _a = 1; + _b = 0; + } if (_b == 0) { _c = -point.getX(); @@ -76,23 +81,18 @@ bool Line2d::intersectsLine(const Line2d &line, Vector2d *pos) const { float x, y; - if (d * b - a * e == 0 || a == 0) { + const float det = a * e - b * d; + + if (fabsf(det) < 0.0001f) { return false; } - if (!pos) { - return true; - } + x = (-c * e + b * f) / det; + y = (-a * f + c * d) / det; - /* - * {ax + by + c = 0 -> x = -(by + c) / a - * {dx + ey + f = 0 -> y = (-dc + af) / (db - ae) - */ + if (pos) + *pos = Vector2d(x, y); - y = (-d * c + a * f) / (d * b - a * e); - x = -(b * y + c) / a; - - *pos = Vector2d(x, y); return true; } diff --git a/math/rect2d.cpp b/math/rect2d.cpp index 23cf34c80a2..4ce9b54091b 100644 --- a/math/rect2d.cpp +++ b/math/rect2d.cpp @@ -129,9 +129,17 @@ bool Rect2d::intersectsCircle(const Vector2d ¢er, float radius) const { } } +inline bool le(float a, float b) { + return (a < b || (fabsf(a - b) < 0.0001f)); +} + +inline bool ge(float a, float b) { + return (a > b || (fabsf(a - b) < 0.0001f)); +} + bool Rect2d::containsPoint(const Vector2d &point) const { - return (point.getX() >= _topLeft.getX() && point.getX() <= _bottomRight.getX() && - point.getY() >= _topLeft.getY() && point.getY() <= _bottomRight.getY()); + return ge(point.getX(), _topLeft.getX()) && le(point.getX(), _bottomRight.getX()) && + ge(point.getY(), _topLeft.getY()) && le(point.getY(), _bottomRight.getY()); } Vector2d Rect2d::getCenter() const {