offhand module

offhand: Minecraft 26.3 cheat module, full source for every implementation (3 clients: Meteor Client, OfflineClient, LiquidBounce (Kotlin)).

3 implementationsCombatCOMBATPLAYER

Full module source: 3 implementations

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

Meteor ClientCombatsrc/main/java/meteordevelopment/meteorclient/systems/modules/combat/Offhand.javaJava · 277 lines · 9.7 KB

Allows you to hold specified items in your offhand.

Settingsitem-switch-delayitemhotbarright-gapplesword-gapplealways-gap-on-swordalways-pot-on-swordsword-potmin-healthelytrafallingexplosion
Offhand.javaJava · Minecraft 26.2 · 277 lines · 9.7 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
3
 * Copyright (c) Meteor Development.
4
 */
5
6
package meteordevelopment.meteorclient.systems.modules.combat;
7
8
import meteordevelopment.meteorclient.events.meteor.MouseClickEvent;
9
import meteordevelopment.meteorclient.events.world.TickEvent;
10
import meteordevelopment.meteorclient.settings.*;
11
import meteordevelopment.meteorclient.systems.modules.Categories;
12
import meteordevelopment.meteorclient.systems.modules.Module;
13
import meteordevelopment.meteorclient.systems.modules.Modules;
14
import meteordevelopment.meteorclient.utils.Utils;
15
import meteordevelopment.meteorclient.utils.misc.input.KeyAction;
16
import meteordevelopment.meteorclient.utils.player.FindItemResult;
17
import meteordevelopment.meteorclient.utils.player.InvUtils;
18
import meteordevelopment.meteorclient.utils.player.PlayerUtils;
19
import meteordevelopment.orbit.EventHandler;
20
import net.minecraft.tags.ItemTags;
21
import net.minecraft.world.entity.EquipmentSlot;
22
import net.minecraft.world.item.AxeItem;
23
import net.minecraft.world.item.Items;
24
25
import static meteordevelopment.orbit.EventPriority.HIGHEST;
26
import static com.mojang.blaze3d.platform.InputConstants.MOUSE_BUTTON_RIGHT;
27
28
public class Offhand extends Module {
29
    private final SettingGroup sgCombat = settings.createGroup("Combat");
30
    private final SettingGroup sgTotem = settings.createGroup("Totem");
31
32
    //Combat
33
34
    private final Setting<Integer> delayTicks = sgCombat.add(new IntSetting.Builder()
35
        .name("item-switch-delay")
36
        .description("The delay in ticks between slot movements.")
37
        .defaultValue(0)
38
        .min(0)
39
        .sliderMax(20)
40
        .build()
41
    );
42
    private final Setting<Item> preferreditem = sgCombat.add(new EnumSetting.Builder<Item>()
43
        .name("item")
44
        .description("Which item to hold in your offhand.")
45
        .defaultValue(Item.Crystal)
46
        .build()
47
    );
48
49
    private final Setting<Boolean> hotbar = sgCombat.add(new BoolSetting.Builder()
50
        .name("hotbar")
51
        .description("Whether to use items from your hotbar.")
52
        .defaultValue(false)
53
        .build()
54
    );
55
56
    private final Setting<Boolean> rightgapple = sgCombat.add(new BoolSetting.Builder()
57
        .name("right-gapple")
58
        .description("Will switch to a gapple when holding right click.(DO NOT USE WITH POTION ON)")
59
        .defaultValue(false)
60
        .build()
61
    );
62
63
64
    private final Setting<Boolean> SwordGap = sgCombat.add(new BoolSetting.Builder()
65
        .name("sword-gapple")
66
        .description("Will switch to a gapple when holding a sword and right click.")
67
        .defaultValue(false)
68
        .visible(rightgapple::get)
69
        .build()
70
    );
71
72
    private final Setting<Boolean> alwaysSwordGap = sgCombat.add(new BoolSetting.Builder()
73
        .name("always-gap-on-sword")
74
        .description("Holds an Enchanted Golden Apple when you are holding a sword.")
75
        .defaultValue(false)
76
        .visible(() -> !rightgapple.get())
77
        .build()
78
    );
79
80
81
    private final Setting<Boolean> alwaysPot = sgCombat.add(new BoolSetting.Builder()
82
        .name("always-pot-on-sword")
83
        .description("Will switch to a potion when holding a sword")
84
        .defaultValue(false)
85
        .visible(() -> !rightgapple.get() && !alwaysSwordGap.get())
86
        .build()
87
    );
88
    private final Setting<Boolean> potionClick = sgCombat.add(new BoolSetting.Builder()
89
        .name("sword-pot")
90
        .description("Will switch to a potion when holding a sword and right click.")
91
        .defaultValue(false)
92
        .visible(() -> !rightgapple.get() && !alwaysPot.get() && !alwaysSwordGap.get())
93
        .build()
94
    );
95
96
    //Totem
97
98
    private final Setting<Double> minHealth = sgTotem.add(new DoubleSetting.Builder()
99
        .name("min-health")
100
        .description("Will hold a totem when below this amount of health.")
101
        .defaultValue(10)
102
        .range(0, 36)
103
        .sliderRange(0, 36)
104
        .build()
105
    );
106
107
    private final Setting<Boolean> elytra = sgTotem.add(new BoolSetting.Builder()
108
        .name("elytra")
109
        .description("Will always hold a totem while flying with an elytra.")
110
        .defaultValue(false)
111
        .build()
112
    );
113
114
    private final Setting<Boolean> falling = sgTotem.add(new BoolSetting.Builder()
115
        .name("falling")
116
        .description("Will hold a totem if fall damage could kill you.")
117
        .defaultValue(false)
118
        .build()
119
    );
120
121
    private final Setting<Boolean> explosion = sgTotem.add(new BoolSetting.Builder()
122
        .name("explosion")
123
        .description("Will hold a totem when explosion damage could kill you.")
124
        .defaultValue(true)
125
        .build()
126
    );
127
128
129
    private boolean isClicking;
130
    private boolean sentMessage;
131
132
    private Item currentItem;
133
    public boolean locked;
134
135
    private int totems, ticks;
136
137
    public Offhand() {
138
        super(Categories.Combat, "offhand", "Allows you to hold specified items in your offhand.");
139
    }
140
141
    @Override
142
    public void onActivate() {
143
        ticks = 0;
144
        sentMessage = false;
145
        isClicking = false;
146
        currentItem = preferreditem.get();
147
    }
148
149
    @EventHandler(priority = HIGHEST + 999)
150
    private void onTick(TickEvent.Pre event) {
151
        FindItemResult result = InvUtils.find(Items.TOTEM_OF_UNDYING);
152
        totems = result.count();
153
154
        if (totems <= 0) locked = false;
155
        else if (ticks > delayTicks.get()) {
156
            boolean low = mc.player.getHealth() + mc.player.getAbsorptionAmount() - PlayerUtils.possibleHealthReductions(explosion.get(), falling.get()) <= minHealth.get();
157
            boolean ely = elytra.get() && mc.player.getItemBySlot(EquipmentSlot.CHEST).getItem() == Items.ELYTRA && mc.player.isFallFlying();
158
            FindItemResult item = InvUtils.find(itemStack -> itemStack.getItem() == currentItem.item, 0, 35);
159
160
            // Calculates Damage from Falling, Explosions + Elyta
161
            locked = (low || ely);
162
163
            if (locked && mc.player.getMainHandItem().getItem() != Items.TOTEM_OF_UNDYING) {
164
                InvUtils.move().from(result.slot()).toOffhand();
165
            }
166
167
            ticks = 0;
168
            return;
169
        }
170
        ticks++;
171
172
        AutoTotem autoTotem = Modules.get().get(AutoTotem.class);
173
174
        // Returns to the original Item
175
        currentItem = preferreditem.get();
176
177
        // Sword Gap & Right Gap
178
        if (rightgapple.get()) {
179
            if (!locked) {
180
                if (SwordGap.get() && mc.player.getMainHandItem().is(ItemTags.SWORDS)) {
181
                    if (isClicking) {
182
                        currentItem = Item.EGap;
183
                    }
184
                }
185
                if (!SwordGap.get()) {
186
                    if (isClicking) {
187
                        currentItem = Item.EGap;
188
                    }
189
                }
190
            }
191
        }
192
193
        // Always Gap
194
        else if ((mc.player.getMainHandItem().is(ItemTags.SWORDS) || mc.player.getMainHandItem().getItem() instanceof AxeItem) && alwaysSwordGap.get())
195
            currentItem = Item.EGap;
196
197
            // Potion Click
198
        else if (potionClick.get()) {
199
            if (!locked) {
200
                if (mc.player.getMainHandItem().is(ItemTags.SWORDS)) {
201
                    if (isClicking) {
202
                        currentItem = Item.Potion;
203
                    }
204
                }
205
            }
206
        }
207
208
        // Always Pot
209
        else if ((mc.player.getMainHandItem().is(ItemTags.SWORDS) || mc.player.getMainHandItem().getItem() instanceof AxeItem) && alwaysPot.get())
210
            currentItem = Item.Potion;
211
212
213
        else currentItem = preferreditem.get();
214
215
        // Checking offhand item
216
        if (mc.player.getOffhandItem().getItem() != currentItem.item) {
217
            if (ticks >= delayTicks.get()) {
218
                if (!locked) {
219
                    FindItemResult item = InvUtils.find(itemStack -> itemStack.getItem() == currentItem.item, hotbar.get() ? 0 : 9, 35);
220
221
                    // No offhand item
222
                    if (!item.found()) {
223
                        if (!sentMessage) {
224
                            warning("Chosen item not found.");
225
                            sentMessage = true;
226
                        }
227
                    }
228
229
                    // Swap to offhand
230
                    else if ((isClicking || !autoTotem.isLocked() && !item.isOffhand())) {
231
                        InvUtils.move().from(item.slot()).toOffhand();
232
                        sentMessage = false;
233
                    }
234
                    ticks = 0;
235
                    return;
236
                }
237
                ticks++;
238
            }
239
        }
240
    }
241
242
    @EventHandler
243
    private void onMouseClick(MouseClickEvent event) {
244
        // Detects if the User is right-clicking
245
        isClicking = mc.gui.screen() == null && !Modules.get().get(AutoTotem.class).isLocked() && !usableItem() && !mc.player.isUsingItem() && event.action == KeyAction.Press && event.button() == MOUSE_BUTTON_RIGHT;
246
    }
247
248
    private boolean usableItem() {
249
        // What counts as a Usable Item
250
        return mc.player.getMainHandItem().getItem() == Items.BOW
251
            || mc.player.getMainHandItem().getItem() == Items.TRIDENT
252
            || mc.player.getMainHandItem().getItem() == Items.CROSSBOW
253
            || Utils.isFood(mc.player.getMainHandItem());
254
    }
255
256
    @Override
257
    public String getInfoString() {
258
        return preferreditem.get().name();
259
    }
260
261
    public enum Item {
262
        // Items the module could put on your offhand
263
        EGap(Items.ENCHANTED_GOLDEN_APPLE),
264
        Gap(Items.GOLDEN_APPLE),
265
        Crystal(Items.END_CRYSTAL),
266
        Totem(Items.TOTEM_OF_UNDYING),
267
        Shield(Items.SHIELD),
268
        Potion(Items.POTION);
269
        final net.minecraft.world.item.Item item;
270
271
        Item(net.minecraft.world.item.Item item) {
272
            this.item = item;
273
        }
274
    }
275
276
}
277
OfflineClientCOMBATsrc/main/java/com/jellypudding/offlineclient/modules/combat/Offhand.javaJava · 230 lines · 8.4 KB

