X-Git-Url: https://git.localhorst.tv/?a=blobdiff_plain;ds=sidebyside;f=src%2Fgraphics%2FVector.h;h=97dfd4ac70662c4a22eada8982bb116fbc8f89b3;hb=501ffe20da16eaab69e668871001f735697c4a42;hp=b5c6d7d11dd9f9452c0a65b781a511b8fa9603ad;hpb=61c2d30a60d586cbe63885885c6a373c7713af1e;p=space.git diff --git a/src/graphics/Vector.h b/src/graphics/Vector.h index b5c6d7d..97dfd4a 100644 --- a/src/graphics/Vector.h +++ b/src/graphics/Vector.h @@ -2,7 +2,9 @@ #define SPACE_VECTOR_H_ #include +#include #include +#include namespace space { @@ -17,6 +19,12 @@ public: template constexpr Vector(Vector other) : x(other.x), y(other.y) { } + static Vector FromPolar(Scalar rad, Scalar az) { + return Vector(rad * std::cos(az), rad * std::sin(az)); + } + + static constexpr Vector unit45 = Vector(-0.7071, 0.7071); + public: Vector &operator +=(Vector other) { x += other.x; @@ -29,12 +37,53 @@ public: return *this; } + SDL_Point ToPoint() const { + SDL_Point p; + p.x = x; + p.y = y; + return p; + } + public: Scalar x; Scalar y; }; +template +constexpr Vector Vector::unit45; + +/// specialization with same layout as SDL_Point +template<> +class Vector +: public SDL_Point { + +public: + constexpr Vector() : SDL_Point({0, 0}) { } + constexpr Vector(int x, int y) : SDL_Point({x, y}) { } + + template + constexpr Vector(Vector other) + : SDL_Point({int(other.x), int(other.y)}) { } + +public: + Vector &operator +=(Vector other) { + x += other.x; + y += other.y; + return *this; + } + Vector &operator -=(Vector other) { + x -= other.x; + y -= other.y; + return *this; + } + + SDL_Point ToPoint() const { + return *this; + } + +}; + template constexpr Vector operator -(Vector v) { @@ -93,6 +142,37 @@ constexpr bool operator !=(Vector lhs, Vector rhs) { } +template +constexpr Scalar Cross2D(Vector lhs, Vector rhs) { + return (lhs.x * rhs.y) - (lhs.y * rhs.x); +} +template +constexpr Scalar Dot(Vector lhs, Vector rhs) { + return (lhs.x * rhs.x) + (lhs.y * rhs.y); +} +template +constexpr Scalar Length(Vector v) { + return std::sqrt(Dot(v, v)); +} +template +constexpr Vector Norm(Vector v) { + return v / Length(v); +} + +template +constexpr Vector Rotate90(Vector v) { + return Vector(-v.y, v.x); +} +template +constexpr Vector Rotate180(Vector v) { + return -v; +} +template +constexpr Vector Rotate270(Vector v) { + return Vector(v.y, -v.x); +} + + template inline std::ostream &operator <<(std::ostream &out, Vector v) { return out << '<' << v.x << ',' << v.y << '>';