summaryrefslogtreecommitdiffstats
path: root/crawl-ref/source/dat/clua/point.lua
blob: a6a80779977148d4d1cfc271aa62b62aba5e1918 (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
--------------------------------------------------------------------------
-- point.lua
--------------------------------------------------------------------------

local point_metatable = { }

point_metatable.__index = point_metatable

function dgn.point(x, y)
  local pt = { x = x, y = y }
  setmetatable(pt, point_metatable)
  return pt
end

local function sgn(x)
  if x < 0 then
    return -1
  elseif x > 0 then
    return 1
  else
    return 0
  end
end

point_metatable.sgn = function (p)
                        return dgn.point(sgn(p.x), sgn(p.y))
                      end

point_metatable.__eq = function (a, b)
                         return a.x == b.x and a.y == b.y
                       end

point_metatable.__add = function (a, b)
                          if type(b) == "number" then
                            return dgn.point(a.x + b, a.y + b)
                          else
                            return dgn.point(a.x + b.x, a.y + b.y)
                          end
                        end

point_metatable.__sub = function (a, b)
                          if type(b) == "number" then
                            return dgn.point(a.x - b, a.y - b)
                          else
                            return dgn.point(a.x - b.x, a.y - b.y)
                          end
                        end

point_metatable.__div = function (a, b)
                          if type(b) ~= "number" then
                            error("Can only divide by numbers.")
                          end
                          return dgn.point(math.floor(a.x / b),
                                           math.floor(a.y / b))
                        end

point_metatable.__mul = function (a, b)
                          if type(b) ~= "number" then
                            error("Can only multiply by numbers.")
                          end
                          return dgn.point(a.x * b, a.y * b)
                        end

point_metatable.__unm = function (a)
                          return dgn.point(-a.x, -a.y)
                        end

point_metatable.__concat = function (pre, post)
                             local function pstr(p)
                               return "(" .. p.x .. "," .. p.y .. ")"
                             end
                             if getmetatable(pre) == point_metatable then
                               return pstr(pre) .. post
                             else
                               return pre .. pstr(post)
                             end
                           end