vec3meta = { }

function vec3meta.__add(_a, _b)
	if (type(_a) == "number") then
		return vec3(_a + _b.x,   _a + _b.y,   _a + _b.z)
	elseif (type(_b) == "number") then
		return vec3(_a.x + _b,   _a.y + _b,   _a.z + _b)
	else
		return vec3(_a.x + _b.x, _a.y + _b.y, _a.z + _b.z)
	end
end

function vec3meta.__sub(_a, _b)
	--print(type(_t), type(_v))
	if (type(_a) == "number") then
		return vec3(_a - _b.x,   _a - _b.y,   _a - _b.z)
	elseif (type(_b) == "number") then
		return vec3(_a.x - _b,   _a.y - _b,   _a.z - _b)
	else
		return vec3(_a.x - _b.x, _a.y - _b.y, _a.z - _b.z)
	end
end

function vec3meta.__unm(_a)
	return vec3(-_a.x, -_a.y, -_a.z)
end

function vec3meta.__mul(_a, _b)
	--print(type(_t), type(_v))
	if (type(_a) == "number") then
		return vec3(_a * _b.x,   _a * _b.y,   _a * _b.z)
	elseif (type(_b) == "number") then
		return vec3(_a.x * _b,   _a.y * _b,   _a.z * _b)
	else
		return vec3(_a.x * _b.x, _a.y * _b.y, _a.z * _b.z)
	end
end

function vec3meta.__div(_a, _b)
	--print(type(_t), type(_v))
	if (type(_a) == "number") then
		return vec3(_a / _b.x,   _a / _b.y,   _a / _b.z)
	elseif (type(_b) == "number") then
		return vec3(_a.x / _b,   _a.y / _b,   _a.z / _b)
	else
		return vec3(_a.x / _b.x, _a.y / _b.y, _a.z / _b.z)
	end
end


function vec3(x,y,z)
	local stuf = {}

	stuf.x = x
	stuf.y = y
	stuf.z = z
	setmetatable(stuf, vec3meta)
	return stuf
end


function length3(v)
	return math.sqrt(v.x*v.x + v.y*v.y + v.z*v.z)
end

function dot3(a,b)
	return a.x*b.x + a.y*b.y + a.z*b.z
end

function normalize3(v)
	local x,y,z,invlen
	invlen = 1.0 / length3(v)
	x = v.x * invlen
	y = v.y * invlen
	z = v.z * invlen
	return vec3(x,y,z)
end

function abs3(v)
	return vec3(math.abs(v.x), math.abs(v.y), math.abs(v.z))
end

function vecstr3(v)
	return string.format("vec3(%.2f,%.2f,%.2f)", v.x, v.y, v.z )
end