Support.AddUserInputListener("\069\110\100\101\100","\077\111\117\115\101\066\117\116\116\111\110\049",true,function(M)if not HandleResizing then return end HandleResizing=false Core.Targeting.CancelSelecting()ClearConnection("\072\097\110\100\108\101\082\101\108\101\097\115\101")for M,C in pairs(InitialState)do M:MakeJoints()M.CanCollide=C.CanCollide M.Anchored=C.Anchored end RegisterChange()end)function HideHandles()if not Handles or not Handles.Visible then return end Handles.Visible=false Handles.Parent=nil ClearConnection("\065\117\116\111\102\111\099\117\115\072\097\110\100\108\101")end function ResizePartsByFace(M,C,F,Q)if F=="\066\111\116\104"then C=C*2 end local t=AxisSizeMultipliers[M]local b=C*t local v=FaceAxisNames[M]local a,I,G,K for M,F in pairs(Q)do local Q=F.Size[v]+C if Q<.049999 and(not a or a and Q<a)then a,I=Q,M elseif Q>2048 and(not G or G and Q>G)then G,K=Q,M end end if a then local M=Q[I].Size[v]local F=M-ResizeTool.Increment*tonumber((tostring((M-.05)/ResizeTool.Increment)):gsub("\037\046\046\043",""))return false,(C+F)-a end if G then local M=ResizeTool.Increment*tonumber((tostring(2048/ResizeTool.Increment)):gsub("\037\046\046\043",""))return false,(C+M)-G end for Q,t in pairs(Q)do if Q:IsA("\080\097\114\116")then if Q.Shape==Enum.PartType.Ball then Q.Size=t.Size+Vector3.new(C,C,C)elseif Q.Shape==Enum.PartType.Cylinder and v~="\088"then Q.Size=t.Size+Vector3.new(0,C,C)else Q.Size=t.Size+b end else Q.Size=t.Size+b end if F=="\078\111\114\109\097\108"then Q.CFrame=t.CFrame*CFrame.new((AxisPositioningMultipliers[M]*C)/2)elseif F=="\066\111\116\104"then Q.CFrame=t.CFrame end end return true end function BindShortcutKeys()table.insert(Connections,UserInputService.InputBegan:connect(function(M,C)if C then return end if M.UserInputType~=Enum.UserInputType.Keyboard then return end if UserInputService:GetFocusedTextBox()then return end if M.KeyCode==Enum.KeyCode.Return or M.KeyCode==Enum.KeyCode.KeypadEnter then if ResizeTool.Directions=="\078\111\114\109\097\108"then SetDirections("\066\111\116\104")elseif ResizeTool.Directions=="\066\111\116\104"then SetDirections("\078\111\114\109\097\108")end elseif M.KeyCode==Enum.KeyCode.Minus or M.KeyCode==Enum.KeyCode.KeypadMinus then if ResizeTool.UI then ResizeTool.UI.IncrementOption.Increment.TextBox:CaptureFocus()end elseif M.KeyCode==Enum.KeyCode.KeypadEight then NudgeSelectionByFace(Enum.NormalId.Top)elseif M.KeyCode==Enum.KeyCode.KeypadTwo then NudgeSelectionByFace(Enum.NormalId.Bottom)elseif M.KeyCode==Enum.KeyCode.KeypadNine then NudgeSelectionByFace(Enum.NormalId.Front)elseif M.KeyCode==Enum.KeyCode.KeypadOne then NudgeSelectionByFace(Enum.NormalId.Back)elseif M.KeyCode==Enum.KeyCode.KeypadFour then NudgeSelectionByFace(Enum.NormalId.Left)elseif M.KeyCode==Enum.KeyCode.KeypadSix then NudgeSelectionByFace(Enum.NormalId.Right)elseif M.KeyCode==Enum.KeyCode.R and not Selection.Multiselecting then StartSnapping()end end))table.insert(Connections,UserInputService.InputEnded:connect(function(M,C)if C then return end if M.UserInputType~=Enum.UserInputType.Keyboard then return end if UserInputService:GetFocusedTextBox()then return end if M.KeyCode==Enum.KeyCode.R and not Selection.Multiselecting then FinishSnapping()end end))end function SetAxisSize(M,C)TrackChange()local F=PreparePartsForResizing()for F,Q in pairs(F)do F.Size=Vector3.new(M=="\088"and C or F.Size.X,M=="\089"and C or F.Size.Y,M=="\090"and C or F.Size.Z)F.CFrame=Q.CFrame end local Q=Security.GetPermissions(Security.GetSelectionAreas(Selection.Items),Core.Player)if Core.Mode=="\084\111\111\108"and Security.ArePartsViolatingAreas(Selection.Items,Core.Player,false,Q)then for M,C in pairs(F)do M.Size=C.Size M.CFrame=C.CFrame end end for M,C in pairs(F)do M:MakeJoints()M.CanCollide=C.CanCollide M.Anchored=C.Anchored end RegisterChange()end function NudgeSelectionByFace(M)local C=ResizeTool.Increment local F=Support.FlipTable(Support.GetListMembers(UserInputService:GetKeysPressed(),"\075\101\121\067\111\100\101"))if F[Enum.KeyCode.LeftShift]or F[Enum.KeyCode.RightShift]then C=-C end TrackChange()local Q=PreparePartsForResizing()local t,b=ResizePartsByFace(M,C,ResizeTool.Directions,Q)if not t then ResizePartsByFace(M,b,ResizeTool.Directions,Q)end if ResizeTool.UI then ResizeTool.UI.Changes.Text.Text="\114\101\115\105\122\101\100 "..(Support.Round(b or C,3).." \115\116\117\100\115")end local v=Security.GetPermissions(Security.GetSelectionAreas(Selection.Items),Core.Player)if Core.Mode=="\084\111\111\108"and Security.ArePartsViolatingAreas(Selection.Items,Core.Player,false,v)then for M,C in pairs(Q)do M.Size=C.Size M.CFrame=C.CFrame end end for M,C in pairs(Q)do M:MakeJoints()M.CanCollide=C.CanCollide M.Anchored=C.Anchored end RegisterChange()end function TrackChange()HistoryRecord={Parts=Support.CloneTable(Selection.Items);BeforeSize={};AfterSize={};BeforeCFrame={};AfterCFrame={},Unapply=function(M)Selection.Replace(M.Parts)local C={}for F,Q in pairs(M.Parts)do table.insert(C,{Part=Q;Size=M.BeforeSize[Q],CFrame=M.BeforeCFrame[Q]})end Core.SyncAPI:Invoke("\083\121\110\099\082\101\115\105\122\101",C)end;Apply=function(M)Selection.Replace(M.Parts)local C={}for F,Q in pairs(M.Parts)do table.insert(C,{Part=Q;Size=M.AfterSize[Q];CFrame=M.AfterCFrame[Q]})end Core.SyncAPI:Invoke("\083\121\110\099\082\101\115\105\122\101",C)end}for M,C in pairs(HistoryRecord.Parts)do HistoryRecord.BeforeSize[C]=C.Size HistoryRecord.BeforeCFrame[C]=C.CFrame end end function RegisterChange()if not HistoryRecord then return end local M={}for C,F in pairs(HistoryRecord.Parts)do HistoryRecord.AfterSize[F]=F.Size HistoryRecord.AfterCFrame[F]=F.CFrame table.insert(M,{Part=F,Size=F.Size;CFrame=F.CFrame})end Core.SyncAPI:Invoke("\083\121\110\099\082\101\115\105\122\101",M)Core.History.Add(HistoryRecord)HistoryRecord=nil end function PreparePartsForResizing()local M={}for C,F in pairs(Selection.Items)do M[F]={Anchored=F.Anchored,CanCollide=F.CanCollide,Size=F.Size;CFrame=F.CFrame}F.Anchored=true F.CanCollide=false F:BreakJoints()F.Velocity=Vector3.new()F.RotVelocity=Vector3.new()end return M end function GetIncrementMultiple(M,C)local F=M%C local Q=M-F local t=(M-F)+C local b=math.abs(M-Q)local v=math.abs(M-t)if b<=v then M=Q else M=t end return M end

