forked from cirosantilli/cpp-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec3.h
132 lines (106 loc) · 2.97 KB
/
vec3.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
simple 3d vector class so as not to create large dependencies
on simple tests
For anything serious, use real math libraries.
TODO: DRY up with common.hpp.
*/
#include <cmath>
#include <cstdio>
template <class T=float>
class Vec3 {
public:
//TODO how? maybe impossible
//const static Vec3<T> X;
//const static Vec3<T> Y;
//const static Vec3<T> Z;
T x;
T y;
T z;
Vec3()
: x(0.), y(0.), z(0.)
{
}
Vec3(T x, T y, T z)
: x(x), y(y), z(z)
{
}
Vec3(const Vec3<T>& v)
: x(v.x), y(v.y), z(v.z)
{
}
Vec3<T>& operator+=(const Vec3<T>& otherv){
this->x += otherv.x;
this->y += otherv.y;
this->z += otherv.z;
return *this;
}
Vec3<T>& operator-=(const Vec3<T>& otherv){
this->x -= otherv.x;
this->y -= otherv.y;
this->z -= otherv.z;
return *this;
}
Vec3<T>& operator*=(const T& a){
this->x *= a;
this->y *= a;
this->z *= a;
return *this;
}
Vec3<T>& operator/=(const T& a){
this->x /= a;
this->y /= a;
this->z /= a;
return *this;
}
//vector sum
Vec3<T> operator+(const Vec3<T>& otherv){
return Vec3<T>(*this) += otherv;
}
//vector subtraction
Vec3<T> operator-(const Vec3<T>& otherv){
return Vec3<T>(*this) -= otherv;
}
//multiplication by constant
Vec3<T> operator*(T a){
return Vec3<T>(*this) *= a;
}
//division by constant
Vec3<T> operator/(T a){
return Vec3<T>(*this) /= a;
}
//dot product
T dot(const Vec3<T>& otherv){
return this->x * otherv.x + this->y * otherv.y + this->z * otherv.z;
}
//returns the euclidean norm of this vector
T norm(){
return sqrt( this->dot(*this) );
}
//returns the taxi norm of this vector (largest absolute value of a corrdinate)
T taxi_norm(){
//return max(abs(x), abs(y), abs(z));
return 0.0;
}
//returns a unit vector in the same direction as this vector
T unit(){
return (*this) / this->norm();
}
//euclidean distance
T eucl(const Vec3<T>& other){
return (*this - other).norm();
}
//get a string representation
std::string str(){
char out[64];
sprintf(out, "%4.2f\n%4.2f\n%4.2f\n", x, y, z);
return std::string(out);
}
void rotY(GLfloat angle){
GLfloat oldx = x;
GLfloat oldz = z;
GLfloat sina = sin(angle);
GLfloat cosa = cos(angle);
x = oldx*cosa + oldz*sina;
z = - oldx*sina + oldz*cosa;
}
};