local function B(B)if B.Magnitude==0 then return Vector3.zero end return B.Unit end local function G(B,G,R,p)local r=p-B local c=r:Dot(G)c=math.clamp(c,-R,R)return B+G*c end local function R(R,p,r,c)local j=G(R.Position,R.UpVector,p*.5,c)local y=(j-c).Magnitude local W=B(c-j)local l=y<=r return l,j+W*r,W end return function(B,G,p,r)debug.profilebegin("\067\097\112\115\117\108\101 \084\101\115\116\105\110\103")local c=(G.Y<G.Z and G.Y or G.Z)*.5 local j=G.X B*=CFrame.Angles(math.rad(90),-math.rad(90),0)local y,W,l=R(B,j,c,p)if y then return y,W,l end local a=(W-p).Magnitude y=a<r debug.profileend()return y,W,l end
--!native
local function SafeUnit(v3)
	if v3.Magnitude == 0 then
		return Vector3.zero
	end

	return v3.Unit
end

local function solve(p0, d0, len, p1)
	local v = p1 - p0
	local k = v:Dot(d0)
	k = math.clamp(k, -len, len)
	return p0 + d0 * k
end

local function ClosestPointFunc(cframe, length, radius, point)
	local l0 = solve(cframe.Position, cframe.UpVector, length * 0.5, point)

	local distance = (l0 - point).Magnitude
	local normal = SafeUnit(point - l0)
	local is_inside = (distance <= radius)

	return is_inside, l0 + (normal * radius), normal
end

return function(CapsuleCFrame, CapsuleSize, Point, Radius)
	debug.profilebegin("Capsule Testing")
	local CapsuleRadius = (CapsuleSize.Y < CapsuleSize.Z and CapsuleSize.Y or CapsuleSize.Z) * 0.5
	local CapsuleLength = CapsuleSize.X

	CapsuleCFrame *= CFrame.Angles(math.rad(90), -math.rad(90), 0) -- Optomize

	local IsInside, ClosestPoint, Normal = ClosestPointFunc(CapsuleCFrame, CapsuleLength, CapsuleRadius, Point)

	if IsInside then
		return IsInside, ClosestPoint, Normal
	end

	local DistanceToCp = (ClosestPoint - Point).Magnitude

	IsInside = (DistanceToCp < Radius)
	debug.profileend()
	return IsInside, ClosestPoint, Normal
end
