| 6 | * License as published by the Free Software Foundation; either |
| 7 | * version 2.1 of the License, or (at your option) any later version. |
| 8 | * |
| 9 | * This library is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 12 | * Lesser General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU Lesser General Public |
| 15 | * License along with this library; if not, write to the Free Software |
| 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA |
| 17 | */ |
| 18 |
| 19 | #ifndef VLINE_H |
| 20 | #define VLINE_H |
| 21 |
| 22 | #include "vglobal.h" |
| 23 | #include "vpoint.h" |
| 24 |
| 25 | V_BEGIN_NAMESPACE |
| 26 |
| 27 | class VLine { |
| 28 | public: |
| 29 | VLine() = default; |
| 30 | VLine(float x1, float y1, float x2, float y2) |
| 31 | : mX1(x1), mY1(y1), mX2(x2), mY2(y2) |
| 32 | { |
| 33 | } |
| 34 | VLine(const VPointF &p1, const VPointF &p2) |
| 35 | : mX1(p1.x()), mY1(p1.y()), mX2(p2.x()), mY2(p2.y()) |
| 36 | { |
| 37 | } |
| 38 | float length() const { return length(mX1, mY1, mX2, mY2);} |
| 39 | void splitAtLength(float length, VLine &left, VLine &right) const; |
| 40 | VPointF p1() const { return {mX1, mY1}; } |
| 41 | VPointF p2() const { return {mX2, mY2}; } |
| 42 | float angle() const; |
| 43 | static float length(float x1, float y1, float x2, float y2); |
| 44 |
| 45 | private: |
| 46 | float mX1{0}; |
| 47 | float mY1{0}; |
| 48 | float mX2{0}; |
| 49 | float mY2{0}; |
| 50 | }; |
| 51 |
| 52 | inline float VLine::angle() const |
| 53 | { |
| 54 | const float dx = mX2 - mX1; |
| 55 | const float dy = mY2 - mY1; |
| 56 |
| 57 | const float theta = std::atan2(dy, dx) * 180.0 / M_PI; |
| 58 | return theta; |
| 59 | } |
| 60 |
| 61 | // approximate sqrt(x*x + y*y) using alpha max plus beta min algorithm. |
| 62 | // With alpha = 1, beta = 3/8, giving results with the largest error less |
| 63 | // than 7% compared to the exact value. |
| 64 | inline float VLine::length(float x1, float y1, float x2, float y2) |
| 65 | { |
| 66 | float x = x2 - x1; |
| 67 | float y = y2 - y1; |
| 68 |
| 69 | x = x < 0 ? -x : x; |
| 70 | y = y < 0 ? -y : y; |
| 71 |
| 72 | return (x > y ? x + 0.375 * y : y + 0.375 * x); |
| 73 | } |
| 74 |
| 75 | inline void VLine::splitAtLength(float lengthAt, VLine &left, VLine &right) const |
| 76 | { |
| 77 | float len = length(); |
| 78 | float dx = ((mX2 - mX1) / len) * lengthAt; |
| 79 | float dy = ((mY2 - mY1) / len) * lengthAt; |
| 80 |
| 81 | left.mX1 = mX1; |
| 82 | left.mY1 = mY1; |
| 83 | left.mX2 = left.mX1 + dx; |
| 84 | left.mY2 = left.mY1 + dy; |
| 85 |
| 86 | right.mX1 = left.mX2; |
| 87 | right.mY1 = left.mY2; |
| 88 | right.mX2 = mX2; |
| 89 | right.mY2 = mY2; |
| 90 | } |
| 91 |
| 92 | #endif //VLINE_H |
| 93 |