qPerfectionWeld 2.0

The old one used a lot of weird and outdated practices so Yeah I updated it to make it more readable and optimized

Old:

local NEVER_BREAK_JOINTS = false
local function CallOnChildren(Instance, FunctionToCall)
	FunctionToCall(Instance)
	for _, Child in next, Instance:GetChildren() do
		CallOnChildren(Child, FunctionToCall)
	end
end
local function GetNearestParent(Instance, ClassName)
	local Ancestor = Instance
	repeat
		Ancestor = Ancestor.Parent
		if Ancestor == nil then
			return nil
		end
	until Ancestor:IsA(ClassName)

	return Ancestor
end

local function GetBricks(StartInstance)
	local List = {}
	CallOnChildren(StartInstance, function(Item)
		if Item:IsA("BasePart") then
			List[#List+1] = Item;
		end
	end)

	return List
end

local function Modify(Instance, Values)
	assert(type(Values) == "table", "Values is not a table");
	for Index, Value in next, Values do
		if type(Index) == "number" then
			Value.Parent = Instance
		else
			Instance[Index] = Value
		end
	end
	return Instance
end
local function Make(ClassType, Properties) 
	return Modify(Instance.new(ClassType), Properties)
end
local Surfaces = {"TopSurface", "BottomSurface", "LeftSurface", "RightSurface", "FrontSurface", "BackSurface"}
local HingSurfaces = {"Hinge", "Motor", "SteppingMotor"}

local function HasWheelJoint(Part)
	for _, SurfaceName in pairs(Surfaces) do
		for _, HingSurfaceName in pairs(HingSurfaces) do
			if Part[SurfaceName].Name == HingSurfaceName then
				return true
			end
		end
	end
	
	return false
end
local function ShouldBreakJoints(Part)
	if NEVER_BREAK_JOINTS then
		return false
	end
	if HasWheelJoint(Part) then
		return false
	end
	local Connected = Part:GetConnectedParts()
	if #Connected == 1 then
		return false
	end
	for _, Item in pairs(Connected) do
		if HasWheelJoint(Item) then
			return false
		elseif not Item:IsDescendantOf(script.Parent) then
			return false
		end
	end
	
	return true
end
local function WeldTogether(Part0, Part1, JointType, WeldParent)
	JointType = JointType or "Weld"
	local RelativeValue = Part1:FindFirstChild("qRelativeCFrameWeldValue")
	
	local NewWeld = Part1:FindFirstChild("qCFrameWeldThingy") or Instance.new(JointType)
	Modify(NewWeld, {
		Name = "qCFrameWeldThingy";
		Part0  = Part0;
		Part1  = Part1;
		C0     = CFrame.new();
		C1     = RelativeValue and RelativeValue.Value or Part1.CFrame:toObjectSpace(Part0.CFrame);
		Parent = Part1;
	})

	if not RelativeValue then
		RelativeValue = Make("CFrameValue", {
			Parent     = Part1;
			Name       = "qRelativeCFrameWeldValue";
			Archivable = true;
			Value      = NewWeld.C1;
		})
	end

	return NewWeld
end
local function WeldParts(Parts, MainPart, JointType, DoNotUnanchor)	
	for _, Part in pairs(Parts) do
		if ShouldBreakJoints(Part) then
			Part:BreakJoints()
		end
	end
	for _, Part in pairs(Parts) do
		if Part ~= MainPart then
			WeldTogether(MainPart, Part, JointType, MainPart)
		end
	end
	if not DoNotUnanchor then
		for _, Part in pairs(Parts) do
			Part.Anchored = false
		end
		MainPart.Anchored = false
	end
end
local function PerfectionWeld()	
	local Tool = GetNearestParent(script, "Tool")

	local Parts = GetBricks(script.Parent)
	local PrimaryPart = Tool and Tool:FindFirstChild("Handle") and Tool.Handle:IsA("BasePart") and Tool.Handle or script.Parent:IsA("Model") and script.Parent.PrimaryPart or Parts[1]

	if PrimaryPart then
		WeldParts(Parts, PrimaryPart, "Weld", false)
	else
		warn("qWeld - Unable to weld part")
	end
	return Tool
end
local Tool = PerfectionWeld()
if Tool and script.ClassName == "Script" then
	script.Parent.AncestryChanged:connect(function()
		PerfectionWeld()
	end)
end

New (Thanks @Zhekoay for some of the improvements):

local NEVER_BREAK_JOINTS = false

local function HasWheelJoint(Part)
	local HingeSurfaces = {
		[Enum.SurfaceType.Hinge] = true,
		[Enum.SurfaceType.Motor] = true,
		[Enum.SurfaceType.SteppingMotor] = true,
	}

	return HingeSurfaces[Part.TopSurface]
		or HingeSurfaces[Part.BottomSurface]
		or HingeSurfaces[Part.LeftSurface]
		or HingeSurfaces[Part.RightSurface]
		or HingeSurfaces[Part.FrontSurface]
		or HingeSurfaces[Part.BackSurface]
end

local function ShouldBreakJoints(Part)
	local ConnectedParts = Part:GetConnectedParts()
	if NEVER_BREAK_JOINTS or HasWheelJoint(Part) or #ConnectedParts == 1 then
		return false
	end

	for _, Item in ipairs(ConnectedParts) do
		if HasWheelJoint(Item) or not Item:IsDescendantOf(script.Parent) then
			return false
		end
	end
	
	return true
end

local function WeldTogether(Part0, Part1, JointType, WeldParent)
	JointType = JointType or "Weld"
	WeldParent = WeldParent or Part1

	if Part0 == Part1 then
		warn("Can't weld the same part")
		return
	end

	local RelativeValue = Part1:FindFirstChild("qRelativeCFrameWeldValue")
	if not RelativeValue then
		RelativeValue = Instance.new("CFrameValue")
		RelativeValue.Name = "qRelativeCFrameWeldValue"
		RelativeValue.Archivable = true
		RelativeValue.Value = Part1.CFrame:ToObjectSpace(Part0.CFrame)
		RelativeValue.Parent = Part1
	end
	
	local Weld = Part1:FindFirstChild("qCFrameWeldThingy") or Instance.new(JointType)
	Weld.Name = "qCFrameWeldThingy"
	Weld.Part0 = Part0
	Weld.Part1 = Part1
	Weld.C0 = CFrame.identity
	Weld.C1 = RelativeValue.Value
	Weld.Parent = WeldParent

	return Weld
end

local function WeldParts(Parts, MainPart, JointType, DoNotUnanchor)	
	for _, Part in ipairs(Parts) do
		if ShouldBreakJoints(Part) then
			Part:BreakJoints()
		end

		WeldTogether(MainPart, Part, JointType, MainPart)

		if not DoNotUnanchor then
			Part.Anchored = false
		end
	end

	if not DoNotUnanchor then
		MainPart.Anchored = false
	end
end

local function PerfectionWeld()	
	local Tool = script:FindFirstAncestorWhichIsA("Tool")
	local ToolHandle = Tool and Tool:QueryDescendants("BasePart[#Handle]")[1]
	local Parts = script.Parent:QueryDescendants("BasePart")

	local PrimaryPart =
		ToolHandle or
		(script.Parent:IsA("Model") and script.Parent.PrimaryPart) or
		(script.Parent:IsA("BasePart") and script.Parent) or
		Parts[1]

	if PrimaryPart then
		WeldParts(Parts, PrimaryPart, "Weld", false)
	else
		warn("qWeld - Unable to weld part")
	end

	return Tool
end

if
	_VERSION == "Luau" and
	typeof(game) == "Instance" and
	typeof(script.Parent) == "Instance" and
	game:GetService("RunService"):IsServer() and
	PerfectionWeld()
then
	script.Parent.AncestryChanged:Connect(PerfectionWeld)
end

Feedback would be appreciated!

12 Likes

nooooo it cant be qperfectionweld its not made by quenty!!!

cool tho, the code does seem better

1 Like

Yes now it is cPerfectionWeld

2 Likes

Here’s a further improved version:

-- qPerfectionWeld.lua
-- Server-side utility that welds every BasePart under the parent
-- to a single root part while skipping any wheel/hinge assemblies.
-- Welds re-apply automatically if the model is re-parented.

--------------------------------------------------------------------
-- Early-out: server only
--------------------------------------------------------------------
local RunService = game:GetService("RunService")
if not RunService:IsServer() then
	return
end

--------------------------------------------------------------------
-- Constants / Configuration
--------------------------------------------------------------------
local Container: Instance = script.Parent :: Instance
local WeldName       = "AutoWeldConstraint"  -- Tag applied to each WeldConstraint
local BreakableJoints = true                 -- Set false to leave joints intact

-- What counts as a “wheel” joint
local HingeSurfaces: {[string]: boolean} = {
	Hinge         = true,
	Motor         = true,
	SteppingMotor = true,
}

--------------------------------------------------------------------
-- Helper Functions
--------------------------------------------------------------------
-- 1) Detect wheels without dynamic property access
local function HasWheelJoint(part: BasePart): boolean
	return HingeSurfaces[part.TopSurface.Name]
		or HingeSurfaces[part.BottomSurface.Name]
		or HingeSurfaces[part.LeftSurface.Name]
		or HingeSurfaces[part.RightSurface.Name]
		or HingeSurfaces[part.FrontSurface.Name]
		or HingeSurfaces[part.BackSurface.Name]
