initial commit, lordsawar source, slightly modified
[lordsawar] / src / rectangle.h
1 //  Copyright (C) 2007 Ole Laursen
2 //
3 //  This program is free software; you can redistribute it and/or modify
4 //  it under the terms of the GNU General Public License as published by
5 //  the Free Software Foundation; either version 3 of the License, or
6 //  (at your option) any later version.
7 //
8 //  This program is distributed in the hope that it will be useful,
9 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
10 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 //  GNU Library General Public License for more details.
12 //
13 //  You should have received a copy of the GNU General Public License
14 //  along with this program; if not, write to the Free Software
15 //  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 
16 //  02110-1301, USA.
17
18 #ifndef RECTANGLE_H
19 #define RECTANGLE_H
20
21 #include "vector.h"
22
23 struct Rectangle
24 {
25     Rectangle() : x(pos.x), y(pos.y), w(dim.x), h(dim.y) {}
26
27     Rectangle(int x_, int y_, int w_, int h_)
28         : pos(x_, y_), dim(w_, h_), x(pos.x), y(pos.y), w(dim.x), h(dim.y) {}
29
30     Rectangle(Vector<int> pos_, Vector<int> dim_)
31         : pos(pos_), dim(dim_), x(pos.x), y(pos.y), w(dim.x), h(dim.y) {}
32     
33     Rectangle(const Rectangle &other)
34         : pos(other.pos), dim(other.dim), x(pos.x), y(pos.y), w(dim.x), h(dim.y) {}
35
36     const Rectangle &operator=(const Rectangle &other)
37     {
38         pos = other.pos;
39         dim = other.dim;
40         return *this;
41     }
42
43     Vector<int> pos, dim; // position and dimensions
44
45     // accessors - sometimes it's easier with .x instead of .pos.x
46     int &x, &y, &w, &h;
47 };
48
49 inline bool operator==(const Rectangle &lhs, const Rectangle &rhs)
50 {
51     return lhs.pos == rhs.pos && lhs.dim == rhs.dim;
52 }
53
54 inline bool operator!=(const Rectangle &lhs, const Rectangle &rhs)
55 {
56     return !(lhs == rhs);
57 }
58
59 inline bool is_inside(const Rectangle &r, Vector<int> v)
60 {
61     return r.x <= v.x && v.x < r.x + r.w
62         && r.y <= v.y && v.y < r.y + r.h;
63 }
64
65 inline bool is_overlapping(const Rectangle &r1, const Rectangle &r2)
66 {
67     // find the leftmost rectangle
68     Rectangle const *l, *r;
69     if (r1.x <= r2.x)
70     {
71         l = &r1;
72         r = &r2;
73     }
74     else
75     {
76         l = &r2;
77         r = &r1;
78     }
79     
80     // leftmost is too far to the left
81     if (l->x + l->w <= r->x)
82         return false;
83
84     // find the upper rectangle
85     Rectangle const *u, *d;
86     if (r1.y <= r2.y)
87     {
88         u = &r1;
89         d = &r2;
90     }
91     else
92     {
93         u = &r2;
94         d = &r1;
95     }
96
97     // upper is too high up
98     if (u->y + u->h <= d->y)
99         return false;
100
101     return true;
102 }
103
104 #endif