Open Source Tomb Raider Engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Vec3.cpp 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /*!
  2. * \file src/math/Vec3.cpp
  3. * \brief 3D Math vector
  4. *
  5. * \author Mongoose
  6. */
  7. #include <math.h>
  8. #include "global.h"
  9. #include "math/Vec3.h"
  10. Vec3::Vec3(float _x, float _y, float _z) {
  11. x = _x;
  12. y = _y;
  13. z = _z;
  14. }
  15. Vec3::Vec3(float v[3]) {
  16. assert(v != nullptr);
  17. x = v[0];
  18. y = v[1];
  19. z = v[2];
  20. }
  21. float Vec3::magnitude() {
  22. return sqrtf(x * x + y * y + z * z);
  23. }
  24. void Vec3::normalize() {
  25. float norm = magnitude();
  26. x /= norm;
  27. y /= norm;
  28. z /= norm;
  29. }
  30. Vec3 Vec3::unit() {
  31. float norm = magnitude();
  32. return Vec3(x / norm,
  33. y / norm,
  34. z / norm);
  35. }
  36. Vec3 Vec3::operator +(const Vec3& v) {
  37. return Vec3(x + v.x,
  38. y + v.y,
  39. z + v.z);
  40. }
  41. Vec3 Vec3::operator -(const Vec3& v) {
  42. return Vec3(x - v.x,
  43. y - v.y,
  44. z - v.z);
  45. }
  46. Vec3 Vec3::operator -() {
  47. return Vec3(-x,
  48. -y,
  49. -z);
  50. }
  51. Vec3 Vec3::operator *(float s) {
  52. return Vec3(s * x,
  53. s * y,
  54. s * z);
  55. }
  56. Vec3 Vec3::operator /(float s) {
  57. return Vec3(x / s,
  58. y / s,
  59. z / s);
  60. }
  61. float Vec3::operator *(const Vec3& v) {
  62. return dot(*this, v);
  63. }
  64. Vec3& Vec3::operator +=(const Vec3& v) {
  65. x += v.x;
  66. y += v.y;
  67. z += v.z;
  68. return *this;
  69. }
  70. Vec3& Vec3::operator -=(const Vec3& v) {
  71. x -= v.x;
  72. y -= v.y;
  73. z -= v.z;
  74. return *this;
  75. }
  76. Vec3& Vec3::operator *=(float s) {
  77. x *= s;
  78. y *= s;
  79. z *= s;
  80. return *this;
  81. }
  82. bool Vec3::operator ==(const Vec3& v) {
  83. return equalEpsilon(x, v.x)
  84. && equalEpsilon(y, v.y)
  85. && equalEpsilon(z, v.z);
  86. }
  87. bool Vec3::operator !=(const Vec3& v) {
  88. return !((*this) == v);
  89. }
  90. float Vec3::dot(const Vec3& u, const Vec3& v) {
  91. return (u.x * v.x + u.y * v.y + u.z * v.z);
  92. }
  93. Vec3 Vec3::cross(const Vec3& u, const Vec3& v) {
  94. return Vec3(u.y * v.z - u.z * v.y,
  95. u.z * v.x - u.x * v.z,
  96. u.x * v.y - u.y * v.x);
  97. }