end

-- 2) Remove legacy joints manually (BreakJoints is deprecated)
local function DestroyAttachedJoints(part: BasePart)
	for _, child in ipairs(part:GetChildren()) do
		if child:IsA("JointInstance") then
			child:Destroy()
		end
	end
end

-- 3) Decide whether it is safe to break a part’s joints
local function CanBreak(part: BasePart): boolean
	if not BreakableJoints or HasWheelJoint(part) then
		return false
	end

	local connected = part:GetConnectedParts()
	if #connected == 1 then -- Only connected to itself
		return false
	end

	for _, other in ipairs(connected) do
		if not other:IsDescendantOf(Container) or HasWheelJoint(other) then
			return false
		end
	end

	return true
end

-- 4) Weld a pair (skip if already welded)
local function WeldPair(root: BasePart, part: BasePart)
	if part:FindFirstChild(WeldName) then
		return
	end

	local weld = Instance.new("WeldConstraint")
	weld.Name  = WeldName
	weld.Part0 = root
	weld.Part1 = part
	weld.Parent = root
end

-- 5) Collect all BaseParts once
local function CollectParts(scope: Instance): {BasePart}
	local list = {}
	for _, obj in ipairs(scope:GetDescendants()) do
		if obj:IsA("BasePart") then
			table.insert(list, obj)
		end
	end
	return list
