-
Notifications
You must be signed in to change notification settings - Fork 1
/
Vec.lua
144 lines (126 loc) · 2.17 KB
/
Vec.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
local class = require("class")
---@class util.Vec
---@operator call: util.Vec
---@operator unm: util.Vec
---@operator add: util.Vec
---@operator sub: util.Vec
---@operator mul: util.Vec
---@operator div: util.Vec
---@operator concat: string
local Vec = class()
---@return number
function Vec:abs2()
local sum = 0
for i = 1, #self do
sum = sum + self[i] ^ 2
end
return sum
end
---@return number
function Vec:abs()
return math.sqrt(self:abs2())
end
---@return util.Vec
function Vec:copy()
local c = {}
for i = 1, #self do
c[i] = self[i]
end
return Vec(c)
end
---@return util.Vec
function Vec:norm()
local r = self:abs()
if r ~= 0 then
return self / r
end
local c = {}
for i = 1, #self do
c[i] = 0
end
return Vec(c)
end
---@return util.Vec
function Vec:floor()
local c = {}
for i = 1, #self do
c[i] = math.floor(self[i])
end
return Vec(c)
end
---@param a util.Vec
---@param b util.Vec
---@return boolean
function Vec.__eq(a, b)
return (a - b):abs() < 1e-12
end
---@param a util.Vec
---@return util.Vec
function Vec.__unm(a)
local c = {}
for i = 1, #a do
c[i] = -a[i]
end
return Vec(c)
end
---@param a util.Vec
---@param b util.Vec
---@return util.Vec
function Vec.__add(a, b)
local c = {}
for i = 1, #a do
c[i] = a[i] + b[i]
end
return Vec(c)
end
---@param a util.Vec
---@param b util.Vec
---@return util.Vec
function Vec.__sub(a, b)
local c = {}
for i = 1, #a do
c[i] = a[i] - b[i]
end
return Vec(c)
end
---@param a util.Vec
---@param b util.Vec
---@return util.Vec
function Vec.__mul(a, b)
local c = {}
for i = 1, #a do
c[i] = a[i] * b
end
return Vec(c)
end
---@param a util.Vec
---@param b util.Vec
---@return util.Vec
function Vec.__div(a, b)
local c = {}
for i = 1, #a do
c[i] = a[i] / b
end
return Vec(c)
end
function Vec.__mod()
return error("not implemented")
end
function Vec.__lt()
return error("not implemented")
end
function Vec.__le()
return error("not implemented")
end
---@param a util.Vec
---@param b util.Vec
---@return string
function Vec.__concat(a, b)
return tostring(a) .. tostring(b)
end
---@param a util.Vec
---@return string
function Vec.__tostring(a)
return ("{%s}"):format(table.concat(a, ", "))
end
return Vec