Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. class Quaternion
  2. {
  3. public:
  4. float x, y, z, w;
  5.  
  6. void Multiply(const Quaternion& other)
  7. {
  8. x = x * other.w + y * other.z - z * other.y + w * other.x;
  9. y = -x * other.z + y * other.w + z * other.x + w * other.y;
  10. z = x * other.y - y * other.x + z * other.w + w * other.z;
  11. w = -x * other.x - y * other.y - z * other.z + w * other.w;
  12. }
  13.  
  14. Vector3 GetForwardVector()
  15. {
  16. return Vector3(
  17. 2 * (x * z + w * y),
  18. 2 * (y * z + w * x),
  19. 1 - 2 * (x * x + y * y)
  20. );
  21. }
  22.  
  23. static Vector3 ToEulerAngles(const Quaternion& q)
  24. {
  25. Vector3 v;
  26.  
  27. // roll (x-axis rotation)
  28. double sinr_cosp = + 2.0 * (q.w * q.x + q.y * q.z);
  29. double cosr_cosp = + 1.0 - 2.0 * (q.x * q.x + q.y * q.y);
  30. v.Z = (float)atan2(sinr_cosp, cosr_cosp);
  31.  
  32. // pitch (y-axis rotation)
  33. double sinp = +2.0 * (q.w * q.y - q.z * q.x);
  34. if (sinp >= 1 || sinp <= -1)
  35. v.Y = (float)copysign(Math.PI / 2, sinp); // use 90 degrees if out of range
  36. else
  37. v.Y = (float)asin(sinp);
  38.  
  39. // yaw (z-axis rotation)
  40. double siny_cosp = +2.0 * (q.w * q.z + q.x * q.y);
  41. double cosy_cosp = +1.0 - 2.0 * (q.y * q.y + q.z * q.z);
  42. v.X = (float)atan2(siny_cosp, cosy_cosp);
  43.  
  44. return v;
  45. }
  46.  
  47. static Quaternion CreateFromAxisAngle(const Vector3& vector, float angle)
  48. {
  49. Quaternion q;
  50. float s = sin(angle / 2);
  51. q.x = vector.x * s;
  52. q.y = vector.y * s;
  53. q.z = vector.z * s;
  54. q.w = cos(angle / 2);
  55. return q;
  56. }
  57.  
  58. static Quaternion CreateFromYawPitchRoll(double yaw, double pitch, double roll) // yaw (Z), pitch (Y), roll (X)
  59. {
  60. // Abbreviations for the various angular functions
  61. double cy = cos(yaw * 0.5);
  62. double sy = sin(yaw * 0.5);
  63. double cp = cos(pitch * 0.5);
  64. double sp = sin(pitch * 0.5);
  65. double cr = cos(roll * 0.5);
  66. double sr = sin(roll * 0.5);
  67.  
  68. Quaternion q;
  69. q.w = (float)(cy * cp * cr + sy * sp * sr);
  70. q.x = (float)(cy * cp * sr - sy * sp * cr);
  71. q.y = (float)(sy * cp * sr + cy * sp * cr);
  72. q.z = (float)(sy * cp * cr - cy * sp * sr);
  73.  
  74. return q;
  75. }
  76.  
  77. Quaternion(float x, float y, float z, float w)
  78. {
  79. this->x = x;
  80. this->y = y;
  81. this->z = z;
  82. this->w = w;
  83. }
  84.  
  85. Quaternion() = default;
  86. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement