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.

986 lines
44KB

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