summaryrefslogtreecommitdiffstats
path: root/src/CraftingRecipes.cpp
blob: a2ce359f30b299c54e7ce74194e6084f80f41f6a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860

// CraftingRecipes.cpp

// Interfaces to the cCraftingRecipes class representing the storage of crafting recipes

#include "Globals.h"
#include "CraftingRecipes.h"
#include "Root.h"
#include "Bindings/PluginManager.h"





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cCraftingGrid:

cCraftingGrid::cCraftingGrid(int a_Width, int a_Height) :
	m_Width(a_Width),
	m_Height(a_Height),
	m_Items(new cItem[a_Width * a_Height])
{
}





cCraftingGrid::cCraftingGrid(const cItem * a_Items, int a_Width, int a_Height) :
	m_Width(a_Width),
	m_Height(a_Height),
	m_Items(new cItem[a_Width * a_Height])
{
	for (int i = a_Width * a_Height - 1; i >= 0; i--)
	{
		m_Items[i] = a_Items[i];
	}
}





cCraftingGrid::cCraftingGrid(const cCraftingGrid & a_Original) :
	m_Width(a_Original.m_Width),
	m_Height(a_Original.m_Height),
	m_Items(new cItem[a_Original.m_Width * a_Original.m_Height])
{
	for (int i = m_Width * m_Height - 1; i >= 0; i--)
	{
		m_Items[i] = a_Original.m_Items[i];
	}
}





cCraftingGrid::~cCraftingGrid()
{
	delete[] m_Items;
	m_Items = NULL;
}





cItem & cCraftingGrid::GetItem(int x, int y) const
{
	// Accessible through scripting, must verify parameters:
	if ((x < 0) || (x >= m_Width) || (y < 0) || (y >= m_Height))
	{
		LOGERROR("Attempted to get an invalid item from a crafting grid: (%d, %d), grid dimensions: (%d, %d).",
			x, y, m_Width, m_Height
		);
		return m_Items[0];
	}
	return m_Items[x + m_Width * y];
}





void cCraftingGrid::SetItem(int x, int y, ENUM_ITEM_ID a_ItemType, int a_ItemCount, short a_ItemHealth)
{
	// Accessible through scripting, must verify parameters:
	if ((x < 0) || (x >= m_Width) || (y < 0) || (y >= m_Height))
	{
		LOGERROR("Attempted to set an invalid item in a crafting grid: (%d, %d), grid dimensions: (%d, %d).",
			x, y, m_Width, m_Height
		);
		return;
	}
	
	m_Items[x + m_Width * y] = cItem(a_ItemType, a_ItemCount, a_ItemHealth);
}





void cCraftingGrid::SetItem(int x, int y, const cItem & a_Item)
{
	// Accessible through scripting, must verify parameters:
	if ((x < 0) || (x >= m_Width) || (y < 0) || (y >= m_Height))
	{
		LOGERROR("Attempted to set an invalid item in a crafting grid: (%d, %d), grid dimensions: (%d, %d).",
			x, y, m_Width, m_Height
		);
		return;
	}
	
	m_Items[x + m_Width * y] = a_Item;
}





void cCraftingGrid::Clear(void)
{
	for (int y = 0; y < m_Height; y++) for (int x = 0; x < m_Width; x++)
	{
		m_Items[x + m_Width * y].Empty();
	}
}





