1 /**
2 Copyright: Copyright (c) 2016-2017 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 module voxelman.world.storage.activechunks;
7 
8 import voxelman.log;
9 import std.array : empty;
10 import cbor;
11 import voxelman.container.hashset;
12 
13 import voxelman.world.storage;
14 
15 struct ActiveChunks
16 {
17 	private auto dbKey = IoKey("voxelman.world.active_chunks");
18 	HashSet!ChunkWorldPos chunks;
19 	void delegate(ChunkWorldPos cwp) loadChunk;
20 	void delegate(ChunkWorldPos cwp) unloadChunk;
21 
22 	void add(ChunkWorldPos cwp) {
23 		chunks.put(cwp);
24 		loadChunk(cwp);
25 	}
26 
27 	void remove(ChunkWorldPos cwp) {
28 		if (chunks.remove(cwp))
29 			unloadChunk(cwp);
30 	}
31 
32 	void loadActiveChunks() {
33 		foreach(cwp; chunks) {
34 			loadChunk(cwp);
35 			infof("load active: %s", cwp);
36 		}
37 	}
38 
39 	package(voxelman.world) void read(ref PluginDataLoader loader) {
40 		ubyte[] data = loader.readEntryRaw(dbKey);
41 		if (!data.empty) {
42 			auto token = decodeCborToken(data);
43 			assert(token.type == CborTokenType.arrayHeader);
44 			foreach(_; 0..token.uinteger)
45 				chunks.put(decodeCborSingle!ChunkWorldPos(data));
46 			assert(data.empty);
47 		}
48 	}
49 
50 	package(voxelman.world) void write(ref PluginDataSaver saver) {
51 		auto sink = saver.beginWrite();
52 		encodeCborArrayHeader(sink, chunks.length);
53 		foreach(cwp; chunks)
54 			encodeCbor(sink, cwp);
55 		saver.endWrite(dbKey);
56 	}
57 }