AutoFarm module

AutoFarm: Minecraft 26.3 cheat module, full source for every implementation (2 clients: OfflineClient, LiquidBounce (Kotlin)).

2 implementationsWORLD

Full module source: 2 implementations

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

OfflineClientWORLDsrc/main/java/com/jellypudding/offlineclient/modules/world/AutoFarm.javaJava · 732 lines · 30.0 KB

Harvests the ripe crops in reach and replants them.

SettingsRangeHarvestHarvest plantsReplantReplant plantsBonemealBlocks per tickLine of sightDraw spotsSpot colourDraw harvestHarvest colourDraw replantReplant colour
AutoFarm.javaJava · Minecraft 26.2 · 732 lines · 30.0 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.world;
2
3
import com.jellypudding.offlineclient.OfflineClient;
4
import com.jellypudding.offlineclient.event.Subscribe;
5
import com.jellypudding.offlineclient.event.events.Render3DEvent;
6
import com.jellypudding.offlineclient.event.events.TickEvent;
7
import com.jellypudding.offlineclient.mixin.MultiPlayerGameModeAccessor;
8
import com.jellypudding.offlineclient.module.Category;
9
import com.jellypudding.offlineclient.module.ExclusivityGroup;
10
import com.jellypudding.offlineclient.module.Module;
11
import com.jellypudding.offlineclient.render.DrawBatch;
12
import com.jellypudding.offlineclient.setting.BoolSetting;
13
import com.jellypudding.offlineclient.setting.ChoiceListSetting;
14
import com.jellypudding.offlineclient.setting.ColorSetting;
15
import com.jellypudding.offlineclient.setting.EnumSetting;
16
import com.jellypudding.offlineclient.setting.NumberSetting;
17
import com.jellypudding.offlineclient.util.BlockMiner;
18
import com.jellypudding.offlineclient.util.BlockUtil;
19
import com.jellypudding.offlineclient.util.FaceMode;
20
import com.jellypudding.offlineclient.util.InputUtil;
21
import com.jellypudding.offlineclient.util.InventoryUtil;
22
import com.jellypudding.offlineclient.util.RotationPriority;
23
import com.jellypudding.offlineclient.util.SwingMode;
24
import net.minecraft.core.BlockPos;
25
import net.minecraft.core.Direction;
26
import net.minecraft.tags.BlockTags;
27
import net.minecraft.tags.FluidTags;
28
import net.minecraft.world.InteractionHand;
29
import net.minecraft.world.item.Item;
30
import net.minecraft.world.item.ItemStack;
31
import net.minecraft.world.item.Items;
32
import net.minecraft.world.level.block.Blocks;
33
import net.minecraft.world.level.block.CaveVines;
34
import net.minecraft.world.level.block.ChorusFlowerBlock;
35
import net.minecraft.world.level.block.CocoaBlock;
36
import net.minecraft.world.level.block.CropBlock;
37
import net.minecraft.world.level.block.NetherWartBlock;
38
import net.minecraft.world.level.block.PipeBlock;
39
import net.minecraft.world.level.block.PitcherCropBlock;
40
import net.minecraft.world.level.block.SeaPickleBlock;
41
import net.minecraft.world.level.block.SweetBerryBushBlock;
42
import net.minecraft.world.level.block.state.BlockState;
43
import net.minecraft.world.level.block.state.properties.DoubleBlockHalf;
44
import net.minecraft.world.level.material.FluidState;
45
import net.minecraft.world.phys.AABB;
46
import net.minecraft.world.phys.Vec3;
47
48
import java.util.ArrayList;
49
import java.util.HashMap;
50
import java.util.HashSet;
51
import java.util.List;
52
import java.util.Map;
53
import java.util.Set;
54
import java.util.function.Predicate;
55
56
// Cuts the ripe crops around you and puts the seeds back in the ground. It
57
// never walks anywhere and only farms what is already in reach.
58
public final class AutoFarm extends Module {
59
60
    // A block test that needs the state as well as the position.
61
    private interface PlantTest {
62
        boolean matches(BlockPos pos, BlockState state);
63
    }
64
65
    // One kind of plant. The spot test marks where a seed belongs and the mine
66
    // and interact tests say when the grown part is ready to take.
67
    private record Plant(String name, Item seed, PlantTest spot, Predicate<BlockPos> surface,
68
                         PlantTest mine, PlantTest interact) {
69
    }
70
71
    private static final PlantTest NEVER = (pos, state) -> false;
72
73
    private static final List<Plant> PLANTS = List.of(
74
        new Plant("Amethyst", Items.BUDDING_AMETHYST,
75
            (pos, state) -> state.is(Blocks.BUDDING_AMETHYST), pos -> true,
76
            (pos, state) -> state.is(Blocks.AMETHYST_CLUSTER), NEVER),
77
        new Plant("Bamboo", Items.BAMBOO,
78
            (pos, state) -> (state.is(Blocks.BAMBOO) || state.is(Blocks.BAMBOO_SAPLING))
79
                && !below(pos).is(Blocks.BAMBOO) && !below(pos).is(Blocks.BAMBOO_SAPLING)
80
                && below(pos).is(BlockTags.SUPPORTS_BAMBOO),
81
            pos -> below(pos).is(BlockTags.SUPPORTS_BAMBOO),
82
            (pos, state) -> state.is(Blocks.BAMBOO) && isSpot("Bamboo", pos.below()), NEVER),
83
        new Plant("Beetroots", Items.BEETROOT_SEEDS,
84
            (pos, state) -> state.is(Blocks.BEETROOTS), AutoFarm::cropSurface,
85
            AutoFarm::ripeCrop, NEVER),
86
        new Plant("Cactus", Items.CACTUS,
87
            (pos, state) -> state.is(Blocks.CACTUS) && !below(pos).is(Blocks.CACTUS)
88
                && cactusSurface(pos),
89
            AutoFarm::cactusSurface,
90
            (pos, state) -> (state.is(Blocks.CACTUS) || state.is(Blocks.CACTUS_FLOWER))
91
                && isSpot("Cactus", pos.below()), NEVER),
92
        new Plant("Carrots", Items.CARROT,
93
            (pos, state) -> state.is(Blocks.CARROTS), AutoFarm::cropSurface,
94
            AutoFarm::ripeCrop, NEVER),
95
        new Plant("Chorus plants", Items.CHORUS_FLOWER,
96
            (pos, state) -> (state.is(Blocks.CHORUS_FLOWER) || state.is(Blocks.CHORUS_PLANT))
97
                && below(pos).is(BlockTags.SUPPORTS_CHORUS_FLOWER),
98
            pos -> below(pos).is(BlockTags.SUPPORTS_CHORUS_FLOWER),
99
            AutoFarm::ripeChorus, NEVER),
100
        new Plant("Cocoa beans", Items.COCOA_BEANS,
101
            (pos, state) -> state.getBlock() instanceof CocoaBlock, AutoFarm::cocoaSurface,
102
            (pos, state) -> state.getBlock() instanceof CocoaBlock
103
                && state.getValue(CocoaBlock.AGE) >= CocoaBlock.MAX_AGE, NEVER),
104
        new Plant("Glow berries", Items.GLOW_BERRIES,
105
            (pos, state) -> state.getBlock() instanceof CaveVines && vineCeiling(pos),
106
            AutoFarm::vineCeiling,
107
            (pos, state) -> state.getBlock() instanceof CaveVines && !vineCeiling(pos),
108
            (pos, state) -> state.getBlock() instanceof CaveVines
109
                && CaveVines.hasGlowBerries(state) && vineCeiling(pos)),
110
        new Plant("Kelp", Items.KELP,
111
            (pos, state) -> (state.is(Blocks.KELP) || state.is(Blocks.KELP_PLANT))
112
                && !below(pos).is(Blocks.KELP) && !below(pos).is(Blocks.KELP_PLANT)
113
                && kelpSurface(pos),
114
            AutoFarm::kelpSurface,
115
            (pos, state) -> (state.is(Blocks.KELP) || state.is(Blocks.KELP_PLANT))
116
                && isSpot("Kelp", pos.below()), NEVER),
117
        new Plant("Melons", Items.MELON_SEEDS,
118
            (pos, state) -> state.is(Blocks.MELON_STEM) || state.is(Blocks.ATTACHED_MELON_STEM),
119
            pos -> below(pos).is(BlockTags.SUPPORTS_MELON_STEM),
120
            (pos, state) -> state.is(Blocks.MELON), NEVER),
121
        new Plant("Nether wart", Items.NETHER_WART,
122
            (pos, state) -> state.getBlock() instanceof NetherWartBlock,
123
            pos -> below(pos).is(BlockTags.SUPPORTS_NETHER_WART),
124
            (pos, state) -> state.getBlock() instanceof NetherWartBlock
125
                && state.getValue(NetherWartBlock.AGE) >= NetherWartBlock.MAX_AGE, NEVER),
126
        new Plant("Pitcher plants", Items.PITCHER_POD,
127
            (pos, state) -> state.is(Blocks.PITCHER_CROP)
128
                && state.getValue(PitcherCropBlock.HALF) == DoubleBlockHalf.LOWER
129
                && cropSurface(pos),
130
            AutoFarm::cropSurface,
131
            (pos, state) -> state.is(Blocks.PITCHER_CROP)
132
                && state.getValue(PitcherCropBlock.AGE) >= PitcherCropBlock.MAX_AGE, NEVER),
133
        new Plant("Potatoes", Items.POTATO,
134
            (pos, state) -> state.is(Blocks.POTATOES), AutoFarm::cropSurface,
135
            AutoFarm::ripeCrop, NEVER),
136
        new Plant("Pumpkins", Items.PUMPKIN_SEEDS,
137
            (pos, state) -> state.is(Blocks.PUMPKIN_STEM) || state.is(Blocks.ATTACHED_PUMPKIN_STEM),
138
            pos -> below(pos).is(BlockTags.SUPPORTS_PUMPKIN_STEM),
139
            (pos, state) -> state.is(Blocks.PUMPKIN), NEVER),
140
        new Plant("Sea pickles", Items.SEA_PICKLE,
141
            (pos, state) -> state.getBlock() instanceof SeaPickleBlock && pickleSurface(pos),
142
            AutoFarm::pickleSurface,
143
            (pos, state) -> state.getBlock() instanceof SeaPickleBlock
144
                && state.getValue(SeaPickleBlock.PICKLES) > 1, NEVER),
145
        new Plant("Sugar cane", Items.SUGAR_CANE,
146
            (pos, state) -> state.is(Blocks.SUGAR_CANE) && !below(pos).is(Blocks.SUGAR_CANE)
147
                && caneSurface(pos),
148
            AutoFarm::caneSurface,
149
            (pos, state) -> state.is(Blocks.SUGAR_CANE) && isSpot("Sugar cane", pos.below()),
150
            NEVER),
151
        new Plant("Sweet berries", Items.SWEET_BERRIES,
152
            (pos, state) -> state.getBlock() instanceof SweetBerryBushBlock && berrySurface(pos),
153
            AutoFarm::berrySurface, NEVER,
154
            (pos, state) -> state.getBlock() instanceof SweetBerryBushBlock
155
                && state.getValue(SweetBerryBushBlock.AGE) > 1),
156
        new Plant("Torchflowers", Items.TORCHFLOWER_SEEDS,
157
            (pos, state) -> (state.is(Blocks.TORCHFLOWER) || state.is(Blocks.TORCHFLOWER_CROP))
158
                && cropSurface(pos),
159
            AutoFarm::cropSurface,
160
            (pos, state) -> state.is(Blocks.TORCHFLOWER), NEVER),
161
        new Plant("Twisting vines", Items.TWISTING_VINES,
162
            (pos, state) -> isTwisting(state) && twistingFloor(pos), AutoFarm::twistingFloor,
163
            (pos, state) -> isTwisting(state) && !twistingFloor(pos), NEVER),
164
        new Plant("Weeping vines", Items.WEEPING_VINES,
165
            (pos, state) -> isWeeping(state) && weepingCeiling(pos), AutoFarm::weepingCeiling,
166
            (pos, state) -> isWeeping(state) && !weepingCeiling(pos), NEVER),
167
        new Plant("Wheat", Items.WHEAT_SEEDS,
168
            (pos, state) -> state.is(Blocks.WHEAT), AutoFarm::cropSurface,
169
            AutoFarm::ripeCrop, NEVER));
170
171
    private static final List<String> PLANT_NAMES = PLANTS.stream().map(Plant::name).toList();
172
173
    // Vines grow fast enough to be a nuisance. They start switched off.
174
    private static final List<String> PLANTS_ON = PLANT_NAMES.stream()
175
        .filter(name -> !name.endsWith("vines")).toList();
176
177
    // Ticks before the same block is sent again.
178
    private static final int RETRY_TICKS = 10;
179
180
    // Ticks a slower block gets on top of its break time before it is given up on.
181
    private static final int SLOW_GRACE_TICKS = 20;
182
183
    // Ticks a cut spot waits for its seed.
184
    private static final int PLANT_TICKS = 60;
185
186
    // Vanilla repeats a held right click at this rate.
187
    private static final int USE_INTERVAL = 4;
188
189
    private static final AABB NODE = new AABB(BlockPos.ZERO).deflate(0.3);
190
    private static final AABB SHELL = new AABB(BlockPos.ZERO).deflate(1 / 16.0);
191
192
    private final NumberSetting range = new NumberSetting("Range",
193
        "How far from your eyes to farm.", 4.5, 1, 6, 0.1).max(6);
194
    private final BoolSetting harvest = new BoolSetting("Harvest",
195
        "Takes the parts of a plant that have finished growing.", true);
196
    private final ChoiceListSetting harvestPlants = new ChoiceListSetting("Harvest plants",
197
        "Which plants to take from.", () -> PLANT_NAMES, PLANTS_ON)
198
        .under(harvest);
199
    private final BoolSetting replant = new BoolSetting("Replant",
200
        "Puts a seed back into every spot you just cleared.", true);
201
    private final ChoiceListSetting replantPlants = new ChoiceListSetting("Replant plants",
202
        "Which plants to put back.", () -> PLANT_NAMES, PLANTS_ON)
203
        .under(replant);
204
    private final BoolSetting bonemeal = new BoolSetting("Bonemeal",
205
        "Feeds bone meal to the crops that are still growing.", false);
206
    private final NumberSetting perTick = new NumberSetting("Blocks per tick",
207
        "How many crops to cut each tick.", 4, 1, 16, 1);
208
    private final BoolSetting lineOfSight = new BoolSetting("Line of sight",
209
        "Skip anything your eyes cannot see.", false);
210
    private final EnumSetting<FaceMode> faceTarget = FaceMode.setting(FaceMode.SERVER);
211
    private final EnumSetting<SwingMode> swing = SwingMode.setting(SwingMode.BOTH);
212
    private final BoolSetting drawSpots = new BoolSetting("Draw spots",
213
        "Marks the spots being tracked for replanting.", true);
214
    private final ColorSetting spotColor = new ColorSetting("Spot colour",
215
        "Colour of the tracked spots.", 180, 0.79f, 0.88f, false)
216
        .under(drawSpots);
217
    private final BoolSetting drawHarvest = new BoolSetting("Draw harvest",
218
        "Marks the plants that are ready to take and how far the break has got.", true);
219
    private final ColorSetting harvestColor = new ColorSetting("Harvest colour",
220
        "Colour of the plants that are ready.", 120, 0.79f, 0.88f, false)
221
        .under(drawHarvest);
222
    private final BoolSetting drawReplant = new BoolSetting("Draw replant",
223
        "Marks the empty spots waiting for a seed.", true);
224
    private final ColorSetting replantColor = new ColorSetting("Replant colour",
225
        "Colour of the spots waiting for a seed.", 0, 0.79f, 0.88f, false)
226
        .under(drawReplant);
227
228
    private final Map<BlockPos, Integer> attempted = new HashMap<>();
229
    private final Map<BlockPos, Plant> spots = new HashMap<>();
230
    private final Map<BlockPos, Integer> spotExpiry = new HashMap<>();
231
232
    private List<BlockPos> shownHarvest = List.of();
233
    private List<BlockPos> shownReplant = List.of();
234
    private BlockPos mining;
235
236
    private BlockPos slowPending;
237
    private int slowDeadline;
238
    private int lastUse;
239
    private int lastTick;
240
241
    private final InventoryUtil.HotbarLoan loan = new InventoryUtil.HotbarLoan();
242
243
    public AutoFarm() {
244
        super("AutoFarm", "Harvests the ripe crops in reach and replants them.", Category.WORLD);
245
        addSettings(range, harvest, harvestPlants, replant, replantPlants, bonemeal, perTick,
246
            lineOfSight, faceTarget, swing, drawSpots, spotColor, drawHarvest, harvestColor,
247
            drawReplant, replantColor);
248
        searchTags("farm", "crops", "harvest", "replant", "wheat", "berries");
249
    }
250
251
    @Override
252
    public String getSuffix() {
253
        return range.getValueString();
254
    }
255
256
    // Break packets for anything slower than one hit share the one server slot.
257
    @Override
258
    public ExclusivityGroup getExclusivityGroup() {
259
        return ExclusivityGroup.MINING;
260
    }
261
262
    @Override
263
    protected void onEnable() {
264
        reset();
265
    }
266
267
    @Override
268
    protected void onDisable() {
269
        reset();
270
        loan.giveBack();
271
    }
272
273
    private void reset() {
274
        attempted.clear();
275
        spots.clear();
276
        spotExpiry.clear();
277
        shownHarvest = List.of();
278
        shownReplant = List.of();
279
        mining = null;
280
        slowPending = null;
281
        lastUse = 0;
282
        lastTick = 0;
283
    }
284
285
    @Subscribe
286
    private void onTick(TickEvent event) {
287
        if (!inGame() || mc.player.isSpectator()) {
288
            loan.giveBack();
289
            return;
290
        }
291
        // A held attack or an open container means the player is busy by hand.
292
        if (InputUtil.physicallyHeld(mc.options.keyAttack) || mc.player.isUsingItem()
293
            || mc.gui.screen() != null) {
294
            loan.giveBack();
295
            return;
296
        }
297
298
        int now = mc.player.tickCount;
299
        // The tick count restarts on a respawn.
300
        if (now < lastTick) {
301
            reset();
302
        }
303
        lastTick = now;
304
        attempted.values().removeIf(expiry -> expiry <= now);
305
        spotExpiry.entrySet().removeIf(entry -> {
306
            boolean gone = entry.getValue() <= now;
307
            if (gone) {
308
                spots.remove(entry.getKey());
309
            }
310
            return gone;
311
        });
312
        if (slowPending != null && (now >= slowDeadline || !readyToMine(slowPending))) {
313
            slowPending = null;
314
        }
315
316
        List<BlockPos> scan = BlockUtil.positionsWithin(range.getValue());
317
        for (BlockPos pos : scan) {
318
            Plant plant = spotPlant(pos);
319
            if (plant != null) {
320
                spots.put(pos.immutable(), plant);
321
                spotExpiry.put(pos.immutable(), now + PLANT_TICKS);
322
            }
323
        }
324
325
        List<BlockPos> toMine = new ArrayList<>();
326
        List<BlockPos> toInteract = new ArrayList<>();
327
        List<BlockPos> toReplant = new ArrayList<>();
328
        sort(scan, toMine, toInteract, toReplant);
329
        shownHarvest = toMine;
330
        shownReplant = toReplant;
331
332
        boolean acted = replant.isOn() && plantSeeds(toReplant, now);
333
        if (!acted && harvest.isOn()) {
334
            acted = pickByHand(toInteract, now);
335
        }
336
        if (!acted && harvest.isOn()) {
337
            mineTick(toMine, now);
338
        } else {
339
            mining = null;
340
        }
341
        if (!acted && bonemeal.isOn()) {
342
            feedTick(scan, now);
343
        }
344
    }
345
346
    private void sort(List<BlockPos> scan, List<BlockPos> toMine, List<BlockPos> toInteract,
347
                      List<BlockPos> toReplant) {
348
        for (BlockPos pos : scan) {
349
            if (lineOfSight.isOn() && !BlockUtil.canSee(pos)) {
350
                continue;
351
            }
352
            BlockState state = BlockUtil.state(pos);
353
            if (state.canBeReplaced()) {
354
                Plant waiting = spots.get(pos);
355
                if (waiting != null && replantPlants.contains(waiting.name())
356
                    && waiting.surface().test(pos)) {
357
                    toReplant.add(pos.immutable());
358
                }
359
                continue;
360
            }
361
            for (Plant plant : PLANTS) {
362
                if (!harvestPlants.contains(plant.name())) {
363
                    continue;
364
                }
365
                if (plant.interact().matches(pos, state)) {
366
                    toInteract.add(pos.immutable());
367
                    break;
368
                }
369
                if (plant.mine().matches(pos, state)) {
370
                    toMine.add(pos.immutable());
371
                    break;
372
                }
373
            }
374
        }
375
    }
376
377
    // Creative with no turning can spam every crop at once. Anything else goes
378
    // block by block because only one angle rides the packet each tick.
379
    private void mineTick(List<BlockPos> toMine, int now) {
380
        boolean spam = mc.player.getAbilities().instabuild && faceTarget.is(FaceMode.OFF);
381
        int limit = spam ? toMine.size() : perTick.getInt();
382
        int sent = 0;
383
        mining = null;
384
        for (BlockPos pos : toMine) {
385
            if (sent >= limit) {
386
                break;
387
            }
388
            if (attempted.containsKey(pos)) {
389
                continue;
390
            }
391
            boolean instant = BlockUtil.canInstantBreak(pos);
392
            if (!instant && slowPending != null) {
393
                continue;
394
            }
395
            if (sent == 0) {
396
                mining = pos;
397
                faceTarget.getValue().face(BlockUtil.hitPoint(pos, BlockUtil.facingSide(pos)),
398
                    RotationPriority.MINE);
399
            }
400
            BlockMiner.breakInstantly(pos);
401
            if (instant) {
402
                attempted.put(pos, now + RETRY_TICKS);
403
            } else {
404
                slowPending = pos;
405
                slowDeadline = now + BlockUtil.breakTicks(pos) + SLOW_GRACE_TICKS;
406
                attempted.put(pos, slowDeadline);
407
            }
408
            sent++;
409
        }
410
        if (sent > 0) {
411
            swing.getValue().swing(InteractionHand.MAIN_HAND);
412
        }
413
    }
414
415
    // Berries and glow berries come off with a right click and leave the plant standing.
416
    private boolean pickByHand(List<BlockPos> toInteract, int now) {
417
        if (toInteract.isEmpty() || now - lastUse < USE_INTERVAL) {
418
            return false;
419
        }
420
        // A right click with bone meal would fertilise the bush instead.
421
        if (mc.player.getMainHandItem().is(Items.BONE_MEAL)) {
422
            int other = InventoryUtil.hotbarSlot(stack -> !stack.is(Items.BONE_MEAL));
423
            if (other == -1) {
424
                return false;
425
            }
426
            loan.select(other);
427
            return true;
428
        }
429
        for (BlockPos pos : toInteract) {
430
            Direction side = BlockUtil.facingSide(pos);
431
            faceTarget.getValue().face(BlockUtil.hitPoint(pos, side), RotationPriority.PLACE);
432
            if (BlockUtil.interact(pos, side)) {
433
                lastUse = now;
434
                return true;
435
            }
436
        }
437
        return false;
438
    }
439
440
    private boolean plantSeeds(List<BlockPos> toReplant, int now) {
441
        if (toReplant.isEmpty() || now - lastUse < USE_INTERVAL) {
442
            return false;
443
        }
444
        for (BlockPos pos : toReplant) {
445
            Plant plant = spots.get(pos);
446
            if (plant == null) {
447
                continue;
448
            }
449
            if (!holdSeed(plant.seed())) {
450
                continue;
451
            }
452
            faceTarget.getValue().face(Vec3.atCenterOf(pos), RotationPriority.PLACE);
453
            if (BlockUtil.placeAny(pos, false, false)) {
454
                swing.getValue().swing(InteractionHand.MAIN_HAND);
455
                spots.remove(pos);
456
                spotExpiry.remove(pos);
457
                lastUse = now;
458
            }
459
            return true;
460
        }
461
        return false;
462
    }
463
464
    // Takes the seed from anywhere in the inventory and conjures one in creative.
465
    private boolean holdSeed(Item seed) {
466
        if (mc.player.getMainHandItem().is(seed)) {
467
            return true;
468
        }
469
        int slot = InventoryUtil.findSlot(seed, InventoryUtil.WHOLE_INVENTORY);
470
        if (slot != -1) {
471
            return loan.select(slot) && mc.player.getMainHandItem().is(seed);
472
        }
473
        if (!mc.player.getAbilities().instabuild) {
474
            return false;
475
        }
476
        int free = InventoryUtil.freeHotbarSlot(InventoryUtil.selectedSlot());
477
        ItemStack stack = new ItemStack(seed);
478
        mc.player.getInventory().setSelectedSlot(free);
479
        mc.player.getInventory().setItem(free, stack);
480
        mc.gameMode.handleCreativeModeItemAdd(stack, InventoryUtil.networkSlot(free));
481
        return true;
482
    }
483
484
    private void feedTick(List<BlockPos> scan, int now) {
485
        if (now - lastUse < USE_INTERVAL) {
486
            return;
487
        }
488
        BlockPos target = findGrowing(scan);
489
        if (target == null) {
490
            return;
491
        }
492
        int slot = InventoryUtil.findSlot(Items.BONE_MEAL, InventoryUtil.WHOLE_INVENTORY);
493
        if (slot == -1 || !loan.select(slot)) {
494
            return;
495
        }
496
        Direction side = BlockUtil.facingSide(target);
497
        faceTarget.getValue().face(BlockUtil.hitPoint(target, side), RotationPriority.PLACE);
498
        if (BlockUtil.useOn(target, false, false)) {
499
            swing.getValue().swing(InteractionHand.MAIN_HAND);
500
            lastUse = now;
501
        }
502
    }
503
504
    private BlockPos findGrowing(List<BlockPos> scan) {
505
        for (BlockPos pos : scan) {
506
            BlockState state = BlockUtil.state(pos);
507
            if (state.getBlock() instanceof CropBlock crop && !crop.isMaxAge(state)) {
508
                return pos;
509
            }
510
            if (state.getBlock() instanceof CocoaBlock
511
                && state.getValue(CocoaBlock.AGE) < CocoaBlock.MAX_AGE) {
512
                return pos;
513
            }
514
        }
515
        return null;
516
    }
517
518
    private boolean readyToMine(BlockPos pos) {
519
        BlockState state = BlockUtil.state(pos);
520
        for (Plant plant : PLANTS) {
521
            if (harvestPlants.contains(plant.name()) && plant.mine().matches(pos, state)) {
522
                return true;
523
            }
524
        }
525
        return false;
526
    }
527
528
    private Plant spotPlant(BlockPos pos) {
529
        BlockState state = BlockUtil.state(pos);
530
        for (Plant plant : PLANTS) {
531
            if (plant.spot().matches(pos, state)) {
532
                return plant;
533
            }
534
        }
535
        return null;
536
    }
537
538
    @Subscribe
539
    private void onRender3D(Render3DEvent event) {
540
        if (!inGame()) {
541
            return;
542
        }
543
        DrawBatch batch = event.getBatch();
544
        if (drawSpots.isOn()) {
545
            int colour = spotColor.getColor();
546
            for (BlockPos pos : spots.keySet()) {
547
                batch.outlineBox(NODE.move(pos), colour, false);
548
            }
549
        }
550
        if (drawHarvest.isOn()) {
551
            int colour = harvestColor.getColor();
552
            for (BlockPos pos : shownHarvest) {
553
                batch.outlineBox(SHELL.move(pos), colour, false);
554
            }
555
            drawProgress(batch, colour);
556
        }
557
        if (drawReplant.isOn()) {
558
            int colour = replantColor.getColor();
559
            for (BlockPos pos : shownReplant) {
560
                batch.outlineBox(SHELL.move(pos), colour, false);
561
            }
562
        }
563
    }
564
565
    // The break shell shrinks from the whole block down to nothing as it goes.
566
    private void drawProgress(DrawBatch batch, int colour) {
567
        if (mining == null || !(mc.gameMode instanceof MultiPlayerGameModeAccessor access)) {
568
            return;
569
        }
570
        float progress = access.offlineclient$destroyProgress();
571
        if (progress <= 0 || !mining.equals(access.offlineclient$destroyBlockPos())) {
572
            return;
573
        }
574
        batch.solidBox(new AABB(BlockPos.ZERO).deflate(progress * 0.5).move(mining), colour, false);
575
    }
576
577
    private static BlockState below(BlockPos pos) {
578
        return BlockUtil.state(pos.below());
579
    }
580
581
    // Whether the plant of that name would put a seed here.
582
    private static boolean isSpot(String name, BlockPos pos) {
583
        for (Plant plant : PLANTS) {
584
            if (plant.name().equals(name)) {
585
                return plant.spot().matches(pos, BlockUtil.state(pos));
586
            }
587
        }
588
        return false;
589
    }
590
591
    private static boolean ripeCrop(BlockPos pos, BlockState state) {
592
        return state.getBlock() instanceof CropBlock crop && crop.isMaxAge(state);
593
    }
594
595
    private static boolean cropSurface(BlockPos pos) {
596
        return below(pos).is(BlockTags.SUPPORTS_CROPS);
597
    }
598
599
    private static boolean cocoaSurface(BlockPos pos) {
600
        for (Direction side : Direction.Plane.HORIZONTAL) {
601
            if (BlockUtil.state(pos.relative(side)).is(BlockTags.SUPPORTS_COCOA)) {
602
                return true;
603
            }
604
        }
605
        return false;
606
    }
607
608
    // A cactus needs clear sides or it snaps as soon as it grows.
609
    private static boolean cactusSurface(BlockPos pos) {
610
        if (!below(pos).is(BlockTags.SUPPORTS_CACTUS)) {
611
            return false;
612
        }
613
        for (Direction side : Direction.Plane.HORIZONTAL) {
614
            BlockState neighbour = BlockUtil.state(pos.relative(side));
615
            if (BlockUtil.blocksMotion(neighbour) || neighbour.getFluidState().is(FluidTags.LAVA)) {
616
                return false;
617
            }
618
        }
619
        return true;
620
    }
621
622
    private static boolean caneSurface(BlockPos pos) {
623
        BlockPos floor = pos.below();
624
        if (!BlockUtil.state(floor).is(BlockTags.SUPPORTS_SUGAR_CANE)) {
625
            return false;
626
        }
627
        for (Direction side : Direction.Plane.HORIZONTAL) {
628
            BlockState neighbour = BlockUtil.state(floor.relative(side));
629
            if (neighbour.getFluidState().is(FluidTags.SUPPORTS_SUGAR_CANE_ADJACENTLY)
630
                || neighbour.is(BlockTags.SUPPORTS_SUGAR_CANE_ADJACENTLY)) {
631
                return true;
632
            }
633
        }
634
        return false;
635
    }
636
637
    private static boolean kelpSurface(BlockPos pos) {
638
        FluidState fluid = BlockUtil.state(pos).getFluidState();
639
        if (!fluid.is(FluidTags.WATER) || fluid.getAmount() != 8) {
640
            return false;
641
        }
642
        BlockPos floor = pos.below();
643
        return !BlockUtil.state(floor).is(BlockTags.CANNOT_SUPPORT_KELP)
644
            && BlockUtil.state(floor).isFaceSturdy(OfflineClient.MC.level, floor, Direction.UP);
645
    }
646
647
    private static boolean pickleSurface(BlockPos pos) {
648
        if (!below(pos).is(BlockTags.CORAL_BLOCKS)) {
649
            return false;
650
        }
651
        FluidState fluid = BlockUtil.state(pos).getFluidState();
652
        return fluid.is(FluidTags.WATER) && fluid.getAmount() == 8;
653
    }
654
655
    private static boolean berrySurface(BlockPos pos) {
656
        return below(pos).is(BlockTags.SUPPORTS_VEGETATION);
657
    }
658
659
    // The topmost vine hangs from something solid rather than from more vine.
660
    private static boolean vineCeiling(BlockPos pos) {
661
        BlockPos ceiling = pos.above();
662
        BlockState state = BlockUtil.state(ceiling);
663
        return !(state.getBlock() instanceof CaveVines)
664
            && state.isFaceSturdy(OfflineClient.MC.level, ceiling, Direction.DOWN);
665
    }
666
667
    private static boolean isTwisting(BlockState state) {
668
        return state.is(Blocks.TWISTING_VINES) || state.is(Blocks.TWISTING_VINES_PLANT);
669
    }
670
671
    private static boolean twistingFloor(BlockPos pos) {
672
        BlockPos floor = pos.below();
673
        BlockState state = BlockUtil.state(floor);
674
        return !isTwisting(state)
675
            && state.isFaceSturdy(OfflineClient.MC.level, floor, Direction.UP);
676
    }
677
678
    private static boolean isWeeping(BlockState state) {
679
        return state.is(Blocks.WEEPING_VINES) || state.is(Blocks.WEEPING_VINES_PLANT);
680
    }
681
682
    private static boolean weepingCeiling(BlockPos pos) {
683
        BlockPos ceiling = pos.above();
684
        BlockState state = BlockUtil.state(ceiling);
685
        return !isWeeping(state)
686
            && state.isFaceSturdy(OfflineClient.MC.level, ceiling, Direction.DOWN);
687
    }
688
689
    // A flower is done when it stops growing. A stem is only cut once every
690
    // flower it holds up has been taken.
691
    private static boolean ripeChorus(BlockPos pos, BlockState state) {
692
        if (state.is(Blocks.CHORUS_FLOWER)) {
693
            return state.getValueOrElse(ChorusFlowerBlock.AGE, 0) == ChorusFlowerBlock.DEAD_AGE
694
                || !BlockUtil.state(pos.above()).isAir();
695
        }
696
        return state.is(Blocks.CHORUS_PLANT) && !holdsFlower(pos, state, new HashSet<>());
697
    }
698
699
    private static boolean holdsFlower(BlockPos pos, BlockState state, Set<BlockPos> seen) {
700
        // A plant this large is left alone rather than walked in full.
701
        if (seen.size() > 1000) {
702
            return true;
703
        }
704
        if (!seen.add(pos.immutable())) {
705
            return false;
706
        }
707
        for (Direction side : Direction.values()) {
708
            if (side == Direction.DOWN
709
                || !state.getValueOrElse(PipeBlock.PROPERTY_BY_DIRECTION.get(side), false)) {
710
                continue;
711
            }
712
            BlockPos next = pos.relative(side);
713
            BlockState nextState = BlockUtil.state(next);
714
            if (nextState.is(Blocks.CHORUS_FLOWER)) {
715
                return true;
716
            }
717
            if (!nextState.is(Blocks.CHORUS_PLANT)) {
718
                continue;
719
            }
720
            // A sideways branch that also reaches down hangs off the main stem.
721
            if (side.getAxis().isHorizontal()
722
                && nextState.getValueOrElse(PipeBlock.DOWN, false)) {
723
                continue;
724
            }
725
            if (holdsFlower(next, nextState, seen)) {
726
                return true;
727
            }
728
        }
729
        return false;
730
    }
731
}
732
LiquidBounce (Kotlin)WORLDsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/world/autofarm/ModuleAutoFarm.ktKotlin · 373 lines · 14.6 KB

