AutoFish module

AutoFish: Minecraft 26.3 cheat module, full source for every implementation (5 clients: MelaHack (ThunderHack fork), OfflineClient, Nicotine, …).

5 implementationsMISCPLAYERPlayer

Full module source: 5 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/AutoFish.javaJava · 117 lines · 4.5 KB

Automatically fishes.

SettingsDetectModeRodSaveChangeRodAutoSell
AutoFish.javaJava · Minecraft 26.2 · 117 lines · 4.5 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.misc;
2
3
import meteordevelopment.orbit.EventHandler;
4
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
5
import net.minecraft.network.protocol.game.ServerboundSwingPacket;
6
import net.minecraft.sounds.SoundEvents;
7
import net.minecraft.world.InteractionHand;
8
import net.minecraft.world.entity.projectile.FishingHook;
9
import net.minecraft.world.item.FishingRodItem;
10
import net.minecraft.world.item.ItemStack;
11
import net.minecraft.world.item.Items;
12
import thunder.hack.core.Managers;
13
import thunder.hack.events.impl.PacketEvent;
14
import thunder.hack.features.modules.Module;
15
import thunder.hack.setting.Setting;
16
import thunder.hack.utility.Timer;
17
import thunder.hack.utility.math.MathUtility;
18
import thunder.hack.utility.player.InventoryUtility;
19
20
import static thunder.hack.features.modules.client.ClientSettings.isRu;
21
22
public class AutoFish extends Module {
23
    public AutoFish() {
24
        super("AutoFish", Category.MISC);
25
    }
26
27
    private final Setting<DetectMode> detectMode = new Setting<>("DetectMode", DetectMode.DataTracker);
28
    private final Setting<Boolean> rodSave = new Setting<>("RodSave", true);
29
    private final Setting<Boolean> changeRod = new Setting<>("ChangeRod", false);
30
    private final Setting<Boolean> autoSell = new Setting<>("AutoSell", false);
31
32
    private boolean flag = false;
33
    private final Timer timeout = new Timer();
34
    private final Timer cooldown = new Timer();
35
36
    private enum DetectMode {
37
        Sound, DataTracker
38
    }
39
40
    @Override
41
    public void onEnable() {
42
        if (fullNullCheck()) disable("NPE protection");
43
    }
44
45
    @Override
46
    public void onDisable() {
47
        flag = false;
48
    }
49
50
    @EventHandler
51
    public void onPacketReceive(PacketEvent.Receive e) {
52
        if (e.getPacket() instanceof ClientboundSoundPacket sound && detectMode.getValue() == DetectMode.Sound)
53
            if (sound.getSound().value().equals(SoundEvents.FISHING_BOBBER_SPLASH) && mc.player.fishing != null && mc.player.fishing.distanceToSqr(sound.getX(), sound.getY(), sound.getZ()) < 4f)
54
                catchFish();
55
    }
56
57
    @Override
58
    public void onUpdate() {
59
        if (mc.player.getMainHandItem().getItem() instanceof FishingRodItem) {
60
            if (mc.player.getMainHandItem().getDamageValue() > 52) {
61
                if (rodSave.getValue() && !changeRod.getValue()) {
62
                    disable(isRu() ? "Удочка почти сломалась!" : "Saving the rod...");
63
                } else if (changeRod.getValue() && getRodSlot() != -1) {
64
                    sendMessage(isRu() ? "Свапнулся на новую удочку" : "Swapped to a new rod");
65
                    InventoryUtility.switchTo(getRodSlot());
66
                    cooldown.reset();
67
                } else disable(isRu() ? "Удочка почти сломалась!" : "Saving the rod...");
68
            }
69
        }
70
71
        if (!cooldown.passedMs(1000)) return;
72
73
        if (timeout.passedMs(45000) && mc.player.getMainHandItem().getItem() instanceof FishingRodItem) {
74
            mc.gameMode.useItem(mc.player, InteractionHand.MAIN_HAND);
75
            sendPacket(new ServerboundSwingPacket(InteractionHand.MAIN_HAND));
76
            timeout.reset();
77
            cooldown.reset();
78
        }
79
80
        if (mc.player.fishing != null && detectMode.getValue() == DetectMode.DataTracker) {
81
            boolean caughtFish = mc.player.fishing.getEntityData().get(FishingHook.DATA_BITING);
82
            if (!flag && caughtFish) {
83
                catchFish();
84
                flag = true;
85
            } else if (!caughtFish) flag = false;
86
        }
87
    }
88
89
    private void catchFish() {
90
        Managers.ASYNC.run(() -> {
91
92
            mc.gameMode.useItem(mc.player, InteractionHand.MAIN_HAND);
93
            sendPacket(new ServerboundSwingPacket(InteractionHand.MAIN_HAND));
94
95
            if (autoSell.getValue() && timeout.passedMs(1000)) mc.player.connection.sendCommand("sellfish");
96
97
            try {
98
                Thread.sleep((int) MathUtility.random(899, 1399));
99
            } catch (InterruptedException e) {
100
                throw new RuntimeException(e);
101
            }
102
103
            mc.gameMode.useItem(mc.player, InteractionHand.MAIN_HAND);
104
            sendPacket(new ServerboundSwingPacket(InteractionHand.MAIN_HAND));
105
            timeout.reset();
106
        }, (int) MathUtility.random(199, 349));
107
    }
108
109
    private int getRodSlot() {
110
        for (int i = 0; i < 9; i++) {
111
            final ItemStack item = mc.player.getInventory().getItem(i);
112
            if (item.getItem() == Items.FISHING_ROD && item.getDamageValue() < 52) return i;
113
        }
114
        return -1;
115
    }
116
}
117
OfflineClientPLAYERsrc/main/java/com/jellypudding/offlineclient/modules/player/AutoFish.javaJava · 615 lines · 23.6 KB

