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 static bool hasGroupItem(const std::vector<std::string> &recipe)
42 for (const auto &item : recipe) {
43 if (isGroupRecipeStr(item))
49 inline u64 getHashForString(const std::string &recipe_str)
51 /*errorstream << "Hashing craft string \"" << recipe_str << '"';*/
52 return murmur_hash_64_ua(recipe_str.data(), recipe_str.length(), 0xdeadbeef);
55 static u64 getHashForGrid(CraftHashType type, const std::vector<std::string> &grid_names)
58 case CRAFT_HASH_TYPE_ITEM_NAMES: {
59 std::ostringstream os;
61 for (const std::string &grid_name : grid_names) {
62 if (!grid_name.empty()) {
63 os << (is_first ? "" : "\n") << grid_name;
67 return getHashForString(os.str());
68 } case CRAFT_HASH_TYPE_COUNT: {
70 for (const std::string &grid_name : grid_names)
71 if (!grid_name.empty())
74 } case CRAFT_HASH_TYPE_UNHASHED:
77 // invalid CraftHashType
82 // Check if input matches recipe
83 // Takes recipe groups into account
84 static bool inputItemMatchesRecipe(const std::string &inp_name,
85 const std::string &rec_name, IItemDefManager *idef)
88 if (inp_name == rec_name)
92 if (isGroupRecipeStr(rec_name) && idef->isKnown(inp_name)) {
93 const struct ItemDefinition &def = idef->get(inp_name);
94 Strfnd f(rec_name.substr(6));
95 bool all_groups_match = true;
97 std::string check_group = f.next(",");
98 if (itemgroup_get(def.groups, check_group) == 0) {
99 all_groups_match = false;
102 } while (!f.at_end());
103 if (all_groups_match)
111 // Deserialize an itemstring then return the name of the item
112 static std::string craftGetItemName(const std::string &itemstring, IGameDef *gamedef)
115 item.deSerialize(itemstring, gamedef->idef());
119 // (mapcar craftGetItemName itemstrings)
120 static std::vector<std::string> craftGetItemNames(
121 const std::vector<std::string> &itemstrings, IGameDef *gamedef)
123 std::vector<std::string> result;
124 result.reserve(itemstrings.size());
125 for (const auto &itemstring : itemstrings) {
126 result.push_back(craftGetItemName(itemstring, gamedef));
131 // Get name of each item, and return them as a new list.
132 static std::vector<std::string> craftGetItemNames(
133 const std::vector<ItemStack> &items, IGameDef *gamedef)
135 std::vector<std::string> result;
136 result.reserve(items.size());
137 for (const auto &item : items) {
138 result.push_back(item.name);
143 // convert a list of item names, to ItemStacks.
144 static std::vector<ItemStack> craftGetItems(
145 const std::vector<std::string> &items, IGameDef *gamedef)
147 std::vector<ItemStack> result;
148 result.reserve(items.size());
149 for (const auto &item : items) {
150 result.emplace_back(std::string(item), (u16)1,
151 (u16)0, gamedef->getItemDefManager());
156 // Compute bounding rectangle given a matrix of items
157 // Returns false if every item is ""
158 static bool craftGetBounds(const std::vector<std::string> &items, unsigned int width,
159 unsigned int &min_x, unsigned int &max_x,
160 unsigned int &min_y, unsigned int &max_y)
162 bool success = false;
165 for (const std::string &item : items) {
166 // Is this an actual item?
169 // This is the first nonempty item
174 if (x < min_x) min_x = x;
175 if (x > max_x) max_x = x;
176 if (y < min_y) min_y = y;
177 if (y > max_y) max_y = y;
191 // Removes 1 from each item stack
192 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
194 for (auto &item : input.items) {
200 // Removes 1 from each item stack with replacement support
201 // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"),
202 // a water bucket will not be removed but replaced by an empty bucket.
203 static void craftDecrementOrReplaceInput(CraftInput &input,
204 std::vector<ItemStack> &output_replacements,
205 const CraftReplacements &replacements,
208 if (replacements.pairs.empty()) {
209 craftDecrementInput(input, gamedef);
213 // Make a copy of the replacements pair list
214 std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
216 for (auto &item : input.items) {
217 // Find an appropriate replacement
218 bool found_replacement = false;
219 for (auto j = pairs.begin(); j != pairs.end(); ++j) {
220 if (inputItemMatchesRecipe(item.name, j->first, gamedef->idef())) {
221 if (item.count == 1) {
222 item.deSerialize(j->second, gamedef->idef());
223 found_replacement = true;
229 rep.deSerialize(j->second, gamedef->idef());
231 found_replacement = true;
232 output_replacements.push_back(rep);
237 // No replacement was found, simply decrement count by one
238 if (!found_replacement && item.count > 0)
243 // Dump an itemstring matrix
244 static std::string craftDumpMatrix(const std::vector<std::string> &items,
247 std::ostringstream os(std::ios::binary);
250 for(std::vector<std::string>::size_type i = 0;
251 i < items.size(); i++, x++) {
258 os << '"' << items[i] << '"';
264 // Dump an item matrix
265 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
268 std::ostringstream os(std::ios::binary);
271 for (std::vector<ItemStack>::size_type i = 0;
272 i < items.size(); i++, x++) {
279 os << '"' << (items[i].getItemString()) << '"';
290 bool CraftInput::empty() const
292 for (const auto &item : items) {
299 std::string CraftInput::dump() const
301 std::ostringstream os(std::ios::binary);
302 os << "(method=" << ((int)method) << ", items="
303 << craftDumpMatrix(items, width) << ")";
311 std::string CraftOutput::dump() const
313 std::ostringstream os(std::ios::binary);
314 os << "(item=\"" << item << "\", time=" << time << ")";
322 std::string CraftReplacements::dump() const
324 std::ostringstream os(std::ios::binary);
326 const char *sep = "";
327 for (const auto &repl_p : pairs) {
329 << '"' << (repl_p.first)
330 << "\"=>\"" << (repl_p.second) << '"';
338 CraftDefinitionShaped
341 CraftDefinitionShaped::CraftDefinitionShaped(
342 const std::string &output_,
344 const std::vector<std::string> &recipe_,
345 const CraftReplacements &replacements_):
346 output(output_), width(width_), recipe(recipe_), replacements(replacements_)
348 if (hasGroupItem(recipe))
349 priority = PRIORITY_SHAPED_AND_GROUPS;
351 priority = PRIORITY_SHAPED;
354 std::string CraftDefinitionShaped::getName() const
359 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
361 if (input.method != CRAFT_METHOD_NORMAL)
364 // Get input item matrix
365 std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
366 unsigned int inp_width = input.width;
369 while (inp_names.size() % inp_width != 0)
370 inp_names.emplace_back("");
373 unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0;
374 if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x,
375 inp_min_y, inp_max_y))
376 return false; // it was empty
378 std::vector<std::string> rec_names;
380 rec_names = recipe_names;
382 rec_names = craftGetItemNames(recipe, gamedef);
384 // Get recipe item matrix
385 unsigned int rec_width = width;
388 while (rec_names.size() % rec_width != 0)
389 rec_names.emplace_back("");
392 unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
393 if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x,
394 rec_min_y, rec_max_y))
395 return false; // it was empty
398 if (inp_max_x - inp_min_x != rec_max_x - rec_min_x ||
399 inp_max_y - inp_min_y != rec_max_y - rec_min_y)
402 // Verify that all item names in the bounding box are equal
403 unsigned int w = inp_max_x - inp_min_x + 1;
404 unsigned int h = inp_max_y - inp_min_y + 1;
406 for (unsigned int y=0; y < h; y++) {
407 unsigned int inp_y = (inp_min_y + y) * inp_width;
408 unsigned int rec_y = (rec_min_y + y) * rec_width;
410 for (unsigned int x=0; x < w; x++) {
411 unsigned int inp_x = inp_min_x + x;
412 unsigned int rec_x = rec_min_x + x;
414 if (!inputItemMatchesRecipe(
415 inp_names[inp_y + inp_x],
416 rec_names[rec_y + rec_x], gamedef->idef())) {
425 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
427 return CraftOutput(output, 0);
430 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
432 return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
435 void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
436 IGameDef *gamedef) const
438 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
441 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
443 assert(hash_inited); // Pre-condition
444 assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
445 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
447 std::vector<std::string> rec_names = recipe_names;
448 std::sort(rec_names.begin(), rec_names.end());
449 return getHashForGrid(type, rec_names);
452 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
457 recipe_names = craftGetItemNames(recipe, gamedef);
459 if (hasGroupItem(recipe_names))
460 hash_type = CRAFT_HASH_TYPE_COUNT;
462 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
465 std::string CraftDefinitionShaped::dump() const
467 std::ostringstream os(std::ios::binary);
468 os << "(shaped, output=\"" << output
469 << "\", recipe=" << craftDumpMatrix(recipe, width)
470 << ", replacements=" << replacements.dump() << ")";
475 CraftDefinitionShapeless
478 CraftDefinitionShapeless::CraftDefinitionShapeless(
479 const std::string &output_,
480 const std::vector<std::string> &recipe_,
481 const CraftReplacements &replacements_):
482 output(output_), recipe(recipe_), replacements(replacements_)
484 if (hasGroupItem(recipe))
485 priority = PRIORITY_SHAPELESS_AND_GROUPS;
487 priority = PRIORITY_SHAPELESS;
490 std::string CraftDefinitionShapeless::getName() const
495 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
497 if (input.method != CRAFT_METHOD_NORMAL)
500 // Filter empty items out of input
501 std::vector<std::string> input_filtered;
502 for (const auto &item : input.items) {
503 if (!item.name.empty())
504 input_filtered.push_back(item.name);
507 // If there is a wrong number of items in input, no match
508 if (input_filtered.size() != recipe.size()) {
509 /*dstream<<"Number of input items ("<<input_filtered.size()
510 <<") does not match recipe size ("<<recipe.size()<<") "
511 <<"of recipe with output="<<output<<std::endl;*/
515 std::vector<std::string> recipe_copy;
517 recipe_copy = recipe_names;
519 recipe_copy = craftGetItemNames(recipe, gamedef);
520 std::sort(recipe_copy.begin(), recipe_copy.end());
523 // Try with all permutations of the recipe,
524 // start from the lexicographically first permutation (=sorted),
525 // recipe_names is pre-sorted
527 // If all items match, the recipe matches
528 bool all_match = true;
529 //dstream<<"Testing recipe (output="<<output<<"):";
530 for (size_t i=0; i<recipe.size(); i++) {
531 //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
532 if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
538 //dstream<<" -> match="<<all_match<<std::endl;
541 } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
546 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
548 return CraftOutput(output, 0);
551 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
553 return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
556 void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
557 IGameDef *gamedef) const
559 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
562 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
564 assert(hash_inited); // Pre-condition
565 assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
566 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
567 return getHashForGrid(type, recipe_names);
570 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
575 recipe_names = craftGetItemNames(recipe, gamedef);
576 std::sort(recipe_names.begin(), recipe_names.end());
578 if (hasGroupItem(recipe_names))
579 hash_type = CRAFT_HASH_TYPE_COUNT;
581 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
584 std::string CraftDefinitionShapeless::dump() const
586 std::ostringstream os(std::ios::binary);
587 os << "(shapeless, output=\"" << output
588 << "\", recipe=" << craftDumpMatrix(recipe, recipe.size())
589 << ", replacements=" << replacements.dump() << ")";
594 CraftDefinitionToolRepair
597 CraftDefinitionToolRepair::CraftDefinitionToolRepair(float additional_wear_):
598 additional_wear(additional_wear_)
600 priority = PRIORITY_TOOLREPAIR;
603 static ItemStack craftToolRepair(
604 const ItemStack &item1,
605 const ItemStack &item2,
606 float additional_wear,
609 IItemDefManager *idef = gamedef->idef();
610 if (item1.count != 1 || item2.count != 1 || item1.name != item2.name
611 || idef->get(item1.name).type != ITEM_TOOL
612 || itemgroup_get(idef->get(item1.name).groups, "disable_repair") == 1) {
617 s32 item1_uses = 65536 - (u32) item1.wear;
618 s32 item2_uses = 65536 - (u32) item2.wear;
619 s32 new_uses = item1_uses + item2_uses;
620 s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
621 if (new_wear >= 65536)
626 ItemStack repaired = item1;
627 repaired.wear = new_wear;
631 std::string CraftDefinitionToolRepair::getName() const
636 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
638 if (input.method != CRAFT_METHOD_NORMAL)
643 for (const auto &item : input.items) {
647 else if (item2.empty())
653 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
654 return !repaired.empty();
657 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
661 for (const auto &item : input.items) {
665 else if (item2.empty())
669 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
670 return CraftOutput(repaired.getItemString(), 0);
673 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
675 std::vector<ItemStack> stack;
676 stack.emplace_back();
677 return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack);
680 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
681 IGameDef *gamedef) const
683 craftDecrementInput(input, gamedef);
686 std::string CraftDefinitionToolRepair::dump() const
688 std::ostringstream os(std::ios::binary);
689 os << "(toolrepair, additional_wear=" << additional_wear << ")";
694 CraftDefinitionCooking
697 CraftDefinitionCooking::CraftDefinitionCooking(
698 const std::string &output_,
699 const std::string &recipe_,
701 const CraftReplacements &replacements_):
702 output(output_), recipe(recipe_), cooktime(cooktime_), replacements(replacements_)
704 if (isGroupRecipeStr(recipe))
705 priority = PRIORITY_SHAPELESS_AND_GROUPS;
707 priority = PRIORITY_SHAPELESS;
710 std::string CraftDefinitionCooking::getName() const
715 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
717 if (input.method != CRAFT_METHOD_COOKING)
720 // Filter empty items out of input
721 std::vector<std::string> input_filtered;
722 for (const auto &item : input.items) {
723 const std::string &name = item.name;
725 input_filtered.push_back(name);
728 // If there is a wrong number of items in input, no match
729 if (input_filtered.size() != 1) {
730 /*dstream<<"Number of input items ("<<input_filtered.size()
731 <<") does not match recipe size (1) "
732 <<"of cooking recipe with output="<<output<<std::endl;*/
736 // Check the single input item
737 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
740 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
742 return CraftOutput(output, cooktime);
745 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
747 std::vector<std::string> rec;
748 rec.push_back(recipe);
749 return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
752 void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
753 IGameDef *gamedef) const
755 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
758 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
760 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
761 return getHashForString(recipe_name);
764 if (type == CRAFT_HASH_TYPE_COUNT) {
768 // illegal hash type for this CraftDefinition (pre-condition)
773 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
778 recipe_name = craftGetItemName(recipe, gamedef);
780 if (isGroupRecipeStr(recipe_name))
781 hash_type = CRAFT_HASH_TYPE_COUNT;
783 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
786 std::string CraftDefinitionCooking::dump() const
788 std::ostringstream os(std::ios::binary);
789 os << "(cooking, output=\"" << output
790 << "\", recipe=\"" << recipe
791 << "\", cooktime=" << cooktime << ")"
792 << ", replacements=" << replacements.dump() << ")";
800 CraftDefinitionFuel::CraftDefinitionFuel(
801 const std::string &recipe_,
803 const CraftReplacements &replacements_):
804 recipe(recipe_), burntime(burntime_), replacements(replacements_)
806 if (isGroupRecipeStr(recipe_name))
807 priority = PRIORITY_SHAPELESS_AND_GROUPS;
809 priority = PRIORITY_SHAPELESS;
812 std::string CraftDefinitionFuel::getName() const
817 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
819 if (input.method != CRAFT_METHOD_FUEL)
822 // Filter empty items out of input
823 std::vector<std::string> input_filtered;
824 for (const auto &item : input.items) {
825 const std::string &name = item.name;
827 input_filtered.push_back(name);
830 // If there is a wrong number of items in input, no match
831 if (input_filtered.size() != 1) {
832 /*dstream<<"Number of input items ("<<input_filtered.size()
833 <<") does not match recipe size (1) "
834 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
838 // Check the single input item
839 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
842 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
844 return CraftOutput("", burntime);
847 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
849 std::vector<std::string> rec;
850 rec.push_back(recipe);
851 return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
854 void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
855 IGameDef *gamedef) const
857 craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
860 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
862 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
863 return getHashForString(recipe_name);
866 if (type == CRAFT_HASH_TYPE_COUNT) {
870 // illegal hash type for this CraftDefinition (pre-condition)
875 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
880 recipe_name = craftGetItemName(recipe, gamedef);
882 if (isGroupRecipeStr(recipe_name))
883 hash_type = CRAFT_HASH_TYPE_COUNT;
885 hash_type = CRAFT_HASH_TYPE_ITEM_NAMES;
888 std::string CraftDefinitionFuel::dump() const
890 std::ostringstream os(std::ios::binary);
891 os << "(fuel, recipe=\"" << recipe
892 << "\", burntime=" << burntime << ")"
893 << ", replacements=" << replacements.dump() << ")";
898 Craft definition manager
901 class CCraftDefManager: public IWritableCraftDefManager
906 m_craft_defs.resize(craft_hash_type_max + 1);
909 virtual ~CCraftDefManager()
914 virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
915 std::vector<ItemStack> &output_replacement, bool decrementInput,
916 IGameDef *gamedef) const
921 std::vector<std::string> input_names;
922 input_names = craftGetItemNames(input.items, gamedef);
923 std::sort(input_names.begin(), input_names.end());
925 // Try hash types with increasing collision rate
926 // while remembering the latest, highest priority recipe.
927 CraftDefinition::RecipePriority priority_best =
928 CraftDefinition::PRIORITY_NO_RECIPE;
929 CraftDefinition *def_best = nullptr;
930 for (int type = 0; type <= craft_hash_type_max; type++) {
931 u64 hash = getHashForGrid((CraftHashType) type, input_names);
933 /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
935 // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
936 // but that doesn't compile for some reason. This does.
937 auto col_iter = (m_craft_defs[type]).find(hash);
939 if (col_iter == (m_craft_defs[type]).end())
942 const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
943 // Walk crafting definitions from back to front, so that later
944 // definitions can override earlier ones.
945 for (std::vector<CraftDefinition*>::size_type
946 i = hash_collisions.size(); i > 0; i--) {
947 CraftDefinition *def = hash_collisions[i - 1];
949 /*errorstream << "Checking " << input.dump() << std::endl
950 << " against " << def->dump() << std::endl;*/
952 CraftDefinition::RecipePriority priority = def->getPriority();
953 if (priority > priority_best
954 && def->check(input, gamedef)) {
955 // Check if the crafted node/item exists
956 CraftOutput out = def->getOutput(input, gamedef);
958 is.deSerialize(out.item, gamedef->idef());
959 if (!is.isKnown(gamedef->idef())) {
960 infostream << "trying to craft non-existent "
961 << out.item << ", ignoring recipe" << std::endl;
966 priority_best = priority;
971 if (priority_best == CraftDefinition::PRIORITY_NO_RECIPE)
974 def_best->decrementInput(input, output_replacement, gamedef);
978 virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
979 IGameDef *gamedef, unsigned limit=0) const
981 std::vector<CraftDefinition*> recipes;
983 auto vec_iter = m_output_craft_definitions.find(output.item);
985 if (vec_iter == m_output_craft_definitions.end())
988 const std::vector<CraftDefinition*> &vec = vec_iter->second;
990 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
992 for (std::vector<CraftDefinition*>::size_type i = vec.size();
994 CraftDefinition *def = vec[i - 1];
995 if (limit && recipes.size() >= limit)
997 recipes.push_back(def);
1003 virtual bool clearCraftsByOutput(const CraftOutput &output, IGameDef *gamedef)
1005 auto to_clear = m_output_craft_definitions.find(output.item);
1007 if (to_clear == m_output_craft_definitions.end())
1010 for (auto def : to_clear->second) {
1011 // Recipes are not yet hashed at this point
1012 std::vector<CraftDefinition *> &defs = m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0];
1013 defs.erase(std::remove(defs.begin(), defs.end(), def), defs.end());
1016 m_output_craft_definitions.erase(to_clear);
1020 virtual bool clearCraftsByInput(const CraftInput &input, IGameDef *gamedef)
1025 // Recipes are not yet hashed at this point
1026 std::vector<CraftDefinition *> &defs = m_craft_defs[(int)CRAFT_HASH_TYPE_UNHASHED][0];
1027 std::vector<CraftDefinition *> new_defs;
1028 bool got_hit = false;
1029 for (auto def : defs) {
1030 if (!def->check(input, gamedef)) {
1031 new_defs.push_back(def);
1035 std::string output = def->getOutput(input, gamedef).item;
1037 auto it = m_output_craft_definitions.find(craftGetItemName(output, gamedef));
1038 if (it == m_output_craft_definitions.end())
1040 std::vector<CraftDefinition *> &outdefs = it->second;
1041 outdefs.erase(std::remove(outdefs.begin(), outdefs.end(), def), outdefs.end());
1044 defs.swap(new_defs);
1049 virtual std::string dump() const
1051 std::ostringstream os(std::ios::binary);
1052 os << "Crafting definitions:\n";
1053 for (int type = 0; type <= craft_hash_type_max; ++type) {
1054 for (auto it = m_craft_defs[type].begin();
1055 it != m_craft_defs[type].end(); ++it) {
1056 for (std::vector<CraftDefinition*>::size_type i = 0;
1057 i < it->second.size(); i++) {
1058 os << "type " << type
1059 << " hash " << it->first
1060 << " def " << it->second[i]->dump()
1067 virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
1069 verbosestream << "registerCraft: registering craft definition: "
1070 << def->dump() << std::endl;
1071 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
1074 std::string output_name = craftGetItemName(
1075 def->getOutput(input, gamedef).item, gamedef);
1076 m_output_craft_definitions[output_name].push_back(def);
1078 virtual void clear()
1080 for (int type = 0; type <= craft_hash_type_max; ++type) {
1081 for (auto &it : m_craft_defs[type]) {
1082 for (auto &iit : it.second) {
1087 m_craft_defs[type].clear();
1089 m_output_craft_definitions.clear();
1091 virtual void initHashes(IGameDef *gamedef)
1093 // Move the CraftDefs from the unhashed layer into layers higher up.
1094 std::vector<CraftDefinition *> &unhashed =
1095 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1096 for (auto def : unhashed) {
1097 // Initialize and get the definition's hash
1098 def->initHash(gamedef);
1099 CraftHashType type = def->getHashType();
1100 u64 hash = def->getHash(type);
1102 // Enter the definition
1103 m_craft_defs[type][hash].push_back(def);
1108 std::vector<std::unordered_map<u64, std::vector<CraftDefinition*> > >
1110 std::unordered_map<std::string, std::vector<CraftDefinition*> >
1111 m_output_craft_definitions;
1114 IWritableCraftDefManager* createCraftDefManager()
1116 return new CCraftDefManager();