scaffold module

scaffold: Minecraft 26.3 cheat module, full source for every implementation (6 clients: Meteor Client, MelaHack (ThunderHack fork), OfflineClient, …).

6 implementationsMovementMOVEMENTWORLDPLAYERPlayer

Full module source: 6 implementations

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

Meteor ClientMovementsrc/main/java/meteordevelopment/meteorclient/systems/modules/movement/Scaffold.javaJava · 324 lines · 12.9 KB

Automatically places blocks under you.

Settingsblocksblocks-filterfast-towertower-speedwhile-movingonly-on-clickswingauto-switchrotateair-placeahead-distanceclosest-block-rangeradiusblocks-per-tickrendershape-modeside-colorline-color
Scaffold.javaJava · Minecraft 26.2 · 324 lines · 12.9 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
3
 * Copyright (c) Meteor Development.
4
 */
5
6
package meteordevelopment.meteorclient.systems.modules.movement;
7
8
import com.google.common.collect.Streams;
9
import meteordevelopment.meteorclient.events.world.TickEvent;
10
import meteordevelopment.meteorclient.renderer.ShapeMode;
11
import meteordevelopment.meteorclient.settings.*;
12
import meteordevelopment.meteorclient.systems.modules.Categories;
13
import meteordevelopment.meteorclient.systems.modules.Module;
14
import meteordevelopment.meteorclient.utils.misc.ListMode;
15
import meteordevelopment.meteorclient.utils.player.FindItemResult;
16
import meteordevelopment.meteorclient.utils.player.InvUtils;
17
import meteordevelopment.meteorclient.utils.player.PlayerUtils;
18
import meteordevelopment.meteorclient.utils.render.RenderUtils;
19
import meteordevelopment.meteorclient.utils.render.color.SettingColor;
20
import meteordevelopment.meteorclient.utils.world.BlockUtils;
21
import meteordevelopment.orbit.EventHandler;
22
import net.minecraft.core.BlockPos;
23
import net.minecraft.world.item.BlockItem;
24
import net.minecraft.world.item.ItemStack;
25
import net.minecraft.world.level.block.Block;
26
import net.minecraft.world.level.block.FallingBlock;
27
import net.minecraft.world.phys.AABB;
28
import net.minecraft.world.phys.Vec3;
29
30
import java.util.ArrayList;
31
import java.util.Comparator;
32
import java.util.List;
33
34
public class Scaffold extends Module {
35
    private final SettingGroup sgGeneral = settings.getDefaultGroup();
36
    private final SettingGroup sgRender = settings.createGroup("Render");
37
38
    private final Setting<List<Block>> blocks = sgGeneral.add(new BlockListSetting.Builder()
39
        .name("blocks")
40
        .description("Selected blocks.")
41
        .build()
42
    );
43
44
    private final Setting<ListMode> blocksFilter = sgGeneral.add(new EnumSetting.Builder<ListMode>()
45
        .name("blocks-filter")
46
        .description("How to use the block list setting")
47
        .defaultValue(ListMode.Blacklist)
48
        .build()
49
    );
50
51
    private final Setting<Boolean> fastTower = sgGeneral.add(new BoolSetting.Builder()
52
        .name("fast-tower")
53
        .description("Whether or not to scaffold upwards faster.")
54
        .defaultValue(false)
55
        .build()
56
    );
57
58
    private final Setting<Double> towerSpeed = sgGeneral.add(new DoubleSetting.Builder()
59
        .name("tower-speed")
60
        .description("The speed at which to tower.")
61
        .defaultValue(0.5)
62
        .min(0)
63
        .sliderMax(1)
64
        .visible(fastTower::get)
65
        .build()
66
    );
67
68
    private final Setting<Boolean> whileMoving = sgGeneral.add(new BoolSetting.Builder()
69
        .name("while-moving")
70
        .description("Allows you to tower while moving.")
71
        .defaultValue(false)
72
        .visible(fastTower::get)
73
        .build()
74
    );
75
76
    private final Setting<Boolean> onlyOnClick = sgGeneral.add(new BoolSetting.Builder()
77
        .name("only-on-click")
78
        .description("Only places blocks when holding right click.")
79
        .defaultValue(false)
80
        .build()
81
    );
82
83
    private final Setting<Boolean> renderSwing = sgGeneral.add(new BoolSetting.Builder()
84
        .name("swing")
85
        .description("Renders your client-side swing.")
86
        .defaultValue(false)
87
        .build()
88
    );
89
90
    private final Setting<Boolean> autoSwitch = sgGeneral.add(new BoolSetting.Builder()
91
        .name("auto-switch")
92
        .description("Automatically swaps to a block before placing.")
93
        .defaultValue(true)
94
        .build()
95
    );
96
97
    private final Setting<Boolean> rotate = sgGeneral.add(new BoolSetting.Builder()
98
        .name("rotate")
99
        .description("Rotates towards the blocks being placed.")
100
        .defaultValue(true)
101
        .build()
102
    );
103
104
    private final Setting<Boolean> airPlace = sgGeneral.add(new BoolSetting.Builder()
105
        .name("air-place")
106
        .description("Allow air place. This also allows you to modify scaffold radius.")
107
        .defaultValue(false)
108
        .build()
109
    );
110
111
    private final Setting<Double> aheadDistance = sgGeneral.add(new DoubleSetting.Builder()
112
        .name("ahead-distance")
113
        .description("How far ahead to place blocks.")
114
        .defaultValue(0)
115
        .min(0)
116
        .sliderMax(1)
117
        .visible(() -> !airPlace.get())
118
        .build()
119
    );
120
121
    private final Setting<Double> placeRange = sgGeneral.add(new DoubleSetting.Builder()
122
        .name("closest-block-range")
123
        .description("How far can scaffold place blocks when you are in air.")
124
        .defaultValue(4)
125
        .min(0)
126
        .sliderMax(8)
127
        .visible(() -> !airPlace.get())
128
        .build()
129
    );
130
131
    private final Setting<Double> radius = sgGeneral.add(new DoubleSetting.Builder()
132
        .name("radius")
133
        .description("Scaffold radius.")
134
        .defaultValue(0)
135
        .min(0)
136
        .max(6)
137
        .visible(airPlace::get)
138
        .build()
139
    );
140
141
    private final Setting<Integer> blocksPerTick = sgGeneral.add(new IntSetting.Builder()
142
        .name("blocks-per-tick")
143
        .description("How many blocks to place in one tick.")
144
        .defaultValue(3)
145
        .min(1)
146
        .visible(airPlace::get)
147
        .build()
148
    );
149
150
    // Render
151
152
    private final Setting<Boolean> render = sgRender.add(new BoolSetting.Builder()
153
        .name("render")
154
        .description("Whether to render blocks that have been placed.")
155
        .defaultValue(true)
156
        .build()
157
    );
158
159
    private final Setting<ShapeMode> shapeMode = sgRender.add(new EnumSetting.Builder<ShapeMode>()
160
        .name("shape-mode")
161
        .description("How the shapes are rendered.")
162
        .defaultValue(ShapeMode.Both)
163
        .visible(render::get)
164
        .build()
165
    );
166
167
    private final Setting<SettingColor> sideColor = sgRender.add(new ColorSetting.Builder()
168
        .name("side-color")
169
        .description("The side color of the target block rendering.")
170
        .defaultValue(new SettingColor(197, 137, 232, 10))
171
        .visible(render::get)
172
        .build()
173
    );
174
175
    private final Setting<SettingColor> lineColor = sgRender.add(new ColorSetting.Builder()
176
        .name("line-color")
177
        .description("The line color of the target block rendering.")
178
        .defaultValue(new SettingColor(197, 137, 232))
179
        .visible(render::get)
180
        .build()
181
    );
182
183
    private final BlockPos.MutableBlockPos bp = new BlockPos.MutableBlockPos();
184
185
    public Scaffold() {
186
        super(Categories.Movement, "scaffold", "Automatically places blocks under you.");
187
    }
188
189
190
    @EventHandler
191
    private void onTick(TickEvent.Pre event) {
192
        if (onlyOnClick.get() && !mc.options.keyUse.isDown()) return;
193
194
        Vec3 vec = mc.player.position().add(mc.player.getDeltaMovement()).add(0, -0.75, 0);
195
        if (airPlace.get()) {
196
            bp.set(vec.x(), vec.y(), vec.z());
197
        } else {
198
            Vec3 pos = mc.player.position();
199
            if (aheadDistance.get() != 0 && !towering() && !mc.level.getBlockState(mc.player.blockPosition().below()).getCollisionShape(mc.level, mc.player.blockPosition()).isEmpty()) {
200
                Vec3 dir = Vec3.directionFromRotation(0, mc.player.getYRot()).multiply(aheadDistance.get(), 0, aheadDistance.get());
201
                if (mc.options.keyUp.isDown()) pos = pos.add(dir.x, 0, dir.z);
202
                if (mc.options.keyDown.isDown()) pos = pos.add(-dir.x, 0, -dir.z);
203
                if (mc.options.keyLeft.isDown()) pos = pos.add(dir.z, 0, -dir.x);
204
                if (mc.options.keyRight.isDown()) pos = pos.add(-dir.z, 0, dir.x);
205
            }
206
            bp.set(pos.x, vec.y, pos.z);
207
        }
208
        if (mc.options.keyShift.isDown() && !mc.options.keyJump.isDown() && mc.player.getY() + vec.y > -1) {
209
            bp.setY(bp.getY() - 1);
210
        }
211
        if (bp.getY() >= mc.player.blockPosition().getY()) {
212
            bp.setY(mc.player.blockPosition().getY() - 1);
213
        }
214
        BlockPos targetBlock = bp.immutable();
215
216
        if (!airPlace.get() && (BlockUtils.getPlaceSide(bp) == null)) {
217
            Vec3 pos = mc.player.position();
218
            pos = pos.add(0, -0.98f, 0);
219
            pos.add(mc.player.getDeltaMovement());
220
221
            List<BlockPos> blockPosArray = new ArrayList<>();
222
            for (int x = (int) (mc.player.getX() - placeRange.get()); x < mc.player.getX() + placeRange.get(); x++) {
223
                for (int z = (int) (mc.player.getZ() - placeRange.get()); z < mc.player.getZ() + placeRange.get(); z++) {
224
                    for (int y = (int) Math.max(mc.level.getMinY(), mc.player.getY() - placeRange.get()); y < Math.min(mc.level.getHeight(), mc.player.getY() + placeRange.get()); y++) {
225
                        bp.set(x, y, z);
226
                        if (BlockUtils.getPlaceSide(bp) == null) continue;
227
                        if (!BlockUtils.canPlace(bp)) continue;
228
                        if (mc.player.getEyePosition().distanceToSqr(Vec3.atCenterOf(bp.relative(BlockUtils.getClosestPlaceSide(bp)))) > 36)
229
                            continue;
230
                        blockPosArray.add(new BlockPos(bp));
231
                    }
232
                }
233
            }
234
            if (blockPosArray.isEmpty()) return;
235
236
            blockPosArray.sort(Comparator.comparingDouble(blockPos -> blockPos.distSqr(targetBlock)));
237
238
            bp.set(blockPosArray.getFirst());
239
        }
240
241
        if (airPlace.get()) {
242
            List<BlockPos> blocks = new ArrayList<>();
243
            for (int x = (int) (bp.getX() - radius.get()); x <= bp.getX() + radius.get(); x++) {
244
                for (int z = (int) (bp.getZ() - radius.get()); z <= bp.getZ() + radius.get(); z++) {
245
                    BlockPos blockPos = BlockPos.containing(x, bp.getY(), z);
246
                    if (mc.player.position().distanceTo(Vec3.atCenterOf(blockPos)) <= radius.get() || (x == bp.getX() && z == bp.getZ())) {
247
                        blocks.add(blockPos);
248
                    }
249
                }
250
            }
251
252
            if (!blocks.isEmpty()) {
253
                blocks.sort(Comparator.comparingDouble(PlayerUtils::squaredDistanceTo));
254
                int counter = 0;
255
                for (BlockPos block : blocks) {
256
                    if (place(block)) {
257
                        counter++;
258
                    }
259
260
                    if (counter >= blocksPerTick.get()) {
261
                        break;
262
                    }
263
                }
264
            }
265
        } else {
266
            place(bp);
267
        }
268
269
        FindItemResult result = InvUtils.findInHotbar(itemStack -> validItem(itemStack, bp));
270
        if (fastTower.get() && mc.options.keyJump.isDown() && !mc.options.keyShift.isDown() && result.found() && (autoSwitch.get() || result.getHand() != null)) {
271
            Vec3 velocity = mc.player.getDeltaMovement();
272
            AABB playerBox = mc.player.getBoundingBox();
273
            if (Streams.stream(mc.level.getBlockCollisions(mc.player, playerBox.move(0, 1, 0))).toList().isEmpty()) {
274
                // If there is no block above the player: move the player up, so he can place another block
275
                if (whileMoving.get() || !PlayerUtils.isMoving()) {
276
                    velocity = new Vec3(velocity.x, towerSpeed.get(), velocity.z);
277
                }
278
                mc.player.setDeltaMovement(velocity);
279
            } else {
280
                // If there is a block above the player: move the player down, so he's on top of the placed block
281
                mc.player.setDeltaMovement(velocity.x, Math.ceil(mc.player.getY()) - mc.player.getY(), velocity.z);
282
                mc.player.setOnGround(true);
283
            }
284
        }
285
    }
286
287
    public boolean scaffolding() {
288
        return isActive() && (!onlyOnClick.get() || (onlyOnClick.get() && mc.options.keyUse.isDown()));
289
    }
290
291
    public boolean towering() {
292
        FindItemResult result = InvUtils.findInHotbar(itemStack -> validItem(itemStack, bp));
293
        return scaffolding() && fastTower.get() && mc.options.keyJump.isDown() && !mc.options.keyShift.isDown() &&
294
            (whileMoving.get() || !PlayerUtils.isMoving()) && result.found() && (autoSwitch.get() || result.getHand() != null);
295
    }
296
297
    private boolean validItem(ItemStack itemStack, BlockPos pos) {
298
        if (!(itemStack.getItem() instanceof BlockItem)) return false;
299
300
        Block block = ((BlockItem) itemStack.getItem()).getBlock();
301
302
        if (!blocksFilter.get().allows(blocks.get().contains(block))) return false;
303
304
        if (!Block.isShapeFullBlock(block.defaultBlockState().getCollisionShape(mc.level, pos))) return false;
305
        return !(block instanceof FallingBlock) || !FallingBlock.isFree(mc.level.getBlockState(pos));
306
    }
307
308
    private boolean place(BlockPos bp) {
309
        FindItemResult item = InvUtils.findInHotbar(itemStack -> validItem(itemStack, bp));
310
        if (!item.found()) return false;
311
312
        if (item.getHand() == null && !autoSwitch.get()) return false;
313
314
        if (BlockUtils.place(bp, item, rotate.get(), 50, renderSwing.get(), true)) {
315
            // Render block if was placed
316
            if (render.get())
317
                RenderUtils.renderTickingBlock(bp.immutable(), sideColor.get(), lineColor.get(), shapeMode.get(), 0, 8, true, false);
318
            return true;
319
        }
320
        return false;
321
    }
322
323
}
324
MelaHack (ThunderHack fork)MOVEMENTsrc/main/java/thunder/hack/features/modules/movement/Scaffold.javaJava · 330 lines · 14.6 KB

Puts blocks under your thighs.

SettingsModePlaceModeSwitchRotateLockYOnlyNotHoldingSpaceAutoJumpWorkWhileSneakingTowerSafeWalkEchestHoldingRenderRenderModeAnimationModeRenderFillColorRenderLineColorRenderLineWidth
Scaffold.javaJava · Minecraft 26.2 · 330 lines · 14.6 KB · complete file, verbatimOriginal ↗
1
package thunder.hack.features.modules.movement;
2
3
import meteordevelopment.orbit.EventHandler;
4
import net.minecraft.core.BlockPos;
5
import net.minecraft.network.protocol.game.*;
6
import net.minecraft.world.InteractionHand;
7
import net.minecraft.world.inventory.ContainerInput;
8
import net.minecraft.world.item.BlockItem;
9
import net.minecraft.world.phys.BlockHitResult;
10
import net.minecraft.world.phys.Vec3;
11
import thunder.hack.events.impl.EventMove;
12
import thunder.hack.events.impl.EventPostSync;
13
import thunder.hack.events.impl.EventSync;
14
import thunder.hack.events.impl.EventTick;
15
import thunder.hack.features.modules.Module;
16
import thunder.hack.features.modules.client.HudEditor;
17
import thunder.hack.setting.Setting;
18
import thunder.hack.setting.impl.ColorSetting;
19
import thunder.hack.setting.impl.SettingGroup;
20
import thunder.hack.utility.Timer;
21
import thunder.hack.utility.player.InteractionUtility;
22
import thunder.hack.utility.player.InteractionUtility.BlockPosWithFacing;
23
import thunder.hack.utility.player.InventoryUtility;
24
import thunder.hack.utility.player.MovementUtility;
25
import thunder.hack.utility.player.SearchInvResult;
26
import thunder.hack.utility.render.BlockAnimationUtility;
27
28
import static thunder.hack.utility.player.InteractionUtility.BlockPosWithFacing;
29
import static thunder.hack.utility.player.InteractionUtility.checkNearBlocks;
30
31
public class Scaffold extends Module {
32
    private final Setting<Mode> mode = new Setting<>("Mode", Mode.NCP);
33
    private final Setting<InteractionUtility.PlaceMode> placeMode = new Setting<>("PlaceMode", InteractionUtility.PlaceMode.Normal, v -> !mode.is(Mode.Grim));
34
    private final Setting<Switch> autoSwitch = new Setting<>("Switch", Switch.Silent);
35
    private final Setting<Boolean> rotate = new Setting<>("Rotate", true);
36
    private final Setting<Boolean> lockY = new Setting<>("LockY", false);
37
    private final Setting<Boolean> onlyNotHoldingSpace = new Setting<>("OnlyNotHoldingSpace", false, v -> lockY.getValue());
38
    private final Setting<Boolean> autoJump = new Setting<>("AutoJump", false);
39
    private final Setting<Boolean> allowShift = new Setting<>("WorkWhileSneaking", false);
40
    private final Setting<Boolean> tower = new Setting<>("Tower", true, v -> !mode.is(Mode.Grim));
41
    private final Setting<Boolean> safewalk = new Setting<>("SafeWalk", true, v -> !mode.is(Mode.Grim));
42
    private final Setting<Boolean> echestholding = new Setting<>("EchestHolding", false);
43
    private final Setting<SettingGroup> renderCategory = new Setting<>("Render", new SettingGroup(false, 0));
44
    private final Setting<Boolean> render = new Setting<>("Render", true).addToGroup(renderCategory);
45
    private final Setting<BlockAnimationUtility.BlockRenderMode> renderMode = new Setting<>("RenderMode", BlockAnimationUtility.BlockRenderMode.All).addToGroup(renderCategory);
46
    private final Setting<BlockAnimationUtility.BlockAnimationMode> animationMode = new Setting<>("AnimationMode", BlockAnimationUtility.BlockAnimationMode.Fade).addToGroup(renderCategory);
47
    private final Setting<ColorSetting> renderFillColor = new Setting<>("RenderFillColor", new ColorSetting(HudEditor.getColor(0))).addToGroup(renderCategory);
48
    private final Setting<ColorSetting> renderLineColor = new Setting<>("RenderLineColor", new ColorSetting(HudEditor.getColor(0))).addToGroup(renderCategory);
49
    private final Setting<Integer> renderLineWidth = new Setting<>("RenderLineWidth", 2, 1, 5).addToGroup(renderCategory);
50
51
    private enum Mode {
52
        NCP, StrictNCP, Grim
53
    }
54
55
    private enum Switch {
56
        Normal, Silent, Inventory, None
57
    }
58
59
    private final Timer timer = new Timer();
60
    private BlockPosWithFacing currentblock;
61
    private int prevY;
62
63
    public Scaffold() {
64
        super("Scaffold", Category.MOVEMENT);
65
    }
66
67
    @Override
68
    public void onEnable() {
69
        prevY = -999;
70
    }
71
72
    @EventHandler
73
    public void onMove(EventMove event) {
74
        if (fullNullCheck()) return;
75
        if (safewalk.getValue() && !mode.is(Mode.Grim)) {
76
            double x = event.getX();
77
            double y = event.getY();
78
            double z = event.getZ();
79
80
            if (mc.player.onGround() && !mc.player.noPhysics) {
81
                double increment;
82
                for (increment = 0.05D; x != 0.0D && isOffsetBBEmpty(x, 0.0D); ) {
83
                    if (x < increment && x >= -increment) {
84
                        x = 0.0D;
85
                    } else if (x > 0.0D) {
86
                        x -= increment;
87
                    } else {
88
                        x += increment;
89
                    }
90
                }
91
                while (z != 0.0D && isOffsetBBEmpty(0.0D, z)) {
92
                    if (z < increment && z >= -increment) {
93
                        z = 0.0D;
94
                    } else if (z > 0.0D) {
95
                        z -= increment;
96
                    } else {
97
                        z += increment;
98
                    }
99
                }
100
                while (x != 0.0D && z != 0.0D && isOffsetBBEmpty(x, z)) {
101
                    if (x < increment && x >= -increment) {
102
                        x = 0.0D;
103
                    } else if (x > 0.0D) {
104
                        x -= increment;
105
                    } else {
106
                        x += increment;
107
                    }
108
                    if (z < increment && z >= -increment) {
109
                        z = 0.0D;
110
                    } else if (z > 0.0D) {
111
                        z -= increment;
112
                    } else {
113
                        z += increment;
114
                    }
115
                }
116
            }
117
            event.setX(x);
118
            event.setY(y);
119
            event.setZ(z);
120
            event.cancel();
121
        }
122
    }
123
124
    @EventHandler
125
    public void onTick(EventTick e) {
126
        if (mode.is(Mode.Grim)) {
127
            preAction();
128
            postAction();
129
        }
130
    }
131
132
    @EventHandler
133
    public void onPre(EventSync e) {
134
        if (!mode.is(Mode.Grim))
135
            preAction();
136
    }
137
138
    public void preAction() {
139
        currentblock = null;
140
141
        if (mc.player.isShiftKeyDown() && !allowShift.getValue()) return;
142
143
        if (prePlace(false) == -1) return;
144
145
        if (mc.options.keyJump.isDown() && !MovementUtility.isMoving())
146
            prevY = (int) (Math.floor(mc.player.getY() - 1));
147
148
        if (MovementUtility.isMoving() && autoJump.getValue()) {
149
            if (mc.options.keyJump.isDown()) {
150
                if (onlyNotHoldingSpace.getValue())
151
                    prevY = (int) (Math.floor(mc.player.getY() - 1));
152
            } else if (mc.player.onGround())
153
                mc.player.jumpFromGround();
154
        }
155
156
        BlockPos blockPos2 = lockY.getValue() && prevY != -999 ?
157
                BlockPos.containing(mc.player.getX(), prevY, mc.player.getZ())
158
                : new BlockPos((int) Math.floor(mc.player.getX()), (int) (Math.floor(mc.player.getY() - 1)), (int) Math.floor(mc.player.getZ()));
159
160
        if (!mc.level.getBlockState(blockPos2).canBeReplaced()) return;
161
162
        currentblock = checkNearBlocksExtended(blockPos2);
163
        if (currentblock != null) {
164
            if (rotate.getValue() && !mode.is(Mode.Grim)) {
165
                Vec3 hitVec = new Vec3(currentblock.position().getX() + 0.5, currentblock.position().getY() + 0.5, currentblock.position().getZ() + 0.5).add(new Vec3(currentblock.facing().step()).scale(0.5));
166
                float[] rotations = InteractionUtility.calculateAngle(hitVec);
167
                mc.player.setYRot(rotations[0]);
168
                mc.player.setXRot(rotations[1]);
169
            }
170
        }
171
    }
172
173
    @EventHandler
174
    public void onPost(EventPostSync e) {
175
        if (!mode.is(Mode.Grim))
176
            postAction();
177
    }
178
179
    public void postAction() {
180
        float offset = mode.is(Mode.Grim) ? 0.3f : 0.2f;
181
182
        if (mc.level.getBlockCollisions(mc.player, mc.player.getBoundingBox().inflate(-offset, 0, -offset).move(0, -0.5, 0)).iterator().hasNext())
183
            return;
184
185
        if (currentblock == null) return;
186
187
        int prevItem = prePlace(true);
188
189
        if (prevItem != -1) {
190
            if (mc.options.keyJump.isDown() && !MovementUtility.isMoving() && tower.getValue() && !mode.is(Mode.Grim)) {
191
                mc.player.setDeltaMovement(0.0, 0.42, 0.0);
192
                if (timer.passedMs(1500)) {
193
                    mc.player.setDeltaMovement(mc.player.getDeltaMovement().x, -0.28, mc.player.getDeltaMovement().z);
194
                    timer.reset();
195
                }
196
            } else timer.reset();
197
198
            BlockHitResult bhr;
199
200
            if (mode.is(Mode.StrictNCP))
201
                bhr = new BlockHitResult(new Vec3(currentblock.position().getX() + 0.5, currentblock.position().getY() + 0.5, currentblock.position().getZ() + 0.5).add(new Vec3(currentblock.facing().step()).scale(0.5)), currentblock.facing(), currentblock.position(), false);
202
            else
203
                bhr = new BlockHitResult(new Vec3((double) currentblock.position().getX() + Math.random(), currentblock.position().getY() + 0.99f, (double) currentblock.position().getZ() + Math.random()), currentblock.facing(), currentblock.position(), false);
204
205
            float[] rotations = InteractionUtility.calculateAngle(bhr.getLocation());
206
207
            boolean sneak = InteractionUtility.needSneak(mc.level.getBlockState(bhr.getBlockPos()).getBlock()) && !mc.player.isShiftKeyDown();
208
209
            if (sneak)
210
                mc.player.connection.send(new net.minecraft.network.protocol.game.ServerboundPlayerInputPacket(new net.minecraft.world.entity.player.Input(false, false, false, false, false, true, false)));
211
212
            if (mode.is(Mode.Grim))
213
                sendPacket(new ServerboundMovePlayerPacket.PosRot(mc.player.getX(), mc.player.getY(), mc.player.getZ(), rotations[0], rotations[1], mc.player.onGround(), mc.player.horizontalCollision));
214
215
            if (placeMode.getValue() == InteractionUtility.PlaceMode.Packet && !mode.is(Mode.Grim)) {
216
                boolean finalIsOffhand = prevItem == -2;
217
                sendSequencedPacket(id -> new ServerboundUseItemOnPacket(finalIsOffhand ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND, bhr, id));
218
            } else
219
                mc.gameMode.useItemOn(mc.player, prevItem == -2 ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND, bhr);
220
221
            mc.player.connection.send(new ServerboundSwingPacket(prevItem == -2 ? InteractionHand.OFF_HAND : InteractionHand.MAIN_HAND));
222
223
            prevY = currentblock.position().getY();
224
225
            if (sneak)
226
                mc.player.connection.send(new net.minecraft.network.protocol.game.ServerboundPlayerInputPacket(new net.minecraft.world.entity.player.Input(false, false, false, false, false, false, false)));
227
228
            if (mode.is(Mode.Grim))
229
                sendPacket(new ServerboundMovePlayerPacket.PosRot(mc.player.getX(), mc.player.getY(), mc.player.getZ(), mc.player.getYRot(), mc.player.getXRot(), mc.player.onGround(), mc.player.horizontalCollision));
230
231
            if (render.getValue())
232
                BlockAnimationUtility.renderBlock(currentblock.position(), renderLineColor.getValue().getColorObject(), renderLineWidth.getValue(), renderFillColor.getValue().getColorObject(), animationMode.getValue(), renderMode.getValue());
233
234
            postPlace(prevItem);
235
        }
236
    }
237
238
    private BlockPosWithFacing checkNearBlocksExtended(BlockPos blockPos) {
239
        BlockPosWithFacing ret = null;
240
241
        ret = checkNearBlocks(blockPos);
242
        if (ret != null) return ret;
243
244
        ret = checkNearBlocks(blockPos.offset(-1, 0, 0));
245
        if (ret != null) return ret;
246
247
        ret = checkNearBlocks(blockPos.offset(1, 0, 0));
248
        if (ret != null) return ret;
249
250
        ret = checkNearBlocks(blockPos.offset(0, 0, 1));
251
        if (ret != null) return ret;
252
253
        ret = checkNearBlocks(blockPos.offset(0, 0, -1));
254
        if (ret != null) return ret;
255
256
        ret = checkNearBlocks(blockPos.offset(-2, 0, 0));
257
        if (ret != null) return ret;
258
259
        ret = checkNearBlocks(blockPos.offset(2, 0, 0));
260
        if (ret != null) return ret;
261
262
        ret = checkNearBlocks(blockPos.offset(0, 0, 2));
263
        if (ret != null) return ret;
264
265
        ret = checkNearBlocks(blockPos.offset(0, 0, -2));
266
        if (ret != null) return ret;
267
268
        ret = checkNearBlocks(blockPos.offset(0, -1, 0));
269
        if (ret != null) return ret;
270
271
        ret = checkNearBlocks(blockPos.offset(1, -1, 0));
272
        if (ret != null) return ret;
273
274
        ret = checkNearBlocks(blockPos.offset(-1, -1, 0));
275
        if (ret != null) return ret;
276
277
        ret = checkNearBlocks(blockPos.offset(0, -1, 1));
278
        if (ret != null) return ret;
279
280
        return checkNearBlocks(blockPos.offset(0, -1, -1));
281
    }
282
283
    private int prePlace(boolean swap) {
284
        if (mc.player == null || mc.level == null || mc.gameMode == null)
285
            return -1;
286
287
        if (mc.player.getOffhandItem().getItem() instanceof BlockItem bi && !bi.getBlock().defaultBlockState().canBeReplaced())
288
            return -2;
289
290
        if (mc.player.getMainHandItem().getItem() instanceof BlockItem bi && !bi.getBlock().defaultBlockState().canBeReplaced())
291
            return mc.player.getInventory().getSelectedSlot();
292
293
        int prevSlot = mc.player.getInventory().getSelectedSlot();
294
295
        SearchInvResult hotbarResult = InventoryUtility.findInHotBar(i -> i.getItem() instanceof BlockItem bi && !bi.getBlock().defaultBlockState().canBeReplaced());
296
        SearchInvResult invResult = InventoryUtility.findInInventory(i -> i.getItem() instanceof BlockItem bi && !bi.getBlock().defaultBlockState().canBeReplaced());
297
298
        if (swap)
299
            switch (autoSwitch.getValue()) {
300
                case Inventory -> {
301
                    if (invResult.found()) {
302
                        prevSlot = invResult.slot();
303
                        mc.gameMode.handleContainerInput(mc.player.containerMenu.containerId, prevSlot, mc.player.getInventory().getSelectedSlot(), ContainerInput.SWAP, mc.player);
304
                        sendPacket(new ServerboundContainerClosePacket(mc.player.containerMenu.containerId));
305
                    }
306
                }
307
                case Normal, Silent -> hotbarResult.switchTo();
308
            }
309
310
        return prevSlot;
311
    }
312
313
    private void postPlace(int prevSlot) {
314
        if (prevSlot == -1 || prevSlot == -2)
315
            return;
316
317
        switch (autoSwitch.getValue()) {
318
            case Inventory -> {
319
                mc.gameMode.handleContainerInput(mc.player.containerMenu.containerId, prevSlot, mc.player.getInventory().getSelectedSlot(), ContainerInput.SWAP, mc.player);
320
                sendPacket(new ServerboundContainerClosePacket(mc.player.containerMenu.containerId));
321
            }
322
            case Silent -> InventoryUtility.switchTo(prevSlot);
323
        }
324
    }
325
326
    private boolean isOffsetBBEmpty(double x, double z) {
327
        return !mc.level.getBlockCollisions(mc.player, mc.player.getBoundingBox().inflate(-0.1, 0, -0.1).move(x, -2, z)).iterator().hasNext();
328
    }
329
}
330
OfflineClientWORLDsrc/main/java/com/jellypudding/offlineclient/modules/world/Scaffold.javaJava · 373 lines · 14.9 KB

