AutoDodge module

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

2 implementationsMOVEMENTCOMBAT

Full module source: 2 implementations

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

CombatantMOVEMENTsrc/main/java/combatant/client/features/module/modules/movement/AutoDodge.javaJava · 942 lines · 34.1 KB
SettingsautododgeThreatsautododgeRangeautododgeMaxTicksautododgeMaxThreatsautododgeDangerPaddingautododgeAllowRotationChangeautododgeAllowJumpautododgeAllowTimerautododgeTimerSpeedautododgePathCheckTicksautododgeFallFailsafeautododgeEdgeSafeWalkautododgeMaxPredictedFallDamageautododgeIgnoreOpenInventoryautododgeIgnoreUsingItemautododgeIgnoreScaffold
AutoDodge.javaJava · Minecraft 26.2 · 942 lines · 34.1 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.movement;
15
16
import combatant.client.util.screen.ClientScreen;
17
import net.minecraft.client.Minecraft;
18
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
19
import net.minecraft.client.player.LocalPlayer;
20
import net.minecraft.core.Holder;
21
import net.minecraft.core.Registry;
22
import net.minecraft.core.registries.Registries;
23
import net.minecraft.resources.ResourceKey;
24
import net.minecraft.util.Mth;
25
import net.minecraft.world.damagesource.CombatRules;
26
import net.minecraft.world.damagesource.DamageSource;
27
import net.minecraft.world.effect.MobEffectInstance;
28
import net.minecraft.world.effect.MobEffects;
29
import net.minecraft.world.entity.Entity;
30
import net.minecraft.world.entity.EquipmentSlot;
31
import net.minecraft.world.entity.ai.attributes.Attributes;
32
import net.minecraft.world.entity.projectile.Projectile;
33
import net.minecraft.world.entity.projectile.ShulkerBullet;
34
import net.minecraft.world.entity.projectile.arrow.AbstractArrow;
35
import net.minecraft.world.entity.projectile.arrow.ThrownTrident;
36
import net.minecraft.world.entity.projectile.hurtingprojectile.Fireball;
37
import net.minecraft.world.entity.projectile.hurtingprojectile.windcharge.WindCharge;
38
import net.minecraft.world.entity.projectile.throwableitemprojectile.AbstractThrownPotion;
39
import net.minecraft.world.entity.projectile.throwableitemprojectile.Snowball;
40
import net.minecraft.world.item.ItemStack;
41
import net.minecraft.world.item.enchantment.Enchantment;
42
import net.minecraft.world.item.enchantment.EnchantmentHelper;
43
import net.minecraft.world.item.enchantment.Enchantments;
44
import net.minecraft.world.level.ClipContext;
45
import net.minecraft.world.phys.AABB;
46
import net.minecraft.world.phys.HitResult;
47
import net.minecraft.world.phys.Vec3;
48
import combatant.client.config.values.BooleanMapValue;
49
import combatant.client.config.values.BooleanValue;
50
import combatant.client.config.values.NumberValue;
51
import combatant.client.events.EventHandler;
52
import combatant.client.events.impl.MovementInputEvent;
53
import combatant.client.features.module.Module;
54
import combatant.client.features.module.ModuleCategory;
55
import combatant.client.features.module.ModuleInfo;
56
import combatant.client.features.module.Modules;
57
import combatant.client.features.module.modules.player.Scaffold;
58
import combatant.client.mixins.accessors.PersistentProjectileEntityAccessor;
59
import combatant.client.util.player.simulation.PlayerSimulationCache;
60
import combatant.client.util.projectile.SimulatedArrow;
61
62
import java.util.ArrayList;
63
import java.util.LinkedHashMap;
64
import java.util.List;
65
import java.util.Map;
66
67
//todo Description
68
@ModuleInfo(
69
        id = "autododge",
70
        displayName = "AutoDodge",
71
        category = ModuleCategory.MOVEMENT
72
)
73
public final class AutoDodge extends Module {
74
75
    private static final String THREAT_ARROW = "arrow";
76
    private static final String THREAT_TRIDENT = "trident";
77
    private static final String THREAT_FIREBALL = "fireball";
78
    private static final String THREAT_WIND_CHARGE = "wind_charge";
79
    private static final String THREAT_SHULKER_BULLET = "shulker_bullet";
80
    private static final String THREAT_POTION = "potion";
81
82
    private static final double SAFE_DISTANCE = 1.5 * 0.3 + 1.5 * 0.5;
83
    private static final double DEFAULT_DANGER_PADDING = 1.5;
84
    private static final double INPUT_DEAD_DOT = 0.25;
85
    private static final double PLAYER_HALF_WIDTH = 0.3;
86
    private static final double PATH_STEP_SPEED = 0.13;
87
    private static final double COLLISION_MARGIN = 0.03;
88
    private static final EquipmentSlot[] ARMOR_SLOTS = {
89
            EquipmentSlot.HEAD,
90
            EquipmentSlot.CHEST,
91
            EquipmentSlot.LEGS,
92
            EquipmentSlot.FEET
93
    };
94
95
    private final Minecraft mc = Minecraft.getInstance();
96
97
    private final BooleanMapValue threats = group("autododgeThreats", defaultThreats());
98
    private final NumberValue<Double> range = num("autododgeRange", 24.0, 4.0, 96.0);
99
    private final NumberValue<Integer> maxTicks = num("autododgeMaxTicks", 80, 10, 120);
100
    private final NumberValue<Integer> maxThreats = num("autododgeMaxThreats", 24, 1, 96);
101
    private final NumberValue<Double> dangerPadding =
102
            num("autododgeDangerPadding", DEFAULT_DANGER_PADDING, 0.45, 3.0);
103
    private final BooleanValue allowRotationChange = bool("autododgeAllowRotationChange", false);
104
    private final BooleanValue allowJump =
105
            visibleWhen(bool("autododgeAllowJump", true), allowRotationChange::get);
106
    private final BooleanValue allowTimer = bool("autododgeAllowTimer", false);
107
    private final NumberValue<Float> timerSpeed =
108
            visibleWhen(num("autododgeTimerSpeed", 2.0f, 1.0f, 10.0f), allowTimer::get);
109
    private final NumberValue<Integer> pathCheckTicks =
110
            num("autododgePathCheckTicks", 5, 1, 12);
111
    private final BooleanValue fallFailsafe = bool("autododgeFallFailsafe", true);
112
    private final BooleanValue edgeSafeWalk =
113
            visibleWhen(bool("autododgeEdgeSafeWalk", true), fallFailsafe::get);
114
    private final NumberValue<Double> maxPredictedFallDamage =
115
            visibleWhen(num("autododgeMaxPredictedFallDamage", 4.0, 0.0, 20.0), fallFailsafe::get);
116
    private final BooleanValue ignoreOpenInventory = bool("autododgeIgnoreOpenInventory", true);
117
    private final BooleanValue ignoreUsingItem = bool("autododgeIgnoreUsingItem", true);
118
    private final BooleanValue ignoreScaffold = bool("autododgeIgnoreScaffold", true);
119
120
    private boolean timerActive;
121
    private boolean dodgedThisTick;
122
    private int lastDodgeAge = -1;
123
124
    private static Map<String, Boolean> defaultThreats() {
125
        Map<String, Boolean> defaults = new LinkedHashMap<>();
126
        defaults.put(THREAT_ARROW, true);
127
        defaults.put(THREAT_TRIDENT, true);
128
        defaults.put(THREAT_FIREBALL, true);
129
        defaults.put(THREAT_WIND_CHARGE, true);
130
        defaults.put(THREAT_SHULKER_BULLET, true);
131
        defaults.put(THREAT_POTION, false);
132
        return defaults;
133
    }
134
135
    @Override
136
    public void onDisable() {
137
        clearTimer();
138
        dodgedThisTick = false;
139
    }
140
141
    @Override
142
    public void onTick() {
143
        if (timerActive && !dodgedThisTick) {
144
            clearTimer();
145
        }
146
        dodgedThisTick = false;
147
    }
148
149
    @EventHandler(priority = -100)
150
    private void onMovementInput(MovementInputEvent event) {
151
        LocalPlayer player = mc.player;
152
        if (!canOperate(player)) {
153
            return;
154
        }
155
156
        List<Entity> candidates = findThreats(player);
157
        if (candidates.isEmpty()) {
158
            return;
159
        }
160
161
        HitInfo hit = getInflictedHit(candidates);
162
        if (hit == null) {
163
            return;
164
        }
165
166
        DodgePlan plan = planEvasion(player, hit);
167
        if (plan == null) {
168
            return;
169
        }
170
171
        applyInput(event, plan.input());
172
173
        if (plan.yawChange() != null) {
174
            player.setYRot(plan.yawChange());
175
        }
176
177
        if (plan.shouldJump() && allowJump.get() && player.onGround()) {
178
            event.setJump(true);
179
        }
180
181
        boolean edgeRecovered = applyEdgeSafeWalk(player, event);
182
183
        if (!edgeRecovered && allowTimer.get() && plan.useTimer()) {
184
            Timer.setExternalTickTimer(timerSpeed.get());
185
            timerActive = true;
186
        }
187
188
        dodgedThisTick = true;
189
        lastDodgeAge = player.tickCount;
190
    }
191
192
    public boolean hasDodgedRecently(LocalPlayer player, int ticks) {
193
        if (!isEnabled() || player == null || lastDodgeAge < 0) {
194
            return false;
195
        }
196
197
        int delta = player.tickCount - lastDodgeAge;
198
        return delta >= 0 && delta <= ticks;
199
    }
200
201
    public boolean isTimerActive() {
202
        return timerActive;
203
    }
204
205
    private boolean canOperate(LocalPlayer player) {
206
        if (!isEnabled() || player == null || mc.level == null) {
207
            return false;
208
        }
209
210
        if (!ignoreOpenInventory.get()
211
                && (ClientScreen.current() instanceof AbstractContainerScreen<?>)) {
212
            return false;
213
        }
214
215
        if (!ignoreUsingItem.get() && player.isUsingItem()) {
216
            return false;
217
        }
218
219
        Scaffold scaffold = Modules.get(Scaffold.class);
220
        return ignoreScaffold.get() || scaffold == null || !scaffold.isEnabled();
221
    }
222
223
    private List<Entity> findThreats(LocalPlayer player) {
224
        List<Entity> out = new ArrayList<>();
225
        double maxRangeSq = range.get() * range.get();
226
227
        for (Entity entity : mc.level.entitiesForRendering()) {
228
            if (entity == null || entity == player || !entity.isAlive()) {
229
                continue;
230
            }
231
            if (entity.distanceToSqr(player) > maxRangeSq) {
232
                continue;
233
            }
234
            if (entity instanceof Projectile projectile && projectile.getOwner() == player) {
235
                continue;
236
            }
237
            if (!isEnabledThreat(entity)) {
238
                continue;
239
            }
240
            if (entity.getDeltaMovement().lengthSqr() < 1.0E-7) {
241
                continue;
242
            }
243
244
            out.add(entity);
245
        }
246
247
        out.sort((a, b) -> Double.compare(a.distanceToSqr(player), b.distanceToSqr(player)));
248
        int limit = Math.max(1, maxThreats.get());
249
        if (out.size() > limit) {
250
            return new ArrayList<>(out.subList(0, limit));
251
        }
252
        return out;
253
    }
254
255
    private boolean isEnabledThreat(Entity entity) {
256
        if (entity instanceof ThrownTrident trident) {
257
            return threats.get(THREAT_TRIDENT) && !trident.isNoPhysics() && !isInGround(trident);
258
        }
259
260
        if (entity instanceof AbstractArrow projectile) {
261
            return threats.get(THREAT_ARROW) && !projectile.isNoPhysics() && !isInGround(projectile);
262
        }
263
264
        if (entity instanceof Fireball) {
265
            return threats.get(THREAT_FIREBALL);
266
        }
267
268
        if (entity instanceof WindCharge) {
269
            return threats.get(THREAT_WIND_CHARGE);
270
        }
271
272
        if (entity instanceof ShulkerBullet) {
273
            return threats.get(THREAT_SHULKER_BULLET);
274
        }
275
276
        if (entity instanceof AbstractThrownPotion || entity instanceof Snowball) {
277
            return threats.get(THREAT_POTION);
278
        }
279
280
        return false;
281
    }
282
283
    private HitInfo getInflictedHit(List<Entity> threats) {
284
        PlayerSimulationCache.SimulatedPlayerCache playerSimulation =
285
                PlayerSimulationCache.getSimulationForLocalPlayer();
286
        if (playerSimulation == null) {
287
            return null;
288
        }
289
290
        List<ThreatSimulation> simulations = new ArrayList<>(threats.size());
291
        for (Entity threat : threats) {
292
            ThreatSimulation simulation = createSimulation(threat);
293
            if (simulation != null) {
294
                simulations.add(simulation);
295
            }
296
        }
297
298
        double expansion = Math.max(SAFE_DISTANCE, dangerPadding.get());
299
        int ticks = Math.max(1, maxTicks.get());
300
        for (int tick = 0; tick < ticks; tick++) {
301
            PlayerSimulationCache.SimulatedPlayerSnapshot snapshot =
302
                    playerSimulation.getSnapshotAt(tick + 1);
303
            if (snapshot == null) {
304
                break;
305
            }
306
307
            AABB playerBox = new AABB(-0.3, 0.0, -0.3, 0.3, 1.8, 0.3)
308
                    .inflate(expansion)
309
                    .move(snapshot.pos());
310
311
            for (ThreatSimulation simulation : simulations) {
312
                if (!simulation.tick()) {
313
                    continue;
314
                }
315
316
                Vec3 hitPos = playerBox.clip(simulation.previousPos(), simulation.pos()).orElse(null);
317
                if (hitPos != null) {
318
                    return new HitInfo(
319
                            tick,
320
                            simulation.entity(),
321
                            hitPos,
322
                            simulation.previousPos(),
323
                            simulation.velocity()
324
                    );
325
                }
326
            }
327
        }
328
329
        return null;
330
    }
331
332
    private ThreatSimulation createSimulation(Entity entity) {
333
        if (entity instanceof AbstractArrow
334
                || entity instanceof ThrownTrident
335
                || entity instanceof AbstractThrownPotion
336
                || entity instanceof Snowball) {
337
            return new ArrowLikeThreatSimulation(entity);
338
        }
339
340
        return new LinearThreatSimulation(entity);
341
    }
342
343
    private DodgePlan planEvasion(LocalPlayer player, HitInfo hit) {
344
        Vec3 threatVelocity = horizontal(hit.velocity());
345
        if (threatVelocity.lengthSqr() < 1.0E-7) {
346
            threatVelocity = horizontal(hit.hitPos().subtract(hit.previousThreatPos()));
347
        }
348
        if (threatVelocity.lengthSqr() < 1.0E-7) {
349
            return null;
350
        }
351
352
        Line threatLine = new Line(horizontal(hit.previousThreatPos()), threatVelocity.normalize());
353
        Vec3 playerPos2d = horizontal(player.position());
354
        Vec3 nearestPoint = threatLine.nearestPoint(playerPos2d);
355
        double distanceToThreatLine = nearestPoint.distanceTo(playerPos2d);
356
        double safeDistanceWithPadding = Math.max(SAFE_DISTANCE, dangerPadding.get());
357
358
        if (distanceToThreatLine > safeDistanceWithPadding) {
359
            return null;
360
        }
361
362
        CandidatePlan candidate = findBestDodgeCandidate(player, hit, threatLine, safeDistanceWithPadding);
363
        if (candidate == null) {
364
            return null;
365
        }
366
367
        Vec3 relativeDodge = candidate.relativeDodge();
368
        DodgePlan basePlan = new DodgePlan(candidate.input(), false, null, false);
369
        if (distanceToThreatLine > SAFE_DISTANCE) {
370
            return basePlan;
371
        }
372
373
        DodgePlan escalated = escalateIfNeeded(player, hit, relativeDodge, basePlan);
374
        return escalated != null ? escalated : basePlan;
375
    }
376
377
    private DodgePlan escalateIfNeeded(LocalPlayer player,
378
                                       HitInfo hit,
379
                                       Vec3 relativeDodge,
380
                                       DodgePlan basePlan) {
381
        Vec3 actualDirection = inputDirection(player.getYRot(), basePlan.input());
382
        double effectiveness = similarity(actualDirection, relativeDodge);
383
        if (effectiveness <= 0.05) {
384
            effectiveness = 0.05;
385
        }
386
387
        double safeDistanceWithPadding = Math.max(SAFE_DISTANCE, dangerPadding.get());
388
        double distanceToTravel = Math.max(0.0, relativeDodge.length() - (safeDistanceWithPadding - SAFE_DISTANCE));
389
        double travelTime = distanceToTravel / (effectiveness * 0.11);
390
        int ticksToImpact = hit.tickDelta() + 1;
391
392
        if (ticksToImpact > travelTime) {
393
            return null;
394
        }
395
396
        boolean useTimer = shouldUseTimer(distanceToTravel, ticksToImpact);
397
        if (!allowRotationChange.get()) {
398
            return new DodgePlan(basePlan.input(), false, null, useTimer);
399
        }
400
401
        float yaw = yawTowards(relativeDodge);
402
        double effectiveVelocity = player.getDeltaMovement().horizontalDistance()
403
                * Math.max(0.0, similarity(horizontal(player.getDeltaMovement()), relativeDodge));
404
        double travelTimeWithRotation = distanceToTravel / 0.13;
405
        boolean shouldJump = ticksToImpact < travelTimeWithRotation && effectiveVelocity > 0.11;
406
407
        return new DodgePlan(InputPlan.FORWARD, shouldJump, yaw, useTimer);
408
    }
409
410
    private boolean shouldUseTimer(double distanceToTravel, int ticksToImpact) {
411
        if (!allowTimer.get()) {
412
            return false;
413
        }
414
415
        double baseSpeed = allowRotationChange.get() ? 0.155 : 0.11;
416
        return (distanceToTravel / baseSpeed) / (ticksToImpact + 1.0) > 1.6;
417
    }
418
419
    private CandidatePlan findBestDodgeCandidate(LocalPlayer player,
420
                                                 HitInfo hit,
421
                                                 Line threatLine,
422
                                                 double safeDistanceWithPadding) {
423
        Vec3 playerPos2d = horizontal(player.position());
424
        Vec3 optimalDodgePosition = findOptimalDodgePosition(player, threatLine, safeDistanceWithPadding);
425
        Vec3 preferredRelative = optimalDodgePosition.subtract(playerPos2d);
426
        if (preferredRelative.lengthSqr() < 1.0E-7) {
427
            return null;
428
        }
429
430
        double currentDistance = threatLine.nearestPoint(playerPos2d).distanceTo(playerPos2d);
431
        int horizon = Mth.clamp(Math.min(hit.tickDelta() + 1, pathCheckTicks.get()), 1, 12);
432
433
        CandidatePlan best = null;
434
        double bestScore = -Double.MAX_VALUE;
435
        for (InputPlan input : InputPlan.CANDIDATES) {
436
            Vec3 direction = inputDirection(player.getYRot(), input);
437
            if (direction.lengthSqr() < 1.0E-7) {
438
                continue;
439
            }
440
441
            double preference = similarity(direction, preferredRelative);
442
            if (preference < -0.15) {
443
                continue;
444
            }
445
446
            CandidateSafety safety = evaluateCandidateSafety(player, direction, horizon);
447
            if (safety.blocked()) {
448
                continue;
449
            }
450
            if (fallFailsafe.get() && !safety.fallSafe()) {
451
                continue;
452
            }
453
454
            Vec3 projected = playerPos2d.add(direction.scale(PATH_STEP_SPEED * horizon));
455
            double distanceAfter = threatLine.nearestPoint(projected).distanceTo(projected);
456
            if (distanceAfter <= currentDistance + 0.015) {
457
                continue;
458
            }
459
460
            double score = distanceAfter * 3.0
461
                    + preference
462
                    - safety.predictedFallDamage() * 0.35
463
                    - (safety.unsupported() ? 0.8 : 0.0);
464
            if (score > bestScore) {
465
                Vec3 relative = projected.subtract(playerPos2d);
466
                bestScore = score;
467
                best = new CandidatePlan(input, relative);
468
            }
469
        }
470
471
        if (best != null) {
472
            return best;
473
        }
474
475
        InputPlan fallback = chooseInputFor(player.getYRot(), preferredRelative);
476
        if (fallback == null) {
477
            return null;
478
        }
479
480
        Vec3 direction = inputDirection(player.getYRot(), fallback);
481
        CandidateSafety safety = evaluateCandidateSafety(player, direction, horizon);
482
        if (safety.blocked() || (fallFailsafe.get() && !safety.fallSafe())) {
483
            return null;
484
        }
485
        return new CandidatePlan(fallback, preferredRelative);
486
    }
487
488
    private CandidateSafety evaluateCandidateSafety(LocalPlayer player, Vec3 direction, int horizon) {
489
        AABB baseBox = player.getBoundingBox();
490
        Vec3 basePos = player.position();
491
        boolean unsupported = false;
492
        double predictedFallDamage = 0.0;
493
494
        int safeHorizon = Math.max(1, horizon);
495
        for (int tick = 1; tick <= safeHorizon; tick++) {
496
            Vec3 offset = direction.scale(PATH_STEP_SPEED * tick);
497
            AABB pathBox = baseBox.move(offset.x, 0.0, offset.z).deflate(COLLISION_MARGIN, 0.0, COLLISION_MARGIN);
498
            if (!mc.level.noCollision(player, pathBox)) {
499
                return new CandidateSafety(true, false, true, Double.POSITIVE_INFINITY);
500
            }
501
502
            if (!hasGroundSupport(player, pathBox) && !player.isInWater() && !player.isFallFlying()) {
503
                unsupported = true;
504
            }
505
        }
506
507
        if (unsupported && fallFailsafe.get()) {
508
            Vec3 finalOffset = direction.scale(PATH_STEP_SPEED * safeHorizon);
509
            Vec3 finalPos = basePos.add(finalOffset.x, 0.0, finalOffset.z);
510
            predictedFallDamage = predictFallDamage(player, finalPos);
511
        }
512
513
        boolean fallSafe = !unsupported
514
                || !fallFailsafe.get()
515
                || predictedFallDamage <= maxPredictedFallDamage.get()
516
                && predictedFallDamage < player.getHealth() + player.getAbsorptionAmount() - 0.5f;
517
        return new CandidateSafety(false, unsupported, fallSafe, predictedFallDamage);
518
    }
519
520
    private boolean hasGroundSupport(LocalPlayer player, AABB box) {
521
        AABB supportBox = new AABB(
522
                box.minX + 0.05,
523
                box.minY - 0.10,
524
                box.minZ + 0.05,
525
                box.maxX - 0.05,
526
                box.minY - 0.01,
527
                box.maxZ - 0.05
528
        );
529
        return !mc.level.noCollision(player, supportBox);
530
    }
531
532
    private double predictFallDamage(LocalPlayer player, Vec3 horizontalLandingPos) {
533
        if (mc.level == null) {
534
            return Double.POSITIVE_INFINITY;
535
        }
536
537
        double landingY = findLandingY(player, horizontalLandingPos);
538
        if (!Double.isFinite(landingY)) {
539
            return Double.POSITIVE_INFINITY;
540
        }
541
542
        double fallDistance = Math.max(0.0, player.fallDistance + player.getY() - landingY);
543
        if (fallDistance <= player.getAttributeValue(Attributes.SAFE_FALL_DISTANCE)) {
544
            return 0.0;
545
        }
546
547
        float raw = Mth.floor((fallDistance + 1.0E-6 - player.getAttributeValue(Attributes.SAFE_FALL_DISTANCE))
548
                * player.getAttributeValue(Attributes.FALL_DAMAGE_MULTIPLIER));
549
        if (raw <= 0.0f) {
550
            return 0.0;
551
        }
552
553
        return applyFallReductions(player, raw);
554
    }
555
556
    private double findLandingY(LocalPlayer player, Vec3 horizontalLandingPos) {
557
        double startY = player.getY() + 0.2;
558
        double endY = mc.level.getMinY();
559
        double[][] samples = {
560
                {0.0, 0.0},
561
                {PLAYER_HALF_WIDTH - 0.04, PLAYER_HALF_WIDTH - 0.04},
562
                {PLAYER_HALF_WIDTH - 0.04, -PLAYER_HALF_WIDTH + 0.04},
563
                {-PLAYER_HALF_WIDTH + 0.04, PLAYER_HALF_WIDTH - 0.04},
564
                {-PLAYER_HALF_WIDTH + 0.04, -PLAYER_HALF_WIDTH + 0.04}
565
        };
566
567
        double bestY = Double.NEGATIVE_INFINITY;
568
        for (double[] sample : samples) {
569
            Vec3 from = new Vec3(horizontalLandingPos.x + sample[0], startY, horizontalLandingPos.z + sample[1]);
570
            Vec3 to = new Vec3(from.x, endY, from.z);
571
            HitResult hit = mc.level.clip(new ClipContext(
572
                    from,
573
                    to,
574
                    ClipContext.Block.COLLIDER,
575
                    ClipContext.Fluid.ANY,
576
                    player
577
            ));
578
            if (hit != null && hit.getType() != HitResult.Type.MISS) {
579
                bestY = Math.max(bestY, hit.getLocation().y);
580
            }
581
        }
582
583
        return bestY;
584
    }
585
586
    private float applyFallReductions(LocalPlayer player, float damage) {
587
        DamageSource source = player.damageSources().fall();
588
        float armor = player.getArmorValue();
589
        float toughness = (float) player.getAttributeValue(Attributes.ARMOR_TOUGHNESS);
590
        float out = CombatRules.getDamageAfterAbsorb(player, damage, source, armor, toughness);
591
592
        MobEffectInstance resistance = player.getEffect(MobEffects.RESISTANCE);
593
        if (resistance != null) {
594
            int reduced = 25 - (resistance.getAmplifier() + 1) * 5;
595
            out = Math.max(out * reduced / 25.0f, 0.0f);
596
        }
597
598
        float protection = getFallProtectionAmount(player);
599
        return protection > 0.0f ? CombatRules.getDamageAfterMagicAbsorb(out, protection) : out;
600
    }
601
602
    private float getFallProtectionAmount(LocalPlayer player) {
603
        float total = 0.0f;
604
        for (EquipmentSlot slot : ARMOR_SLOTS) {
605
            ItemStack stack = player.getItemBySlot(slot);
606
            total += getEnchantmentLevel(Enchantments.PROTECTION, stack);
607
            if (slot == EquipmentSlot.FEET) {
608
                total += getEnchantmentLevel(Enchantments.FEATHER_FALLING, stack) * 3.0f;
609
            }
610
        }
611
        return total;
612
    }
613
614
    private int getEnchantmentLevel(ResourceKey<Enchantment> key, ItemStack stack) {
615
        Holder<Enchantment> entry = getEnchantmentEntry(key);
616
        return entry != null ? EnchantmentHelper.getItemEnchantmentLevel(entry, stack) : 0;
617
    }
618
619
    private Holder<Enchantment> getEnchantmentEntry(ResourceKey<Enchantment> key) {
620
        if (mc.level == null || key == null) {
621
            return null;
622
        }
623
624
        Registry<Enchantment> registry = mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
625
        Enchantment enchantment = registry.getValue(key);
626
        return enchantment != null ? registry.wrapAsHolder(enchantment) : null;
627
    }
628
629
    private Vec3 findOptimalDodgePosition(LocalPlayer player, Line threatLine, double safeDistanceWithPadding) {
630
        Vec3 playerPos2d = horizontal(player.position());
631
        Vec3 velocity = horizontal(player.getDeltaMovement());
632
        Vec3 freeMovementPos = playerPos2d.add(velocity.scale(2.0));
633
        Vec3 nearestPosToLine = threatLine.nearestPoint(playerPos2d);
634
635
        Line[] borders = dangerZoneBorders(threatLine, safeDistanceWithPadding);
636
        Vec3 first = borders[0].nearestPoint(freeMovementPos);
637
        Vec3 second = borders[1].nearestPoint(freeMovementPos);
638
639
        if (walkableDistance(player, nearestPosToLine, first) < SAFE_DISTANCE) {
640
            return second;
641
        }
642
643
        if (walkableDistance(player, nearestPosToLine, second) < SAFE_DISTANCE) {
644
            return first;
645
        }
646
647
        return first.distanceTo(freeMovementPos) < second.distanceTo(freeMovementPos) - 0.05 ? first : second;
648
    }
649
650
    private double walkableDistance(LocalPlayer player, Vec3 basePos, Vec3 dodgePos) {
651
        double bestSq = Double.POSITIVE_INFINITY;
652
        double[] rayHeights = {0.6, 1.6};
653
        for (double height : rayHeights) {
654
            Vec3 from = new Vec3(basePos.x, player.getY() + height, basePos.z);
655
            Vec3 to = new Vec3(dodgePos.x, player.getY() + height, dodgePos.z);
656
            HitResult hit = mc.level.clip(new ClipContext(
657
                    from,
658
                    to,
659
                    ClipContext.Block.COLLIDER,
660
                    ClipContext.Fluid.NONE,
661
                    player
662
            ));
663
            Vec3 realTo = hit != null && hit.getType() != HitResult.Type.MISS ? hit.getLocation() : to;
664
            bestSq = Math.min(bestSq, from.distanceToSqr(realTo));
665
        }
666
667
        return Math.sqrt(bestSq);
668
    }
669
670
    private Line[] dangerZoneBorders(Line baseLine, double distance) {
671
        Vec3 ortho = new Vec3(-baseLine.direction().z, 0.0, baseLine.direction().x).normalize();
672
        Vec3 offset = ortho.scale(distance);
673
        return new Line[]{
674
                new Line(baseLine.position().subtract(offset), baseLine.direction()),
675
                new Line(baseLine.position().add(offset), baseLine.direction())
676
        };
677
    }
678
679
    private InputPlan chooseInputFor(float yaw, Vec3 desiredDirection) {
680
        Vec3 desired = horizontal(desiredDirection);
681
        if (desired.lengthSqr() < 1.0E-7) {
682
            return null;
683
        }
684
        desired = desired.normalize();
685
686
        InputPlan best = null;
687
        double bestDot = -Double.MAX_VALUE;
688
        for (InputPlan candidate : InputPlan.CANDIDATES) {
689
            Vec3 direction = inputDirection(yaw, candidate);
690
            double dot = direction.dot(desired);
691
            if (dot > bestDot) {
692
                bestDot = dot;
693
                best = candidate;
694
            }
695
        }
696
697
        return bestDot >= INPUT_DEAD_DOT ? best : null;
698
    }
699
700
    private Vec3 inputDirection(float yaw, InputPlan input) {
701
        float forward = input.forward() == input.backward() ? 0.0f : (input.forward() ? 1.0f : -1.0f);
702
        float sideways = input.left() == input.right() ? 0.0f : (input.left() ? 1.0f : -1.0f);
703
        if (forward == 0.0f && sideways == 0.0f) {
704
            return Vec3.ZERO;
705
        }
706
707
        double sin = Math.sin(Math.toRadians(yaw + 90.0f));
708
        double cos = Math.cos(Math.toRadians(yaw + 90.0f));
709
        Vec3 direction = new Vec3(
710
                forward * cos + sideways * sin,
711
                0.0,
712
                forward * sin - sideways * cos
713
        );
714
715
        return direction.lengthSqr() > 1.0 ? direction.normalize() : direction;
716
    }
717
718
    private void applyInput(MovementInputEvent event, InputPlan input) {
719
        event.setForward(input.forward());
720
        event.setBackward(input.backward());
721
        event.setLeft(input.left());
722
        event.setRight(input.right());
723
        if (input.forward()) {
724
            event.setSprint(true);
725
        }
726
    }
727
728
    private boolean applyEdgeSafeWalk(LocalPlayer player, MovementInputEvent event) {
729
        if (!fallFailsafe.get() || !edgeSafeWalk.get()) {
730
            return false;
731
        }
732
733
        SafeWalk safeWalk = Modules.get(SafeWalk.class);
734
        return safeWalk != null && safeWalk.handleExternalOnEdge(player, event);
735
    }
736
737
    private float yawTowards(Vec3 direction) {
738
        return Mth.wrapDegrees((float) Math.toDegrees(Math.atan2(direction.z, direction.x)) - 90.0f);
739
    }
740
741
    private double similarity(Vec3 a, Vec3 b) {
742
        Vec3 ah = horizontal(a);
743
        Vec3 bh = horizontal(b);
744
        double len = ah.length() * bh.length();
745
        if (len < 1.0E-7) {
746
            return 0.0;
747
        }
748
        return ah.dot(bh) / len;
749
    }
750
751
    private Vec3 horizontal(Vec3 vec) {
752
        if (vec == null) {
753
            return Vec3.ZERO;
754
        }
755
        return new Vec3(vec.x, 0.0, vec.z);
756
    }
757
758
    private boolean isInGround(AbstractArrow projectile) {
759
        try {
760
            return ((PersistentProjectileEntityAccessor) projectile).combatant$isInGround();
761
        } catch (Throwable ignored) {
762
            return false;
763
        }
764
    }
765
766
    private void clearTimer() {
767
        if (timerActive) {
768
            Timer.clearExternalTickTimer();
769
            timerActive = false;
770
        }
771
    }
772
773
    private interface ThreatSimulation {
774
        Entity entity();
775
776
        Vec3 previousPos();
777
778
        Vec3 pos();
779
780
        Vec3 velocity();
781
782
        boolean tick();
783
    }
784
785
    private record HitInfo(int tickDelta, Entity threat, Vec3 hitPos, Vec3 previousThreatPos, Vec3 velocity) {
786
    }
787
788
    private record DodgePlan(InputPlan input, boolean shouldJump, Float yawChange, boolean useTimer) {
789
    }
790
791
    private record CandidatePlan(InputPlan input, Vec3 relativeDodge) {
792
    }
793
794
    private record CandidateSafety(boolean blocked,
795
                                   boolean unsupported,
796
                                   boolean fallSafe,
797
                                   double predictedFallDamage) {
798
    }
799
800
    private record InputPlan(boolean forward, boolean backward, boolean left, boolean right) {
801
        private static final InputPlan FORWARD = new InputPlan(true, false, false, false);
802
        private static final InputPlan[] CANDIDATES = {
803
                FORWARD,
804
                new InputPlan(true, false, true, false),
805
                new InputPlan(false, false, true, false),
806
                new InputPlan(false, true, true, false),
807
                new InputPlan(false, true, false, false),
808
                new InputPlan(false, true, false, true),
809
                new InputPlan(false, false, false, true),
810
                new InputPlan(true, false, false, true)
811
        };
812
    }
813
814
    private record Line(Vec3 position, Vec3 direction) {
815
        private Vec3 nearestPoint(Vec3 point) {
816
            double lengthSq = direction.lengthSqr();
817
            if (lengthSq < 1.0E-7) {
818
                return position;
819
            }
820
            double t = point.subtract(position).dot(direction) / lengthSq;
821
            return position.add(direction.scale(t));
822
        }
823
    }
824
825
    private final class ArrowLikeThreatSimulation implements ThreatSimulation {
826
        private final Entity entity;
827
        private final SimulatedArrow arrow;
828
        private Vec3 previousPos;
829
        private Vec3 pos;
830
        private Vec3 velocity;
831
        private boolean done;
832
833
        private ArrowLikeThreatSimulation(Entity entity) {
834
            this.entity = entity;
835
            this.arrow = new SimulatedArrow(mc.level, entity.position(), entity.getDeltaMovement(), false);
836
            this.previousPos = entity.position();
837
            this.pos = entity.position();
838
            this.velocity = entity.getDeltaMovement();
839
        }
840
841
        @Override
842
        public Entity entity() {
843
            return entity;
844
        }
845
846
        @Override
847
        public Vec3 previousPos() {
848
            return previousPos;
849
        }
850
851
        @Override
852
        public Vec3 pos() {
853
            return pos;
854
        }
855
856
        @Override
857
        public Vec3 velocity() {
858
            return velocity;
859
        }
860
861
        @Override
862
        public boolean tick() {
863
            if (done) {
864
                return false;
865
            }
866
867
            previousPos = arrow.getPos();
868
            HitResult hit = arrow.tick();
869
            pos = arrow.getPos();
870
            velocity = pos.subtract(previousPos);
871
            if (hit != null) {
872
                done = true;
873
            }
874
875
            return velocity.lengthSqr() > 1.0E-9;
876
        }
877
    }
878
879
    private final class LinearThreatSimulation implements ThreatSimulation {
880
        private final Entity entity;
881
        private Vec3 previousPos;
882
        private Vec3 pos;
883
        private Vec3 velocity;
884
        private boolean done;
885
886
        private LinearThreatSimulation(Entity entity) {
887
            this.entity = entity;
888
            this.previousPos = entity.position();
889
            this.pos = entity.position();
890
            this.velocity = entity.getDeltaMovement();
891
        }
892
893
        @Override
894
        public Entity entity() {
895
            return entity;
896
        }
897
898
        @Override
899
        public Vec3 previousPos() {
900
            return previousPos;
901
        }
902
903
        @Override
904
        public Vec3 pos() {
905
            return pos;
906
        }
907
908
        @Override
909
        public Vec3 velocity() {
910
            return velocity;
911
        }
912
913
        @Override
914
        public boolean tick() {
915
            if (done || velocity.lengthSqr() < 1.0E-9) {
916
                return false;
917
            }
918
919
            previousPos = pos;
920
            Vec3 nextPos = pos.add(velocity);
921
            HitResult hit = mc.level.clip(new ClipContext(
922
                    pos,
923
                    nextPos,
924
                    ClipContext.Block.COLLIDER,
925
                    ClipContext.Fluid.NONE,
926
                    entity
927
            ));
928
929
            if (hit != null && hit.getType() != HitResult.Type.MISS) {
930
                pos = hit.getLocation();
931
                velocity = pos.subtract(previousPos);
932
                done = true;
933
                return velocity.lengthSqr() > 1.0E-9;
934
            }
935
936
            pos = nextPos;
937
            velocity = entity instanceof ShulkerBullet ? velocity.scale(0.95) : velocity;
938
            return true;
939
        }
940
    }
941
}
942
LiquidBounce (Kotlin)COMBATsrc/main/kotlin/net/ccbluex/liquidbounce/features/module/modules/movement/autododge/ModuleAutoDodge.ktKotlin · 229 lines · 8.4 KB

