-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
StorageContainerMenuBase.java
1503 lines (1325 loc) · 54.9 KB
/
StorageContainerMenuBase.java
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
package net.p3pp3rf1y.sophisticatedcore.common.gui;
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
import com.mojang.datafixers.util.Pair;
import it.unimi.dsi.fastutil.ints.IntComparators;
import net.minecraft.core.BlockPos;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.Container;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.ClickAction;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.inventory.ContainerListener;
import net.minecraft.world.inventory.ContainerSynchronizer;
import net.minecraft.world.inventory.InventoryMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.ResultSlot;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.fml.util.ObfuscationReflectionHelper;
import net.minecraftforge.items.SlotItemHandler;
import net.p3pp3rf1y.sophisticatedcore.SophisticatedCore;
import net.p3pp3rf1y.sophisticatedcore.api.IStorageWrapper;
import net.p3pp3rf1y.sophisticatedcore.client.gui.utils.TranslationHelper;
import net.p3pp3rf1y.sophisticatedcore.inventory.InventoryHandler;
import net.p3pp3rf1y.sophisticatedcore.network.SyncContainerClientDataMessage;
import net.p3pp3rf1y.sophisticatedcore.settings.ISlotColorCategory;
import net.p3pp3rf1y.sophisticatedcore.settings.SettingsHandler;
import net.p3pp3rf1y.sophisticatedcore.settings.SettingsManager;
import net.p3pp3rf1y.sophisticatedcore.settings.main.MainSettingsCategory;
import net.p3pp3rf1y.sophisticatedcore.settings.memory.MemorySettingsCategory;
import net.p3pp3rf1y.sophisticatedcore.settings.nosort.NoSortSettingsCategory;
import net.p3pp3rf1y.sophisticatedcore.upgrades.IOverflowResponseUpgrade;
import net.p3pp3rf1y.sophisticatedcore.upgrades.IUpgradeItem;
import net.p3pp3rf1y.sophisticatedcore.upgrades.IUpgradeWrapper;
import net.p3pp3rf1y.sophisticatedcore.upgrades.UpgradeHandler;
import net.p3pp3rf1y.sophisticatedcore.util.NoopStorageWrapper;
import javax.annotation.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
public abstract class StorageContainerMenuBase<S extends IStorageWrapper> extends AbstractContainerMenu {
public static final int NUMBER_OF_PLAYER_SLOTS = 36;
public static final ResourceLocation EMPTY_UPGRADE_SLOT_BACKGROUND = new ResourceLocation(SophisticatedCore.MOD_ID, "item/empty_upgrade_slot");
protected static final String UPGRADE_ENABLED_TAG = "upgradeEnabled";
protected static final String UPGRADE_SLOT_TAG = "upgradeSlot";
protected static final String ACTION_TAG = "action";
protected static final String OPEN_TAB_ID_TAG = "openTabId";
protected static final String SORT_BY_TAG = "sortBy";
private static final Method ON_SWAP_CRAFT = ObfuscationReflectionHelper.findMethod(Slot.class, "m_6405_", int.class);
public final NonNullList<ItemStack> lastUpgradeSlots = NonNullList.create();
public final List<Slot> upgradeSlots = Lists.newArrayList();
public final NonNullList<ItemStack> remoteUpgradeSlots = NonNullList.create();
public final NonNullList<ItemStack> lastRealSlots = NonNullList.create();
public final List<Slot> realInventorySlots = Lists.newArrayList();
private final Map<Integer, UpgradeContainerBase<?, ?>> upgradeContainers = new LinkedHashMap<>();
private final NonNullList<ItemStack> remoteRealSlots = NonNullList.create();
protected final Player player;
protected final S storageWrapper;
protected final IStorageWrapper parentStorageWrapper;
private final Map<Integer, ItemStack> slotStacksToUpdate = new HashMap<>();
private final int storageItemSlotIndex;
private final boolean shouldLockStorageItemSlot;
private int storageItemSlotNumber = -1;
private Consumer<StorageContainerMenuBase<?>> upgradeChangeListener = null;
private boolean isUpdatingFromPacket = false;
private long errorResultExpirationTime = 0;
@Nullable
private UpgradeSlotChangeResult errorUpgradeSlotChangeResult;
private CompoundTag lastSettingsNbt = null;
protected StorageContainerMenuBase(MenuType<?> pMenuType, int pContainerId, Player player, S storageWrapper, IStorageWrapper parentStorageWrapper, int storageItemSlotIndex, boolean shouldLockStorageItemSlot) {
super(pMenuType, pContainerId);
this.player = player;
this.storageWrapper = storageWrapper;
this.parentStorageWrapper = parentStorageWrapper;
this.storageItemSlotIndex = storageItemSlotIndex;
this.shouldLockStorageItemSlot = shouldLockStorageItemSlot;
removeOpenTabIfKeepOff();
storageWrapper.fillWithLoot(player);
initSlotsAndContainers(player, storageItemSlotIndex, shouldLockStorageItemSlot);
}
public abstract Optional<BlockPos> getBlockPosition();
protected void initSlotsAndContainers(Player player, int storageItemSlotIndex, boolean shouldLockStorageItemSlot) {
addStorageInventorySlots();
addPlayerInventorySlots(player.getInventory(), storageItemSlotIndex, shouldLockStorageItemSlot);
addUpgradeSlots();
addUpgradeSettingsContainers(player);
}
public S getStorageWrapper() {
return storageWrapper;
}
protected void addUpgradeSettingsContainers(Player player) {
UpgradeHandler upgradeHandler = storageWrapper.getUpgradeHandler();
upgradeHandler.getSlotWrappers().forEach((slot, wrapper) -> UpgradeContainerRegistry.instantiateContainer(player, slot, wrapper)
.ifPresent(container -> upgradeContainers.put(slot, container)));
for (UpgradeContainerBase<?, ?> container : upgradeContainers.values()) {
container.getSlots().forEach(this::addUpgradeSlot);
container.onInit();
}
storageWrapper.getOpenTabId().ifPresent(id -> {
if (upgradeContainers.containsKey(id)) {
upgradeContainers.get(id).setIsOpen(true);
}
});
}
private void addUpgradeSlots() {
UpgradeHandler upgradeHandler = storageWrapper.getUpgradeHandler();
int numberOfSlots = upgradeHandler.getSlots();
if (numberOfSlots == 0) {
return;
}
int slotIndex = 0;
while (slotIndex < upgradeHandler.getSlots()) {
addUpgradeSlot(instantiateUpgradeSlot(upgradeHandler, slotIndex));
slotIndex++;
}
}
public int getColumnsTaken() {
return storageWrapper.getColumnsTaken();
}
public Optional<UpgradeSlotChangeResult> getErrorUpgradeSlotChangeResult() {
if (errorUpgradeSlotChangeResult != null && player.level.getGameTime() >= errorResultExpirationTime) {
errorResultExpirationTime = 0;
errorUpgradeSlotChangeResult = null;
}
return Optional.ofNullable(errorUpgradeSlotChangeResult);
}
protected void sendStorageSettingsToClient() {
//noop by default
}
protected abstract StorageUpgradeSlot instantiateUpgradeSlot(UpgradeHandler upgradeHandler, int slotIndex);
protected void addUpgradeSlot(Slot slot) {
slot.index = getTotalSlotsNumber();
upgradeSlots.add(slot);
lastUpgradeSlots.add(ItemStack.EMPTY);
remoteUpgradeSlots.add(ItemStack.EMPTY);
}
protected void addNoSortSlot(Slot slot) {
slot.index = getInventorySlotsSize();
realInventorySlots.add(slot);
lastRealSlots.add(ItemStack.EMPTY);
remoteRealSlots.add(ItemStack.EMPTY);
}
@Override
protected Slot addSlot(Slot slot) {
slot.index = getInventorySlotsSize();
slots.add(slot);
lastSlots.add(ItemStack.EMPTY);
remoteSlots.add(ItemStack.EMPTY);
realInventorySlots.add(slot);
lastRealSlots.add(ItemStack.EMPTY);
remoteRealSlots.add(ItemStack.EMPTY);
return slot;
}
public int getInventorySlotsSize() {
return realInventorySlots.size();
}
public int getNumberOfStorageInventorySlots() {
return storageWrapper.getInventoryHandler().getSlots();
}
public int getNumberOfUpgradeSlots() {
return storageWrapper.getUpgradeHandler().getSlots();
}
public Map<Integer, UpgradeContainerBase<?, ?>> getUpgradeContainers() {
return upgradeContainers;
}
protected void addStorageInventorySlots() {
InventoryHandler inventoryHandler = storageWrapper.getInventoryHandler();
int slotIndex = 0;
Set<Integer> noSortSlotIndexes = getNoSortSlotIndexes();
while (slotIndex < inventoryHandler.getSlots()) {
int finalSlotIndex = slotIndex;
StorageInventorySlot slot = new StorageInventorySlot(player.level.isClientSide, storageWrapper, inventoryHandler, finalSlotIndex);
if (noSortSlotIndexes.contains(slotIndex)) {
addNoSortSlot(slot);
} else {
addSlot(slot);
}
slotIndex++;
}
}
protected void addPlayerInventorySlots(Inventory playerInventory, int storageItemSlotIndex, boolean shouldLockStorageItemSlot) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 9; ++j) {
int slotIndex = j + i * 9 + 9;
Slot slot = addStorageItemSafeSlot(playerInventory, slotIndex, storageItemSlotIndex, shouldLockStorageItemSlot);
addSlotAndUpdateStorageItemSlotNumber(storageItemSlotIndex, shouldLockStorageItemSlot, slotIndex, slot);
}
}
for (int slotIndex = 0; slotIndex < 9; ++slotIndex) {
Slot slot = addStorageItemSafeSlot(playerInventory, slotIndex, storageItemSlotIndex, shouldLockStorageItemSlot);
addSlotAndUpdateStorageItemSlotNumber(storageItemSlotIndex, shouldLockStorageItemSlot, slotIndex, slot);
}
}
private Slot addStorageItemSafeSlot(Inventory playerInventory, int slotIndex, int storageItemSlotIndex, boolean shouldLockStorageItemSlot) {
Slot slot;
if (shouldLockStorageItemSlot && slotIndex == storageItemSlotIndex) {
slot = new Slot(playerInventory, slotIndex, 0, 0) {
@Override
public boolean mayPickup(Player playerIn) {
return false;
}
@Override
public void setChanged() {
super.setChanged();
closeScreenIfSomethingMessedWithStorageItemStack(getItem());
}
};
} else {
slot = new Slot(playerInventory, slotIndex, 0, 0);
}
return addSlot(slot);
}
public void closeScreenIfSomethingMessedWithStorageItemStack(ItemStack supposedToBeStorageItemStack) {
if (!isClientSide() && isNotCorrectStorageItem(supposedToBeStorageItemStack)) {
player.closeContainer();
}
}
protected boolean isClientSide() {
return player.level.isClientSide;
}
private void addSlotAndUpdateStorageItemSlotNumber(int storageItemSlotIndex, boolean lockStorageItemSlot, int slotIndex, Slot slot) {
if (lockStorageItemSlot && slotIndex == storageItemSlotIndex) {
storageItemSlotNumber = slot.index;
}
}
public int getNumberOfRows() {
return storageWrapper.getNumberOfSlotRows();
}
public int getFirstUpgradeSlot() {
return getInventorySlotsSize();
}
public boolean isFirstLevelStorage() {
return parentStorageWrapper == NoopStorageWrapper.INSTANCE;
}
@Override
public void initializeContents(int stateId, List<ItemStack> items, ItemStack carried) {
storageWrapper.setPersistent(player.level.isClientSide);
isUpdatingFromPacket = true;
super.initializeContents(stateId, items, carried);
isUpdatingFromPacket = false;
storageWrapper.setPersistent(true);
storageWrapper.getInventoryHandler().saveInventory();
storageWrapper.getUpgradeHandler().saveInventory();
}
protected boolean isUpgradeSettingsSlot(int index) {
return index >= getNumberOfStorageInventorySlots() + getNumberOfUpgradeSlots() + StorageContainerMenuBase.NUMBER_OF_PLAYER_SLOTS;
}
public boolean isStorageInventorySlot(int index) {
return index >= 0 && index < getNumberOfStorageInventorySlots();
}
protected boolean isUpgradeSlot(int index) {
return index >= getFirstUpgradeSlot() && (index - getFirstUpgradeSlot() < getNumberOfUpgradeSlots());
}
@Override
public void clicked(int slotId, int dragType, ClickType clickType, Player player) {
if (isUpgradeSettingsSlot(slotId) && getSlot(slotId) instanceof IFilterSlot && getSlot(slotId).mayPlace(getCarried())) {
Slot slot = getSlot(slotId);
ItemStack cursorStack = getCarried().copy();
if (cursorStack.getCount() > 1) {
cursorStack.setCount(1);
}
slot.set(cursorStack);
return;
} else if (isUpgradeSlot(slotId) && getSlot(slotId) instanceof StorageContainerMenuBase<?>.StorageUpgradeSlot slot) {
ItemStack slotStack = slot.getItem();
if (slot.mayPlace(getCarried())) {
ItemStack cursorStack = getCarried();
IUpgradeItem<?> upgradeItem = (IUpgradeItem<?>) cursorStack.getItem();
int newColumnsTaken = upgradeItem.getInventoryColumnsTaken();
int currentColumnsTaken = 0;
if (!slotStack.isEmpty()) {
currentColumnsTaken = ((IUpgradeItem<?>) slotStack.getItem()).getInventoryColumnsTaken();
}
if (needsSlotsThatAreOccupied(cursorStack, currentColumnsTaken, slot, newColumnsTaken)) {
return;
}
int columnsToRemove = newColumnsTaken - currentColumnsTaken;
if (slotStack.isEmpty() || slot.canSwapStack(player, cursorStack)) {
setCarried(slotStack);
slot.set(cursorStack);
updateColumnsTaken(columnsToRemove);
slot.setChanged();
}
} else if ((getCarried().isEmpty() || slot.mayPlace(getCarried())) && !slotStack.isEmpty() && slot.mayPickup(player)) {
int k2 = dragType == 0 ? Math.min(slotStack.getCount(), slotStack.getMaxStackSize()) : Math.min(slotStack.getMaxStackSize() + 1, slotStack.getCount() + 1) / 2;
int columnsTaken = ((IUpgradeItem<?>) slotStack.getItem()).getInventoryColumnsTaken();
if (clickType == ClickType.QUICK_MOVE) {
quickMoveStack(player, slotId);
} else {
setCarried(slot.remove(k2));
}
updateColumnsTaken(-columnsTaken);
slot.onTake(player, getCarried());
}
return;
} else if (isOverflowLogicSlotAndAction(slotId, clickType) && handleOverflow(slotId, clickType, dragType, player)) {
return;
}
super.clicked(slotId, dragType, clickType, player);
}
@Override
public boolean isValidSlotIndex(int slotIndex) {
return slotIndex == -1 || slotIndex == -999 || slotIndex < getTotalSlotsNumber();
}
private boolean handleOverflow(int slotId, ClickType clickType, int dragType, Player player) {
ItemStack cursorStack = clickType == ClickType.SWAP ? player.getInventory().getItem(dragType) : getCarried();
Consumer<ItemStack> updateCursorStack = clickType == ClickType.SWAP ? s -> player.getInventory().setItem(dragType, s) : this::setCarried;
Slot slot = getSlot(slotId);
if ((clickType != ClickType.SWAP && cursorStack.isEmpty()) || !slot.mayPlace(cursorStack)) {
return false;
}
ItemStack slotStack = slot.getItem();
if (slotStack.isEmpty() || (slot.mayPickup(player) && slotStack.getItem() != cursorStack.getItem() && cursorStack.getCount() <= slot.getMaxStackSize(cursorStack) && slotStack.getCount() <= slotStack.getMaxStackSize())) {
return processOverflowIfSlotWithSameItemFound(slotId, cursorStack, updateCursorStack);
} else if (slotStack.getItem() == cursorStack.getItem()) {
return processOverflowForAnythingOverSlotMaxSize(cursorStack, updateCursorStack, slot, slotStack);
}
return false;
}
private boolean processOverflowForAnythingOverSlotMaxSize(ItemStack cursorStack, Consumer<ItemStack> updateCursorStack, Slot slot, ItemStack slotStack) {
int remainingSpaceInSlot = slot.getMaxStackSize(cursorStack) - slotStack.getCount();
if (remainingSpaceInSlot < cursorStack.getCount()) {
ItemStack overflow = cursorStack.copy();
int overflowCount = cursorStack.getCount() - remainingSpaceInSlot;
overflow.setCount(overflowCount);
ItemStack result = processOverflowLogic(overflow);
if (result.getCount() < overflowCount) {
cursorStack.shrink(overflowCount - result.getCount());
if (cursorStack.isEmpty()) {
updateCursorStack.accept(ItemStack.EMPTY);
return true;
} else {
updateCursorStack.accept(cursorStack);
}
}
}
return false;
}
private boolean processOverflowIfSlotWithSameItemFound(int slotId, ItemStack cursorStack, Consumer<ItemStack> updateCursorStack) {
for (IOverflowResponseUpgrade overflowUpgrade : storageWrapper.getUpgradeHandler().getWrappersThatImplement(IOverflowResponseUpgrade.class)) {
if (overflowUpgrade.stackMatchesFilter(cursorStack) && overflowUpgrade.worksInGui()
&& findSlotWithMatchingStack(slotId, cursorStack, updateCursorStack, overflowUpgrade)) {
return true;
}
}
return false;
}
private boolean findSlotWithMatchingStack(int slotId, ItemStack cursorStack, Consumer<ItemStack> updateCursorStack, IOverflowResponseUpgrade overflowUpgrade) {
for (int slotIndex = 0; slotIndex < getNumberOfStorageInventorySlots(); slotIndex++) {
if (slotIndex != slotId && overflowUpgrade.stackMatchesFilterStack(getSlot(slotIndex).getItem(), cursorStack)) {
ItemStack result = cursorStack;
result = overflowUpgrade.onOverflow(result);
updateCursorStack.accept(result);
if (result.isEmpty()) {
return true;
}
}
}
return false;
}
private boolean isOverflowLogicSlotAndAction(int slotId, ClickType clickType) {
return isStorageInventorySlot(slotId) && (clickType == ClickType.SWAP || clickType == ClickType.PICKUP);
}
protected void updateColumnsTaken(int columnsToRemove) {
if (columnsToRemove != 0) {
storageWrapper.setColumnsTaken(Math.max(0, storageWrapper.getColumnsTaken() + columnsToRemove));
storageWrapper.onContentsNbtUpdated();
refreshAllSlots();
}
}
protected boolean needsSlotsThatAreOccupied(ItemStack cursorStack, int currentColumnsTaken, StorageContainerMenuBase<?>.StorageUpgradeSlot upgradeSlot, int newColumnsTaken) {
if (currentColumnsTaken >= newColumnsTaken) {
return false;
}
int slotsToCheck = (newColumnsTaken - currentColumnsTaken) * getNumberOfRows();
InventoryHandler invHandler = storageWrapper.getInventoryHandler();
Set<Integer> errorSlots = new HashSet<>();
int slots = getNumberOfStorageInventorySlots();
for (int slotIndex = slots - 1; slotIndex >= slots - slotsToCheck; slotIndex--) {
if (!invHandler.getStackInSlot(slotIndex).isEmpty()) {
errorSlots.add(slotIndex);
}
}
if (!errorSlots.isEmpty()) {
upgradeSlot.updateSlotChangeError(new UpgradeSlotChangeResult.Fail(TranslationHelper.INSTANCE.translError("add.needs_occupied_inventory_slots", slotsToCheck, cursorStack.getHoverName()), Collections.emptySet(), errorSlots, Collections.emptySet()));
return true;
}
return false;
}
public int getUpgradeSlotsSize() {
return upgradeSlots.size();
}
public List<Integer> getSlotOverlayColors(int slot) {
List<Integer> ret = new ArrayList<>();
storageWrapper.getSettingsHandler().getCategoriesThatImplement(ISlotColorCategory.class).forEach(c -> c.getSlotColor(slot).ifPresent(ret::add));
return ret;
}
public Optional<UpgradeContainerBase<?, ?>> getOpenContainer() {
return storageWrapper.getOpenTabId().flatMap(id -> upgradeContainers.containsKey(id) ? Optional.of(upgradeContainers.get(id)) : Optional.empty());
}
protected void sendToServer(Consumer<CompoundTag> addData) {
CompoundTag data = new CompoundTag();
addData.accept(data);
SophisticatedCore.PACKET_HANDLER.sendToServer(new SyncContainerClientDataMessage(data));
}
public void setUpgradeEnabled(int upgradeSlot, boolean enabled) {
Map<Integer, IUpgradeWrapper> slotWrappers = storageWrapper.getUpgradeHandler().getSlotWrappers();
if (!slotWrappers.containsKey(upgradeSlot)) {
return;
}
if (isClientSide()) {
sendToServer(data -> {
data.putBoolean(UPGRADE_ENABLED_TAG, enabled);
data.putInt(UPGRADE_SLOT_TAG, upgradeSlot);
});
}
slotWrappers.get(upgradeSlot).setEnabled(enabled);
}
public boolean getUpgradeEnabled(int upgradeSlot) {
Map<Integer, IUpgradeWrapper> slotWrappers = storageWrapper.getUpgradeHandler().getSlotWrappers();
if (!slotWrappers.containsKey(upgradeSlot)) {
return false;
}
return slotWrappers.get(upgradeSlot).isEnabled();
}
public boolean canDisableUpgrade(int upgradeSlot) {
Map<Integer, IUpgradeWrapper> slotWrappers = storageWrapper.getUpgradeHandler().getSlotWrappers();
if (!slotWrappers.containsKey(upgradeSlot)) {
return false;
}
return slotWrappers.get(upgradeSlot).canBeDisabled();
}
public void sort() {
if (isClientSide()) {
sendToServer(data -> data.putString(ACTION_TAG, "sort"));
return;
}
storageWrapper.sort();
}
public void setOpenTabId(int tabId) {
if (isClientSide()) {
sendToServer(data -> data.putInt(OPEN_TAB_ID_TAG, tabId));
}
if (tabId == -1) {
storageWrapper.removeOpenTabId();
} else {
storageWrapper.setOpenTabId(tabId);
}
}
public void removeOpenTabId() {
setOpenTabId(-1);
}
public SortBy getSortBy() {
return storageWrapper.getSortBy();
}
public void setSortBy(SortBy sortBy) {
if (isClientSide()) {
sendToServer(data -> data.putString(SORT_BY_TAG, sortBy.getSerializedName()));
}
storageWrapper.setSortBy(sortBy);
}
public void handleMessage(CompoundTag data) {
if (data.contains("containerId")) {
int containerId = data.getInt("containerId");
if (upgradeContainers.containsKey(containerId)) {
upgradeContainers.get(containerId).handleMessage(data);
}
} else if (data.contains(OPEN_TAB_ID_TAG)) {
setOpenTabId(data.getInt(OPEN_TAB_ID_TAG));
} else if (data.contains(SORT_BY_TAG)) {
setSortBy(SortBy.fromName(data.getString(SORT_BY_TAG)));
} else if (data.contains(ACTION_TAG)) {
String actionName = data.getString(ACTION_TAG);
switch (actionName) {
case "sort" -> sort();
case "openSettings" -> openSettings();
default -> {
//noop
}
}
} else if (data.contains(UPGRADE_ENABLED_TAG)) {
setUpgradeEnabled(data.getInt(UPGRADE_SLOT_TAG), data.getBoolean(UPGRADE_ENABLED_TAG));
}
}
public Optional<UpgradeContainerBase<?, ?>> getSlotUpgradeContainer(Slot slot) {
if (isUpgradeSettingsSlot(slot.index)) {
for (UpgradeContainerBase<?, ?> upgradeContainer : upgradeContainers.values()) {
if (upgradeContainer.containsSlot(slot)) {
return Optional.of(upgradeContainer);
}
}
}
return Optional.empty();
}
@Override
public ItemStack quickMoveStack(Player player, int index) {
ItemStack itemstack = ItemStack.EMPTY;
Slot slot = getSlot(index);
if (slot.hasItem()) {
Optional<UpgradeContainerBase<?, ?>> upgradeContainer = getSlotUpgradeContainer(slot);
ItemStack slotStack = upgradeContainer.map(c -> c.getSlotStackToTransfer(slot)).orElse(slot.getItem());
itemstack = slotStack.copy();
if (!mergeSlotStack(slot, index, slotStack)) {
return ItemStack.EMPTY;
}
if (slotStack.isEmpty()) {
slot.set(ItemStack.EMPTY);
} else {
slot.setChanged();
}
slot.onQuickCraft(slotStack, itemstack);
if (upgradeContainer.isPresent()) {
upgradeContainer.ifPresent(c -> c.onTakeFromSlot(slot, player, slotStack));
} else {
slot.onTake(player, slotStack);
}
}
return itemstack;
}
private boolean mergeSlotStack(Slot slot, int index, ItemStack slotStack) {
if (isUpgradeSlot(index)) {
return mergeStackToStorage(slotStack) || mergeStackToPlayersInventory(slotStack);
} else if (isStorageInventorySlot(index)) {
if (shouldShiftClickIntoOpenTabFirst()) {
return mergeStackToOpenUpgradeTab(slotStack) || mergeStackToPlayersInventory(slotStack);
}
return mergeStackToPlayersInventory(slotStack) || mergeStackToOpenUpgradeTab(slotStack);
} else if (isUpgradeSettingsSlot(index)) {
if (getSlotUpgradeContainer(slot).map(c -> c.mergeIntoStorageFirst(slot)).orElse(true)) {
return mergeStackToStorage(slotStack) || mergeStackToPlayersInventory(slotStack);
}
return mergeStackToPlayersInventory(slotStack) || mergeStackToStorage(slotStack);
} else {
if (shouldShiftClickIntoOpenTabFirst()) {
return mergeStackToOpenUpgradeTab(slotStack) || mergeStackToUpgradeSlots(slotStack) || mergeStackToStorage(slotStack);
}
return mergeStackToUpgradeSlots(slotStack) || mergeStackToStorage(slotStack) || mergeStackToOpenUpgradeTab(slotStack);
}
}
private boolean shouldShiftClickIntoOpenTabFirst() {
MainSettingsCategory category = storageWrapper.getSettingsHandler().getGlobalSettingsCategory();
return SettingsManager.getSettingValue(player, category.getPlayerSettingsTagName(), category, SettingsManager.SHIFT_CLICK_INTO_OPEN_TAB_FIRST);
}
private boolean mergeStackToUpgradeSlots(ItemStack slotStack) {
return !upgradeSlots.isEmpty() && moveItemStackTo(slotStack, getInventorySlotsSize(), getInventorySlotsSize() + getNumberOfUpgradeSlots(), false);
}
private boolean mergeStackToOpenUpgradeTab(ItemStack slotStack) {
return getOpenContainer().map(c -> {
List<Slot> slots = c.getSlots();
if (slots.isEmpty()) {
return false;
}
int firstSlotIndex = slots.get(0).index;
int lastSlotIndex = slots.get(slots.size() - 1).index;
return mergeItemStack(slotStack, firstSlotIndex, lastSlotIndex + 1, false, true);
}).orElse(false);
}
private boolean mergeStackToStorage(ItemStack slotStack) {
return mergeItemStack(slotStack, 0, getNumberOfStorageInventorySlots(), false, false, true);
}
private boolean mergeStackToPlayersInventory(ItemStack slotStack) {
return mergeItemStack(slotStack, getNumberOfStorageInventorySlots(), getInventorySlotsSize(), true, true);
}
public boolean isPlayersInventorySlot(int slotNumber) {
return slotNumber >= getNumberOfStorageInventorySlots() && slotNumber < getInventorySlotsSize();
}
public Optional<ItemStack> getMemorizedStackInSlot(int slotId) {
return storageWrapper.getSettingsHandler().getTypeCategory(MemorySettingsCategory.class).getSlotFilterItem(slotId).map(ItemStack::new);
}
public void setUpgradeChangeListener(Consumer<StorageContainerMenuBase<?>> upgradeChangeListener) {
this.upgradeChangeListener = upgradeChangeListener;
}
public abstract void openSettings();
protected abstract boolean isNotCorrectStorageItem(ItemStack supposedToBeStorageItemStack);
@SuppressWarnings("unchecked") // both conditions of T are checked before casting it in the result
public <T extends UpgradeContainerBase<?, ?> & ICraftingContainer> Optional<T> getOpenOrFirstCraftingContainer() {
T firstContainer = null;
for (UpgradeContainerBase<?, ?> container : upgradeContainers.values()) {
if (container instanceof ICraftingContainer) {
if (container.isOpen()) {
return Optional.of((T) container);
} else if (firstContainer == null) {
firstContainer = (T) container;
}
}
}
return Optional.ofNullable(firstContainer);
}
public int getTotalSlotsNumber() {
return getInventorySlotsSize() + upgradeSlots.size();
}
protected void removeOpenTabIfKeepOff() {
MainSettingsCategory category = storageWrapper.getSettingsHandler().getGlobalSettingsCategory();
if (Boolean.FALSE.equals(SettingsManager.getSettingValue(player, category.getPlayerSettingsTagName(), category, SettingsManager.KEEP_TAB_OPEN))) {
storageWrapper.removeOpenTabId();
}
}
protected Set<Integer> getNoSortSlotIndexes() {
SettingsHandler settingsHandler = storageWrapper.getSettingsHandler();
Set<Integer> slotIndexesExcludedFromSort = new HashSet<>();
slotIndexesExcludedFromSort.addAll(settingsHandler.getTypeCategory(NoSortSettingsCategory.class).getNoSortSlots());
slotIndexesExcludedFromSort.addAll(settingsHandler.getTypeCategory(MemorySettingsCategory.class).getSlotIndexes());
return slotIndexesExcludedFromSort;
}
@Override
public void broadcastFullState() {
broadcastFullStateOf(lastUpgradeSlots, upgradeSlots, getFirstUpgradeSlot());
broadcastFullStateOf(lastRealSlots, realInventorySlots, 0);
sendAllDataToRemote();
}
private void broadcastFullStateOf(NonNullList<ItemStack> lastSlotsCollection, List<Slot> slotsCollection, int slotIndexOffset) {
for (int i = 0; i < slotsCollection.size(); ++i) {
ItemStack itemstack = slotsCollection.get(i).getItem();
triggerSlotListeners(i, itemstack, itemstack::copy, lastSlotsCollection, slotIndexOffset);
}
}
protected void triggerSlotListeners(int stackIndex, ItemStack slotStack, Supplier<ItemStack> slotStackCopy, NonNullList<ItemStack> lastSlotsCollection, int slotIndexOffset) {
ItemStack itemstack = lastSlotsCollection.get(stackIndex);
if (!ItemStack.matches(itemstack, slotStack)) {
boolean clientStackChanged = !slotStack.equals(itemstack, true);
ItemStack stackCopy = slotStackCopy.get();
lastSlotsCollection.set(stackIndex, stackCopy);
if (clientStackChanged) {
for (ContainerListener containerlistener : containerListeners) {
containerlistener.slotChanged(this, stackIndex + slotIndexOffset, stackCopy);
}
}
}
}
@Override
public void sendAllDataToRemote() {
for (int i = 0; i < getInventorySlotsSize(); ++i) {
remoteRealSlots.set(i, realInventorySlots.get(i).getItem().copy());
}
for (int i = 0; i < upgradeSlots.size(); ++i) {
remoteUpgradeSlots.set(i, upgradeSlots.get(i).getItem().copy());
}
NonNullList<ItemStack> allRemoteSlots = NonNullList.create();
allRemoteSlots.addAll(remoteRealSlots);
allRemoteSlots.addAll(remoteUpgradeSlots);
remoteCarried = getCarried().copy();
if (synchronizer != null) {
synchronizer.sendInitialData(this, allRemoteSlots, remoteCarried, new int[] {});
}
}
@Override
public void setRemoteSlot(int slotIndex, ItemStack stack) {
if (slotIndex < getInventorySlotsSize()) {
remoteRealSlots.set(slotIndex, stack.copy());
} else {
remoteUpgradeSlots.set(slotIndex, stack.copy());
}
}
@Override
public void setRemoteSlotNoCopy(int slotIndex, ItemStack stack) {
if (slotIndex < getInventorySlotsSize()) {
remoteRealSlots.set(slotIndex, stack);
} else {
remoteUpgradeSlots.set(slotIndex - getInventorySlotsSize(), stack);
}
}
@Override
public OptionalInt findSlot(Container container, int slotIdx) {
for (int i = 0; i < getTotalSlotsNumber(); ++i) {
Slot slot = getSlot(i);
if (slot.container == container && slotIdx == slot.getContainerSlot()) {
return OptionalInt.of(i);
}
}
return OptionalInt.empty();
}
private void refreshAllSlots() {
slots.clear();
lastSlots.clear();
realInventorySlots.clear();
lastRealSlots.clear();
remoteRealSlots.clear();
upgradeSlots.clear();
lastUpgradeSlots.clear();
remoteUpgradeSlots.clear();
upgradeContainers.clear();
initSlotsAndContainers(player, storageItemSlotIndex, shouldLockStorageItemSlot);
}
protected ItemStack processOverflowLogic(ItemStack stack) {
ItemStack result = stack;
for (IOverflowResponseUpgrade overflowUpgrade : storageWrapper.getUpgradeHandler().getWrappersThatImplement(IOverflowResponseUpgrade.class)) {
if (overflowUpgrade.worksInGui()) {
result = overflowUpgrade.onOverflow(result);
if (result.isEmpty()) {
break;
}
}
}
return result;
}
private void onSwapCraft(Slot slot, int numItemsCrafted) {
try {
ON_SWAP_CRAFT.invoke(slot, numItemsCrafted);
}
catch (IllegalAccessException | InvocationTargetException e) {
SophisticatedCore.LOGGER.error("Error invoking onSwapCraft method in Slot class", e);
}
}
//copy of Container's doClick with the replacement of inventorySlots.get to getSlot, call to onswapcraft as that's protected in vanilla and an addition of upgradeSlots to pickup all
@SuppressWarnings("java:S3776")
//complexity here is brutal, but it's something that's in vanilla and need to keep this as close to it as possible for easier ports
@Override
protected void doClick(int slotId, int dragType, ClickType clickType, Player player) {
Inventory inventory = player.getInventory();
if (clickType == ClickType.QUICK_CRAFT) {
int i = quickcraftStatus;
quickcraftStatus = getQuickcraftHeader(dragType);
if ((i != 1 || quickcraftStatus != 2) && i != quickcraftStatus) {
resetQuickCraft();
} else if (getCarried().isEmpty()) {
resetQuickCraft();
} else if (quickcraftStatus == 0) {
quickcraftType = getQuickcraftType(dragType);
if (isValidQuickcraftType(quickcraftType, player)) {
quickcraftStatus = 1;
quickcraftSlots.clear();
} else {
resetQuickCraft();
}
} else if (quickcraftStatus == 1) {
Slot slot = getSlot(slotId);
ItemStack itemstack = getCarried();
if (StorageContainerMenuBase.canItemQuickReplace(slot, itemstack) && slot.mayPlace(itemstack) && (quickcraftType == 2 || itemstack.getCount() > quickcraftSlots.size()) && canDragTo(slot)) {
quickcraftSlots.add(slot);
}
} else if (quickcraftStatus == 2) {
if (!quickcraftSlots.isEmpty()) {
if (quickcraftSlots.size() == 1) {
int l = (quickcraftSlots.iterator().next()).index;
resetQuickCraft();
clicked(l, quickcraftType, ClickType.PICKUP, player);
return;
}
ItemStack carried = getCarried().copy();
int j1 = getCarried().getCount();
for (Slot slot1 : quickcraftSlots) {
ItemStack itemstack1 = getCarried();
if (slot1 != null && StorageContainerMenuBase.canItemQuickReplace(slot1, itemstack1) && slot1.mayPlace(itemstack1) && (quickcraftType == 2 || itemstack1.getCount() >= quickcraftSlots.size()) && canDragTo(slot1)) {
ItemStack carriedCopy = carried.copy();
int j = slot1.hasItem() ? slot1.getItem().getCount() : 0;
getQuickCraftSlotCount(quickcraftSlots, quickcraftType, carriedCopy, j);
int slotStackLimit = slot1.getMaxStackSize(carriedCopy);
if (!(slot1 instanceof StorageInventorySlot) && slotStackLimit > carriedCopy.getMaxStackSize()) {
slotStackLimit = carriedCopy.getMaxStackSize();
}
if (carriedCopy.getCount() > slotStackLimit) {
carriedCopy.setCount(slotStackLimit);
}
j1 -= carriedCopy.getCount() - j;
slot1.set(carriedCopy);
}
}
carried.setCount(j1);
setCarried(carried);
}
resetQuickCraft();
} else {
resetQuickCraft();
}
} else if (quickcraftStatus != 0) {
resetQuickCraft();
} else if ((clickType == ClickType.PICKUP || clickType == ClickType.QUICK_MOVE) && (dragType == 0 || dragType == 1)) {
ClickAction clickaction = dragType == 0 ? ClickAction.PRIMARY : ClickAction.SECONDARY;
if (slotId == -999) {
if (!getCarried().isEmpty()) {
if (clickaction == ClickAction.PRIMARY) {
player.drop(getCarried(), true);
setCarried(ItemStack.EMPTY);
} else {
player.drop(getCarried().split(1), true);
}
}
} else if (clickType == ClickType.QUICK_MOVE) {
if (slotId < 0) {
return;
}
Slot slot6 = getSlot(slotId);
if (!slot6.mayPickup(player)) {
return;
}
if (isStorageInventorySlot(slotId)) {
quickMoveStack(this.player, slotId).copy();
} else {
ItemStack itemstack8 = quickMoveStack(this.player, slotId);
while (!itemstack8.isEmpty() && ItemStack.isSame(slot6.getItem(), itemstack8)) {
itemstack8 = quickMoveStack(this.player, slotId);
}
}
} else {
if (slotId < 0) {
return;
}
Slot slot7 = getSlot(slotId);
ItemStack slotStack = slot7.getItem();
ItemStack carriedStack = getCarried();
player.updateTutorialInventoryAction(carriedStack, slot7.getItem(), clickaction);
if (!carriedStack.overrideStackedOnOther(slot7, clickaction, player) && !slotStack.overrideOtherStackedOnMe(carriedStack, slot7, clickaction, player, createCarriedSlotAccess())) {
if (slotStack.isEmpty()) {
if (!carriedStack.isEmpty()) {
int l2 = clickaction == ClickAction.PRIMARY ? carriedStack.getCount() : 1;
setCarried(slot7.safeInsert(carriedStack, l2));
}
} else if (slot7.mayPickup(player)) {
if (carriedStack.isEmpty()) {
int i3 = clickaction == ClickAction.PRIMARY ? Math.min(slotStack.getCount(), slotStack.getMaxStackSize()) : Math.min(slotStack.getMaxStackSize() + 1, slotStack.getCount() + 1) / 2;
Optional<ItemStack> optional1 = slot7.tryRemove(i3, Integer.MAX_VALUE, player);
optional1.ifPresent((p_150421_) -> {
setCarried(p_150421_);
slot7.onTake(player, p_150421_);
});
} else if (slot7.mayPlace(carriedStack)) {
if (ItemStack.isSameItemSameTags(slotStack, carriedStack)) {
int j3 = clickaction == ClickAction.PRIMARY ? carriedStack.getCount() : 1;
setCarried(slot7.safeInsert(carriedStack, j3));
} else if (carriedStack.getCount() <= slot7.getMaxStackSize(carriedStack) && slotStack.getCount() <= slotStack.getMaxStackSize()) {
slot7.set(carriedStack);
setCarried(slotStack);
}
} else if (ItemStack.isSameItemSameTags(slotStack, carriedStack)) {
Optional<ItemStack> optional = slot7.tryRemove(slotStack.getCount(), carriedStack.getMaxStackSize() - carriedStack.getCount(), player);
optional.ifPresent((p_150428_) -> {
carriedStack.grow(p_150428_.getCount());
slot7.onTake(player, p_150428_);
});
}
}
}
slot7.setChanged();
}
} else if (clickType == ClickType.SWAP) {
Slot slot2 = getSlot(slotId);
ItemStack itemstack4 = inventory.getItem(dragType);
ItemStack slotStack = slot2.getItem();
if (!itemstack4.isEmpty() || !slotStack.isEmpty()) {
if (itemstack4.isEmpty()) {
if (slot2.mayPickup(player)) {
if (slotStack.getCount() <= slotStack.getMaxStackSize()) {
inventory.setItem(dragType, slotStack);
onSwapCraft(slot2, slotStack.getCount());
slot2.set(ItemStack.EMPTY);
slot2.onTake(player, slotStack);
} else {
inventory.setItem(dragType, slotStack.split(slotStack.getMaxStackSize()));
slot2.setChanged();
}
}
} else if (slotStack.isEmpty()) {
if (slot2.mayPlace(itemstack4)) {
int l1 = slot2.getMaxStackSize(itemstack4);
if (itemstack4.getCount() > l1) {
slot2.set(itemstack4.split(l1));
} else {
slot2.set(itemstack4);
inventory.setItem(dragType, ItemStack.EMPTY);