void cCraftingGrid::ConsumeGrid(const cCraftingGrid & a_Grid)
{
	if ((a_Grid.m_Width != m_Width) || (a_Grid.m_Height != m_Height))
	{
		LOGWARNING("Consuming a grid of different dimensions: (%d, %d) vs (%d, %d)",
			a_Grid.m_Width, a_Grid.m_Height, m_Width, m_Height
		);
	}
	int MinX = std::min(a_Grid.m_Width,  m_Width);
	int MinY = std::min(a_Grid.m_Height, m_Height);
	for (int y = 0; y <  MinY; y++) for (int x = 0; x < MinX; x++)
	{
		int ThatIdx = x + a_Grid.m_Width * y;
		if (a_Grid.m_Items[ThatIdx].IsEmpty())
		{
			continue;
		}
		int ThisIdx = x + m_Width * y;
		if (a_Grid.m_Items[ThatIdx].m_ItemType != m_Items[ThisIdx].m_ItemType)
		{
			LOGWARNING("Consuming incompatible grids: item at (%d, %d) is %d in grid and %d in ingredients. Item not consumed.",
				x, y, m_Items[ThisIdx].m_ItemType, a_Grid.m_Items[ThatIdx].m_ItemType
			);
			continue;
		}
		char NumWantedItems = a_Grid.m_Items[ThatIdx].m_ItemCount;
		if (NumWantedItems > m_Items[ThisIdx].m_ItemCount)
		{
			LOGWARNING("Consuming more items than there actually are in slot (%d, %d), item %d (want %d, have %d). Item zeroed out.",
				x, y, m_Items[ThisIdx].m_ItemType,
				NumWantedItems, m_Items[ThisIdx].m_ItemCount
			);
			NumWantedItems = m_Items[ThisIdx].m_ItemCount;
		}
		m_Items[ThisIdx].m_ItemCount -= NumWantedItems;
		if (m_Items[ThisIdx].m_ItemCount == 0)
		{
			m_Items[ThisIdx].Clear();
		}
	}  // for x, for y
}





void cCraftingGrid::CopyToItems(cItem * a_Items) const
{
	for (int i = m_Height * m_Width - 1; i >= 0; i--)
	{
		a_Items[i] = m_Items[i];
	}  // for x, for y
}





void cCraftingGrid::Dump(void)
{
	for (int y = 0; y < m_Height; y++) for (int x = 0; x < m_Width; x++)
	{
		#ifdef _DEBUG
		int idx = x + m_Width * y;
		#endif
		LOGD("Slot (%d, %d): Type %d, health %d, count %d",
			x, y, m_Items[idx].m_ItemType, m_Items[idx].m_ItemDamage, m_Items[idx].m_ItemCount
		);
	}
}





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cCraftingRecipe:

cCraftingRecipe::cCraftingRecipe(const cCraftingGrid & a_CraftingGrid) :
	m_Ingredients(a_CraftingGrid)
{
}





void cCraftingRecipe::Clear(void)
{
	m_Ingredients.Clear();
	m_Result.Clear();
}





void cCraftingRecipe::SetResult(ENUM_ITEM_ID a_ItemType, int a_ItemCount, short a_ItemHealth)
{
	m_Result = cItem(a_ItemType, a_ItemCount, a_ItemHealth);
}





void cCraftingRecipe::ConsumeIngredients(cCraftingGrid & a_CraftingGrid)
{
	a_CraftingGrid.ConsumeGrid(m_Ingredients);
}





void cCraftingRecipe::Dump(void)
{
	LOGD("Recipe ingredients:");
	m_Ingredients.Dump();
	LOGD("Result: Type %d, health %d, count %d",
		m_Result.m_ItemType, m_Result.m_ItemDamage, m_Result.m_ItemCount
	);
}





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cCraftingRecipes:

cCraftingRecipes::cCraftingRecipes(void)
{
	LoadRecipes();
}





cCraftingRecipes::~cCraftingRecipes()
{
	ClearRecipes();
}





void cCraftingRecipes::GetRecipe(const cPlayer * a_Player, const cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe)
{
	// Allow plugins to intercept recipes using a pre-craft hook:
	if (cRoot::Get()->GetPluginManager()->CallHookPreCrafting(a_Player, &a_CraftingGrid, &a_Recipe))
	{
		return;
	}
	
	// Built-in recipes:
	std::auto_ptr<cRecipe> Recipe(FindRecipe(a_CraftingGrid.GetItems(), a_CraftingGrid.GetWidth(), a_CraftingGrid.GetHeight()));
	a_Recipe.Clear();
	if (Recipe.get() == NULL)
	{
		// Allow plugins to intercept a no-recipe-found situation:
		cRoot::Get()->GetPluginManager()->CallHookCraftingNoRecipe(a_Player, &a_CraftingGrid, &a_Recipe);
		return;
	}
	for (cRecipeSlots::const_iterator itr = Recipe->m_Ingredients.begin(); itr != Recipe->m_Ingredients.end(); ++itr)
	{
		a_Recipe.SetIngredient(itr->x, itr->y, itr->m_Item);
	}  // for itr
	a_Recipe.SetResult(Recipe->m_Result);
	
	// Allow plugins to intercept recipes after they are processed:
	cRoot::Get()->GetPluginManager()->CallHookPostCrafting(a_Player, &a_CraftingGrid, &a_Recipe);
}





