3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "inventory.h"
21 #include "serialization.h"
28 #include "content_mapnode.h" // For loading legacy MaterialItems
29 #include "nameidmapping.h" // For loading legacy MaterialItems
35 static content_t content_translate_from_19_to_internal(content_t c_from)
37 for(u32 i=0; i<sizeof(trans_table_19)/sizeof(trans_table_19[0]); i++)
39 if(trans_table_19[i][1] == c_from)
41 return trans_table_19[i][0];
47 // If the string contains spaces, quotes or control characters, encodes as JSON.
48 // Else returns the string unmodified.
49 static std::string serializeJsonStringIfNeeded(const std::string &s)
51 for(size_t i = 0; i < s.size(); ++i)
53 if(s[i] <= 0x1f || s[i] >= 0x7f || s[i] == ' ' || s[i] == '\"')
54 return serializeJsonString(s);
59 // Parses a string serialized by serializeJsonStringIfNeeded.
60 static std::string deSerializeJsonStringIfNeeded(std::istream &is)
62 std::ostringstream tmp_os;
63 bool expect_initial_quote = true;
65 bool was_backslash = false;
71 if(expect_initial_quote && c == '"')
80 was_backslash = false;
84 break; // Found end of string
99 expect_initial_quote = false;
103 std::istringstream tmp_is(tmp_os.str(), std::ios::binary);
104 return deSerializeJsonString(tmp_is);
111 ItemStack::ItemStack(std::string name_, u16 count_,
112 u16 wear_, std::string metadata_,
113 IItemDefManager *itemdef)
115 name = itemdef->getAlias(name_);
118 metadata = metadata_;
120 if(name.empty() || count == 0)
122 else if(itemdef->get(name).type == ITEM_TOOL)
126 void ItemStack::serialize(std::ostream &os) const
128 DSTACK(__FUNCTION_NAME);
133 // Check how many parts of the itemstring are needed
142 os<<serializeJsonStringIfNeeded(name);
148 os<<" "<<serializeJsonStringIfNeeded(metadata);
151 void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
153 DSTACK(__FUNCTION_NAME);
158 name = deSerializeJsonStringIfNeeded(is);
162 std::getline(is, tmp, ' ');
164 throw SerializationError("Unexpected text after item name");
166 if(name == "MaterialItem")
168 // Obsoleted on 2011-07-30
174 // Convert old materials
176 material = content_translate_from_19_to_internal(material);
177 if(material > MAX_CONTENT)
178 throw SerializationError("Too large material number");
179 // Convert old id to name
180 NameIdMapping legacy_nimap;
181 content_mapnode_get_name_id_mapping(&legacy_nimap);
182 legacy_nimap.getName(material, name);
184 name = "unknown_block";
185 name = itemdef->getAlias(name);
186 count = materialcount;
188 else if(name == "MaterialItem2")
190 // Obsoleted on 2011-11-16
196 if(material > MAX_CONTENT)
197 throw SerializationError("Too large material number");
198 // Convert old id to name
199 NameIdMapping legacy_nimap;
200 content_mapnode_get_name_id_mapping(&legacy_nimap);
201 legacy_nimap.getName(material, name);
203 name = "unknown_block";
204 name = itemdef->getAlias(name);
205 count = materialcount;
207 else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
208 || name == "craft" || name == "CraftItem")
210 // Obsoleted on 2012-01-07
213 std::getline(is, all, '\n');
214 // First attempt to read inside ""
217 // If didn't skip to end, we have ""s
219 name = fnd.next("\"");
220 } else { // No luck, just read a word then
222 name = fnd.next(" ");
225 name = itemdef->getAlias(name);
226 count = stoi(trim(fnd.next("")));
230 else if(name == "MBOItem")
232 // Obsoleted on 2011-10-14
233 throw SerializationError("MBOItem not supported anymore");
235 else if(name == "tool" || name == "ToolItem")
237 // Obsoleted on 2012-01-07
240 std::getline(is, all, '\n');
241 // First attempt to read inside ""
244 // If didn't skip to end, we have ""s
246 name = fnd.next("\"");
247 } else { // No luck, just read a word then
249 name = fnd.next(" ");
254 name = itemdef->getAlias(name);
255 wear = stoi(trim(fnd.next("")));
259 do // This loop is just to allow "break;"
263 // Apply item aliases
264 name = itemdef->getAlias(name);
267 std::string count_str;
268 std::getline(is, count_str, ' ');
269 if(count_str.empty())
275 count = stoi(count_str);
278 std::string wear_str;
279 std::getline(is, wear_str, ' ');
283 wear = stoi(wear_str);
286 metadata = deSerializeJsonStringIfNeeded(is);
288 // In case fields are added after metadata, skip space here:
289 //std::getline(is, tmp, ' ');
291 // throw SerializationError("Unexpected text after metadata");
296 if(name.empty() || count == 0)
298 else if(itemdef->get(name).type == ITEM_TOOL)
302 void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
304 std::istringstream is(str, std::ios::binary);
305 deSerialize(is, itemdef);
308 std::string ItemStack::getItemString() const
311 std::ostringstream os(std::ios::binary);
316 ItemStack ItemStack::addItem(const ItemStack &newitem_,
317 IItemDefManager *itemdef)
319 ItemStack newitem = newitem_;
321 // If the item is empty or the position invalid, bail out
324 // nothing can be added trivially
326 // If this is an empty item, it's an easy job.
332 // If item name differs, bail out
333 else if(name != newitem.name)
337 // If the item fits fully, add counter and delete it
338 else if(newitem.count <= freeSpace(itemdef))
343 // Else the item does not fit fully. Add all that fits and return
347 u16 freespace = freeSpace(itemdef);
349 newitem.remove(freespace);
355 bool ItemStack::itemFits(const ItemStack &newitem_,
357 IItemDefManager *itemdef) const
359 ItemStack newitem = newitem_;
361 // If the item is empty or the position invalid, bail out
364 // nothing can be added trivially
366 // If this is an empty item, it's an easy job.
371 // If item name differs, bail out
372 else if(name != newitem.name)
376 // If the item fits fully, delete it
377 else if(newitem.count <= freeSpace(itemdef))
381 // Else the item does not fit fully. Return the rest.
385 u16 freespace = freeSpace(itemdef);
386 newitem.remove(freespace);
391 return newitem.empty();
394 ItemStack ItemStack::takeItem(u32 takecount)
396 if(takecount == 0 || count == 0)
399 ItemStack result = *this;
400 if(takecount >= count)
409 result.count = takecount;
414 ItemStack ItemStack::peekItem(u32 peekcount) const
416 if(peekcount == 0 || count == 0)
419 ItemStack result = *this;
420 if(peekcount < count)
421 result.count = peekcount;
429 InventoryList::InventoryList(std::string name, u32 size, IItemDefManager *itemdef)
438 InventoryList::~InventoryList()
442 void InventoryList::clearItems()
446 for(u32 i=0; i<m_size; i++)
448 m_items.push_back(ItemStack());
454 void InventoryList::setSize(u32 newsize)
456 if(newsize != m_items.size())
457 m_items.resize(newsize);
461 void InventoryList::serialize(std::ostream &os) const
463 //os.imbue(std::locale("C"));
465 for(u32 i=0; i<m_items.size(); i++)
467 const ItemStack &item = m_items[i];
480 os<<"EndInventoryList\n";
483 void InventoryList::deSerialize(std::istream &is)
485 //is.imbue(std::locale("C"));
493 std::getline(is, line, '\n');
495 std::istringstream iss(line);
496 //iss.imbue(std::locale("C"));
499 std::getline(iss, name, ' ');
501 if(name == "EndInventoryList")
505 // This is a temporary backwards compatibility fix
506 else if(name == "end")
510 else if(name == "Item")
512 if(item_i > getSize() - 1)
513 throw SerializationError("too many items");
515 item.deSerialize(iss, m_itemdef);
516 m_items[item_i++] = item;
518 else if(name == "Empty")
520 if(item_i > getSize() - 1)
521 throw SerializationError("too many items");
522 m_items[item_i++].clear();
526 throw SerializationError("Unknown inventory identifier");
531 InventoryList::InventoryList(const InventoryList &other)
536 InventoryList & InventoryList::operator = (const InventoryList &other)
538 m_items = other.m_items;
539 m_size = other.m_size;
540 m_name = other.m_name;
541 m_itemdef = other.m_itemdef;
547 const std::string &InventoryList::getName() const
552 u32 InventoryList::getSize() const
554 return m_items.size();
557 u32 InventoryList::getUsedSlots() const
560 for(u32 i=0; i<m_items.size(); i++)
562 if(!m_items[i].empty())
568 u32 InventoryList::getFreeSlots() const
570 return getSize() - getUsedSlots();
573 const ItemStack& InventoryList::getItem(u32 i) const
579 ItemStack& InventoryList::getItem(u32 i)
585 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
587 if(i >= m_items.size())
590 ItemStack olditem = m_items[i];
591 m_items[i] = newitem;
596 void InventoryList::deleteItem(u32 i)
598 assert(i < m_items.size());
602 ItemStack InventoryList::addItem(const ItemStack &newitem_)
604 ItemStack newitem = newitem_;
610 First try to find if it could be added to some existing items
612 for(u32 i=0; i<m_items.size(); i++)
614 // Ignore empty slots
615 if(m_items[i].empty())
618 newitem = addItem(i, newitem);
620 return newitem; // All was eaten
624 Then try to add it to empty slots
626 for(u32 i=0; i<m_items.size(); i++)
628 // Ignore unempty slots
629 if(!m_items[i].empty())
632 newitem = addItem(i, newitem);
634 return newitem; // All was eaten
641 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
643 if(i >= m_items.size())
646 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
647 //if(leftover != newitem)
652 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
653 ItemStack *restitem) const
655 if(i >= m_items.size())
662 return m_items[i].itemFits(newitem, restitem, m_itemdef);
665 bool InventoryList::roomForItem(const ItemStack &item_) const
667 ItemStack item = item_;
669 for(u32 i=0; i<m_items.size(); i++)
671 if(itemFits(i, item, &leftover))
678 bool InventoryList::containsItem(const ItemStack &item) const
680 u32 count = item.count;
683 for(std::vector<ItemStack>::const_reverse_iterator
684 i = m_items.rbegin();
685 i != m_items.rend(); i++)
689 if(i->name == item.name)
691 if(i->count >= count)
700 ItemStack InventoryList::removeItem(const ItemStack &item)
703 for(std::vector<ItemStack>::reverse_iterator
704 i = m_items.rbegin();
705 i != m_items.rend(); i++)
707 if(i->name == item.name)
709 u32 still_to_remove = item.count - removed.count;
710 removed.addItem(i->takeItem(still_to_remove), m_itemdef);
711 if(removed.count == item.count)
718 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
720 if(i >= m_items.size())
723 ItemStack taken = m_items[i].takeItem(takecount);
729 ItemStack InventoryList::peekItem(u32 i, u32 peekcount) const
731 if(i >= m_items.size())
734 return m_items[i].peekItem(peekcount);
737 void InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i, u32 count)
739 if(this == dest && i == dest_i)
742 // Take item from source list
745 item1 = changeItem(i, ItemStack());
747 item1 = takeItem(i, count);
752 // Try to add the item to destination list
753 u32 oldcount = item1.count;
754 item1 = dest->addItem(dest_i, item1);
756 // If something is returned, the item was not fully added
759 // If olditem is returned, nothing was added.
760 bool nothing_added = (item1.count == oldcount);
762 // If something else is returned, part of the item was left unadded.
763 // Add the other part back to the source item
766 // If olditem is returned, nothing was added.
770 // Take item from source list
771 item1 = changeItem(i, ItemStack());
772 // Adding was not possible, swap the items.
773 ItemStack item2 = dest->changeItem(dest_i, item1);
774 // Put item from destination list to the source list
775 changeItem(i, item2);
784 Inventory::~Inventory()
789 void Inventory::clear()
791 for(u32 i=0; i<m_lists.size(); i++)
798 Inventory::Inventory(IItemDefManager *itemdef)
803 Inventory::Inventory(const Inventory &other)
808 Inventory & Inventory::operator = (const Inventory &other)
810 // Gracefully handle self assignment
814 m_itemdef = other.m_itemdef;
815 for(u32 i=0; i<other.m_lists.size(); i++)
817 m_lists.push_back(new InventoryList(*other.m_lists[i]));
823 void Inventory::serialize(std::ostream &os) const
825 for(u32 i=0; i<m_lists.size(); i++)
827 InventoryList *list = m_lists[i];
828 os<<"List "<<list->getName()<<" "<<list->getSize()<<"\n";
832 os<<"EndInventory\n";
835 void Inventory::deSerialize(std::istream &is)
842 std::getline(is, line, '\n');
844 std::istringstream iss(line);
847 std::getline(iss, name, ' ');
849 if(name == "EndInventory")
853 // This is a temporary backwards compatibility fix
854 else if(name == "end")
858 else if(name == "List")
860 std::string listname;
863 std::getline(iss, listname, ' ');
866 InventoryList *list = new InventoryList(listname, listsize, m_itemdef);
867 list->deSerialize(is);
869 m_lists.push_back(list);
873 throw SerializationError("Unknown inventory identifier");
878 InventoryList * Inventory::addList(const std::string &name, u32 size)
880 s32 i = getListIndex(name);
883 if(m_lists[i]->getSize() != size)
886 m_lists[i] = new InventoryList(name, size, m_itemdef);
892 InventoryList *list = new InventoryList(name, size, m_itemdef);
893 m_lists.push_back(list);
898 InventoryList * Inventory::getList(const std::string &name)
900 s32 i = getListIndex(name);
906 bool Inventory::deleteList(const std::string &name)
908 s32 i = getListIndex(name);
912 m_lists.erase(m_lists.begin() + i);
916 const InventoryList * Inventory::getList(const std::string &name) const
918 s32 i = getListIndex(name);
924 const s32 Inventory::getListIndex(const std::string &name) const
926 for(u32 i=0; i<m_lists.size(); i++)
928 if(m_lists[i]->getName() == name)