module(..., package.seeall)


function distance2d(p0, p1)
	local dx= p0.x - p1.x
	local dy= p0.y - p1.y
	
	return math.sqrt(dx*dx + dy*dy)
end

function distance_from_line_segment2d(p, v, w, test_point)
	local diff= vector_from_points(p, test_point)
	local dot= dot2d(diff, v)
	
	if (dot < 0) then
		dot= 0
	elseif (dot > w) then
		dot= w
	end
	
	local point_on_line= offset_point(p, v, dot)
	return distance2d(test_point, point_on_line)
end

function dot2d(v0, v1)
	return v0.x*v1.x + v0.y*v1.y
end

function magnitude_squared(v)
	return (v.x*v.x + v.y*v.y)
end

function magnitude(v)
	return math.sqrt(magnitude_squared(v))
end

function normalize2d(v0)
	local mag= math.sqrt(v0.x*v0.x + v0.y*v0.y)
	if (mag>0) then
		v0.x = v0.x/mag
		v0.y = v0.y/mag
	end
	
	return mag
end

function scale(v0, s) 
	v0.x = v0.x*s
	v0.y = v0.y*s
end

function vector_from_points(p0, p1)
	local v= {}
	v.x= p1.x-p0.x
	v.y= p1.y-p0.y
	return v
end

function vector_rotate(v, angle)
	local sine= math.sin(angle);
	local cosine= math.cos(angle);
	local result= {}

	result.x= cosine*v.x - sine*v.y;
	result.y= sine*v.x + cosine*v.y;

	return result
end

function vector_from_angle(angle)
	local result= {}

	result.x= math.cos(angle)
	result.y= math.sin(angle)

	return result

end

function offset_point(p, v, t)
	local result= {}
	
	result.x= p.x + v.x*t
	result.y= p.y + v.y*t
	
	return result
end