vectozavr-shooter/engine/Triangle.cpp

47 lines
1.4 KiB
C++
Raw Normal View History

2021-09-13 15:53:43 +03:00
//
// Created by Иван Ильин on 13.01.2021.
//
#include "Triangle.h"
2021-10-28 16:58:02 +03:00
#include "Consts.h"
2021-09-13 15:53:43 +03:00
2021-10-28 16:58:02 +03:00
Triangle::Triangle(const Vec4D& p1, const Vec4D& p2, const Vec4D& p3, sf::Color color) : _color(color), _points{p1, p2, p3} {
2021-09-13 15:53:43 +03:00
}
2021-10-28 16:58:02 +03:00
Triangle::Triangle(const Triangle &triangle) : _points{triangle._points[0], triangle._points[1], triangle._points[2]}, _color(triangle._color) {
}
2021-09-13 15:53:43 +03:00
Triangle Triangle::operator*(const Matrix4x4 &matrix4X4) const {
return Triangle(matrix4X4 * _points[0], matrix4X4 * _points[1], matrix4X4 * _points[2], _color);
2021-09-13 15:53:43 +03:00
}
Vec3D Triangle::norm() const {
2021-09-13 15:53:43 +03:00
Vec3D v1 = Vec3D(_points[1] - _points[0]);
Vec3D v2 = Vec3D(_points[2] - _points[0]);
Vec3D crossProduct = v1.cross(v2);
2021-09-13 15:53:43 +03:00
2021-10-28 16:58:02 +03:00
if(crossProduct.sqrAbs() > Consts::EPS) {
return crossProduct.normalized();
2021-10-28 16:58:02 +03:00
} else {
return Vec3D(0);
2021-10-28 16:58:02 +03:00
}
2021-09-13 15:53:43 +03:00
}
2021-10-28 16:58:02 +03:00
Vec4D Triangle::operator[](int i) const {
return _points[i];
2021-09-13 15:53:43 +03:00
}
bool Triangle::isPointInside(const Vec3D &point) const {
Vec3D triangleNorm = norm();
2021-09-13 15:53:43 +03:00
double dot1 = (point - Vec3D(_points[0])).cross(Vec3D(_points[1] - _points[0])).dot(triangleNorm);
double dot2 = (point - Vec3D(_points[1])).cross(Vec3D(_points[2] - _points[1])).dot(triangleNorm);
double dot3 = (point - Vec3D(_points[2])).cross(Vec3D(_points[0] - _points[2])).dot(triangleNorm);
2021-09-13 15:53:43 +03:00
2021-10-28 16:58:02 +03:00
if((dot1 >= 0 && dot2 >= 0 && dot3 >= 0) || (dot1 <= 0 && dot2 <= 0 && dot3 <= 0)) {
2021-09-13 15:53:43 +03:00
return true;
2021-10-28 16:58:02 +03:00
}
2021-09-13 15:53:43 +03:00
return false;
}