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.

537 lines
13KB

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