Keeps a chosen item in your offhand.

SettingsItemHotbarQuick itemDelayTotem healthElytraFallingExplosion
Offhand.javaJava · Minecraft 26.2 · 230 lines · 8.4 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.combat;
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.util.DamageUtil;
11
import com.jellypudding.offlineclient.util.EntityUtil;
12
import com.jellypudding.offlineclient.util.InputUtil;
13
import com.jellypudding.offlineclient.util.InventoryUtil;
14
import com.jellypudding.offlineclient.util.InventoryUtil.Swap;
15
import com.jellypudding.offlineclient.util.Modules;
16
import net.minecraft.core.component.DataComponents;
17
import net.minecraft.tags.ItemTags;
18
import net.minecraft.world.item.Item;
19
import net.minecraft.world.item.ItemStack;
20
import net.minecraft.world.item.Items;
21
22
// Steps aside whilst AutoTotem has claimed the offhand for a totem.
23
public final class Offhand extends Module {
24
25
    private static final double HEART = 2;
26
    private static final int HOTBAR_SIZE = InventoryUtil.HOTBAR_SIZE;
27
28
    public enum Choice {
29
        CRYSTAL("Crystal", Items.END_CRYSTAL),
30
        TOTEM("Totem", Items.TOTEM_OF_UNDYING),
31
        GAPPLE("Golden apple", Items.GOLDEN_APPLE),
32
        EGAPPLE("Enchanted apple", Items.ENCHANTED_GOLDEN_APPLE),
33
        SHIELD("Shield", Items.SHIELD),
34
        POTION("Potion", Items.POTION);
35
36
        private final String label;
37
        private final Item item;
38
39
        Choice(String label, Item item) {
40
            this.label = label;
41
            this.item = item;
42
        }
43
44
        @Override
45
        public String toString() {
46
            return label;
47
        }
48
    }
49
50
    public enum Quick {
51
        NONE, CLICK_APPLE, SWORD_CLICK_APPLE, SWORD_APPLE, SWORD_CLICK_POTION, SWORD_POTION
52
    }
53
54
    private final EnumSetting<Choice> item = new EnumSetting<>("Item",
55
        "What to keep in your offhand.", Choice.CRYSTAL);
56
    private final BoolSetting hotbar = new BoolSetting("Hotbar",
57
        "Takes items from the hotbar too. Off leaves your hotbar stacks alone.", false);
58
    private final EnumSetting<Quick> quick = new EnumSetting<>("Quick item",
59
        "Brings a different item across in some situations.", Quick.NONE)
60
        .describe(Quick.NONE, "Nothing extra.")
61
        .describe(Quick.CLICK_APPLE,
62
            "An enchanted apple whilst you hold use with anything but a bow or crossbow "
63
                + "or trident or food.")
64
        .describe(Quick.SWORD_CLICK_APPLE, "An enchanted apple whilst you hold use with a sword.")
65
        .describe(Quick.SWORD_APPLE, "An enchanted apple whenever you hold a sword or an axe.")
66
        .describe(Quick.SWORD_CLICK_POTION, "A potion whilst you hold use with a sword.")
67
        .describe(Quick.SWORD_POTION, "A potion whenever you hold a sword or an axe.");
68
    private final NumberSetting delay = new NumberSetting("Delay",
69
        "Ticks to wait between swaps.", 0, 0, 20, 1, " ticks");
70
71
    private final NumberSetting totemHealth = new NumberSetting("Totem health",
72
        "Swaps to a totem once you drop to this many hearts. Zero never swaps.",
73
        7, 0, 10, 0.5, " hearts");
74
    private final BoolSetting elytra = new BoolSetting("Elytra",
75
        "Holds a totem whilst you glide.", false).visibleWhen(this::totemWanted);
76
    private final BoolSetting falling = new BoolSetting("Falling",
77
        "Counts the fall you are in against the totem health.", false)
78
        .visibleWhen(this::totemWanted);
79
    private final BoolSetting explosion = new BoolSetting("Explosion",
80
        "Counts a nearby crystal or bed or anchor against the totem health.", true)
81
        .visibleWhen(this::totemWanted);
82
83
    private final InventoryUtil.StrandedStack cursor = new InventoryUtil.StrandedStack();
84
    private int timer;
85
86
    public Offhand() {
87
        super("Offhand", "Keeps a chosen item in your offhand.", Category.COMBAT);
88
        addSettings(item, hotbar, quick, delay, totemHealth, elytra, falling, explosion);
89
        searchTags("totem", "crystal", "gapple", "potion");
90
    }
91
92
    @Override
93
    public String getSuffix() {
94
        return item.getValueString();
95
    }
96
97
    @Override
98
    protected void onEnable() {
99
        timer = 0;
100
    }
101
102
    @Override
103
    protected void onDisable() {
104
        if (inGame()) {
105
            cursor.giveBack();
106
        }
107
    }
108
109
    private boolean totemWanted() {
110
        return totemHealth.getValue() > 0;
111
    }
112
113
    @Subscribe
114
    private void onTick(TickEvent event) {
115
        if (!inGame() || mc.player.isSpectator()) {
116
            return;
117
        }
118
        if (!cursor.recover()) {
119
            return;
120
        }
121
        if (autoTotemLocked()) {
122
            return;
123
        }
124
125
        Item wanted = wantedItem();
126
        if (mc.player.getOffhandItem().is(wanted)) {
127
            return;
128
        }
129
130
        if (!InventoryUtil.canClick()) {
131
            return;
132
        }
133
        if (!InventoryUtil.carried().isEmpty()) {
134
            return;
135
        }
136
        if (timer > 0) {
137
            timer--;
138
            return;
139
        }
140
141
        int slot = findSlot(wanted);
142
        if (slot == -1) {
143
            return;
144
        }
145
146
        Swap result = InventoryUtil.swap(slot, InventoryUtil.OFFHAND_SLOT);
147
        if (result == Swap.REFUSED) {
148
            return;
149
        }
150
        if (result == Swap.STRANDED) {
151
            // Whatever the new item displaced had nowhere to go.
152
            cursor.hold(slot);
153
        }
154
        timer = delay.getInt();
155
    }
156
157
    private static boolean autoTotemLocked() {
158
        AutoTotem autoTotem = Modules.get(AutoTotem.class);
159
        return autoTotem != null && autoTotem.isLocked();
160
    }
161
162
    private Item wantedItem() {
163
        if (totemNeeded() && haveTotem()) {
164
            return Items.TOTEM_OF_UNDYING;
165
        }
166
        Item extra = quickItem();
167
        return extra != null ? extra : item.getValue().item;
168
    }
169
170
    private boolean haveTotem() {
171
        return mc.player.getOffhandItem().is(Items.TOTEM_OF_UNDYING)
172
            || findSlot(Items.TOTEM_OF_UNDYING) != -1;
173
    }
174
175
    // True once the health line is crossed after the damage already on its way.
176
    private boolean totemNeeded() {
177
        if (!totemWanted()) {
178
            return false;
179
        }
180
        if (elytra.isOn() && mc.player.isFallFlying()) {
181
            return true;
182
        }
183
        float incoming = DamageUtil.possibleIncoming(DamageUtil.BLAST_RANGE,
184
            explosion.isOn(), false, falling.isOn());
185
        return EntityUtil.totalHealth(mc.player) - incoming <= totemHealth.getValue() * HEART;
186
    }
187
188
    // The item the quick rule asks for right now. Null when it asks for nothing.
189
    private Item quickItem() {
190
        ItemStack held = mc.player.getInventory().getSelectedItem();
191
        boolean sword = held.is(ItemTags.SWORDS);
192
        boolean swordOrAxe = sword || held.is(ItemTags.AXES);
193
        boolean clicking = mc.gui.screen() == null && InputUtil.physicallyHeld(mc.options.keyUse);
194
        return switch (quick.getValue()) {
195
            case NONE -> null;
196
            case CLICK_APPLE -> clicking && !usable(held) ? apple() : null;
197
            case SWORD_CLICK_APPLE -> clicking && sword ? apple() : null;
198
            case SWORD_APPLE -> swordOrAxe ? apple() : null;
199
            case SWORD_CLICK_POTION -> clicking && sword ? Items.POTION : null;
200
            case SWORD_POTION -> swordOrAxe ? Items.POTION : null;
201
        };
202
    }
203
204
    // Right clicking these uses them in the main hand. The offhand never fires.
205
    private static boolean usable(ItemStack held) {
206
        return held.is(Items.BOW) || held.is(Items.CROSSBOW) || held.is(Items.TRIDENT)
207
            || held.has(DataComponents.FOOD);
208
    }
209
210
    // A golden apple stands in whilst there is no enchanted one.
211
    private Item apple() {
212
        if (mc.player.getOffhandItem().is(Items.ENCHANTED_GOLDEN_APPLE)
213
            || findSlot(Items.ENCHANTED_GOLDEN_APPLE) != -1) {
214
            return Items.ENCHANTED_GOLDEN_APPLE;
215
        }
216
        return findSlot(Items.GOLDEN_APPLE) == -1 ? null : Items.GOLDEN_APPLE;
217
    }
218
219
    // Network slot of the first stack of the item. Minus one when absent.
220
    private int findSlot(Item wanted) {
221
        int first = hotbar.isOn() ? 0 : HOTBAR_SIZE;
222
        for (int i = first; i < InventoryUtil.WHOLE_INVENTORY; i++) {
223
            if (mc.player.getInventory().getItem(i).is(wanted)) {
224
                return InventoryUtil.networkSlot(i);
225
            }
226
        }
227
        return -1;
228
    }
229
}
230
LiquidBounce (Kotlin)PLAYERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/player/offhand/ModuleOffhand.ktKotlin · 429 lines · 15.0 KB

