HighwayBuilder module

HighwayBuilder: Minecraft 26.3 cheat module, full source for every implementation (1 client: OfflineClient).

1 implementationWORLD

Clients with this module

Full module source: 1 implementation

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

OfflineClientWORLDsrc/main/java/com/jellypudding/offlineclient/modules/world/HighwayBuilder.javaJava · 1,472 lines · 55.7 KB

Digs and builds a highway along one line at a fixed height.

SettingsWidthHeightDiagonalMovementFree lookSkip unreachableRelevelPause on lagBlocksFloorReplace floorWallsWall heightReplace wallsMine above wallsCeilingReplace ceilingFill liquidsTorchesTorch spacingTorch heightRotationBreak delayBreaks per tickDouble mineFast breakSave pickaxesPlace rangePlace delayPlacements per tickRestock hotbarInventory delaySearch shulkersSearch ender chestMine ender chestsSave ender chestsGrind amountGrind blockadeEject useless shulkersMinimum empty slots
HighwayBuilder.javaJava · Minecraft 26.2 · 1,472 lines · 55.7 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.world;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.Render3DEvent;
5
import com.jellypudding.offlineclient.event.events.TickEvent;
6
import com.jellypudding.offlineclient.module.Category;
7
import com.jellypudding.offlineclient.module.ExclusivityGroup;
8
import com.jellypudding.offlineclient.module.Module;
9
import com.jellypudding.offlineclient.modules.combat.KillAura;
10
import com.jellypudding.offlineclient.modules.movement.NoKnockback;
11
import com.jellypudding.offlineclient.modules.movement.Speed;
12
import com.jellypudding.offlineclient.render.BoxStyle;
13
import com.jellypudding.offlineclient.setting.BoolSetting;
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.setting.RegistryListSetting;
18
import com.jellypudding.offlineclient.util.AxisWalker;
19
import com.jellypudding.offlineclient.util.BlockMiner;
20
import com.jellypudding.offlineclient.util.BlockUtil;
21
import com.jellypudding.offlineclient.util.ChatUtil;
22
import com.jellypudding.offlineclient.util.ColorUtil;
23
import com.jellypudding.offlineclient.util.InputUtil;
24
import com.jellypudding.offlineclient.util.InventoryUtil;
25
import com.jellypudding.offlineclient.util.ItemUtil;
26
import com.jellypudding.offlineclient.util.InventoryUtil.SlotSwap;
27
import com.jellypudding.offlineclient.util.Modules;
28
import com.jellypudding.offlineclient.util.ProjectileUtil;
29
import com.jellypudding.offlineclient.util.RotationManager;
30
import com.jellypudding.offlineclient.util.RotationPriority;
31
import com.jellypudding.offlineclient.util.TickRate;
32
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
33
import net.minecraft.core.BlockPos;
34
import net.minecraft.core.Direction;
35
import net.minecraft.core.component.DataComponents;
36
import net.minecraft.core.registries.BuiltInRegistries;
37
import net.minecraft.network.chat.Component;
38
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
39
import net.minecraft.tags.ItemTags;
40
import net.minecraft.world.entity.Entity;
41
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
42
import net.minecraft.world.inventory.AbstractContainerMenu;
43
import net.minecraft.world.inventory.ContainerInput;
44
import net.minecraft.world.inventory.Slot;
45
import net.minecraft.world.item.BlockItem;
46
import net.minecraft.world.item.Item;
47
import net.minecraft.world.item.ItemStack;
48
import net.minecraft.world.item.Items;
49
import net.minecraft.world.level.block.state.BlockState;
50
import net.minecraft.world.item.enchantment.Enchantments;
51
import net.minecraft.world.item.component.ItemContainerContents;
52
import net.minecraft.world.level.block.Block;
53
import net.minecraft.world.level.block.ShulkerBoxBlock;
54
import net.minecraft.world.level.block.Blocks;
55
import net.minecraft.world.phys.Vec3;
56
57
import java.util.ArrayList;
58
import java.util.HashSet;
59
import java.util.List;
60
import java.util.Set;
61
import java.util.function.Predicate;
62
63
// Builds a highway along one line at a fixed height doing the nearest job each tick.
64
// Clears first then floor then walls then ceiling. Unsupported blocks go into the air.
65
public final class HighwayBuilder extends Module {
66
67
    // Finished depths that must lie ahead before the module walks on.
68
    private static final int LEAD = 2;
69
70
    // How far ahead of the player the work reaches and how far behind it is checked.
71
    private static final int AHEAD = 6;
72
    private static final int BEHIND = 2;
73
74
    // Ticks of no progress before the module gives up walking on its own.
75
    private static final int IDLE_LIMIT = 200;
76
77
    // A walking pace in blocks per tick whilst the view is left free.
78
    private static final double WALK_SPEED = 0.13;
79
80
    // How long the server may go quiet before the module waits for it.
81
    private static final long LAG_MILLIS = 1500;
82
83
    // Arrow speed in blocks per tick at a full draw and the ticks that draw takes.
84
    private static final double BOW_SPEED = 3;
85
    private static final int FULL_DRAW = 20;
86
    private static final int CRYSTAL_SHOTS = 3;
87
    private static final double CRYSTAL_NEAR = 12;
88
    private static final double CRYSTAL_FAR = 24;
89
90
    // The most boxes the render draws in one frame.
91
    private static final int MAX_DRAWN = 512;
92
93
    // Ticks a shulker restock may take before it is written off.
94
    private static final int RESTOCK_LIMIT = 200;
95
96
    // Ticks a grind may run before it is abandoned.
97
    private static final int GRIND_LIMIT = 2400;
98
99
    public enum Movement { AUTO, MANUAL }
100
101
    public enum Rotation { NONE, MINE, PLACE, BOTH }
102
103
    private enum Stage { NONE, TAKE, BREAK, GRIND }
104
105
    private final NumberSetting width = new NumberSetting("Width",
106
        "How wide the highway is.", 4, 1, 5, 1, " blocks").min(1).max(9);
107
    private final NumberSetting height = new NumberSetting("Height",
108
        "How tall the tunnel is.", 3, 2, 5, 1, " blocks").min(2).max(9);
109
    private final BoolSetting diagonal = new BoolSetting("Diagonal",
110
        "Lets the line run at forty five degrees when you face that way.", false);
111
    private final EnumSetting<Movement> movement = new EnumSetting<>("Movement",
112
        "Who walks.", Movement.AUTO)
113
        .describe(Movement.AUTO, "The module walks on once the stretch ahead is finished.")
114
        .describe(Movement.MANUAL, "You walk. The module builds around wherever you are along the line.");
115
    private final BoolSetting freeLook = new BoolSetting("Free look",
116
        "Leaves your view alone. The walking and building follow the line on their own.", false)
117
        .under(movement, Movement.AUTO);
118
    private final BoolSetting skipUnreachable = new BoolSetting("Skip unreachable",
119
        "Walks on past blocks you cannot reach from the line instead of waiting for them.", true)
120
        .under(movement, Movement.AUTO);
121
    private final BoolSetting reLevel = new BoolSetting("Relevel",
122
        "Jumps and paves under your feet when you drop below the floor.", true);
123
    private final BoolSetting pauseOnLag = new BoolSetting("Pause on lag",
124
        "Waits whilst the server has gone quiet for over a second.", true);
125
    private final RegistryListSetting<Block> blocks = new RegistryListSetting<>("Blocks",
126
        "The blocks allowed in the build. The one in your hand wins and otherwise the first in the hotbar.",
127
        BuiltInRegistries.BLOCK,
128
        List.of(Blocks.OBSIDIAN, Blocks.NETHERRACK, Blocks.BLACKSTONE, Blocks.BASALT,
129
            Blocks.COBBLESTONE, Blocks.COBBLED_DEEPSLATE));
130
    private final BoolSetting floor = new BoolSetting("Floor",
131
        "Fills the floor under the highway.", true);
132
    private final BoolSetting replaceFloor = new BoolSetting("Replace floor",
133
        "Digs out floor blocks that are not on the list and paves over them.", false)
134
        .under(floor);
135
    private final BoolSetting walls = new BoolSetting("Walls",
136
        "Builds a wall down each side of the highway.", false);
137
    private final NumberSetting wallHeight = new NumberSetting("Wall height",
138
        "How tall each wall is. One gives a railing at foot level.", 3, 1, 5, 1, " blocks")
139
        .min(1).max(9).under(walls);
140
    private final BoolSetting replaceWalls = new BoolSetting("Replace walls",
141
        "Digs out wall blocks that are not on the list and rebuilds them.", false)
142
        .under(walls);
143
    private final BoolSetting mineAboveWalls = new BoolSetting("Mine above walls",
144
        "Clears the rest of the column over each wall so the sides stay open.", true)
145
        .under(walls);
146
    private final BoolSetting ceiling = new BoolSetting("Ceiling",
147
        "Roofs the highway over.", false);
148
    private final BoolSetting replaceCeiling = new BoolSetting("Replace ceiling",
149
        "Digs out ceiling blocks that are not on the list and roofs over them.", false)
150
        .under(ceiling);
151
    private final BoolSetting fillLiquids = new BoolSetting("Fill liquids",
152
        "Plugs any water or lava in the stretch before anything else.", true);
153
    private final BoolSetting torches = new BoolSetting("Torches",
154
        "Puts a torch on the left edge as you go. Needs torches in your hotbar.", false);
155
    private final NumberSetting torchSpacing = new NumberSetting("Torch spacing",
156
        "Blocks between one torch and the next.", 8, 2, 16, 1, " blocks").min(1)
157
        .under(torches);
158
    private final NumberSetting torchHeight = new NumberSetting("Torch height",
159
        "Blocks of air under each torch. Zero stands it on the floor and more hangs it on the wall.",
160
        0, 0, 4, 1, " blocks").min(0).max(8).under(torches);
161
    private final EnumSetting<Rotation> rotation = new EnumSetting<>("Rotation",
162
        "When a look packet is sent.", Rotation.BOTH)
163
        .describe(Rotation.NONE, "Never. The server keeps your own view.")
164
        .describe(Rotation.MINE, "Only towards blocks being broken.")
165
        .describe(Rotation.PLACE, "Only towards blocks being placed.")
166
        .describe(Rotation.BOTH, "Towards everything the module touches.");
167
    private final NumberSetting breakDelay = new NumberSetting("Break delay",
168
        "Ticks between one block break and the next.", 0, 0, 20, 1, " ticks").min(0);
169
    private final NumberSetting breaksPerTick = new NumberSetting("Breaks per tick",
170
        "How many one hit blocks come out in a tick whilst no mining rotation is sent.",
171
        1, 1, 16, 1).min(1).max(100);
172
    private final BoolSetting doubleMine = new BoolSetting("Double mine",
173
        "Breaks a second block with packets whilst the first is mined by hand.", true);
174
    private final BoolSetting fastBreak = new BoolSetting("Fast break",
175
        "Sends the second block its stop packet early instead of waiting for full progress.", true)
176
        .under(doubleMine);
177
    private final NumberSetting savePickaxes = new NumberSetting("Save pickaxes",
178
        "Turns the module off once you are down to this many pickaxes. Zero never stops.",
179
        1, 0, 36, 1).min(0).max(36);
180
    private final NumberSetting placeRange = new NumberSetting("Place range",
181
        "The furthest a block is placed from your eyes.", 4.5, 1, 5.5, 0.1).min(1).max(5.5);
182
    private final NumberSetting placeDelay = new NumberSetting("Place delay",
183
        "Ticks between one placement and the next.", 0, 0, 20, 1, " ticks").min(0);
184
    private final NumberSetting placementsPerTick = new NumberSetting("Placements per tick",
185
        "How many blocks may go down in one tick.", 1, 1, 8, 1).min(1);
186
    private final BoolSetting restock = new BoolSetting("Restock hotbar",
187
        "Moves blocks and a pickaxe up from your inventory when the hotbar runs dry.", true);
188
    private final NumberSetting inventoryDelay = new NumberSetting("Inventory delay",
189
        "Ticks between one inventory click and the next.", 3, 0, 20, 1, " ticks").min(0);
190
    private final BoolSetting searchShulkers = new BoolSetting("Search shulkers",
191
        "Sets a shulker box down behind you and takes the build blocks out of it.", true);
192
    private final BoolSetting searchEnderChest = new BoolSetting("Search ender chest",
193
        "Sets your ender chest down behind you and takes the build blocks out once the shulkers are empty. A Silk Touch pickaxe gets the chest back.",
194
        false);
195
    private final BoolSetting mineEnderChests = new BoolSetting("Mine ender chests",
196
        "With obsidian on the list and no blocks left an ender chest goes down behind you and is mined for obsidian.",
197
        true);
198
    private final NumberSetting saveEnderChests = new NumberSetting("Save ender chests",
199
        "Ender chests never used below this count.", 2, 0, 64, 1).min(0)
200
        .under(mineEnderChests);
201
    private final NumberSetting grindAmount = new NumberSetting("Grind amount",
202
        "How much obsidian one grind gathers before building goes on.", 64, 8, 256, 8).min(1)
203
        .under(mineEnderChests);
204
    private final BoolSetting grindBlockade = new BoolSetting("Grind blockade",
205
        "Walls you in with whatever blocks you have whilst the chests are ground.", true)
206
        .under(mineEnderChests);
207
    private final BoolSetting ejectShulkers = new BoolSetting("Eject useless shulkers",
208
        "Drops any shulker box holding no blocks or pickaxes or food.", true);
209
    private final NumberSetting emptySlots = new NumberSetting("Minimum empty slots",
210
        "Free slots to keep clear after a restock.", 3, 0, 9, 1).min(0);
211
    private final BoolSetting throwTrash = new BoolSetting("Throw out trash",
212
        "Turns round and drops the listed items so the inventory keeps room.", false);
213
    private final RegistryListSetting<Item> trash = new RegistryListSetting<>("Trash",
214
        "The items thrown out. Click to pick them.", BuiltInRegistries.ITEM,
215
        List.of(Items.NETHERRACK, Items.QUARTZ, Items.GOLD_NUGGET, Items.GOLDEN_SWORD,
216
            Items.GLOWSTONE_DUST, Items.GLOWSTONE, Items.BLACKSTONE, Items.BASALT,
217
            Items.GHAST_TEAR, Items.SOUL_SAND, Items.SOUL_SOIL, Items.ROTTEN_FLESH,
218
            Items.MAGMA_BLOCK))
219
        .under(throwTrash);
220
    private final BoolSetting crystalTraps = new BoolSetting("Shoot crystal traps",
221
        "Puts an arrow through any end crystal sitting in the way ahead.", true);
222
    private final BoolSetting stopWhenEmpty = new BoolSetting("Stop when empty",
223
        "Turns the module off once you run out of blocks.", true);
224
    private final BoolSetting disconnectOnStop = new BoolSetting("Disconnect on stop",
225
        "Leaves the server with the run totals whenever the module stops itself.", false);
226
    private final BoolSetting outline = new BoolSetting("Outline",
227
        "Draws the stretch being worked on.", true);
228
    private final ColorSetting outlineColor = new ColorSetting("Outline colour",
229
        "Colour of the outline.", 200, false).under(outline);
230
    private final BoolSetting renderMine = new BoolSetting("Show blocks to mine",
231
        "Draws every block still to come out of the stretch.", true);
232
    private final BoxStyle mineBox = new BoxStyle("Mine", BoxStyle.Shape.BOTH, 0)
233
        .under(renderMine);
234
    private final BoolSetting renderPlace = new BoolSetting("Show blocks to place",
235
        "Draws every block still to go into the stretch.", true);
236
    private final BoxStyle placeBox = new BoxStyle("Place", BoxStyle.Shape.BOTH, 220)
237
        .under(renderPlace);
238
239
    private final AxisWalker walker = new AxisWalker();
240
    private final SlotSwap slots = new SlotSwap();
241
242
    private int idleTicks;
243
    private double bestTravelled;
244
    private boolean walking;
245
246
    private BlockPos mineTarget;
247
    private BlockPos placeTarget;
248
249
    private int sinceBreak;
250
    private int sincePlace;
251
    private int sinceInventory;
252
    private int blocksBroken;
253
    private int blocksPlaced;
254
255
    // The block the hand was on last tick. Used only to count what really broke.
256
    private BlockPos wasMining;
257
258
    private PacketDig spare;
259
260
    private Stage stage = Stage.NONE;
261
    private BlockPos shulkerPos;
262
263
    // How much obsidian the running grind is heading for.
264
    private int grindGoal;
265
    private int stageTicks;
266
267
    private final Set<Integer> ignoredCrystals = new HashSet<>();
268
    private Entity crystal;
269
    private int crystalShots;
270
    private boolean drawing;
271
272
    // Every block of the shell around the player this tick.
273
    private final List<BlockPos> stretch = new ArrayList<>();
274
275
    // A second block taken down with packets whilst the hand works the first.
276
    private static final class PacketDig {
277
278
        private final BlockPos pos;
279
        private final Direction side;
280
        private float progress;
281
282
        private PacketDig(BlockPos pos, Direction side) {
283
            this.pos = pos;
284
            this.side = side;
285
        }
286
    }
287
288
    public HighwayBuilder() {
289
        super("HighwayBuilder", "Digs and builds a highway along one line at a fixed height.", Category.WORLD);
290
        addSettings(width, height, diagonal, movement, freeLook, skipUnreachable, reLevel,
291
            pauseOnLag, blocks, floor, replaceFloor, walls, wallHeight, replaceWalls,
292
            mineAboveWalls, ceiling, replaceCeiling, fillLiquids, torches, torchSpacing,
293
            torchHeight, rotation, breakDelay, breaksPerTick, doubleMine, fastBreak,
294
            savePickaxes, placeRange, placeDelay, placementsPerTick, restock, inventoryDelay,
295
            searchShulkers, searchEnderChest, mineEnderChests, saveEnderChests, grindAmount,
296
            grindBlockade, ejectShulkers, emptySlots, throwTrash, trash,
297
            crystalTraps, stopWhenEmpty, disconnectOnStop, outline,
298
            outlineColor, renderMine);
299
        addSettings(mineBox.settings());
300
        addSettings(renderPlace);
301
        addSettings(placeBox.settings());
302
        searchTags("highway", "nether", "tunnel", "road", "railings");
303
    }
304
305
    @Override
306
    public String getSuffix() {
307
        if (!walker.isLocked()) {
308
            return null;
309
        }
310
        return walker.heading() + " " + (int) Math.max(0, bestTravelled);
311
    }
312
313
    // Bringing this back at launch would start digging at once.
314
    @Override
315
    public boolean savesEnabledState() {
316
        return false;
317
    }
318
319
    @Override
320
    public ExclusivityGroup getExclusivityGroup() {
321
        return ExclusivityGroup.MINING;
322
    }
323
324
    @Override
325
    protected void onEnable() {
326
        walker.clear();
327
        slots.forget();
328
        mineTarget = null;
329
        placeTarget = null;
330
        spare = null;
331
        crystal = null;
332
        drawing = false;
333
        ignoredCrystals.clear();
334
        blocksBroken = 0;
335
        blocksPlaced = 0;
336
        sinceBreak = 0;
337
        sincePlace = 0;
338
        sinceInventory = 0;
339
        stage = Stage.NONE;
340
        shulkerPos = null;
341
        if (inGame()) {
342
            lockAxis();
343
            warnAboutModules();
344
        }
345
    }
346
347
    @Override
348
    protected void onDisable() {
349
        BlockMiner.release();
350
        slots.restoreIfMine();
351
        stopWalking();
352
        releaseBow();
353
        walker.clear();
354
        mineTarget = null;
355
        placeTarget = null;
356
        spare = null;
357
        stage = Stage.NONE;
358
        shulkerPos = null;
359
        stretch.clear();
360
        if (blocksBroken > 0 || blocksPlaced > 0) {
361
            ChatUtil.message("§bHighwayBuilder §7covered §f" + (int) bestTravelled
362
                + "§7 blocks and broke §f" + blocksBroken + "§7 and placed §f" + blocksPlaced + "§7.");
363
        }
364
    }
365
366
    private void warnAboutModules() {
367
        if (diagonal.isOn() && Modules.enabled(Speed.class)) {
368
            ChatUtil.error("Turn Speed off on a diagonal or you will drift off the line.");
369
        }
370
        if (!Modules.enabled(NoKnockback.class)) {
371
            ChatUtil.message("§bHighwayBuilder §7works better with §fNoKnockback§7 on.");
372
        }
373
    }
374
375
    private void lockAxis() {
376
        walker.lock(diagonal.isOn());
377
        idleTicks = 0;
378
        bestTravelled = 0;
379
    }
380
381
    @Subscribe
382
    private void onTick(TickEvent event) {
383
        countBreak();
384
        mineTarget = null;
385
        placeTarget = null;
386
        if (!inGame()) {
387
            stopWalking();
388
            return;
389
        }
390
        if (!walker.isLocked()) {
391
            lockAxis();
392
        }
393
        if (paused()) {
394
            stopWalking();
395
            BlockMiner.release();
396
            return;
397
        }
398
        if (!safeToWork()) {
399
            return;
400
        }
401
        boolean auto = movement.is(Movement.AUTO);
402
        // Manual hands the walking back rather than leaving the key held.
403
        if (!auto) {
404
            stopWalking();
405
        }
406
        walker.holdAxis(auto && !freeLook.isOn());
407
        trackProgress();
408
409
        double here = walker.travelled();
410
        gatherStretch(here - BEHIND, here + AHEAD);
411
        if (shootCrystal()) {
412
            stopWalking();
413
            return;
414
        }
415
        if (levelUp()) {
416
            stopWalking();
417
            return;
418
        }
419
        if (tidyInventory()) {
420
            stopWalking();
421
            return;
422
        }
423
        driveSpare();
424
        if (work()) {
425
            if (auto) {
426
                stopWalking();
427
            }
428
            return;
429
        }
430
        // Running out of blocks turns the module off inside a fill.
431
        if (!isEnabled()) {
432
            return;
433
        }
434
        if (auto) {
435
            walk(here);
436
        }
437
    }
438
439
    // Anything else with a claim on the hands takes the tick.
440
    private boolean paused() {
441
        if (pauseOnLag.isOn() && TickRate.INSTANCE.lagging(LAG_MILLIS)) {
442
            return true;
443
        }
444
        if (Modules.eating()) {
445
            return true;
446
        }
447
        KillAura aura = Modules.active(KillAura.class);
448
        return aura != null && aura.getTarget() != null;
449
    }
450
451
    private void countBreak() {
452
        if (wasMining != null && inGame() && BlockUtil.state(wasMining).isAir()) {
453
            blocksBroken++;
454
        }
455
        wasMining = null;
456
    }
457
458
    private boolean safeToWork() {
459
        if (mc.player.isSpectator() || mc.player.isPassenger()) {
460
            stop("HighwayBuilder stopped because you cannot build from there.");
461
            return false;
462
        }
463
        if (!reLevel.isOn() && Math.abs(mc.player.getY() - walker.floorY()) > 1.5) {
464
            stop("HighwayBuilder stopped because you left the highway floor.");
465
            return false;
466
        }
467
        if (savePickaxes.getInt() > 0 && pickaxeCount() <= savePickaxes.getInt()) {
468
            stop("HighwayBuilder stopped because you are nearly out of pickaxes.");
469
            return false;
470
        }
471
        if (movement.is(Movement.AUTO) && idleTicks > IDLE_LIMIT) {
472
            stop("HighwayBuilder stopped because it could not get any further.");
473
            return false;
474
        }
475
        return true;
476
    }
477
478
    private int pickaxeCount() {
479
        int total = 0;
480
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
481
            if (mc.player.getInventory().getItem(i).is(ItemTags.PICKAXES)) {
482
                total++;
483
            }
484
        }
485
        return total;
486
    }
