--
-- VEC2D.LUA
--
-- Purpose: 2D vector arithmetics
--
-- Note: Original code extracted from Thatcher Ulrich's 'Meteor Shower' game.
--
local m= { _info= { MODULE= "2D vector maths",
                    AUTHOR= "asko.kauppi@sci.fi",
                    LICENSE= "LGPL",
                    CREDITS= "Thatcher Ulrich (original author)" }
         }

local my_meta= {
    __add= function(a,b) return m.new( a.x+b.x, a.y+b.y ) end,
    __sub= function(a,b) return m.new( a.x-b.x, a.y-b.y ) end,
    __mul= function(a,b) return (tonumber(a) and m.new( a*b.x, a*b.y )) or
                                (tonumber(b) and m.new( a.x*b, a.y*b )) or
			                        (a.x*b.x + a.y*b.y) -- dot product
           end,
    __div= function(a,b) 
                ASSUME( tonumber(b) and b~=0 )
                return m.new( a.x/b, a.y/b )
           end,
    __unm= function(a) return m.new( -a.x, -a.y ) end,

    __eq=  function(a,b) return (a.x==b.x) and (a.y==b.y) end,
    }

-----
-- obj= new( [x,y] )
-- obj= new{ x, y }
-- obj= new{ x=x, y=y }
--
function m.new( x,y )
    --
    local obj= {}

    if type(x)=="table" then
        obj.x= x.x or x[1] or 0
        obj.y= x.y or x[2] or 0
    else
        obj.x= x or 0
        obj.y= y or 0
    end

    setmetatable( obj, my_meta )

    obj.norm= 
        function(a)
            local d= math.sqrt( (a.x)^2 + (a.y)^2 )
            
	        if d < 0.000001 then
                a.x, a.y = 1, 0
	        else
                a.x, a.y = a.x/d, a.y/d
	        end
            return a
        end

    return obj
end


return m
