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.

521 lines
12KB

  1. #pragma once
  2. #include <complex>
  3. #include <algorithm> // for std::min, max
  4. #include <common.hpp>
  5. namespace rack {
  6. /** Supplemental `<cmath>` functions and types
  7. */
  8. namespace math {
  9. ////////////////////
  10. // basic integer functions
  11. ////////////////////
  12. /** Returns true if `x` is odd. */
  13. template <typename T>
  14. bool isEven(T x) {
  15. return x % 2 == 0;
  16. }
  17. /** Returns true if `x` is odd. */
  18. template <typename T>
  19. bool isOdd(T x) {
  20. return x % 2 != 0;
  21. }
  22. /** Limits `x` between `a` and `b`.
  23. If `b < a`, returns a.
  24. */
  25. inline int clamp(int x, int a, int b) {
  26. return std::max(std::min(x, b), a);
  27. }
  28. /** Limits `x` between `a` and `b`.
  29. If `b < a`, switches the two values.
  30. */
  31. inline int clampSafe(int x, int a, int b) {
  32. return (a <= b) ? clamp(x, a, b) : clamp(x, b, a);
  33. }
  34. /** Euclidean modulus. Always returns `0 <= mod < b`.
  35. `b` must be positive.
  36. See https://en.wikipedia.org/wiki/Euclidean_division
  37. */
  38. inline int eucMod(int a, int b) {
  39. int mod = a % b;
  40. if (mod < 0) {
  41. mod += b;
  42. }
  43. return mod;
  44. }
  45. /** Euclidean division.
  46. `b` must be positive.
  47. */
  48. inline int eucDiv(int a, int b) {
  49. int div = a / b;
  50. int mod = a % b;
  51. if (mod < 0) {
  52. div -= 1;
  53. }
  54. return div;
  55. }
  56. inline void eucDivMod(int a, int b, int* div, int* mod) {
  57. *div = a / b;
  58. *mod = a % b;
  59. if (*mod < 0) {
  60. *div -= 1;
  61. *mod += b;
  62. }
  63. }
  64. /** Returns `floor(log_2(n))`, or 0 if `n == 1`. */
  65. inline int log2(int n) {
  66. int i = 0;
  67. while (n >>= 1) {
  68. i++;
  69. }
  70. return i;
  71. }
  72. /** Returns whether `n` is a power of 2. */
  73. template <typename T>
  74. bool isPow2(T n) {
  75. return n > 0 && (n & (n - 1)) == 0;
  76. }
  77. /** Returns 1 for positive numbers, -1 for negative numbers, and 0 for zero.
  78. See https://en.wikipedia.org/wiki/Sign_function.
  79. */
  80. template <typename T>
  81. T sgn(T x) {
  82. return x > 0 ? 1 : (x < 0 ? -1 : 0);
  83. }
  84. ////////////////////
  85. // basic float functions
  86. ////////////////////
  87. /** Limits `x` between `a` and `b`.
  88. If `b < a`, returns a.
  89. */
  90. inline float clamp(float x, float a = 0.f, float b = 1.f) {
  91. return std::fmax(std::fmin(x, b), a);
  92. }
  93. /** Limits `x` between `a` and `b`.
  94. If `b < a`, switches the two values.
  95. */
  96. inline float clampSafe(float x, float a = 0.f, float b = 1.f) {
  97. return (a <= b) ? clamp(x, a, b) : clamp(x, b, a);
  98. }
  99. /** Converts -0.f to 0.f. Leaves all other values unchanged. */
  100. inline float normalizeZero(float x) {
  101. return x + 0.f;
  102. }
  103. /** Euclidean modulus. Always returns `0 <= mod < b`.
  104. See https://en.wikipedia.org/wiki/Euclidean_division.
  105. */
  106. inline float eucMod(float a, float b) {
  107. float mod = std::fmod(a, b);
  108. if (mod < 0.f) {
  109. mod += b;
  110. }
  111. return mod;
  112. }
  113. /** Returns whether `a` is within epsilon distance from `b`. */
  114. inline bool isNear(float a, float b, float epsilon = 1e-6f) {
  115. return std::fabs(a - b) <= epsilon;
  116. }
  117. /** If the magnitude of `x` if less than epsilon, return 0. */
  118. inline float chop(float x, float epsilon = 1e-6f) {
  119. return std::fabs(x) <= epsilon ? 0.f : x;
  120. }
  121. /** Rescales `x` from the range `[xMin, xMax]` to `[yMin, yMax]`.
  122. */
  123. inline float rescale(float x, float xMin, float xMax, float yMin = 0.f, float yMax = 1.f) {
  124. return yMin + (x - xMin) / (xMax - xMin) * (yMax - yMin);
  125. }
  126. /** Linearly interpolates between `a` and `b`, from `p = 0` to `p = 1`.
  127. */
  128. inline float crossfade(float a, float b, float p) {
  129. return a + (b - a) * p;
  130. }
  131. /** Linearly interpolates an array `p` with index `x`.
  132. The array at `p` must be at least length `floor(x) + 2`.
  133. */
  134. inline float interpolateLinear(const float* p, float x) {
  135. int xi = x;
  136. float xf = x - xi;
  137. return crossfade(p[xi], p[xi + 1], xf);
  138. }
  139. /** Complex multiplication `c = a * b`.
  140. Arguments may be the same pointers.
  141. Example:
  142. cmultf(ar, ai, br, bi, &ar, &ai);
  143. */
  144. inline void complexMult(float ar, float ai, float br, float bi, float* cr, float* ci) {
  145. *cr = ar * br - ai * bi;
  146. *ci = ar * bi + ai * br;
  147. }
  148. ////////////////////
  149. // 2D vector and rectangle
  150. ////////////////////
  151. struct Rect;
  152. /** 2-dimensional vector of floats, representing a point on the plane for graphics.
  153. */
  154. struct Vec {
  155. float x = 0.f;
  156. float y = 0.f;
  157. Vec() {}
  158. Vec(float x) : x(x), y(x) {}
  159. Vec(float x, float y) : x(x), y(y) {}
  160. float& operator[](int i) {
  161. return (i == 0) ? x : y;
  162. }
  163. const float& operator[](int i) const {
  164. return (i == 0) ? x : y;
  165. }
  166. /** Negates the vector.
  167. Equivalent to a reflection across the `y = -x` line.
  168. */
  169. Vec neg() const {
  170. return Vec(-x, -y);
  171. }
  172. Vec plus(Vec b) const {
  173. return Vec(x + b.x, y + b.y);
  174. }
  175. Vec minus(Vec b) const {
  176. return Vec(x - b.x, y - b.y);
  177. }
  178. Vec mult(float s) const {
  179. return Vec(x * s, y * s);
  180. }
  181. Vec mult(Vec b) const {
  182. return Vec(x * b.x, y * b.y);
  183. }
  184. Vec div(float s) const {
  185. return Vec(x / s, y / s);
  186. }
  187. Vec div(Vec b) const {
  188. return Vec(x / b.x, y / b.y);
  189. }
  190. float dot(Vec b) const {
  191. return x * b.x + y * b.y;
  192. }
  193. float arg() const {
  194. return std::atan2(y, x);
  195. }
  196. float norm() const {
  197. return std::hypot(x, y);
  198. }
  199. Vec normalize() const {
  200. return div(norm());
  201. }
  202. float square() const {
  203. return x * x + y * y;
  204. }
  205. float area() const {
  206. return x * y;
  207. }
  208. /** Rotates counterclockwise in radians. */
  209. Vec rotate(float angle) {
  210. float sin = std::sin(angle);
  211. float cos = std::cos(angle);
  212. return Vec(x * cos - y * sin, x * sin + y * cos);
  213. }
  214. /** Swaps the coordinates.
  215. Equivalent to a reflection across the `y = x` line.
  216. */
  217. Vec flip() const {
  218. return Vec(y, x);
  219. }
  220. Vec min(Vec b) const {
  221. return Vec(std::fmin(x, b.x), std::fmin(y, b.y));
  222. }
  223. Vec max(Vec b) const {
  224. return Vec(std::fmax(x, b.x), std::fmax(y, b.y));
  225. }
  226. Vec abs() const {
  227. return Vec(std::fabs(x), std::fabs(y));
  228. }
  229. Vec round() const {
  230. return Vec(std::round(x), std::round(y));
  231. }
  232. Vec floor() const {
  233. return Vec(std::floor(x), std::floor(y));
  234. }
  235. Vec ceil() const {
  236. return Vec(std::ceil(x), std::ceil(y));
  237. }
  238. bool equals(Vec b) const {
  239. return x == b.x && y == b.y;
  240. }
  241. bool isZero() const {
  242. return x == 0.f && y == 0.f;
  243. }
  244. bool isFinite() const {
  245. return std::isfinite(x) && std::isfinite(y);
  246. }
  247. Vec clamp(Rect bound) const;
  248. Vec clampSafe(Rect bound) const;
  249. Vec crossfade(Vec b, float p) {
  250. return this->plus(b.minus(*this).mult(p));
  251. }
  252. // Method aliases
  253. bool isEqual(Vec b) const {
  254. return equals(b);
  255. }
  256. };
  257. /** 2-dimensional rectangle for graphics.
  258. Mathematically, Rects include points on its left/top edge but *not* its right/bottom edge.
  259. The infinite Rect (equal to the entire plane) is defined using pos=-inf and size=inf.
  260. */
  261. struct Rect {
  262. Vec pos;
  263. Vec size;
  264. Rect() {}
  265. Rect(Vec pos, Vec size) : pos(pos), size(size) {}
  266. Rect(float posX, float posY, float sizeX, float sizeY) : pos(Vec(posX, posY)), size(Vec(sizeX, sizeY)) {}
  267. /** Constructs a Rect from the upper-left position `a` and lower-right pos `b`. */
  268. static Rect fromMinMax(Vec a, Vec b) {
  269. return Rect(a, b.minus(a));
  270. }
  271. /** Returns the infinite Rect. */
  272. static Rect inf() {
  273. return Rect(Vec(-INFINITY, -INFINITY), Vec(INFINITY, INFINITY));
  274. }
  275. /** Returns whether this Rect contains a point, inclusive on the left/top, exclusive on the right/bottom.
  276. Correctly handles infinite Rects.
  277. */
  278. bool contains(Vec v) const {
  279. return (pos.x <= v.x) && (size.x == INFINITY || v.x < pos.x + size.x)
  280. && (pos.y <= v.y) && (size.y == INFINITY || v.y < pos.y + size.y);
  281. }
  282. /** Returns whether this Rect contains (is a superset of) a Rect.
  283. Correctly handles infinite Rects.
  284. */
  285. bool contains(Rect r) const {
  286. return (pos.x <= r.pos.x) && (r.pos.x - size.x <= pos.x - r.size.x)
  287. && (pos.y <= r.pos.y) && (r.pos.y - size.y <= pos.y - r.size.y);
  288. }
  289. /** Returns whether this Rect overlaps with another Rect.
  290. Correctly handles infinite Rects.
  291. */
  292. bool intersects(Rect r) const {
  293. return (r.size.x == INFINITY || pos.x < r.pos.x + r.size.x) && (size.x == INFINITY || r.pos.x < pos.x + size.x)
  294. && (r.size.y == INFINITY || pos.y < r.pos.y + r.size.y) && (size.y == INFINITY || r.pos.y < pos.y + size.y);
  295. }
  296. bool equals(Rect r) const {
  297. return pos.equals(r.pos) && size.equals(r.size);
  298. }
  299. float getLeft() const {
  300. return pos.x;
  301. }
  302. float getRight() const {
  303. return (size.x == INFINITY) ? INFINITY : (pos.x + size.x);
  304. }
  305. float getTop() const {
  306. return pos.y;
  307. }
  308. float getBottom() const {
  309. return (size.y == INFINITY) ? INFINITY : (pos.y + size.y);
  310. }
  311. /** Returns the center point of the rectangle.
  312. Returns a NaN coordinate if pos=-inf and size=inf.
  313. */
  314. Vec getCenter() const {
  315. return pos.plus(size.mult(0.5f));
  316. }
  317. Vec getTopLeft() const {
  318. return pos;
  319. }
  320. Vec getTopRight() const {
  321. return Vec(getRight(), getTop());
  322. }
  323. Vec getBottomLeft() const {
  324. return Vec(getLeft(), getBottom());
  325. }
  326. Vec getBottomRight() const {
  327. return Vec(getRight(), getBottom());
  328. }
  329. /** Clamps the edges of the rectangle to fit within a bound. */
  330. Rect clamp(Rect bound) const {
  331. Rect r;
  332. r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x);
  333. r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y);
  334. r.size.x = math::clamp(pos.x + size.x, bound.pos.x, bound.pos.x + bound.size.x) - r.pos.x;
  335. r.size.y = math::clamp(pos.y + size.y, bound.pos.y, bound.pos.y + bound.size.y) - r.pos.y;
  336. return r;
  337. }
  338. /** Nudges the position to fix inside a bounding box. */
  339. Rect nudge(Rect bound) const {
  340. Rect r;
  341. r.size = size;
  342. r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x - size.x);
  343. r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y - size.y);
  344. return r;
  345. }
  346. /** Returns the bounding box of the union of `this` and `b`. */
  347. Rect expand(Rect b) const {
  348. Rect r;
  349. r.pos.x = std::fmin(pos.x, b.pos.x);
  350. r.pos.y = std::fmin(pos.y, b.pos.y);
  351. r.size.x = std::fmax(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x;
  352. r.size.y = std::fmax(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y;
  353. return r;
  354. }
  355. /** Returns the intersection of `this` and `b`. */
  356. Rect intersect(Rect b) const {
  357. Rect r;
  358. r.pos.x = std::fmax(pos.x, b.pos.x);
  359. r.pos.y = std::fmax(pos.y, b.pos.y);
  360. r.size.x = std::fmin(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x;
  361. r.size.y = std::fmin(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y;
  362. return r;
  363. }
  364. /** Returns a Rect with its position set to zero. */
  365. Rect zeroPos() const {
  366. return Rect(Vec(), size);
  367. }
  368. /** Expands each corner.
  369. Use a negative delta to shrink.
  370. */
  371. Rect grow(Vec delta) const {
  372. Rect r;
  373. r.pos = pos.minus(delta);
  374. r.size = size.plus(delta.mult(2.f));
  375. return r;
  376. }
  377. // Method aliases
  378. bool isContaining(Vec v) const {
  379. return contains(v);
  380. }
  381. bool isIntersecting(Rect r) const {
  382. return intersects(r);
  383. }
  384. bool isEqual(Rect r) const {
  385. return equals(r);
  386. }
  387. };
  388. inline Vec Vec::clamp(Rect bound) const {
  389. return Vec(
  390. math::clamp(x, bound.pos.x, bound.pos.x + bound.size.x),
  391. math::clamp(y, bound.pos.y, bound.pos.y + bound.size.y));
  392. }
  393. inline Vec Vec::clampSafe(Rect bound) const {
  394. return Vec(
  395. math::clampSafe(x, bound.pos.x, bound.pos.x + bound.size.x),
  396. math::clampSafe(y, bound.pos.y, bound.pos.y + bound.size.y));
  397. }
  398. // Operator overloads for Vec
  399. inline Vec operator+(const Vec& a) {
  400. return a;
  401. }
  402. inline Vec operator-(const Vec& a) {
  403. return a.neg();
  404. }
  405. inline Vec operator+(const Vec& a, const Vec& b) {
  406. return a.plus(b);
  407. }
  408. inline Vec operator-(const Vec& a, const Vec& b) {
  409. return a.minus(b);
  410. }
  411. inline Vec operator*(const Vec& a, const Vec& b) {
  412. return a.mult(b);
  413. }
  414. inline Vec operator*(const Vec& a, const float& b) {
  415. return a.mult(b);
  416. }
  417. inline Vec operator*(const float& a, const Vec& b) {
  418. return b.mult(a);
  419. }
  420. inline Vec operator/(const Vec& a, const Vec& b) {
  421. return a.div(b);
  422. }
  423. inline Vec operator/(const Vec& a, const float& b) {
  424. return a.div(b);
  425. }
  426. inline Vec operator+=(Vec& a, const Vec& b) {
  427. return a = a.plus(b);
  428. }
  429. inline Vec operator-=(Vec& a, const Vec& b) {
  430. return a = a.minus(b);
  431. }
  432. inline Vec operator*=(Vec& a, const Vec& b) {
  433. return a = a.mult(b);
  434. }
  435. inline Vec operator*=(Vec& a, const float& b) {
  436. return a = a.mult(b);
  437. }
  438. inline Vec operator/=(Vec& a, const Vec& b) {
  439. return a = a.div(b);
  440. }
  441. inline Vec operator/=(Vec& a, const float& b) {
  442. return a = a.div(b);
  443. }
  444. inline bool operator==(const Vec& a, const Vec& b) {
  445. return a.equals(b);
  446. }
  447. inline bool operator!=(const Vec& a, const Vec& b) {
  448. return !a.equals(b);
  449. }
  450. // Operator overloads for Rect
  451. inline bool operator==(const Rect& a, const Rect& b) {
  452. return a.equals(b);
  453. }
  454. inline bool operator!=(const Rect& a, const Rect& b) {
  455. return !a.equals(b);
  456. }
  457. /** Expands a Vec and Rect into a comma-separated list.
  458. Useful for print debugging.
  459. printf("(%f %f) (%f %f %f %f)", VEC_ARGS(v), RECT_ARGS(r));
  460. Or passing the values to a C function.
  461. nvgRect(vg, RECT_ARGS(r));
  462. */
  463. #define VEC_ARGS(v) (v).x, (v).y
  464. #define RECT_ARGS(r) (r).pos.x, (r).pos.y, (r).size.x, (r).size.y
  465. } // namespace math
  466. } // namespace rack