3 Copyright (C) 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.
22 #include "irrlichttypes.h"
28 #include "inventory.h"
29 #include "util/serialize.h"
30 #include "util/string.h"
31 #include "util/numeric.h"
32 #include "util/strfnd.h"
33 #include "exceptions.h"
35 inline bool isGroupRecipeStr(const std::string &rec_name)
37 return str_starts_with(rec_name, std::string("group:"));
40 inline u64 getHashForString(const std::string &recipe_str)
42 /*errorstream << "Hashing craft string \"" << recipe_str << '"';*/
43 return murmur_hash_64_ua(recipe_str.data(), recipe_str.length(), 0xdeadbeef);
46 static u64 getHashForGrid(CraftHashType type, const std::vector<std::string> &grid_names)
49 case CRAFT_HASH_TYPE_ITEM_NAMES: {
50 std::ostringstream os;
52 for (size_t i = 0; i < grid_names.size(); i++) {
53 if (!grid_names[i].empty()) {
54 os << (is_first ? "" : "\n") << grid_names[i];
58 return getHashForString(os.str());
59 } case CRAFT_HASH_TYPE_COUNT: {
61 for (size_t i = 0; i < grid_names.size(); i++)
62 if (!grid_names[i].empty())
65 } case CRAFT_HASH_TYPE_UNHASHED:
68 // invalid CraftHashType
73 // Check if input matches recipe
74 // Takes recipe groups into account
75 static bool inputItemMatchesRecipe(const std::string &inp_name,
76 const std::string &rec_name, IItemDefManager *idef)
79 if (inp_name == rec_name)
83 if (isGroupRecipeStr(rec_name) && idef->isKnown(inp_name)) {
84 const struct ItemDefinition &def = idef->get(inp_name);
85 Strfnd f(rec_name.substr(6));
86 bool all_groups_match = true;
88 std::string check_group = f.next(",");
89 if (itemgroup_get(def.groups, check_group) == 0) {
90 all_groups_match = false;
93 } while (!f.at_end());
102 // Deserialize an itemstring then return the name of the item
103 static std::string craftGetItemName(const std::string &itemstring, IGameDef *gamedef)
106 item.deSerialize(itemstring, gamedef->idef());
110 // (mapcar craftGetItemName itemstrings)
111 static std::vector<std::string> craftGetItemNames(
112 const std::vector<std::string> &itemstrings, IGameDef *gamedef)
114 std::vector<std::string> result;
115 for (const auto &itemstring : itemstrings) {
116 result.push_back(craftGetItemName(itemstring, gamedef));
121 // Get name of each item, and return them as a new list.
122 static std::vector<std::string> craftGetItemNames(
123 const std::vector<ItemStack> &items, IGameDef *gamedef)
125 std::vector<std::string> result;
126 for (const auto &item : items) {
127 result.push_back(item.name);
132 // convert a list of item names, to ItemStacks.
133 static std::vector<ItemStack> craftGetItems(
134 const std::vector<std::string> &items, IGameDef *gamedef)
136 std::vector<ItemStack> result;
137 for (const auto &item : items) {
138 result.emplace_back(std::string(item), (u16)1,
139 (u16)0, gamedef->getItemDefManager());
144 // Compute bounding rectangle given a matrix of items
145 // Returns false if every item is ""
146 static bool craftGetBounds(const std::vector<std::string> &items, unsigned int width,
147 unsigned int &min_x, unsigned int &max_x,
148 unsigned int &min_y, unsigned int &max_y)
150 bool success = false;
153 for (std::vector<std::string>::size_type i = 0;
154 i < items.size(); i++) {
155 // Is this an actual item?
156 if (!items[i].empty()) {
158 // This is the first nonempty item
163 if (x < min_x) min_x = x;
164 if (x > max_x) max_x = x;
165 if (y < min_y) min_y = y;
166 if (y > max_y) max_y = y;
180 // Removes 1 from each item stack
181 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
183 for (auto &item : input.items) {
189 // Removes 1 from each item stack with replacement support
190 // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"),
191 // a water bucket will not be removed but replaced by an empty bucket.
192 static void craftDecrementOrReplaceInput(CraftInput &input,
193 std::vector<ItemStack> &output_replacements,
194 const CraftReplacements &replacements,
197 if (replacements.pairs.empty()) {
198 craftDecrementInput(input, gamedef);
202 // Make a copy of the replacements pair list
203 std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
205 for (auto &item : input.items) {
206 // Find an appropriate replacement
207 bool found_replacement = false;
208 for (auto j = pairs.begin(); j != pairs.end(); ++j) {
209 if (inputItemMatchesRecipe(item.name, j->first, gamedef->idef())) {
210 if (item.count == 1) {
211 item.deSerialize(j->second, gamedef->idef());
212 found_replacement = true;
218 rep.deSerialize(j->second, gamedef->idef());
220 found_replacement = true;
221 output_replacements.push_back(rep);
226 // No replacement was found, simply decrement count by one
227 if (!found_replacement && item.count > 0)
232 // Dump an itemstring matrix
233 static std::string craftDumpMatrix(const std::vector<std::string> &items,
236 std::ostringstream os(std::ios::binary);
239 for(std::vector<std::string>::size_type i = 0;
240 i < items.size(); i++, x++) {
247 os << '"' << items[i] << '"';
253 // Dump an item matrix
254 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
257 std::ostringstream os(std::ios::binary);
260 for (std::vector<ItemStack>::size_type i = 0;
261 i < items.size(); i++, x++) {
268 os << '"' << (items[i].getItemString()) << '"';
279 std::string CraftInput::dump() const
281 std::ostringstream os(std::ios::binary);
282 os << "(method=" << ((int)method) << ", items="
283 << craftDumpMatrix(items, width) << ")";
291 std::string CraftOutput::dump() const
293 std::ostringstream os(std::ios::binary);
294 os << "(item=\"" << item << "\", time=" << time << ")";
302 std::string CraftReplacements::dump() const
304 std::ostringstream os(std::ios::binary);
306 const char *sep = "";
307 for (const auto &repl_p : pairs) {
309 << '"' << (repl_p.first)
310 << "\"=>\"" << (repl_p.second) << '"';
318 CraftDefinitionShaped
321 std::string CraftDefinitionShaped::getName() const
326 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
328 if (input.method != CRAFT_METHOD_NORMAL)
331 // Get input item matrix
332 std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
333 unsigned int inp_width = input.width;
336 while (inp_names.size() % inp_width != 0)
337 inp_names.emplace_back("");
340 unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0;
341 if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x,
342 inp_min_y, inp_max_y))
343 return false; // it was empty
345 std::vector<std::string> rec_names;
347 rec_names = recipe_names;
349 rec_names = craftGetItemNames(recipe, gamedef);
351 // Get recipe item matrix
352 unsigned int rec_width = width;
355 while (rec_names.size() % rec_width != 0)
356 rec_names.emplace_back("");
359 unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
360 if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x,
361 rec_min_y, rec_max_y))
362 return false; // it was empty
365 if (inp_max_x - inp_min_x != rec_max_x - rec_min_x ||
366 inp_max_y - inp_min_y != rec_max_y - rec_min_y)
369 // Verify that all item names in the bounding box are equal
370 unsigned int w = inp_max_x - inp_min_x + 1;
371 unsigned int h = inp_max_y - inp_min_y + 1;
373 for (unsigned int y=0; y < h; y++) {
374 unsigned int inp_y = (inp_min_y + y) * inp_width;
375 unsigned int rec_y = (rec_min_y + y) * rec_width;
377 for (unsigned int x=0; x < w; x++) {
378 unsigned int inp_x = inp_min_x + x;
379 unsigned int rec_x = rec_min_x + x;
381 if (!inputItemMatchesRecipe(
382 inp_names[inp_y + inp_x],
383 rec_names[rec_y + rec_x], gamedef->idef())) {
392 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
394 return CraftOutput(output, 0);
397 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
399 return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
402 void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
403 IGameDef *gamedef) const
405 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
408 CraftHashType CraftDefinitionShaped::getHashType() const
410 assert(hash_inited); // Pre-condition
411 bool has_group = false;
412 for (const auto &recipe_name : recipe_names) {
413 if (isGroupRecipeStr(recipe_name)) {
419 return CRAFT_HASH_TYPE_COUNT;
421 return CRAFT_HASH_TYPE_ITEM_NAMES;
424 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
426 assert(hash_inited); // Pre-condition
427 assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
428 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
430 std::vector<std::string> rec_names = recipe_names;
431 std::sort(rec_names.begin(), rec_names.end());
432 return getHashForGrid(type, rec_names);
435 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
440 recipe_names = craftGetItemNames(recipe, gamedef);
443 std::string CraftDefinitionShaped::dump() const
445 std::ostringstream os(std::ios::binary);
446 os << "(shaped, output=\"" << output
447 << "\", recipe=" << craftDumpMatrix(recipe, width)
448 << ", replacements=" << replacements.dump() << ")";
453 CraftDefinitionShapeless
456 std::string CraftDefinitionShapeless::getName() const
461 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
463 if (input.method != CRAFT_METHOD_NORMAL)
466 // Filter empty items out of input
467 std::vector<std::string> input_filtered;
468 for (const auto &item : input.items) {
469 if (!item.name.empty())
470 input_filtered.push_back(item.name);
473 // If there is a wrong number of items in input, no match
474 if (input_filtered.size() != recipe.size()) {
475 /*dstream<<"Number of input items ("<<input_filtered.size()
476 <<") does not match recipe size ("<<recipe.size()<<") "
477 <<"of recipe with output="<<output<<std::endl;*/
481 std::vector<std::string> recipe_copy;
483 recipe_copy = recipe_names;
485 recipe_copy = craftGetItemNames(recipe, gamedef);
486 std::sort(recipe_copy.begin(), recipe_copy.end());
489 // Try with all permutations of the recipe,
490 // start from the lexicographically first permutation (=sorted),
491 // recipe_names is pre-sorted
493 // If all items match, the recipe matches
494 bool all_match = true;
495 //dstream<<"Testing recipe (output="<<output<<"):";
496 for (size_t i=0; i<recipe.size(); i++) {
497 //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
498 if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
504 //dstream<<" -> match="<<all_match<<std::endl;
507 } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
512 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
514 return CraftOutput(output, 0);
517 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
519 return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
522 void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
523 IGameDef *gamedef) const
525 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
528 CraftHashType CraftDefinitionShapeless::getHashType() const
530 assert(hash_inited); // Pre-condition
531 bool has_group = false;
532 for (const auto &recipe_name : recipe_names) {
533 if (isGroupRecipeStr(recipe_name)) {
539 return CRAFT_HASH_TYPE_COUNT;
541 return CRAFT_HASH_TYPE_ITEM_NAMES;
544 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
546 assert(hash_inited); // Pre-condition
547 assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
548 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
549 return getHashForGrid(type, recipe_names);
552 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
557 recipe_names = craftGetItemNames(recipe, gamedef);
558 std::sort(recipe_names.begin(), recipe_names.end());
561 std::string CraftDefinitionShapeless::dump() const
563 std::ostringstream os(std::ios::binary);
564 os << "(shapeless, output=\"" << output
565 << "\", recipe=" << craftDumpMatrix(recipe, recipe.size())
566 << ", replacements=" << replacements.dump() << ")";
571 CraftDefinitionToolRepair
574 static ItemStack craftToolRepair(
575 const ItemStack &item1,
576 const ItemStack &item2,
577 float additional_wear,
580 IItemDefManager *idef = gamedef->idef();
581 if (item1.count != 1 || item2.count != 1 || item1.name != item2.name
582 || idef->get(item1.name).type != ITEM_TOOL
583 || idef->get(item2.name).type != ITEM_TOOL) {
588 s32 item1_uses = 65536 - (u32) item1.wear;
589 s32 item2_uses = 65536 - (u32) item2.wear;
590 s32 new_uses = item1_uses + item2_uses;
591 s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
592 if (new_wear >= 65536)
597 ItemStack repaired = item1;
598 repaired.wear = new_wear;
602 std::string CraftDefinitionToolRepair::getName() const
607 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
609 if (input.method != CRAFT_METHOD_NORMAL)
614 for (const auto &item : input.items) {
618 else if (item2.empty())
624 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
625 return !repaired.empty();
628 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
632 for (const auto &item : input.items) {
636 else if (item2.empty())
640 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
641 return CraftOutput(repaired.getItemString(), 0);
644 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
646 std::vector<ItemStack> stack;
647 stack.emplace_back();
648 return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack);
651 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
652 IGameDef *gamedef) const
654 craftDecrementInput(input, gamedef);
657 std::string CraftDefinitionToolRepair::dump() const
659 std::ostringstream os(std::ios::binary);
660 os << "(toolrepair, additional_wear=" << additional_wear << ")";
665 CraftDefinitionCooking
668 std::string CraftDefinitionCooking::getName() const
673 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
675 if (input.method != CRAFT_METHOD_COOKING)
678 // Filter empty items out of input
679 std::vector<std::string> input_filtered;
680 for (const auto &item : input.items) {
681 const std::string &name = item.name;
683 input_filtered.push_back(name);
686 // If there is a wrong number of items in input, no match
687 if (input_filtered.size() != 1) {
688 /*dstream<<"Number of input items ("<<input_filtered.size()
689 <<") does not match recipe size (1) "
690 <<"of cooking recipe with output="<<output<<std::endl;*/
694 // Check the single input item
695 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
698 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
700 return CraftOutput(output, cooktime);
703 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
705 std::vector<std::string> rec;
706 rec.push_back(recipe);
707 return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
710 void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
711 IGameDef *gamedef) const
713 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
716 CraftHashType CraftDefinitionCooking::getHashType() const
718 if (isGroupRecipeStr(recipe_name))
719 return CRAFT_HASH_TYPE_COUNT;
721 return CRAFT_HASH_TYPE_ITEM_NAMES;
724 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
726 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
727 return getHashForString(recipe_name);
729 if (type == CRAFT_HASH_TYPE_COUNT) {
732 //illegal hash type for this CraftDefinition (pre-condition)
738 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
743 recipe_name = craftGetItemName(recipe, gamedef);
746 std::string CraftDefinitionCooking::dump() const
748 std::ostringstream os(std::ios::binary);
749 os << "(cooking, output=\"" << output
750 << "\", recipe=\"" << recipe
751 << "\", cooktime=" << cooktime << ")"
752 << ", replacements=" << replacements.dump() << ")";
760 std::string CraftDefinitionFuel::getName() const
765 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
767 if (input.method != CRAFT_METHOD_FUEL)
770 // Filter empty items out of input
771 std::vector<std::string> input_filtered;
772 for (const auto &item : input.items) {
773 const std::string &name = item.name;
775 input_filtered.push_back(name);
778 // If there is a wrong number of items in input, no match
779 if (input_filtered.size() != 1) {
780 /*dstream<<"Number of input items ("<<input_filtered.size()
781 <<") does not match recipe size (1) "
782 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
786 // Check the single input item
787 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
790 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
792 return CraftOutput("", burntime);
795 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
797 std::vector<std::string> rec;
798 rec.push_back(recipe);
799 return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
802 void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
803 IGameDef *gamedef) const
805 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
808 CraftHashType CraftDefinitionFuel::getHashType() const
810 if (isGroupRecipeStr(recipe_name))
811 return CRAFT_HASH_TYPE_COUNT;
813 return CRAFT_HASH_TYPE_ITEM_NAMES;
816 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
818 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
819 return getHashForString(recipe_name);
822 if (type == CRAFT_HASH_TYPE_COUNT) {
825 //illegal hash type for this CraftDefinition (pre-condition)
831 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
836 recipe_name = craftGetItemName(recipe, gamedef);
838 std::string CraftDefinitionFuel::dump() const
840 std::ostringstream os(std::ios::binary);
841 os << "(fuel, recipe=\"" << recipe
842 << "\", burntime=" << burntime << ")"
843 << ", replacements=" << replacements.dump() << ")";
848 Craft definition manager
851 class CCraftDefManager: public IWritableCraftDefManager
856 m_craft_defs.resize(craft_hash_type_max + 1);
859 virtual ~CCraftDefManager()
864 virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
865 std::vector<ItemStack> &output_replacement, bool decrementInput,
866 IGameDef *gamedef) const
871 // If all input items are empty, abort.
872 bool all_empty = true;
873 for (const auto &item : input.items) {
882 std::vector<std::string> input_names;
883 input_names = craftGetItemNames(input.items, gamedef);
884 std::sort(input_names.begin(), input_names.end());
886 // Try hash types with increasing collision rate, and return if found.
887 for (int type = 0; type <= craft_hash_type_max; type++) {
888 u64 hash = getHashForGrid((CraftHashType) type, input_names);
890 /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
892 // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
893 // but that doesn't compile for some reason. This does.
894 auto col_iter = (m_craft_defs[type]).find(hash);
896 if (col_iter == (m_craft_defs[type]).end())
899 const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
900 // Walk crafting definitions from back to front, so that later
901 // definitions can override earlier ones.
902 for (std::vector<CraftDefinition*>::size_type
903 i = hash_collisions.size(); i > 0; i--) {
904 CraftDefinition *def = hash_collisions[i - 1];
906 /*errorstream << "Checking " << input.dump() << std::endl
907 << " against " << def->dump() << std::endl;*/
909 if (def->check(input, gamedef)) {
910 // Get output, then decrement input (if requested)
911 output = def->getOutput(input, gamedef);
913 def->decrementInput(input, output_replacement, gamedef);
914 /*errorstream << "Check RETURNS TRUE" << std::endl;*/
922 virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
923 IGameDef *gamedef, unsigned limit=0) const
925 std::vector<CraftDefinition*> recipes;
927 auto vec_iter = m_output_craft_definitions.find(output.item);
929 if (vec_iter == m_output_craft_definitions.end())
932 const std::vector<CraftDefinition*> &vec = vec_iter->second;
934 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
936 for (std::vector<CraftDefinition*>::size_type i = vec.size();
938 CraftDefinition *def = vec[i - 1];
939 if (limit && recipes.size() >= limit)
941 recipes.push_back(def);
947 virtual bool clearCraftRecipesByOutput(const CraftOutput &output, IGameDef *gamedef)
949 auto vec_iter = m_output_craft_definitions.find(output.item);
951 if (vec_iter == m_output_craft_definitions.end())
954 std::vector<CraftDefinition*> &vec = vec_iter->second;
955 for (auto def : vec) {
956 // Recipes are not yet hashed at this point
957 std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
958 std::vector<CraftDefinition*> new_vec_by_input;
959 /* We will preallocate necessary memory addresses, so we don't need to reallocate them later.
960 This would save us some performance. */
961 new_vec_by_input.reserve(unhashed_inputs_vec.size());
962 for (auto &i2 : unhashed_inputs_vec) {
964 new_vec_by_input.push_back(i2);
967 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
969 m_output_craft_definitions.erase(output.item);
973 virtual bool clearCraftRecipesByInput(CraftMethod craft_method, unsigned int craft_grid_width,
974 const std::vector<std::string> &recipe, IGameDef *gamedef)
976 bool all_empty = true;
977 for (const auto &i : recipe) {
986 CraftInput input(craft_method, craft_grid_width, craftGetItems(recipe, gamedef));
987 // Recipes are not yet hashed at this point
988 std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
989 std::vector<CraftDefinition*> new_vec_by_input;
990 bool got_hit = false;
991 for (std::vector<CraftDefinition*>::size_type
992 i = unhashed_inputs_vec.size(); i > 0; i--) {
993 CraftDefinition *def = unhashed_inputs_vec[i - 1];
994 /* If the input doesn't match the recipe definition, this recipe definition later
995 will be added back in source map. */
996 if (!def->check(input, gamedef)) {
997 new_vec_by_input.push_back(def);
1000 CraftOutput output = def->getOutput(input, gamedef);
1002 auto vec_iter = m_output_craft_definitions.find(output.item);
1003 if (vec_iter == m_output_craft_definitions.end())
1005 std::vector<CraftDefinition*> &vec = vec_iter->second;
1006 std::vector<CraftDefinition*> new_vec_by_output;
1007 /* We will preallocate necessary memory addresses, so we don't need
1008 to reallocate them later. This would save us some performance. */
1009 new_vec_by_output.reserve(vec.size());
1010 for (auto &vec_i : vec) {
1011 /* If pointers from map by input and output are not same,
1012 we will add 'CraftDefinition*' to a new vector. */
1014 /* Adding dereferenced iterator value (which are
1015 'CraftDefinition' reference) to a new vector. */
1016 new_vec_by_output.push_back(vec_i);
1019 // Swaps assigned to current key value with new vector for output map.
1020 m_output_craft_definitions[output.item].swap(new_vec_by_output);
1023 // Swaps value with new vector for input map.
1024 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
1029 virtual std::string dump() const
1031 std::ostringstream os(std::ios::binary);
1032 os << "Crafting definitions:\n";
1033 for (int type = 0; type <= craft_hash_type_max; ++type) {
1034 for (auto it = m_craft_defs[type].begin();
1035 it != m_craft_defs[type].end(); ++it) {
1036 for (std::vector<CraftDefinition*>::size_type i = 0;
1037 i < it->second.size(); i++) {
1038 os << "type " << type
1039 << " hash " << it->first
1040 << " def " << it->second[i]->dump()
1047 virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
1049 verbosestream << "registerCraft: registering craft definition: "
1050 << def->dump() << std::endl;
1051 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
1054 std::string output_name = craftGetItemName(
1055 def->getOutput(input, gamedef).item, gamedef);
1056 m_output_craft_definitions[output_name].push_back(def);
1058 virtual void clear()
1060 for (int type = 0; type <= craft_hash_type_max; ++type) {
1061 for (auto &it : m_craft_defs[type]) {
1062 for (auto iit = it.second.begin();
1063 iit != it.second.end(); ++iit) {
1068 m_craft_defs[type].clear();
1070 m_output_craft_definitions.clear();
1072 virtual void initHashes(IGameDef *gamedef)
1074 // Move the CraftDefs from the unhashed layer into layers higher up.
1075 std::vector<CraftDefinition *> &unhashed =
1076 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1077 for (auto def : unhashed) {
1078 // Initialize and get the definition's hash
1079 def->initHash(gamedef);
1080 CraftHashType type = def->getHashType();
1081 u64 hash = def->getHash(type);
1083 // Enter the definition
1084 m_craft_defs[type][hash].push_back(def);
1089 //TODO: change both maps to unordered_map when c++11 can be used
1090 std::vector<std::map<u64, std::vector<CraftDefinition*> > > m_craft_defs;
1091 std::map<std::string, std::vector<CraftDefinition*> > m_output_craft_definitions;
1094 IWritableCraftDefManager* createCraftDefManager()
1096 return new CCraftDefManager();