Support.AddUserInputListener('Ended', 'MouseButton1', true, function (Input)

	-- Ensure handle resizing is ongoing
	if not HandleResizing then
		return;
	end;

	-- Disable resizing
	HandleResizing = false;

	-- Prevent selection
	Core.Targeting.CancelSelecting();

	-- Clear this connection to prevent it from firing again
	ClearConnection 'HandleRelease';

	-- Make joints, restore original anchor and collision states
	for Part, State in pairs(InitialState) do
		Part:MakeJoints();
		Part.CanCollide = State.CanCollide;
		Part.Anchored = State.Anchored;
	end;

	-- Register the change
	RegisterChange();

end);

function HideHandles()
	-- Hides the resizing handles

	-- Make sure handles exist and are visible
	if not Handles or not Handles.Visible then
		return;
	end;

	-- Hide the handles
	Handles.Visible = false;
	Handles.Parent = nil;

	-- Clear unnecessary resources
	ClearConnection 'AutofocusHandle';

end;

function ResizePartsByFace(Face, Distance, Directions, InitialStates)
	-- Resizes the selection on face `Face` by `Distance` studs, in the given `Directions`

	-- Adjust the size increment to the resizing direction mode
	if Directions == 'Both' then
		Distance = Distance * 2;
	end;

	-- Calculate the increment vector for this resizing
	local AxisSizeMultiplier = AxisSizeMultipliers[Face];
	local IncrementVector = Distance * AxisSizeMultiplier;

	-- Get name of axis the resize will occur on
	local AxisName = FaceAxisNames[Face];

	-- Check for any potential undersizing or oversizing
	local ShortestSize, ShortestPart, LongestSize, LongestPart;
	for Part, InitialState in pairs(InitialStates) do

		-- Calculate target size for this resize
		local TargetSize = InitialState.Size[AxisName] + Distance;

		-- If target size is under 0.05, note if it's the shortest size
		if TargetSize < 0.049999 and (not ShortestSize or (ShortestSize and TargetSize < ShortestSize)) then
			ShortestSize, ShortestPart = TargetSize, Part;

		-- If target size is over 2048, note if it's the longest size
		elseif TargetSize > 2048 and (not LongestSize or (LongestSize and TargetSize > LongestSize)) then
			LongestSize, LongestPart = TargetSize, Part;
		end;

	end;

	-- Return adjustment for undersized parts (snap to lowest possible valid increment multiple)
	if ShortestSize then
		local InitialSize = InitialStates[ShortestPart].Size[AxisName];
		local TargetSize = InitialSize - ResizeTool.Increment * tonumber((tostring((InitialSize - 0.05) / ResizeTool.Increment):gsub('%..+', '')));
		return false, Distance + TargetSize - ShortestSize;
	end;

	-- Return adjustment for oversized parts (snap to highest possible valid increment multiple)
	if LongestSize then
		local TargetSize = ResizeTool.Increment * tonumber((tostring(2048 / ResizeTool.Increment):gsub('%..+', '')));
		return false, Distance + TargetSize - LongestSize;
	end;

	-- Resize each part
	for Part, InitialState in pairs(InitialStates) do

		-- Perform the size change depending on shape
		if Part:IsA 'Part' then

			-- Resize spheres on all axes
			if Part.Shape == Enum.PartType.Ball then
				Part.Size = InitialState.Size + Vector3.new(Distance, Distance, Distance);

			-- Resize cylinders on both Y & Z axes for circle sides
			elseif Part.Shape == Enum.PartType.Cylinder and AxisName ~= 'X' then
				Part.Size = InitialState.Size + Vector3.new(0, Distance, Distance);

			-- Resize block parts and cylinder lengths normally
			else
				Part.Size = InitialState.Size + IncrementVector;
			end;

		-- Perform the size change normally on all other parts
		else
			Part.Size = InitialState.Size + IncrementVector;
		end;

		-- Offset the part when resizing in the normal, one direction
		if Directions == 'Normal' then
			Part.CFrame = InitialState.CFrame * CFrame.new(AxisPositioningMultipliers[Face] * Distance / 2);

		-- Keep the part centered when resizing in both directions
		elseif Directions == 'Both' then
			Part.CFrame = InitialState.CFrame;

		end;

	end;

	-- Indicate that the resizing happened successfully
	return true;
