chore: init

This commit is contained in:
2026-01-06 21:53:52 +02:00
commit 0ac6d6e214
32 changed files with 4016 additions and 0 deletions

35
default.project.json Normal file
View File

@@ -0,0 +1,35 @@
{
"name": "project",
"tree": {
"$className": "DataModel",
"ReplicatedStorage": {
"$className": "ReplicatedStorage",
"$ignoreUnknownInstances": true,
"$path": "src/ReplicatedStorage"
},
"ServerScriptService": {
"$className": "ServerScriptService",
"$ignoreUnknownInstances": true,
"$path": "src/ServerScriptService"
},
"StarterGui": {
"$className": "StarterGui",
"$ignoreUnknownInstances": true,
"$path": "src/StarterGui"
},
"StarterPlayer": {
"$className": "StarterPlayer",
"StarterPlayerScripts": {
"$className": "StarterPlayerScripts",
"$ignoreUnknownInstances": true,
"$path": "src/StarterPlayer/StarterPlayerScripts"
},
"$ignoreUnknownInstances": true
},
"Workspace": {
"$className": "Workspace",
"$ignoreUnknownInstances": true,
"$path": "src/Workspace"
}
}
}

View File

@@ -0,0 +1,86 @@
local BlockManager = {}
BlockManager.BlockIdMappings = {} :: {BasePart}
for i,v in pairs(game:GetService("ReplicatedStorage"):WaitForChild("Blocks"):GetChildren()) do
BlockManager.BlockIdMappings[v:GetAttribute("n")] = v
end
BlockManager.UpdateIdMappings = {} :: {BasePart}
for i,v in pairs(game:GetService("ReplicatedStorage"):WaitForChild("BlockUpdateOperations"):GetChildren()) do
local success, reason = pcall(function()
BlockManager.UpdateIdMappings[v:GetAttribute("n")] = require(v)
end)
if not success then
warn("[BLOCKMANAGER] Invalid update operation",v:GetAttribute("n"),":",reason)
end
end
local warnedBlockIds = {}
function BlockManager:GetBlock(blockId: number, attr: {[typeof("")]: any}?)
task.synchronize()
if not BlockManager.BlockIdMappings[blockId] then
if not warnedBlockIds[blockId] then
warnedBlockIds[blockId] = true
warn("[BLOCKMANAGER] Invalid block id",blockId)
end
return script.invalid:Clone()
end
local b = BlockManager.BlockIdMappings[blockId]:Clone()
b.Size = Vector3.new(3.95,3.95,3.95)
for i,v in pairs(attr or {}) do
b:SetAttribute(i,v)
end
if BlockManager.UpdateIdMappings[blockId] then
local success, reason = pcall(function()
BlockManager.UpdateIdMappings[blockId](b)
end)
if not success then
warn("[BLOCKMANAGER] Failed update operation",blockId,":",reason)
end
end
return b
end
-- ChatGPT Generated Func!!!!
function BlockManager:GetBlockRotated(blockId: number, face: Enum.NormalId, attr: {[typeof("")]: any}?)
-- Returns block with id blockId, rotated so the given face (NormalId) points north (+X).
local block = BlockManager:GetBlock(blockId, attr)
local rot = CFrame.new()
task.synchronize()
if face == Enum.NormalId.Front then
rot = CFrame.Angles(0, 0, 0) -- no rot
elseif face == Enum.NormalId.Back then
rot = CFrame.Angles(0, math.rad(180), 0)
elseif face == Enum.NormalId.Left then
rot = CFrame.Angles(0, math.rad(90), 0)
elseif face == Enum.NormalId.Right then
rot = CFrame.Angles(0, math.rad(-90), 0)
elseif face == Enum.NormalId.Top then
rot = CFrame.Angles(math.rad(-90), 0, 0) -- top +x
elseif face == Enum.NormalId.Bottom then
rot = CFrame.Angles(math.rad(90), 0, 0) -- bottom +x
end
-- ocbwoy3's fix
block:PivotTo(rot)
block.CFrame = CFrame.new(rot.Position)
return block
end
return BlockManager

View File

@@ -0,0 +1,3 @@
{
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,180 @@
local Chunk = {}
Chunk.__index = Chunk
Chunk.UpdateBlockBindable = Instance.new("BindableEvent") :: BindableEvent
Chunk.AllChunks = {} :: {[typeof("")]: typeof(Chunk.new(0,0,0))}
local RunService = game:GetService("RunService")
local function Swait(l)
for i = 1,l do
RunService.Stepped:Wait()
end
end
export type BlockData = {
id: number,
state: {
[typeof("")]: string | boolean | number
}
}
function Chunk.new(x,y,z)
local self = setmetatable({}, Chunk)
self.pos = Vector3.new(x,y,z)
-- Tick ONLY in a 5 chunk distance of LP's char
self.inhabitedTime = tick()
self.instance = Instance.new("Folder")
self.unloadChunkHook = function() end
self.UpdateBlockBindableL = Instance.new("BindableEvent") :: BindableEvent
self.loaded = false
self.loading = false
self.data = {} :: {[typeof("")]: BlockData} -- "X,Y,Z": BlockData ("-1,-1,1": BlockData)
return self
end
function Chunk.from(x,y,z,data)
local self = setmetatable({}, Chunk)
self.pos = Vector3.new(x,y,z)
-- Tick ONLY in a 5 chunk distance of LP's char
self.inhabitedTime = tick()
self.instance = Instance.new("Folder")
self.unloadChunkHook = function() end
self.UpdateBlockBindableL = Instance.new("BindableEvent") :: BindableEvent
self.data = data :: {[typeof("")]: BlockData} -- "X,Y,Z": BlockData ("-1,-1,1": BlockData)
return self
end
function Chunk:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, offsetX, offsetY, offsetZ)
task.desynchronize()
-- Calculate the local position of the neighboring block
local neighborRX, neighborRY, neighborRZ = rx + offsetX, ry + offsetY, rz + offsetZ
local neighborGX, neighborGY, neighborGZ = gx, gy, gz
-- Adjust for chunk boundaries
if neighborRX < 1 then
neighborRX = 8
neighborGX = gx - 1
elseif neighborRX > 8 then
neighborRX = 1
neighborGX = gx + 1
end
if neighborRY < 1 then
neighborRY = 8
neighborGY = gy - 1
elseif neighborRY > 8 then
neighborRY = 1
neighborGY = gy + 1
end
if neighborRZ < 1 then
neighborRZ = 8
neighborGZ = gz - 1
elseif neighborRZ > 8 then
neighborRZ = 1
neighborGZ = gz + 1
end
if neighborGY < 0 then
return true
end
-- Get the neighboring chunk
local neighborChunk = Chunk.AllChunks[`{neighborGX},{neighborGY},{neighborGZ}`]
if not neighborChunk then
return false -- Treat unloaded chunks as empty so edges render
end
-- Check if the block exists in the neighboring chunk
return neighborChunk:GetBlockAt(neighborRX, neighborRY, neighborRZ) ~= nil
end
function Chunk:IsBlockRenderable(rx, ry, rz)
task.desynchronize()
local gx, gy, gz = self.pos.X, self.pos.Y, self.pos.Z
-- Check all six neighboring blocks
local d = not (
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 1, 0, 0) and
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, -1, 0, 0) and
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 0, 1, 0) and
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 0, -1, 0) and
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 0, 0, 1) and
self:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, 0, 0, -1)
)
return d
end
function Chunk:Tick()
self.inhabitedTime = tick()
end
function Chunk:PropogateChanges(x: number,y: number,z: number,d:BlockData)
self.UpdateBlockBindableL:Fire(x,y,z,d)
end
function Chunk:GetBlockAt(x,y,z)
task.desynchronize()
if not self.data[`{tostring(x)},{tostring(y)},{tostring(z)}`] then
return nil
end
return self.data[`{tostring(x)},{tostring(y)},{tostring(z)}`]
end
function Chunk:CreateBlock(x: number,y: number,z: number,d:BlockData)
self.data[`{tostring(x)},{tostring(y)},{tostring(z)}`] = d
self:PropogateChanges(x,y,z,d)
return self:GetBlockAt(x,y,z)
end
function Chunk:RemoveBlock(x, y, z)
self.data[x .. "," .. y .. "," .. z] = nil
self:PropogateChanges(x,y,z,0)
end
-- unsure why this exists
function Chunk:Load()
end
function Chunk:Unload()
task.synchronize()
self.loaded = false
-- SLOWCLEAR
task.defer(function()
local g = 0
for _,v in pairs(self.instance:GetChildren()) do
pcall(function()
v:Destroy()
end)
g += 1
if g == 30 then
g = 0
Swait(2)
end
end
task.synchronize()
self.instance.Parent = nil
self.instance:Destroy()
self.unloadChunkHook()
task.desynchronize()
end)
end
-- DO NOT INTERACT WITH CHUNK AFTER CALLING THIS
function Chunk:Destroy()
self.data = {}
end
return Chunk :: typeof(Chunk)

