1 #ifndef RECTANGLEUTIL_HH
2 #define RECTANGLEUTIL_HH
3 
4 namespace RectangleUtil {
5 
insideRectangle(int x,int y,int width,int height,int px,int py)6 inline bool insideRectangle(int x, int y, int width, int height, int px, int py) {
7 
8     return
9         px >= x &&
10         px < (x + width) &&
11         py >= y &&
12         py < (y + height);
13 }
14 
15 /*
16  * Determines if a point is inside a rectangle-like objects border.
17  * @param rect A rectangle-like object that has accessors for x, y, width, and
18  *        height.
19  * @param x
20  * @param y
21  * @param border The size of the border.
22  * @returns true if point is inside the rectangle-like object.
23 */
24 
25 template <typename RectangleLike>
insideBorder(const RectangleLike & rect,int x,int y,int border)26 bool insideBorder(const RectangleLike& rect,
27                   int x, int y,
28                   int border) {
29     const int w = static_cast<int>(rect.width()) - border;
30     const int h = static_cast<int>(rect.height()) - border;
31     return insideRectangle(rect.x() + border, rect.y() + border, w, h, x, y);
32 }
33 
34 
35 
36 /*
37  * Determines if rectangle 'a' overlaps rectangle 'b'
38  * @returns true if 'a' overlaps 'b'
39  *
40  *    outside              overlap situations
41  *
42  *  a----a            a----a         a--------a  b--------b
43  *  |    | b----b     |  b-+--b      | b----b |  | a----a |
44  *  a----a |    |     a--+-a  |      | |    | |  | |    | |
45  *         b----b        b----b      | b----b |  | a----a |
46  *                                   a--------a  b--------b
47  *
48  */
49 
overlapRectangles(int ax,int ay,int awidth,int aheight,int bx,int by,int bwidth,int bheight)50 inline bool overlapRectangles(
51         int ax, int ay, int awidth, int aheight,
52         int bx, int by, int bwidth, int bheight) {
53 
54     bool do_not_overlap =
55          ax > (bx + bwidth)
56       || bx > (ax + awidth)
57       || ay > (by + bheight)
58       || by > (ay + aheight);
59 
60     return !do_not_overlap;
61 }
62 
63 
64 /*
65  * Determines if rectangle 'a' overlaps rectangle 'b'
66  * @param a - rectangle a
67  * @param b - rectangle b
68  * @returns true if 'a' overlaps 'b'
69  */
70 template <typename RectangleLikeA, typename RectangleLikeB>
overlapRectangles(const RectangleLikeA & a,const RectangleLikeB & b)71 bool overlapRectangles(const RectangleLikeA& a, const RectangleLikeB& b) {
72 
73     return overlapRectangles(
74             a.x(), a.y(), a.width(), a.height(),
75             b.x(), b.y(), b.width(), b.height());
76 }
77 
78 } // namespace RectangleUtil
79 
80 
81 #endif // RECTANGLEUTIL_HH
82