void cCraftingRecipes::LoadRecipes(void)
{
	LOGD("Loading crafting recipes from crafting.txt...");
	ClearRecipes();
	
	// Load the crafting.txt file:
	cFile f;
	if (!f.Open("crafting.txt", cFile::fmRead))
	{
		LOGWARNING("Cannot open file \"crafting.txt\", no crafting recipes will be available!");
		return;
	}
	AString Everything;
	f.ReadRestOfFile(Everything);
	f.Close();
	
	// Split it into lines, then process each line as a single recipe:
	AStringVector Split = StringSplit(Everything, "\n");
	int LineNum = 1;
	for (AStringVector::const_iterator itr = Split.begin(); itr != Split.end(); ++itr, ++LineNum)
	{
		// Remove anything after a '#' sign and trim away the whitespace:
		AString Recipe = TrimString(itr->substr(0, itr->find('#')));
		if (Recipe.empty())
		{
			// Empty recipe
			continue;
		}
		AddRecipeLine(LineNum, Recipe);
	}  // for itr - Split[]
	LOG("Loaded " SIZE_T_FMT " crafting recipes", m_Recipes.size());
}




void cCraftingRecipes::ClearRecipes(void)
{
	for (cRecipes::iterator itr = m_Recipes.begin(); itr != m_Recipes.end(); ++itr)
	{
		delete *itr;
	}
	m_Recipes.clear();
}





void cCraftingRecipes::AddRecipeLine(int a_LineNum, const AString & a_RecipeLine)
{
	AStringVector Sides = StringSplit(a_RecipeLine, "=");
	if (Sides.size() != 2)
	{
		LOGWARNING("crafting.txt: line %d: A single '=' was expected, got %d", a_LineNum, (int)Sides.size() - 1);
		LOGINFO("Offending line: \"%s\"", a_RecipeLine.c_str());
		return;
	}
	
	std::auto_ptr<cCraftingRecipes::cRecipe> Recipe(new cCraftingRecipes::cRecipe);
	
	// Parse the result:
	AStringVector ResultSplit = StringSplit(Sides[0], ",");
	if (ResultSplit.empty())
	{
		LOGWARNING("crafting.txt: line %d: Result is empty, ignoring the recipe.", a_LineNum);
		LOGINFO("Offending line: \"%s\"", a_RecipeLine.c_str());
		return;
	}
	if (!ParseItem(ResultSplit[0], Recipe->m_Result))
	{
		LOGWARNING("crafting.txt: line %d: Cannot parse result item, ignoring the recipe.", a_LineNum);
		LOGINFO("Offending line: \"%s\"", a_RecipeLine.c_str());
		return;
	}
	if (ResultSplit.size() > 1)
	{
		Recipe->m_Result.m_ItemCount = atoi(ResultSplit[1].c_str());
		if (Recipe->m_Result.m_ItemCount == 0)
		{
			LOGWARNING("crafting.txt: line %d: Cannot parse result count, ignoring the recipe.", a_LineNum);
			LOGINFO("Offending line: \"%s\"", a_RecipeLine.c_str());
			return;
		}
	}
	else
	{
		Recipe->m_Result.m_ItemCount = 1;
	}
	
	// Parse each ingredient:
	AStringVector Ingredients = StringSplit(Sides[1], "|");
	int Num = 1;
	for (AStringVector::const_iterator itr = Ingredients.begin(); itr != Ingredients.end(); ++itr, ++Num)
	{
		if (!ParseIngredient(*itr, Recipe.get()))
		{
			LOGWARNING("crafting.txt: line %d: Cannot parse ingredient #%d, ignoring the recipe.", a_LineNum, Num);
			LOGINFO("Offending line: \"%s\"", a_RecipeLine.c_str());
			return;
		}
	}  // for itr - Ingredients[]
	
	NormalizeIngredients(Recipe.get());
	
	m_Recipes.push_back(Recipe.release());
}





