Advertisement
candlemaster1

vmath/vmath_includes.h

Mar 26th, 2017
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #ifndef HVH_WC_MATH_VMATHINCLUDES_H
  2. #define HVH_WC_MATH_VMATHINCLUDES_H
  3.  
  4. #include <stdint.h>
  5. #include <limits.h>
  6. #include <math.h>
  7. #include <float.h>
  8.  
  9. constexpr float PI = 3.14159265359f;
  10. constexpr float QUARTER_PI = PI / 4;
  11. constexpr float HALF_PI = PI / 2;
  12. constexpr float PI2 = PI * 2;
  13. constexpr float PI4 = PI * 4;
  14.  
  15. constexpr float TAU = 6.28318530718f;
  16. constexpr float QUARTER_TAU = TAU / 4;
  17. constexpr float HALF_TAU = TAU / 2;
  18. constexpr float TAU2 = TAU * 2;
  19. constexpr float TAU4 = TAU * 4;
  20.  
  21. constexpr float to_radians(float degrees)
  22. {
  23.     return degrees * (TAU / 360.0f);
  24. }
  25.  
  26. constexpr float to_degrees(float radians)
  27. {
  28.     return radians * (360.0f / TAU);
  29. }
  30.  
  31. inline float springf(float current, float& velocity, float target, float delta_time, float tightness)
  32. {
  33.     float current_to_target = target - current;
  34.     float spring_force = current_to_target * tightness;
  35.     float damping_force = -velocity * 2 * sqrtf(tightness);
  36.     float force = spring_force + damping_force;
  37.     velocity += force * delta_time;
  38.     float displacement = velocity * delta_time;
  39.     return current + displacement;
  40. }
  41.  
  42. inline float lerp(float from, float to, float amount)
  43. {
  44.     return (from * (1.0f - amount)) + (to * amount);
  45. }
  46.  
  47. inline float clampf(float value, float minimum, float maximum)
  48. {
  49.     return fminf(maximum, fmaxf(minimum, value));
  50. }
  51.  
  52. inline bool nearly_equals(float a, float b, float epsilon = 0.000001f)
  53. {
  54.     // http://floating-point-gui.de/errors/comparison/
  55.     float absA = fabsf(a);
  56.     float absB = fabsf(b);
  57.     float diff = fabsf(a - b);
  58.  
  59.     if (a == b) // shortcut, handles infinities
  60.         return true;
  61.     else if (a == 0 || b == 0 || diff < FLT_EPSILON)
  62.         return diff < epsilon;
  63.     else
  64.         return (diff / fminf(absA + absB, FLT_MAX)) < epsilon;
  65. }
  66.  
  67. #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement