Fix aliases not working in shapeless crafting recipes
[oweals/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 "strfnd.h"
31 #include "exceptions.h"
32
33 // Check if input matches recipe
34 // Takes recipe groups into account
35 static bool inputItemMatchesRecipe(const std::string &inp_name,
36                 const std::string &rec_name, IItemDefManager *idef)
37 {
38         // Exact name
39         if(inp_name == rec_name)
40                 return true;
41
42         // Group
43         if(rec_name.substr(0,6) == "group:" && idef->isKnown(inp_name)){
44                 const struct ItemDefinition &def = idef->get(inp_name);
45                 Strfnd f(rec_name.substr(6));
46                 bool all_groups_match = true;
47                 do{
48                         std::string check_group = f.next(",");
49                         if(itemgroup_get(def.groups, check_group) == 0){
50                                 all_groups_match = false;
51                                 break;
52                         }
53                 }while(!f.atend());
54                 if(all_groups_match)
55                         return true;
56         }
57
58         // Didn't match
59         return false;
60 }
61
62 // Deserialize an itemstring then return the name of the item
63 static std::string craftGetItemName(const std::string &itemstring, IGameDef *gamedef)
64 {
65         ItemStack item;
66         item.deSerialize(itemstring, gamedef->idef());
67         return item.name;
68 }
69
70 // (mapcar craftGetItemName itemstrings)
71 static std::vector<std::string> craftGetItemNames(
72                 const std::vector<std::string> &itemstrings, IGameDef *gamedef)
73 {
74         std::vector<std::string> result;
75         for(std::vector<std::string>::const_iterator
76                         i = itemstrings.begin();
77                         i != itemstrings.end(); i++)
78         {
79                 result.push_back(craftGetItemName(*i, gamedef));
80         }
81         return result;
82 }
83
84 // Get name of each item, and return them as a new list.
85 static std::vector<std::string> craftGetItemNames(
86                 const std::vector<ItemStack> &items, IGameDef *gamedef)
87 {
88         std::vector<std::string> result;
89         for(std::vector<ItemStack>::const_iterator
90                         i = items.begin();
91                         i != items.end(); i++)
92         {
93                 result.push_back(i->name);
94         }
95         return result;
96 }
97
98 // convert a list of item names, to ItemStacks.
99 static std::vector<ItemStack> craftGetItems(
100                 const std::vector<std::string> &items, IGameDef *gamedef)
101 {
102         std::vector<ItemStack> result;
103         for(std::vector<std::string>::const_iterator
104                         i = items.begin();
105                         i != items.end(); i++)
106         {
107                 result.push_back(ItemStack(std::string(*i),(u16)1,(u16)0,"",gamedef->getItemDefManager()));
108         }
109         return result;
110 }
111
112 // Compute bounding rectangle given a matrix of items
113 // Returns false if every item is ""
114 static bool craftGetBounds(const std::vector<std::string> &items, unsigned int width,
115                 unsigned int &min_x, unsigned int &max_x,
116                 unsigned int &min_y, unsigned int &max_y)
117 {
118         bool success = false;
119         unsigned int x = 0;
120         unsigned int y = 0;
121         for(std::vector<std::string>::const_iterator
122                         i = items.begin();
123                         i != items.end(); i++)
124         {
125                 if(*i != "")  // Is this an actual item?
126                 {
127                         if(!success)
128                         {
129                                 // This is the first nonempty item
130                                 min_x = max_x = x;
131                                 min_y = max_y = y;
132                                 success = true;
133                         }
134                         else
135                         {
136                                 if(x < min_x) min_x = x;
137                                 if(x > max_x) max_x = x;
138                                 if(y < min_y) min_y = y;
139                                 if(y > max_y) max_y = y;
140                         }
141                 }
142
143                 // Step coordinate
144                 x++;
145                 if(x == width)
146                 {
147                         x = 0;
148                         y++;
149                 }
150         }
151         return success;
152 }
153
154 // Removes 1 from each item stack
155 static void craftDecrementInput(CraftInput &input, IGameDef *gamedef)
156 {
157         for(std::vector<ItemStack>::iterator
158                         i = input.items.begin();
159                         i != input.items.end(); i++)
160         {
161                 if(i->count != 0)
162                         i->remove(1);
163         }
164 }
165
166 // Removes 1 from each item stack with replacement support
167 // Example: if replacements contains the pair ("bucket:bucket_water", "bucket:bucket_empty"),
168 //   a water bucket will not be removed but replaced by an empty bucket.
169 static void craftDecrementOrReplaceInput(CraftInput &input,
170                 const CraftReplacements &replacements,
171                 IGameDef *gamedef)
172 {
173         if(replacements.pairs.empty())
174         {
175                 craftDecrementInput(input, gamedef);
176                 return;
177         }
178
179         // Make a copy of the replacements pair list
180         std::vector<std::pair<std::string, std::string> > pairs = replacements.pairs;
181
182         for(std::vector<ItemStack>::iterator
183                         i = input.items.begin();
184                         i != input.items.end(); i++)
185         {
186                 if(i->count == 1)
187                 {
188                         // Find an appropriate replacement
189                         bool found_replacement = false;
190                         for(std::vector<std::pair<std::string, std::string> >::iterator
191                                         j = pairs.begin();
192                                         j != pairs.end(); j++)
193                         {
194                                 ItemStack from_item;
195                                 from_item.deSerialize(j->first, gamedef->idef());
196                                 if(i->name == from_item.name)
197                                 {
198                                         i->deSerialize(j->second, gamedef->idef());
199                                         found_replacement = true;
200                                         pairs.erase(j);
201                                         break;
202                                 }
203                         }
204                         // No replacement was found, simply decrement count to zero
205                         if(!found_replacement)
206                                 i->remove(1);
207                 }
208                 else if(i->count >= 2)
209                 {
210                         // Ignore replacements for items with count >= 2
211                         i->remove(1);
212                 }
213         }
214 }
215
216 // Dump an itemstring matrix
217 static std::string craftDumpMatrix(const std::vector<std::string> &items,
218                 unsigned int width)
219 {
220         std::ostringstream os(std::ios::binary);
221         os<<"{ ";
222         unsigned int x = 0;
223         for(std::vector<std::string>::const_iterator
224                         i = items.begin();
225                         i != items.end(); i++, x++)
226         {
227                 if(x == width)
228                 {
229                         os<<"; ";
230                         x = 0;
231                 }
232                 else if(x != 0)
233                 {
234                         os<<",";
235                 }
236                 os<<"\""<<(*i)<<"\"";
237         }
238         os<<" }";
239         return os.str();
240 }
241
242 // Dump an item matrix
243 std::string craftDumpMatrix(const std::vector<ItemStack> &items,
244                 unsigned int width)
245 {
246         std::ostringstream os(std::ios::binary);
247         os<<"{ ";
248         unsigned int x = 0;
249         for(std::vector<ItemStack>::const_iterator
250                         i = items.begin();
251                         i != items.end(); i++, x++)
252         {
253                 if(x == width)
254                 {
255                         os<<"; ";
256                         x = 0;
257                 }
258                 else if(x != 0)
259                 {
260                         os<<",";
261                 }
262                 os<<"\""<<(i->getItemString())<<"\"";
263         }
264         os<<" }";
265         return os.str();
266 }
267
268
269 /*
270         CraftInput
271 */
272
273 std::string CraftInput::dump() const
274 {
275         std::ostringstream os(std::ios::binary);
276         os<<"(method="<<((int)method)<<", items="<<craftDumpMatrix(items, width)<<")";
277         return os.str();
278 }
279
280 /*
281         CraftOutput
282 */
283
284 std::string CraftOutput::dump() const
285 {
286         std::ostringstream os(std::ios::binary);
287         os<<"(item=\""<<item<<"\", time="<<time<<")";
288         return os.str();
289 }
290
291 /*
292         CraftReplacements
293 */
294
295 std::string CraftReplacements::dump() const
296 {
297         std::ostringstream os(std::ios::binary);
298         os<<"{";
299         const char *sep = "";
300         for(std::vector<std::pair<std::string, std::string> >::const_iterator
301                         i = pairs.begin();
302                         i != pairs.end(); i++)
303         {
304                 os<<sep<<"\""<<(i->first)<<"\"=>\""<<(i->second)<<"\"";
305                 sep = ",";
306         }
307         os<<"}";
308         return os.str();
309 }
310
311 void CraftReplacements::serialize(std::ostream &os) const
312 {
313         writeU16(os, pairs.size());
314         for(u32 i=0; i<pairs.size(); i++)
315         {
316                 os<<serializeString(pairs[i].first);
317                 os<<serializeString(pairs[i].second);
318         }
319 }
320
321 void CraftReplacements::deSerialize(std::istream &is)
322 {
323         pairs.clear();
324         u32 count = readU16(is);
325         for(u32 i=0; i<count; i++)
326         {
327                 std::string first = deSerializeString(is);
328                 std::string second = deSerializeString(is);
329                 pairs.push_back(std::make_pair(first, second));
330         }
331 }
332
333 /*
334         CraftDefinition
335 */
336
337 void CraftDefinition::serialize(std::ostream &os) const
338 {
339         writeU8(os, 1); // version
340         os<<serializeString(getName());
341         serializeBody(os);
342 }
343
344 CraftDefinition* CraftDefinition::deSerialize(std::istream &is)
345 {
346         int version = readU8(is);
347         if(version != 1) throw SerializationError(
348                         "unsupported CraftDefinition version");
349         std::string name = deSerializeString(is);
350         CraftDefinition *def = NULL;
351         if(name == "shaped")
352         {
353                 def = new CraftDefinitionShaped;
354         }
355         else if(name == "shapeless")
356         {
357                 def = new CraftDefinitionShapeless;
358         }
359         else if(name == "toolrepair")
360         {
361                 def = new CraftDefinitionToolRepair;
362         }
363         else if(name == "cooking")
364         {
365                 def = new CraftDefinitionCooking;
366         }
367         else if(name == "fuel")
368         {
369                 def = new CraftDefinitionFuel;
370         }
371         else
372         {
373                 infostream<<"Unknown CraftDefinition name=\""<<name<<"\""<<std::endl;
374                 throw SerializationError("Unknown CraftDefinition name");
375         }
376         def->deSerializeBody(is, version);
377         return def;
378 }
379
380 /*
381         CraftDefinitionShaped
382 */
383
384 std::string CraftDefinitionShaped::getName() const
385 {
386         return "shaped";
387 }
388
389 bool CraftDefinitionShaped::check(const CraftInput &input, IGameDef *gamedef) const
390 {
391         if(input.method != CRAFT_METHOD_NORMAL)
392                 return false;
393
394         // Get input item matrix
395         std::vector<std::string> inp_names = craftGetItemNames(input.items, gamedef);
396         unsigned int inp_width = input.width;
397         if(inp_width == 0)
398                 return false;
399         while(inp_names.size() % inp_width != 0)
400                 inp_names.push_back("");
401
402         // Get input bounds
403         unsigned int inp_min_x=0, inp_max_x=0, inp_min_y=0, inp_max_y=0;
404         if(!craftGetBounds(inp_names, inp_width, inp_min_x, inp_max_x, inp_min_y, inp_max_y))
405                 return false;  // it was empty
406
407         // Get recipe item matrix
408         std::vector<std::string> rec_names = craftGetItemNames(recipe, gamedef);
409         unsigned int rec_width = width;
410         if(rec_width == 0)
411                 return false;
412         while(rec_names.size() % rec_width != 0)
413                 rec_names.push_back("");
414
415         // Get recipe bounds
416         unsigned int rec_min_x=0, rec_max_x=0, rec_min_y=0, rec_max_y=0;
417         if(!craftGetBounds(rec_names, rec_width, rec_min_x, rec_max_x, rec_min_y, rec_max_y))
418                 return false;  // it was empty
419
420         // Different sizes?
421         if(inp_max_x - inp_min_x != rec_max_x - rec_min_x)
422                 return false;
423         if(inp_max_y - inp_min_y != rec_max_y - rec_min_y)
424                 return false;
425
426         // Verify that all item names in the bounding box are equal
427         unsigned int w = inp_max_x - inp_min_x + 1;
428         unsigned int h = inp_max_y - inp_min_y + 1;
429         for(unsigned int y=0; y<h; y++)
430         for(unsigned int x=0; x<w; x++)
431         {
432                 unsigned int inp_x = inp_min_x + x;
433                 unsigned int inp_y = inp_min_y + y;
434                 unsigned int rec_x = rec_min_x + x;
435                 unsigned int rec_y = rec_min_y + y;
436
437                 if(!inputItemMatchesRecipe(
438                                 inp_names[inp_y * inp_width + inp_x],
439                                 rec_names[rec_y * rec_width + rec_x], gamedef->idef())
440                 ){
441                         return false;
442                 }
443         }
444
445         return true;
446 }
447
448 CraftOutput CraftDefinitionShaped::getOutput(const CraftInput &input, IGameDef *gamedef) const
449 {
450         return CraftOutput(output, 0);
451 }
452
453 CraftInput CraftDefinitionShaped::getInput(const CraftOutput &output, IGameDef *gamedef) const
454 {
455         return CraftInput(CRAFT_METHOD_NORMAL,width,craftGetItems(recipe,gamedef));
456 }
457
458 void CraftDefinitionShaped::decrementInput(CraftInput &input, IGameDef *gamedef) const
459 {
460         craftDecrementOrReplaceInput(input, replacements, gamedef);
461 }
462
463 std::string CraftDefinitionShaped::dump() const
464 {
465         std::ostringstream os(std::ios::binary);
466         os<<"(shaped, output=\""<<output
467                 <<"\", recipe="<<craftDumpMatrix(recipe, width)
468                 <<", replacements="<<replacements.dump()<<")";
469         return os.str();
470 }
471
472 void CraftDefinitionShaped::serializeBody(std::ostream &os) const
473 {
474         os<<serializeString(output);
475         writeU16(os, width);
476         writeU16(os, recipe.size());
477         for(u32 i=0; i<recipe.size(); i++)
478                 os<<serializeString(recipe[i]);
479         replacements.serialize(os);
480 }
481
482 void CraftDefinitionShaped::deSerializeBody(std::istream &is, int version)
483 {
484         if(version != 1) throw SerializationError(
485                         "unsupported CraftDefinitionShaped version");
486         output = deSerializeString(is);
487         width = readU16(is);
488         recipe.clear();
489         u32 count = readU16(is);
490         for(u32 i=0; i<count; i++)
491                 recipe.push_back(deSerializeString(is));
492         replacements.deSerialize(is);
493 }
494
495 /*
496         CraftDefinitionShapeless
497 */
498
499 std::string CraftDefinitionShapeless::getName() const
500 {
501         return "shapeless";
502 }
503
504 bool CraftDefinitionShapeless::check(const CraftInput &input, IGameDef *gamedef) const
505 {
506         if(input.method != CRAFT_METHOD_NORMAL)
507                 return false;
508         
509         // Filter empty items out of input
510         std::vector<std::string> input_filtered;
511         for(std::vector<ItemStack>::const_iterator
512                         i = input.items.begin();
513                         i != input.items.end(); i++)
514         {
515                 if(i->name != "")
516                         input_filtered.push_back(i->name);
517         }
518
519         // If there is a wrong number of items in input, no match
520         if(input_filtered.size() != recipe.size()){
521                 /*dstream<<"Number of input items ("<<input_filtered.size()
522                                 <<") does not match recipe size ("<<recipe.size()<<") "
523                                 <<"of recipe with output="<<output<<std::endl;*/
524                 return false;
525         }
526
527         // Try with all permutations of the recipe
528         std::vector<std::string> recipe_copy = craftGetItemNames(recipe, gamedef);
529         // Start from the lexicographically first permutation (=sorted)
530         std::sort(recipe_copy.begin(), recipe_copy.end());
531         //while(std::prev_permutation(recipe_copy.begin(), recipe_copy.end())){}
532         do{
533                 // If all items match, the recipe matches
534                 bool all_match = true;
535                 //dstream<<"Testing recipe (output="<<output<<"):";
536                 for(size_t i=0; i<recipe.size(); i++){
537                         //dstream<<" ("<<input_filtered[i]<<" == "<<recipe_copy[i]<<")";
538                         if(!inputItemMatchesRecipe(input_filtered[i], recipe_copy[i],
539                                         gamedef->idef())){
540                                 all_match = false;
541                                 break;
542                         }
543                 }
544                 //dstream<<" -> match="<<all_match<<std::endl;
545                 if(all_match)
546                         return true;
547         }while(std::next_permutation(recipe_copy.begin(), recipe_copy.end()));
548
549         return false;
550 }
551
552 CraftOutput CraftDefinitionShapeless::getOutput(const CraftInput &input, IGameDef *gamedef) const
553 {
554         return CraftOutput(output, 0);
555 }
556
557 CraftInput CraftDefinitionShapeless::getInput(const CraftOutput &output, IGameDef *gamedef) const
558 {
559         return CraftInput(CRAFT_METHOD_NORMAL,0,craftGetItems(recipe,gamedef));
560 }
561
562 void CraftDefinitionShapeless::decrementInput(CraftInput &input, IGameDef *gamedef) const
563 {
564         craftDecrementOrReplaceInput(input, replacements, gamedef);
565 }
566
567 std::string CraftDefinitionShapeless::dump() const
568 {
569         std::ostringstream os(std::ios::binary);
570         os<<"(shapeless, output=\""<<output
571                 <<"\", recipe="<<craftDumpMatrix(recipe, recipe.size())
572                 <<", replacements="<<replacements.dump()<<")";
573         return os.str();
574 }
575
576 void CraftDefinitionShapeless::serializeBody(std::ostream &os) const
577 {
578         os<<serializeString(output);
579         writeU16(os, recipe.size());
580         for(u32 i=0; i<recipe.size(); i++)
581                 os<<serializeString(recipe[i]);
582         replacements.serialize(os);
583 }
584
585 void CraftDefinitionShapeless::deSerializeBody(std::istream &is, int version)
586 {
587         if(version != 1) throw SerializationError(
588                         "unsupported CraftDefinitionShapeless version");
589         output = deSerializeString(is);
590         recipe.clear();
591         u32 count = readU16(is);
592         for(u32 i=0; i<count; i++)
593                 recipe.push_back(deSerializeString(is));
594         replacements.deSerialize(is);
595 }
596
597 /*
598         CraftDefinitionToolRepair
599 */
600
601 static ItemStack craftToolRepair(
602                 const ItemStack &item1,
603                 const ItemStack &item2,
604                 float additional_wear,
605                 IGameDef *gamedef)
606 {
607         IItemDefManager *idef = gamedef->idef();
608         if(item1.count != 1 || item2.count != 1 || item1.name != item2.name
609                         || idef->get(item1.name).type != ITEM_TOOL
610                         || idef->get(item2.name).type != ITEM_TOOL)
611         {
612                 // Failure
613                 return ItemStack();
614         }
615
616         s32 item1_uses = 65536 - (u32) item1.wear;
617         s32 item2_uses = 65536 - (u32) item2.wear;
618         s32 new_uses = item1_uses + item2_uses;
619         s32 new_wear = 65536 - new_uses + floor(additional_wear * 65536 + 0.5);
620         if(new_wear >= 65536)
621                 return ItemStack();
622         if(new_wear < 0)
623                 new_wear = 0;
624
625         ItemStack repaired = item1;
626         repaired.wear = new_wear;
627         return repaired;
628 }
629
630 std::string CraftDefinitionToolRepair::getName() const
631 {
632         return "toolrepair";
633 }
634
635 bool CraftDefinitionToolRepair::check(const CraftInput &input, IGameDef *gamedef) const
636 {
637         if(input.method != CRAFT_METHOD_NORMAL)
638                 return false;
639
640         ItemStack item1;
641         ItemStack item2;
642         for(std::vector<ItemStack>::const_iterator
643                         i = input.items.begin();
644                         i != input.items.end(); i++)
645         {
646                 if(!i->empty())
647                 {
648                         if(item1.empty())
649                                 item1 = *i;
650                         else if(item2.empty())
651                                 item2 = *i;
652                         else
653                                 return false;
654                 }
655         }
656         ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
657         return !repaired.empty();
658 }
659
660 CraftOutput CraftDefinitionToolRepair::getOutput(const CraftInput &input, IGameDef *gamedef) const
661 {
662         ItemStack item1;
663         ItemStack item2;
664         for(std::vector<ItemStack>::const_iterator
665                         i = input.items.begin();
666                         i != input.items.end(); i++)
667         {
668                 if(!i->empty())
669                 {
670                         if(item1.empty())
671                                 item1 = *i;
672                         else if(item2.empty())
673                                 item2 = *i;
674                 }
675         }
676         ItemStack repaired = craftToolRepair(item1, item2, additional_wear, gamedef);
677         return CraftOutput(repaired.getItemString(), 0);
678 }
679
680 CraftInput CraftDefinitionToolRepair::getInput(const CraftOutput &output, IGameDef *gamedef) const
681 {
682         std::vector<ItemStack> stack;
683         stack.push_back(ItemStack());
684         return CraftInput(CRAFT_METHOD_COOKING,additional_wear,stack);
685 }
686
687 void CraftDefinitionToolRepair::decrementInput(CraftInput &input, IGameDef *gamedef) const
688 {
689         craftDecrementInput(input, gamedef);
690 }
691
692 std::string CraftDefinitionToolRepair::dump() const
693 {
694         std::ostringstream os(std::ios::binary);
695         os<<"(toolrepair, additional_wear="<<additional_wear<<")";
696         return os.str();
697 }
698
699 void CraftDefinitionToolRepair::serializeBody(std::ostream &os) const
700 {
701         writeF1000(os, additional_wear);
702 }
703
704 void CraftDefinitionToolRepair::deSerializeBody(std::istream &is, int version)
705 {
706         if(version != 1) throw SerializationError(
707                         "unsupported CraftDefinitionToolRepair version");
708         additional_wear = readF1000(is);
709 }
710
711 /*
712         CraftDefinitionCooking
713 */
714
715 std::string CraftDefinitionCooking::getName() const
716 {
717         return "cooking";
718 }
719
720 bool CraftDefinitionCooking::check(const CraftInput &input, IGameDef *gamedef) const
721 {
722         if(input.method != CRAFT_METHOD_COOKING)
723                 return false;
724
725         // Filter empty items out of input
726         std::vector<std::string> input_filtered;
727         for(std::vector<ItemStack>::const_iterator
728                         i = input.items.begin();
729                         i != input.items.end(); i++)
730         {
731                 if(i->name != "")
732                         input_filtered.push_back(i->name);
733         }
734
735         // If there is a wrong number of items in input, no match
736         if(input_filtered.size() != 1){
737                 /*dstream<<"Number of input items ("<<input_filtered.size()
738                                 <<") does not match recipe size (1) "
739                                 <<"of cooking recipe with output="<<output<<std::endl;*/
740                 return false;
741         }
742         
743         // Check the single input item
744         return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
745 }
746
747 CraftOutput CraftDefinitionCooking::getOutput(const CraftInput &input, IGameDef *gamedef) const
748 {
749         return CraftOutput(output, cooktime);
750 }
751
752 CraftInput CraftDefinitionCooking::getInput(const CraftOutput &output, IGameDef *gamedef) const
753 {
754         std::vector<std::string> rec;
755         rec.push_back(recipe);
756         return CraftInput(CRAFT_METHOD_COOKING,cooktime,craftGetItems(rec,gamedef));
757 }
758
759 void CraftDefinitionCooking::decrementInput(CraftInput &input, IGameDef *gamedef) const
760 {
761         craftDecrementOrReplaceInput(input, replacements, gamedef);
762 }
763
764 std::string CraftDefinitionCooking::dump() const
765 {
766         std::ostringstream os(std::ios::binary);
767         os<<"(cooking, output=\""<<output
768                 <<"\", recipe=\""<<recipe
769                 <<"\", cooktime="<<cooktime<<")"
770                 <<", replacements="<<replacements.dump()<<")";
771         return os.str();
772 }
773
774 void CraftDefinitionCooking::serializeBody(std::ostream &os) const
775 {
776         os<<serializeString(output);
777         os<<serializeString(recipe);
778         writeF1000(os, cooktime);
779         replacements.serialize(os);
780 }
781
782 void CraftDefinitionCooking::deSerializeBody(std::istream &is, int version)
783 {
784         if(version != 1) throw SerializationError(
785                         "unsupported CraftDefinitionCooking version");
786         output = deSerializeString(is);
787         recipe = deSerializeString(is);
788         cooktime = readF1000(is);
789         replacements.deSerialize(is);
790 }
791
792 /*
793         CraftDefinitionFuel
794 */
795
796 std::string CraftDefinitionFuel::getName() const
797 {
798         return "fuel";
799 }
800
801 bool CraftDefinitionFuel::check(const CraftInput &input, IGameDef *gamedef) const
802 {
803         if(input.method != CRAFT_METHOD_FUEL)
804                 return false;
805
806         // Filter empty items out of input
807         std::vector<std::string> input_filtered;
808         for(std::vector<ItemStack>::const_iterator
809                         i = input.items.begin();
810                         i != input.items.end(); i++)
811         {
812                 if(i->name != "")
813                         input_filtered.push_back(i->name);
814         }
815
816         // If there is a wrong number of items in input, no match
817         if(input_filtered.size() != 1){
818                 /*dstream<<"Number of input items ("<<input_filtered.size()
819                                 <<") does not match recipe size (1) "
820                                 <<"of fuel recipe with burntime="<<burntime<<std::endl;*/
821                 return false;
822         }
823         
824         // Check the single input item
825         return inputItemMatchesRecipe(input_filtered[0], recipe, gamedef->idef());
826 }
827
828 CraftOutput CraftDefinitionFuel::getOutput(const CraftInput &input, IGameDef *gamedef) const
829 {
830         return CraftOutput("", burntime);
831 }
832
833 CraftInput CraftDefinitionFuel::getInput(const CraftOutput &output, IGameDef *gamedef) const
834 {
835         std::vector<std::string> rec;
836         rec.push_back(recipe);
837         return CraftInput(CRAFT_METHOD_COOKING,(int)burntime,craftGetItems(rec,gamedef));
838 }
839
840 void CraftDefinitionFuel::decrementInput(CraftInput &input, IGameDef *gamedef) const
841 {
842         craftDecrementOrReplaceInput(input, replacements, gamedef);
843 }
844
845 std::string CraftDefinitionFuel::dump() const
846 {
847         std::ostringstream os(std::ios::binary);
848         os<<"(fuel, recipe=\""<<recipe
849                 <<"\", burntime="<<burntime<<")"
850                 <<", replacements="<<replacements.dump()<<")";
851         return os.str();
852 }
853
854 void CraftDefinitionFuel::serializeBody(std::ostream &os) const
855 {
856         os<<serializeString(recipe);
857         writeF1000(os, burntime);
858         replacements.serialize(os);
859 }
860
861 void CraftDefinitionFuel::deSerializeBody(std::istream &is, int version)
862 {
863         if(version != 1) throw SerializationError(
864                         "unsupported CraftDefinitionFuel version");
865         recipe = deSerializeString(is);
866         burntime = readF1000(is);
867         replacements.deSerialize(is);
868 }
869
870 /*
871         Craft definition manager
872 */
873
874 class CCraftDefManager: public IWritableCraftDefManager
875 {
876 public:
877         virtual ~CCraftDefManager()
878         {
879                 clear();
880         }
881         virtual bool getCraftResult(CraftInput &input, CraftOutput &output,
882                         bool decrementInput, IGameDef *gamedef) const
883         {
884                 output.item = "";
885                 output.time = 0;
886
887                 // If all input items are empty, abort.
888                 bool all_empty = true;
889                 for(std::vector<ItemStack>::const_iterator
890                                 i = input.items.begin();
891                                 i != input.items.end(); i++)
892                 {
893                         if(!i->empty())
894                         {
895                                 all_empty = false;
896                                 break;
897                         }
898                 }
899                 if(all_empty)
900                         return false;
901
902                 // Walk crafting definitions from back to front, so that later
903                 // definitions can override earlier ones.
904                 for(std::vector<CraftDefinition*>::const_reverse_iterator
905                                 i = m_craft_definitions.rbegin();
906                                 i != m_craft_definitions.rend(); i++)
907                 {
908                         CraftDefinition *def = *i;
909
910                         /*infostream<<"Checking "<<input.dump()<<std::endl
911                                         <<" against "<<def->dump()<<std::endl;*/
912
913                         try {
914                                 if(def->check(input, gamedef))
915                                 {
916                                         // Get output, then decrement input (if requested)
917                                         output = def->getOutput(input, gamedef);
918                                         if(decrementInput)
919                                                 def->decrementInput(input, gamedef);
920                                         return true;
921                                 }
922                         }
923                         catch(SerializationError &e)
924                         {
925                                 errorstream<<"getCraftResult: ERROR: "
926                                                 <<"Serialization error in recipe "
927                                                 <<def->dump()<<std::endl;
928                                 // then go on with the next craft definition
929                         }
930                 }
931                 return false;
932         }
933         virtual bool getCraftRecipe(CraftInput &input, CraftOutput &output,
934                         IGameDef *gamedef) const
935         {
936                 CraftOutput tmpout;
937                 tmpout.item = "";
938                 tmpout.time = 0;
939
940                 // If output item is empty, abort.
941                 if(output.item.empty())
942                         return false;
943
944                 // Walk crafting definitions from back to front, so that later
945                 // definitions can override earlier ones.
946                 for(std::vector<CraftDefinition*>::const_reverse_iterator
947                                 i = m_craft_definitions.rbegin();
948                                 i != m_craft_definitions.rend(); i++)
949                 {
950                         CraftDefinition *def = *i;
951
952                         /*infostream<<"Checking "<<input.dump()<<std::endl
953                                         <<" against "<<def->dump()<<std::endl;*/
954
955                         try {
956                                 tmpout = def->getOutput(input, gamedef);
957                                 if(tmpout.item.substr(0,output.item.length()) == output.item)
958                                 {
959                                         // Get output, then decrement input (if requested)
960                                         input = def->getInput(output, gamedef);
961                                         return true;
962                                 }
963                         }
964                         catch(SerializationError &e)
965                         {
966                                 errorstream<<"getCraftResult: ERROR: "
967                                                 <<"Serialization error in recipe "
968                                                 <<def->dump()<<std::endl;
969                                 // then go on with the next craft definition
970                         }
971                 }
972                 return false;
973         }
974         virtual std::vector<CraftDefinition*> getCraftRecipes(CraftOutput &output,
975                         IGameDef *gamedef) const
976         {
977                 std::vector<CraftDefinition*> recipes_list;
978                 CraftInput input;
979                 CraftOutput tmpout;
980                 tmpout.item = "";
981                 tmpout.time = 0;
982
983                 for(std::vector<CraftDefinition*>::const_reverse_iterator
984                                 i = m_craft_definitions.rbegin();
985                                 i != m_craft_definitions.rend(); i++)
986                 {
987                         CraftDefinition *def = *i;
988
989                         /*infostream<<"Checking "<<input.dump()<<std::endl
990                                         <<" against "<<def->dump()<<std::endl;*/
991
992                         try {
993                                 tmpout = def->getOutput(input, gamedef);
994                                 if(tmpout.item.substr(0,output.item.length()) == output.item)
995                                 {
996                                         // Get output, then decrement input (if requested)
997                                         input = def->getInput(output, gamedef);
998                                         recipes_list.push_back(*i);
999                                 }
1000                         }
1001                         catch(SerializationError &e)
1002                         {
1003                                 errorstream<<"getCraftResult: ERROR: "
1004                                                 <<"Serialization error in recipe "
1005                                                 <<def->dump()<<std::endl;
1006                                 // then go on with the next craft definition
1007                         }
1008                 }
1009                 return recipes_list;
1010         }
1011         virtual std::string dump() const
1012         {
1013                 std::ostringstream os(std::ios::binary);
1014                 os<<"Crafting definitions:\n";
1015                 for(std::vector<CraftDefinition*>::const_iterator
1016                                 i = m_craft_definitions.begin();
1017                                 i != m_craft_definitions.end(); i++)
1018                 {
1019                         os<<(*i)->dump()<<"\n";
1020                 }
1021                 return os.str();
1022         }
1023         virtual void registerCraft(CraftDefinition *def)
1024         {
1025                 verbosestream<<"registerCraft: registering craft definition: "
1026                                 <<def->dump()<<std::endl;
1027                 m_craft_definitions.push_back(def);
1028         }
1029         virtual void clear()
1030         {
1031                 for(std::vector<CraftDefinition*>::iterator
1032                                 i = m_craft_definitions.begin();
1033                                 i != m_craft_definitions.end(); i++){
1034                         delete *i;
1035                 }
1036                 m_craft_definitions.clear();
1037         }
1038         virtual void serialize(std::ostream &os) const
1039         {
1040                 writeU8(os, 0); // version
1041                 u16 count = m_craft_definitions.size();
1042                 writeU16(os, count);
1043                 for(std::vector<CraftDefinition*>::const_iterator
1044                                 i = m_craft_definitions.begin();
1045                                 i != m_craft_definitions.end(); i++){
1046                         CraftDefinition *def = *i;
1047                         // Serialize wrapped in a string
1048                         std::ostringstream tmp_os(std::ios::binary);
1049                         def->serialize(tmp_os);
1050                         os<<serializeString(tmp_os.str());
1051                 }
1052         }
1053         virtual void deSerialize(std::istream &is)
1054         {
1055                 // Clear everything
1056                 clear();
1057                 // Deserialize
1058                 int version = readU8(is);
1059                 if(version != 0) throw SerializationError(
1060                                 "unsupported CraftDefManager version");
1061                 u16 count = readU16(is);
1062                 for(u16 i=0; i<count; i++){
1063                         // Deserialize a string and grab a CraftDefinition from it
1064                         std::istringstream tmp_is(deSerializeString(is), std::ios::binary);
1065                         CraftDefinition *def = CraftDefinition::deSerialize(tmp_is);
1066                         // Register
1067                         registerCraft(def);
1068                 }
1069         }
1070 private:
1071         std::vector<CraftDefinition*> m_craft_definitions;
1072 };
1073
1074 IWritableCraftDefManager* createCraftDefManager()
1075 {
1076         return new CCraftDefManager();
1077 }
1078