487
488
    private void trackProgress() {
489
        double travelled = walker.travelled();
490
        if (travelled > bestTravelled + 0.05) {
491
            bestTravelled = travelled;
492
            idleTicks = 0;
493
        } else {
494
            idleTicks++;
495
        }
496
    }
497
498
    // Collects every block of the tunnel and its shell between two depths along the
499
    // line by sieving the box around the player by distance along and across it.
500
    private void gatherStretch(double from, double to) {
501
        stretch.clear();
502
        int reach = AHEAD + width.getInt() + 2;
503
        BlockPos centre = mc.player.blockPosition();
504
        int tall = height.getInt();
505
        double nearEdge = leftLane() - 1.5;
506
        double farEdge = rightLane() + 1.5;
507
        for (int dx = -reach; dx <= reach; dx++) {
508
            for (int dz = -reach; dz <= reach; dz++) {
509
                int x = centre.getX() + dx;
510
                int z = centre.getZ() + dz;
511
                double along = walker.alongOf(x + 0.5, z + 0.5);
512
                if (along < from || along > to) {
513
                    continue;
514
                }
515
                double across = walker.acrossOf(x + 0.5, z + 0.5);
516
                if (across < nearEdge || across > farEdge) {
517
                    continue;
518
                }
519
                for (int up = -1; up <= tall; up++) {
520
                    stretch.add(new BlockPos(x, walker.floorY() + up, z));
521
                }
522
            }
523
        }
524
    }
