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"
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] != "") {
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] != "")
65 } case CRAFT_HASH_TYPE_UNHASHED:
68 // invalid CraftHashType
72 // Check if input matches recipe
73 // Takes recipe groups into account
74 static bool inputItemMatchesRecipe(const std::string &inp_name,
75 const std::string &rec_name, IItemDefManager *idef)
78 if (inp_name == rec_name)
82 if (isGroupRecipeStr(rec_name) && idef->isKnown(inp_name)) {
83 const struct ItemDefinition &def = idef->get(inp_name);
84 Strfnd f(rec_name.substr(6));
85 bool all_groups_match = true;
87 std::string check_group = f.next(",");
88 if (itemgroup_get(def.groups, check_group) == 0) {
89 all_groups_match = false;
101 // Deserialize an itemstring then return the name of the item
102 static std::string craftGetItemName(const std::string &itemstring, IGameDef *gamedef)
105 item.deSerialize(itemstring, gamedef->idef());
109 // (mapcar craftGetItemName itemstrings)
110 static std::vector<std::string> craftGetItemNames(
111 const std::vector<std::string> &itemstrings, IGameDef *gamedef)
113 std::vector<std::string> result;
114 for (std::vector<std::string>::const_iterator
115 it = itemstrings.begin();
116 it != itemstrings.end(); it++) {
117 result.push_back(craftGetItemName(*it, 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 for (std::vector<ItemStack>::const_iterator
129 it != items.end(); it++) {
130 result.push_back(it->name);
135 // convert a list of item names, to ItemStacks.
136 static std::vector<ItemStack> craftGetItems(
137 const std::vector<std::string> &items, IGameDef *gamedef)
139 std::vector<ItemStack> result;
140 for (std::vector<std::string>::const_iterator
142 it != items.end(); it++) {
143 result.push_back(ItemStack(std::string(*it), (u16)1,
144 (u16)0, "", gamedef->getItemDefManager()));
149 // Compute bounding rectangle given a matrix of items
150 // Returns false if every item is ""
151 static bool craftGetBounds(const std::vector<std::string> &items, unsigned int width,
152 unsigned int &min_x, unsigned int &max_x,
153 unsigned int &min_y, unsigned int &max_y)
155 bool success = false;
158 for (std::vector<std::string>::const_iterator
160 it != items.end(); it++) {
161 // Is this an actual item?
164 // This is the first nonempty item
169 if (x < min_x) min_x = x;
170 if (x > max_x) max_x = x;
171 if (y < min_y) min_y = y;
172 if (y > max_y) max_y = y;
186 // Removes 1 from each item stack
187 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
189 for (std::vector<ItemStack>::iterator
190 it = input.items.begin();
191 it != input.items.end(); it++) {
197 // Removes 1 from each item stack with replacement support
198 // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"),
199 // a water bucket will not be removed but replaced by an empty bucket.
200 static void craftDecrementOrReplaceInput(CraftInput &input,
201 const CraftReplacements &replacements,
204 if (replacements.pairs.empty()) {
205 craftDecrementInput(input, gamedef);
209 // Make a copy of the replacements pair list
210 std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
212 for (std::vector<ItemStack>::iterator
213 it = input.items.begin();
214 it != input.items.end(); it++) {
215 if (it->count == 1) {
216 // Find an appropriate replacement
217 bool found_replacement = false;
218 for (std::vector<std::pair<std::string, std::string> >::iterator
220 j != pairs.end(); j++) {
221 if (it->name == craftGetItemName(j->first, gamedef)) {
222 it->deSerialize(j->second, gamedef->idef());
223 found_replacement = true;
228 // No replacement was found, simply decrement count to zero
229 if (!found_replacement)
231 } else if (it->count >= 2) {
232 // Ignore replacements for items with count >= 2
238 // Dump an itemstring matrix
239 static std::string craftDumpMatrix(const std::vector<std::string> &items,
242 std::ostringstream os(std::ios::binary);
245 for(std::vector<std::string>::const_iterator
247 it != items.end(); it++, x++) {
254 os << '"' << (*it) << '"';
260 // Dump an item matrix
261 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
264 std::ostringstream os(std::ios::binary);
267 for (std::vector<ItemStack>::const_iterator
269 it != items.end(); it++, x++) {
276 os << '"' << (it->getItemString()) << '"';
287 std::string CraftInput::dump() const
289 std::ostringstream os(std::ios::binary);
290 os << "(method=" << ((int)method) << ", items="
291 << craftDumpMatrix(items, width) << ")";
299 std::string CraftOutput::dump() const
301 std::ostringstream os(std::ios::binary);
302 os << "(item=\"" << item << "\", time=" << time << ")";
310 std::string CraftReplacements::dump() const
312 std::ostringstream os(std::ios::binary);
314 const char *sep = "";
315 for (std::vector<std::pair<std::string, std::string> >::const_iterator
317 it != pairs.end(); it++) {
318 os << sep << '"' << (it->first) << "\"=>\"" << (it->second) << '"';
325 void CraftReplacements::serialize(std::ostream &os) const
327 writeU16(os, pairs.size());
328 for (u32 i=0; i<pairs.size(); i++) {
329 os << serializeString(pairs[i].first);
330 os << serializeString(pairs[i].second);
334 void CraftReplacements::deSerialize(std::istream &is)
337 u32 count = readU16(is);
338 for (u32 i=0; i<count; i++) {
339 std::string first = deSerializeString(is);
340 std::string second = deSerializeString(is);
341 pairs.push_back(std::make_pair(first, second));
349 void CraftDefinition::serialize(std::ostream &os) const
351 writeU8(os, 1); // version
352 os << serializeString(getName());
356 CraftDefinition* CraftDefinition::deSerialize(std::istream &is)
358 int version = readU8(is);
359 if (version != 1) throw SerializationError(
360 "unsupported CraftDefinition version");
361 std::string name = deSerializeString(is);
362 CraftDefinition *def = NULL;
363 if (name == "shaped") {
364 def = new CraftDefinitionShaped;
365 } else if (name == "shapeless") {
366 def = new CraftDefinitionShapeless;
367 } else if (name == "toolrepair") {
368 def = new CraftDefinitionToolRepair;
369 } else if (name == "cooking") {
370 def = new CraftDefinitionCooking;
371 } else if (name == "fuel") {
372 def = new CraftDefinitionFuel;
374 infostream << "Unknown CraftDefinition name=\""
375 << name << '"' << std::endl;
376 throw SerializationError("Unknown CraftDefinition name");
378 def->deSerializeBody(is, version);
383 CraftDefinitionShaped
386 std::string CraftDefinitionShaped::getName() const
391 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
393 if (input.method != CRAFT_METHOD_NORMAL)
396 // Get input item matrix
397 std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
398 unsigned int inp_width = input.width;
401 while (inp_names.size() % inp_width != 0)
402 inp_names.push_back("");
405 unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0;
406 if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x,
407 inp_min_y, inp_max_y))
408 return false; // it was empty
410 std::vector<std::string> rec_names;
412 rec_names = recipe_names;
414 rec_names = craftGetItemNames(recipe, gamedef);
416 // Get recipe item matrix
417 unsigned int rec_width = width;
420 while (rec_names.size() % rec_width != 0)
421 rec_names.push_back("");
424 unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
425 if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x,
426 rec_min_y, rec_max_y))
427 return false; // it was empty
430 if (inp_max_x - inp_min_x != rec_max_x - rec_min_x ||
431 inp_max_y - inp_min_y != rec_max_y - rec_min_y)
434 // Verify that all item names in the bounding box are equal
435 unsigned int w = inp_max_x - inp_min_x + 1;
436 unsigned int h = inp_max_y - inp_min_y + 1;
438 for (unsigned int y=0; y < h; y++) {
439 unsigned int inp_y = (inp_min_y + y) * inp_width;
440 unsigned int rec_y = (rec_min_y + y) * rec_width;
442 for (unsigned int x=0; x < w; x++) {
443 unsigned int inp_x = inp_min_x + x;
444 unsigned int rec_x = rec_min_x + x;
446 if (!inputItemMatchesRecipe(
447 inp_names[inp_y + inp_x],
448 rec_names[rec_y + rec_x], gamedef->idef())) {
457 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
459 return CraftOutput(output, 0);
462 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
464 return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
467 void CraftDefinitionShaped::decrementInput(CraftInput &input, IGameDef *gamedef) const
469 craftDecrementOrReplaceInput(input, replacements, gamedef);
472 CraftHashType CraftDefinitionShaped::getHashType() const
474 assert(hash_inited); // Pre-condition
475 bool has_group = false;
476 for (size_t i = 0; i < recipe_names.size(); i++) {
477 if (isGroupRecipeStr(recipe_names[i])) {
483 return CRAFT_HASH_TYPE_COUNT;
485 return CRAFT_HASH_TYPE_ITEM_NAMES;
488 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
490 assert(hash_inited); // Pre-condition
491 assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
492 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
494 std::vector<std::string> rec_names = recipe_names;
495 std::sort(rec_names.begin(), rec_names.end());
496 return getHashForGrid(type, rec_names);
499 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
504 recipe_names = craftGetItemNames(recipe, gamedef);
507 std::string CraftDefinitionShaped::dump() const
509 std::ostringstream os(std::ios::binary);
510 os << "(shaped, output=\"" << output
511 << "\", recipe=" << craftDumpMatrix(recipe, width)
512 << ", replacements=" << replacements.dump() << ")";
516 void CraftDefinitionShaped::serializeBody(std::ostream &os) const
518 os << serializeString(output);
520 writeU16(os, recipe.size());
521 for (u32 i=0; i<recipe.size(); i++)
522 os << serializeString(recipe[i]);
523 replacements.serialize(os);
526 void CraftDefinitionShaped::deSerializeBody(std::istream &is, int version)
528 if (version != 1) throw SerializationError(
529 "unsupported CraftDefinitionShaped version");
530 output = deSerializeString(is);
533 u32 count = readU16(is);
534 for (u32 i=0; i<count; i++)
535 recipe.push_back(deSerializeString(is));
536 replacements.deSerialize(is);
540 CraftDefinitionShapeless
543 std::string CraftDefinitionShapeless::getName() const
548 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
550 if (input.method != CRAFT_METHOD_NORMAL)
553 // Filter empty items out of input
554 std::vector<std::string> input_filtered;
555 for (std::vector<ItemStack>::const_iterator
556 it = input.items.begin();
557 it != input.items.end(); it++) {
559 input_filtered.push_back(it->name);
562 // If there is a wrong number of items in input, no match
563 if (input_filtered.size() != recipe.size()) {
564 /*dstream<<"Number of input items ("<<input_filtered.size()
565 <<") does not match recipe size ("<<recipe.size()<<") "
566 <<"of recipe with output="<<output<<std::endl;*/
570 std::vector<std::string> recipe_copy;
572 recipe_copy = recipe_names;
574 recipe_copy = craftGetItemNames(recipe, gamedef);
575 std::sort(recipe_copy.begin(), recipe_copy.end());
578 // Try with all permutations of the recipe,
579 // start from the lexicographically first permutation (=sorted),
580 // recipe_names is pre-sorted
582 // If all items match, the recipe matches
583 bool all_match = true;
584 //dstream<<"Testing recipe (output="<<output<<"):";
585 for (size_t i=0; i<recipe.size(); i++) {
586 //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
587 if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
593 //dstream<<" -> match="<<all_match<<std::endl;
596 } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
601 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
603 return CraftOutput(output, 0);
606 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
608 return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
611 void CraftDefinitionShapeless::decrementInput(CraftInput &input, IGameDef *gamedef) const
613 craftDecrementOrReplaceInput(input, replacements, gamedef);
616 CraftHashType CraftDefinitionShapeless::getHashType() const
618 assert(hash_inited); // Pre-condition
619 bool has_group = false;
620 for (size_t i = 0; i < recipe_names.size(); i++) {
621 if (isGroupRecipeStr(recipe_names[i])) {
627 return CRAFT_HASH_TYPE_COUNT;
629 return CRAFT_HASH_TYPE_ITEM_NAMES;
632 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
634 assert(hash_inited); // Pre-condition
635 assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
636 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
637 return getHashForGrid(type, recipe_names);
640 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
645 recipe_names = craftGetItemNames(recipe, gamedef);
646 std::sort(recipe_names.begin(), recipe_names.end());
649 std::string CraftDefinitionShapeless::dump() const
651 std::ostringstream os(std::ios::binary);
652 os << "(shapeless, output=\"" << output
653 << "\", recipe=" << craftDumpMatrix(recipe, recipe.size())
654 << ", replacements=" << replacements.dump() << ")";
658 void CraftDefinitionShapeless::serializeBody(std::ostream &os) const
660 os << serializeString(output);
661 writeU16(os, recipe.size());
662 for (u32 i=0; i<recipe.size(); i++)
663 os << serializeString(recipe[i]);
664 replacements.serialize(os);
667 void CraftDefinitionShapeless::deSerializeBody(std::istream &is, int version)
669 if (version != 1) throw SerializationError(
670 "unsupported CraftDefinitionShapeless version");
671 output = deSerializeString(is);
673 u32 count = readU16(is);
674 for (u32 i=0; i<count; i++)
675 recipe.push_back(deSerializeString(is));
676 replacements.deSerialize(is);
680 CraftDefinitionToolRepair
683 static ItemStack craftToolRepair(
684 const ItemStack &item1,
685 const ItemStack &item2,
686 float additional_wear,
689 IItemDefManager *idef = gamedef->idef();
690 if (item1.count != 1 || item2.count != 1 || item1.name != item2.name
691 || idef->get(item1.name).type != ITEM_TOOL
692 || idef->get(item2.name).type != ITEM_TOOL) {
697 s32 item1_uses = 65536 - (u32) item1.wear;
698 s32 item2_uses = 65536 - (u32) item2.wear;
699 s32 new_uses = item1_uses + item2_uses;
700 s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
701 if (new_wear >= 65536)
706 ItemStack repaired = item1;
707 repaired.wear = new_wear;
711 std::string CraftDefinitionToolRepair::getName() const
716 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
718 if (input.method != CRAFT_METHOD_NORMAL)
723 for (std::vector<ItemStack>::const_iterator
724 it = input.items.begin();
725 it != input.items.end(); it++) {
729 else if (item2.empty())
735 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
736 return !repaired.empty();
739 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
743 for (std::vector<ItemStack>::const_iterator
744 it = input.items.begin();
745 it != input.items.end(); it++) {
749 else if (item2.empty())
753 ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
754 return CraftOutput(repaired.getItemString(), 0);
757 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
759 std::vector<ItemStack> stack;
760 stack.push_back(ItemStack());
761 return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack);
764 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, IGameDef *gamedef) const
766 craftDecrementInput(input, gamedef);
769 std::string CraftDefinitionToolRepair::dump() const
771 std::ostringstream os(std::ios::binary);
772 os << "(toolrepair, additional_wear=" << additional_wear << ")";
776 void CraftDefinitionToolRepair::serializeBody(std::ostream &os) const
778 writeF1000(os, additional_wear);
781 void CraftDefinitionToolRepair::deSerializeBody(std::istream &is, int version)
783 if (version != 1) throw SerializationError(
784 "unsupported CraftDefinitionToolRepair version");
785 additional_wear = readF1000(is);
789 CraftDefinitionCooking
792 std::string CraftDefinitionCooking::getName() const
797 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
799 if (input.method != CRAFT_METHOD_COOKING)
802 // Filter empty items out of input
803 std::vector<std::string> input_filtered;
804 for (std::vector<ItemStack>::const_iterator
805 it = input.items.begin();
806 it != input.items.end(); it++) {
808 input_filtered.push_back(it->name);
811 // If there is a wrong number of items in input, no match
812 if (input_filtered.size() != 1) {
813 /*dstream<<"Number of input items ("<<input_filtered.size()
814 <<") does not match recipe size (1) "
815 <<"of cooking recipe with output="<<output<<std::endl;*/
819 // Check the single input item
820 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
823 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
825 return CraftOutput(output, cooktime);
828 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
830 std::vector<std::string> rec;
831 rec.push_back(recipe);
832 return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
835 void CraftDefinitionCooking::decrementInput(CraftInput &input, IGameDef *gamedef) const
837 craftDecrementOrReplaceInput(input, replacements, gamedef);
840 CraftHashType CraftDefinitionCooking::getHashType() const
842 if (isGroupRecipeStr(recipe_name))
843 return CRAFT_HASH_TYPE_COUNT;
845 return CRAFT_HASH_TYPE_ITEM_NAMES;
848 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
850 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
851 return getHashForString(recipe_name);
852 } else if (type == CRAFT_HASH_TYPE_COUNT) {
855 //illegal hash type for this CraftDefinition (pre-condition)
861 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
866 recipe_name = craftGetItemName(recipe, gamedef);
869 std::string CraftDefinitionCooking::dump() const
871 std::ostringstream os(std::ios::binary);
872 os << "(cooking, output=\"" << output
873 << "\", recipe=\"" << recipe
874 << "\", cooktime=" << cooktime << ")"
875 << ", replacements=" << replacements.dump() << ")";
879 void CraftDefinitionCooking::serializeBody(std::ostream &os) const
881 os << serializeString(output);
882 os << serializeString(recipe);
883 writeF1000(os, cooktime);
884 replacements.serialize(os);
887 void CraftDefinitionCooking::deSerializeBody(std::istream &is, int version)
889 if (version != 1) throw SerializationError(
890 "unsupported CraftDefinitionCooking version");
891 output = deSerializeString(is);
892 recipe = deSerializeString(is);
893 cooktime = readF1000(is);
894 replacements.deSerialize(is);
901 std::string CraftDefinitionFuel::getName() const
906 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
908 if (input.method != CRAFT_METHOD_FUEL)
911 // Filter empty items out of input
912 std::vector<std::string> input_filtered;
913 for (std::vector<ItemStack>::const_iterator
914 it = input.items.begin();
915 it != input.items.end(); it++) {
917 input_filtered.push_back(it->name);
920 // If there is a wrong number of items in input, no match
921 if (input_filtered.size() != 1) {
922 /*dstream<<"Number of input items ("<<input_filtered.size()
923 <<") does not match recipe size (1) "
924 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
928 // Check the single input item
929 return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
932 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
934 return CraftOutput("", burntime);
937 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
939 std::vector<std::string> rec;
940 rec.push_back(recipe);
941 return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
944 void CraftDefinitionFuel::decrementInput(CraftInput &input, IGameDef *gamedef) const
946 craftDecrementOrReplaceInput(input, replacements, gamedef);
949 CraftHashType CraftDefinitionFuel::getHashType() const
951 if (isGroupRecipeStr(recipe_name))
952 return CRAFT_HASH_TYPE_COUNT;
954 return CRAFT_HASH_TYPE_ITEM_NAMES;
957 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
959 if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
960 return getHashForString(recipe_name);
961 } else if (type == CRAFT_HASH_TYPE_COUNT) {
964 //illegal hash type for this CraftDefinition (pre-condition)
970 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
975 recipe_name = craftGetItemName(recipe, gamedef);
977 std::string CraftDefinitionFuel::dump() const
979 std::ostringstream os(std::ios::binary);
980 os << "(fuel, recipe=\"" << recipe
981 << "\", burntime=" << burntime << ")"
982 << ", replacements=" << replacements.dump() << ")";
986 void CraftDefinitionFuel::serializeBody(std::ostream &os) const
988 os << serializeString(recipe);
989 writeF1000(os, burntime);
990 replacements.serialize(os);
993 void CraftDefinitionFuel::deSerializeBody(std::istream &is, int version)
995 if (version != 1) throw SerializationError(
996 "unsupported CraftDefinitionFuel version");
997 recipe = deSerializeString(is);
998 burntime = readF1000(is);
999 replacements.deSerialize(is);
1003 Craft definition manager
1006 class CCraftDefManager: public IWritableCraftDefManager
1011 m_craft_defs.resize(craft_hash_type_max + 1);
1014 virtual ~CCraftDefManager()
1019 virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
1020 bool decrementInput, IGameDef *gamedef) const
1025 // If all input items are empty, abort.
1026 bool all_empty = true;
1027 for (std::vector<ItemStack>::const_iterator
1028 it = input.items.begin();
1029 it != input.items.end(); it++) {
1038 std::vector<std::string> input_names;
1039 input_names = craftGetItemNames(input.items, gamedef);
1040 std::sort(input_names.begin(), input_names.end());
1042 // Try hash types with increasing collision rate, and return if found.
1043 for (int type = 0; type <= craft_hash_type_max; type++) {
1044 u64 hash = getHashForGrid((CraftHashType) type, input_names);
1046 /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
1048 // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
1049 // but that doesn't compile for some reason. This does.
1050 std::map<u64, std::vector<CraftDefinition*> >::const_iterator
1051 col_iter = (m_craft_defs[type]).find(hash);
1053 if (col_iter == (m_craft_defs[type]).end())
1056 const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
1057 // Walk crafting definitions from back to front, so that later
1058 // definitions can override earlier ones.
1059 for (std::vector<CraftDefinition*>::const_reverse_iterator
1060 it = hash_collisions.rbegin();
1061 it != hash_collisions.rend(); it++) {
1062 CraftDefinition *def = *it;
1064 /*errorstream << "Checking " << input.dump() << std::endl
1065 << " against " << def->dump() << std::endl;*/
1067 if (def->check(input, gamedef)) {
1068 // Get output, then decrement input (if requested)
1069 output = def->getOutput(input, gamedef);
1071 def->decrementInput(input, gamedef);
1072 /*errorstream << "Check RETURNS TRUE" << std::endl;*/
1080 virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
1081 IGameDef *gamedef, unsigned limit=0) const
1083 std::vector<CraftDefinition*> recipes;
1085 std::map<std::string, std::vector<CraftDefinition*> >::const_iterator
1086 vec_iter = m_output_craft_definitions.find(output.item);
1088 if (vec_iter == m_output_craft_definitions.end())
1091 const std::vector<CraftDefinition*> &vec = vec_iter->second;
1093 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
1095 for (std::vector<CraftDefinition*>::const_reverse_iterator
1096 it = vec.rbegin(); it != vec.rend(); ++it) {
1097 if (limit && recipes.size() >= limit)
1099 recipes.push_back(*it);
1104 virtual std::string dump() const
1106 std::ostringstream os(std::ios::binary);
1107 os << "Crafting definitions:\n";
1108 for (int type = 0; type <= craft_hash_type_max; type++) {
1109 for (std::map<u64, std::vector<CraftDefinition*> >::const_iterator
1110 it = (m_craft_defs[type]).begin();
1111 it != (m_craft_defs[type]).end(); it++) {
1112 for (std::vector<CraftDefinition*>::const_iterator
1113 iit = it->second.begin(); iit != it->second.end(); iit++) {
1114 os << "type " << type << " hash " << it->first << (*iit)->dump() << "\n";
1120 virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
1122 verbosestream << "registerCraft: registering craft definition: "
1123 << def->dump() << std::endl;
1124 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
1127 std::string output_name = craftGetItemName(
1128 def->getOutput(input, gamedef).item, gamedef);
1129 m_output_craft_definitions[output_name].push_back(def);
1131 virtual void clear()
1133 for (int type = 0; type <= craft_hash_type_max; type++) {
1134 for (std::map<u64, std::vector<CraftDefinition*> >::iterator
1135 it = m_craft_defs[type].begin();
1136 it != m_craft_defs[type].end(); it++) {
1137 for (std::vector<CraftDefinition*>::iterator
1138 iit = it->second.begin(); iit != it->second.end(); iit++) {
1143 m_craft_defs[type].clear();
1145 m_output_craft_definitions.clear();
1147 virtual void initHashes(IGameDef *gamedef)
1149 // Move the CraftDefs from the unhashed layer into layers higher up.
1150 for (std::vector<CraftDefinition*>::iterator
1151 it = (m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0]).begin();
1152 it != (m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0]).end(); it++) {
1153 CraftDefinition *def = *it;
1155 // Initialize and get the definition's hash
1156 def->initHash(gamedef);
1157 CraftHashType type = def->getHashType();
1158 u64 hash = def->getHash(type);
1160 // Enter the definition
1161 m_craft_defs[type][hash].push_back(def);
1163 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].clear();
1166 //TODO: change both maps to unordered_map when c++11 can be used
1167 std::vector<std::map<u64, std::vector<CraftDefinition*> > > m_craft_defs;
1168 std::map<std::string, std::vector<CraftDefinition*> > m_output_craft_definitions;
1171 IWritableCraftDefManager* createCraftDefManager()
1173 return new CCraftDefManager();