]> git.lizzy.rs Git - minetest.git/blob - src/craftdef.cpp
Speed up the craft definition handling (#8097)
[minetest.git] / src / craftdef.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include "craftdef.h"
21
22 #include "irrlichttypes.h"
23 #include "log.h"
24 #include <sstream>
25 #include <set>
26 #include <algorithm>
27 #include "gamedef.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"
34
35 inline bool isGroupRecipeStr(const std::string &rec_name)
36 {
37         return str_starts_with(rec_name, std::string("group:"));
38 }
39
40 inline u64 getHashForString(const std::string &recipe_str)
41 {
42         /*errorstream << "Hashing craft string  \"" << recipe_str << '"';*/
43         return murmur_hash_64_ua(recipe_str.data(), recipe_str.length(), 0xdeadbeef);
44 }
45
46 static u64 getHashForGrid(CraftHashType type, const std::vector<std::string> &grid_names)
47 {
48         switch (type) {
49                 case CRAFT_HASH_TYPE_ITEM_NAMES: {
50                         std::ostringstream os;
51                         bool is_first = true;
52                         for (const std::string &grid_name : grid_names) {
53                                 if (!grid_name.empty()) {
54                                         os << (is_first ? "" : "\n") << grid_name;
55                                         is_first = false;
56                                 }
57                         }
58                         return getHashForString(os.str());
59                 } case CRAFT_HASH_TYPE_COUNT: {
60                         u64 cnt = 0;
61                         for (const std::string &grid_name : grid_names)
62                                 if (!grid_name.empty())
63                                         cnt++;
64                         return cnt;
65                 } case CRAFT_HASH_TYPE_UNHASHED:
66                         return 0;
67         }
68         // invalid CraftHashType
69         assert(false);
70         return 0;
71 }
72
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)
77 {
78         // Exact name
79         if (inp_name == rec_name)
80                 return true;
81
82         // Group
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;
87                 do {
88                         std::string check_group = f.next(",");
89                         if (itemgroup_get(def.groups, check_group) == 0) {
90                                 all_groups_match = false;
91                                 break;
92                         }
93                 } while (!f.at_end());
94                 if (all_groups_match)
95                         return true;
96         }
97
98         // Didn't match
99         return false;
100 }
101
102 // Deserialize an itemstring then return the name of the item
103 static std::string craftGetItemName(const std::string &itemstring, IGameDef *gamedef)
104 {
105         ItemStack item;
106         item.deSerialize(itemstring, gamedef->idef());
107         return item.name;
108 }
109
110 // (mapcar craftGetItemName itemstrings)
111 static std::vector<std::string> craftGetItemNames(
112                 const std::vector<std::string> &itemstrings, IGameDef *gamedef)
113 {
114         std::vector<std::string> result;
115         result.reserve(itemstrings.size());
116         for (const auto &itemstring : itemstrings) {
117                 result.push_back(craftGetItemName(itemstring, gamedef));
118         }
119         return result;
120 }
121
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)
125 {
126         std::vector<std::string> result;
127         result.reserve(items.size());
128         for (const auto &item : items) {
129                 result.push_back(item.name);
130         }
131         return result;
132 }
133
134 // convert a list of item names, to ItemStacks.
135 static std::vector<ItemStack> craftGetItems(
136                 const std::vector<std::string> &items, IGameDef *gamedef)
137 {
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());
143         }
144         return result;
145 }
146
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)
152 {
153         bool success = false;
154         unsigned int x = 0;
155         unsigned int y = 0;
156         for (const std::string &item : items) {
157                 // Is this an actual item?
158                 if (!item.empty()) {
159                         if (!success) {
160                                 // This is the first nonempty item
161                                 min_x = max_x = x;
162                                 min_y = max_y = y;
163                                 success = true;
164                         } else {
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;
169                         }
170                 }
171
172                 // Step coordinate
173                 x++;
174                 if (x == width) {
175                         x = 0;
176                         y++;
177                 }
178         }
179         return success;
180 }
181
182 // Removes 1 from each item stack
183 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
184 {
185         for (auto &item : input.items) {
186                 if (item.count != 0)
187                         item.remove(1);
188         }
189 }
190
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,
197                 IGameDef *gamedef)
198 {
199         if (replacements.pairs.empty()) {
200                 craftDecrementInput(input, gamedef);
201                 return;
202         }
203
204         // Make a copy of the replacements pair list
205         std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
206
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;
215                                         pairs.erase(j);
216                                         break;
217                                 }
218
219                                 ItemStack rep;
220                                 rep.deSerialize(j->second, gamedef->idef());
221                                 item.remove(1);
222                                 found_replacement = true;
223                                 output_replacements.push_back(rep);
224                                 break;
225
226                         }
227                 }
228                 // No replacement was found, simply decrement count by one
229                 if (!found_replacement && item.count > 0)
230                         item.remove(1);
231         }
232 }
233
234 // Dump an itemstring matrix
235 static std::string craftDumpMatrix(const std::vector<std::string> &items,
236                 unsigned int width)
237 {
238         std::ostringstream os(std::ios::binary);
239         os << "{ ";
240         unsigned int x = 0;
241         for(std::vector<std::string>::size_type i = 0;
242                         i < items.size(); i++, x++) {
243                 if (x == width) {
244                         os << "; ";
245                         x = 0;
246                 } else if (x != 0) {
247                         os << ",";
248                 }
249                 os << '"' << items[i] << '"';
250         }
251         os << " }";
252         return os.str();
253 }
254
255 // Dump an item matrix
256 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
257                 unsigned int width)
258 {
259         std::ostringstream os(std::ios::binary);
260         os << "{ ";
261         unsigned int x = 0;
262         for (std::vector<ItemStack>::size_type i = 0;
263                         i < items.size(); i++, x++) {
264                 if (x == width) {
265                         os << "; ";
266                         x = 0;
267                 } else if (x != 0) {
268                         os << ",";
269                 }
270                 os << '"' << (items[i].getItemString()) << '"';
271         }
272         os << " }";
273         return os.str();
274 }
275
276
277 /*
278         CraftInput
279 */
280
281 std::string CraftInput::dump() const
282 {
283         std::ostringstream os(std::ios::binary);
284         os << "(method=" << ((int)method) << ", items="
285                 << craftDumpMatrix(items, width) << ")";
286         return os.str();
287 }
288
289 /*
290         CraftOutput
291 */
292
293 std::string CraftOutput::dump() const
294 {
295         std::ostringstream os(std::ios::binary);
296         os << "(item=\"" << item << "\", time=" << time << ")";
297         return os.str();
298 }
299
300 /*
301         CraftReplacements
302 */
303
304 std::string CraftReplacements::dump() const
305 {
306         std::ostringstream os(std::ios::binary);
307         os<<"{";
308         const char *sep = "";
309         for (const auto &repl_p : pairs) {
310                 os << sep
311                         << '"' << (repl_p.first)
312                         << "\"=>\"" << (repl_p.second) << '"';
313                 sep = ",";
314         }
315         os << "}";
316         return os.str();
317 }
318
319 /*
320         CraftDefinitionShaped
321 */
322
323 std::string CraftDefinitionShaped::getName() const
324 {
325         return "shaped";
326 }
327
328 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
329 {
330         if (input.method != CRAFT_METHOD_NORMAL)
331                 return false;
332
333         // Get input item matrix
334         std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
335         unsigned int inp_width = input.width;
336         if (inp_width == 0)
337                 return false;
338         while (inp_names.size() % inp_width != 0)
339                 inp_names.emplace_back("");
340
341         // Get input bounds
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
346
347         std::vector<std::string> rec_names;
348         if (hash_inited)
349                 rec_names = recipe_names;
350         else
351                 rec_names = craftGetItemNames(recipe, gamedef);
352
353         // Get recipe item matrix
354         unsigned int rec_width = width;
355         if (rec_width == 0)
356                 return false;
357         while (rec_names.size() % rec_width != 0)
358                 rec_names.emplace_back("");
359
360         // Get recipe bounds
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
365
366         // Different sizes?
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)
369                 return false;
370
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;
374
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;
378
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;
382
383                         if (!inputItemMatchesRecipe(
384                                         inp_names[inp_y + inp_x],
385                                         rec_names[rec_y + rec_x], gamedef->idef())) {
386                                 return false;
387                         }
388                 }
389         }
390
391         return true;
392 }
393
394 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
395 {
396         return CraftOutput(output, 0);
397 }
398
399 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
400 {
401         return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
402 }
403
404 void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
405          IGameDef *gamedef) const
406 {
407         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
408 }
409
410 CraftHashType CraftDefinitionShaped::getHashType() const
411 {
412         assert(hash_inited); // Pre-condition
413         bool has_group = false;
414         for (const auto &recipe_name : recipe_names) {
415                 if (isGroupRecipeStr(recipe_name)) {
416                         has_group = true;
417                         break;
418                 }
419         }
420         if (has_group)
421                 return CRAFT_HASH_TYPE_COUNT;
422
423         return CRAFT_HASH_TYPE_ITEM_NAMES;
424 }
425
426 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
427 {
428         assert(hash_inited); // Pre-condition
429         assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
430                 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
431
432         std::vector<std::string> rec_names = recipe_names;
433         std::sort(rec_names.begin(), rec_names.end());
434         return getHashForGrid(type, rec_names);
435 }
436
437 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
438 {
439         if (hash_inited)
440                 return;
441         hash_inited = true;
442         recipe_names = craftGetItemNames(recipe, gamedef);
443 }
444
445 std::string CraftDefinitionShaped::dump() const
446 {
447         std::ostringstream os(std::ios::binary);
448         os << "(shaped, output=\"" << output
449                 << "\", recipe=" << craftDumpMatrix(recipe, width)
450                 << ", replacements=" << replacements.dump() << ")";
451         return os.str();
452 }
453
454 /*
455         CraftDefinitionShapeless
456 */
457
458 std::string CraftDefinitionShapeless::getName() const
459 {
460         return "shapeless";
461 }
462
463 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
464 {
465         if (input.method != CRAFT_METHOD_NORMAL)
466                 return false;
467
468         // Filter empty items out of input
469         std::vector<std::string> input_filtered;
470         for (const auto &item : input.items) {
471                 if (!item.name.empty())
472                         input_filtered.push_back(item.name);
473         }
474
475         // If there is a wrong number of items in input, no match
476         if (input_filtered.size() != recipe.size()) {
477                 /*dstream<<"Number of input items ("<<input_filtered.size()
478                                 <<") does not match recipe size ("<<recipe.size()<<") "
479                                 <<"of recipe with output="<<output<<std::endl;*/
480                 return false;
481         }
482
483         std::vector<std::string> recipe_copy;
484         if (hash_inited)
485                 recipe_copy = recipe_names;
486         else {
487                 recipe_copy = craftGetItemNames(recipe, gamedef);
488                 std::sort(recipe_copy.begin(), recipe_copy.end());
489         }
490
491         // Try with all permutations of the recipe,
492         // start from the lexicographically first permutation (=sorted),
493         // recipe_names is pre-sorted
494         do {
495                 // If all items match, the recipe matches
496                 bool all_match = true;
497                 //dstream<<"Testing recipe (output="<<output<<"):";
498                 for (size_t i=0; i<recipe.size(); i++) {
499                         //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
500                         if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
501                                         gamedef->idef())) {
502                                 all_match = false;
503                                 break;
504                         }
505                 }
506                 //dstream<<" -> match="<<all_match<<std::endl;
507                 if (all_match)
508                         return true;
509         } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
510
511         return false;
512 }
513
514 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
515 {
516         return CraftOutput(output, 0);
517 }
518
519 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
520 {
521         return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
522 }
523
524 void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
525         IGameDef *gamedef) const
526 {
527         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
528 }
529
530 CraftHashType CraftDefinitionShapeless::getHashType() const
531 {
532         assert(hash_inited); // Pre-condition
533         bool has_group = false;
534         for (const auto &recipe_name : recipe_names) {
535                 if (isGroupRecipeStr(recipe_name)) {
536                         has_group = true;
537                         break;
538                 }
539         }
540         if (has_group)
541                 return CRAFT_HASH_TYPE_COUNT;
542
543         return CRAFT_HASH_TYPE_ITEM_NAMES;
544 }
545
546 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
547 {
548         assert(hash_inited); // Pre-condition
549         assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
550                 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
551         return getHashForGrid(type, recipe_names);
552 }
553
554 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
555 {
556         if (hash_inited)
557                 return;
558         hash_inited = true;
559         recipe_names = craftGetItemNames(recipe, gamedef);
560         std::sort(recipe_names.begin(), recipe_names.end());
561 }
562
563 std::string CraftDefinitionShapeless::dump() const
564 {
565         std::ostringstream os(std::ios::binary);
566         os << "(shapeless, output=\"" << output
567                 << "\", recipe=" << craftDumpMatrix(recipe, recipe.size())
568                 << ", replacements=" << replacements.dump() << ")";
569         return os.str();
570 }
571
572 /*
573         CraftDefinitionToolRepair
574 */
575
576 static ItemStack craftToolRepair(
577                 const ItemStack &item1,
578                 const ItemStack &item2,
579                 float additional_wear,
580                 IGameDef *gamedef)
581 {
582         IItemDefManager *idef = gamedef->idef();
583         if (item1.count != 1 || item2.count != 1 || item1.name != item2.name
584                         || idef->get(item1.name).type != ITEM_TOOL
585                         || itemgroup_get(idef->get(item1.name).groups, "disable_repair") == 1) {
586                 // Failure
587                 return ItemStack();
588         }
589
590         s32 item1_uses = 65536 - (u32) item1.wear;
591         s32 item2_uses = 65536 - (u32) item2.wear;
592         s32 new_uses = item1_uses + item2_uses;
593         s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
594         if (new_wear >= 65536)
595                 return ItemStack();
596         if (new_wear < 0)
597                 new_wear = 0;
598
599         ItemStack repaired = item1;
600         repaired.wear = new_wear;
601         return repaired;
602 }
603
604 std::string CraftDefinitionToolRepair::getName() const
605 {
606         return "toolrepair";
607 }
608
609 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
610 {
611         if (input.method != CRAFT_METHOD_NORMAL)
612                 return false;
613
614         ItemStack item1;
615         ItemStack item2;
616         for (const auto &item : input.items) {
617                 if (!item.empty()) {
618                         if (item1.empty())
619                                 item1 = item;
620                         else if (item2.empty())
621                                 item2 = item;
622                         else
623                                 return false;
624                 }
625         }
626         ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
627         return !repaired.empty();
628 }
629
630 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
631 {
632         ItemStack item1;
633         ItemStack item2;
634         for (const auto &item : input.items) {
635                 if (!item.empty()) {
636                         if (item1.empty())
637                                 item1 = item;
638                         else if (item2.empty())
639                                 item2 = item;
640                 }
641         }
642         ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
643         return CraftOutput(repaired.getItemString(), 0);
644 }
645
646 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
647 {
648         std::vector<ItemStack> stack;
649         stack.emplace_back();
650         return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack);
651 }
652
653 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
654         IGameDef *gamedef) const
655 {
656         craftDecrementInput(input, gamedef);
657 }
658
659 std::string CraftDefinitionToolRepair::dump() const
660 {
661         std::ostringstream os(std::ios::binary);
662         os << "(toolrepair, additional_wear=" << additional_wear << ")";
663         return os.str();
664 }
665
666 /*
667         CraftDefinitionCooking
668 */
669
670 std::string CraftDefinitionCooking::getName() const
671 {
672         return "cooking";
673 }
674
675 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
676 {
677         if (input.method != CRAFT_METHOD_COOKING)
678                 return false;
679
680         // Filter empty items out of input
681         std::vector<std::string> input_filtered;
682         for (const auto &item : input.items) {
683                 const std::string &name = item.name;
684                 if (!name.empty())
685                         input_filtered.push_back(name);
686         }
687
688         // If there is a wrong number of items in input, no match
689         if (input_filtered.size() != 1) {
690                 /*dstream<<"Number of input items ("<<input_filtered.size()
691                                 <<") does not match recipe size (1) "
692                                 <<"of cooking recipe with output="<<output<<std::endl;*/
693                 return false;
694         }
695
696         // Check the single input item
697         return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
698 }
699
700 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
701 {
702         return CraftOutput(output, cooktime);
703 }
704
705 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
706 {
707         std::vector<std::string> rec;
708         rec.push_back(recipe);
709         return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
710 }
711
712 void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
713         IGameDef *gamedef) const
714 {
715         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
716 }
717
718 CraftHashType CraftDefinitionCooking::getHashType() const
719 {
720         if (isGroupRecipeStr(recipe_name))
721                 return CRAFT_HASH_TYPE_COUNT;
722
723         return CRAFT_HASH_TYPE_ITEM_NAMES;
724 }
725
726 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
727 {
728         if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
729                 return getHashForString(recipe_name);
730         }
731
732         if (type == CRAFT_HASH_TYPE_COUNT) {
733                 return 1;
734         }
735
736         // illegal hash type for this CraftDefinition (pre-condition)
737         assert(false);
738         return 0;
739 }
740
741 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
742 {
743         if (hash_inited)
744                 return;
745         hash_inited = true;
746         recipe_name = craftGetItemName(recipe, gamedef);
747 }
748
749 std::string CraftDefinitionCooking::dump() const
750 {
751         std::ostringstream os(std::ios::binary);
752         os << "(cooking, output=\"" << output
753                 << "\", recipe=\"" << recipe
754                 << "\", cooktime=" << cooktime << ")"
755                 << ", replacements=" << replacements.dump() << ")";
756         return os.str();
757 }
758
759 /*
760         CraftDefinitionFuel
761 */
762
763 std::string CraftDefinitionFuel::getName() const
764 {
765         return "fuel";
766 }
767
768 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
769 {
770         if (input.method != CRAFT_METHOD_FUEL)
771                 return false;
772
773         // Filter empty items out of input
774         std::vector<std::string> input_filtered;
775         for (const auto &item : input.items) {
776                 const std::string &name = item.name;
777                 if (!name.empty())
778                         input_filtered.push_back(name);
779         }
780
781         // If there is a wrong number of items in input, no match
782         if (input_filtered.size() != 1) {
783                 /*dstream<<"Number of input items ("<<input_filtered.size()
784                                 <<") does not match recipe size (1) "
785                                 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
786                 return false;
787         }
788
789         // Check the single input item
790         return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
791 }
792
793 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
794 {
795         return CraftOutput("", burntime);
796 }
797
798 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
799 {
800         std::vector<std::string> rec;
801         rec.push_back(recipe);
802         return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
803 }
804
805 void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
806         IGameDef *gamedef) const
807 {
808         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
809 }
810
811 CraftHashType CraftDefinitionFuel::getHashType() const
812 {
813         if (isGroupRecipeStr(recipe_name))
814                 return CRAFT_HASH_TYPE_COUNT;
815
816         return CRAFT_HASH_TYPE_ITEM_NAMES;
817 }
818
819 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
820 {
821         if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
822                 return getHashForString(recipe_name);
823         }
824
825         if (type == CRAFT_HASH_TYPE_COUNT) {
826                 return 1;
827         }
828
829         // illegal hash type for this CraftDefinition (pre-condition)
830         assert(false);
831         return 0;
832 }
833
834 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
835 {
836         if (hash_inited)
837                 return;
838         hash_inited = true;
839         recipe_name = craftGetItemName(recipe, gamedef);
840 }
841 std::string CraftDefinitionFuel::dump() const
842 {
843         std::ostringstream os(std::ios::binary);
844         os << "(fuel, recipe=\"" << recipe
845                 << "\", burntime=" << burntime << ")"
846                 << ", replacements=" << replacements.dump() << ")";
847         return os.str();
848 }
849
850 /*
851         Craft definition manager
852 */
853
854 class CCraftDefManager: public IWritableCraftDefManager
855 {
856 public:
857         CCraftDefManager()
858         {
859                 m_craft_defs.resize(craft_hash_type_max + 1);
860         }
861
862         virtual ~CCraftDefManager()
863         {
864                 clear();
865         }
866
867         virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
868                         std::vector<ItemStack> &output_replacement, bool decrementInput,
869                         IGameDef *gamedef) const
870         {
871                 output.item = "";
872                 output.time = 0;
873
874                 // If all input items are empty, abort.
875                 bool all_empty = true;
876                 for (const auto &item : input.items) {
877                         if (!item.empty()) {
878                                 all_empty = false;
879                                 break;
880                         }
881                 }
882                 if (all_empty)
883                         return false;
884
885                 std::vector<std::string> input_names;
886                 input_names = craftGetItemNames(input.items, gamedef);
887                 std::sort(input_names.begin(), input_names.end());
888
889                 // Try hash types with increasing collision rate, and return if found.
890                 for (int type = 0; type <= craft_hash_type_max; type++) {
891                         u64 hash = getHashForGrid((CraftHashType) type, input_names);
892
893                         /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
894
895                         // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
896                         // but that doesn't compile for some reason. This does.
897                         auto col_iter = (m_craft_defs[type]).find(hash);
898
899                         if (col_iter == (m_craft_defs[type]).end())
900                                 continue;
901
902                         const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
903                         // Walk crafting definitions from back to front, so that later
904                         // definitions can override earlier ones.
905                         for (std::vector<CraftDefinition*>::size_type
906                                         i = hash_collisions.size(); i > 0; i--) {
907                                 CraftDefinition *def = hash_collisions[i - 1];
908
909                                 /*errorstream << "Checking " << input.dump() << std::endl
910                                         << " against " << def->dump() << std::endl;*/
911
912                                 if (def->check(input, gamedef)) {
913                                         // Check if the crafted node/item exists
914                                         CraftOutput out = def->getOutput(input, gamedef);
915                                         ItemStack is;
916                                         is.deSerialize(out.item, gamedef->idef());
917                                         if (!is.isKnown(gamedef->idef())) {
918                                                 infostream << "trying to craft non-existent "
919                                                         << out.item << ", ignoring recipe" << std::endl;
920                                                 continue;
921                                         }
922
923                                         // Get output, then decrement input (if requested)
924                                         output = out;
925                     
926                                         if (decrementInput)
927                                                 def->decrementInput(input, output_replacement, gamedef);
928                                         /*errorstream << "Check RETURNS TRUE" << std::endl;*/
929                                         return true;
930                                 }
931                         }
932                 }
933                 return false;
934         }
935
936         virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
937                         IGameDef *gamedef, unsigned limit=0) const
938         {
939                 std::vector<CraftDefinition*> recipes;
940
941                 auto vec_iter = m_output_craft_definitions.find(output.item);
942
943                 if (vec_iter == m_output_craft_definitions.end())
944                         return recipes;
945
946                 const std::vector<CraftDefinition*> &vec = vec_iter->second;
947
948                 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
949
950                 for (std::vector<CraftDefinition*>::size_type i = vec.size();
951                                 i > 0; i--) {
952                         CraftDefinition *def = vec[i - 1];
953                         if (limit && recipes.size() >= limit)
954                                 break;
955                         recipes.push_back(def);
956                 }
957
958                 return recipes;
959         }
960
961         virtual bool clearCraftRecipesByOutput(const CraftOutput &output, IGameDef *gamedef)
962         {
963                 auto vec_iter = m_output_craft_definitions.find(output.item);
964
965                 if (vec_iter == m_output_craft_definitions.end())
966                         return false;
967
968                 std::vector<CraftDefinition*> &vec = vec_iter->second;
969                 for (auto def : vec) {
970                         // Recipes are not yet hashed at this point
971                         std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
972                         std::vector<CraftDefinition*> new_vec_by_input;
973                         /* We will preallocate necessary memory addresses, so we don't need to reallocate them later.
974                                 This would save us some performance. */
975                         new_vec_by_input.reserve(unhashed_inputs_vec.size());
976                         for (auto &i2 : unhashed_inputs_vec) {
977                                 if (def != i2) {
978                                         new_vec_by_input.push_back(i2);
979                                 }
980                         }
981                         m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
982                 }
983                 m_output_craft_definitions.erase(output.item);
984                 return true;
985         }
986
987         virtual bool clearCraftRecipesByInput(CraftMethod craft_method, unsigned int craft_grid_width,
988                 const std::vector<std::string> &recipe, IGameDef *gamedef)
989         {
990                 bool all_empty = true;
991                 for (const auto &i : recipe) {
992                         if (!i.empty()) {
993                                 all_empty = false;
994                                 break;
995                         }
996                 }
997                 if (all_empty)
998                         return false;
999
1000                 CraftInput input(craft_method, craft_grid_width, craftGetItems(recipe, gamedef));
1001                 // Recipes are not yet hashed at this point
1002                 std::vector<CraftDefinition*> &unhashed_inputs_vec = m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1003                 std::vector<CraftDefinition*> new_vec_by_input;
1004                 bool got_hit = false;
1005                 for (std::vector<CraftDefinition*>::size_type
1006                                 i = unhashed_inputs_vec.size(); i > 0; i--) {
1007                         CraftDefinition *def = unhashed_inputs_vec[i - 1];
1008                         /* If the input doesn't match the recipe definition, this recipe definition later
1009                                 will be added back in source map. */
1010                         if (!def->check(input, gamedef)) {
1011                                 new_vec_by_input.push_back(def);
1012                                 continue;
1013                         }
1014                         CraftOutput output = def->getOutput(input, gamedef);
1015                         got_hit = true;
1016                         auto vec_iter = m_output_craft_definitions.find(output.item);
1017                         if (vec_iter == m_output_craft_definitions.end())
1018                                 continue;
1019                         std::vector<CraftDefinition*> &vec = vec_iter->second;
1020                         std::vector<CraftDefinition*> new_vec_by_output;
1021                         /* We will preallocate necessary memory addresses, so we don't need
1022                                 to reallocate them later. This would save us some performance. */
1023                         new_vec_by_output.reserve(vec.size());
1024                         for (auto &vec_i : vec) {
1025                                 /* If pointers from map by input and output are not same,
1026                                         we will add 'CraftDefinition*' to a new vector. */
1027                                 if (def != vec_i) {
1028                                         /* Adding dereferenced iterator value (which are
1029                                                 'CraftDefinition' reference) to a new vector. */
1030                                         new_vec_by_output.push_back(vec_i);
1031                                 }
1032                         }
1033                         // Swaps assigned to current key value with new vector for output map.
1034                         m_output_craft_definitions[output.item].swap(new_vec_by_output);
1035                 }
1036                 if (got_hit)
1037                         // Swaps value with new vector for input map.
1038                         m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].swap(new_vec_by_input);
1039
1040                 return got_hit;
1041         }
1042
1043         virtual std::string dump() const
1044         {
1045                 std::ostringstream os(std::ios::binary);
1046                 os << "Crafting definitions:\n";
1047                 for (int type = 0; type <= craft_hash_type_max; ++type) {
1048                         for (auto it = m_craft_defs[type].begin();
1049                                         it != m_craft_defs[type].end(); ++it) {
1050                                 for (std::vector<CraftDefinition*>::size_type i = 0;
1051                                                 i < it->second.size(); i++) {
1052                                         os << "type " << type
1053                                                 << " hash " << it->first
1054                                                 << " def " << it->second[i]->dump()
1055                                                 << "\n";
1056                                 }
1057                         }
1058                 }
1059                 return os.str();
1060         }
1061         virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
1062         {
1063                 verbosestream << "registerCraft: registering craft definition: "
1064                                 << def->dump() << std::endl;
1065                 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
1066
1067                 CraftInput input;
1068                 std::string output_name = craftGetItemName(
1069                                 def->getOutput(input, gamedef).item, gamedef);
1070                 m_output_craft_definitions[output_name].push_back(def);
1071         }
1072         virtual void clear()
1073         {
1074                 for (int type = 0; type <= craft_hash_type_max; ++type) {
1075                         for (auto &it : m_craft_defs[type]) {
1076                                 for (auto &iit : it.second) {
1077                                         delete iit;
1078                                 }
1079                                 it.second.clear();
1080                         }
1081                         m_craft_defs[type].clear();
1082                 }
1083                 m_output_craft_definitions.clear();
1084         }
1085         virtual void initHashes(IGameDef *gamedef)
1086         {
1087                 // Move the CraftDefs from the unhashed layer into layers higher up.
1088                 std::vector<CraftDefinition *> &unhashed =
1089                         m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1090                 for (auto def : unhashed) {
1091                         // Initialize and get the definition's hash
1092                         def->initHash(gamedef);
1093                         CraftHashType type = def->getHashType();
1094                         u64 hash = def->getHash(type);
1095
1096                         // Enter the definition
1097                         m_craft_defs[type][hash].push_back(def);
1098                 }
1099                 unhashed.clear();
1100         }
1101 private:
1102         //TODO: change both maps to unordered_map when c++11 can be used
1103         std::vector<std::map<u64, std::vector<CraftDefinition*> > > m_craft_defs;
1104         std::map<std::string, std::vector<CraftDefinition*> > m_output_craft_definitions;
1105 };
1106
1107 IWritableCraftDefManager* createCraftDefManager()
1108 {
1109         return new CCraftDefManager();
1110 }