Last active
October 19, 2022 09:59
-
-
Save gue-ni/bcd16ec179f1767ba747d11ed4414297 to your computer and use it in GitHub Desktop.
A simple header only vector math library for C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <cmath> | |
namespace q { | |
template <typename T> | |
struct vec3 { | |
union { | |
struct { T x, y, z; }; | |
struct { T r, g, b; }; | |
}; | |
vec3() = default; | |
vec3(T s): x(s), y(s), z(s) {} | |
vec3(T _x, T _y, T _z) : x(_x), y(_y), z(_z) {} | |
void normalize() | |
{ | |
T m = length(*this); | |
(*this).x /= m; | |
(*this).y /= m; | |
(*this).z /= m; | |
} | |
}; | |
template <typename T> | |
vec3<T> operator*(const vec3<T>& a, const vec3<T>& b) | |
{ return vec3<T>(a.x * b.x, a.y * b.y, a.z * b.z); } | |
template <typename T> | |
vec3<T> operator/(const vec3<T>& a, const vec3<T>& b) | |
{ return vec3<T>(a.x / b.x, a.y / b.y, a.z / b.z); } | |
template <typename T> | |
vec3<T> operator+(const vec3<T> a, const vec3<T>& b) | |
{ return vec3<T>(a.x + b.x, a.y + b.y, a.z + b.z); } | |
template <typename T> | |
vec3<T> operator-(const vec3<T> a, const vec3<T>& b) | |
{ return vec3<T>(a.x - b.x, a.y - b.y, a.z - b.z); } | |
template <typename T> | |
T dot(const vec3<T>& a, const vec3<T>& b) | |
{ return a.x * b.x + a.y * b.y + a.z * b.z; } | |
template <typename T> | |
T length(const vec3<T>& a) | |
{ return std::sqrt(dot(a, a)); } | |
template <typename T> | |
vec3<T> cross(const vec3<T>& a, const vec3<T>& b) | |
{ return vec3<T>( a.y * b.z - a.z * b.y, \ | |
a.z * b.x - a.x * b.z, \ | |
a.x * b.y - a.y * b.x ); } | |
template <typename T> | |
std::ostream& operator<<(std::ostream& o, const vec3<T>& v) | |
{ return o << "{ " << v.x << ", " << v.y << ", " << v.z << " }"; } | |
typedef vec3<int> vec3i; | |
typedef vec3<float> vec3f; | |
typedef vec3<double> vec3d; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment