-- Geometry module for Lunatic. local ffi = require("ffi") local math = require("math") local type = type local assert = assert module(...) ffi.cdef[[ typedef struct { double x, y; } dvec2_t; typedef struct { double x, y, z; } dvec3_t; ]] local vec2_ local vec2_mt = { __add = function(a, b) return vec2_(a.x+b.x, a.y+b.y) end, __sub = function(a, b) return vec2_(a.x-b.x, a.y-b.y) end, __unm = function(a) return vec2_(-a.x, -a.x) end, __mul = function(a,b) if (type(a)=="number") then return vec2_(a*b.x, a*b.y) end assert(type(b)=="number") return vec2_(a.x*b, a.y*b) end, __div = function(a,b) assert(type(b)=="number") return vec2_(a.x/b, a.y/b) end, --[[ -- NOTE: metamethods from metatype() are invoken on *any mix of types* -- This means that we can't check a "maybe-vec2" variable like "v ~= nil". __eq = function(a,b) return (a.x==b.x and a.y==b.y) end, --]] __len = function(a) return math.sqrt(a.x*a.x + a.y*a.y) end, __tostring = function(a) return "vec2("..a.x..", "..a.y..")" end, __index = { lensq = function(a) return a.x*a.x + a.y*a.y end, }, } local vec3_ local vec3_mt = { __add = function(a, b) return vec3_(a.x+b.x, a.y+b.y, a.z+b.z) end, __sub = function(a, b) return vec3_(a.x-b.x, a.y-b.y, a.z-b.z) end, __unm = function(a) return vec3_(-a.x, -a.x, -a.z) end, __mul = function(a,b) if (type(a)=="number") then return vec3_(a*b.x, a*b.y, a*b.z) end assert(type(b)=="number") return vec2_(a.x*b, a.y*b, a.z*b) end, __div = function(a,b) assert(type(b)=="number") return vec2_(a.x/b, a.y/b, a.z/b) end, --[[ __eq = function(a,b) return (a.x==b.x and a.y==b.y and a.z==b.z) end, --]] __len = function(a) return math.sqrt(a.x*a.x + a.y*a.y + a.z*a.z) end, __tostring = function(a) return "vec3("..a.x..", "..a.y..", "..a.z..")" end, __index = { lensq = function(a) return a.x*a.x + a.y*a.y + a.z*a.z end, }, } -- VEC2 user data constructor. -- * vec2(