This repository was archived by the owner on Dec 8, 2025. It is now read-only.
forked from AqlaSolutions/MagicStorage
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathCraftingGUI.cs
More file actions
1909 lines (1673 loc) · 57.1 KB
/
CraftingGUI.cs
File metadata and controls
1909 lines (1673 loc) · 57.1 KB
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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using MagicStorageExtra.Components;
using MagicStorageExtra.Items;
using MagicStorageExtra.Sorting;
using MagicStorageExtra.UI;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Terraria;
using Terraria.GameContent.UI.Elements;
using Terraria.ID;
using Terraria.Localization;
using Terraria.Map;
using Terraria.ModLoader;
using Terraria.UI;
namespace MagicStorageExtra
{
public static class CraftingGUI
{
private const int RecipeButtonsAvailableChoice = 0;
private const int RecipeButtonsBlacklistChoice = 3;
private const int RecipeButtonsFavoritesChoice = 2;
private const int padding = 4;
private const int numColumns = 10;
private const int numColumns2 = 7;
private const float inventoryScale = 0.85f;
private const float smallScale = 0.7f;
private const int startMaxCraftTimer = 20;
private const int startMaxRightClickTimer = 20;
private static HashSet<int> threadCheckListFoundItems;
private static volatile bool wasItemChecklistRetrieved;
private static MouseState curMouse;
private static MouseState oldMouse;
private static UIPanel basePanel;
private static float panelTop;
private static float panelLeft;
private static float panelWidth;
private static float panelHeight;
private static UIElement topBar;
public static UISearchBar searchBar;
private static UIButtonChoice sortButtons;
internal static UIButtonChoice recipeButtons;
private static UIElement topBar2;
private static UIButtonChoice filterButtons;
private static UIText stationText;
private static readonly UISlotZone stationZone = new UISlotZone(HoverStation, GetStation, inventoryScale / 1.55f);
private static readonly UISlotZone recipeZone = new UISlotZone(HoverRecipe, GetRecipe, inventoryScale);
private static readonly UIScrollbar scrollBar = new UIScrollbar();
private static int scrollBarFocus;
private static int scrollBarFocusMouseStart;
private static float scrollBarFocusPositionStart;
private static readonly float scrollBarViewSize = 1f;
private static float scrollBarMaxViewSize = 2f;
private static readonly List<Item> items = new List<Item>();
private static readonly Dictionary<int, int> itemCounts = new Dictionary<int, int>();
private static List<Recipe> recipes = new List<Recipe>();
private static List<bool> recipeAvailable = new List<bool>();
private static Recipe selectedRecipe;
private static int numRows;
private static int displayRows;
private static bool slotFocus;
private static readonly UIElement bottomBar = new UIElement();
private static UIText capacityText;
private static UIPanel recipePanel;
private static float recipeTop;
private static float recipeLeft;
private static float recipeWidth;
private static float recipeHeight;
private static UIText recipePanelHeader;
private static UIText ingredientText;
private static readonly UISlotZone ingredientZone = new UISlotZone(HoverItem, GetIngredient, smallScale);
private static readonly UISlotZone recipeHeaderZone = new UISlotZone(HoverHeader, GetHeader, smallScale);
private static UIText reqObjText;
private static UIText reqObjText2;
private static UIText storedItemsText;
private static readonly UISlotZone storageZone = new UISlotZone(HoverStorage, GetStorage, smallScale);
private static int numRows2;
private static int displayRows2;
private static readonly List<Item> storageItems = new List<Item>();
private static readonly List<ItemData> blockStorageItems = new List<ItemData>();
private static readonly UIScrollbar scrollBar2 = new UIScrollbar();
private static readonly float scrollBar2ViewSize = 1f;
private static float scrollBar2MaxViewSize = 2f;
private static UITextPanel<LocalizedText> craftButton;
private static readonly ModSearchBox modSearchBox = new ModSearchBox(RefreshItems);
private static Item result;
private static readonly UISlotZone resultZone = new UISlotZone(HoverResult, GetResult, inventoryScale);
private static int craftTimer;
private static int maxCraftTimer = startMaxCraftTimer;
private static int rightClickTimer;
private static int maxRightClickTimer = startMaxRightClickTimer;
private static readonly object threadLock = new object();
private static readonly object recipeLock = new object();
private static bool threadRunning;
private static bool threadNeedsRestart;
private static SortMode threadSortMode;
private static FilterMode threadFilterMode;
private static readonly List<Recipe> threadRecipes = new List<Recipe>();
private static readonly List<bool> threadRecipeAvailable = new List<bool>();
private static List<Recipe> nextRecipes = new List<Recipe>();
private static List<bool> nextRecipeAvailable = new List<bool>();
private static Dictionary<int, Recipe[]> _productToRecipes;
public static bool compoundCrafting;
public static List<Item> compoundCraftSurplus = new List<Item>();
private static MethodInfo _getAcceptedGroups;
public static bool[] adjTiles { get; private set; } = new bool[TileLoader.TileCount];
public static bool adjWater { get; private set; }
public static bool adjLava { get; private set; }
public static bool adjHoney { get; private set; }
public static bool zoneSnow { get; private set; }
public static bool alchemyTable { get; private set; }
public static bool MouseClicked => curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released;
public static bool RightMouseClicked => curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released;
private static StoragePlayer ModPlayer => Main.LocalPlayer.GetModPlayer<StoragePlayer>();
public static void Initialize()
{
lock (recipeLock)
{
recipes = nextRecipes;
recipeAvailable = nextRecipeAvailable;
}
InitLangStuff();
float itemSlotWidth = Main.inventoryBackTexture.Width * inventoryScale;
float itemSlotHeight = Main.inventoryBackTexture.Height * inventoryScale;
float smallSlotWidth = Main.inventoryBackTexture.Width * smallScale;
float smallSlotHeight = Main.inventoryBackTexture.Height * smallScale;
panelTop = Main.instance.invBottom + 60;
panelLeft = 20f;
basePanel = new UIPanel();
float innerPanelWidth = numColumns * (itemSlotWidth + padding) + 20f + padding;
panelWidth = basePanel.PaddingLeft + innerPanelWidth + basePanel.PaddingRight;
panelHeight = Main.screenHeight - panelTop - 40f;
basePanel.Left.Set(panelLeft, 0f);
basePanel.Top.Set(panelTop, 0f);
basePanel.Width.Set(panelWidth, 0f);
basePanel.Height.Set(panelHeight, 0f);
basePanel.Recalculate();
recipePanel = new UIPanel();
recipeTop = panelTop;
recipeLeft = panelLeft + panelWidth;
recipeWidth = numColumns2 * (smallSlotWidth + padding) + 20f + padding;
recipeWidth += recipePanel.PaddingLeft + recipePanel.PaddingRight;
recipeHeight = panelHeight;
recipePanel.Left.Set(recipeLeft, 0f);
recipePanel.Top.Set(recipeTop, 0f);
recipePanel.Width.Set(recipeWidth, 0f);
recipePanel.Height.Set(recipeHeight, 0f);
recipePanel.Recalculate();
topBar = new UIElement();
topBar.Width.Set(0f, 1f);
topBar.Height.Set(32f, 0f);
basePanel.Append(topBar);
InitSortButtons();
topBar.Append(sortButtons);
float sortButtonsRight = sortButtons.GetDimensions().Width + padding;
InitRecipeButtons();
float recipeButtonsLeft = sortButtonsRight + 3 * padding;
recipeButtons.Left.Set(recipeButtonsLeft, 0f);
topBar.Append(recipeButtons);
float recipeButtonsRight = recipeButtonsLeft + recipeButtons.GetDimensions().Width + padding;
searchBar.Left.Set(recipeButtonsRight + padding, 0f);
searchBar.Width.Set(-recipeButtonsRight - 2 * padding, 1f);
searchBar.Height.Set(0f, 1f);
topBar.Append(searchBar);
topBar2 = new UIElement();
topBar2.Width.Set(0f, 1f);
topBar2.Height.Set(32f, 0f);
topBar2.Top.Set(36f, 0f);
basePanel.Append(topBar2);
InitFilterButtons();
float filterButtonsRight = filterButtons.GetDimensions().Width + padding;
topBar2.Append(filterButtons);
modSearchBox.Button.Left.Set(filterButtonsRight + padding, 0f);
modSearchBox.Button.Width.Set(-filterButtonsRight - 2 * padding, 1f);
modSearchBox.Button.Height.Set(0f, 1f);
modSearchBox.Button.OverflowHidden = true;
topBar2.Append(modSearchBox.Button);
stationText.Top.Set(76f, 0f);
basePanel.Append(stationText);
stationZone.Width.Set(0f, 1f);
stationZone.Top.Set(100f, 0f);
stationZone.Height.Set(110f, 0f);
stationZone.SetDimensions(15, 3);
basePanel.Append(stationZone);
recipeZone.Width.Set(0f, 1f);
recipeZone.Top.Set(196f, 0f);
recipeZone.Height.Set(-196f, 1f);
basePanel.Append(recipeZone);
numRows = (recipes.Count + numColumns - 1) / numColumns;
displayRows = (int) recipeZone.GetDimensions().Height / ((int) itemSlotHeight + padding);
recipeZone.SetDimensions(numColumns, displayRows);
int noDisplayRows = numRows - displayRows;
if (noDisplayRows < 0)
noDisplayRows = 0;
scrollBarMaxViewSize = 1 + noDisplayRows;
scrollBar.Height.Set(displayRows * (itemSlotHeight + padding), 0f);
scrollBar.Left.Set(-20f, 1f);
scrollBar.SetView(scrollBarViewSize, scrollBarMaxViewSize);
recipeZone.Append(scrollBar);
bottomBar.Width.Set(0f, 1f);
bottomBar.Height.Set(32f, 0f);
bottomBar.Top.Set(-32f, 1f);
basePanel.Append(bottomBar);
capacityText.Left.Set(6f, 0f);
capacityText.Top.Set(6f, 0f);
TEStorageHeart heart = GetHeart();
int numItems = 0;
int capacity = 0;
if (heart != null)
foreach (TEAbstractStorageUnit abstractStorageUnit in heart.GetStorageUnits())
if (abstractStorageUnit is TEStorageUnit storageUnit)
{
numItems += storageUnit.NumItems;
capacity += storageUnit.Capacity;
}
capacityText.SetText(numItems + "/" + capacity + " Items");
bottomBar.Append(capacityText);
recipePanelHeader.Left.Set(60, 0f);
recipePanel.Append(recipePanelHeader);
ingredientText.Top.Set(30f, 0f);
ingredientText.Left.Set(60, 0f);
recipeHeaderZone.SetDimensions(1, 1);
recipePanel.Append(recipeHeaderZone);
recipePanel.Append(ingredientText);
int itemsNeeded = selectedRecipe?.requiredItem.Count(item => !item.IsAir) ?? numColumns2 * 2;
int recipeRows = itemsNeeded / numColumns2;
int extraRow = itemsNeeded % numColumns2 != 0 ? 1 : 0;
int totalRows = recipeRows + extraRow;
if (totalRows < 2)
totalRows = 2;
const float ingredientZoneTop = 54f;
float ingredientZoneHeight = 30f * totalRows;
ingredientZone.SetDimensions(numColumns2, totalRows);
ingredientZone.Top.Set(ingredientZoneTop, 0f);
ingredientZone.Width.Set(0f, 1f);
ingredientZone.Height.Set(ingredientZoneHeight, 0f);
recipePanel.Append(ingredientZone);
float reqObjTextTop = ingredientZoneTop + ingredientZoneHeight + 11 * totalRows;
float reqObjText2Top = reqObjTextTop + 24;
reqObjText.Top.Set(reqObjTextTop, 0f);
recipePanel.Append(reqObjText);
reqObjText2.Top.Set(reqObjText2Top, 0f);
recipePanel.Append(reqObjText2);
int reqObjText2Rows = reqObjText2.Text.Count(c => c == '\n') + 1;
float storedItemsTextTop = reqObjText2Top + 30 * reqObjText2Rows;
float storageZoneTop = storedItemsTextTop + 24;
storedItemsText.Top.Set(storedItemsTextTop, 0f);
recipePanel.Append(storedItemsText);
storageZone.Top.Set(storageZoneTop, 0f);
storageZone.Width.Set(0f, 1f);
storageZone.Height.Set(-storageZoneTop - 36, 1f);
recipePanel.Append(storageZone);
numRows2 = (storageItems.Count + numColumns2 - 1) / numColumns2;
displayRows2 = (int) storageZone.GetDimensions().Height / ((int) smallSlotHeight + padding);
storageZone.SetDimensions(numColumns2, displayRows2);
int noDisplayRows2 = numRows2 - displayRows2;
if (noDisplayRows2 < 0)
noDisplayRows2 = 0;
scrollBar2MaxViewSize = 1 + noDisplayRows2;
scrollBar2.Height.Set(displayRows2 * (smallSlotHeight + padding), 0f);
scrollBar2.Left.Set(-20f, 1f);
scrollBar2.SetView(scrollBar2ViewSize, scrollBar2MaxViewSize);
storageZone.Append(scrollBar2);
craftButton.Top.Set(-32f, 1f);
craftButton.Width.Set(100f, 0f);
craftButton.Height.Set(24f, 0f);
craftButton.PaddingTop = 8f;
craftButton.PaddingBottom = 8f;
recipePanel.Append(craftButton);
resultZone.SetDimensions(1, 1);
resultZone.Left.Set(-itemSlotWidth, 1f);
resultZone.Top.Set(-itemSlotHeight, 1f);
resultZone.Width.Set(itemSlotWidth, 0f);
resultZone.Height.Set(itemSlotHeight, 0f);
recipePanel.Append(resultZone);
}
private static void InitLangStuff()
{
if (searchBar == null)
searchBar = new UISearchBar(Language.GetText("Mods.MagicStorageExtra.SearchName"), RefreshItems);
if (stationText == null)
stationText = new UIText(Language.GetText("Mods.MagicStorageExtra.CraftingStations"));
if (capacityText == null)
capacityText = new UIText("Items");
if (recipePanelHeader == null)
recipePanelHeader = new UIText(Language.GetText("Mods.MagicStorageExtra.SelectedRecipe"));
if (ingredientText == null)
ingredientText = new UIText(Language.GetText("Mods.MagicStorageExtra.Ingredients"));
if (reqObjText == null)
reqObjText = new UIText(Language.GetText("LegacyInterface.22"));
if (reqObjText2 == null)
reqObjText2 = new UIText("");
if (storedItemsText == null)
storedItemsText = new UIText(Language.GetText("Mods.MagicStorageExtra.StoredItems"));
if (craftButton == null)
craftButton = new UITextPanel<LocalizedText>(Language.GetText("LegacyMisc.72"));
modSearchBox.InitLangStuff();
}
internal static void Unload()
{
sortButtons = null;
filterButtons = null;
recipeButtons = null;
selectedRecipe = null;
}
private static void InitSortButtons()
{
if (sortButtons == null)
sortButtons = GUIHelpers.MakeSortButtons(RefreshItems);
}
private static void InitRecipeButtons()
{
if (recipeButtons == null)
{
recipeButtons = new UIButtonChoice(RefreshItems, new[]
{
MagicStorageExtra.Instance.GetTexture("Assets/RecipeAvailable"),
MagicStorageExtra.Instance.GetTexture("Assets/RecipeAll"),
MagicStorageExtra.Instance.GetTexture("Assets/FilterMisc"),
MagicStorageExtra.Instance.GetTexture("Assets/RecipeAll")
}, new[]
{
Language.GetText("Mods.MagicStorageExtra.RecipeAvailable"),
Language.GetText("Mods.MagicStorageExtra.RecipeAll"),
Language.GetText("Mods.MagicStorageExtra.ShowOnlyFavorited"),
Language.GetText("Mods.MagicStorageExtra.RecipeBlacklist")
});
if (MagicStorageConfig.UseConfigFilter)
recipeButtons.Choice = MagicStorageConfig.ShowAllRecipes ? 1 : 0;
}
}
private static void InitFilterButtons()
{
if (filterButtons == null)
filterButtons = GUIHelpers.MakeFilterButtons(false, RefreshItems);
}
private static void InitReflection()
{
if (_getAcceptedGroups == null)
_getAcceptedGroups = typeof(RecipeFinder).GetMethod("GetAcceptedGroups", BindingFlags.NonPublic | BindingFlags.Static);
}
private static List<int> GetAcceptedVanillaGroups(Recipe recipe) => (List<int>) _getAcceptedGroups?.Invoke(null, new object[] {recipe});
public static void Update(GameTime gameTime)
{
try
{
if (MagicStorageExtra.IsItemKnownHotKey != null && MagicStorageExtra.IsItemKnownHotKey.GetAssignedKeys().Count > 0 && MagicStorageExtra.IsItemKnownHotKey.JustPressed && Main.HoverItem != null && !Main.HoverItem.IsAir)
{
string s = Main.HoverItem.Name + " is ";
int t = Main.HoverItem.type;
if (GetKnownItems().Contains(t))
{
s += "known";
int sum = ModPlayer.LatestAccessedStorage?.GetStoredItems().Where(x => x.type == t).Select(x => x.stack).DefaultIfEmpty().Sum() ?? 0;
if (sum > 0)
s += $" ({sum} in l.a.s.)";
}
else
{
s += "new";
}
Main.NewTextMultiline(s);
}
}
catch (KeyNotFoundException)
{
// ignore
}
try
{
oldMouse = StorageGUI.oldMouse;
curMouse = StorageGUI.curMouse;
if (Main.playerInventory && Main.LocalPlayer.GetModPlayer<StoragePlayer>().ViewingStorage().X >= 0 && StoragePlayer.IsStorageCrafting())
{
if (curMouse.RightButton == ButtonState.Released)
ResetSlotFocus();
basePanel?.Update(gameTime);
recipePanel?.Update(gameTime);
UpdateRecipeText();
UpdateScrollBar();
UpdateCraftButton();
modSearchBox.Update(curMouse, oldMouse);
}
else
{
scrollBarFocus = 0;
craftTimer = 0;
maxCraftTimer = startMaxCraftTimer;
ResetSlotFocus();
}
}
catch (Exception e)
{
Main.NewTextMultiline(e.ToString());
}
}
public static void Draw(TEStorageHeart heart)
{
try
{
Player player = Main.LocalPlayer;
Initialize();
InitReflection();
if (Main.mouseX > panelLeft && Main.mouseX < recipeWidth + panelWidth + panelLeft && Main.mouseY > panelTop && Main.mouseY < panelTop + panelHeight)
{
Main.mouseText = true;
player.mouseInterface = true;
player.showItemIcon = false;
InterfaceHelper.HideItemIconCache();
}
basePanel.Draw(Main.spriteBatch);
recipePanel.Draw(Main.spriteBatch);
Vector2 pos = recipeZone.GetDimensions().Position();
if (threadRunning)
Utils.DrawBorderString(Main.spriteBatch, "Loading", pos + new Vector2(8f, 8f), Color.White);
stationZone.DrawText();
recipeZone.DrawText();
ingredientZone.DrawText();
recipeHeaderZone.DrawText();
storageZone.DrawText();
resultZone.DrawText();
sortButtons.DrawText();
recipeButtons.DrawText();
filterButtons.DrawText();
DrawCraftButton();
}
catch (Exception e)
{
Main.NewTextMultiline(e.ToString());
}
}
private static void DrawCraftButton()
{
Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton);
if (Main.netMode == NetmodeID.SinglePlayer && curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height && selectedRecipe != null && Main.mouseItem.IsAir && CanItemBeTakenForTest(selectedRecipe.createItem))
Main.instance.MouseText(Language.GetText("Mods.MagicStorageExtra.CraftTooltip").Value);
}
private static Item GetStation(int slot, ref int context)
{
Item[] stations = GetCraftingStations();
if (stations == null || slot >= stations.Length)
return new Item();
return stations[slot];
}
private static Item GetRecipe(int slot, ref int context)
{
if (threadRunning)
return new Item();
int index = slot + numColumns * (int) Math.Round(scrollBar.ViewPosition);
Item item = index < recipes.Count ? recipes[index].createItem : new Item();
if (!item.IsAir)
{
if (recipes[index] == selectedRecipe)
context = 6;
if (!recipeAvailable[index])
context = recipes[index] == selectedRecipe ? 4 : 3;
if (ModPlayer.FavoritedRecipes.Contains(item))
{
item = item.Clone();
item.favorited = true;
}
if (!ModPlayer.SeenRecipes.Contains(item))
{
item = item.Clone();
item.newAndShiny = MagicStorageConfig.GlowNewItems;
}
}
return item;
}
private static Item GetHeader(int slot, ref int context)
{
if (selectedRecipe == null)
return new Item();
Item item = selectedRecipe.createItem;
if (item.IsAir)
{
int t = item.type;
item = new Item();
item.SetDefaults(t);
item.stack = 0;
}
return item;
}
private static Item GetIngredient(int slot, ref int context)
{
if (selectedRecipe == null || slot >= selectedRecipe.requiredItem.Length)
return new Item();
Item item = selectedRecipe.requiredItem[slot].Clone();
if (selectedRecipe.anyWood && item.type == ItemID.Wood)
item.SetNameOverride(Language.GetText("LegacyMisc.37").Value + " " + Lang.GetItemNameValue(ItemID.Wood));
if (selectedRecipe.anySand && item.type == ItemID.SandBlock)
item.SetNameOverride(Language.GetText("LegacyMisc.37").Value + " " + Lang.GetItemNameValue(ItemID.SandBlock));
if (selectedRecipe.anyIronBar && item.type == ItemID.IronBar)
item.SetNameOverride(Language.GetText("LegacyMisc.37").Value + " " + Lang.GetItemNameValue(ItemID.IronBar));
if (selectedRecipe.anyFragment && item.type == ItemID.FragmentSolar)
item.SetNameOverride(Language.GetText("LegacyMisc.37").Value + " " + Language.GetText("LegacyMisc.51").Value);
if (selectedRecipe.anyPressurePlate && item.type == ItemID.GrayPressurePlate)
item.SetNameOverride(Language.GetText("LegacyMisc.37").Value + " " + Language.GetText("LegacyMisc.38").Value);
if (selectedRecipe.ProcessGroupsForText(item.type, out string nameOverride))
item.SetNameOverride(nameOverride);
Item storageItem;
int totalGroupStack = 0;
lock (storageItems)
{
storageItem = storageItems.FirstOrDefault(i => i.type == item.type) ?? new Item();
List<int> vanillaGroups = GetAcceptedVanillaGroups(selectedRecipe);
IEnumerable<int> allGroups = selectedRecipe.acceptedGroups;
if (vanillaGroups != null)
allGroups = allGroups.Union(vanillaGroups);
foreach (RecipeGroup rec in allGroups.Select(index => RecipeGroup.recipeGroups[index]))
if (rec.ValidItems.Contains(item.type))
foreach (int type in rec.ValidItems)
totalGroupStack += storageItems.Where(i => i.type == type).Sum(i => i.stack);
}
if (!item.IsAir)
{
if (storageItem.IsAir && totalGroupStack == 0)
context = 3; // Unavailable - Red
else if (storageItem.stack < item.stack && totalGroupStack < item.stack)
context = 4; // Partially in stock - Pinkish
// context == 0 - Available - Default Blue
if (context != 0)
{
bool craftable = _productToRecipes.ContainsKey(item.type) && _productToRecipes[item.type].Any(recipe => IsAvailable(recipe) && AmountCraftable(recipe) > 0);
if (craftable)
context = 6; // Craftable - Light green
}
}
return item;
}
// Calculates how many times a recipe can be crafted using available items
private static int AmountCraftable(Recipe recipe)
{
if (!IsAvailable(recipe))
return 0;
int maxCraftable = int.MaxValue;
if (RecursiveCraftIntegration.Enabled)
recipe = RecursiveCraftIntegration.ApplyThreadCompoundRecipe(recipe);
lock (items)
{
foreach (Item reqItem in recipe.requiredItem)
{
int total = 0;
if (reqItem.type == ItemID.None)
break;
foreach (Item invItem in items)
if (invItem.type == reqItem.type || RecipeGroupMatch(recipe, invItem.type, reqItem.type))
total += invItem.stack;
int craftable = total / reqItem.stack;
if (craftable < maxCraftable)
maxCraftable = craftable;
}
}
return maxCraftable;
}
private static Item GetStorage(int slot, ref int context)
{
int index = slot + numColumns2 * (int) Math.Round(scrollBar2.ViewPosition);
Item item = index < storageItems.Count ? storageItems[index] : new Item();
lock (blockStorageItems)
{
if (blockStorageItems.Contains(new ItemData(item)))
context = 3;
}
return item;
}
private static Item GetResult(int slot, ref int context) => slot == 0 && result != null ? result : new Item();
private static void UpdateRecipeText()
{
if (selectedRecipe == null)
{
reqObjText2.SetText("");
recipePanelHeader.SetText(Language.GetText("Mods.MagicStorageExtra.SelectedRecipe").Value);
}
else
{
bool isEmpty = true;
string text = "";
int rows = 0;
void AddText(string addText)
{
if ((text.Length + addText.Length) / 35 > rows)
{
text += "\n";
++rows;
}
text += addText;
}
foreach (int tile in selectedRecipe.requiredTile.TakeWhile(tile => tile != -1))
{
if (!isEmpty)
text += ", ";
AddText(Lang.GetMapObjectName(MapHelper.TileToLookup(tile, 0)));
isEmpty = false;
}
if (selectedRecipe.needWater)
{
if (!isEmpty)
text += ", ";
AddText(Language.GetTextValue("LegacyInterface.53"));
isEmpty = false;
}
if (selectedRecipe.needHoney)
{
if (!isEmpty)
text += ", ";
AddText(Language.GetTextValue("LegacyInterface.58"));
isEmpty = false;
}
if (selectedRecipe.needLava)
{
if (!isEmpty)
text += ", ";
AddText(Language.GetTextValue("LegacyInterface.56"));
isEmpty = false;
}
if (selectedRecipe.needSnowBiome)
{
if (!isEmpty)
text += ", ";
AddText(Language.GetTextValue("LegacyInterface.123"));
isEmpty = false;
}
if (isEmpty)
text = Language.GetTextValue("LegacyInterface.23");
reqObjText2.SetText(text);
Item item = selectedRecipe.createItem;
double dps = CompareDps.GetDps(item);
if (dps >= 1d)
recipePanelHeader.SetText("DPS = " + dps.ToString("F"));
else
recipePanelHeader.SetText("");
}
}
private static void UpdateScrollBar()
{
if (slotFocus)
{
scrollBarFocus = 0;
return;
}
Rectangle dim = scrollBar.GetClippingRectangle(Main.spriteBatch);
var boxPos = new Vector2(dim.X, dim.Y + dim.Height * (scrollBar.ViewPosition / scrollBarMaxViewSize));
float boxWidth = 20f * Main.UIScale;
float boxHeight = dim.Height * (scrollBarViewSize / scrollBarMaxViewSize);
Rectangle dim2 = scrollBar2.GetClippingRectangle(Main.spriteBatch);
var box2Pos = new Vector2(dim2.X, dim2.Y + dim2.Height * (scrollBar2.ViewPosition / scrollBar2MaxViewSize));
float box2Height = dim2.Height * (scrollBar2ViewSize / scrollBar2MaxViewSize);
if (scrollBarFocus > 0)
{
if (curMouse.LeftButton == ButtonState.Released)
{
scrollBarFocus = 0;
}
else
{
int difference = curMouse.Y - scrollBarFocusMouseStart;
switch (scrollBarFocus)
{
case 1:
scrollBar.ViewPosition = scrollBarFocusPositionStart + difference / boxHeight;
break;
case 2:
scrollBar2.ViewPosition = scrollBarFocusPositionStart + difference / box2Height;
break;
}
}
}
else if (MouseClicked)
{
if (curMouse.X > boxPos.X && curMouse.X < boxPos.X + boxWidth && curMouse.Y > boxPos.Y - 3f && curMouse.Y < boxPos.Y + boxHeight + 4f)
{
scrollBarFocus = 1;
scrollBarFocusMouseStart = curMouse.Y;
scrollBarFocusPositionStart = scrollBar.ViewPosition;
}
else if (curMouse.X > box2Pos.X && curMouse.X < box2Pos.X + boxWidth && curMouse.Y > box2Pos.Y - 3f && curMouse.Y < box2Pos.Y + box2Height + 4f)
{
scrollBarFocus = 2;
scrollBarFocusMouseStart = curMouse.Y;
scrollBarFocusPositionStart = scrollBar2.ViewPosition;
}
}
if (scrollBarFocus == 0)
{
int difference = oldMouse.ScrollWheelValue / 250 - curMouse.ScrollWheelValue / 250;
scrollBar.ViewPosition += difference;
}
}
private static void UpdateCraftButton()
{
Rectangle dim = InterfaceHelper.GetFullRectangle(craftButton);
bool flag = false;
if (curMouse.X > dim.X && curMouse.X < dim.X + dim.Width && curMouse.Y > dim.Y && curMouse.Y < dim.Y + dim.Height)
{
craftButton.BackgroundColor = new Color(73, 94, 171);
if (RightMouseClicked && selectedRecipe != null && Main.mouseItem.IsAir)
{
Item item = selectedRecipe.createItem;
if (CanItemBeTakenForTest(item))
{
int type = item.type;
var testItem = new Item();
testItem.SetDefaults(type, true);
MarkAsTestItem(testItem);
Main.mouseItem = testItem;
ModPlayer.TestedRecipes.Add(selectedRecipe.createItem);
}
}
else if (curMouse.LeftButton == ButtonState.Pressed && selectedRecipe != null && IsAvailable(selectedRecipe, false) && PassesBlock(selectedRecipe))
{
if (craftTimer <= 0)
{
craftTimer = maxCraftTimer;
maxCraftTimer = maxCraftTimer * 3 / 4;
if (maxCraftTimer <= 0)
maxCraftTimer = 1;
TryCraft();
if (RecursiveCraftIntegration.Enabled)
if (RecursiveCraftIntegration.UpdateRecipe(selectedRecipe))
SetSelectedRecipe(selectedRecipe);
RefreshItems();
Main.PlaySound(SoundID.Grab);
}
craftTimer--;
flag = true;
if (ModPlayer.AddToCraftedRecipes(selectedRecipe.createItem))
RefreshItems();
}
}
else
{
craftButton.BackgroundColor = new Color(63, 82, 151) * 0.7f;
}
if (selectedRecipe == null || !IsAvailable(selectedRecipe, false) || !PassesBlock(selectedRecipe))
craftButton.BackgroundColor = new Color(30, 40, 100) * 0.7f;
if (!flag)
{
craftTimer = 0;
maxCraftTimer = startMaxCraftTimer;
}
}
private static bool CanItemBeTakenForTest(Item item) =>
Main.netMode == NetmodeID.SinglePlayer && !item.consumable && (item.mana > 0 || item.magic || item.ranged || item.thrown || item.melee || item.headSlot >= 0 || item.bodySlot >= 0 || item.legSlot >= 0 || item.accessory || Main.projHook[item.shoot] || item.pick > 0 || item.axe > 0 || item.hammer > 0) && !item.summon && item.createTile < TileID.Dirt && item.createWall < 0 && !item.potion && item.fishingPole <= 1 && item.ammo == AmmoID.None && !ModPlayer.TestedRecipes.Contains(item);
public static void MarkAsTestItem(Item testItem)
{
testItem.value = 0;
testItem.shopCustomPrice = 0;
testItem.material = false;
testItem.rare = -11;
testItem.SetNameOverride(Lang.GetItemNameValue(testItem.type) + Language.GetTextValue("Mods.MagicStorageExtra.TestItemSuffix"));
}
public static bool IsTestItem(Item item) => item.Name.EndsWith(Language.GetTextValue("Mods.MagicStorageExtra.TestItemSuffix"));
private static TEStorageHeart GetHeart() => ModPlayer.GetStorageHeart();
private static TECraftingAccess GetCraftingEntity() => ModPlayer.GetCraftingAccess();
private static Item[] GetCraftingStations()
{
TECraftingAccess ent = GetCraftingEntity();
return ent?.stations;
}
public static void RefreshItems()
{
StoragePlayer modPlayer = ModPlayer;
if (modPlayer.SeenRecipes.Count == 0)
foreach (int item in GetKnownItems())
modPlayer.SeenRecipes.Add(item);
lock (items)
{
items.Clear();
TEStorageHeart heart = GetHeart();
if (heart == null)
return;
items.AddRange(ItemSorter.SortAndFilter(heart.GetStoredItems(), SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, ""));
}
AnalyzeIngredients();
InitLangStuff();
InitSortButtons();
InitRecipeButtons();
InitFilterButtons();
var sortMode = (SortMode) sortButtons.Choice;
var filterMode = (FilterMode) filterButtons.Choice;
RefreshStorageItems();
GetKnownItems(out HashSet<int> foundItems, out HashSet<int> hiddenRecipes, out HashSet<int> craftedRecipes, out HashSet<int> asKnownRecipes);
foundItems.UnionWith(asKnownRecipes);
var favoritesCopy = new HashSet<int>(modPlayer.FavoritedRecipes.Items.Select(x => x.type));
EnsureProductToRecipesInited();
lock (threadLock)
{
threadNeedsRestart = true;
threadSortMode = sortMode;
threadFilterMode = filterMode;
threadCheckListFoundItems = foundItems;
if (!threadRunning)
{
threadRunning = true;
Task.Run(() => RefreshRecipes(hiddenRecipes, craftedRecipes, favoritesCopy));
}
}
}
public static HashSet<int> GetKnownItems()
{
GetKnownItems(out HashSet<int> a, out HashSet<int> b, out HashSet<int> c, out HashSet<int> d);
a.UnionWith(b);
a.UnionWith(c);
a.UnionWith(d);
return a;
}
private static void GetKnownItems(out HashSet<int> foundItems, out HashSet<int> hiddenRecipes, out HashSet<int> craftedRecipes, out HashSet<int> asKnownRecipes)
{
foundItems = new HashSet<int>(RetrieveFoundItemsCheckList());
StoragePlayer modPlayer = ModPlayer;
hiddenRecipes = new HashSet<int>(modPlayer.HiddenRecipes.Select(x => x.type));
craftedRecipes = new HashSet<int>(modPlayer.CraftedRecipes.Select(x => x.type));
asKnownRecipes = new HashSet<int>(modPlayer.AsKnownRecipes.Items.Select(x => x.type));
}
private static IEnumerable<int> RetrieveFoundItemsCheckList()
{
Mod itemChecklist = MagicStorageExtra.ItemChecklist;
if (itemChecklist is null || !(itemChecklist.Call("RequestFoundItems") is bool[] foundItems))
return Enumerable.Empty<int>();
if (foundItems.Length > 0)
wasItemChecklistRetrieved = true;
return foundItems.Select((found, type) => (found, type)).Where(x => x.found).Select(x => x.type);
}
private static void EnsureProductToRecipesInited()
{
if (!(_productToRecipes is null))
return;
IEnumerable<Recipe> allRecipes = ItemSorter.GetRecipes(SortMode.Id, FilterMode.All, ModSearchBox.ModIndexAll, "")
.Where(r => r?.createItem != null && r.createItem.type > ItemID.None);
_productToRecipes = allRecipes.GroupBy(r => r.createItem.type).ToDictionary(x => x.Key, x => x.ToArray());
}
/// <summary>
/// Checks all crafting tree until it finds already available ingredients
/// </summary>
private static bool IsKnownRecursively(Recipe recipe, HashSet<int> availableSet, HashSet<int> recursionTree, Dictionary<Recipe, bool> cache)
{
if (cache.TryGetValue(recipe, out bool v))
return v;
foreach (int tile in recipe.requiredTile.TakeWhile(tile => tile != -1))
{
if (!StorageWorld.TileToCreatingItem.TryGetValue(tile, out List<int> possibleItems))
continue;
if (!possibleItems.Any(x => IsKnownRecursively_CheckIngredient(x, availableSet, recursionTree, cache)))
{
cache[recipe] = false;
return false;
}
}
int ingredients = 0;
foreach (int t in recipe.requiredItem.Select(item => item.type).Where(t => t > 0))
{
ingredients++;
if (IsKnownRecursively_CheckIngredient(t, availableSet, recursionTree, cache))
continue;
if (IsKnownRecursively_CheckAcceptedGroupsForIngredient(recipe, availableSet, recursionTree, cache, t))
continue;
cache[recipe] = false;
return false;
}
if (ingredients > 0)