Automatically dodges projectiles like arrows.

SettingsAllowJumpTimerSpeedIgnore
ModuleAutoDodge.ktKotlin · Minecraft 26.2 · 229 lines · 8.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
@file:Suppress("WildcardImport")
20
21
package net.ccbluex.liquidbounce.features.module.modules.movement.autododge
22
23
import net.ccbluex.fastutil.mapToArray
24
import net.ccbluex.liquidbounce.config.types.group.ToggleableValueGroup
25
import net.ccbluex.liquidbounce.config.types.list.Tagged
26
import net.ccbluex.liquidbounce.event.events.MovementInputEvent
27
import net.ccbluex.liquidbounce.event.handler
28
import net.ccbluex.liquidbounce.event.once
29
import net.ccbluex.liquidbounce.features.blink.BlinkManager
30
import net.ccbluex.liquidbounce.features.module.ClientModule
31
import net.ccbluex.liquidbounce.features.module.ModuleCategories
32
import net.ccbluex.liquidbounce.features.module.modules.player.ModuleBlink
33
import net.ccbluex.liquidbounce.features.module.modules.render.murdermystery.ModuleMurderMystery
34
import net.ccbluex.liquidbounce.features.module.modules.world.scaffold.ModuleScaffold
35
import net.ccbluex.liquidbounce.utils.client.Timer
36
import net.ccbluex.liquidbounce.utils.entity.CachedPlayerSimulation
37
import net.ccbluex.liquidbounce.utils.entity.PlayerSimulation
38
import net.ccbluex.liquidbounce.utils.entity.PlayerSimulationCache
39
import net.ccbluex.liquidbounce.utils.entity.SimulatedArrow
40
import net.ccbluex.liquidbounce.utils.inventory.InventoryManager
41
import net.ccbluex.liquidbounce.utils.kotlin.Priority
42
import net.minecraft.client.gui.screens.inventory.ContainerScreen
43
import net.minecraft.client.multiplayer.ClientLevel
44
import net.minecraft.world.entity.Entity
45
import net.minecraft.world.entity.projectile.arrow.Arrow
46
import net.minecraft.world.entity.projectile.arrow.SpectralArrow
47
import net.minecraft.world.entity.projectile.arrow.ThrownTrident
48
import net.minecraft.world.phys.AABB
49
import net.minecraft.world.phys.Vec3
50
51
object ModuleAutoDodge : ClientModule("AutoDodge", ModuleCategories.COMBAT) {
52
    private const val MIN_PACKET_DISTANCE = 0.9
53
    private const val MIN_PACKET_DISTANCE_SQ = MIN_PACKET_DISTANCE * MIN_PACKET_DISTANCE
54
55
    private object AllowRotationChange : ToggleableValueGroup(this, "AllowRotationChange", false) {
56
        val allowJump by boolean("AllowJump", true)
57
    }
58
59
    private object AllowTimer : ToggleableValueGroup(this, "AllowTimer", false) {
60
        val timerSpeed by float("TimerSpeed", 2.0F, 1.0F..10.0F, suffix = "x")
61
    }
62
63
    private val ignore by multiEnumChoice("Ignore", Ignore.entries)
64
65
    init {
66
        tree(AllowRotationChange)
67
        tree(AllowTimer)
68
    }
69
70
    override val running: Boolean get() =
71
        super.running
72
           // We aren't where we are because of blink. So this module shall not cause any disturbance in that case.
73
        && !ModuleBlink.running
74
        && !ModuleMurderMystery.disallowsArrowDodge()
75
        && !(Ignore.OPEN_INVENTORY !in ignore
76
            && (InventoryManager.isInventoryOpen || mc.gui.screen() is ContainerScreen))
77
        && !(Ignore.USING_ITEM !in ignore && player.isUsingItem)
78
        && !(Ignore.USING_SCAFFOLD !in ignore && ModuleScaffold.running)
79
80
    @Suppress("unused")
81
    val tickRep = handler<MovementInputEvent> { event ->
82
        val arrows = world.findFlyingArrows()
83
84
        val simulatedPlayer = CachedPlayerSimulation(PlayerSimulationCache.getSimulationForLocalPlayer())
85
86
        val inflictedHit =
87
            getInflictedHits(simulatedPlayer, arrows, hitboxExpansion = DodgePlanner.SAFE_DISTANCE_WITH_PADDING)
88
                ?: return@handler
89
90
        val dodgePlan =
91
            planEvasion(DodgePlannerConfig(allowRotations = AllowRotationChange.enabled), inflictedHit)
92
                ?: return@handler
93
94
        event.directionalInput = dodgePlan.directionalInput
95
96
        dodgePlan.yawChange?.let { yawChange ->
97
            player.yRot = yawChange
98
        }
99
100
        if (dodgePlan.shouldJump && AllowRotationChange.allowJump && player.onGround()) {
101
            once<MovementInputEvent> { movementInputEvent ->
102
                movementInputEvent.jump = true
103
            }
104
        }
105
106
        if (AllowTimer.enabled && dodgePlan.useTimer) {
107
            Timer.requestTimerSpeed(AllowTimer.timerSpeed, Priority.IMPORTANT_FOR_PLAYER_LIFE, this@ModuleAutoDodge)
108
        }
109
    }
110
111
    private fun ClientLevel.findFlyingArrows() = entitiesForRendering().filter { entity ->
112
        (entity is Arrow || entity is SpectralArrow ||
113
                (entity is ThrownTrident && entity.clientSideReturnTridentTickCount == 0)) && !entity.isInGround
114
    }
115
116
    private fun <T : PlayerSimulation> getInflictedHits(
117
        simulatedPlayer: T,
118
        arrows: List<Entity>,
119
        maxTicks: Int = 80,
120
        hitboxExpansion: Double = 0.7,
121
    ): HitInfo? {
122
        val simulatedArrows = arrows.mapToArray {
123
            SimulatedArrow(it.level(), it.position(), it.deltaMovement, false)
124
        }
125
126
        for (i in 0 until maxTicks) {
127
            simulatedPlayer.tick()
128
129
            simulatedArrows.forEachIndexed { arrowIndex, arrow ->
130
                if (arrow.inGround) {
131
                    return@forEachIndexed
132
                }
133
134
                val lastPos = arrow.pos
135
136
                arrow.tick()
137
138
                val playerHitBox =
139
                    AABB(-0.3, 0.0, -0.3, 0.3, 1.8, 0.3)
140
                        .inflate(hitboxExpansion)
141
                        .move(simulatedPlayer.pos)
142
                val raycastResult = playerHitBox.clip(lastPos, arrow.pos)
143
144
                raycastResult.orElse(null)?.let { hitPos ->
145
                    return HitInfo(i, arrows[arrowIndex], hitPos, lastPos, arrow.velocity)
146
                }
147
            }
148
        }
149
150
        return null
151
    }
152
153
    data class EvadingPacket(
154
        val idx: Int,
155
        /**
156
         * Ticks until impact. Null if evaded
157
         */
158
        val ticksToImpact: Int?
159
    )
160
161
    /**
162
     * Returns the index of the first position packet that avoids all arrows in the next X seconds
163
     */
164
    @Suppress("ReturnCount")
165
    fun findAvoidingArrowPosition(): EvadingPacket? {
166
        var packetIndex = 0
167
168
        var lastPosition: Vec3? = null
169
170
        var bestPacketPosition: Vec3? = null
171
        var bestPacketIdx: Int? = null
172
        var bestTimeToImpact = 0
173
174
        for (position in BlinkManager.positions) {
175
            packetIndex += 1
176
177
            // Process packets only if they are at least some distance away from each other
178
            if (lastPosition != null) {
179
                if (lastPosition.distanceToSqr(position) < MIN_PACKET_DISTANCE_SQ) {
180
                    continue
181
                }
182
            }
183
184
            lastPosition = position
185
186
            val inflictedHit = getInflictedHit(position)
187
188
            if (inflictedHit == null) {
189
                return EvadingPacket(packetIndex - 1, null)
190
            } else if (inflictedHit.tickDelta > bestTimeToImpact) {
191
                bestTimeToImpact = inflictedHit.tickDelta
192
                bestPacketIdx = packetIndex - 1
193
                bestPacketPosition = position
194
            }
195
        }
196
197
        // If the evading packet is less than one player hitbox away from the current position, we should rather
198
        // call the evasion a failure
199
        if (bestPacketIdx != null && bestPacketPosition!!.distanceToSqr(player.position()) > MIN_PACKET_DISTANCE_SQ) {
200
            return EvadingPacket(bestPacketIdx, bestTimeToImpact)
201
        }
202
203
        return null
204
    }
205
206
    fun getInflictedHit(pos: Vec3): HitInfo? {
207
        val arrows = world.findFlyingArrows()
208
        val playerSimulation = PlayerSimulation.Rigid(pos)
209
210
        return getInflictedHits(playerSimulation, arrows, maxTicks = 40)
211
    }
212
213
    data class HitInfo(
214
        val tickDelta: Int,
215
        val arrowEntity: Entity,
216
        val hitPos: Vec3,
217
        val prevArrowPos: Vec3,
218
        val arrowVelocity: Vec3,
219
    )
220
221
    private enum class Ignore(
222
        override val tag: String
223
    ) : Tagged {
224
        OPEN_INVENTORY("OpenInventory"),
225
        USING_ITEM("UsingItem"),
226
        USING_SCAFFOLD("UsingScaffold")
227
    }
228
}
229