chore: refractor

This commit is contained in:
2026-01-08 22:58:58 +02:00
parent da7de7b08a
commit 2c41f40151
49 changed files with 6 additions and 6 deletions

View File

@@ -0,0 +1,84 @@
--!native
--!optimize 2
local BlockManager = {}
BlockManager.BlockIdMappings = {} :: {BasePart}
for _,v in pairs(game:GetService("ReplicatedStorage"):WaitForChild("Blocks"):GetChildren()) do
BlockManager.BlockIdMappings[v:GetAttribute("n")] = v
end
BlockManager.UpdateIdMappings = {} :: {BasePart}
for _,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}?)
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 _,v in pairs(attr or {}) do
b:SetAttribute(_,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()
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,217 @@
--!native
--!optimize 2
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 normalizeCoord(n)
if typeof(n) ~= "number" then
return n
end
if n >= 0 then
return math.floor(n + 0.5)
end
return math.ceil(n - 0.5)
end
local function keyFromCoords(x, y, z)
x = normalizeCoord(x)
y = normalizeCoord(y)
z = normalizeCoord(z)
return `{tostring(x)},{tostring(y)},{tostring(z)}`
end
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.delayedRemoval = {}
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)
self.delayedRemoval = {}
return self
end
function Chunk:DoesNeighboringBlockExist(rx, ry, rz, gx, gy, gz, offsetX, offsetY, offsetZ)
-- 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)
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)
if not self.data[keyFromCoords(x, y, z)] then
return nil
end
return self.data[keyFromCoords(x, y, z)]
end
function Chunk:CreateBlock(x: number,y: number,z: number,d:BlockData)
self.data[keyFromCoords(x, y, z)] = d
self:PropogateChanges(x,y,z,d)
return self:GetBlockAt(x,y,z)
end
function Chunk:RemoveBlock(x, y, z)
local blockKey = keyFromCoords(x, y, z)
self.data[blockKey] = nil
self:PropogateChanges(x,y,z,0)
end
function Chunk:RemoveBlockSmooth(x, y, z)
local blockKey = keyFromCoords(x, y, z)
self.data[blockKey] = nil
self.delayedRemoval[blockKey] = true
self:PropogateChanges(x,y,z,0)
end
-- unsure why this exists
function Chunk:Load()
end
function Chunk:Unload()
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
self.instance.Parent = nil
self.instance:Destroy()
self.unloadChunkHook()
end)
end
function Chunk:UnloadImmediate()
self.loaded = false
pcall(function()
self.unloadChunkHook()
end)
pcall(function()
if self.instance then
self.instance.Parent = nil
self.instance:Destroy()
end
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,246 @@
--!native
--!optimize 2
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 DEBUG_GHOST = true
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)
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
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
else
local existing = c.instance:FindFirstChild(`{x},{y},{z}`)
if existing then
existing:Destroy()
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)
if finished == false then
newcache[`{x},{y},{z}`] = d
return
end
for _, o in pairs(NEIGHBOR_OFFSETS) do
local b = {x = x + o[1], y = y + o[2], z = z + o[3]}
local chPos = {x = c.pos.X, y = c.pos.Y, z = c.pos.Z}
if b.x < 1 then chPos.x = c.pos.X - 1 b.x = 8 end
if b.x > 8 then chPos.x = c.pos.X + 1 b.x = 1 end
if b.y < 1 then chPos.y = c.pos.Y - 1 b.y = 8 end
if b.y > 8 then chPos.y = c.pos.Y + 1 b.y = 1 end
if b.z < 1 then chPos.z = c.pos.Z - 1 b.z = 8 end
if b.z > 8 then chPos.z = c.pos.Z + 1 b.z = 1 end
propogateNeighboringBlockChanges(chPos.x, chPos.y, chPos.z, b.x, b.y, b.z)
end
local blockName = `{x},{y},{z}`
local existing = ch:FindFirstChild(blockName)
if d == 0 then
if c.delayedRemoval and c.delayedRemoval[blockName] then
c.delayedRemoval[blockName] = nil
if existing then
task.defer(function()
RunService.RenderStepped:Wait()
if existing.Parent then
existing:Destroy()
end
end)
elseif DEBUG_GHOST then
print("[CHUNKBUILDER][GHOST] Delayed remove missing instance", c.pos, blockName)
end
return
end
if existing then
existing:Destroy()
elseif DEBUG_GHOST then
print("[CHUNKBUILDER][GHOST] Remove missing instance", c.pos, blockName)
end
return
end
if not c:IsBlockRenderable(x, y, z) then
if existing then
existing:Destroy()
end
return
end
if existing then
existing:Destroy()
end
if not d then return end
if d.id == 0 then return end
local N = util.RotationStringToNormalId(d.state["r"] or "f")
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
end)
c.unloadChunkHook = function()
conn:Disconnect()
blocks = nil
c = nil
end
task.defer(function()
local p = 0
local hb = false
for _,b in pairs(blocks) do
hb = true
break
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
local coords = util.BlockPosStringToCoords(a)
if not c or not c.IsBlockRenderable or not c:IsBlockRenderable(coords.X, coords.Y, coords.Z) then
if ch:FindFirstChild(a) then
ch:FindFirstChild(a):Destroy()
end
continue
end
local N = util.RotationStringToNormalId(b.state["r"] or "f")
local block = BlockManager:GetBlockRotated(b.id, N, b.state)
local existing = ch:FindFirstChild(a)
if existing then
existing: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
border:Destroy()
task.defer(function()
for key, data in pairs(newcache) do
local coords = util.BlockPosStringToCoords(key)
for _, o in pairs(NEIGHBOR_OFFSETS) do
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 or not c.IsBlockRenderable or 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)
end)
c.loaded = true
return ch
end
return ChunkBuilder