Places blocks under you as you walk.

SettingsBlocksList modeTowerTower speedTower whilst movingLook aheadAir placeRadiusBlocks per tickReachRotateSwingAuto switchSwap backOnly on clickDownShow placed
Scaffold.javaJava · Minecraft 26.2 · 373 lines · 14.9 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.Module;
8
import com.jellypudding.offlineclient.render.BoxStyle;
9
import com.jellypudding.offlineclient.render.DrawBatch;
10
import com.jellypudding.offlineclient.util.InputUtil;
11
import com.jellypudding.offlineclient.setting.BoolSetting;
12
import com.jellypudding.offlineclient.setting.EnumSetting;
13
import com.jellypudding.offlineclient.setting.NumberSetting;
14
import com.jellypudding.offlineclient.setting.RegistryListSetting;
15
import com.jellypudding.offlineclient.util.BlockUtil;
16
import com.jellypudding.offlineclient.util.InventoryUtil;
17
import com.jellypudding.offlineclient.util.InventoryUtil.SlotSwap;
18
import net.minecraft.core.BlockPos;
19
import net.minecraft.core.Direction;
20
import net.minecraft.core.registries.BuiltInRegistries;
21
import net.minecraft.util.Mth;
22
import net.minecraft.world.entity.player.Input;
23
import net.minecraft.world.item.BlockItem;
24
import net.minecraft.world.level.block.Block;
25
import net.minecraft.world.level.block.Blocks;
26
import net.minecraft.world.phys.Vec3;
27
import net.minecraft.world.phys.shapes.CollisionContext;
28
29
import java.util.ArrayList;
30
import java.util.Comparator;
31
import java.util.Iterator;
32
import java.util.List;
33
34
// Keeps a block under the player's feet. Targets come from the current
35
// position and where the speed puts the player over the next few ticks.
36
public final class Scaffold extends Module {
37
38
    public enum ListMode { ONLY_LISTED, EXCEPT_LISTED }
39
40
    private static final Direction[] BRIDGE_SIDES = {
41
        Direction.DOWN, Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST
42
    };
43
    private static final int MAX_PLACES_PER_TICK = 2;
44
45
    // How far from the eyes a support face may sit for the click to land.
46
    private static final double CLICK_REACH_SQ = 36;
47
48
    // Ticks a placed block stays drawn whilst it fades out.
49
    private static final int FADE_TICKS = 8;
50
51
    private final RegistryListSetting<Block> blocks = new RegistryListSetting<>("Blocks",
52
        "The blocks the list mode below applies to.",
53
        BuiltInRegistries.BLOCK,
54
        List.of(Blocks.COBBLESTONE, Blocks.COBBLED_DEEPSLATE, Blocks.NETHERRACK,
55
            Blocks.DIRT, Blocks.STONE, Blocks.DEEPSLATE, Blocks.OBSIDIAN));
56
    private final EnumSetting<ListMode> listMode = new EnumSetting<>("List mode",
57
        "How the block list is used.", ListMode.ONLY_LISTED)
58
        .describe(ListMode.ONLY_LISTED, "Only listed blocks go under your feet. An empty list allows any building block.")
59
        .describe(ListMode.EXCEPT_LISTED, "Any building block goes under your feet except the listed ones.");
60
    private final BoolSetting tower = new BoolSetting("Tower",
61
        "Hold jump to build straight up.", true);
62
    private final NumberSetting towerSpeed = new NumberSetting("Tower speed",
63
        "How hard each tower jump pushes you up.", 0.42, 0.3, 0.5, 0.01)
64
        .min(0.1).max(1).under(tower);
65
    private final BoolSetting towerWhilstMoving = new BoolSetting("Tower whilst moving",
66
        "Keeps the tower boost on whilst you walk. Off means jump only lifts you when you stand still.", false)
67
        .under(tower);
68
    private final NumberSetting lookAhead = new NumberSetting("Look ahead",
69
        "Ticks of movement to build ahead of you.", 2, 0, 5, 1, " ticks").min(0).max(10);
70
    private final BoolSetting airPlace = new BoolSetting("Air place",
71
        "Places straight into the air with nothing to lean on. Needs a server that allows it.", false);
72
    private final NumberSetting radius = new NumberSetting("Radius",
73
        "Also fills every spot within this distance on the same level for a platform.", 0, 0, 6, 0.5, " blocks")
74
        .min(0).max(6).under(airPlace);
75
    private final NumberSetting blocksPerTick = new NumberSetting("Blocks per tick",
76
        "How many blocks may go down in one tick.", 3, 1, 10, 1, " blocks")
77
        .min(1).under(airPlace);
78
    private final NumberSetting reach = new NumberSetting("Reach",
79
        "When nothing touches the spot under you the nearest spot with support within this range is filled instead.",
80
        4, 0, 8, 0.5, " blocks").min(0).max(8).unless(airPlace);
81
    private final BoolSetting rotate = new BoolSetting("Rotate",
82
        "Turn towards each block on the server side.", true);
83
    private final BoolSetting swing = new BoolSetting("Swing",
84
        "Swings your arm on each placement.", false);
85
    private final BoolSetting autoSwitch = new BoolSetting("Auto switch",
86
        "Switches to a block in your hotbar. Off only places whilst you already hold one.", true);
87
    private final BoolSetting swapBack = new BoolSetting("Swap back",
88
        "Returns to the slot you had after every placement.", true)
89
        .under(autoSwitch);
90
    private final BoolSetting onlyOnClick = new BoolSetting("Only on click",
91
        "Only place whilst you hold the use key down.", false);
92
    private final BoolSetting down = new BoolSetting("Down",
93
        "Sneak to build one level lower. When off sneaking pauses Scaffold.", true);
94
    private final BoolSetting showPlaced = new BoolSetting("Show placed",
95
        "Draws each placed block for a moment.", true);
96
    private final BoxStyle style = new BoxStyle(BoxStyle.Shape.BOTH, 278).under(showPlaced);
97
98
    private final SlotSwap slots = new SlotSwap();
99
100
    // Blocks placed lately and the ticks each has left to show.
101
    private final List<Placed> placed = new ArrayList<>();
102
103
    private boolean descending;
104
105
    private boolean rotatedThisTick;
106
107
    public Scaffold() {
108
        super("Scaffold", "Places blocks under you as you walk.", Category.WORLD);
109
        addSettings(blocks, listMode, tower, towerSpeed, towerWhilstMoving, lookAhead, airPlace,
110
            radius, blocksPerTick, reach, rotate, swing, autoSwitch, swapBack, onlyOnClick, down,
111
            showPlaced);
112
        addSettings(style.settings());
113
        searchTags("bridge", "auto bridge", "tower");
114
    }
115
116
    // PlayerMixin lifts the sneak edge clamp whilst this is true.
117
    public boolean isDescending() {
118
        return isEnabled() && descending;
119
    }
120
121
    @Override
122
    protected void onDisable() {
123
        descending = false;
124
        placed.clear();
125
        slots.restoreIfMine();
126
    }
127
128
    @Subscribe
129
    private void onTick(TickEvent event) {
130
        descending = false;
131
        rotatedThisTick = false;
132
        agePlaced();
133
        if (!inGame() || mc.player.isSpectator() || mc.player.isPassenger()) {
134
            return;
135
        }
136
        // The input object is swapped for a silent one by Freecam.
137
        Input keys = mc.player.input.keyPresses;
138
        boolean jumping = keys.jump();
139
        boolean sneaking = keys.shift();
140
141
        Vec3 pos = mc.player.position();
142
        Vec3 velocity = mc.player.getDeltaMovement();
143
144
        if (sneaking && !jumping && !down.isOn()) {
145
            return;
146
        }
147
        if (onlyOnClick.isOn() && !InputUtil.physicallyHeld(mc.options.keyUse)) {
148
            return;
149
        }
150
        descending = sneaking && !jumping && down.isOn();
151
152
        int targetY = Mth.floor(pos.y) - 1;
153
        if (descending) {
154
            targetY--;
155
        }
156
157
        int limit = airPlace.isOn() ? blocksPerTick.getInt() : MAX_PLACES_PER_TICK;
158
        int count = 0;
159
        for (BlockPos target : targets(pos, velocity, targetY)) {
160
            if (count >= limit) {
161
                break;
162
            }
163
            if (!BlockUtil.isReplaceable(target) || occupied(target)) {
164
                continue;
165
            }
166
            if (place(target)) {
167
                count++;
168
            }
169
        }
170
171
        if (tower.isOn() && jumping && !sneaking) {
172
            towerUp(velocity);
173
        }
174
    }
175
176
    @Subscribe
177
    private void onRender3D(Render3DEvent event) {
178
        if (!showPlaced.isOn()) {
179
            return;
180
        }
181
        for (Placed entry : placed) {
182
            float strength = (float) entry.ticksLeft / FADE_TICKS;
183
            style.drawFading(event.getBatch(), DrawBatch.blockBox(entry.pos), strength, false);
184
        }
185
    }
186
187
    private void agePlaced() {
188
        Iterator<Placed> it = placed.iterator();
189
        while (it.hasNext()) {
190
            Placed entry = it.next();
191
            if (--entry.ticksLeft <= 0) {
192
                it.remove();
193
            }
194
        }
195
    }
196
197
    private List<BlockPos> targets(Vec3 pos, Vec3 velocity, int y) {
198
        int ahead = lookAhead.getInt();
199
        List<BlockPos> result = new ArrayList<>(ahead + 1);
200
        for (int ticksAhead = 0; ticksAhead <= ahead; ticksAhead++) {
201
            double x = pos.x + velocity.x * ticksAhead;
202
            double z = pos.z + velocity.z * ticksAhead;
203
            BlockPos target = new BlockPos(Mth.floor(x), y, Mth.floor(z));
204
            if (!result.contains(target)) {
205
                result.add(target);
206
            }
207
        }
208
        if (airPlace.isOn() && radius.getValue() > 0) {
209
            addPlatform(result, pos, y);
210
        }
211
        return result;
212
    }
213
214
    // Every spot on the level within the radius of the player. Nearest first.
215
    private void addPlatform(List<BlockPos> result, Vec3 pos, int y) {
216
        double range = radius.getValue();
217
        List<BlockPos> ring = new ArrayList<>();
218
        for (int x = Mth.floor(pos.x - range); x <= Mth.floor(pos.x + range); x++) {
219
            for (int z = Mth.floor(pos.z - range); z <= Mth.floor(pos.z + range); z++) {
220
                BlockPos spot = new BlockPos(x, y, z);
221
                if (!result.contains(spot) && pos.distanceTo(Vec3.atCenterOf(spot)) <= range) {
222
                    ring.add(spot);
223
                }
224
            }
225
        }
226
        ring.sort(Comparator.comparingDouble(spot -> pos.distanceToSqr(Vec3.atCenterOf(spot))));
227
        result.addAll(ring);
228
    }
229
230
    private boolean place(BlockPos target) {
231
        if (airPlace.isOn()) {
232
            return placeWith(target, null);
233
        }
234
        Direction support = BlockUtil.findPlaceSupport(target);
235
        if (support != null) {
236
            return placeWith(target, support);
237
        }
238
        // Nothing solid touches the target. A supported neighbour is filled first.
239
        for (Direction side : BRIDGE_SIDES) {
240
            BlockPos helper = target.relative(side);
241
            if (!BlockUtil.isReplaceable(helper) || occupied(helper)) {
242
                continue;
243
            }
244
            Direction helperSupport = BlockUtil.findPlaceSupport(helper);
245
            if (helperSupport != null) {
246
                return placeWith(helper, helperSupport);
247
            }
248
        }
249
        BlockPos nearest = nearestSupported(target);
250
        return nearest != null && placeWith(nearest, BlockUtil.findPlaceSupport(nearest));
251
    }
252
253
    // The supported spot within reach that sits closest to the target.
254
    // Used in open air where even the neighbours have nothing to lean on.
255
    private BlockPos nearestSupported(BlockPos target) {
256
        double range = reach.getValue();
257
        if (range <= 0) {
258
            return null;
259
        }
260
        Vec3 eye = mc.player.getEyePosition();
261
        BlockPos best = null;
262
        double bestDistance = Double.MAX_VALUE;
263
        for (BlockPos pos : BlockUtil.positionsWithin(range)) {
264
            if (!BlockUtil.isReplaceable(pos) || occupied(pos)) {
265
                continue;
266
            }
267
            Direction support = BlockUtil.findPlaceSupport(pos);
268
            if (support == null) {
269
                continue;
270
            }
271
            Vec3 hit = BlockUtil.hitPoint(pos.relative(support), support.getOpposite());
272
            if (eye.distanceToSqr(hit) > CLICK_REACH_SQ) {
273
                continue;
274
            }
275
            double distance = pos.distSqr(target);
276
            if (distance < bestDistance) {
277
                bestDistance = distance;
278
                best = pos.immutable();
279
            }
280
        }
281
        return best;
282
    }
283
284
    // Places at the spot against the support or straight into the air without one.
285
    private boolean placeWith(BlockPos target, Direction support) {
286
        int slot = BlockUtil.findBlockSlot(block -> allowed(block, target));
287
        if (slot == -1) {
288
            return false;
289
        }
290
        if (!autoSwitch.isOn()) {
291
            if (!holdsAllowedBlock(target)) {
292
                return false;
293
            }
294
            slot = InventoryUtil.selectedSlot();
295
        }
296
297
        slots.select(slot);
298
        // Only the first block of a tick turns. A burst of look packets is a plain tell.
299
        boolean turn = rotate.isOn() && !rotatedThisTick;
300
        rotatedThisTick |= turn;
301
        boolean done = support == null
302
            ? BlockUtil.placeDirect(target, turn, swing.isOn())
303
            : BlockUtil.place(target, support, turn, swing.isOn());
304
        if (autoSwitch.isOn() && swapBack.isOn()) {
305
            slots.restoreIfMine();
306
        } else {
307
            slots.forget();
308
        }
309
        if (done) {
310
            placed.add(new Placed(target.immutable(), FADE_TICKS));
311
        }
312
        return done;
313
    }
314
315
    private boolean holdsAllowedBlock(BlockPos target) {
316
        return mc.player.getInventory().getSelectedItem().getItem() instanceof BlockItem item
317
            && allowed(item.getBlock(), target);
318
    }
319
320
    // Any entity standing in the square gets the placement refused by the server.
321
    private boolean occupied(BlockPos pos) {
322
        if (BlockUtil.intersectsPlayer(pos)) {
323
            return true;
324
        }
325
        return !mc.level.isUnobstructed(Blocks.STONE.defaultBlockState(), pos,
326
            CollisionContext.empty());
327
    }
328
329
    // A listed block still has to be something worth standing on. An empty allow
330
    // list falls back to any plain building block.
331
    private boolean allowed(Block block, BlockPos target) {
332
        if (!BlockUtil.isBuildingBlock(block, target)) {
333
            return false;
334
        }
335
        if (listMode.is(ListMode.EXCEPT_LISTED)) {
336
            return !blocks.contains(block);
337
        }
338
        return blocks.size() == 0 || blocks.contains(block);
339
    }
340
341
    private void towerUp(Vec3 velocity) {
342
        if (mc.player.getAbilities().flying) {
343
            return;
344
        }
345
        // A block placed under a moving player often lands beside them instead.
346
        if (!towerWhilstMoving.isOn() && mc.player.input.getMoveVector().lengthSquared() > 1.0E-6f) {
347
            return;
348
        }
349
        if (mc.player.onGround()) {
350
            mc.player.setDeltaMovement(velocity.x, towerSpeed.getValue(), velocity.z);
351
            return;
352
        }
353
        if (velocity.y > 0) {
354
            BlockPos justBelow = BlockPos.containing(
355
                mc.player.getX(), mc.player.getY() - 0.01, mc.player.getZ());
356
            if (BlockUtil.isSolid(justBelow)) {
357
                mc.player.setDeltaMovement(velocity.x, 0, velocity.z);
358
            }
359
        }
360
    }
361
362
    private static final class Placed {
363
364
        private final BlockPos pos;
365
        private int ticksLeft;
366
367
        private Placed(BlockPos pos, int ticksLeft) {
368
            this.pos = pos;
369
            this.ticksLeft = ticksLeft;
370
        }
371
    }
372
}
373
CombatantPLAYERsrc/main/java/combatant/client/features/module/modules/player/Scaffold.javaJava · 2,415 lines · 105.2 KB
Scaffold.javaJava · Minecraft 26.2 · 2,415 lines · 105.2 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Combatant modifications copyright (c) 2026 pivosos2007.
4
 *
5
 * Portions of this file are based on LiquidBounce
