#ifndef VECTOR3F_H
#define VECTOR3F_H
#include <iostream>
#include <math.h>
class Vector3f {
public:
float x;
float y;
float z;
Vector3f() : x(0.0f), y(0.0f), z(0.0f) {}
Vector3f(float x, float y, float z) : x(x), y(y), z(z) {}
Vector3f(const Vector3f& start, const Vector3f& end) {
this->x = end.x - start.x;
this->y = end.y - start.y;
this->z = end.z - start.z;
}
const void set(float x, float y, float z) {
this->x = x;
this->y = y;
this->z = z;
}
const void add(const Vector3f& v) {
this->x += v.x;
this->y += v.y;
this->z += v.z;
}
const void sub(const Vector3f& v) {
this->x -= v.x;
this->y -= v.y;
this->z -= v.z;
}
const void mul(float n) {
this->x *= n;
this->y *= n;
this->z *= n;
}
const void normalize() {
float _l = 1.0f / sqrt(
this->x * this->x + this->y * this->y + this->z * this->z);
this->x *= _l;
this->y *= _l;
this->z *= _l;
}
const void invert() {
this->x *= -1.0f;
this->y *= -1.0f;
this->z *= -1.0f;
}
const float dotProduct(const Vector3f& v) const {
return this->x * v.x + this->y * v.y + this->z * v.z;
}
const void crossProduct(const Vector3f& v1, const Vector3f& v2) {
this->x = v1.y * v2.z - v1.z * v2.y;
this->y = v1.z * v2.x - v1.x * v2.z;
this->z = v1.x * v2.y - v1.y * v2.x;
}
friend std::ostream& operator << (std::ostream &stream, const Vector3f& v);
};
ostream& operator << (std::ostream &os, const Vector3f& v)
{
os << "(" << v.x << ", " << v.y << ", " << v.z << ")";
return os;
}
#endif
int main (void) {
Vector3f vec1(1, 0, 0);
Vector3f vec2(1, 1, 1);
Vector3f vec3(vec1, vec2);
cout << vec1 << ", " << vec2 << ", " << vec3 << endl;
vec3.crossProduct(vec1, vec2);
cout << vec3 << endl;
vec1.add(Vector3f(33, 44, 55));
cout << vec1 << endl;
vec1.sub(Vector3f(11, 22, 33));
cout << vec1 << endl;
vec3.set(1, 1, 1);
cout << vec1.dotProduct(vec3) << endl;
vec1.mul(100);
vec1.invert();
cout << vec1 << endl;
vec1.normalize();
cout << vec1 << endl;
return 0;
}
Output:
(1, 0, 0), (1, 1, 1), (0, 1, 1)
(0, -1, 1)
(34, 44, 55)
(23, 22, 22)
67
(-2300, -2200, -2200)
(-0.594452, -0.568606, -0.568606)