525
526
    // Does the nearest job across the stretch. Liquid goes first then clearing wins
527
    // over filling. True when the tick was spent.
528
    private boolean work() {
529
        if (fillLiquids.isOn()) {
530
            BlockPos plug = nearest(this::isLiquid, placeRange.getValue());
531
            if (plug != null) {
532
                placeTarget = plug;
533
                return placeRound(plug);
534
            }
535
        }
536
        BlockPos dig = nearest(this::needsClearing, mc.player.blockInteractionRange());
537
        if (dig != null) {
538
            return mine(dig);
539
        }
540
        BlockMiner.release();
541
        BlockPos fill = nearest(this::needsFilling, placeRange.getValue());
542
        if (fill != null) {
543
            placeTarget = fill;
544
            return placeRound(fill);
545
        }
546
        BlockPos torch = nearest(this::needsTorch, placeRange.getValue());
547
        if (torch != null) {
548
            return placeTorch(torch);
549
        }
550
        slots.restoreIfMine();
551
        return false;
552
    }
553
554
    private boolean mine(BlockPos dig) {
555
        if (sinceBreak < breakDelay.getInt()) {
556
            sinceBreak++;
557
            BlockMiner.release();
558
            return true;
559
        }
560
        mineTarget = dig;
561
        idleTicks = 0;
562
        slots.restoreIfMine();
563
        // With no mining rotation the server takes the packets on their own.
564
        if (!rotation.isAny(Rotation.MINE, Rotation.BOTH)) {
565
            return packetMine();
566
        }
567
        if (!BlockMiner.mine(dig, true)) {
568
            mineTarget = null;
569
            return false;
570
        }
571
        wasMining = dig;
572
        sinceBreak = 0;
573
        if (doubleMine.isOn() && spare == null) {
574
            takeSpare(dig);
575
        }
576
        return true;
577
    }