6
 * (https://github.com/CCBlueX/LiquidBounce).
7
 * Copyright (c) 2015-2026 CCBlueX.
8
 *
9
 * LiquidBounce portions are licensed under GPLv3-or-later.
10
 * Combatant modifications are licensed under GPLv3.
11
 * See THIRD_PARTY_NOTICES.md for details.
12
 */
13
14
package combatant.client.features.module.modules.player;
15
16
import combatant.client.render.engine.text.BuiltinFontCatalog;
17
import combatant.client.config.common.CommonSettingSchemas;
18
import combatant.client.config.values.*;
19
import combatant.client.events.impl.*;
20
import combatant.client.features.module.*;
21
import combatant.client.features.module.Module;
22
import combatant.client.util.block.scaffold.*;
23
import combatant.client.util.screen.ClientScreen;
24
import net.minecraft.client.Minecraft;
25
import net.minecraft.client.gui.GuiGraphicsExtractor;
26
import net.minecraft.client.player.LocalPlayer;
27
import net.minecraft.core.BlockPos;
28
import net.minecraft.core.Direction;
29
import net.minecraft.network.protocol.game.ClientboundPlayerPositionPacket;
30
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
31
import net.minecraft.util.Mth;
32
import net.minecraft.world.InteractionHand;
33
import net.minecraft.world.InteractionResult;
34
import net.minecraft.world.entity.player.Input;
35
import net.minecraft.world.item.ItemStack;
36
import net.minecraft.world.level.ClipContext;
37
import net.minecraft.world.level.block.state.BlockState;
38
import net.minecraft.world.phys.AABB;
39
import net.minecraft.world.phys.BlockHitResult;
40
import net.minecraft.world.phys.HitResult;
41
import net.minecraft.world.phys.Vec3;
42
import combatant.client.config.SettingDef;
43
import combatant.client.config.values.*;
44
import combatant.client.events.EventHandler;
45
import combatant.client.events.impl.*;
46
import combatant.client.features.gui.hud.nondraggable.impl.BetterTooltips;
47
import combatant.client.features.module.*;
48
import combatant.client.mixins.accessors.ServerboundMovePlayerPacketAccessor;
49
import combatant.client.render.engine.RenderState;
50
import combatant.client.render.engine.color.RenderColor;
51
import combatant.client.render.engine.core.ViewportContext;
52
import combatant.client.render.engine.math.HudScale;
53
import combatant.client.render.engine.renderer.Renderer2D;
54
import combatant.client.render.engine.renderer.Renderer3D;
55
import combatant.client.render.engine.text.TextRenderer;
56
import combatant.client.render.helpers.TickDelta;
57
import combatant.client.util.aiming.RestrictedSingleUseAction;
58
import combatant.client.util.aiming.RotationManager;
59
import combatant.client.util.aiming.RotationTarget;
60
import combatant.client.util.aiming.RotationUtil;
61
import combatant.client.util.aiming.data.Rotation;
62
import combatant.client.util.aiming.features.MovementCorrection;
63
import combatant.client.util.aiming.features.processors.RotationProcessor;
64
import combatant.client.util.aiming.features.processors.anglesmooth.AngleSmooth;
65
import combatant.client.util.aiming.features.processors.anglesmooth.impl.AccelerationAngleSmooth;
66
import combatant.client.util.aiming.features.processors.anglesmooth.impl.InterpolationAngleSmooth;
67
import combatant.client.util.aiming.features.processors.anglesmooth.impl.LinearAngleSmooth;
68
import combatant.client.util.aiming.features.processors.anglesmooth.impl.SigmoidAngleSmooth;
69
import combatant.client.util.block.scaffold.*;
70
import combatant.client.util.entity.EagleUtil;
71
import combatant.client.util.player.MovementUtil;
72
import combatant.client.util.player.inventory.InventorySwap;
73
74
import java.util.ArrayList;
75
import java.util.Comparator;
76
import java.util.List;
77
78
//todo Description
79
@ModuleInfo(id = "scaffold", displayName = "Scaffold", aliases = {"bridge", "autobridge"}, category = ModuleCategory.PLAYER)
80
public class Scaffold extends Module {
81
    private static final boolean DEBUG_LOGS = true;
82
    private static final List<BlockPos> NORMAL_OFFSETS = commonOffsets(0, -1, 1);
83
    private static final List<BlockPos> DOWN_OFFSETS = commonOffsets(0, -1, 1, -2, 2);
84
    private final EnumValue<RotationTiming> rotationTiming =
85
            new EnumValue<>("rotation_timing", RotationTiming.NORMAL, RotationTiming.values());
86
    private final EnumValue<Technique> technique =
87
            new EnumValue<>("technique", Technique.NORMAL, Technique.values());
88
    private final EnumValue<SameYMode> sameY =
89
            new EnumValue<>("same_y", SameYMode.OFF, SameYMode.values());
90
    private final EnumValue<MovementCorrection> movementCorrection =
91
            new EnumValue<>("movement_correction", MovementCorrection.SILENT, MovementCorrection.values());
92
    private final EnumValue<AngleSmoothMode> angleSmoothMode =
93
            new EnumValue<>("angle_smooth_mode", AngleSmoothMode.INTERPOLATION, AngleSmoothMode.values());
94
    private final EnumValue<SprintMode> clientSprintMode =
95
            new EnumValue<>("client_sprint_mode", SprintMode.DO_NOT_CHANGE, SprintMode.values());
96
    private final EnumValue<SprintMode> serverSprintMode =
97
            new EnumValue<>("server_sprint_mode", SprintMode.DO_NOT_CHANGE, SprintMode.values());
98
    private final EnumValue<TowerMode> towerMode =
99
            new EnumValue<>("tower_mode", TowerMode.NONE, TowerMode.values());
100
    private final EnumValue<TellyResetMode> tellyResetMode =
101
            new EnumValue<>("telly_reset_mode", TellyResetMode.RESET, TellyResetMode.values());
102
    private final EnumValue<ScaffoldFacePositionFactory.Mode> aimMode =
103
            new EnumValue<>("aim_mode", ScaffoldFacePositionFactory.Mode.STABILIZED, ScaffoldFacePositionFactory.Mode.values());
104
    private final EnumValue<IndicatorSide> placementIndicatorSide =
105
            new EnumValue<>("placement_indicator_side", IndicatorSide.LEFT, IndicatorSide.values());
106
    private final EnumValue<IndicatorStyle> placementIndicatorStyle =
107
            new EnumValue<>("placement_indicator_style", IndicatorStyle.PILL, IndicatorStyle.values());
108
    private final EnumValue<IndicatorCountMode> placementIndicatorCountMode =
109
            new EnumValue<>("placement_indicator_count_mode", IndicatorCountMode.CURRENT_STACK, IndicatorCountMode.values());
110
    private final BooleanValue autoBlock =
111
            new BooleanValue("auto_block", true);
112
    private final BooleanValue renderPlacement =
113
            new BooleanValue("render_placement", true);
114
    private final BooleanValue placementIndicator =
115
            new BooleanValue("placement_indicator", true);
116
    private final BooleanValue placementIndicatorBackground =
117
            new BooleanValue("placement_indicator_background", true);
118
    private final BooleanValue autoBlockAlways =
119
            new BooleanValue("auto_block_always", false);
120
    private final BooleanValue prediction =
121
            new BooleanValue("prediction", true);
122
    private final BooleanValue considerInventory =
123
            new BooleanValue("consider_inventory", false);
124
    private final BooleanValue down =
125
            new BooleanValue("down", false);
126
    private final BooleanValue eagle =
127
            new BooleanValue("eagle", false);
128
    private final BooleanValue eagleOnlyOnGround =
129
            new BooleanValue("eagle_only_on_ground", true);
130
    private final NumberValue<Double> placementSpeed =
131
            new NumberValue<>("placement_speed", 6.0, 1.0, 20.0);
132
    private final NumberValue<Integer> delay =
133
            new NumberValue<>("delay", 0, 0, 20);
134
    private final NumberValue<Integer> autoBlockSlotResetDelay =
135
            new NumberValue<>("auto_block_slot_reset_delay", 5, 0, 40);
136
    private final NumberValue<Integer> autoBlockDoNotUseBelowCount =
137
            new NumberValue<>("auto_block_do_not_use_below_count", 1, 0, 64);
138
    private final NumberValue<Integer> blocksToEagle =
139
            new NumberValue<>("blocks_to_eagle", 0, 0, 10);
140
    private final NumberValue<Integer> expandLength =
141
            new NumberValue<>("expand_length", 4, 1, 10);
142
    private final NumberValue<Double> eagleEdgeDistance =
143
            new NumberValue<>("eagle_edge_distance", 0.01, 0.01, 1.3);
144
    private final NumberValue<Double> minDist =
145
            new NumberValue<>("min_dist", 0.0, 0.0, 0.25);
146
    private final BooleanValue acceleration =
147
            new BooleanValue("acceleration", false);
148
    private final NumberValue<Double> accelerationMultiplier =
149
            new NumberValue<>("acceleration_multiplier", 0.6, 0.1, 3.0);
150
    private final BooleanValue accelerationOnlyOnGround =
151
            new BooleanValue("acceleration_only_on_ground", false);
152
    private final BooleanValue strafe =
153
            new BooleanValue("strafe", false);
154
    private final NumberValue<Double> strafeSpeed =
155
            new NumberValue<>("strafe_speed", 0.247, 0.0, 5.0);
156
    private final BooleanValue strafeHypixel =
157
            new BooleanValue("strafe_hypixel", false);
158
    private final BooleanValue strafeOnlyOnGround =
159
            new BooleanValue("strafe_only_on_ground", false);
160
    private final BooleanValue jumpStrafe =
161
            new BooleanValue("jump_strafe", false);
162
    private final NumberValue<Double> jumpStrafeStraightMin =
163
            new NumberValue<>("jump_strafe_straight_min", 0.48, 0.1, 1.0);
164
    private final NumberValue<Double> jumpStrafeStraightMax =
165
            new NumberValue<>("jump_strafe_straight_max", 0.49, 0.1, 1.0);
166
    private final NumberValue<Double> jumpStrafeDiagonalMin =
167
            new NumberValue<>("jump_strafe_diagonal_min", 0.48, 0.1, 1.0);
168
    private final NumberValue<Double> jumpStrafeDiagonalMax =
169
            new NumberValue<>("jump_strafe_diagonal_max", 0.49, 0.1, 1.0);
170
    private final BooleanValue speedLimiter =
171
            new BooleanValue("speed_limiter", false);
172
    private final BooleanValue stabilizeMovement =
173
            new BooleanValue("stabilize_movement", false);
174
    private final BooleanValue telly =
175
            new BooleanValue("telly", false);
176
    private final BooleanValue tellyAimOnTower =
177
            new BooleanValue("telly_aim_on_tower", true);
178
    private final BooleanValue ceiling =
179
            new BooleanValue("ceiling", false);
180
    private final BooleanValue headHitter =
181
            new BooleanValue("head_hitter", false);
182
    private final NumberValue<Double> speedLimit =
183
            new NumberValue<>("speed_limit", 0.11, 0.01, 0.4);
184
    private final NumberValue<Integer> tellyStraightTicks =
185
            new NumberValue<>("telly_straight_ticks", 0, 0, 5);
186
    private final NumberValue<Integer> tellyJumpTicksMin =
187
            new NumberValue<>("telly_jump_ticks_min", 0, 0, 10);
188
    private final NumberValue<Integer> tellyJumpTicksMax =
189
            new NumberValue<>("telly_jump_ticks_max", 0, 0, 10);
190
    private final NumberValue<Double> towerMotion =
191
            new NumberValue<>("tower_motion", 0.42, 0.0, 1.0);
192
    private final NumberValue<Double> towerTriggerHeight =
193
            new NumberValue<>("tower_trigger_height", 0.78, 0.76, 1.0);
194
    private final NumberValue<Double> towerSlow =
195
            new NumberValue<>("tower_slow", 1.0, 0.0, 3.0);
196
    private final RGBAColorValue renderFillColor =
197
            new RGBAColorValue("render_fill_color", "#3264A0A0");
198
    private final RGBAColorValue renderLineColor =
199
            new RGBAColorValue("render_line_color", "#96A0FFFF");
200
    private final NumberValue<Integer> renderLineWidth =
201
            new NumberValue<>("render_line_width", 2, 1, 5);
202
    private final NumberValue<Double> renderBobAmplitude =
203
            new NumberValue<>("render_bob_amplitude", 0.08, 0.0, 0.3);
204
    private final NumberValue<Double> renderBobSpeed =
205
            new NumberValue<>("render_bob_speed", 2.2, 0.2, 8.0);
206
    private final NumberValue<Double> renderPlaceAnimTime =
207
            new NumberValue<>("render_place_anim_time", 0.22, 0.05, 1.0);
208
    private final NumberValue<Double> placementIndicatorScale =
209
            new NumberValue<>("placement_indicator_scale", 1.0, 0.5, 3.0);
210
    private final NumberValue<Double> placementIndicatorOffsetX =
211
            new NumberValue<>("placement_indicator_offset_x", 26.0, -120.0, 120.0);
212
    private final NumberValue<Double> placementIndicatorOffsetY =
213
            new NumberValue<>("placement_indicator_offset_y", 0.0, -120.0, 120.0);
214
    private final NumberValue<Float> linearHorMin =
215
            new NumberValue<>("linear_horizontal_min", 180f, 0f, 180f);
216
    private final NumberValue<Float> linearHorMax =
217
            new NumberValue<>("linear_horizontal_max", 180f, 0f, 180f);
218
    private final NumberValue<Float> linearVertMin =
219
            new NumberValue<>("linear_vertical_min", 180f, 0f, 180f);
220
    private final NumberValue<Float> linearVertMax =
221
            new NumberValue<>("linear_vertical_max", 180f, 0f, 180f);
222
    private final NumberValue<Float> sigmoidHorMin =
223
            new NumberValue<>("sigmoid_horizontal_min", 180f, 0f, 180f);
224
    private final NumberValue<Float> sigmoidHorMax =
225
            new NumberValue<>("sigmoid_horizontal_max", 180f, 0f, 180f);
226
    private final NumberValue<Float> sigmoidVertMin =
227
            new NumberValue<>("sigmoid_vertical_min", 180f, 0f, 180f);
228
    private final NumberValue<Float> sigmoidVertMax =
229
            new NumberValue<>("sigmoid_vertical_max", 180f, 0f, 180f);
230
    private final NumberValue<Float> sigmoidSteepness =
231
            new NumberValue<>("sigmoid_steepness", 10f, 0f, 20f);
232
    private final NumberValue<Float> sigmoidMidpoint =
233
            new NumberValue<>("sigmoid_midpoint", 0.3f, 0f, 1f);
234
    private final NumberValue<Integer> interpHorMin =
235
            new NumberValue<>("interp_horizontal_min", 80, 1, 100);
236
    private final NumberValue<Integer> interpHorMax =
237
            new NumberValue<>("interp_horizontal_max", 85, 1, 100);
238
    private final NumberValue<Integer> interpVertMin =
239
            new NumberValue<>("interp_vertical_min", 20, 1, 100);
240
    private final NumberValue<Integer> interpVertMax =
241
            new NumberValue<>("interp_vertical_max", 25, 1, 100);
242
    private final NumberValue<Integer> interpDirMin =
243
            new NumberValue<>("interp_direction_change_min", 95, 0, 100);
244
    private final NumberValue<Integer> interpDirMax =
245
            new NumberValue<>("interp_direction_change_max", 100, 0, 100);
246
    private final NumberValue<Float> interpMidpoint =
247
            new NumberValue<>("interp_midpoint", 0.35f, 0.0f, 1.0f);
248
    private final NumberValue<Float> accelYawMin =
249
            new NumberValue<>("accel_yaw_min", 20f, 1f, 180f);
250
    private final NumberValue<Float> accelYawMax =
251
            new NumberValue<>("accel_yaw_max", 25f, 1f, 180f);
252
    private final NumberValue<Float> accelPitchMin =
253
            new NumberValue<>("accel_pitch_min", 20f, 1f, 180f);
254
    private final NumberValue<Float> accelPitchMax =
255
            new NumberValue<>("accel_pitch_max", 25f, 1f, 180f);
256
    private final BooleanValue accelDynamicEnabled =
257
            new BooleanValue("accel_dynamic_enabled", false);
258
    private final NumberValue<Float> accelCoefDistance =
259
            new NumberValue<>("accel_coef_distance", -1.393f, -2f, 2f);
260
    private final NumberValue<Float> accelYawCrossMin =
261
            new NumberValue<>("accel_yaw_cross_min", 17f, 1f, 180f);
262
    private final NumberValue<Float> accelYawCrossMax =
263
            new NumberValue<>("accel_yaw_cross_max", 20f, 1f, 180f);
264
    private final NumberValue<Float> accelPitchCrossMin =
265
            new NumberValue<>("accel_pitch_cross_min", 17f, 1f, 180f);
266
    private final NumberValue<Float> accelPitchCrossMax =
267
            new NumberValue<>("accel_pitch_cross_max", 20f, 1f, 180f);
268
    private final BooleanValue accelErrorEnabled =
269
            new BooleanValue("accel_error_enabled", true);
270
    private final NumberValue<Float> accelYawError =
271
            new NumberValue<>("accel_yaw_error", 0.1f, 0.01f, 1f);
272
    private final NumberValue<Float> accelPitchError =
273
            new NumberValue<>("accel_pitch_error", 0.1f, 0.01f, 1f);
274
    private final BooleanValue constantErrorEnabled =
275
            new BooleanValue("constant_error_enabled", true);
276
    private final NumberValue<Float> constantYawError =
277
            new NumberValue<>("constant_yaw_error", 0.1f, 0.01f, 1f);
278
    private final NumberValue<Float> constantPitchError =
279
            new NumberValue<>("constant_pitch_error", 0.1f, 0.01f, 1f);
280
    private final BooleanValue sigmoidDecelEnabled =
281
            new BooleanValue("sigmoid_decel_enabled", false);
282
    private final NumberValue<Float> sigmoidDecelSteepness =
283
            new NumberValue<>("sigmoid_decel_steepness", 10f, 0.0f, 20f);
284
    private final NumberValue<Float> sigmoidDecelMidpoint =
285
            new NumberValue<>("sigmoid_decel_midpoint", 0.3f, 0.0f, 1.0f);
286
    private final ScaffoldMovementPlanner movementPlanner = new ScaffoldMovementPlanner();
287
    private final ScaffoldMovementPrediction movementPrediction = new ScaffoldMovementPrediction();
288
    private final ScaffoldPlacementGate placementGate = new ScaffoldPlacementGate();
289
    private final InterpolationAngleSmooth interpolationSmooth = new InterpolationAngleSmooth(
290
            interpHorMin, interpHorMax, interpVertMin, interpVertMax, interpDirMin, interpDirMax, interpMidpoint
291
    );
292
    private final LinearAngleSmooth linearSmooth = new LinearAngleSmooth(
293
            linearHorMin, linearHorMax, linearVertMin, linearVertMax
294
    );
295
    private final SigmoidAngleSmooth sigmoidSmooth = new SigmoidAngleSmooth(
296
            sigmoidHorMin, sigmoidHorMax, sigmoidVertMin, sigmoidVertMax,
297
            sigmoidSteepness, sigmoidMidpoint
298
    );
299
    private final AccelerationAngleSmooth accelerationSmooth = new AccelerationAngleSmooth(
300
            accelYawMin, accelYawMax, accelPitchMin, accelPitchMax,
301
            accelDynamicEnabled, accelCoefDistance,
302
            accelYawCrossMin, accelYawCrossMax, accelPitchCrossMin, accelPitchCrossMax,
303
            accelErrorEnabled, accelYawError, accelPitchError,
304
            constantErrorEnabled, constantYawError, constantPitchError,
305
            sigmoidDecelEnabled, sigmoidDecelSteepness, sigmoidDecelMidpoint
306
    );
307
    private ScaffoldPlacementTarget currentTarget;
308
    private int placementY;
309
    private int delayLeft;
310
    private boolean wasPlaced;
311
    private int towerAirTicks;
312
    private double towerJumpBaseY = Double.NaN;
313
    private boolean rawForward;
314
    private boolean rawBackward;
315
    private boolean rawLeft;
316
    private boolean rawRight;
317
    private int strafeMoveTicks;
318
    private int ticksUntilTellyJump;
319
    private int tellyJumpTicks;
320
    private ItemStack indicatorStack = ItemStack.EMPTY;
321
    private boolean indicatorVisible;
322
    private float indicatorX;
323
    private float indicatorY;
324
    private float indicatorSize;
325
    private float indicatorScaleFactor;
326
    private String indicatorCountText = "";
327
    private float indicatorCountX;
328
    private float indicatorCountY;
329
    private float indicatorTextScale;
330
    private int indicatorCountValue;
331
    private boolean indicatorRenderItem;
332
    private BlockPos lastPlacedRenderPos;
333
    private long lastPlacedRenderMillis;
334
    private long debugAttemptCounter;
335
    private BlockPos debugLastTargetPos;
336
    private BlockPos debugPendingPlacedPos;
337
    private int debugPendingPlacedTicks;
338
    private long debugPendingPlacedAttempt;
339
    private boolean debugPendingPlacedSeenSolid;
340
    private ScaffoldLine currentOptimalLine;
341
342
    {
343
        declareSettings();
344
    }
345
346
    private static List<BlockPos> commonOffsets(int... xzOffsets) {
347
        List<BlockPos> list = new ArrayList<>(xzOffsets.length * xzOffsets.length * 2);
348
        for (int x : xzOffsets) {
349
            for (int z : xzOffsets) {
350
                list.add(new BlockPos(x, 0, z));
351
                list.add(new BlockPos(x, -1, z));
352
            }
353
        }
354
        return List.copyOf(list);
355
    }
356
357
    private static int withAlphaScale(int argb, float scale) {
358
        int alpha = (argb >>> 24) & 0xFF;
359
        int scaledAlpha = Mth.clamp((int) (alpha * scale), 0, 255);
360
        return (argb & 0x00FFFFFF) | (scaledAlpha << 24);
361
    }
362
363
    private static int getPillCountColor(int count) {
364
        int low = 0xFFFF5C5C;
365
        int mid = 0xFFDCE61E;
366
        int high = 0xFF63F27D;
367
368
        if (count <= 64) {
369
            float t = Mth.clamp(count / 64.0f, 0.0f, 1.0f);
370
            return lerpColor(low, mid, t);
371
        }
372
373
        float t = Mth.clamp((count - 64) / 64.0f, 0.0f, 1.0f);
374
        return lerpColor(mid, high, t);
375
    }
376
377
    private static int lerpColor(int from, int to, float t) {
378
        int a1 = (from >>> 24) & 0xFF;
379
        int r1 = (from >>> 16) & 0xFF;
380
        int g1 = (from >>> 8) & 0xFF;
381
        int b1 = from & 0xFF;
382
383
        int a2 = (to >>> 24) & 0xFF;
384
        int r2 = (to >>> 16) & 0xFF;
385
        int g2 = (to >>> 8) & 0xFF;
386
        int b2 = to & 0xFF;
387
388
        int a = Mth.lerpInt(t, a1, a2);
389
        int r = Mth.lerpInt(t, r1, r2);
390
        int g = Mth.lerpInt(t, g1, g2);
391
        int b = Mth.lerpInt(t, b1, b2);
392
        return (a << 24) | (r << 16) | (g << 8) | b;
393
    }
394
395
    private static int colorWithAlpha(int rgb, int alpha) {
396
        return (alpha << 24) | (rgb & 0x00FFFFFF);
397
    }
398
399
    private static void addFilledBox(Renderer3D renderer, AABB box, int argb) {
400
        int a = (argb >>> 24) & 0xFF;
401
        int r = (argb >>> 16) & 0xFF;
402
        int g = (argb >>> 8) & 0xFF;
403
        int b = argb & 0xFF;
404
405
        double minX = box.minX;
406
        double minY = box.minY;
407
        double minZ = box.minZ;
408
        double maxX = box.maxX;
409
        double maxY = box.maxY;
410
        double maxZ = box.maxZ;
411
412
        renderer.quad(minX, minY, minZ, maxX, minY, minZ, maxX, minY, maxZ, minX, minY, maxZ, r, g, b, a);
413
        renderer.quad(minX, maxY, minZ, minX, maxY, maxZ, maxX, maxY, maxZ, maxX, maxY, minZ, r, g, b, a);
414
        renderer.quad(minX, minY, maxZ, maxX, minY, maxZ, maxX, maxY, maxZ, minX, maxY, maxZ, r, g, b, a);
415
        renderer.quad(minX, minY, minZ, minX, maxY, minZ, maxX, maxY, minZ, maxX, minY, minZ, r, g, b, a);
416
        renderer.quad(maxX, minY, minZ, maxX, maxY, minZ, maxX, maxY, maxZ, maxX, minY, maxZ, r, g, b, a);
417
        renderer.quad(minX, minY, minZ, minX, minY, maxZ, minX, maxY, maxZ, minX, maxY, minZ, r, g, b, a);
418
    }
419
420
    private static void addOutlineBox(Renderer3D renderer, AABB box, int argb) {
421
        int a = (argb >>> 24) & 0xFF;
422
        int r = (argb >>> 16) & 0xFF;
423
        int g = (argb >>> 8) & 0xFF;
424
        int b = argb & 0xFF;
425
426
        double minX = box.minX;
427
        double minY = box.minY;
428
        double minZ = box.minZ;
429
        double maxX = box.maxX;
430
        double maxY = box.maxY;
431
        double maxZ = box.maxZ;
432
433
        renderer.line(minX, minY, minZ, maxX, minY, minZ, r, g, b, a);
434
        renderer.line(maxX, minY, minZ, maxX, minY, maxZ, r, g, b, a);
435
        renderer.line(maxX, minY, maxZ, minX, minY, maxZ, r, g, b, a);
436
        renderer.line(minX, minY, maxZ, minX, minY, minZ, r, g, b, a);
437
438
        renderer.line(minX, maxY, minZ, maxX, maxY, minZ, r, g, b, a);
439
        renderer.line(maxX, maxY, minZ, maxX, maxY, maxZ, r, g, b, a);
440
        renderer.line(maxX, maxY, maxZ, minX, maxY, maxZ, r, g, b, a);
441
        renderer.line(minX, maxY, maxZ, minX, maxY, minZ, r, g, b, a);
442
443
        renderer.line(minX, minY, minZ, minX, maxY, minZ, r, g, b, a);
444
        renderer.line(maxX, minY, minZ, maxX, maxY, minZ, r, g, b, a);
445
        renderer.line(maxX, minY, maxZ, maxX, maxY, maxZ, r, g, b, a);
446
        renderer.line(minX, minY, maxZ, minX, maxY, maxZ, r, g, b, a);
447
    }
448
449
    private static void debugLog(String pattern, Object... args) {
450
        if (!DEBUG_LOGS) {
451
        }
452
    }
453
454
    private static String describeTarget(ScaffoldPlacementTarget target) {
455
        if (target == null) return "null";
456
        return "placed=" + target.getPlacedBlockPos()
457
                + " interact=" + target.getInteractedBlockPos()
458
                + " side=" + target.getDirection()
459
                + " rot=" + describeRotation(target.getRotation());
460
    }
461
462
    private static String describeHit(BlockHitResult hit) {
463
        if (hit == null) return "null";
464
        return "block=" + hit.getBlockPos()
465
                + " side=" + hit.getDirection()
466
                + " pos=" + formatVec(hit.getLocation());
467
    }
468
469
    private static String describeRotation(Rotation rotation) {
470
        if (rotation == null) return "null";
471
        return String.format(java.util.Locale.ROOT, "(yaw=%.2f,pitch=%.2f)", rotation.yaw(), rotation.pitch());
472
    }
473
474
    private static String formatVec(Vec3 vec) {
475
        if (vec == null) return "null";
476
        return String.format(java.util.Locale.ROOT, "(%.3f,%.3f,%.3f)", vec.x, vec.y, vec.z);
477
    }
478
479
    @Override
480
    public HudPhase getHudPhase() {
481
        return HudPhase.LAST;
482
    }
483
484
    @Override
485
    public WorldPhase getWorldPhase() {
486
        return WorldPhase.END_MAIN;
487
    }
488
489
    private void declareSettings() {
490
        List<SettingDef> defs = new ArrayList<>();
491
        defs.add(SettingDef.mode(rotationTiming));
492
        defs.add(SettingDef.mode(technique));
493
        defs.add(SettingDef.mode(sameY));
494
        defs.add(SettingDef.mode(movementCorrection).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL));
495
        defs.add(SettingDef.mode(angleSmoothMode).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL));
496
        defs.add(SettingDef.number(linearHorMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.LINEAR));
497
        defs.add(SettingDef.number(linearHorMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.LINEAR));
498
        defs.add(SettingDef.number(linearVertMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.LINEAR));
499
        defs.add(SettingDef.number(linearVertMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.LINEAR));
500
        defs.add(SettingDef.number(sigmoidHorMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.SIGMOID));
501
        defs.add(SettingDef.number(sigmoidHorMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.SIGMOID));
502
        defs.add(SettingDef.number(sigmoidVertMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.SIGMOID));
503
        defs.add(SettingDef.number(sigmoidVertMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.SIGMOID));
504
        defs.add(SettingDef.number(sigmoidSteepness).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.SIGMOID));
