summaryrefslogtreecommitdiff
path: root/common/chunk.lua
blob: affdab86b9247a5e968a92035bb9ce70c16c1ea6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
local json = require"common.dkjson"
local class = require"common.class"
local coords = require"common.coords"

local CHUNK_SIZE = require"common.constants".CHUNK_SIZE

local function index_ok(offq,offr)
	return 0<=offq and 0<=offr and offq<CHUNK_SIZE and offr<CHUNK_SIZE
end

local function index(offq,offr)
	-- indexes start at 0
	-- and go up to (CHUNK_SIZE^2)-1
	assert(index_ok(offq,offr), "chunk hex offset out of bounds")
	return CHUNK_SIZE*offq + offr + 1
end

local Chunk = class()
function Chunk.make(cls,cp,tiles)
	return setmetatable({cp=cp,tiles=tiles},cls)
end
function Chunk.at(self,hoffs)
	return self:_atqr(hoffs.q,hoffs.r)
end
function Chunk._atqr(self,q,r)
	if not index_ok(q,r) then return nil end
	return self.tiles[index(q,r)]
end
function Chunk.set_at(self,hoffs,tile)
	if not index_ok(hoffs.q,hoffs.r) then return end
	self.tiles[index(hoffs.q,hoffs.r)] = tile
end

function Chunk.data_packet(self)
	return json.encode{t="chunk",tiles=self.tiles,u=self.cp.u,v=self.cp.v}
end
function Chunk.from_packet_data(packet)
	-- assuming packet has already been json.decoded
	-- since otherwise how would we know it's a chunk packet

	local cp = coords.ChunkPos:make(packet.u,packet.v)
	return Chunk:make(cp,packet.tiles)
end

return {
	Chunk=Chunk,
	index=index,
	index_ok=index_ok,
}