local D=require(script.Parent:WaitForChild("\103\101\116\076\097\115\116\087\111\114\100\070\114\111\109\080\097\115\099\097\108\067\097\115\101"))local K={}for D,n in pairs(script:GetChildren())do K[n.Name]=n end function getConstraintTemplate(n)n=D(n)return K[n]or K.Default end function createConstraint(D)local K=D.Joint.Name local n=(getConstraintTemplate(K)):Clone()n.Attachment0=D.Attachment0 n.Attachment1=D.Attachment1 n.Name=K.."\082\097\103\100\111\108\108\067\111\110\115\116\114\097\105\110\116"local b=Instance.new("\079\098\106\101\099\116\086\097\108\117\101",n)b.Name="\082\105\103\105\100\074\111\105\110\116"b.Value=D.Joint return n end return function(D)local K=Instance.new("\070\111\108\100\101\114")K.Name="\082\097\103\100\111\108\108\067\111\110\115\116\114\097\105\110\116\115"for D,n in pairs(D)do if n.Joint.Name~="\082\111\111\116"then local D=createConstraint(n)D.Parent=K end end return K end

	
local getLastWordFromPascaleCase = require(script.Parent:WaitForChild("getLastWordFromPascalCase"))

local constraints = {}
for _,v in pairs(script:GetChildren()) do
	constraints[v.Name] = v
end

function getConstraintTemplate(jointName)
	jointName = getLastWordFromPascaleCase(jointName)
	return constraints[jointName] or constraints.Default
end

function createConstraint(jointData)
	local jointName = jointData.Joint.Name
	local constraint = getConstraintTemplate(jointName):Clone()
	
	constraint.Attachment0 = jointData.Attachment0
	constraint.Attachment1 = jointData.Attachment1
	constraint.Name = jointName.."RagdollConstraint"
	
	-- Constraints don't work if there is a rigid joint connecting its two parts,
	-- so when we enter ragdoll we need to turn off the joint, and turn it back on
	-- when we leave ragdoll. This allows us to tell which joint corresponds with
	-- which constraint
	local rigidPointer = Instance.new("ObjectValue", constraint)
	rigidPointer.Name = "RigidJoint"
	rigidPointer.Value = jointData.Joint
	
	return constraint
end

return function(attachmentMap)
	local ragdollConstraints = Instance.new("Folder")
	ragdollConstraints.Name = "RagdollConstraints"

	for attachmentName,jointData in pairs(attachmentMap) do
		if jointData.Joint.Name ~= "Root" then
			local ragdollConstraint = createConstraint(jointData)
			ragdollConstraint.Parent = ragdollConstraints
		end
	end
	
	return ragdollConstraints
end