View File

@@ -0,0 +1,257 @@
local ChunkBuilder = {}
local Chunk = require("./Chunk")
local BlockManager = require("./BlockManager")
local util = require("../Util")
local objects = script.Parent.Parent.Parent.Objects
local RunService = game:GetService("RunService")
local ChunkBorderFolder = game:GetService("Workspace"):FindFirstChildOfClass("Terrain")
local NEIGHBOR_OFFSETS = {
{-1, 0, 0}, {1, 0, 0},
{0, -1, 0}, {0, 1, 0},
{0, 0, -1}, {0, 0, 1}
}
-- TODO: Move to Chunk
type BlockData = {
id: number,
state: {
[typeof("")]: string | boolean | number
}
}
local function placeBorder(a,b,c)
local pos = util.ChunkPosToCFrame(Vector3.new(a,b,c),Vector3.new(1,1,1)).Position - Vector3.new(2,2,2)
local d = objects.ChunkLoading:Clone()
d:PivotTo(CFrame.new(pos))
d.Parent = ChunkBorderFolder
return d
end
local function Swait(l)
for i = 1,l do
RunService.Stepped:Wait()
end
end
local function propogateNeighboringBlockChanges(cx, cy, cz, x, y, z)
--warn("propogateNeighboringBlockChanges",cx,cy,cz,x,y,z)
-- updates block in another chunk
local c = Chunk.AllChunks[`{cx},{cy},{cz}`]
if not c then return end
local d = c.data[`{x},{y},{z}`]
if not d then return end
if c:IsBlockRenderable(x, y, z) then
if c.instance:FindFirstChild(`{x},{y},{z}`) then return end
task.synchronize()
local block = BlockManager:GetBlockRotated(d.id, util.RotationStringToNormalId(d.state["r"] or "f"), d.state)
block.Name = `{x},{y},{z}`
block:PivotTo(util.ChunkPosToCFrame(c.pos, Vector3.new(x, y, z)))
block.Parent = c.instance
task.desynchronize()
else
local existing = c.instance:FindFirstChild(`{x},{y},{z}`)
if existing then
task.synchronize()
existing:Destroy()
task.desynchronize()
end
end
end
function ChunkBuilder:BuildChunk(c: typeof(Chunk.new(0,0,0)),parent: Instance?)
if c.loaded then
return c.instance
end
local blocks = c.data
local newcache = {} :: {[typeof("")]: BlockData}
local finished = false
local ch = Instance.new("Folder")
ch.Parent = parent
ch.Name = `{c.pos.X},{c.pos.Y},{c.pos.Z}`
local conn = c.UpdateBlockBindableL.Event:Connect(function(x: number, y: number, z: number, d: BlockData)
task.desynchronize()
if finished == false then
newcache[`{x},{y},{z}`] = d
return
end
task.synchronize()
for _, o in pairs(NEIGHBOR_OFFSETS) do
--warn("propogate",o[1],o[2],o[3])
-- Adjust for chunk boundaries
local b = {x = x + o[1], y = y + o[2], z = z + o[3]}
local ch = {x = c.pos.X, y = c.pos.Y, z = c.pos.Z}
if b.x < 1 then ch.x = c.pos.X - 1 b.x = 8 end
if b.x > 8 then ch.x = c.pos.X + 1 b.x = 1 end
if b.y < 1 then ch.y = c.pos.Y - 1 b.y = 8 end
if b.y > 8 then ch.y = c.pos.Y + 1 b.y = 1 end
if b.z < 1 then ch.z = c.pos.Z - 1 b.z = 8 end
if b.z > 8 then ch.z = c.pos.Z + 1 b.z = 1 end
propogateNeighboringBlockChanges(ch.x, ch.y, ch.z, b.x, b.y, b.z)
--BlockManager:GetBlock(ch.x)
end
local blockName = `{x},{y},{z}`
local existing = ch:FindFirstChild(blockName)
if d == 0 then
if existing then
task.synchronize()
existing:Destroy()
task.desynchronize()
end
return
end
if not c:IsBlockRenderable(x, y, z) then
if existing then
task.synchronize()
existing:Destroy()
task.desynchronize()
end
return
end
if existing then
task.synchronize()
existing:Destroy()
task.desynchronize()
end
if not d then return end
if d.id == 0 then return end
local N = util.RotationStringToNormalId(d.state["r"] or "f")
task.synchronize()
local block = BlockManager:GetBlockRotated(d.id, N, d.state)
block.Name = blockName
block:PivotTo(util.ChunkPosToCFrame(c.pos, Vector3.new(x, y, z)))
block.Parent = ch
task.desynchronize()
end)
c.unloadChunkHook = function()
conn:Disconnect()
blocks = nil
c = nil
end
task.defer(function()
local p = 0
task.synchronize()
local hb = false
for a,b in pairs(blocks) do
hb = true
end
local border = Instance.new("Part")
if hb == true then
border:Destroy()
border = placeBorder(c.pos.X, c.pos.Y, c.pos.Z)
end
for a,b in pairs(blocks) do
task.desynchronize()
local coords = util.BlockPosStringToCoords(a)
if not c:IsBlockRenderable(coords.X, coords.Y, coords.Z) then
if ch:FindFirstChild(a) then
task.synchronize()
ch:FindFirstChild(a):Destroy()
task.desynchronize()
end
continue
end
task.desynchronize()
local N = util.RotationStringToNormalId(b.state["r"] or "f")
task.synchronize()
local block = BlockManager:GetBlockRotated(b.id, N, b.state)
if ch:FindFirstChild(a) then
ch:FindFirstChild(a):Destroy()
end
block.Name = a
block:PivotTo(util.ChunkPosToCFrame(c.pos, coords))
block.Parent = ch
p += 1
if p == 15 then
p = 0
Swait(1)
end
end
finished = true
task.synchronize()
border:Destroy()
task.desynchronize()
task.defer(function()
task.synchronize()
for key, data in pairs(newcache) do
local coords = util.BlockPosStringToCoords(key)
for _, o in pairs(NEIGHBOR_OFFSETS) do
-- chunks are 8x8x8
local nb = {x = coords.X + o[1], y = coords.Y + o[2], z = coords.Z + o[3]}
local chCoords = {x = c.pos.X, y = c.pos.Y, z = c.pos.Z}
if nb.x == 0 then chCoords.x = c.pos.X - 1 nb.x = 8 end
if nb.x == 9 then chCoords.x = c.pos.X + 1 nb.x = 1 end
if nb.y == 0 then chCoords.y = c.pos.Y - 1 nb.y = 8 end
if nb.y == 9 then chCoords.y = c.pos.Y + 1 nb.y = 1 end
if nb.z == 0 then chCoords.z = c.pos.Z - 1 nb.z = 8 end
if nb.z == 9 then chCoords.z = c.pos.Z + 1 nb.z = 1 end
propogateNeighboringBlockChanges(chCoords.x, chCoords.y, chCoords.z, nb.x, nb.y, nb.z)
end
local existing = ch:FindFirstChild(key)
if data == 0 or (data and data.id == 0) then
if existing then
existing:Destroy()
end
continue
end
if not c:IsBlockRenderable(coords.X, coords.Y, coords.Z) then
if existing then
existing:Destroy()
end
continue
end
if existing then
existing:Destroy()
end
if not data then
continue
end
local N = util.RotationStringToNormalId(data.state["r"] or "f")
local block = BlockManager:GetBlockRotated(data.id, N, data.state)
block.Name = key
block:PivotTo(util.ChunkPosToCFrame(c.pos, coords))
block.Parent = ch
end
newcache = nil
blocks = nil
end)
task.desynchronize()
end)
c.loaded = true
return ch
end
return ChunkBuilder