bool cCraftingRecipes::ParseItem(const AString & a_String, cItem & a_Item)
{
	// The caller provides error logging
	
	AStringVector Split = StringSplit(a_String, "^");
	if (Split.empty())
	{
		return false;
	}
	
	if (!StringToItem(Split[0], a_Item))
	{
		return false;
	}
	
	if (Split.size() > 1)
	{
		AString Damage = TrimString(Split[1]);
		a_Item.m_ItemDamage = atoi(Damage.c_str());
		if ((a_Item.m_ItemDamage == 0) && (Damage.compare("0") != 0))
		{
			// Parsing the number failed
			return false;
		}
	}
	
	// Success
	return true;
}





bool cCraftingRecipes::ParseIngredient(const AString & a_String, cRecipe * a_Recipe)
{
	// a_String is in this format: "ItemType^damage, X:Y, X:Y, X:Y..."
	AStringVector Split = StringSplit(a_String, ",");
	if (Split.size() < 2)
	{
		// Not enough split items
		return false;
	}
	cItem Item;
	if (!ParseItem(Split[0], Item))
	{
		return false;
	}
	Item.m_ItemCount = 1;
	
	cCraftingRecipes::cRecipeSlots TempSlots;
	for (AStringVector::const_iterator itr = Split.begin() + 1; itr != Split.end(); ++itr)
	{
		// Parse the coords in the split item:
		AStringVector Coords = StringSplit(*itr, ":");
		if ((Coords.size() == 1) && (TrimString(Coords[0]) == "*"))
		{
			cCraftingRecipes::cRecipeSlot Slot;
			Slot.m_Item = Item;
			Slot.x = -1;
			Slot.y = -1;
			TempSlots.push_back(Slot);
			continue;
		}
		if (Coords.size() != 2)
		{
			return false;
		}
		Coords[0] = TrimString(Coords[0]);
		Coords[1] = TrimString(Coords[1]);
		if (Coords[0].empty() || Coords[1].empty())
		{
			return false;
		}
		cCraftingRecipes::cRecipeSlot Slot;
		Slot.m_Item = Item;
		switch (Coords[0][0])
		{
			case '1': Slot.x = 0;  break;
			case '2': Slot.x = 1;  break;
			case '3': Slot.x = 2;  break;
			case '*': Slot.x = -1; break;
			default:
			{
				return false;
			}
		}
		switch (Coords[1][0])
		{
			case '1': Slot.y = 0;  break;
			case '2': Slot.y = 1;  break;
			case '3': Slot.y = 2;  break;
			case '*': Slot.y = -1; break;
			default:
			{
				return false;
			}
		}
		TempSlots.push_back(Slot);
	}  // for itr - Split[]
	
	// Append the ingredients:
	a_Recipe->m_Ingredients.insert(a_Recipe->m_Ingredients.end(), TempSlots.begin(), TempSlots.end());
	return true;
}





void cCraftingRecipes::NormalizeIngredients(cCraftingRecipes::cRecipe * a_Recipe)
{
	// Calculate the minimum coords for ingredients, excluding the "anywhere" items:
	int MinX = MAX_GRID_WIDTH, MaxX = 0;
	int MinY = MAX_GRID_HEIGHT, MaxY = 0;
	for (cRecipeSlots::const_iterator itr = a_Recipe->m_Ingredients.begin(); itr != a_Recipe->m_Ingredients.end(); ++itr)
	{
		if (itr->x >= 0)
		{
			MinX = std::min(itr->x, MinX);
			MaxX = std::max(itr->x, MaxX);
		}
		if (itr->y >= 0)
		{
			MinY = std::min(itr->y, MinY);
			MaxY = std::max(itr->y, MaxY);
		}
	}  // for itr - a_Recipe->m_Ingredients[]

	// Move ingredients so that the minimum coords are 0:0
	for (cRecipeSlots::iterator itr = a_Recipe->m_Ingredients.begin(); itr != a_Recipe->m_Ingredients.end(); ++itr)
	{
		if (itr->x >= 0)
		{
			itr->x -= MinX;
		}
		if (itr->y >= 0)
		{
			itr->y -= MinY;
		}
	}  // for itr - a_Recipe->m_Ingredients[]
	a_Recipe->m_Width  = std::max(MaxX - MinX + 1, 1);
	a_Recipe->m_Height = std::max(MaxY - MinY + 1, 1);
	
	// TODO: Compress two same ingredients with the same coords into a single ingredient with increased item count
}





