aboutsummaryrefslogtreecommitdiff
path: root/src/util/areastore.cpp
blob: 58f08a8c2e22918cdce829b1a45c5340177054fe (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/*
Minetest
Copyright (C) 2015 est31 <mtest31@outlook.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "util/areastore.h"
#include "util/serialize.h"
#include "util/container.h"

#if USE_SPATIAL
	#include <spatialindex/SpatialIndex.h>
	#include <spatialindex/RTree.h>
	#include <spatialindex/Point.h>
#endif

#define AST_SMALLER_EQ_AS(p, q) (((p).X <= (q).X) && ((p).Y <= (q).Y) && ((p).Z <= (q).Z))

#define AST_OVERLAPS_IN_DIMENSION(amine, amaxe, b, d) \
	(!(((amine).d > (b)->maxedge.d) || ((amaxe).d < (b)->minedge.d)))

#define AST_CONTAINS_PT(a, p) (AST_SMALLER_EQ_AS((a)->minedge, (p)) && \
	AST_SMALLER_EQ_AS((p), (a)->maxedge))

#define AST_CONTAINS_AREA(amine, amaxe, b)         \
	(AST_SMALLER_EQ_AS((amine), (b)->minedge) \
	&& AST_SMALLER_EQ_AS((b)->maxedge, (amaxe)))

#define AST_AREAS_OVERLAP(amine, amaxe, b)                \
	(AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), X) && \
	AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), Y) &&  \
	AST_OVERLAPS_IN_DIMENSION((amine), (amaxe), (b), Z))


AreaStore *AreaStore::getOptimalImplementation()
{
#if USE_SPATIAL
	return new SpatialAreaStore();
#else
	return new VectorAreaStore();
#endif
}

const Area *AreaStore::getArea(u32 id) const
{
	AreaMap::const_iterator it = areas_map.find(id);
	if (it == areas_map.end())
		return NULL;
	return &it->second;
}

void AreaStore::serialize(std::ostream &os) const
{
	writeU8(os, 0); // Serialisation version

	// TODO: Compression?
	writeU16(os, areas_map.size());
	for (AreaMap::const_iterator it = areas_map.begin();
			it != areas_map.end(); ++it) {
		const Area &a = it->second;
		writeV3S16(os, a.minedge);
		writeV3S16(os, a.maxedge);
		writeU16(os, a.data.size());
		os.write(a.data.data(), a.data.size());
	}
}

void AreaStore::deserialize(std::istream &is)
{
	u8 ver = readU8(is);
	if (ver != 0)
		throw SerializationError("Unknown AreaStore "
				"serialization version!");

	u16 num_areas = readU16(is);
	for (u32 i = 0; i < num_areas; ++i) {
		Area a;
		a.minedge = readV3S16(is);
		a.maxedge = readV3S16(is);
		u16 data_len = readU16(is);
		char *data = new char[data_len];
		is.read(data, data_len);
		a.data = std::string(data, data_len);
		insertArea(&a);
	}
}

void AreaStore::invalidateCache()
{
	if (m_cache_enabled) {
		m_res_cache.invalidate();
	}
}

void AreaStore::setCacheParams(bool enabled, u8 block_radius, size_t limit)
{
	m_cache_enabled = enabled;
	m_cacheblock_radius = MYMAX(block_radius, 16);
	m_res_cache.setLimit(MYMAX(limit, 20));
	invalidateCache();
}

void AreaStore::cacheMiss(void *data, const v3s16 &mpos, std::vector<Area *> *dest)
{
	AreaStore *as = (AreaStore *)data;
	u8 r = as->m_cacheblock_radius;

	// get the points at the edges of the mapblock
	v3s16 minedge(mpos.X * r, mpos.Y * r, mpos.Z * r);
	v3s16 maxedge(
		minedge.X + r - 1,
		minedge.Y + r - 1,
		minedge.Z + r - 1);

	as->getAreasInArea(dest, minedge, maxedge, true);

	/* infostream << "Cache miss with " << dest->size() << " areas, between ("
			<< minedge.X << ", " << minedge.Y << ", " << minedge.Z
			<< ") and ("
			<< maxedge.X << ", " << maxedge.Y << ", " << maxedge.Z
			<< ")" << std::endl; // */
}

