arithmetics.hpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #pragma once
  2. #include <cmath>
  3. namespace msdfgen {
  4. /// Returns the smaller of the arguments.
  5. template <typename T>
  6. inline T min(T a, T b) {
  7. return b < a ? b : a;
  8. }
  9. /// Returns the larger of the arguments.
  10. template <typename T>
  11. inline T max(T a, T b) {
  12. return a < b ? b : a;
  13. }
  14. /// Returns the middle out of three values
  15. template <typename T>
  16. inline T median(T a, T b, T c) {
  17. return max(min(a, b), min(max(a, b), c));
  18. }
  19. /// Returns the weighted average of a and b.
  20. template <typename T, typename S>
  21. inline T mix(T a, T b, S weight) {
  22. return T((S(1)-weight)*a+weight*b);
  23. }
  24. /// Clamps the number to the interval from 0 to 1.
  25. template <typename T>
  26. inline T clamp(T n) {
  27. return n >= T(0) && n <= T(1) ? n : T(n > T(0));
  28. }
  29. /// Clamps the number to the interval from 0 to b.
  30. template <typename T>
  31. inline T clamp(T n, T b) {
  32. return n >= T(0) && n <= b ? n : T(n > T(0))*b;
  33. }
  34. /// Clamps the number to the interval from a to b.
  35. template <typename T>
  36. inline T clamp(T n, T a, T b) {
  37. return n >= a && n <= b ? n : n < a ? a : b;
  38. }
  39. /// Returns 1 for positive values, -1 for negative values, and 0 for zero.
  40. template <typename T>
  41. inline int sign(T n) {
  42. return (T(0) < n)-(n < T(0));
  43. }
  44. /// Returns 1 for non-negative values and -1 for negative values.
  45. template <typename T>
  46. inline int nonZeroSign(T n) {
  47. return 2*(n > T(0))-1;
  48. }
  49. }