cCraftingRecipes::cRecipe * cCraftingRecipes::FindRecipe(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight)
{
	ASSERT(a_GridWidth <= MAX_GRID_WIDTH);
	ASSERT(a_GridHeight <= MAX_GRID_HEIGHT);
	
	// Get the real bounds of the crafting grid:
	int GridLeft = MAX_GRID_WIDTH, GridTop = MAX_GRID_HEIGHT;
	int GridRight = 0,  GridBottom = 0;
	for (int y = 0; y < a_GridHeight; y++ ) for(int x = 0; x < a_GridWidth; x++)
	{
		if (!a_CraftingGrid[x + y * a_GridWidth].IsEmpty())
		{
			GridRight  = std::max(x, GridRight);
			GridBottom = std::max(y, GridBottom);
			GridLeft   = std::min(x, GridLeft);
			GridTop    = std::min(y, GridTop);
		}
	}
	int GridWidth = GridRight - GridLeft + 1;
	int GridHeight = GridBottom - GridTop + 1;
	
	// Search in the possibly minimized grid, but keep the stride:
	const cItem * Grid = a_CraftingGrid + GridLeft + (a_GridWidth * GridTop);
	cRecipe * Recipe = FindRecipeCropped(Grid, GridWidth, GridHeight, a_GridWidth);
	if (Recipe == NULL)
	{
		return NULL;
	}
	
	// A recipe has been found, move it to correspond to the original crafting grid:
	for (cRecipeSlots::iterator itrS = Recipe->m_Ingredients.begin(); itrS != Recipe->m_Ingredients.end(); ++itrS)
	{
		itrS->x += GridLeft;
		itrS->y += GridTop;
	}  // for itrS - Recipe->m_Ingredients[]
	
	return Recipe;
}





cCraftingRecipes::cRecipe * cCraftingRecipes::FindRecipeCropped(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight, int a_GridStride)
{
	for (cRecipes::const_iterator itr = m_Recipes.begin(); itr != m_Recipes.end(); ++itr)
	{
		// Both the crafting grid and the recipes are normalized. The only variable possible is the "anywhere" items.
		// This still means that the "anywhere" item may be the one that is offsetting the grid contents to the right or downwards, so we need to check all possible positions.
		// E. g. recipe "A, * | B, 1:1 | ..." still needs to check grid for B at 2:2 (in case A was in grid's 1:1)
		// Calculate the maximum offsets for this recipe relative to the grid size, and iterate through all combinations of offsets.
		// Also, this calculation automatically filters out recipes that are too large for the current grid - the loop won't be entered at all.
		
		int MaxOfsX = a_GridWidth  - (*itr)->m_Width;
		int MaxOfsY = a_GridHeight - (*itr)->m_Height;
		for (int x = 0; x <= MaxOfsX; x++) for (int y = 0; y <= MaxOfsY; y++)
		{
			cRecipe * Recipe = MatchRecipe(a_CraftingGrid, a_GridWidth, a_GridHeight, a_GridStride, *itr, x, y);
			if (Recipe != NULL)
			{
				return Recipe;
			}
		}  // for y, for x
	}  // for itr - m_Recipes[]
	
	// No matching recipe found
	return NULL;
}





