forked from blushiemagic/MagicStorage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStorageGUI.cs
More file actions
588 lines (463 loc) · 17 KB
/
StorageGUI.cs
File metadata and controls
588 lines (463 loc) · 17 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using MagicStorage.Common.Systems;
using MagicStorage.Components;
using MagicStorage.CrossMod;
using MagicStorage.Sorting;
using MagicStorage.UI;
using MagicStorage.UI.States;
using Microsoft.Xna.Framework.Input;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.ModLoader.Default;
using Terraria.ModLoader.IO;
namespace MagicStorage
{
public static class StorageGUI
{
public const int padding = 4;
public const int numColumns = 10;
public const float inventoryScale = 0.85f;
public const int startMaxRightClickTimer = 20;
public static MouseState curMouse;
public static MouseState oldMouse;
internal static int slotFocus = -1;
private static int rightClickTimer;
private static int maxRightClickTimer = startMaxRightClickTimer;
internal static readonly float scrollBarViewSize = 1f;
internal static float scrollBarMaxViewSize = 2f;
internal static readonly List<Item> items = new();
internal static readonly List<List<Item>> sourceItems = new();
internal static readonly List<bool> didMatCheck = new();
//Legacy properties required for UISearchBar to function properly
public static bool MouseClicked => curMouse.LeftButton == ButtonState.Pressed && oldMouse.LeftButton == ButtonState.Released;
public static bool RightMouseClicked => curMouse.RightButton == ButtonState.Pressed && oldMouse.RightButton == ButtonState.Released;
internal static void Unload() {
showcaseItems = null;
}
public static TEStorageHeart GetHeart() => StoragePlayer.LocalPlayer.GetStorageHeart();
public static bool needRefresh;
public static event Action OnRefresh;
internal static void CheckRefresh() {
if (needRefresh)
RefreshItems();
}
internal static void InvokeOnRefresh() => OnRefresh?.Invoke();
public static void RefreshItems()
{
if (StoragePlayer.IsStorageCrafting())
{
CraftingGUI.RefreshItems();
return;
}
if (StoragePlayer.IsStorageEnvironment())
return;
items.Clear();
didMatCheck.Clear();
sourceItems.Clear();
TEStorageHeart heart = GetHeart();
if (heart == null)
return;
NetHelper.Report(true, "Refreshing storage items");
int sortMode = MagicUI.storageUI.GetPage<SortingPage>("Sorting").option;
int filterMode = MagicUI.storageUI.GetPage<FilteringPage>("Filtering").option;
var storagePage = MagicUI.storageUI.GetPage<StorageUIState.StoragePage>("Storage");
string searchText = storagePage.searchBar.Text;
bool onlyFavorites = storagePage.filterFavorites.Value;
int modSearch = storagePage.modSearchBox.ModIndex;
void DoFiltering()
{
ItemSorter.AggregateContext context;
if (filterMode == FilteringOptionLoader.Definitions.Recent.Type)
{
Dictionary<int, Item> stored = heart.GetStoredItems().GroupBy(x => x.type).ToDictionary(x => x.Key, x => x.First());
IEnumerable<Item> toFilter = heart.UniqueItemsPutHistory.Reverse().Where(x => stored.ContainsKey(x.type)).Select(x => stored[x.type]);
context = new(toFilter);
context.items = ItemSorter.SortAndFilter(context, sortMode == SortingOptionLoader.Definitions.Default.Type ? -1 : sortMode, FilteringOptionLoader.Definitions.All.Type, searchText, modSearch, 100);
}
else
{
context = new(heart.GetStoredItems());
context.items = ItemSorter.SortAndFilter(context, sortMode, filterMode, searchText, modSearch);
}
if (MagicStorageConfig.CraftingFavoritingEnabled) {
context.items = context.items.OrderByDescending(x => x.favorited ? 1 : 0);
context.sourceItems = context.sourceItems.OrderByDescending(x => x[0].favorited ? 1 : 0);
}
items.AddRange(context.items.Where(x => !MagicStorageConfig.CraftingFavoritingEnabled || !onlyFavorites || x.favorited));
sourceItems.AddRange(context.sourceItems.Where(x => !MagicStorageConfig.CraftingFavoritingEnabled || !onlyFavorites || x[0].favorited));
NetHelper.Report(false, "Filtering applied. Item count: " + items.Count);
}
DoFiltering();
bool didDefault = false;
// now if nothing found we disable filters one by one
if (searchText.Trim().Length > 0)
{
if (items.Count == 0 && filterMode != FilteringOptionLoader.Definitions.All.Type)
{
// search all categories
filterMode = FilteringOptionLoader.Definitions.All.Type;
MagicUI.lastKnownSearchBarErrorReason = Language.GetTextValue("Mods.MagicStorage.Warnings.StorageDefaultToAllItems");
didDefault = true;
DoFiltering();
}
if (items.Count == 0 && modSearch != ModSearchBox.ModIndexAll)
{
// search all mods
modSearch = ModSearchBox.ModIndexAll;
MagicUI.lastKnownSearchBarErrorReason = Language.GetTextValue("Mods.MagicStorage.Warnings.StorageDefaultToAllMods");
didDefault = true;
DoFiltering();
}
}
if (!didDefault)
MagicUI.lastKnownSearchBarErrorReason = null;
for (int k = 0; k < items.Count; k++)
didMatCheck.Add(false);
OnRefresh?.Invoke();
needRefresh = false;
}
internal static void ResetSlotFocus()
{
slotFocus = -1;
rightClickTimer = 0;
maxRightClickTimer = startMaxRightClickTimer;
}
internal static void SlotFocusLogic()
{
if (slotFocus >= items.Count ||
!Main.mouseItem.IsAir && (!ItemCombining.CanCombineItems(Main.mouseItem, items[slotFocus]) || Main.mouseItem.stack >= Main.mouseItem.maxStack))
{
ResetSlotFocus();
}
else
{
if (rightClickTimer <= 0)
{
rightClickTimer = maxRightClickTimer;
maxRightClickTimer = maxRightClickTimer * 3 / 4;
if (maxRightClickTimer <= 0)
maxRightClickTimer = 1;
Item toWithdraw = items[slotFocus].Clone();
toWithdraw.stack = 1;
Item result = DoWithdraw(toWithdraw);
if (Main.mouseItem.IsAir)
Main.mouseItem = result;
else {
Utility.CallOnStackHooks(Main.mouseItem, result, result.stack);
Main.mouseItem.stack += result.stack;
}
needRefresh = true;
SoundEngine.PlaySound(SoundID.MenuTick);
}
rightClickTimer--;
}
}
internal static List<Item> showcaseItems;
internal static void DepositShowcaseItemsToCurrentStorage() {
if (GetHeart() is not TEStorageHeart heart || heart.GetStoredItems().Any())
return;
if (showcaseItems is not null)
goto DepositTheItems;
showcaseItems = new();
HashSet<int> addedTypes = new();
void MakeItemsForUnloadedDataShowcase(int type, int stack) {
showcaseItems.Add(new Item(type, stack));
Item item = new(type, stack);
AddRandomUnloadedItemDataToItem(item);
showcaseItems.Add(item);
addedTypes.Add(type);
}
void MakeItemsForSellingShowcase(int type) {
HashSet<int> rolledPrefixes = new();
int tries = 200;
for (int i = 0; i < 5; i++) {
Item item = new(type);
item.Prefix(-1);
if (!rolledPrefixes.Add(item.prefix)) {
i--;
tries--;
if (tries <= 0)
break;
}
showcaseItems.Add(item);
tries = 200;
}
addedTypes.Add(type);
}
void MakeCoinsForStackingShowcase() {
void MakeCoins(int type, int total) {
while (total > 0) {
showcaseItems.Add(new Item(type, Math.Min(100, total)));
total -= 100;
}
addedTypes.Add(type);
}
MakeCoins(ItemID.CopperCoin, 135);
MakeCoins(ItemID.SilverCoin, 215);
MakeCoins(ItemID.GoldCoin, 180);
MakeCoins(ItemID.PlatinumCoin, 60);
}
bool MakeRandomItem(ref int i, Func<Item, bool> condition, Action onValidItemFail = null) {
int type = Main.rand.Next(0, ItemLoader.ItemCount);
Item item = new(type);
if (item.IsAir) {
i--;
return false;
}
item.stack = Main.rand.Next(1, item.maxStack + 1);
if (!condition(item)) {
onValidItemFail?.Invoke();
i--;
return false;
}
if (!addedTypes.Add(type)) {
i--;
return false;
}
showcaseItems.Add(item);
return true;
}
void MakeItem(int type) {
if (addedTypes.Add(type)) {
Item item = new(type);
item.stack = item.maxStack;
showcaseItems.Add(item);
}
}
void MakeResearchedItems(bool researched) {
bool CheckIsValidResearchableItemForShowcase(Item item) {
if (item.dye > 0 || item.maxStack == 1)
return false;
return researched != Utility.IsFullyResearched(item.type, true);
}
int tries = 1000;
for (int i = 0; i < 10; i++) {
if (MakeRandomItem(ref i, CheckIsValidResearchableItemForShowcase, () => tries--))
tries = 1000;
else if (tries <= 0)
return;
}
}
void MakeIngredientItems() {
bool CheckIsValidMaterialAndMaximizeStack(Item item) {
if (item.maxStack == 1 || !item.material || item.type == ItemID.DirtBlock || item.createTile >= TileID.Dirt || item.dye > 0 || item.createWall > WallID.None)
return false;
item.stack = item.maxStack;
return true;
}
for (int i = 0; i < 50; i++)
MakeRandomItem(ref i, CheckIsValidMaterialAndMaximizeStack);
MakeItem(ItemID.Wood);
MakeItem(ItemID.StoneBlock);
MakeItem(ItemID.Torch);
MakeItem(ItemID.ClayBlock);
MakeItem(ItemID.SandBlock);
MakeItem(ItemID.Glass);
MakeItem(ItemID.Cobweb);
}
MakeItemsForUnloadedDataShowcase(ItemID.WoodenSword, 1);
MakeItemsForUnloadedDataShowcase(ItemID.CopperHelmet, 1);
MakeItemsForUnloadedDataShowcase(ItemID.FlamingArrow, 100);
MakeItemsForSellingShowcase(ItemID.Megashark);
MakeItemsForSellingShowcase(ItemID.LightningBoots);
MakeCoinsForStackingShowcase();
MakeResearchedItems(true);
MakeResearchedItems(false);
MakeIngredientItems();
Main.NewText("Showcase initialized. Item count: " + showcaseItems.Count);
DepositTheItems:
heart.TryDeposit(showcaseItems.Select(i => i.Clone()).ToList());
needRefresh = true;
}
internal static readonly FieldInfo UnloadedGlobalItem_data = typeof(UnloadedGlobalItem).GetField("data", BindingFlags.NonPublic | BindingFlags.Instance);
private static void AddRandomUnloadedItemDataToItem(Item item) {
if (item is null || item.IsAir || item.ModItem is UnloadedItem)
return;
if (TEStorageHeart.Item_globalItems.GetValue(item) is not Instanced<GlobalItem>[] globalItems || globalItems.Length == 0)
return;
//Create the data
TagCompound modData = new() {
["mod"] = "MagicStorage",
["name"] = "ShowcaseItemData",
["data"] = new TagCompound() {
["randomData"] = Main.rand.Next()
}
};
if (item.TryGetGlobalItem(out UnloadedGlobalItem obj))
(UnloadedGlobalItem_data.GetValue(obj) as IList<TagCompound>).Add(modData);
else {
Instanced<GlobalItem>[] array = (Instanced<GlobalItem>[])globalItems.Clone();
int index = array.Length;
Array.Resize(ref array, array.Length + 1);
//Create the instance
obj = new();
UnloadedGlobalItem_data.SetValue(obj, new List<TagCompound>() { modData });
array[^1] = new((ushort)index, obj);
TEStorageHeart.Item_globalItems.SetValue(item, array);
}
}
internal static void FavoriteItem(int slot) {
if (slot < 0 || slot >= items.Count)
return;
//Favorite all of the source items
bool doFavorite = !sourceItems[slot][0].favorited;
foreach (var item in sourceItems[slot])
item.favorited = doFavorite;
needRefresh = true;
}
/// <summary>
/// Simulates a deposit attempt into a storage center (Storage Heart, Storage Access, etc.).
/// </summary>
/// <param name="center">The tile entity used to attempt to retrieve a Storage Heart</param>
/// <param name="item">The item to deposit</param>
/// <returns>Whether the deposit was successful</returns>
public static bool TryDespoit(TEStorageCenter center, Item item) {
if (center is null)
return false;
StoragePlayer.StorageHeartAccessWrapper wrapper = new(center);
if (wrapper.Valid) {
int oldStack = item.stack;
TEStorageHeart heart = wrapper.Heart;
heart.TryDeposit(item);
return oldStack != item.stack;
}
return false;
}
/// <summary>
/// Simulates a deposit attempt into the currently assigned Storage Heart.
/// </summary>
/// <param name="item">The item to deposit</param>
/// <returns>Whether the deposit was successful</returns>
public static bool TryDeposit(Item item)
{
int oldStack = item.stack;
TEStorageHeart heart = GetHeart();
heart.TryDeposit(item);
return oldStack != item.stack;
}
/// <summary>
/// Simulates a deposit attempt into a storage center (Storage Heart, Storage Access, etc.).
/// </summary>
/// <param name="center">The tile entity used to attempt to retrieve a Storage Heart</param>
/// <param name="items">The items to deposit</param>
/// <returns>Whether the deposit was successful</returns>
public static bool TryDeposit(TEStorageCenter center, List<Item> items)
{
if (center is null)
return false;
StoragePlayer.StorageHeartAccessWrapper wrapper = new(center);
if (wrapper.Valid) {
TEStorageHeart heart = wrapper.Heart;
return heart.TryDeposit(items);
}
return false;
}
/// <summary>
/// Simulates a deposit attempt into a storage center (Storage Heart, Storage Access, etc.).
/// </summary>
/// <param name="center">The tile entity used to attempt to retrieve a Storage Heart</param>
/// <param name="items">The items to deposit</param>
/// <param name="quickStack">Whether the operation is a quick stack</param>
/// <returns>Whether the deposit was successful</returns>
public static bool TryDeposit(TEStorageCenter center, List<Item> items, bool quickStack = false)
{
if (center is null)
return false;
StoragePlayer.StorageHeartAccessWrapper wrapper = new(center);
if (wrapper.Valid) {
TEStorageHeart heart = wrapper.Heart;
if (quickStack)
items = new(items.Where(i => heart.HasItem(i, ignorePrefix: true)));
return heart.TryDeposit(items);
}
return false;
}
/// <summary>
/// Simulates a deposit attempt into the currently assigned Storage Heart.
/// </summary>
/// <param name="items">The items to deposit</param>
/// <returns>Whether the deposit was successful</returns>
public static bool TryDeposit(List<Item> items)
{
TEStorageHeart heart = GetHeart();
return heart.TryDeposit(items);
}
internal static bool TryDepositAll(bool quickStack)
{
Player player = Main.LocalPlayer;
TEStorageHeart heart = GetHeart();
bool filter(Item item) => !item.IsAir && !item.favorited && (!quickStack || heart.HasItem(item, true));
var items = new List<Item>();
for (int k = 10; k < 50; k++)
{
Item item = player.inventory[k];
if (filter(item))
items.Add(item);
}
return heart.TryDeposit(items);
}
internal static bool TryRestock()
{
Player player = Main.LocalPlayer;
GetHeart();
bool changed = false;
foreach (Item item in player.inventory)
if (item is not null && !item.IsAir && item.stack < item.maxStack)
{
Item toWithdraw = item.Clone();
toWithdraw.stack = item.maxStack - item.stack;
toWithdraw = DoWithdraw(toWithdraw, true, true);
if (!toWithdraw.IsAir)
{
item.stack += toWithdraw.stack;
toWithdraw.TurnToAir();
changed = true;
}
}
return changed;
}
/// <summary>
/// Attempts to withdraw an item from a storage center (Storage Heart, Storage Access, etc.).
/// </summary>
/// <param name="center">The tile entity used to attempt to retrieve a Storage Heart</param>
/// <param name="item">The item to withdraw</param>
/// <param name="toInventory">
/// Whether the item goes into the player inventory.
/// This parameter is only used if <see cref="Main.netMode"/> is <see cref="NetmodeID.MultiplayerClient"/>
/// </param>
/// <param name="keepOneIfFavorite">Whether at least one item should remain in the storage if it's favourited</param>
/// <returns>A valid item instance if the withdrawal was succesful, an air item otherwise.</returns>
public static Item DoWithdraw(TEStorageCenter center, Item item, bool toInventory = false, bool keepOneIfFavorite = false)
{
if (center is null)
return new Item();
StoragePlayer.StorageHeartAccessWrapper wrapper = new(center);
if (wrapper.Valid) {
TEStorageHeart heart = wrapper.Heart;
return heart.TryWithdraw(item, keepOneIfFavorite, toInventory);
}
return new Item();
}
/// <summary>
/// Attempts to withdraw an item from the currently assigned Storage Heart.
/// </summary>
/// <param name="item">The item to withdraw</param>
/// <param name="toInventory">
/// Whether the item goes into the player inventory.
/// This parameter is only used if <see cref="Main.netMode"/> is <see cref="NetmodeID.MultiplayerClient"/>
/// </param>
/// <param name="keepOneIfFavorite">Whether at least one item should remain in the storage if it's favourited</param>
/// <returns>A valid item instance if the withdrawal was succesful, an air item otherwise.</returns>
public static Item DoWithdraw(Item item, bool toInventory = false, bool keepOneIfFavorite = false)
{
TEStorageHeart heart = GetHeart();
return heart.TryWithdraw(item, keepOneIfFavorite, toInventory);
}
}
}