1 /**
2 Copyright: Copyright (c) 2016-2018 Andrey Penechko.
3 License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 Authors: Andrey Penechko.
5 */
6 module datadriven.storage;
7 
8 import datadriven.api;
9 import voxelman.log;
10 import voxelman.container.buffer;
11 import voxelman.container.hash.map;
12 import voxelman.container.hash.set;
13 import voxelman.serialization.hashtable;
14 
15 struct HashmapComponentStorage(_ComponentType)
16 {
17 	private HashMap!(EntityId, ComponentType, EntityId.max, EntityId.max-1) components;
18 	alias ComponentType = _ComponentType;
19 
20 	void set(EntityId eid, ComponentType component)
21 	{
22 		components[eid] = component;
23 	}
24 
25 	void remove(EntityId eid)
26 	{
27 		components.remove(eid);
28 	}
29 
30 	void removeAll()
31 	{
32 		components.clear();
33 	}
34 
35 	size_t length() @property
36 	{
37 		return components.length;
38 	}
39 
40 	ComponentType* get(EntityId eid)
41 	{
42 		return eid in components;
43 	}
44 
45 	ComponentType* getOrCreate(EntityId eid, ComponentType defVal = ComponentType.init)
46 	{
47 		return components.getOrCreate(eid, defVal);
48 	}
49 
50 	auto byKey() {
51 		return components.byKey;
52 	}
53 
54 	int opApply(scope int delegate(in EntityId, ref ComponentType) del) {
55 		return components.opApply(del);
56 	}
57 
58 	void serialize(Buffer!ubyte* sink)
59 	{
60 		serializeMap(components, sink);
61 	}
62 
63 	void serializePartial(Buffer!ubyte* sink, HashSet!EntityId externalEntities)
64 	{
65 		serializeMapPartial(components, sink, externalEntities);
66 	}
67 
68 	void deserialize(ubyte[] input)
69 	{
70 		deserializeMap(components, input);
71 	}
72 }
73 
74 static assert(isComponentStorage!(HashmapComponentStorage!int, int));
75 
76 struct EntitySet
77 {
78 	private HashSet!EntityId entities;
79 
80 	void set(EntityId eid)
81 	{
82 		entities.put(eid);
83 	}
84 
85 	void remove(EntityId eid)
86 	{
87 		entities.remove(eid);
88 	}
89 
90 	void removeAll()
91 	{
92 		entities.clear();
93 	}
94 
95 	size_t length() @property
96 	{
97 		return entities.length;
98 	}
99 
100 	bool get(EntityId eid)
101 	{
102 		return eid in entities;
103 	}
104 
105 	int opApply(scope int delegate(in EntityId) del) {
106 		return entities.opApply(del);
107 	}
108 
109 	void serialize(Buffer!ubyte* sink)
110 	{
111 		serializeSet(entities, sink);
112 	}
113 
114 	void serializePartial(Buffer!ubyte* sink, HashSet!EntityId externalEntities)
115 	{
116 		serializeSetPartial(entities, sink, externalEntities);
117 	}
118 
119 	void deserialize(ubyte[] input)
120 	{
121 		deserializeSet(entities, input);
122 	}
123 }
124 
125 static assert(isEntitySet!(EntitySet));