Casts and reels the fishing rod for you.

SettingsBite modeValid rangeAuto castRecast delayRecast spreadCatch delayCatch spreadRetry delayPatienceAuto switchAnti breakStop when out of rodsStop when fullShallow water warningmcMMO modemcMMO rangemcMMO range bugmcMMO limitDebug drawDebug colour
AutoFish.javaJava · Minecraft 26.2 · 615 lines · 23.6 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.PacketReceiveEvent;
5
import com.jellypudding.offlineclient.event.events.Render3DEvent;
6
import com.jellypudding.offlineclient.event.events.TickEvent;
7
import com.jellypudding.offlineclient.module.Category;
8
import com.jellypudding.offlineclient.module.Module;
9
import com.jellypudding.offlineclient.modules.combat.AimAssist;
10
import com.jellypudding.offlineclient.modules.misc.AntiAfk;
11
import com.jellypudding.offlineclient.render.DrawBatch;
12
import com.jellypudding.offlineclient.setting.BoolSetting;
13
import com.jellypudding.offlineclient.setting.ColorSetting;
14
import com.jellypudding.offlineclient.setting.EnumSetting;
15
import com.jellypudding.offlineclient.setting.NumberSetting;
16
import com.jellypudding.offlineclient.util.ChatUtil;
17
import com.jellypudding.offlineclient.util.ColorUtil;
18
import com.jellypudding.offlineclient.util.EntityUtil;
19
import com.jellypudding.offlineclient.util.InventoryUtil;
20
import com.jellypudding.offlineclient.util.ItemUtil;
21
import com.jellypudding.offlineclient.util.Modules;
22
import com.jellypudding.offlineclient.util.RotationManager;
23
import com.jellypudding.offlineclient.util.RotationPriority;
24
import com.jellypudding.offlineclient.util.TickRate;
25
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
26
import net.minecraft.client.player.LocalPlayer;
27
import net.minecraft.core.BlockPos;
28
import net.minecraft.network.protocol.game.ClientboundSoundPacket;
29
import net.minecraft.sounds.SoundEvents;
30
import net.minecraft.tags.FluidTags;
31
import net.minecraft.util.Mth;
32
import net.minecraft.world.InteractionHand;
33
import net.minecraft.world.entity.projectile.FishingHook;
34
import net.minecraft.world.inventory.ContainerInput;
35
import net.minecraft.world.item.FishingRodItem;
36
import net.minecraft.world.item.ItemStack;
37
import net.minecraft.world.item.enchantment.Enchantments;
38
import net.minecraft.world.phys.AABB;
39
import net.minecraft.world.phys.Vec3;
40
41
import java.util.ArrayList;
42
import java.util.Comparator;
43
import java.util.List;
44
import java.util.concurrent.ThreadLocalRandom;
45
46
// A bite is spotted from the bobber's synced flag and from the splash sound near it.
47
// The delays run at the server's tick rate. A lagging server still reels in on time.
48
public final class AutoFish extends Module {
49
50
    // Durability points left that count as about to break.
51
    private static final int NEARLY_BROKEN = 2;
52
    private static final double TICKS_PER_SECOND = 20;
53
54
    // What each enchantment level is worth when picking the best rod.
55
    private static final int LUCK_WORTH = 9;
56
    private static final int LURE_WORTH = 9;
57
    private static final int UNBREAKING_WORTH = 2;
58
59
    // A random shift is cut off at this many standard deviations.
60
    private static final double SPREAD_CUTOFF = 3;
61
62
    // How far the player may drift before a recorded spot is thrown away.
63
    private static final double SPOT_DRIFT = 0.4;
64
65
    // Two casts count as the same aim within this many degrees.
66
    private static final float SAME_AIM = 0.5f;
67
68
    public enum BiteMode {
69
        SOUND,
70
        ENTITY,
71
        BOTH
72
    }
73
74
    private final EnumSetting<BiteMode> biteMode = new EnumSetting<>("Bite mode",
75
        "Which signal is trusted to mean a fish is on the line.", BiteMode.BOTH)
76
        .describe(BiteMode.SOUND, "Only the splash sound. Safer against anti cheat.")
77
        .describe(BiteMode.ENTITY, "Only the bobber's own bite flag. More accurate.")
78
        .describe(BiteMode.BOTH, "Either signal reels the rod in.");
79
    private final NumberSetting validRange = new NumberSetting("Valid range",
80
        "How far from your bobber a splash may sound and still count as yours.",
81
        1.5, 0.25, 8, 0.25, " blocks").min(0.25)
82
        .under(biteMode, BiteMode.SOUND, BiteMode.BOTH);
83
    private final BoolSetting autoCast = new BoolSetting("Auto cast",
84
        "Casts the rod for you. Off only reels in and leaves the casting to you.", true);
85
    private final NumberSetting recastDelay = new NumberSetting("Recast delay",
86
        "Ticks to wait after reeling in before casting again.", 15, 1, 60, 1, " ticks")
87
        .under(autoCast);
88
    private final NumberSetting recastSpread = new NumberSetting("Recast spread",
89
        "The most ticks the recast delay shifts either way. The shift is random and usually small.",
90
        0, 0, 30, 1, " ticks").min(0)
91
        .under(autoCast);
92
    private final NumberSetting catchDelay = new NumberSetting("Catch delay",
93
        "Ticks to wait after a bite before reeling in.", 4, 0, 20, 1, " ticks");
94
    private final NumberSetting catchSpread = new NumberSetting("Catch spread",
95
        "The most ticks the catch delay shifts either way. Above 10 a quick bite can be missed.",
96
        0, 0, 10, 1, " ticks").min(0);
97
    private final NumberSetting retryDelay = new NumberSetting("Retry delay",
98
        "Ticks to wait after a cast or a reel in that the game refused.",
99
        15, 0, 100, 1, " ticks").min(0);
100
    private final NumberSetting patience = new NumberSetting("Patience",
101
        "Seconds to wait without a bite before reeling in and recasting.", 60, 10, 120, 1, "s");
102
    private final BoolSetting autoSwitch = new BoolSetting("Auto switch",
103
        "Move to the best fishing rod you own. The whole inventory and the offhand are searched.",
104
        true);
105
    private final BoolSetting antiBreak = new BoolSetting("Anti break",
106
        "Never use a rod that is about to break.", true);
107
    private final BoolSetting stopOutOfRods = new BoolSetting("Stop when out of rods",
108
        "Switch the module off once no usable rod is left.", false);
109
    private final BoolSetting stopWhenFull = new BoolSetting("Stop when full",
110
        "Switch the module off once your inventory has no free slot.", false);
111
    private final BoolSetting shallowWarning = new BoolSetting("Shallow water warning",
112
        "Warn in chat when the bobber is not in open water so no treasure can be caught.", true);
113
    private final BoolSetting mcmmoMode = new BoolSetting("mcMMO mode",
114
        "Cycle between two fishing spots so the mcMMO overfishing penalty never starts.", false);
115
    private final NumberSetting mcmmoRange = new NumberSetting("mcMMO range",
116
        "The MoveRange value of the plugin. The least distance between the two spots.",
117
        3, 1, 50, 1, " blocks").min(1)
118
        .under(mcmmoMode);
119
    private final BoolSetting mcmmoRangeBug = new BoolSetting("mcMMO range bug",
120
        "Round the range down to an even number the way the plugin's own check does.", true)
121
        .under(mcmmoMode);
122
    private final NumberSetting mcmmoLimit = new NumberSetting("mcMMO limit",
123
        "The OverFishLimit value of the plugin. Fish taken from one spot before switching.",
124
        10, 2, 1000, 1, "").min(2)
125
        .under(mcmmoMode);
126
    private final BoolSetting debugDraw = new BoolSetting("Debug draw",
127
        "Draw the valid range around the bobber and every splash you hear.", false);
128
    private final ColorSetting debugColor = new ColorSetting("Debug colour",
129
        "Colour of the debug drawing.", 0, 0.79f, 0.88f, false)
130
        .under(debugDraw);
131
132
    private final InventoryUtil.HotbarLoan loan = new InventoryUtil.HotbarLoan();
133
    private double castTimer;
134
    private boolean reeling;
135
    private double reelTimer;
136
    private int patienceTimer;
137
    // Written from the packet thread.
138
    private volatile boolean splashHeard;
139
    private volatile Vec3 lastSoundPos;
140
    // Holding the bobber itself would pin the world.
141
    private int reeledId = -1;
142
    private int caught;
143
    private boolean outOfRods;
144
    private boolean warnedShallow;
145
146
    // One cast of the rod. The bobber lands where the aim sent it.
147
    private record Spot(Vec3 playerPos, float yaw, float pitch, Vec3 bobberPos) {
148
    }
149
150
    private final List<Spot> spots = new ArrayList<>();
151
    private Spot lastSpot;
152
    private Spot nextSpot;
153
    private Vec3 castPos = Vec3.ZERO;
154
    private float castYaw;
155
    private float castPitch;
156
    private int caughtAtSpot;
157
    private boolean askedForSpot;
158
    private boolean toldToWait;
159
    private boolean toldReady;
160
161
    public AutoFish() {
162
        super("AutoFish", "Casts and reels the fishing rod for you.", Category.PLAYER);
163
        addSettings(biteMode, validRange, autoCast, recastDelay, recastSpread, catchDelay,
164
            catchSpread, retryDelay, patience, autoSwitch, antiBreak, stopOutOfRods,
165
            stopWhenFull, shallowWarning, mcmmoMode, mcmmoRange, mcmmoRangeBug, mcmmoLimit,
166
            debugDraw, debugColor);
167
        searchTags("fishing", "afk fish", "rod", "mcmmo");
168
    }
169
170
    @Override
171
    public String getSuffix() {
172
        return outOfRods ? "out of rods" : caught + " caught";
173
    }
174
175
    @Override
176
    protected void onDisable() {
177
        loan.giveBack();
178
        spots.clear();
179
    }
180
181
    @Override
182
    protected void onEnable() {
183
        castTimer = 0;
184
        reeling = false;
185
        patienceTimer = 0;
186
        splashHeard = false;
187
        lastSoundPos = null;
188
        reeledId = -1;
189
        caught = 0;
190
        outOfRods = false;
191
        warnedShallow = false;
192
        resetSpots();
193
        // Both of these fight the rod for the view and the use key.
194
        AntiAfk antiAfk = Modules.active(AntiAfk.class);
195
        if (antiAfk != null) {
196
            antiAfk.setEnabled(false);
197
        }
198
        AimAssist aimAssist = Modules.active(AimAssist.class);
199
        if (aimAssist != null) {
200
            aimAssist.setEnabled(false);
201
        }
202
    }
203
204
    @Subscribe
205
    private void onTick(TickEvent event) {
206
        if (!inGame() || mc.player.isSpectator()) {
207
            return;
208
        }
209
        if (castTimer > 0) {
210
            castTimer -= serverTick();
211
        }
212
        if (mc.gui.screen() != null) {
213
            return;
214
        }
215
        if (!pickRod()) {
216
            return;
217
        }
218
        ItemStack held = mc.player.getMainHandItem();
219
        if (!(held.getItem() instanceof FishingRodItem)) {
220
            return;
221
        }
222
        // Reeling in wears the rod down as much as casting does.
223
        if (antiBreak.isOn() && ItemUtil.nearlyBroken(held, NEARLY_BROKEN)) {
224
            return;
225
        }
226
227
        FishingHook bobber = mc.player.fishing;
228
        if (bobber == null || bobber.isRemoved()) {
229
            tryCast();
230
            return;
231
        }
232
        // The old bobber lingers for a tick or two after reeling.
233
        if (bobber.getId() == reeledId) {
234
            return;
235
        }
236
        tryReel(bobber);
237
    }
238
239
    // The patience clock is wound whilst no bobber is out. A cast made by
240
    // hand is timed the same as one made here.
241
    private void tryCast() {
242
        reeling = false;
243
        splashHeard = false;
244
        reeledId = -1;
245
        patienceTimer = patience.getInt() * 20;
246
        if (!autoCast.isOn() || castTimer > 0) {
247
            return;
248
        }
249
        if (!readyToCast()) {
250
            return;
251
        }
252
        castTimer = useRod() ? shifted(recastDelay.getInt(), recastSpread.getInt())
253
            : retryDelay.getInt();
254
    }
255
256
    private void tryReel(FishingHook bobber) {
257
        boolean bite = bitten(bobber);
258
        if (bite && !reeling) {
259
            reeling = true;
260
            reelTimer = shifted(catchDelay.getInt(), catchSpread.getInt());
261
            checkWater(bobber);
262
            recordSpot(bobber);
263
        }
264
        if (!reeling && patienceTimer > 0) {
265
            patienceTimer--;
266
            if (patienceTimer == 0) {
267
                reeling = true;
268
                reelTimer = 0;
269
            }
270
        }
271
        if (!reeling) {
272
            return;
273
        }
274
        if (reelTimer > 0) {
275
            reelTimer -= serverTick();
276
            return;
277
        }
278
279
        if (!useRod()) {
280
            reelTimer = retryDelay.getInt();
281
            return;
282
        }
283
        if (bite) {
284
            caught++;
285
        }
286
        reeledId = bobber.getId();
287
        reeling = false;
288
        splashHeard = false;
289
        castTimer = shifted(recastDelay.getInt(), recastSpread.getInt());
290
    }
291
292
    private boolean bitten(FishingHook bobber) {
293
        boolean entity = bobber.biting || bobber.getHookedIn() != null;
294
        return switch (biteMode.getValue()) {
295
            case SOUND -> splashHeard;
296
            case ENTITY -> entity;
297
            case BOTH -> entity || splashHeard;
298
        };
299
    }
300
301
    @Subscribe
302
    private void onPacketReceive(PacketReceiveEvent event) {
303
        if (biteMode.is(BiteMode.ENTITY)) {
304
            return;
305
        }
306
        if (!(event.getPacket() instanceof ClientboundSoundPacket sound)) {
307
            return;
308
        }
309
        if (sound.getSound().value() != SoundEvents.FISHING_BOBBER_SPLASH) {
310
            return;
311
        }
312
        // The packet thread can drop the player mid handler.
313
        LocalPlayer player = mc.player;
314
        FishingHook bobber = player == null ? null : player.fishing;
315
        if (bobber == null || bobber.isRemoved()) {
316
            return;
317
        }
318
        lastSoundPos = new Vec3(sound.getX(), sound.getY(), sound.getZ());
319
        // Someone else's bobber can splash nearby.
320
        double dx = Math.abs(sound.getX() - bobber.getX());
321
        double dz = Math.abs(sound.getZ() - bobber.getZ());
322
        if (Math.max(dx, dz) <= validRange.getValue()) {
323
            splashHeard = true;
324
        }
325
    }
326
327
    private boolean useRod() {
328
        MultiPlayerGameMode gameMode = mc.gameMode;
329
        if (gameMode == null) {
330
            return false;
331
        }
332
        if (!gameMode.useItem(mc.player, InteractionHand.MAIN_HAND).consumesAction()) {
333
            return false;
334
        }
335
        mc.player.swing(InteractionHand.MAIN_HAND);
336
        return true;
337
    }
338
339
    // How much of a server tick one client tick is worth.
340
    private static double serverTick() {
341
        return TickRate.INSTANCE.tps() / TICKS_PER_SECOND;
342
    }
343
344
    // The delay shifted by a random amount that is usually small and never
345
    // more than the spread either way.
346
    private static double shifted(int delay, int spread) {
347
        if (spread == 0) {
348
            return delay;
349
        }
350
        double normal = ThreadLocalRandom.current().nextGaussian();
351
        double share = Math.clamp(normal, -SPREAD_CUTOFF, SPREAD_CUTOFF) / SPREAD_CUTOFF;
352
        return Math.max(0, delay + Math.round(share * spread));
353
    }
354
355
    // False whilst the hand is busy or the rod moved this tick.
356
    private boolean pickRod() {
357
        if (Modules.eating()) {
358
            return false;
359
        }
360
        int best = -1;
361
        int bestScore = -1;
362
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
363
            int score = rodScore(mc.player.getInventory().getItem(i));
364
            if (score > bestScore) {
365
                bestScore = score;
366
                best = i;
367
            }
368
        }
369
        if (rodScore(mc.player.getOffhandItem()) > bestScore) {
370
            best = InventoryUtil.OFFHAND_SLOT;
371
        }
372
        outOfRods = best == -1;
373
        if (outOfRods && stopOutOfRods.isOn()) {
374
            ChatUtil.message("AutoFish has run out of rods.");
375
            setEnabled(false);
376
            return false;
377
        }
378
        if (stopWhenFull.isOn() && mc.player.getInventory().getFreeSlot() == -1) {
379
            ChatUtil.message("AutoFish has stopped because your inventory is full.");
380
            setEnabled(false);
381
            return false;
382
        }
383
        if (!autoSwitch.isOn() || best == -1) {
384
            return true;
385
        }
386
        if (best == InventoryUtil.OFFHAND_SLOT) {
387
            return borrowOffhand();
388
        }
389
        int before = InventoryUtil.selectedSlot();
390
        return loan.select(best) && InventoryUtil.selectedSlot() == before;
391
    }
