summaryrefslogtreecommitdiff
path: root/city/geometry.lua
blob: 163239370a8a53e507b980d2bc665df4adb62a75 (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
local geom = {}

local function class(tbl)
   setmetatable(tbl, tbl)
   return tbl
end

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- point
--
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

geom.point = class{
   __call = function(this, x, y)
      local pt = {}
      pt.x = x
      pt.y = y
      setmetatable(pt, {__index=this})
      return pt
   end,

   distance_to = function(self, pt)
      local d_x = self.x - pt.x
      local d_y = self.y - pt.y
      return math.sqrt(d_x*d_x + d_y*d_y)
   end,
}


-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- square
--
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

geom.square = class{
   __call = function(this, center, span)
      local square = {}
      square.center = center
      square.span = span
      square.x = this.axis_range(center.x, span/2)
      square.y = this.axis_range(center.y, span/2)
      setmetatable(square, {__index=this})
      return square
   end,

   axis_range = function(c, r) return {min=c-r, max=c+r} end,

   contains = function(self, point)
      local x_overlap =
	 (point.x > self.x.min) and (point.x <= self.x.max)
      local y_overlap =
	 (point.y > self.y.min) and (point.y <= self.y.max)

      if x_overlap and y_overlap then
	 return true
      end
      return false
   end
}

return geom