Add chunk wrapping

This commit is contained in:
shylie 2025-07-19 11:02:00 -04:00
parent ccfa075d24
commit 071b00d922

View File

@ -4,6 +4,7 @@ local zprite = require("zprite.zprite")
---@field private _chunks {integer: {z: zprite, x: integer, y: integer}}
---@field private _chunk_size integer
---@field private _chunk_height integer
---@field private _chunk_wrap integer
---@field private _texture love.Image
---@field private _height_scale number
local zchunk = {}
@ -12,7 +13,8 @@ zchunk.__index = zchunk
---@param texture love.Image
---@param chunk_size integer?
---@param chunk_height integer?
function zchunk.new(texture, chunk_size, chunk_height)
---@param chunk_wrap integer?
function zchunk.new(texture, chunk_size, chunk_height, chunk_wrap)
chunk_size = chunk_size or 16
chunk_height = chunk_height or 32
if chunk_size < 1 then
@ -21,6 +23,9 @@ function zchunk.new(texture, chunk_size, chunk_height)
if chunk_height < 1 then
error("chunk height must be at least 1")
end
if chunk_wrap and chunk_wrap < 1 then
error("chunk wrap must be at least 1")
end
if not texture then
error("must have a texture")
end
@ -30,6 +35,7 @@ function zchunk.new(texture, chunk_size, chunk_height)
obj._chunks = {}
obj._chunk_size = chunk_size
obj._chunk_height = chunk_height
obj._chunk_wrap = chunk_wrap
obj._texture = texture
@ -42,7 +48,14 @@ end
---@param y integer
---@return integer
function zchunk:_chunk_index(x, y)
return math.floor(x / self._chunk_size) + math.floor(y / self._chunk_size) * 1e7
local cx = math.floor(x / self._chunk_size)
local cy = math.floor(y / self._chunk_size)
if self._chunk_wrap then
cx = cx % self._chunk_wrap
cy = cy % self._chunk_wrap
end
return cx + cy * 1e7
end
---@param x integer?
@ -52,10 +65,7 @@ function zchunk:remove(x, y)
self._chunks = {}
else
local index = self:_chunk_index(x, y)
if not self._chunks[index] then
return
end
self._chunks[index] = {}
self._chunks[index] = nil
end
end
@ -80,19 +90,19 @@ end
---@param y number
---@param quad love.Quad
---@param layer_count integer
---@param color_map fun(integer): number, number, number, number?
---@param color_map fun(layer: integer): number, number, number
---@param base_layer integer?
function zchunk:put(x, y, quad, layer_count, color_map, base_layer)
local index = self:_chunk_index(x, y)
if not self._chunks[index] then
self._chunks[index] = {
z = zprite.new(self._texture, self._chunk_size * self._chunk_size * self._chunk_height),
x = math.floor(x / self._chunk_size),
y = math.floor(y / self._chunk_size),
}
self._chunks[index].z._height_scale = self._height_scale
end
self._chunks[index].z:put(x, y, quad, layer_count, color_map, base_layer)
self._chunks[index].x = math.floor(x / self._chunk_size)
self._chunks[index].y = math.floor(y / self._chunk_size)
end
local transform = love.math.newTransform()