392
393
    // Minus one when the stack is no rod or no rod worth using.
394
    private int rodScore(ItemStack stack) {
395
        if (!(stack.getItem() instanceof FishingRodItem)) {
396
            return -1;
397
        }
398
        if (antiBreak.isOn() && ItemUtil.nearlyBroken(stack, NEARLY_BROKEN)) {
399
            return -1;
400
        }
401
        int keeps = ItemUtil.enchantLevel(Enchantments.VANISHING_CURSE, stack) == 0 ? 1 : 0;
402
        return ItemUtil.enchantLevel(Enchantments.LUCK_OF_THE_SEA, stack) * LUCK_WORTH
403
            + ItemUtil.enchantLevel(Enchantments.LURE, stack) * LURE_WORTH
404
            + ItemUtil.enchantLevel(Enchantments.UNBREAKING, stack) * UNBREAKING_WORTH
405
            + ItemUtil.enchantLevel(Enchantments.MENDING, stack)
406
            + keeps;
407
    }
408
409
    // Swaps the offhand rod into the hotbar. Always waits a tick afterwards.
410
    private boolean borrowOffhand() {
411
        if (!InventoryUtil.canClick() || !InventoryUtil.carried().isEmpty()) {
412
            return false;
413
        }
414
        int hotbar = InventoryUtil.freeHotbarSlot(InventoryUtil.selectedSlot());
415
        mc.gameMode.handleContainerInput(0, InventoryUtil.OFFHAND_SLOT, hotbar,
416
            ContainerInput.SWAP, mc.player);
417
        mc.player.getInventory().setSelectedSlot(hotbar);
418
        return false;
419
    }
