Quaternion.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #include <cmath>
  2. #include "math/MathConstants.h"
  3. #include "math/Quaternion.h"
  4. Quaternion::Quaternion() : w(1.0f) {
  5. }
  6. Quaternion::Quaternion(const Vector3& axis, float angle) : xyz(axis) {
  7. angle *= (M_PI / 360.0f);
  8. xyz.normalize();
  9. w = cosf(angle);
  10. xyz *= sinf(angle);
  11. }
  12. Quaternion Quaternion::lerp(float f, const Quaternion& other) const {
  13. Quaternion q;
  14. q.xyz = xyz * (1.0f - f) + other.xyz * f;
  15. q.w = w * (1.0f - f) + other.w * f;
  16. float iLength = 1.0f / sqrtf(q.xyz.squareLength() + q.w * q.w);
  17. q.xyz *= iLength;
  18. q.w *= iLength;
  19. return q;
  20. }
  21. Quaternion& Quaternion::operator*=(const Quaternion& other) {
  22. float dot = xyz.dot(other.xyz);
  23. xyz = other.xyz * w + xyz * other.w + xyz.cross(other.xyz);
  24. w = w * other.w - dot;
  25. return *this;
  26. }
  27. Quaternion Quaternion::operator*(const Quaternion& other) const {
  28. Quaternion q(*this);
  29. q *= other;
  30. return q;
  31. }
  32. Vector3 Quaternion::operator*(const Vector3& v) const {
  33. Vector3 qv = v * w + xyz.cross(v);
  34. Vector3 qvq = xyz * xyz.dot(v) + qv * w - qv.cross(xyz);
  35. return qvq;
  36. }