vectozavr-shooter/engine/math/Vec3D.cpp

97 lines
2.1 KiB
C++
Raw Normal View History

//
// Created by Иван Ильин on 09.10.2021.
//
#include <cmath>
#include <stdexcept>
2021-10-31 11:39:08 +03:00
#include "Vec3D.h"
2022-07-11 16:58:05 +03:00
#include "../Consts.h"
2021-10-31 11:39:08 +03:00
Vec3D::Vec3D(const Vec3D &vec) {
_arr_point[0] = vec.x();
_arr_point[1] = vec.y();
_arr_point[2] = vec.z();
}
2021-10-31 11:39:08 +03:00
Vec3D::Vec3D(const Vec4D &point4D) {
_arr_point[0] = point4D.x();
_arr_point[1] = point4D.y();
_arr_point[2] = point4D.z();
}
2021-10-31 11:39:08 +03:00
Vec3D::Vec3D(double x, double y, double z) {
_arr_point[0] = x;
_arr_point[1] = y;
_arr_point[2] = z;
}
Vec3D Vec3D::operator-() const {
return Vec3D(-x(), -y(), -z());
}
2021-10-31 11:39:08 +03:00
bool Vec3D::operator==(const Vec3D &vec) const {
return (*this - vec).sqrAbs() < Consts::EPS;
}
2021-10-31 11:39:08 +03:00
bool Vec3D::operator!=(const Vec3D &vec) const {
return !(*this == vec);
}
// Operations with Vec3D
2021-10-31 11:39:08 +03:00
Vec3D Vec3D::operator+(const Vec3D &vec) const {
return Vec3D(x() + vec.x(), y() + vec.y(), z() + vec.z());
}
2021-10-31 11:39:08 +03:00
Vec3D Vec3D::operator-(const Vec3D &vec) const {
2021-11-04 03:35:34 +03:00
return *this + -vec;
}
Vec3D Vec3D::operator*(double number) const {
2021-10-31 11:39:08 +03:00
return Vec3D(x() * number, y() * number, z() * number);
}
Vec3D Vec3D::operator/(double number) const {
2021-10-31 11:39:08 +03:00
if (std::abs(number) > Consts::EPS) {
2021-11-04 03:35:34 +03:00
return *this * (1.0 / number);
2021-10-28 16:58:02 +03:00
} else {
throw std::domain_error{"Vec3D::operator/(double number): division by zero"};
2021-10-28 16:58:02 +03:00
}
}
// Other useful methods
double Vec3D::sqrAbs() const {
2021-10-31 11:39:08 +03:00
return x() * x() + y() * y() + z() * z();
}
double Vec3D::abs() const {
return sqrt(sqrAbs());
}
Vec3D Vec3D::normalized() const {
2021-11-04 03:35:34 +03:00
double vecAbs = sqrAbs();
2021-10-31 11:39:08 +03:00
if (vecAbs > Consts::EPS) {
2021-11-04 03:35:34 +03:00
return *this / sqrt(vecAbs);
2021-10-28 16:58:02 +03:00
} else {
return Vec3D(1);
2021-10-28 16:58:02 +03:00
}
}
2021-10-31 11:39:08 +03:00
double Vec3D::dot(const Vec3D &vec) const {
return vec.x() * x() + vec.y() * y() + vec.z() * z();
}
2021-10-31 11:39:08 +03:00
Vec3D Vec3D::cross(const Vec3D &vec) const {
return Vec3D{y() * vec.z() - vec.y() * z(),
z() * vec.x() - vec.z() * x(),
x() * vec.y() - vec.x() * y()};
}
2021-10-28 16:58:02 +03:00
Vec4D Vec3D::makePoint4D() const {
return Vec4D(x(), y(), z(), 1.0);
}
2021-10-29 19:43:39 +03:00
Vec3D Vec3D::Random() {
2021-10-31 11:39:08 +03:00
return Vec3D((double) rand() / RAND_MAX, (double) rand() / RAND_MAX, (double) rand() / RAND_MAX);
2021-10-29 19:43:39 +03:00
}