Manages your offhand.

SettingsSwitchModeSwitchDelayCycleOnlyWhileKillAuraGappleBindOnlyWhileCrystalAuraWhenNoTotemsCrystalBindOnlyWhileHoldingSwordStrengthBindWhileScaffoldWhileEagle
ModuleOffhand.ktKotlin · Minecraft 26.2 · 429 lines · 15.0 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.offhand
20
21
import com.mojang.blaze3d.platform.InputConstants
22
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
23
import net.ccbluex.liquidbounce.config.types.list.Tagged
24
import net.ccbluex.liquidbounce.event.EventManager
25
import net.ccbluex.liquidbounce.event.events.KeyEvent
26
import net.ccbluex.liquidbounce.event.events.RefreshArrayListEvent
27
import net.ccbluex.liquidbounce.event.events.ScheduleInventoryActionEvent
28
import net.ccbluex.liquidbounce.event.handler
29
import net.ccbluex.liquidbounce.features.module.ClientModule
30
import net.ccbluex.liquidbounce.features.module.ModuleCategories
31
import net.ccbluex.liquidbounce.features.module.modules.combat.crystalaura.ModuleCrystalAura
32
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.ModuleKillAura
33
import net.ccbluex.liquidbounce.features.module.modules.player.ModuleEagle
34
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ModuleScaffold
35
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ScaffoldBlockItemSelection
36
import net.ccbluex.liquidbounce.utils.client.Chronometer
37
import net.ccbluex.liquidbounce.utils.client.isNewerThanOrEquals1_16
38
import net.ccbluex.liquidbounce.utils.network.sendHeldItemChange
39
import net.ccbluex.liquidbounce.utils.network.sendSwapItemWithOffhand
40
import net.ccbluex.liquidbounce.utils.client.usesViaFabricPlus
41
import net.ccbluex.liquidbounce.utils.inventory.HotbarItemSlot
42
import net.ccbluex.liquidbounce.utils.inventory.InventoryAction
43
import net.ccbluex.liquidbounce.utils.inventory.ItemSlot
44
import net.ccbluex.liquidbounce.utils.inventory.PlayerInventoryConstraints
45
import net.ccbluex.liquidbounce.utils.inventory.Slots
46
import net.ccbluex.liquidbounce.utils.item.getPotionEffects
47
import net.ccbluex.liquidbounce.utils.item.isSword
48
import net.minecraft.core.component.DataComponents
49
import net.minecraft.world.effect.MobEffects
50
import net.minecraft.world.item.Item
51
import net.minecraft.world.item.ItemStack
52
import net.minecraft.world.item.Items
53
import java.util.function.Predicate
54
55
/**
56
 * Offhand module
57
 *
58
 * Manages your offhand.
59
 */
