Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 1 | #ifndef AOS_VISION_COMP_GEO_SEGMENT_H_ |
| 2 | #define AOS_VISION_COMP_GEO_SEGMENT_H_ |
| 3 | |
| 4 | #include <cmath> |
| 5 | |
| 6 | #include "aos/vision/math/vector.h" |
| 7 | |
Stephan Pleines | d99b1ee | 2024-02-02 20:56:44 -0800 | [diff] [blame] | 8 | namespace aos::vision { |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 9 | |
| 10 | template <int Size> |
| 11 | class Segment { |
| 12 | public: |
| 13 | Segment() : A_(), B_() {} |
| 14 | |
| 15 | Segment(Vector<Size> A, Vector<Size> B) : A_(A), B_(B) {} |
| 16 | |
| 17 | Segment(double ax, double ay, double az, double bx, double by, double bz) |
| 18 | : A_(ax, ay, az), B_(bx, by, bz) {} |
| 19 | |
| 20 | ~Segment() {} |
| 21 | |
| 22 | void Set(Vector<Size> a, Vector<Size> b) { |
| 23 | A_ = a; |
| 24 | B_ = b; |
| 25 | } |
| 26 | |
| 27 | Vector<Size> A() const { return A_; } |
| 28 | Vector<Size> B() const { return B_; } |
| 29 | |
| 30 | Vector<Size> AsVector() const { return B_ - A_; } |
| 31 | Vector<Size> AsNormed() const { return AsVector().normed(); } |
| 32 | |
| 33 | Vector<Size> Center() const { return (A_ + B_) * (0.5); } |
| 34 | |
| 35 | // Fast part of length. |
| 36 | double MagSqr() { return (AsVector()).MagSqr(); } |
| 37 | |
| 38 | // Length of the vector. |
| 39 | double Mag() { return std::sqrt(MagSqr()); } |
| 40 | |
| 41 | Segment<Size> Scale(const double &other) { |
| 42 | return Segment<Size>(A_ * (other), B_ * (other)); |
| 43 | } |
| 44 | |
| 45 | // Intersect two lines in a plane. |
Parker Schuh | 02f13f6 | 2019-02-16 16:42:41 -0800 | [diff] [blame] | 46 | Vector<2> Intersect(const Segment<2> &other) const { |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 47 | static_assert(Size == 2, "Only works for size == 2"); |
| 48 | double x1 = A_.x(); |
| 49 | double y1 = A_.y(); |
| 50 | double x2 = B_.x(); |
| 51 | double y2 = B_.y(); |
| 52 | |
| 53 | double x3 = other.A().x(); |
| 54 | double y3 = other.A().y(); |
| 55 | double x4 = other.B().x(); |
| 56 | double y4 = other.B().y(); |
| 57 | |
| 58 | // check wikipedia on how to intersect two lines. |
| 59 | double xn = |
| 60 | (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4); |
| 61 | double xd = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); |
| 62 | |
| 63 | double yn = |
| 64 | (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4); |
| 65 | double yd = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); |
| 66 | |
| 67 | return Vector<2>(xn / xd, yn / yd); |
| 68 | } |
| 69 | |
| 70 | private: |
| 71 | // Begining point. |
| 72 | Vector<Size> A_; |
| 73 | |
| 74 | // Ending point. |
| 75 | Vector<Size> B_; |
| 76 | }; |
| 77 | |
Stephan Pleines | d99b1ee | 2024-02-02 20:56:44 -0800 | [diff] [blame] | 78 | } // namespace aos::vision |
Parker Schuh | 6691f19 | 2017-01-14 17:01:02 -0800 | [diff] [blame] | 79 | |
| 80 | #endif // AOS_VISION_COMP_GEO_VECTOR_H_ |