View File

@@ -0,0 +1,232 @@
local ChunkManager = {}
local RunService = game:GetService("RunService")
local Chunk = require("./ChunkManager/Chunk")
local BlockManager = require("./ChunkManager/BlockManager")
local ChunkBuilder = require("./ChunkManager/ChunkBuilder")
local remote = game:GetService("ReplicatedStorage"):WaitForChild("RecieveChunkPacket")
local tickremote = game:GetService("ReplicatedStorage"):WaitForChild("Tick")
local ChunkFolder = Instance.new("Folder")
ChunkFolder.Name = "$blockscraft_client"
ChunkManager.ChunkFolder = ChunkFolder
local CHUNK_RADIUS = 5
local LOAD_BATCH = 8
local FORCELOAD_CHUNKS = {
{0, 1, 0}
}
local unloadingChunks = {}
local pendingChunkRequests = {}
local CHUNK_OFFSETS = {}
do
for y = -CHUNK_RADIUS, CHUNK_RADIUS do
for x = -CHUNK_RADIUS, CHUNK_RADIUS do
for z = -CHUNK_RADIUS, CHUNK_RADIUS do
table.insert(CHUNK_OFFSETS, {x, y, z, (x * x) + (y * y) + (z * z)})
end
end
end
table.sort(CHUNK_OFFSETS, function(a, b)
return a[4] < b[4]
end)
end
local function Swait(l)
task.synchronize()
for _ = 1, l do
RunService.Stepped:Wait()
end
end
function ChunkManager:GetChunk(x, y, z)
local key = `{x},{y},{z}`
if Chunk.AllChunks[key] then
return Chunk.AllChunks[key]
end
if pendingChunkRequests[key] then
task.synchronize()
while pendingChunkRequests[key] do
task.wait()
end
return Chunk.AllChunks[key]
end
task.synchronize()
pendingChunkRequests[key] = true
local ok, data = pcall(function()
return remote:InvokeServer(x, y, z)
end)
if not ok then
data = {}
end
task.synchronize()
local ch = Chunk.from(x, y, z, data)
Chunk.AllChunks[key] = ch
pendingChunkRequests[key] = nil
return ch
end
local function ensureNeighboringChunksLoaded(x, y, z)
local offsets = {
{1, 0, 0}, {-1, 0, 0},
{0, 1, 0}, {0, -1, 0},
{0, 0, 1}, {0, 0, -1}
}
for _, offset in ipairs(offsets) do
local nx, ny, nz = x + offset[1], y + offset[2], z + offset[3]
ChunkManager:GetChunk(nx, ny, nz):Tick()
end
end
function ChunkManager:LoadChunk(x, y, z)
local key = `{x},{y},{z}`
if unloadingChunks[key] or not Chunk.AllChunks[key] or Chunk.AllChunks[key].loaded then
return
end
unloadingChunks[key] = true
task.defer(function()
task.desynchronize()
ensureNeighboringChunksLoaded(x, y, z)
local chunk = Chunk.AllChunks[key]
if not chunk then
chunk = ChunkManager:GetChunk(x, y, z)
Chunk.AllChunks[key] = chunk
end
task.synchronize()
local instance = ChunkBuilder:BuildChunk(chunk, ChunkFolder)
chunk.instance = instance
chunk.loaded = true
unloadingChunks[key] = nil
end)
end
function ChunkManager:ForceTick()
for _, coords in ipairs(FORCELOAD_CHUNKS) do
local key = `{coords[1]},{coords[2]},{coords[3]}`
local chunk = Chunk.AllChunks[key]
if not chunk then
ChunkManager:LoadChunk(coords[1], coords[2], coords[3])
else
chunk:Tick()
end
end
end
function ChunkManager:TickI()
for key, chunk in pairs(Chunk.AllChunks) do
if tick() - chunk.inhabitedTime <= 5 then
tickremote:FireServer(key)
end
end
end
function ChunkManager:Tick()
ChunkManager:ForceTick()
local player = game:GetService("Players").LocalPlayer
if not player.Character then
return
end
local pos = player.Character:GetPivot().Position
local chunkPos = {
x = math.round(pos.X / 32),
y = math.round(pos.Y / 32),
z = math.round(pos.Z / 32)
}
task.defer(function()
local processed = 0
for _, offset in ipairs(CHUNK_OFFSETS) do
local cx, cy, cz = chunkPos.x + offset[1], chunkPos.y + offset[2], chunkPos.z + offset[3]
local chunk = ChunkManager:GetChunk(cx, cy, cz)
chunk.inhabitedTime = tick()
if not chunk.loaded then
ChunkManager:LoadChunk(cx, cy, cz)
processed += 1
if processed % LOAD_BATCH == 0 then
Swait(1)
end
end
end
end)
--[[
task.defer(function()
for y = 0, 2 do
task.defer(function()
for x = -CHUNK_RADIUS, CHUNK_RADIUS do
task.desynchronize()
for z = -CHUNK_RADIUS, CHUNK_RADIUS do
local cx, cy, cz = chunkPos.x + x, y, chunkPos.z + z
local key = `{cx},{cy},{cz}`
local chunk = ChunkManager:GetChunk(cx, cy, cz)
chunk.inhabitedTime = tick()
if not chunk.loaded then
ChunkManager:LoadChunk(cx, cy, cz)
Swait(2)
end
end
task.synchronize()
end
end)
Swait(10)
end
end)
--]]
for key, loadedChunk in pairs(Chunk.AllChunks) do
if tick() - loadedChunk.inhabitedTime > 15 and not unloadingChunks[key] then
unloadingChunks[key] = true
task.defer(function()
task.synchronize()
loadedChunk:Unload()
loadedChunk:Destroy()
Chunk.AllChunks[key] = nil
unloadingChunks[key] = nil
end)
end
end
end
function ChunkManager:Init()
if not RunService:IsClient() then
error("ChunkManager:Init can only be called on the client")
end
ChunkFolder.Parent = game:GetService("Workspace")
ChunkManager:ForceTick()
task.defer(function()
while true do
wait(2)
ChunkManager:TickI()
end
end)
task.defer(function()
while true do
task.defer(function()
local success, err = pcall(function()
ChunkManager:Tick()
end)
if not success then
warn("[CHUNKMANAGER]", err)
end
end)
Swait(20)
end
end)
end
return ChunkManager

View File

@@ -0,0 +1,47 @@
local ML = {}
type modContext = {
name: string,
description: string,
ns: string,
author: {string},
init: typeof(function()end)
}
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Shared = ReplicatedStorage:WaitForChild("Shared")
local ModsFolder = ReplicatedStorage:WaitForChild("Mods")
function ML.loadModsS()
print("[SSModLoader] Loading Mods")
for _, m in pairs(ModsFolder:GetChildren()) do
local success, reason = pcall(function()
-- ignore type err
local mod: modContext = require(m)
mod.init()
print(`[SSModLoader] Loaded {mod.name} ({mod.ns}) by {table.concat(mod.author,", ")}`)
end)
if not success then
warn(`[CSModLoader] Error loading {m.Name}: {reason}`)
end
end
end
function ML.loadModsC()
print("[CSModLoader] Loading Mods")
for _, m in pairs(ModsFolder:GetChildren()) do
local success, reason = pcall(function()
-- ignore type err
local mod: modContext = require(m)
mod.init()
print(`[CSModLoader] Loaded {mod.name} ({mod.ns}) by {table.concat(mod.author,", ")}`)
end)
if not success then
warn(`[CSModLoader] Error loading {m.Name}: {reason}`)
end
end
end
return ML

