-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector2f.cpp
109 lines (88 loc) · 2.31 KB
/
vector2f.cpp
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
#include <cmath>
#include <string>
#include <iostream>
#include "vector2f.h"
Vector2f& Vector2f::operator=(const Vector2f& rhs) {
if ( this != &rhs ) {
v[0] = rhs[0];
v[1] = rhs[1];
}
return *this;
}
Vector2f::Vector2f(float x, float y) {
v[0] = x;
v[1] = y;
}
float &Vector2f::operator[](int index) {
return v[index];
}
float Vector2f::operator[](int index) const {
return v[index];
}
Vector2f Vector2f::operator*(float scale) const {
return Vector2f(v[0] * scale, v[1] * scale);
}
Vector2f Vector2f::operator/(float scale) const {
if ( scale < 0.001 && scale > -0.001 ) {
throw std::string("scale too small in /");
}
return Vector2f(v[0] / scale, v[1] / scale);
}
Vector2f Vector2f::operator+(const Vector2f &other) const {
return Vector2f(v[0] + other.v[0], v[1] + other.v[1]);
}
Vector2f Vector2f::operator-(const Vector2f &other) const {
return Vector2f(v[0] - other.v[0], v[1] - other.v[1]);
}
Vector2f Vector2f::operator-() const {
return Vector2f(-v[0], -v[1]);
}
const Vector2f &Vector2f::operator*=(float scale) {
v[0] *= scale;
v[1] *= scale;
return *this;
}
const Vector2f &Vector2f::operator/=(float scale) {
if ( scale < 0.001 && scale > -0.001 ) {
throw std::string("scale too small in /=");
}
v[0] /= scale;
v[1] /= scale;
return *this;
}
const Vector2f &Vector2f::operator+=(const Vector2f &other) {
v[0] += other.v[0];
v[1] += other.v[1];
return *this;
}
const Vector2f &Vector2f::operator-=(const Vector2f &other) {
v[0] -= other.v[0];
v[1] -= other.v[1];
return *this;
}
float Vector2f::magnitude() const {
return sqrt(v[0] * v[0] + v[1] * v[1]);
}
float Vector2f::magnitudeSquared() const {
return v[0] * v[0] + v[1] * v[1];
}
Vector2f Vector2f::normalize() const {
float m = sqrt(v[0] * v[0] + v[1] * v[1]);
if ( m < 0.001 && m > -0.001 ) {
throw std::string("Point too close in Vector2f::normalize");
}
return Vector2f(v[0] / m, v[1] / m);
}
float Vector2f::dot(const Vector2f &other) const {
return v[0] * other.v[0] + v[1] * other.v[1] ;
}
Vector2f Vector2f::cross(const Vector2f &) const {
throw std::string("Cross Product not implemented!");
}
Vector2f operator*(float scale, const Vector2f &v) {
return v * scale;
}
std::ostream &operator<<(std::ostream &output, const Vector2f &v) {
std::cout << '(' << v[0] << ", " << v[1] << ')';
return output;
}