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.

83 lines
2.1 KiB

  1. //
  2. // Lol Engine
  3. //
  4. // Copyright © 2010—2020 Sam Hocevar <sam@hocevar.net>
  5. //
  6. // Lol Engine is free software. It comes without any warranty, to
  7. // the extent permitted by applicable law. You can redistribute it
  8. // and/or modify it under the terms of the Do What the Fuck You Want
  9. // to Public License, Version 2, as published by the WTFPL Task Force.
  10. // See http://www.wtfpl.net/ for more details.
  11. //
  12. #pragma once
  13. //
  14. // Various math utility functions
  15. // ——————————————————————————————
  16. //
  17. #include <lol/math/functions.h>
  18. #include <cstdlib>
  19. #include <stdint.h>
  20. namespace lol
  21. {
  22. /* Next power of two. */
  23. template <typename T> static inline T PotUp(T val)
  24. {
  25. val = val - 1;
  26. if (sizeof(val) > 4) val = val | ((uint64_t)val >> 32);
  27. if (sizeof(val) > 2) val = val | ((uint64_t)val >> 16);
  28. if (sizeof(val) > 1) val = val | ((uint64_t)val >> 8);
  29. val = val | ((uint64_t)val >> 4);
  30. val = val | ((uint64_t)val >> 2);
  31. val = val | ((uint64_t)val >> 1);
  32. return val + 1;
  33. }
  34. //Damp for float
  35. template <typename T1, typename T2, typename Tf> static inline T1 damp(const T1 &a, const T2 &b, const Tf &x, const Tf &dt)
  36. {
  37. if (dt <= .0f)
  38. return a;
  39. return lol::lerp(a, b, dt / (dt + x));
  40. }
  41. //SmoothClamp clamps x in [a - sd, b + sd] and returns a value in [a, b] that is smoothed at the borders.
  42. static inline float SmoothClamp(float &x, float a, float b, float sd)
  43. {
  44. if (b < a)
  45. Swap(a, b);
  46. float tx = x;
  47. float ta = a - sd;
  48. float tb = b + sd;
  49. if (sd > 0.f)
  50. {
  51. if ((b - a) < 2.f * sd)
  52. sd = .5f * (b - a);
  53. if (tx < a + sd && tx > a - sd)
  54. {
  55. float t = (tx - a) / sd;
  56. t = 0.25f * (t + 1.0f) * (t + 1.0f);
  57. tx = a + t * sd;
  58. }
  59. else if (tx < b + sd && tx > b - sd)
  60. {
  61. float t = -(tx - b) / sd;
  62. t = 0.25f * (t + 1.0f) * (t + 1.0f);
  63. tx = b - t * sd;
  64. }
  65. }
  66. x = lol::clamp(x, ta, tb);
  67. return lol::clamp(tx, a, b);
  68. }
  69. } /* namespace lol */