mat_to_quat.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "mat_to_quat.h"
  2. #include <cmath>
  3. // This could be replaced by something fast
  4. template <typename Q_type>
  5. static inline Q_type ReciprocalSqrt( const Q_type x )
  6. {
  7. return 1.0/sqrt(x);
  8. }
  9. //// Converts row major order matrix to quat
  10. //// http://software.intel.com/sites/default/files/m/d/4/1/d/8/293748.pdf
  11. //template <typename Q_type>
  12. //IGL_INLINE void igl::mat4_to_quat(const Q_type * m, Q_type * q)
  13. //{
  14. // Q_type t = + m[0 * 4 + 0] + m[1 * 4 + 1] + m[2 * 4 + 2] + 1.0f;
  15. // Q_type s = ReciprocalSqrt( t ) * 0.5f;
  16. // q[3] = s * t;
  17. // q[2] = ( m[0 * 4 + 1] - m[1 * 4 + 0] ) * s;
  18. // q[1] = ( m[2 * 4 + 0] - m[0 * 4 + 2] ) * s;
  19. // q[0] = ( m[1 * 4 + 2] - m[2 * 4 + 1] ) * s;
  20. //}
  21. // https://bmgame.googlecode.com/svn/idlib/math/Simd_AltiVec.cpp
  22. template <typename Q_type>
  23. IGL_INLINE void igl::mat4_to_quat(const Q_type * mat, Q_type * q)
  24. {
  25. Q_type trace;
  26. Q_type s;
  27. Q_type t;
  28. int i;
  29. int j;
  30. int k;
  31. static int next[3] = { 1, 2, 0 };
  32. trace = mat[0 * 4 + 0] + mat[1 * 4 + 1] + mat[2 * 4 + 2];
  33. if ( trace > 0.0f ) {
  34. t = trace + 1.0f;
  35. s = ReciprocalSqrt( t ) * 0.5f;
  36. q[3] = s * t;
  37. q[0] = ( mat[1 * 4 + 2] - mat[2 * 4 + 1] ) * s;
  38. q[1] = ( mat[2 * 4 + 0] - mat[0 * 4 + 2] ) * s;
  39. q[2] = ( mat[0 * 4 + 1] - mat[1 * 4 + 0] ) * s;
  40. } else {
  41. i = 0;
  42. if ( mat[1 * 4 + 1] > mat[0 * 4 + 0] ) {
  43. i = 1;
  44. }
  45. if ( mat[2 * 4 + 2] > mat[i * 4 + i] ) {
  46. i = 2;
  47. }
  48. j = next[i];
  49. k = next[j];
  50. t = ( mat[i * 4 + i] - ( mat[j * 4 + j] + mat[k * 4 + k] ) ) + 1.0f;
  51. s = ReciprocalSqrt( t ) * 0.5f;
  52. q[i] = s * t;
  53. q[3] = ( mat[j * 4 + k] - mat[k * 4 + j] ) * s;
  54. q[j] = ( mat[i * 4 + j] + mat[j * 4 + i] ) * s;
  55. q[k] = ( mat[i * 4 + k] + mat[k * 4 + i] ) * s;
  56. }
  57. //// Unused translation
  58. //jq.t[0] = mat[0 * 4 + 3];
  59. //jq.t[1] = mat[1 * 4 + 3];
  60. //jq.t[2] = mat[2 * 4 + 3];
  61. }
  62. #ifndef IGL_HEADER_ONLY
  63. // Explicit template specialization
  64. template void igl::mat4_to_quat<double>(double const*, double*);
  65. template void igl::mat4_to_quat<float>(float const*, float*);
  66. #endif