end;

function BindShortcutKeys()
	-- Enables useful shortcut keys for this tool

	-- Track user input while this tool is equipped
	table.insert(Connections, UserInputService.InputBegan:connect(function (InputInfo, GameProcessedEvent)

		-- Make sure this is an intentional event
		if GameProcessedEvent then
			return;
		end;

		-- Make sure this input is a key press
		if InputInfo.UserInputType ~= Enum.UserInputType.Keyboard then
			return;
		end;

		-- Make sure it wasn't pressed while typing
		if UserInputService:GetFocusedTextBox() then
			return;
		end;

		-- Check if the enter key was pressed
		if InputInfo.KeyCode == Enum.KeyCode.Return or InputInfo.KeyCode == Enum.KeyCode.KeypadEnter then

			-- Toggle the current directions mode
			if ResizeTool.Directions == 'Normal' then
				SetDirections('Both');

			elseif ResizeTool.Directions == 'Both' then
				SetDirections('Normal');
			end;

		-- Check if the - key was pressed
		elseif InputInfo.KeyCode == Enum.KeyCode.Minus or InputInfo.KeyCode == Enum.KeyCode.KeypadMinus then

			-- Focus on the increment input
			if ResizeTool.UI then
				ResizeTool.UI.IncrementOption.Increment.TextBox:CaptureFocus();
			end;

		-- Nudge up if the 8 button on the keypad is pressed
		elseif InputInfo.KeyCode == Enum.KeyCode.KeypadEight then
			NudgeSelectionByFace(Enum.NormalId.Top);

		-- Nudge down if the 2 button on the keypad is pressed
		elseif InputInfo.KeyCode == Enum.KeyCode.KeypadTwo then
			NudgeSelectionByFace(Enum.NormalId.Bottom);

		-- Nudge forward if the 9 button on the keypad is pressed
		elseif InputInfo.KeyCode == Enum.KeyCode.KeypadNine then
			NudgeSelectionByFace(Enum.NormalId.Front);

		-- Nudge backward if the 1 button on the keypad is pressed
		elseif InputInfo.KeyCode == Enum.KeyCode.KeypadOne then
			NudgeSelectionByFace(Enum.NormalId.Back);

		-- Nudge left if the 4 button on the keypad is pressed
		elseif InputInfo.KeyCode == Enum.KeyCode.KeypadFour then
			NudgeSelectionByFace(Enum.NormalId.Left);

		-- Nudge right if the 6 button on the keypad is pressed
		elseif InputInfo.KeyCode == Enum.KeyCode.KeypadSix then
			NudgeSelectionByFace(Enum.NormalId.Right);

		-- Start snapping when the R key is pressed down, and it's not the selection clearing hotkey
		elseif InputInfo.KeyCode == Enum.KeyCode.R and not Selection.Multiselecting then
			StartSnapping();

		end;

	end));

	-- Track ending user input while this tool is equipped
	table.insert(Connections, UserInputService.InputEnded:connect(function (InputInfo, GameProcessedEvent)

		-- Make sure this is an intentional event
		if GameProcessedEvent then
			return;
		end;

		-- Make sure this is input from the keyboard
		if InputInfo.UserInputType ~= Enum.UserInputType.Keyboard then
			return;
		end;

		-- Make sure it wasn't pressed while typing
		if UserInputService:GetFocusedTextBox() then
			return;
		end;

		-- Finish snapping when the R key is released, and it's not the selection clearing hotkey
		if InputInfo.KeyCode == Enum.KeyCode.R and not Selection.Multiselecting then
			FinishSnapping();

		end;

	end));