578
579
    // Sends the pair for a run of one hit blocks in the same tick.
580
    private boolean packetMine() {
581
        int sent = 0;
582
        for (BlockPos pos : stretch) {
583
            if (sent >= breaksPerTick.getInt()) {
584
                break;
585
            }
586
            if (!needsClearing(pos) || BlockUtil.distanceTo(pos) > mc.player.blockInteractionRange()) {
587
                continue;
588
            }
589
            if (!BlockUtil.canInstantBreak(pos)) {
590
                continue;
591
            }
592
            BlockMiner.breakInstantly(pos);
593
            blocksBroken++;
594
            sent++;
595
        }
596
        if (sent == 0 && mineTarget != null) {
597
            BlockMiner.breakInstantly(mineTarget);
598
            wasMining = mineTarget;
599
            sent = 1;
600
        }
601
        sinceBreak = 0;
602
        return sent > 0;
603
    }
604
605
    // Picks a second block for the packet miner. The one the hand is on is skipped.
606
    private void takeSpare(BlockPos busy) {
607
        double reach = mc.player.blockInteractionRange();
608
        BlockPos best = null;
609
        double bestDistance = Double.MAX_VALUE;
610
        for (BlockPos pos : stretch) {
611
            if (pos.equals(busy) || !needsClearing(pos)) {
612
                continue;
613
            }
614
            double distance = BlockUtil.distanceTo(pos);
615
            if (distance <= reach && distance < bestDistance) {
616
                bestDistance = distance;
617
                best = pos;
618
            }
619
        }
620
        if (best == null) {
621
            return;
622
        }
623
        Direction side = BlockUtil.facingSide(best);
624
        mc.player.connection.send(new ServerboundPlayerActionPacket(
625
            ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK, best, side));
626
        spare = new PacketDig(best, side);
627
    }
628
629
    // Feeds the second block its progress and stops it once it is due.
630
    private void driveSpare() {
631
        if (spare == null) {
632
            return;
633
        }
634
        if (!needsClearing(spare.pos) || BlockUtil.distanceTo(spare.pos) > mc.player.blockInteractionRange()) {
635
            spare = null;
636
            return;
637
        }
638
        spare.progress += BlockUtil.breakDelta(mc.player.getMainHandItem(), spare.pos);
639
        float due = fastBreak.isOn() ? 0.7f : 1f;
640
        if (spare.progress < due) {
641
            return;
642
        }
643
        mc.player.connection.send(new ServerboundPlayerActionPacket(
644
            ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK, spare.pos, spare.side));
645
        blocksBroken++;
646
        spare = null;
647
    }
648
649
    // The closest block of the stretch within the reach that passes the test.
650
    private BlockPos nearest(Predicate<BlockPos> wanted, double reach) {
651
        BlockPos best = null;
652
        double bestDistance = Double.MAX_VALUE;
653
        for (BlockPos pos : stretch) {
654
            if (!wanted.test(pos)) {
655
                continue;
656
            }
657
            double distance = BlockUtil.distanceTo(pos);
658
            if (distance <= reach && distance < bestDistance) {
659
                bestDistance = distance;
660
                best = pos;
661
            }
662
        }
663
        return best;
664
    }
665
666
    private enum Part { TUNNEL, FLOOR, WALL, ABOVE_WALL, CEILING, OUTSIDE }
667
668
    // Walls off leaves the whole column beside the tunnel alone.
669
    private int wallTall() {
670
        return walls.isOn() ? Math.min(wallHeight.getInt(), height.getInt()) : height.getInt();
671
    }
672
673
    // Which part of the highway a block belongs to by where its middle falls.
674
    private Part partOf(BlockPos pos) {
675
        int up = pos.getY() - walker.floorY();
676
        double across = walker.acrossOf(pos);
677
        boolean inside = across >= leftLane() - 0.5 && across <= rightLane() + 0.5;
678
        boolean beside = !inside && across >= leftLane() - 1.5 && across <= rightLane() + 1.5;
679
        int tall = height.getInt();
680
        if (inside && up >= 0 && up < tall) {
681
            return Part.TUNNEL;
682
        }
683
        if (inside && up == -1) {
684
            return Part.FLOOR;
685
        }
686
        if (beside && up >= 0 && up < wallTall()) {
687
            return Part.WALL;
688
        }
689
        if (beside && up >= wallTall() && up < tall) {
690
            return Part.ABOVE_WALL;
691
        }
692
        if (up == tall && (inside || (beside && walls.isOn() && wallTall() == tall))) {
693
            return Part.CEILING;
694
        }
695
        // The blocks the walls stand on are part of the floor once walls are wanted.
696
        if (beside && up == -1 && walls.isOn()) {
697
            return Part.FLOOR;
698
        }
699
        return Part.OUTSIDE;
700
    }
