]> git.lizzy.rs Git - minetest.git/blob - src/craftdef.cpp
022b98da3285ed5e842b24c115e078546274a2b8
[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 "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 (size_t i = 0; i < grid_names.size(); i++) {
53                                 if (grid_names[i] != "") {
54                                         os << (is_first ? "" : "\n") << grid_names[i];
55                                         is_first = false;
56                                 }
57                         }
58                         return getHashForString(os.str());
59                 } case CRAFT_HASH_TYPE_COUNT: {
60                         u64 cnt = 0;
61                         for (size_t i = 0; i < grid_names.size(); i++)
62                                 if (grid_names[i] != "")
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.atend());
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         for (std::vector<std::string>::size_type i = 0;
116                         i < itemstrings.size(); i++) {
117                 result.push_back(craftGetItemName(itemstrings[i], 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         for (std::vector<ItemStack>::size_type i = 0;
128                         i < items.size(); i++) {
129                 result.push_back(items[i].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         for (std::vector<std::string>::size_type i = 0;
140                         i < items.size(); i++) {
141                 result.push_back(ItemStack(std::string(items[i]), (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 (std::vector<std::string>::size_type i = 0;
157                         i < items.size(); i++) {
158                 // Is this an actual item?
159                 if (items[i] != "") {
160                         if (!success) {
161                                 // This is the first nonempty item
162                                 min_x = max_x = x;
163                                 min_y = max_y = y;
164                                 success = true;
165                         } else {
166                                 if (x < min_x) min_x = x;
167                                 if (x > max_x) max_x = x;
168                                 if (y < min_y) min_y = y;
169                                 if (y > max_y) max_y = y;
170                         }
171                 }
172
173                 // Step coordinate
174                 x++;
175                 if (x == width) {
176                         x = 0;
177                         y++;
178                 }
179         }
180         return success;
181 }
182
183 // Removes 1 from each item stack
184 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
185 {
186         for (std::vector<ItemStack>::size_type i = 0;
187                         i < input.items.size(); i++) {
188                 if (input.items[i].count != 0)
189                         input.items[i].remove(1);
190         }
191 }
192
193 // Removes 1 from each item stack with replacement support
194 // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"),
195 //   a water bucket will not be removed but replaced by an empty bucket.
196 static void craftDecrementOrReplaceInput(CraftInput &input,
197                 std::vector<ItemStack> &output_replacements,
198                 const CraftReplacements &replacements,
199                 IGameDef *gamedef)
200 {
201         if (replacements.pairs.empty()) {
202                 craftDecrementInput(input, gamedef);
203                 return;
204         }
205
206         // Make a copy of the replacements pair list
207         std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
208
209         for (std::vector<ItemStack>::size_type i = 0;
210                         i < input.items.size(); i++) {
211                 ItemStack &item = input.items[i];
212                 // Find an appropriate replacement
213                 bool found_replacement = false;
214                 for (std::vector<std::pair<std::string, std::string> >::iterator
215                                 j = pairs.begin();
216                                 j != pairs.end(); ++j) {
217                         if (item.name == craftGetItemName(j->first, gamedef)) {
218                                 if (item.count == 1) {
219                                         item.deSerialize(j->second, gamedef->idef());
220                                         found_replacement = true;
221                                         pairs.erase(j);
222                                         break;
223                                 } else {
224                                         ItemStack rep;
225                                         rep.deSerialize(j->second, gamedef->idef());
226                                         item.remove(1);
227                                         found_replacement = true;
228                                         output_replacements.push_back(rep);
229                                         break;
230                                 }
231                         }
232                 }
233                 // No replacement was found, simply decrement count by one
234                 if (!found_replacement && item.count > 0)
235                         item.remove(1);
236         }
237 }
238
239 // Dump an itemstring matrix
240 static std::string craftDumpMatrix(const std::vector<std::string> &items,
241                 unsigned int width)
242 {
243         std::ostringstream os(std::ios::binary);
244         os << "{ ";
245         for(std::vector<std::string>::size_type i = 0;
246                         i < items.size(); i++) {
247                 if (i == width) {
248                         os << "; ";
249                         i = 0;
250                 } else if (i != 0) {
251                         os << ",";
252                 }
253                 os << '"' << items[i] << '"';
254         }
255         os << " }";
256         return os.str();
257 }
258
259 // Dump an item matrix
260 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
261                 unsigned int width)
262 {
263         std::ostringstream os(std::ios::binary);
264         os << "{ ";
265         for (std::vector<ItemStack>::size_type i = 0;
266                         i < items.size(); i++) {
267                 if (i == width) {
268                         os << "; ";
269                         i = 0;
270                 } else if (i != 0) {
271                         os << ",";
272                 }
273                 os << '"' << (items[i].getItemString()) << '"';
274         }
275         os << " }";
276         return os.str();
277 }
278
279
280 /*
281         CraftInput
282 */
283
284 std::string CraftInput::dump() const
285 {
286         std::ostringstream os(std::ios::binary);
287         os << "(method=" << ((int)method) << ", items="
288                 << craftDumpMatrix(items, width) << ")";
289         return os.str();
290 }
291
292 /*
293         CraftOutput
294 */
295
296 std::string CraftOutput::dump() const
297 {
298         std::ostringstream os(std::ios::binary);
299         os << "(item=\"" << item << "\", time=" << time << ")";
300         return os.str();
301 }
302
303 /*
304         CraftReplacements
305 */
306
307 std::string CraftReplacements::dump() const
308 {
309         std::ostringstream os(std::ios::binary);
310         os<<"{";
311         const char *sep = "";
312         for (std::vector<std::pair<std::string, std::string> >::size_type i = 0;
313                         i < pairs.size(); i++) {
314                 const std::pair<std::string, std::string> &repl_p = pairs[i];
315                 os << sep
316                         << '"' << (repl_p.first)
317                         << "\"=>\"" << (repl_p.second) << '"';
318                 sep = ",";
319         }
320         os << "}";
321         return os.str();
322 }
323
324 /*
325         CraftDefinitionShaped
326 */
327
328 std::string CraftDefinitionShaped::getName() const
329 {
330         return "shaped";
331 }
332
333 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
334 {
335         if (input.method != CRAFT_METHOD_NORMAL)
336                 return false;
337
338         // Get input item matrix
339         std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
340         unsigned int inp_width = input.width;
341         if (inp_width == 0)
342                 return false;
343         while (inp_names.size() % inp_width != 0)
344                 inp_names.push_back("");
345
346         // Get input bounds
347         unsigned int inp_min_x = 0, inp_max_x = 0, inp_min_y = 0, inp_max_y = 0;
348         if (!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x,
349                         inp_min_y, inp_max_y))
350                 return false;  // it was empty
351
352         std::vector<std::string> rec_names;
353         if (hash_inited)
354                 rec_names = recipe_names;
355         else
356                 rec_names = craftGetItemNames(recipe, gamedef);
357
358         // Get recipe item matrix
359         unsigned int rec_width = width;
360         if (rec_width == 0)
361                 return false;
362         while (rec_names.size() % rec_width != 0)
363                 rec_names.push_back("");
364
365         // Get recipe bounds
366         unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
367         if (!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x,
368                         rec_min_y, rec_max_y))
369                 return false;  // it was empty
370
371         // Different sizes?
372         if (inp_max_x - inp_min_x != rec_max_x - rec_min_x ||
373                         inp_max_y - inp_min_y != rec_max_y - rec_min_y)
374                 return false;
375
376         // Verify that all item names in the bounding box are equal
377         unsigned int w = inp_max_x - inp_min_x + 1;
378         unsigned int h = inp_max_y - inp_min_y + 1;
379
380         for (unsigned int y=0; y < h; y++) {
381                 unsigned int inp_y = (inp_min_y + y) * inp_width;
382                 unsigned int rec_y = (rec_min_y + y) * rec_width;
383
384                 for (unsigned int x=0; x < w; x++) {
385                         unsigned int inp_x = inp_min_x + x;
386                         unsigned int rec_x = rec_min_x + x;
387
388                         if (!inputItemMatchesRecipe(
389                                         inp_names[inp_y + inp_x],
390                                         rec_names[rec_y + rec_x], gamedef->idef())) {
391                                 return false;
392                         }
393                 }
394         }
395
396         return true;
397 }
398
399 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
400 {
401         return CraftOutput(output, 0);
402 }
403
404 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
405 {
406         return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
407 }
408
409 void CraftDefinitionShaped::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
410          IGameDef *gamedef) const
411 {
412         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
413 }
414
415 CraftHashType CraftDefinitionShaped::getHashType() const
416 {
417         assert(hash_inited); // Pre-condition
418         bool has_group = false;
419         for (size_t i = 0; i < recipe_names.size(); i++) {
420                 if (isGroupRecipeStr(recipe_names[i])) {
421                         has_group = true;
422                         break;
423                 }
424         }
425         if (has_group)
426                 return CRAFT_HASH_TYPE_COUNT;
427         else
428                 return CRAFT_HASH_TYPE_ITEM_NAMES;
429 }
430
431 u64 CraftDefinitionShaped::getHash(CraftHashType type) const
432 {
433         assert(hash_inited); // Pre-condition
434         assert((type == CRAFT_HASH_TYPE_ITEM_NAMES)
435                 || (type == CRAFT_HASH_TYPE_COUNT)); // Pre-condition
436
437         std::vector<std::string> rec_names = recipe_names;
438         std::sort(rec_names.begin(), rec_names.end());
439         return getHashForGrid(type, rec_names);
440 }
441
442 void CraftDefinitionShaped::initHash(IGameDef *gamedef)
443 {
444         if (hash_inited)
445                 return;
446         hash_inited = true;
447         recipe_names = craftGetItemNames(recipe, gamedef);
448 }
449
450 std::string CraftDefinitionShaped::dump() const
451 {
452         std::ostringstream os(std::ios::binary);
453         os << "(shaped, output=\"" << output
454                 << "\", recipe=" << craftDumpMatrix(recipe, width)
455                 << ", replacements=" << replacements.dump() << ")";
456         return os.str();
457 }
458
459 /*
460         CraftDefinitionShapeless
461 */
462
463 std::string CraftDefinitionShapeless::getName() const
464 {
465         return "shapeless";
466 }
467
468 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
469 {
470         if (input.method != CRAFT_METHOD_NORMAL)
471                 return false;
472
473         // Filter empty items out of input
474         std::vector<std::string> input_filtered;
475         for (std::vector<ItemStack>::size_type i = 0;
476                         i < input.items.size(); i++) {
477                 const ItemStack &item = input.items[i];
478                 if (item.name != "")
479                         input_filtered.push_back(item.name);
480         }
481
482         // If there is a wrong number of items in input, no match
483         if (input_filtered.size() != recipe.size()) {
484                 /*dstream<<"Number of input items ("<<input_filtered.size()
485                                 <<") does not match recipe size ("<<recipe.size()<<") "
486                                 <<"of recipe with output="<<output<<std::endl;*/
487                 return false;
488         }
489
490         std::vector<std::string> recipe_copy;
491         if (hash_inited)
492                 recipe_copy = recipe_names;
493         else {
494                 recipe_copy = craftGetItemNames(recipe, gamedef);
495                 std::sort(recipe_copy.begin(), recipe_copy.end());
496         }
497
498         // Try with all permutations of the recipe,
499         // start from the lexicographically first permutation (=sorted),
500         // recipe_names is pre-sorted
501         do {
502                 // If all items match, the recipe matches
503                 bool all_match = true;
504                 //dstream<<"Testing recipe (output="<<output<<"):";
505                 for (size_t i=0; i<recipe.size(); i++) {
506                         //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
507                         if (!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
508                                         gamedef->idef())) {
509                                 all_match = false;
510                                 break;
511                         }
512                 }
513                 //dstream<<" -> match="<<all_match<<std::endl;
514                 if (all_match)
515                         return true;
516         } while (std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
517
518         return false;
519 }
520
521 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
522 {
523         return CraftOutput(output, 0);
524 }
525
526 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
527 {
528         return CraftInput(CRAFT_METHOD_NORMAL, 0, craftGetItems(recipe, gamedef));
529 }
530
531 void CraftDefinitionShapeless::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
532         IGameDef *gamedef) const
533 {
534         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
535 }
536
537 CraftHashType CraftDefinitionShapeless::getHashType() const
538 {
539         assert(hash_inited); // Pre-condition
540         bool has_group = false;
541         for (size_t i = 0; i < recipe_names.size(); i++) {
542                 if (isGroupRecipeStr(recipe_names[i])) {
543                         has_group = true;
544                         break;
545                 }
546         }
547         if (has_group)
548                 return CRAFT_HASH_TYPE_COUNT;
549         else
550                 return CRAFT_HASH_TYPE_ITEM_NAMES;
551 }
552
553 u64 CraftDefinitionShapeless::getHash(CraftHashType type) const
554 {
555         assert(hash_inited); // Pre-condition
556         assert(type == CRAFT_HASH_TYPE_ITEM_NAMES
557                 || type == CRAFT_HASH_TYPE_COUNT); // Pre-condition
558         return getHashForGrid(type, recipe_names);
559 }
560
561 void CraftDefinitionShapeless::initHash(IGameDef *gamedef)
562 {
563         if (hash_inited)
564                 return;
565         hash_inited = true;
566         recipe_names = craftGetItemNames(recipe, gamedef);
567         std::sort(recipe_names.begin(), recipe_names.end());
568 }
569
570 std::string CraftDefinitionShapeless::dump() const
571 {
572         std::ostringstream os(std::ios::binary);
573         os << "(shapeless, output=\"" << output
574                 << "\", recipe=" << craftDumpMatrix(recipe, recipe.size())
575                 << ", replacements=" << replacements.dump() << ")";
576         return os.str();
577 }
578
579 /*
580         CraftDefinitionToolRepair
581 */
582
583 static ItemStack craftToolRepair(
584                 const ItemStack &item1,
585                 const ItemStack &item2,
586                 float additional_wear,
587                 IGameDef *gamedef)
588 {
589         IItemDefManager *idef = gamedef->idef();
590         if (item1.count != 1 || item2.count != 1 || item1.name != item2.name
591                         || idef->get(item1.name).type != ITEM_TOOL
592                         || idef->get(item2.name).type != ITEM_TOOL) {
593                 // Failure
594                 return ItemStack();
595         }
596
597         s32 item1_uses = 65536 - (u32) item1.wear;
598         s32 item2_uses = 65536 - (u32) item2.wear;
599         s32 new_uses = item1_uses + item2_uses;
600         s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
601         if (new_wear >= 65536)
602                 return ItemStack();
603         if (new_wear < 0)
604                 new_wear = 0;
605
606         ItemStack repaired = item1;
607         repaired.wear = new_wear;
608         return repaired;
609 }
610
611 std::string CraftDefinitionToolRepair::getName() const
612 {
613         return "toolrepair";
614 }
615
616 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
617 {
618         if (input.method != CRAFT_METHOD_NORMAL)
619                 return false;
620
621         ItemStack item1;
622         ItemStack item2;
623         for (std::vector<ItemStack>::size_type i = 0;
624                         i < input.items.size(); i++) {
625                 const ItemStack &item = input.items[i];
626                 if (!item.empty()) {
627                         if (item1.empty())
628                                 item1 = item;
629                         else if (item2.empty())
630                                 item2 = item;
631                         else
632                                 return false;
633                 }
634         }
635         ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
636         return !repaired.empty();
637 }
638
639 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
640 {
641         ItemStack item1;
642         ItemStack item2;
643         for (std::vector<ItemStack>::size_type i = 0;
644                         i < input.items.size(); i++) {
645                 const ItemStack &item = input.items[i];
646                 if (!item.empty()) {
647                         if (item1.empty())
648                                 item1 = item;
649                         else if (item2.empty())
650                                 item2 = item;
651                 }
652         }
653         ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
654         return CraftOutput(repaired.getItemString(), 0);
655 }
656
657 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
658 {
659         std::vector<ItemStack> stack;
660         stack.push_back(ItemStack());
661         return CraftInput(CRAFT_METHOD_COOKING, additional_wear, stack);
662 }
663
664 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
665         IGameDef *gamedef) const
666 {
667         craftDecrementInput(input, gamedef);
668 }
669
670 std::string CraftDefinitionToolRepair::dump() const
671 {
672         std::ostringstream os(std::ios::binary);
673         os << "(toolrepair, additional_wear=" << additional_wear << ")";
674         return os.str();
675 }
676
677 /*
678         CraftDefinitionCooking
679 */
680
681 std::string CraftDefinitionCooking::getName() const
682 {
683         return "cooking";
684 }
685
686 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
687 {
688         if (input.method != CRAFT_METHOD_COOKING)
689                 return false;
690
691         // Filter empty items out of input
692         std::vector<std::string> input_filtered;
693         for (std::vector<ItemStack>::size_type i = 0;
694                         i < input.items.size(); i++) {
695                 const std::string &name = input.items[i].name;
696                 if (name != "")
697                         input_filtered.push_back(name);
698         }
699
700         // If there is a wrong number of items in input, no match
701         if (input_filtered.size() != 1) {
702                 /*dstream<<"Number of input items ("<<input_filtered.size()
703                                 <<") does not match recipe size (1) "
704                                 <<"of cooking recipe with output="<<output<<std::endl;*/
705                 return false;
706         }
707
708         // Check the single input item
709         return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
710 }
711
712 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
713 {
714         return CraftOutput(output, cooktime);
715 }
716
717 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
718 {
719         std::vector<std::string> rec;
720         rec.push_back(recipe);
721         return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
722 }
723
724 void CraftDefinitionCooking::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
725         IGameDef *gamedef) const
726 {
727         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
728 }
729
730 CraftHashType CraftDefinitionCooking::getHashType() const
731 {
732         if (isGroupRecipeStr(recipe_name))
733                 return CRAFT_HASH_TYPE_COUNT;
734         else
735                 return CRAFT_HASH_TYPE_ITEM_NAMES;
736 }
737
738 u64 CraftDefinitionCooking::getHash(CraftHashType type) const
739 {
740         if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
741                 return getHashForString(recipe_name);
742         } else if (type == CRAFT_HASH_TYPE_COUNT) {
743                 return 1;
744         } else {
745                 //illegal hash type for this CraftDefinition (pre-condition)
746                 assert(false);
747                 return 0;
748         }
749 }
750
751 void CraftDefinitionCooking::initHash(IGameDef *gamedef)
752 {
753         if (hash_inited)
754                 return;
755         hash_inited = true;
756         recipe_name = craftGetItemName(recipe, gamedef);
757 }
758
759 std::string CraftDefinitionCooking::dump() const
760 {
761         std::ostringstream os(std::ios::binary);
762         os << "(cooking, output=\"" << output
763                 << "\", recipe=\"" << recipe
764                 << "\", cooktime=" << cooktime << ")"
765                 << ", replacements=" << replacements.dump() << ")";
766         return os.str();
767 }
768
769 /*
770         CraftDefinitionFuel
771 */
772
773 std::string CraftDefinitionFuel::getName() const
774 {
775         return "fuel";
776 }
777
778 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
779 {
780         if (input.method != CRAFT_METHOD_FUEL)
781                 return false;
782
783         // Filter empty items out of input
784         std::vector<std::string> input_filtered;
785         for (std::vector<ItemStack>::size_type i = 0;
786                         i < input.items.size(); i++) {
787                 const std::string &name = input.items[i].name;
788                 if (name != "")
789                         input_filtered.push_back(name);
790         }
791
792         // If there is a wrong number of items in input, no match
793         if (input_filtered.size() != 1) {
794                 /*dstream<<"Number of input items ("<<input_filtered.size()
795                                 <<") does not match recipe size (1) "
796                                 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
797                 return false;
798         }
799
800         // Check the single input item
801         return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
802 }
803
804 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
805 {
806         return CraftOutput("", burntime);
807 }
808
809 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
810 {
811         std::vector<std::string> rec;
812         rec.push_back(recipe);
813         return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
814 }
815
816 void CraftDefinitionFuel::decrementInput(CraftInput &input, std::vector<ItemStack> &output_replacements,
817         IGameDef *gamedef) const
818 {
819         craftDecrementOrReplaceInput(input, output_replacements, replacements, gamedef);
820 }
821
822 CraftHashType CraftDefinitionFuel::getHashType() const
823 {
824         if (isGroupRecipeStr(recipe_name))
825                 return CRAFT_HASH_TYPE_COUNT;
826         else
827                 return CRAFT_HASH_TYPE_ITEM_NAMES;
828 }
829
830 u64 CraftDefinitionFuel::getHash(CraftHashType type) const
831 {
832         if (type == CRAFT_HASH_TYPE_ITEM_NAMES) {
833                 return getHashForString(recipe_name);
834         } else if (type == CRAFT_HASH_TYPE_COUNT) {
835                 return 1;
836         } else {
837                 //illegal hash type for this CraftDefinition (pre-condition)
838                 assert(false);
839                 return 0;
840         }
841 }
842
843 void CraftDefinitionFuel::initHash(IGameDef *gamedef)
844 {
845         if (hash_inited)
846                 return;
847         hash_inited = true;
848         recipe_name = craftGetItemName(recipe, gamedef);
849 }
850 std::string CraftDefinitionFuel::dump() const
851 {
852         std::ostringstream os(std::ios::binary);
853         os << "(fuel, recipe=\"" << recipe
854                 << "\", burntime=" << burntime << ")"
855                 << ", replacements=" << replacements.dump() << ")";
856         return os.str();
857 }
858
859 /*
860         Craft definition manager
861 */
862
863 class CCraftDefManager: public IWritableCraftDefManager
864 {
865 public:
866         CCraftDefManager()
867         {
868                 m_craft_defs.resize(craft_hash_type_max + 1);
869         }
870
871         virtual ~CCraftDefManager()
872         {
873                 clear();
874         }
875
876         virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
877                         std::vector<ItemStack> &output_replacement, bool decrementInput,
878                         IGameDef *gamedef) const
879         {
880                 output.item = "";
881                 output.time = 0;
882
883                 // If all input items are empty, abort.
884                 bool all_empty = true;
885                 for (std::vector<ItemStack>::size_type i = 0;
886                         i < input.items.size(); i++) {
887                         if (!input.items[i].empty()) {
888                                 all_empty = false;
889                                 break;
890                         }
891                 }
892                 if (all_empty)
893                         return false;
894
895                 std::vector<std::string> input_names;
896                 input_names = craftGetItemNames(input.items, gamedef);
897                 std::sort(input_names.begin(), input_names.end());
898
899                 // Try hash types with increasing collision rate, and return if found.
900                 for (int type = 0; type <= craft_hash_type_max; type++) {
901                         u64 hash = getHashForGrid((CraftHashType) type, input_names);
902
903                         /*errorstream << "Checking type " << type << " with hash " << hash << std::endl;*/
904
905                         // We'd like to do "const [...] hash_collisions = m_craft_defs[type][hash];"
906                         // but that doesn't compile for some reason. This does.
907                         std::map<u64, std::vector<CraftDefinition*> >::const_iterator
908                                 col_iter = (m_craft_defs[type]).find(hash);
909
910                         if (col_iter == (m_craft_defs[type]).end())
911                                 continue;
912
913                         const std::vector<CraftDefinition*> &hash_collisions = col_iter->second;
914                         // Walk crafting definitions from back to front, so that later
915                         // definitions can override earlier ones.
916                         for (std::vector<CraftDefinition*>::size_type
917                                         i = hash_collisions.size(); i > 0; i--) {
918                                 CraftDefinition *def = hash_collisions[i - 1];
919
920                                 /*errorstream << "Checking " << input.dump() << std::endl
921                                         << " against " << def->dump() << std::endl;*/
922
923                                 if (def->check(input, gamedef)) {
924                                         // Get output, then decrement input (if requested)
925                                         output = def->getOutput(input, gamedef);
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                 std::map<std::string, std::vector<CraftDefinition*> >::const_iterator
942                         vec_iter = m_output_craft_definitions.find(output.item);
943
944                 if (vec_iter == m_output_craft_definitions.end())
945                         return recipes;
946
947                 const std::vector<CraftDefinition*> &vec = vec_iter->second;
948
949                 recipes.reserve(limit ? MYMIN(limit, vec.size()) : vec.size());
950
951                 for (std::vector<CraftDefinition*>::size_type i = vec.size();
952                                 i > 0; i--) {
953                         CraftDefinition *def = vec[i - 1];
954                         if (limit && recipes.size() >= limit)
955                                 break;
956                         recipes.push_back(def);
957                 }
958
959                 return recipes;
960         }
961         virtual std::string dump() const
962         {
963                 std::ostringstream os(std::ios::binary);
964                 os << "Crafting definitions:\n";
965                 for (int type = 0; type <= craft_hash_type_max; type++) {
966                         for (std::map<u64, std::vector<CraftDefinition*> >::const_iterator
967                                         it = (m_craft_defs[type]).begin();
968                                         it != (m_craft_defs[type]).end(); it++) {
969                                 for (std::vector<CraftDefinition*>::size_type i = 0;
970                                                 i < it->second.size(); i++) {
971                                         os << "type " << type
972                                                 << " hash " << it->first
973                                                 << " def " << it->second[i]->dump()
974                                                 << "\n";
975                                 }
976                         }
977                 }
978                 return os.str();
979         }
980         virtual void registerCraft(CraftDefinition *def, IGameDef *gamedef)
981         {
982                 verbosestream << "registerCraft: registering craft definition: "
983                                 << def->dump() << std::endl;
984                 m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0].push_back(def);
985
986                 CraftInput input;
987                 std::string output_name = craftGetItemName(
988                                 def->getOutput(input, gamedef).item, gamedef);
989                 m_output_craft_definitions[output_name].push_back(def);
990         }
991         virtual void clear()
992         {
993                 for (int type = 0; type <= craft_hash_type_max; type++) {
994                         for (std::map<u64, std::vector<CraftDefinition*> >::iterator
995                                         it = m_craft_defs[type].begin();
996                                         it != m_craft_defs[type].end(); it++) {
997                                 for (std::vector<CraftDefinition*>::iterator
998                                                 iit = it->second.begin();
999                                                 iit != it->second.end(); ++iit) {
1000                                         delete *iit;
1001                                 }
1002                                 it->second.clear();
1003                         }
1004                         m_craft_defs[type].clear();
1005                 }
1006                 m_output_craft_definitions.clear();
1007         }
1008         virtual void initHashes(IGameDef *gamedef)
1009         {
1010                 // Move the CraftDefs from the unhashed layer into layers higher up.
1011                 std::vector<CraftDefinition *> &unhashed =
1012                         m_craft_defs[(int) CRAFT_HASH_TYPE_UNHASHED][0];
1013                 for (std::vector<CraftDefinition*>::size_type i = 0;
1014                         i < unhashed.size(); i++) {
1015                         CraftDefinition *def = unhashed[i];
1016
1017                         // Initialize and get the definition's hash
1018                         def->initHash(gamedef);
1019                         CraftHashType type = def->getHashType();
1020                         u64 hash = def->getHash(type);
1021
1022                         // Enter the definition
1023                         m_craft_defs[type][hash].push_back(def);
1024                 }
1025                 unhashed.clear();
1026         }
1027 private:
1028         //TODO: change both maps to unordered_map when c++11 can be used
1029         std::vector<std::map<u64, std::vector<CraftDefinition*> > > m_craft_defs;
1030         std::map<std::string, std::vector<CraftDefinition*> > m_output_craft_definitions;
1031 };
1032
1033 IWritableCraftDefManager* createCraftDefManager()
1034 {
1035         return new CCraftDefManager();
1036 }
1037