end;

function SetAxisSize(Axis, Size)
	-- Sets the selection's size on axis `Axis` to `Size`

	-- Track this change
	TrackChange();

	-- Prepare parts to be resized
	local InitialStates = PreparePartsForResizing();

	-- Update each part
	for Part, InitialState in pairs(InitialStates) do

		-- Set the part's new size
		Part.Size = Vector3.new(
			Axis == 'X' and Size or Part.Size.X,
			Axis == 'Y' and Size or Part.Size.Y,
			Axis == 'Z' and Size or Part.Size.Z
		);

		-- Keep the part in place
		Part.CFrame = InitialState.CFrame;

	end;

	-- Cache up permissions for all private areas
	local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Selection.Items), Core.Player);

	-- Revert changes if player is not authorized to resize parts towards the end destination
	if Core.Mode == 'Tool' and Security.ArePartsViolatingAreas(Selection.Items, Core.Player, false, AreaPermissions) then
		for Part, State in pairs(InitialStates) do
			Part.Size = State.Size;
			Part.CFrame = State.CFrame;
		end;
	end;

	-- Restore the parts' original states
	for Part, State in pairs(InitialStates) do
		Part:MakeJoints();
		Part.CanCollide = State.CanCollide;
		Part.Anchored = State.Anchored;
	end;

	-- Register the change
	RegisterChange();

end;

