diff --git a/option/option.lua b/option/option.lua index 03b712b..9636c42 100644 --- a/option/option.lua +++ b/option/option.lua @@ -22,7 +22,7 @@ function Some(value) setmetatable(opt, { __index = Option, __tostring = function() - return "Some(" .. value .. ")" + return "Some(" .. value:__tostring() .. ")" end }) diff --git a/vector/vec3.lua b/vector/vec3.lua index 0584fc7..577db41 100644 --- a/vector/vec3.lua +++ b/vector/vec3.lua @@ -1,30 +1,59 @@ +require "option.option" + __Vec3 = { - x = 0, - y = 0, - z = 0 + _x = 0, + _y = 0, + _z = 0, } function Vec3(vec) return setmetatable({ - x = vec[1] or 0, - y = vec[2] or 0, - z = vec[3] or 0, - }, {__index = __Vec3, - }) + _x = vec[1] or 0, + _y = vec[2] or 0, + _z = vec[3] or 0, + }, { + __index = __Vec3, + __tostring = __Vec3.__tostring, + __add = __Vec3.add, + __mul = __Vec3.scale, + __unm = function(self) + return __Vec3.scale(self, -1) + end, + __eq = function(self, other) + return + self._x == other._x + and self._y == other._y + and self._z == other._z + end, + }) end -function __Vec3:add(v1, v2) - return Vec3 { v1.x + v2.x, v1.y + v2.y, v1.z + v2.z } +function __Vec3:add(other) + Vec3 { self._x + other._x, self._y + other._y, self._z + other._z } +end + +function __Vec3:scale(factor) + return Vec3 { self._x * factor, self._y * factor, self._z * factor } end function __Vec3:length() - return math.sqrt(self.x ^ 2 + self.y ^ 2 + self.z ^ 2) + return math.sqrt(self._x ^ 2 + self._y ^ 2 + self._z ^ 2) end -function __Vec3:to_string() - return "{".. self.x .. ", " .. self.y .. ", " .. self.z .. "}" +function __Vec3:normalize() + local length = self:length() + if not length then return None end + return Some(Vec3 { + self._x / length, + self._y / length, + self._z / length + }) end -local v = Vec3 {1, 2, 3} +function __Vec3:dot(other) + return self._x * other._x + self._y * other._y + self._z * other._z +end -print(v:to_string()) \ No newline at end of file +function __Vec3:__tostring() + return "Vec3{" .. self._x .. ", " .. self._y .. ", " .. self._z .. "}" +end