Skip to content

Instantly share code, notes, and snippets.

@mattatz
Created April 23, 2016 04:46
Show Gist options
  • Save mattatz/699ad2b82e2e1d56af334c601c7e345b to your computer and use it in GitHub Desktop.
Save mattatz/699ad2b82e2e1d56af334c601c7e345b to your computer and use it in GitHub Desktop.
Conversion 4x4 matrix to quaternion cginc
#ifndef _MATRIX_TO_QUATERNION_
#define _MATRIX_TO_QUATERNION_
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
float4 matrix_to_quaternion(float4x4 m) {
float tr = m[0][0] + m[1][1] + m[2][2];
float4 q = float4(0, 0, 0, 0);
if (tr > 0) {
float s = sqrt(tr + 1.0) * 2; // S=4*qw
q.w = 0.25 * s;
q.x = (m[2][1] - m[1][2]) / s;
q.y = (m[0][2] - m[2][0]) / s;
q.z = (m[1][0] - m[0][1]) / s;
} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {
float s = sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]) * 2; // S=4*qx
q.w = (m[2][1] - m[1][2]) / s;
q.x = 0.25 * s;
q.y = (m[0][1] + m[1][0]) / s;
q.z = (m[0][2] + m[2][0]) / s;
} else if (m[1][1] > m[2][2]) {
float s = sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]) * 2; // S=4*qy
q.w = (m[0][2] - m[2][0]) / s;
q.x = (m[0][1] + m[1][0]) / s;
q.y = 0.25 * s;
q.z = (m[1][2] + m[2][1]) / s;
} else {
float s = sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]) * 2; // S=4*qz
q.w = (m[1][0] - m[0][1]) / s;
q.x = (m[0][2] + m[2][0]) / s;
q.y = (m[1][2] + m[2][1]) / s;
q.z = 0.25 * s;
}
return q;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment