First attempt at Mat4 to Quaternion (might have rows and columns swapped?)

This commit is contained in:
Ben Visness
2018-06-20 12:57:17 +02:00
parent 850efa3606
commit eedda7ca4c
4 changed files with 102 additions and 47 deletions

View File

@@ -1245,6 +1245,8 @@ HMM_INLINE hmm_mat4 HMM_DivideMat4f(hmm_mat4 Matrix, float Scalar)
HMM_EXTERN hmm_mat4 HMM_DivideMat4f(hmm_mat4 Matrix, float Scalar);
#endif
HMM_EXTERN hmm_quaternion HMM_Mat4ToQuaternion(hmm_mat4 Matrix);
/*
* Common graphics transformations
@@ -2345,6 +2347,42 @@ hmm_mat4 HMM_DivideMat4f(hmm_mat4 Matrix, float Scalar)
}
#endif
hmm_quaternion HMM_Mat4ToQuaternion(hmm_mat4 m)
{
hmm_quaternion q;
float trace = m.Elements[0][0] + m.Elements[1][1] + m.Elements[2][2];
if (trace > 0) {
float s = 0.5f / HMM_SquareRootF(trace + 1.0f);
q.X = (m.Elements[2][1] - m.Elements[1][2] ) * s;
q.Y = (m.Elements[0][2] - m.Elements[2][0] ) * s;
q.Z = (m.Elements[1][0] - m.Elements[0][1] ) * s;
q.W = 0.25f / s;
} else {
if (m.Elements[0][0] > m.Elements[1][1] && m.Elements[0][0] > m.Elements[2][2]) {
float s = 2.0f * HMM_SquareRootF(1.0f + m.Elements[0][0] - m.Elements[1][1] - m.Elements[2][2]);
q.X = 0.25f * s;
q.Y = (m.Elements[0][1] + m.Elements[1][0] ) / s;
q.Z = (m.Elements[0][2] + m.Elements[2][0] ) / s;
q.W = (m.Elements[2][1] - m.Elements[1][2] ) / s;
} else if (m.Elements[1][1] > m.Elements[2][2]) {
float s = 2.0f * HMM_SquareRootF( 1.0f + m.Elements[1][1] - m.Elements[0][0] - m.Elements[2][2]);
q.X = (m.Elements[0][1] + m.Elements[1][0] ) / s;
q.Y = 0.25f * s;
q.Z = (m.Elements[1][2] + m.Elements[2][1] ) / s;
q.W = (m.Elements[0][2] - m.Elements[2][0] ) / s;
} else {
float s = 2.0f * HMM_SquareRootF( 1.0f + m.Elements[2][2] - m.Elements[0][0] - m.Elements[1][1] );
q.X = (m.Elements[0][2] + m.Elements[2][0] ) / s;
q.Y = (m.Elements[1][2] + m.Elements[2][1] ) / s;
q.Z = 0.25f * s;
q.W = (m.Elements[1][0] - m.Elements[0][1] ) / s;
}
}
return q;
}
hmm_mat4 HMM_Rotate(float Angle, hmm_vec3 Axis)
{
hmm_mat4 Result = HMM_Mat4d(1.0f);