local function D(D,J,I)return J*I:Dot(D)-D*I:Dot(J)end local function J(J,I,f)local z=I[#I]local T=-z if#I==4 then local D,J,g=I[3],I[2],I[1]local y,Z,n=D-z,J-z,g-z local s,o,l=y:Cross(Z),Z:Cross(n),n:Cross(y)s=s:Dot(n)>0 and-s or s o=o:Dot(y)>0 and-o or o l=l:Dot(Z)>0 and-l or l if s:Dot(T)>0 then table.remove(I,1)f=s elseif o:Dot(T)>0 then table.remove(I,2)f=o elseif l:Dot(T)>0 then table.remove(I,3)f=l else return true end elseif#I==3 then local J,g=I[2],I[1]local y,Z=J-z,g-z local n=y:Cross(Z)local s=(D(Z,y,y)).Unit local o=(D(y,Z,Z)).Unit if s:Dot(T)>0 then table.remove(I,1)f=s elseif o:Dot(T)>0 then table.remove(I,2)f=o else local D=z-z==ZERO3 if not D then return true else f=n:Dot(T)>0 and n or-n end end else local J=I[1]local g=J-z local y=(D(g,T,g)).Unit f=y end return false,f end


local function tripleProduct(a, b, c)
	return b * c:Dot(a) - a * c:Dot(b)
end

local function containsOrigin(self, simplex, direction)
	local a = simplex[#simplex]
	local ao = -a

	if (#simplex == 4) then
		local b, c, d = simplex[3], simplex[2], simplex[1]
		local ab, ac, ad = b - a, c - a, d - a
		local abc, acd, adb = ab:Cross(ac), ac:Cross(ad), ad:Cross(ab)
		
		abc = abc:Dot(ad) > 0 and -abc or abc
		acd = acd:Dot(ab) > 0 and -acd or acd
		adb = adb:Dot(ac) > 0 and -adb or adb
		
		if (abc:Dot(ao) > 0) then
			table.remove(simplex, 1)
			direction = abc
		elseif (acd:Dot(ao) > 0) then
			table.remove(simplex, 2)
			direction = acd
		elseif (adb:Dot(ao) > 0) then
			table.remove(simplex, 3)
			direction = adb
		else
			return true
		end
	elseif (#simplex == 3) then
		local b, c = simplex[2], simplex[1]
		local ab, ac = b - a, c - a
		
		local abc = ab:Cross(ac)
		local abPerp = tripleProduct(ac, ab, ab).Unit
		local acPerp = tripleProduct(ab, ac, ac).Unit
		
		if (abPerp:Dot(ao) > 0) then
			table.remove(simplex, 1)
			direction = abPerp
		elseif (acPerp:Dot(ao) > 0) then
			table.remove(simplex, 2)
			direction = acPerp
		else
			local isV3 = ((a - a) == ZERO3)
			if (not isV3) then
				return true
			else
				direction = abc:Dot(ao) > 0 and abc or -abc
			end
		end
	else
		local b = simplex[1]
		local ab = b - a
		local bcPerp = tripleProduct(ab, ao, ab).Unit
		direction = bcPerp
	end
	
	return false, direction
end
