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.

math.cpp 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*!
  2. *
  3. * \file src/math/math.cpp
  4. * \brief Vector and Matrix math
  5. *
  6. * \author Mongoose
  7. * \author xythobuz
  8. */
  9. #include <cstdlib>
  10. #include <cmath>
  11. #include <float.h>
  12. #include <algorithm>
  13. #include "global.h"
  14. #include "math/Vec3.h"
  15. #include "math/Matrix.h"
  16. #include "math/math.h"
  17. bool equalEpsilon(float a, float b) {
  18. float epsilon = FLT_EPSILON;
  19. if (fabs(a - b) <= (std::max(fabs(a), fabs(b)) * epsilon))
  20. return true;
  21. return false;
  22. }
  23. int intersectionLinePolygon(float intersect[3],
  24. float p1[3], float p2[3], float polygon[3][3]) {
  25. assert(polygon != NULL);
  26. // float normal[3], a[3], b[3];
  27. Vec3 a, b, normal, pA, pB;
  28. float d, denominator, mu;
  29. pA = Vec3(p1);
  30. pB = Vec3(p2);
  31. // Find normal
  32. a = Vec3(polygon[1]) - Vec3(polygon[0]);
  33. b = Vec3(polygon[2]) - Vec3(polygon[0]);
  34. normal = Vec3::cross(a, b);
  35. normal.normalize();
  36. // find D
  37. d = (normal.x * polygon[0][0] -
  38. normal.y * polygon[0][1] -
  39. normal.z * polygon[0][2]);
  40. // line segment parallel to plane?
  41. a = pB - pA;
  42. denominator = Vec3::dot(normal, a);
  43. if (denominator > 0.0)
  44. return 0;
  45. // Line segment contains intercept point?
  46. mu = -((d + Vec3::dot(normal, pA)) / denominator);
  47. if (mu < 0.0 || mu > 1.0)
  48. return 0;
  49. b = pA + (a * mu);
  50. intersect[0] = b.x;
  51. intersect[1] = b.y;
  52. intersect[2] = b.z;
  53. // See if the intercept is bound by polygon by winding number
  54. // assume convex polygons here for sure
  55. double theta = Vec3::dot(b - Vec3(polygon[0]), normal); // b = intersect
  56. if (theta >= 90.0) // Yeah I know
  57. return 0;
  58. return 1;
  59. }
  60. float distance(const float a[3], const float b[3]) {
  61. return sqrtf(((b[0] - a[0]) * (b[0] - a[0])) +
  62. ((b[1] - a[1]) * (b[1] - a[1])) +
  63. ((b[2] - a[2]) * (b[2] - a[2])));
  64. }
  65. void midpoint(const float a[3], const float b[3], float mid[3]) {
  66. mid[0] = (a[0] + b[0]) / 2.0f;
  67. mid[1] = (a[1] + b[1]) / 2.0f;
  68. mid[2] = (a[2] + b[2]) / 2.0f;
  69. }
  70. float randomNum(float from, float to) {
  71. return from + ((to - from) * rand() / (RAND_MAX + 1.0f));
  72. }