vec2.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #pragma once
  2. #include <stdbool.h>
  3. #include <cmath>
  4. #define VEC2_EPSILON (float)0.001
  5. class Vec2 {
  6. public:
  7. float x;
  8. float y;
  9. Vec2()
  10. : x(0)
  11. , y(0) {
  12. }
  13. Vec2(float x_, float y_)
  14. : x(x_)
  15. , y(y_) {
  16. }
  17. Vec2 operator+(const Vec2& rhs) const {
  18. return Vec2(x + rhs.x, y + rhs.y);
  19. }
  20. Vec2 operator+(float s) const {
  21. return Vec2(x + s, y + s);
  22. }
  23. void operator+=(const Vec2& rhs) {
  24. x += rhs.x;
  25. y += rhs.y;
  26. }
  27. Vec2 operator-(const Vec2& rhs) const {
  28. return Vec2(x - rhs.x, y - rhs.y);
  29. }
  30. Vec2 operator-(float s) const {
  31. return Vec2(x - s, y - s);
  32. }
  33. void operator-=(const Vec2& rhs) {
  34. x -= rhs.x;
  35. y -= rhs.y;
  36. }
  37. Vec2 operator*(float s) const {
  38. return Vec2(x * s, y * s);
  39. }
  40. void operator*=(float s) {
  41. x *= s;
  42. y *= s;
  43. }
  44. Vec2 operator/(float s) const {
  45. return Vec2(x / s, y / s);
  46. }
  47. bool operator==(const Vec2& rhs) const {
  48. return x == rhs.x && y == rhs.y;
  49. }
  50. // Magnitude / length of vector
  51. float mag() const {
  52. return sqrtf(x * x + y * y);
  53. }
  54. // Magnitude squared
  55. float mag2() const {
  56. return x * x + y * y;
  57. }
  58. // Dot product: this.x * v.x + this.y * v.y
  59. float dot(const Vec2& v) const {
  60. return x * v.x + y * v.y;
  61. }
  62. // Cross product
  63. float cross(const Vec2& v) const {
  64. return x * v.y - y * v.x;
  65. }
  66. void normalize(void) {
  67. float len = mag();
  68. if(len > VEC2_EPSILON) {
  69. float inverse_len = 1.0f / len;
  70. x *= inverse_len;
  71. y *= inverse_len;
  72. }
  73. }
  74. // Distance squared between this and next
  75. float dist2(const Vec2& v) const {
  76. float dx = x - v.x;
  77. float dy = y - v.y;
  78. return dx * dx + dy * dy;
  79. }
  80. // Distance between tihs and next
  81. float dist(const Vec2& v) const {
  82. return sqrtf(dist2(v));
  83. }
  84. };
  85. inline Vec2 operator*(float s, const Vec2& v) {
  86. return Vec2(s * v.x, s * v.y);
  87. }
  88. // // Returns the closest point to the line segment ab and p
  89. Vec2 Vec2_closest(const Vec2& a, const Vec2& b, const Vec2& p);