AttributeSwap module

AttributeSwap: Minecraft 26.3 cheat module, full source for every implementation (2 clients: OfflineClient, Combatant).

2 implementationsCOMBAT

Clients with this module

Full module source: 2 implementations

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

OfflineClientCOMBATsrc/main/java/com/jellypudding/offlineclient/modules/combat/AttributeSwap.javaJava · 457 lines · 18.4 KB

Swaps to your best item for the hit the moment you attack.

SettingsModeTarget slotSwap on missMin gainSwap backSwap back delayAnti breakShield breakerDurability saverSword enchantmentsFire aspectLootingSharpnessSmiteBane of arthropodsSweeping edgeMace enchantmentsRegular maceDensityBreachWind burstSpear swapsLungeReachKeep lunge spearOther enchantmentsImpalingOnly with KillAuraOnly on weaponSwordAxePickaxeShovelHoeMaceTrident
AttributeSwap.javaJava · Minecraft 26.2 · 457 lines · 18.4 KB · complete file, verbatimOriginal ↗
1
package com.jellypudding.offlineclient.modules.combat;
2
3
import com.jellypudding.offlineclient.event.Subscribe;
4
import com.jellypudding.offlineclient.event.events.AttackEntityEvent;
5
import com.jellypudding.offlineclient.event.events.LeftClickEvent;
6
import com.jellypudding.offlineclient.event.events.TickEvent;
7
import com.jellypudding.offlineclient.module.Category;
8
import com.jellypudding.offlineclient.module.ExclusivityGroup;
9
import com.jellypudding.offlineclient.module.Module;
10
import com.jellypudding.offlineclient.setting.BoolSetting;
11
import com.jellypudding.offlineclient.setting.EnumSetting;
12
import com.jellypudding.offlineclient.setting.NumberSetting;
13
import com.jellypudding.offlineclient.util.EntityUtil;
14
import com.jellypudding.offlineclient.util.InventoryUtil.SlotSwap;
15
import com.jellypudding.offlineclient.util.InventoryUtil;
16
import com.jellypudding.offlineclient.util.ItemUtil;
17
import com.jellypudding.offlineclient.util.Modules;
18
import net.minecraft.resources.ResourceKey;
19
import net.minecraft.tags.EntityTypeTags;
20
import net.minecraft.tags.ItemTags;
21
import net.minecraft.world.effect.MobEffects;
22
import net.minecraft.world.entity.Entity;
23
import net.minecraft.world.entity.EquipmentSlot;
24
import net.minecraft.world.entity.LivingEntity;
25
import net.minecraft.world.entity.ai.attributes.Attributes;
26
import net.minecraft.world.entity.player.Player;
27
import net.minecraft.world.item.ItemStack;
28
import net.minecraft.world.item.MaceItem;
29
import net.minecraft.world.item.TridentItem;
30
import net.minecraft.world.item.enchantment.Enchantment;
31
import net.minecraft.world.item.enchantment.Enchantments;
32
import net.minecraft.world.phys.AABB;
33
import net.minecraft.world.phys.HitResult;
34
import net.minecraft.world.phys.Vec3;
35
36
public final class AttributeSwap extends Module {
37
38
    public enum Mode { SIMPLE, SMART }
39
40
    // How far a spear swing is looked along for something to reach.
41
    private static final double SPEAR_LOOK = 7;
42
43
    // A spear hits a little outside the hitbox.
44
    private static final double SPEAR_MARGIN = 0.15;
45
46
    // Blocks past the normal reach before a spear is worth swapping to.
47
    private static final double REACH_SLACK = 0.5;
48
49
    // A mace only smashes after falling further than this.
50
    private static final double SMASH_FALL = 1.5;
51
52
    // A mob under this much health is about to drop its loot.
53
    private static final float NEARLY_DEAD = 20;
54
55
    private final EnumSetting<Mode> mode = new EnumSetting<>("Mode",
56
        "What the swap goes to.", Mode.SMART)
57
        .describe(Mode.SIMPLE, "Always the one hotbar slot you pick.")
58
        .describe(Mode.SMART, "Whatever scores best against the target you hit.");
59
    private final NumberSetting targetSlot = new NumberSetting("Target slot",
60
        "The hotbar slot to swap to.", 1, 1, 9, 1)
61
        .under(mode, Mode.SIMPLE);
62
    private final BoolSetting swapOnMiss = new BoolSetting("Swap on miss",
63
        "Also swap on a swing that hits nothing so a spear can lunge.", false)
64
        .under(mode, Mode.SIMPLE);
65
    private final NumberSetting minGain = new NumberSetting("Min gain",
66
        "The other item must beat what you hold by this many points.", 0.5, 0, 10, 0.5)
67
        .under(mode, Mode.SMART);
68
    private final BoolSetting swapBack = new BoolSetting("Swap back",
69
        "Return to the slot you had once the hit has landed.", true);
70
    private final NumberSetting swapBackDelay = new NumberSetting("Swap back delay",
71
        "Ticks to hold the swapped item before returning.", 2, 0, 20, 1, " ticks")
72
        .under(swapBack);
73
    private final BoolSetting antiBreak = new BoolSetting("Anti break",
74
        "Skip items that are about to break.", true);
75
76
    private final BoolSetting shieldBreaker = new BoolSetting("Shield breaker",
77
        "Swap to an axe when the target is holding a shield up.", true)
78
        .under(mode, Mode.SMART);
79
    private final BoolSetting durabilitySaver = new BoolSetting("Durability saver",
80
        "Lean towards items that cannot wear out or carry Unbreaking.", true)
81
        .under(mode, Mode.SMART);
82
83
    private final BoolSetting swords = new BoolSetting("Sword enchantments",
84
        "Score the enchantments swords carry.", true)
85
        .under(mode, Mode.SMART);
86
    private final BoolSetting fireAspect = new BoolSetting("Fire aspect",
87
        "Prefer Fire Aspect against a target that is not burning yet.", true)
88
        .under(swords);
89
    private final BoolSetting looting = new BoolSetting("Looting",
90
        "Prefer Looting against mobs and twice as much when they are nearly dead.", true)
91
        .under(swords);
92
    private final BoolSetting sharpness = new BoolSetting("Sharpness",
93
        "Count the extra damage from Sharpness.", true)
94
        .under(swords);
95
    private final BoolSetting smite = new BoolSetting("Smite",
96
        "Count the extra damage from Smite against the undead.", true)
97
        .under(swords);
98
    private final BoolSetting bane = new BoolSetting("Bane of arthropods",
99
        "Count the extra damage from Bane of Arthropods against bugs.", true)
100
        .under(swords);
101
    private final BoolSetting sweeping = new BoolSetting("Sweeping edge",
102
        "Prefer Sweeping Edge for the wider hit.", true)
103
        .under(swords);
104
105
    private final BoolSetting maces = new BoolSetting("Mace enchantments",
106
        "Score maces and their enchantments whilst you are falling.", true)
107
        .under(mode, Mode.SMART);
108
    private final BoolSetting regularMace = new BoolSetting("Regular mace",
109
        "Swap to any mace once you have fallen far enough to smash.", true)
110
        .under(maces);
111
    private final BoolSetting density = new BoolSetting("Density",
112
        "Prefer Density for the harder smash the further you fall.", true)
113
        .under(maces);
114
    private final BoolSetting breach = new BoolSetting("Breach",
115
        "Prefer Breach against a target wearing armour.", true)
116
        .under(maces);
117
    private final BoolSetting windBurst = new BoolSetting("Wind burst",
118
        "Prefer Wind Burst to bounce up again after the smash.", true)
119
        .under(maces);
120
121
    private final BoolSetting spears = new BoolSetting("Spear swaps",
122
        "Swap to a spear for reach or for a lunge.", true)
123
        .under(mode, Mode.SMART);
124
    private final BoolSetting lunge = new BoolSetting("Lunge",
125
        "Swap to a Lunge spear on a swing that hits nothing so you travel.", true)
126
        .under(spears);
127
    private final BoolSetting reach = new BoolSetting("Reach",
128
        "Swap to a spear when what you swing at is past normal reach.", true)
129
        .under(spears);
130
    private final BoolSetting keepLungeSpear = new BoolSetting("Keep lunge spear",
131
        "Never use a Lunge spear for the reach swap.", true)
132
        .under(reach);
133
134
    private final BoolSetting others = new BoolSetting("Other enchantments",
135
        "Score enchantments that live on tridents and spears.", true)
136
        .under(mode, Mode.SMART);
137
    private final BoolSetting impaling = new BoolSetting("Impaling",
138
        "Count the extra damage from Impaling against sea creatures.", true)
139
        .under(others);
140
141
    private final BoolSetting onlyWithKillAura = new BoolSetting("Only with KillAura",
142
        "Stay put unless KillAura is on.", false);
143
    private final BoolSetting onlyOnWeapon = new BoolSetting("Only on weapon",
144
        "Only swap whilst you already hold one of the ticked kinds.", false);
145
    private final BoolSetting sword = new BoolSetting("Sword", "A sword counts.", true)
146
        .under(onlyOnWeapon);
147
    private final BoolSetting axe = new BoolSetting("Axe", "An axe counts.", true)
148
        .under(onlyOnWeapon);
149
    private final BoolSetting pickaxe = new BoolSetting("Pickaxe", "A pickaxe counts.", true)
150
        .under(onlyOnWeapon);
151
    private final BoolSetting shovel = new BoolSetting("Shovel", "A shovel counts.", true)
152
        .under(onlyOnWeapon);
153
    private final BoolSetting hoe = new BoolSetting("Hoe", "A hoe counts.", true)
154
        .under(onlyOnWeapon);
155
    private final BoolSetting mace = new BoolSetting("Mace", "A mace counts.", true)
156
        .under(onlyOnWeapon);
157
    private final BoolSetting trident = new BoolSetting("Trident", "A trident counts.", true)
158
        .under(onlyOnWeapon);
159
160
    private final SlotSwap slots = new SlotSwap();
161
    private int timer;
162
163
    public AttributeSwap() {
164
        super("AttributeSwap", "Swaps to your best item for the hit the moment you attack.",
165
            Category.COMBAT);
166
        addSettings(mode, targetSlot, swapOnMiss, minGain, swapBack, swapBackDelay, antiBreak,
167
            shieldBreaker, durabilitySaver,
168
            swords, fireAspect, looting, sharpness, smite, bane, sweeping,
169
            maces, regularMace, density, breach, windBurst,
170
            spears, lunge, reach, keepLungeSpear,
171
            others, impaling,
172
            onlyWithKillAura, onlyOnWeapon, sword, axe, pickaxe, shovel, hoe, mace, trident);
173
        searchTags("attribute", "damage swap", "hotbar", "spear", "mace");
174
    }
175
176
    @Override
177
    public ExclusivityGroup getExclusivityGroup() {
178
        return ExclusivityGroup.WEAPON_SWAP;
179
    }
180
181
    @Override
182
    protected void onEnable() {
183
        slots.forget();
184
        timer = 0;
185
    }
186
187
    @Override
188
    protected void onDisable() {
189
        slots.restore();
190
    }
191
192
    // The click arrives before the game reads the held item. A swap here counts.
193
    @Subscribe
194
    private void onLeftClick(LeftClickEvent event) {
195
        if (!canSwap() || mc.hitResult == null || mc.hitResult.getType() == HitResult.Type.BLOCK) {
196
            return;
197
        }
198
        if (mode.is(Mode.SIMPLE)) {
199
            if (swapOnMiss.isOn()) {
200
                swapTo(targetSlot.getInt() - 1);
201
            }
202
            return;
203
        }
204
        if (!spears.isOn()) {
205
            return;
206
        }
207
        Entity far = reach.isOn() ? spearTarget() : null;
208
        if (far != null) {
209
            if (mc.player.distanceTo(far) <= mc.player.entityInteractionRange() + REACH_SLACK) {
210
                return;
211
            }
212
            int spear = spearSlot(false);
213
            if (spear != -1) {
214
                swapTo(spear);
215
                return;
216
            }
217
        }
218
        if (lunge.isOn()) {
219
            swapTo(spearSlot(true));
220
        }
221
    }
222
223
    @Subscribe
224
    private void onAttack(AttackEntityEvent event) {
225
        if (!canSwap()) {
226
            return;
227
        }
228
        if (mode.is(Mode.SIMPLE)) {
229
            // The miss swap already handled this click.
230
            if (!swapOnMiss.isOn()) {
231
                swapTo(targetSlot.getInt() - 1);
232
            }
233
            return;
234
        }
235
        if (event.getTarget() instanceof LivingEntity target) {
236
            swapTo(bestSlot(target));
237
        }
238
    }
239
240
    @Subscribe
241
    private void onTick(TickEvent event) {
242
        if (!inGame() || !slots.isHolding()) {
243
            return;
244
        }
245
        if (!swapBack.isOn()) {
246
            slots.forget();
247
            return;
248
        }
249
        if (timer > 0) {
250
            timer--;
251
            return;
252
        }
253
        slots.restore();
254
    }
255
256
    private boolean canSwap() {
257
        if (!inGame() || mc.player.isSpectator() || slots.isHolding()) {
258
            return false;
259
        }
260
        if (onlyWithKillAura.isOn() && !Modules.enabled(KillAura.class)) {
261
            return false;
262
        }
263
        return !onlyOnWeapon.isOn() || allowedWeapon(mc.player.getMainHandItem());
264
    }
265
266
    private boolean allowedWeapon(ItemStack held) {
267
        return sword.isOn() && held.is(ItemTags.SWORDS)
268
            || axe.isOn() && held.is(ItemTags.AXES)
269
            || pickaxe.isOn() && held.is(ItemTags.PICKAXES)
270
            || shovel.isOn() && held.is(ItemTags.SHOVELS)
271
            || hoe.isOn() && held.is(ItemTags.HOES)
272
            || mace.isOn() && held.getItem() instanceof MaceItem
273
            || trident.isOn() && held.getItem() instanceof TridentItem;
274
    }
275
276
    // The slot packet leaves before the attack packet.
277
    private void swapTo(int slot) {
278
        if (slot < 0 || slot >= InventoryUtil.HOTBAR_SIZE || slot == InventoryUtil.selectedSlot()) {
279
            return;
280
        }
281
        slots.select(slot);
282
        timer = swapBackDelay.getInt();
283
    }
284
285
    // The first spear in the hotbar that fits. A lunge spear is asked for or avoided.
286
    private int spearSlot(boolean wantLunge) {
287
        for (int i = 0; i < InventoryUtil.HOTBAR_SIZE; i++) {
288
            ItemStack stack = mc.player.getInventory().getItem(i);
289
            if (i == InventoryUtil.selectedSlot() || !stack.is(ItemTags.SPEARS) || skipped(stack)) {
290
                continue;
291
            }
292
            boolean hasLunge = ItemUtil.enchantLevel(Enchantments.LUNGE, stack) > 0;
293
            if (wantLunge ? hasLunge : !(keepLungeSpear.isOn() && hasLunge)) {
294
                return i;
295
            }
296
        }
297
        return -1;
298
    }
299
300
    // The nearest entity a spear thrust along the crosshair would touch.
301
    private Entity spearTarget() {
302
        Vec3 start = mc.player.getEyePosition();
303
        Vec3 look = mc.player.getViewVector(1);
304
        Vec3 end = start.add(look.scale(SPEAR_LOOK));
305
        AABB sweep = mc.player.getBoundingBox().expandTowards(look.scale(SPEAR_LOOK)).inflate(1);
306
        Entity best = null;
307
        double bestDistance = SPEAR_LOOK * SPEAR_LOOK;
308
        for (Entity entity : mc.level.getEntities(mc.player, sweep,
309
            other -> !other.isSpectator() && other.isPickable())) {
310
            if (entity.getBoundingBox().inflate(SPEAR_MARGIN).clip(start, end).isEmpty()) {
311
                continue;
312
            }
313
            double distance = start.distanceToSqr(entity.position());
314
            if (distance < bestDistance) {
315
                bestDistance = distance;
316
                best = entity;
317
            }
318
        }
319
        return best;
320
    }
321
322
    private boolean skipped(ItemStack stack) {
323
        return antiBreak.isOn() && ItemUtil.nearlyBroken(stack);
324
    }
325
326
    // The hotbar slot scoring best against the target or minus one to stay put.
327
    private int bestSlot(LivingEntity target) {
328
        ItemStack held = mc.player.getMainHandItem();
329
        if (shieldBreaker.isOn() && target.isBlocking() && !held.is(ItemTags.AXES)) {
330
            int axeSlot = AutoWeapon.bestAxeSlot(target, antiBreak.isOn());
331
            if (axeSlot != -1) {
332
                return axeSlot;
333
            }
334
        }
335
        int selected = InventoryUtil.selectedSlot();
336
        double bestScore = score(held, target) + minGain.getValue();
337
        int best = -1;
338
        for (int i = 0; i < InventoryUtil.HOTBAR_SIZE; i++) {
339
            ItemStack stack = mc.player.getInventory().getItem(i);
340
            if (i == selected || skipped(stack) || stack.isEmpty() && !durabilitySaver.isOn()) {
341
                continue;
342
            }
343
            double score = score(stack, target);
344
            if (score > bestScore) {
345
                bestScore = score;
346
                best = i;
347
            }
348
        }
349
        return best;
350
    }
351
352
    // Points for one item. Real damage counts one point a heart and the rest are bonuses.
353
    private double score(ItemStack stack, LivingEntity target) {
354
        double score = durabilitySaver.isOn() ? durabilityScore(stack) : 0;
355
        if (stack.isEmpty()) {
356
            return score;
357
        }
358
        score += ItemUtil.attributeValue(stack, Attributes.ATTACK_DAMAGE, EquipmentSlot.MAINHAND);
359
        if (swords.isOn()) {
360
            score += swordScore(stack, target);
361
        }
362
        if (maces.isOn()) {
363
            score += maceScore(stack, target);
364
        }
365
        if (others.isOn() && impaling.isOn()
366
            && EntityUtil.typeIs(target, EntityTypeTags.SENSITIVE_TO_IMPALING)) {
367
            score += 2.5 * level(Enchantments.IMPALING, stack);
368
        }
369
        return score;
370
    }
371
372
    // An item that cannot wear out is a free hit. Unbreaking is a small nudge.
373
    private double durabilityScore(ItemStack stack) {
374
        if (!stack.isDamageableItem()) {
375
            return 1.5;
376
        }
377
        return 0.1 * level(Enchantments.UNBREAKING, stack);
378
    }
379
380
    private double swordScore(ItemStack stack, LivingEntity target) {
381
        double score = 0;
382
        boolean burning = target.isOnFire();
383
        if (fireAspect.isOn() && !burning && !fireProof(target)) {
384
            score += 4 * level(Enchantments.FIRE_ASPECT, stack);
385
        }
386
        if (looting.isOn() && !(target instanceof Player)) {
387
            boolean nearlyDead = target.getHealth() < NEARLY_DEAD || burning;
388
            score += (nearlyDead ? 4 : 2) * level(Enchantments.LOOTING, stack);
389
        }
390
        if (sharpness.isOn()) {
391
            int sharp = level(Enchantments.SHARPNESS, stack);
392
            score += sharp > 0 ? 0.5 * sharp + 0.5 : 0;
393
        }
394
        if (smite.isOn() && EntityUtil.typeIs(target, EntityTypeTags.SENSITIVE_TO_SMITE)) {
395
            score += 2.5 * level(Enchantments.SMITE, stack);
396
        }
397
        if (bane.isOn() && EntityUtil.typeIs(target, EntityTypeTags.SENSITIVE_TO_BANE_OF_ARTHROPODS)) {
398
            score += 2.5 * level(Enchantments.BANE_OF_ARTHROPODS, stack);
399
        }
400
        if (sweeping.isOn()) {
401
            score += level(Enchantments.SWEEPING_EDGE, stack);
402
        }
403
        return score;
404
    }
405
406
    // A mace only earns anything mid fall apart from Breach which works on the ground too.
407
    private double maceScore(ItemStack stack, LivingEntity target) {
408
        double score = 0;
409
        double armor = target.getAttributeValue(Attributes.ARMOR);
410
        if (breach.isOn() && armor > 0) {
411
            score += 0.15 * armor * level(Enchantments.BREACH, stack);
412
        }
413
        double fall = mc.player.fallDistance;
414
        if (fall <= SMASH_FALL) {
415
            return score;
416
        }
417
        if (regularMace.isOn() && stack.getItem() instanceof MaceItem) {
418
            score += smashBonus(fall);
419
        }
420
        if (density.isOn()) {
421
            score += 0.5 * fall * level(Enchantments.DENSITY, stack);
422
        }
423
        if (windBurst.isOn()) {
424
            score += 3 * level(Enchantments.WIND_BURST, stack);
425
        }
426
        return score;
427
    }
428
429
    // The vanilla smash bonus. Four a block to three then two to eight then one.
430
    private static double smashBonus(double fall) {
431
        if (fall <= 3) {
432
            return 4 * fall;
433
        }
434
        if (fall <= 8) {
435
            return 12 + 2 * (fall - 3);
436
        }
437
        return 22 + (fall - 8);
438
    }
439
440
    // Fire Resistance or any Fire Protection makes Fire Aspect a waste.
441
    private static boolean fireProof(LivingEntity target) {
442
        if (target.hasEffect(MobEffects.FIRE_RESISTANCE)) {
443
            return true;
444
        }
445
        for (EquipmentSlot slot : ItemUtil.ARMOR_SLOTS) {
446
            if (level(Enchantments.FIRE_PROTECTION, target.getItemBySlot(slot)) > 0) {
447
                return true;
448
            }
449
        }
450
        return false;
451
    }
452
453
    private static int level(ResourceKey<Enchantment> enchantment, ItemStack stack) {
454
        return ItemUtil.enchantLevel(enchantment, stack);
455
    }
456
}
457
CombatantCOMBATsrc/main/java/combatant/client/features/module/modules/combat/AttributeSwap.javaJava · 1,923 lines · 76.1 KB
SettingsattributeSwapActionsattributeSwapProtocolHeuristicsattributeSwapSearchattributeSwapBestDamageWeaponModeattributeSwapOnlyPlayersattributeSwapMinFallDistanceattributeSwapRestoreItemattributeSwapAutoElytraCycleattributeSwapAutoGlideAfterRestoreattributeSwapAutoGlideDelayattributeSwapMinDownVelocityattributeSwapMinApproachSpeedattributeSwapPredictionTicksattributeSwapMaxPredictedHorizontalDistanceattributeSwapElytraCycleTimeoutattributeSwapWindBurstSafetyattributeSwapWindBurstMinRemainingHealthattributeSwapWindBurstStrictElytraattributeSwapWindBurstDebugLog
AttributeSwap.javaJava · Minecraft 26.2 · 1,923 lines · 76.1 KB · complete file, verbatimOriginal ↗
1
/*
2
 * This file is part of the Combatant Client distribution.
3
 * Copyright (c) 2026 pivosos2007.
4
 *
5
 * Licensed under the GNU General Public License v3.0.
6
 */