cCraftingRecipes::cRecipe * cCraftingRecipes::MatchRecipe(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight, int a_GridStride, const cRecipe * a_Recipe, int a_OffsetX, int a_OffsetY)
{
	// Check the regular items first:
	bool HasMatched[MAX_GRID_WIDTH][MAX_GRID_HEIGHT];
	memset(HasMatched, 0, sizeof(HasMatched));
	for (cRecipeSlots::const_iterator itrS = a_Recipe->m_Ingredients.begin(); itrS != a_Recipe->m_Ingredients.end(); ++itrS)
	{
		if ((itrS->x < 0) || (itrS->y < 0))
		{
			// "Anywhere" item, process later
			continue;
		}
		ASSERT(itrS->x + a_OffsetX < a_GridWidth);
		ASSERT(itrS->y + a_OffsetY < a_GridHeight);
		int GridID = (itrS->x + a_OffsetX) + a_GridStride * (itrS->y + a_OffsetY);
		
		const cItem & Item = itrS->m_Item;
		if (
			(itrS->x >= a_GridWidth) ||
			(itrS->y >= a_GridHeight) ||
			(Item.m_ItemType != a_CraftingGrid[GridID].m_ItemType) ||       // same item type?
			(Item.m_ItemCount > a_CraftingGrid[GridID].m_ItemCount) ||  // not enough items
			(
				(Item.m_ItemDamage > 0) &&  // should compare damage values?
				(Item.m_ItemDamage != a_CraftingGrid[GridID].m_ItemDamage)
			)
		)
		{
			// Doesn't match
			return NULL;
		}
		HasMatched[itrS->x + a_OffsetX][itrS->y + a_OffsetY] = true;
	}  // for itrS - Recipe->m_Ingredients[]
	
	// Process the "Anywhere" items now, and only in the cells that haven't matched yet
	// The "anywhere" items are processed on a first-come-first-served basis.
	// Do not use a recipe with one horizontal and one vertical "anywhere" ("*:1, 1:*") as it may not match properly!
	cRecipeSlots MatchedSlots;  // Stores the slots of "anywhere" items that have matched, with the match coords
	for (cRecipeSlots::const_iterator itrS = a_Recipe->m_Ingredients.begin(); itrS != a_Recipe->m_Ingredients.end(); ++itrS)
	{
		if ((itrS->x >= 0) && (itrS->y >= 0))
		{
			// Regular item, already processed
			continue;
		}
		int StartX = 0, EndX = a_GridWidth  - 1;
		int StartY = 0, EndY = a_GridHeight - 1;
		if (itrS->x >= 0)
		{
			StartX = itrS->x;
			EndX = itrS->x;
		}
		else if (itrS->y >= 0)
		{
			StartY = itrS->y;
			EndY = itrS->y;
		}
		bool Found = false;
		for (int x = StartX; x <= EndX; x++)
		{
			for (int y = StartY; y <= EndY; y++)
			{
				if (HasMatched[x][y])
				{
					// Already matched some other item
					continue;
				}
				int GridIdx = x + a_GridStride * y;
				if (
					(a_CraftingGrid[GridIdx].m_ItemType == itrS->m_Item.m_ItemType) &&
					(
						(itrS->m_Item.m_ItemDamage < 0) ||  // doesn't want damage comparison
						(itrS->m_Item.m_ItemDamage == a_CraftingGrid[GridIdx].m_ItemDamage)  // the damage matches
					)
				)
				{
					HasMatched[x][y] = true;
					Found = true;
					MatchedSlots.push_back(*itrS);
					MatchedSlots.back().x = x;
					MatchedSlots.back().y = y;
					break;
				}
			}  // for y
			if (Found)
			{
				break;
			}
		}  // for x
		if (!Found)
		{
			return NULL;
		}
	}  // for itrS - a_Recipe->m_Ingredients[]
	
	// Check if the whole grid has matched:
	for (int x = 0; x < a_GridWidth; x++) for (int y = 0; y < a_GridHeight; y++)
	{
		if (!HasMatched[x][y] && !a_CraftingGrid[x + a_GridStride * y].IsEmpty())
		{
			// There's an unmatched item in the grid
			return NULL;
		}
	}  // for y, for x
	
	// The recipe has matched. Create a copy of the recipe and set its coords to match the crafting grid:
	std::auto_ptr<cRecipe> Recipe(new cRecipe);
	Recipe->m_Result = a_Recipe->m_Result;
	Recipe->m_Width  = a_Recipe->m_Width;
	Recipe->m_Height = a_Recipe->m_Height;
	for (cRecipeSlots::const_iterator itrS = a_Recipe->m_Ingredients.begin(); itrS != a_Recipe->m_Ingredients.end(); ++itrS)
	{
		if ((itrS->x < 0) || (itrS->y < 0))
		{
			// "Anywhere" item, process later
			continue;
		}
		Recipe->m_Ingredients.push_back(*itrS);
	}
	Recipe->m_Ingredients.insert(Recipe->m_Ingredients.end(), MatchedSlots.begin(), MatchedSlots.end());

	// We use Recipe instead of a_Recipe because we want the wildcard ingredients' slot numbers as well, which was just added previously
	HandleFireworks(a_CraftingGrid, Recipe.get(), a_GridStride, a_OffsetX, a_OffsetY);

	return Recipe.release();
}





