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.

979 lines
44KB

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