View File

@@ -0,0 +1,413 @@
--!native
--!optimize 2
local ChunkManager = {}
local RunService = game:GetService("RunService")
local Chunk = require("./ChunkManager/Chunk")
local BlockManager = require("./ChunkManager/BlockManager")
local ChunkBuilder = require("./ChunkManager/ChunkBuilder")
local Util = require("./Util")
local Globals = require(script.Parent:WaitForChild("Globals"))
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 = Globals.RenderDistance or 5
local LOAD_BATCH = Globals.LoadBatch or 8
local RESYNC_INTERVAL = Globals.ResyncInterval or 5
local RESYNC_RADIUS = Globals.ResyncRadius or 2
local DEBUG_RESYNC = true
local FORCELOAD_CHUNKS = {
{0, 1, 0}
}
local unloadingChunks = {}
local pendingChunkRequests = {}
local lastChunkKey: string? = nil
local lastHeavyTick = 0
local HEAVY_TICK_INTERVAL = 1.5
local lastUnloadSweep = 0
local UNLOAD_SWEEP_INTERVAL = 1.5
local function worldToChunkCoord(v: number): number
return math.floor((v + 16) / 32)
end
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
function ChunkManager:UnloadAllNow()
for key, chunk in pairs(Chunk.AllChunks) do
unloadingChunks[key] = true
pcall(function()
if chunk.loaded then
chunk:UnloadImmediate()
end
end)
pcall(function()
chunk:Destroy()
end)
Chunk.AllChunks[key] = nil
unloadingChunks[key] = nil
end
end
local function Swait(l)
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
while pendingChunkRequests[key] do
task.wait()
end
return Chunk.AllChunks[key]
end
pendingChunkRequests[key] = true
local ok, data = pcall(function()
return remote:InvokeServer(x, y, z)
end)
if not ok then
data = {}
end
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()
ensureNeighboringChunksLoaded(x, y, z)
local chunk = Chunk.AllChunks[key]
if not chunk then
chunk = ChunkManager:GetChunk(x, y, z)
Chunk.AllChunks[key] = chunk
end
local instance = ChunkBuilder:BuildChunk(chunk, ChunkFolder)
chunk.instance = instance
chunk.loaded = true
unloadingChunks[key] = nil
end)
end
function ChunkManager:RefreshChunk(x, y, z)
local key = `{x},{y},{z}`
local chunk = Chunk.AllChunks[key]
if not chunk then
pendingChunkRequests[key] = nil
ChunkManager:GetChunk(x, y, z)
ChunkManager:LoadChunk(x, y, z)
return
end
local ok, newData = pcall(function()
return remote:InvokeServer(x, y, z)
end)
if not ok or typeof(newData) ~= "table" then
if DEBUG_RESYNC then
warn("[CHUNKMANAGER][RESYNC] Failed to fetch chunk data", key, ok, typeof(newData))
end
return
end
local function sameState(a, b)
if a == b then
return true
end
if not a or not b then
return false
end
local count = 0
for k, v in pairs(a) do
count += 1
if b[k] ~= v then
return false
end
end
for _ in pairs(b) do
count -= 1
end
return count == 0
end
local function sameBlockData(a, b)
if a == b then
return true
end
if not a or not b then
return false
end
if a.id ~= b.id then
return false
end
return sameState(a.state, b.state)
end
local changed = 0
local removed = 0
for keyStr, newBlock in pairs(newData) do
local oldBlock = chunk.data[keyStr]
if not sameBlockData(oldBlock, newBlock) then
chunk.data[keyStr] = newBlock
local coords = Util.BlockPosStringToCoords(keyStr)
chunk:PropogateChanges(coords.X, coords.Y, coords.Z, newBlock)
changed += 1
end
end
for keyStr in pairs(chunk.data) do
if not newData[keyStr] then
chunk.data[keyStr] = nil
local coords = Util.BlockPosStringToCoords(keyStr)
chunk:PropogateChanges(coords.X, coords.Y, coords.Z, 0)
removed += 1
end
end
if chunk.loaded and chunk.instance then
local pruned = 0
for _, child in ipairs(chunk.instance:GetChildren()) do
if not newData[child.Name] then
pruned += 1
child:Destroy()
end
end
if DEBUG_RESYNC and pruned > 0 then
print("[CHUNKMANAGER][RESYNC] Pruned ghost instances", key, "count", pruned)
end
end
if DEBUG_RESYNC and (changed > 0 or removed > 0) then
print("[CHUNKMANAGER][RESYNC] Applied diff", key, "changed", changed, "removed", removed)
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 = worldToChunkCoord(pos.X),
y = worldToChunkCoord(pos.Y),
z = worldToChunkCoord(pos.Z)
}
local ck = `{chunkPos.x},{chunkPos.y},{chunkPos.z}`
local now = tick()
local shouldHeavyTick = (ck ~= lastChunkKey) or (now - lastHeavyTick >= HEAVY_TICK_INTERVAL)
lastChunkKey = ck
if shouldHeavyTick then
lastHeavyTick = now
end
if shouldHeavyTick then
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 = now
if not chunk.loaded then
ChunkManager:LoadChunk(cx, cy, cz)
processed += 1
if processed % LOAD_BATCH == 0 then
Swait(1)
end
end
end
end)
else
local current = Chunk.AllChunks[ck]
if current then
current.inhabitedTime = now
end
end
--[[
task.defer(function()
for y = 0, 2 do
task.defer(function()
for x = -CHUNK_RADIUS, CHUNK_RADIUS do
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
end
end)
Swait(10)
end
end)
--]]
if now - lastUnloadSweep >= UNLOAD_SWEEP_INTERVAL then
lastUnloadSweep = now
for key, loadedChunk in pairs(Chunk.AllChunks) do
if now - loadedChunk.inhabitedTime > 15 and not unloadingChunks[key] then
unloadingChunks[key] = true
task.defer(function()
loadedChunk:Unload()
loadedChunk:Destroy()
Chunk.AllChunks[key] = nil
unloadingChunks[key] = nil
end)
end
end
end
end
function ChunkManager:ResyncAroundPlayer(radius: number)
local player = game:GetService("Players").LocalPlayer
if not player.Character then
return
end
local pos = player.Character:GetPivot().Position
local chunkPos = {
x = worldToChunkCoord(pos.X),
y = worldToChunkCoord(pos.Y),
z = worldToChunkCoord(pos.Z)
}
for y = -radius, radius do
for x = -radius, radius do
for z = -radius, radius do
local cx, cy, cz = chunkPos.x + x, chunkPos.y + y, chunkPos.z + z
ChunkManager:RefreshChunk(cx, cy, cz)
end
end
end
end
function ChunkManager:ResyncAroundChunk(cx: number, cy: number, cz: number, radius: number)
for y = -radius, radius do
for x = -radius, radius do
for z = -radius, radius do
ChunkManager:RefreshChunk(cx + x, cy + y, cz + z)
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()
tickremote.OnClientEvent:Connect(function(m)
if m == "U_ALL" then
ChunkManager:UnloadAllNow()
end
end)
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)
task.defer(function()
while true do
wait(RESYNC_INTERVAL)
local ok, err = pcall(function()
ChunkManager:ResyncAroundPlayer(RESYNC_RADIUS)
end)
if not ok then
warn("[CHUNKMANAGER][RESYNC]", err)
end
end
end)
end
return ChunkManager