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.

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