arithmetics.hpp 1.3 KB

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