420
421
    private void checkWater(FishingHook bobber) {
422
        if (openWater(bobber)) {
423
            warnedShallow = false;
424
            return;
425
        }
426
        if (!shallowWarning.isOn() || warnedShallow) {
427
            return;
428
        }
429
        ChatUtil.message("You are fishing in shallow water.");
430
        ChatUtil.message("No treasure can be caught like this. Use OpenWaterESP to find deeper water.");
431
        warnedShallow = true;
432
    }
433
434
    // A bobber riding high sits in the air block above the water it floats on.
435
    private boolean openWater(FishingHook bobber) {
436
        BlockPos pos = bobber.blockPosition();
437
        if (!mc.level.getFluidState(pos).is(FluidTags.WATER)) {
438
            BlockPos below = pos.below();
439
            if (mc.level.getFluidState(below).is(FluidTags.WATER)) {
440
                pos = below;
441
            }
442
        }
443
        return bobber.calculateOpenWater(pos);
444
    }
445
446
    private void resetSpots() {
447
        spots.clear();
448
        lastSpot = null;
449
        nextSpot = null;
450
        castPos = Vec3.ZERO;
451
        castYaw = 0;
452
        castPitch = 0;
453
        caughtAtSpot = 0;
454
        askedForSpot = false;
455
        toldToWait = false;
456
        toldReady = false;
457
    }
