summaryrefslogtreecommitdiff
path: root/rect.c
blob: bcc95cd871dcf6ec76859a66ddb4a1d5833aaf6f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include "maths.h"
#include "rect.h"

Rectangle make_rect(int x, int y, int w, int h) {
	Rectangle r;
	r.x = x;
	r.y = y;
	r.w = w;
	r.h = h;
	return r;
}

int rects_overlap(const Rectangle* a, const Rectangle* b) {
	return
		a->x + a->w > b->x &&
		a->y + a->h > b->y &&
		a->x < b->x + b->w &&
		a->y < b->y + b->h;
}

int rects_overlap2(
	int x0,
	int y0,
	int w0,
	int h0,
	int x1,
	int y1,
	int w1,
	int h1
) {
	return
		x0 + w0 > x1 &&
		y0 + h0 > y1 &&
		x0 < x1 + w1 &&
		y0 < y1 + h1;
}

int point_rect_overlap(
	const Rectangle* r,
	int px,
	int py
) {
	return
		px >= r->x &&
		py >= r->y &&
		px <= r->x + r->w &&
		py <= r->y + r->h;
}

int point_rect_overlap2(
	int x,
	int y,
	int w,
	int h,
	int px,
	int py
) {
	return
		px > x &&
		py > y &&
		px < x + w &&
		py < y + h;
}

Rectangle rect_intersect(
	const Rectangle* a,
	const Rectangle* b
) {
	int x1, y1, x2, y2;
	Rectangle r;
  x1 = maxi(a->x, b->x);
  y1 = maxi(a->y, b->y);
  x2 = mini(a->x + a->w, b->x + b->w);
  y2 = mini(a->y + a->h, b->y + b->h);
  r.x = x1;
  r.y = y1;
  r.w = maxi(0, x2 - x1);
  r.h = maxi(0, y2 - y1);
  return r;
}

Rectangle* rect_merge(
	Rectangle* d,
	const Rectangle* r
) {
	int x1, y1, x2, y2;
	x1 = mini(d->x, r->x);
	y1 = mini(d->y, r->y);
	x2 = maxi(d->x + d->w, r->x + r->w);
	y2 = maxi(d->y + d->h, r->y + r->h);
	d->x = x1;
	d->y = y1;
	d->w = x2 - x1;
	d->h = y2 - y1;
	return d;
}