aboutsummaryrefslogtreecommitdiff
path: root/src/particles.h
blob: 7ffb1c72826ae88dbece777bd110e853c7b7bb02 (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
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.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.
*/

#ifndef PARTICLES_HEADER
#define PARTICLES_HEADER

#define DIGGING_PARTICLES_AMOUNT 10

#include <iostream>
#include "irrlichttypes_extrabloated.h"
#include "client/tile.h"
#include "localplayer.h"
#include "environment.h"
#include "tileanimation.h"

struct ClientEvent;
class ParticleManager;
class ClientEnvironment;
struct MapNode;
struct ContentFeatures;

class Particle : public scene::ISceneNode
{
	public:
	Particle(
		IGameDef* gamedef,
		scene::ISceneManager* mgr,
		LocalPlayer *player,
		ClientEnvironment *env,
		v3f pos,
		v3f velocity,
		v3f acceleration,
		float expirationtime,
		float size,
		bool collisiondetection,
		bool collision_removal,
		bool vertical,
		video::ITexture *texture,
		v2f texpos,
		v2f texsize,
		const struct TileAnimationParams &anim,
		u8 glow,
		video::SColor color = video::SColor(0xFFFFFFFF)
	);
	~Particle();

	virtual const aabb3f &getBoundingBox() const
	{
		return m_box;
	}

	virtual u32 getMaterialCount() const
	{
		return 1;
	}

	virtual video::SMaterial& getMaterial(u32 i)
	{
		return m_material;
	}

	virtual void OnRegisterSceneNode();
	virtual void render();

	void step(float dtime);

	bool get_expired ()
	{ return m_expiration < m_time; }

private:
	void updateLight();
	void updateVertices();

	video::S3DVertex m_vertices[4];
	float m_time;
	float m_expiration;

	ClientEnvironment *m_env;
	IGameDef *m_gamedef;
	aabb3f m_box;
	aabb3f m_collisionbox;
	video::SMaterial m_material;
	v2f m_texpos;
	v2f m_texsize;
	v3f m_pos;
	v3f m_velocity;
	v3f m_acceleration;
	LocalPlayer *m_player;
	float m_size;
	//! Color without lighting
	video::SColor m_base_color;
	//! Final rendered color
	video::SColor m_color;
	bool m_collisiondetection;
	bool m_collision_removal;
	bool m_vertical;
	v3s16 m_camera_offset;
	struct TileAnimationParams m_animation;
	float m_animation_time;
	int m_animation_frame;
	u8 m_glow;
};

class ParticleSpawner
{
	public:
	ParticleSpawner(IGameDef* gamedef,
		scene::ISceneManager *smgr,
		LocalPlayer *player,
		u16 amount,
		float time,
		v3f minp, v3f maxp,
		v3f minvel, v3f maxvel,
		v3f minacc, v3f maxacc,
		float minexptime, float maxexptime,
		float minsize, float maxsize,
		bool collisiondetection,
		bool collision_removal,
		u16 attached_id,
		bool vertical,
		video::ITexture *texture,
		u32 id,
		const struct TileAnimationParams &anim, u8 glow,
		ParticleManager* p_manager);

	~ParticleSpawner();

	void step(float dtime, ClientEnvironment *env);

	bool get_expired ()
	{ return (m_amount <= 0) && m_spawntime != 0; }

	private:
	ParticleManager* m_particlemanager;
	float m_time;
	IGameDef *m_gamedef;
	scene::ISceneManager *m_smgr;
	LocalPlayer *m_player;
	u16 m_amount;
	float m_spawntime;
	v3f m_minpos;
	v3f m_maxpos;
	v3f m_minvel;
	v3f m_maxvel;
	v3f m_minacc;
	v3f m_maxacc;
	float m_minexptime;
	float m_maxexptime;
	float m_minsize;
	float m_maxsize;
	video::ITexture *m_texture;
	std::vector<float> m_spawntimes;
	bool m_collisiondetection;
	bool m_collision_removal;
	bool m_vertical;
	u16 m_attached_id;
	struct TileAnimationParams m_animation;
	u8 m_glow;
};

/**
 * Class doing particle as well as their spawners handling
 */
class ParticleManager
{
friend class ParticleSpawner;
public:
	ParticleManager(ClientEnvironment* env);
	~ParticleManager();

	void step (float dtime);

	void handleParticleEvent(ClientEvent *event, Client *client,
			scene::ISceneManager* smgr, LocalPlayer *player);

	void addDiggingParticles(IGameDef* gamedef, scene::ISceneManager* smgr,
		LocalPlayer *player, v3s16 pos, const MapNode &n,
		const ContentFeatures &f);

	void addPunchingParticles(IGameDef* gamedef, scene::ISceneManager* smgr,
		LocalPlayer *player, v3s16 pos, const MapNode &n,
		const ContentFeatures &f);

	void addNodeParticle(IGameDef* gamedef, scene::ISceneManager* smgr,
		LocalPlayer *player, v3s16 pos, const MapNode &n,
		const ContentFeatures &f);

protected:
	void addParticle(Particle* toadd);

private:

	void stepParticles (float dtime);
	void stepSpawners (float dtime);

	void clearAll ();

	std::vector<Particle*> m_particles;
	std::map<u32, ParticleSpawner*> m_particle_spawners;

	ClientEnvironment* m_env;
	Mutex m_particle_list_lock;
	Mutex m_spawner_list_lock;
};

#endif
> 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.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 "inventory.h"
#include "serialization.h"
#include "debug.h"
#include <sstream>
#include "log.h"
#include "itemdef.h"
#include "util/strfnd.h"
#include "content_mapnode.h" // For loading legacy MaterialItems
#include "nameidmapping.h" // For loading legacy MaterialItems
#include "util/serialize.h"
#include "util/string.h"

/*
	ItemStack
*/

static content_t content_translate_from_19_to_internal(content_t c_from)
{
	for (const auto &tt : trans_table_19) {
		if(tt[1] == c_from) {
			return tt[0];
		}
	}
	return c_from;
}

ItemStack::ItemStack(const std::string &name_, u16 count_,
		u16 wear_, IItemDefManager *itemdef) :
	name(itemdef->getAlias(name_)),
	count(count_),
	wear(wear_)
{
	if (name.empty() || count == 0)
		clear();
	else if (itemdef->get(name).type == ITEM_TOOL)
		count = 1;
}

void ItemStack::serialize(std::ostream &os) const
{
	if (empty())
		return;

	// Check how many parts of the itemstring are needed
	int parts = 1;
	if(count != 1)
		parts = 2;
	if(wear != 0)
		parts = 3;
	if (!metadata.empty())
		parts = 4;

	os<<serializeJsonStringIfNeeded(name);
	if(parts >= 2)
		os<<" "<<count;
	if(parts >= 3)
		os<<" "<<wear;
	if (parts >= 4) {
		os << " ";
		metadata.serialize(os);
	}
}

void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
{
	clear();

	// Read name
	name = deSerializeJsonStringIfNeeded(is);

	// Skip space
	std::string tmp;
	std::getline(is, tmp, ' ');
	if(!tmp.empty())
		throw SerializationError("Unexpected text after item name");

	if(name == "MaterialItem")
	{
		// Obsoleted on 2011-07-30

		u16 material;
		is>>material;
		u16 materialcount;
		is>>materialcount;
		// Convert old materials
		if(material <= 0xff)
			material = content_translate_from_19_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.empty())
			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.empty())
			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;
			}

			count = stoi(count_str);

			// Read the wear
			std::string wear_str;
			std::getline(is, wear_str, ' ');
			if(wear_str.empty())
				break;

			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(ItemStack newitem, IItemDefManager *itemdef)
{
	// 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())
	{
		const u16 stackMax = newitem.getStackMax(itemdef);

		*this = newitem;

		// If the item fits fully, delete it
		if (count <= stackMax) {
			newitem.clear();
		} else { // Else the item does not fit fully. Return the rest.
			count = stackMax;
			newitem.remove(count);
		}
	}
	// 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(ItemStack newitem,
		ItemStack *restitem,
		IItemDefManager *itemdef) const
{

	// 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())
	{
		const u16 stackMax = newitem.getStackMax(itemdef);

		// If the item fits fully, delete it
		if (newitem.count <= stackMax) {
			newitem.clear();
		} else { // Else the item does not fit fully. Return the rest.
			newitem.remove(stackMax);
		}
	}
	// 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.
	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_itemdef(itemdef)
{
	clearItems();
}

void InventoryList::clearItems()
{
	m_items.clear();

	for (u32 i=0; i < m_size; i++) {
		m_items.emplace_back();
	}

	//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 (const auto &item : m_items) {
		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
		if (name == "end") {
			break;
		}

		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 (const auto &m_item : m_items) {
		if (!m_item.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 (auto 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;

			count -= i->count;
		}
	}
	return false;
}

ItemStack InventoryList::removeItem(const ItemStack &item)
{
	ItemStack removed;
	for (auto 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 (auto &m_list : m_lists) {
		delete m_list;
	}
	m_lists.clear();
}

void Inventory::clearContents()
{
	m_dirty = true;
	for (InventoryList *list : m_lists) {
		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 (InventoryList *list : other.m_lists) {
			m_lists.push_back(new InventoryList(*list));
		}
	}
	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 (InventoryList *list : m_lists) {
		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
		if (name == "end") {
			break;
		}

		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];
	}


	//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 (auto list : m_lists) {
		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