3 Copyright (C) 2010-2013 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 Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser 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"
27 #include "util/strfnd.h"
28 #include "content_mapnode.h" // For loading legacy MaterialItems
29 #include "nameidmapping.h" // For loading legacy MaterialItems
30 #include "util/serialize.h"
31 #include "util/string.h"
37 static content_t content_translate_from_19_to_internal(content_t c_from)
39 for (const auto &tt : trans_table_19) {
47 ItemStack::ItemStack(const std::string &name_, u16 count_,
48 u16 wear_, IItemDefManager *itemdef) :
49 name(itemdef->getAlias(name_)),
53 if (name.empty() || count == 0)
55 else if (itemdef->get(name).type == ITEM_TOOL)
59 void ItemStack::serialize(std::ostream &os, bool serialize_meta) const
64 // Check how many parts of the itemstring are needed
66 if (!metadata.empty())
73 os << serializeJsonStringIfNeeded(name);
81 metadata.serialize(os);
83 os << "<metadata size=" << metadata.size() << ">";
87 void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
92 name = deSerializeJsonStringIfNeeded(is);
96 std::getline(is, tmp, ' ');
98 throw SerializationError("Unexpected text after item name");
100 if(name == "MaterialItem")
102 // Obsoleted on 2011-07-30
108 // Convert old materials
110 material = content_translate_from_19_to_internal(material);
112 throw SerializationError("Too large material number");
113 // Convert old id to name
114 NameIdMapping legacy_nimap;
115 content_mapnode_get_name_id_mapping(&legacy_nimap);
116 legacy_nimap.getName(material, name);
118 name = "unknown_block";
120 name = itemdef->getAlias(name);
121 count = materialcount;
123 else if(name == "MaterialItem2")
125 // Obsoleted on 2011-11-16
132 throw SerializationError("Too large material number");
133 // Convert old id to name
134 NameIdMapping legacy_nimap;
135 content_mapnode_get_name_id_mapping(&legacy_nimap);
136 legacy_nimap.getName(material, name);
138 name = "unknown_block";
140 name = itemdef->getAlias(name);
141 count = materialcount;
143 else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
144 || name == "craft" || name == "CraftItem")
146 // Obsoleted on 2012-01-07
149 std::getline(is, all, '\n');
150 // First attempt to read inside ""
153 // If didn't skip to end, we have ""s
155 name = fnd.next("\"");
156 } else { // No luck, just read a word then
158 name = fnd.next(" ");
162 name = itemdef->getAlias(name);
163 count = stoi(trim(fnd.next("")));
167 else if(name == "MBOItem")
169 // Obsoleted on 2011-10-14
170 throw SerializationError("MBOItem not supported anymore");
172 else if(name == "tool" || name == "ToolItem")
174 // Obsoleted on 2012-01-07
177 std::getline(is, all, '\n');
178 // First attempt to read inside ""
181 // If didn't skip to end, we have ""s
183 name = fnd.next("\"");
184 } else { // No luck, just read a word then
186 name = fnd.next(" ");
192 name = itemdef->getAlias(name);
193 wear = stoi(trim(fnd.next("")));
197 do // This loop is just to allow "break;"
201 // Apply item aliases
203 name = itemdef->getAlias(name);
206 std::string count_str;
207 std::getline(is, count_str, ' ');
208 if (count_str.empty()) {
213 count = stoi(count_str);
216 std::string wear_str;
217 std::getline(is, wear_str, ' ');
221 wear = stoi(wear_str);
224 metadata.deSerialize(is);
226 // In case fields are added after metadata, skip space here:
227 //std::getline(is, tmp, ' ');
229 // throw SerializationError("Unexpected text after metadata");
234 if (name.empty() || count == 0)
236 else if (itemdef && itemdef->get(name).type == ITEM_TOOL)
240 void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
242 std::istringstream is(str, std::ios::binary);
243 deSerialize(is, itemdef);
246 std::string ItemStack::getItemString(bool include_meta) const
248 std::ostringstream os(std::ios::binary);
249 serialize(os, include_meta);
253 std::string ItemStack::getDescription(IItemDefManager *itemdef) const
255 std::string desc = metadata.getString("description");
257 desc = getDefinition(itemdef).description;
258 return desc.empty() ? name : desc;
262 ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef)
264 // If the item is empty or the position invalid, bail out
267 // nothing can be added trivially
269 // If this is an empty item, it's an easy job.
275 // If item name or metadata differs, bail out
276 else if (name != newitem.name
277 || metadata != newitem.metadata)
281 // If the item fits fully, add counter and delete it
282 else if(newitem.count <= freeSpace(itemdef))
287 // Else the item does not fit fully. Add all that fits and return
291 u16 freespace = freeSpace(itemdef);
293 newitem.remove(freespace);
299 bool ItemStack::itemFits(ItemStack newitem,
301 IItemDefManager *itemdef) const
304 // If the item is empty or the position invalid, bail out
307 // nothing can be added trivially
309 // If this is an empty item, it's an easy job.
314 // If item name or metadata differs, bail out
315 else if (name != newitem.name
316 || metadata != newitem.metadata)
320 // If the item fits fully, delete it
321 else if(newitem.count <= freeSpace(itemdef))
325 // Else the item does not fit fully. Return the rest.
328 u16 freespace = freeSpace(itemdef);
329 newitem.remove(freespace);
335 return newitem.empty();
338 ItemStack ItemStack::takeItem(u32 takecount)
340 if(takecount == 0 || count == 0)
343 ItemStack result = *this;
344 if(takecount >= count)
353 result.count = takecount;
358 ItemStack ItemStack::peekItem(u32 peekcount) const
360 if(peekcount == 0 || count == 0)
363 ItemStack result = *this;
364 if(peekcount < count)
365 result.count = peekcount;
373 InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef):
381 void InventoryList::clearItems()
385 for (u32 i=0; i < m_size; i++) {
386 m_items.emplace_back();
392 void InventoryList::setSize(u32 newsize)
394 if (newsize == m_items.size())
397 m_items.resize(newsize);
402 void InventoryList::setWidth(u32 newwidth)
408 void InventoryList::setName(const std::string &name)
414 void InventoryList::serialize(std::ostream &os, bool incremental) const
416 //os.imbue(std::locale("C"));
418 os<<"Width "<<m_width<<"\n";
420 for (const auto &item : m_items) {
427 // TODO: Implement this:
428 // if (!incremental || item.checkModified())
433 os<<"EndInventoryList\n";
436 void InventoryList::deSerialize(std::istream &is)
438 //is.imbue(std::locale("C"));
446 std::getline(is, line, '\n');
448 std::istringstream iss(line);
449 //iss.imbue(std::locale("C"));
452 std::getline(iss, name, ' ');
454 if (name == "EndInventoryList" || name == "end") {
455 // If partial incremental: Clear leftover items (should not happen!)
456 for (size_t i = item_i; i < m_items.size(); ++i)
461 if (name == "Width") {
464 throw SerializationError("incorrect width property");
466 else if(name == "Item")
468 if(item_i > getSize() - 1)
469 throw SerializationError("too many items");
471 item.deSerialize(iss, m_itemdef);
472 m_items[item_i++] = item;
474 else if(name == "Empty")
476 if(item_i > getSize() - 1)
477 throw SerializationError("too many items");
478 m_items[item_i++].clear();
479 } else if (name == "Keep") {
480 ++item_i; // Unmodified item
484 // Contents given to deSerialize() were not terminated properly: throw error.
486 std::ostringstream ss;
487 ss << "Malformatted inventory list. list="
488 << m_name << ", read " << item_i << " of " << getSize()
489 << " ItemStacks." << std::endl;
490 throw SerializationError(ss.str());
493 InventoryList::InventoryList(const InventoryList &other)
498 InventoryList & InventoryList::operator = (const InventoryList &other)
500 m_items = other.m_items;
501 m_size = other.m_size;
502 m_width = other.m_width;
503 m_name = other.m_name;
504 m_itemdef = other.m_itemdef;
510 bool InventoryList::operator == (const InventoryList &other) const
512 if(m_size != other.m_size)
514 if(m_width != other.m_width)
516 if(m_name != other.m_name)
518 for (u32 i = 0; i < m_items.size(); i++)
519 if (m_items[i] != other.m_items[i])
525 const std::string &InventoryList::getName() const
530 u32 InventoryList::getSize() const
532 return m_items.size();
535 u32 InventoryList::getWidth() const
540 u32 InventoryList::getUsedSlots() const
543 for (const auto &m_item : m_items) {
550 u32 InventoryList::getFreeSlots() const
552 return getSize() - getUsedSlots();
555 const ItemStack& InventoryList::getItem(u32 i) const
557 assert(i < m_size); // Pre-condition
561 ItemStack& InventoryList::getItem(u32 i)
563 assert(i < m_size); // Pre-condition
567 ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
569 if(i >= m_items.size())
572 ItemStack olditem = m_items[i];
573 m_items[i] = newitem;
578 void InventoryList::deleteItem(u32 i)
580 assert(i < m_items.size()); // Pre-condition
585 ItemStack InventoryList::addItem(const ItemStack &newitem_)
587 ItemStack newitem = newitem_;
593 First try to find if it could be added to some existing items
595 for(u32 i=0; i<m_items.size(); i++)
597 // Ignore empty slots
598 if(m_items[i].empty())
601 newitem = addItem(i, newitem);
603 return newitem; // All was eaten
607 Then try to add it to empty slots
609 for(u32 i=0; i<m_items.size(); i++)
611 // Ignore unempty slots
612 if(!m_items[i].empty())
615 newitem = addItem(i, newitem);
617 return newitem; // All was eaten
624 ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
626 if(i >= m_items.size())
629 ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
630 if (leftover != newitem)
635 bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
636 ItemStack *restitem) const
638 if(i >= m_items.size())
645 return m_items[i].itemFits(newitem, restitem, m_itemdef);
648 bool InventoryList::roomForItem(const ItemStack &item_) const
650 ItemStack item = item_;
652 for(u32 i=0; i<m_items.size(); i++)
654 if(itemFits(i, item, &leftover))
661 bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const
663 u32 count = item.count;
667 for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
670 if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) {
671 if (i->count >= count)
680 ItemStack InventoryList::removeItem(const ItemStack &item)
683 for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
684 if (i->name == item.name) {
685 u32 still_to_remove = item.count - removed.count;
686 ItemStack leftover = removed.addItem(i->takeItem(still_to_remove),
688 // Allow oversized stacks
689 removed.count += leftover.count;
691 if (removed.count == item.count)
695 if (!removed.empty())
700 ItemStack InventoryList::takeItem(u32 i, u32 takecount)
702 if(i >= m_items.size())
705 ItemStack taken = m_items[i].takeItem(takecount);
711 void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
713 // Take item from source list
716 item1 = changeItem(i, ItemStack());
718 item1 = takeItem(i, count);
724 leftover = dest->addItem(item1);
726 if (!leftover.empty()) {
727 // Add the remaining part back to the source item
728 addItem(i, leftover);
732 u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
733 u32 count, bool swap_if_needed, bool *did_swap)
735 if(this == dest && i == dest_i)
738 // Take item from source list
741 item1 = changeItem(i, ItemStack());
743 item1 = takeItem(i, count);
748 // Try to add the item to destination list
749 u32 oldcount = item1.count;
750 item1 = dest->addItem(dest_i, item1);
752 // If something is returned, the item was not fully added
755 // If olditem is returned, nothing was added.
756 bool nothing_added = (item1.count == oldcount);
758 // If something else is returned, part of the item was left unadded.
759 // Add the other part back to the source item
762 // If olditem is returned, nothing was added.
764 if (nothing_added && swap_if_needed) {
765 // Tell that we swapped
766 if (did_swap != NULL) {
769 // Take item from source list
770 item1 = changeItem(i, ItemStack());
771 // Adding was not possible, swap the items.
772 ItemStack item2 = dest->changeItem(dest_i, item1);
773 // Put item from destination list to the source list
774 changeItem(i, item2);
777 return (oldcount - item1.count);
784 Inventory::~Inventory()
789 void Inventory::clear()
791 for (auto &m_list : m_lists) {
798 Inventory::Inventory(IItemDefManager *itemdef)
804 Inventory::Inventory(const Inventory &other)
809 Inventory & Inventory::operator = (const Inventory &other)
811 // Gracefully handle self assignment
815 m_itemdef = other.m_itemdef;
816 for (InventoryList *list : other.m_lists) {
817 m_lists.push_back(new InventoryList(*list));
824 bool Inventory::operator == (const Inventory &other) const
826 if(m_lists.size() != other.m_lists.size())
829 for(u32 i=0; i<m_lists.size(); i++)
831 if(*m_lists[i] != *other.m_lists[i])
837 void Inventory::serialize(std::ostream &os, bool incremental) const
839 //std::cout << "Serialize " << (int)incremental << ", n=" << m_lists.size() << std::endl;
840 for (const InventoryList *list : m_lists) {
841 if (!incremental || list->checkModified()) {
842 os << "List " << list->getName() << " " << list->getSize() << "\n";
843 list->serialize(os, incremental);
845 os << "KeepList " << list->getName() << "\n";
849 os<<"EndInventory\n";
852 void Inventory::deSerialize(std::istream &is)
854 std::vector<InventoryList *> new_lists;
855 new_lists.reserve(m_lists.size());
859 std::getline(is, line, '\n');
861 std::istringstream iss(line);
864 std::getline(iss, name, ' ');
866 if (name == "EndInventory" || name == "end") {
867 // Remove all lists that were not sent
868 for (auto &list : m_lists) {
869 if (std::find(new_lists.begin(), new_lists.end(), list) != new_lists.end())
876 m_lists.erase(std::remove(m_lists.begin(), m_lists.end(),
877 nullptr), m_lists.end());
881 if (name == "List") {
882 std::string listname;
885 std::getline(iss, listname, ' ');
888 InventoryList *list = getList(listname);
889 bool create_new = !list;
891 list = new InventoryList(listname, listsize, m_itemdef);
893 list->setSize(listsize);
894 list->deSerialize(is);
896 new_lists.push_back(list);
898 m_lists.push_back(list);
900 } else if (name == "KeepList") {
901 // Incrementally sent list
902 std::string listname;
903 std::getline(iss, listname, ' ');
905 InventoryList *list = getList(listname);
907 new_lists.push_back(list);
909 errorstream << "Inventory::deSerialize(): Tried to keep list '" <<
910 listname << "' which is non-existent." << std::endl;
913 // Any additional fields will throw errors when received by a client
914 // older than PROTOCOL_VERSION 38
917 // Contents given to deSerialize() were not terminated properly: throw error.
919 std::ostringstream ss;
920 ss << "Malformatted inventory (damaged?). "
921 << m_lists.size() << " lists read." << std::endl;
922 throw SerializationError(ss.str());
925 InventoryList * Inventory::addList(const std::string &name, u32 size)
928 s32 i = getListIndex(name);
931 if(m_lists[i]->getSize() != size)
934 m_lists[i] = new InventoryList(name, size, m_itemdef);
935 m_lists[i]->setModified();
941 //don't create list with invalid name
942 if (name.find(' ') != std::string::npos)
945 InventoryList *list = new InventoryList(name, size, m_itemdef);
947 m_lists.push_back(list);
951 InventoryList * Inventory::getList(const std::string &name)
953 s32 i = getListIndex(name);
959 std::vector<const InventoryList*> Inventory::getLists()
961 std::vector<const InventoryList*> lists;
962 for (auto list : m_lists) {
963 lists.push_back(list);
968 bool Inventory::deleteList(const std::string &name)
970 s32 i = getListIndex(name);
976 m_lists.erase(m_lists.begin() + i);
980 const InventoryList * Inventory::getList(const std::string &name) const
982 s32 i = getListIndex(name);
988 const s32 Inventory::getListIndex(const std::string &name) const
990 for(u32 i=0; i<m_lists.size(); i++)
992 if(m_lists[i]->getName() == name)