local function T(T,g,b,R)local G=T:pointToObjectSpace(g)local Y=G.Unit local a=G.Magnitude local C=forwardV3:Cross(-Y)local v=math.acos(-Y.Z)local K=T*(fromAxisAngle(C,v)):inverse()if a<math.max(R,b)-math.min(R,b)then return K*CF(0,0,(math.max(R,b)-math.min(R,b))-a),-hpi,pi elseif a>b+R then return K,hpi,0 else local T=-math.acos(((-(R*R)+b*b)+a*a)/((2*b)*a))local g=math.acos(((R*R-b*b)+a*a)/((2*R)*a))return K,hpi-T,-(g-T)end end


local function solveLegIK(o,t,l0,l1) -- Does the major math
	-- Make the position local relative to the origin
	local l = o:pointToObjectSpace(t) -- World space to local space
	local lu = l.Unit -- Get normalized unit for future math
	
	local m = l.Magnitude -- Get the length from the position to the target
	
	-- Make a CFrame pointing from the shoulder position directing to the second position
	local x = forwardV3:Cross(-lu) -- Cross the forward vector with the negative of the normalized unit
	local g = math.acos(-lu.Z) -- Get the arc-cosine of the negative normalized unit
	local p = o*fromAxisAngle(x,g):inverse() -- Get the IK plane
	
	-- In a right-triangle, we have the hypotenuse and the two shorter legs.
	-- In a right triangle, the hypotenuse is side "c," and the legs are a and b.
	-- This information will be helpful later on.
	
	if m < math.max(l1,l0)-math.min(l1,l0) then
		-- If c is between the lengths of a and b then return an offsetted plane so that one of the lengths reaches the goal,
		-- but the other length is folded so it looks natural
		-- This cacluation is done when a position comes before the end of the leg, and may look a bit... odd
		
		return p*CF(0,0,math.max(l1,l0)-math.min(l1,l0)-m),-hpi,pi
	elseif m > l0+l1 then
		-- If c > a + b then return flat angles and an offsetted plane which reaches its target
		-- Basically, this make the leg flat if there is nothing to place it on
		
		return p,hpi,0
	else
		-- Otherwise, use the law of cosines
		-- This is going to be all cases where the leg actually bends
		
		local a1 = -math.acos((-(l1*l1)+(l0*l0)+(m*m))/(2*l0*m))
		local a2 = math.acos(((l1*l1)-(l0*l0)+(m*m))/(2*l1*m))
		return p,hpi-a1,-(a2-a1)
	end
end