505
        defs.add(SettingDef.number(sigmoidMidpoint).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.SIGMOID));
506
        defs.add(SettingDef.number(interpHorMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.INTERPOLATION));
507
        defs.add(SettingDef.number(interpHorMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.INTERPOLATION));
508
        defs.add(SettingDef.number(interpVertMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.INTERPOLATION));
509
        defs.add(SettingDef.number(interpVertMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.INTERPOLATION));
510
        defs.add(SettingDef.number(interpDirMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.INTERPOLATION));
511
        defs.add(SettingDef.number(interpDirMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.INTERPOLATION));
512
        defs.add(SettingDef.number(interpMidpoint).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.INTERPOLATION));
513
        defs.add(SettingDef.number(accelYawMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION));
514
        defs.add(SettingDef.number(accelYawMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION));
515
        defs.add(SettingDef.number(accelPitchMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION));
516
        defs.add(SettingDef.number(accelPitchMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION));
517
        defs.add(SettingDef.bool(accelDynamicEnabled).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION));
518
        defs.add(SettingDef.number(accelCoefDistance).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && accelDynamicEnabled.get()));
519
        defs.add(SettingDef.number(accelYawCrossMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && accelDynamicEnabled.get()));
520
        defs.add(SettingDef.number(accelYawCrossMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && accelDynamicEnabled.get()));
521
        defs.add(SettingDef.number(accelPitchCrossMin).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && accelDynamicEnabled.get()));
522
        defs.add(SettingDef.number(accelPitchCrossMax).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && accelDynamicEnabled.get()));
523
        defs.add(SettingDef.bool(accelErrorEnabled).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION));
524
        defs.add(SettingDef.number(accelYawError).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && accelErrorEnabled.get()));
525
        defs.add(SettingDef.number(accelPitchError).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && accelErrorEnabled.get()));
526
        defs.add(SettingDef.bool(constantErrorEnabled).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION));
527
        defs.add(SettingDef.number(constantYawError).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && constantErrorEnabled.get()));
528
        defs.add(SettingDef.number(constantPitchError).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && constantErrorEnabled.get()));
529
        defs.add(SettingDef.bool(sigmoidDecelEnabled).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION));
530
        defs.add(SettingDef.number(sigmoidDecelSteepness).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && sigmoidDecelEnabled.get()));
531
        defs.add(SettingDef.number(sigmoidDecelMidpoint).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL && angleSmoothMode.get() == AngleSmoothMode.ACCELERATION && sigmoidDecelEnabled.get()));
532
        defs.add(SettingDef.bool(autoBlock));
533
        defs.add(SettingDef.bool(renderPlacement));
534
        defs.add(SettingDef.color(renderFillColor).visibleWhen(renderPlacement::get));
535
        defs.add(SettingDef.color(renderLineColor).visibleWhen(renderPlacement::get));
536
        defs.add(SettingDef.number(renderLineWidth).visibleWhen(renderPlacement::get));
537
        defs.add(SettingDef.number(renderBobAmplitude).visibleWhen(renderPlacement::get));
538
        defs.add(SettingDef.number(renderBobSpeed).visibleWhen(renderPlacement::get));
539
        defs.add(SettingDef.number(renderPlaceAnimTime).visibleWhen(renderPlacement::get));
540
        defs.add(SettingDef.bool(placementIndicator));
541
        defs.add(SettingDef.mode(placementIndicatorStyle).visibleWhen(placementIndicator::get));
542
        defs.add(SettingDef.mode(placementIndicatorSide).visibleWhen(placementIndicator::get));
543
        defs.add(SettingDef.mode(placementIndicatorCountMode).visibleWhen(placementIndicator::get));
544
        defs.add(SettingDef.number(placementIndicatorScale).visibleWhen(placementIndicator::get));
545
        defs.add(SettingDef.number(placementIndicatorOffsetX).visibleWhen(placementIndicator::get));
546
        defs.add(SettingDef.number(placementIndicatorOffsetY).visibleWhen(placementIndicator::get));
547
        defs.add(SettingDef.bool(placementIndicatorBackground).visibleWhen(placementIndicator::get));
548
        defs.add(SettingDef.bool(autoBlockAlways).visibleWhen(autoBlock::get));
549
        defs.add(SettingDef.number(autoBlockSlotResetDelay).visibleWhen(autoBlock::get));
550
        defs.add(SettingDef.number(autoBlockDoNotUseBelowCount).visibleWhen(autoBlock::get));
551
        defs.add(SettingDef.bool(prediction));
552
        defs.add(SettingDef.bool(considerInventory).visibleWhen(() -> rotationTiming.get() == RotationTiming.NORMAL));
553
        defs.add(SettingDef.number(placementSpeed).common(CommonSettingSchemas.PLACEMENT_SPEED));
554
        defs.add(SettingDef.number(delay));
555
        defs.add(SettingDef.bool(down));
556
        defs.add(SettingDef.bool(eagle));
557
        defs.add(SettingDef.number(blocksToEagle).visibleWhen(eagle::get));
558
        defs.add(SettingDef.number(eagleEdgeDistance).visibleWhen(eagle::get));
559
        defs.add(SettingDef.bool(eagleOnlyOnGround).visibleWhen(eagle::get));
560
        defs.add(SettingDef.number(expandLength).visibleWhen(() -> technique.get() == Technique.EXPAND));
561
        defs.add(SettingDef.bool(acceleration));
562
        defs.add(SettingDef.number(accelerationMultiplier).visibleWhen(acceleration::get));
563
        defs.add(SettingDef.bool(accelerationOnlyOnGround).visibleWhen(acceleration::get));
564
        defs.add(SettingDef.bool(strafe));
565
        defs.add(SettingDef.number(strafeSpeed).visibleWhen(strafe::get));
566
        defs.add(SettingDef.bool(strafeHypixel).visibleWhen(strafe::get));
567
        defs.add(SettingDef.bool(strafeOnlyOnGround).visibleWhen(strafe::get));
568
        defs.add(SettingDef.bool(jumpStrafe));
569
        defs.add(SettingDef.number(jumpStrafeStraightMin).visibleWhen(jumpStrafe::get));
570
        defs.add(SettingDef.number(jumpStrafeStraightMax).visibleWhen(jumpStrafe::get));
571
        defs.add(SettingDef.number(jumpStrafeDiagonalMin).visibleWhen(jumpStrafe::get));
572
        defs.add(SettingDef.number(jumpStrafeDiagonalMax).visibleWhen(jumpStrafe::get));
573
        defs.add(SettingDef.bool(speedLimiter));
574
        defs.add(SettingDef.number(speedLimit).visibleWhen(speedLimiter::get));
575
        defs.add(SettingDef.bool(stabilizeMovement).visibleWhen(() -> technique.get() == Technique.NORMAL));
576
        defs.add(SettingDef.bool(telly).visibleWhen(() -> technique.get() == Technique.NORMAL));
577
        defs.add(SettingDef.mode(aimMode).visibleWhen(() -> technique.get() == Technique.NORMAL));
578
        defs.add(SettingDef.mode(tellyResetMode).visibleWhen(() -> technique.get() == Technique.NORMAL && telly.get()));
579
        defs.add(SettingDef.number(tellyStraightTicks).visibleWhen(() -> technique.get() == Technique.NORMAL && telly.get()));
580
        defs.add(SettingDef.number(tellyJumpTicksMin).visibleWhen(() -> technique.get() == Technique.NORMAL && telly.get()));
581
        defs.add(SettingDef.number(tellyJumpTicksMax).visibleWhen(() -> technique.get() == Technique.NORMAL && telly.get()));
582
        defs.add(SettingDef.bool(tellyAimOnTower).visibleWhen(() -> technique.get() == Technique.NORMAL && telly.get()));
583
        defs.add(SettingDef.bool(ceiling).visibleWhen(() -> technique.get() == Technique.NORMAL));
584
        defs.add(SettingDef.bool(headHitter).visibleWhen(() -> technique.get() == Technique.NORMAL));
585
        defs.add(SettingDef.mode(towerMode));
586
        defs.add(SettingDef.number(towerMotion).visibleWhen(() -> towerMode.get() == TowerMode.MOTION));
587
        defs.add(SettingDef.number(towerTriggerHeight).visibleWhen(() -> towerMode.get() == TowerMode.MOTION));
588
        defs.add(SettingDef.number(towerSlow).visibleWhen(() -> towerMode.get() == TowerMode.MOTION));
589
        defs.add(SettingDef.mode(clientSprintMode));
590
        defs.add(SettingDef.mode(serverSprintMode));
591
        defs.forEach(this::setting);
592
    }
593
594
    @Override
595
    public void onEnable() {
596
        LocalPlayer player = player();
597
        if (player == null) return;
598
        placementY = player.getBlockY() - 1;
599
        delayLeft = 0;
600
        placementGate.reset();
601
        wasPlaced = false;
602
        currentTarget = null;
603
        towerAirTicks = 0;
604
        towerJumpBaseY = Double.NaN;
605
        strafeMoveTicks = 0;
606
        ticksUntilTellyJump = 0;
607
        tellyJumpTicks = randomTellyJumpTicks();
608
        currentOptimalLine = null;
609
        indicatorStack = ItemStack.EMPTY;
610
        indicatorVisible = false;
611
        indicatorCountText = "";
612
        indicatorCountValue = 0;
613
        indicatorRenderItem = false;
614
        lastPlacedRenderPos = null;
615
        lastPlacedRenderMillis = 0L;
616
        debugPendingPlacedPos = null;
617
        debugPendingPlacedTicks = 0;
618
        debugPendingPlacedAttempt = 0L;
619
        debugPendingPlacedSeenSolid = false;
620
        movementPlanner.reset();
621
        movementPrediction.reset();
622
    }
623
624
    @Override
625
    public void onDisable() {
626
        InventorySwap.INSTANCE.releaseHotbar(this);
627
        currentTarget = null;
628
        wasPlaced = false;
629
        delayLeft = 0;
630
        placementGate.reset();
631
        towerAirTicks = 0;
632
        towerJumpBaseY = Double.NaN;
633
        strafeMoveTicks = 0;
634
        ticksUntilTellyJump = 0;
635
        tellyJumpTicks = 0;
636
        currentOptimalLine = null;
637
        indicatorStack = ItemStack.EMPTY;
638
        indicatorVisible = false;
639
        indicatorCountText = "";
640
        indicatorCountValue = 0;
641
        indicatorRenderItem = false;
642
        lastPlacedRenderPos = null;
643
        lastPlacedRenderMillis = 0L;
644
        debugPendingPlacedPos = null;
645
        debugPendingPlacedTicks = 0;
646
        debugPendingPlacedAttempt = 0L;
647
        debugPendingPlacedSeenSolid = false;
648
        movementPlanner.reset();
649
        movementPrediction.reset();
650
        RotationManager.INSTANCE.release(this);
651
    }
652
653
    public boolean shouldSuppressOmniDirectionalSprint() {
654
        return isEnabled() && (currentTarget != null || wasPlaced);
655
    }
656
657
    @Override
658
    public void onRenderWorldEngine(Renderer3D renderer, Renderer3D depthRenderer, float tickDelta) {
659
        if (!renderPlacement.get()) return;
660
661
        LocalPlayer player = player();
662
        Minecraft mc = Minecraft.getInstance();
663
        if (player == null || mc.level == null) return;
664
665
        RenderPreview preview = getRenderPreview(tickDelta);
666
        if (preview == null) return;
667
668
        AABB box = animatedRenderBox(preview.pos, preview.progress, tickDelta);
669
        int fill = withAlphaScale(renderFillColor.getArgb(), preview.progress);
670
        int line = withAlphaScale(renderLineColor.getArgb(), preview.progress);
671
672
        float prevWidth = RenderState.lineWidth;
673
        RenderState.lineWidth = Math.max(1.0f, renderLineWidth.get());
674
        try {
675
            addFilledBox(renderer, box, fill);
676
            addOutlineBox(renderer, box, line);
677
        } finally {
678
            RenderState.lineWidth = prevWidth;
679
        }
680
    }
681
682
    @EventHandler
683
    private void onGameTick(GameTickEvent event) {
684
        LocalPlayer player = player();
685
        if (player == null) return;
686
687
        if (debugPendingPlacedPos != null) {
688
            BlockState state = player.level().getBlockState(debugPendingPlacedPos);
689
            boolean solid = !state.isAir();
690
            if (solid) {
691
                debugPendingPlacedSeenSolid = true;
692
            } else if (debugPendingPlacedSeenSolid) {
693
                debugLog(
694
                        "post-place-rollback attempt#%d pos=%s playerPos=%s vel=%s current=%s server=%s",
695
                        debugPendingPlacedAttempt,
696
                        debugPendingPlacedPos,
697
                        formatVec(player.position()),
698
                        formatVec(player.getDeltaMovement()),
699
                        describeRotation(RotationManager.INSTANCE.getCurrentRotation()),
700
                        describeRotation(RotationManager.INSTANCE.getServerRotation())
701
                );
702
                debugPendingPlacedPos = null;
703
                debugPendingPlacedTicks = 0;
704
                debugPendingPlacedAttempt = 0L;
705
                debugPendingPlacedSeenSolid = false;
706
            } else if (debugPendingPlacedTicks == 2) {
707
                debugLog(
708
                        "post-place-missing attempt#%d pos=%s playerPos=%s vel=%s current=%s server=%s",
709
                        debugPendingPlacedAttempt,
710
                        debugPendingPlacedPos,
711
                        formatVec(player.position()),
712
                        formatVec(player.getDeltaMovement()),
713
                        describeRotation(RotationManager.INSTANCE.getCurrentRotation()),
714
                        describeRotation(RotationManager.INSTANCE.getServerRotation())
715
                );
716
            }
717
718
            if (debugPendingPlacedPos != null) {
719
                debugPendingPlacedTicks--;
720
                if (debugPendingPlacedTicks <= 0) {
721
                    debugPendingPlacedPos = null;
722
                    debugPendingPlacedAttempt = 0L;
723
                    debugPendingPlacedSeenSolid = false;
724
                }
725
            }
726
        }
727
728
        if (delayLeft > 0) delayLeft--;
729
        InventorySwap.INSTANCE.tick();
730
        if (player.onGround()) {
731
            placementY = player.getBlockY() - 1;
732
            towerAirTicks = 0;
733
            ticksUntilTellyJump++;
734
        } else {
735
            towerAirTicks++;
736
        }
737
        if (wasPlaced) {
738
            wasPlaced = false;
739
        }
740
741
        handleTower(player);
742
        handleHeadHitter(player);
743
        handleAcceleration(player);
744
        handleStrafe(player);
745
        updateStrafeMoveTicks(player);
746
    }
747
748
    @Override
749
    public void onRenderHudEngine(Renderer2D renderer, TextRenderer textRenderer, GuiGraphicsExtractor ctx, float tickDelta) {
750
        indicatorVisible = false;
751
        indicatorCountText = "";
752
        indicatorCountValue = 0;
753
        indicatorRenderItem = false;
754
        if (!placementIndicator.get() || ctx == null || !isEnabled()) return;
755
756
        LocalPlayer player = player();
757
        if (player == null) return;
758
759
        PlacementIndicatorData data = getPlacementIndicatorData(player);
760
        if (data == null || data.stack().isEmpty()) return;
761
762
        Minecraft client = Minecraft.getInstance();
763
        int fbw = client.getWindow().getWidth();
764
        int fbh = client.getWindow().getHeight();
765
766
        ViewportContext.beginUnscaledLogical(ctx);
767
        try {
768
            float centerX = HudScale.virtualWidth(fbw, fbh) * 0.5f;
769
            float centerY = HudScale.virtualHeight(fbw, fbh) * 0.5f;
770
            BetterTooltips tooltips = BetterTooltips.get();
771
            float userScale = placementIndicatorScale.get().floatValue();
772
            float renderScale = userScale * 3.0f;
773
            float slotSize = (tooltips != null ? tooltips.shulkerPreviewSlotSize() : 18.0f) * renderScale;
774
            float slotRadius = (tooltips != null ? tooltips.shulkerPreviewSlotRadius() : 5.0f) * renderScale;
775
            float slotSoftness = (tooltips != null ? tooltips.shulkerPreviewSlotSoftness() : 1.0f) * renderScale;
776
            float stroke = 0.35f * renderScale;
777
            float offsetX = placementIndicatorOffsetX.get().floatValue();
778
            float offsetY = placementIndicatorOffsetY.get().floatValue();
779
            boolean pill = placementIndicatorStyle.get() == IndicatorStyle.PILL;
780
            float textScale = pill ? 1.08f * renderScale : 0.86f * renderScale;
781
            TextRenderer countRenderer = BuiltinFontCatalog.INTER_BOLD.renderer(textRenderer);
782
            float countWidth = data.countText().isEmpty() ? 0.0f : (float) countRenderer.getWidth(data.countText(), false) * textScale;
783
            float textHeight = (float) countRenderer.getHeight(false) * textScale;
784
            float pillPadX = 3.0f * renderScale;
785
            float pillPadY = renderScale;
786
            float bodyWidth = pill
787
                    ? Math.max(10.0f * renderScale, countWidth + pillPadX * 2.0f)
788
                    : slotSize;
789
            float bodyHeight = pill
790
                    ? textHeight + pillPadY * 2.0f
791
                    : slotSize;
792
            float bodyRadius = placementIndicatorStyle.get() == IndicatorStyle.PILL
793
                    ? bodyHeight * 0.5f
794
                    : slotRadius;
795
796
            float x;
797
            float y;
798
            switch (placementIndicatorSide.get()) {
799
                case RIGHT -> {
800
                    x = centerX + offsetX;
801
                    y = centerY - bodyHeight * 0.5f + offsetY;
802
                }
803
                case TOP -> {
804
                    x = centerX - bodyWidth * 0.5f + offsetX;
805
                    y = centerY - bodyHeight + offsetY;
806
                }
807
                case BOTTOM -> {
808
                    x = centerX - bodyWidth * 0.5f + offsetX;
809
                    y = centerY + offsetY;
810
                }
811
                case LEFT -> {
812
                    x = centerX - bodyWidth - offsetX;
813
                    y = centerY - bodyHeight * 0.5f + offsetY;
814
                }
815
                default -> {
816
                    x = centerX - bodyWidth - offsetX;
817
                    y = centerY - bodyHeight * 0.5f + offsetY;
818
                }
819
            }
820
821
            if (placementIndicatorBackground.get()) {
822
                if (pill) {
823
                    renderer.roundedRect(x, y, bodyWidth, bodyHeight, bodyRadius, 0.0f, 0xD0101010);
824
                } else {
825
                    int slotRgb = tooltips != null ? tooltips.shulkerPreviewSlotBgRgb() : 0x202020;
826
                    int borderRgb = tooltips != null ? tooltips.shulkerPreviewSlotBorderRgb() : 0x2F2F2F;
827
                    int borderAlpha = tooltips != null ? tooltips.shulkerPreviewSlotBorderAlpha() : 160;
828
                    renderer.roundedRect(x, y, bodyWidth, bodyHeight, bodyRadius, slotSoftness, colorWithAlpha(slotRgb, 0xFF));
829
                    renderer.roundedRectStroke(x, y, bodyWidth, bodyHeight, bodyRadius, slotSoftness, stroke, colorWithAlpha(borderRgb, borderAlpha));
830
                }
831
            }
832
833
            indicatorStack = data.stack().copy();
834
            indicatorVisible = true;
835
            indicatorRenderItem = !pill;
836
            indicatorX = x;
837
            indicatorY = y;
838
            indicatorSize = bodyHeight;
839
            indicatorScaleFactor = renderScale;
840
            indicatorCountText = data.countText();
841
            indicatorCountValue = data.count();
842
            indicatorTextScale = textScale;
843
            if (pill && !indicatorCountText.isEmpty()) {
844
                indicatorCountX = x + (bodyWidth - countWidth) * 0.5f;
845
                indicatorCountY = y + (bodyHeight - textHeight) * 0.5f;
846
                countRenderer.begin(indicatorTextScale, false, false);
847
                countRenderer.render(indicatorCountText, indicatorCountX, indicatorCountY, new RenderColor(getPillCountColor(indicatorCountValue)), false);
848
                countRenderer.end();
849
            } else {
850
                indicatorCountX = x + bodyWidth - 3.0f * renderScale;
851
                indicatorCountY = y + bodyHeight - 2.0f * renderScale;
852
            }
853
        } finally {
854
            ViewportContext.beginUnscaled(ctx);
855
        }
856
    }
857
858
    @Override
859
    public void onRenderHudEngineForeground(Renderer2D renderer, TextRenderer textRenderer, GuiGraphicsExtractor ctx, float tickDelta) {
860
        if (!indicatorVisible || ctx == null) return;
861
862
        ViewportContext.beginUnscaledLogical(ctx);
863
        try {
864
            if (indicatorRenderItem && !indicatorStack.isEmpty()) {
865
                float iconSize = 16.0f * indicatorScaleFactor;
866
                float offset = (indicatorSize - iconSize) * 0.5f;
867
                renderer.item(
868
                        indicatorStack,
869
                        indicatorX + offset,
870
                        indicatorY + offset,
871
                        indicatorScaleFactor,
872
                        0,
873
                        Renderer2D.ITEM_OVERLAY_ALL,
874
                        null
875
                );
876
            }
877
878
            if (!indicatorCountText.isEmpty() && indicatorRenderItem) {
879
                float ratio = Renderer2D.getUnscaledItemRatio();
880
                TextRenderer countRenderer = BuiltinFontCatalog.INTER_BOLD.renderer(textRenderer);
881
                countRenderer.begin(indicatorTextScale * ratio);
882
                double textX = indicatorCountX * ratio;
883
                double textY = indicatorCountY * ratio;
884
                double width = countRenderer.getWidth(indicatorCountText, false);
885
                textX -= width;
886
                textY -= countRenderer.getHeight(false);
887
                countRenderer.render(indicatorCountText, textX, textY, new RenderColor(0xFFFFFFFF), false);
888
                countRenderer.end();
889
            }
890
        } finally {
891
            ViewportContext.beginUnscaled(ctx);
892
        }
893
    }