Automatically farms crops.

SettingsRangeWallRangeInteractDelayDisableOnFullInventorySwapBackDelayUseFortune
ModuleAutoFarm.ktKotlin · Minecraft 26.2 · 373 lines · 14.6 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.world.autofarm
20
21
import net.ccbluex.fastutil.enumSetOf
22
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
23
import net.ccbluex.liquidbounce.config.utils.asRefreshable
24
import net.ccbluex.liquidbounce.event.events.NotificationEvent
25
import net.ccbluex.liquidbounce.event.events.RotationUpdateEvent
26
import net.ccbluex.liquidbounce.event.handler
27
import net.ccbluex.liquidbounce.event.tickHandler
28
import net.ccbluex.liquidbounce.event.waitTicks
29
import net.ccbluex.liquidbounce.features.module.ClientModule
30
import net.ccbluex.liquidbounce.features.module.ModuleCategories
31
import net.ccbluex.liquidbounce.features.module.modules.player.ModuleBlink
32
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug
33
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug.debugGeometry
34
import net.ccbluex.liquidbounce.render.engine.type.Color4b
35
import net.ccbluex.liquidbounce.utils.aiming.RotationManager
36
import net.ccbluex.liquidbounce.utils.aiming.RotationsValueGroup
37
import net.ccbluex.liquidbounce.utils.aiming.utils.selectBlockTarget
38
import net.ccbluex.liquidbounce.utils.aiming.utils.raytraceBlockSide
39
import net.ccbluex.liquidbounce.utils.block.ChunkScanner
40
import net.ccbluex.liquidbounce.utils.block.doBreak
41
import net.ccbluex.liquidbounce.utils.block.doPlacement
42
import net.ccbluex.liquidbounce.utils.block.getCenterDistanceSquared
43
import net.ccbluex.liquidbounce.utils.block.searchBlocksInRangeSorted
44
import net.ccbluex.liquidbounce.utils.block.searchBlocksInCuboid
45
import net.ccbluex.liquidbounce.utils.block.state
46
import net.ccbluex.liquidbounce.utils.block.targetfinding.BlockTargetPlan
47
import net.ccbluex.liquidbounce.utils.client.Chronometer
48
import net.ccbluex.liquidbounce.utils.client.SilentHotbar
49
import net.ccbluex.liquidbounce.utils.client.notification
50
import net.ccbluex.liquidbounce.utils.inventory.Slots
51
import net.ccbluex.liquidbounce.utils.inventory.findClosestSlot
52
import net.ccbluex.liquidbounce.utils.inventory.hasInventorySpace
53
import net.ccbluex.liquidbounce.utils.item.getEnchantment
54
import net.ccbluex.liquidbounce.utils.kotlin.Priority
55
import net.ccbluex.liquidbounce.utils.math.getNearestPointOnSide
56
import net.ccbluex.liquidbounce.utils.math.sq
57
import net.ccbluex.liquidbounce.utils.raytracing.traceFromPoint
58
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen
59
import net.minecraft.core.BlockPos
60
import net.minecraft.world.item.BoneMealItem
61
import net.minecraft.world.item.enchantment.Enchantments
62
import net.minecraft.world.level.block.state.BlockState
63
import net.minecraft.world.phys.AABB
64
import net.minecraft.world.phys.HitResult
65
import net.minecraft.world.phys.Vec3
66
import net.minecraft.world.phys.shapes.CollisionContext
67
68
/**
69
 * AutoFarm module
70
 *
71
 * Automatically farms stuff for you.
72
 */
