add maths utils

This commit is contained in:
2023-06-02 17:54:58 +02:00
parent 14efe2cc39
commit deb0075aac
3 changed files with 207 additions and 1 deletions

58
src/misc/Maths.cpp Normal file
View File

@@ -0,0 +1,58 @@
#include "misc/Maths.h"
namespace td {
namespace maths {
Mat4f Perspective(float fovY, float aspectRatio, float zNear, float zFar) {
const float tanHalfFovy = std::tan(fovY / 2.0f);
Mat4f result{};
result.x0 = 1.0f / (aspectRatio * tanHalfFovy);
result.y1 = 1.0f / (tanHalfFovy);
result.z2 = -(zFar + zNear) / (zFar - zNear);
result.z3 = -1.0f;
result.w2 = -(2.0f * zFar * zNear) / (zFar - zNear);
return result;
}
Mat4f LookAt(const Vec3f& eye, const Vec3f& center, const Vec3f& up) {
const Vec3f f = Normalize(center - eye);
const Vec3f s = Normalize(Cross(f, up));
const Vec3f u = Cross(s, f);
Mat4f result = Identity<float>();
result.x0 = s.x;
result.y0 = s.y;
result.z0 = s.z;
result.x1 = u.x;
result.y1 = u.y;
result.z1 = u.z;
result.x2 = -f.x;
result.y2 = -f.y;
result.z2 = -f.z;
result.w0 = -Dot(s, eye);
result.w1 = -Dot(u, eye);
result.w2 = Dot(f, eye);
return result;
}
Mat4f Dot(const Mat4f& mat, const Mat4f& other) {
Mat4f result {};
static const int MAT_SIZE = 4;
for (int i = 0; i < MAT_SIZE; i++) {
for (int j = 0; j < MAT_SIZE; j++) {
for (int k = 0; k < MAT_SIZE; k++) {
result[i * MAT_SIZE + j] += mat[i * MAT_SIZE + k] * other[k * MAT_SIZE + j];
}
}
}
return result;
}
} // namespace maths
} // namespace td