ChestStealer module

ChestStealer: Minecraft 26.3 cheat module, full source for every implementation (3 clients: MelaHack (ThunderHack fork), OfflineClient, LiquidBounce

3 implementationsMISCPLAYER

Full module source: 3 implementations

Every implementation below is the complete module file, verbatim. Expand a client to read its code.

MelaHack (ThunderHack fork)MISCsrc/main/java/thunder/hack/features/modules/misc/ChestStealer.javaJava · 101 lines · 4.6 KB

Steals items from chests.

SettingsItemsDelayRandomCloseAutoMystSort
ChestStealer.javaJava · Minecraft 26.2 · 101 lines · 4.6 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.misc;
2
3
import meteordevelopment.orbit.EventHandler;
4
import net.minecraft.core.Direction;
5
import net.minecraft.world.InteractionHand;
6
import net.minecraft.world.inventory.ChestMenu;
7
import net.minecraft.world.inventory.ContainerInput;
8
import net.minecraft.world.inventory.Slot;
9
import net.minecraft.world.item.ItemStack;
10
import net.minecraft.world.level.block.entity.BlockEntity;
11
import net.minecraft.world.level.block.entity.EnderChestBlockEntity;
12
import net.minecraft.world.phys.BlockHitResult;
13
import thunder.hack.core.manager.client.ModuleManager;
14
import thunder.hack.events.impl.PlayerUpdateEvent;
15
import thunder.hack.features.modules.Module;
16
import thunder.hack.features.modules.client.Religion;
17
import thunder.hack.setting.Setting;
18
import thunder.hack.setting.impl.ItemSelectSetting;
19
import thunder.hack.utility.Timer;
20
import thunder.hack.utility.math.MathUtility;
21
22
import java.util.ArrayList;
23
import java.util.Random;
24
25
import static thunder.hack.features.modules.client.ClientSettings.isRu;
26
import static thunder.hack.features.modules.render.StorageEsp.getBlockEntities;
27
28
import com.mojang.blaze3d.vertex.PoseStack;
29
30
public class ChestStealer extends Module {
31
    public ChestStealer() {
32
        super("ChestStealer", Category.MISC);
33
    }
34
35
    public final Setting<ItemSelectSetting> items = new Setting<>("Items", new ItemSelectSetting(new ArrayList<>()));
36
    private final Setting<Integer> delay = new Setting<>("Delay", 100, 0, 1000);
37
    private final Setting<Boolean> random = new Setting<>("Random", false);
38
    private final Setting<Boolean> close = new Setting<>("Close", false);
39
    private final Setting<Boolean> autoMyst = new Setting<>("AutoMyst", false);
40
    private final Setting<Sort> sort = new Setting<>("Sort", Sort.None);
41
42
    private final Timer autoMystDelay = new Timer();
43
    private final Timer timer = new Timer();
44
    private final Random rnd = new Random();
45
46
    @Override
47
    public void onEnable() {
48
        if (ModuleManager.religion.isOn() && ModuleManager.religion.ReligionSetting.is(Religion.YourReligion.Christianity)) {
49
            ModuleManager.religion.sendMessage(isRu() ? "Не укради!" : "Do not steal!");
50
            disable();
51
        }
52
    }
53
54
    public void onRender3D(PoseStack stack) {
55
        if (mc.player.containerMenu instanceof ChestMenu chest) {
56
            for (int i = 0; i < chest.getContainer().getContainerSize(); i++) {
57
                Slot slot = chest.getSlot(i);
58
                if (slot.hasItem() && isAllowed(slot.getItem())
59
                        && timer.every(delay.getValue() + (random.getValue() && delay.getValue() != 0 ? rnd.nextInt(delay.getValue()) : 0))
60
                        && !(mc.gui.screen().getTitle().getString().contains("Аукцион") || mc.gui.screen().getTitle().getString().contains("покупки"))) {
61
                    mc.gameMode.handleContainerInput(mc.player.containerMenu.containerId, i, 0, ContainerInput.QUICK_MOVE, mc.player);
62
                    autoMystDelay.reset();
63
                }
64
            }
65
            if (isContainerEmpty(chest) && close.getValue())
66
                mc.player.closeContainer();
67
        }
68
    }
69
70
    @EventHandler
71
    public void onPlayerUpdate(PlayerUpdateEvent event) {
72
        if (autoMyst.getValue() && mc.gui.screen() == null && autoMystDelay.passedMs(3000)) {
73
            for (BlockEntity be : getBlockEntities()) {
74
                if (be instanceof EnderChestBlockEntity) {
75
                    if (mc.player.distanceToSqr(net.minecraft.world.phys.Vec3.atBottomCenterOf(be.getBlockPos())) > 39)
76
                        continue;
77
                    mc.gameMode.useItemOn(mc.player, InteractionHand.MAIN_HAND, new BlockHitResult(net.minecraft.world.phys.Vec3.atBottomCenterOf(be.getBlockPos()).add(MathUtility.random(-0.4, 0.4), 0.375, MathUtility.random(-0.4, 0.4)), Direction.UP, be.getBlockPos(), false));
78
                    mc.player.swing(InteractionHand.MAIN_HAND);
79
                    break;
80
                }
81
            }
82
        }
83
    }
84
85
    private boolean isAllowed(ItemStack stack) {
86
        boolean allowed = items.getValue().contains(stack.getItem().getDescriptionId().replace("block.minecraft.", "").replace("item.minecraft.", ""));
87
        return switch (sort.getValue()) {
88
            case None -> true;
89
            case WhiteList -> allowed;
90
            default -> !allowed;
91
        };
92
    }
93
94
    private boolean isContainerEmpty(ChestMenu container) {
95
        for (int i = 0; i < (container.getContainer().getContainerSize() == 90 ? 54 : 27); i++)
96
            if (container.getSlot(i).hasItem()) return false;
97
        return true;
98
    }
99
100
    private enum Sort {None, WhiteList, BlackList}
101
}
OfflineClientPLAYERsrc/main/java/com/jellypudding/offlineclient/modules/player/ChestStealer.javaJava · 221 lines · 8.3 KB

Takes everything out of containers for you.

SettingsDelayInitial delayJitterList modeItemsScreensThrow outThrow backwardsButtonsClose when done
ChestStealer.javaJava · Minecraft 26.2 · 221 lines · 8.3 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.player;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.TickEvent;
5
import com.jellypudding.offlineclient.module.Category;
6
import com.jellypudding.offlineclient.module.Module;
7
import com.jellypudding.offlineclient.setting.BoolSetting;
8
import com.jellypudding.offlineclient.setting.EnumSetting;
9
import com.jellypudding.offlineclient.setting.NumberSetting;
10
import com.jellypudding.offlineclient.setting.RegistryListSetting;
11
import com.jellypudding.offlineclient.util.InventoryUtil;
12
import com.jellypudding.offlineclient.util.Modules;
13
import com.jellypudding.offlineclient.util.RotationManager;
14
import com.jellypudding.offlineclient.util.RotationPriority;
15
import net.minecraft.client.gui.screens.Screen;
16
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
17
import net.minecraft.core.registries.BuiltInRegistries;
18
import net.minecraft.world.inventory.AbstractContainerMenu;
19
import net.minecraft.world.inventory.ContainerInput;
20
import net.minecraft.world.inventory.MenuType;
21
import net.minecraft.world.inventory.Slot;
22
import net.minecraft.world.item.Item;
23
import net.minecraft.world.item.ItemStack;
24
25
import java.util.List;
26
import java.util.concurrent.ThreadLocalRandom;
27
28
public final class ChestStealer extends Module {
29
30
    public enum ListMode { WHITELIST, BLACKLIST }
31
32
    private final NumberSetting delay = new NumberSetting("Delay",
33
        "Milliseconds between each item grab.", 50, 0, 500, 10, "ms").min(0).max(5000);
34
    private final NumberSetting initialDelay = new NumberSetting("Initial delay",
35
        "Milliseconds to wait before the first grab of a container.", 50, 0, 1000, 10, "ms")
36
        .min(0).max(5000);
37
    private final NumberSetting jitter = new NumberSetting("Jitter",
38
        "Adds up to this many milliseconds at random to each grab.", 50, 0, 500, 10, "ms")
39
        .min(0).max(1000);
40
    private final EnumSetting<ListMode> listMode = new EnumSetting<>("List mode",
41
        "What the list means.", ListMode.BLACKLIST)
42
        .describe(ListMode.WHITELIST, "Takes only the listed items.")
43
        .describe(ListMode.BLACKLIST, "Takes everything except the listed items.");
44
    private final RegistryListSetting<Item> items = new RegistryListSetting<>("Items",
45
        "The items the list applies to. Click to pick them.", BuiltInRegistries.ITEM,
46
        List.of());
47
    private final RegistryListSetting<MenuType<?>> screens = new RegistryListSetting<>("Screens",
48
        "Which container screens are stolen from. Click to pick them.", BuiltInRegistries.MENU,
49
        List.of(MenuType.GENERIC_9x3, MenuType.GENERIC_9x6, MenuType.SHULKER_BOX,
50
            MenuType.HOPPER, MenuType.GENERIC_3x3));
51
    private final BoolSetting throwOut = new BoolSetting("Throw out",
52
        "Throws each item on the ground instead of into your inventory.", false);
53
    private final BoolSetting backwards = new BoolSetting("Throw backwards",
54
        "Turns you around whilst throwing so the pile lands behind you.", false)
55
        .under(throwOut);
56
    private final BoolSetting buttons = new BoolSetting("Buttons",
57
        "Draws Steal and Dump buttons above every container screen.", true);
58
    private final BoolSetting close = new BoolSetting("Close when done",
59
        "Close the container once everything is taken.", false);
60
61
    private long nextClick;
62
    private int lastSlot = -1;
63
    private int lastCount = -1;
64
    private boolean inventoryFull;
65
    private boolean open;
66
    // Set by the dump button. One stack moves per tick until the pass is done.
67
    private boolean dumpOnce;
68
69
    public ChestStealer() {
70
        super("ChestStealer", "Takes everything out of containers for you.", Category.PLAYER);
71
        addSettings(delay, initialDelay, jitter, listMode, items, screens, throwOut, backwards,
72
            buttons, close);
73
        searchTags("loot", "chest", "filter", "steal", "dump");
74
    }
75
76
    @Override
77
    public String getSuffix() {
78
        return items.size() == 0 ? null : listMode.getValueString();
79
    }
80
81
    public boolean showsButtons() {
82
        return isEnabled() && buttons.isOn();
83
    }
84
85
    // A button press makes the next grab due at once.
86
    public void stealNow() {
87
        nextClick = 0;
88
    }
89
90
    public void dumpNow() {
91
        dumpOnce = true;
92
        nextClick = 0;
93
    }
94
95
    // The screens the module works in. A menu built without a type is skipped.
96
    public boolean handles(Screen screen) {
97
        if (!(screen instanceof AbstractContainerScreen<?> container)) {
98
            return false;
99
        }
100
        MenuType<?> type = container.getMenu().menuType;
101
        return type != null && screens.contains(type);
102
    }
103
104
    @Subscribe
105
    private void onTick(TickEvent event) {
106
        if (!inGame()) {
107
            return;
108
        }
109
        if (!handles(mc.gui.screen())) {
110
            forget();
111
            return;
112
        }
113
        if (!open) {
114
            open = true;
115
            nextClick = System.currentTimeMillis() + initialDelay.getInt();
116
        }
117
        if (dumpOnce) {
118
            dumpOnce = false;
119
            dumpPass();
120
            return;
121
        }
122
        if (inventoryFull && !throwOut.isOn()) {
123
            if (mc.player.getInventory().getFreeSlot() == -1) {
124
                return;
125
            }
126
            // The refused slot has to look new again or the next pass skips it.
127
            lastSlot = -1;
128
            lastCount = -1;
129
            inventoryFull = false;
130
        }
131
        if (System.currentTimeMillis() < nextClick) {
132
            return;
133
        }
134
135
        AbstractContainerMenu menu = mc.player.containerMenu;
136
        int containerSlots = menu.slots.size() - InventoryUtil.WHOLE_INVENTORY;
137
        if (containerSlots <= 0) {
138
            return;
139
        }
140
141
        for (int i = 0; i < containerSlots; i++) {
142
            Slot slot = menu.slots.get(i);
143
            if (!slot.hasItem() || !wanted(slot.getItem())) {
144
                continue;
145
            }
146
            // A click that moved nothing means the inventory is full.
147
            if (i == lastSlot && slot.getItem().getCount() == lastCount) {
148
                inventoryFull = true;
149
                return;
150
            }
151
            lastSlot = i;
152
            lastCount = slot.getItem().getCount();
153
            take(menu, i);
154
            waitAgain();
155
            return;
156
        }
157
158
        if (close.isOn()) {
159
            mc.player.closeContainer();
160
        }
161
    }
162
163
    private void take(AbstractContainerMenu menu, int slot) {
164
        if (!throwOut.isOn()) {
165
            mc.gameMode.handleContainerInput(menu.containerId, slot, 0,
166
                ContainerInput.QUICK_MOVE, mc.player);
167
            return;
168
        }
169
        if (backwards.isOn()) {
170
            RotationManager.requestExact(mc.player.getYRot() + 180f, mc.player.getXRot(),
171
                RotationPriority.IDLE);
172
        }
173
        // Button one throws the whole stack straight onto the ground.
174
        mc.gameMode.handleContainerInput(menu.containerId, slot, 1,
175
            ContainerInput.THROW, mc.player);
176
    }
177
178
    // Moves everything the filter does not want back into the container.
179
    private void dumpPass() {
180
        AbstractContainerMenu menu = mc.player.containerMenu;
181
        InventoryTweaks tweaks = Modules.get(InventoryTweaks.class);
182
        for (int i = menu.slots.size() - InventoryUtil.WHOLE_INVENTORY; i < menu.slots.size(); i++) {
183
            Slot slot = menu.slots.get(i);
184
            ItemStack stack = slot.getItem();
185
            if (stack.isEmpty()) {
186
                continue;
187
            }
188
            if (tweaks != null && !tweaks.dumps(stack)) {
189
                continue;
190
            }
191
            mc.gameMode.handleContainerInput(menu.containerId, i, 0,
192
                ContainerInput.QUICK_MOVE, mc.player);
193
            waitAgain();
194
            dumpOnce = true;
195
            return;
196
        }
197
    }
198
199
    private void waitAgain() {
200
        int wait = delay.getInt();
201
        if (jitter.getInt() > 0) {
202
            wait += ThreadLocalRandom.current().nextInt(jitter.getInt() + 1);
203
        }
204
        nextClick = System.currentTimeMillis() + wait;
205
    }
206
207
    private void forget() {
208
        nextClick = 0;
209
        lastSlot = -1;
210
        lastCount = -1;
211
        inventoryFull = false;
212
        open = false;
213
        dumpOnce = false;
214
    }
215
216
    // An empty blacklist leaves every item wanted.
217
    private boolean wanted(ItemStack stack) {
218
        return items.contains(stack.getItem()) == listMode.is(ListMode.WHITELIST);
219
    }
220
}
221
LiquidBounce (Kotlin)PLAYERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/player/cheststealer/ModuleChestStealer.ktKotlin · 430 lines · 17.3 KB

Automatically steals all items from a chest.

SettingsAutoCloseMoveModeQuickSwapsOnFullStartItemRandomFactorOrder
ModuleChestStealer.ktKotlin · Minecraft 26.2 · 430 lines · 17.3 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of LiquidBounce (https://github.com/CCBlueX/LiquidBounce)
3
 *
4
 * Copyright (c) 2015 - 2026 CCBlueX
5
 *
6
 * LiquidBounce is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * LiquidBounce is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
package net.ccbluex.liquidbounce.features.module.modules.player.cheststealer
20
21
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet
22
import net.ccbluex.fastutil.swap
23
import net.ccbluex.liquidbounce.config.types.list.Tagged
24
import net.ccbluex.liquidbounce.config.types.group.Mode
25
import net.ccbluex.liquidbounce.config.types.group.ModeValueGroup
26
import net.ccbluex.liquidbounce.event.events.ScheduleInventoryActionEvent
27
import net.ccbluex.liquidbounce.event.handler
28
import net.ccbluex.liquidbounce.features.module.ClientModule
29
import net.ccbluex.liquidbounce.features.module.ModuleCategories
30
import net.ccbluex.liquidbounce.features.module.modules.player.cheststealer.features.FeatureChestAura
31
import net.ccbluex.liquidbounce.features.module.modules.player.cheststealer.features.FeatureSilentScreen
32
import net.ccbluex.liquidbounce.features.module.modules.player.invcleaner.CleanupPlanGenerator
33
import net.ccbluex.liquidbounce.features.module.modules.player.invcleaner.InventoryCleanupPlan
34
import net.ccbluex.liquidbounce.features.module.modules.player.invcleaner.ItemCategorization
35
import net.ccbluex.liquidbounce.features.module.modules.player.invcleaner.ModuleInventoryCleaner
36
import net.ccbluex.liquidbounce.utils.inventory.CheckScreenHandlerTypeValueGroup
37
import net.ccbluex.liquidbounce.utils.inventory.CheckScreenTitleValueGroup
38
import net.ccbluex.liquidbounce.utils.inventory.ContainerItemSlot
39
import net.ccbluex.liquidbounce.utils.inventory.HotbarItemSlot
40
import net.ccbluex.liquidbounce.utils.inventory.InventoryAction
41
import net.ccbluex.liquidbounce.utils.inventory.InventoryConstraints
42
import net.ccbluex.liquidbounce.utils.inventory.ItemSlot
43
import net.ccbluex.liquidbounce.utils.inventory.Slots
44
import net.ccbluex.liquidbounce.utils.inventory.findItemsInContainer
45
import net.ccbluex.liquidbounce.utils.inventory.mergeableCapacityFor
46
import net.ccbluex.liquidbounce.utils.inventory.findNonEmptySlotsInInventory
47
import net.ccbluex.liquidbounce.utils.item.isMergeable
48
import net.ccbluex.liquidbounce.utils.kotlin.random
49
import net.minecraft.client.gui.screens.Screen
50
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen
51
import net.minecraft.client.gui.screens.inventory.InventoryScreen
52
import net.minecraft.world.item.ItemStack
53
import java.util.concurrent.ThreadLocalRandom
54
import kotlin.math.ceil
55
56
/**
57
 * ChestStealer module
58
 *
59
 * Automatically steals all items from a chest.
60
 */
61
62
object ModuleChestStealer : ClientModule("ChestStealer", ModuleCategories.PLAYER) {
63
64
    private val inventoryConstrains = tree(InventoryConstraints())
65
    private val autoClose by boolean("AutoClose", true)
66
67
    private val selectionMode = choices("SelectionMode", Distance, arrayOf(Distance, Index, Random)).apply(::tagBy)
68
    private val itemMoveMode by enumChoice("MoveMode", ItemMoveMode.QUICK_MOVE)
69
    private val quickSwaps by boolean("QuickSwaps", true)
70
71
    private val onFull by enumChoice("OnFull", OnFull.THROW)
72
73
    private enum class OnFull(override val tag: String) : Tagged {
74
        NONE("None"),
75
        THROW("Throw"),
76
//        PUT_BACK("PutBack"), TODO: Fix this
77
    }
78
79
    private val checkScreenHandlerType = tree(CheckScreenHandlerTypeValueGroup(this))
80
    private val checkScreenTitle = tree(CheckScreenTitleValueGroup(this))
81
82
    init {
83
        tree(FeatureChestAura)
84
        tree(FeatureSilentScreen)
85
    }
86
87
    @Suppress("unused")
88
    private val scheduleInventoryAction = handler<ScheduleInventoryActionEvent> { event ->
89
        // Check if we are in a chest screen
90
        val screen = getChestScreen() ?: return@handler
91
92
        val cleanupPlan = createCleanupPlan(screen)
93
        // Quick swap items in hotbar (i.e. swords), some servers hate them
94
        if (quickSwaps && performQuickSwaps(event, cleanupPlan, screen)) {
95
            return@handler
96
        }
97
98
        val itemsToCollect = cleanupPlan.usefulItems.filterIsInstanceTo(ArrayList<ContainerItemSlot>())
99
100
        val stillRequiredSpace = getStillRequiredSpace(cleanupPlan, itemsToCollect.size)
101
        selectionMode.activeMode.process(itemsToCollect)
102
103
        val targetBlacklist = ObjectOpenHashSet<ItemSlot>()
104
105
        for (slot in itemsToCollect) {
106
            val moveActions = Slots.HotbarAndInventory.findPossiblePickActions(screen, slot, targetBlacklist)
107
108
            if (moveActions != null) {
109
                event.schedule(
110
                    inventoryConstrains, moveActions,
111
                    /**
112
                     * we prioritize item based on how important it is
113
                     * for example we should prioritize armor over apples
114
                     */
115
                    ItemCategorization.Default.getItemFacets(slot).maxOf { it.category.type.allocationPriority }
116
                )
117
            } else if (stillRequiredSpace > 0) {
118
                // Throw useless items
119
                event.schedule(
120
                    inventoryConstrains,
121
                    throwItem(cleanupPlan, screen, targetBlacklist) ?: break
122
                )
123
            }
124
        }
125
126
        // Check if stealing the chest was completed
127
        if (autoClose && itemsToCollect.isEmpty()) {
128
            event.schedule(inventoryConstrains, InventoryAction.CloseScreen(screen))
129
        }
130
    }
131
132
    /**
133
     * Gets the clicks from mergeable or empty slots, or null if impossible to pick
134
     */
135
    @Suppress("CognitiveComplexMethod")
136
    private fun Iterable<ItemSlot>.findPossiblePickActions(
137
        screen: AbstractContainerScreen<*>,
138
        from: ItemSlot,
139
        targetBlacklist: MutableSet<ItemSlot>? = null,
140
    ): List<InventoryAction.Click>? {
141
        val fromStack = from.itemStack
142
        val remaining = mergeableCapacityFor(fromStack, blacklist = targetBlacklist)
143
144
        // Impossible to pick any item into inventory
145
        if (remaining == 0) return null
146
147
        targetBlacklist?.add(from)
148
        return when (itemMoveMode) {
149
            ItemMoveMode.QUICK_MOVE -> listOf(InventoryAction.Click.performQuickMove(screen, from))
150
151
            ItemMoveMode.DRAG_AND_DROP -> {
152
                // Never empty
153
                val targets = filterTo(ArrayDeque()) {
154
                    (targetBlacklist == null || it !in targetBlacklist) &&
155
                        (it.itemStack.isEmpty || it.itemStack.isMergeable(fromStack))
156
                }
157
158
                /* The remaining count after merged with [fromStack]. Negative -> fromStack has remaining */
159
                fun mergedRemaining(target: ItemStack) = fromStack.maxStackSize - fromStack.count - target.count
160
161
                buildList {
162
                    // Pick up
163
                    this += InventoryAction.Click.performPickup(screen, from)
164
165
                    val possibleSinglePut = targets.firstOrNull { mergedRemaining(it.itemStack) >= 0 }
166
                    if (possibleSinglePut != null) {
167
                        this += InventoryAction.Click.performPickup(screen, possibleSinglePut)
168
                        targetBlacklist?.add(possibleSinglePut)
169
                    } else {
170
                        // Now all `mergedRemaining` result of [targets] are negative
171
                        // Minimize click count
172
                        targets.sortBy { mergedRemaining(it.itemStack) }
173
                        var count = fromStack.count
174
                        while (count >= 0) {
175
                            val target = targets.removeFirstOrNull() ?: break
176
                            count += mergedRemaining(target.itemStack)
177
                            this += InventoryAction.Click.performPickup(screen, target)
178
                            targetBlacklist?.add(target)
179
                        }
180
                    }
181
182
                    if (remaining < fromStack.count) {
183
                        // Unable to take all, put remaining items back
184
                        this += InventoryAction.Click.performPickup(screen, from)
185
                    }
186
                }
187
            }
188
        }
189
    }
190
191
    /**
192
     * @return if we should wait
193
     */
194
    private fun throwItem(
195
        cleanupPlan: InventoryCleanupPlan,
196
        screen: AbstractContainerScreen<*>,
197
        targetBlacklist: MutableSet<ItemSlot>,
198
    ): List<InventoryAction>? {
199
        val itemsInInv = findNonEmptySlotsInInventory()
200
        val itemToThrowOut = cleanupPlan.findItemsToThrowOut(itemsInInv)
201
            .firstOrNull { it.getIdForServer(screen) != null } ?: return null
202
203
        return when (onFull) {
204
            OnFull.NONE -> null
205
//            OnFull.PUT_BACK -> screen.getSlotsInContainer()
206
//                .findPossiblePickActions(screen, itemToThrowOut, targetBlacklist)
207
            OnFull.THROW -> {
208
                targetBlacklist.add(itemToThrowOut)
209
                listOf(InventoryAction.Click.performThrow(screen, itemToThrowOut))
210
            }
211
        }
212
    }
213
214
    /**
215
     * @param slotsToCollect amount of items we need to take
216
     */
217
    private fun getStillRequiredSpace(
218
        cleanupPlan: InventoryCleanupPlan,
219
        slotsToCollect: Int,
220
    ): Int {
221
        val freeSlotsInInv = Slots.HotbarAndInventory.count { it.itemStack.isEmpty }
222
223
        val spaceGainedThroughMerge = cleanupPlan.mergeableItems.entries.sumOf { (id, slots) ->
224
            val slotsInChest = slots.count { it.slotType == ItemSlot.Type.CONTAINER }
225
            val totalCount = slots.sumOf { it.itemStack.count }
226
227
            val mergedStackCount = ceil(totalCount.toDouble() / id.item.defaultMaxStackSize.toDouble()).toInt()
228
229
            (slots.size - mergedStackCount).coerceAtMost(slotsInChest)
230
        }
231
232
        return (slotsToCollect - freeSlotsInInv - spaceGainedThroughMerge).coerceAtLeast(0)
233
    }
234
235
    /**
236
     * @return true if a quick swap transaction was scheduled and the plan should be regenerated next tick
237
     */
238
    @Suppress("CognitiveComplexMethod")
239
    private fun performQuickSwaps(
240
        event: ScheduleInventoryActionEvent,
241
        cleanupPlan: InventoryCleanupPlan,
242
        screen: AbstractContainerScreen<*>
243
    ): Boolean {
244
        cleanupPlan.swaps.forEach { hotbarSwap ->
245
            // We only care about swaps from the chest to the hotbar
246
            if (hotbarSwap.from.slotType != ItemSlot.Type.CONTAINER) {
247
                return@forEach
248
            }
249
250
            val hotbarSlot = hotbarSwap.to as? HotbarItemSlot ?: return@forEach
251
            if (!hotbarSlot.canBeSwapTarget) {
252
                return@forEach
253
            }
254
255
            val actions = when {
256
                // Target slot is empty, swap
257
                hotbarSlot.itemStack.isEmpty -> listOf(
258
                    InventoryAction.Click.performSwap(screen, hotbarSwap.from, hotbarSlot)
259
                )
260
261
                // Target slot item is useful, swap it with another empty slot
262
                hotbarSlot in cleanupPlan.usefulItems ->
263
                    Slots.Inventory.firstOrNull { it.itemStack.isEmpty }?.let { emptyInventorySlot ->
264
                        listOf(
265
                            InventoryAction.Click.performSwap(screen, emptyInventorySlot, hotbarSlot),
266
                            InventoryAction.Click.performSwap(screen, hotbarSwap.from, hotbarSlot),
267
                        )
268
                    } ?: return@forEach
269
270
                // Target slot item is useless, throw and swap
271
                else -> if (hotbarSlot.isOffHand) {
272
                    // Throwing offhand item inside container looks not legit
273
                    listOf(InventoryAction.Click.performSwap(screen, hotbarSwap.from, hotbarSlot))
274
                } else {
275
                    listOf(
276
                        InventoryAction.Click.performThrow(screen, hotbarSlot),
277
                        InventoryAction.Click.performSwap(screen, hotbarSwap.from, hotbarSlot),
278
                    )
279
                }
280
            }
281
282
            if (actions.any { it.slot.getIdForServer(screen) == null }) {
283
                return@forEach
284
            }
285
286
            event.schedule(
287
                inventoryConstrains,
288
                actions,
289
                /**
290
                 * we prioritize item based on how important it is
291
                 * for example we should prioritize armor over apples
292
                 */
293
                hotbarSwap.priority
294
            )
295
296
            return true
297
        }
298
299
        return false
300
    }
301
302
    /**
303
     * Either asks [ModuleInventoryCleaner] what to do or just takes everything.
304
     */
305
    private fun createCleanupPlan(screen: AbstractContainerScreen<*>): InventoryCleanupPlan {
306
        val cleanupPlan = if (!ModuleInventoryCleaner.running) {
307
            val usefulItems = screen.findItemsInContainer()
308
309
            InventoryCleanupPlan(ObjectOpenHashSet(usefulItems), mutableListOf(), hashMapOf())
310
        } else {
311
            val availableItems = findNonEmptySlotsInInventory() + screen.findItemsInContainer()
312
313
            CleanupPlanGenerator(ModuleInventoryCleaner.cleanupTemplateFromSettings, availableItems).generatePlan()
314
        }
315
316
        return cleanupPlan
317
    }
318
319
    private sealed class SelectionMode(name: String) : Mode(name) {
320
        final override val parent: ModeValueGroup<*>
321
            get() = selectionMode
322
323
        abstract fun process(slots: ArrayList<ContainerItemSlot>)
324
    }
325
326
    private object Distance : SelectionMode("Distance") {
327
        private val startItem by enumChoice("StartItem", StartItem.DEFAULT)
328
        private val randomFactor by floatRange("RandomFactor", 1.0f..1.0f, 0.25f..2f)
329
330
        override fun process(slots: ArrayList<ContainerItemSlot>) {
331
            val n = slots.size
332
            if (n <= 1) return
333
334
            val startIndex = startItem.getStartIndex(slots)
335
            if (startIndex != 0) {
336
                slots.swap(0, startIndex)
337
            }
338
339
            if (n <= 2) return
340
341
            for (i in 0..<n - 1) {
342
                var bestIdx = i + 1
343
                var bestDist = Float.POSITIVE_INFINITY
344
345
                val current = slots[i]
346
347
                for (j in i + 1..<n) {
348
                    val candidate = slots[j]
349
                    val distance = current.distance(candidate).toFloat()
350
                    val factor = if (randomFactor.isEmpty()) 1F else randomFactor.random()
351
                    val effectiveDistance = distance * factor
352
353
                    if (effectiveDistance < bestDist) {
354
                        bestDist = effectiveDistance
355
                        bestIdx = j
356
                    }
357
                }
358
359
                slots.swap(i + 1, bestIdx)
360
            }
361
        }
362
363
        private enum class StartItem(override val tag: String) : Tagged {
364
            DEFAULT("Default") {
365
                override fun getStartIndex(slots: List<ContainerItemSlot>): Int = 0
366
            },
367
            RANDOM("Random") {
368
                override fun getStartIndex(slots: List<ContainerItemSlot>): Int {
369
                    return ThreadLocalRandom.current().nextInt(slots.size)
370
                }
371
            },
372
            MAX_SLOT("MaxSlot") {
373
                override fun getStartIndex(slots: List<ContainerItemSlot>): Int {
374
                    return slots.indices.maxBy { slots[it].slotInContainer }
375
                }
376
            },
377
            MIN_SLOT("MinSlot") {
378
                override fun getStartIndex(slots: List<ContainerItemSlot>): Int {
379
                    return slots.indices.minBy { slots[it].slotInContainer }
380
                }
381
            };
382
383
            abstract fun getStartIndex(slots: List<ContainerItemSlot>): Int
384
        }
385
    }
386
387
    private object Index : SelectionMode("Index") {
388
        private val order by enumChoice("Order", Order.ASCENDING)
389
390
        override fun process(slots: ArrayList<ContainerItemSlot>) {
391
            slots.sortWith(order)
392
        }
393
394
        private enum class Order(override val tag: String) : Tagged, Comparator<ContainerItemSlot> {
395
            ASCENDING("Ascending") {
396
                override fun compare(o1: ContainerItemSlot, o2: ContainerItemSlot): Int {
397
                    return o1.slotInContainer.compareTo(o2.slotInContainer)
398
                }
399
            },
400
            DESCENDING("Descending") {
401
                override fun compare(o1: ContainerItemSlot, o2: ContainerItemSlot): Int {
402
                    return o2.slotInContainer.compareTo(o1.slotInContainer)
403
                }
404
            },
405
        }
406
    }
407
408
    private object Random : SelectionMode("Random") {
409
        override fun process(slots: ArrayList<ContainerItemSlot>) = slots.shuffle()
410
    }
411
412
    /**
413
     * @return the chest screen if it is open and the title matches the chest title
414
     */
415
    private fun getChestScreen(): AbstractContainerScreen<*>? {
416
        return mc.gui.screen()?.takeIf { it.canBeStolen() } as AbstractContainerScreen<*>?
417
    }
418
419
    fun Screen.canBeStolen(): Boolean {
420
        return running && this is AbstractContainerScreen<*> && this !is InventoryScreen &&
421
            checkScreenHandlerType.isValid(this) && checkScreenTitle.isValid(this)
422
    }
423
424
    private enum class ItemMoveMode(override val tag: String) : Tagged {
425
        QUICK_MOVE("QuickMove"),
426
        DRAG_AND_DROP("DragAndDrop"),
427
    }
428
429
}
430