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 (const std::string &grid_name : grid_names) {
53 if (!grid_name.empty()) {
54 os << (is_first ? "" : "\n") << grid_name;
58 return getHashForString(os.str());
59 } case CRAFT_HASH_TYPE_COUNT: {
61 for (const std::string &grid_name : grid_names)
62 if (!grid_name.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 result.reserve(itemstrings.size());
116 for (const auto &itemstring : itemstrings) {
117 result.push_back(craftGetItemName(itemstring, gamedef));
122 // Get name of each item, and return them as a new list.
123 static std::vector<std::string> craftGetItemNames(
124 const std::vector<ItemStack> &items, IGameDef *gamedef)
126 std::vector<std::string> result;
127 result.reserve(items.size());
128 for (const auto &item : items) {
129 result.push_back(item.name);
134 // convert a list of item names, to ItemStacks.
135 static std::vector<ItemStack> craftGetItems(
136 const std::vector<std::string> &items, IGameDef *gamedef)
138 std::vector<ItemStack> result;
139 result.reserve(items.size());
140 for (const auto &item : items) {
141 result.emplace_back(std::string(item), (u16)1,
142 (u16)0, gamedef->getItemDefManager());
147 // Compute bounding rectangle given a matrix of items
148 // Returns false if every item is ""
149 static bool craftGetBounds(const std::vector<std::string> &items, unsigned int width,
150 unsigned int &min_x, unsigned int &max_x,
151 unsigned int &min_y, unsigned int &max_y)
153 bool success = false;
156 for (const std::string &item : items) {
157 // Is this an actual item?
160 // This is the first nonempty item
165 if (x < min_x) min_x = x;
166 if (x > max_x) max_x = x;
167 if (y < min_y) min_y = y;
168 if (y > max_y) max_y = y;
182 // Removes 1 from each item stack
183 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
185 for (auto &item : input.items) {
191 // Removes 1 from each item stack with replacement support
192 // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"),
193 // a water bucket will not be removed but replaced by an empty bucket.
194 static void craftDecrementOrReplaceInput(CraftInput &input,
195 std::vector<ItemStack> &output_replacements,
196 const CraftReplacements &replacements,
199 if (replacements.pairs.empty()) {
200 craftDecrementInput(input, gamedef);
204 // Make a copy of the replacements pair list
205 std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
207 for (auto &item : input.items) {
208 // Find an appropriate replacement
209 bool found_replacement = false;
210 for (auto j = pairs.begin(); j != pairs.end(); ++j) {
211 if (inputItemMatchesRecipe(item.name, j->first, gamedef->idef())) {
212 if (item.count == 1) {
213 item.deSerialize(j->second, gamedef->idef());
214 found_replacement = true;
220 rep.deSerialize(j->second, gamedef->idef());
222 found_replacement = true;
223 output_replacements.push_back(rep);
228 // No replacement was found, simply decrement count by one
229 if (!found_replacement && item.count > 0)
234 // Dump an itemstring matrix
235 static std::string craftDumpMatrix(const std::vector<std::string> &items,
238 std::ostringstream os(std::ios::binary);
241 for(std::vector<std::string>::size_type i = 0;
242 i < items.size(); i++, x++) {
249 os << '"' << items[i] << '"';
255 // Dump an item matrix
256 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
259 std::ostringstream os(std::ios::binary);
262 for (std::vector<ItemStack>::size_type i = 0;
263 i < items.size(); i++, x++) {
270 os << '"' << (items[i].getItemString()) << '"';
281 std::string CraftInput::dump() const
283 std::ostringstream os(std::ios::binary);
284 os << "(method=" << ((int)method) << ", items="
285 << craftDumpMatrix(items, width) << ")";
293 std::string CraftOutput::dump() const
295 std::ostringstream os(std::ios::binary);
296 os << "(item=\"" << item << "\", time=" << time << ")";
304 std::string CraftReplacements::dump() const
306 std::ostringstream os(std::ios::binary);
308 const char *sep = "";
309 for (const auto &repl_p : pairs) {
311 << '"' << (repl_p.first)
312 << "\"=>\"" << (repl_p.second) << '"';
320 CraftDefinitionShaped
323 std::string CraftDefinitionShaped::getName() const
328 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
330 if (input.method != CRAFT_METHOD_NORMAL)
333 // Get input item matrix
334 std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
335 unsigned int inp_width = input.width;
338 while (inp_names.size() % inp_width != 0)
339 inp_names.emplace_back("");
342 unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0;
343 if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x,
344 inp_min_y, inp_max_y))
345 return false; // it was empty
347 std::vector<std::string> rec_names;
349 rec_names = recipe_names;
351 rec_names = craftGetItemNames(recipe, gamedef);
353 // Get recipe item matrix
354 unsigned int rec_width = width;
357 while (rec_names.size() % rec_width != 0)
358 rec_names.emplace_back("");
361 unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
362 if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x,
363 rec_min_y, rec_max_y))
364 return false; // it was empty
367 if (inp_max_x - inp_min_x != rec_max_x - rec_min_x ||
368 inp_max_y - inp_min_y != rec_max_y - rec_min_y)
371 // Verify that all item names in the bounding box are equal
372 unsigned int w = inp_max_x - inp_min_x + 1;
373 unsigned int h = inp_max_y - inp_min_y + 1;
375 for (unsigned int y=0; y < h; y++) {
376 unsigned int inp_y = (inp_min_y + y) * inp_width;
377 unsigned int rec_y = (rec_min_y + y) * rec_width;
379 for (unsigned int x=0; x < w; x++) {
380 unsigned int inp_x = inp_min_x + x;
381 unsigned int rec_x = rec_min_x + x;
383 if (!inputItemMatchesRecipe(
384 inp_names[inp_y + inp_x],
385 rec_names[rec_y + rec_x], gamedef->idef())) {
394 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
396 return CraftOutput(output, 0);
399 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
401 return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
404 void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
405 IGameDef *gamedef) const
407 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
410 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
412 assert(hash_inited); // Pre-condition
413 assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
414 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
416 std::vector<std::string> rec_names = recipe_names;
417 std::sort(rec_names.begin(), rec_names.end());
418 return getHashForGrid(type, rec_names);
421 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
426 recipe_names = craftGetItemNames(recipe, gamedef);
428 bool has_group = false;
429 for (const auto &recipe_name : recipe_names) {
430 if (isGroupRecipeStr(recipe_name)) {
436 hash_type = CRAFT_HASH_TYPE_COUNT;
437 priority = SHAPED_AND_GROUPS;
439 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
444 std::string CraftDefinitionShaped::dump() const
446 std::ostringstream os(std::ios::binary);
447 os << "(shaped, output=\"" << output
448 << "\", recipe=" << craftDumpMatrix(recipe, width)
449 << ", replacements=" << replacements.dump() << ")";
454 CraftDefinitionShapeless
457 std::string CraftDefinitionShapeless::getName() const
462 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
464 if (input.method != CRAFT_METHOD_NORMAL)
467 // Filter empty items out of input
468 std::vector<std::string> input_filtered;
469 for (const auto &item : input.items) {
470 if (!item.name.empty())
471 input_filtered.push_back(item.name);
474 // If there is a wrong number of items in input, no match
475 if (input_filtered.size() != recipe.size()) {
476 /*dstream<<"Number of input items ("<<input_filtered.size()
477 <<") does not match recipe size ("<<recipe.size()<<") "
478 <<"of recipe with output="<<output<<std::endl;*/
482 std::vector<std::string> recipe_copy;
484 recipe_copy = recipe_names;
486 recipe_copy = craftGetItemNames(recipe, gamedef);
487 std::sort(recipe_copy.begin(), recipe_copy.end());
490 // Try with all permutations of the recipe,
491 // start from the lexicographically first permutation (=sorted),
492 // recipe_names is pre-sorted
494 // If all items match, the recipe matches
495 bool all_match = true;
496 //dstream<<"Testing recipe (output="<<output<<"):";
497 for (size_t i=0; i<recipe.size(); i++) {
498 //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
499 if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
505 //dstream<<" -> match="<<all_match<<std::endl;
508 } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
513 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
515 return CraftOutput(output, 0);
518 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
520 return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
523 void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
524 IGameDef *gamedef) const
526 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
529 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
531 assert(hash_inited); // Pre-condition
532 assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
533 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
534 return getHashForGrid(type, recipe_names);
537 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
542 recipe_names = craftGetItemNames(recipe, gamedef);
543 std::sort(recipe_names.begin(), recipe_names.end());
545 bool has_group = false;
546 for (const auto &recipe_name : recipe_names) {
547 if (isGroupRecipeStr(recipe_name)) {
553 hash_type = CRAFT_HASH_TYPE_COUNT;
554 priority = SHAPELESS_AND_GROUPS;
556 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
557 priority = SHAPELESS;
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 || itemgroup_get(idef->get(item1.name).groups, "disable_repair") == 1) {
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 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
718 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
719 return getHashForString(recipe_name);
722 if (type == CRAFT_HASH_TYPE_COUNT) {
726 // illegal hash type for this CraftDefinition (pre-condition)
731 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
736 recipe_name = craftGetItemName(recipe, gamedef);
738 if (isGroupRecipeStr(recipe_name)) {
739 hash_type = CRAFT_HASH_TYPE_COUNT;
740 priority = SHAPELESS_AND_GROUPS;
742 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
743 priority = SHAPELESS;
747 std::string CraftDefinitionCooking::dump() const
749 std::ostringstream os(std::ios::binary);
750 os << "(cooking, output=\"" << output
751 << "\", recipe=\"" << recipe
752 << "\", cooktime=" << cooktime << ")"
753 << ", replacements=" << replacements.dump() << ")";
761 std::string CraftDefinitionFuel::getName() const
766 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
768 if (input.method != CRAFT_METHOD_FUEL)
771 // Filter empty items out of input
772 std::vector<std::string> input_filtered;
773 for (const auto &item : input.items) {
774 const std::string &name = item.name;
776 input_filtered.push_back(name);
779 // If there is a wrong number of items in input, no match
780 if (input_filtered.size() != 1) {
781 /*dstream<<"Number of input items ("<<input_filtered.size()
782 <<") does not match recipe size (1) "
783 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
787 // Check the single input item
788 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
791 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
793 return CraftOutput("", burntime);
796 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
798 std::vector<std::string> rec;
799 rec.push_back(recipe);
800 return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
803 void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
804 IGameDef *gamedef) const
806 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
809 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
811 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
812 return getHashForString(recipe_name);
815 if (type == CRAFT_HASH_TYPE_COUNT) {
819 // illegal hash type for this CraftDefinition (pre-condition)
824 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
829 recipe_name = craftGetItemName(recipe, gamedef);
831 if (isGroupRecipeStr(recipe_name)) {
832 hash_type = CRAFT_HASH_TYPE_COUNT;
833 priority = SHAPELESS_AND_GROUPS;
835 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
836 priority = SHAPELESS;
840 std::string CraftDefinitionFuel::dump() const
842 std::ostringstream os(std::ios::binary);
843 os << "(fuel, recipe=\"" << recipe
844 << "\", burntime=" << burntime << ")"
845 << ", replacements=" << replacements.dump() << ")";
850 Craft definition manager
853 class CCraftDefManager: public IWritableCraftDefManager
858 m_craft_defs.resize(craft_hash_type_max + 1);
861 virtual ~CCraftDefManager()
866 virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
867 std::vector<ItemStack> &output_replacement, bool decrementInput,
868 IGameDef *gamedef) const
873 // If all input items are empty, abort.
874 bool all_empty = true;
875 for (const auto &item : input.items) {
884 std::vector<std::string> input_names;
885 input_names = craftGetItemNames(input.items, gamedef);
886 std::sort(input_names.begin(), input_names.end());
888 // Try hash types with increasing collision rate
889 // while remembering the latest, highest priority recipe.
890 CraftDefinition::RecipePriority priority_best =
891 CraftDefinition::NO_RECIPE;
892 CraftDefinition *def_best = nullptr;
893 for (int type = 0; type <= craft_hash_type_max; type++) {
894 u64 hash = getHashForGrid((CraftHashType) type, input_names);
896 /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
898 // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
899 // but that doesn't compile for some reason. This does.
900 auto col_iter = (m_craft_defs[type]).find(hash);
902 if (col_iter == (m_craft_defs[type]).end())
905 const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
906 // Walk crafting definitions from back to front, so that later
907 // definitions can override earlier ones.
908 for (std::vector<CraftDefinition*>::size_type
909 i = hash_collisions.size(); i > 0; i--) {
910 CraftDefinition *def = hash_collisions[i - 1];
912 /*errorstream << "Checking " << input.dump() << std::endl
913 << " against " << def->dump() << std::endl;*/
915 CraftDefinition::RecipePriority priority = def->getPriority();
916 if (priority > priority_best
917 && def->check(input, gamedef)) {
918 // Check if the crafted node/item exists
919 CraftOutput out = def->getOutput(input, gamedef);
921 is.deSerialize(out.item, gamedef->idef());
922 if (!is.isKnown(gamedef->idef())) {
923 infostream << "trying to craft non-existent "
924 << out.item << ", ignoring recipe" << std::endl;
929 priority_best = priority;
934 if (priority_best == CraftDefinition::NO_RECIPE)
937 def_best->decrementInput(input, output_replacement, gamedef);
941 virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
942 IGameDef *gamedef, unsigned limit=0) const
944 std::vector<CraftDefinition*> recipes;
946 auto vec_iter = m_output_craft_definitions.find(output.item);
948 if (vec_iter == m_output_craft_definitions.end())
951 const std::vector<CraftDefinition*> &vec = vec_iter->second;
953 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
955 for (std::vector<CraftDefinition*>::size_type i = vec.size();
957 CraftDefinition *def = vec[i - 1];
958 if (limit && recipes.size() >= limit)
960 recipes.push_back(def);
966 virtual bool clearCraftRecipesByOutput(const CraftOutput &output, IGameDef *gamedef)
968 auto vec_iter = m_output_craft_definitions.find(output.item);
970 if (vec_iter == m_output_craft_definitions.end())
973 std::vector<CraftDefinition*> &vec = vec_iter->second;
974 for (auto def : vec) {
975 // Recipes are not yet hashed at this point
976 std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
977 std::vector<CraftDefinition*> new_vec_by_input;
978 /* We will preallocate necessary memory addresses, so we don't need to reallocate them later.
979 This would save us some performance. */
980 new_vec_by_input.reserve(unhashed_inputs_vec.size());
981 for (auto &i2 : unhashed_inputs_vec) {
983 new_vec_by_input.push_back(i2);
986 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
988 m_output_craft_definitions.erase(output.item);
992 virtual bool clearCraftRecipesByInput(CraftMethod craft_method, unsigned int craft_grid_width,
993 const std::vector<std::string> &recipe, IGameDef *gamedef)
995 bool all_empty = true;
996 for (const auto &i : recipe) {
1005 CraftInput input(craft_method, craft_grid_width, craftGetItems(recipe, gamedef));
1006 // Recipes are not yet hashed at this point
1007 std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1008 std::vector<CraftDefinition*> new_vec_by_input;
1009 bool got_hit = false;
1010 for (std::vector<CraftDefinition*>::size_type
1011 i = unhashed_inputs_vec.size(); i > 0; i--) {
1012 CraftDefinition *def = unhashed_inputs_vec[i - 1];
1013 /* If the input doesn't match the recipe definition, this recipe definition later
1014 will be added back in source map. */
1015 if (!def->check(input, gamedef)) {
1016 new_vec_by_input.push_back(def);
1019 CraftOutput output = def->getOutput(input, gamedef);
1021 auto vec_iter = m_output_craft_definitions.find(output.item);
1022 if (vec_iter == m_output_craft_definitions.end())
1024 std::vector<CraftDefinition*> &vec = vec_iter->second;
1025 std::vector<CraftDefinition*> new_vec_by_output;
1026 /* We will preallocate necessary memory addresses, so we don't need
1027 to reallocate them later. This would save us some performance. */
1028 new_vec_by_output.reserve(vec.size());
1029 for (auto &vec_i : vec) {
1030 /* If pointers from map by input and output are not same,
1031 we will add 'CraftDefinition*' to a new vector. */
1033 /* Adding dereferenced iterator value (which are
1034 'CraftDefinition' reference) to a new vector. */
1035 new_vec_by_output.push_back(vec_i);
1038 // Swaps assigned to current key value with new vector for output map.
1039 m_output_craft_definitions[output.item].swap(new_vec_by_output);
1042 // Swaps value with new vector for input map.
1043 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
1048 virtual std::string dump() const
1050 std::ostringstream os(std::ios::binary);
1051 os << "Crafting definitions:\n";
1052 for (int type = 0; type <= craft_hash_type_max; ++type) {
1053 for (auto it = m_craft_defs[type].begin();
1054 it != m_craft_defs[type].end(); ++it) {
1055 for (std::vector<CraftDefinition*>::size_type i = 0;
1056 i < it->second.size(); i++) {
1057 os << "type " << type
1058 << " hash " << it->first
1059 << " def " << it->second[i]->dump()
1066 virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
1068 verbosestream << "registerCraft: registering craft definition: "
1069 << def->dump() << std::endl;
1070 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
1073 std::string output_name = craftGetItemName(
1074 def->getOutput(input, gamedef).item, gamedef);
1075 m_output_craft_definitions[output_name].push_back(def);
1077 virtual void clear()
1079 for (int type = 0; type <= craft_hash_type_max; ++type) {
1080 for (auto &it : m_craft_defs[type]) {
1081 for (auto &iit : it.second) {
1086 m_craft_defs[type].clear();
1088 m_output_craft_definitions.clear();
1090 virtual void initHashes(IGameDef *gamedef)
1092 // Move the CraftDefs from the unhashed layer into layers higher up.
1093 std::vector<CraftDefinition *> &unhashed =
1094 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1095 for (auto def : unhashed) {
1096 // Initialize and get the definition's hash
1097 def->initHash(gamedef);
1098 CraftHashType type = def->getHashType();
1099 u64 hash = def->getHash(type);
1101 // Enter the definition
1102 m_craft_defs[type][hash].push_back(def);
1107 std::vector<std::unordered_map<u64, std::vector<CraftDefinition*> > >
1109 std::unordered_map<std::string, std::vector<CraftDefinition*> >
1110 m_output_craft_definitions;
1113 IWritableCraftDefManager* createCraftDefManager()
1115 return new CCraftDefManager();