summaryrefslogtreecommitdiff
path: root/server/chunk.lua
blob: 852f1fea6939b64a6783e9816d9949d5e1190165 (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
51
52
local class = require"common.class"
local Chunk = require"common.chunk".Chunk
local json = require"common.dkjson"
local db = require'db'

local ChunkS = class.extend(Chunk)
function ChunkS.make(cls,...)
	local self = Chunk.make(cls,...)
	self.dirty = false
	return self
end

function ChunkS.apply_migrations(self)
	-- if tile format has changed and format in db isn't up to date any more
	-- then perform updates here
	for i,t in ipairs(self.tiles) do
		if t == false then self.tiles[i] = 0
		elseif t == true then self.tiles[i] = 9 end
	end
end

function ChunkS.load_from_disk(cls,cp)
	-- tries to load from database. returns nil if not there.
	local txn,dbi = db.get_db('chunks')
	local d = dbi[tostring(cp)]
	txn:commit()

	if not d then return nil end
	local j = json.decode(d)

	local self = cls:from_packet_data(j)
	self:apply_migrations()

	return self
end

function ChunkS.save_if_dirty(self)
	if self.dirty then
		print("saving chunk",self.cp)
		local txn,dbi = db.get_db('chunks',true)
		dbi[tostring(self.cp)] = self:data_packet()
		txn:commit()
		self.dirty = false
	end
end

function ChunkS.set_at(self,...)
	Chunk.set_at(self,...)
	self.dirty = true
end

return {ChunkS=ChunkS}