1 /**
2 Copyright: Copyright (c) 2017-2018 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 module railroad.rail.railgraph;
7 
8 import voxelman.container.hash.map;
9 import voxelman.math;
10 import voxelman.log;
11 import voxelman.serialization.hashtable;
12 
13 import voxelman.world.storage;
14 import railroad.rail.utils;
15 
16 
17 struct RailGraph
18 {
19 	HashMap!(RailPos, RailData) rails;
20 
21 	auto dbKey = IoKey("railroad.rail_graph");
22 
23 	void read(ref PluginDataLoader loader)
24 	{
25 		ubyte[] data = loader.readEntryRaw(dbKey);
26 		deserializeMap(rails, data);
27 	}
28 
29 	void write(ref PluginDataSaver saver)
30 	{
31 		auto sink = saver.beginWrite();
32 		serializeMap(rails, sink);
33 		saver.endWrite(dbKey);
34 	}
35 
36 	void onRailEdit(RailPos pos, RailData railData, RailEditOp editOp)
37 	{
38 		final switch(editOp)
39 		{
40 			case RailEditOp.add: onRailAdd(pos, railData); break;
41 			case RailEditOp.remove: onRailRemove(pos, railData); break;
42 		}
43 	}
44 
45 	void onRailAdd(RailPos pos, RailData railData)
46 	{
47 		auto data = rails.getOrCreate(pos, RailData());
48 		data.addRail(railData);
49 	}
50 
51 	void onRailRemove(RailPos pos, RailData railData)
52 	{
53 		if (auto data = pos in rails) {
54 			(*data).removeRail(railData);
55 			if ((*data).empty) {
56 				rails.removeByPtr(data);
57 			}
58 		}
59 	}
60 }