701
702
    // Anything in the tunnel or a shell block off the list when that shell is replaced.
703
    private boolean needsClearing(BlockPos pos) {
704
        if (!BlockUtil.diggable(pos) || BlockUtil.isStandingOn(pos)) {
705
            return false;
706
        }
707
        Part part = partOf(pos);
708
        if (part == Part.TUNNEL) {
709
            // Torches light the way and never block it.
710
            return !isTorch(BlockUtil.state(pos).getBlock());
711
        }
712
        if (part == Part.ABOVE_WALL) {
713
            return mineAboveWalls.isOn() && !isTorch(BlockUtil.state(pos).getBlock());
714
        }
715
        if (allowed(BlockUtil.state(pos).getBlock())) {
716
            return false;
717
        }
718
        return switch (part) {
719
            case FLOOR -> floor.isOn() && replaceFloor.isOn();
720
            case WALL -> walls.isOn() && replaceWalls.isOn();
721
            case CEILING -> ceiling.isOn() && replaceCeiling.isOn();
722
            default -> false;
723
        };
724
    }
725
726
    private boolean needsFilling(BlockPos pos) {
727
        if (!BlockUtil.isReplaceable(pos) || BlockUtil.intersectsPlayer(pos)) {
728
            return false;
729
        }
730
        return switch (partOf(pos)) {
731
            case FLOOR -> floor.isOn();
732
            case WALL -> walls.isOn();
733
            case CEILING -> ceiling.isOn();
734
            default -> false;
735
        };
736
    }
737
738
    // Liquid anywhere in the shell is plugged whatever part it sits in.
739
    private boolean isLiquid(BlockPos pos) {
740
        if (mc.level.getFluidState(pos).isEmpty() || BlockUtil.intersectsPlayer(pos)) {
741
            return false;
742
        }
743
        return BlockUtil.isReplaceable(pos) && partOf(pos) != Part.OUTSIDE;
744
    }
745
746
    // Places up to the round size at the target and around it.
747
    private boolean placeRound(BlockPos first) {
748
        if (sincePlace < placeDelay.getInt()) {
749
            sincePlace++;
750
            return true;
751
        }
752
        if (!place(first)) {
753
            return false;
754
        }
755
        sincePlace = 0;
756
        int placed = 1;
757
        while (placed < placementsPerTick.getInt()) {
758
            BlockPos next = nearest(pos -> !pos.equals(first)
759
                && (needsFilling(pos) || (fillLiquids.isOn() && isLiquid(pos))), placeRange.getValue());
760
            if (next == null || !place(next)) {
761
                break;
762
            }
763
            placed++;
764
        }
765
        return true;
766
    }
767
768
    // A block goes against a neighbour if there is one and into the air if there is not.
769
    private boolean place(BlockPos target) {
770
        int slot = BlockUtil.findBlockSlot(this::allowed);
771
        if (slot == -1) {
772
            if (stopWhenEmpty.isOn()) {
773
                stop("HighwayBuilder stopped because you ran out of blocks.");
774
            }
775
            return false;
776
        }
777
        slots.select(slot);
778
        boolean placed = BlockUtil.placeAny(target, rotation.isAny(Rotation.PLACE, Rotation.BOTH), true);
779
        if (placed) {
780
            idleTicks = 0;
781
            blocksPlaced++;
782
        }
783
        return placed;
784
    }
785
786
    // The torch never sits above the top of the tunnel.
787
    private int torchUp() {
788
        return Math.min(torchHeight.getInt(), height.getInt() - 1);
789
    }
790
791
    // The torch spots sit on the left edge every few blocks at the chosen height. On the
792
    // floor a torch stands on the block below. Higher up it hangs on the wall beside it.
793
    private boolean needsTorch(BlockPos pos) {
794
        if (!torches.isOn() || pos.getY() - walker.floorY() != torchUp()) {
795
            return false;
796
        }
797
        double across = walker.acrossOf(pos);
798
        if (across < leftLane() - 0.5 || across >= leftLane() + 0.5) {
799
            return false;
800
        }
801
        int depth = walker.depthOf(pos);
802
        if (depth <= 0 || depth % torchSpacing.getInt() != 0) {
803
            return false;
804
        }
805
        return BlockUtil.isReplaceable(pos) && !BlockUtil.intersectsPlayer(pos) && torchSupport(pos) != null;
806
    }
807
808
    private Direction torchSupport(BlockPos pos) {
809
        if (BlockUtil.isSolid(pos.below())) {
810
            return Direction.DOWN;
811
        }
812
        for (Direction side : Direction.Plane.HORIZONTAL) {
813
            BlockPos beside = pos.relative(side);
814
            if (BlockUtil.isSolid(beside) && partOf(beside) == Part.WALL) {
815
                return side;
816
            }
817
        }
818
        return null;
819
    }
820
821
    private boolean placeTorch(BlockPos pos) {
822
        int slot = BlockUtil.findBlockSlot(block -> block == Blocks.TORCH || block == Blocks.SOUL_TORCH);
823
        if (slot == -1) {
824
            return false;
825
        }
826
        Direction support = torchSupport(pos);
827
        if (support == null) {
828
            return false;
829
        }
830
        slots.select(slot);
831
        boolean placed = BlockUtil.place(pos, support, rotation.isAny(Rotation.PLACE, Rotation.BOTH), true);
832
        slots.restoreIfMine();
833
        return placed;
834
    }
835
836
    // Jumps and paves underfoot after a fall. The line keeps its height.
837
    private boolean levelUp() {
838
        if (!reLevel.isOn()) {
839
            return false;
840
        }
841
        double drop = walker.floorY() - mc.player.getY();
842
        if (drop < 0.5) {
843
            return false;
844
        }
845
        if (mc.player.onGround()) {
846
            mc.player.jumpFromGround();
847
            return true;
848
        }
849
        BlockPos under = mc.player.blockPosition().below();
850
        if (mc.player.getDeltaMovement().y < 0 && BlockUtil.isReplaceable(under)) {
851
            place(under);
852
        }
853
        return true;
854
    }
855
856
    // Moves what the build needs up into the hotbar and drops what it does not.
857
    private boolean tidyInventory() {
858
        if (stage == Stage.GRIND) {
859
            return enderChestGrind();
860
        }
861
        if (stage != Stage.NONE) {
862
            return shulkerRestock();
863
        }
864
        if (sinceInventory < inventoryDelay.getInt()) {
865
            sinceInventory++;
866
            return false;
867
        }
868
        if (restock.isOn() && restockHotbar()) {
869
            return true;
870
        }
871
        if (searchShulkers.isOn() && shulkerRestock()) {
872
            return true;
873
        }
874
        if (mineEnderChests.isOn() && enderChestGrind()) {
875
            return true;
876
        }
877
        if (searchEnderChest.isOn() && enderChestRestock()) {
878
            return true;
879
        }
880
        if (ejectShulkers.isOn() && dropUselessShulker()) {
881
            return true;
882
        }
883
        return throwTrash.isOn() && dropTrash();
884
    }
885
886
    // Puts a shulker down behind you and empties it then mines it back.