void cCraftingRecipes::HandleFireworks(const cItem * a_CraftingGrid, cCraftingRecipes::cRecipe * a_Recipe, int a_GridStride, int a_OffsetX, int a_OffsetY)
{
	// TODO: add support for more than one dye in the recipe
	// A manual and temporary solution (listing everything) is in crafting.txt for fade colours, but a programmatic solutions needs to be done for everything else

	if (a_Recipe->m_Result.m_ItemType == E_ITEM_FIREWORK_ROCKET)
	{
		for (cRecipeSlots::const_iterator itr = a_Recipe->m_Ingredients.begin(); itr != a_Recipe->m_Ingredients.end(); ++itr)
		{
			switch (itr->m_Item.m_ItemType)
			{
				case E_ITEM_FIREWORK_STAR:
				{
					// Result was a rocket, found a star - copy star data to rocket data
					int GridID = (itr->x + a_OffsetX) + a_GridStride * (itr->y + a_OffsetY);
					a_Recipe->m_Result.m_FireworkItem.CopyFrom(a_CraftingGrid[GridID].m_FireworkItem);
					break;
				}
				case E_ITEM_GUNPOWDER:
				{
					// Gunpowder - increase flight time
					a_Recipe->m_Result.m_FireworkItem.m_FlightTimeInTicks += 20;
					break;
				}
				case E_ITEM_PAPER: break;
				default: LOG("Unexpected item in firework rocket recipe, was the crafting file's fireworks section changed?"); break;
			}
		}
	}
	else if (a_Recipe->m_Result.m_ItemType == E_ITEM_FIREWORK_STAR)
	{
		std::vector<int> DyeColours;
		bool FoundStar = false;

		for (cRecipeSlots::const_iterator itr = a_Recipe->m_Ingredients.begin(); itr != a_Recipe->m_Ingredients.end(); ++itr)
		{
			switch (itr->m_Item.m_ItemType)
			{
				case E_ITEM_FIREWORK_STAR:
				{
					// Result was star, found another star - probably adding fade colours, but copy data over anyhow
					FoundStar = true;
					int GridID = (itr->x + a_OffsetX) + a_GridStride * (itr->y + a_OffsetY);
					a_Recipe->m_Result.m_FireworkItem.CopyFrom(a_CraftingGrid[GridID].m_FireworkItem);
					break;
				}
				case E_ITEM_DYE:
				{
					int GridID = (itr->x + a_OffsetX) + a_GridStride * (itr->y + a_OffsetY);
					DyeColours.push_back(cFireworkItem::GetVanillaColourCodeFromDye((NIBBLETYPE)(a_CraftingGrid[GridID].m_ItemDamage & 0x0f)));
					break;
				}
				case E_ITEM_GUNPOWDER: break;
				case E_ITEM_DIAMOND: a_Recipe->m_Result.m_FireworkItem.m_HasTrail = true; break;
				case E_ITEM_GLOWSTONE_DUST: a_Recipe->m_Result.m_FireworkItem.m_HasFlicker = true; break;

				case E_ITEM_FIRE_CHARGE: a_Recipe->m_Result.m_FireworkItem.m_Type = 1; break;
				case E_ITEM_GOLD_NUGGET: a_Recipe->m_Result.m_FireworkItem.m_Type = 2; break;
				case E_ITEM_FEATHER: a_Recipe->m_Result.m_FireworkItem.m_Type = 4; break;
				case E_ITEM_HEAD: a_Recipe->m_Result.m_FireworkItem.m_Type = 3; break;
				default: LOG("Unexpected item in firework star recipe, was the crafting file's fireworks section changed?"); break; // ermahgerd BARD ardmins
			}
		}

		if (FoundStar && (!DyeColours.empty()))
		{
			// Found a star and a dye? Fade colours.
			a_Recipe->m_Result.m_FireworkItem.m_FadeColours = DyeColours;
		}
		else if (!DyeColours.empty())
		{
			// Only dye? Normal colours.
			a_Recipe->m_Result.m_FireworkItem.m_Colours = DyeColours;
		}
	}
}