458
459
    // Remembers where this cast is aimed and turns towards the next spot when
460
    // the current one has given up its share of the fish.
461
    private boolean readyToCast() {
462
        castPos = mc.player.position();
463
        castYaw = mc.player.getYRot();
464
        castPitch = mc.player.getXRot();
465
        if (!mcmmoMode.isOn()) {
466
            return true;
467
        }
468
        if (lastSpot == null) {
469
            if (!toldToWait) {
470
                ChatUtil.message("Starting mcMMO mode. Wait whilst the first spot is recorded.");
471
                toldToWait = true;
472
            }
473
            return true;
474
        }
475
        toldToWait = false;
476
        if (caughtAtSpot < mcmmoLimit.getInt() - 1) {
477
            return true;
478
        }
479
        if (nextSpot == null) {
480
            nextSpot = chooseNextSpot();
481
        }
482
        if (nextSpot == null) {
483
            if (!askedForSpot) {
484
                ChatUtil.message("mcMMO mode needs a second fishing spot.");
485
                ChatUtil.message("Aim so the bobber lands outside the box then cast by hand.");
486
                askedForSpot = true;
487
                toldReady = false;
488
            }
489
            return false;
490
        }
491
        askedForSpot = false;
492
        return turnToNextSpot();
493
    }
494
495
    // False whilst the view is still swinging round or the spot has gone stale.
