LightningLion58

Extra Terrain Tools by LightningLion58

Sep 14th, 2024 (edited)
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 25.17 KB | Source Code | 0 0
  1. --@author LightningLion58
  2.  
  3. --Services:
  4. local UserInputService = game:GetService("UserInputService")
  5. local Studio = settings().Studio
  6. local Selection = game:GetService("Selection")
  7. local ChangeHistoryService = game:GetService("ChangeHistoryService")
  8. local Terrain = workspace:WaitForChild("Terrain")
  9.  
  10. --Variables:
  11. --Initiate the UI:
  12. local mouse : PluginMouse = plugin:GetMouse()
  13.  
  14. local toolbar  : PluginToolbar = plugin:CreateToolbar("Extra Terrain Tools")
  15.  
  16. local toggleMenuBtn : PluginToolbarButton=  toolbar:CreateButton("Open/Close Terrain Tools", "Click this button to open the terrain tools window.", "rbxasset://textures/TerrainTools/icon_terrain_big.png")
  17. toggleMenuBtn.ClickableWhenViewportHidden = false
  18.  
  19. local widgetInfo = DockWidgetPluginGuiInfo.new(
  20.     Enum.InitialDockState.Left,
  21.     false,
  22.     false,
  23.     400, --default:
  24.     400,
  25.     350, --minimum
  26.     350
  27. )
  28.  
  29. local GUI : DockWidgetPluginGui = plugin:CreateDockWidgetPluginGui("TerrainToolsUI", widgetInfo)
  30. GUI.Title = "Extra Terrain Tools"
  31.  
  32. local frame = script.Parent:WaitForChild("TerrainEditorFrame")
  33. local Tools = frame:WaitForChild("Tools")
  34. local SelectRegionButton = Tools:WaitForChild("SelectRegionButton")
  35. local Instruction = frame:WaitForChild("Instruction")
  36. local CheckBox = frame.PasteAirCheckBox.CheckBox
  37.  
  38.  
  39. local function correctColors() --Correctly set the colors of the UI to match the studio theme
  40.     frame.BackgroundColor3 = Studio.Theme:GetColor(Enum.StudioStyleGuideColor.MainBackground, Enum.StudioStyleGuideModifier.Default)
  41.  
  42.     local isDark = Studio.Theme.Name == "Dark"
  43.  
  44.     for _, frame in pairs(Tools:GetChildren()) do
  45.         if(frame:IsA("Frame")) then
  46.             frame.Title.TextColor3 = Studio.Theme:GetColor(Enum.StudioStyleGuideColor.MainText, Enum.StudioStyleGuideModifier.Default)
  47.             if(isDark) then
  48.                 frame.Activation.BackgroundColor3 = Color3.fromRGB(0,0,0)
  49.             else
  50.                 frame.Activation.BackgroundColor3 = Color3.fromRGB(255,255,255)
  51.             end
  52.         end
  53.     end
  54.     if(isDark) then
  55.         CheckBox.BackgroundColor3 = Color3.fromRGB(38, 38, 38)
  56.     else
  57.         CheckBox.BackgroundColor3 = Color3.fromRGB(184, 184, 184)
  58.     end
  59.     CheckBox.Parent.Title.TextColor3 = Studio.Theme:GetColor(Enum.StudioStyleGuideColor.MainText, Enum.StudioStyleGuideModifier.Default)
  60.     Instruction.TextColor3 = Studio.Theme:GetColor(Enum.StudioStyleGuideColor.MainText, Enum.StudioStyleGuideModifier.Default)
  61. end
  62.  
  63. correctColors()
  64. Studio.ThemeChanged:Connect(correctColors) --Update the colors if the studio theme changes
  65.  
  66.  
  67.  
  68. CheckBox.Activated:Connect(function() --Toggle the paste-air checkbox
  69.     if(CheckBox.Text == "") then
  70.         CheckBox.Text = "✓"
  71.     else
  72.         CheckBox.Text = ""
  73.     end
  74. end)
  75.  
  76.  
  77. frame.Parent = GUI
  78.  
  79.  
  80. --Main Code: (Handles the terrain tools)
  81. --[[
  82. Three modes:
  83. selecting - when the user is selecting a region
  84. pasting - when the user is selecting where to paste the region
  85. changing - when the user is editing the size/position of the region selection box using the **handles**, not the studio tools.
  86. ]]
  87. local selecting = false
  88. local pasting = false
  89. local changing = false
  90.  
  91. local currentRegion --The current region instance that has been copied.
  92.  
  93. --[[
  94. The Region Selection uses 3 main instances:
  95.  
  96. selectionBox - The selection box that you can scale and move to select the terrain region.
  97. highlight - Only used for decoration
  98. handles - The handles that you can use to resize and move the selection box
  99. ]]
  100. local selectionBox
  101. local handles
  102.  
  103.  
  104. local function newSelectionBox()
  105.     selectionBox = Instance.new("Part")
  106.     selectionBox.Size = Vector3.new(2,2,2)
  107.     selectionBox.Locked = true
  108.     selectionBox.Name = "TerrainToolsSelectionBox"
  109.     selectionBox.Transparency = 0.95
  110.     selectionBox.Color = Color3.fromRGB(0, 170, 255)
  111.     selectionBox.TopSurface = Enum.SurfaceType.Smooth
  112.     selectionBox.BottomSurface = Enum.SurfaceType.Smooth
  113.  
  114.     --[[
  115.     roundToTop gets a number (n), and rounds it to the closest integer. If there's a decimal of 0.5, it will round it up.
  116.     If size is true, it will make sure that the number is at least 1.
  117.     ]]
  118.     local function roundToTop(n : number, size : boolean?)
  119.         n = math.round(n)
  120.         if(size and n < 1) then
  121.             return 1
  122.         end
  123.         if(n % 1 == 0.5) then
  124.             return n + 0.5
  125.         else
  126.             return n
  127.         end
  128.     end
  129.  
  130.     --The code below makes sure the user doesn't break the plugin by using the studio tools on the selection box, or by deleting the selectionBox
  131.     selectionBox:GetPropertyChangedSignal("Position"):Connect(function()
  132.         if(not changing) then
  133.             local x,y,z = selectionBox.Position.X, selectionBox.Position.Y, selectionBox.Position.Z
  134.             selectionBox.Position = Vector3.new(roundToTop(x), roundToTop(y), roundToTop(z)) --Round the position, terrain CopyRegion gets an integer-based Vector3.
  135.         end
  136.     end)
  137.     selectionBox:GetPropertyChangedSignal("Size"):Connect(function()
  138.         if(not changing) then
  139.             local x,y,z = selectionBox.Size.X, selectionBox.Size.Y, selectionBox.Size.Z
  140.             selectionBox.Size = Vector3.new(roundToTop(x, true), roundToTop(y,true ), roundToTop(z,true ))
  141.         end
  142.     end)
  143.     selectionBox:GetPropertyChangedSignal("Locked"):Connect(function() --Do not allow the selection box to be unlocked.
  144.         --The reason for that is that using the studio tools on the box can break the selection box, or cause inaccurate selections.
  145.         if(not selectionBox.Locked) then
  146.             selectionBox.Locked = true
  147.         end
  148.     end)
  149.     selectionBox:GetPropertyChangedSignal("Orientation"):Connect(function() --Do not allow the user to use the rotate tool, otherwise the wrong corner will be selected, thus the wrong region will be copied.
  150.         selectionBox.Orientation = Vector3.zero
  151.     end)
  152.     selectionBox.AncestryChanged:Connect(function() --If the user destroys the selection box, toggle off the handles.
  153.         if(not selectionBox:IsDescendantOf(game)) then
  154.             handles.Visible = false
  155.             handles.Adornee = nil
  156.         else
  157.             if(not selectionBox:IsDescendantOf(workspace)) then --If the try to move it elsewhere, put it back into the workspace.
  158.                 selectionBox.Parent = workspace
  159.             end
  160.         end
  161.     end)
  162.  
  163. end
  164. newSelectionBox()
  165.  
  166.  
  167. local highlight
  168.  
  169.  
  170. function onHighlightDestroy()
  171.     if(highlight.Parent ~= selectionBox) then
  172.         newHightlight()
  173.         highlight.AncestryChanged:Connect(onHighlightDestroy)
  174.     end
  175. end
  176.  
  177.  
  178. function newHightlight()
  179.     highlight = Instance.new("SelectionBox")
  180.     highlight.LineThickness = 0.1
  181.     highlight.Color3 = Color3.fromRGB(0, 170, 255)
  182.     highlight.Visible = true
  183.     highlight.Adornee = selectionBox
  184.     highlight.Parent = selectionBox
  185.     highlight.AncestryChanged:Connect(onHighlightDestroy)
  186.  
  187. end
  188.  
  189. newHightlight()
  190.  
  191.  
  192.  
  193.  
  194. handles = Instance.new("Handles")
  195. handles.Name = "TerrainToolsHandles"
  196. handles.Style = Enum.HandlesStyle.Movement
  197. handles.Adornee = selectionBox
  198. handles.Visible = false
  199. handles.Color3 = Color3.fromRGB(0, 170, 255)
  200. handles.Parent = game:GetService("CoreGui")
  201.  
  202.  
  203.  
  204. --The two functions below are used to allow the user to undo/redo an action they've performed.
  205. local lastRecordingActive = nil
  206. local function beginRecording(name)
  207.     if(lastRecordingActive) then
  208.         ChangeHistoryService:FinishRecording(lastRecordingActive, Enum.FinishRecordingOperation.Commit)
  209.     end
  210.     lastRecordingActive = ChangeHistoryService:TryBeginRecording(name)
  211.     if(not lastRecordingActive) then
  212.         error("Extra Terrain Tools - A plugin action has begun but was never finished")
  213.     end
  214.  
  215. end
  216.  
  217. local function finishRecording()
  218.     if(lastRecordingActive) then
  219.         ChangeHistoryService:FinishRecording(lastRecordingActive, Enum.FinishRecordingOperation.Commit)
  220.         lastRecordingActive = nil
  221.     end
  222. end
  223.  
  224. ChangeHistoryService.OnUndo:Connect(function(name)
  225.     if(name == "Begin Selecting") then
  226.         selecting = false
  227.         SelectRegionButton.Title.Text = "Select Region"
  228.         SelectRegionButton.Activation.Selecting.Enabled = true
  229.         SelectRegionButton.Activation.NotSelecting.Enabled = false
  230.     end
  231.     if(selectionBox == nil) then
  232.         newSelectionBox()
  233.     end
  234. end)
  235.  
  236. --Below is the code that allows the handles to resize and move the selection box:
  237.  
  238. local function getSizeFromNormalId(normalId : Enum.NormalId) --Returns the size of the part on the axis based on the normalId. (e.g. Top/Bottom - Y axis...)
  239.     return (selectionBox.Size * Vector3.FromNormalId(normalId):Abs()).Magnitude
  240. end
  241.  
  242.  
  243. --[[
  244. getPositionAndSize returns the new size and position of the selection box,
  245. based on the face that was clicked on and how far the handles were dragged.
  246.  
  247. keepInSamePosition - If the player presses left-shift to keep the same position, this will return the same position.
  248. ]]
  249. local function getPositionAndSize(face, delta, keepInSamePosition)
  250.     local addition = Vector3.FromNormalId(face)
  251.     local moveAddition = addition/2
  252.  
  253.     addition = addition:Abs()
  254.     addition *= math.round(delta)
  255.     moveAddition *= math.round(delta)
  256.  
  257.     return (selectionBox.Size + addition), if keepInSamePosition then selectionBox.Position else selectionBox.Position + moveAddition
  258. end
  259.  
  260.  
  261. local lastDistance = 0 --This will be used to calculate how far the handles were dragged from the last time they were dragged.
  262.  
  263. --Handling mouse events for the handles:
  264. handles.MouseButton1Down:Connect(function()
  265.     beginRecording("Selection Box Resized")
  266.     lastDistance = 0 --Reset the lastDistance, since the user is beginning a new drag.
  267.     changing = true --User has begun editing the selection box using the handles.
  268. end)
  269. handles.MouseButton1Up:Connect(function()
  270.     changing = false
  271.     finishRecording()
  272. end)
  273.  
  274. handles.MouseDrag:Connect(function(face, distance) --When the handles are dragged:
  275.     local delta = distance - lastDistance --Calculate how far the were dragged
  276.     if(math.abs(delta) >= 1) then --Make sure they were dragged at least one stud
  277.  
  278.         if(handles.Style == Enum.HandlesStyle.Resize) then --If the handles are set to Resize mode:
  279.             if(math.round(delta) % 1 == 0.5) then  --Make sure math.round will round 0.5 to 1, we don't want any .5's in the size.
  280.                 delta += 0.5
  281.             end
  282.             if(getSizeFromNormalId(face) + math.round(delta) < 1) then --Make sure the size of the face's axis will not be resized to less than 1 stud.
  283.                 return
  284.             end
  285.             --Get the new size and position, and keep the selection box in the same position if the user is pressing LeftShift:
  286.             local size, position = getPositionAndSize(face, delta, UserInputService:IsKeyDown(Enum.KeyCode.LeftShift))
  287.             selectionBox.Position = position
  288.             selectionBox.Size = size
  289.         else
  290.             --Move the part along the face's axis by the distance dragged
  291.             selectionBox.Position += Vector3.FromNormalId(face) * math.round(delta)
  292.         end
  293.         lastDistance = distance
  294.     end
  295. end)
  296.  
  297. --The code below handles the selection, deselection, copy-pasting and insert region instance.
  298.  
  299. local thread
  300. local pastingThread
  301. local selectionPlacementConn : RBXScriptConnection?
  302. local pastingConnection : RBXScriptConnection?
  303.  
  304. local function deselect() --Deselect without changing any text
  305.     selecting = false
  306.     selectionBox.Parent = nil
  307.     if(selectionPlacementConn) then
  308.         selectionPlacementConn:Disconnect()
  309.         coroutine.close(thread)
  310.     end
  311.     handles.Adornee = nil
  312.     handles.Visible = false
  313. end
  314.  
  315.  
  316. local function deselectRegion() --Handles the actual deselection, and the UI text changes.
  317.     deselect()
  318.     Instruction.Text = ""
  319.     SelectRegionButton.Title.Text = "Select Region"
  320.     SelectRegionButton.Activation.Selecting.Enabled = true
  321.     SelectRegionButton.Activation.NotSelecting.Enabled = false
  322.     if(pasting) then
  323.         Tools.PasteRegionButton.Title.Text = "Paste Region"
  324.         Tools.PasteRegionButton.Title2.Text = ""
  325.         if(pastingConnection) then
  326.             pastingConnection:Disconnect()
  327.         end
  328.         Instruction.Text = ""
  329.         pasting = false
  330.         coroutine.close(pastingThread)
  331.     end
  332. end
  333.  
  334. local function selectRegion(pastingRegion : TerrainRegion?) --Prompts the user to select a region (to copy or to paste)
  335.     pasting = pastingRegion ~= nil
  336.  
  337.     --Update the text.
  338.     Instruction.Text = "Click on the region you'd like to select"
  339.  
  340.     selecting = true --Update the mode variable.
  341.  
  342.  
  343.     thread = coroutine.running()
  344.  
  345.     selectionPlacementConn = UserInputService.InputEnded:Connect(function(input, process)
  346.         if(not process and input.UserInputType == Enum.UserInputType.MouseButton1) then
  347.             coroutine.resume(thread) --Resume the thread only when the user presses left mouse click on the viewport.
  348.         end
  349.     end)
  350.     SelectRegionButton.Title.Text = "Selecting..."
  351.     coroutine.yield() --Yield the thread (will be resumed when click the left mouse button)
  352.     if(mouse.Target) then --If the user is not selecting the sky.
  353.         --Change the text according to the mode:
  354.         beginRecording("Begin Selecting")
  355.         if(not pasting) then
  356.             Instruction.Text = "Press R to switch mode (Move, Scale)"
  357.         else
  358.             Instruction.Text = "Move the orange box to where you'd like to paste your region."
  359.         end
  360.         changing = true --About to change the position and size without the studio tools, so change the mode to true:
  361.  
  362.         selectionBox.Position = mouse.Hit.Position:Floor() --Round down the position.
  363.         --Settings and colour based on the mode (copy/paste)
  364.         if(pastingRegion) then
  365.             selectionBox.Color = Color3.fromRGB(255, 170, 0)
  366.             highlight.Color3 = Color3.fromRGB(255, 85, 0)
  367.             handles.Color3 = Color3.fromRGB(255, 85, 0)
  368.             selectionBox.Size = pastingRegion.SizeInCells*4
  369.             handles.Style = Enum.HandlesStyle.Movement
  370.         else
  371.             selectionBox.Size = Vector3.new(2,2,2)
  372.             selectionBox.Color = Color3.fromRGB(0, 170, 255)
  373.             handles.Color3 = Color3.fromRGB(0, 170, 255)
  374.             highlight.Color3 = Color3.fromRGB(0, 170, 255)
  375.         end
  376.         changing = false
  377.         handles.Adornee = selectionBox
  378.         selectionBox.Locked = true
  379.         handles.Visible = true
  380.         selectionBox.Parent = workspace
  381.         --Changes the UI Text:
  382.         finishRecording()
  383.         SelectRegionButton.Title.Text = "Deselect Region"
  384.         SelectRegionButton.Activation.Selecting.Enabled = false
  385.         SelectRegionButton.Activation.NotSelecting.Enabled = true
  386.     else
  387.         --Changes the UI Text:
  388.         Instruction.Text = ""
  389.         SelectRegionButton.Title.Text = "Select Region"
  390.         SelectRegionButton.Activation.Selecting.Enabled = true
  391.         SelectRegionButton.Activation.NotSelecting.Enabled = false
  392.     end
  393. end
  394.  
  395. --Handles pasting a region:
  396.  
  397. local function pasteRegion(region)
  398.  
  399.     if(selecting) then
  400.         SelectRegionButton.Activation.Selecting.Enabled = true
  401.         deselect()
  402.     end
  403.  
  404.     Tools.PasteRegionButton.Title.Text = "Confirm (Left Click)"
  405.     Tools.PasteRegionButton.Title2.Text = "Cancel (Right Click)"
  406.     pastingThread = coroutine.running()
  407.  
  408.     coroutine.wrap(function() --Select a region (In a new thread, to allow the user to press the paste button with left/right mouse buttons.)
  409.         selectRegion(region)
  410.     end)()
  411.  
  412.     pastingConnection = Tools.PasteRegionButton.Activation.InputEnded:Connect(function(input) --When the user presses the button:
  413.         if(input.UserInputType == Enum.UserInputType.MouseButton1) then --If the press was using the left mouse button:
  414.             coroutine.resume(pastingThread) --Continue the pasting thread (see above)
  415.  
  416.             if pastingConnection then
  417.                 pastingConnection:Disconnect() --Stop listening for input on the button.
  418.             end
  419.         elseif(input.UserInputType == Enum.UserInputType.MouseButton2) then
  420.             deselectRegion() --Cancel the selection and pasting.
  421.         end
  422.     end)
  423.     coroutine.yield() --Yield until the user presses the left mouse button (or the right button, but then the coroutine will be closed)
  424.     local minCorner = ((selectionBox.Position - selectionBox.Size/2)/4) --Calculate the minCorner (in cells, not studs)
  425.  
  426.     minCorner = Vector3int16.new(minCorner.X, minCorner.Y, minCorner.Z) --Convert it to an int16 Vector3
  427.     beginRecording("Region Paste")
  428.     Terrain:PasteRegion(region, minCorner, CheckBox.Text ~= "") --Paste the region, and also paste the air if the checkbox is selected.
  429.     deselectRegion() --Finish the selection process.
  430.     finishRecording()
  431. end
  432.  
  433. local function getCorners(isInt16 : boolean?, isInCells : boolean?)
  434.     local cornerMin = (selectionBox.Position - (selectionBox.Size/2):Floor())
  435.     local cornerMax = (selectionBox.Position + (selectionBox.Size/2):Floor())
  436.  
  437.     if(isInCells) then
  438.         cornerMin /= 4
  439.         cornerMax /= 4
  440.     end
  441.  
  442.     if(isInt16) then
  443.         cornerMin = Vector3int16.new(cornerMin.X, cornerMin.Y, cornerMin.Z)
  444.         cornerMax = Vector3int16.new(cornerMax.X, cornerMax.Y, cornerMax.Z)
  445.     else
  446.         cornerMin = Vector3.new(cornerMin.X, cornerMin.Y, cornerMin.Z)
  447.         cornerMax = Vector3.new(cornerMax.X, cornerMax.Y, cornerMax.Z)
  448.  
  449.     end
  450.  
  451.     return cornerMin, cornerMax
  452. end
  453.  
  454. -- Helper function to truncate a 3D array
  455. local function truncateArray(array, newSize: Vector3)
  456.     local result = {}
  457.     for x = 1, math.min(array.Size.X, newSize.X) do
  458.         result[x] = {}
  459.         for y = 1, math.min(array.Size.Y, newSize.Y) do
  460.             result[x][y] = {}
  461.             for z = 1, math.min(array.Size.Z, newSize.Z) do
  462.                 result[x][y][z] = array[x][y][z]
  463.             end
  464.         end
  465.     end
  466.     result.Size = Vector3.new(
  467.         math.min(array.Size.X, newSize.X),
  468.         math.min(array.Size.Y, newSize.Y),
  469.         math.min(array.Size.Z, newSize.Z)
  470.     )
  471.     return result
  472. end
  473.  
  474. --Shrink a Region3 to match a given size in voxel units
  475. local function shrinkRegion3ToFitArray(region: Region3, arraySize: Vector3, resolution: number): Region3
  476.     local origin = region.CFrame.Position - (region.Size / 2)
  477.     local newSize = Vector3.new(
  478.         arraySize.X * resolution,
  479.         arraySize.Y * resolution,
  480.         arraySize.Z * resolution
  481.     )
  482.     local newCFrame = CFrame.new(origin + newSize / 2)
  483.     return Region3.new(newCFrame.Position - newSize / 2, newCFrame.Position + newSize / 2)
  484. end
  485.  
  486. --Adjust array and Region3
  487. local function fitArrayToRegion3(array, region : Region3, resolution : number)
  488.     local arraySize = array.Size
  489.     local regionSize = region.Size
  490.  
  491.     --Compute how many voxels fit in the Region3
  492.     local regionVoxelSize = Vector3.new(
  493.         math.floor(regionSize.X / resolution),
  494.         math.floor(regionSize.Y / resolution),
  495.         math.floor(regionSize.Z / resolution)
  496.     )
  497.  
  498.     --Determine new voxel size that fits both
  499.     local finalVoxelSize = Vector3.new(
  500.         math.min(regionVoxelSize.X, arraySize.X),
  501.         math.min(regionVoxelSize.Y, arraySize.Y),
  502.         math.min(regionVoxelSize.Z, arraySize.Z)
  503.     )
  504.  
  505.     --Truncate array to match final voxel size
  506.     local truncatedArray = truncateArray(array, finalVoxelSize)
  507.  
  508.     --Shrink Region3 to match array size in world units
  509.     local adjustedRegion = shrinkRegion3ToFitArray(region, truncatedArray.Size, resolution)
  510.  
  511.     return truncatedArray, adjustedRegion
  512. end
  513.  
  514. local function rotateSelection(direction : number)
  515.     local region = Region3.new(selectionBox.Position - selectionBox.Size/2, selectionBox.Position + selectionBox.Size/2):ExpandToGrid(4)
  516.     selectionBox.Size = Vector3.new(selectionBox.Size.Z, selectionBox.Size.Y, selectionBox.Size.X)
  517.     --Read current voxels:
  518.     local materials, occupancies = Terrain:ReadVoxels(region, 4)
  519.  
  520.     local newSize = Vector3.new(occupancies.Size.Z, occupancies.Size.Y, occupancies.Size.X)
  521.     local newMaterials, newOccupancies = {Size = newSize}, {Size = newSize}
  522.     --Perform the rotation:
  523.     for x = 1, occupancies.Size.Z, 1 do
  524.  
  525.         local newXIndex
  526.         if(direction == 1) then
  527.             newXIndex = occupancies.Size.Z - x + 1
  528.         else           
  529.             newXIndex = x
  530.         end    
  531.         newOccupancies[newXIndex] = {}
  532.         newMaterials[newXIndex] = {}
  533.  
  534.         for y = 1, occupancies.Size.Y, 1 do
  535.             newOccupancies[newXIndex][y] = {}
  536.             newMaterials[newXIndex][y] = {}
  537.             for z = occupancies.Size.X, 1, -1 do
  538.                 local newZIndex
  539.                 if(direction == 1) then
  540.                     newZIndex = z
  541.                 else           
  542.                     newZIndex = occupancies.Size.X - z + 1
  543.                 end
  544.                 --Perform rotation on the 3D array along the Y axis:
  545.                 newOccupancies[newXIndex][y][newZIndex] = occupancies[occupancies.Size.X - z + 1][y][occupancies.Size.Z - x + 1]
  546.                 newMaterials[newXIndex][y][newZIndex] = materials[occupancies.Size.X - z + 1][y][occupancies.Size.Z - x + 1]
  547.             end
  548.         end
  549.     end
  550.     --Write the new voxels:
  551.     local newRegion = Region3.new(selectionBox.Position - selectionBox.Size/2, selectionBox.Position + selectionBox.Size/2):ExpandToGrid(4)
  552.     newOccupancies, newRegion = fitArrayToRegion3(newOccupancies, newRegion, 4)
  553.     newMaterials, newRegion = fitArrayToRegion3(newMaterials, newRegion, 4)
  554.    
  555.     Terrain:WriteVoxels(newRegion, 4, newMaterials, newOccupancies)
  556. end
  557.  
  558. --Below is the code the connects the tool button presses to their matching functions:
  559. local buttonFunctions = {
  560.     ["SelectRegionButton"] = function() --This activates when the user presses the SelectRegionButton.
  561.         if(selecting) then --If the user is already selecting, then deselect.
  562.             deselectRegion()
  563.         else --Otherwise, select.
  564.             selectRegion()
  565.         end
  566.     end,
  567.     ["CopyRegionButton"] = function()--This activates when the user presses the CopyRegionButton.
  568.  
  569.         local selected = Selection:Get()[1] --Gets their first selection and checks if it's a terrain region:
  570.         if(selected and selected:IsA("TerrainRegion")) then
  571.             --If it is and the user pressed copy, save it as the current region copied.
  572.             currentRegion = selected:Clone()
  573.             return
  574.         end
  575.         if(selecting) then --If they are selecting, then copy the selection:
  576.             local cornerMin, cornerMax = getCorners(true, true)
  577.  
  578.             currentRegion = Terrain:CopyRegion(Region3int16.new(cornerMin, cornerMax))
  579.             Tools.CopyRegionButton.Title.Text = "Copied!"
  580.             task.wait(0.5)
  581.             Tools.CopyRegionButton.Title.Text = "Copy Selection"
  582.         else --If they have nothing selected, then tell them they need to select something:
  583.             Tools.CopyRegionButton.Title.Text = "Nothing Selected!"
  584.             task.wait(0.5)
  585.             Tools.CopyRegionButton.Title.Text = "Copy Selection"
  586.         end
  587.     end,
  588.     ["PasteRegionButton"] = function() --This activates when the user presses the PasteRegionButton.
  589.         if(pasting) then --If the user isn't already pasting something.
  590.             return
  591.         end
  592.         local selected = Selection:Get()[1]  --Gets their first selection and checks if it's a terrain region:
  593.         if(selected and selected:IsA("TerrainRegion")) then
  594.             pasteRegion(selected)--If it is and the user pressed paste, then prompt them to select where to paste.
  595.         else
  596.             if(currentRegion) then --If a terrain region has already been selected and copied, then paste it:
  597.                 pasteRegion(currentRegion)
  598.             else --If they have nothing copied, then tell them they need to select something:
  599.                 Tools.PasteRegionButton.Title.Text = "Nothing Selected!"
  600.                 task.wait(0.5)
  601.                 Tools.PasteRegionButton.Title.Text = "Paste Region"
  602.  
  603.             end
  604.         end
  605.     end,
  606.     ["InsertRegionInstance"] = function() --This activates when the user presses the InsertRegionInstanceButton.
  607.         if(currentRegion) then --If a terrain region has already been selected and copied, then insert it:
  608.             beginRecording("Insert Terrain Region Instance")
  609.             local newRegion = currentRegion:Clone()
  610.             newRegion.Parent = workspace
  611.             Selection:Set({newRegion})
  612.             finishRecording()
  613.         else --If they have nothing copied, then tell them they need to select something:
  614.             Tools.InsertRegionInstance.Title.Text = "Nothing Selected!"
  615.             task.wait(0.5)
  616.             Tools.InsertRegionInstance.Title.Text = "Insert Region Instance"
  617.         end
  618.     end,
  619.     ["RotateLeftButton"] = function()--This activates when the user presses the RotateLeftButton is pressed
  620.         if(selecting and not pasting) then --If they are selecting, then copy the selection:
  621.             beginRecording("Rotate Terrain Left")
  622.             --Perform Rotation:
  623.             rotateSelection(1)
  624.             finishRecording()
  625.         end
  626.     end,
  627.     ["RotateRightButton"] = function()--This activates when the user presses the RotateLeftButton is pressed
  628.         if(selecting and not pasting) then --If they are selecting, then copy the selection:
  629.             beginRecording("Rotate Terrain Right")
  630.             --Perform Rotation:
  631.             rotateSelection(-1)
  632.             finishRecording()
  633.         end
  634.     end
  635. }
  636. --Connects the button events to their matching functions:
  637. for _, btn in pairs(Tools:GetChildren()) do
  638.     if(btn:IsA("Frame")) then
  639.         btn.Activation.Activated:Connect(buttonFunctions[btn.Name])
  640.     end
  641. end
  642.  
  643. --Below is the code that allows the user to select regions using the handles, and change the mode (resize/move) them using the R key.
  644. UserInputService.InputBegan:Connect(function(input, process)
  645.     if(process or not selecting) then
  646.         return
  647.     end
  648.     if(input.KeyCode == Enum.KeyCode.R and not pasting) then
  649.         if(handles.Style == Enum.HandlesStyle.Resize) then
  650.             handles.Style = Enum.HandlesStyle.Movement
  651.         else
  652.             handles.Style = Enum.HandlesStyle.Resize
  653.         end
  654.     elseif(input.KeyCode == Enum.KeyCode.Escape) then
  655.         deselectRegion()
  656.     elseif(input.KeyCode == Enum.KeyCode.C and UserInputService:IsKeyDown(Enum.KeyCode.LeftControl)) then
  657.         buttonFunctions["CopyRegionButton"]()
  658.     elseif(UserInputService:IsKeyDown(Enum.KeyCode.C) and UserInputService:IsKeyDown(Enum.KeyCode.LeftControl)) then
  659.         buttonFunctions["CopyRegionButton"]()
  660.     elseif(UserInputService:IsKeyDown(Enum.KeyCode.V) and UserInputService:IsKeyDown(Enum.KeyCode.LeftControl)) then
  661.         buttonFunctions["PasteRegionButton"]()
  662.     end
  663. end)
  664. --If the user selects a terrain region using the explorer, suggest them to copy/paste it using the plugin.
  665. Selection.SelectionChanged:Connect(function()
  666.     local firstSelection = Selection:Get()[1]
  667.     if(firstSelection and firstSelection:IsA("TerrainRegion")) then
  668.         Tools.PasteRegionButton.Title.Text = "Paste Selected Region"
  669.         Tools.CopyRegionButton.Title.Text = "Copy Selected Region"
  670.     else
  671.         Tools.PasteRegionButton.Title.Text = "Paste Region"
  672.         Tools.CopyRegionButton.Title.Text = "Copy Selection"
  673.     end
  674. end)
  675.  
  676. --Deselect if the user clicks off the plugin or uninstalls/disables it:
  677. toggleMenuBtn.Click:Connect(function()
  678.     GUI.Enabled = not GUI.Enabled
  679.     if(GUI.Enabled == false) then
  680.         deselectRegion()
  681.     end
  682. end)
  683.  
  684. plugin.Unloading:Connect(function()
  685.     finishRecording()
  686.     handles:Destroy()
  687.     selectionBox:Destroy()
  688. end)
  689.  
  690. --Thank you for checking out my plugin,
  691. --LightningLion58
Advertisement
Add Comment
Please, Sign In to add comment