inventory.cpp 22 KB

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