View File

@@ -0,0 +1,221 @@
local PlacementManager = {}
local ChunkManager = require("./ChunkManager")
local Util = require("./Util")
PlacementManager.ChunkFolder = ChunkManager.ChunkFolder
local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {PlacementManager.ChunkFolder}
raycastParams.FilterType = Enum.RaycastFilterType.Include
raycastParams.IgnoreWater = true
if _G.SB then return nil end
_G.SB = true
PlacementManager.SelectionBox = script.SelectionBox:Clone()
PlacementManager.SelectionBox.Name = "$SelectionBox"..(game:GetService("RunService"):IsServer() and "_SERVER" or "")
PlacementManager.SelectionBox.Parent = game:GetService("Workspace"):FindFirstChildOfClass("Terrain")
-- Trash method TODO: Fix this
local function findParent(i: Instance): Instance
local f = i:FindFirstAncestorOfClass("Folder")
local d = i
repeat
d = d.Parent
until d.Parent == f
return d
end
local Mouse: Mouse = nil
local lastNormalId: Enum.NormalId? = nil
local function normalIdToOffset(normal: Enum.NormalId): Vector3
if normal == Enum.NormalId.Top then
return Vector3.new(0, 1, 0)
elseif normal == Enum.NormalId.Bottom then
return Vector3.new(0, -1, 0)
elseif normal == Enum.NormalId.Left then
return Vector3.new(-1, 0, 0)
elseif normal == Enum.NormalId.Right then
return Vector3.new(1, 0, 0)
elseif normal == Enum.NormalId.Back then
return Vector3.new(0, 0, 1)
elseif normal == Enum.NormalId.Front then
return Vector3.new(0, 0, -1)
end
return Vector3.new(0, 0, 0)
end
local function offsetChunkBlock(chunk: Vector3, block: Vector3, offset: Vector3)
local cx, cy, cz = chunk.X, chunk.Y, chunk.Z
local bx, by, bz = block.X + offset.X, block.Y + offset.Y, block.Z + offset.Z
if bx < 1 then
bx = 8
cx -= 1
elseif bx > 8 then
bx = 1
cx += 1
end
if by < 1 then
by = 8
cy -= 1
elseif by > 8 then
by = 1
cy += 1
end
if bz < 1 then
bz = 8
cz -= 1
elseif bz > 8 then
bz = 1
cz += 1
end
return Vector3.new(cx, cy, cz), Vector3.new(bx, by, bz)
end
-- Gets the block and normalid of the block (and surface) the player is looking at
function PlacementManager:Raycast()
if not Mouse then
Mouse = game:GetService("Players").LocalPlayer:GetMouse()
end
task.synchronize()
local objLookingAt = Mouse.Target
local dir = Mouse.TargetSurface
if not objLookingAt then
PlacementManager.SelectionBox.Adornee = nil
script.RaycastResult.Value = nil
lastNormalId = nil
return
end
--if not objLookingAt:IsDescendantOf(ChunkManager.ChunkFolder) then return end
local parent = findParent(objLookingAt)
if parent:GetAttribute("ns") == true then
PlacementManager.SelectionBox.Adornee = nil
script.RaycastResult.Value = nil
lastNormalId = nil
return
end
PlacementManager.SelectionBox.Adornee = parent
script.RaycastResult.Value = parent
lastNormalId = dir
return parent, dir
end
function PlacementManager:RaycastGetResult()
return script.RaycastResult.Value
end
local remotes = game:GetService("ReplicatedStorage"):WaitForChild("Remotes")
local placeRemote = remotes:WaitForChild("PlaceBlock")
local breakRemote = remotes:WaitForChild("BreakBlock")
local tickRemote = game:GetService("ReplicatedStorage").Tick
-- FIRES REMOTE
function PlacementManager:PlaceBlock(cx, cy, cz, x, y, z, blockId: string)
--print("placeblock")
--local chunk = ChunkManager:GetChunk(cx, cy, cz)
--chunk:CreateBlock(x, y, z, blockData)
placeRemote:FireServer(cx, cy, cz, x, y, z, blockId)
end
-- FIRES REMOTE
function PlacementManager:BreakBlock(cx, cy, cz, x, y, z)
--print("breakblock")
--local chunk = ChunkManager:GetChunk(cx, cy, cz)
--chunk:RemoveBlock(x, y, z)
breakRemote:FireServer(cx, cy, cz, x, y, z)
end
-- CLIENTSIDED
function PlacementManager:PlaceBlockLocal(cx, cy, cz, x, y, z, blockData)
local chunk = ChunkManager:GetChunk(cx, cy, cz)
chunk:CreateBlock(x, y, z, blockData)
end
-- CLIENTSIDED
function PlacementManager:BreakBlockLocal(cx, cy, cz, x, y, z)
local chunk = ChunkManager:GetChunk(cx, cy, cz)
chunk:RemoveBlock(x, y, z)
end
function PlacementManager:GetBlockAtMouse(): nil | {chunk:Vector3, block: Vector3}
local selectedPart = PlacementManager:RaycastGetResult()
--print(selectedPart and selectedPart:GetFullName() or nil)
if selectedPart == nil then
PlacementManager.SelectionBox.Adornee = nil
script.RaycastResult.Value = nil
lastNormalId = nil
return nil
end
if not selectedPart.Parent then
PlacementManager.SelectionBox.Adornee = nil
script.RaycastResult.Value = nil
lastNormalId = nil
return nil
end
local chunkCoords = Util.BlockPosStringToCoords(selectedPart.Parent.Name)
local blockCoords = Util.BlockPosStringToCoords(selectedPart.Name)
return {
chunk = chunkCoords,
block = blockCoords
}
end
function PlacementManager:GetTargetAtMouse(): nil | {chunk:Vector3, block: Vector3, normal: Enum.NormalId}
local hit = PlacementManager:GetBlockAtMouse()
if not hit or not lastNormalId then
return nil
end
return {
chunk = hit.chunk,
block = hit.block,
normal = lastNormalId
}
end
function PlacementManager:GetPlacementAtMouse(): nil | {chunk:Vector3, block: Vector3}
local hit = PlacementManager:GetTargetAtMouse()
if not hit then
return nil
end
local offset = normalIdToOffset(hit.normal)
local placeChunk, placeBlock = offsetChunkBlock(hit.chunk, hit.block, offset)
return {
chunk = placeChunk,
block = placeBlock
}
end
function PlacementManager:Init()
game:GetService("RunService").Heartbeat:Connect(function()
local a,b = pcall(function()
PlacementManager:Raycast()
end)
if not a then
task.synchronize()
PlacementManager.SelectionBox.Adornee = nil
script.RaycastResult.Value = nil
task.desynchronize()
end
end)
tickRemote.OnClientEvent:Connect(function(m, cx, cy, cz, x, y, z, d)
--warn("PROPOGATED TICK", m, cx, cy, cz, x, y, z, d)
if m == "B_C" then
PlacementManager:PlaceBlockLocal(cx, cy, cz, x, y ,z, d)
end
if m == "B_D" then
PlacementManager:BreakBlockLocal(cx, cy, cz, x, y ,z)
end
end)
end
return PlacementManager

View File