496
    private boolean turnToNextSpot() {
497
        if (mc.player.position().distanceToSqr(nextSpot.playerPos()) > SPOT_DRIFT * SPOT_DRIFT) {
498
            spots.remove(nextSpot);
499
            nextSpot = null;
500
            return false;
501
        }
502
        RotationManager.requestExact(nextSpot.yaw(), nextSpot.pitch(), RotationPriority.IDLE);
503
        if (!RotationManager.sentIsFacing(nextSpot.yaw(), nextSpot.pitch(), SAME_AIM)) {
504
            return false;
505
        }
506
        castYaw = nextSpot.yaw();
507
        castPitch = nextSpot.pitch();
508
        lastSpot = nextSpot;
509
        nextSpot = null;
510
        caughtAtSpot = 0;
511
        if (!toldReady) {
512
            ChatUtil.message("Both spots are set. AutoFish will switch between them.");
513
            toldReady = true;
514
        }
515
        return true;
516
    }
517
518
    private void recordSpot(FishingHook bobber) {
519
        if (!mcmmoMode.isOn()) {
520
            return;
521
        }
522
        boolean sameAim = lastSpot != null && sameAim(lastSpot);
523
        boolean sameWater = lastSpot != null && inRange(lastSpot.bobberPos(), bobber.position());
524
        caughtAtSpot = sameWater ? caughtAtSpot + 1 : 1;
525
        if (!sameAim) {
526
            lastSpot = new Spot(castPos, castYaw, castPitch, bobber.position());
527
            spots.add(lastSpot);
528
            return;
529
        }
530
        if (!sameWater) {
531
            // The same aim landed somewhere new. The old note was wrong.
532
            Spot fixed = new Spot(lastSpot.playerPos(), lastSpot.yaw(), lastSpot.pitch(),
533
                bobber.position());
534
            spots.remove(lastSpot);
535
            spots.add(fixed);
536
            lastSpot = fixed;
537
        }
538
    }
539
540
    private boolean sameAim(Spot spot) {
541
        return Mth.degreesDifferenceAbs(spot.yaw(), castYaw) <= SAME_AIM
542
            && Math.abs(spot.pitch() - castPitch) <= SAME_AIM
543
            && spot.playerPos().distanceToSqr(castPos) <= SPOT_DRIFT * SPOT_DRIFT;
544
    }
545
546
    // The nearest aim that lands the bobber clear of the spot in use.