7
8
package combatant.client.features.module.modules.combat;
9
10
import net.minecraft.client.Minecraft;
11
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
12
import net.minecraft.client.player.LocalPlayer;
13
import net.minecraft.core.BlockPos;
14
import net.minecraft.core.Direction;
15
import net.minecraft.core.Holder;
16
import net.minecraft.core.component.DataComponents;
17
import net.minecraft.core.registries.BuiltInRegistries;
18
import net.minecraft.core.registries.Registries;
19
import net.minecraft.network.protocol.game.ServerboundPlayerCommandPacket;
20
import net.minecraft.util.Mth;
21
import net.minecraft.world.effect.MobEffectInstance;
22
import net.minecraft.world.effect.MobEffects;
23
import net.minecraft.world.entity.Entity;
24
import net.minecraft.world.entity.EquipmentSlot;
25
import net.minecraft.world.entity.EquipmentSlotGroup;
26
import net.minecraft.world.entity.LivingEntity;
27
import net.minecraft.world.entity.ai.attributes.Attribute;
28
import net.minecraft.world.entity.ai.attributes.AttributeModifier;
29
import net.minecraft.world.entity.ai.attributes.Attributes;
30
import net.minecraft.world.entity.player.Player;
31
import net.minecraft.world.item.ItemStack;
32
import net.minecraft.world.item.Items;
33
import net.minecraft.world.item.enchantment.Enchantment;
34
import net.minecraft.world.item.enchantment.EnchantmentHelper;
35
import net.minecraft.world.item.enchantment.Enchantments;
36
import net.minecraft.world.item.equipment.Equippable;
37
import net.minecraft.world.level.ClipContext;
38
import net.minecraft.world.level.block.Blocks;
39
import net.minecraft.world.level.block.PointedDripstoneBlock;
40
import net.minecraft.world.level.block.state.BlockState;
41
import net.minecraft.world.level.block.state.properties.SpeleothemThickness;
42
import net.minecraft.world.phys.AABB;
43
import net.minecraft.world.phys.EntityHitResult;
44
import net.minecraft.world.phys.HitResult;
45
import net.minecraft.world.phys.Vec3;
46
import combatant.client.config.common.CommonSettingSchemas;
47
import combatant.client.config.values.BooleanMapValue;
48
import combatant.client.config.values.BooleanValue;
49
import combatant.client.config.values.EnumValue;
50
import combatant.client.config.values.ModeValue;
51
import combatant.client.config.values.NumberValue;
52
import combatant.client.events.EventHandler;
53
import combatant.client.events.impl.EventSync;
54
import combatant.client.features.module.Module;
55
import combatant.client.features.module.ModuleCategory;
56
import combatant.client.features.module.ModuleInfo;
57
import combatant.client.features.module.Modules;
58
import combatant.client.features.module.modules.movement.NoFall;
59
import combatant.client.features.module.modules.player.AutoTotem;
60
import combatant.client.mixins.accessors.PlayerInventoryAccessor;
61
import combatant.client.util.combat.AttackUtil;
62
import combatant.client.util.combat.protocol.CombatProtocolHeuristics;
63
import combatant.client.util.logging.DebugLog;
64
import combatant.client.util.player.ResetAttackCooldown;
65
import combatant.client.util.player.inventory.InventorySwap;
66
import combatant.client.util.player.simulation.PlayerSimulationCache;
67
import combatant.client.util.combat.protocol.ProtocolUtil;
68
69
import java.util.LinkedHashMap;
70
import java.util.Map;
71
import java.util.concurrent.ThreadLocalRandom;
72
73
//todo Description
74
@ModuleInfo(
75
        id = "attributeswap",
76
        displayName = "AttributeSwap",
77
        category = ModuleCategory.COMBAT
78
)
79
public class AttributeSwap extends Module {
80
81
    private static final int HOTBAR_RESET_TICKS = 0;
82
    private static final double MIN_MEANINGFUL_MACE_FALL_DISTANCE = 1.6;
83
    private static final long FAST_AURA_MACE_DELAY_MIN_MS = 140L;
84
    private static final long FAST_AURA_MACE_DELAY_MAX_MS = 230L;
85
    private static final int CHEST_SCREEN_SLOT = 6;
86
    private static final int CYCLE_NONE = 0;
87
    private static final int CYCLE_WAIT_NORMAL_ATTACK = 1;
88
    private static final int CYCLE_WAIT_MACE_SYNC = 2;
89
    private static final int CYCLE_WAIT_ELYTRA_RESTORE = 3;
90
    private static final int WIND_BURST_ABSORPTION_MIN_TICKS = 200;
91
    private static final int WIND_BURST_PREDICTION_TICKS = 140;
92
    private static final double WIND_BURST_EXPLOSION_RADIUS = 3.5;
93
    private static final double WIND_BURST_SWEEP_MARGIN = 0.04;
94
    private static final String ACTION_SHIELD_BREAKER = "shield_breaker";
95
    private static final String ACTION_HEIGHT_MACE = "height_mace";
96
    private static final String ACTION_BEST_DAMAGE_WEAPON = "best_damage_weapon";
97
    private final Minecraft mc = Minecraft.getInstance();
98
    private final BooleanMapValue actions =
99
            group(
100
                    "attributeSwapActions",
101
                    "actions",
102
                    actionDefaults()
103
            );
104
    private final BooleanMapValue protocolHeuristicSources =
105
            group(
106
                    "attributeSwapProtocolHeuristics",
107
                    "protocol_heuristics",
108
                    CombatProtocolHeuristics.defaultSourceToggles()
109
            );
110
    private final ModeValue searchMode =
111
            visibleWhen(modeCommon(
112
                    "attributeSwapSearch",
113
                    "search_scope",
114
                    CommonSettingSchemas.INVENTORY_SEARCH_SCOPE,
115
                    "HOTBAR",
116
                    "HOTBAR",
117
                    "INVENTORY"
118
            ), this::isHeightMaceEnabled);
119
    private final EnumValue<BestDamageWeaponMode> bestDamageWeaponMode =
120
            visibleWhen(enumSetting(
121
                    "attributeSwapBestDamageWeaponMode",
122
                    "best_damage_weapon_mode",
123
                    BestDamageWeaponMode.BOTH,
124
                    BestDamageWeaponMode.values()
125
            ), this::isBestDamageWeaponEnabled);
126
    private final BooleanValue onlyPlayers =
127
            boolCommon(
128
                    "attributeSwapOnlyPlayers",
129
                    "only_players",
130
                    CommonSettingSchemas.COMBAT_ONLY_PLAYERS,
131
                    true
132
            );
133
    private final NumberValue<Double> minFallDistance =
134
            visibleWhen(numCommon(
135
                    "attributeSwapMinFallDistance",
136
                    "min_fall_distance",
137
                    CommonSettingSchemas.COMBAT_MIN_FALL_DISTANCE,
138
                    2.0,
139
                    MIN_MEANINGFUL_MACE_FALL_DISTANCE,
140
                    20.0
141
            ), this::isHeightMaceEnabled);
142
    private final BooleanValue restoreItem =
143
            boolCommon(
144
                    "attributeSwapRestoreItem",
145
                    "restore_item",
146
                    CommonSettingSchemas.INVENTORY_RESTORE_ITEM,
147
                    true
148
            );
149
    private final BooleanValue autoElytraCycle =
150
            visibleWhen(bool(
151
                    "attributeSwapAutoElytraCycle",
152
                    "auto_elytra_cycle",
153
                    true
154
            ), this::isHeightMaceEnabled);
155
    private final BooleanValue autoGlideAfterRestore =
156
            visibleWhen(bool(
157
                    "attributeSwapAutoGlideAfterRestore",
158
                    "auto_glide_after_restore",
159
                    false
160
            ), this::isAutoElytraCycleEnabled);
161
    private final NumberValue<Integer> autoGlideDelay =
162
            visibleWhen(num(
163
                    "attributeSwapAutoGlideDelay",
164
                    "auto_glide_delay",
165
                    2,
166
                    1,
167
                    10
168
            ), () -> isAutoElytraCycleEnabled() && autoGlideAfterRestore.get());
169
    private final NumberValue<Double> minDownVelocity =
170
            visibleWhen(num(
171
                    "attributeSwapMinDownVelocity",
172
                    "min_down_velocity",
173
                    0.08,
174
                    0.01,
175
                    1.0
176
            ), this::isAutoElytraCycleEnabled);
177
    private final NumberValue<Double> minApproachSpeed =
178
            visibleWhen(num(
179
                    "attributeSwapMinApproachSpeed",
180
                    "min_approach_speed",
181
                    0.25,
182
                    0.0,
183
                    3.0
184
            ), this::isAutoElytraCycleEnabled);
185
    private final NumberValue<Integer> predictionTicks =
186
            visibleWhen(num(
187
                    "attributeSwapPredictionTicks",
188
                    "prediction_ticks",
189
                    8,
190
                    1,
191
                    20
192
            ), this::isAutoElytraCycleEnabled);
193
    private final NumberValue<Double> maxPredictedHorizontalDistance =
194
            visibleWhen(num(
195
                    "attributeSwapMaxPredictedHorizontalDistance",
196
                    "max_predicted_horizontal_distance",
197
                    4.5,
198
                    1.5,
199
                    8.0
200
            ), this::isAutoElytraCycleEnabled);
201
    private final NumberValue<Integer> elytraCycleTimeout =
202
            visibleWhen(num(
203
                    "attributeSwapElytraCycleTimeout",
204
                    "elytra_cycle_timeout",
205
                    5,
206
                    1,
207
                    12
208
            ), this::isAutoElytraCycleEnabled);
209
    private final BooleanValue windBurstSafety =
210
            visibleWhen(bool(
211
                    "attributeSwapWindBurstSafety",
212
                    "wind_burst_safety",
213
                    true
214
            ), this::isHeightMaceEnabled);
215
    private final NumberValue<Float> windBurstMinRemainingHealth =
216
            visibleWhen(num(
217
                    "attributeSwapWindBurstMinRemainingHealth",
218
                    "wind_burst_min_remaining_health",
219
                    6.0f,
220
                    0.5f,
221
                    40.0f
222
            ), this::isWindBurstSafetyEnabled);
223
    private final BooleanValue windBurstStrictElytra =
224
            visibleWhen(bool(
225
                    "attributeSwapWindBurstStrictElytra",
226
                    "wind_burst_strict_elytra",
227
                    false
228
            ), this::isWindBurstSafetyEnabled);
229
    private final BooleanValue windBurstDebugLog =
230
            visibleWhen(bool(
231
                    "attributeSwapWindBurstDebugLog",
232
                    "wind_burst_debug_log",
233
                    false
234
            ), this::isWindBurstSafetyEnabled);
235
    private int pendingTargetId = -1;
236
    private boolean pendingKeepSprint = false;
237
    private int pendingRestoreSyncId = -1;
238
    private int pendingRestoreFromScreenSlot = -1;
239
    private int pendingRestoreToScreenSlot = -1;
240
    private int pendingRestoreAge = -1;
241
    private boolean elytraCycleActive;
242
    private int elytraCycleTargetId = -1;
243
    private int elytraReturnInventorySlot = -1;
244
    private int elytraCycleExpireAge = -1;
245
    private int elytraCycleStage = CYCLE_NONE;
246
    private int elytraMaceAttackAge = -1;
247
    private int elytraRestoreAge = -1;
248
    private boolean elytraCycleKeepSprint;
249
    private boolean queuedRestoreGlide;
250
    private int restoreGlideAge = -1;
251
    private int restoreGlideExpireAge = -1;
252
    private long lastFastAuraMaceAttackMs;
253
    private long nextFastAuraMaceDelayMs = randomFastAuraMaceDelay();
254
    private boolean externalTargetBlocking = false;
255
    private int auraControlTicks = 0;
256
    private boolean attributeSwapSequence = false;
257
    private int lastAttributeSwapTargetId = -1;
258
    private int lastAttributeSwapAge = -1;
259
260
    private static Map<String, Boolean> actionDefaults() {
261
        LinkedHashMap<String, Boolean> defaults = new LinkedHashMap<>();
262
        defaults.put(ACTION_SHIELD_BREAKER, true);
263
        defaults.put(ACTION_HEIGHT_MACE, true);
264
        defaults.put(ACTION_BEST_DAMAGE_WEAPON, true);
265
        return defaults;
266
    }
267
268
    public static QueueResult queueAttackResult(LivingEntity target, boolean keepSprint) {
269
        AttributeSwap attributeSwap = Modules.get(AttributeSwap.class);
270
        return attributeSwap != null ? attributeSwap.queueAttack(target, keepSprint) : QueueResult.PASS;
271
    }
272
273
    public static boolean shouldBypassAuraCooldownFor(LocalPlayer player, LivingEntity target) {
274
        AttributeSwap attributeSwap = Modules.get(AttributeSwap.class);
275
        return attributeSwap != null && attributeSwap.shouldBypassAuraCooldown(player, target);
276
    }
277
278
    public static void afterNormalAttackIfActive(LivingEntity target, boolean keepSprint) {
279
        AttributeSwap attributeSwap = Modules.get(AttributeSwap.class);
280
        if (attributeSwap != null) {
281
            attributeSwap.afterNormalAttack(target, keepSprint);
282
        }
283
    }
284
285
    public static void handleAuraTarget(LivingEntity target, boolean breakShields) {
286
        AttributeSwap attributeSwap = Modules.get(AttributeSwap.class);
287
        if (attributeSwap == null || !attributeSwap.isEnabled()) return;
288
289
        attributeSwap.suppressCrosshairForAuraTick();
290
291
        if (breakShields && target instanceof Player player) {
292
            attributeSwap.handleExternalTarget(player);
293
        } else {
294
            attributeSwap.handleExternalTarget(null);
295
        }
296
    }
297
298
    public static void clearAuraControlIfActive() {
299
        AttributeSwap attributeSwap = Modules.get(AttributeSwap.class);
300
        if (attributeSwap != null) {
301
            attributeSwap.clearAuraControl();
302
        }
303
    }
304
305
    public static boolean tryBreakShieldPostAttack(LivingEntity target, boolean keepSprint, boolean enabled) {
306
        AttributeSwap attributeSwap = Modules.get(AttributeSwap.class);
307
        if (attributeSwap == null || !attributeSwap.isEnabled()) return false;
308
        return attributeSwap.tryPostAttackAttributeSwap(target, keepSprint, enabled);
309
    }
310
311
    public static boolean tryBreakShieldAfterClientAttack(Entity target) {
312
        AttributeSwap attributeSwap = Modules.get(AttributeSwap.class);
313
        if (attributeSwap == null || !attributeSwap.isEnabled() || attributeSwap.isAuraControlled()) return false;
314
        if (!(target instanceof LivingEntity)) return false;
315
316
        Minecraft mc = Minecraft.getInstance();
317
        if (!(mc.hitResult instanceof EntityHitResult ehr) || ehr.getEntity() != target) {
318
            return false;
319
        }
320
321
        return attributeSwap.tryAttributeSwapAfterClientAttack(target);
322
    }
323
324
    private static boolean isBlockingShieldTarget(LivingEntity target) {
325
        if (!(target instanceof Player player)) {
326
            return false;
327
        }
328
        return player.isBlocking() || isUsingShieldStatic(player);
329
    }
330
331
    private static boolean isUsingShieldStatic(Player target) {
332
        return target != null
333
                && target.isUsingItem()
334
                && target.getUseItem().is(Items.SHIELD);
335
    }
336
337
    private static AABB union(AABB a, AABB b) {
338
        return new AABB(
339
                Math.min(a.minX, b.minX),
340
                Math.min(a.minY, b.minY),
341
                Math.min(a.minZ, b.minZ),
342
                Math.max(a.maxX, b.maxX),
343
                Math.max(a.maxY, b.maxY),
344
                Math.max(a.maxZ, b.maxZ)
345
        );
346
    }
347
348
    private static double lerp(double delta, double start, double end) {
349
        return start + delta * (end - start);
350
    }
351
352
    private static String format3(double value) {
353
        return String.format(java.util.Locale.ROOT, "%.3f", value);
354
    }
355
356
    private static long randomFastAuraMaceDelay() {
357
        return ThreadLocalRandom.current().nextLong(
358
                FAST_AURA_MACE_DELAY_MIN_MS,
359
                FAST_AURA_MACE_DELAY_MAX_MS + 1
360
        );
361
    }
362
363
    private boolean isActionEnabled(String action) {
364
        return actions.get(action);
365
    }
366
367
    private boolean isHeightMaceEnabled() {
368
        return isActionEnabled(ACTION_HEIGHT_MACE);
369
    }
370
371
    private boolean isBestDamageWeaponEnabled() {
372
        return isActionEnabled(ACTION_BEST_DAMAGE_WEAPON);
373
    }
374
375
    private boolean shouldUseBestDamageWeaponForAura() {
376
        return isBestDamageWeaponEnabled() && bestDamageWeaponMode.get().usesAura();
377
    }
378
379
    private boolean shouldUseBestDamageWeaponForNextHit() {
380
        return isBestDamageWeaponEnabled() && bestDamageWeaponMode.get().usesNextHit();
381
    }
382
383
    private boolean isAutoElytraCycleEnabled() {
384
        return isHeightMaceEnabled() && autoElytraCycle.get();
385
    }
386
387
    private boolean isWindBurstSafetyEnabled() {
388
        return isHeightMaceEnabled() && windBurstSafety.get();
389
    }
390
391
    @Override
392
    public void onDisable() {
393
        pendingTargetId = -1;
394
        pendingKeepSprint = false;
395
        clearPendingRestore();
396
        restoreElytraIfNeeded();
397
        clearRestoreGlide();
398
        clearAuraControl();
399
        clearAttributeSwapSequence();
400
        InventorySwap.INSTANCE.releaseHotbar(this);
401
    }
402
403
    @Override
404
    public void onTick() {
405
        if (isEnabled()) {
406
            InventorySwap.INSTANCE.tick();
407
            flushPendingRestore();
408
            tickElytraCycle();
409
            tickRestoreGlide();
410
            tickAuraControl();
411
            externalTargetBlocking = false;
412
        }
413
    }
414
415
    public QueueResult queueAttack(LivingEntity target, boolean keepSprint) {
416
        if (!isEnabled()) return QueueResult.PASS;
417
        if (mc.player == null || mc.gameMode == null || mc.level == null) return QueueResult.PASS;
418
        if (!isValidTarget(target)) return QueueResult.PASS;
419
420
        if (elytraCycleActive) {
421
            if (elytraCycleTargetId != target.getId()) {
422
                restoreElytraIfNeeded();
423
                return QueueResult.PASS;
424
            }
425
426
            elytraCycleKeepSprint = keepSprint;
427
            return elytraCycleStage == CYCLE_WAIT_MACE_SYNC
428
                    ? QueueResult.SUPPRESS
429
                    : QueueResult.PASS;
430
        }
431
432
433
        if (isBlockingShieldTarget(target)) {
434
            return QueueResult.PASS;
435
        }
436
437
        if (isHeightMaceEnabled()) {
438
            int maceSlot = findDesiredMaceSlot(mc.player, target);
439
            if (maceSlot != -1) {
440
                if (tryStartElytraCycle(mc.player, target, keepSprint)) {
441
                    return QueueResult.PASS;
442
                }
443
444
                boolean fastAuraMace = shouldBypassAuraCooldown(mc.player, target, maceSlot);
445
                if (fastAuraMace && maceSlot < 9) {
446
                    return attackWithLeasedHotbar(mc.player, target, keepSprint, maceSlot)
447
                            ? QueueResult.HANDLE
448
                            : QueueResult.SUPPRESS;
449
                }
450
451
                if (!canAttackNow(mc.player)) return QueueResult.PASS;
452
453
                queuePendingMaceAttack(target, keepSprint);
454
                return QueueResult.HANDLE;
455
            }
456
        }
457
458
        return tryBestDamageWeaponForAura(target, keepSprint);
459
    }
460
461
    public boolean shouldBypassAuraCooldown(LocalPlayer player, LivingEntity target) {
462
        int maceSlot = findDesiredHotbarMaceSlot(player, target);
463
        return shouldBypassAuraCooldown(player, target, maceSlot);
464
    }
465
466
    private void queuePendingMaceAttack(LivingEntity target, boolean keepSprint) {
467
        pendingTargetId = target.getId();
468
        pendingKeepSprint = keepSprint;
469
    }
470
471
    @EventHandler(priority = -2000)
472
    private void onSync(EventSync event) {
473
        flushPendingRestore();
474
        if (!isEnabled()) return;
475
        tickElytraCycleSync();
476
        tickRestoreGlideSync();
477
        if (pendingTargetId == -1) return;
478
479
        LocalPlayer player = mc.player;
480
        MultiPlayerGameMode manager = mc.gameMode;
481
        int targetId = pendingTargetId;
482
        boolean keepSprint = pendingKeepSprint;
483
        pendingTargetId = -1;
484
        pendingKeepSprint = false;
485
        if (player == null || manager == null || mc.level == null) return;
486
        if (player.isUsingItem()) return;
487
488
        Entity entity = mc.level.getEntity(targetId);
489
        if (!(entity instanceof LivingEntity target) || !isValidTarget(target)) return;
490
491
        int maceSlot = findDesiredMaceSlot(player, target);
492
        if (maceSlot == -1) return;
493
494
        if (maceSlot < 9) {
495
            attackWithLeasedHotbar(player, target, keepSprint, maceSlot);
496
            return;
497
        }
498
499
        PlayerInventoryAccessor inv = (PlayerInventoryAccessor) player.getInventory();
500
        int selectedSlot = inv.combatant$getSelectedSlot();
501
        int syncId = player.inventoryMenu != null ? player.inventoryMenu.containerId : -1;
502
        int maceScreenSlot = InventorySwap.mapInventoryToScreenSlot(maceSlot);
503
        int selectedScreenSlot = InventorySwap.mapHotbarToScreenSlot(selectedSlot);
504
        boolean needsSwap = maceScreenSlot != selectedScreenSlot;
505
        if (needsSwap) {
506
            if (syncId < 0) return;
507
            InventorySwap.INSTANCE.swapScreenSlots(maceScreenSlot, selectedScreenSlot);
508
        }
509
        try {
510
            if (!AttackUtil.attackCurrentItem(mc, target, keepSprint)) return;
511
            ResetAttackCooldown.resetAttackCooldown(player);
512
            restoreElytraIfNeeded();
513
        } finally {
514
            if (needsSwap && restoreItem.get()) {
515
                schedulePendingRestore(player.tickCount, syncId, maceScreenSlot, selectedScreenSlot);
516
            }
517
        }
518
    }
519
520
    private boolean attackWithLeasedHotbar(LocalPlayer player,
521
                                           LivingEntity target,
522
                                           boolean keepSprint,
523
                                           int hotbarSlot) {
524
        return attackWithLeasedHotbar(player, target, keepSprint, hotbarSlot, true);
525
    }
526
527
    private boolean attackWithLeasedHotbar(LocalPlayer player,
528
                                           LivingEntity target,
529
                                           boolean keepSprint,
530
                                           int hotbarSlot,
531
                                           boolean updateFastMaceDelay) {
532
        int resetTicks = restoreItem.get() ? 1 : HOTBAR_RESET_TICKS;
533
        if (!InventorySwap.INSTANCE.leaseHotbar(this, hotbarSlot, resetTicks)) return false;
534
        if (!AttackUtil.attackCurrentItem(mc, target, keepSprint)) return false;
535
        ResetAttackCooldown.resetAttackCooldown(player);
536
        if (updateFastMaceDelay) {
537
            lastFastAuraMaceAttackMs = System.currentTimeMillis();
538
            nextFastAuraMaceDelayMs = randomFastAuraMaceDelay();
539
        }
540
        return true;
541
    }
542
543
    private boolean attackWithAttributeHotbar(LocalPlayer player,
544
                                              LivingEntity target,
545
                                              boolean keepSprint,
546
                                              int hotbarSlot) {
547
        if (player == null || target == null || !InventorySwap.INSTANCE.leaseHotbar(this, hotbarSlot, 0)) {
548
            return false;
549
        }
550
551
        attributeSwapSequence = true;
552
        lastAttributeSwapTargetId = target.getId();
553
        lastAttributeSwapAge = player.tickCount;
554
        try {
555
            if (!AttackUtil.attackCurrentItem(mc, target, keepSprint)) return false;
556
            ResetAttackCooldown.resetAttackCooldown(player);
557
            return true;
558
        } finally {
559
            attributeSwapSequence = false;
560
            InventorySwap.INSTANCE.releaseHotbar(this);
561
        }
562
    }
563
564
    private boolean wasAttributeSwapUsedThisTick(LivingEntity target) {
565
        LocalPlayer player = mc.player;
566
        return player != null
567
                && target != null
568
                && lastAttributeSwapTargetId == target.getId()
569
                && lastAttributeSwapAge == player.tickCount;
570
    }
571
572
    private void clearAttributeSwapSequence() {
573
        attributeSwapSequence = false;
574
        lastAttributeSwapTargetId = -1;
575
        lastAttributeSwapAge = -1;
576
    }
577
578
    private void tickAuraControl() {
579
        if (auraControlTicks > 0) {
580
            auraControlTicks--;
581
        }
582
    }
583
584
    public void afterNormalAttack(LivingEntity target, boolean keepSprint) {
585
        if (!isEnabled()) return;
586
        if (!elytraCycleActive) {
587
            return;
588
        }
589
        if (target == null || target.getId() != elytraCycleTargetId) return;
590
        if (elytraCycleStage != CYCLE_WAIT_NORMAL_ATTACK) return;
591
592
        LocalPlayer player = mc.player;
593
        if (player == null) return;
594
        if (!isValidTarget(target) || target.getHealth() <= 0.0f) {
595
            restoreElytraIfNeeded();
596
            return;
597
        }
598
        elytraCycleKeepSprint = keepSprint;
599
        elytraCycleStage = CYCLE_WAIT_MACE_SYNC;
600
        elytraMaceAttackAge = player.tickCount + 1;
601
    }
602
603
    public void suppressCrosshairForAuraTick() {
604
        auraControlTicks = 2;
605
    }
606
607
    public boolean isAuraControlled() {
608
        return auraControlTicks > 0;
609
    }
610
611
    public void clearAuraControl() {
612
        auraControlTicks = 0;
613
        externalTargetBlocking = false;
614
    }
615
616
    public void handleExternalTarget(Player target) {
617
        if (!isEnabled() || mc.player == null) return;
618
619
        auraControlTicks = 2;
620
        externalTargetBlocking = isUsingShield(target);
621
    }
622
623
    public boolean tryPostAttackAttributeSwap(LivingEntity target, boolean keepSprint, boolean allowShieldBreak) {
624
        if (!isEnabled()) return false;
625
        suppressCrosshairForAuraTick();
626
627
        return allowShieldBreak && target instanceof Player player && tryBreakShield(player, keepSprint);
628
    }
629
630
    public boolean tryAttributeSwapAfterClientAttack(Entity target) {
631
        if (!isEnabled() || isAuraControlled()) return false;
632
        if (!(target instanceof LivingEntity living)) return false;
633
        if (!(mc.hitResult instanceof EntityHitResult ehr) || ehr.getEntity() != target) {
634
            return false;
635
        }
636
637
        return tryPostAttackAttributeSwap(living, false, true);
638
    }
639
640
    public boolean tryBreakShield(Player target, boolean keepSprint) {
641
        if (!isActionEnabled(ACTION_SHIELD_BREAKER)) return false;
642
        if (attributeSwapSequence) return false;
643
        if (mc.player == null || mc.gameMode == null) return false;
644
        if (target == null || !target.isAlive() || target.isRemoved()) return false;
645
        if (wasAttributeSwapUsedThisTick(target)) return false;
646
        if (!isUsingShield(target)) return false;
647
        if (!isShieldFacingPlayer(target)) return false;
648
649
        int axeSlot = findHotbarAxeSlot(mc.player);
650
        if (axeSlot == -1) return false;
651
652
        int selected = ((PlayerInventoryAccessor) mc.player.getInventory()).combatant$getSelectedSlot();
653
        if (axeSlot == selected && isAxe(mc.player.getMainHandItem())) return false;
654
655
        return attackWithAttributeHotbar(mc.player, target, keepSprint, axeSlot);
656
    }
657
658
    private boolean attackMaceNow(LocalPlayer player,
659
                                  LivingEntity target,
660
                                  boolean keepSprint,
661
                                  int maceSlot) {
662
        if (maceSlot < 9) {
663
            return attackWithLeasedHotbar(player, target, keepSprint, maceSlot);
664
        }
665
666
        if (player.inventoryMenu == null) return false;
667
668
        int selectedSlot = ((PlayerInventoryAccessor) player.getInventory()).combatant$getSelectedSlot();
669
        int syncId = player.inventoryMenu.containerId;
670
        int maceScreenSlot = InventorySwap.mapInventoryToScreenSlot(maceSlot);
671
        int selectedScreenSlot = InventorySwap.mapHotbarToScreenSlot(selectedSlot);
672
        boolean needsSwap = maceScreenSlot != selectedScreenSlot;
673
        if (needsSwap) {
674
            InventorySwap.INSTANCE.swapScreenSlots(maceScreenSlot, selectedScreenSlot);
675
        }
676
677
        try {
678
            if (!AttackUtil.attackCurrentItem(mc, target, keepSprint)) return false;
679
            ResetAttackCooldown.resetAttackCooldown(player);
680
            return true;
681
        } finally {
682
            if (needsSwap && restoreItem.get()) {
683
                schedulePendingRestore(player.tickCount, syncId, maceScreenSlot, selectedScreenSlot);
684
            }
685
        }
686
    }
687
688
    public boolean handleManualAttack() {
689
        if (!isEnabled()) {
690
            return false;
691
        }
692
693
        LocalPlayer player = mc.player;
694
        MultiPlayerGameMode manager = mc.gameMode;
695
        if (player == null || manager == null || mc.level == null) {
696
            return false;
697
        }
698
699
        LivingEntity target = resolveCrosshairTarget();
700
        if (!isValidTarget(target)) return false;
701
        if (isBlockingShieldTarget(target)) return false;
702
703
        if (isHeightMaceEnabled() && canAttackNow(player)) {
704
            int maceSlot = findDesiredMaceSlot(player, target);
705
            if (maceSlot != -1) {
706
                int selectedSlot = ((PlayerInventoryAccessor) player.getInventory()).combatant$getSelectedSlot();
707
                if (maceSlot == selectedSlot && player.getMainHandItem().is(Items.MACE)) {
708
                    return false;
709
                }
710
711
                if (maceSlot < 9) {
712
                    if (!InventorySwap.INSTANCE.leaseHotbar(this, maceSlot, HOTBAR_RESET_TICKS)) return false;
713
                    try {
714
                        if (!AttackUtil.attackCurrentItem(mc, target, false)) return false;
715
                        ResetAttackCooldown.resetAttackCooldown(player);
716
                        return true;
717
                    } finally {
718
                        if (restoreItem.get()) {
719
                            InventorySwap.INSTANCE.releaseHotbar(this);
720
                        }
721
                    }
722
                }
723
724
                if (player.inventoryMenu == null) {
725
                    return false;
726
                }
727
728
                int syncId = player.inventoryMenu.containerId;
729
                int maceScreenSlot = InventorySwap.mapInventoryToScreenSlot(maceSlot);
730
                int selectedScreenSlot = InventorySwap.mapHotbarToScreenSlot(selectedSlot);
731
                boolean needsSwap = maceScreenSlot != selectedScreenSlot;
732
                if (needsSwap) {
733
                    InventorySwap.INSTANCE.swapScreenSlots(maceScreenSlot, selectedScreenSlot);
734
                }
735
                try {
736
                    if (!AttackUtil.attackCurrentItem(mc, target, false)) return false;
737
                    ResetAttackCooldown.resetAttackCooldown(player);
738
                    return true;
739
                } finally {
740
                    if (needsSwap && restoreItem.get()) {
741
                        InventorySwap.INSTANCE.swapScreenSlots(maceScreenSlot, selectedScreenSlot);
742
                    }
743
                }
744
            }
745
        }
746
747
        BestWeaponPrepareResult bestWeaponPrepare = prepareBestDamageWeaponForNextHit(player, target);
748
        return bestWeaponPrepare == BestWeaponPrepareResult.FAILED;
749
    }
750
751
    private void schedulePendingRestore(int currentAge, int syncId, int fromScreenSlot, int toScreenSlot) {
752
        pendingRestoreSyncId = syncId;
753
        pendingRestoreFromScreenSlot = fromScreenSlot;
754
        pendingRestoreToScreenSlot = toScreenSlot;
755
        pendingRestoreAge = currentAge + 1;
756
    }
757
758
    private void flushPendingRestore() {
759
        if (pendingRestoreAge == -1) {
760
            return;
761
        }
762
763
        LocalPlayer player = mc.player;
764
        MultiPlayerGameMode manager = mc.gameMode;
765
        if (player == null || manager == null) {
766
            clearPendingRestore();
767
            return;
768
        }
769
770
        if (player.tickCount < pendingRestoreAge) {
771
            return;
772
        }
773
774
        InventorySwap.INSTANCE.swapScreenSlots(pendingRestoreFromScreenSlot, pendingRestoreToScreenSlot);
775
        clearPendingRestore();
776
    }
777
778
    private void clearPendingRestore() {
779
        pendingRestoreSyncId = -1;
780
        pendingRestoreFromScreenSlot = -1;
781
        pendingRestoreToScreenSlot = -1;
782
        pendingRestoreAge = -1;
783
    }
784
785
    private boolean tryStartElytraCycle(LocalPlayer player, LivingEntity target, boolean keepSprint) {
786
        if (!isAutoElytraCycleEnabled()) return false;
787
        if (elytraCycleActive) return false;
788
        if (player == null || target == null || player.inventoryMenu == null) return false;
789
        if (!player.isFallFlying()) return false;
790
        if (!player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) return false;
791
        if (player.getMainHandItem().is(Items.MACE)) return false;
792
        if (player.getAttackStrengthScale(0.5f) < 1.0f) return false;
793
        if (!isVectorFallingDown(player)) return false;
794
        if (!isHorizontallyMovingIntoTarget(player, target)) return false;
795
796
        int swapSlot = findElytraRemovalSlot(player);
797
        if (swapSlot == -1) return false;
798
799
        int invScreenSlot = InventorySwap.mapInventoryToScreenSlot(swapSlot);
800
        if (!InventorySwap.INSTANCE.swapScreenSlots(invScreenSlot, CHEST_SCREEN_SLOT)) return false;
801
802
        elytraCycleActive = true;
803
        elytraCycleTargetId = target.getId();
804
        elytraReturnInventorySlot = swapSlot;
805
        elytraCycleExpireAge = player.tickCount + elytraCycleTimeout.get();
806
        elytraCycleStage = CYCLE_WAIT_NORMAL_ATTACK;
807
        elytraMaceAttackAge = -1;
808
        elytraRestoreAge = -1;
809
        elytraCycleKeepSprint = keepSprint;
810
        return true;
811
    }
812
813
    private void tickElytraCycleSync() {
814
        if (!elytraCycleActive) return;
815
        if (elytraCycleStage != CYCLE_WAIT_MACE_SYNC) return;
816
817
        LocalPlayer player = mc.player;
818
        if (player == null || mc.level == null) {
819
            clearElytraCycle();
820
            return;
821
        }
822
823
        if (player.tickCount < elytraMaceAttackAge) return;
824
825
        Entity entity = mc.level.getEntity(elytraCycleTargetId);
826
        if (!(entity instanceof LivingEntity target) || !isValidTarget(target) || target.getHealth() <= 0.0f) {
827
            restoreElytraIfNeeded();
828
            return;
829
        }
830
831
        int maceSlot = findDesiredMaceSlot(player, target);
832
        if (maceSlot == -1) {
833
            restoreElytraIfNeeded();
834
            return;
835
        }
836
837
        if (!attackMaceNow(player, target, elytraCycleKeepSprint, maceSlot)) {
838
            restoreElytraIfNeeded();
839
            return;
840
        }
841
842
        elytraCycleStage = CYCLE_WAIT_ELYTRA_RESTORE;
843
        elytraRestoreAge = player.tickCount + (maceSlot < 9 || !restoreItem.get() ? 1 : 2);
844
    }
845
846
    private void tickElytraCycle() {
847
        if (!elytraCycleActive) return;
848
849
        LocalPlayer player = mc.player;
850
        if (player == null || mc.level == null) {
851
            clearElytraCycle();
852
            return;
853
        }
854
855
        Entity entity = mc.level.getEntity(elytraCycleTargetId);
856
        boolean expired = elytraCycleExpireAge >= 0 && player.tickCount >= elytraCycleExpireAge;
857
        if (expired || !(entity instanceof LivingEntity living) || !isValidTarget(living)) {
858
            restoreElytraIfNeeded();
859
            return;
860
        }
861
862
        if (elytraCycleStage == CYCLE_WAIT_ELYTRA_RESTORE && player.tickCount >= elytraRestoreAge) {
863
            restoreElytraIfNeeded();
864
        }
865
    }
866
867
    private void restoreElytraIfNeeded() {
868
        if (!elytraCycleActive) return;
869
870
        LocalPlayer player = mc.player;
871
        if (player == null || player.inventoryMenu == null) {
872
            clearElytraCycle();
873
            return;
874
        }
875
876
        boolean restored = false;
877
        if (player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) {
878
            restored = true;
879
        } else if (elytraReturnInventorySlot >= 0 && elytraReturnInventorySlot < 36
880
                && player.getInventory().getItem(elytraReturnInventorySlot).is(Items.ELYTRA)) {
881
            restored = InventorySwap.INSTANCE.swapScreenSlots(
882
                    InventorySwap.mapInventoryToScreenSlot(elytraReturnInventorySlot),
883
                    CHEST_SCREEN_SLOT
884
            );
885
        }
886
887
        if (restored) {
888
            queueRestoreGlide(player);
889
            clearElytraCycle();
890
            return;
891
        }
892
893
        clearElytraCycle();
894
    }
895
896
    private void queueRestoreGlide(LocalPlayer player) {
897
        if (!autoGlideAfterRestore.get()) return;
898
        if (player == null) return;
899
        if (player.isFallFlying()) return;
900
        if (player.isPassenger()) return;
901
        if (player.getAbilities().flying) return;
902
        if (player.onGround() || player.isInWater() || player.isInLava()) return;
903
904
        int delay = Math.max(1, autoGlideDelay.get());
905
        queuedRestoreGlide = true;
906
        restoreGlideAge = player.tickCount + delay;
907
        restoreGlideExpireAge = player.tickCount + delay + 10;
908
    }
909
910
    private void tickRestoreGlide() {
911
        if (!queuedRestoreGlide) return;
912
913
        LocalPlayer player = mc.player;
914
        if (player == null || player.isFallFlying()) {
915
            clearRestoreGlide();
916
            return;
917
        }
918
919
        if (restoreGlideExpireAge >= 0 && player.tickCount > restoreGlideExpireAge) {
920
            clearRestoreGlide();
921
            return;
922
        }
923
924
        if (player.tickCount < restoreGlideAge) {
925
            return;
926
        }
927
928
        if (!canStartRestoreGlide(player)) {
929
            clearRestoreGlide();
930
        }
931
    }
932
933
    private void tickRestoreGlideSync() {
934
        if (!queuedRestoreGlide) return;
935
936
        LocalPlayer player = mc.player;
937
        if (player == null) {
938
            clearRestoreGlide();
939
            return;
940
        }
941
942
        if (player.tickCount < restoreGlideAge) return;
943
        if (player.isFallFlying()) {
944
            clearRestoreGlide();
945
            return;
946
        }
947
948
        if (!canStartRestoreGlide(player)) {
949
            clearRestoreGlide();
950
            return;
951
        }
952
953
        if (player.getDeltaMovement().y > 0.0) {
954
            restoreGlideAge = player.tickCount + 1;
955
            return;
956
        }
957
958
        if (mc.getConnection() == null) return;
959
960
        if (player.tryToStartFallFlying()) {
961
            if (player.isFallFlying()) {
962
                mc.getConnection().send(new ServerboundPlayerCommandPacket(
963
                        player,
964
                        ServerboundPlayerCommandPacket.Action.START_FALL_FLYING
965
                ));
966
                clearRestoreGlide();
967
            } else {
968
                restoreGlideAge = player.tickCount + 1;
969
            }
970
        } else {
971
            restoreGlideAge = player.tickCount + 1;
972
        }
973
    }
974
975
    private boolean canStartRestoreGlide(LocalPlayer player) {
976
        if (player == null) return false;
977
        if (player.isFallFlying()) return false;
978
        if (player.isPassenger()) return false;
979
        if (player.getAbilities().flying) return false;
980
        if (!player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) return false;
981
        if (player.isInWater() || player.isInLava()) return false;
982
        return !player.onGround();
983
    }
984
985
    private void clearRestoreGlide() {
986
        queuedRestoreGlide = false;
987
        restoreGlideAge = -1;
988
        restoreGlideExpireAge = -1;
989
    }
990
991
    private void clearElytraCycle() {
992
        elytraCycleActive = false;
993
        elytraCycleTargetId = -1;
994
        elytraReturnInventorySlot = -1;
995
        elytraCycleExpireAge = -1;
996
        elytraCycleStage = CYCLE_NONE;
997
        elytraMaceAttackAge = -1;
998
        elytraRestoreAge = -1;
999
        elytraCycleKeepSprint = false;
1000
    }
1001
1002
    public boolean isElytraCycleActive() {
1003
        return isEnabled() && elytraCycleActive;
1004
    }
1005
1006
    private boolean shouldBypassAuraCooldown(LocalPlayer player, LivingEntity target, int maceSlot) {
1007
        if (!isEnabled()) return false;
1008
        if (!isHeightMaceEnabled()) return false;
1009
        if (player == null || !isValidTarget(target)) return false;
1010
        if (elytraCycleActive) return false;
1011
        if (player.isUsingItem()) return false;
1012
        if (maceSlot < 0 || maceSlot >= 9) return false;
1013
        if (isBlockingShieldTarget(target)) return false;
1014
        if (System.currentTimeMillis() - lastFastAuraMaceAttackMs < nextFastAuraMaceDelayMs) return false;
1015
        return !player.getMainHandItem().is(Items.MACE)
1016
                || ((PlayerInventoryAccessor) player.getInventory()).combatant$getSelectedSlot() != maceSlot;
1017
    }
1018
1019
    private boolean canAttackNow(LocalPlayer player) {
1020
        if (player == null) return false;
1021
        if (player.isUsingItem()) return false;
1022
        return player.getAttackStrengthScale(0.5f) >= 1.0f;
1023
    }
1024
1025
    private boolean canUseBestDamageWeaponNow(LocalPlayer player) {
1026
        if (player == null) return false;
1027
        if (player.isUsingItem()) return false;
1028
        return isLegacyAttackProtocol() || canAttackNow(player);
1029
    }
1030
1031
    private QueueResult tryBestDamageWeaponForAura(LivingEntity target, boolean keepSprint) {
1032
        LocalPlayer player = mc.player;
1033
        if (!shouldUseBestDamageWeaponForAura()) return QueueResult.PASS;
1034
        if (!canUseBestDamageWeaponNow(player)) return QueueResult.PASS;
1035
1036
        BestWeaponPrepareResult result = prepareBestDamageWeaponForAttack(player, target);
1037
        return switch (result) {
1038
            case NONE, PREPARED -> QueueResult.PASS;
1039
            case FAILED -> QueueResult.SUPPRESS;
1040
        };
1041
    }
1042
1043
    private BestWeaponPrepareResult prepareBestDamageWeaponForNextHit(LocalPlayer player, LivingEntity target) {
1044
        if (!shouldUseBestDamageWeaponForNextHit()) return BestWeaponPrepareResult.NONE;
1045
        if (!canUseBestDamageWeaponNow(player)) return BestWeaponPrepareResult.NONE;
1046
        return prepareBestDamageWeaponForAttack(player, target);
1047
    }
1048
1049
    private BestWeaponPrepareResult prepareBestDamageWeaponForAttack(LocalPlayer player, LivingEntity target) {
1050
        int weaponSlot = findBestDamageWeaponSlot(player, target);
1051
        if (weaponSlot == -1) return BestWeaponPrepareResult.NONE;
1052
        return selectBestDamageWeaponSlot(player, weaponSlot)
1053
                ? BestWeaponPrepareResult.PREPARED
1054
                : BestWeaponPrepareResult.FAILED;
1055
    }
1056
1057
    private boolean selectBestDamageWeaponSlot(LocalPlayer player, int hotbarSlot) {
1058
        if (player == null || hotbarSlot < 0 || hotbarSlot >= 9) return false;
1059
        int selectedSlot = ((PlayerInventoryAccessor) player.getInventory()).combatant$getSelectedSlot();
1060
        if (selectedSlot == hotbarSlot) return true;
1061
        return InventorySwap.INSTANCE.selectHotbar(hotbarSlot);
1062
    }
1063
1064
    private boolean isLegacyAttackProtocol() {
1065
        return ProtocolUtil.isLegacyAttackProtocol(protocolHeuristicSources.getAll());
1066
    }
1067
1068
    private boolean shouldUseSmartMace(LocalPlayer player, LivingEntity target, ItemStack maceStack) {
1069
        if (player == null || target == null || maceStack == null || !maceStack.is(Items.MACE)) return false;
1070
        if (!isValidTarget(target)) return false;
1071
        if (isBlockingShieldTarget(target)) return false;
1072
1073
        ItemStack currentStack = player.getMainHandItem();
1074
        double currentDamage = estimateAppliedAttackDamage(player, target, currentStack);
1075
        double maceDamage = estimateAppliedAttackDamage(player, target, maceStack);
1076
        return maceDamage > currentDamage + 0.05;
1077
    }
1078
1079
    private double estimateAppliedAttackDamage(LocalPlayer player, LivingEntity target, ItemStack stack) {
1080
        return estimateAppliedAttackDamage(player, target, stack, 1.0);
1081
    }
1082
1083
    private double estimateAppliedAttackDamage(LocalPlayer player, LivingEntity target, ItemStack stack, double cooldownProgress) {
1084
        if (player == null || target == null) return 0.0;
1085
1086
        double rawDamage = estimateRawAttackDamage(player, target, stack, cooldownProgress);
1087
        return applyEstimatedArmorReduction(target, rawDamage, stack);
1088
    }
1089
1090
    private double estimateRawAttackDamage(LocalPlayer player, LivingEntity target, ItemStack stack) {
1091
        return estimateRawAttackDamage(player, target, stack, 1.0);
1092
    }
1093
1094
    private double estimateRawAttackDamage(LocalPlayer player, LivingEntity target, ItemStack stack, double cooldownProgress) {
1095
        double safeCooldown = Mth.clamp(cooldownProgress, 0.0, 1.0);
1096
        double damage = 1.0 + getMainHandAttackDamage(stack);
1097
        damage += estimateWeaponEnchantmentDamageBonus(target, stack);
1098
        if (safeCooldown < 1.0) {
1099
            damage *= 0.2 + safeCooldown * safeCooldown * 0.8;
1100
        }
1101
        damage += estimateMaceBonusDamage(player, target, stack);
1102
1103
        if (safeCooldown > 0.9 && canEstimateCriticalHit(player, target)) {
1104
            damage *= 1.5;
1105
        }
1106
1107
        return Math.max(0.0, damage);
1108
    }
1109
1110
    private double estimateWeaponEnchantmentDamageBonus(LivingEntity target, ItemStack stack) {
1111
        if (target == null || stack == null || stack.isEmpty()) return 0.0;
1112
1113
        int sharpness = getEnchantmentLevel(stack, Enchantments.SHARPNESS);
1114
        double bonus = sharpness > 0 ? 0.5 * sharpness + 0.5 : 0.0;
1115
1116
        int smite = getEnchantmentLevel(stack, Enchantments.SMITE);
1117
        if (smite > 0 && target.getType().builtInRegistryHolder().is(net.minecraft.tags.EntityTypeTags.SENSITIVE_TO_SMITE)) {
1118
            bonus += 2.5 * smite;
1119
        }
1120
1121
        int bane = getEnchantmentLevel(stack, Enchantments.BANE_OF_ARTHROPODS);
1122
        if (bane > 0 && target.getType().builtInRegistryHolder().is(net.minecraft.tags.EntityTypeTags.SENSITIVE_TO_BANE_OF_ARTHROPODS)) {
1123
            bonus += 2.5 * bane;
1124
        }
1125
1126
        return bonus;
1127
    }
1128
1129
    private double estimateMaceBonusDamage(LocalPlayer player, LivingEntity target, ItemStack stack) {
1130
        if (player == null || target == null || stack == null || !stack.is(Items.MACE)) return 0.0;
1131
        if (!shouldMaceSmashApply(player)) return 0.0;
1132
1133
        double fallDistance = Math.max(0.0, player.fallDistance);
1134
        double baseSmash;
1135
        if (fallDistance <= 3.0) {
1136
            baseSmash = 4.0 * fallDistance;
1137
        } else if (fallDistance <= 8.0) {
1138
            baseSmash = 12.0 + 2.0 * (fallDistance - 3.0);
1139
        } else {
1140
            baseSmash = 22.0 + fallDistance - 8.0;
1141
        }
1142
1143
        int densityLevel = getEnchantmentLevel(stack, Enchantments.DENSITY);
1144
        double densityBonus = densityLevel > 0 ? 0.5 * densityLevel * fallDistance : 0.0;
1145
        return baseSmash + densityBonus;
1146
    }
1147
1148
    private boolean shouldMaceSmashApply(LocalPlayer player) {
1149
        return player != null && player.fallDistance > 1.5f && !player.isFallFlying();
1150
    }
1151
1152
    private double applyEstimatedArmorReduction(LivingEntity target, double damage, ItemStack weaponStack) {
1153
        if (target == null || damage <= 0.0) return 0.0;
1154
1155
        double armor = target.getAttributeValue(Attributes.ARMOR);
1156
        if (armor <= 0.0) return damage;
1157
1158
        double toughness = target.getAttributeValue(Attributes.ARMOR_TOUGHNESS);
1159
        double toughnessFactor = 2.0 + toughness / 4.0;
1160
        double armorEffectiveness = Mth.clamp(
1161
                armor - damage / toughnessFactor,
1162
                armor * 0.2,
1163
                20.0
1164
        ) / 25.0;
1165
1166
        int breachLevel = getEnchantmentLevel(weaponStack, Enchantments.BREACH);
1167
        if (breachLevel > 0) {
1168
            armorEffectiveness = Mth.clamp(armorEffectiveness - 0.15 * breachLevel, 0.0, 1.0);
1169
        }
1170
1171
        return damage * (1.0 - armorEffectiveness);
1172
    }
1173
1174
    private boolean canEstimateCriticalHit(LocalPlayer player, LivingEntity target) {
1175
        return player != null
1176
                && target != null
1177
                && player.fallDistance > 0.0f
1178
                && !player.onGround()
1179
                && !player.onClimbable()
1180
                && !player.isInWater()
1181
                && !player.hasEffect(MobEffects.BLINDNESS)
1182
                && !player.isPassenger()
1183
                && !player.isSprinting();
1184
    }
1185
1186
    private LivingEntity resolveCrosshairTarget() {
1187
        if (!(mc.hitResult instanceof EntityHitResult ehr)) return null;
1188
        if (!(ehr.getEntity() instanceof LivingEntity living)) return null;
1189
        return living;
1190
    }
1191
1192
    private boolean isValidTarget(LivingEntity target) {
1193
        if (target == null || !target.isAlive() || target.isRemoved()) return false;
1194
        return !onlyPlayers.get() || target instanceof Player;
1195
    }
1196
1197
    private double getMainHandAttackDamage(ItemStack stack) {
1198
        if (stack == null || stack.isEmpty()) return 0.0;
1199
1200
        final double[] add = {0.0};
1201
        final double[] mulBase = {0.0};
1202
        final double[] mulTotal = {1.0};
1203
        stack.forEachModifier(EquipmentSlotGroup.MAINHAND, (attribute, modifier, display) -> {
1204
            if (!attribute.equals(Attributes.ATTACK_DAMAGE)) {
1205
                return;
1206
            }
1207
1208
            AttributeModifier.Operation op = modifier.operation();
1209
            double amount = modifier.amount();
1210
            if (op == AttributeModifier.Operation.ADD_VALUE) {
1211
                add[0] += amount;
1212
            } else if (op == AttributeModifier.Operation.ADD_MULTIPLIED_BASE) {
1213
                mulBase[0] += amount;
1214
            } else if (op == AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL) {
1215
                mulTotal[0] *= 1.0 + amount;
1216
            }
1217
        });
1218
1219
        return (add[0] + mulBase[0]) * mulTotal[0];
1220
    }
1221
1222
    private double getMainHandAttackSpeed(LocalPlayer player, ItemStack stack) {
1223
        return estimateMainHandAttributeValue(player, stack, Attributes.ATTACK_SPEED, 4.0);
1224
    }
1225
1226
    private double estimateMainHandAttributeValue(LocalPlayer player,
1227
                                                  ItemStack stack,
1228
                                                  Holder<Attribute> attribute,
1229
                                                  double fallbackBase) {
1230
        double base = player != null ? player.getAttributeBaseValue(attribute) : fallbackBase;
1231
        if (stack == null || stack.isEmpty()) return Math.max(0.1, base);
1232
1233
        final double[] add = {0.0};
1234
        final double[] mulBase = {0.0};
1235
        final double[] mulTotal = {1.0};
1236
        stack.forEachModifier(EquipmentSlotGroup.MAINHAND, (candidateAttribute, modifier, display) -> {
1237
            if (!candidateAttribute.equals(attribute)) {
1238
                return;
1239
            }
1240
1241
            AttributeModifier.Operation op = modifier.operation();
1242
            double amount = modifier.amount();
1243
            if (op == AttributeModifier.Operation.ADD_VALUE) {
1244
                add[0] += amount;
1245
            } else if (op == AttributeModifier.Operation.ADD_MULTIPLIED_BASE) {
1246
                mulBase[0] += amount;
1247
            } else if (op == AttributeModifier.Operation.ADD_MULTIPLIED_TOTAL) {
1248
                mulTotal[0] *= 1.0 + amount;
1249
            }
1250
        });
1251
1252
        double value = (base + add[0] + base * mulBase[0]) * mulTotal[0];
1253
        return Math.max(0.1, value);
1254
    }
1255
1256
    private int findBestDamageWeaponSlot(LocalPlayer player, LivingEntity target) {
1257
        if (player == null || target == null) return -1;
1258
        if (!isValidTarget(target)) return -1;
1259
        if (isBlockingShieldTarget(target)) return -1;
1260
1261
        ItemStack currentStack = player.getMainHandItem();
1262
1263
        int selectedSlot = ((PlayerInventoryAccessor) player.getInventory()).combatant$getSelectedSlot();
1264
        double currentScore = estimateBestDamageWeaponScore(player, target, currentStack);
1265
        double bestScore = currentScore + 0.05;
1266
        int bestSlot = -1;
1267
1268
        for (int i = 0; i < 9; i++) {
1269
            if (i == selectedSlot) continue;
1270
1271
            ItemStack stack = player.getInventory().getItem(i);
1272
            if (!isBestDamageWeaponCandidate(stack)) continue;
1273
1274
            double score = estimateBestDamageWeaponScore(player, target, stack);
1275
            if (score > bestScore) {
1276
                bestScore = score;
1277
                bestSlot = i;
1278
            }
1279
        }
1280
1281
        return bestSlot;
1282
    }
1283
1284
    private boolean isBestDamageWeaponCandidate(ItemStack stack) {
1285
        if (stack == null || stack.isEmpty()) return false;
1286
        return getMainHandAttackDamage(stack) > 0.0;
1287
    }
1288
1289
    private double estimateBestDamageWeaponScore(LocalPlayer player, LivingEntity target, ItemStack stack) {
1290
        if (player == null || target == null || stack == null) return 0.0;
1291
1292
        double damage = estimateAppliedAttackDamage(player, target, stack, 1.0);
1293
        if (isLegacyAttackProtocol()) {
1294
            return damage;
1295
        }
1296
1297
        double attackSpeed = getMainHandAttackSpeed(player, stack);
1298
        return damage * attackSpeed;
1299
    }
1300
1301
    private int findHotbarAxeSlot(LocalPlayer player) {
1302
        if (player == null) return -1;
1303
        for (int i = 0; i < 9; i++) {
1304
            ItemStack stack = player.getInventory().getItem(i);
1305
            if (isAxe(stack)) return i;
1306
        }
1307
        return -1;
1308
    }
1309
1310
    private boolean isAxe(ItemStack stack) {
1311
        return stack != null && (
1312
                stack.is(Items.WOODEN_AXE) ||
1313
                        stack.is(Items.STONE_AXE) ||
1314
                        stack.is(Items.IRON_AXE) ||
1315
                        stack.is(Items.GOLDEN_AXE) ||
1316
                        stack.is(Items.DIAMOND_AXE) ||
1317
                        stack.is(Items.NETHERITE_AXE)
1318
        );
1319
    }
1320
1321
    private boolean isUsingShield(Player target) {
1322
        return target != null
1323
                && target.isUsingItem()
1324
                && target.getUseItem().is(Items.SHIELD);
1325
    }
1326
1327
    private boolean isShieldFacingPlayer(Player target) {
1328
        if (mc.player == null || target == null) return false;
1329
1330
        Vec3 toPlayer = mc.player.getBoundingBox().getCenter().subtract(target.getEyePosition());
1331
        float yawToPlayer = (float) Math.toDegrees(Math.atan2(toPlayer.z, toPlayer.x)) - 90.0f;
1332
        float diff = Mth.wrapDegrees(target.getYRot() - yawToPlayer);
1333
1334
        return Math.abs(diff) < 90.0f;
1335
    }
1336
1337
    private boolean isVectorFallingDown(LocalPlayer player) {
1338
        Vec3 velocity = player.getDeltaMovement();
1339
        if (velocity.y > -minDownVelocity.get()) return false;
1340
1341
        double predictedFall = predictUnglidedFallDistance(player, predictionTicks.get());
1342
        return predictedFall >= minFallDistance.get();
1343
    }
1344
1345
    private double predictUnglidedFallDistance(LocalPlayer player, int ticks) {
1346
        double fall = Math.max(0.0, player.fallDistance);
1347
        double yVelocity = player.getDeltaMovement().y;
1348
        int safeTicks = Math.max(1, ticks);
1349
1350
        for (int i = 0; i < safeTicks; i++) {
1351
            if (yVelocity < 0.0) {
1352
                fall += -yVelocity;
1353
            }
1354
            yVelocity = (yVelocity - 0.08) * 0.9800000190734863;
1355
        }
1356
1357
        return fall;
1358
    }
1359
1360
    private boolean isHorizontallyMovingIntoTarget(LocalPlayer player, LivingEntity target) {
1361
        Vec3 velocity = player.getDeltaMovement();
1362
        Vec3 horizontalVelocity = new Vec3(velocity.x, 0.0, velocity.z);
1363
        double horizontalSpeed = horizontalVelocity.length();
1364
        if (horizontalSpeed <= 1.0E-4) return false;
1365
1366
        int ticks = predictionTicks.get();
1367
        Vec3 playerPos = predictedLocalPlayerPos(player, ticks);
1368
        Vec3 targetPos = predictedTargetPos(target, ticks);
1369
        Vec3 toTarget = new Vec3(
1370
                targetPos.x - playerPos.x,
1371
                0.0,
1372
                targetPos.z - playerPos.z
1373
        );
1374
        double distance = toTarget.length();
1375
        if (distance <= 1.0E-4) return true;
1376
1377
        double approachSpeed = horizontalVelocity.dot(toTarget.scale(1.0 / distance));
1378
        if (approachSpeed < minApproachSpeed.get()) return false;
1379
1380
        Vec3 projectedPlayer = playerPos.add(horizontalVelocity.scale(ticks));
1381
        double currentDistance = horizontalDistance(playerPos, targetPos);
1382
        double projectedDistance = horizontalDistance(projectedPlayer, targetPos);
1383
        return projectedDistance < currentDistance
1384
                && projectedDistance <= maxPredictedHorizontalDistance.get();
1385
    }
1386
1387
    private Vec3 predictedLocalPlayerPos(LocalPlayer player, int ticks) {
1388
        PlayerSimulationCache.SimulatedPlayerCache simulation = PlayerSimulationCache.getSimulationForLocalPlayer();
1389
        if (simulation == null) {
1390
            return player.position().add(player.getDeltaMovement().scale(Math.max(1, ticks)));
1391
        }
1392
1393
        return simulation.getSnapshotAt(Math.max(1, ticks)).pos();
1394
    }
1395
1396
    private Vec3 predictedTargetPos(LivingEntity target, int ticks) {
1397
        if (target instanceof Player playerTarget) {
1398
            return PlayerSimulationCache.getSimulationForOtherPlayers(playerTarget)
1399
                    .getSnapshotAt(Math.max(1, ticks))
1400
                    .pos();
1401
        }
1402
        return target.position().add(target.getDeltaMovement().scale(Math.max(1, ticks)));
1403
    }
1404
1405
    private double horizontalDistance(Vec3 a, Vec3 b) {
1406
        double dx = a.x - b.x;
1407
        double dz = a.z - b.z;
1408
        return Math.sqrt(dx * dx + dz * dz);
1409
    }
1410
1411
    private int findElytraRemovalSlot(LocalPlayer player) {
1412
        int selectedSlot = ((PlayerInventoryAccessor) player.getInventory()).combatant$getSelectedSlot();
1413
        int bestChestSlot = -1;
1414
        int bestChestScore = -1;
1415
        int firstEmptySlot = -1;
1416
1417
        for (int i = 0; i < 36; i++) {
1418
            if (i == selectedSlot) continue;
1419
1420
            ItemStack stack = player.getInventory().getItem(i);
1421
            if (stack.isEmpty()) {
1422
                if (firstEmptySlot == -1) firstEmptySlot = i;
1423
                continue;
1424
            }
1425
1426
            int score = getChestDefenseScore(stack);
1427
            if (score > bestChestScore) {
1428
                bestChestScore = score;
1429
                bestChestSlot = i;
1430
            }
1431
        }
1432
1433
        if (bestChestSlot != -1) return bestChestSlot;
1434
        return firstEmptySlot;
1435
    }
1436
1437
    private int getChestDefenseScore(ItemStack stack) {
1438
        if (!isChestplate(stack)) return 0;
1439
1440
        int base =
1441
                stack.is(Items.LEATHER_CHESTPLATE) ? 3 :
1442
                        stack.is(Items.COPPER_CHESTPLATE) ? 4 :
1443
                                stack.is(Items.CHAINMAIL_CHESTPLATE) ? 5 :
1444
                                        stack.is(Items.GOLDEN_CHESTPLATE) ? 5 :
1445
                                                stack.is(Items.IRON_CHESTPLATE) ? 6 :
1446
                                                        stack.is(Items.DIAMOND_CHESTPLATE) ? 8 :
1447
                                                                stack.is(Items.NETHERITE_CHESTPLATE) ? 9 : 0;
1448
        return base;
1449
    }
1450
1451
    private boolean isChestplate(ItemStack stack) {
1452
        if (stack == null || stack.isEmpty() || stack.is(Items.ELYTRA)) return false;
1453
        Equippable equippable = stack.get(DataComponents.EQUIPPABLE);
1454
        return equippable != null && equippable.slot() == EquipmentSlot.CHEST;
1455
    }
1456
1457
    private int findDesiredMaceSlot(LocalPlayer player, LivingEntity target) {
1458
        int start = 0;
1459
        int end = "INVENTORY".equalsIgnoreCase(searchMode.get()) ? 36 : 9;
1460
        return findBestDamageMaceSlot(player, target, start, end);
1461
    }
1462
1463
    private int findDesiredHotbarMaceSlot(LocalPlayer player, LivingEntity target) {
1464
        if (player == null) return -1;
1465
        return findBestDamageMaceSlot(player, target, 0, 9);
1466
    }
1467
1468
    private int findBestDamageMaceSlot(LocalPlayer player, LivingEntity target, int startInclusive, int endExclusive) {
1469
        if (player == null || target == null) return -1;
1470
1471
        int selectedSlot = ((PlayerInventoryAccessor) player.getInventory()).combatant$getSelectedSlot();
1472
        double currentDamage = estimateAppliedAttackDamage(player, target, player.getMainHandItem());
1473
        double bestDamage = currentDamage + 0.05;
1474
        int bestSlot = -1;
1475
1476
        for (int i = startInclusive; i < endExclusive; i++) {
1477
            if (i == selectedSlot) continue;
1478
1479
            ItemStack stack = player.getInventory().getItem(i);
1480
            if (!stack.is(Items.MACE)) continue;
1481
            if (isUnsafeWindBurstMace(player, stack)) continue;
1482
            if (!shouldUseSmartMace(player, target, stack)) continue;
1483
1484
            double damage = estimateAppliedAttackDamage(player, target, stack);
1485
            if (damage > bestDamage) {
1486
                bestDamage = damage;
1487
                bestSlot = i;
1488
            }
1489
        }
1490
1491
        return bestSlot;
1492
    }
1493
1494
    private int getEnchantmentLevel(ItemStack stack, net.minecraft.resources.ResourceKey<Enchantment> key) {
1495
        if (stack == null || stack.isEmpty() || mc.level == null) return 0;
1496
        var registry = mc.level.registryAccess().lookupOrThrow(Registries.ENCHANTMENT);
1497
        Enchantment enchantment = registry.getValue(key);
1498
        if (enchantment == null) return 0;
1499
        Holder<Enchantment> entry = registry.wrapAsHolder(enchantment);
1500
        return EnchantmentHelper.getItemEnchantmentLevel(entry, stack);
1501
    }
1502
1503
    private boolean isUnsafeWindBurstMace(LocalPlayer player, ItemStack mace) {
1504
        if (!isWindBurstSafetyEnabled()) return false;
1505
        if (player == null || mc.level == null || mace == null || mace.isEmpty()) return false;
1506
1507
        int windBurstLevel = getEnchantmentLevel(mace, Enchantments.WIND_BURST);
1508
        if (windBurstLevel <= 0) return false;
1509
1510
        NoFall noFall = Modules.get(NoFall.class);
1511
        if (noFall != null && noFall.isEnabled()) {
1512
            logWindBurstDecision(player, windBurstLevel, null, null, "ALLOW_NOFALL", false);
1513
            return false;
1514
        }
1515
1516
        float healthBudget = getWindBurstHealthBudget(player);
1517
        float minRemainingHealth = windBurstMinRemainingHealth.get();
1518
        if (healthBudget <= minRemainingHealth) {
1519
            logWindBurstDecision(player, windBurstLevel, null, null, "BLOCK_CURRENT_HP_AT_OR_BELOW_LIMIT", true);
1520
            return true;
1521
        }
1522
1523
        WindBurstImpulse impulse = calculateWindBurstImpulse(player, windBurstLevel);
1524
        PredictedWindBurstFall fall = predictWindBurstFall(player, impulse.vertical());
1525
        FallDamageEstimate damage = estimateFallDamage(player, fall.fallDistance(), fall.damagePerDistance());
1526
        float predictedDamage = damage.finalDamage();
1527
        float remainingHealth = healthBudget - predictedDamage;
1528
        if (remainingHealth >= minRemainingHealth) {
1529
            logWindBurstDecision(player, windBurstLevel, impulse, fall, damage, "ALLOW_PREDICTED_HP_OK", false);
1530
            return false;
1531
        }
1532
1533
        if (!windBurstStrictElytra.get() && hasElytraFallback(player)) {
1534
            logWindBurstDecision(player, windBurstLevel, impulse, fall, damage, "ALLOW_ELYTRA_FALLBACK", false);
1535
            return false;
1536
        }
1537
1538
        requestAutoTotemForWindBurst(player);
1539
        boolean unsafe = !hasTotemInOffhand(player);
1540
        logWindBurstDecision(player, windBurstLevel, impulse, fall, damage, unsafe ? "BLOCK_PREDICTED_HP_LOW" : "ALLOW_OFFHAND_TOTEM", unsafe);
1541
        return unsafe;
1542
    }
1543
1544
    private boolean hasTotemInOffhand(LocalPlayer player) {
1545
        return player != null && player.getOffhandItem().is(Items.TOTEM_OF_UNDYING);
1546
    }
1547
1548
    private void requestAutoTotemForWindBurst(LocalPlayer player) {
1549
        AutoTotem autoTotem = Modules.get(AutoTotem.class);
1550
        if (autoTotem != null) {
1551
            autoTotem.ensureTotemForDanger(player);
1552
        }
1553
    }
1554
1555
    private PredictedWindBurstFall predictWindBurstFall(LocalPlayer player, double verticalImpulse) {
1556
        AABB baseBox = player.getBoundingBox();
1557
        Vec3 offset = Vec3.ZERO;
1558
        Vec3 velocity = player.getDeltaMovement().add(0.0, verticalImpulse, 0.0);
1559
        double fallDistance = Math.max(0.0, player.fallDistance);
1560
        double maxRise = 0.0;
1561
        int ceilingCuts = 0;
1562
1563
        for (int tick = 1; tick <= WIND_BURST_PREDICTION_TICKS; tick++) {
1564
            Vec3 previousOffset = offset;
1565
            offset = offset.add(velocity);
1566
            maxRise = Math.max(maxRise, offset.y);
1567
1568
            AABB previousBox = baseBox.move(previousOffset);
1569
            AABB nextBox = baseBox.move(offset);
1570
            AABB swept = union(previousBox, nextBox).inflate(WIND_BURST_SWEEP_MARGIN);
1571
            if (hasSolidCollision(player, swept)) {
1572
                if (velocity.y > 0.0) {
1573
                    ceilingCuts++;
1574
                    offset = previousOffset;
1575
                    velocity = new Vec3(velocity.x * 0.4, 0.0, velocity.z * 0.4);
1576
                    continue;
1577
                }
1578
1579
                BlockState landingState = getLandingBlockState(player, nextBox);
1580
                double damageFallDistance = isStalagmiteTip(landingState) ? fallDistance + 2.5 : fallDistance;
1581
                return new PredictedWindBurstFall(
1582
                        damageFallDistance,
1583
                        getFallDamagePerDistance(landingState),
1584
                        tick,
1585
                        blockId(landingState),
1586
                        ceilingCuts,
1587
                        maxRise,
1588
                        false
1589
                );
1590
            }
1591
1592
            if (velocity.y < 0.0) {
1593
                fallDistance += -velocity.y;
1594
            }
1595
1596
            velocity = new Vec3(
1597
                    velocity.x * 0.91,
1598
                    (velocity.y - 0.08) * 0.9800000190734863,
1599
                    velocity.z * 0.91
1600
            );
1601
        }
1602
1603
        return new PredictedWindBurstFall(fallDistance, 1.0f, WIND_BURST_PREDICTION_TICKS, "timeout", ceilingCuts, maxRise, true);
1604
    }
1605
1606
    private WindBurstImpulse calculateWindBurstImpulse(LocalPlayer player, int windBurstLevel) {
1607
        Vec3 explosionPos = player.position();
1608
        Vec3 affectedPos = player.getEyePosition();
1609
        double blastDiameter = WIND_BURST_EXPLOSION_RADIUS * 2.0;
1610
        double distanceRatio = Math.sqrt(player.distanceToSqr(explosionPos)) / blastDiameter;
1611
        if (distanceRatio > 1.0) {
1612
            return new WindBurstImpulse(0.0, 0.0, distanceRatio, getWindBurstKnockbackMultiplier(windBurstLevel), 0.0);
1613
        }
1614
1615
        Vec3 direction = affectedPos.subtract(explosionPos);
1616
        if (direction.lengthSqr() < 1.0E-6) {
1617
            direction = new Vec3(0.0, 1.0, 0.0);
1618
        } else {
1619
            direction = direction.normalize();
1620
        }
1621
1622
        double exposure = calculateExplosionExposure(explosionPos, player);
1623
        double resistance = player.getAttributeValue(Attributes.EXPLOSION_KNOCKBACK_RESISTANCE);
1624
        double multiplier = getWindBurstKnockbackMultiplier(windBurstLevel);
1625
        double vertical = direction.y
1626
                * (1.0 - distanceRatio)
1627
                * exposure
1628
                * multiplier
1629
                * (1.0 - resistance);
1630
        return new WindBurstImpulse(vertical, exposure, distanceRatio, multiplier, resistance);
1631
    }
1632
1633
    private double calculateExplosionExposure(Vec3 source, LocalPlayer player) {
1634
        AABB box = player.getBoundingBox();
1635
        double xStep = 1.0 / ((box.maxX - box.minX) * 2.0 + 1.0);
1636
        double yStep = 1.0 / ((box.maxY - box.minY) * 2.0 + 1.0);
1637
        double zStep = 1.0 / ((box.maxZ - box.minZ) * 2.0 + 1.0);
1638
        double xOffset = (1.0 - Math.floor(1.0 / xStep) * xStep) / 2.0;
1639
        double zOffset = (1.0 - Math.floor(1.0 / zStep) * zStep) / 2.0;
1640
        int clear = 0;
1641
        int total = 0;
1642
1643
        for (double x = 0.0; x <= 1.0; x += xStep) {
1644
            for (double y = 0.0; y <= 1.0; y += yStep) {
1645
                for (double z = 0.0; z <= 1.0; z += zStep) {
1646
                    Vec3 sample = new Vec3(
1647
                            lerp(x, box.minX, box.maxX) + xOffset,
1648
                            lerp(y, box.minY, box.maxY),
1649
                            lerp(z, box.minZ, box.maxZ) + zOffset
1650
                    );
1651
                    HitResult hit = mc.level.clip(new ClipContext(
1652
                            sample,
1653
                            source,
1654
                            ClipContext.Block.COLLIDER,
1655
                            ClipContext.Fluid.NONE,
1656
                            player
1657
                    ));
1658
                    if (hit.getType() == HitResult.Type.MISS) {
1659
                        clear++;
1660
                    }
1661
                    total++;
1662
                }
1663
            }
1664
        }
1665
1666
        return total == 0 ? 0.0 : (double) clear / total;
1667
    }
1668
1669
    private double getWindBurstKnockbackMultiplier(int level) {
1670
        return switch (level) {
1671
            case 1 -> 1.2;
1672
            case 2 -> 1.75;
1673
            case 3 -> 2.2;
1674
            default -> 1.2 + Math.max(0, level - 1) * 0.5;
1675
        };
1676
    }
1677
1678
    private FallDamageEstimate estimateFallDamage(LocalPlayer player, double fallDistance, float damagePerDistance) {
1679
        if (player == null || fallDistance <= 0.0 || damagePerDistance <= 0.0f) {
1680
            return new FallDamageEstimate(0.0, 0.0f, 0.0, 0.0, 0.0, 0.0f, 0);
1681
        }
1682
1683
        double safeFallDistance = player.getAttributeValue(Attributes.SAFE_FALL_DISTANCE);
1684
        double fallMultiplier = player.getAttributeValue(Attributes.FALL_DAMAGE_MULTIPLIER);
1685
        double unsafeFallDistance = fallDistance + 1.0E-6 - safeFallDistance;
1686
        int rawDamage = (int) Math.floor(
1687
                unsafeFallDistance
1688
                        * damagePerDistance
1689
                        * fallMultiplier
1690
        );
1691
        if (rawDamage <= 0) {
1692
            return new FallDamageEstimate(rawDamage, 0.0f, unsafeFallDistance, safeFallDistance, fallMultiplier, 0.0f, 0);
1693
        }
1694
1695
        float amount = rawDamage;
1696
        int resistanceReduction = 0;
1697
        MobEffectInstance resistance = player.getEffect(MobEffects.RESISTANCE);
1698
        if (resistance != null) {
1699
            resistanceReduction = (resistance.getAmplifier() + 1) * 5;
1700
            amount = Math.max(amount * (25 - resistanceReduction) / 25.0f, 0.0f);
1701
        }
1702
1703
        float protection = getFallProtectionAmount(player);
1704
        if (protection > 0.0f) {
1705
            amount *= 1.0f - Math.min(protection, 20.0f) / 25.0f;
1706
        }
1707
1708
        return new FallDamageEstimate(rawDamage, Math.max(0.0f, amount), unsafeFallDistance, safeFallDistance, fallMultiplier, protection, resistanceReduction);
1709
    }
1710
1711
    private float getFallProtectionAmount(LocalPlayer player) {
1712
        float protection = 0.0f;
1713
        for (EquipmentSlot slot : EquipmentSlot.values()) {
1714
            ItemStack stack = player.getItemBySlot(slot);
1715
            if (stack == null || stack.isEmpty()) continue;
1716
            protection += getEnchantmentLevel(stack, Enchantments.PROTECTION);
1717
        }
1718
        protection += getEnchantmentLevel(player.getItemBySlot(EquipmentSlot.FEET), Enchantments.FEATHER_FALLING) * 3.0f;
1719
        return protection;
1720
    }
1721
1722
    private float getWindBurstHealthBudget(LocalPlayer player) {
1723
        float absorption = Math.max(0.0f, player.getAbsorptionAmount());
1724
        MobEffectInstance absorptionEffect = player.getEffect(MobEffects.ABSORPTION);
1725
        if (absorptionEffect != null && absorptionEffect.getDuration() < WIND_BURST_ABSORPTION_MIN_TICKS) {
1726
            absorption = 0.0f;
1727
        }
1728
        return Math.max(0.0f, player.getHealth()) + absorption;
1729
    }
1730
1731
    private boolean hasElytraFallback(LocalPlayer player) {
1732
        if (player == null) return false;
1733
        if (player.getItemBySlot(EquipmentSlot.CHEST).is(Items.ELYTRA)) return true;
1734
1735
        for (int i = 0; i < 36; i++) {
1736
            if (player.getInventory().getItem(i).is(Items.ELYTRA)) {
1737
                return true;
1738
            }
1739
        }
1740
1741
        return false;
1742
    }
1743
1744
    private float getFallDamagePerDistance(BlockState landingState) {
1745
        if (landingState == null) return 1.0f;
1746
        if (landingState.is(Blocks.WATER)
1747
                || landingState.is(Blocks.POWDER_SNOW)
1748
                || landingState.is(Blocks.COBWEB)
1749
                || landingState.is(Blocks.SLIME_BLOCK)) {
1750
            return 0.0f;
1751
        }
1752
        if (landingState.is(Blocks.HAY_BLOCK) || landingState.is(Blocks.HONEY_BLOCK)) {
1753
            return 0.2f;
1754
        }
1755
        if (isStalagmiteTip(landingState)) {
1756
            return 2.0f;
1757
        }
1758
        return 1.0f;
1759
    }
1760
1761
    private BlockState getLandingBlockState(LocalPlayer player, AABB nextBox) {
1762
        BlockPos pos = BlockPos.containing(nextBox.getCenter().x, nextBox.minY - 0.001, nextBox.getCenter().z);
1763
        BlockState state = mc.level.getBlockState(pos);
1764
        if (state.isAir()) {
1765
            state = mc.level.getBlockState(pos.below());
1766
        }
1767
        return state;
1768
    }
1769
1770
    private boolean isStalagmiteTip(BlockState state) {
1771
        return state != null
1772
                && state.is(Blocks.POINTED_DRIPSTONE)
1773
                && state.getValue(PointedDripstoneBlock.TIP_DIRECTION) == Direction.UP
1774
                && state.getValue(net.minecraft.world.level.block.SpeleothemBlock.THICKNESS) == SpeleothemThickness.TIP;
1775
    }
1776
1777
    private boolean hasSolidCollision(LocalPlayer player, AABB box) {
1778
        for (var shape : mc.level.getBlockCollisions(player, box)) {
1779
            if (!shape.isEmpty()) {
1780
                return true;
1781
            }
1782
        }
1783
        return false;
1784
    }
1785
1786
    private String blockId(BlockState state) {
1787
        if (state == null) return "null";
1788
        return BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString();
1789
    }
1790
1791
    private void logWindBurstDecision(LocalPlayer player,
1792
                                      int windBurstLevel,
1793
                                      WindBurstImpulse impulse,
1794
                                      PredictedWindBurstFall fall,
1795
                                      String reason,
1796
                                      boolean blocked) {
1797
        logWindBurstDecision(player, windBurstLevel, impulse, fall, null, reason, blocked);
1798
    }
1799
1800
    private void logWindBurstDecision(LocalPlayer player,
1801
                                      int windBurstLevel,
1802
                                      WindBurstImpulse impulse,
1803
                                      PredictedWindBurstFall fall,
1804
                                      FallDamageEstimate damage,
1805
                                      String reason,
1806
                                      boolean blocked) {
1807
        if (!windBurstDebugLog.get() || player == null) return;
1808
1809
        MobEffectInstance resistance = player.getEffect(MobEffects.RESISTANCE);
1810
        MobEffectInstance absorptionEffect = player.getEffect(MobEffects.ABSORPTION);
1811
        float absorption = Math.max(0.0f, player.getAbsorptionAmount());
1812
        int absorptionTicks = absorptionEffect != null ? absorptionEffect.getDuration() : -1;
1813
        boolean absorptionCounted = absorption <= 0.0f
1814
                || absorptionEffect == null
1815
                || absorptionTicks >= WIND_BURST_ABSORPTION_MIN_TICKS;
1816
1817
        DebugLog.info(
1818
                "[AttributeSwap][WindBurst] decision=%s blocked=%s wind=%d hp=%.2f absorption=%.2f absorptionTicks=%d absorptionCounted=%s budget=%.2f minRemain=%.2f noFall=%s elytraFallback=%s strictElytra=%s offhandTotem=%s fallDistance=%.2f velocity=(%.3f,%.3f,%.3f) impulseY=%s exposure=%s distRatio=%s kbMul=%s explosionRes=%s predictedFall=%s rawDamage=%s finalDamage=%s unsafeFall=%s safeFall=%s fallMul=%s protection=%s resistReduction=%s landing=%s tick=%s ceilingCuts=%s maxRise=%s timedOut=%s",
1819
                reason,
1820
                blocked,
1821
                windBurstLevel,
1822
                player.getHealth(),
1823
                absorption,
1824
                absorptionTicks,
1825
                absorptionCounted,
1826
                getWindBurstHealthBudget(player),
1827
                windBurstMinRemainingHealth.get(),
1828
                Modules.enabled(NoFall.class),
1829
                hasElytraFallback(player),
1830
                windBurstStrictElytra.get(),
1831
                hasTotemInOffhand(player),
1832
                player.fallDistance,
1833
                player.getDeltaMovement().x,
1834
                player.getDeltaMovement().y,
1835
                player.getDeltaMovement().z,
1836
                impulse != null ? format3(impulse.vertical()) : "n/a",
1837
                impulse != null ? format3(impulse.exposure()) : "n/a",
1838
                impulse != null ? format3(impulse.distanceRatio()) : "n/a",
1839
                impulse != null ? format3(impulse.knockbackMultiplier()) : "n/a",
1840
                impulse != null ? format3(impulse.explosionResistance()) : "n/a",
1841
                fall != null ? format3(fall.fallDistance()) : "n/a",
1842
                damage != null ? format3(damage.rawDamage()) : "n/a",
1843
                damage != null ? format3(damage.finalDamage()) : "n/a",
1844
                damage != null ? format3(damage.unsafeFallDistance()) : "n/a",
1845
                damage != null ? format3(damage.safeFallDistance()) : "n/a",
1846
                damage != null ? format3(damage.fallDamageMultiplier()) : "n/a",
1847
                damage != null ? format3(damage.protection()) : "n/a",
1848
                damage != null ? damage.resistanceReduction() : "n/a",
1849
                fall != null ? fall.landingBlock() : "n/a",
1850
                fall != null ? fall.tick() : "n/a",
1851
                fall != null ? fall.ceilingCuts() : "n/a",
1852
                fall != null ? format3(fall.maxRise()) : "n/a",
1853
                fall != null ? fall.timedOut() : "n/a"
1854
        );
1855
    }
1856
1857
    private enum BestWeaponPrepareResult {
1858
        NONE,
1859
        PREPARED,
1860
        FAILED
1861
    }
1862
1863
    public enum QueueResult {
1864
        PASS,
1865
        SUPPRESS,
1866
        HANDLE
1867
    }
1868
1869
    public enum BestDamageWeaponMode implements EnumValue.IdProvider {
1870
        AURA_NEXT_HIT("aura_next_hit", true, false),
1871
        NEXT_HIT("next_hit", false, true),
1872
        BOTH("both", true, true);
1873
1874
        private final String id;
1875
        private final boolean aura;
1876
        private final boolean nextHit;
1877
1878
        BestDamageWeaponMode(String id, boolean aura, boolean nextHit) {
1879
            this.id = id;
1880
            this.aura = aura;
1881
            this.nextHit = nextHit;
1882
        }
1883
1884
        @Override
1885
        public String getId() {
1886
            return id;
1887
        }
1888
1889
        boolean usesAura() {
1890
            return aura;
1891
        }
1892
1893
        boolean usesNextHit() {
1894
            return nextHit;
1895
        }
1896
    }
1897
1898
    private record WindBurstImpulse(double vertical,
1899
                                    double exposure,
1900
                                    double distanceRatio,
1901
                                    double knockbackMultiplier,
1902
                                    double explosionResistance) {
1903
    }
1904
1905
    private record PredictedWindBurstFall(double fallDistance,
1906
                                          float damagePerDistance,
1907
                                          int tick,
1908
                                          String landingBlock,
1909
                                          int ceilingCuts,
1910
                                          double maxRise,
1911
                                          boolean timedOut) {
1912
    }
1913
1914
    private record FallDamageEstimate(double rawDamage,
1915
                                      float finalDamage,
1916
                                      double unsafeFallDistance,
1917
                                      double safeFallDistance,
1918
                                      double fallDamageMultiplier,
1919
                                      float protection,
1920
                                      int resistanceReduction) {
1921
    }
1922
}
1923