summaryrefslogtreecommitdiff
path: root/common/chunk.lua
blob: 563723e635bd37e4361ddebfd1faf763d6687ac5 (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
50
local json = require"common.dkjson"
local class = require"common.class"
local coords = require"common.coords"
local rle = require"common.rle"

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)
	-- errors if invalid offset
	return self:_atqr(hoffs.q,hoffs.r)
end
function Chunk._atqr(self,q,r)
	return self.tiles[index(q,r)]
end
function Chunk.set_at(self,hoffs,tile)
	-- errors if invalid offset
	self.tiles[index(hoffs.q,hoffs.r)] = tile
end

function Chunk.data_packet(self)
	return json.encode{t="chunk",tiles=rle.encode(self.tiles),u=self.cp.u,v=self.cp.v}
end
function Chunk.from_packet_data(cls,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 cls:make(cp,rle.decode(packet.tiles))
end

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