function NudgeSelectionByFace(Face)
	-- Nudges the size of the selection in the direction of the given face

	-- Get amount to nudge by
	local NudgeAmount = ResizeTool.Increment;

	-- Reverse nudge amount if shift key is held while nudging
	local PressedKeys = Support.FlipTable(Support.GetListMembers(UserInputService:GetKeysPressed(), 'KeyCode'));
	if PressedKeys[Enum.KeyCode.LeftShift] or PressedKeys[Enum.KeyCode.RightShift] then
		NudgeAmount = -NudgeAmount;
	end;

	-- Track this change
	TrackChange();

	-- Prepare parts to be resized
	local InitialState = PreparePartsForResizing();

	-- Perform the resizing
	local Success, Adjustment = ResizePartsByFace(Face, NudgeAmount, ResizeTool.Directions, InitialState);

	-- If the resizing did not succeed, resize according to the suggested adjustment
	if not Success then
		ResizePartsByFace(Face, Adjustment, ResizeTool.Directions, InitialState);
	end;

	-- Update "studs resized" indicator
	if ResizeTool.UI then
		ResizeTool.UI.Changes.Text.Text = 'resized ' .. Support.Round(Adjustment or NudgeAmount, 3) .. ' studs';
	end;

	-- Cache up permissions for all private areas
	local AreaPermissions = Security.GetPermissions(Security.GetSelectionAreas(Selection.Items), Core.Player);

	-- Revert changes if player is not authorized to resize parts towards the end destination
	if Core.Mode == 'Tool' and Security.ArePartsViolatingAreas(Selection.Items, Core.Player, false, AreaPermissions) then
		for Part, State in pairs(InitialState) do
			Part.Size = State.Size;
			Part.CFrame = State.CFrame;
		end;
	end;

	-- Restore the parts' original states
	for Part, State in pairs(InitialState) do
		Part:MakeJoints();
		Part.CanCollide = State.CanCollide;
		Part.Anchored = State.Anchored;
	end;

	-- Register the change
	RegisterChange();

end;

function TrackChange()

	-- Start the record
	HistoryRecord = {
		Parts = Support.CloneTable(Selection.Items);
		BeforeSize = {};
		AfterSize = {};
		BeforeCFrame = {};
		AfterCFrame = {};

		Unapply = function (Record)
			-- Reverts this change

			-- Select the changed parts
			Selection.Replace(Record.Parts);

			-- Put together the change request
			local Changes = {};
			for _, Part in pairs(Record.Parts) do
				table.insert(Changes, { Part = Part, Size = Record.BeforeSize[Part], CFrame = Record.BeforeCFrame[Part] });
			end;

			-- Send the change request
			Core.SyncAPI:Invoke('SyncResize', Changes);

		end;

		Apply = function (Record)
			-- Applies this change

			-- Select the changed parts
			Selection.Replace(Record.Parts);

			-- Put together the change request
			local Changes = {};
			for _, Part in pairs(Record.Parts) do
				table.insert(Changes, { Part = Part, Size = Record.AfterSize[Part], CFrame = Record.AfterCFrame[Part] });
			end;

			-- Send the change request
			Core.SyncAPI:Invoke('SyncResize', Changes);

		end;

	};

	-- Collect the selection's initial state
	for _, Part in pairs(HistoryRecord.Parts) do
		HistoryRecord.BeforeSize[Part] = Part.Size;
		HistoryRecord.BeforeCFrame[Part] = Part.CFrame;
	end;

end;

function RegisterChange()
	-- Finishes creating the history record and registers it

	-- Make sure there's an in-progress history record
	if not HistoryRecord then
		return;
	end;

	-- Collect the selection's final state
	local Changes = {};
	for _, Part in pairs(HistoryRecord.Parts) do
		HistoryRecord.AfterSize[Part] = Part.Size;
		HistoryRecord.AfterCFrame[Part] = Part.CFrame;
		table.insert(Changes, { Part = Part, Size = Part.Size, CFrame = Part.CFrame });
	end;

	-- Send the change to the server
	Core.SyncAPI:Invoke('SyncResize', Changes);

	-- Register the record and clear the staging
	Core.History.Add(HistoryRecord);
	HistoryRecord = nil;

end;

function PreparePartsForResizing()
	-- Prepares parts for resizing and returns the initial state of the parts

	local InitialState = {};

	-- Stop parts from moving, and capture the initial state of the parts
	for _, Part in pairs(Selection.Items) do
		InitialState[Part] = { Anchored = Part.Anchored, CanCollide = Part.CanCollide, Size = Part.Size, CFrame = Part.CFrame };
		Part.Anchored = true;
		Part.CanCollide = false;
		Part:BreakJoints();
		Part.Velocity = Vector3.new();
		Part.RotVelocity = Vector3.new();
	end;

	return InitialState;
end;

function GetIncrementMultiple(Number, Increment)

	-- Get how far the actual distance is from a multiple of our increment
	local MultipleDifference = Number % Increment;

	-- Identify the closest lower and upper multiples of the increment
	local LowerMultiple = Number - MultipleDifference;
	local UpperMultiple = Number - MultipleDifference + Increment;

	-- Calculate to which of the two multiples we're closer
	local LowerMultipleProximity = math.abs(Number - LowerMultiple);
	local UpperMultipleProximity = math.abs(Number - UpperMultiple);

	-- Use the closest multiple of our increment as the distance moved
	if LowerMultipleProximity <= UpperMultipleProximity then
		Number = LowerMultiple;
	else
		Number = UpperMultiple;
	end;

	return Number;
end;