547
    private Spot chooseNextSpot() {
548
        Vec3 here = mc.player.position();
549
        return spots.stream()
550
            .filter(spot -> spot != lastSpot)
551
            .filter(spot -> spot.playerPos().distanceToSqr(here) <= SPOT_DRIFT * SPOT_DRIFT)
552
            .filter(spot -> !inRange(spot.bobberPos(), lastSpot.bobberPos()))
553
            .min(Comparator.comparingDouble(spot -> Mth.degreesDifferenceAbs(spot.yaw(),
554
                lastSpot.yaw()) + Math.abs(spot.pitch() - lastSpot.pitch())))
555
            .orElse(null);
556
    }
557
558
    private boolean inRange(Vec3 first, Vec3 second) {
559
        if (Math.abs(first.y - second.y) > 2) {
560
            return false;
561
        }
562
        double dx = Math.abs(first.x - second.x);
563
        double dz = Math.abs(first.z - second.z);
564
        return Math.max(dx, dz) <= spotRange();
565
    }
566
567
    // The plugin measures the range in whole even blocks whilst the bug stands.
568
    private int spotRange() {
569
        return mcmmoRangeBug.isOn() ? mcmmoRange.getInt() / 2 * 2 : mcmmoRange.getInt();
570
    }
571
572
    @Subscribe
573
    private void onRender3D(Render3DEvent event) {
574
        if (!inGame()) {
575
            return;
576
        }
577
        if (debugDraw.isOn()) {
578
            drawDebug(event.getBatch(), event.getPartialTicks());
579
        }
580
        if (mcmmoMode.isOn() && lastSpot != null && (nextSpot == null || debugDraw.isOn())) {
581
            drawSpotRange(event.getBatch());
582
        }
583
    }
584
585
    private void drawDebug(DrawBatch batch, float partialTicks) {
586
        int colour = debugColor.getColor();
587
        FishingHook bobber = mc.player.fishing;
588
        if (bobber != null && !bobber.isRemoved()) {
589
            double range = validRange.getValue();
590
            Vec3 pos = EntityUtil.lerpedBox(bobber, partialTicks).getCenter();
591
            batch.outlineBox(new AABB(-range, -0.0625, -range, range, 0.0625, range).move(pos),
592
                colour, false);
593
        }
594
        Vec3 sound = lastSoundPos;
595
        if (sound != null) {
596
            batch.line(sound.add(-0.125, 0, -0.125), sound.add(0.125, 0, 0.125), colour, false);
597
            batch.line(sound.add(0.125, 0, -0.125), sound.add(-0.125, 0, 0.125), colour, false);
598
        }
599
        for (Spot spot : spots) {
600
            batch.outlineBox(new AABB(spot.bobberPos(), spot.bobberPos()).inflate(0.2),
601
                colour, false);
602
            batch.line(spot.playerPos().add(0, mc.player.getEyeHeight(), 0), spot.bobberPos(),
603
                colour, false);
604
        }
605
    }
606
607
    private void drawSpotRange(DrawBatch batch) {
608
        int colour = debugColor.getColor();
609
        int range = spotRange();
610
        AABB box = new AABB(lastSpot.bobberPos(), lastSpot.bobberPos()).inflate(range, 1, range);
611
        batch.solidBox(box, ColorUtil.withAlpha(colour, 64), false);
612
        batch.outlineBox(box, colour, false);
613
    }
614
}
615
NicotinePlayersrc/client/java/nicotine/mod/mods/player/AutoFish.javaJava · 30 lines · 676 B
AutoFish.javaJava · Minecraft 26.3 · 30 lines · 676 B · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.player;
2
3
import nicotine.events.CaughtFishEvent;
4
import nicotine.mod.Mod;
5
import nicotine.mod.ModCategory;
6
import nicotine.util.EventBus;
7
8
import static nicotine.util.Common.mc;
9
10
public class AutoFish extends Mod {
11
12
    public AutoFish() {
13
        super(ModCategory.Player, "AutoFish");
14
    }
15
16
    @Override
17
    protected void init() {
18
        EventBus.register(CaughtFishEvent.class, event -> {
19
            if (!this.enabled)
20
                return true;
21
22
            mc.gameMode.useItem(mc.player, mc.player.getUsedItemHand());
23
            mc.gameMode.useItem(mc.player, mc.player.getUsedItemHand());
24
25
            return true;
26
        });
27
28
    }
29
}
30
Goon ClientPlayersrc/main/java/com/pendonym/module/player/AutoFish.javaJava · 13 lines · 292 B
AutoFish.javaJava · Minecraft 26.2 · 13 lines · 292 B · complete file, verbatim
1
package com.pendonym.module.player;
2
3
import com.pendonym.module.Module;
4
5
@Module.Info(name = "key.module.goon.auto_fish", category = "Player")
6
public class AutoFish extends Module {
7
    public static final AutoFish INSTANCE = new AutoFish();
8
9
    @Override
10
    public void onTick() {
11
12
    }
13
}
LiquidBounce (Kotlin)PLAYERsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/player/ModuleAutoFish.ktKotlin · 151 lines · 5.0 KB

Automatically catches fish when using a rod.