887
    private boolean shulkerRestock() {
888
        if (stage == Stage.NONE) {
889
            return startRestock();
890
        }
891
        if (++stageTicks > RESTOCK_LIMIT || shulkerPos == null) {
892
            endRestock();
893
            return false;
894
        }
895
        BlockState container = BlockUtil.state(shulkerPos);
896
        boolean standing = container.getBlock() instanceof ShulkerBoxBlock || container.is(Blocks.ENDER_CHEST);
897
        if (stage == Stage.BREAK) {
898
            if (!standing) {
899
                endRestock();
900
                return false;
901
            }
902
            // Without Silk Touch an ender chest breaks into obsidian. It is left standing instead.
903
            if (container.is(Blocks.ENDER_CHEST) && !holdSilkTouch(container)) {
904
                endRestock();
905
                return false;
906
            }
907
            BlockMiner.mine(shulkerPos, rotation.isAny(Rotation.MINE, Rotation.BOTH));
908
            return true;
909
        }
910
        if (!standing) {
911
            endRestock();
912
            return false;
913
        }
914
        if (!(mc.gui.screen() instanceof AbstractContainerScreen<?>)) {
915
            BlockUtil.useOn(shulkerPos, rotation.isAny(Rotation.PLACE, Rotation.BOTH), true);
916
            return true;
917
        }
918
        return emptyShulker();
919
    }
920
921
    private boolean startRestock() {
922
        if (hasBlocksSomewhere() || mc.player.getInventory().getFreeSlot() == -1) {
923
            return false;
924
        }
925
        int slot = InventoryUtil.findSlot(this::usefulShulker, InventoryUtil.WHOLE_INVENTORY);
926
        if (slot == -1) {
927
            return false;
928
        }
929
        if (slot >= InventoryUtil.HOTBAR_SIZE) {
930
            return moveToHotbar(slot);
931
        }
932
        BlockPos spot = restockSpot();
933
        if (spot == null) {
934
            return false;
935
        }
936
        slots.select(slot);
937
        if (!BlockUtil.placeAny(spot, rotation.isAny(Rotation.PLACE, Rotation.BOTH), true)) {
938
            return false;
939
        }
940
        shulkerPos = spot;
941
        stage = Stage.TAKE;
942
        stageTicks = 0;
943
        return true;
944
    }
945
946
    // Sets an ender chest down and empties it the way a shulker is emptied.
947
    private boolean enderChestRestock() {
948
        if (hasBlocksSomewhere() || mc.player.getInventory().getFreeSlot() == -1) {
949
            return false;
950
        }
951
        int slot = InventoryUtil.findSlot(Items.ENDER_CHEST, InventoryUtil.WHOLE_INVENTORY);
952
        if (slot == -1) {
953
            return false;
954
        }
955
        if (slot >= InventoryUtil.HOTBAR_SIZE) {
956
            return moveToHotbar(slot);
957
        }
958
        BlockPos spot = restockSpot();
959
        if (spot == null) {
960
            return false;
961
        }
962
        slots.select(slot);
963
        if (!BlockUtil.placeAny(spot, rotation.isAny(Rotation.PLACE, Rotation.BOTH), true)) {
964
            return false;
965
        }
966
        shulkerPos = spot;
967
        stage = Stage.TAKE;
968
        stageTicks = 0;
969
        return true;
970
    }
971
972
    // Sets ender chests down behind you and mines them back for obsidian until enough is held.
973
    private boolean enderChestGrind() {
974
        if (stage == Stage.NONE) {
975
            if (hasBlocksSomewhere() || !allowed(Blocks.OBSIDIAN)
976
                || enderChests() <= saveEnderChests.getInt()) {
977
                return false;
978
            }
979
            BlockPos spot = restockSpot();
980
            if (spot == null) {
981
                return false;
982
            }
983
            shulkerPos = spot;
984
            grindGoal = obsidian() + grindAmount.getInt();
985
            stage = Stage.GRIND;
986
            stageTicks = 0;
987
            return true;
988
        }
989
        BlockState state = BlockUtil.state(shulkerPos);
990
        boolean chestDown = state.is(Blocks.ENDER_CHEST);
991
        if (++stageTicks > GRIND_LIMIT || obsidian() >= grindGoal
992
            || (!chestDown && enderChests() <= saveEnderChests.getInt())) {
993
            endRestock();
994
            return false;
995
        }
996
        if (grindBlockade.isOn() && buildBlockade()) {
997
            return true;
998
        }
999
        if (chestDown) {
1000
            if (!holdPlainPickaxe(state)) {
1001
                ChatUtil.error("HighwayBuilder needs a pickaxe without Silk Touch to grind ender chests.");
1002
                endRestock();
1003
                return false;
1004
            }
1005
            BlockMiner.mine(shulkerPos, rotation.isAny(Rotation.MINE, Rotation.BOTH));
1006
            return true;
1007
        }
1008
        BlockMiner.release();
1009
        if (!BlockUtil.isReplaceable(shulkerPos)) {
1010
            endRestock();
1011
            return false;
1012
        }
1013
        int slot = InventoryUtil.findSlot(Items.ENDER_CHEST, InventoryUtil.WHOLE_INVENTORY);
1014
        if (slot >= InventoryUtil.HOTBAR_SIZE) {
1015
            return moveToHotbar(slot);
1016
        }
1017
        slots.select(slot);
1018
        BlockUtil.placeAny(shulkerPos, rotation.isAny(Rotation.PLACE, Rotation.BOTH), true);
1019
        return true;
1020
    }
1021
1022
    // Fills the sides round you at foot and head height apart from the chest spot.
1023
    // True when a block went down this tick.
1024
    private boolean buildBlockade() {
1025
        BlockPos feet = mc.player.blockPosition();
1026
        for (int up = 0; up < 2; up++) {
1027
            for (Direction side : Direction.Plane.HORIZONTAL) {
1028
                BlockPos pos = feet.above(up).relative(side);
1029
                if (pos.equals(shulkerPos) || !BlockUtil.isReplaceable(pos)) {
1030
                    continue;
1031
                }
1032
                int slot = BlockUtil.findBlockSlot();
1033
                if (slot == -1) {
1034
                    return false;
1035
                }
1036
                slots.select(slot);
1037
                return BlockUtil.placeAny(pos, rotation.isAny(Rotation.PLACE, Rotation.BOTH), true);
1038
            }
1039
        }
1040
        return false;
1041
    }
1042
1043
    // Selects a pickaxe of the given kind for the block. True once one is in hand.
1044
    private boolean holdPickaxe(BlockState state, boolean silkTouch) {
1045
        int slot = ItemUtil.bestToolSlot(state, 1,
1046
            stack -> (ItemUtil.enchantLevel(Enchantments.SILK_TOUCH, stack) > 0) == silkTouch,
1047
            InventoryUtil.HOTBAR_SIZE);
1048
        if (slot == -1) {
1049
            return false;
1050
        }
1051
        slots.select(slot);
1052
        return true;
1053
    }
1054
1055
    private boolean holdSilkTouch(BlockState state) {
1056
        return holdPickaxe(state, true);
1057
    }
1058
1059
    private boolean holdPlainPickaxe(BlockState state) {
1060
        return holdPickaxe(state, false);
1061
    }
1062
1063
    private int enderChests() {
1064
        return InventoryUtil.count(Items.ENDER_CHEST, InventoryUtil.WHOLE_INVENTORY);
1065
    }
1066
1067
    private int obsidian() {
1068
        return InventoryUtil.count(Items.OBSIDIAN, InventoryUtil.WHOLE_INVENTORY);
1069
    }
1070
1071
    // Quick moves what the build needs and closes once there is nothing left.
1072
    private boolean emptyShulker() {
1073
        if (sinceInventory < inventoryDelay.getInt()) {
1074
            sinceInventory++;
1075
            return true;
1076
        }
1077
        AbstractContainerMenu menu = mc.player.containerMenu;
1078
        int containerSlots = menu.slots.size() - InventoryUtil.WHOLE_INVENTORY;
1079
        if (containerSlots > 0 && freeSlots() > emptySlots.getInt()) {
1080
            for (int i = 0; i < containerSlots; i++) {
1081
                Slot slot = menu.slots.get(i);
1082
                if (!slot.hasItem() || !neededItem(slot.getItem())) {
1083
                    continue;
1084
                }
1085
                mc.gameMode.handleContainerInput(menu.containerId, i, 0,
1086
                    ContainerInput.QUICK_MOVE, mc.player);
1087
                sinceInventory = 0;
1088
                return true;
1089
            }
1090
        }
1091
        mc.player.closeContainer();
1092
        stage = Stage.BREAK;
1093
        stageTicks = 0;
1094
        return true;
1095
    }