894
895
    @EventHandler
896
    private void onRotationUpdate(RotationUpdateEvent event) {
897
        if (event.getType() != RotationUpdateEvent.Type.PRE) {
898
            return;
899
        }
900
901
        LocalPlayer player = player();
902
        boolean hasTarget = refreshCurrentTarget(player);
903
        if (rotationTiming.get() != RotationTiming.NORMAL) return;
904
905
        if (!hasTarget) {
906
            requestNormalStrictMoonwalkRotation(player);
907
            return;
908
        }
909
910
        List<RotationProcessor> processors = buildRotationProcessors();
911
        ScaffoldPlacementTarget targetSnapshot = currentTarget;
912
        RotationTarget target = new RotationTarget(
913
                targetSnapshot.getRotation(),
914
                null,
915
                processors,
916
                2,
917
                4.0f,
918
                considerInventory.get(),
919
                movementCorrection.get(),
920
                new RestrictedSingleUseAction(() -> executeScheduledNormalPlacement(
921
                        targetSnapshot,
922
                        RotationManager.INSTANCE.getCurrentRotation() != null
923
                                ? RotationManager.INSTANCE.getCurrentRotation()
924
                                : targetSnapshot.getRotation(),
925
                        preparePlacementHand(player()),
926
                        resolveNormalScheduledHit(player(), targetSnapshot)
927
                ))
928
        );
929
        RotationManager.INSTANCE.setRotationTarget(target, 100, this);
930
    }
931
932
    private void requestNormalStrictMoonwalkRotation(LocalPlayer player) {
933
        if (player == null || technique.get() != Technique.NORMAL) return;
934
        if (movementCorrection.get() != MovementCorrection.STRICT) return;
935
        if (!hasRawInput() || blockCount(player) <= 0) return;
936
937
        float movementYaw = getRawMovementDirectionYaw(player, player.getYRot());
938
        Rotation moonwalkRotation = new Rotation(movementYaw + 180.0f, 75.0f, false).normalize();
939
        RotationTarget target = new RotationTarget(
940
                moonwalkRotation,
941
                null,
942
                buildRotationProcessors(),
943
                2,
944
                4.0f,
945
                considerInventory.get(),
946
                movementCorrection.get(),
947
                null
948
        );
949
        RotationManager.INSTANCE.setRotationTarget(target, 100, this);
950
    }
951
952
    @EventHandler
953
    private void onMovementInput(MovementInputEvent event) {
954
        LocalPlayer player = player();
955
        if (!canOperate(player)) return;
956
957
        rawForward = event.isForward();
958
        rawBackward = event.isBackward();
959
        rawLeft = event.isLeft();
960
        rawRight = event.isRight();
961
        currentOptimalLine = hasRawInput()
962
                ? movementPlanner.getOptimalMovementLine(player, getRawMovementDirectionYaw(player, player.getYRot()))
963
                : null;
964
965
        refreshCurrentTarget(player);
966
967
        if (handleNormalOnTickPlacement(player, event)) {
968
            return;
969
        }
970
971
        if (speedLimiter.get() && horizontalSpeed(player.getDeltaMovement()) > speedLimit.get()) {
972
            event.setForward(false);
973
            event.setBackward(false);
974
            event.setLeft(false);
975
            event.setRight(false);
976
            return;
977
        }
978
979
        handleStabilizeMovement(player, event);
980
        handleTelly(player, event);
981
982
        if (shouldGoDown(player)) {
983
            event.setSneak(false);
984
            return;
985
        }
986
987
        handleNormalStrictMoonwalkInput(player, event);
988
989
        if (shouldEagle(player, event) && !event.isSneak()) {
990
            event.setSneak(true);
991
        }
992
    }
993
994
    @EventHandler
995
    private void onSafeWalk(PlayerSafeWalkEvent event) {
996
        LocalPlayer player = player();
997
        boolean canOperate = canOperate(player);
998
        if (!ScaffoldPlacementGate.shouldSafeWalk(
999
                isEnabled(),
1000
                eagle.get(),
1001
                canOperate,
1002
                canOperate && player.onGround(),
1003
                canOperate && player.getAbilities().flying,
1004
                canOperate && shouldGoDown(player),
1005
                canOperate && blockCount(player) > 0
1006
        )) return;
1007
1008
        // Eagle must never depend on rotation smoothing or placement cadence. Vanilla edge
1009
        // clipping keeps the player on the current block while the one-tick Eagle pulse ends.
1010
        event.setSafeWalk(true);
1011
    }
1012
1013
    @EventHandler
1014
    private void onSync(EventSync event) {
1015
    }
1016
1017
    @EventHandler
1018
    private void onPostPlayerUpdate(PostPlayerUpdateEvent event) {
1019
        LocalPlayer player = player();
1020
        if (!canOperate(player) || rotationTiming.get() != RotationTiming.ON_TICK) return;
1021
        executeOnTickPlacement(player);
1022
    }
1023
1024
    private boolean handleNormalOnTickPlacement(LocalPlayer player, MovementInputEvent event) {
1025
        if (player == null || event == null) return false;
1026
        if (technique.get() != Technique.NORMAL || rotationTiming.get() != RotationTiming.ON_TICK) return false;
1027
        if (shouldGoDown(player) || player.getAbilities().flying) return false;
1028
        if (!normalOnTickPlacementRequired(player)) return false;
1029
1030
        boolean placed = executeOnTickPlacement(player);
1031
        if (placed) {
1032
            return false;
1033
        }
1034
1035
        stopHorizontalInput(event);
1036
        return true;
1037
    }
1038
1039
    private boolean normalOnTickPlacementRequired(LocalPlayer player) {
1040
        if (player == null || player.level() == null) return false;
1041
        if (!hasRawInput()) return false;
1042
1043
        BlockPos targetPos = getTargetedPosition(player);
1044
        if (targetPos == null || !player.level().isInWorldBounds(targetPos)) {
1045
            return false;
1046
        }
1047
1048
        return player.level().getBlockState(targetPos).canBeReplaced();
1049
    }
1050
1051
    private void stopHorizontalInput(MovementInputEvent event) {
1052
        if (event == null) return;
1053
        event.setForward(false);
1054
        event.setBackward(false);
1055
        event.setLeft(false);
1056
        event.setRight(false);
1057
        event.setSprint(false);
1058
    }
1059
1060
    private boolean executeOnTickPlacement(LocalPlayer player) {
1061
        if (!canOperate(player) || currentTarget == null || !isPlacementCadenceReady()) return false;
1062
        if (isTargetStaleForPlayer(player, currentTarget)) {
1063
            debugLog(
1064
                    "target-cleared reason=stale-window target=%s playerPos=%s vel=%s onGround=%s",
1065
                    describeTarget(currentTarget),
1066
                    formatVec(player.position()),
1067
                    formatVec(player.getDeltaMovement()),
1068
                    player.onGround()
1069
            );
1070
            currentTarget = null;
1071
            return false;
1072
        }
1073
1074
        InteractionHand hand = preparePlacementHand(player);
1075
        if (hand == null) return false;
1076
1077
        debugLog(
1078
                "attempt#%d timing=%s tech=%s target=%s server=%s current=%s hand=%s delay=%d pos=%s vel=%s",
1079
                ++debugAttemptCounter,
1080
                EnumIds.defaultId(rotationTiming.get()),
1081
                EnumIds.defaultId(technique.get()),
1082
                describeTarget(currentTarget),
1083
                describeRotation(RotationManager.INSTANCE.getServerRotation()),
1084
                describeRotation(RotationManager.INSTANCE.getCurrentRotation()),
1085
                hand,
1086
                delayLeft,
1087
                formatVec(player.position()),
1088
                formatVec(player.getDeltaMovement())
1089
        );
1090
1091
        Rotation currentRotation = currentTarget.getRotation();
1092
        if (currentRotation == null) {
1093
            return false;
1094
        }
1095
1096
        Rotation serverRotation = RotationManager.INSTANCE.getServerRotation();
1097
        if (serverRotation == null || !serverRotation.approximatelyEquals(currentRotation, 0.01f)) {
1098
            debugLog(
1099
                    "attempt#%d on-tick-pre-look server=%s targetRot=%s",
1100
                    debugAttemptCounter,
1101
                    describeRotation(serverRotation),
1102
                    describeRotation(currentRotation)
1103
            );
1104
            sendLookPacket(player, currentRotation);
1105
        }
1106
1107
        BlockHitResult hitResult = resolvePlacementHit(player, currentTarget, currentRotation);
1108
        if (!currentTarget.matches(hitResult) || !isValidCrosshairTarget(player, hitResult)) {
1109
            return false;
1110
        }
1111
1112
        boolean placed = tryPlace(player, hand, hitResult);
1113
        if (!placed) {
1114
            return false;
1115
        }
1116
1117
        restoreOnTickPlayerRotation(player, currentRotation);
1118
        return true;
1119
    }
1120
1121
    private void restoreOnTickPlayerRotation(LocalPlayer player, Rotation scaffoldRotation) {
1122
        if (player == null || scaffoldRotation == null) return;
1123
1124
        Rotation playerRotation = new Rotation(player.getYRot(), player.getXRot(), true);
1125
        Rotation updatedServerRotation = RotationManager.INSTANCE.getServerRotation();
1126
        if (updatedServerRotation == null || !updatedServerRotation.approximatelyEquals(playerRotation, 0.01f)) {
1127
            debugLog(
1128
                    "attempt#%d on-tick-post-restore server=%s player=%s",
1129
                    debugAttemptCounter,
1130
                    describeRotation(updatedServerRotation),
1131
                    describeRotation(playerRotation)
1132
            );
1133
            sendLookPacket(player, new Rotation(
1134
                    RotationUtil.withFixedYaw(player.getYRot(), scaffoldRotation.yaw()),
1135
                    player.getXRot(),
1136
                    true
1137
            ));
1138
        }
1139
    }
1140
1141
    private void executeScheduledNormalPlacement(
1142
            ScaffoldPlacementTarget target,
1143
            Rotation rotation,
1144
            InteractionHand hand,
1145
            BlockHitResult hitResult
1146
    ) {
1147
        LocalPlayer player = player();
1148
        if (!isEnabled() || player == null || target == null || hitResult == null || hand == null
1149
                || !isPlacementCadenceReady()) {
1150
            return;
1151
        }
1152
        if (currentTarget != target) {
1153
            if (!samePlacementTarget(currentTarget, target)) {
1154
                currentTarget = target;
1155
            }
1156
        }
1157
        if (isTargetStaleForPlayer(player, target)) {
1158
            currentTarget = null;
1159
            return;
1160
        }
1161
1162
        long attemptId = ++debugAttemptCounter;
1163
        debugLog(
1164
                "attempt#%d timing=%s tech=%s target=%s server=%s current=%s hand=%s delay=%d pos=%s vel=%s",
1165
                attemptId,
1166
                EnumIds.defaultId(rotationTiming.get()),
1167
                EnumIds.defaultId(technique.get()),
1168
                describeTarget(target),
1169
                describeRotation(RotationManager.INSTANCE.getServerRotation()),
1170
                describeRotation(rotation),
1171
                hand,
1172
                delayLeft,
1173
                formatVec(player.position()),
1174
                formatVec(player.getDeltaMovement())
1175
        );
1176
1177
        tryPlace(player, hand, hitResult);
1178
    }
1179
1180
    private boolean samePlacementTarget(ScaffoldPlacementTarget a, ScaffoldPlacementTarget b) {
1181
        if (a == null || b == null) {
1182
            return false;
1183
        }
1184
        return a.getPlacedBlockPos().equals(b.getPlacedBlockPos())
1185
                && a.getInteractedBlockPos().equals(b.getInteractedBlockPos())
1186
                && a.getDirection() == b.getDirection();
1187
    }
1188
1189
    private BlockHitResult resolveNormalScheduledHit(LocalPlayer player, ScaffoldPlacementTarget target) {
1190
        if (player == null || target == null) {
1191
            return null;
1192
        }
1193
1194
        Rotation currentRotation = RotationManager.INSTANCE.getCurrentRotation();
1195
        if (currentRotation == null) {
1196
            currentRotation = target.getRotation();
1197
        }
1198
        if (currentRotation == null) {
1199
            currentRotation = new Rotation(player.getYRot(), player.getXRot(), true);
1200
        }
1201
1202
        return switch (technique.get()) {
1203
            case NORMAL -> getNormalCrosshairTarget(player, target, currentRotation);
1204
            default -> getTechniqueCrosshairTarget(player, target, currentRotation);
1205
        };
1206
    }
1207
1208
    private BlockHitResult resolvePlacementHit(
1209
            LocalPlayer player,
1210
            ScaffoldPlacementTarget target,
1211
            Rotation currentRotation
1212
    ) {
1213
        if (player == null || target == null || currentRotation == null) {
1214
            return null;
1215
        }
1216
1217
        BlockHitResult hitResult = switch (technique.get()) {
1218
            case NORMAL -> getNormalCrosshairTarget(player, target, currentRotation);
1219
            default -> getTechniqueCrosshairTarget(player, target, currentRotation);
1220
        };
1221
1222
        if (hitResult != null) {
1223
            return hitResult;
1224
        }
1225
1226
        if (technique.get() != Technique.NORMAL) {
1227
            return null;
1228
        }
1229
1230
        RotationTiming timing = rotationTiming.get();
1231
        if (timing != RotationTiming.ON_TICK) {
1232
            return null;
1233
        }
1234
1235
        return getOnTickHorizontalFallbackHit(player, target);
1236
    }
1237
1238
    @EventHandler
1239
    private void onPacketSend(PacketEvent.Send event) {
1240
        LocalPlayer player = player();
1241
        if (!isEnabled() || player == null || towerMode.get() != TowerMode.VULCAN || !isTowering(player)) return;
1242
        if (!(event.getPacket() instanceof ServerboundMovePlayerPacket packet)) return;
1243
        if (isMoving(player)) return;
1244
1245
        ServerboundMovePlayerPacketAccessor accessor = (ServerboundMovePlayerPacketAccessor) packet;
1246
        if (player.tickCount % 2 == 0) {
1247
            accessor.combatant$setX(packet.getX(player.getX()) + 0.1);
1248
            accessor.combatant$setZ(packet.getZ(player.getZ()) + 0.1);
1249
        }
1250
    }
1251
1252
    @EventHandler
1253
    private void onPacketReceive(PacketEvent.Receive event) {
1254
        LocalPlayer player = player();
1255
        if (!isEnabled() || player == null) return;
1256
        if (!(event.getPacket() instanceof ClientboundPlayerPositionPacket packet)) return;
1257
1258
        debugLog(
1259
                "server-correct packetRot=%s playerPos=%s vel=%s target=%s current=%s server=%s",
1260
                describeRotation(new Rotation(packet.change().yRot(), packet.change().xRot(), true)),
1261
                formatVec(player.position()),
1262
                formatVec(player.getDeltaMovement()),
1263
                describeTarget(currentTarget),
1264
                describeRotation(RotationManager.INSTANCE.getCurrentRotation()),
1265
                describeRotation(RotationManager.INSTANCE.getServerRotation())
1266
        );
1267
    }
1268
1269
    @EventHandler
1270
    private void onSprintControl(SprintControlEvent event) {
1271
        if (!isEnabled()) return;
1272
1273
        SprintMode mode = switch (event.getSource()) {
1274
            case INPUT, MOVEMENT_TICK -> clientSprintMode.get();
1275
            case NETWORK -> serverSprintMode.get();
1276
            default -> SprintMode.DO_NOT_CHANGE;
1277
        };
1278
1279
        if (mode == SprintMode.DO_NOT_CHANGE) return;
1280
1281
        switch (mode) {
1282
            case FORCE_SPRINT -> {
1283
                if (event.isMoving()) {
1284
                    event.setSprint(true);
1285
                }
1286
            }
1287
            case FORCE_NO_SPRINT -> event.setSprint(false);
1288
            case NO_SPRINT_ON_PLACE -> {
1289
                if (wasPlaced) {
1290
                    event.setSprint(false);
1291
                }
1292
            }
1293
            case NO_SPRINT_ON_GROUND -> {
1294
                LocalPlayer player = player();
1295
                if (player != null) {
1296
                    event.setSprint(!player.onGround());
1297
                }
1298
            }
1299
            default -> {
1300
            }
1301
        }
1302
    }
1303
1304
    private boolean tryPlace(LocalPlayer player, InteractionHand hand, BlockHitResult hitResult) {
1305
        if (player == null || currentTarget == null || hitResult == null || !isPlacementCadenceReady()) return false;
1306
1307
        Vec3 previousFallOffPos = currentOptimalLine != null
1308
                ? movementPrediction.getFallOffPositionOnLine(player, currentOptimalLine)
1309
                : null;
1310
1311
        InteractionResult result = Minecraft.getInstance().gameMode.useItemOn(
1312
                player,
1313
                hand,
1314
                hitResult
1315
        );
1316
        if (result == null || !result.consumesAction()) {
1317
            debugLog(
1318
                    "attempt#%d place-fail result=%s hit=%s target=%s playerPos=%s vel=%s onGround=%s current=%s server=%s",
1319
                    debugAttemptCounter,
1320
                    result,
1321
                    describeHit(hitResult),
1322
                    describeTarget(currentTarget),
1323
                    formatVec(player.position()),
1324
                    formatVec(player.getDeltaMovement()),
1325
                    player.onGround(),
1326
                    describeRotation(RotationManager.INSTANCE.getCurrentRotation()),
1327
                    describeRotation(RotationManager.INSTANCE.getServerRotation())
1328
            );
1329
            return false;
1330
        }
1331
1332
        player.swing(hand);
1333
        debugLog(
1334
                "attempt#%d place-ok hit=%s target=%s",
1335
                debugAttemptCounter,
1336
                describeHit(hitResult),
1337
                describeTarget(currentTarget)
1338
        );
1339
        wasPlaced = true;
1340
        debugPendingPlacedPos = currentTarget.getPlacedBlockPos();
1341
        debugPendingPlacedTicks = 3;
1342
        debugPendingPlacedAttempt = debugAttemptCounter;
1343
        debugPendingPlacedSeenSolid = false;
1344
        movementPlanner.trackPlacedBlock(currentTarget.getPlacedBlockPos());
1345
        movementPrediction.onPlace(currentOptimalLine, previousFallOffPos, player.position());
1346
        lastPlacedRenderPos = currentTarget.getPlacedBlockPos();
1347
        lastPlacedRenderMillis = System.currentTimeMillis();
1348
        placementGate.recordSuccessfulPlacement(System.nanoTime(), blocksToEagle.get());
1349
        delayLeft = delay.get();
1350
        currentTarget = null;
1351
        return true;
1352
    }
1353
1354
    private BlockHitResult getNormalCrosshairTarget(
1355
            LocalPlayer player,
1356
            ScaffoldPlacementTarget target,
1357
            Rotation currentRotation
1358
    ) {
1359
        if (player == null || target == null || currentRotation == null) return null;
1360
1361
        BlockHitResult crosshairTarget = traceScaffoldTarget(player, currentRotation);
1362
        if (target.matches(crosshairTarget)) {
1363
            return crosshairTarget;
1364
        }
1365
1366
        return shouldGoDown(player) ? target.toHitResult() : null;
1367
    }
1368
1369
    private BlockHitResult getTechniqueCrosshairTarget(
1370
            LocalPlayer player,
1371
            ScaffoldPlacementTarget target,
1372
            Rotation currentRotation
1373
    ) {
1374
        if (player == null || target == null || currentRotation == null) return null;
1375
1376
        BlockHitResult crosshairTarget = traceScaffoldTarget(player, currentRotation);
1377
        if (target.matches(crosshairTarget)) {
1378
            return crosshairTarget;
1379
        }
1380
1381
        return switch (technique.get()) {
1382
            case EXPAND -> target.toHitResult();
1383
            case NORMAL -> shouldGoDown(player) ? target.toHitResult() : null;
1384
            default -> null;
1385
        };
1386
    }
1387
1388
    private boolean isValidCrosshairTarget(LocalPlayer player, BlockHitResult hitResult) {
1389
        return player != null && isValidCrosshairTarget(player.getEyePosition(), hitResult);
1390
    }
1391
1392
    private boolean isValidCrosshairTarget(Vec3 eyePos, BlockHitResult hitResult) {
1393
        if (eyePos == null || hitResult == null) return false;
1394
1395
        Vec3 diff = hitResult.getLocation().subtract(eyePos);
1396
        Direction side = hitResult.getDirection();
1397
1398
        if (side.getAxis() != Direction.Axis.Y) {
1399
            double dist = (side == Direction.NORTH || side == Direction.SOUTH) ? diff.z : diff.x;
1400
            return !(Math.abs(dist) < minDist.get());
1401
        }
1402
1403
        return true;
1404
    }
1405
1406
    private boolean isTargetStaleForPlayer(LocalPlayer player, ScaffoldPlacementTarget target) {
1407
        if (player == null || target == null) return false;
1408
        if (player.onGround()) return false;
1409
        if (player.getDeltaMovement().y >= 0.0) return false;
1410
1411
        Direction side = target.getDirection();
1412
        if (side.getAxis() == Direction.Axis.Y) {
1413
            return false;
1414
        }
1415
1416
        double staleY = target.getInteractedBlockPos().getY() + 1.0;
1417
        return player.getY() < staleY;
1418
    }
1419
1420
    private BlockHitResult traceScaffoldTarget(LocalPlayer player, Rotation rotation) {
1421
        if (player == null || rotation == null) return null;
1422
        return traceScaffoldTarget(player, player.getEyePosition(), rotation);
1423
    }
1424
1425
    private BlockHitResult getOnTickHorizontalFallbackHit(
1426
            LocalPlayer player,
1427
            ScaffoldPlacementTarget target
1428
    ) {
1429
        if (player == null || target == null) {
1430
            return null;
1431
        }
1432
        if (target.getDirection().getAxis() == Direction.Axis.Y) {
1433
            return null;
1434
        }
1435
1436
        BlockHitResult fallbackHit = target.toHitResult();
1437
        return isWithinBlockInteractionRange(player, fallbackHit.getLocation()) ? fallbackHit : null;
1438
    }
1439
1440
    private boolean isWithinBlockInteractionRange(LocalPlayer player, Vec3 point) {
1441
        if (player == null || point == null) {
1442
            return false;
1443
        }
1444
        double range = player.blockInteractionRange();
1445
        return player.getEyePosition().distanceToSqr(point) <= range * range;
1446
    }
1447
1448
    private BlockHitResult traceScaffoldTarget(LocalPlayer player, Vec3 eyes, Rotation rotation) {
1449
        if (player == null || eyes == null || rotation == null || player.level() == null) return null;
1450
1451
        double range = Math.max(player.blockInteractionRange(), player.entityInteractionRange());
1452
        Vec3 end = eyes.add(rotation.directionVector().scale(range));
1453
        HitResult hitResult = player.level().clip(new ClipContext(
1454
                eyes,
1455
                end,
1456
                ClipContext.Block.OUTLINE,
1457
                ClipContext.Fluid.NONE,
1458
                player
1459
        ));
1460
1461
        return hitResult instanceof BlockHitResult blockHitResult ? blockHitResult : null;
1462
    }
1463
1464
    @EventHandler
1465
    private void onPlayerJump(PlayerJumpEvent event) {
1466
        LocalPlayer player = player();
1467
        if (!isEnabled() || player == null) return;
1468
1469
        ticksUntilTellyJump = 0;
1470
        tellyJumpTicks = randomTellyJumpTicks();
1471
        if (!jumpStrafe.get()) return;
1472
1473
        float direction = getRawMovementDirectionYaw(player, player.getYRot());
1474
        boolean straight = Math.round(direction / 45.0f) * 45 % 90 == 0;
1475
        double min = straight ? jumpStrafeStraightMin.get() : jumpStrafeDiagonalMin.get();
1476
        double max = straight ? jumpStrafeStraightMax.get() : jumpStrafeDiagonalMax.get();
1477
        double speed = randomRange(min, max);
1478
        Vec3 strafeVelocity = MovementUtil.withStrafe(player.getDeltaMovement(), new Vec3(0.0, 0.0, 1.0), direction, speed, 1.0);
1479
        player.setDeltaMovement(strafeVelocity.x, player.getDeltaMovement().y, strafeVelocity.z);
1480
    }
1481
1482
    private InteractionHand preparePlacementHand(LocalPlayer player) {
1483
        if (player == null) return null;
1484
        if (ScaffoldBlockItemSelection.isValidBlock(player.getMainHandItem())) return InteractionHand.MAIN_HAND;
1485
        if (ScaffoldBlockItemSelection.isValidBlock(player.getOffhandItem())) return InteractionHand.OFF_HAND;
1486
        if (!autoBlock.get()) return null;
1487
1488
        int bestSlot = ScaffoldBlockItemSelection.findBestHotbarSlot(
1489
                player,
1490
                autoBlockDoNotUseBelowCount.get(),
1491
                InventorySwap.INSTANCE.serverSelectedSlot()
1492
        );
1493
        if (bestSlot < 0) return null;
1494
        InventorySwap.INSTANCE.leaseHotbar(this, bestSlot, autoBlockSlotResetDelay.get());
1495
1496
        return ScaffoldBlockItemSelection.isValidBlock(player.getMainHandItem()) ? InteractionHand.MAIN_HAND : null;
1497
    }
