inventory.cpp 21 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "inventory.h"
  17. #include "serialization.h"
  18. #include "debug.h"
  19. #include <algorithm>
  20. #include <sstream>
  21. #include "log.h"
  22. #include "itemdef.h"
  23. #include "util/strfnd.h"
  24. #include "content_mapnode.h" // For loading legacy MaterialItems
  25. #include "nameidmapping.h" // For loading legacy MaterialItems
  26. #include "util/serialize.h"
  27. #include "util/string.h"
  28. /*
  29. ItemStack
  30. */
  31. static content_t content_translate_from_19_to_internal(content_t c_from)
  32. {
  33. for (const auto &tt : trans_table_19) {
  34. if(tt[1] == c_from) {
  35. return tt[0];
  36. }
  37. }
  38. return c_from;
  39. }
  40. ItemStack::ItemStack(const std::string &name_, u16 count_,
  41. u16 wear_, IItemDefManager *itemdef) :
  42. name(itemdef->getAlias(name_)),
  43. count(count_),
  44. wear(wear_)
  45. {
  46. if (name.empty() || count == 0)
  47. clear();
  48. else if (itemdef->get(name).type == ITEM_TOOL)
  49. count = 1;
  50. }
  51. void ItemStack::serialize(std::ostream &os, bool serialize_meta) const
  52. {
  53. if (empty())
  54. return;
  55. // Check how many parts of the itemstring are needed
  56. int parts = 1;
  57. if (!metadata.empty())
  58. parts = 4;
  59. else if (wear != 0)
  60. parts = 3;
  61. else if (count != 1)
  62. parts = 2;
  63. os << serializeJsonStringIfNeeded(name);
  64. if (parts >= 2)
  65. os << " " << count;
  66. if (parts >= 3)
  67. os << " " << wear;
  68. if (parts >= 4) {
  69. os << " ";
  70. if (serialize_meta)
  71. metadata.serialize(os);
  72. else
  73. os << "<metadata size=" << metadata.size() << ">";
  74. }
  75. }
  76. void ItemStack::deSerialize(std::istream &is, IItemDefManager *itemdef)
  77. {
  78. clear();
  79. // Read name
  80. name = deSerializeJsonStringIfNeeded(is);
  81. // Skip space
  82. std::string tmp;
  83. std::getline(is, tmp, ' ');
  84. if(!tmp.empty())
  85. throw SerializationError("Unexpected text after item name");
  86. if(name == "MaterialItem")
  87. {
  88. // Obsoleted on 2011-07-30
  89. u16 material;
  90. is>>material;
  91. u16 materialcount;
  92. is>>materialcount;
  93. // Convert old materials
  94. if(material <= 0xff)
  95. material = content_translate_from_19_to_internal(material);
  96. if(material > 0xfff)
  97. throw SerializationError("Too large material number");
  98. // Convert old id to name
  99. NameIdMapping legacy_nimap;
  100. content_mapnode_get_name_id_mapping(&legacy_nimap);
  101. legacy_nimap.getName(material, name);
  102. if(name.empty())
  103. name = "unknown_block";
  104. if (itemdef)
  105. name = itemdef->getAlias(name);
  106. count = materialcount;
  107. }
  108. else if(name == "MaterialItem2")
  109. {
  110. // Obsoleted on 2011-11-16
  111. u16 material;
  112. is>>material;
  113. u16 materialcount;
  114. is>>materialcount;
  115. if(material > 0xfff)
  116. throw SerializationError("Too large material number");
  117. // Convert old id to name
  118. NameIdMapping legacy_nimap;
  119. content_mapnode_get_name_id_mapping(&legacy_nimap);
  120. legacy_nimap.getName(material, name);
  121. if(name.empty())
  122. name = "unknown_block";
  123. if (itemdef)
  124. name = itemdef->getAlias(name);
  125. count = materialcount;
  126. }
  127. else if(name == "node" || name == "NodeItem" || name == "MaterialItem3"
  128. || name == "craft" || name == "CraftItem")
  129. {
  130. // Obsoleted on 2012-01-07
  131. std::string all;
  132. std::getline(is, all, '\n');
  133. // First attempt to read inside ""
  134. Strfnd fnd(all);
  135. fnd.next("\"");
  136. // If didn't skip to end, we have ""s
  137. if(!fnd.at_end()){
  138. name = fnd.next("\"");
  139. } else { // No luck, just read a word then
  140. fnd.start(all);
  141. name = fnd.next(" ");
  142. }
  143. fnd.skip_over(" ");
  144. if (itemdef)
  145. name = itemdef->getAlias(name);
  146. count = stoi(trim(fnd.next("")));
  147. if(count == 0)
  148. count = 1;
  149. }
  150. else if(name == "MBOItem")
  151. {
  152. // Obsoleted on 2011-10-14
  153. throw SerializationError("MBOItem not supported anymore");
  154. }
  155. else if(name == "tool" || name == "ToolItem")
  156. {
  157. // Obsoleted on 2012-01-07
  158. std::string all;
  159. std::getline(is, all, '\n');
  160. // First attempt to read inside ""
  161. Strfnd fnd(all);
  162. fnd.next("\"");
  163. // If didn't skip to end, we have ""s
  164. if(!fnd.at_end()){
  165. name = fnd.next("\"");
  166. } else { // No luck, just read a word then
  167. fnd.start(all);
  168. name = fnd.next(" ");
  169. }
  170. count = 1;
  171. // Then read wear
  172. fnd.skip_over(" ");
  173. if (itemdef)
  174. name = itemdef->getAlias(name);
  175. wear = stoi(trim(fnd.next("")));
  176. }
  177. else
  178. {
  179. do // This loop is just to allow "break;"
  180. {
  181. // The real thing
  182. // Apply item aliases
  183. if (itemdef)
  184. name = itemdef->getAlias(name);
  185. // Read the count
  186. std::string count_str;
  187. std::getline(is, count_str, ' ');
  188. if (count_str.empty()) {
  189. count = 1;
  190. break;
  191. }
  192. count = stoi(count_str);
  193. // Read the wear
  194. std::string wear_str;
  195. std::getline(is, wear_str, ' ');
  196. if(wear_str.empty())
  197. break;
  198. wear = stoi(wear_str);
  199. // Read metadata
  200. metadata.deSerialize(is);
  201. // In case fields are added after metadata, skip space here:
  202. //std::getline(is, tmp, ' ');
  203. //if(!tmp.empty())
  204. // throw SerializationError("Unexpected text after metadata");
  205. } while(false);
  206. }
  207. if (name.empty() || count == 0)
  208. clear();
  209. else if (itemdef && itemdef->get(name).type == ITEM_TOOL)
  210. count = 1;
  211. }
  212. void ItemStack::deSerialize(const std::string &str, IItemDefManager *itemdef)
  213. {
  214. std::istringstream is(str, std::ios::binary);
  215. deSerialize(is, itemdef);
  216. }
  217. std::string ItemStack::getItemString(bool include_meta) const
  218. {
  219. std::ostringstream os(std::ios::binary);
  220. serialize(os, include_meta);
  221. return os.str();
  222. }
  223. std::string ItemStack::getDescription(IItemDefManager *itemdef) const
  224. {
  225. std::string desc = metadata.getString("description");
  226. if (desc.empty())
  227. desc = getDefinition(itemdef).description;
  228. return desc.empty() ? name : desc;
  229. }
  230. std::string ItemStack::getShortDescription(IItemDefManager *itemdef) const
  231. {
  232. std::string desc = metadata.getString("short_description");
  233. if (desc.empty())
  234. desc = getDefinition(itemdef).short_description;
  235. if (!desc.empty())
  236. return desc;
  237. // no short_description because of old server version or modified builtin
  238. // return first line of description
  239. std::stringstream sstr(getDescription(itemdef));
  240. std::getline(sstr, desc, '\n');
  241. return desc;
  242. }
  243. ItemStack ItemStack::addItem(ItemStack newitem, IItemDefManager *itemdef)
  244. {
  245. // If the item is empty or the position invalid, bail out
  246. if(newitem.empty())
  247. {
  248. // nothing can be added trivially
  249. }
  250. // If this is an empty item, it's an easy job.
  251. else if(empty())
  252. {
  253. *this = newitem;
  254. newitem.clear();
  255. }
  256. // If item name or metadata differs, bail out
  257. else if (name != newitem.name
  258. || metadata != newitem.metadata)
  259. {
  260. // cannot be added
  261. }
  262. // If the item fits fully, add counter and delete it
  263. else if(newitem.count <= freeSpace(itemdef))
  264. {
  265. add(newitem.count);
  266. newitem.clear();
  267. }
  268. // Else the item does not fit fully. Add all that fits and return
  269. // the rest.
  270. else
  271. {
  272. u16 freespace = freeSpace(itemdef);
  273. add(freespace);
  274. newitem.remove(freespace);
  275. }
  276. return newitem;
  277. }
  278. bool ItemStack::itemFits(ItemStack newitem,
  279. ItemStack *restitem,
  280. IItemDefManager *itemdef) const
  281. {
  282. // If the item is empty or the position invalid, bail out
  283. if(newitem.empty())
  284. {
  285. // nothing can be added trivially
  286. }
  287. // If this is an empty item, it's an easy job.
  288. else if(empty())
  289. {
  290. newitem.clear();
  291. }
  292. // If item name or metadata differs, bail out
  293. else if (name != newitem.name
  294. || metadata != newitem.metadata)
  295. {
  296. // cannot be added
  297. }
  298. // If the item fits fully, delete it
  299. else if(newitem.count <= freeSpace(itemdef))
  300. {
  301. newitem.clear();
  302. }
  303. // Else the item does not fit fully. Return the rest.
  304. else
  305. {
  306. u16 freespace = freeSpace(itemdef);
  307. newitem.remove(freespace);
  308. }
  309. if(restitem)
  310. *restitem = newitem;
  311. return newitem.empty();
  312. }
  313. ItemStack ItemStack::takeItem(u32 takecount)
  314. {
  315. if(takecount == 0 || count == 0)
  316. return ItemStack();
  317. ItemStack result = *this;
  318. if(takecount >= count)
  319. {
  320. // Take all
  321. clear();
  322. }
  323. else
  324. {
  325. // Take part
  326. remove(takecount);
  327. result.count = takecount;
  328. }
  329. return result;
  330. }
  331. ItemStack ItemStack::peekItem(u32 peekcount) const
  332. {
  333. if(peekcount == 0 || count == 0)
  334. return ItemStack();
  335. ItemStack result = *this;
  336. if(peekcount < count)
  337. result.count = peekcount;
  338. return result;
  339. }
  340. /*
  341. Inventory
  342. */
  343. InventoryList::InventoryList(const std::string &name, u32 size, IItemDefManager *itemdef):
  344. m_name(name),
  345. m_size(size),
  346. m_itemdef(itemdef)
  347. {
  348. clearItems();
  349. }
  350. void InventoryList::clearItems()
  351. {
  352. m_items.clear();
  353. for (u32 i=0; i < m_size; i++) {
  354. m_items.emplace_back();
  355. }
  356. setModified();
  357. }
  358. void InventoryList::setSize(u32 newsize)
  359. {
  360. if (newsize == m_items.size())
  361. return;
  362. m_items.resize(newsize);
  363. m_size = newsize;
  364. setModified();
  365. }
  366. void InventoryList::setWidth(u32 newwidth)
  367. {
  368. m_width = newwidth;
  369. setModified();
  370. }
  371. void InventoryList::setName(const std::string &name)
  372. {
  373. m_name = name;
  374. setModified();
  375. }
  376. void InventoryList::serialize(std::ostream &os, bool incremental) const
  377. {
  378. //os.imbue(std::locale("C"));
  379. os<<"Width "<<m_width<<"\n";
  380. for (const auto &item : m_items) {
  381. if (item.empty()) {
  382. os<<"Empty";
  383. } else {
  384. os<<"Item ";
  385. item.serialize(os);
  386. }
  387. // TODO: Implement this:
  388. // if (!incremental || item.checkModified())
  389. // os << "Keep";
  390. os<<"\n";
  391. }
  392. os<<"EndInventoryList\n";
  393. }
  394. void InventoryList::deSerialize(std::istream &is)
  395. {
  396. //is.imbue(std::locale("C"));
  397. setModified();
  398. u32 item_i = 0;
  399. m_width = 0;
  400. while (is.good()) {
  401. std::string line;
  402. std::getline(is, line, '\n');
  403. std::istringstream iss(line);
  404. std::string name;
  405. std::getline(iss, name, ' ');
  406. if (name == "EndInventoryList" || name == "end") {
  407. // If partial incremental: Clear leftover items (should not happen!)
  408. for (size_t i = item_i; i < m_items.size(); ++i)
  409. m_items[i].clear();
  410. return;
  411. }
  412. if (name == "Width") {
  413. iss >> m_width;
  414. if (iss.fail())
  415. throw SerializationError("incorrect width property");
  416. }
  417. else if(name == "Item")
  418. {
  419. if(item_i > getSize() - 1)
  420. throw SerializationError("too many items");
  421. ItemStack item;
  422. item.deSerialize(iss, m_itemdef);
  423. m_items[item_i++] = item;
  424. }
  425. else if(name == "Empty")
  426. {
  427. if(item_i > getSize() - 1)
  428. throw SerializationError("too many items");
  429. m_items[item_i++].clear();
  430. } else if (name == "Keep") {
  431. ++item_i; // Unmodified item
  432. }
  433. }
  434. // Contents given to deSerialize() were not terminated properly: throw error.
  435. std::ostringstream ss;
  436. ss << "Malformatted inventory list. list="
  437. << m_name << ", read " << item_i << " of " << getSize()
  438. << " ItemStacks." << std::endl;
  439. throw SerializationError(ss.str());
  440. }
  441. InventoryList::InventoryList(const InventoryList &other)
  442. {
  443. *this = other;
  444. }
  445. InventoryList & InventoryList::operator = (const InventoryList &other)
  446. {
  447. m_items = other.m_items;
  448. m_size = other.m_size;
  449. m_width = other.m_width;
  450. m_name = other.m_name;
  451. m_itemdef = other.m_itemdef;
  452. //setDirty(true);
  453. return *this;
  454. }
  455. bool InventoryList::operator == (const InventoryList &other) const
  456. {
  457. if(m_size != other.m_size)
  458. return false;
  459. if(m_width != other.m_width)
  460. return false;
  461. if(m_name != other.m_name)
  462. return false;
  463. for (u32 i = 0; i < m_items.size(); i++)
  464. if (m_items[i] != other.m_items[i])
  465. return false;
  466. return true;
  467. }
  468. const std::string &InventoryList::getName() const
  469. {
  470. return m_name;
  471. }
  472. u32 InventoryList::getSize() const
  473. {
  474. return m_items.size();
  475. }
  476. u32 InventoryList::getWidth() const
  477. {
  478. return m_width;
  479. }
  480. u32 InventoryList::getUsedSlots() const
  481. {
  482. u32 num = 0;
  483. for (const auto &m_item : m_items) {
  484. if (!m_item.empty())
  485. num++;
  486. }
  487. return num;
  488. }
  489. u32 InventoryList::getFreeSlots() const
  490. {
  491. return getSize() - getUsedSlots();
  492. }
  493. const ItemStack& InventoryList::getItem(u32 i) const
  494. {
  495. assert(i < m_size); // Pre-condition
  496. return m_items[i];
  497. }
  498. ItemStack& InventoryList::getItem(u32 i)
  499. {
  500. assert(i < m_size); // Pre-condition
  501. return m_items[i];
  502. }
  503. ItemStack InventoryList::changeItem(u32 i, const ItemStack &newitem)
  504. {
  505. if(i >= m_items.size())
  506. return newitem;
  507. ItemStack olditem = m_items[i];
  508. m_items[i] = newitem;
  509. setModified();
  510. return olditem;
  511. }
  512. void InventoryList::deleteItem(u32 i)
  513. {
  514. assert(i < m_items.size()); // Pre-condition
  515. m_items[i].clear();
  516. setModified();
  517. }
  518. ItemStack InventoryList::addItem(const ItemStack &newitem_)
  519. {
  520. ItemStack newitem = newitem_;
  521. if(newitem.empty())
  522. return newitem;
  523. /*
  524. First try to find if it could be added to some existing items
  525. */
  526. for(u32 i=0; i<m_items.size(); i++)
  527. {
  528. // Ignore empty slots
  529. if(m_items[i].empty())
  530. continue;
  531. // Try adding
  532. newitem = addItem(i, newitem);
  533. if(newitem.empty())
  534. return newitem; // All was eaten
  535. }
  536. /*
  537. Then try to add it to empty slots
  538. */
  539. for(u32 i=0; i<m_items.size(); i++)
  540. {
  541. // Ignore unempty slots
  542. if(!m_items[i].empty())
  543. continue;
  544. // Try adding
  545. newitem = addItem(i, newitem);
  546. if(newitem.empty())
  547. return newitem; // All was eaten
  548. }
  549. // Return leftover
  550. return newitem;
  551. }
  552. ItemStack InventoryList::addItem(u32 i, const ItemStack &newitem)
  553. {
  554. if(i >= m_items.size())
  555. return newitem;
  556. ItemStack leftover = m_items[i].addItem(newitem, m_itemdef);
  557. if (leftover != newitem)
  558. setModified();
  559. return leftover;
  560. }
  561. bool InventoryList::itemFits(const u32 i, const ItemStack &newitem,
  562. ItemStack *restitem) const
  563. {
  564. if(i >= m_items.size())
  565. {
  566. if(restitem)
  567. *restitem = newitem;
  568. return false;
  569. }
  570. return m_items[i].itemFits(newitem, restitem, m_itemdef);
  571. }
  572. bool InventoryList::roomForItem(const ItemStack &item_) const
  573. {
  574. ItemStack item = item_;
  575. ItemStack leftover;
  576. for(u32 i=0; i<m_items.size(); i++)
  577. {
  578. if(itemFits(i, item, &leftover))
  579. return true;
  580. item = leftover;
  581. }
  582. return false;
  583. }
  584. bool InventoryList::containsItem(const ItemStack &item, bool match_meta) const
  585. {
  586. u32 count = item.count;
  587. if (count == 0)
  588. return true;
  589. for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
  590. if (count == 0)
  591. break;
  592. if (i->name == item.name && (!match_meta || (i->metadata == item.metadata))) {
  593. if (i->count >= count)
  594. return true;
  595. count -= i->count;
  596. }
  597. }
  598. return false;
  599. }
  600. ItemStack InventoryList::removeItem(const ItemStack &item)
  601. {
  602. ItemStack removed;
  603. for (auto i = m_items.rbegin(); i != m_items.rend(); ++i) {
  604. if (i->name == item.name) {
  605. u32 still_to_remove = item.count - removed.count;
  606. ItemStack leftover = removed.addItem(i->takeItem(still_to_remove),
  607. m_itemdef);
  608. // Allow oversized stacks
  609. removed.count += leftover.count;
  610. if (removed.count == item.count)
  611. break;
  612. }
  613. }
  614. if (!removed.empty())
  615. setModified();
  616. return removed;
  617. }
  618. ItemStack InventoryList::takeItem(u32 i, u32 takecount)
  619. {
  620. if(i >= m_items.size())
  621. return ItemStack();
  622. ItemStack taken = m_items[i].takeItem(takecount);
  623. if (!taken.empty())
  624. setModified();
  625. return taken;
  626. }
  627. void InventoryList::moveItemSomewhere(u32 i, InventoryList *dest, u32 count)
  628. {
  629. // Take item from source list
  630. ItemStack item1;
  631. if (count == 0)
  632. item1 = changeItem(i, ItemStack());
  633. else
  634. item1 = takeItem(i, count);
  635. if (item1.empty())
  636. return;
  637. ItemStack leftover;
  638. leftover = dest->addItem(item1);
  639. if (!leftover.empty()) {
  640. // Add the remaining part back to the source item
  641. addItem(i, leftover);
  642. }
  643. }
  644. u32 InventoryList::moveItem(u32 i, InventoryList *dest, u32 dest_i,
  645. u32 count, bool swap_if_needed, bool *did_swap)
  646. {
  647. if (this == dest && i == dest_i)
  648. return count;
  649. // Take item from source list
  650. ItemStack item1;
  651. if (count == 0)
  652. item1 = changeItem(i, ItemStack());
  653. else
  654. item1 = takeItem(i, count);
  655. if (item1.empty())
  656. return 0;
  657. // Try to add the item to destination list
  658. u32 oldcount = item1.count;
  659. item1 = dest->addItem(dest_i, item1);
  660. // If something is returned, the item was not fully added
  661. if (!item1.empty()) {
  662. // If olditem is returned, nothing was added.
  663. bool nothing_added = (item1.count == oldcount);
  664. // If something else is returned, part of the item was left unadded.
  665. // Add the other part back to the source item
  666. addItem(i, item1);
  667. // If olditem is returned, nothing was added.
  668. // Swap the items
  669. if (nothing_added && swap_if_needed) {
  670. // Tell that we swapped
  671. if (did_swap != NULL) {
  672. *did_swap = true;
  673. }
  674. // Take item from source list
  675. item1 = changeItem(i, ItemStack());
  676. // Adding was not possible, swap the items.
  677. ItemStack item2 = dest->changeItem(dest_i, item1);
  678. // Put item from destination list to the source list
  679. changeItem(i, item2);
  680. }
  681. }
  682. return (oldcount - item1.count);
  683. }
  684. /*
  685. Inventory
  686. */
  687. Inventory::~Inventory()
  688. {
  689. clear();
  690. }
  691. void Inventory::clear()
  692. {
  693. for (auto &m_list : m_lists) {
  694. delete m_list;
  695. }
  696. m_lists.clear();
  697. setModified();
  698. }
  699. Inventory::Inventory(IItemDefManager *itemdef)
  700. {
  701. m_itemdef = itemdef;
  702. setModified();
  703. }
  704. Inventory::Inventory(const Inventory &other)
  705. {
  706. *this = other;
  707. }
  708. Inventory & Inventory::operator = (const Inventory &other)
  709. {
  710. // Gracefully handle self assignment
  711. if(this != &other)
  712. {
  713. clear();
  714. m_itemdef = other.m_itemdef;
  715. for (InventoryList *list : other.m_lists) {
  716. m_lists.push_back(new InventoryList(*list));
  717. }
  718. setModified();
  719. }
  720. return *this;
  721. }
  722. bool Inventory::operator == (const Inventory &other) const
  723. {
  724. if(m_lists.size() != other.m_lists.size())
  725. return false;
  726. for(u32 i=0; i<m_lists.size(); i++)
  727. {
  728. if(*m_lists[i] != *other.m_lists[i])
  729. return false;
  730. }
  731. return true;
  732. }
  733. void Inventory::serialize(std::ostream &os, bool incremental) const
  734. {
  735. //std::cout << "Serialize " << (int)incremental << ", n=" << m_lists.size() << std::endl;
  736. for (const InventoryList *list : m_lists) {
  737. if (!incremental || list->checkModified()) {
  738. os << "List " << list->getName() << " " << list->getSize() << "\n";
  739. list->serialize(os, incremental);
  740. } else {
  741. os << "KeepList " << list->getName() << "\n";
  742. }
  743. }
  744. os<<"EndInventory\n";
  745. }
  746. void Inventory::deSerialize(std::istream &is)
  747. {
  748. std::vector<InventoryList *> new_lists;
  749. new_lists.reserve(m_lists.size());
  750. while (is.good()) {
  751. std::string line;
  752. std::getline(is, line, '\n');
  753. std::istringstream iss(line);
  754. std::string name;
  755. std::getline(iss, name, ' ');
  756. if (name == "EndInventory" || name == "end") {
  757. // Remove all lists that were not sent
  758. for (auto &list : m_lists) {
  759. if (std::find(new_lists.begin(), new_lists.end(), list) != new_lists.end())
  760. continue;
  761. delete list;
  762. list = nullptr;
  763. setModified();
  764. }
  765. m_lists.erase(std::remove(m_lists.begin(), m_lists.end(),
  766. nullptr), m_lists.end());
  767. return;
  768. }
  769. if (name == "List") {
  770. std::string listname;
  771. u32 listsize;
  772. std::getline(iss, listname, ' ');
  773. iss>>listsize;
  774. InventoryList *list = getList(listname);
  775. bool create_new = !list;
  776. if (create_new)
  777. list = new InventoryList(listname, listsize, m_itemdef);
  778. else
  779. list->setSize(listsize);
  780. list->deSerialize(is);
  781. new_lists.push_back(list);
  782. if (create_new)
  783. m_lists.push_back(list);
  784. } else if (name == "KeepList") {
  785. // Incrementally sent list
  786. std::string listname;
  787. std::getline(iss, listname, ' ');
  788. InventoryList *list = getList(listname);
  789. if (list) {
  790. new_lists.push_back(list);
  791. } else {
  792. errorstream << "Inventory::deSerialize(): Tried to keep list '" <<
  793. listname << "' which is non-existent." << std::endl;
  794. }
  795. }
  796. // Any additional fields will throw errors when received by a client
  797. // older than PROTOCOL_VERSION 38
  798. }
  799. // Contents given to deSerialize() were not terminated properly: throw error.
  800. std::ostringstream ss;
  801. ss << "Malformatted inventory (damaged?). "
  802. << m_lists.size() << " lists read." << std::endl;
  803. throw SerializationError(ss.str());
  804. }
  805. InventoryList * Inventory::addList(const std::string &name, u32 size)
  806. {
  807. setModified();
  808. // Remove existing lists
  809. s32 i = getListIndex(name);
  810. if (i != -1) {
  811. delete m_lists[i];
  812. m_lists[i] = new InventoryList(name, size, m_itemdef);
  813. m_lists[i]->setModified();
  814. return m_lists[i];
  815. }
  816. //don't create list with invalid name
  817. if (name.find(' ') != std::string::npos)
  818. return nullptr;
  819. InventoryList *list = new InventoryList(name, size, m_itemdef);
  820. list->setModified();
  821. m_lists.push_back(list);
  822. return list;
  823. }
  824. InventoryList * Inventory::getList(const std::string &name)
  825. {
  826. s32 i = getListIndex(name);
  827. if(i == -1)
  828. return nullptr;
  829. return m_lists[i];
  830. }
  831. std::vector<const InventoryList*> Inventory::getLists()
  832. {
  833. std::vector<const InventoryList*> lists;
  834. lists.reserve(m_lists.size());
  835. for (auto list : m_lists) {
  836. lists.push_back(list);
  837. }
  838. return lists;
  839. }
  840. bool Inventory::deleteList(const std::string &name)
  841. {
  842. s32 i = getListIndex(name);
  843. if(i == -1)
  844. return false;
  845. setModified();
  846. delete m_lists[i];
  847. m_lists.erase(m_lists.begin() + i);
  848. return true;
  849. }
  850. const InventoryList *Inventory::getList(const std::string &name) const
  851. {
  852. s32 i = getListIndex(name);
  853. if(i == -1)
  854. return nullptr;
  855. return m_lists[i];
  856. }
  857. const s32 Inventory::getListIndex(const std::string &name) const
  858. {
  859. for(u32 i=0; i<m_lists.size(); i++)
  860. {
  861. if(m_lists[i]->getName() == name)
  862. return i;
  863. }
  864. return -1;
  865. }
  866. //END