From e68d14c4d5b4cced62c2148323c38e7f49292bd7 Mon Sep 17 00:00:00 2001 From: Matthew Kosarek Date: Thu, 17 Jun 2021 20:44:55 -0400 Subject: Rotating 3d square --- shared_cpp/mathlib.h | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) (limited to 'shared_cpp/mathlib.h') diff --git a/shared_cpp/mathlib.h b/shared_cpp/mathlib.h index ec0ae87..c922032 100644 --- a/shared_cpp/mathlib.h +++ b/shared_cpp/mathlib.h @@ -91,6 +91,10 @@ struct Vector3 { float length() { return sqrtf(x * x + y * y + z * z); } + + Vector3 operator+(const Vector3& other) { + return { x + other.x, y + other.y, z + other.z }; + } }; struct Vector4 { @@ -166,6 +170,55 @@ struct Mat4x4 { return result; } + Mat4x4 getXRotationMatrix(float angleRadians) { + return { + { 1, 0, 0, 0, + 0, cos(angleRadians), -sin(angleRadians), 0, + 0, sin(angleRadians), cos(angleRadians), 0, + 0, 0, 0, 1 } + }; + } + + Mat4x4 getYRotationMatrix(float angleRadians) { + return { + { cos(angleRadians), 0, sin(angleRadians), 0, + 0, 1, 0, 0, + -sin(angleRadians), 0, cos(angleRadians), 0, + 0, 0, 0, 1 } + }; + } + + Mat4x4 getZRotationMatrix(float angleRadians) { + return { + { cos(angleRadians), -sin(angleRadians), 0, 0, + sin(angleRadians), cos(angleRadians), 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1 } + }; + } + + Mat4x4 rotate(float xRadians, float yRadians, float zRadians) { + Mat4x4 result = copy(); + + Mat4x4 rotationMatrix; + if (xRadians != 0) { + rotationMatrix = getXRotationMatrix(xRadians); + result = result * rotationMatrix; + } + + if (yRadians != 0) { + rotationMatrix = getYRotationMatrix(yRadians); + result = result * rotationMatrix; + } + + if (zRadians != 0) { + rotationMatrix = getZRotationMatrix(zRadians); + result = result * rotationMatrix; + } + + return result; + } + Vector2 multByVec2(Vector2 v) { Vector4 vec4 = { v.x, v.y, 0.0, 1.0 }; return { @@ -178,6 +231,22 @@ struct Mat4x4 { return multByVec2(v); } + Mat4x4 multMat4x4(const Mat4x4& other) { + Mat4x4 result; + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + int row = i * 4; + result.m[row + j] = m[row + 0] * other.m[0 + j] + m[row + 1] * other.m[4 + j] + m[row + 2] * other.m[8 + j] + m[row + 3] * other.m[12 + j]; + } + } + + return result; + } + + Mat4x4 operator*(const Mat4x4& other) { + return multMat4x4(other); + } + Mat4x4 getOrthographicMatrix(float left, float right, float bottom, float top) { Mat4x4 result; result.m[0] = 2.0 / (right - left); -- cgit v1.2.1