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.

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