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.

juce_Rectangle.h 45KB

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