end

-- 6) Pick a primary part (Tool > Model.PrimaryPart > first part)
local function DetermineRoot(scope: Instance, parts: {BasePart}): BasePart?
	local tool = scope:FindFirstAncestorWhichIsA("Tool")
	if tool then
		local inst = tool:FindFirstChild("Handle", true)
		if inst and inst:IsA("BasePart") then
			return inst
		end
	end

	if scope:IsA("Model") then
		local model = scope :: Model
		if model.PrimaryPart then
			return model.PrimaryPart
		end
	end

	return parts[1]
end

-- 7) Weld everything to that root
local function WeldAssembly(parts: {BasePart}, root: BasePart, anchorOpt: boolean?)
	local anchor: boolean = anchorOpt == true

	for _, part in ipairs(parts) do
		if CanBreak(part) then
			DestroyAttachedJoints(part)
		end

		if part ~= root then
			WeldPair(root, part)
		end

		part.Anchored = anchor
	end

	root.Anchored = anchor
end

--------------------------------------------------------------------
-- Main Routine (Re-entrant)
--------------------------------------------------------------------
local function AutoWeld()
	local parts = CollectParts(Container)
	if #parts == 0 then
		warn("qPerfectionWeld: No BaseParts under " .. Container:GetFullName())
		return
	end

	local root = DetermineRoot(Container, parts)
	if not root then
		warn("qPerfectionWeld: Could not determine a root part for " .. Container:GetFullName())
		return
	end

	WeldAssembly(parts, root, false)