1096
1097
    private void endRestock() {
1098
        stage = Stage.NONE;
1099
        shulkerPos = null;
1100
        BlockMiner.release();
1101
    }
1102
1103
    // The block behind you at floor level or one beside it.
1104
    private BlockPos restockSpot() {
1105
        BlockPos feet = mc.player.blockPosition();
1106
        List<BlockPos> tries = new ArrayList<>();
1107
        tries.add(feet.relative(mc.player.getDirection().getOpposite()));
1108
        for (Direction side : Direction.Plane.HORIZONTAL) {
1109
            tries.add(feet.relative(side));
1110
        }
1111
        for (BlockPos spot : tries) {
1112
            if (BlockUtil.isReplaceable(spot) && !BlockUtil.intersectsPlayer(spot)
1113
                && BlockUtil.isSolid(spot.below())) {
1114
                return spot;
1115
            }
1116
        }
1117
        return null;
1118
    }
1119
1120
    private boolean hasBlocksSomewhere() {
1121
        return InventoryUtil.findSlot(stack -> stack.getItem() instanceof BlockItem item
1122
            && allowed(item.getBlock()), InventoryUtil.WHOLE_INVENTORY) != -1;
1123
    }
1124
1125
    private int freeSlots() {
1126
        int free = 0;
1127
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
1128
            if (mc.player.getInventory().getItem(i).isEmpty()) {
1129
                free++;
1130
            }
1131
        }
1132
        return free;
1133
    }
1134
1135
    private boolean neededItem(ItemStack stack) {
1136
        return (stack.getItem() instanceof BlockItem item && allowed(item.getBlock()))
1137
            || stack.is(ItemTags.PICKAXES) || stack.has(DataComponents.FOOD);
1138
    }
1139
1140
    private boolean usefulShulker(ItemStack stack) {
1141
        if (!(stack.getItem() instanceof BlockItem item)
1142
            || !(item.getBlock() instanceof ShulkerBoxBlock)) {
1143
            return false;
1144
        }
1145
        ItemContainerContents contents = stack.get(DataComponents.CONTAINER);
1146
        if (contents == null) {
1147
            return false;
1148
        }
1149
        return contents.nonEmptyItemCopyStream().anyMatch(this::neededItem);
1150
    }
1151
1152
    // A shulker with nothing the build wants is dead weight.
1153
    private boolean dropUselessShulker() {
1154
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
1155
            ItemStack stack = mc.player.getInventory().getItem(i);
1156
            if (!(stack.getItem() instanceof BlockItem item)
1157
                || !(item.getBlock() instanceof ShulkerBoxBlock) || usefulShulker(stack)) {
1158
                continue;
1159
            }
1160
            mc.gameMode.handleContainerInput(0, InventoryUtil.networkSlot(i), 1,
1161
                ContainerInput.THROW, mc.player);
1162
            sinceInventory = 0;
1163
            return true;
1164
        }
1165
        return false;
1166
    }
1167
1168
    private boolean restockHotbar() {
1169
        if (BlockUtil.findBlockSlot(this::allowed) == -1) {
1170
            int from = InventoryUtil.findSlot(stack -> stack.getItem() instanceof BlockItem item
1171
                && allowed(item.getBlock()), InventoryUtil.WHOLE_INVENTORY);
1172
            if (from >= InventoryUtil.HOTBAR_SIZE) {
1173
                return moveToHotbar(from);
1174
            }
1175
        }
1176
        if (InventoryUtil.hotbarSlot(stack -> stack.is(ItemTags.PICKAXES)) == -1) {
1177
            int from = InventoryUtil.findSlot(stack -> stack.is(ItemTags.PICKAXES),
1178
                InventoryUtil.WHOLE_INVENTORY);
1179
            if (from >= InventoryUtil.HOTBAR_SIZE) {
1180
                return moveToHotbar(from);
1181
            }
1182
        }
1183
        return false;
1184
    }
1185
1186
    private boolean moveToHotbar(int from) {
1187
        InventoryUtil.swap(InventoryUtil.networkSlot(from), InventoryUtil.networkSlot(spareHotbarSlot()));
1188
        sinceInventory = 0;
1189
        return true;
1190
    }
1191
1192
    // An empty slot first then a tool then trash then the smallest stack of blocks.
1193
    private int spareHotbarSlot() {
1194
        int smallest = -1;
1195
        int smallestCount = Integer.MAX_VALUE;
1196
        int tool = -1;
1197
        int rubbish = -1;
1198
        for (int i = 0; i < InventoryUtil.HOTBAR_SIZE; i++) {
1199
            ItemStack stack = mc.player.getInventory().getItem(i);
1200
            if (stack.isEmpty()) {
1201
                return i;
1202
            }
1203
            if (trash.contains(stack.getItem())) {
1204
                rubbish = i;
1205
            } else if (stack.isDamageableItem() && !stack.is(ItemTags.PICKAXES)) {
1206
                tool = i;
1207
            } else if (stack.getItem() instanceof BlockItem && stack.getCount() < smallestCount) {
1208
                smallestCount = stack.getCount();
1209
                smallest = i;
1210
            }
1211
        }
1212
        if (tool != -1) {
1213
            return tool;
1214
        }
1215
        if (rubbish != -1) {
1216
            return rubbish;
1217
        }
1218
        return smallest == -1 ? InventoryUtil.HOTBAR_SIZE - 1 : smallest;
1219
    }
1220
1221
    // The biggest trash block stack stays behind for plugging liquid and corners.
1222
    private boolean dropTrash() {
1223
        int keep = -1;
1224
        int keepCount = 0;
1225
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
1226
            ItemStack stack = mc.player.getInventory().getItem(i);
1227
            if (stack.getItem() instanceof BlockItem && trash.contains(stack.getItem())
1228
                && stack.getCount() > keepCount) {
1229
                keepCount = stack.getCount();
1230
                keep = i;
1231
            }
1232
        }
1233
        for (int i = 0; i < InventoryUtil.WHOLE_INVENTORY; i++) {
1234
            ItemStack stack = mc.player.getInventory().getItem(i);
1235
            if (i == keep || stack.isEmpty() || !trash.contains(stack.getItem())) {
1236
                continue;
1237
            }
1238
            // Facing back and up keeps the pile off the line ahead.
1239
            RotationManager.requestExact(mc.player.getYRot() + 180, -25, RotationPriority.IDLE);
1240
            mc.gameMode.handleContainerInput(0, InventoryUtil.networkSlot(i), 1,
1241
                ContainerInput.THROW, mc.player);
1242
            sinceInventory = 0;
1243
            return true;
1244
        }
1245
        return false;
1246
    }
1247
1248
    // An end crystal in the way is a trap. Three arrows and then it is left alone.
1249
    private boolean shootCrystal() {
1250
        if (!crystalTraps.isOn()) {
1251
            releaseBow();
1252
            return false;
1253
        }
1254
        if (crystal != null && (!crystal.isAlive() || outOfBand(crystal))) {
1255
            ignoredCrystals.add(crystal.getId());
1256
            crystal = null;
1257
            crystalShots = 0;
1258
        }
1259
        if (crystal == null) {
1260
            crystal = findCrystal();
1261
            crystalShots = 0;
1262
        }
1263
        if (crystal == null) {
1264
            releaseBow();
1265
            return false;
1266
        }
1267
        int slot = InventoryUtil.hotbarSlot(stack -> stack.is(Items.BOW));
1268
        if (slot == -1) {
1269
            ignoredCrystals.add(crystal.getId());
1270
            crystal = null;
1271
            return false;
1272
        }
1273
        BlockMiner.release();
1274
        slots.select(slot);
1275
        aimAtCrystal();
1276
        if (mc.player.getTicksUsingItem() >= FULL_DRAW) {
1277
            releaseBow();
1278
            crystalShots++;
1279
            if (crystalShots >= CRYSTAL_SHOTS) {
1280
                ignoredCrystals.add(crystal.getId());
1281
                crystal = null;
1282
            }
1283
            return true;
1284
        }
1285
        InputUtil.hold(mc.options.keyUse);
1286
        drawing = true;
1287
        return true;
1288
    }