1498
1499
    private void restoreSelectedSlot() {
1500
        InventorySwap.INSTANCE.releaseHotbar(this);
1501
    }
1502
1503
    private ItemStack getPreferredPlacementStack(LocalPlayer player) {
1504
        if (player == null) return ItemStack.EMPTY;
1505
        if (ScaffoldBlockItemSelection.isValidBlock(player.getMainHandItem())) return player.getMainHandItem();
1506
        if (ScaffoldBlockItemSelection.isValidBlock(player.getOffhandItem())) return player.getOffhandItem();
1507
        if (!autoBlock.get()) return ItemStack.EMPTY;
1508
1509
        int bestSlot = ScaffoldBlockItemSelection.findBestHotbarSlot(
1510
                player,
1511
                autoBlockDoNotUseBelowCount.get(),
1512
                InventorySwap.INSTANCE.serverSelectedSlot()
1513
        );
1514
        if (bestSlot < 0) return ItemStack.EMPTY;
1515
1516
        if (autoBlockAlways.get()) {
1517
            InventorySwap.INSTANCE.leaseHotbar(this, bestSlot, autoBlockSlotResetDelay.get());
1518
            if (ScaffoldBlockItemSelection.isValidBlock(player.getMainHandItem())) {
1519
                return player.getMainHandItem();
1520
            }
1521
        }
1522
1523
        return player.getInventory().getItem(bestSlot);
1524
    }
1525
1526
    private ItemStack peekPlacementIndicatorStack(LocalPlayer player) {
1527
        if (player == null) return ItemStack.EMPTY;
1528
        if (ScaffoldBlockItemSelection.isValidBlock(player.getMainHandItem())) return player.getMainHandItem();
1529
        if (ScaffoldBlockItemSelection.isValidBlock(player.getOffhandItem())) return player.getOffhandItem();
1530
        if (!autoBlock.get()) return ItemStack.EMPTY;
1531
1532
        int silentSlot = InventorySwap.INSTANCE.isHotbarLeasedBy(this) ? InventorySwap.INSTANCE.serverSelectedSlot() : -1;
1533
        if (silentSlot >= 0 && silentSlot <= 8) {
1534
            ItemStack stack = player.getInventory().getItem(silentSlot);
1535
            if (ScaffoldBlockItemSelection.isValidBlock(stack)) {
1536
                return stack;
1537
            }
1538
        }
1539
1540
        int bestSlot = ScaffoldBlockItemSelection.findBestHotbarSlot(
1541
                player,
1542
                autoBlockDoNotUseBelowCount.get(),
1543
                InventorySwap.INSTANCE.serverSelectedSlot()
1544
        );
1545
        return bestSlot >= 0 ? player.getInventory().getItem(bestSlot) : ItemStack.EMPTY;
1546
    }
1547
1548
    private PlacementIndicatorData getPlacementIndicatorData(LocalPlayer player) {
1549
        ItemStack stack = peekPlacementIndicatorStack(player);
1550
        if (stack.isEmpty()) return null;
1551
1552
        int count = getPlacementIndicatorCount(player, stack);
1553
        return new PlacementIndicatorData(stack, Math.max(count, 0), String.valueOf(Math.max(count, 0)));
1554
    }
1555
1556
    private int getPlacementIndicatorCount(LocalPlayer player, ItemStack stack) {
1557
        if (player == null || stack.isEmpty()) return 0;
1558
1559
        return switch (placementIndicatorCountMode.get()) {
1560
            case CURRENT_STACK -> stack.getCount();
1561
            case SAME_ITEM -> countAvailableScaffoldBlocks(player, candidate ->
1562
                    ItemStack.isSameItemSameComponents(candidate, stack));
1563
            case ALL_PLACEABLE -> countAvailableScaffoldBlocks(player, ScaffoldBlockItemSelection::isValidBlock);
1564
        };
1565
    }
1566
1567
    private int countAvailableScaffoldBlocks(LocalPlayer player, java.util.function.Predicate<ItemStack> predicate) {
1568
        int count = 0;
1569
1570
        ItemStack offhand = player.getOffhandItem();
1571
        if (predicate.test(offhand)) {
1572
            count += offhand.getCount();
1573
        }
1574
1575
        for (int slot = 0; slot < 36; slot++) {
1576
            ItemStack stack = player.getInventory().getItem(slot);
1577
            if (predicate.test(stack)) {
1578
                count += stack.getCount();
1579
            }
1580
        }
1581
1582
        return count;
1583
    }
1584
1585
    private RenderPreview getRenderPreview(float tickDelta) {
1586
        Minecraft mc = Minecraft.getInstance();
1587
        if (mc.level == null) return null;
1588
1589
        if (currentTarget != null) {
1590
            BlockPos pos = currentTarget.getPlacedBlockPos();
1591
            if (mc.level.getBlockState(pos).canBeReplaced()) {
1592
                return new RenderPreview(pos, 1.0f);
1593
            }
1594
        }
1595
1596
        if (lastPlacedRenderPos == null) return null;
1597
1598
        double elapsed = (System.currentTimeMillis() - lastPlacedRenderMillis) / 1000.0;
1599
        double duration = renderPlaceAnimTime.get();
1600
        if (elapsed >= duration) {
1601
            lastPlacedRenderPos = null;
1602
            return null;
1603
        }
1604
1605
        float progress = (float) (1.0 - (elapsed / duration));
1606
        return new RenderPreview(lastPlacedRenderPos, Mth.clamp(progress, 0.0f, 1.0f));
1607
    }
1608
1609
    private AABB animatedRenderBox(BlockPos pos, float progress, float tickDelta) {
1610
        double time = (System.currentTimeMillis() / 1000.0) * renderBobSpeed.get();
1611
        double bob = Math.sin((time + tickDelta) * Math.PI) * renderBobAmplitude.get() * progress;
1612
        double inset = 0.06 * (1.0 - progress);
1613
1614
        return new AABB(
1615
                pos.getX() + inset,
1616
                pos.getY() + inset + bob,
1617
                pos.getZ() + inset,
1618
                pos.getX() + 1.0 - inset,
1619
                pos.getY() + 1.0 - inset + bob,
1620
                pos.getZ() + 1.0 - inset
1621
        );
1622
    }
1623
1624
    private BlockPos getTargetedPosition(LocalPlayer player) {
1625
        Vec3 predictedPos = getPlacementBasePosition(player);
1626
        BlockPos basePos = BlockPos.containing(predictedPos);
1627
        if (shouldGoDown(player)) {
1628
            return basePos.below(2);
1629
        }
1630
        if (canConstructCeiling(player)) {
1631
            return basePos.above(3);
1632
        }
1633
        if (Minecraft.getInstance().options.keyJump.isDown()
1634
                && (!isMoving(player) || player.horizontalCollision)) {
1635
            return basePos.below();
1636
        }
1637
1638
        return switch (sameY.get()) {
1639
            case ON -> new BlockPos(basePos.getX(), placementY, basePos.getZ());
1640
            case FALLING -> player.getDeltaMovement().y < 0.2
1641
                    ? new BlockPos(basePos.getX(), placementY, basePos.getZ())
1642
                    : basePos.below();
1643
            case OFF -> basePos.below();
1644
        };
1645
    }
1646
1647
    private ScaffoldPlacementTarget findPlacementTarget(LocalPlayer player, ItemStack stack) {
1648
        return switch (technique.get()) {
1649
            case EXPAND -> findExpandPlacementTarget(player, stack);
1650
            case NORMAL -> findNormalPlacementTarget(player, stack);
1651
        };
1652
    }
1653
1654
    private boolean refreshCurrentTarget(LocalPlayer player) {
1655
        if (!canOperate(player)) {
1656
            currentTarget = null;
1657
            if (debugLastTargetPos != null) {
1658
                debugLog("target-cleared reason=canOperate-false");
1659
                debugLastTargetPos = null;
1660
            }
1661
            return false;
1662
        }
1663
1664
        ItemStack stack = getPreferredPlacementStack(player);
1665
        if (!ScaffoldBlockItemSelection.isValidBlock(stack)) {
1666
            currentTarget = null;
1667
            if (debugLastTargetPos != null) {
1668
                debugLog("target-cleared reason=no-valid-stack");
1669
                debugLastTargetPos = null;
1670
            }
1671
            return false;
1672
        }
1673
1674
        currentTarget = findPlacementTarget(player, stack);
1675
        BlockPos currentPos = currentTarget != null ? currentTarget.getPlacedBlockPos() : null;
1676
        if (currentPos == null) {
1677
            if (debugLastTargetPos != null) {
1678
                debugLog("target-cleared reason=findPlacementTarget-null");
1679
                debugLastTargetPos = null;
1680
            }
1681
        } else if (!currentPos.equals(debugLastTargetPos)) {
1682
            debugLog(
1683
                    "target-acquired tech=%s timing=%s target=%s playerPos=%s vel=%s",
1684
                    EnumIds.defaultId(technique.get()),
1685
                    EnumIds.defaultId(rotationTiming.get()),
1686
                    describeTarget(currentTarget),
1687
                    formatVec(player.position()),
1688
                    formatVec(player.getDeltaMovement())
1689
            );
1690
            debugLastTargetPos = currentPos;
1691
        }
1692
        return currentTarget != null;
1693
    }
1694
1695
    private boolean shouldKeepPreviousTarget(
1696
            LocalPlayer player,
1697
            ScaffoldPlacementTarget previousTarget,
1698
            ScaffoldPlacementTarget nextTarget
1699
    ) {
1700
        if (player == null || previousTarget == null || nextTarget == null) {
1701
            return false;
1702
        }
1703
        if (isTargetStaleForPlayer(player, previousTarget)) {
1704
            return false;
1705
        }
1706
        if (!isNearbyPlacementTransition(previousTarget, nextTarget)) {
1707
            return false;
1708
        }
1709
        if (!isPreviousTargetStillActionable(player, previousTarget)) {
1710
            return false;
1711
        }
1712
1713
        Rotation previousRotation = previousTarget.getRotation();
1714
        Rotation nextRotation = nextTarget.getRotation();
1715
        if (previousRotation == null || nextRotation == null) {
1716
            return false;
1717
        }
1718
1719
        return previousRotation.angleTo(nextRotation) > 90.0f;
1720
    }
1721
1722
    private boolean isNearbyPlacementTransition(ScaffoldPlacementTarget previousTarget, ScaffoldPlacementTarget nextTarget) {
1723
        if (previousTarget == null || nextTarget == null) {
1724
            return false;
1725
        }
1726
1727
        BlockPos previousPlaced = previousTarget.getPlacedBlockPos();
1728
        BlockPos nextPlaced = nextTarget.getPlacedBlockPos();
1729
        if (previousPlaced.equals(nextPlaced)) {
1730
            return true;
1731
        }
1732
1733
        int dx = Math.abs(previousPlaced.getX() - nextPlaced.getX());
1734
        int dy = Math.abs(previousPlaced.getY() - nextPlaced.getY());
1735
        int dz = Math.abs(previousPlaced.getZ() - nextPlaced.getZ());
1736
        return dy == 0 && dx + dz <= 1;
1737
    }
1738
1739
    private boolean isPreviousTargetStillActionable(LocalPlayer player, ScaffoldPlacementTarget target) {
1740
        if (player == null || target == null || player.level() == null) {
1741
            return false;
1742
        }
1743
1744
        BlockState supportState = player.level().getBlockState(target.getInteractedBlockPos());
1745
        if (supportState == null || supportState.canBeReplaced()) {
1746
            return false;
1747
        }
1748
1749
        BlockState placedState = player.level().getBlockState(target.getPlacedBlockPos());
1750
        if (placedState == null || !placedState.canBeReplaced()) {
1751
            return false;
1752
        }
1753
1754
        return isWithinBlockInteractionRange(player, target.getHitVec());
1755
    }
1756
1757
    private ScaffoldPlacementTarget findNormalPlacementTarget(LocalPlayer player, ItemStack stack) {
1758
        Vec3 placementEyePos = getPlacementEyePos(player);
1759
        Comparator<BlockPos> comparator = getNormalTargetComparator(player, placementEyePos);
1760
        List<BlockPos> offsets = shouldGoDown(player) ? DOWN_OFFSETS : NORMAL_OFFSETS;
1761
        ScaffoldFacePositionFactory facePositionFactory = createPlacementFacePositionFactory(player, aimMode.get(), placementEyePos);
1762
        BlockPos targetedPos = getTargetedPosition(player);
1763
        List<BlockPos> movementOffsets = movementAlignedNormalOffsets(player, targetedPos, offsets);
1764
        if (movementOffsets.isEmpty()) {
1765
            return null;
1766
        }
1767
1768
        return findNormalPlacementTargetAt(
1769
                player,
1770
                stack,
1771
                targetedPos,
1772
                movementOffsets,
1773
                comparator,
1774
                facePositionFactory,
1775
                placementEyePos
1776
        );
1777
    }
1778
1779
    private List<BlockPos> movementAlignedNormalOffsets(LocalPlayer player, BlockPos targetedPos, List<BlockPos> offsets) {
1780
        if (player == null || targetedPos == null || offsets == null || offsets.isEmpty()) {
1781
            return offsets;
1782
        }
1783
        if (currentOptimalLine == null || !hasRawInput() || shouldGoDown(player)) {
1784
            return offsets;
1785
        }
1786
1787
        Vec3 reference = currentOptimalLine.getNearestPointTo(player.position());
1788
        Vec3 direction = currentOptimalLine.direction();
1789
        List<BlockPos> aligned = new ArrayList<>(offsets.size());
1790
1791
        for (BlockPos offset : offsets) {
1792
            BlockPos candidate = targetedPos.offset(offset);
1793
            double progress = Vec3.atCenterOf(candidate).subtract(reference).dot(direction);
1794
            if (progress >= -0.15) {
1795
                aligned.add(offset);
1796
            }
1797
        }
1798
1799
        return aligned;
1800
    }
1801
1802
    private ScaffoldPlacementTarget findNormalPlacementTargetAt(
1803
            LocalPlayer player,
1804
            ItemStack stack,
1805
            BlockPos targetedPos,
1806
            List<BlockPos> offsets,
1807
            Comparator<BlockPos> comparator,
1808
            ScaffoldFacePositionFactory facePositionFactory,
1809
            Vec3 placementEyePos
1810
    ) {
1811
        return ScaffoldTargetFinder.findTarget(
1812
                player,
1813
                targetedPos,
1814
                stack,
1815
                offsets,
1816
                comparator,
1817
                shouldGoDown(player),
1818
                facePositionFactory,
1819
                placementEyePos
1820
        );
1821
    }
1822
1823
    private ScaffoldPlacementTarget findExpandPlacementTarget(LocalPlayer player, ItemStack stack) {
1824
        Vec3 placementEyePos = getPlacementEyePos(player);
1825
        for (int i = 0; i <= expandLength.get(); i++) {
1826
            BlockPos position = getExpandTargetedPosition(player, i);
1827
            ScaffoldPlacementTarget target = ScaffoldTargetFinder.findTarget(
1828
                    player,
1829
                    position,
1830
                    stack,
1831
                    List.of(BlockPos.ZERO),
1832
                    Comparator.comparingDouble((BlockPos pos) -> Vec3.atCenterOf(pos).distanceToSqr(placementEyePos)).reversed(),
1833
                    true,
1834
                    new ScaffoldFacePositionFactory(
1835
                            player,
1836
                            placementEyePos,
1837
                            ScaffoldFacePositionFactory.Mode.CENTER,
1838
                            currentOptimalLine,
1839
                            randomRange(-1.0, 1.0)
1840
                    ),
1841
                    placementEyePos
1842
            );
1843
            if (target == null) continue;
1844
            Vec3 blockCenter = Vec3.atCenterOf(target.getPlacedBlockPos());
1845
            Rotation rotation = Rotation.lookingAt(blockCenter, placementEyePos);
1846
            return target.withRotation(rotation);
1847
        }
1848
        return null;
1849
    }
1850
1851
    private ScaffoldPlacementTarget findCenterPlacementTarget(LocalPlayer player, ItemStack stack) {
1852
        Vec3 placementEyePos = getPlacementEyePos(player);
1853
        return ScaffoldTargetFinder.findTarget(
1854
                player,
1855
                getTargetedPosition(player),
1856
                stack,
1857
                NORMAL_OFFSETS,
1858
                Comparator.comparingDouble((BlockPos pos) -> Vec3.atCenterOf(pos).distanceToSqr(placementEyePos)).reversed(),
1859
                false,
1860
                new ScaffoldFacePositionFactory(
1861
                        player,
1862
                        placementEyePos,
1863
                        ScaffoldFacePositionFactory.Mode.CENTER,
1864
                        currentOptimalLine,
1865
                        randomRange(-1.0, 1.0)
1866
                ),
1867
                placementEyePos
1868
        );
1869
    }
1870
1871
    private BlockPos getExpandTargetedPosition(LocalPlayer player, int expand) {
1872
        Vec3 position = player.position();
1873
        float yaw = player.getYRot();
1874
        int x = (int) (-Math.sin(Math.toRadians(yaw)) * expand);
1875
        int z = (int) (Math.cos(Math.toRadians(yaw)) * expand);
1876
        BlockPos expanded = BlockPos.containing(position).offset(x, 0, z);
1877
        return getTargetedPositionFromBase(player, expanded);
1878
    }
1879
1880
    private BlockPos getTargetedPositionFromBase(LocalPlayer player, BlockPos basePos) {
1881
        if (shouldGoDown(player)) {
1882
            return basePos.below(2);
1883
        }
1884
        if (Minecraft.getInstance().options.keyJump.isDown()
1885
                && (!isMoving(player) || player.horizontalCollision)) {
1886
            return basePos.below();
1887
        }
1888
        return switch (sameY.get()) {
1889
            case ON -> new BlockPos(basePos.getX(), placementY, basePos.getZ());
1890
            case FALLING -> player.getDeltaMovement().y < 0.2
1891
                    ? new BlockPos(basePos.getX(), placementY, basePos.getZ())
1892
                    : basePos.below();
1893
            case OFF -> basePos.below();
1894
        };
1895
    }
1896
1897
    private void sendLookPacket(LocalPlayer player, Rotation rotation) {
1898
        if (player == null || player.connection == null || rotation == null) return;
1899
        Rotation normalized = rotation.normalize();
1900
        debugLog(
1901
                "send-look pos=%s rot=%s onGround=%s horiz=%s",
1902
                formatVec(player.position()),
1903
                describeRotation(normalized),
1904
                player.onGround(),
1905
                player.horizontalCollision
1906
        );
1907
        player.connection.send(new ServerboundMovePlayerPacket.PosRot(
1908
                player.getX(),
1909
                player.getY(),
1910
                player.getZ(),
1911
                normalized.yaw(),
1912
                normalized.pitch(),
1913
                player.onGround(),
1914
                player.horizontalCollision
1915
        ));
1916
    }
1917
1918
    private boolean canOperate(LocalPlayer player) {
1919
        Minecraft mc = Minecraft.getInstance();
1920
        return player != null
1921
                && mc.level != null
1922
                && mc.gameMode != null
1923
                && ClientScreen.current() == null;
1924
    }
1925
1926
    private boolean isMoving(LocalPlayer player) {
1927
        if (player == null || player.input == null) return false;
1928
        return Math.abs(player.input.getMoveVector().x) > 1.0E-5f
1929
                || Math.abs(player.input.getMoveVector().y) > 1.0E-5f;
1930
    }
1931
1932
    private boolean shouldGoDown(LocalPlayer player) {
1933
        Minecraft mc = Minecraft.getInstance();
1934
        return down.get()
1935
                && player != null
1936
                && mc.options.keyShift.isDown()
1937
                && canStandOn(player.blockPosition().below(2));
1938
    }
1939
1940
    private boolean shouldEagle(LocalPlayer player, MovementInputEvent event) {
1941
        if (player == null || event == null) return false;
1942
1943
        EagleUtil.EdgeCheck edgeCheck = EagleUtil.checkEdge(player, event, eagleEdgeDistance.get());
1944
        return placementGate.consumeEaglePulse(
1945
                eagle.get(),
1946
                edgeCheck.closeToEdge(),
1947
                eagleOnlyOnGround.get(),
1948
                player.onGround(),
1949
                player.getAbilities().flying,
1950
                shouldGoDown(player)
1951
        );
1952
    }
1953
1954
    private boolean isPlacementCadenceReady() {
1955
        return placementGate.isPlacementReady(System.nanoTime(), placementSpeed.get(), delayLeft);
1956
    }
1957
1958
    private void handleTower(LocalPlayer player) {
1959
        if (!isEnabled() || player == null) return;
1960
        if (!isTowering(player)) {
1961
            towerJumpBaseY = Double.NaN;
1962
            return;
1963
        }
1964
1965
        switch (towerMode.get()) {
1966
            case MOTION -> handleMotionTower(player);
1967
            case VULCAN -> handleVulcanTower(player);
1968
            case HYPIXEL -> handleHypixelTower(player);
1969
            default -> {
1970
            }
1971
        }
1972
    }
1973
1974
    private void handleAcceleration(LocalPlayer player) {
1975
        if (!acceleration.get() || player == null) return;
1976
        if (accelerationOnlyOnGround.get() && !player.onGround()) return;
1977
1978
        Vec3 velocity = player.getDeltaMovement();
1979
        player.setDeltaMovement(
1980
                velocity.x * accelerationMultiplier.get(),
1981
                velocity.y,
1982
                velocity.z * accelerationMultiplier.get()
1983
        );
1984
    }
1985
1986
    private void updateStrafeMoveTicks(LocalPlayer player) {
1987
        if (player == null) return;
1988
        if (isMoving(player)) {
1989
            strafeMoveTicks++;
1990
        } else {
1991
            strafeMoveTicks = 0;
1992
        }
1993
    }
1994
1995
    private void handleHeadHitter(LocalPlayer player) {
1996
        if (!headHitter.get() || technique.get() != Technique.NORMAL || player == null) return;
1997
        if (!player.onGround() || !isMoving(player)) return;
1998
        BlockPos above = player.blockPosition().above(2);
1999
        if (player.level().getBlockState(above).isAir()) return;
2000
        player.jumpFromGround();
2001
    }
2002
2003
    private void handleStabilizeMovement(LocalPlayer player, MovementInputEvent event) {
2004
        if (!stabilizeMovement.get() || technique.get() != Technique.NORMAL || player == null) return;
2005
        if (rotationTiming.get() != RotationTiming.NORMAL) return;
2006
        if (event.isJump() && player.onGround()) return;
2007
2008
        ScaffoldLine optimalLine = currentOptimalLine;
2009
        if (optimalLine == null) return;
2010
2011
        Vec3 nearestPoint = optimalLine.getNearestPointTo(player.position());
2012
        Vec3 toLine = nearestPoint.subtract(player.position());
2013
        Vec3 lineDirection = new Vec3(optimalLine.direction().x, 0.0, optimalLine.direction().z);
2014
        if (lineDirection.lengthSqr() < 1.0E-7) return;
2015
2016
        Vec3 desiredWorld = lineDirection.normalize();
2017
        double correctionLength = Math.hypot(toLine.x, toLine.z);
2018
        if (correctionLength > 1.0E-7) {
2019
            Vec3 correction = new Vec3(toLine.x / correctionLength, 0.0, toLine.z / correctionLength);
2020
            double correctionStrength = Mth.clamp(0.35 + correctionLength * 3.0, 0.35, 1.0);
2021
            desiredWorld = desiredWorld.add(correction.scale(correctionStrength)).normalize();
2022
        }
2023
2024
        applyLineHoldInput(event, desiredWorld, player.getYRot());
2025
    }
2026
2027
    private void applyLineHoldInput(MovementInputEvent event, Vec3 desiredWorld, float yaw) {
2028
        double rad = Math.toRadians(yaw);
2029
        double sin = Math.sin(rad);
2030
        double cos = Math.cos(rad);
2031
        double localForward = desiredWorld.z * cos - desiredWorld.x * sin;
2032
        double localSideways = desiredWorld.x * cos + desiredWorld.z * sin;
2033
2034
        event.setForward(localForward > 1.0E-4);
2035
        event.setBackward(localForward < -1.0E-4);
2036
        event.setLeft(localSideways < -1.0E-4);
2037
        event.setRight(localSideways > 1.0E-4);
2038
    }
