Quaternion.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. module Core.Quaternion;
  2. import Core.Math;
  3. import Core.Std;
  4. import Core.ToString;
  5. Core::Quaternion::Quaternion() : v(0.0f, 0.0f, 0.0f, 1.0f) {
  6. }
  7. Core::Quaternion::Quaternion(const Vector3& axis, float angle) :
  8. v(axis[0], axis[1], axis[2], 1.0f) {
  9. v.xyz().normalize();
  10. float factor = 0.0f;
  11. sincosf(angle * 0.5f, &factor, &v[3]);
  12. v.xyz() *= factor;
  13. }
  14. Core::Quaternion Core::Quaternion::lerp(
  15. float f, const Quaternion& other) const {
  16. Quaternion q;
  17. q.v = interpolate(v, other.v, f);
  18. q.v.normalize();
  19. return q;
  20. }
  21. Core::Quaternion& Core::Quaternion::operator*=(const Quaternion& other) {
  22. float dot = v.xyz().dot(other.v.xyz());
  23. v.xyz() = other.v.xyz() * v[3] + v.xyz() * other.v[3] +
  24. cross(v.xyz(), other.v.xyz());
  25. v[3] = v[3] * other.v[3] - dot;
  26. return *this;
  27. }
  28. Core::Quaternion Core::Quaternion::operator*(const Quaternion& other) const {
  29. Quaternion q(*this);
  30. q *= other;
  31. return q;
  32. }
  33. Core::Vector3 Core::Quaternion::operator*(const Vector3& v3) const {
  34. Vector3 qv = v3 * v[3] + cross(v.xyz(), v3);
  35. return v.xyz() * v.xyz().dot(v3) + qv * v[3] - cross(qv, v.xyz());
  36. }
  37. size_t Core::Quaternion::toString(char* s, size_t n) const {
  38. return formatBuffer(
  39. s, n, "({.3} i + {.3} j + {.3} k + {.3})", v[0], v[1], v[2], v[3]);
  40. }