1289
1290
    private void releaseBow() {
1291
        if (drawing) {
1292
            InputUtil.release(mc.options.keyUse);
1293
            drawing = false;
1294
        }
1295
    }
1296
1297
    private Entity findCrystal() {
1298
        Entity best = null;
1299
        double bestDistance = Double.MAX_VALUE;
1300
        for (Entity entity : mc.level.entitiesForRendering()) {
1301
            if (!(entity instanceof EndCrystal) || ignoredCrystals.contains(entity.getId())) {
1302
                continue;
1303
            }
1304
            if (outOfBand(entity) || !mc.player.hasLineOfSight(entity)) {
1305
                continue;
1306
            }
1307
            double distance = mc.player.distanceTo(entity);
1308
            if (distance < bestDistance) {
1309
                bestDistance = distance;
1310
                best = entity;
1311
            }
1312
        }
1313
        return best;
1314
    }
1315
1316
    private boolean outOfBand(Entity entity) {
1317
        double distance = mc.player.distanceTo(entity);
1318
        return distance < CRYSTAL_NEAR || distance > CRYSTAL_FAR;
1319
    }
1320
1321
    private void aimAtCrystal() {
1322
        Vec3 eye = mc.player.getEyePosition();
1323
        Vec3 at = crystal.getBoundingBox().getCenter();
1324
        double dx = at.x - eye.x;
1325
        double dz = at.z - eye.z;
1326
        float yaw = (float) Math.toDegrees(Math.atan2(dz, dx)) - 90f;
1327
        RotationManager.requestExact(yaw, bowPitch(eye, at), RotationPriority.ATTACK);
1328
    }
1329
1330
    // The lower of the two arcs that reach the point with no drag worked in.
1331
    private static float bowPitch(Vec3 from, Vec3 to) {
1332
        double dx = to.x - from.x;
1333
        double dz = to.z - from.z;
1334
        double flat = Math.sqrt(dx * dx + dz * dz);
1335
        double rise = to.y - from.y;
1336
        double g = ProjectileUtil.ARROW_GRAVITY;
1337
        double v2 = BOW_SPEED * BOW_SPEED;
1338
        double root = v2 * v2 - g * (g * flat * flat + 2 * rise * v2);
1339
        if (root < 0 || flat < 0.01) {
1340
            return (float) -Math.toDegrees(Math.atan2(rise, Math.max(flat, 0.01)));
1341
        }
1342
        double angle = Math.atan((v2 - Math.sqrt(root)) / (g * flat));
1343
        return (float) -Math.toDegrees(angle);
1344
    }
1345
1346
    // Walks once the stretch just ahead is finished or only holds work out of reach.
1347
    private void walk(double here) {
1348
        slots.restoreIfMine();
1349
        boolean go = stretchDone(here + 1, here + LEAD);
1350
        if (freeLook.isOn()) {
1351
            stopWalking();
1352
            if (go) {
1353
                walker.walkAlong(WALK_SPEED);
1354
            }
1355
            return;
1356
        }
1357
        walking = go;
1358
        if (go) {
1359
            mc.options.keyUp.setDown(true);
1360
        } else {
1361
            InputUtil.release(mc.options.keyUp);
1362
        }
1363
    }
1364
1365
    private boolean stretchDone(double from, double to) {
1366
        double reach = mc.player.blockInteractionRange();
1367
        for (BlockPos pos : stretch) {
1368
            double along = walker.alongOf(pos);
1369
            if (along < from || along > to) {
1370
                continue;
1371
            }
1372
            if (!needsClearing(pos) && !needsFilling(pos)) {
1373
                continue;
1374
            }
1375
            if (!skipUnreachable.isOn() || BlockUtil.distanceTo(pos) <= reach) {
1376
                return false;
1377
            }
1378
        }
1379
        return true;
1380
    }
1381
1382
    private void stopWalking() {
1383
        if (walking) {
1384
            walking = false;
1385
            InputUtil.release(mc.options.keyUp);
1386
        }
1387
    }
1388
1389
    // An empty list means any plain building block will do.
1390
    private boolean allowed(Block block) {
1391
        if (blocks.size() == 0) {
1392
            return BlockUtil.isBuildingBlock(block, BlockPos.ZERO);
1393
        }
1394
        return blocks.contains(block);
1395
    }
1396
1397
    private static boolean isTorch(Block block) {
1398
        return block == Blocks.TORCH || block == Blocks.WALL_TORCH
1399
            || block == Blocks.SOUL_TORCH || block == Blocks.SOUL_WALL_TORCH;
1400
    }
1401
1402
    private int leftLane() {
1403
        return -((width.getInt() - 1) / 2);
1404
    }
1405
1406
    private int rightLane() {
1407
        return width.getInt() - 1 + leftLane();
1408
    }
1409
1410
    private void stop(String reason) {
1411
        ChatUtil.error(reason);
1412
        String totals = "§7Went §f" + (int) bestTravelled + "§7 blocks. Broke §f"
1413
            + blocksBroken + "§7 and placed §f" + blocksPlaced + "§7.";
1414
        boolean leave = disconnectOnStop.isOn() && inGame();
1415
        setEnabled(false);
1416
        if (leave) {
1417
            mc.player.connection.getConnection().disconnect(
1418
                Component.literal("§b[§3Offline§b] §fHighwayBuilder stopped.\n§7" + reason + "\n" + totals));
1419
        }
1420
    }
1421
1422
    @Subscribe
1423
    private void onRender3D(Render3DEvent event) {
1424
        if (!walker.isLocked() || !inGame()) {
1425
            return;
1426
        }
1427
        if (outline.isOn()) {
1428
            drawStretch(event);
1429
        }
1430
        drawJobs(event);
1431
    }
1432
1433
    private void drawJobs(Render3DEvent event) {
1434
        int drawn = 0;
1435
        for (BlockPos pos : stretch) {
1436
            if (drawn >= MAX_DRAWN) {
1437
                return;
1438
            }
1439
            if (renderMine.isOn() && needsClearing(pos)) {
1440
                mineBox.draw(event.getBatch(), pos, false);
1441
                drawn++;
1442
            } else if (renderPlace.isOn()
1443
                && (needsFilling(pos) || (fillLiquids.isOn() && isLiquid(pos)))) {
1444
                placeBox.draw(event.getBatch(), pos, false);
1445
                drawn++;
1446
            }
1447
        }
1448
    }
1449
1450
    // A frame around the tunnel from just behind the player to the end of the reach.
1451
    private void drawStretch(Render3DEvent event) {
1452
        int color = ColorUtil.withAlpha(outlineColor.getColor(), 255);
1453
        double here = Math.floor(walker.travelled());
1454
        double from = here - BEHIND;
1455
        double to = here + AHEAD + 1;
1456
        double left = leftLane() - 0.5;
1457
        double right = rightLane() + 0.5;
1458
        int tall = height.getInt();
1459
        Vec3[] corners = {
1460
            walker.pointAt(from, left, 0), walker.pointAt(from, right, 0),
1461
            walker.pointAt(to, right, 0), walker.pointAt(to, left, 0)
1462
        };
1463
        for (int i = 0; i < 4; i++) {
1464
            Vec3 a = corners[i];
1465
            Vec3 b = corners[(i + 1) % 4];
1466
            event.getBatch().line(a, b, color, true);
1467
            event.getBatch().line(a.add(0, tall, 0), b.add(0, tall, 0), color, true);
1468
            event.getBatch().line(a, a.add(0, tall, 0), color, true);
1469
        }
1470
    }
1471
}
1472