void AreaStore::getAreasForPos(std::vector<Area *> *result, v3s16 pos)
{
	if (m_cache_enabled) {
		v3s16 mblock = getContainerPos(pos, m_cacheblock_radius);
		const std::vector<Area *> *pre_list = m_res_cache.lookupCache(mblock);

		size_t s_p_l = pre_list->size();
		for (size_t i = 0; i < s_p_l; i++) {
			Area *b = (*pre_list)[i];
			if (AST_CONTAINS_PT(b, pos)) {
				result->push_back(b);
			}
		}
	} else {
		return getAreasForPosImpl(result, pos);
	}
}


////
// VectorAreaStore
////


bool VectorAreaStore::insertArea(Area *a)
{
	if (a->id == U32_MAX)
		a->id = getNextId();
	std::pair<AreaMap::iterator, bool> res =
			areas_map.insert(std::make_pair(a->id, *a));
	if (!res.second)
		// ID is not unique
		return false;
	m_areas.push_back(&res.first->second);
	invalidateCache();
	return true;
}

bool VectorAreaStore::removeArea(u32 id)
{
	AreaMap::iterator it = areas_map.find(id);
	if (it == areas_map.end())
		return false;
	Area *a = &it->second;
	for (std::vector<Area *>::iterator v_it = m_areas.begin();
			v_it != m_areas.end(); ++v_it) {
		if (*v_it == a) {
			m_areas.erase(v_it);
			break;
		}
	}
	areas_map.erase(it);
	invalidateCache();
	return true;
}

void VectorAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos)
{
	for (size_t i = 0; i < m_areas.size(); ++i) {
		Area *b = m_areas[i];
		if (AST_CONTAINS_PT(b, pos)) {
			result->push_back(b);
		}
	}
}

void VectorAreaStore::getAreasInArea(std::vector<Area *> *result,
		v3s16 minedge, v3s16 maxedge, bool accept_overlap)
{
	for (size_t i = 0; i < m_areas.size(); ++i) {
		Area *b = m_areas[i];
		if (accept_overlap ? AST_AREAS_OVERLAP(minedge, maxedge, b) :
				AST_CONTAINS_AREA(minedge, maxedge, b)) {
			result->push_back(b);
		}
	}
}

#if USE_SPATIAL

static inline SpatialIndex::Region get_spatial_region(const v3s16 minedge,
		const v3s16 maxedge)
{
	const double p_low[] = {(double)minedge.X,
		(double)minedge.Y, (double)minedge.Z};
	const double p_high[] = {(double)maxedge.X, (double)maxedge.Y,
		(double)maxedge.Z};
	return SpatialIndex::Region(p_low, p_high, 3);
}

static inline SpatialIndex::Point get_spatial_point(const v3s16 pos)
{
	const double p[] = {(double)pos.X, (double)pos.Y, (double)pos.Z};
	return SpatialIndex::Point(p, 3);
}


bool SpatialAreaStore::insertArea(Area *a)
{
	if (a->id == U32_MAX)
		a->id = getNextId();
	if (!areas_map.insert(std::make_pair(a->id, *a)).second)
		// ID is not unique
		return false;
	m_tree->insertData(0, NULL, get_spatial_region(a->minedge, a->maxedge), a->id);
	invalidateCache();
	return true;
}

bool SpatialAreaStore::removeArea(u32 id)
{
	std::map<u32, Area>::iterator itr = areas_map.find(id);
	if (itr != areas_map.end()) {
		Area *a = &itr->second;
		bool result = m_tree->deleteData(get_spatial_region(a->minedge,
			a->maxedge), id);
		areas_map.erase(itr);
		invalidateCache();
		return result;
	} else {
		return false;
	}
}

void SpatialAreaStore::getAreasForPosImpl(std::vector<Area *> *result, v3s16 pos)
{
	VectorResultVisitor visitor(result, this);
	m_tree->pointLocationQuery(get_spatial_point(pos), visitor);
}

void SpatialAreaStore::getAreasInArea(std::vector<Area *> *result,
		v3s16 minedge, v3s16 maxedge, bool accept_overlap)
{
	VectorResultVisitor visitor(result, this);
	if (accept_overlap) {
		m_tree->intersectsWithQuery(get_spatial_region(minedge, maxedge),
			visitor);
	} else {
		m_tree->containsWhatQuery(get_spatial_region(minedge, maxedge), visitor);
	}
}

