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.

math.hpp 13KB

6 years ago
6 years ago
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. float getWidth() const {
  323. return size.x;
  324. }
  325. float getHeight() const {
  326. return size.y;
  327. }
  328. /** Returns the center point of the rectangle.
  329. Returns a NaN coordinate if pos=-inf and size=inf.
  330. */
  331. Vec getCenter() const {
  332. return pos.plus(size.mult(0.5f));
  333. }
  334. Vec getTopLeft() const {
  335. return pos;
  336. }
  337. Vec getTopRight() const {
  338. return Vec(getRight(), getTop());
  339. }
  340. Vec getBottomLeft() const {
  341. return Vec(getLeft(), getBottom());
  342. }
  343. Vec getBottomRight() const {
  344. return Vec(getRight(), getBottom());
  345. }
  346. /** Clamps the edges of the rectangle to fit within a bound. */
  347. Rect clamp(Rect bound) const {
  348. Rect r;
  349. r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x);
  350. r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y);
  351. r.size.x = math::clamp(pos.x + size.x, bound.pos.x, bound.pos.x + bound.size.x) - r.pos.x;
  352. r.size.y = math::clamp(pos.y + size.y, bound.pos.y, bound.pos.y + bound.size.y) - r.pos.y;
  353. return r;
  354. }
  355. /** Nudges the position to fix inside a bounding box. */
  356. Rect nudge(Rect bound) const {
  357. Rect r;
  358. r.size = size;
  359. r.pos.x = math::clampSafe(pos.x, bound.pos.x, bound.pos.x + bound.size.x - size.x);
  360. r.pos.y = math::clampSafe(pos.y, bound.pos.y, bound.pos.y + bound.size.y - size.y);
  361. return r;
  362. }
  363. /** Returns the bounding box of the union of `this` and `b`. */
  364. Rect expand(Rect b) const {
  365. Rect r;
  366. r.pos.x = std::fmin(pos.x, b.pos.x);
  367. r.pos.y = std::fmin(pos.y, b.pos.y);
  368. r.size.x = std::fmax(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x;
  369. r.size.y = std::fmax(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y;
  370. return r;
  371. }
  372. /** Returns the intersection of `this` and `b`. */
  373. Rect intersect(Rect b) const {
  374. Rect r;
  375. r.pos.x = std::fmax(pos.x, b.pos.x);
  376. r.pos.y = std::fmax(pos.y, b.pos.y);
  377. r.size.x = std::fmin(pos.x + size.x, b.pos.x + b.size.x) - r.pos.x;
  378. r.size.y = std::fmin(pos.y + size.y, b.pos.y + b.size.y) - r.pos.y;
  379. return r;
  380. }
  381. /** Returns a Rect with its position set to zero. */
  382. Rect zeroPos() const {
  383. return Rect(Vec(), size);
  384. }
  385. /** Expands each corner. */
  386. Rect grow(Vec delta) const {
  387. Rect r;
  388. r.pos = pos.minus(delta);
  389. r.size = size.plus(delta.mult(2.f));
  390. return r;
  391. }
  392. /** Contracts each corner. */
  393. Rect shrink(Vec delta) const {
  394. Rect r;
  395. r.pos = pos.plus(delta);
  396. r.size = size.minus(delta.mult(2.f));
  397. return r;
  398. }
  399. /** Returns `pos + size * p` */
  400. Vec interpolate(Vec p) {
  401. return pos.plus(size.mult(p));
  402. }
  403. // Method aliases
  404. bool isContaining(Vec v) const {
  405. return contains(v);
  406. }
  407. bool isIntersecting(Rect r) const {
  408. return intersects(r);
  409. }
  410. bool isEqual(Rect r) const {
  411. return equals(r);
  412. }
  413. };
  414. inline Vec Vec::clamp(Rect bound) const {
  415. return Vec(
  416. math::clamp(x, bound.pos.x, bound.pos.x + bound.size.x),
  417. math::clamp(y, bound.pos.y, bound.pos.y + bound.size.y)
  418. );
  419. }
  420. inline Vec Vec::clampSafe(Rect bound) const {
  421. return Vec(
  422. math::clampSafe(x, bound.pos.x, bound.pos.x + bound.size.x),
  423. math::clampSafe(y, bound.pos.y, bound.pos.y + bound.size.y)
  424. );
  425. }
  426. // Operator overloads for Vec
  427. inline Vec operator+(const Vec& a) {
  428. return a;
  429. }
  430. inline Vec operator-(const Vec& a) {
  431. return a.neg();
  432. }
  433. inline Vec operator+(const Vec& a, const Vec& b) {
  434. return a.plus(b);
  435. }
  436. inline Vec operator-(const Vec& a, const Vec& b) {
  437. return a.minus(b);
  438. }
  439. inline Vec operator*(const Vec& a, const Vec& b) {
  440. return a.mult(b);
  441. }
  442. inline Vec operator*(const Vec& a, const float& b) {
  443. return a.mult(b);
  444. }
  445. inline Vec operator*(const float& a, const Vec& b) {
  446. return b.mult(a);
  447. }
  448. inline Vec operator/(const Vec& a, const Vec& b) {
  449. return a.div(b);
  450. }
  451. inline Vec operator/(const Vec& a, const float& b) {
  452. return a.div(b);
  453. }
  454. inline Vec operator+=(Vec& a, const Vec& b) {
  455. return a = a.plus(b);
  456. }
  457. inline Vec operator-=(Vec& a, const Vec& b) {
  458. return a = a.minus(b);
  459. }
  460. inline Vec operator*=(Vec& a, const Vec& b) {
  461. return a = a.mult(b);
  462. }
  463. inline Vec operator*=(Vec& a, const float& b) {
  464. return a = a.mult(b);
  465. }
  466. inline Vec operator/=(Vec& a, const Vec& b) {
  467. return a = a.div(b);
  468. }
  469. inline Vec operator/=(Vec& a, const float& b) {
  470. return a = a.div(b);
  471. }
  472. inline bool operator==(const Vec& a, const Vec& b) {
  473. return a.equals(b);
  474. }
  475. inline bool operator!=(const Vec& a, const Vec& b) {
  476. return !a.equals(b);
  477. }
  478. // Operator overloads for Rect
  479. inline bool operator==(const Rect& a, const Rect& b) {
  480. return a.equals(b);
  481. }
  482. inline bool operator!=(const Rect& a, const Rect& b) {
  483. return !a.equals(b);
  484. }
  485. /** Expands a Vec and Rect into a comma-separated list.
  486. Useful for print debugging.
  487. printf("(%f %f) (%f %f %f %f)", VEC_ARGS(v), RECT_ARGS(r));
  488. Or passing the values to a C function.
  489. nvgRect(vg, RECT_ARGS(r));
  490. */
  491. #define VEC_ARGS(v) (v).x, (v).y
  492. #define RECT_ARGS(r) (r).pos.x, (r).pos.y, (r).size.x, (r).size.y
  493. } // namespace math
  494. } // namespace rack