@@ -0,0 +1,3 @@
{
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,48 @@
local module = {}
function module.BlockPosStringToCoords(s: string): Vector3
-- a,b,c
local split = string.split(s,",")
return Vector3.new(tonumber(split[1]), tonumber(split[2]), tonumber(split[3]))
end
function module.RotationStringToNormalId(s: string): Enum.NormalId
if not s then return Enum.NormalId.Front end
if s == "f" then
return Enum.NormalId.Front
end
if s == "b" then
return Enum.NormalId.Back
end
if s == "l" then
return Enum.NormalId.Left
end
if s == "r" then
return Enum.NormalId.Right
end
if s == "t" then
return Enum.NormalId.Top
end
if s == "b" then
return Enum.NormalId.Bottom
end
warn("Could not convert",s,"to Enum.NormalId")
return Enum.NormalId.Front
end
-- chunk size 8x8x8 relative block indexs 1-8
function module.GlobalBlockPosToRelative(x: number,y:number,z:number)
return x%8,y%8,z%8
end
function module.ChunkPosToCFrame(chunk: Vector3, block: Vector3): CFrame
return CFrame.new(
CFrame.new(
(32*chunk.X)+(block.X*4)-18,
(32*chunk.Y)+(block.Y*4)-18,
(32*chunk.Z)+(block.Z*4)-18
).Position
)
end
return module

View File

@@ -0,0 +1,3 @@
{
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,38 @@
local Node = {}
Node.__index = Node
function Node.new(data)
local node = setmetatable({}, Node)
node.data = data
node.left = nil
node.right = nil
return node
end
-- return an iterator that traverses the tree in order
function Node:inorder()
local stack = {}
local current = {self, ""}
table.insert(stack, current)
return function()
while current[1].left do
local parent = current
current = {parent[1].left, parent[2] .. "0"}
table.insert(stack, current)
end
if #stack > 0 then
local node = table.remove(stack)
if node[1].right then
local parent = node
current = {parent[1].right, parent[2] .. "1"}
table.insert(stack, current)
end
return node[1], node[2]
end
end
end
return Node

View File

@@ -0,0 +1,232 @@
--[[
PriorityQueue - v1.0.1 - public domain Lua priority queue
implemented with indirect binary heap
no warranty implied; use at your own risk
based on binaryheap library (github.com/iskolbin/binaryheap)
author: Ilya Kolbin (iskolbin@gmail.com)
url: github.com/iskolbin/priorityqueue
See documentation in README file.
COMPATIBILITY
Lua 5.1, 5.2, 5.3, LuaJIT 1, 2
LICENSE
This software is dual-licensed to the public domain and under the following
license: you are granted a perpetual, irrevocable license to copy, modify,
publish, and distribute this file as you see fit.
--]]
local floor, setmetatable = math.floor, setmetatable
local function siftup( self, from )
local items, priorities, indices, higherpriority = self, self._priorities, self._indices, self._higherpriority
local index = from
local parent = floor( index / 2 )
while index > 1 and higherpriority( priorities[index], priorities[parent] ) do
priorities[index], priorities[parent] = priorities[parent], priorities[index]
items[index], items[parent] = items[parent], items[index]
indices[items[index]], indices[items[parent]] = index, parent
index = parent
parent = floor( index / 2 )
end
return index
end
local function siftdown( self, limit )
local items, priorities, indices, higherpriority, size = self, self._priorities, self._indices, self._higherpriority, self._size
for index = limit, 1, -1 do
local left = index + index
local right = left + 1
while left <= size do
local smaller = left
if right <= size and higherpriority( priorities[right], priorities[left] ) then
smaller = right
end
if higherpriority( priorities[smaller], priorities[index] ) then
items[index], items[smaller] = items[smaller], items[index]
priorities[index], priorities[smaller] = priorities[smaller], priorities[index]
indices[items[index]], indices[items[smaller]] = index, smaller
else
break
end
index = smaller
left = index + index
right = left + 1
end
end
end
local PriorityQueueMt
local PriorityQueue = {}
local function minishigher( a, b )
return a < b
end
local function maxishigher( a, b )
return a > b
end
function PriorityQueue.new( priority_or_array )
local t = type( priority_or_array )
local higherpriority = minishigher
if t == 'table' then
higherpriority = priority_or_array.higherpriority or higherpriority
elseif t == 'function' or t == 'string' then
higherpriority = priority_or_array
elseif t ~= 'nil' then
local msg = 'Wrong argument type to PriorityQueue.new, it must be table or function or string, has: %q'
error( msg:format( t ))
end
if type( higherpriority ) == 'string' then
if higherpriority == 'min' then
higherpriority = minishigher
elseif higherpriority == 'max' then
higherpriority = maxishigher
else
local msg = 'Wrong string argument to PriorityQueue.new, it must be "min" or "max", has: %q'
error( msg:format( tostring( higherpriority )))
end
end
local self = setmetatable( {
_priorities = {},
_indices = {},
_size = 0,
_higherpriority = higherpriority or minishigher
}, PriorityQueueMt )
if t == 'table' then
self:batchenq( priority_or_array )
end
return self
end
function PriorityQueue:enqueue( item, priority )
local items, priorities, indices = self, self._priorities, self._indices
if indices[item] ~= nil then
error( 'Item ' .. tostring(indices[item]) .. ' is already in the heap' )
end
local size = self._size + 1
self._size = size
items[size], priorities[size], indices[item] = item, priority, size
siftup( self, size )
return self
end
function PriorityQueue:remove( item )
local index = self._indices[item]
if index ~= nil then
local size = self._size
local items, priorities, indices = self, self._priorities, self._indices
indices[item] = nil
if size == index then
items[size], priorities[size] = nil, nil
self._size = size - 1
else
local lastitem = items[size]
items[index], priorities[index] = items[size], priorities[size]
items[size], priorities[size] = nil, nil
indices[lastitem] = index
size = size - 1
self._size = size
if size > 1 then
siftdown( self, siftup( self, index ))
end
end
return true
else
return false
end
end
function PriorityQueue:contains( item )
return self._indices[item] ~= nil
end
function PriorityQueue:update( item, priority )
local ok = self:remove( item )
if ok then
self:enqueue( item, priority )
return true
else
return false
end
end
function PriorityQueue:dequeue()
local size = self._size
assert( size > 0, 'Heap is empty' )
local items, priorities, indices = self, self._priorities, self._indices
local item, priority = items[1], priorities[1]
indices[item] = nil
if size > 1 then
local newitem = items[size]
items[1], priorities[1] = newitem, priorities[size]
items[size], priorities[size] = nil, nil
indices[newitem] = 1
size = size - 1
self._size = size
siftdown( self, 1 )
else
items[1], priorities[1] = nil, nil
self._size = 0
end
return item, priority
end
function PriorityQueue:peek()
return self[1], self._priorities[1]
end
function PriorityQueue:len()
return self._size
end
function PriorityQueue:empty()
return self._size <= 0
end
function PriorityQueue:batchenq( iparray )
local items, priorities, indices = self, self._priorities, self._indices
local size = self._size
for i = 1, #iparray, 2 do
local item, priority = iparray[i], iparray[i+1]
if indices[item] ~= nil then
error( 'Item ' .. tostring(indices[item]) .. ' is already in the heap' )
end
size = size + 1
items[size], priorities[size] = item, priority
indices[item] = size
end
self._size = size
if size > 1 then
siftdown( self, floor( size / 2 ))
end
end
PriorityQueueMt = {
__index = PriorityQueue,
__len = PriorityQueue.len,
}
return setmetatable( PriorityQueue, {
__call = function( _, ... )
return PriorityQueue.new( ... )
end
} )

View File

@@ -0,0 +1,114 @@
--Huffman.lua
--iiau, Sat May 18 2024
--Implementation of huffman coding algorithm for use in Roblox
local Huffman = {}
local PriorityQueue = require(script.PriorityQueue)
local Node = require(script.Node)
local BitBuffer = require(script.BitBuffer)
local CHUNK_SIZE = 256
--thanks to https://stackoverflow.com/a/32220398 for helping me with this
local function to_bin(n)
local t = {}
for _ = 1, 32 do
n = bit32.rrotate(n, -1)
table.insert(t, bit32.band(n, 1))
end
return table.concat(t)
end
-- Encode a string to huffman coded string. Limitation is that the data should not be more than 16777215 bytes.
-- @param data The string to encode
-- @return The encoded string
Huffman.encode = function(data: string) : string
assert(#data > 0, "Data must not be empty")
local buffer = BitBuffer()
-- get the frequency of each character in the string
local freq, dict, size = {}, {}, 0
for c in data:gmatch(".") do
freq[c] = (freq[c] or 0) + 1
end
for _ in pairs(freq) do
size += 1
end
local q = PriorityQueue.new 'min'
for k: string, v: number in pairs(freq) do
local leaf = Node.new(string.byte(k))
q:enqueue(leaf, v)
end
while q:len() > 1 do
local left, freq_l = q:dequeue()
local right, freq_r = q:dequeue()
local parent = Node.new()
parent.left = left
parent.right = right
q:enqueue(parent, freq_l + freq_r)
end
local tree = q:dequeue()
buffer.writeUInt8(size-1)
buffer.writeUnsigned(24, #data)
for node, bits: string in tree:inorder() do
if not node.data then
continue
end
local number = tonumber(bits, 2)
local bit_array = string.split(bits, "")
for i = 1, #bit_array do
bit_array[i] = tonumber(bit_array[i])
end
dict[string.char(node.data)] = bit_array
buffer.writeUInt8(node.data) -- char
buffer.writeUnsigned(5, #bits) -- number of bits
buffer.writeUnsigned(#bits, number) -- bits
end
for c in data:gmatch(".") do
buffer.writeBits(table.unpack(dict[c]))
end
-- to avoid the dreaded too many results to unpack error
local chunks = {}
for _, chunk in buffer.exportChunk(CHUNK_SIZE) do
table.insert(chunks, chunk)
end
return table.concat(chunks)
end
-- Decode a string from huffman coded string
-- @param data The string to decode
-- @return The decoded string
Huffman.decode = function(data: string) : string
assert(#data > 0, "Data must not be empty")
local buffer = BitBuffer(data)
local dict_size = buffer.readUInt8()+1
local len_data = buffer.readUnsigned(24)
local dict, read = {}, 0
for i = 1, dict_size do
local char = buffer.readUInt8()
local digits = buffer.readUnsigned(5)
local bits = buffer.readUnsigned(digits)
dict[to_bin(bits):sub(-digits)] = char
end
local decoded = {}
local bits = ""
while read < len_data do
bits ..= buffer.readBits(1)[1]
local char = dict[bits]
if char then
table.insert(decoded, string.char(char))
bits = ""
read += 1
end
end
return table.concat(decoded)
end
return Huffman

View File

@@ -0,0 +1,170 @@
-- Module by 1waffle1 and boatbomber, optimized and fixed by iiau
-- https://devforum.roblox.com/t/text-compression/163637/37
local dictionary = {} -- key to len
do -- populate dictionary
local length = 0
for i = 32, 127 do
if i ~= 34 and i ~= 92 then
local c = string.char(i)
dictionary[c] = length
dictionary[length] = c
length = length + 1
end
end
end
local escapemap_126, escapemap_127 = {}, {}
local unescapemap_126, unescapemap_127 = {}, {}
local blacklisted_126 = { 34, 92 }
for i = 126, 180 do
table.insert(blacklisted_126, i)
end
do -- Populate escape map
-- represents the numbers 0-31, 34, 92, 126, 127 (36 characters)
-- and 128-180 (52 characters)
-- https://devforum.roblox.com/t/text-compression/163637/5
for i = 0, 31 + #blacklisted_126 do
local b = blacklisted_126[i - 31]
local s = i + 32
-- Note: 126 and 127 are magic numbers
local c = string.char(b or i)
local e = string.char(s + (s >= 34 and 1 or 0) + (s >= 91 and 1 or 0))
escapemap_126[c] = e
unescapemap_126[e] = c
end
for i = 1, 255 - 180 do
local c = string.char(i + 180)
local s = i + 34
local e = string.char(s + (s >= 92 and 1 or 0))
escapemap_127[c] = e
unescapemap_127[e] = c
end
end
local function escape(s)
-- escape the control characters 0-31, double quote 34, backslash 92, Tilde 126, and DEL 127 (36 chars)
-- escape characters 128-180 (53 chars)
return string.gsub(string.gsub(s, '[%c"\\\126-\180]', function(c)
return "\126" .. escapemap_126[c]
end), '[\181-\255]', function(c)
return "\127" .. escapemap_127[c]
end)
end
local function unescape(s)
return string.gsub(string.gsub(s, "\127(.)", function(e)
return unescapemap_127[e]
end), "\126(.)", function(e)
return unescapemap_126[e]
end)
end
local b93Cache = {}
local function tobase93(n)
local value = b93Cache[n]
if value then
return value
end
local c = n
value = ""
repeat
local remainder = n % 93
value = dictionary[remainder] .. value
n = (n - remainder) / 93
until n == 0
b93Cache[c] = value
return value
end
local b10Cache = {}
local function tobase10(value)
local n = b10Cache[value]
if n then
return n
end
n = 0
for i = 1, #value do
n = n + math.pow(93, i - 1) * dictionary[string.sub(value, -i, -i)]
end
b10Cache[value] = n
return n
end
local function compress(text)
assert(type(text) == "string", "bad argument #1 to 'compress' (string expected, got " .. typeof(text) .. ")")
local dictionaryCopy = table.clone(dictionary)
local key, sequence, size = "", {}, #dictionary
local width, spans, span = 1, {}, 0
local function listkey(k)
local value = tobase93(dictionaryCopy[k])
local valueLength = #value
if valueLength > width then
width, span, spans[width] = valueLength, 0, span
end
table.insert(sequence, string.rep(" ", width - valueLength) .. value)
span += 1
end
text = escape(text)
for i = 1, #text do
local c = string.sub(text, i, i)
local new = key .. c
if dictionaryCopy[new] then
key = new
else
listkey(key)
key = c
size += 1
dictionaryCopy[new] = size
dictionaryCopy[size] = new
end
end
listkey(key)
spans[width] = span
return table.concat(spans, ",") .. "|" .. table.concat(sequence)
end
local function decompress(text)
assert(type(text) == "string", "bad argument #1 to 'decompress' (string expected, got " .. typeof(text) .. ")")
local dictionaryCopy = table.clone(dictionary)
local sequence, spans, content = {}, string.match(text, "(.-)|(.*)")
local groups, start = {}, 1
for span in string.gmatch(spans, "%d+") do
local width = #groups + 1
groups[width] = string.sub(content, start, start + span * width - 1)
start = start + span * width
end
local previous
for width, group in ipairs(groups) do
for value in string.gmatch(group, string.rep(".", width)) do
local entry = dictionaryCopy[tobase10(value)]
if previous then
if entry then
table.insert(dictionaryCopy, previous .. string.sub(entry, 1, 1))
else
entry = previous .. string.sub(previous, 1, 1)
table.insert(dictionaryCopy, entry)
end
table.insert(sequence, entry)
else
sequence[1] = entry
end
previous = entry
end
end
return unescape(table.concat(sequence))
end
return { compress = compress, decompress = decompress }

View File

@@ -0,0 +1,19 @@
--Deflate.lua
--iiau, Sat May 18 2024
local Deflate = {}
local LZW = require(script.LZW)
local Huffman = require(script.Huffman)
Deflate.encode = function(data: string) : string
data = LZW.compress(data)
return Huffman.encode(data)
end
Deflate.decode = function(data: string) : string
data = Huffman.decode(data)
return LZW.decompress(data)
end
return Deflate

View File

@@ -0,0 +1,70 @@
local TerrainGen = {}
local deflate = require("./TerrainGen/Deflate")
local DSS = game:GetService("DataStoreService")
local WORLDNAME = "DEFAULT"
local WORLDID = "b73bb5a6-297d-4352-b637-daec7e8c8f3e"
local Store = DSS:GetDataStore("BlockscraftWorldV1", WORLDID)
local ChunkManager = require(game:GetService("ReplicatedStorage"):WaitForChild("Shared").ChunkManager)
local Chunk = require(game:GetService("ReplicatedStorage"):WaitForChild("Shared").ChunkManager.Chunk)
TerrainGen.ServerChunkCache = {} :: {[typeof("")]: typeof(Chunk.new(0,0,0))}
-- Load a chunk from the DataStore or generate it if not found
function TerrainGen:GetChunk(x, y, z)
local key = `{x},{y},{z}`
if TerrainGen.ServerChunkCache[key] then
return TerrainGen.ServerChunkCache[key]
end
-- Generate a new chunk if it doesn't exist
local chunk = Chunk.new(x, y, z)
if y == 1 then
for cx = 1, 8 do
for cz = 1, 8 do
--local perlin = math.noise(((x*8)+cx)/100,((z*8)+cz)/100)
chunk:CreateBlock(cx, 1, cz, { id = 1, state = {} })
--chunk:CreateBlock(x, 2, z, { id = 1, state = {} })
end
end
end
if y == 0 then
for cx = 1, 8 do
for cy = 1, 8 do
for cz = 1, 8 do
--local perlin = math.noise(((x*8)+cx)/100,((z*8)+cz)/100)
chunk:CreateBlock(cx, cy, cz, { id = 2, state = {} })
--chunk:CreateBlock(x, 2, z, { id = 1, state = {} })
end
end
end
end
TerrainGen.ServerChunkCache[key] = chunk
return chunk
end
-- Fake Chunk
function TerrainGen:GetFakeChunk(x, y, z)
-- Generate a new chunk if it doesn't exist
local chunk = Chunk.new(x, y, z)
for cy = 1,8 do
for cx = 1, 8 do
for cz = 1, 8 do
--local perlin = math.noise(((x*8)+cx)/100,((z*8)+cz)/100)
chunk:CreateBlock(cx, cy, cz, { id = -2, state = {} })
--chunk:CreateBlock(x, 2, z, { id = 1, state = {} })
end
end
end
return chunk
end
TerrainGen.CM = ChunkManager
return TerrainGen

View File

@@ -0,0 +1,189 @@
print("Hello world!")
task.synchronize()
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Shared = ReplicatedStorage:WaitForChild("Shared")
local ModsFolder = ReplicatedStorage:WaitForChild("Mods")
local Util = require(Shared.Util)
local TG = require("./ServerChunkManager/TerrainGen")
do
local workspaceModFolder = game:GetService("Workspace"):WaitForChild("mods")
for _,v in pairs(workspaceModFolder:GetChildren()) do
v.Parent = ModsFolder
end
workspaceModFolder:Destroy()
end
local ML = require(Shared.ModLoader)
ML.loadModsS()
do
local bv = Instance.new("BoolValue")
bv.Name = "MLLoaded"
bv.Value = true
bv.Parent = ReplicatedStorage:WaitForChild("Objects")
end
local MAX_CHUNK_DIST = 200
local FakeChunk = TG:GetFakeChunk(-5,-5,-5)
task.synchronize()
ReplicatedStorage.Tick.OnServerEvent:Connect(function(player: Player, v: string)
if TG.ServerChunkCache[v] then
pcall(function()
TG.ServerChunkCache[v].inhabitedTime = tick()
end)
end
end)
ReplicatedStorage.RecieveChunkPacket.OnServerInvoke = function(plr: Player, x: number, y: number, z: number)
-- validate xyz type and limit
if typeof(x) ~= "number" or typeof(y) ~= "number" or typeof(z) ~= "number" then
return {}
end
if math.abs(x) > MAX_CHUNK_DIST or math.abs(y) > MAX_CHUNK_DIST or math.abs(z) > MAX_CHUNK_DIST then
return FakeChunk.data
end
task.desynchronize()
local chunk = TG:GetChunk(x, y, z)
local chunkdata = chunk.data
task.synchronize()
return chunkdata
end
local tickRemote = ReplicatedStorage.Tick
local remotes = ReplicatedStorage:WaitForChild("Remotes")
local placeRemote = remotes:WaitForChild("PlaceBlock")
local breakRemote = remotes:WaitForChild("BreakBlock")
local blocksFolder = ReplicatedStorage:WaitForChild("Blocks")
local function propogate(a, cx, cy, cz, x, y, z, bd)
task.synchronize()
tickRemote:FireAllClients(a, cx, cy, cz, x, y, z, bd)
task.desynchronize()
end
local MAX_REACH = 24
local blockIdMap = {}
local function rebuildBlockIdMap()
table.clear(blockIdMap)
for _, block in ipairs(blocksFolder:GetChildren()) do
local id = block:GetAttribute("n")
if id ~= nil then
blockIdMap[id] = id
blockIdMap[tostring(id)] = id
end
end
end
rebuildBlockIdMap()
blocksFolder.ChildAdded:Connect(rebuildBlockIdMap)
blocksFolder.ChildRemoved:Connect(rebuildBlockIdMap)
local function getPlayerPosition(player: Player): Vector3?
local character = player.Character
if not character then
return nil
end
local root = character:FindFirstChild("HumanoidRootPart")
if not root then
return nil
end
return root.Position
end
local function isWithinReach(player: Player, cx: number, cy: number, cz: number, x: number, y: number, z: number): boolean
local playerPos = getPlayerPosition(player)
if not playerPos then
return false
end
local blockPos = Util.ChunkPosToCFrame(Vector3.new(cx, cy, cz), Vector3.new(x, y, z)).Position
return (blockPos - playerPos).Magnitude <= MAX_REACH
end
local function resolveBlockId(blockId: any): string | number | nil
return blockIdMap[blockId]
end
local function getServerChunk(cx: number, cy: number, cz: number)
task.desynchronize()
local chunk = TG:GetChunk(cx, cy, cz)
task.synchronize()
return chunk
end
placeRemote.OnServerEvent:Connect(function(player, cx, cy, cz, x, y, z, blockId)
--print("place",player, cx, cy, cz, x, y, z, blockData)
if typeof(cx) ~= "number" or typeof(cy) ~= "number" or typeof(cz) ~= "number" then
return
end
if typeof(x) ~= "number" or typeof(y) ~= "number" or typeof(z) ~= "number" then
return
end
if x < 1 or x > 8 or y < 1 or y > 8 or z < 1 or z > 8 then
return
end
if math.abs(cx) > MAX_CHUNK_DIST or math.abs(cy) > MAX_CHUNK_DIST or math.abs(cz) > MAX_CHUNK_DIST then
--return
end
if not isWithinReach(player, cx, cy, cz, x, y, z) then
return
end
local resolvedId = resolveBlockId(blockId)
if not resolvedId then
return
end
local chunk = getServerChunk(cx, cy, cz)
if chunk:GetBlockAt(x, y, z) then
return
end
local data = {
id = resolvedId,
state = {}
}
chunk:CreateBlock(x, y, z, data)
propogate("B_C", cx, cy, cz, x, y, z, data)
end)
breakRemote.OnServerEvent:Connect(function(player, cx, cy, cz, x, y, z)
--print("del",player, cx, cy, cz, x, y, z)
if typeof(cx) ~= "number" or typeof(cy) ~= "number" or typeof(cz) ~= "number" then
return
end
if typeof(x) ~= "number" or typeof(y) ~= "number" or typeof(z) ~= "number" then
return
end
if x < 1 or x > 8 or y < 1 or y > 8 or z < 1 or z > 8 then
return
end
if math.abs(cx) > MAX_CHUNK_DIST or math.abs(cy) > MAX_CHUNK_DIST or math.abs(cz) > MAX_CHUNK_DIST then
return
end
if not isWithinReach(player, cx, cy, cz, x, y, z) then
return
end
local chunk = getServerChunk(cx, cy, cz)
if not chunk:GetBlockAt(x, y, z) then
return
end
chunk:RemoveBlock(x, y, z)
propogate("B_D", cx, cy, cz, x, y, z, 0)
end)
task.desynchronize()

View File

@@ -0,0 +1,4 @@
{
"className": "Actor",
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,22 @@
-- force first person mode on the person's camera
if not game:IsLoaded() then
game.Loaded:Wait()
end
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UIS = game:GetService("UserInputService")
ReplicatedStorage:WaitForChild("Objects"):WaitForChild("MLLoaded")
game:GetService("Players").LocalPlayer.CameraMode = Enum.CameraMode.LockFirstPerson
UIS.MouseIconEnabled = false
UIS.InputEnded:Connect(function(k)
if k.KeyCode == Enum.KeyCode.M then
local v = not script.Parent.DummyButton.Modal
UIS.MouseIconEnabled = v
script.Parent.CrosshairLabel.Visible = not v
script.Parent.DummyButton.Modal = v
end
end)

View File

@@ -0,0 +1,4 @@
{
"className": "ScreenGui",
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,62 @@
if not game:IsLoaded() then
game.Loaded:Wait()
end
local ui = script.Parent
local ReplicatedStorage = game:GetService("ReplicatedStorage")
ReplicatedStorage:WaitForChild("Objects"):WaitForChild("MLLoaded")
local cd = ReplicatedStorage.Objects.ChunkDebug:Clone()
local sky = ReplicatedStorage.Objects.Sky:Clone()
local base = ReplicatedStorage.Objects.FakeBaseplate:Clone()
cd.Parent = game:GetService("Workspace"):FindFirstChildOfClass("Terrain")
sky.Parent = game:GetService("Workspace"):FindFirstChildOfClass("Terrain")
base.Parent = game:GetService("Workspace"):FindFirstChildOfClass("Terrain")
game:GetService("RunService").RenderStepped:Connect(function(dt)
local fps = math.round(1/dt)
pcall(function()
-- pos in chunks of 32 studs of char
local pos = game:GetService("Players").LocalPlayer.Character:GetPivot()
local chunk = {
x = math.round(pos.X/32),
y = math.round(pos.Y/32),
z = math.round(pos.Z/32)
}
if math.abs(chunk.x) == 0 then chunk.x = 0 end
if math.abs(chunk.y) == 0 then chunk.y = 0 end
if math.abs(chunk.z) == 0 then chunk.z = 0 end
local bpos = {
x = math.round(pos.X/4),
y = math.round(pos.Y/4),
z = math.round(pos.Z/4)
}
if math.abs(bpos.x) == 0 then bpos.x = 0 end
if math.abs(bpos.y) == 0 then bpos.y = 0 end
if math.abs(bpos.z) == 0 then bpos.z = 0 end
sky.CFrame = pos
ui.DebugUpperText.Text = `Chunk {chunk.x} {chunk.y} {chunk.z}\nPos {bpos.x} {bpos.y} {bpos.z}\n<b>{fps} FPS</b>`
cd:PivotTo(CFrame.new(
chunk.x*32,
chunk.y*32,
chunk.z*32
))
base.CFrame = CFrame.new(
chunk.x*32,
-24,
chunk.z*32
)
end)
end)

View File

@@ -0,0 +1,4 @@
{
"className": "ScreenGui",
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,26 @@
if not game:IsLoaded() then
game.Loaded:Wait()
end
pcall(function()
task.synchronize()
game:GetService("Workspace"):WaitForChild("$blockscraft_server",5):Destroy()
end)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
ReplicatedStorage:WaitForChild("Objects"):WaitForChild("MLLoaded")
local ML = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("ModLoader"))
ML.loadModsC()
do
local PM = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("PlacementManager"))
PM:Init()
end
do
local CM = require(ReplicatedStorage:WaitForChild("Shared"):WaitForChild("ChunkManager"))
CM:Init()
end

View File

@@ -0,0 +1,92 @@
if not game:IsLoaded() then
game.Loaded:Wait()
end
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UIS = game:GetService("UserInputService")
ReplicatedStorage:WaitForChild("Objects"):WaitForChild("MLLoaded")
local blocksFolder = ReplicatedStorage:WaitForChild("Blocks")
local PM = require(ReplicatedStorage.Shared.PlacementManager)
local HOTBAR_SIZE = 9
local hotbar = table.create(HOTBAR_SIZE)
local selectedSlot = 1
local keyToSlot = {
[Enum.KeyCode.One] = 1,
[Enum.KeyCode.Two] = 2,
[Enum.KeyCode.Three] = 3,
[Enum.KeyCode.Four] = 4,
[Enum.KeyCode.Five] = 5,
[Enum.KeyCode.Six] = 6,
[Enum.KeyCode.Seven] = 7,
[Enum.KeyCode.Eight] = 8,
[Enum.KeyCode.Nine] = 9,
}
local function rebuildHotbar()
local ids = {}
for _, block in ipairs(blocksFolder:GetChildren()) do
local id = block:GetAttribute("n")
if id ~= nil then
table.insert(ids, tostring(id))
end
end
table.sort(ids)
for i = 1, HOTBAR_SIZE do
hotbar[i] = ids[i] or ""
end
selectedSlot = math.clamp(selectedSlot, 1, HOTBAR_SIZE)
end
local function getSelectedBlockId(): string?
local id = hotbar[selectedSlot]
if id == "" then
return nil
end
return id
end
local function setSelectedSlot(slot: number)
if slot < 1 or slot > HOTBAR_SIZE then
return
end
selectedSlot = slot
end
rebuildHotbar()
blocksFolder.ChildAdded:Connect(rebuildHotbar)
blocksFolder.ChildRemoved:Connect(rebuildHotbar)
UIS.InputBegan:Connect(function(input: InputObject, gameProcessedEvent: boolean)
if gameProcessedEvent then
return
end
local slot = keyToSlot[input.KeyCode]
if slot then
setSelectedSlot(slot)
return
end
if input.UserInputType == Enum.UserInputType.MouseButton1 then
local mouseBlock = PM:GetBlockAtMouse()
if not mouseBlock then
return
end
PM:BreakBlock(mouseBlock.chunk.X, mouseBlock.chunk.Y, mouseBlock.chunk.Z, mouseBlock.block.X, mouseBlock.block.Y, mouseBlock.block.Z)
elseif input.UserInputType == Enum.UserInputType.MouseButton2 then
local mouseBlock = PM:GetPlacementAtMouse()
if not mouseBlock then
return
end
local blockId = getSelectedBlockId()
if not blockId then
return
end
PM:PlaceBlock(mouseBlock.chunk.X, mouseBlock.chunk.Y, mouseBlock.chunk.Z, mouseBlock.block.X, mouseBlock.block.Y, mouseBlock.block.Z, blockId)
end
end)

View File

@@ -0,0 +1,4 @@
{
"className": "Actor",
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,3 @@
{
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,23 @@
local mod = {
name = "Blockscraft",
description = "Base Blockscraft blocks",
ns = "mc",
author = { "ocbwoy3" }
}
local rep = game:GetService("ReplicatedStorage"):WaitForChild("Blocks")
local upd = game:GetService("ReplicatedStorage"):WaitForChild("BlockUpdateOperations")
function mod.init()
for a,b in pairs(script.blocks:GetChildren()) do
local upop = b:FindFirstChild("BlockUpdateOperation")
if upop then
upop.Name = b:GetAttribute("n")
upop:SetAttribute("n",b:GetAttribute("n"))
upop.Parent = upd
end
b:Clone().Parent = rep
end
end
return mod

View File

@@ -0,0 +1,3 @@
{
"ignoreUnknownInstances": true
}

View File

@@ -0,0 +1,3 @@
return function(p: typeof(script.Parent.Parent.blocks["mc:grass_block"]))
p.block.Grass.Color = Color3.new(p:GetAttribute("x"),p:GetAttribute("x"),p:GetAttribute("x"))
end

View File

@@ -0,0 +1,3 @@
{
"ignoreUnknownInstances": true
}