SpatialAreaStore::~SpatialAreaStore()
{
	delete m_tree;
}

SpatialAreaStore::SpatialAreaStore()
{
	m_storagemanager =
		SpatialIndex::StorageManager::createNewMemoryStorageManager();
	SpatialIndex::id_type id;
	m_tree = SpatialIndex::RTree::createNewRTree(
		*m_storagemanager,
		.7, // Fill factor
		100, // Index capacity
		100, // Leaf capacity
		3, // dimension :)
		SpatialIndex::RTree::RV_RSTAR,
		id);
}

#endif
to_internal(material); if(material > 0xfff) throw SerializationError("Too large material number"); // Convert old id to name NameIdMapping legacy_nimap; content_mapnode_get_name_id_mapping(&legacy_nimap); legacy_nimap.getName(material, name); if(name == "") name = "unknown_block"; if (itemdef) name = itemdef->getAlias(name); count = materialcount; } else if(name == "MaterialItem2") { // Obsoleted on 2011-11-16 u16 material; is>>material; u16 materialcount; is>>materialcount; if(material > 0xfff) throw SerializationError("Too large material number"); // Convert old id to name NameIdMapping legacy_nimap; content_mapnode_get_name_id_mapping(&legacy_nimap); legacy_nimap.getName(material, name); if(name == "") name = "unknown_block"; if (itemdef) name = itemdef->getAlias(name); count = materialcount; } else if(name == "node" || name == "NodeItem" || name == "MaterialItem3" || name == "craft" || name == "CraftItem") { // Obsoleted on 2012-01-07 std::string all; std::getline(is, all, '\n'); // First attempt to read inside "" Strfnd fnd(all); fnd.next("\""); // If didn't skip to end, we have ""s if(!fnd.at_end()){ name = fnd.next("\""); } else { // No luck, just read a word then fnd.start(all); name = fnd.next(" "); } fnd.skip_over(" "); if (itemdef) name = itemdef->getAlias(name); count = stoi(trim(fnd.next(""))); if(count == 0) count = 1; } else if(name == "MBOItem") { // Obsoleted on 2011-10-14 throw SerializationError("MBOItem not supported anymore"); } else if(name == "tool" || name == "ToolItem") { // Obsoleted on 2012-01-07 std::string all; std::getline(is, all, '\n'); // First attempt to read inside "" Strfnd fnd(all); fnd.next("\""); // If didn't skip to end, we have ""s if(!fnd.at_end()){ name = fnd.next("\""); } else { // No luck, just read a word then fnd.start(all); name = fnd.next(" "); } count = 1; // Then read wear fnd.skip_over(" "); if (itemdef) name = itemdef->getAlias(name); wear = stoi(trim(fnd.next(""))); } else { do // This loop is just to allow "break;" { // The real thing // Apply item aliases if (itemdef) name = itemdef->getAlias(name); // Read the count std::string count_str; std::getline(is, count_str, ' '); if(count_str.empty()) { count = 1; break; } else count = stoi(count_str); // Read the wear std::string wear_str; std::getline(is, wear_str, ' '); if(wear_str.empty()) break; else wear = stoi(wear_str); // Read metadata metadata.deSerialize(is); // In case fields are added after metadata, skip space here: //std::getline(is, tmp, ' '); //if(!tmp.empty()) // throw SerializationError("Unexpected text after metadata"); } while(false); } if (name.empty() || count == 0) clear(); else if (itemdef && itemdef->get(name).type == ITEM_TOOL) count = 1; } void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef) { std::istringstream is(str, std::ios::binary); deSerialize(is, itemdef); } std::string ItemStack::getItemString() const { std::ostringstream os(std::ios::binary); serialize(os); return os.str(); } ItemStack ItemStack::addItem(const ItemStack &newitem_, IItemDefManager *itemdef) { ItemStack newitem = newitem_; // If the item is empty or the position invalid, bail out if(newitem.empty()) { // nothing can be added trivially } // If this is an empty item, it's an easy job. else if(empty()) { *this = newitem; newitem.clear(); } // If item name or metadata differs, bail out else if (name != newitem.name || metadata != newitem.metadata) { // cannot be added } // If the item fits fully, add counter and delete it else if(newitem.count <= freeSpace(itemdef)) { add(newitem.count); newitem.clear(); } // Else the item does not fit fully. Add all that fits and return // the rest. else { u16 freespace = freeSpace(itemdef); add(freespace); newitem.remove(freespace); } return newitem; } bool ItemStack::itemFits(const ItemStack &newitem_, ItemStack *restitem, IItemDefManager *itemdef) const { ItemStack newitem = newitem_; // If the item is empty or the position invalid, bail out if(newitem.empty()) { // nothing can be added trivially } // If this is an empty item, it's an easy job. else if(empty()) { newitem.clear(); } // If item name or metadata differs, bail out else if (name != newitem.name || metadata != newitem.metadata) { // cannot be added } // If the item fits fully, delete it else if(newitem.count <= freeSpace(itemdef)) { newitem.clear(); } // Else the item does not fit fully. Return the rest. // the rest. else { u16 freespace = freeSpace(itemdef); newitem.remove(freespace); } if(restitem) *restitem = newitem; return newitem.empty(); } ItemStack ItemStack::takeItem(u32 takecount) { if(takecount == 0 || count == 0) return ItemStack(); ItemStack result = *this; if(takecount >= count) { // Take all clear(); } else { // Take part remove(takecount); result.count = takecount; } return result; } ItemStack ItemStack::peekItem(u32 peekcount) const { if(peekcount == 0 || count == 0) return ItemStack(); ItemStack result = *this; if(peekcount < count) result.count = peekcount; return result; } /* Inventory */ InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef): m_name(name), m_size(size), m_width(0), m_itemdef(itemdef) { clearItems(); } InventoryList::~InventoryList() { } void InventoryList::clearItems() { m_items.clear(); for(u32 i=0; i<m_size; i++) { m_items.push_back(ItemStack()); } //setDirty(true); } void InventoryList::setSize(u32 newsize) { if(newsize != m_items.size()) m_items.resize(newsize); m_size = newsize; } void InventoryList::setWidth(u32 newwidth) { m_width = newwidth; } void InventoryList::setName(const std::string &name) { m_name = name; } void InventoryList::serialize(std::ostream &os) const { //os.imbue(std::locale("C")); os<<"Width "<<m_width<<"\n"; for(u32 i=0; i<m_items.size(); i++) { const ItemStack &item = m_items[i]; if(item.empty()) { os<<"Empty"; } else { os<<"Item "; item.serialize(os); } os<<"\n"; } os<<"EndInventoryList\n"; } void InventoryList::deSerialize(std::istream &is) { //is.imbue(std::locale("C")); clearItems(); u32 item_i = 0; m_width = 0; for(;;) { std::string line; std::getline(is, line, '\n'); std::istringstream iss(line); //iss.imbue(std::locale("C")); std::string name; std::getline(iss, name, ' '); if(name == "EndInventoryList") { break; } // This is a temporary backwards compatibility fix else if(name == "end") { break; } else if(name == "Width") { iss >> m_width; if (iss.fail()) throw SerializationError("incorrect width property"); } else if(name == "Item") { if(item_i > getSize() - 1) throw SerializationError("too many items"); ItemStack item; item.deSerialize(iss, m_itemdef); m_items[item_i++] = item; } else if(name == "Empty") { if(item_i > getSize() - 1) throw SerializationError("too many items"); m_items[item_i++].clear(); } } } InventoryList::InventoryList(const InventoryList &other) { *this = other; } InventoryList & InventoryList::operator = (const InventoryList &other) { m_items = other.m_items; m_size = other.m_size; m_width = other.m_width; m_name = other.m_name; m_itemdef = other.m_itemdef; //setDirty(true); return *this; } bool InventoryList::operator == (const InventoryList &other) const { if(m_size != other.m_size) return false; if(m_width != other.m_width) return false; if(m_name != other.m_name) return false; for(u32 i=0; i<m_items.size(); i++) { ItemStack s1 = m_items[i]; ItemStack s2 = other.m_items[i]; if(s1.name != s2.name || s1.wear!= s2.wear || s1.count != s2.count || s1.metadata != s2.metadata) return false; } return true; } const std::string &InventoryList::getName() const { return m_name; } u32 InventoryList::getSize() const { return m_items.size(); } u32 InventoryList::getWidth() const { return m_width; } u32 InventoryList::getUsedSlots() const { u32 num = 0; for(u32 i=0; i<m_items.size(); i++) { if(!m_items[i].empty()) num++; } return num; } u32 InventoryList::getFreeSlots() const { return getSize() - getUsedSlots(); } const ItemStack& InventoryList::getItem(u32 i) const { assert(i < m_size); // Pre-condition return m_items[i]; } ItemStack& InventoryList::getItem(u32 i) { assert(i < m_size); // Pre-condition return m_items[i]; } ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem) { if(i >= m_items.size()) return newitem; ItemStack olditem = m_items[i]; m_items[i] = newitem; //setDirty(true); return olditem; } void InventoryList::deleteItem(u32 i) { assert(i < m_items.size()); // Pre-condition m_items[i].clear(); } ItemStack InventoryList::addItem(const ItemStack &newitem_) { ItemStack newitem = newitem_; if(newitem.empty()) return newitem; /* First try to find if it could be added to some existing items */ for(u32 i=0; i<m_items.size(); i++) { // Ignore empty slots if(m_items[i].empty()) continue; // Try adding newitem = addItem(i, newitem); if(newitem.empty()) return newitem; // All was eaten } /* Then try to add it to empty slots */ for(u32 i=0; i<m_items.size(); i++) { // Ignore unempty slots if(!m_items[i].empty()) continue; // Try adding newitem = addItem(i, newitem); if(newitem.empty()) return newitem; // All was eaten } // Return leftover return newitem; } ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem) { if(i >= m_items.size()) return newitem; ItemStack leftover = m_items[i].addItem(newitem, m_itemdef); //if(leftover != newitem) // setDirty(true); return leftover; } bool InventoryList::itemFits(const u32 i, const ItemStack &newitem, ItemStack *restitem) const { if(i >= m_items.size()) { if(restitem) *restitem = newitem; return false; } return m_items[i].itemFits(newitem, restitem, m_itemdef); } bool InventoryList::roomForItem(const ItemStack &item_) const { ItemStack item = item_; ItemStack leftover; for(u32 i=0; i<m_items.size(); i++) { if(itemFits(i, item, &leftover)) return true; item = leftover; } return false; } bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const { u32 count = item.count; if(count == 0) return true; for(std::vector<ItemStack>::const_reverse_iterator i = m_items.rbegin(); i != m_items.rend(); ++i) { if(count == 0) break; if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) { if (i->count >= count) return true; else count -= i->count; } } return false; } ItemStack InventoryList::removeItem(const ItemStack &item) { ItemStack removed; for(std::vector<ItemStack>::reverse_iterator i = m_items.rbegin(); i != m_items.rend(); ++i) { if(i->name == item.name) { u32 still_to_remove = item.count - removed.count; removed.addItem(i->takeItem(still_to_remove), m_itemdef); if(removed.count == item.count) break; } } return removed; } ItemStack InventoryList::takeItem(u32 i, u32 takecount) { if(i >= m_items.size()) return ItemStack(); ItemStack taken = m_items[i].takeItem(takecount); //if(!taken.empty()) // setDirty(true); return taken; } void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count) { // Take item from source list ItemStack item1; if (count == 0) item1 = changeItem(i, ItemStack()); else item1 = takeItem(i, count); if (item1.empty()) return; // Try to add the item to destination list u32 dest_size = dest->getSize(); // First try all the non-empty slots for (u32 dest_i = 0; dest_i < dest_size; dest_i++) { if (!m_items[dest_i].empty()) { item1 = dest->addItem(dest_i, item1); if (item1.empty()) return; } } // Then try all the empty ones for (u32 dest_i = 0; dest_i < dest_size; dest_i++) { if (m_items[dest_i].empty()) { item1 = dest->addItem(dest_i, item1); if (item1.empty()) return; } } // If we reach this, the item was not fully added // Add the remaining part back to the source item addItem(i, item1); } u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count, bool swap_if_needed, bool *did_swap) { if(this == dest && i == dest_i) return count; // Take item from source list ItemStack item1; if(count == 0) item1 = changeItem(i, ItemStack()); else item1 = takeItem(i, count); if(item1.empty()) return 0; // Try to add the item to destination list u32 oldcount = item1.count; item1 = dest->addItem(dest_i, item1); // If something is returned, the item was not fully added if(!item1.empty()) { // If olditem is returned, nothing was added. bool nothing_added = (item1.count == oldcount); // If something else is returned, part of the item was left unadded. // Add the other part back to the source item addItem(i, item1); // If olditem is returned, nothing was added. // Swap the items if (nothing_added && swap_if_needed) { // Tell that we swapped if (did_swap != NULL) { *did_swap = true; } // Take item from source list item1 = changeItem(i, ItemStack()); // Adding was not possible, swap the items. ItemStack item2 = dest->changeItem(dest_i, item1); // Put item from destination list to the source list changeItem(i, item2); } } return (oldcount - item1.count); } /* Inventory */ Inventory::~Inventory() { clear(); } void Inventory::clear() { m_dirty = true; for(u32 i=0; i<m_lists.size(); i++) { delete m_lists[i]; } m_lists.clear(); } void Inventory::clearContents() { m_dirty = true; for(u32 i=0; i<m_lists.size(); i++) { InventoryList *list = m_lists[i]; for(u32 j=0; j<list->getSize(); j++) { list->deleteItem(j); } } } Inventory::Inventory(IItemDefManager *itemdef) { m_dirty = false; m_itemdef = itemdef; } Inventory::Inventory(const Inventory &other) { *this = other; m_dirty = false; } Inventory & Inventory::operator = (const Inventory &other) { // Gracefully handle self assignment if(this != &other) { m_dirty = true; clear(); m_itemdef = other.m_itemdef; for(u32 i=0; i<other.m_lists.size(); i++) { m_lists.push_back(new InventoryList(*other.m_lists[i])); } } return *this; } bool Inventory::operator == (const Inventory &other) const { if(m_lists.size() != other.m_lists.size()) return false; for(u32 i=0; i<m_lists.size(); i++) { if(*m_lists[i] != *other.m_lists[i]) return false; } return true; } void Inventory::serialize(std::ostream &os) const { for(u32 i=0; i<m_lists.size(); i++) { InventoryList *list = m_lists[i]; os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n"; list->serialize(os); } os<<"EndInventory\n"; } void Inventory::deSerialize(std::istream &is) { clear(); for(;;) { std::string line; std::getline(is, line, '\n'); std::istringstream iss(line); std::string name; std::getline(iss, name, ' '); if(name == "EndInventory") { break; } // This is a temporary backwards compatibility fix else if(name == "end") { break; } else if(name == "List") { std::string listname; u32 listsize; std::getline(iss, listname, ' '); iss>>listsize; InventoryList *list = new InventoryList(listname, listsize, m_itemdef); list->deSerialize(is); m_lists.push_back(list); } else { throw SerializationError("invalid inventory specifier: " + name); } } } InventoryList * Inventory::addList(const std::string &name, u32 size) { m_dirty = true; s32 i = getListIndex(name); if(i != -1) { if(m_lists[i]->getSize() != size) { delete m_lists[i]; m_lists[i] = new InventoryList(name, size, m_itemdef); } return m_lists[i]; } else { //don't create list with invalid name if (name.find(" ") != std::string::npos) return NULL; InventoryList *list = new InventoryList(name, size, m_itemdef); m_lists.push_back(list); return list; } } InventoryList * Inventory::getList(const std::string &name) { s32 i = getListIndex(name); if(i == -1) return NULL; return m_lists[i]; } std::vector<const InventoryList*> Inventory::getLists() { std::vector<const InventoryList*> lists; for(u32 i=0; i<m_lists.size(); i++) { InventoryList *list = m_lists[i]; lists.push_back(list); } return lists; } bool Inventory::deleteList(const std::string &name) { s32 i = getListIndex(name); if(i == -1) return false; m_dirty = true; delete m_lists[i]; m_lists.erase(m_lists.begin() + i); return true; } const InventoryList * Inventory::getList(const std::string &name) const { s32 i = getListIndex(name); if(i == -1) return NULL; return m_lists[i]; } const s32 Inventory::getListIndex(const std::string &name) const { for(u32 i=0; i<m_lists.size(); i++) { if(m_lists[i]->getName() == name) return i; } return -1; } //END