Audio plugin host https://kx.studio/carla
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.

997 lines
45KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For the technical preview this file cannot be licensed commercially.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. #ifndef DOXYGEN
  16. namespace detail
  17. {
  18. template <typename> struct Tag {};
  19. inline auto getNumericValue (StringRef s, Tag<int>) { return s.text.getIntValue32(); }
  20. inline auto getNumericValue (StringRef s, Tag<double>) { return s.text.getDoubleValue(); }
  21. inline auto getNumericValue (StringRef s, Tag<float>) { return static_cast<float> (s.text.getDoubleValue()); }
  22. template <typename ValueType>
  23. ValueType parseAfterSpace (StringRef s) noexcept
  24. {
  25. return static_cast<ValueType> (getNumericValue (s.text.findEndOfWhitespace(),
  26. Tag<ValueType>{}));
  27. }
  28. inline int floorAsInt (int n) noexcept { return n; }
  29. inline int floorAsInt (float n) noexcept { return n > (float) std::numeric_limits<int>::min() ? (int) std::floor (n) : std::numeric_limits<int>::min(); }
  30. inline int floorAsInt (double n) noexcept { return n > (double) std::numeric_limits<int>::min() ? (int) std::floor (n) : std::numeric_limits<int>::min(); }
  31. inline int ceilAsInt (int n) noexcept { return n; }
  32. inline int ceilAsInt (float n) noexcept { return n < (float) std::numeric_limits<int>::max() ? (int) std::ceil (n) : std::numeric_limits<int>::max(); }
  33. inline int ceilAsInt (double n) noexcept { return n < (double) std::numeric_limits<int>::max() ? (int) std::ceil (n) : std::numeric_limits<int>::max(); }
  34. } // namespace detail
  35. #endif
  36. //==============================================================================
  37. /**
  38. Manages a rectangle and allows geometric operations to be performed on it.
  39. @see RectangleList, Path, Line, Point
  40. @tags{Graphics}
  41. */
  42. template <typename ValueType>
  43. class Rectangle
  44. {
  45. public:
  46. //==============================================================================
  47. /** Creates a rectangle of zero size.
  48. The default coordinates will be (0, 0, 0, 0).
  49. */
  50. Rectangle() = default;
  51. /** Creates a copy of another rectangle. */
  52. Rectangle (const Rectangle&) = default;
  53. /** Creates a rectangle with a given position and size. */
  54. Rectangle (ValueType initialX, ValueType initialY,
  55. ValueType width, ValueType height) noexcept
  56. : pos (initialX, initialY),
  57. w (width), h (height)
  58. {
  59. }
  60. /** Creates a rectangle with a given size, and a position of (0, 0). */
  61. Rectangle (ValueType width, ValueType height) noexcept
  62. : w (width), h (height)
  63. {
  64. }
  65. /** Creates a Rectangle from the positions of two opposite corners. */
  66. Rectangle (Point<ValueType> corner1, Point<ValueType> corner2) noexcept
  67. : pos (jmin (corner1.x, corner2.x),
  68. jmin (corner1.y, corner2.y)),
  69. w (corner1.x - corner2.x),
  70. h (corner1.y - corner2.y)
  71. {
  72. if (w < ValueType()) w = -w;
  73. if (h < ValueType()) h = -h;
  74. }
  75. /** Creates a Rectangle from a set of left, right, top, bottom coordinates.
  76. The right and bottom values must be larger than the left and top ones, or the resulting
  77. rectangle will have a negative size.
  78. */
  79. static Rectangle leftTopRightBottom (ValueType left, ValueType top,
  80. ValueType right, ValueType bottom) noexcept
  81. {
  82. return { left, top, right - left, bottom - top };
  83. }
  84. /** Creates a copy of another rectangle. */
  85. Rectangle& operator= (const Rectangle&) = default;
  86. /** Destructor. */
  87. ~Rectangle() = default;
  88. //==============================================================================
  89. /** Returns true if the rectangle's width or height are zero or less */
  90. bool isEmpty() const noexcept { return w <= ValueType() || h <= ValueType(); }
  91. /** Returns true if the rectangle's values are all finite numbers, i.e. not NaN or infinity. */
  92. inline bool isFinite() const noexcept { return pos.isFinite() && juce_isfinite (w) && juce_isfinite (h); }
  93. /** Returns the x coordinate of the rectangle's left-hand-side. */
  94. inline ValueType getX() const noexcept { return pos.x; }
  95. /** Returns the y coordinate of the rectangle's top edge. */
  96. inline ValueType getY() const noexcept { return pos.y; }
  97. /** Returns the width of the rectangle. */
  98. inline ValueType getWidth() const noexcept { return w; }
  99. /** Returns the height of the rectangle. */
  100. inline ValueType getHeight() const noexcept { return h; }
  101. /** Returns the x coordinate of the rectangle's right-hand-side. */
  102. inline ValueType getRight() const noexcept { return pos.x + w; }
  103. /** Returns the y coordinate of the rectangle's bottom edge. */
  104. inline ValueType getBottom() const noexcept { return pos.y + h; }
  105. /** Returns the x coordinate of the rectangle's centre. */
  106. ValueType getCentreX() const noexcept { return pos.x + w / (ValueType) 2; }
  107. /** Returns the y coordinate of the rectangle's centre. */
  108. ValueType getCentreY() const noexcept { return pos.y + h / (ValueType) 2; }
  109. /** Returns the centre point of the rectangle. */
  110. Point<ValueType> getCentre() const noexcept { return { pos.x + w / (ValueType) 2,
  111. pos.y + h / (ValueType) 2 }; }
  112. /** Returns the aspect ratio of the rectangle's width / height.
  113. If widthOverHeight is true, it returns width / height; if widthOverHeight is false,
  114. it returns height / width. */
  115. ValueType getAspectRatio (bool widthOverHeight = true) const noexcept { return widthOverHeight ? w / h : h / w; }
  116. //==============================================================================
  117. /** Returns the rectangle's top-left position as a Point. */
  118. inline Point<ValueType> getPosition() const noexcept { return pos; }
  119. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  120. inline void setPosition (Point<ValueType> newPos) noexcept { pos = newPos; }
  121. /** Changes the position of the rectangle's top-left corner (leaving its size unchanged). */
  122. inline void setPosition (ValueType newX, ValueType newY) noexcept { pos.setXY (newX, newY); }
  123. /** Returns the rectangle's top-left position as a Point. */
  124. Point<ValueType> getTopLeft() const noexcept { return pos; }
  125. /** Returns the rectangle's top-right position as a Point. */
  126. Point<ValueType> getTopRight() const noexcept { return { pos.x + w, pos.y }; }
  127. /** Returns the rectangle's bottom-left position as a Point. */
  128. Point<ValueType> getBottomLeft() const noexcept { return { pos.x, pos.y + h }; }
  129. /** Returns the rectangle's bottom-right position as a Point. */
  130. Point<ValueType> getBottomRight() const noexcept { return { pos.x + w, pos.y + h }; }
  131. /** Returns the rectangle's left and right positions as a Range. */
  132. Range<ValueType> getHorizontalRange() const noexcept { return Range<ValueType>::withStartAndLength (pos.x, w); }
  133. /** Returns the rectangle's top and bottom positions as a Range. */
  134. Range<ValueType> getVerticalRange() const noexcept { return Range<ValueType>::withStartAndLength (pos.y, h); }
  135. /** Changes the rectangle's size, leaving the position of its top-left corner unchanged. */
  136. void setSize (ValueType newWidth, ValueType newHeight) noexcept { w = newWidth; h = newHeight; }
  137. /** Changes all the rectangle's coordinates. */
  138. void setBounds (ValueType newX, ValueType newY,
  139. ValueType newWidth, ValueType newHeight) noexcept { pos.x = newX; pos.y = newY; w = newWidth; h = newHeight; }
  140. /** Changes the rectangle's X coordinate */
  141. inline void setX (ValueType newX) noexcept { pos.x = newX; }
  142. /** Changes the rectangle's Y coordinate */
  143. inline void setY (ValueType newY) noexcept { pos.y = newY; }
  144. /** Changes the rectangle's width */
  145. inline void setWidth (ValueType newWidth) noexcept { w = newWidth; }
  146. /** Changes the rectangle's height */
  147. inline void setHeight (ValueType newHeight) noexcept { h = newHeight; }
  148. /** Changes the position of the rectangle's centre (leaving its size unchanged). */
  149. inline void setCentre (ValueType newCentreX, ValueType newCentreY) noexcept { pos.x = newCentreX - w / (ValueType) 2;
  150. pos.y = newCentreY - h / (ValueType) 2; }
  151. /** Changes the position of the rectangle's centre (leaving its size unchanged). */
  152. inline void setCentre (Point<ValueType> newCentre) noexcept { setCentre (newCentre.x, newCentre.y); }
  153. /** Changes the position of the rectangle's left and right edges. */
  154. void setHorizontalRange (Range<ValueType> range) noexcept { pos.x = range.getStart(); w = range.getLength(); }
  155. /** Changes the position of the rectangle's top and bottom edges. */
  156. void setVerticalRange (Range<ValueType> range) noexcept { pos.y = range.getStart(); h = range.getLength(); }
  157. /** Returns a rectangle which has the same size and y-position as this one, but with a different x-position. */
  158. JUCE_NODISCARD Rectangle withX (ValueType newX) const noexcept { return { newX, pos.y, w, h }; }
  159. /** Returns a rectangle which has the same size and x-position as this one, but with a different y-position. */
  160. JUCE_NODISCARD Rectangle withY (ValueType newY) const noexcept { return { pos.x, newY, w, h }; }
  161. /** Returns a rectangle which has the same size and y-position as this one, but whose right-hand edge has the given position. */
  162. JUCE_NODISCARD Rectangle withRightX (ValueType newRightX) const noexcept { return { newRightX - w, pos.y, w, h }; }
  163. /** Returns a rectangle which has the same size and x-position as this one, but whose bottom edge has the given position. */
  164. JUCE_NODISCARD Rectangle withBottomY (ValueType newBottomY) const noexcept { return { pos.x, newBottomY - h, w, h }; }
  165. /** Returns a rectangle with the same size as this one, but a new position. */
  166. JUCE_NODISCARD Rectangle withPosition (ValueType newX, ValueType newY) const noexcept { return { newX, newY, w, h }; }
  167. /** Returns a rectangle with the same size as this one, but a new position. */
  168. JUCE_NODISCARD Rectangle withPosition (Point<ValueType> newPos) const noexcept { return { newPos.x, newPos.y, w, h }; }
  169. /** Returns a rectangle whose size is the same as this one, but whose top-left position is (0, 0). */
  170. JUCE_NODISCARD Rectangle withZeroOrigin() const noexcept { return { w, h }; }
  171. /** Returns a rectangle with the same size as this one, but a new centre position. */
  172. JUCE_NODISCARD Rectangle withCentre (Point<ValueType> newCentre) const noexcept { return { newCentre.x - w / (ValueType) 2,
  173. newCentre.y - h / (ValueType) 2, w, h }; }
  174. /** Returns a rectangle which has the same position and height as this one, but with a different width. */
  175. JUCE_NODISCARD Rectangle withWidth (ValueType newWidth) const noexcept { return { pos.x, pos.y, jmax (ValueType(), newWidth), h }; }
  176. /** Returns a rectangle which has the same position and width as this one, but with a different height. */
  177. JUCE_NODISCARD Rectangle withHeight (ValueType newHeight) const noexcept { return { pos.x, pos.y, w, jmax (ValueType(), newHeight) }; }
  178. /** Returns a rectangle with the same top-left position as this one, but a new size. */
  179. JUCE_NODISCARD Rectangle withSize (ValueType newWidth, ValueType newHeight) const noexcept { return { pos.x, pos.y, jmax (ValueType(), newWidth), jmax (ValueType(), newHeight) }; }
  180. /** Returns a rectangle with the same centre position as this one, but a new size. */
  181. JUCE_NODISCARD Rectangle withSizeKeepingCentre (ValueType newWidth, ValueType newHeight) const noexcept { return { pos.x + (w - newWidth) / (ValueType) 2,
  182. pos.y + (h - newHeight) / (ValueType) 2, newWidth, newHeight }; }
  183. /** Moves the x position, adjusting the width so that the right-hand edge remains in the same place.
  184. If the x is moved to be on the right of the current right-hand edge, the width will be set to zero.
  185. @see withLeft
  186. */
  187. void setLeft (ValueType newLeft) noexcept { w = jmax (ValueType(), pos.x + w - newLeft); pos.x = newLeft; }
  188. /** Returns a new rectangle with a different x position, but the same right-hand edge as this one.
  189. If the new x is beyond the right of the current right-hand edge, the width will be set to zero.
  190. @see setLeft
  191. */
  192. JUCE_NODISCARD Rectangle withLeft (ValueType newLeft) const noexcept { return { newLeft, pos.y, jmax (ValueType(), pos.x + w - newLeft), h }; }
  193. /** Moves the y position, adjusting the height so that the bottom edge remains in the same place.
  194. If the y is moved to be below the current bottom edge, the height will be set to zero.
  195. @see withTop
  196. */
  197. void setTop (ValueType newTop) noexcept { h = jmax (ValueType(), pos.y + h - newTop); pos.y = newTop; }
  198. /** Returns a new rectangle with a different y position, but the same bottom edge as this one.
  199. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  200. @see setTop
  201. */
  202. JUCE_NODISCARD Rectangle withTop (ValueType newTop) const noexcept { return { pos.x, newTop, w, jmax (ValueType(), pos.y + h - newTop) }; }
  203. /** Adjusts the width so that the right-hand edge of the rectangle has this new value.
  204. If the new right is below the current X value, the X will be pushed down to match it.
  205. @see getRight, withRight
  206. */
  207. void setRight (ValueType newRight) noexcept { pos.x = jmin (pos.x, newRight); w = newRight - pos.x; }
  208. /** Returns a new rectangle with a different right-hand edge position, but the same left-hand edge as this one.
  209. If the new right edge is below the current left-hand edge, the width will be set to zero.
  210. @see setRight
  211. */
  212. JUCE_NODISCARD Rectangle withRight (ValueType newRight) const noexcept { return { jmin (pos.x, newRight), pos.y, jmax (ValueType(), newRight - pos.x), h }; }
  213. /** Adjusts the height so that the bottom edge of the rectangle has this new value.
  214. If the new bottom is lower than the current Y value, the Y will be pushed down to match it.
  215. @see getBottom, withBottom
  216. */
  217. void setBottom (ValueType newBottom) noexcept { pos.y = jmin (pos.y, newBottom); h = newBottom - pos.y; }
  218. /** Returns a new rectangle with a different bottom edge position, but the same top edge as this one.
  219. If the new y is beyond the bottom of the current rectangle, the height will be set to zero.
  220. @see setBottom
  221. */
  222. JUCE_NODISCARD Rectangle withBottom (ValueType newBottom) const noexcept { return { pos.x, jmin (pos.y, newBottom), w, jmax (ValueType(), newBottom - pos.y) }; }
  223. /** Returns a version of this rectangle with the given amount removed from its left-hand edge. */
  224. JUCE_NODISCARD Rectangle withTrimmedLeft (ValueType amountToRemove) const noexcept { return withLeft (pos.x + amountToRemove); }
  225. /** Returns a version of this rectangle with the given amount removed from its right-hand edge. */
  226. JUCE_NODISCARD Rectangle withTrimmedRight (ValueType amountToRemove) const noexcept { return withWidth (w - amountToRemove); }
  227. /** Returns a version of this rectangle with the given amount removed from its top edge. */
  228. JUCE_NODISCARD Rectangle withTrimmedTop (ValueType amountToRemove) const noexcept { return withTop (pos.y + amountToRemove); }
  229. /** Returns a version of this rectangle with the given amount removed from its bottom edge. */
  230. JUCE_NODISCARD Rectangle withTrimmedBottom (ValueType amountToRemove) const noexcept { return withHeight (h - amountToRemove); }
  231. //==============================================================================
  232. /** Moves the rectangle's position by adding amount to its x and y coordinates. */
  233. void translate (ValueType deltaX,
  234. ValueType deltaY) noexcept
  235. {
  236. pos.x += deltaX;
  237. pos.y += deltaY;
  238. }
  239. /** Returns a rectangle which is the same as this one moved by a given amount. */
  240. Rectangle translated (ValueType deltaX,
  241. ValueType deltaY) const noexcept
  242. {
  243. return { pos.x + deltaX, pos.y + deltaY, w, h };
  244. }
  245. /** Returns a rectangle which is the same as this one moved by a given amount. */
  246. Rectangle operator+ (Point<ValueType> deltaPosition) const noexcept
  247. {
  248. return { pos.x + deltaPosition.x, pos.y + deltaPosition.y, w, h };
  249. }
  250. /** Moves this rectangle by a given amount. */
  251. Rectangle& operator+= (Point<ValueType> deltaPosition) noexcept
  252. {
  253. pos += deltaPosition;
  254. return *this;
  255. }
  256. /** Returns a rectangle which is the same as this one moved by a given amount. */
  257. Rectangle operator- (Point<ValueType> deltaPosition) const noexcept
  258. {
  259. return { pos.x - deltaPosition.x, pos.y - deltaPosition.y, w, h };
  260. }
  261. /** Moves this rectangle by a given amount. */
  262. Rectangle& operator-= (Point<ValueType> deltaPosition) noexcept
  263. {
  264. pos -= deltaPosition;
  265. return *this;
  266. }
  267. /** Returns a rectangle that has been scaled by the given amount, centred around the origin.
  268. Note that if the rectangle has int coordinates and it's scaled by a
  269. floating-point amount, then the result will be converted back to integer
  270. coordinates using getSmallestIntegerContainer().
  271. */
  272. template <typename FloatType>
  273. Rectangle operator* (FloatType scaleFactor) const noexcept
  274. {
  275. Rectangle r (*this);
  276. r *= scaleFactor;
  277. return r;
  278. }
  279. /** Scales this rectangle by the given amount, centred around the origin.
  280. Note that if the rectangle has int coordinates and it's scaled by a
  281. floating-point amount, then the result will be converted back to integer
  282. coordinates using getSmallestIntegerContainer().
  283. */
  284. template <typename FloatType>
  285. Rectangle operator*= (FloatType scaleFactor) noexcept
  286. {
  287. Rectangle<FloatType> ((FloatType) pos.x * scaleFactor,
  288. (FloatType) pos.y * scaleFactor,
  289. (FloatType) w * scaleFactor,
  290. (FloatType) h * scaleFactor).copyWithRounding (*this);
  291. return *this;
  292. }
  293. /** Scales this rectangle by the given X and Y factors, centred around the origin.
  294. Note that if the rectangle has int coordinates and it's scaled by a
  295. floating-point amount, then the result will be converted back to integer
  296. coordinates using getSmallestIntegerContainer().
  297. */
  298. template <typename FloatType>
  299. Rectangle operator*= (Point<FloatType> scaleFactor) noexcept
  300. {
  301. Rectangle<FloatType> ((FloatType) pos.x * scaleFactor.x,
  302. (FloatType) pos.y * scaleFactor.y,
  303. (FloatType) w * scaleFactor.x,
  304. (FloatType) h * scaleFactor.y).copyWithRounding (*this);
  305. return *this;
  306. }
  307. /** Scales this rectangle by the given amount, centred around the origin. */
  308. template <typename FloatType>
  309. Rectangle operator/ (FloatType scaleFactor) const noexcept
  310. {
  311. Rectangle r (*this);
  312. r /= scaleFactor;
  313. return r;
  314. }
  315. /** Scales this rectangle by the given amount, centred around the origin. */
  316. template <typename FloatType>
  317. Rectangle operator/= (FloatType scaleFactor) noexcept
  318. {
  319. Rectangle<FloatType> ((FloatType) pos.x / scaleFactor,
  320. (FloatType) pos.y / scaleFactor,
  321. (FloatType) w / scaleFactor,
  322. (FloatType) h / scaleFactor).copyWithRounding (*this);
  323. return *this;
  324. }
  325. /** Scales this rectangle by the given X and Y factors, centred around the origin. */
  326. template <typename FloatType>
  327. Rectangle operator/= (Point<FloatType> scaleFactor) noexcept
  328. {
  329. Rectangle<FloatType> ((FloatType) pos.x / scaleFactor.x,
  330. (FloatType) pos.y / scaleFactor.y,
  331. (FloatType) w / scaleFactor.x,
  332. (FloatType) h / scaleFactor.y).copyWithRounding (*this);
  333. return *this;
  334. }
  335. /** Expands the rectangle by a given amount.
  336. Effectively, its new size is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  337. @see expanded, reduce, reduced
  338. */
  339. void expand (ValueType deltaX,
  340. ValueType deltaY) noexcept
  341. {
  342. auto nw = jmax (ValueType(), w + deltaX * 2);
  343. auto nh = jmax (ValueType(), h + deltaY * 2);
  344. setBounds (pos.x - deltaX, pos.y - deltaY, nw, nh);
  345. }
  346. /** Returns a rectangle that is larger than this one by a given amount.
  347. Effectively, the rectangle returned is (x - deltaX, y - deltaY, w + deltaX * 2, h + deltaY * 2).
  348. @see expand, reduce, reduced
  349. */
  350. Rectangle expanded (ValueType deltaX,
  351. ValueType deltaY) const noexcept
  352. {
  353. auto nw = jmax (ValueType(), w + deltaX * 2);
  354. auto nh = jmax (ValueType(), h + deltaY * 2);
  355. return { pos.x - deltaX, pos.y - deltaY, nw, nh };
  356. }
  357. /** Returns a rectangle that is larger than this one by a given amount.
  358. Effectively, the rectangle returned is (x - delta, y - delta, w + delta * 2, h + delta * 2).
  359. @see expand, reduce, reduced
  360. */
  361. Rectangle expanded (ValueType delta) const noexcept
  362. {
  363. return expanded (delta, delta);
  364. }
  365. /** Shrinks the rectangle by a given amount.
  366. Effectively, its new size is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  367. @see reduced, expand, expanded
  368. */
  369. void reduce (ValueType deltaX,
  370. ValueType deltaY) noexcept
  371. {
  372. expand (-deltaX, -deltaY);
  373. }
  374. /** Returns a rectangle that is smaller than this one by a given amount.
  375. Effectively, the rectangle returned is (x + deltaX, y + deltaY, w - deltaX * 2, h - deltaY * 2).
  376. @see reduce, expand, expanded
  377. */
  378. Rectangle reduced (ValueType deltaX,
  379. ValueType deltaY) const noexcept
  380. {
  381. return expanded (-deltaX, -deltaY);
  382. }
  383. /** Returns a rectangle that is smaller than this one by a given amount.
  384. Effectively, the rectangle returned is (x + delta, y + delta, w - delta * 2, h - delta * 2).
  385. @see reduce, expand, expanded
  386. */
  387. Rectangle reduced (ValueType delta) const noexcept
  388. {
  389. return reduced (delta, delta);
  390. }
  391. /** Removes a strip from the top of this rectangle, reducing this rectangle
  392. by the specified amount and returning the section that was removed.
  393. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  394. return (100, 100, 300, 50) and leave this rectangle as (100, 150, 300, 250).
  395. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  396. that value.
  397. */
  398. Rectangle removeFromTop (ValueType amountToRemove) noexcept
  399. {
  400. const Rectangle r (pos.x, pos.y, w, jmin (amountToRemove, h));
  401. pos.y += r.h; h -= r.h;
  402. return r;
  403. }
  404. /** Removes a strip from the left-hand edge of this rectangle, reducing this rectangle
  405. by the specified amount and returning the section that was removed.
  406. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  407. return (100, 100, 50, 300) and leave this rectangle as (150, 100, 250, 300).
  408. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  409. that value.
  410. */
  411. Rectangle removeFromLeft (ValueType amountToRemove) noexcept
  412. {
  413. const Rectangle r (pos.x, pos.y, jmin (amountToRemove, w), h);
  414. pos.x += r.w; w -= r.w;
  415. return r;
  416. }
  417. /** Removes a strip from the right-hand edge of this rectangle, reducing this rectangle
  418. by the specified amount and returning the section that was removed.
  419. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  420. return (350, 100, 50, 300) and leave this rectangle as (100, 100, 250, 300).
  421. If amountToRemove is greater than the width of this rectangle, it'll be clipped to
  422. that value.
  423. */
  424. Rectangle removeFromRight (ValueType amountToRemove) noexcept
  425. {
  426. amountToRemove = jmin (amountToRemove, w);
  427. const Rectangle r (pos.x + w - amountToRemove, pos.y, amountToRemove, h);
  428. w -= amountToRemove;
  429. return r;
  430. }
  431. /** Removes a strip from the bottom of this rectangle, reducing this rectangle
  432. by the specified amount and returning the section that was removed.
  433. E.g. if this rectangle is (100, 100, 300, 300) and amountToRemove is 50, this will
  434. return (100, 350, 300, 50) and leave this rectangle as (100, 100, 300, 250).
  435. If amountToRemove is greater than the height of this rectangle, it'll be clipped to
  436. that value.
  437. */
  438. Rectangle removeFromBottom (ValueType amountToRemove) noexcept
  439. {
  440. amountToRemove = jmin (amountToRemove, h);
  441. const Rectangle r (pos.x, pos.y + h - amountToRemove, w, amountToRemove);
  442. h -= amountToRemove;
  443. return r;
  444. }
  445. //==============================================================================
  446. /** Returns the nearest point to the specified point that lies within this rectangle. */
  447. Point<ValueType> getConstrainedPoint (Point<ValueType> point) const noexcept
  448. {
  449. return { jlimit (pos.x, pos.x + w, point.x),
  450. jlimit (pos.y, pos.y + h, point.y) };
  451. }
  452. /** Returns a point within this rectangle, specified as proportional coordinates.
  453. The relative X and Y values should be between 0 and 1, where 0 is the left or
  454. top of this rectangle, and 1 is the right or bottom. (Out-of-bounds values
  455. will return a point outside the rectangle).
  456. */
  457. template <typename FloatType>
  458. Point<ValueType> getRelativePoint (FloatType relativeX, FloatType relativeY) const noexcept
  459. {
  460. return { pos.x + static_cast<ValueType> ((FloatType) w * relativeX),
  461. pos.y + static_cast<ValueType> ((FloatType) h * relativeY) };
  462. }
  463. /** Returns a proportion of the width of this rectangle. */
  464. template <typename FloatType>
  465. ValueType proportionOfWidth (FloatType proportion) const noexcept
  466. {
  467. return static_cast<ValueType> ((FloatType) w * proportion);
  468. }
  469. /** Returns a proportion of the height of this rectangle. */
  470. template <typename FloatType>
  471. ValueType proportionOfHeight (FloatType proportion) const noexcept
  472. {
  473. return static_cast<ValueType> ((FloatType) h * proportion);
  474. }
  475. /** Returns a rectangle based on some proportional coordinates relative to this one.
  476. So for example getProportion ({ 0.25f, 0.25f, 0.5f, 0.5f }) would return a rectangle
  477. of half the original size, with the same centre.
  478. */
  479. template <typename FloatType>
  480. Rectangle getProportion (Rectangle<FloatType> proportionalRect) const noexcept
  481. {
  482. return { pos.x + static_cast<ValueType> (w * proportionalRect.pos.x),
  483. pos.y + static_cast<ValueType> (h * proportionalRect.pos.y),
  484. proportionOfWidth (proportionalRect.w),
  485. proportionOfHeight (proportionalRect.h) };
  486. }
  487. //==============================================================================
  488. /** Returns true if the two rectangles are identical. */
  489. bool operator== (const Rectangle& other) const noexcept { return pos == other.pos && w == other.w && h == other.h; }
  490. /** Returns true if the two rectangles are not identical. */
  491. bool operator!= (const Rectangle& other) const noexcept { return pos != other.pos || w != other.w || h != other.h; }
  492. /** Returns true if this coordinate is inside the rectangle. */
  493. bool contains (ValueType xCoord, ValueType yCoord) const noexcept
  494. {
  495. return xCoord >= pos.x && yCoord >= pos.y && xCoord < pos.x + w && yCoord < pos.y + h;
  496. }
  497. /** Returns true if this coordinate is inside the rectangle. */
  498. bool contains (Point<ValueType> point) const noexcept
  499. {
  500. return point.x >= pos.x && point.y >= pos.y && point.x < pos.x + w && point.y < pos.y + h;
  501. }
  502. /** Returns true if this other rectangle is completely inside this one. */
  503. bool contains (Rectangle other) const noexcept
  504. {
  505. return pos.x <= other.pos.x && pos.y <= other.pos.y
  506. && pos.x + w >= other.pos.x + other.w && pos.y + h >= other.pos.y + other.h;
  507. }
  508. /** Returns true if any part of another rectangle overlaps this one. */
  509. bool intersects (Rectangle other) const noexcept
  510. {
  511. return pos.x + w > other.pos.x
  512. && pos.y + h > other.pos.y
  513. && pos.x < other.pos.x + other.w
  514. && pos.y < other.pos.y + other.h
  515. && w > ValueType() && h > ValueType()
  516. && other.w > ValueType() && other.h > ValueType();
  517. }
  518. /** Returns true if any part of the given line lies inside this rectangle. */
  519. bool intersects (const Line<ValueType>& line) const noexcept
  520. {
  521. return contains (line.getStart()) || contains (line.getEnd())
  522. || line.intersects (Line<ValueType> (getTopLeft(), getTopRight()))
  523. || line.intersects (Line<ValueType> (getTopRight(), getBottomRight()))
  524. || line.intersects (Line<ValueType> (getBottomRight(), getBottomLeft()))
  525. || line.intersects (Line<ValueType> (getBottomLeft(), getTopLeft()));
  526. }
  527. /** Returns the region that is the overlap between this and another rectangle.
  528. If the two rectangles don't overlap, the rectangle returned will be empty.
  529. */
  530. Rectangle getIntersection (Rectangle other) const noexcept
  531. {
  532. auto nx = jmax (pos.x, other.pos.x);
  533. auto ny = jmax (pos.y, other.pos.y);
  534. auto nw = jmin (pos.x + w, other.pos.x + other.w) - nx;
  535. if (nw >= ValueType())
  536. {
  537. auto nh = jmin (pos.y + h, other.pos.y + other.h) - ny;
  538. if (nh >= ValueType())
  539. return { nx, ny, nw, nh };
  540. }
  541. return {};
  542. }
  543. /** Clips a set of rectangle coordinates so that they lie only within this one.
  544. This is a non-static version of intersectRectangles().
  545. Returns false if the two rectangles didn't overlap.
  546. */
  547. bool intersectRectangle (ValueType& otherX, ValueType& otherY, ValueType& otherW, ValueType& otherH) const noexcept
  548. {
  549. auto maxX = jmax (otherX, pos.x);
  550. otherW = jmin (otherX + otherW, pos.x + w) - maxX;
  551. if (otherW > ValueType())
  552. {
  553. auto maxY = jmax (otherY, pos.y);
  554. otherH = jmin (otherY + otherH, pos.y + h) - maxY;
  555. if (otherH > ValueType())
  556. {
  557. otherX = maxX; otherY = maxY;
  558. return true;
  559. }
  560. }
  561. return false;
  562. }
  563. /** Clips a rectangle so that it lies only within this one.
  564. Returns false if the two rectangles didn't overlap.
  565. */
  566. bool intersectRectangle (Rectangle<ValueType>& rectangleToClip) const noexcept
  567. {
  568. return intersectRectangle (rectangleToClip.pos.x, rectangleToClip.pos.y,
  569. rectangleToClip.w, rectangleToClip.h);
  570. }
  571. /** Returns the smallest rectangle that contains both this one and the one passed-in.
  572. If either this or the other rectangle are empty, they will not be counted as
  573. part of the resulting region.
  574. */
  575. Rectangle getUnion (Rectangle other) const noexcept
  576. {
  577. if (other.isEmpty()) return *this;
  578. if (isEmpty()) return other;
  579. auto newX = jmin (pos.x, other.pos.x);
  580. auto newY = jmin (pos.y, other.pos.y);
  581. return { newX, newY,
  582. jmax (pos.x + w, other.pos.x + other.w) - newX,
  583. jmax (pos.y + h, other.pos.y + other.h) - newY };
  584. }
  585. /** If this rectangle merged with another one results in a simple rectangle, this
  586. will set this rectangle to the result, and return true.
  587. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  588. or if they form a complex region.
  589. */
  590. bool enlargeIfAdjacent (Rectangle other) noexcept
  591. {
  592. if (pos.x == other.pos.x && getRight() == other.getRight()
  593. && (other.getBottom() >= pos.y && other.pos.y <= getBottom()))
  594. {
  595. auto newY = jmin (pos.y, other.pos.y);
  596. h = jmax (getBottom(), other.getBottom()) - newY;
  597. pos.y = newY;
  598. return true;
  599. }
  600. if (pos.y == other.pos.y && getBottom() == other.getBottom()
  601. && (other.getRight() >= pos.x && other.pos.x <= getRight()))
  602. {
  603. auto newX = jmin (pos.x, other.pos.x);
  604. w = jmax (getRight(), other.getRight()) - newX;
  605. pos.x = newX;
  606. return true;
  607. }
  608. return false;
  609. }
  610. /** If after removing another rectangle from this one the result is a simple rectangle,
  611. this will set this object's bounds to be the result, and return true.
  612. Returns false and does nothing to this rectangle if the two rectangles don't overlap,
  613. or if removing the other one would form a complex region.
  614. */
  615. bool reduceIfPartlyContainedIn (Rectangle other) noexcept
  616. {
  617. int inside = 0;
  618. auto otherR = other.getRight();
  619. if (pos.x >= other.pos.x && pos.x < otherR) inside = 1;
  620. auto otherB = other.getBottom();
  621. if (pos.y >= other.pos.y && pos.y < otherB) inside |= 2;
  622. auto r = pos.x + w;
  623. if (r >= other.pos.x && r < otherR) inside |= 4;
  624. auto b = pos.y + h;
  625. if (b >= other.pos.y && b < otherB) inside |= 8;
  626. switch (inside)
  627. {
  628. case 1 + 2 + 8: w = r - otherR; pos.x = otherR; return true;
  629. case 1 + 2 + 4: h = b - otherB; pos.y = otherB; return true;
  630. case 2 + 4 + 8: w = other.pos.x - pos.x; return true;
  631. case 1 + 4 + 8: h = other.pos.y - pos.y; return true;
  632. default: break;
  633. }
  634. return false;
  635. }
  636. /** Tries to fit this rectangle within a target area, returning the result.
  637. If this rectangle is not completely inside the target area, then it'll be
  638. shifted (without changing its size) so that it lies within the target. If it
  639. is larger than the target rectangle in either dimension, then that dimension
  640. will be reduced to fit within the target.
  641. */
  642. Rectangle constrainedWithin (Rectangle areaToFitWithin) const noexcept
  643. {
  644. auto newPos = areaToFitWithin.withSize (areaToFitWithin.getWidth() - w,
  645. areaToFitWithin.getHeight() - h)
  646. .getConstrainedPoint (pos);
  647. return { newPos.x, newPos.y,
  648. jmin (w, areaToFitWithin.getWidth()),
  649. jmin (h, areaToFitWithin.getHeight()) };
  650. }
  651. /** Returns the smallest rectangle that can contain the shape created by applying
  652. a transform to this rectangle.
  653. This should only be used on floating point rectangles.
  654. */
  655. Rectangle transformedBy (const AffineTransform& transform) const noexcept
  656. {
  657. using FloatType = typename TypeHelpers::SmallestFloatType<ValueType>::type;
  658. auto x1 = static_cast<FloatType> (pos.x), y1 = static_cast<FloatType> (pos.y);
  659. auto x2 = static_cast<FloatType> (pos.x + w), y2 = static_cast<FloatType> (pos.y);
  660. auto x3 = static_cast<FloatType> (pos.x), y3 = static_cast<FloatType> (pos.y + h);
  661. auto x4 = static_cast<FloatType> (x2), y4 = static_cast<FloatType> (y3);
  662. transform.transformPoints (x1, y1, x2, y2);
  663. transform.transformPoints (x3, y3, x4, y4);
  664. auto rx1 = jmin (x1, x2, x3, x4);
  665. auto rx2 = jmax (x1, x2, x3, x4);
  666. auto ry1 = jmin (y1, y2, y3, y4);
  667. auto ry2 = jmax (y1, y2, y3, y4);
  668. Rectangle r;
  669. Rectangle<FloatType> (rx1, ry1, rx2 - rx1, ry2 - ry1).copyWithRounding (r);
  670. return r;
  671. }
  672. /** Returns the smallest integer-aligned rectangle that completely contains this one.
  673. This is only relevant for floating-point rectangles, of course.
  674. @see toFloat(), toNearestInt(), toNearestIntEdges()
  675. */
  676. Rectangle<int> getSmallestIntegerContainer() const noexcept
  677. {
  678. return Rectangle<int>::leftTopRightBottom (detail::floorAsInt (pos.x),
  679. detail::floorAsInt (pos.y),
  680. detail::ceilAsInt (pos.x + w),
  681. detail::ceilAsInt (pos.y + h));
  682. }
  683. /** Casts this rectangle to a Rectangle<int>.
  684. This uses roundToInt to snap x, y, width and height to the nearest integer (losing precision).
  685. If the rectangle already uses integers, this will simply return a copy.
  686. @see getSmallestIntegerContainer(), toNearestIntEdges()
  687. */
  688. Rectangle<int> toNearestInt() const noexcept
  689. {
  690. return { roundToInt (pos.x), roundToInt (pos.y),
  691. roundToInt (w), roundToInt (h) };
  692. }
  693. /** Casts this rectangle to a Rectangle<int>.
  694. This uses roundToInt to snap top, left, right and bottom to the nearest integer (losing precision).
  695. If the rectangle already uses integers, this will simply return a copy.
  696. @see getSmallestIntegerContainer(), toNearestInt()
  697. */
  698. Rectangle<int> toNearestIntEdges() const noexcept
  699. {
  700. return Rectangle<int>::leftTopRightBottom (roundToInt (pos.x), roundToInt (pos.y),
  701. roundToInt (getRight()), roundToInt (getBottom()));
  702. }
  703. /** Casts this rectangle to a Rectangle<float>.
  704. @see getSmallestIntegerContainer
  705. */
  706. Rectangle<float> toFloat() const noexcept
  707. {
  708. return { static_cast<float> (pos.x), static_cast<float> (pos.y),
  709. static_cast<float> (w), static_cast<float> (h) };
  710. }
  711. /** Casts this rectangle to a Rectangle<double>.
  712. @see getSmallestIntegerContainer
  713. */
  714. Rectangle<double> toDouble() const noexcept
  715. {
  716. return { static_cast<double> (pos.x), static_cast<double> (pos.y),
  717. static_cast<double> (w), static_cast<double> (h) };
  718. }
  719. /** Casts this rectangle to a Rectangle with the given type.
  720. If the target type is a conversion from float to int, then the conversion
  721. will be done using getSmallestIntegerContainer().
  722. */
  723. template <typename TargetType>
  724. Rectangle<TargetType> toType() const noexcept
  725. {
  726. Rectangle<TargetType> r;
  727. copyWithRounding (r);
  728. return r;
  729. }
  730. /** Returns the smallest Rectangle that can contain a set of points. */
  731. static Rectangle findAreaContainingPoints (const Point<ValueType>* points, int numPoints) noexcept
  732. {
  733. if (numPoints <= 0)
  734. return {};
  735. auto minX = points[0].x;
  736. auto maxX = minX;
  737. auto minY = points[0].y;
  738. auto maxY = minY;
  739. for (int i = 1; i < numPoints; ++i)
  740. {
  741. minX = jmin (minX, points[i].x);
  742. maxX = jmax (maxX, points[i].x);
  743. minY = jmin (minY, points[i].y);
  744. maxY = jmax (maxY, points[i].y);
  745. }
  746. return { minX, minY, maxX - minX, maxY - minY };
  747. }
  748. //==============================================================================
  749. /** Static utility to intersect two sets of rectangular coordinates.
  750. Returns false if the two regions didn't overlap.
  751. @see intersectRectangle
  752. */
  753. static bool intersectRectangles (ValueType& x1, ValueType& y1, ValueType& w1, ValueType& h1,
  754. ValueType x2, ValueType y2, ValueType w2, ValueType h2) noexcept
  755. {
  756. auto x = jmax (x1, x2);
  757. w1 = jmin (x1 + w1, x2 + w2) - x;
  758. if (w1 > ValueType())
  759. {
  760. auto y = jmax (y1, y2);
  761. h1 = jmin (y1 + h1, y2 + h2) - y;
  762. if (h1 > ValueType())
  763. {
  764. x1 = x; y1 = y;
  765. return true;
  766. }
  767. }
  768. return false;
  769. }
  770. //==============================================================================
  771. /** Creates a string describing this rectangle.
  772. The string will be of the form "x y width height", e.g. "100 100 400 200".
  773. Coupled with the fromString() method, this is very handy for things like
  774. storing rectangles (particularly component positions) in XML attributes.
  775. @see fromString
  776. */
  777. String toString() const
  778. {
  779. String s;
  780. s.preallocateBytes (32);
  781. s << pos.x << ' ' << pos.y << ' ' << w << ' ' << h;
  782. return s;
  783. }
  784. /** Parses a string containing a rectangle's details.
  785. The string should contain 4 numeric tokens, in the form "x y width height". They
  786. can be comma or whitespace separated.
  787. This method is intended to go with the toString() method, to form an easy way
  788. of saving/loading rectangles as strings.
  789. @see toString
  790. */
  791. static Rectangle fromString (StringRef stringVersion)
  792. {
  793. StringArray toks;
  794. toks.addTokens (stringVersion.text.findEndOfWhitespace(), ",; \t\r\n", "");
  795. return { detail::parseAfterSpace<ValueType> (toks[0]),
  796. detail::parseAfterSpace<ValueType> (toks[1]),
  797. detail::parseAfterSpace<ValueType> (toks[2]),
  798. detail::parseAfterSpace<ValueType> (toks[3]) };
  799. }
  800. #ifndef DOXYGEN
  801. [[deprecated ("This has been renamed to transformedBy in order to match the method names used in the Point class.")]]
  802. Rectangle transformed (const AffineTransform& t) const noexcept { return transformedBy (t); }
  803. #endif
  804. private:
  805. template <typename OtherType> friend class Rectangle;
  806. Point<ValueType> pos;
  807. ValueType w {}, h {};
  808. void copyWithRounding (Rectangle<int>& result) const noexcept { result = getSmallestIntegerContainer(); }
  809. void copyWithRounding (Rectangle<float>& result) const noexcept { result = toFloat(); }
  810. void copyWithRounding (Rectangle<double>& result) const noexcept { result = toDouble(); }
  811. };
  812. } // namespace juce