SettingsReelDelayDelaySoundsMaxDistance
ModuleAutoFish.ktKotlin · Minecraft 26.2 · 151 lines · 5.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
20
21
import net.ccbluex.fastutil.objectRBTreeSetOf
22
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
23
import net.ccbluex.liquidbounce.event.events.PacketEvent
24
import net.ccbluex.liquidbounce.event.handler
25
import net.ccbluex.liquidbounce.event.tickHandler
26
import net.ccbluex.liquidbounce.event.tickUntil
27
import net.ccbluex.liquidbounce.event.waitTicks
28
import net.ccbluex.liquidbounce.features.module.ClientModule
29
import net.ccbluex.liquidbounce.features.module.ModuleCategories
30
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug.debugParameter
31
import net.ccbluex.liquidbounce.utils.collection.asComparator
32
import net.ccbluex.liquidbounce.utils.entity.useItem
33
import net.ccbluex.liquidbounce.utils.math.sq
34
import net.minecraft.core.registries.BuiltInRegistries
35
import net.minecraft.network.protocol.game.ClientboundSoundPacket
36
import net.minecraft.network.protocol.game.ServerboundUseItemPacket
37
import net.minecraft.sounds.SoundEvents
38
import net.minecraft.world.InteractionHand
39
import net.minecraft.world.item.FishingRodItem
40
41
/**
42
 * AutoFish module
43
 *
44
 * Automatically catches fish when using a rod.
45
 */
46
47
object ModuleAutoFish : ClientModule("AutoFish", ModuleCategories.PLAYER) {
48
49
    private val reelDelay by intRange("ReelDelay", 5..8, 0..20, "ticks")
50
51
    private object RecastRod : ToggleableValueGroup(this, "RecastRod", true) {
52
        val delay by intRange("Delay", 15..20, 10..30, "ticks")
53
    }
54
55
    private object AutoCastRod : ToggleableValueGroup(this, "AutoCastRod", false) {
56
        val delay by intRange("Delay", 15..20, 0..30, "ticks")
57
    }
58
59
    /**
60
     * Usually we only require [SoundEvents.FISHING_BOBBER_SPLASH]
61
     * to trigger the pull, but if a server has a custom sound,
62
     * we might want to add it here.
63
     */
64
    private val sounds by sounds(
65
        "Sounds", objectRBTreeSetOf(
66
            BuiltInRegistries.SOUND_EVENT.asComparator(),
67
            SoundEvents.FISHING_BOBBER_SPLASH,
68
        )
69
    )
70
71
    /**
72
     * This is useful to prevent false triggers when the sound is played
73
     * from a different position than our fishing hook.
74
     */
75
    private object PullTriggerSoundDistance : ToggleableValueGroup(
76
        this,
77
        "SoundDistance",
78
        true
79
    ) {
80
        val distance by float("MaxDistance", 1.0f, 0.0f..10.0f, "blocks")
81
    }
82
83
    init {
84
        tree(PullTriggerSoundDistance)
85
        tree(RecastRod)
86
        tree(AutoCastRod)
87
    }
88
89
    private var caughtFish = false
90
91
    override fun onDisabled() {
92
        caughtFish = false
93
    }
94
95
    private fun findFishingRodHand() = InteractionHand.entries.find {
96
        player.getItemInHand(it).item is FishingRodItem
97
    }
98
99
    private fun activeFishingHook() = player.fishing?.takeIf { !it.isRemoved }
100
101
    @Suppress("unused")
102
    private val tickHandler = tickHandler {
103
        val hand = findFishingRodHand() ?: return@tickHandler
104
105
        tickUntil {
106
            caughtFish || activeFishingHook() == null
107
        }
108
109
        if (caughtFish) {
110
            caughtFish = false
111
112
            waitTicks(reelDelay.random())
113
            useItem(hand)
114
115
            if (RecastRod.enabled) {
116
                waitTicks(RecastRod.delay.random())
117
                useItem(hand)
118
            }
119
120
            return@tickHandler
121
        }
122
123
        if (AutoCastRod.enabled && activeFishingHook() == null) {
124
            waitTicks(AutoCastRod.delay.random())
125
            useItem(hand)
126
        }
127
    }
128
129
    @Suppress("unused")
130
    private val packetHandler = handler<PacketEvent> { event ->
131
        val packet = event.packet
132
        val fishHook = activeFishingHook() ?: return@handler
133
134
        if (packet is ClientboundSoundPacket && packet.sound.value() in sounds) {
135
            if (PullTriggerSoundDistance.running) {
136
                val hookToSoundSq = fishHook.position().distanceToSqr(packet.x, packet.y, packet.z)
137
                debugParameter("HookToSoundSq") { hookToSoundSq }
138
139
                // From my testing, we should see distances around 0.04 - 0.08 (Paper version 1.21.1-132)
140
                // so a threshold of 1.0 should be more than enough.
141
                if (hookToSoundSq > PullTriggerSoundDistance.distance.sq()) {
142
                    return@handler
143
                }
144
            }
145
146
            caughtFish = true
147
        }
148
    }
149
150
}
151