vector.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "vector.h"
  2. #include <math.h>
  3. #include <float.h>
  4. #undef vector_add
  5. #undef vector_sub
  6. #undef vector_mul
  7. #undef vector_div
  8. Vector vector_add(Vector a, Vector b) {
  9. return (Vector){.x = a.x + b.x, .y = a.y + b.y};
  10. }
  11. Vector vector_sub(Vector a, Vector b) {
  12. return (Vector){.x = a.x - b.x, .y = a.y - b.y};
  13. }
  14. Vector vector_mul(Vector a, Vector b) {
  15. return (Vector){.x = a.x * b.x, .y = a.y * b.y};
  16. }
  17. Vector vector_div(Vector a, Vector b) {
  18. return (Vector){.x = a.x / b.x, .y = a.y / b.y};
  19. }
  20. Vector vector_addf(Vector a, float b) {
  21. return (Vector){.x = a.x + b, .y = a.y + b};
  22. }
  23. Vector vector_subf(Vector a, float b) {
  24. return (Vector){.x = a.x - b, .y = a.y - b};
  25. }
  26. Vector vector_mulf(Vector a, float b) {
  27. return (Vector){.x = a.x * b, .y = a.y * b};
  28. }
  29. Vector vector_divf(Vector a, float b) {
  30. return (Vector){.x = a.x / b, .y = a.y / b};
  31. }
  32. float vector_length(Vector v) {
  33. return sqrtf(v.x * v.x + v.y * v.y);
  34. }
  35. Vector vector_normalize(Vector v) {
  36. float length = vector_length(v);
  37. if(length < FLT_EPSILON) {
  38. return (Vector){0, 0};
  39. }
  40. return (Vector){v.x / length, v.y / length};
  41. }
  42. float vector_dot(Vector a, Vector b) {
  43. return a.x * b.x + a.y * b.y;
  44. }
  45. Vector vector_rand() {
  46. float x = (rand() % __INT_MAX__) / (float)__INT_MAX__;
  47. float y = (rand() % __INT_MAX__) / (float)__INT_MAX__;
  48. return (Vector){x, y};
  49. }