The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

985 lines
44KB

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