end

--------------------------------------------------------------------
-- Kick Off And Keep Current
--------------------------------------------------------------------
AutoWeld()
Container.AncestryChanged:Connect(AutoWeld)
2 Likes

Why are you using ipairs if it is literally slower than not using it?

  11:45:39.994  >
--!native
--!optimize 2

local warmup_iterations = 10_000
local iterations = 1_000_000
local goons = 1000 -- Number of elements in the table

local t = {}
for i = 1, goons do
	t[i] = i
end

-- Warmup
for _ = 1, warmup_iterations do
	for i, v in t do end
	for i, v in ipairs(t) do end
end

-- ipairs
do
	local clocked = os.clock()

	for _ = 1, iterations do
		for i, v in ipairs(t) do end
	end

	print("ipairs:", os.clock() - clocked)
end

-- None
do
	local clocked = os.clock()

	for _ = 1, iterations do
		for i, v in t do end
	end

	print("None:", os.clock() - clocked)
end  -  Studio
  11:45:44.494  ipairs: 4.4322331999997004  -  Edit
  11:45:47.360  None: 2.8647651999999653  -  Edit

:skull:

1 Like
local Container = script.Parent :: Instance
local function BreakJoints(part)
	for _, child in part:GetJoints() do
		child:Destroy()
	end
end

…

You do know :IsA("Model") automatically autocompletes “scope” as a model?

And if you still want to do that…

scope = scope :: Model

But thanks for showing me ways to make it better :slight_smile:

Yeah, the explicit : Instance is technically redundant, but it keeps the type checker happy when this module is reused in different contexts. Also not sure why you’re pointing out ipairs, it’s standard practice for arrays, still used in Roblox’s own code, and the difference is negligible for a script like this.

1 DestroyAttachedJoints vs GetJoints()

GetJoints() does exist, but it’s the wrong tool here:

  • GetJoints() allocates a new Lua table every single call, adding extra GC pressure if repeatedly used in loops.
    Using :GetChildren() allocates only once per call, meaning fewer allocations overall and lighter GC overhead during iteration.
  • it only returns joints that actively connect this part to something else, so it can miss loose Motor6Ds, unused welds, and other orphaned JointInstances sitting under the part

iterating the children and nuking every JointInstance is both faster and future-proof.


2 if scope:IsA("Model") then …

Inside the if, Luau temporarily treats scope as a Model. Once you exit that block, scope reverts to Instance, so you lose direct access to properties like PrimaryPart. Storing it as:

local model = scope :: Model

keeps the narrowed type for the rest of the function, avoids extra casts, and makes the intent obvious to anyone reading the code.

Appreciate you taking notes :slightly_smiling_face: keep at it

1 Like

Sorry for the inconvenience, but do you happen to have any sources so I can double-check this statement
I would test it myself but I currently can’t use Roblox Studio right now

Thanks :pray:

I personally like using ipairs because it is more readable, it makes for loops pop out (especially with my theme) which I like. I also like the idea of iterator functions over generalized iteration, for the language design

Also out of habit

And the performance difference is barely anything, even if you spam thousands and thousands of for loops

1 Like

New update:

Script now uses Instance:QueryDescendants

Awesome, now I can use a better one for my spaceships

1 Like

New update:

Made it more robust and fixed a bug