summaryrefslogtreecommitdiff
path: root/rect.lua
blob: ca87e491635113d35cea8ce8296c1c0838364eb3 (plain)
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
local class = require'r.class'
local Pos = require'r.pos'
local Rect = class()
function Rect.from_coords(cls, x0, y0, x1, y1)
	assert(x0<x1,"x coords interchanged")
	assert(y0<y1,"y coords interchanged")
	return setmetatable({
		tl=Pos:make(x0,y0),
		br=Pos:make(x1,y1),
		x0=x0, y0=y0, x1=x1, y1=y1,
		w=x1-x0, h=y1-y0,
	}, cls)
end
function Rect.from_pos(cls, tl, br)
	assert(tl.x<br.x,"x coords interchanged")
	assert(tl.y<br.y,"y coords interchanged")
	return setmetatable({
		tl=tl, br=br,
		x0=tl.x, y0=tl.y, x1=br.x, y1=br.y,
		w=br.x-tl.x, h=br.y-tl.y,
	}, cls)
end
function Rect.from_xywh(cls, x0,y0, width,hight)
	assert(0<width, "nonpositive width")
	assert(0<hight, "nonpositive hight")
	return setmetatable({
		tl=Pos:make(x0,y0),
		br=Pos:make(x0+width,y0+hight),
		x0=x0, y0=y0,
		x1=x0+width,
		y1=y0+hight,
		w=width, h=hight,
	}, cls)
end
function Rect.from_centre_dims(cls, centre, width, hight)
	assert(0<width, "nonpositive width")
	assert(0<hight, "nonpositive hight")
	local x0,x1 = centre.x-width/2, centre.x+width/2
	local y0,y1 = centre.y-hight/2, centre.y+hight/2
	return setmetatable({
		tl=Pos:make(x0,y0),
		br=Pos:make(x1,y1),
		x0=x0,y0=y0,x1=x1,y1=y1,
		w=width, h=hight,
	}, cls)
end

function Rect.has(self, point)
	return self.x0 <= point.x and point.x <= self.x1
	   and self.y0 <= point.y and point.y <= self.y1
end

function Rect.vals(self)
	return self.x0, self.y0, self.w, self.h
end

function Rect.draw(self, mode)
	love.graphics.rectangle(mode or 'line', self:vals())
end

function Rect.__tostring(self)
	return tostring(self.tl).."\u{25af}"..tostring(self.br)
end

return Rect