60
object ModuleOffhand : ClientModule("Offhand", ModuleCategories.PLAYER, aliases = listOf("AutoTotem")) {
61
62
    private val inventoryConstraints = tree(PlayerInventoryConstraints())
63
    private val switchMode by enumChoice(
64
        "SwitchMode",
65
        default = if (!usesViaFabricPlus) SwitchMode.SWITCH else SwitchMode.AUTOMATIC
66
    )
67
    private val switchDelay by int("SwitchDelay", 0, 0..500, "ms")
68
    private val cycleSlots by key("Cycle", InputConstants.KEY_H)
69
70
    private object Gapple : ToggleableValueGroup(this, "Gapple", true) {
71
        object WhileHoldingSword : ToggleableValueGroup(this, "WhileHoldingSword", true) {
72
            val onlyWhileKa by boolean("OnlyWhileKillAura", true)
73
        }
74
75
        val gappleBind by key("GappleBind")
76
77
        init {
78
            tree(WhileHoldingSword)
79
        }
80
    }
81
82
    private object Crystal : ToggleableValueGroup(this, "Crystal", true) {
83
        val onlyWhileCa by boolean("OnlyWhileCrystalAura", false)
84
        val whenNoTotems by boolean("WhenNoTotems", true)
85
        val crystalBind by key("CrystalBind")
86
    }
87
88
    private object Strength : ToggleableValueGroup(this, "StrengthPotion", false) {
89
        val onlyWhileHoldingSword by boolean("OnlyWhileHoldingSword", true)
90
        val onlyWhileKa by boolean("OnlyWhileKillAura", true)
91
        val strengthBind by key("StrengthBind")
92
    }
93
94
    private object Block : ToggleableValueGroup(this, "Block", false) {
95
        val whileScaffold by boolean("WhileScaffold", true)
96
        val whileEagle by boolean("WhileEagle", true)
97
    }
98
99
    init {
100
        treeAll(
101
            Totem,
102
            Crystal,
103
            Gapple,
104
            Strength,
105
            Block,
106
        )
107
    }
108
109
    private val INVENTORY_MAIN_PRIORITY = Slots.Inventory + Slots.Hotbar
110
    private val INVENTORY_HOTBAR_PRIORITY = Slots.Hotbar + Slots.Inventory
111
    private val chronometer = Chronometer()
112
    private var activeMode: Mode = Mode.NONE
113
    private var lastMode: Mode? = null
114
    private var lastTagMode: Mode = Mode.NONE
115
    private var staticMode = Mode.NONE
116
    private var last: LastSwitch? = null
117
118
    override val tag: String
119
        get() = activeMode.modeName
120
121
    override fun onEnabled() {
122
        staticMode = when {
123
            Crystal.enabled && Mode.CRYSTAL.canCycleTo() -> Mode.CRYSTAL
124
            Gapple.enabled -> Mode.GAPPLE
125
            Totem.enabled && !Totem.Health.enabled -> Mode.TOTEM
126
            else -> Mode.NONE
127
        }
128
    }
129
130
    @Suppress("unused")
131
    val keyHandler = handler<KeyEvent> {
132
        if (it.action != InputConstants.PRESS) {
133
            return@handler
134
        }
135
136
        when (it.key.value) {
137
            Gapple.gappleBind.value -> Mode.GAPPLE.onBindPress()
138
            Crystal.crystalBind.value -> Mode.CRYSTAL.onBindPress()
139
            Strength.strengthBind.value -> {
140
                // since we can't cycle to strength, its status has to be checked here
141
                if (Strength.enabled) {
142
                    Mode.STRENGTH.onBindPress()
143
                }
144
            }
145
146
            cycleSlots.value -> {
147
                val entries = Mode.entries
148
                val startIndex = staticMode.ordinal
149
                var index = (startIndex + 1) % entries.size
150
151
                while (index != startIndex) {
152
                    val mode = entries[index]
153
                    if (mode.canCycleTo()) {
154
                        staticMode = mode
155
                        return@handler
156
                    }
157
158
                    index = (index + 1) % entries.size
159
                }
160
            }
161
        }
162
    }
163
164
    @Suppress("unused")
165
    private val autoTotemHandler = handler<ScheduleInventoryActionEvent>(priority = 100) {
166
        activeMode = Mode.entries.firstOrNull(Mode::shouldEquip) ?: staticMode
167
        if (activeMode == Mode.NONE && Totem.Health.switchBack && lastMode == Mode.TOTEM) {
168
            activeMode = Mode.BACK
169
        }
170
171
        if (activeMode != lastTagMode) {
172
            EventManager.callEvent(RefreshArrayListEvent)
173
            lastTagMode = activeMode
174
        }
175
176
        if (activeMode != lastMode && lastMode == Mode.TOTEM) {
177
            if (!Totem.switchBackStarted) {
178
                Totem.switchBack.reset()
179
            }
180
181
            Totem.switchBackStarted = true
182
            if (!Totem.switchBack.hasElapsed(Totem.switchBackDelay.toLong())) {
183
                return@handler
184
            }
185
        }
186
187
        Totem.switchBackStarted = false
188
189
        if (!chronometer.hasElapsed(activeMode.getDelay().toLong())) {
190
            return@handler
191
        }
192
193
        val slot = activeMode.getSlot() ?: return@handler
194
        lastMode = activeMode
195
196
        // the item is already located in Off-hand slot
197
        if (slot == HotbarItemSlot.OFFHAND) {
198
            return@handler
199
        }
200
201
        if (Totem.Health.switchBack) {
202
            last = LastSwitch(slot.itemStack.item, slot)
203
        }
204
205
        val actions = switchMode.performSwitch(slot)
206
        if (actions.isEmpty()) {
207
            chronometer.reset()
208
            return@handler
209
        }
210
211
        if (activeMode != Mode.TOTEM || !Totem.send(actions)) {
212
            it.schedule(inventoryConstraints, actions)
213
        }
214
215
        chronometer.reset()
216
    }
217
218
    private fun performSwitch(from: ItemSlot, smart: Boolean): List<InventoryAction.Click> {
219
        return if (smart && from is HotbarItemSlot) {
220
            val selectedSlot = player.inventory.selectedSlot
221
            val targetSlot = from.inventorySlot
222
            if (selectedSlot != targetSlot) {
223
                network.sendHeldItemChange(targetSlot)
224
            }
225
            network.sendSwapItemWithOffhand()
226
            if (selectedSlot != targetSlot) {
227
                network.sendHeldItemChange(selectedSlot)
228
            }
229
            emptyList()
230
        } else {
231
            buildList(3) {
232
                this += InventoryAction.Click.performPickup(slot = from)
233
                this += InventoryAction.Click.performPickup(slot = HotbarItemSlot.OFFHAND)
234
                if (!player.offhandItem.isEmpty) {
235
                    this += InventoryAction.Click.performPickup(slot = from)
236
                }
237
            }
238
        }
239
    }
240
241
    private data class LastSwitch(val item: Item, val slot: ItemSlot)
242
243
    fun isOperating() = running && activeMode != Mode.NONE
244
245
    private enum class Mode(
246
        val modeName: String,
247
        private val item: Predicate<ItemStack>? = null,
248
        private val fallBackItem: Predicate<ItemStack>? = null,
249
    ) {
250
        TOTEM("Totem", Predicate { it.has(DataComponents.DEATH_PROTECTION) }) {
251
            override fun shouldEquip() = Totem.shouldEquip()
252
253
            override fun getDelay() = Totem.switchDelay
254
255
            override fun getPrioritizedInventoryPart() = 1
256
257
            override fun getSlot(): ItemSlot? {
258
                val slot = super.getSlot()
259
                if (slot == null && Crystal.enabled && Crystal.whenNoTotems) {
260
                    return CRYSTAL.getSlot()
261
                }
262
263
                return slot
264
            }
265
266
            override fun canCycleTo() = Totem.enabled
267
        },
268
        STRENGTH("Strength", Predicate { stack ->
269
            stack.`is`(Items.POTION) && stack.getPotionEffects().any { it.effect == MobEffects.STRENGTH }
270
        }) {
271
            override fun shouldEquip(): Boolean {
272
                val killAura = Strength.onlyWhileKa && !ModuleKillAura.running
273
                if (!Strength.enabled || killAura || player.hasEffect(MobEffects.STRENGTH)) {
274
                    return false
275
                }
276
277
                return player.mainHandItem.isSword || !Strength.onlyWhileHoldingSword
278
            }
279
        },
280
        GAPPLE("Gapple", Items.ENCHANTED_GOLDEN_APPLE, Items.GOLDEN_APPLE) {
281
            override fun shouldEquip(): Boolean {
282
                if (!Gapple.enabled) {
283
                    return false
284
                }
285
286
                if (player.mainHandItem.isSword && Gapple.WhileHoldingSword.enabled) {
287
                    return if (Gapple.WhileHoldingSword.onlyWhileKa) {
288
                        ModuleKillAura.running
289
                    } else {
290
                        true
291
                    }
292
                }
293
294
                return false
295
            }
296
297
            override fun canCycleTo() = Gapple.enabled
298
        },
299
        CRYSTAL("Crystal", Items.END_CRYSTAL) {
300
            override fun canCycleTo() = Crystal.enabled && (!Crystal.onlyWhileCa || ModuleCrystalAura.running)
301
        },
302
        BLOCK("Block", ScaffoldBlockItemSelection::isValidBlock) {
303
            override fun shouldEquip(): Boolean =
304
                Block.enabled &&
305
                    ((Block.whileEagle && ModuleEagle.enabled) || (Block.whileScaffold && ModuleScaffold.enabled))
306
307
            override fun canCycleTo() = Block.enabled
308
        },
309
        BACK("Back") {
310
            override fun getSlot(): ItemSlot? {
311
                return last?.let {
312
                    if (it.item == it.slot.itemStack.item) it.slot else null
313
                }
314
            }
315
        },
316
        NONE("None");
317
318
        constructor(
319
            modeName: String,
320
            item: Item,
321
            fallBackItem: Item? = null,
322
        ) : this(modeName, { it.`is`(item) }, fallBackItem?.let { item -> { it.`is`(item) } })
323
324
        private var modeBeforeDirectSwitch: Mode? = null
325
326
        open fun shouldEquip() = false
327
328
        open fun getDelay() = switchDelay
329
330
        open fun canCycleTo() = false
331
332
        /**
333
         * 0 = Main inventory
334
         * 1 = Hotbar
335
         */
336
        open fun getPrioritizedInventoryPart() = 0
337
338
        fun onBindPress() {
339
            if (activeMode == this && modeBeforeDirectSwitch != null && modeBeforeDirectSwitch!!.canCycleTo()) {
340
                staticMode = modeBeforeDirectSwitch!!
341
                modeBeforeDirectSwitch = null
342
            } else if (canCycleTo()) {
343
                modeBeforeDirectSwitch = staticMode
344
                staticMode = this
345
            } else {
346
                modeBeforeDirectSwitch = null
347
            }
348
        }
349
350
        open fun getSlot(): ItemSlot? {
351
            if (item == null) {
352
                return null
353
            }
354
355
            if (item.test(player.offhandItem)) {
356
                return HotbarItemSlot.OFFHAND
357
            }
358
359
            val slots = if (getPrioritizedInventoryPart() == 0) {
360
                INVENTORY_MAIN_PRIORITY
361
            } else {
362
                INVENTORY_HOTBAR_PRIORITY
363
            }
364
365
            var itemSlot = slots.findSlot(item)
366
            if (itemSlot == null && fallBackItem != null) {
367
                if (fallBackItem.test(player.offhandItem)) {
368
                    return HotbarItemSlot.OFFHAND
369
                }
370
371
                itemSlot = slots.findSlot(fallBackItem)
372
            }
373
374
            return itemSlot
375
        }
376
    }
377
378
    @Suppress("unused")
379
    private enum class SwitchMode(override val tag: String) : Tagged {
380
        /**
381
         * Pickup, but it performs a SWAP_ITEM_WITH_OFFHAND action whenever possible to send fewer packets.
382
         * Works on all versions.
383
         *
384
         * It's not the default because some servers kick you when you perform a SWAP_ITEM_WITH_OFFHAND action
385
         * often and quickly.
386
         */
387
        SMART("Smart") {
388
            override fun performSwitch(from: ItemSlot) = performSwitch(from, true)
389
        },
390
391
        /**
392
         * Performs a switch action, works on 1.16.
393
         * The best method on newer servers.
394
         */
395
        SWITCH("Switch") {
396
            override fun performSwitch(from: ItemSlot) = listOf(
397
                InventoryAction.Click.performSwap(
398
                    from = from,
399
                    to = HotbarItemSlot.OFFHAND
400
                )
401
            )
402
        },
403
404
        /**
405
         * Performs 2-3 a pickup actions.
406
         * Works on all versions.
407
         */
408
        PICKUP("PickUp") {
409
            override fun performSwitch(from: ItemSlot) = performSwitch(from, false)
410
        },
411
412
        /**
413
         * Chooses the switch action based on the version. Only works if vfp is installed.
414
         */
415
        AUTOMATIC("Automatic") {
416
            override fun performSwitch(from: ItemSlot): List<InventoryAction.Click> {
417
                return if (isNewerThanOrEquals1_16) {
418
                    SWITCH.performSwitch(from)
419
                } else {
420
                    PICKUP.performSwitch(from)
421
                }
422
            }
423
        };
424
425
        abstract fun performSwitch(from: ItemSlot): List<InventoryAction.Click>
426
    }
427
428
}
429