2039
2040
    private void handleNormalStrictMoonwalkInput(LocalPlayer player, MovementInputEvent event) {
2041
        if (player == null || event == null) return;
2042
        if (technique.get() != Technique.NORMAL) return;
2043
        if (rotationTiming.get() != RotationTiming.NORMAL) return;
2044
        if (movementCorrection.get() != MovementCorrection.STRICT) return;
2045
        if (!hasRawInput() || blockCount(player) <= 0) return;
2046
2047
        Rotation movementRotation = RotationManager.INSTANCE.getCurrentRotation();
2048
        if (movementRotation == null && currentTarget != null) {
2049
            movementRotation = currentTarget.getRotation();
2050
        }
2051
        if (movementRotation == null) {
2052
            movementRotation = new Rotation(getRawMovementDirectionYaw(player, player.getYRot()) + 180.0f, 75.0f, false).normalize();
2053
        }
2054
2055
        Input corrected = RotationUtil.correctMovementInput(
2056
                event.toPlayerInput(),
2057
                player.getYRot(),
2058
                movementRotation.yaw()
2059
        );
2060
        if (corrected == null) return;
2061
2062
        event.setForward(corrected.forward());
2063
        event.setBackward(corrected.backward());
2064
        event.setLeft(corrected.left());
2065
        event.setRight(corrected.right());
2066
        event.setJump(corrected.jump());
2067
        event.setSprint(corrected.sprint() && corrected.forward() && !corrected.backward());
2068
    }
2069
2070
    private void handleTelly(LocalPlayer player, MovementInputEvent event) {
2071
        if (!telly.get() || technique.get() != Technique.NORMAL || player == null) return;
2072
        if (!isMoving(player) || blockCount(player) <= 0 || !player.onGround()) return;
2073
2074
        switch (tellyResetMode.get()) {
2075
            case REVERSE -> event.setJump(true);
2076
            case RESET -> {
2077
                if (shouldTellyJumpNow(player)) {
2078
                    event.setJump(true);
2079
                }
2080
            }
2081
        }
2082
    }
2083
2084
    private void handleStrafe(LocalPlayer player) {
2085
        if (!strafe.get() || player == null) return;
2086
        if (strafeOnlyOnGround.get() && !player.onGround()) return;
2087
2088
        if (strafeHypixel.get()) {
2089
            double speedValue = player.hasEffect(net.minecraft.world.effect.MobEffects.SPEED) ? 0.295 : 0.207;
2090
            if (player.tickCount % 20 == 0 || strafeMoveTicks <= 7) {
2091
                speedValue = 0.09800000190734863;
2092
            }
2093
            Vec3 velocity = MovementUtil.withStrafe(player.getDeltaMovement(), movementInputVector(player), player.getYRot(), speedValue, 1.0);
2094
            player.setDeltaMovement(velocity);
2095
            return;
2096
        }
2097
2098
        Vec3 velocity = MovementUtil.withStrafe(player.getDeltaMovement(), movementInputVector(player), player.getYRot(), strafeSpeed.get(), 1.0);
2099
        player.setDeltaMovement(velocity);
2100
    }
2101
2102
    private void handleMotionTower(LocalPlayer player) {
2103
        if (player.onGround()) {
2104
            player.jumpFromGround();
2105
            towerJumpBaseY = player.getY();
2106
            return;
2107
        }
2108
2109
        if (Double.isNaN(towerJumpBaseY)) return;
2110
        if (player.getY() <= towerJumpBaseY + towerTriggerHeight.get()) return;
2111
2112
        player.absSnapTo(player.getX(), Math.floor(player.getY()), player.getZ());
2113
        Vec3 velocity = player.getDeltaMovement();
2114
        player.setDeltaMovement(
2115
                velocity.x * towerSlow.get(),
2116
                towerMotion.get(),
2117
                velocity.z * towerSlow.get()
2118
        );
2119
        towerJumpBaseY = player.getY();
2120
    }
2121
2122
    private void handleVulcanTower(LocalPlayer player) {
2123
        if (player.tickCount % 2 == 0) {
2124
            player.setDeltaMovement(player.getDeltaMovement().x, 0.7, player.getDeltaMovement().z);
2125
        } else {
2126
            player.setDeltaMovement(player.getDeltaMovement().x, isMoving(player) ? 0.42 : 0.6, player.getDeltaMovement().z);
2127
        }
2128
    }
2129
2130
    private void handleHypixelTower(LocalPlayer player) {
2131
        Vec3 velocity = player.getDeltaMovement();
2132
2133
        if (Math.abs(player.getX() % 1.0) > 1.0E-4 && !isMoving(player)) {
2134
            double adjust = Math.round(player.getX()) - player.getX();
2135
            player.setDeltaMovement(Math.copySign(Math.min(Math.abs(adjust), 0.281), adjust), velocity.y, velocity.z);
2136
            velocity = player.getDeltaMovement();
2137
        }
2138
2139
        if (towerAirTicks > 14) {
2140
            player.setDeltaMovement(velocity.x * 0.6, velocity.y - 0.09, velocity.z * 0.6);
2141
            return;
2142
        }
2143
2144
        int mod = Math.floorMod(towerAirTicks, 3);
2145
        if (mod == 0) {
2146
            Vec3 strafe = MovementUtil.withStrafe(player.getDeltaMovement(), new Vec3(0.0, 0.0, 1.0), player.getYRot(), 0.247, 1.0);
2147
            player.setDeltaMovement(strafe.x, 0.42, strafe.z);
2148
        } else if (mod == 2) {
2149
            player.setDeltaMovement(velocity.x, 1.0 - (player.getY() % 1.0), velocity.z);
2150
        }
2151
    }
2152
2153
    private boolean isTowering(LocalPlayer player) {
2154
        Minecraft mc = Minecraft.getInstance();
2155
        return towerMode.get() != TowerMode.NONE
2156
                && player != null
2157
                && mc.options.keyJump.isDown()
2158
                && !shouldGoDown(player)
2159
                && blockCount(player) > 0
2160
                && isBlockBelow(player);
2161
    }
2162
2163
2164
    private float getRawMovementDirectionYaw(LocalPlayer player, float fallbackYaw) {
2165
        if (player == null) return fallbackYaw;
2166
        boolean forwards = rawForward && !rawBackward;
2167
        boolean backwards = rawBackward && !rawForward;
2168
        boolean left = rawLeft && !rawRight;
2169
        boolean right = rawRight && !rawLeft;
2170
2171
        if (!forwards && !backwards && !left && !right) return fallbackYaw;
2172
2173
        float actualYaw = fallbackYaw;
2174
        float forward = 1.0f;
2175
2176
        if (backwards) {
2177
            actualYaw += 180.0f;
2178
            forward = -0.5f;
2179
        } else if (forwards) {
2180
            forward = 0.5f;
2181
        }
2182
2183
        if (left) {
2184
            actualYaw -= 90.0f * forward;
2185
        }
2186
        if (right) {
2187
            actualYaw += 90.0f * forward;
2188
        }
2189
2190
        return actualYaw;
2191
    }
2192
2193
    private boolean hasRawInput() {
2194
        return rawForward || rawBackward || rawLeft || rawRight;
2195
    }
2196
2197
    private boolean isRawDiagonal() {
2198
        return rawForward != rawBackward && rawLeft != rawRight;
2199
    }
2200
2201
    private Vec3 movementInputVector(LocalPlayer player) {
2202
        if (player == null || player.input == null) return Vec3.ZERO;
2203
        return new Vec3(player.input.getMoveVector().x, 0.0, player.input.getMoveVector().y);
2204
    }
2205
2206
    private double horizontalSpeed(Vec3 velocity) {
2207
        return velocity == null ? 0.0 : Math.hypot(velocity.x, velocity.z);
2208
    }
2209
2210
    private double randomRange(double min, double max) {
2211
        double low = Math.min(min, max);
2212
        double high = Math.max(min, max);
2213
        return low + Math.random() * (high - low);
2214
    }
2215
2216
2217
    private Comparator<BlockPos> getNormalTargetComparator(LocalPlayer player, Vec3 placementEyePos) {
2218
        if (currentOptimalLine != null) {
2219
            return Comparator.comparingDouble((BlockPos pos) -> currentOptimalLine.squaredDistanceTo(Vec3.atCenterOf(pos))).reversed();
2220
        }
2221
        Vec3 referenceEyePos = placementEyePos != null
2222
                ? placementEyePos
2223
                : (player != null ? player.getEyePosition() : Vec3.ZERO);
2224
        return Comparator.comparingDouble((BlockPos pos) -> Vec3.atCenterOf(pos).distanceToSqr(referenceEyePos)).reversed();
2225
    }
2226
2227
    private ScaffoldFacePositionFactory createPlacementFacePositionFactory(
2228
            LocalPlayer player,
2229
            ScaffoldFacePositionFactory.Mode mode,
2230
            Vec3 placementEyePos
2231
    ) {
2232
        return new ScaffoldFacePositionFactory(
2233
                player,
2234
                placementEyePos,
2235
                mode,
2236
                currentOptimalLine,
2237
                randomRange(-1.0, 1.0)
2238
        );
2239
    }
2240
2241
    private Vec3 getPlacementEyePos(LocalPlayer player) {
2242
        if (player == null) {
2243
            return Vec3.ZERO;
2244
        }
2245
2246
        Vec3 placementPos = getPlacementBasePosition(player);
2247
        return placementPos.add(0.0, player.getEyeHeight(player.getPose()), 0.0);
2248
    }
2249
2250
    private boolean canConstructCeiling(LocalPlayer player) {
2251
        return ceiling.get()
2252
                && technique.get() == Technique.NORMAL
2253
                && player != null
2254
                && !player.level().getBlockState(player.blockPosition().below()).isAir();
2255
    }
2256
2257
    private boolean shouldTellyJumpNow(LocalPlayer player) {
2258
        if (ticksUntilTellyJump < tellyJumpTicks) return false;
2259
        if (isTowering(player) && !tellyAimOnTower.get()) return false;
2260
        return RotationManager.INSTANCE.getCurrentRotation() == null || tellyStraightTicks.get() == 0;
2261
    }
2262
2263
    private int randomTellyJumpTicks() {
2264
        int min = Math.min(tellyJumpTicksMin.get(), tellyJumpTicksMax.get());
2265
        int max = Math.max(tellyJumpTicksMin.get(), tellyJumpTicksMax.get());
2266
        return min + (int) Math.floor(Math.random() * (max - min + 1));
2267
    }
2268
2269
2270
    private Vec3 getPlacementBasePosition(LocalPlayer player) {
2271
        if (player == null) return Vec3.ZERO;
2272
        if (prediction.get()) {
2273
            Vec3 predicted = movementPrediction.getPredictedPlacementPos(player, currentOptimalLine);
2274
            if (predicted != null) {
2275
                return predicted;
2276
            }
2277
        }
2278
        if (technique.get() == Technique.NORMAL && isRawDiagonal() && currentOptimalLine != null) {
2279
            return getTickDeltaDiagonalPlacementPos(player);
2280
        }
2281
        return player.position();
2282
    }
2283
2284
    private Vec3 getTickDeltaDiagonalPlacementPos(LocalPlayer player) {
2285
        Vec3 velocity = new Vec3(player.getDeltaMovement().x, 0.0, player.getDeltaMovement().z);
2286
        double tickDelta = TickDelta.get();
2287
        double lead = Math.max(0.35, Math.min(1.35, tickDelta + 0.45));
2288
        Vec3 projected = player.position().add(velocity.scale(lead));
2289
2290
        if (velocity.horizontalDistanceSqr() < 0.02 * 0.02) {
2291
            Vec3 direction = currentOptimalLine.direction().normalize();
2292
            projected = projected.add(direction.scale(0.18 + tickDelta * 0.12));
2293
        }
2294
2295
        return currentOptimalLine.getNearestPointTo(projected);
2296
    }
2297
2298
    private boolean isBlockBelow(LocalPlayer player) {
2299
        return player != null && player.level().getBlockCollisions(
2300
                player,
2301
                player.getBoundingBox().inflate(0.5, 0.0, 0.5).move(0.0, -1.05, 0.0)
2302
        ).iterator().hasNext();
2303
    }
2304
2305
    private boolean canStandOn(BlockPos pos) {
2306
        Minecraft mc = Minecraft.getInstance();
2307
        return mc.level != null
2308
                && mc.level.getBlockState(pos).isFaceSturdy(mc.level, pos, net.minecraft.core.Direction.UP);
2309
    }
2310
2311
    private int blockCount(LocalPlayer player) {
2312
        if (player == null) return 0;
2313
        int count = ScaffoldBlockItemSelection.isValidBlock(player.getOffhandItem()) ? player.getOffhandItem().getCount() : 0;
2314
        for (int i = 0; i < 9; i++) {
2315
            ItemStack stack = player.getInventory().getItem(i);
2316
            if (ScaffoldBlockItemSelection.isValidBlock(stack)) {
2317
                count += stack.getCount();
2318
            }
2319
        }
2320
        return count;
2321
    }
2322
2323
    private LocalPlayer player() {
2324
        Minecraft mc = Minecraft.getInstance();
2325
        return mc != null ? mc.player : null;
2326
    }
2327
2328
    private List<RotationProcessor> buildRotationProcessors() {
2329
        List<RotationProcessor> processors = new ArrayList<>();
2330
        AngleSmooth smooth = selectAngleSmooth();
2331
        if (smooth != null) {
2332
            processors.add(smooth);
2333
        }
2334
        return processors;
2335
    }
2336
2337
    private AngleSmooth selectAngleSmooth() {
2338
        return switch (angleSmoothMode.get()) {
2339
            case LINEAR -> linearSmooth;
2340
            case SIGMOID -> sigmoidSmooth;
2341
            case INTERPOLATION -> interpolationSmooth;
2342
            case ACCELERATION -> accelerationSmooth;
2343
            case NONE -> null;
2344
        };
2345
    }
2346
2347
    public enum RotationTiming {
2348
        NORMAL,
2349
        ON_TICK
2350
    }
2351
2352
    public enum AngleSmoothMode {
2353
        LINEAR,
2354
        SIGMOID,
2355
        INTERPOLATION,
2356
        ACCELERATION,
2357
        NONE
2358
    }
2359
2360
    public enum SameYMode {
2361
        OFF,
2362
        ON,
2363
        FALLING
2364
    }
2365
2366
    public enum SprintMode {
2367
        DO_NOT_CHANGE,
2368
        FORCE_SPRINT,
2369
        FORCE_NO_SPRINT,
2370
        NO_SPRINT_ON_PLACE,
2371
        NO_SPRINT_ON_GROUND
2372
    }
2373
2374
    public enum TowerMode {
2375
        NONE,
2376
        MOTION,
2377
        VULCAN,
2378
        HYPIXEL
2379
    }
2380
2381
    public enum Technique {
2382
        NORMAL,
2383
        EXPAND
2384
    }
2385
2386
    public enum TellyResetMode {
2387
        REVERSE,
2388
        RESET
2389
    }
2390
2391
    public enum IndicatorSide {
2392
        LEFT,
2393
        RIGHT,
2394
        TOP,
2395
        BOTTOM
2396
    }
2397
2398
    public enum IndicatorStyle {
2399
        SLOT,
2400
        PILL
2401
    }
2402
2403
    public enum IndicatorCountMode {
2404
        CURRENT_STACK,
2405
        SAME_ITEM,
2406
        ALL_PLACEABLE
2407
    }
2408
2409
    private record RenderPreview(BlockPos pos, float progress) {
2410
    }
2411
2412
    private record PlacementIndicatorData(ItemStack stack, int count, String countText) {
2413
    }
2414
}
2415
NicotinePlayersrc/client/java/nicotine/mod/mods/player/Scaffold.javaJava · 120 lines · 4.4 KB

Places blocks below you as you move

SettingsSelectBlock
Scaffold.javaJava · Minecraft 26.3 · 120 lines · 4.4 KB · complete file, verbatimOriginal ↗
1
package nicotine.mod.mods.player;
2
3
import com.mojang.blaze3d.platform.InputConstants;
4
import net.minecraft.core.BlockPos;
5
import net.minecraft.core.Direction;
6
import net.minecraft.world.item.BlockItem;
7
import net.minecraft.world.level.block.Blocks;
8
import net.minecraft.world.phys.BlockHitResult;
9
import net.minecraft.world.phys.Vec3;
10
import nicotine.events.ClientLevelTickEvent;
11
import nicotine.mod.Mod;
12
import nicotine.mod.ModCategory;
13
import nicotine.mod.option.ToggleOption;
14
import nicotine.util.EventBus;
15
import nicotine.util.Keybind;
16
import nicotine.util.Player;
17
import nicotine.util.math.BoxUtil;
18
19
import static nicotine.util.Common.mc;
20
21
public class Scaffold extends Mod {
22
23
    private final ToggleOption selectBlock = new ToggleOption("SelectBlock");
24
25
    public Scaffold() {
26
        super(ModCategory.Player, "Scaffold", "Places blocks below you as you move");
27
28
        this.keybind.keyCode = InputConstants.KEY_N;
29
        this.addOptions(selectBlock);
30
    }
31
32
    @Override
33
    protected void init() {
34
        EventBus.register(ClientLevelTickEvent.class, event -> {
35
            if (Keybind.keyReleased(this, keybind.keyCode))
36
                this.toggle();
37
38
            if (!this.enabled || (!(mc.player.getMainHandItem().getItem() instanceof BlockItem) && !selectBlock.enabled) || Player.isBusy())
39
                return true;
40
41
            BlockPos initPos = mc.player.blockPosition();
42
43
            BlockPos placementPos = BlockPos.ZERO;
44
45
            Vec3 lookAtPos;
46
            double lookatX = 0;
47
            double lookatY = 0;
48
            double lookatZ = 0;
49
50
            Direction scaffoldDirection;
51
52
            switch (mc.player.getMotionDirection()) {
53
                case SOUTH:
54
                    placementPos = initPos.offset(0, -1, -1);
55
                    lookatX = initPos.getX();
56
                    lookatY = initPos.getY() - 1;
57
                    lookatZ = BoxUtil.getBlockBoundingBox(placementPos).max(Direction.Axis.Z);
58
                    break;
59
                case NORTH:
60
                    placementPos = initPos.offset(0, -1, 1);
61
                    lookatX = initPos.getX();
62
                    lookatY = initPos.getY() - 1;
63
                    lookatZ = BoxUtil.getBlockBoundingBox(placementPos).min(Direction.Axis.Z);
64
                    break;
65
                case EAST:
66
                    placementPos = initPos.offset(-1, -1, 0);
67
                    lookatX = BoxUtil.getBlockBoundingBox(placementPos).max(Direction.Axis.X);
68
                    lookatY = initPos.getY() - 1;
69
                    lookatZ = initPos.getZ();
70
                    break;
71
                case WEST:
72
                    placementPos = initPos.offset(1, -1, 0);
73
                    lookatX = BoxUtil.getBlockBoundingBox(placementPos).min(Direction.Axis.X);
74
                    lookatY = initPos.getY() - 1;
75
                    lookatZ = initPos.getZ();
76
                    break;
77
            }
78
79
            if (!mc.player.onGround()) {
80
                scaffoldDirection = Direction.UP;
81
                placementPos = initPos.offset(0, -2, 0);
82
83
                lookAtPos = Vec3.atCenterOf(placementPos);
84
85
                if (mc.level.getBlockState(placementPos).getBlock().defaultBlockState().canBeReplaced())
86
                    return true;
87
88
            } else {
89
                scaffoldDirection = mc.player.getMotionDirection();
90
91
                lookAtPos = new Vec3(lookatX, lookatY, lookatZ);
92
            }
93
94
            int targetSlot = -1;
95
96
            if (mc.level.getBlockState(initPos.offset(0, -1, 0)).getBlock() == Blocks.AIR) {
97
                if (selectBlock.enabled && !(mc.player.getMainHandItem().getItem() instanceof BlockItem)) {
98
                    for (int i = 0; i < 9; i++) {
99
                        if (mc.player.getInventory().getItem(i).getItem() instanceof BlockItem) {
100
                            targetSlot = i;
101
                            break;
102
                        }
103
                    }
104
105
                    if (targetSlot == -1) {
106
                        return true;
107
                    }
108
                } else {
109
                    targetSlot = mc.player.getInventory().getSelectedSlot();
110
                }
111
112
                BlockHitResult blockHitResult = new BlockHitResult(new Vec3(placementPos.getX(), placementPos.getY(), placementPos.getZ()), scaffoldDirection, placementPos, false);
113
                Player.lookAndPlace(lookAtPos, blockHitResult, targetSlot, true, false);
114
            }
115
116
            return true;
117
        });
118
    }
119
}
120
LiquidBounce (Kotlin)WORLDsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/world/scaffold/ModuleScaffold.ktKotlin · 752 lines · 28.4 KB

Automatically places blocks beneath your feet allowing you to walk across gaps.

SettingsDelayMinDistTimerSameYConsiderInventoryRotationTimingSwingFailedAttemptsOnlyAutoSpeedLedge
ModuleScaffold.ktKotlin · Minecraft 26.2 · 752 lines · 28.4 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.scaffold
20
21
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
22
import net.ccbluex.liquidbounce.config.types.list.Tagged
23
import net.ccbluex.liquidbounce.event.EventManager
24
import net.ccbluex.liquidbounce.event.events.BlockCountChangeEvent
25
import net.ccbluex.liquidbounce.event.events.GameTickEvent
26
import net.ccbluex.liquidbounce.event.events.MovementInputEvent
27
import net.ccbluex.liquidbounce.event.events.RotationUpdateEvent
28
import net.ccbluex.liquidbounce.event.events.WorldChangeEvent
29
import net.ccbluex.liquidbounce.event.handler
30
import net.ccbluex.liquidbounce.event.tickHandler
31
import net.ccbluex.liquidbounce.event.waitTicks
32
import net.ccbluex.liquidbounce.features.module.ClientModule
33
import net.ccbluex.liquidbounce.features.module.ModuleCategories
34
import net.ccbluex.liquidbounce.features.module.modules.movement.ModuleSafeWalk
35
import net.ccbluex.liquidbounce.features.module.modules.player.nofall.modes.NoFallBlink
36
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug
37
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug.debugGeometry
38
import net.ccbluex.liquidbounce.features.module.modules.render.ModuleDebug.debugParameter
39
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ModuleScaffold.ScaffoldRotationValueGroup.RotationTimingMode.NORMAL
40
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ModuleScaffold.ScaffoldRotationValueGroup.RotationTimingMode.ON_TICK
41
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ModuleScaffold.ScaffoldRotationValueGroup.RotationTimingMode.ON_TICK_SNAP
42
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ModuleScaffold.ScaffoldRotationValueGroup.considerInventory
43
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ModuleScaffold.ScaffoldRotationValueGroup.rotationTiming
44
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ScaffoldBlockItemSelection.isValidBlock
45
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldAccelerationFeature
46
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldAutoBlockFeature
47
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldBlinkFeature
48
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldCeilingFeature
49
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldJumpStrafe
50
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldLedgeExtension
51
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldMovementPrediction
52
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldSpeedLimiterFeature
53
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldSprintControlFeature
54
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ScaffoldStrafeFeature
55
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.features.ledge
56
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.techniques.ScaffoldBreezilyTechnique
57
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.techniques.ScaffoldExpandTechnique
58
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.techniques.ScaffoldGodBridgeTechnique
59
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.techniques.ScaffoldNormalTechnique
60
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.techniques.normal.ScaffoldDownFeature
61
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.techniques.normal.ScaffoldEagleFeature
62
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.tower.ScaffoldTowerHypixel
63
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.tower.ScaffoldTowerKarhu
64
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.tower.ScaffoldTowerMotion
65
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.tower.ScaffoldTowerNone
66
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.tower.ScaffoldTowerPulldown
67
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.tower.ScaffoldTowerVulcan
68
import net.ccbluex.liquidbounce.render.engine.type.Color4b
69
import net.ccbluex.liquidbounce.utils.aiming.RotationManager
70
import net.ccbluex.liquidbounce.utils.aiming.RotationsValueGroup
71
import net.ccbluex.liquidbounce.utils.aiming.utils.withFixedYaw
72
import net.ccbluex.liquidbounce.utils.block.SwingMode
73
import net.ccbluex.liquidbounce.utils.block.doPlacement
74
import net.ccbluex.liquidbounce.utils.block.targetBlockPos
75
import net.ccbluex.liquidbounce.utils.block.targetfinding.BlockPlacementTarget
76
import net.ccbluex.liquidbounce.utils.clicking.Clicker
77
import net.ccbluex.liquidbounce.utils.client.SilentHotbar
78
import net.ccbluex.liquidbounce.utils.client.Timer
79
import net.ccbluex.liquidbounce.utils.entity.moving
80
import net.ccbluex.liquidbounce.utils.entity.rotation
81
import net.ccbluex.liquidbounce.utils.item.PreferAverageHardBlocks
82
import net.ccbluex.liquidbounce.utils.item.PreferFavourableBlocks
83
import net.ccbluex.liquidbounce.utils.item.PreferFullCubeBlocks
84
import net.ccbluex.liquidbounce.utils.item.PreferSolidBlocks
85
import net.ccbluex.liquidbounce.utils.item.PreferStackSize
86
import net.ccbluex.liquidbounce.utils.item.PreferWalkableBlocks
87
import net.ccbluex.liquidbounce.utils.item.getBlock
88
import net.ccbluex.liquidbounce.utils.kotlin.EventPriorityConvention
89
import net.ccbluex.liquidbounce.utils.kotlin.Priority
90
import net.ccbluex.liquidbounce.utils.math.copy
91
import net.ccbluex.liquidbounce.utils.math.geometry.Line
92
import net.ccbluex.liquidbounce.utils.math.minus
93
import net.ccbluex.liquidbounce.utils.math.allEmpty
94
import net.ccbluex.liquidbounce.utils.math.topCenter
95
import net.ccbluex.liquidbounce.utils.movement.DirectionalInput
96
import net.ccbluex.liquidbounce.utils.render.placement.PlacementRenderer
97
import net.ccbluex.liquidbounce.utils.sorting.ComparatorChain
98
import net.minecraft.core.BlockPos
99
import net.minecraft.core.Direction
100
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket.PosRot
101
import net.minecraft.world.InteractionHand
102
import net.minecraft.world.entity.Pose
103
import net.minecraft.world.item.BlockItem
104
import net.minecraft.world.item.ItemStack
105
import net.minecraft.world.item.Items
106
import net.minecraft.world.item.context.BlockPlaceContext
107
import net.minecraft.world.item.context.UseOnContext
108
import net.minecraft.world.level.block.Block
109
import net.minecraft.world.phys.BlockHitResult
110
import net.minecraft.world.phys.HitResult
111
import kotlin.math.abs
112
113
/**
114
 * Scaffold module
115
 *
116
 * Places blocks under you.
117
 */
