-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvector.lua
113 lines (91 loc) · 3.33 KB
/
vector.lua
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
--[[
#########################################################################
# #
# vector.lua #
# #
# 2D vector operations #
# #
# Copyright 2011 Josh Bothun #
# http://minornine.com #
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License <http://www.gnu.org/licenses/> for #
# more details. #
# #
#########################################################################
--]]
require 'math'
require 'leaf.object'
local sin, cos, sqrt = math.sin, math.cos, math.sqrt
local vector = {}
function vector.new(x, y)
return {
x = x or 0,
y = y or 0,
}
end
function vector.translate(x, y, dx, dy)
return x + dx, y + dy
end
function vector.rotate(x, y, theta)
local rx = x * math.cos(theta) - y * math.sin(theta)
local ry = x * math.sin(theta) + y * math.cos(theta)
return rx, ry
end
function vector.scale(x, y, sx, sy)
local sy = sy or sx
return x * sx, y * sy
end
function vector.length(x, y)
return math.sqrt(x * x + y * y)
end
function vector.normalize(x, y)
local len = vector.length(x, y)
if len > 0 then
return x / len, y / len
end
return x, y
end
function vector.perpendicular(x, y, right)
if not right then
return -y, x
else
return y, -x
end
end
-- Wrap all vector methods to accept either a table or flat args
for k, v in pairs(vector) do
vector[k] = function(a, b, ...)
if type(a) == 'table' then
return v(a.x, a.y, b, ...)
end
return v(a, b, ...)
end
end
-- Must pass a table to unpack
function vector.unpack(v)
return v.x, v.y
end
-- Define in-place functions
for _, key in ipairs({"translate", "rotate", "scale", "normalize"}) do
vector[key .. "_i"] = function(v, ...)
v.x, v.y = vector[key](v, ...)
return v
end
end
-- Call shortcut
setmetatable(vector, {
__call = function(self, ...)
return vector.new(...)
end,
})
-- Namespace exports
leaf.vector = vector