quaternion.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2016 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include "common/vector_math.h"
  6. namespace Common {
  7. template <typename T>
  8. class Quaternion {
  9. public:
  10. Vec3<T> xyz;
  11. T w{};
  12. [[nodiscard]] Quaternion<decltype(-T{})> Inverse() const {
  13. return {-xyz, w};
  14. }
  15. [[nodiscard]] Quaternion<decltype(T{} + T{})> operator+(const Quaternion& other) const {
  16. return {xyz + other.xyz, w + other.w};
  17. }
  18. [[nodiscard]] Quaternion<decltype(T{} - T{})> operator-(const Quaternion& other) const {
  19. return {xyz - other.xyz, w - other.w};
  20. }
  21. [[nodiscard]] Quaternion<decltype(T{} * T{} - T{} * T{})> operator*(
  22. const Quaternion& other) const {
  23. return {xyz * other.w + other.xyz * w + Cross(xyz, other.xyz),
  24. w * other.w - Dot(xyz, other.xyz)};
  25. }
  26. [[nodiscard]] Quaternion<T> Normalized() const {
  27. T length = std::sqrt(xyz.Length2() + w * w);
  28. return {xyz / length, w / length};
  29. }
  30. [[nodiscard]] std::array<decltype(-T{}), 16> ToMatrix() const {
  31. const T x2 = xyz[0] * xyz[0];
  32. const T y2 = xyz[1] * xyz[1];
  33. const T z2 = xyz[2] * xyz[2];
  34. const T xy = xyz[0] * xyz[1];
  35. const T wz = w * xyz[2];
  36. const T xz = xyz[0] * xyz[2];
  37. const T wy = w * xyz[1];
  38. const T yz = xyz[1] * xyz[2];
  39. const T wx = w * xyz[0];
  40. return {1.0f - 2.0f * (y2 + z2),
  41. 2.0f * (xy + wz),
  42. 2.0f * (xz - wy),
  43. 0.0f,
  44. 2.0f * (xy - wz),
  45. 1.0f - 2.0f * (x2 + z2),
  46. 2.0f * (yz + wx),
  47. 0.0f,
  48. 2.0f * (xz + wy),
  49. 2.0f * (yz - wx),
  50. 1.0f - 2.0f * (x2 + y2),
  51. 0.0f,
  52. 0.0f,
  53. 0.0f,
  54. 0.0f,
  55. 1.0f};
  56. }
  57. };
  58. template <typename T>
  59. [[nodiscard]] auto QuaternionRotate(const Quaternion<T>& q, const Vec3<T>& v) {
  60. return v + 2 * Cross(q.xyz, Cross(q.xyz, v) + v * q.w);
  61. }
  62. [[nodiscard]] inline Quaternion<float> MakeQuaternion(const Vec3<float>& axis, float angle) {
  63. return {axis * std::sin(angle / 2), std::cos(angle / 2)};
  64. }
  65. } // namespace Common