118
@Suppress("TooManyFunctions")
119
object ModuleScaffold : ClientModule("Scaffold", ModuleCategories.WORLD) {
120
121
    private val delay by intRange("Delay", 0..0, 0..40, "ticks")
122
    private val minDist by float("MinDist", 0.0f, 0.0f..0.25f)
123
    private val timer by float("Timer", 1f, 0.01f..10f)
124
125
    init {
126
        tree(ScaffoldBlockItemSelection)
127
        tree(ScaffoldAutoBlockFeature)
128
        tree(ScaffoldMovementPrediction)
129
    }
130
131
    internal val technique = choices(
132
        "Technique",
133
        ScaffoldNormalTechnique,
134
        arrayOf(
135
            ScaffoldNormalTechnique,
136
            ScaffoldExpandTechnique,
137
            ScaffoldGodBridgeTechnique,
138
            ScaffoldBreezilyTechnique
139
        )
140
    ).apply(::tagBy)
141
142
    private val sameYMode by enumChoice("SameY", SameYMode.OFF)
143
144
    @Suppress("unused")
145
    private enum class SameYMode(
146
        override val tag: String,
147
        val getTargetedBlockPos: (BlockPos) -> BlockPos?
148
    ) : Tagged {
149
150
        OFF("Off", { null }),
151
152
        /**
153
         * Places blocks at the same Y level as the player
154
         */
155
        ON("On", { blockPos -> blockPos.copy(y = placementY) }),
156
157
        /**
158
         * Places blocks at the same Y level only while the physical jump key is not held
159
         */
160
        JUMP_KEY("JumpKey", { blockPos ->
161
            (if (mc.options.keyJump.isDown) OFF else ON).getTargetedBlockPos(blockPos)
162
        }),
163
164
        /**
165
         * Places blocks at the same Y level as the player, but only if the player is not falling
166
         */
167
        FALLING("Falling", { blockPos ->
168
            (if (player.deltaMovement.y < 0.2) ON else OFF).getTargetedBlockPos(blockPos)
169
        }),
170
171
        /**
172
         * Similar to FALLING, but only when a certain velocity is triggered and after
173
         * 2 jumps
174
         */
175
        HYPIXEL("Hypixel", { blockPos ->
176
            if (player.deltaMovement.y == -0.15233518685055708 && jumps >= 2) {
177
                jumps = 0
178
179
                blockPos.copy(y = startY)
180
            } else {
181
                blockPos.copy(y = startY - 1)
182
            }
183
        })
184
185
    }
186
187
    /**
188
     * Scaffold tower mode
189
     */
190
    val towerMode = choices("Tower", 0) {
191
        arrayOf(
192
            ScaffoldTowerNone,
193
            ScaffoldTowerMotion,
194
            ScaffoldTowerPulldown,
195
            ScaffoldTowerKarhu,
196
            ScaffoldTowerVulcan,
197
            ScaffoldTowerHypixel
198
        )
199
    }
200
201
    internal val isTowering: Boolean
202
        get() = if (towerMode.activeMode != ScaffoldTowerNone && mc.options.keyJump.isDown) {
203
            this.wasTowering = true
204
            true
205
        } else {
206
            false
207
        }
208
    private var wasTowering: Boolean = false
209
210
    private val activeTechnique get() = if (isTowering) {
211
        ScaffoldNormalTechnique
212
    } else {
213
        technique.activeMode
214
    }
215
216
    // SafeWalk feature - uses the SafeWalk module as a base
217
    @Suppress("unused")
218
    private val safeWalkMode = choices("SafeWalk", 1, ModuleSafeWalk::safeWalkChoices)
219
220
    internal object ScaffoldRotationValueGroup : RotationsValueGroup(this) {
221
222
        val considerInventory by boolean("ConsiderInventory", false)
223
        val rotationTiming by enumChoice("RotationTiming", NORMAL)
224
225
        enum class RotationTimingMode(override val tag: String) : Tagged {
226
227
            /**
228
             * Rotates the player before the block is placed
229
             */
230
            NORMAL("Normal"),
231
232
            /**
233
             * Rotates the player on the tick the block is placed
234
             */
235
            ON_TICK("OnTick"),
236
237
            /**
238
             * Similar to ON_TICK, but the player will keep the rotation after placing
239
             */
240
            ON_TICK_SNAP("OnTickSnap")
241
242
        }
243
244
    }
245
246
    private var currentTarget: BlockPlacementTarget? = null
247
248
    private val swingMode by enumChoice("Swing", SwingMode.DO_NOT_HIDE)
249
250
    private object SimulatePlacementAttempts : ToggleableValueGroup(this, "SimulatePlacementAttempts", false) {
251
        val clicker = tree(Clicker(ModuleScaffold, mc.options.keyUse, null, maxCps = 100))
252
        val failedAttemptsOnly by boolean("FailedAttemptsOnly", true)
253
    }
254
255
    init {
256
        tree(ScaffoldRotationValueGroup)
257
        tree(ScaffoldSprintControlFeature)
258
        tree(SimulatePlacementAttempts)
259
        tree(ScaffoldAccelerationFeature)
260
        tree(ScaffoldStrafeFeature)
261
        tree(ScaffoldJumpStrafe)
262
        tree(ScaffoldSpeedLimiterFeature)
263
        tree(ScaffoldBlinkFeature)
264
    }
265
266
    /**
267
     * Temporarily turns on [net.ccbluex.liquidbounce.features.module.modules.movement.speed.ModuleSpeed]
268
     * while Scaffold is enabled.
269
     */
270
    val autoSpeed by boolean("AutoSpeed", false)
271
272
    private val ledge by boolean("Ledge", true)
273
274
    private val renderer = tree(PlacementRenderer("Render", true, this, keep = false))
275
276
    private var placementY = 0
277
    private var forceSneak = 0
278
    private var startY = 0
279
    private var jumps = 0
280
281
    private var nextBlock: Block? = null
282
283
    val blockCount: Int
284
        get() {
285
            fun ItemStack.blockCount() = if (isValidBlock(this)) this.count else 0
286
287
            return player.offhandItem.blockCount() + if (ScaffoldAutoBlockFeature.enabled) {
288
                findPlaceableSlots().sumOf { it.value.blockCount() }
289
            } else {
290
                player.inventory.getItem(player.inventory.selectedSlot).blockCount()
291
            }
292
        }
293
294
    val isBlockBelow: Boolean
295
        get() {
296
            // Check if there is a collision box below the player
297
            // In this case we expand the bounding box by 0.5 in all directions and check if there is a collision
298
            // This might cause for "Spider-like" behavior, but it's the most reliable way to check
299
            // and usually the scaffold should start placing blocks
300
            return !world.getBlockCollisions(
301
                player,
302
                player.boundingBox.inflate(0.5, 0.0, 0.5).move(0.0, -1.05, 0.0)
303
            ).allEmpty()
304
        }
305
306
    /**
307
     * This comparator will estimate the value of a block. If this comparator says that Block A > Block B, Scaffold will
308
     * prefer Block A over Block B.
309
     * The chain will prefer the block that is solid. If both are solid, it goes to the next criteria
310
     * (in this case full cube) and so on
311
     */
312
    private val BLOCK_COMPARATOR_FOR_HOTBAR =
313
        ComparatorChain(
314
            PreferFavourableBlocks,
315
            PreferSolidBlocks,
316
            PreferFullCubeBlocks,
317
            PreferWalkableBlocks,
318
            PreferAverageHardBlocks(neutralRange = true),
319
            PreferStackSize.PREFER_MORE,
320
            PreferAverageHardBlocks(neutralRange = false),
321
        )
322
    @JvmField
323
    val BLOCK_COMPARATOR_FOR_INVENTORY =
324
        ComparatorChain(
325
            PreferFavourableBlocks,
326
            PreferSolidBlocks,
327
            PreferFullCubeBlocks,
328
            PreferWalkableBlocks,
329
            PreferAverageHardBlocks(neutralRange = true),
330
            PreferStackSize.PREFER_FEWER,
331
            PreferAverageHardBlocks(neutralRange = false),
332
        )
333
334
    override fun onEnabled() {
335
        // Placement Y is the Y coordinate of the block below the player
336
        placementY = player.blockPosition().y - 1
337
        startY = player.blockPosition().y
338
        jumps = 2
339
340
        ScaffoldMovementPlanner.reset()
341
342
        super.onEnabled()
343
    }
344
345
    override fun onDisabled() {
346
        reset()
347
    }
348
349
    private fun reset() {
350
        NoFallBlink.waitUntilGround = false
351
        ScaffoldMovementPlanner.reset()
352
        ScaffoldMovementPrediction.reset()
353
        SilentHotbar.resetSlot(this)
354
        nextBlock = null
355
        updateRenderCount(null)
356
        forceSneak = 0
357
        currentTarget = null
358
        renderer.clearSilently()
359
    }
360
361
    @Suppress("unused")
362
    private val worldChangeHandler = handler<WorldChangeEvent> {
363
        reset()
364
    }
365
366
    private fun updateRenderCount(count: Int?) {
367
        EventManager.callEvent(BlockCountChangeEvent(nextBlock, count))
368
    }
369
370
    @Suppress("unused")
371
    private val rotationUpdateHandler = handler<RotationUpdateEvent> {
372
        NoFallBlink.waitUntilGround = true
373
374
        val blockInHotbar = findBestValidHotbarSlotForTarget()
375
376
        val bestStack = if (blockInHotbar == null) {
377
            nextBlock = null
378
            ItemStack(Items.SANDSTONE, 64)
379
        } else {
380
            player.inventory.getItem(blockInHotbar).also {
381
                nextBlock = it.getBlock()
382
            }
383
        }
384
385
        val optimalLine = this.currentOptimalLine
386
387
        val predictedPos = ScaffoldMovementPrediction.getPredictedPlacementPos(optimalLine) ?: player.position()
388
        // Check if the player is probably going to sneak at the predicted position
389
        val predictedPose =
390
            if (ScaffoldEagleFeature.enabled && ScaffoldEagleFeature.shouldEagle(DirectionalInput(player.input))) {
391
                Pose.CROUCHING
392
            } else {
393
                Pose.STANDING
394
            }
395
396
        debugGeometry("predictedPos") {
397
            ModuleDebug.DebuggedPoint(predictedPos, Color4b.GREEN, size = 0.1)
398
        }
399
400
        val technique = activeTechnique
401
402
        val target = technique.findPlacementTarget(predictedPos, predictedPose, optimalLine, bestStack)
403
            .also { this.currentTarget = it }
404
405
        debugGeometry("lineToBlock") {
406
            // Debug stuff
407
            val b = target?.placedBlock?.topCenter ?: return@debugGeometry null
408
            val a = optimalLine?.getNearestPointTo(b)  ?: return@debugGeometry null
409
410
            // Debug the line a-b
411
            ModuleDebug.DebuggedLineSegment(
412
                from = a,
413
                to = b,
414
                Color4b.RED,
415
            )
416
        }
417
418
        // Do not aim yet in SKIP mode, since we want to aim at the block only when we are about to place it
419
        if (rotationTiming == NORMAL) {
420
            val rotation = technique.getRotations(target)
421
422
            RotationManager.setRotationTarget(
423
                rotation ?: return@handler,
424
                considerInventory = considerInventory,
425
                valueGroup = ScaffoldRotationValueGroup,
426
                provider = this@ModuleScaffold,
427
                priority = Priority.IMPORTANT_FOR_PLAYER_LIFE
428
            )
429
        }
430
    }
431
432
    var currentOptimalLine: Line? = null
433
        private set
434
    var rawInput = DirectionalInput.NONE
435
        private set
436
437
    @Suppress("unused")
438
    private val handleMovementInput = handler<MovementInputEvent>(
439
        priority = EventPriorityConvention.MODEL_STATE
440
    ) { event ->
441
        this.currentOptimalLine = null
442
        this.rawInput = event.directionalInput
443
444
        val currentInput = event.directionalInput
445
446
        if (currentInput == DirectionalInput.NONE) {
447
            return@handler
448
        }
449
450
        this.currentOptimalLine = ScaffoldMovementPlanner.getOptimalMovementLine(event.directionalInput)
451
    }
452
453
    @Suppress("unused")
454
    private val movementInputHandler = handler<MovementInputEvent>(
455
        // Runs after the model state
456
        priority = EventPriorityConvention.SAFETY_FEATURE
457
    ) { event ->
458
        if (forceSneak > 0) {
459
            event.sneak = true
460
            forceSneak--
461
        }
462
463
        // Ledge feature - AutoJump and AutoSneak
464
        if (ledge) {
465
            val technique = activeTechnique
466
467
            val ledgeAction = ledge(
468
                this.currentTarget,
469
                RotationManager.currentRotation ?: player.rotation,
470
                technique as? ScaffoldLedgeExtension
471
            )
472
473
            if (ledgeAction.jump) {
474
                event.jump = true
475
            }
476
477
            if (ledgeAction.stopInput) {
478
                event.directionalInput = DirectionalInput.NONE
479
            }
480
481
            if (ledgeAction.stepBack) {
482
                event.directionalInput = event.directionalInput.copy(
483
                    forwards = false,
484
                    backwards = true
485
                )
486
            }
487
488
            if (ledgeAction.sneakTime > forceSneak) {
489
                event.sneak = true
490
                forceSneak = ledgeAction.sneakTime
491
            }
492
        }
493
    }
494
495
    @Suppress("unused")
496
    private val timerHandler = handler<GameTickEvent> {
497
        if (timer != 1f) {
498
            Timer.requestTimerSpeed(timer, Priority.IMPORTANT_FOR_USAGE_1, this@ModuleScaffold)
499
        }
500
    }
501
502
    @Suppress("unused")
503
    private val tickHandler = tickHandler {
504
        updateRenderCount(blockCount)
505
506
        if (player.onGround()) {
507
            // Placement Y is the Y coordinate of the block below the player
508
            placementY = player.blockPosition().y - 1
509
            jumps++
510
            wasTowering = false
511
        }
512
513
        if (mc.options.keyJump.isDown) {
514
            startY = player.blockPosition().y
515
            jumps = 2
516
        }
517
518
        debugParameter("IsTowering") { isTowering }
519
        debugParameter("WasTowering") { wasTowering }
520
521
        val target = currentTarget
522
        val technique = activeTechnique
523
524
        val currentRotation = if ((rotationTiming == ON_TICK || rotationTiming == ON_TICK_SNAP) && target != null) {
525
            technique.getRotations(target) ?: (RotationManager.currentRotation ?: player.rotation)
526
        } else {
527
            RotationManager.currentRotation ?: player.rotation
528
        }.normalize()
529
        val currentCrosshairTarget = technique.getCrosshairTarget(target, currentRotation)
530
        val currentDelay = delay.random()
531
532
        var hasBlockInMainHand = isValidBlock(player.inventory.getItem(player.inventory.selectedSlot))
533
        val hasBlockInOffHand = isValidBlock(player.offhandItem)
534
535
        if (ScaffoldAutoBlockFeature.alwaysHoldBlock) {
536
            hasBlockInMainHand = handleSilentBlockSelection(hasBlockInMainHand, hasBlockInOffHand)
537
        }
538
539
        // Prioritize by all means the main hand if it has a block
540
        val suitableHand = InteractionHand.entries.firstOrNull {
541
            isValidBlock(player.getItemInHand(it))
542
        }
543
544
        fun commonPlaceSucceed(placed: BlockPos) {
545
            ScaffoldMovementPlanner.trackPlacedBlock(placed)
546
            renderer.addBlock(placed)
547
            ScaffoldEagleFeature.onBlockPlacement()
548
            ScaffoldBlinkFeature.onBlockPlacement()
549
            ScaffoldSprintControlFeature.onBlockPlacement()
550
        }
551
552
        if (simulatePlacementAttempts(currentCrosshairTarget, suitableHand) && player.moving
553
            && SimulatePlacementAttempts.clicker.isClickTick
554
        ) {
555
            SimulatePlacementAttempts.clicker.click {
556
                doPlacement(currentCrosshairTarget!!, currentRotation, suitableHand!!, {
557
                    commonPlaceSucceed(currentCrosshairTarget.targetBlockPos)
558
                    true
559
                }, swingMode = swingMode)
560
                true
561
            }
562
        }
563
564
        if (target == null || currentCrosshairTarget == null) {
565
            return@tickHandler
566
        }
567
568
        // Does the crosshair target meet the requirements?
569
        if (!target.doesCrosshairTargetMatchRequirements(currentCrosshairTarget) ||
570
            !isValidCrosshairTarget(currentCrosshairTarget)
571
        ) {
572
            return@tickHandler
573
        }
574
575
        if (!ScaffoldAutoBlockFeature.alwaysHoldBlock) {
576
            hasBlockInMainHand = handleSilentBlockSelection(hasBlockInMainHand, hasBlockInOffHand)
577
        }
578
579
        if (!hasBlockInMainHand && !hasBlockInOffHand) {
580
            return@tickHandler
581
        }
582
583
        val handToInteractWith = if (hasBlockInMainHand) InteractionHand.MAIN_HAND else InteractionHand.OFF_HAND
584
        var wasSuccessful = false
585
586
        if (rotationTiming == ON_TICK || rotationTiming == ON_TICK_SNAP) {
587
            // Check if server rotation matches the current rotation
588
            if (currentRotation != RotationManager.serverRotation) {
589
                network.send(
590
                    PosRot(
591
                        player.x, player.y, player.z,
592
                        currentRotation.yaw,
593
                        currentRotation.pitch,
594
                        player.onGround(),
595
                        player.horizontalCollision
596
                    )
597
                )
598
            }
599
600
            if (rotationTiming == ON_TICK_SNAP) {
601
                RotationManager.setRotationTarget(
602
                    currentRotation,
603
                    considerInventory = considerInventory,
604
                    valueGroup = ScaffoldRotationValueGroup,
605
                    provider = this@ModuleScaffold,
606
                    priority = Priority.IMPORTANT_FOR_PLAYER_LIFE
607
                )
608
            }
609
        }
610
611
        // Take the fall off position before placing the block
612
        val previousFallOffPos = currentOptimalLine?.let { l -> ScaffoldMovementPrediction.getFallOffPositionOnLine(l) }
613
614
        doPlacement(currentCrosshairTarget, currentRotation, handToInteractWith, {
615
            commonPlaceSucceed(target.placedBlock)
616
            currentTarget = null
617
            wasSuccessful = true
618
            true
619
        }, swingMode = swingMode)
620
621
        if (rotationTiming == ON_TICK && RotationManager.serverRotation != player.rotation) {
622
            network.send(
623
                PosRot(
624
                    player.x, player.y, player.z, player.withFixedYaw(currentRotation), player.xRot, player.onGround(),
625
                    player.horizontalCollision
626
                )
627
            )
628
        }
629
630
        if (wasSuccessful) {
631
            ScaffoldMovementPrediction.onPlace(currentOptimalLine, previousFallOffPos)
632
633
            waitTicks(currentDelay)
634
        }
635
    }
636
637
    private fun findPlaceableSlots() = buildList(9) {
638
        for (i in 0..8) {
639
            val stack = player.inventory.getItem(i)
640
641
            if (isValidBlock(stack)) {
642
                add(IndexedValue(i, stack))
643
            }
644
        }
645
    }
646
647
    private fun findBestValidHotbarSlotForTarget(): Int? {
648
        val placeableSlots = findPlaceableSlots()
649
        val doNotUseBelowCount = ScaffoldAutoBlockFeature.doNotUseBelowCount
650
651
        val (slot, _) = placeableSlots
652
            .filter { (_, stack) -> stack.count > doNotUseBelowCount }
653
            .maxWithOrNull { o1, o2 -> BLOCK_COMPARATOR_FOR_HOTBAR.compare(o1.value, o2.value) }
654
            ?: placeableSlots.maxWithOrNull { o1, o2 -> BLOCK_COMPARATOR_FOR_HOTBAR.compare(o1.value, o2.value) }
655
            ?: return null
656
657
        return slot
658
    }
659
660
    internal fun isValidCrosshairTarget(rayTraceResult: BlockHitResult): Boolean {
661
        val diff = rayTraceResult.location - player.eyePosition
662
663
        val side = rayTraceResult.direction
664
665
        // Apply minDist
666
        if (side.axis != Direction.Axis.Y) {
667
            val dist = if (side == Direction.NORTH || side == Direction.SOUTH) diff.z else diff.x
668
669
            if (abs(dist) < minDist) {
670
                return false
671
            }
672
        }
673
674
        return true
675
    }
676
677
    internal fun getTargetedPosition(blockPos: BlockPos) = when {
678
        isTowering || wasTowering -> towerMode.activeMode.getTargetedPosition(blockPos)
679
        ScaffoldDownFeature.running && ScaffoldDownFeature.shouldGoDown ->
680
            blockPos.offset(0, -2, 0)
681
        ScaffoldCeilingFeature.running && ScaffoldCeilingFeature.canConstructCeiling() ->
682
            blockPos.offset(0, 3, 0)
683
        player.input.keyPresses.jump && (!player.moving || player.horizontalCollision) ->
684
            blockPos.offset(0, -1, 0)
685
        else -> sameYMode.getTargetedBlockPos(blockPos)
686
            ?: blockPos.offset(0, -1, 0)
687
    }
688
689
    private fun simulatePlacementAttempts(
690
        hitResult: BlockHitResult?,
691
        suitableHand: InteractionHand?,
692
    ): Boolean {
693
        val stack = suitableHand?.let(player::getItemInHand) ?: return false
694
695
        if (hitResult == null || !SimulatePlacementAttempts.enabled) {
696
            return false
697
        }
698
699
        if (hitResult.type != HitResult.Type.BLOCK) {
700
            return false
701
        }
702
703
        val context = UseOnContext(player, suitableHand, hitResult)
704
705
        val canPlaceOnFace = (stack.item as BlockItem).getPlacementState(BlockPlaceContext(context)) != null
706
707
        return when {
708
            SimulatePlacementAttempts.failedAttemptsOnly -> {
709
                !canPlaceOnFace
710
            }
711
712
            sameYMode != SameYMode.OFF &&
713
                (sameYMode != SameYMode.JUMP_KEY || mc.options.keyJump.isDown) -> {
714
                context.clickedPos.y == placementY && (hitResult.direction != Direction.UP || !canPlaceOnFace)
715
            }
716
717
            else -> {
718
                val isTargetUnderPlayer = context.clickedPos.y <= player.blockY - 1
719
                val isTowering =
720
                    context.clickedPos.y == player.blockY - 1 &&
721
                        canPlaceOnFace &&
722
                        context.clickedFace == Direction.UP
723
724
                isTargetUnderPlayer && !isTowering
725
            }
726
        }
727
    }
728
729
    private fun handleSilentBlockSelection(hasBlockInMainHand: Boolean, hasBlockInOffHand: Boolean): Boolean {
730
        // Handle silent block selection
731
        if (ScaffoldAutoBlockFeature.enabled && !hasBlockInMainHand && !hasBlockInOffHand) {
732
            val bestMainHandSlot = findBestValidHotbarSlotForTarget()
733
734
            if (bestMainHandSlot != null) {
735
                SilentHotbar.selectSlotSilently(
736
                    this, bestMainHandSlot,
737
                    ScaffoldAutoBlockFeature.slotResetDelay
738
                )
739
740
                return true
741
            } else {
742
                SilentHotbar.resetSlot(this)
743
            }
744
        } else {
745
            SilentHotbar.resetSlot(this)
746
        }
747
748
        return hasBlockInMainHand
749
    }
750
751
}
752