73
object ModuleAutoFarm : ClientModule("AutoFarm", ModuleCategories.WORLD) {
74
75
    private val range by float("Range", 5F, 1F..6F)
76
    private val wallRange by float("WallRange", 0f, 0F..6F).onChange {
77
        minOf(it, range)
78
    }
79
80
    // The ticks to wait after interacting with something
81
    private val interactDelay by intRange("InteractDelay", 2..3, 1..15, "ticks")
82
83
    private val disableOnFullInventory by boolean("DisableOnFullInventory", false)
84
85
    private object AutoPlaceCrops : ToggleableValueGroup(this, "AutoPlant", true, aliases = listOf("AutoPlace")) {
86
        val swapBackDelay by intRange("SwapBackDelay", 1..2, 1..20, "ticks")
87
    }
88
89
    internal object AutoUseBoneMeal : ToggleableValueGroup(this, "AutoUseBoneMeal", false) {
90
        private val chronometer = Chronometer()
91
        // TODO Use filter (wheat/potato/...)
92
        private val useDelay = intRange("UseDelay", 20..200, 0..20000, "ms").asRefreshable()
93
        val swapBackDelay by intRange("SwapBackDelay", 1..2, 1..20, "ticks")
94
95
        val isReady get() = chronometer.hasElapsed(useDelay.current.toLong())
96
97
        fun reset() {
98
            chronometer.reset()
99
            useDelay.refresh()
100
        }
101
    }
102
103
    private val fortune by boolean("UseFortune", true)
104
105
    init {
106
        tree(AutoFarmAutoWalk)
107
        tree(AutoPlaceCrops)
108
        tree(AutoUseBoneMeal)
109
        tree(AutoFarmVisualizer)
110
    }
111
112
    internal val rotations = tree(RotationsValueGroup(this))
113
114
    private fun swapToSlotWithFortune() {
115
        if (!fortune) {
116
            return
117
        }
118
        // Swap to a fortune item to increase drops
119
        Slots.Hotbar.maxByOrNull { it.itemStack.getEnchantment(Enchantments.FORTUNE) }
120
            ?.takeIf { it.itemStack.getEnchantment(Enchantments.FORTUNE) >= 1 }
121
            ?.let {
122
                SilentHotbar.selectSlotSilently(this, it, 2)
123
            }
124
    }
125
126
    var currentTarget: BlockPos? = null
127
        private set
128
129
    // Find the target on RotationUpdateEvent, which runs right before RotationManager.update, so the
130
    // requested rotation is applied within the same tick.
131
    @Suppress("unused")
132
    private val rotationUpdateHandler = handler<RotationUpdateEvent> {
133
        // Return if the user is inside a screen like the inventory
134
        if (mc.gui.screen() is AbstractContainerScreen<*>) {
135
            return@handler
136
        }
137
138
        updateTarget()
139
    }
140
141
    @Suppress("unused")
142
    private val tickHandler = tickHandler {
143
        // Return if the user is inside a screen like the inventory
144
        if (mc.gui.screen() is AbstractContainerScreen<*>) {
145
            return@tickHandler
146
        }
147
148
        // Return if the blink module is enabled
149
        if (ModuleBlink.running) {
150
            return@tickHandler
151
        }
152
153
        // Disable the module and return if the inventory is full, and the setting for disabling the module is enabled
154
        if (disableOnFullInventory && !hasInventorySpace()) {
155
            notification(message("inventoryFull"), message("disabled"), NotificationEvent.Severity.ERROR)
156
            enabled = false
157
            return@tickHandler
158
        }
159
160
        // Return if we don't have a target
161
        val target = currentTarget ?: return@tickHandler
162
163
        val rotation = RotationManager.serverRotation
164
        val rayTraceResult = traceFromPoint(
165
            range = range.toDouble(),
166
            start = player.eyePosition,
167
            // Use the rotation already sent to the server, so we only interact when the server sees the aim
168
            direction = rotation.directionVector,
169
            entity = player,
170
        )
171
        if (rayTraceResult.type != HitResult.Type.BLOCK) {
172
            return@tickHandler
173
        }
174
175
        val blockPos = rayTraceResult.blockPos
176
177
        // Only act when we are actually aiming at the target block
178
        if (blockPos != target) {
179
            return@tickHandler
180
        }
181
182
        val state = blockPos.state ?: return@tickHandler
183
        if (blockPos.readyForHarvest(state)) {
184
            when (state.block.harvestAction) {
185
                HarvestAction.BREAK -> {
186
                    swapToSlotWithFortune()
187
                    doBreak(rayTraceResult)
188
                }
189
                HarvestAction.USE -> {
190
                    doPlacement(rayTraceResult, rotation)
191
                }
192
                null -> return@tickHandler
193
            }
194
195
            if (interaction.destroyStage == -1) {
196
                // Only wait if the block is completely broken
197
                waitTicks(interactDelay.random())
198
            }
199
        } else if (AutoUseBoneMeal.enabled && AutoUseBoneMeal.isReady && blockPos.canUseBoneMeal(state)) {
200
            val boneMealSlot = Slots.OffhandWithHotbar.findClosestSlot { it.item is BoneMealItem } ?: return@tickHandler
201
202
            SilentHotbar.selectSlotSilently(this, boneMealSlot, AutoUseBoneMeal.swapBackDelay.random())
203
            doPlacement(rayTraceResult, rotation, hand = boneMealSlot.useHand)
204
            AutoUseBoneMeal.reset()
205
            waitTicks(interactDelay.random())
206
        } else {
207
            val blockState = world.getBlockState(blockPos)
208
209
            debugGeometry("RayTraceResult") {
210
                ModuleDebug.DebuggedPoint(rayTraceResult.location, Color4b.RED.alpha(150))
211
            }
212
            debugGeometry("PlantablePos") {
213
                ModuleDebug.DebuggedBox(AABB(blockPos), Color4b.GREEN.alpha(100))
214
            }
215
216
            val sides = AutoFarmTrackedState.Plantable.entries.findPlantableSides(blockPos, blockState)
217
            if (sides.isNotEmpty()) {
218
                val slot = AutoFarmTrackedState.Plantable.entries.firstNotNullOfOrNull {
219
                    if (it.isBlockMatches(blockState)) {
220
                        Slots.OffhandWithHotbar.findClosestSlot(it.items)
221
                    } else {
222
                        null
223
                    }
224
                } ?: return@tickHandler
225
226
                SilentHotbar.selectSlotSilently(this, slot, AutoPlaceCrops.swapBackDelay.random())
227
                doPlacement(rayTraceResult, rotation, hand = slot.useHand)
228
229
                waitTicks(interactDelay.random())
230
            }
231
        }
232
    }
233
234
    private fun updateTarget(possible: Iterable<Pair<BlockPos, BlockState>>): Boolean {
235
        val target = selectBlockTarget(
236
            player.eyePosition,
237
            range - 0.1f,
238
            wallRange - 0.1f,
239
            possible,
240
            rotations,
241
            this
242
        ) ?: return false
243
244
        // set currentTarget to the new target
245
        currentTarget = target
246
        return true
247
    }
248
249
    /** Searches for any blocks within the radius that need to be destroyed, such as crops. */
250
    private fun updateTargetToHarvest(radius: Float, eyesPos: Vec3): Boolean {
251
        val blocksToBreak = eyesPos.searchBlocksInRangeSorted(radius) { pos, state ->
252
            !state.isAir && pos.readyForHarvest(state)
253
        }
254
255
        return updateTarget(blocksToBreak)
256
    }
257
258
    // Searches for any blocks suitable for placing crops or nether wart on
259
    // returns ture if it found a target
260
    private fun updateTargetToPlantable(radius: Float, eyesPos: Vec3): Boolean {
261
        val hotbarItems = Slots.OffhandWithHotbar.items
262
        val radiusSquared = radius * radius
263
264
        val allowedTypes = AutoFarmTrackedState.Plantable.entries.filter { type ->
265
            hotbarItems.any { it in type.items }
266
        }
267
268
        if (allowedTypes.isEmpty()) return false
269
270
        val blocksToPlace =
271
            eyesPos.searchBlocksInCuboid(radius) { _, state ->
272
                !state.isAir && allowedTypes.any { it.isBlockMatches(state) }
273
            }.mapNotNullTo(mutableListOf()) { (pos, state) ->
274
                val sides = allowedTypes.findPlantableSides(pos, state).ifEmpty { return@mapNotNullTo null }
275
                val outlineShape = state.getShape(world, pos)
276
277
                if (outlineShape.isEmpty) return@mapNotNullTo null
278
                // getShape is block-local, move it to world space before measuring distance to the eyes
279
                val box = outlineShape.bounds().move(pos)
280
                // Keep only sides that are within reach and whose face points towards the eyes
281
                sides.removeIf { side ->
282
                    box.getNearestPointOnSide(eyesPos, side).distanceToSqr(eyesPos) > radiusSquared ||
283
                        BlockTargetPlan(pos, side).calculateAngleToPlayerEyeCosine(eyesPos) < 0.0
284
                }
285
286
                pos to sides.ifEmpty { return@mapNotNullTo null }
287
            }.sortedBy { it.first.getCenterDistanceSquared() }
288
289
        val collisionContext = CollisionContext.of(player)
290
        for ((pos, sides) in blocksToPlace) {
291
            val (rotation, _) = sides.firstNotNullOfOrNull { side ->
292
                raytraceBlockSide(
293
                    side,
294
                    pos,
295
                    player.eyePosition,
296
                    rangeSquared = range.sq().toDouble() - 0.1,
297
                    wallsRangeSquared = wallRange.sq().toDouble() - 0.1,
298
                    collisionContext,
299
                )
300
            } ?: continue // We don't have a free angle at the block? Well, let me see the next.
301
302
            // set currentTarget to the new target
303
            currentTarget = pos
304
            // aim at target
305
            RotationManager.setRotationTarget(
306
                rotation,
307
                valueGroup = rotations,
308
                priority = Priority.IMPORTANT_FOR_USAGE_1,
309
                provider = this@ModuleAutoFarm
310
            )
311
312
            return true // We got a free angle at the block? No need to see more of them.
313
        }
314
        return false
315
    }
316
317
    private fun updateTargetToFertilizable(radius: Float, eyesPos: Vec3): Boolean {
318
        if (Slots.OffhandWithHotbar.none { it.itemStack.item is BoneMealItem }) {
319
            return false
320
        }
321
322
        val blocksToFertile = eyesPos.searchBlocksInRangeSorted(radius) { pos, state ->
323
            !state.isAir && pos.canUseBoneMeal(state)
324
        }
325
326
        return updateTarget(blocksToFertile)
327
    }
328
329
    // Finds either a breakable target (such as crops, cactus, etc.)
330
    // or a placeable target (such as a farmblock or soulsand with air above).
331
    // It will prefer a breakable target
332
    private fun updateTarget() {
333
        currentTarget = null
334
335
        val radius = range
336
        val eyesPos = player.eyePosition
337
338
        // Can we find a breakable target?
339
        if (updateTargetToHarvest(radius, eyesPos)) {
340
            return
341
        }
342
343
        // Can we find a placeable target?
344
        if (AutoPlaceCrops.enabled && updateTargetToPlantable(radius, eyesPos)) {
345
            return
346
        }
347
348
        if (AutoUseBoneMeal.enabled && updateTargetToFertilizable(radius, eyesPos)) {
349
            return
350
        }
351
    }
352
353
    /**
354
     * Find plantable sides of the block for all types in the iterable
355
     */
356
    private fun Iterable<AutoFarmTrackedState.Plantable>.findPlantableSides(
357
        pos: BlockPos,
358
        state: BlockState,
359
    ) = flatMapTo(enumSetOf()) { it.findPlantableSides(pos, state) }
360
361
    override fun onEnabled() {
362
        ChunkScanner.subscribe(AutoFarmBlockTracker)
363
    }
364
365
    override fun onDisabled() {
366
        ChunkScanner.unsubscribe(AutoFarmBlockTracker)
367
        currentTarget = null
368
        AutoUseBoneMeal.reset()
369
        SilentHotbar.resetSlot(this)
370
    }
371
372
}
373