Rise 6.0 Disabler module 20 files, 915 lines

Rise 6.0 Disabler: Full Source Analysis

Rise 6.0's Disabler is a mode-selector module: one BooleanValue per bypass, and each value instantiates a dedicated Mode class from the exploit.disabler package that contains all of that bypass's packet logic.

com/alan/clients/module/impl/exploit/Disabler.java · GitHub source ↗

Published 2026-08-12 · Updated 2026-10-14

Analysis

Overview

Rise 6.0's Disabler is a mode-selector module: one BooleanValue per bypass, and each value instantiates a dedicated Mode class from the exploit.disabler package that contains all of that bypass's packet logic. Eighteen of the nineteen mode classes are wired to toggles (three of them reused by deprecated UI aliases); WatchdogDisabler sits in the package but is not registered by the module in this build. Modes hook the client's newevent bus through @EventLink/Listener fields and lean on global components (BadPacketsComponent, PingSpoofComponent, BlinkComponent) that normalize the packet stream for anticheats.

Architecture

The module is a thin composition root. Each BooleanValue is built with four arguments: the display name, the owning module, a default state, and a Mode instance created inline. Mode<T> is the client's per-toggle base class: when a value flips on, the mode is registered with the global EventBus and its onEnable hook runs; flipping off unregisters it. Registration is reflection-based: the bus scans the mode's declared fields for the @EventLink marker, resolves the event type from the Listener<T> generic, and sorts call sites by the marker's priority byte, so every mode in this package is pure event wiring with zero lifecycle code.

The three components the modes depend on are registered once at client startup and expose static state. BadPacketsComponent flags slot/attack/swing/block/inventory packets as they are sent and clears the flags on the next C03PacketPlayer, giving modes a cheap 'is the stream polluted' test. PingSpoofComponent and BlinkComponent both buffer packets in ConcurrentLinkedQueues and replay them on a schedule or on demand. Because the disabler modes drive these components through static calls, several toggles can cooperate without knowing about each other.

Key techniques

Modes shape the outbound stream in three ways. event.setCancelled(true) drops a packet entirely, the choice for keepalives and transactions that the client wants to starve. event.setPacket(...) swaps the payload, used to upgrade C04PacketPlayerPosition into C06PacketPlayerPosLook or to corrupt the uid of a C0FPacketConfirmTransaction. PacketUtil.sendNoEvent injects a packet through addToSendQueueUnregistered so it bypasses the mode's own listener (and every other listener), while PacketUtil.send routes it through the normal pipeline; this distinction is what lets a mode emit a packet from inside its own handler without recursing.

The sprint family (SprintDisabler, DynamicPVP, Lunar, Ghostly) shares one trick: the client's EntityPlayerSP tracks serverSprintState, the sprint state the server last heard, and vanilla only sends C0BPacketEntityAction on state changes. When a START_SPRINTING arrives while the server already believes the player is sprinting, the modes first emit a STOP_SPRINTING via sendNoEvent and clear serverSprintState, then cancel the original START. The server is left believing the player is not sprinting while the client moves at sprint speed, so sprint-speed motion is never matched to a sprint action. Movement modes rewrite or gate C03PacketPlayer itself: position jitter, forced onGround flags, grid-aligned Y snapping, rotation spoofs, and whole-packet cancellation on a tick window.

Anti-cheat targeting

The mode set maps cleanly onto the anticheat landscape of 2022: CubeCraftDisabler, VulcanDisabler, VerusCustomDisabler, UniversoCraftDisabler, MineLandKickDisabler and WatchdogDisabler target named servers or anticheats, while LunarDisabler and OmniSprintDisabler aim at Lunar Client's client-side checks, and RiseBalanceDisabler is tuned against Rise's own 'Balance' anticheat on its practice servers. The generic primitives (KeepAlive, Transaction, Sprint, Input, Vehicle, Teleport, Spectate, Abilities) are server-agnostic building blocks that combine with the components for a full bypass.

Vanilla packet facts verified against the bundled MCP sources: C0FPacketConfirmTransaction carries windowId (one byte on the wire), uid (a short) and accepted, and the server's processConfirmTransaction only marks a container craftable when the echoed uid and windowId match its expected values. C00PacketKeepAlive echoes the server's random key, and processKeepAlive folds the round-trip into the player's ping as an exponential moving average. C18PacketSpectate is only honored for spectator-mode players, and S08PacketPlayerPosLook is the server's teleport-correction packet that PingSpoofComponent delays under its 'teleport' category. The server's processPlayer rejects nothing for a single absurd position packet: the 'moved too quickly' check caps each delta by the player's known motion, which is why TeleportDisabler can jump 2000 blocks and only force a correction.

source Disabler.java (mode selector)

Disabler.java88 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit;
2
3
import com.alan.clients.api.Rise;
4
import com.alan.clients.module.Module;
5
import com.alan.clients.module.api.Category;
6
import com.alan.clients.module.api.ModuleInfo;
7
import com.alan.clients.module.impl.exploit.disabler.*;
8
import com.alan.clients.value.Value;
9
import com.alan.clients.value.impl.BooleanValue;
10
11
@Rise
12
@ModuleInfo(name = "module.combat.disabler.name", description = "module.exploit.disabler.description", category = Category.EXPLOIT)
13
public class Disabler extends Module {
14
    private final BooleanValue cubecraft =
15
            new BooleanValue("Cubecraft", this, false, new CubeCraftDisabler("", this));
16
17
    private final BooleanValue mineLandKick =
18
            new BooleanValue("Mine Land Kick Checks", this, false, new MineLandKickDisabler("", this));
19
20
    private final BooleanValue verus =
21
            new BooleanValue("Verus Checks", this, false, new VerusCustomDisabler("", this));
22
23
    private final BooleanValue vehicle =
24
            new BooleanValue("Vehicle Packets", this, false, new VehicleDisabler("", this));
25
26
    private final BooleanValue teleport =
27
            new BooleanValue("Force Server Teleport", this, false, new TeleportDisabler("", this));
28
29
    private final BooleanValue vulcan =
30
            new BooleanValue("Vulcan Checks", this, false, new VulcanDisabler("", this));
31
32
    private final BooleanValue sprint =
33
            new BooleanValue("Cancel Sprint Packet", this, false, new SprintDisabler("", this));
34
35
    private final BooleanValue omnisprint =
36
            new BooleanValue("OmniSprint", this, false, new OmniSprintDisabler("", this));
37
38
    private final BooleanValue universocraft =
39
            new BooleanValue("UniversoCraft", this, false, new UniversoCraftDisabler("", this));
40
41
    private final BooleanValue riseBalance =
42
            new BooleanValue("Rise Balance Timer Abuse", this, false, new RiseBalanceDisabler("", this));
43
44
    private final BooleanValue cancelTransactions =
45
            new BooleanValue("Cancel Transactions", this, false, new TransactionDisabler("", this));
46
47
    private final BooleanValue Abilities =
48
            new BooleanValue("Abilities", this, false, new AbilitiesDisabler("", this));
49
50
    private final BooleanValue input =
51
            new BooleanValue("Input", this, false, new InputDisabler("", this));
52
53
    private final BooleanValue spectate =
54
            new BooleanValue("Spectate", this, false, new SpectateDisabler("", this));
55
56
    private final BooleanValue cancelKeepAlives =
57
            new BooleanValue("Cancel Keep Alive", this, false, new KeepAliveDisabler("", this));
58
59
    private final BooleanValue deprecated =
60
            new BooleanValue("Deprecated", this, false);
61
62
    private final BooleanValue hypixelSlime =
63
            new BooleanValue("Hypixel Slime (Deprecated)", this, false, new AbilitiesDisabler("", this));
64
65
    private final BooleanValue mmcReachPartial =
66
            new BooleanValue("MMC Partial Reach (Deprecated)", this, false, new TransactionDisabler("", this));
67
68
    private final BooleanValue mmcKeepSprint =
69
            new BooleanValue("MMC Keep Sprint (Deprecated)", this, false, new SprintDisabler("", this));
70
71
    private final BooleanValue dynamicPVP =
72
            new BooleanValue("Dynamic PVP (Deprecated)", this, false, new DynamicPVPDisabler("", this));
73
74
    private final BooleanValue ghostly =
75
            new BooleanValue("Ghostly (Deprecated)", this, false, new GhostlyDisabler("", this));
76
77
    private final BooleanValue lunar =
78
            new BooleanValue("Lunar (Deprecated)", this, false, new LunarDisabler("", this));
79
80
    public Disabler() {
81
        boolean deprecated = false;
82
83
        for (Value<?> value : getValues()) {
84
            if (deprecated) value.hideIf = () -> !this.deprecated.getValue();
85
            if (value.getName().equalsIgnoreCase("deprecated")) deprecated = true;
86
        }
87
    }
88
}

What this file does

The composition root of the entire disabler suite. Twenty-two BooleanValue fields are declared in order; fifteen of them bind a named bypass to a fresh Mode instance passed as the fourth constructor argument (cubecraft, mineLandKick, verus, vehicle, teleport, vulcan, sprint, omnisprint, universocraft, riseBalance, cancelTransactions, Abilities, input, spectate, cancelKeepAlives), and the deprecated block adds hypixelSlime, mmcReachPartial and mmcKeepSprint, which instantiate second copies of AbilitiesDisabler, TransactionDisabler and SprintDisabler rather than new implementations. The class itself contains no packet logic; it only wires values to modes, so the whole file is 87 lines while the behavior lives in the 19 classes of the disabler subpackage.

The constructor implements the UI deprecation scheme. A local boolean starts false and the loop walks getValues() in declaration order: before processing each value it applies hideIf = () -> !this.deprecated.getValue() if the flag is set, then sets the flag when the current value's name equals 'deprecated'. Because the flag is read before the assignment on every iteration, the Deprecated toggle itself is never hidden, but every value declared after it (hypixelSlime through lunar) only appears in the settings screen while the Deprecated master switch is on. The legacy rows are UI aliases, not separate implementations: Hypixel Slime runs the same abilities spoof as Abilities, MMC Partial Reach the same transaction cancellation as Cancel Transactions, and MMC Keep Sprint the same sprint-packet cancellation as Cancel Sprint Packet.

The module is annotated @Rise and @ModuleInfo with the translation keys module.combat.disabler.name (a leftover from when the module lived in the combat category) and module.exploit.disabler.description, category Category.EXPLOIT. Note that WatchdogDisabler exists in the imported wildcard package but no value instantiates it in this build, so it is an orphaned mode reachable only through its class file.

source AbilitiesDisabler.java (mode)

AbilitiesDisabler.java25 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.motion.StrafeEvent;
7
import com.alan.clients.util.packet.PacketUtil;
8
import com.alan.clients.value.Mode;
9
import net.minecraft.entity.player.PlayerCapabilities;
10
import net.minecraft.network.play.client.C13PacketPlayerAbilities;
11
12
public class AbilitiesDisabler extends Mode<Disabler> {
13
    public AbilitiesDisabler(String name, Disabler parent) {
14
        super(name, parent);
15
    }
16
17
    @EventLink
18
    public final Listener<StrafeEvent> onStrafe = event -> {
19
        if (mc.thePlayer.ticksExisted % 5 == 0) {
20
            final PlayerCapabilities playerCapabilities = new PlayerCapabilities();
21
            playerCapabilities.isFlying = true;
22
            PacketUtil.send(new C13PacketPlayerAbilities(playerCapabilities));
23
        }
24
    };
25
}

What this file does

Spoofs the player's ability flags to the server. On a StrafeEvent (fired every tick while movement input is being processed), and only every fifth tick (ticksExisted % 5 == 0), it builds a fresh PlayerCapabilities, sets isFlying = true, and sends a C13PacketPlayerAbilities built from it.

The C13 constructor copies all six capability fields into the packet: disableDamage, isFlying, allowFlying, isCreativeMode, flySpeed and walkSpeed, serialized as one flags byte plus two floats. A fresh PlayerCapabilities has flySpeed 0.05 and walkSpeed 0.1, so the packet tells the server exactly one thing: the player is flying. This is the classic Hypixel slime-block bypass: slime bounce motion looks like flight to ground checks, and periodically re-asserting the flying flag keeps the server's flight/fall tracker in a state it accepts. The same mode is reused verbatim by the deprecated 'Hypixel Slime' toggle, which is why that row behaves identically to Abilities.

source CubeCraftDisabler.java (mode)

CubeCraftDisabler.java33 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.component.impl.player.BadPacketsComponent;
4
import com.alan.clients.component.impl.player.SelectorDetectionComponent;
5
import com.alan.clients.module.impl.exploit.Disabler;
6
import com.alan.clients.newevent.Listener;
7
import com.alan.clients.newevent.annotations.EventLink;
8
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
9
import com.alan.clients.util.packet.PacketUtil;
10
import com.alan.clients.value.Mode;
11
import net.minecraft.network.play.client.C00PacketKeepAlive;
12
import net.minecraft.network.play.client.C03PacketPlayer;
13
import net.minecraft.network.play.client.C08PacketPlayerBlockPlacement;
14
import net.minecraft.util.BlockPos;
15
import net.minecraft.util.EnumFacing;
16
17
public class CubeCraftDisabler extends Mode<Disabler> {
18
19
    public CubeCraftDisabler(String name, Disabler parent) {
20
        super(name, parent);
21
    }
22
23
    @EventLink()
24
    public final Listener<PacketSendEvent> onPacketSend = event -> {
25
        if (event.getPacket() instanceof C03PacketPlayer && !SelectorDetectionComponent.selector() && mc.currentScreen == null) {
26
            PacketUtil.send(new C08PacketPlayerBlockPlacement(new BlockPos(mc.thePlayer).down(5),
27
                    EnumFacing.UP.getIndex(), null, 0.0F, 1.0F, 0.0F));
28
            BadPacketsComponent.reset();
29
        } else if (event.getPacket() instanceof C00PacketKeepAlive) {
30
            event.setCancelled(true);
31
        }
32
    };
33
}

What this file does

Aimed at CubeCraft's anticheat. For every C03PacketPlayer that reaches the send pipeline, and only while no GUI is open (mc.currentScreen == null) and the selector detection is clear, the mode injects a C08PacketPlayerBlockPlacement targeting the player's own position five blocks down: new BlockPos(mc.thePlayer).down(5), EnumFacing.UP.getIndex(), a null item stack, and facing offsets 0.0F, 1.0F, 0.0F. The C08 constructor verified in the MCP sources is (BlockPos, int direction, ItemStack, float facingX, float facingY, float facingZ), so this is a fake 'place a block under myself' interaction with no held item. CubeCraft's checks correlate block interactions with movement; the phantom placement keeps that correlation from ever lining up.

After the injection the mode calls BadPacketsComponent.reset(), clearing the block/attack/swing flags so the follow-up movement packet is not treated as polluted by the component's consumers. It then cancels every C00PacketKeepAlive, starving the server's keepalive round-trip tracking. The SelectorDetectionComponent.selector() guard skips the injection while the held item is a server selector (an item whose display name does not match its registered name, detected by the component at very high priority each PreUpdate), which avoids sending placement spam through CubeCraft's game-mode selection screens.

source DynamicPVPDisabler.java (mode)

DynamicPVPDisabler.java64 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
7
import com.alan.clients.util.packet.PacketUtil;
8
import com.alan.clients.value.Mode;
9
import net.minecraft.client.entity.EntityPlayerSP;
10
import net.minecraft.network.Packet;
11
import net.minecraft.network.play.client.C00PacketKeepAlive;
12
import net.minecraft.network.play.client.C03PacketPlayer;
13
import net.minecraft.network.play.client.C0BPacketEntityAction;
14
import net.minecraft.network.play.client.C0FPacketConfirmTransaction;
15
16
public class DynamicPVPDisabler extends Mode<Disabler> {
17
    public DynamicPVPDisabler(String name, Disabler parent) {
18
        super(name, parent);
19
    }
20
21
    @EventLink
22
    public final Listener<PacketSendEvent> onPacketSend = event -> {
23
        Packet<?> packet = event.getPacket();
24
25
        if (packet instanceof C03PacketPlayer) {
26
            if (mc.thePlayer.ticksExisted % 3 == 0)
27
                event.setCancelled(true);
28
29
            final C03PacketPlayer packetPlayer = (C03PacketPlayer) event.getPacket();
30
            double x = mc.thePlayer.posX, y = mc.thePlayer.posY, z = mc.thePlayer.posZ;
31
32
            if (packetPlayer.isMoving()) {
33
                x = packetPlayer.getPositionX();
34
                y = packetPlayer.getPositionY();
35
                z = packetPlayer.getPositionZ();
36
            }
37
38
            if (mc.thePlayer.ticksExisted % 20 == 0)
39
                PacketUtil.sendNoEvent(new C03PacketPlayer.C04PacketPlayerPosition(x, y, z, packetPlayer.isOnGround()));
40
41
            event.setPacket(new C03PacketPlayer.C06PacketPlayerPosLook(x, y, z, mc.thePlayer.rotationYaw, mc.thePlayer.rotationPitch, packetPlayer.isOnGround()));
42
        }
43
44
        if (packet instanceof C0FPacketConfirmTransaction || packet instanceof C00PacketKeepAlive)
45
            event.setCancelled(true);
46
47
        if (packet instanceof C0BPacketEntityAction) {
48
            final C0BPacketEntityAction c0B = (C0BPacketEntityAction) packet;
49
50
            if (c0B.getAction().equals(C0BPacketEntityAction.Action.START_SPRINTING)) {
51
                if (EntityPlayerSP.serverSprintState) {
52
                    PacketUtil.sendNoEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));
53
                    EntityPlayerSP.serverSprintState = false;
54
                }
55
56
                event.setCancelled(true);
57
            }
58
59
            if (c0B.getAction().equals(C0BPacketEntityAction.Action.STOP_SPRINTING)) {
60
                event.setCancelled(true);
61
            }
62
        }
63
    };
64
}

What this file does

A legacy all-in-one mode (deprecated in the UI) that rewrites the movement stream. On every C03PacketPlayer it cancels the packet outright every third tick (ticksExisted % 3 == 0), reducing the visible packet rate; every twentieth tick it sends a C04PacketPlayerPosition at the current position via sendNoEvent so the server still receives a movement packet during the cancel cadence; and every surviving packet is replaced with a C06PacketPlayerPosLook carrying the player's live rotation and the original onGround flag. The rewrite guarantees the server always sees position and rotation together, which is the state the vanilla handler and most anticheats expect from a moving player.

Transactions and keepalives are cancelled outright (C0FPacketConfirmTransaction and C00PacketKeepAlive), and the sprint block matches the shared family pattern: START_SPRINTING while the server already believes the player is sprinting triggers a STOP_SPRINTING via sendNoEvent and a serverSprintState reset, then the START is cancelled; STOP_SPRINTING is always cancelled. The combination starves the anticheat's timing oracles (transactions, keepalives) and its sprint-state tracking, so ground and speed checks have only position deltas to reason about.

source GhostlyDisabler.java (mode)

GhostlyDisabler.java51 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
7
import com.alan.clients.util.packet.PacketUtil;
8
import com.alan.clients.value.Mode;
9
import net.minecraft.client.entity.EntityPlayerSP;
10
import net.minecraft.network.Packet;
11
import net.minecraft.network.play.client.C03PacketPlayer;
12
import net.minecraft.network.play.client.C0BPacketEntityAction;
13
import net.minecraft.network.play.client.C0CPacketInput;
14
15
public class GhostlyDisabler extends Mode<Disabler> {
16
    public GhostlyDisabler(String name, Disabler parent) {
17
        super(name, parent);
18
    }
19
20
    @EventLink
21
    public final Listener<PacketSendEvent> onPacketSend = event -> {
22
        Packet<?> packet = event.getPacket();
23
24
        if (packet instanceof C03PacketPlayer) {
25
            PacketUtil.sendNoEvent(new C0CPacketInput());
26
27
            C03PacketPlayer c03PacketPlayer = ((C03PacketPlayer) packet);
28
            double mathGround = Math.round(c03PacketPlayer.y / 0.015625) * 0.015625;
29
30
            c03PacketPlayer.y = mathGround;
31
            c03PacketPlayer.setOnGround(true);
32
            event.setPacket(c03PacketPlayer);
33
        }
34
35
        if (packet instanceof C0BPacketEntityAction) {
36
            final C0BPacketEntityAction c0B = (C0BPacketEntityAction) packet;
37
38
            if (c0B.getAction().equals(C0BPacketEntityAction.Action.START_SPRINTING)) {
39
                if (EntityPlayerSP.serverSprintState) {
40
                    PacketUtil.sendNoEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));
41
                    EntityPlayerSP.serverSprintState = false;
42
                }
43
                event.setCancelled(true);
44
            }
45
46
            if (c0B.getAction().equals(C0BPacketEntityAction.Action.STOP_SPRINTING)) {
47
                event.setCancelled(true);
48
            }
49
        }
50
    };
51
}

What this file does

A deprecated movement-normalization mode. On every C03PacketPlayer it first sends an empty C0CPacketInput via sendNoEvent (the no-argument constructor serializes strafeSpeed 0, forwardSpeed 0, jumping false, sneaking false), then rewrites the movement packet: the Y coordinate is snapped with Math.round(y / 0.015625) * 0.015625, the same 1/64 sub-block grid quantization MoveUtil.roundToGround uses, and onGround is forced true.

The grid snap makes the reported Y an exact multiple of the block grid, matching the height values the server's ground and block-collision logic computes with, so the packet always looks 'on the grid'. Forcing onGround true removes the airborne ambiguity that ground checks flag. The empty C0C input tells the server no movement keys are held while the player is clearly moving, which defeats checks that cross-correlate input packets with position deltas. The sprint cancellation block is identical to the shared family pattern used by SprintDisabler and DynamicPVPDisabler.

source InputDisabler.java (mode)

InputDisabler.java20 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.motion.StrafeEvent;
7
import com.alan.clients.util.packet.PacketUtil;
8
import com.alan.clients.value.Mode;
9
import net.minecraft.network.play.client.C0CPacketInput;
10
11
public class InputDisabler extends Mode<Disabler> {
12
    public InputDisabler(String name, Disabler parent) {
13
        super(name, parent);
14
    }
15
16
    @EventLink
17
    public final Listener<StrafeEvent> onStrafe = event -> {
18
        PacketUtil.send(new C0CPacketInput(0.98f, 0, true, true));
19
    };
20
}

What this file does

Spoofs a constant, valid input state. On every StrafeEvent it sends C0CPacketInput(0.98f, 0, true, true). The packet fields verified in the MCP source are strafeSpeed, forwardSpeed, jumping and sneaking; this call reports a strafe speed of 0.98, no forward movement, and both jump and sneak held.

0.98 is the maximum strafe magnitude the client's movement code can produce (the forward/strafe input multiplier), so any diagonal strafing the player performs is fully covered by the reported input, and the jump/sneak flags give the packet a realistic full input state. Servers and anticheats that validate movement against input packets (comparing reported strafe to position deltas, or flagging movement with zero input) see a continuous, key-driven input stream instead of the zero-input packets a cheat normally emits.

source KeepAliveDisabler.java (mode)

KeepAliveDisabler.java21 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
7
import com.alan.clients.value.Mode;
8
import net.minecraft.network.play.client.C00PacketKeepAlive;
9
10
public class KeepAliveDisabler extends Mode<Disabler> {
11
    public KeepAliveDisabler(String name, Disabler parent) {
12
        super(name, parent);
13
    }
14
15
    @EventLink
16
    public final Listener<PacketSendEvent> onPacketSend = event -> {
17
        if (event.getPacket() instanceof C00PacketKeepAlive) {
18
            event.setCancelled(true);
19
        }
20
    };
21
}

What this file does

Cancels every C00PacketKeepAlive outright, with no echo. The vanilla server's processKeepAlive compares the echoed key against the one it sent and folds the measured round-trip into the player's ping as an exponential moving average (ping = (ping * 3 + elapsed) / 4); with no replies at all, the server's ping estimate goes stale and every check that uses keepalive timing as a clock loses its signal.

This is the bluntest primitive in the suite: anticheats use the keepalive round-trip to measure latency for timer and speed checks, and canceling it makes the client look like it is lagging rather than cheating. The trade-off is real: on servers with strict keepalive timeout handling this mode can produce 'Timed out' disconnects, which is why the WatchdogDisabler takes the softer path of delaying keepalives through PingSpoofComponent instead of dropping them.

source LunarDisabler.java (mode)

LunarDisabler.java50 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
7
import com.alan.clients.util.packet.PacketUtil;
8
import com.alan.clients.value.Mode;
9
import net.minecraft.client.entity.EntityPlayerSP;
10
import net.minecraft.network.Packet;
11
import net.minecraft.network.play.client.C00PacketKeepAlive;
12
import net.minecraft.network.play.client.C03PacketPlayer;
13
import net.minecraft.network.play.client.C0BPacketEntityAction;
14
import net.minecraft.network.play.client.C0FPacketConfirmTransaction;
15
import org.apache.commons.lang3.RandomUtils;
16
17
public class LunarDisabler extends Mode<Disabler> {
18
    public LunarDisabler(String name, Disabler parent) {
19
        super(name, parent);
20
    }
21
22
    @EventLink
23
    public final Listener<PacketSendEvent> onPacketSend = event -> {
24
        Packet<?> packet = event.getPacket();
25
26
        if (packet instanceof C0FPacketConfirmTransaction || packet instanceof C00PacketKeepAlive)
27
            event.setCancelled(true);
28
29
        if (packet instanceof C0BPacketEntityAction) {
30
            final C0BPacketEntityAction c0B = (C0BPacketEntityAction) packet;
31
32
            if (c0B.getAction().equals(C0BPacketEntityAction.Action.START_SPRINTING)) {
33
                if (EntityPlayerSP.serverSprintState) {
34
                    PacketUtil.sendNoEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));
35
                    EntityPlayerSP.serverSprintState = false;
36
                }
37
                event.setCancelled(true);
38
            }
39
40
            if (c0B.getAction().equals(C0BPacketEntityAction.Action.STOP_SPRINTING)) {
41
                event.setCancelled(true);
42
            }
43
        }
44
45
        if (packet instanceof C03PacketPlayer.C04PacketPlayerPosition) {
46
            final C03PacketPlayer.C04PacketPlayerPosition packetPlayerPosition = (C03PacketPlayer.C04PacketPlayerPosition) packet;
47
            event.setPacket(new C03PacketPlayer.C06PacketPlayerPosLook(packetPlayerPosition.getX(), packetPlayerPosition.getY(), packetPlayerPosition.getZ(), mc.thePlayer.rotationYaw + (mc.thePlayer.ticksExisted % 2 == 0 ? RandomUtils.nextFloat(0.05F, 0.1F) : -RandomUtils.nextFloat(0.05F, 0.1F)), mc.thePlayer.rotationPitch, packetPlayerPosition.isOnGround()));
48
        }
49
    };
50
}

What this file does

Targets Lunar Client's anticheat integration. It cancels C0FPacketConfirmTransaction and C00PacketKeepAlive, applies the shared sprint-cancellation block, and rewrites every C04PacketPlayerPosition into a C06PacketPlayerPosLook with a jittered yaw: the yaw is offset by plus or minus a random value between 0.05 and 0.1 degrees, with the sign chosen by tick parity (RandomUtils.nextFloat(0.05F, 0.1F)). Pitch and the original onGround flag pass through unchanged.

The rotation jitter is the point of the mode. Lunar's checks (both the client-side anticheat and server-side integration for Lunar users) watch rotation consistency; converting every position-only packet into a rotation-carrying one with a small alternating yaw offset makes the rotation stream look like genuine mouse movement rather than a fixed cheat angle, while movement itself is reported exactly as vanilla would. The small magnitude keeps the yaw drift below any rotation-speed threshold.

source MineLandKickDisabler.java (mode)

MineLandKickDisabler.java51 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.input.MoveInputEvent;
7
import com.alan.clients.newevent.impl.motion.PreMotionEvent;
8
import com.alan.clients.newevent.impl.other.TeleportEvent;
9
import com.alan.clients.util.player.MoveUtil;
10
import com.alan.clients.value.Mode;
11
12
public class MineLandKickDisabler extends Mode<Disabler> {
13
14
    boolean enabled;
15
16
    public MineLandKickDisabler(String name, Disabler parent) {
17
        super(name, parent);
18
    }
19
20
    @EventLink()
21
    public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
22
23
        if (mc.thePlayer.ticksExisted > 20 && mc.thePlayer.ticksExisted <= 40 && mc.thePlayer.onGround) {
24
            this.enabled = true;
25
        } else if (mc.thePlayer.ticksExisted == 100) {
26
            this.enabled = false;
27
        }
28
29
        if (this.enabled) {
30
            event.setOnGround(true);
31
            event.setPosX(mc.thePlayer.posX - 0.1 * (mc.thePlayer.ticksExisted % 2 == 0 ? 1 : -1));
32
            event.setPosZ(mc.thePlayer.posZ - 0.1 * (mc.thePlayer.ticksExisted % 2 == 0 ? 1 : -1));
33
            event.setPosY(MoveUtil.roundToGround(mc.thePlayer.posY + 1));
34
        }
35
    };
36
37
    @EventLink()
38
    public final Listener<TeleportEvent> onTeleport = event -> {
39
        this.enabled = false;
40
    };
41
42
43
    @EventLink()
44
    public final Listener<MoveInputEvent> onMove = event -> {
45
        if (this.enabled) {
46
            event.setForward(0);
47
            event.setStrafe(0);
48
            event.setJump(false);
49
        }
50
    };
51
}

What this file does

Designed against the Mine Land server's join-period kick checks. A boolean state machine arms during a fixed window: enabled once the player has existed more than 20 ticks and at most 40 ticks while standing on the ground, and disabled again at tick 100. A TeleportEvent (fired when the server corrects the player's position) disables it immediately as a safety valve.

While armed, the PreMotionEvent listener forces onGround true, jitters posX and posZ by plus or minus 0.1 blocks alternating with tick parity, and rewrites posY to MoveUtil.roundToGround(posY + 1), i.e. the current Y plus one block snapped to the 1/64 grid. The MoveInputEvent listener zeroes forward, strafe and jump for the same window. The server therefore sees a player hovering exactly one block above grid-aligned ground, drifting 0.1 blocks sideways every tick with no movement input: the pattern the mode is built to defeat is Mine Land's spawn-time checks that sample early movement and kick on the first anomaly, and the teleport guard stops the desync the moment the server re-anchors the player.

source OmniSprintDisabler.java (mode)

OmniSprintDisabler.java25 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.motion.PreMotionEvent;
7
import com.alan.clients.util.player.MoveUtil;
8
import com.alan.clients.util.rotation.RotationUtil;
9
import com.alan.clients.util.vector.Vector2f;
10
import com.alan.clients.value.Mode;
11
12
public class OmniSprintDisabler extends Mode<Disabler> {
13
14
    public OmniSprintDisabler(String name, Disabler parent) {
15
        super(name, parent);
16
    }
17
18
    @EventLink()
19
    public final Listener<PreMotionEvent> onPreMotion = event -> {
20
        if (!mc.thePlayer.isSwingInProgress && mc.gameSettings.keyBindBack.isKeyDown()) {
21
            event.setYaw(RotationUtil.applySensitivityPatch(new Vector2f((float) Math.toDegrees(MoveUtil.direction()),
22
                    event.getPitch())).x);
23
        }
24
    };
25
}

What this file does

Lets the player sprint in every direction, including backwards. On PreMotionEvent, when the player is not swinging (isSwingInProgress false) and is holding the back key (keyBindBack.isKeyDown()), the event's yaw is overwritten with the x component of RotationUtil.applySensitivityPatch(new Vector2f(Math.toDegrees(MoveUtil.direction()), event.getPitch())).

MoveUtil.direction() computes the yaw of the player's movement vector, flipping 180 degrees when moving backwards, so the sent yaw always points along the direction of travel; the server then interprets the motion as forward movement and never revokes the sprint state, which is what makes backwards sprint work. applySensitivityPatch quantizes the target rotation to the mouse-sensitivity multiplier steps (the same mouseSensitivity^3 * 8 * 0.15 formula vanilla uses for mouse turns, clamped to pitch 90) so the programmatic rotation change is indistinguishable from an actual mouse movement and does not trip rotation checks. The swing guard keeps the spoof from firing while attacking, when rotations are already covered by combat logic.

source RiseBalanceDisabler.java (mode)

RiseBalanceDisabler.java102 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.component.impl.player.BadPacketsComponent;
4
import com.alan.clients.component.impl.player.BlinkComponent;
5
import com.alan.clients.module.impl.exploit.Disabler;
6
import com.alan.clients.newevent.Listener;
7
import com.alan.clients.newevent.annotations.EventLink;
8
import com.alan.clients.newevent.impl.motion.PreMotionEvent;
9
import com.alan.clients.newevent.impl.other.WorldChangeEvent;
10
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
11
import com.alan.clients.newevent.impl.render.Render2DEvent;
12
import com.alan.clients.util.chat.ChatUtil;
13
import com.alan.clients.value.Mode;
14
import com.alan.clients.value.impl.BooleanValue;
15
import net.minecraft.network.Packet;
16
import net.minecraft.network.play.client.C03PacketPlayer;
17
import util.time.StopWatch;
18
19
public class RiseBalanceDisabler extends Mode<Disabler> {
20
21
    private BooleanValue resetOnWorldChange = new BooleanValue("Reset On World Change", this, false);
22
    private BooleanValue forceLowTimer = new BooleanValue("Force low timer when Balance is below 0", this, false);
23
    private BooleanValue display = new BooleanValue("Display", this, false);
24
    private BooleanValue pulse = new BooleanValue("Pulse", this, false);
25
    private BooleanValue onlyWhenStill = new BooleanValue("Only Still", this, false);
26
27
    private double balance = 0;
28
    private final StopWatch stopWatch = new StopWatch();
29
    private final StopWatch lastSend = new StopWatch();
30
31
32
    public RiseBalanceDisabler(String name, Disabler parent) {
33
        super(name, parent);
34
    }
35
36
    @Override
37
    public void onEnable() {
38
        this.reset();
39
    }
40
41
    @Override
42
    public void onDisable() {
43
        BlinkComponent.blinking = false;
44
    }
45
46
    @EventLink()
47
    public final Listener<PacketSendEvent> onPacketSend = event -> {
48
        Packet<?> packet = event.getPacket();
49
50
        if (packet instanceof C03PacketPlayer) {
51
            C03PacketPlayer c03PacketPlayer = ((C03PacketPlayer) packet);
52
53
            if (!c03PacketPlayer.getRotating() && !c03PacketPlayer.isMoving() && !BadPacketsComponent.bad() &&
54
                    (!onlyWhenStill.getValue() || (mc.thePlayer.posX == mc.thePlayer.lastTickPosX && mc.thePlayer.posY == mc.thePlayer.lastTickPosY && mc.thePlayer.posZ == mc.thePlayer.lastTickPosZ))) {
55
                event.setCancelled(true);
56
            }
57
58
            // We use this instead of an else because some other modules might cancel c03s
59
            if (!event.isCancelled() || BlinkComponent.blinking) {
60
                this.balance -= 50;
61
            }
62
63
            this.balance += stopWatch.getElapsedTime();
64
            this.stopWatch.reset();
65
        }
66
    };
67
68
    @EventLink()
69
    public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
70
        if (mc.thePlayer.ticksExisted % 20 == 0 && this.display.getValue()) {
71
            ChatUtil.display("Balance: " + this.balance);
72
        }
73
74
        if (this.pulse.getValue() && mc.timer.timerSpeed > 1) {
75
            BlinkComponent.blinking = true;
76
            if (lastSend.finished(50 * 9)) {
77
                lastSend.reset();
78
                BlinkComponent.dispatch();
79
            }
80
        }
81
    };
82
83
    @EventLink()
84
    public final Listener<WorldChangeEvent> onWorldChange = event -> {
85
        if (this.resetOnWorldChange.getValue()) {
86
            this.reset();
87
            this.balance = 0;
88
        }
89
    };
90
91
    private void reset() {
92
        this.balance = 0;
93
        this.stopWatch.reset();
94
    }
95
96
    @EventLink()
97
    public final Listener<Render2DEvent> onRender2D = event -> {
98
        if (this.forceLowTimer.getValue() && this.balance < 200) {
99
            mc.timer.timerSpeed = this.balance < 0 ? 0.5f : 1;
100
        }
101
    };
102
}

What this file does

A timer-abuse disabler tuned against Rise's own 'Balance' anticheat on its practice servers, driven by a self-tracked ledger. On every C03PacketPlayer, an 'empty' packet (no rotation, no movement, and no bad packets pending, optionally gated to moments when the player is not moving at all) is cancelled outright, so the client stops sending the useless no-op movement packets that inflate the packet rate. The ledger then runs: every C03 that actually goes out (or is held by the blink component) subtracts 50, and the elapsed time since the previous C03, read from a StopWatch, is added. Balance therefore approximates time credit minus 50 milliseconds per sent movement packet, a model of how much the anticheat's packet-rate accounting thinks the client owes.

The optional Pulse mode abuses timer speed: when mc.timer.timerSpeed exceeds 1 it sets BlinkComponent.blinking true and every 450 milliseconds (50 * 9) calls BlinkComponent.dispatch(), which flushes all buffered packets at once. Movement packets accumulate invisibly and then dump in a burst, hiding high tick rates behind periodic bursts. The forceLowTimer option, evaluated on Render2DEvent, clamps mc.timer.timerSpeed to 0.5 when the balance goes negative and to 1 when it recovers above zero, slowing the game below real-time so the ledger never overflows. onEnable resets the ledger, onDisable clears the blink state, and the optional resetOnWorldChange re-zeros everything on a WorldChangeEvent; Display prints the running balance to chat every 20 ticks.

source SpectateDisabler.java (mode)

SpectateDisabler.java20 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.motion.StrafeEvent;
7
import com.alan.clients.util.packet.PacketUtil;
8
import com.alan.clients.value.Mode;
9
import net.minecraft.network.play.client.C18PacketSpectate;
10
11
public class SpectateDisabler extends Mode<Disabler> {
12
    public SpectateDisabler(String name, Disabler parent) {
13
        super(name, parent);
14
    }
15
16
    @EventLink
17
    public final Listener<StrafeEvent> onStrafe = event -> {
18
        PacketUtil.sendNoEvent(new C18PacketSpectate(mc.thePlayer.getUniqueID()));
19
    };
20
}

What this file does

Injects C18PacketSpectate with the player's own UUID on every StrafeEvent, sent via sendNoEvent so it bypasses the client's own packet listeners. The C18 packet verified in the MCP sources carries a single UUID and is handled by the server's processSpectate, which only acts when the player is in spectator mode (func_175149_v): it searches all loaded worlds for the entity with that UUID and re-anchors the spectator to it, unmounting any ridden entity and transferring dimensions if needed.

Targeting your own UUID forces the server to re-anchor the spectator camera and position to your own entity, resetting whatever spectator-position tracking the server (or a server-side anticheat integration) samples for that player. On servers that place players in spectator for death spectating or minigames, this keeps the server-side spectator state pinned to the player's true position instead of a stale one.

source SprintDisabler.java (mode)

SprintDisabler.java39 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
7
import com.alan.clients.util.packet.PacketUtil;
8
import com.alan.clients.value.Mode;
9
import net.minecraft.network.Packet;
10
import net.minecraft.network.play.client.C0BPacketEntityAction;
11
12
public class SprintDisabler extends Mode<Disabler> {
13
14
    public SprintDisabler(String name, Disabler parent) {
15
        super(name, parent);
16
    }
17
18
    @EventLink()
19
    public final Listener<PacketSendEvent> onPacketSend = event -> {
20
        final Packet<?> p = event.getPacket();
21
22
        if (p instanceof C0BPacketEntityAction) {
23
            final C0BPacketEntityAction wrapper = (C0BPacketEntityAction) p;
24
25
            if (wrapper.getAction().equals(C0BPacketEntityAction.Action.START_SPRINTING)) {
26
                if (mc.thePlayer.serverSprintState) {
27
                    PacketUtil.sendNoEvent(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));
28
                    mc.thePlayer.serverSprintState = false;
29
                }
30
31
                event.setCancelled(true);
32
            }
33
34
            if (wrapper.getAction().equals(C0BPacketEntityAction.Action.STOP_SPRINTING)) {
35
                event.setCancelled(true);
36
            }
37
        }
38
    };
39
}

What this file does

The generic 'cancel sprint packet' primitive, reused by the deprecated MMC Keep Sprint toggle. It cancels every C0BPacketEntityAction whose action is START_SPRINTING or STOP_SPRINTING, and keeps the client's local sprint bookkeeping consistent: when a START_SPRINTING arrives while mc.thePlayer.serverSprintState is already true, it first sends a STOP_SPRINTING via sendNoEvent and clears serverSprintState, then cancels the original START.

The serverSprintState field, verified in the client's EntityPlayerSP, is the sprint state the server last heard; vanilla only emits C0B sprint packets when that state changes. By intercepting the change packets and mirroring the state manually, the mode ensures the server never learns the player is sprinting while the client moves at sprint speed. Anticheats that flag sprint-speed movement without a matching entity action see nothing to flag, and the manual state mirror keeps the client from desynchronizing its own sprint logic. SprintDisabler is the purest version of the pattern that DynamicPVPDisabler, LunarDisabler and GhostlyDisabler embed in their larger handlers.

source TeleportDisabler.java (mode)

TeleportDisabler.java67 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
4
import com.alan.clients.module.impl.exploit.Disabler;
5
import com.alan.clients.newevent.Listener;
6
import com.alan.clients.newevent.annotations.EventLink;
7
import com.alan.clients.newevent.impl.motion.PreMotionEvent;
8
import com.alan.clients.util.math.MathUtil;
9
import com.alan.clients.util.packet.PacketUtil;
10
import com.alan.clients.util.player.MoveUtil;
11
import com.alan.clients.value.Mode;
12
import com.alan.clients.value.impl.BooleanValue;
13
import com.alan.clients.value.impl.ModeValue;
14
import com.alan.clients.value.impl.NumberValue;
15
import com.alan.clients.value.impl.SubMode;
16
import net.minecraft.network.play.client.C03PacketPlayer;
17
18
public class TeleportDisabler extends Mode<Disabler> {
19
20
    private final ModeValue direction = new ModeValue("Direction", this)
21
            .add(new SubMode("Up"))
22
            .add(new SubMode("Down"))
23
            .add(new SubMode("Horizontal"))
24
            .setDefault("Up");
25
26
    private final NumberValue delay = new NumberValue("Delay", this, 20, 2, 100, 1);
27
    private final BooleanValue mathGround = new BooleanValue("Math Ground", this, false);
28
    private final BooleanValue groundState = new BooleanValue("Ground State", this, false);
29
30
    public TeleportDisabler(String name, Disabler parent) {
31
        super(name, parent);
32
    }
33
34
    @EventLink()
35
    public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
36
37
        if (mc.thePlayer.ticksExisted % delay.getValue().intValue() == 0) {
38
            double x = event.getPosX();
39
            double y = event.getPosY();
40
            double z = event.getPosZ();
41
42
            switch (direction.getValue().getName()) {
43
                case "Up": {
44
                    y += MathUtil.getRandom(1024, 2048);
45
                    break;
46
                }
47
48
                case "Down": {
49
                    y -= MathUtil.getRandom(1024, 2048);
50
                    break;
51
                }
52
53
                case "Horizontal": {
54
                    x += MathUtil.getRandom(1024, 2048);
55
                    z -= MathUtil.getRandom(1024, 2048);
56
                    break;
57
                }
58
            }
59
60
            if (mathGround.getValue()) {
61
                y = MoveUtil.roundToGround(y);
62
            }
63
64
            PacketUtil.send(new C03PacketPlayer.C04PacketPlayerPosition(x, y, z, groundState.getValue()));
65
        }
66
    };
67
}

What this file does

'Force Server Teleport' desynchronizes the server's position model by sending absurd coordinates on a schedule. Every delay ticks (a NumberValue defaulting to 20, range 2-100) it sends a C04PacketPlayerPosition offset from the current position by a random 1024 to 2048 blocks in the chosen direction (Up, Down or Horizontal via a ModeValue with SubModes), with the onGround flag taken from the groundState option; the mathGround option rounds the sent Y to the 1/64 grid before sending.

The trick survives vanilla's sanity checks, verified in the MCP NetHandlerPlayServer.processPlayer: the 'moved too quickly' test computes each delta component as min(|packet delta|, |player motion|) and flags only when the squared sum exceeds 100, so a single 2000-block jump (whose components are capped to near-zero motion values) passes, and only the |x|,|z| > 3e7 'Illegal position' check is absolute. The server then moves its entity by the full delta, sets the player to the packet's coordinates, and either runs the 'moved wrongly'/collision path back to the previous location (an S08PacketPlayerPosLook rubber-band to the client) or leaves the phantom position in place.

Either outcome resets the server-side movement model: after a correction the server's motion and fall-distance tracking (handleFalling, floatingTickCount) restart from a clean slate, and without one the anticheat reasons about a player 2000 blocks away from its true position. The delay spacing keeps the desync alive while staying under the 80-tick floating-kick threshold, and the direction option tunes which tracker gets confused (Up/Down for vertical checks, Horizontal for speed).

source TransactionDisabler.java (mode)

TransactionDisabler.java21 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
7
import com.alan.clients.value.Mode;
8
import net.minecraft.network.play.client.C0FPacketConfirmTransaction;
9
10
public class TransactionDisabler extends Mode<Disabler> {
11
    public TransactionDisabler(String name, Disabler parent) {
12
        super(name, parent);
13
    }
14
15
    @EventLink
16
    public final Listener<PacketSendEvent> onPacketSend = event -> {
17
        if (event.getPacket() instanceof C0FPacketConfirmTransaction) {
18
            event.setCancelled(true);
19
        }
20
    };
21
}

What this file does

Cancels every C0FPacketConfirmTransaction. The C0F packet verified in the MCP sources carries the window id (a byte on the wire), a short uid, and an accepted flag; the server's processConfirmTransaction looks up the expected uid for the open container's window id and only marks the container craftable when both the uid and the window id match.

Anticheats exploit the transaction exchange as a precise round-trip oracle: each S32PacketConfirmTransaction expects the matching C0F echo, the measured delay is a ping sample, and the uid sequence tracks client responsiveness. Canceling all C0Fs starves that oracle: timer, flight and speed checks that gate on transaction pings lose their timing signal, and the client's effective latency looks infinite to the transaction-based measurements while the server's own window logic simply never confirms. This is the same primitive the deprecated MMC Partial Reach toggle runs, and it pairs with keepalive cancellation in the bigger modes.

source UniversoCraftDisabler.java (mode)

UniversoCraftDisabler.java36 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
7
import com.alan.clients.value.Mode;
8
import net.minecraft.network.Packet;
9
import net.minecraft.network.play.client.C02PacketUseEntity;
10
import net.minecraft.network.play.client.C03PacketPlayer;
11
import net.minecraft.network.play.client.C0FPacketConfirmTransaction;
12
import net.minecraft.network.play.server.S07PacketRespawn;
13
14
public class UniversoCraftDisabler extends Mode<Disabler> {
15
    private boolean disabling;
16
    public UniversoCraftDisabler(String name, Disabler parent) {
17
        super(name, parent);
18
    }
19
20
    @EventLink()
21
    public final Listener<PacketSendEvent> onPacketSend = event -> {
22
        Packet packet = event.getPacket();
23
24
        if (packet instanceof S07PacketRespawn) {
25
            disabling = true;
26
        } else if (packet instanceof C02PacketUseEntity) {
27
            disabling = false;
28
        } else if (packet instanceof C03PacketPlayer && mc.thePlayer.ticksExisted <= 10) {
29
            disabling = true;
30
        } else if (packet instanceof C0FPacketConfirmTransaction && disabling && mc.thePlayer.ticksExisted < 350) {
31
            ((C0FPacketConfirmTransaction) event.getPacket()).setUid(
32
                    mc.thePlayer.ticksExisted % 2 == 0 ? Short.MIN_VALUE : Short.MAX_VALUE);
33
        }
34
    };
35
36
}

What this file does

Targets UniversoCraft's anticheat with a transaction-corruption state machine. A boolean flag ('disabling') is armed by three branches in the send pipeline: an S07PacketRespawn passing through, any C02PacketUseEntity (which disarms it), and any C03PacketPlayer sent within the first ten ticks after joining. While the flag is set and the player has existed for fewer than 350 ticks, every C0FPacketConfirmTransaction has its uid rewritten to Short.MIN_VALUE on even ticks and Short.MAX_VALUE on odd ticks.

The uid is a short on the wire (verified in C0FPacketConfirmTransaction.writePacketData, data.writeShort(this.uid)), and the vanilla server matches it exactly against its expected value in processConfirmTransaction. Corrupting it to the two extreme shorts guarantees the match always fails, so the server's transaction correlation for that window desynchronizes and UniversoCraft's checks that sequence transactions to measure the client can never line up their expected uid. One caveat worth noting: the S07 arm is checked on the outbound pipeline, but S07PacketRespawn is a clientbound packet in vanilla (it arrives through the receive path and is handled by handleRespawn), so in stock flow that branch never arms; the practical drivers are the early-join C03 arm and the disarm on the first attack.

source VehicleDisabler.java (mode)

VehicleDisabler.java22 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.motion.PreMotionEvent;
7
import com.alan.clients.util.packet.PacketUtil;
8
import com.alan.clients.value.Mode;
9
import net.minecraft.network.play.client.C0CPacketInput;
10
11
public class VehicleDisabler extends Mode<Disabler> {
12
13
    public VehicleDisabler(String name, Disabler parent) {
14
        super(name, parent);
15
    }
16
17
    @EventLink()
18
    public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
19
20
        PacketUtil.send(new C0CPacketInput());
21
    };
22
}

What this file does

Sends an empty C0CPacketInput on every PreMotionEvent while the mode is on. The no-argument C0C constructor verified in the MCP sources serializes strafeSpeed 0.0, forwardSpeed 0.0, jumping false and sneaking false.

While riding a vehicle, the server steers the ridden entity from the client's C0C input packets, so a constant zero-input stream tells the server the player is holding no movement keys even while the client moves the vehicle locally. This defeats anticheats that verify vehicle speed against the reported input (flagging 'vehicle moved too fast for input'), and keeps the server's vehicle position model from being fed contradictory steering data. It is the vehicle-specific counterpart of InputDisabler, which spoofs a full input state for on-foot movement.

source VerusCustomDisabler.java (mode)

VerusCustomDisabler.java84 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.module.impl.exploit.Disabler;
4
import com.alan.clients.newevent.Listener;
5
import com.alan.clients.newevent.annotations.EventLink;
6
import com.alan.clients.newevent.impl.motion.PreMotionEvent;
7
import com.alan.clients.newevent.impl.other.TeleportEvent;
8
import com.alan.clients.newevent.impl.other.WorldChangeEvent;
9
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
10
import com.alan.clients.util.packet.PacketUtil;
11
import com.alan.clients.value.Mode;
12
import com.alan.clients.value.impl.BooleanValue;
13
import net.minecraft.network.Packet;
14
import net.minecraft.network.play.client.C03PacketPlayer;
15
import net.minecraft.network.play.client.C0BPacketEntityAction;
16
17
import java.util.concurrent.ConcurrentLinkedQueue;
18
19
public class VerusCustomDisabler extends Mode<Disabler> {
20
21
    private final BooleanValue movementDisabler = new BooleanValue("Movement", this, false);
22
    private final BooleanValue sprintDisabler = new BooleanValue("Sprint", this, false);
23
24
    private final ConcurrentLinkedQueue<Packet<?>> transactions = new ConcurrentLinkedQueue<>();
25
    private final ConcurrentLinkedQueue<Packet<?>> keepAlives = new ConcurrentLinkedQueue<>();
26
27
    private boolean teleported;
28
29
    public VerusCustomDisabler(String name, Disabler parent) {
30
        super(name, parent);
31
    }
32
33
    @EventLink()
34
    public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
35
36
        if (movementDisabler.getValue()) {
37
            if (mc.thePlayer.ticksExisted % 100 == 0) {
38
                PacketUtil.sendNoEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, mc.thePlayer.onGround));
39
                PacketUtil.sendNoEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, -0.015625, mc.thePlayer.posZ, false));
40
                PacketUtil.sendNoEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, mc.thePlayer.onGround));
41
42
                teleported = true;
43
            }
44
        }
45
46
        if (sprintDisabler.getValue()) {
47
            PacketUtil.sendNoEvent(new C0BPacketEntityAction(mc.thePlayer,
48
                    mc.thePlayer.ticksExisted % 2 == 0 ? C0BPacketEntityAction.Action.STOP_SPRINTING :
49
                            C0BPacketEntityAction.Action.START_SPRINTING));
50
        }
51
    };
52
53
    @EventLink()
54
    public final Listener<PacketSendEvent> onPacketSend = event -> {
55
        final Packet<?> packet = event.getPacket();
56
57
        if (sprintDisabler.getValue() && packet instanceof C0BPacketEntityAction) {
58
            C0BPacketEntityAction c0b = ((C0BPacketEntityAction) packet);
59
60
            if (c0b.getAction() == C0BPacketEntityAction.Action.START_SPRINTING ||
61
                    c0b.getAction() == C0BPacketEntityAction.Action.STOP_SPRINTING) {
62
                event.setCancelled(true);
63
            }
64
        }
65
    };
66
67
    @EventLink()
68
    public final Listener<TeleportEvent> onTeleport = event -> {
69
        if (movementDisabler.getValue()) {
70
            if (teleported) {
71
                event.setCancelled(true);
72
            }
73
74
            teleported = false;
75
        }
76
    };
77
78
    @EventLink()
79
    public final Listener<WorldChangeEvent> onWorldChange = event -> {
80
        transactions.clear();
81
        keepAlives.clear();
82
        teleported = false;
83
    };
84
}

What this file does

A Verus bypass with two toggles, Movement and Sprint. The Movement path fires every 100 ticks and sends three C04PacketPlayerPosition packets back to back via sendNoEvent: the current position with the real ground flag, then the same x/z at y = -0.015625 with onGround false, then the current position again. The middle packet claims the player sits exactly at the block boundary just below the ground plane, the classic 'snap to ground' spoof that perturbs Verus's movement model; the mode then sets teleported true and, on the resulting TeleportEvent (fired when the server answers with a position correction), cancels that single event and clears the flag, so the client never rubber-bands while the server-side position model is left confused.

The Sprint path alternates STOP_SPRINTING and START_SPRINTING C0BPacketEntityAction every tick via sendNoEvent while simultaneously cancelling every vanilla sprint entity action, burying Verus's sprint checks in toggle spam while the real sprint state stays hidden. WorldChangeEvent clears the two ConcurrentLinkedQueues (transactions and keepAlives) and resets teleported; those queues are declared and flushed on world change but never populated in this version, vestigial fields left over from an older queue-based Verus disabler that delayed transactions and keepalives instead of using the teleport trick.

source VulcanDisabler.java (mode)

VulcanDisabler.java65 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.component.impl.player.BadPacketsComponent;
4
import com.alan.clients.component.impl.player.BlinkComponent;
5
import com.alan.clients.component.impl.player.GUIDetectionComponent;
6
import com.alan.clients.module.impl.exploit.Disabler;
7
import com.alan.clients.newevent.Listener;
8
import com.alan.clients.newevent.annotations.EventLink;
9
import com.alan.clients.newevent.impl.motion.PreMotionEvent;
10
import com.alan.clients.newevent.impl.packet.PacketSendEvent;
11
import com.alan.clients.util.packet.PacketUtil;
12
import com.alan.clients.value.Mode;
13
import com.alan.clients.value.impl.BooleanValue;
14
import net.minecraft.network.play.client.C07PacketPlayerDigging;
15
import net.minecraft.network.play.client.C0BPacketEntityAction;
16
import net.minecraft.network.play.client.C17PacketCustomPayload;
17
import net.minecraft.util.BlockPos;
18
import net.minecraft.util.EnumFacing;
19
20
public class VulcanDisabler extends Mode<Disabler> {
21
22
    private final BooleanValue sprint = new BooleanValue("Omni-Sprint", this, true);
23
    private final BooleanValue autoClicker = new BooleanValue("Auto Clicker", this, true);
24
    private final BooleanValue reach = new BooleanValue("Reach (4.5 Block)", this, true);
25
    private final BooleanValue movement = new BooleanValue("Strafe and Jump", this, true);
26
    private final BooleanValue fastUse = new BooleanValue("Fast Use", this, true);
27
    private final BooleanValue miscellaneous = new BooleanValue("Miscellaneous (Auto-Block, BadPackets)", this, true);
28
    private final BooleanValue keepSprint = new BooleanValue("Keep Sprint (To disable KeepSprint spoof 1.9)", this, true);
29
30
    public VulcanDisabler(String name, Disabler parent) {
31
        super(name, parent);
32
    }
33
34
    @EventLink()
35
    public final Listener<PacketSendEvent> onPacketSend = event -> {
36
        if (miscellaneous.getValue() && event.getPacket() instanceof C17PacketCustomPayload) {
37
            event.setCancelled(true);
38
        }
39
    };
40
41
    @EventLink()
42
    public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
43
        if (sprint.getValue()) {
44
            PacketUtil.send(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.START_SPRINTING));
45
            PacketUtil.send(new C0BPacketEntityAction(mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));
46
        }
47
48
        if (movement.getValue() && mc.thePlayer.ticksExisted % 5 == 0) {
49
            PacketUtil.send(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.STOP_DESTROY_BLOCK, new BlockPos(mc.thePlayer), EnumFacing.UP));
50
        }
51
52
        if (autoClicker.getValue() && !BadPacketsComponent.bad(false, true, true, false, false) && !GUIDetectionComponent.inGUI()) {
53
            PacketUtil.send(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.START_DESTROY_BLOCK, new BlockPos(mc.thePlayer), EnumFacing.UP));
54
        }
55
56
        if (fastUse.getValue() && mc.thePlayer.ticksExisted % 7 == 0) {
57
            PacketUtil.send(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.DROP_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));
58
        }
59
60
        if (reach.getValue()) {
61
            BlinkComponent.blinking = true;
62
            if (mc.thePlayer.ticksExisted % 2 == 0) BlinkComponent.dispatch();
63
        }
64
    };
65
}

What this file does

A seven-toggle bypass suite for the Vulcan anticheat, with everything defaulting to on. Omni-Sprint sends START_SPRINTING then STOP_SPRINTING back to back on every PreMotionEvent through the normal send path, keeping Vulcan's sprint-action spam checks satisfied while the client sprints freely. Strafe and Jump sends a C07PacketPlayerDigging STOP_DESTROY_BLOCK at the player's own position facing UP every 5 ticks; Auto Clicker sends START_DESTROY_BLOCK at the same position whenever BadPacketsComponent.bad(false, true, true, false, false) reports no attack/swing/block pollution and GUIDetectionComponent.inGUI() reports no chest-like GUI open (the component's display-name mismatch confidence heuristic); Fast Use sends DROP_ITEM at BlockPos.ORIGIN facing DOWN every 7 ticks. The digging/drop packets fake a continuous stream of click, dig and item-use activity, so Vulcan's click-consistency and no-swing checks always see a player that is doing something.

The Reach toggle drives BlinkComponent: it sets blinking true and calls dispatch() every 2 ticks, so outgoing packets buffer in the component's queue and flush in alternating bursts, hiding the hit packets of a 4.5-block reach behind blink timing. Miscellaneous cancels every C17PacketCustomPayload, suppressing the MC|Brand channel and any other plugin channel traffic that Vulcan reads to fingerprint the client. The Keep Sprint toggle is declared with the label 'To disable KeepSprint spoof 1.9' but is not referenced by any listener in this version, making it a dead option.

source WatchdogDisabler.java (mode)

WatchdogDisabler.java31 lines · JavaOriginal ↗
1
package com.alan.clients.module.impl.exploit.disabler;
2
3
import com.alan.clients.component.impl.player.BadPacketsComponent;
4
import com.alan.clients.component.impl.player.PingSpoofComponent;
5
import com.alan.clients.module.impl.exploit.Disabler;
6
import com.alan.clients.newevent.Listener;
7
import com.alan.clients.newevent.annotations.EventLink;
8
import com.alan.clients.newevent.impl.motion.PreUpdateEvent;
9
import com.alan.clients.value.Mode;
10
import util.time.StopWatch;
11
12
public class WatchdogDisabler extends Mode<Disabler> {
13
    private StopWatch stopWatch = new StopWatch();
14
    public WatchdogDisabler(String name, Disabler parent) {
15
        super(name, parent);
16
    }
17
18
    @EventLink
19
    public final Listener<PreUpdateEvent> onPreUpdate = event -> {
20
        if (BadPacketsComponent.bad(false,true,true,true,true)) {
21
            stopWatch.reset();
22
        }
23
24
        if (stopWatch.finished(2000)) {
25
            PingSpoofComponent.setSpoofing((int) (Math.random() * 400),
26
                    true,true,false,false,false,true);
27
        } else {
28
            PingSpoofComponent.dispatch();
29
        }
30
    };
31
}

What this file does

A ping-spoof disabler aimed at Hypixel's Watchdog, gated on packet cleanliness. On every PreUpdateEvent (fired at the top of the client's onUpdateWalkingPlayer, before the movement packet is built), if BadPacketsComponent.bad(false, true, true, true, true) reports attack, swing, block or inventory packets since the last C03, a StopWatch is reset, keeping the spoof disabled while the player is actively fighting. Once the stream has been clean for 2000 milliseconds, it arms PingSpoofComponent.setSpoofing((int) (Math.random() * 400), true, true, false, false, false, true): a random 0-400 millisecond delay with the normal, teleport and client spoof categories enabled and velocity, world and entity disabled. While the stream is dirty it calls PingSpoofComponent.dispatch() instead, flushing the queues.

The component mechanics it drives are verified in PingSpoofComponent: while spoofing, outbound packets (C03, entity actions, clicks, payloads, spectate and more) are pulled from the pipeline into a timed queue, and inbound S32PacketConfirmTransaction and S00PacketKeepAlive (the normal category) plus S08PacketPlayerPosLook (the teleport category) are delayed by the same random amount, so the client's measured ping jumps by a random 0-400ms per spoof cycle. Watchdog's heuristics compare click patterns and movement against ping consistency; an unstable fake latency breaks the 'impossible ping for CPS' and latency-band correlations. The 2-second clean window restricts the spoof to movement-only periods, and the component's own guards disable spoofing entirely for the first 20 ticks, during terrain loading, or when 60ms pass without a PreUpdate.

Structural note: WatchdogDisabler is not instantiated by any BooleanValue in Disabler.java in this build, so it is an orphaned mode that the module never toggles, though every component it drives is fully wired.

anticheat Countering Checks

The anticheat code that detects or counters the techniques this module uses. Full source, with the detection mechanism explained below each box.

anticheat SurvivalFly (moving.survivalfly)

SurvivalFly.java2531 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.moving.player;
16
17
import java.util.ArrayList;
18
import java.util.Collection;
19
import java.util.Locale;
20
21
import org.bukkit.ChatColor;
22
import org.bukkit.Location;
23
import org.bukkit.Material;
24
import org.bukkit.entity.LivingEntity;
25
import org.bukkit.entity.Player;
26
import org.bukkit.util.Vector;
27
28
import fr.neatmonster.nocheatplus.NCPAPIProvider;
29
import fr.neatmonster.nocheatplus.actions.ParameterName;
30
import fr.neatmonster.nocheatplus.checks.Check;
31
import fr.neatmonster.nocheatplus.checks.CheckType;
32
import fr.neatmonster.nocheatplus.checks.ViolationData;
33
import fr.neatmonster.nocheatplus.checks.combined.CombinedData;
34
import fr.neatmonster.nocheatplus.checks.combined.Improbable;
35
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
36
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
37
import fr.neatmonster.nocheatplus.checks.moving.envelope.PhysicsEnvelope;
38
import fr.neatmonster.nocheatplus.checks.moving.envelope.PhysicsGroundResolver;
39
import fr.neatmonster.nocheatplus.checks.moving.envelope.workaround.LostGround;
40
import fr.neatmonster.nocheatplus.checks.moving.envelope.workaround.MagicWorkarounds;
41
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput;
42
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput.ForwardDirection;
43
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerKeyboardInput.StrafeDirection;
44
import fr.neatmonster.nocheatplus.checks.moving.model.LiftOffEnvelope;
45
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerMoveData;
46
import fr.neatmonster.nocheatplus.checks.workaround.WRPT;
47
import fr.neatmonster.nocheatplus.compat.AlmostBoolean;
48
import fr.neatmonster.nocheatplus.compat.Bridge1_13;
49
import fr.neatmonster.nocheatplus.compat.Bridge1_9;
50
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
51
import fr.neatmonster.nocheatplus.compat.SchedulerHelper;
52
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker;
53
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker.Direction;
54
import fr.neatmonster.nocheatplus.compat.versions.ClientVersion;
55
import fr.neatmonster.nocheatplus.components.modifier.IAttributeAccess;
56
import fr.neatmonster.nocheatplus.components.registry.event.IGenericInstanceHandle;
57
import fr.neatmonster.nocheatplus.logging.Streams;
58
import fr.neatmonster.nocheatplus.players.DataManager;
59
import fr.neatmonster.nocheatplus.players.IPlayerData;
60
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
61
import fr.neatmonster.nocheatplus.utilities.StringUtil;
62
import fr.neatmonster.nocheatplus.utilities.collision.CollisionUtil;
63
import fr.neatmonster.nocheatplus.utilities.collision.supportingblock.SupportingBlockUtils;
64
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
65
import fr.neatmonster.nocheatplus.utilities.map.BlockFlags;
66
import fr.neatmonster.nocheatplus.utilities.map.BlockProperties;
67
import fr.neatmonster.nocheatplus.utilities.math.MathUtil;
68
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
69
import fr.neatmonster.nocheatplus.utilities.moving.Magic;
70
import fr.neatmonster.nocheatplus.utilities.moving.MovingUtil;
71
72
/**
73
 * The counterpart to the CreativeFly check, designed for ordinary gameplay (Survival/Adventure)
74
 */
75
@SuppressWarnings({"UnstableApiUsage", "StatementWithEmptyBody"})
76
public class SurvivalFly extends Check {
77
78
    // TODO: Unification of vertical and horizontal motion. Also to reduce the number of RichEntityLocation#collide() calls.
79
80
    /** To join some tags with moving check violations. */
81
    private final ArrayList<String> tags = new ArrayList<>(15);
82
    
83
    private final ArrayList<String> justUsedWorkarounds = new ArrayList<>();
84
    
85
    private final BlockChangeTracker blockChangeTracker;
86
    
87
    private final IGenericInstanceHandle<IAttributeAccess> attributeAccess = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstanceHandle(IAttributeAccess.class);
88
    
89
    /**
90
     * The vertical component of liquid push (water/lava).
91
     * This is computed in hdistrel and then used by vidstrel to avoid having to call the getLiquidPush() method twice.
92
     * When computing the horizontal liquid push, the way Mojang coded the function to get the liquid's flowing force
93
     * to calculate horizontal speed with, also affects the vertical speed (See comment in {@link fr.neatmonster.nocheatplus.utilities.location.RichEntityLocation#getFlowForceVector(int, int, int, long)}.
94
     */
95
    private double verticalLiquidPushComponent = 0.0;
96
    
97
    
98
    public SurvivalFly() {
99
        super(CheckType.MOVING_SURVIVALFLY);
100
        blockChangeTracker = NCPAPIProvider.getNoCheatPlusAPI().getBlockChangeTracker();
101
    }
102
    
103
    
104
    /**
105
     * Checks a player
106
     *
107
     * @param multiMoveCount
108
     *            0: Ordinary, 1/2/(...): first/second/(...) part of a split move.
109
     * @param isNormalOrPacketSplitMove
110
     *           Flag to indicate if the packet-based split move mechanic is used instead of the Bukkit-based one (or the move was not split)
111
     *
112
     * @return The Location where to set back the player to. Null in case of no violation.
113
     */
114
    public Location check(final Player player, final PlayerLocation from, final PlayerLocation to,
115
                          final int multiMoveCount, final MovingData data, final MovingConfig cc,
116
                          final IPlayerData pData, final int tick, final long now,
117
                          final boolean useBlockChangeTracker, final boolean isNormalOrPacketSplitMove) {
118
        /*
119
          TODO: Ideally, all this data should really be set outside SurvivalFly (in the MovingListener), since they can be useful
120
          for other checks / stuff.
121
         */
122
        tags.clear();
123
        justUsedWorkarounds.clear();
124
        // Shortcuts:
125
        final boolean debug = pData.isDebugActive(type);
126
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
127
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
128
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
129
        /*
130
         * Actually forgot what this does. But quick guess might be idle move (0,0,0) on count 1 and riptide on count 2.
131
         * TODO: Is this supposed to be here? (Move in MovingListener at the beginning of checkPayerMove?)
132
         */
133
        if (lastMove.tridentRelease.decideOptimistically() && multiMoveCount == 2 && lastMove.yDistance == 0.0) {
134
            thisMove.tridentRelease = AlmostBoolean.YES;
135
            lastMove.tridentRelease = AlmostBoolean.NO;
136
        }
137
        /* Regular and past fromOnGround */
138
        final boolean fromOnGround = from.isOnGround() || useBlockChangeTracker && from.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick);
139
        /* Regular and past toOnGround */
140
        final boolean toOnGround = to.isOnGround() || useBlockChangeTracker && to.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick);  // TODO: Work in the past ground stuff differently (thisMove, touchedGround?, from/to ...)
141
        /* Moving onto/into everything that isn't in air (liquids, stuck-speed, ground, ALL) */
142
        final boolean resetTo = toOnGround || to.isResetCond();
143
        /* Moving off from anything that is not air (liquids, stuck-speed, ground, ALL). */
144
        final boolean resetFrom = fromOnGround || from.isResetCond();
145
        // Run lostground checks.
146
        LostGround.runLostGroundChecks(player, from, to, thisMove.hDistance, thisMove.yDistance, lastMove, data, cc, useBlockChangeTracker ? blockChangeTracker : null, tags);
147
148
        // Set workarounds for the registry
149
        data.ws.setJustUsedIds(justUsedWorkarounds);
150
151
        // Recover from data removal (somewhat random insertion point).
152
        if (data.liftOffEnvelope == LiftOffEnvelope.UNKNOWN) {
153
            data.adjustLiftOffEnvelope(from);
154
        }
155
156
        // Adjust block properties (friction, block speed etc...)
157
        data.adjustMediumProperties(player, from);
158
        
159
        // Ground somehow appeared out of thin air (block place).
160
        // This move is registered as "coming from ground" despite the player not having moved onto ground with the previous move, which was fully in air.
161
        if (thisMove.touchedGround) {
162
            if (multiMoveCount == 0 && thisMove.from.onGround && PhysicsEnvelope.inAir(lastMove) 
163
                && TrigUtil.isSamePosAndLook(thisMove.from, lastMove.to)) {
164
                data.setSetBack(from);
165
                if (debug) {
166
                    debug(player, "Ground appeared due to a block-place: adjust set-back location.");
167
                }
168
            }
169
        }
170
171
        // Decrease bunnyhop delay counter
172
        if (data.jumpDelay > 0) {
173
            data.jumpDelay--;
174
        }
175
      
176
177
178
        /////////////////////////////////////
179
        // Horizontal move                ///
180
        /////////////////////////////////////
181
        double hAllowedDistance, hDistanceAboveLimit, hFreedom;
182
        double[] resGlide = processGliding(from, to, pData, data, player, isNormalOrPacketSplitMove, fromOnGround, toOnGround, debug);
183
        // Set the allowed distance and determine the distance above limit
184
        double[] hRes = Bridge1_9.isGliding(player) ? resGlide : prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
185
        hAllowedDistance = hRes[0];
186
        hDistanceAboveLimit = hRes[1];
187
        // Beyond limit? Check if there may have been a reason for this (and try to re-estimate if needed)
188
        if (hDistanceAboveLimit > 0.0) {
189
            double[] res = hDistAfterFailure(player, from, to, hAllowedDistance, hDistanceAboveLimit, thisMove, lastMove, debug, data, cc, pData, tick, useBlockChangeTracker, fromOnGround, toOnGround, isNormalOrPacketSplitMove);
190
            hAllowedDistance = res[0];
191
            hDistanceAboveLimit = res[1];
192
            hFreedom = res[2];
193
        }
194
        else {
195
            // Clear active velocity if the distance is within limit (clearly not needed. :))
196
            //data.clearActiveHorVel();
197
            hFreedom = 0.0;
198
        }
199
200
201
        /////////////////////////////////////
202
        // Vertical move                  ///
203
        /////////////////////////////////////
204
        // Order of checking in EntityLiving.java water -> lava -> gliding -> air
205
        // TODO: Clean-up this left-over bit of the old implementation (respect MC's order)
206
        double yAllowedDistance, yDistanceAboveLimit;
207
        if (Bridge1_9.isGliding(player)) {
208
            yAllowedDistance = resGlide[2];
209
            yDistanceAboveLimit = resGlide[3];
210
        }
211
        else {
212
            final double[] res = vDistRel(player, from, fromOnGround, resetFrom, to, toOnGround, resetTo, thisMove.yDistance, isNormalOrPacketSplitMove, lastMove, data, pData, false, debug, useBlockChangeTracker );
213
            yAllowedDistance = res[0];
214
            yDistanceAboveLimit = res[1];
215
        }
216
217
        ////////////////////////////
218
        // Debug output.          //
219
        ////////////////////////////
220
        final int tagsLength;
221
        if (debug) {
222
            outputDebug(player, to, from, data, thisMove.hDistance, hAllowedDistance, hFreedom, thisMove.yDistance, yAllowedDistance, fromOnGround, resetFrom, toOnGround, resetTo, thisMove);
223
            tagsLength = tags.size();
224
            data.ws.setJustUsedIds(null);
225
        }
226
        else tagsLength = 0; // JIT vs. IDE.
227
228
229
        //////////////////////////////////////
230
        // Handle violations               ///
231
        //////////////////////////////////////
232
        final boolean inAir = PhysicsEnvelope.inAir(thisMove);
233
        final double result = (Math.max(hDistanceAboveLimit, 0.0) + Math.max(yDistanceAboveLimit, 0.0)) * 100D;
234
        if (result > 0.0) {
235
            final Location vLoc = handleViolation(result, player, from, to, data, cc);
236
            if (inAir) {
237
                data.sfVLInAir = true;
238
            }
239
            // Request a new to-location
240
            if (vLoc != null) {
241
                return vLoc;
242
            }
243
        }
244
        else {
245
            if (canRelaxVL(data, cc, inAir, lastMove, thisMove)) {
246
                // Relax VL.
247
                data.survivalFlyVL *= 0.95;
248
            }
249
        }
250
251
252
        //////////////////////////////////////////////////////////////////////////////////////////////
253
        //  Set data for normal move or violation without cancel (cancel would have returned above) //
254
        //////////////////////////////////////////////////////////////////////////////////////////////
255
        // Adjust lift off envelope to medium
256
        if (thisMove.to.inPowderSnow) {
257
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_POWDER_SNOW;
258
        }
259
        else if (thisMove.to.inWeb) {
260
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_WEBS;
261
        }
262
        else if (thisMove.to.inBerryBush) {
263
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_SWEET_BERRY;
264
        }
265
        else if (thisMove.to.onHoneyBlock) {
266
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_HONEY_BLOCK;
267
        }
268
        else if (resetTo) {
269
            data.liftOffEnvelope = LiftOffEnvelope.NORMAL;
270
        }
271
        else if (thisMove.from.inPowderSnow) {
272
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_POWDER_SNOW;
273
        }
274
        else if (thisMove.from.inWeb) {
275
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_WEBS;
276
        }
277
        else if (thisMove.from.inBerryBush) {
278
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_SWEET_BERRY;
279
        }
280
        else if (thisMove.from.onHoneyBlock) {
281
            data.liftOffEnvelope = LiftOffEnvelope.LIMIT_HONEY_BLOCK;
282
        }
283
        else if (resetFrom || thisMove.touchedGround) {
284
            data.liftOffEnvelope = LiftOffEnvelope.NORMAL;
285
        }
286
        else {
287
            // Air, Keep medium.
288
        }
289
290
        // Apply reset conditions.
291
        if (resetTo) {
292
            // Reset data.
293
            data.setSetBack(to);
294
            data.sfJumpPhase = 0;
295
        }
296
        // The player moved from ground.
297
        else if (resetFrom) {
298
            data.setSetBack(from);
299
            data.sfJumpPhase = 1; // This event is already in air.
300
        }
301
        else {
302
            data.sfJumpPhase ++;
303
            if (!Double.isInfinite(Bridge1_9.getLevitationAmplifier(player))
304
                || Bridge1_13.isRiptiding(player)
305
                || Bridge1_9.isGliding(player)) {
306
                data.setSetBack(to);
307
            }
308
        }
309
310
        // Adjust not in-air stuff.
311
        if (!inAir) {
312
            data.ws.resetConditions(WRPT.G_RESET_NOTINAIR);
313
            data.sfVLInAir = false;
314
        }
315
316
        // Update unused velocity tracking.
317
        // TODO: Hide and seek with API.
318
        // TODO: Pull down tick / timing data (perhaps add an API object for millis + source + tick + sequence count (+ source of sequence count).
319
        if (debug) {
320
            // TODO: Only update, if velocity is queued at all.
321
            data.getVerticalVelocityTracker().updateBlockedState(tick,
322
                    // Assume blocked with being in web/water, despite not entirely correct.
323
                    thisMove.headObstructed || thisMove.from.resetCond,
324
                    // (Similar here.)
325
                    thisMove.touchedGround || thisMove.to.resetCond);
326
            // TODO: TEST: Check unused velocity here too. (Should have more efficient process, pre-conditions for checking.)
327
            UnusedVelocity.checkUnusedVelocity(player, type, data, cc);
328
        }
329
330
        // Adjust various speed/friction factors (both h/v).
331
        data.lastFrictionVertical = data.nextFrictionVertical;
332
        data.lastFrictionHorizontal = data.nextFrictionHorizontal;
333
        data.lastStuckInBlockVertical = data.nextStuckInBlockVertical;
334
        data.lastStuckInBlockHorizontal = data.nextStuckInBlockHorizontal;
335
        data.lastBlockSpeedMultiplier = data.nextBlockSpeedMultiplier;
336
        data.lastInertia = data.nextInertia;
337
        data.lastLevitationLevel = !Double.isInfinite(Bridge1_9.getLevitationAmplifier(player)) ? Bridge1_9.getLevitationAmplifier(player) + 1 : 0.0;
338
        data.lastGravity = data.nextGravity;
339
        data.lastCollidingEntitiesLocations = CollisionUtil.getCollidingEntitiesLocations(player);
340
        cData.wasSprinting = pData.isSprinting();
341
        cData.wasPressingShift = pData.isShiftKeyPressed();
342
        cData.wasSlowFalling = !Double.isInfinite(Bridge1_13.getSlowfallingAmplifier(player));
343
        cData.wasLevitating = !Double.isInfinite(Bridge1_9.getLevitationAmplifier(player));
344
        // Log tags added after violation handling.
345
        if (debug && tags.size() > tagsLength) {
346
            logPostViolationTags(player);
347
        }
348
        // Nothing to do, newTo (MovingListener) stays null
349
        return null;
350
    }
351
    
352
    
353
    /**
354
     * Check if the violation level may decrease.
355
     * 
356
     * @param data
357
     * @param cc
358
     * @param inAir
359
     * @param lastMove
360
     * @param thisMove
361
     * @return
362
     */
363
    private boolean canRelaxVL(MovingData data, MovingConfig cc, boolean inAir, PlayerMoveData lastMove, PlayerMoveData thisMove) {
364
        // Slowly reduce the level with each event, if violations have not recently happened.
365
        return data.getPlayerMoveCount() - data.sfVLMoveCount > cc.survivalFlyVLFreezeCount
366
                && (!cc.survivalFlyVLFreezeInAir || !inAir
367
                // Favor bunny-hopping slightly: clean descend.
368
                || !data.sfVLInAir
369
                && data.liftOffEnvelope == LiftOffEnvelope.NORMAL
370
                && lastMove.toIsValid
371
                && lastMove.yDistance < -Magic.GRAVITY_MIN
372
                && thisMove.yDistance - lastMove.yDistance < -Magic.GRAVITY_MIN);
373
    }
374
    
375
    
376
    /**
377
     * A check to prevent players from bed-flying.
378
     * To be called on PlayerBedLeaveEvent(s)
379
     * (This increases VL and sets tag only. Setback is done in MovingListener).
380
     *
381
     * @return If to prevent action (use the setback location of survivalfly).
382
     */
383
    public boolean checkBed(final Player player, final MovingConfig cc, final MovingData data) {
384
        boolean cancel = false;
385
        // Check if the player had been in bed at all.
386
        if (!data.wasInBed) {
387
            // Violation ...
388
            tags.add("bedfly");
389
            data.survivalFlyVL += 100D;
390
            Improbable.check(player, (float) 5.0, System.currentTimeMillis(), "moving.survivalfly.bedfly", DataManager.getPlayerData(player));
391
            final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, 100D, cc.survivalFlyActions);
392
            if (vd.needsParameters()) vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
393
            cancel = executeActions(vd).willCancel();
394
        }
395
        // Nothing detected.
396
        else data.wasInBed = false;
397
        return cancel;
398
    }
399
400
401
    /**
402
     * Check for push/pull by pistons, alter data appropriately (blockChangeId).
403
     */
404
    private double[] getVerticalBlockMoveResult(final double yDistance, final PlayerLocation from, final PlayerLocation to, final MovingData data) {
405
        /*
406
         * TODO: Pistons pushing horizontally allow similar/same upwards
407
         * (downwards?) moves (possibly all except downwards, which is hard to
408
         * test :p).
409
         */
410
        // TODO: Allow push up to 1.0 (or 0.65 something) even beyond block borders, IF COVERED [adapt PlayerLocation].
411
        // TODO: Other conditions/filters ... ?
412
        // Push (/pull) up.
413
        if (yDistance > 0.0) {
414
            if (yDistance <= 1.015) {
415
                /*
416
                 * (Full blocks: slightly more possible, ending up just above
417
                 * the block. Bounce allows other end positions.)
418
                 */
419
                // TODO: Is the air block wich the slime block is pushed onto really in? 
420
                if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, Direction.Y_POS, Math.min(yDistance, 1.0))) {
421
                    if (yDistance > 1.0) {
422
                        if (to.getY() - to.getBlockY() >= 0.015) {
423
                            // Exclude ordinary cases for this condition.
424
                            return null;
425
                        }
426
                    }
427
                    tags.add("blkmv_y_pos");
428
                    final double maxDistYPos = yDistance; //1.0 - (from.getY() - from.getBlockY()); // TODO: Margin ?
429
                    return new double[]{maxDistYPos, 0.0};
430
                }
431
            }
432
        }
433
        // Push (/pull) down.
434
        else if (yDistance < 0.0 && yDistance >= -1.0) {
435
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, Direction.Y_NEG, -yDistance)) {
436
                tags.add("blkmv_y_neg");
437
                final double maxDistYNeg = yDistance; // from.getY() - from.getBlockY(); // TODO: Margin ?
438
                return new double[]{maxDistYNeg, 0.0};
439
            }
440
        }
441
        // Nothing found.
442
        return null;
443
    }
444
445
446
    /**
447
     * Determine the allowed h / v distance for gliding.
448
     * Handled in its own method because of vertical and horizontal motion being too intertwined to separate (y-distance changes relate to h-distance changes). <br>
449
     * Consistency checks are done within the {@link fr.neatmonster.nocheatplus.checks.combined.CombinedListener}.<br>
450
     * <li> NOTE: this should be called with {@link Bridge1_9#isGliding(LivingEntity)} not {@link Bridge1_9#isGlidingWithElytra(Player)}, because the client does not check for elytra to apply the corresponding motion (EntityLiving, travel())</li>
451
     *
452
     * @return the allowed xyz distances + distances above limit.
453
     */
454
    private double[] processGliding(final PlayerLocation from, final PlayerLocation to, final IPlayerData pData, final MovingData data,
455
                                    final Player player, boolean isNormalOrPacketSplitMove, final boolean fromOnGround, final boolean toOnGround, final boolean debug) {
456
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
457
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
458
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
459
        double yDistanceAboveLimit = 0.0, hDistanceAboveLimit = 0.0;
460
        // TODO: What with gliding + rocket boosting + riptiding + bouncing on slimes/beds while riptiding? LMAO
461
        // Beats me why Mojang keeps letting players perform such ridiculous moves.
462
        if (!Bridge1_9.isGliding(player)) {
463
            // No Gliding, no deal
464
            return new double[] {thisMove.hDistance, 0.0, thisMove.yDistance, 0.0};
465
        }
466
        // Note: WASD key presses, as well as sneaking and item-use are irrelevant when gliding.
467
        // Initialize speed.
468
        thisMove.xAllowedDistance = lastMove.toIsValid ? lastMove.xDistance : 0.0;
469
        thisMove.yAllowedDistance = lastMove.toIsValid ? lastMove.yDistance : 0.0;
470
        thisMove.zAllowedDistance = lastMove.toIsValid ? lastMove.zDistance : 0.0;
471
        // Reset momentum if collided with something on the previous tick.
472
        doWallCollision(lastMove, thisMove);
473
        // Throttle speed if stuck in a block.
474
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
475
            if (data.lastStuckInBlockVertical != 1.0) {
476
                thisMove.yAllowedDistance = 0.0;
477
            }
478
            if (data.lastStuckInBlockHorizontal != 1.0) {
479
                thisMove.xAllowedDistance = thisMove.zAllowedDistance = 0.0;
480
            }
481
        }
482
        // Reset speed if judged to be negligible.
483
        checkNegligibleMomentum(pData, thisMove);
484
        checkNegligibleMomentumVertical(pData, thisMove, null);
485
        // Yes, players can glide and riptide at the same time, increasing speed at a faster rate than chunks can load...
486
        // Surely a questionable decision on Mojang's part.
487
        // NOTE: For the elytra, this has to be done before applying gravity and other motion changes.
488
        if (thisMove.tridentRelease.decideOptimistically()) {
489
            thisMove.tridentRelease = AlmostBoolean.YES;
490
            Vector riptideVelocity = to.getRiptideVelocity(false); // Cannot glide while on ground, so no need to check for it.
491
            thisMove.xAllowedDistance += riptideVelocity.getX();
492
            thisMove.yAllowedDistance += riptideVelocity.getY();
493
            thisMove.zAllowedDistance += riptideVelocity.getZ();
494
        }
495
        // TODO: Reduce verbosity (at least, make it easier to look at)
496
        Vector viewVector = TrigUtil.getLookingDirection(to, player);
497
        float radianPitch = to.getPitch() * TrigUtil.toRadians;
498
        // Horizontal length of the look direction
499
        double viewVecHorizontalLength = MathUtil.dist(viewVector.getX(), viewVector.getZ());
500
        // Horizontal length of the movement
501
        double thisMoveHDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance); // NOTE: MUST BE the ALLOWED distances.
502
        // Overall length of the look direction.
503
        double viewVectorLength = viewVector.length();
504
        // Mojang switched from their own cosine function to the standard Math.cos() one in 1.18.2
505
        double cosPitch = pData.getClientVersion().isAtMost(ClientVersion.V_1_18_2) ? TrigUtil.cos((double)radianPitch) : Math.cos((double)radianPitch);
506
        cosPitch = cosPitch * cosPitch * Math.min(1.0, viewVectorLength / 0.4);
507
        // Base gravity when gliding.
508
        thisMove.yAllowedDistance += (cData.wasSlowFalling && lastMove.yDistance <= 0.0 ? Magic.SLOW_FALL_GRAVITY : Magic.DEFAULT_GRAVITY) * (-1.0 + cosPitch * 0.75);
509
        double baseSpeed;
510
        if (thisMove.yAllowedDistance < 0.0 && viewVecHorizontalLength > 0.0) {
511
            // Slow down.
512
            baseSpeed = thisMove.yAllowedDistance * -0.1 * cosPitch;
513
            thisMove.xAllowedDistance += viewVector.getX() * baseSpeed / viewVecHorizontalLength;
514
            thisMove.yAllowedDistance += baseSpeed;
515
            thisMove.zAllowedDistance += viewVector.getZ() * baseSpeed / viewVecHorizontalLength;
516
        }
517
        if (radianPitch < 0.0 && viewVecHorizontalLength > 0.0) {
518
            // Looking down speeds up the player.
519
            baseSpeed = thisMoveHDistance * (double) (-TrigUtil.sin(radianPitch)) * 0.04;
520
            thisMove.xAllowedDistance += -viewVector.getX() * baseSpeed / viewVecHorizontalLength;
521
            thisMove.yAllowedDistance += baseSpeed * 3.2;
522
            thisMove.zAllowedDistance += -viewVector.getZ() * baseSpeed / viewVecHorizontalLength;
523
        }
524
        if (viewVecHorizontalLength > 0.0) {
525
            // Accelerate
526
            thisMove.xAllowedDistance += (viewVector.getX() / viewVecHorizontalLength * thisMoveHDistance - thisMove.xAllowedDistance) * 0.1;
527
            thisMove.zAllowedDistance += (viewVector.getZ() / viewVecHorizontalLength * thisMoveHDistance - thisMove.zAllowedDistance) * 0.1;
528
        }
529
        // Boosted with a firework: propel the player.
530
        if (data.fireworksBoostDuration > 0) {
531
            // TODO: Firework netcode is horrible (a single firework can tick twice on the same tick, skipping the subsequent one), so simply applying the increase of speed won't cut it.
532
            // Not even sure if we can predict this at all without some kind of hacks / workarounds.
533
            thisMove.xAllowedDistance += viewVector.getX() * 0.1 + (viewVector.getX() * 1.5 - thisMove.xAllowedDistance) * 0.5;
534
            thisMove.yAllowedDistance += viewVector.getY() * 0.1 + (viewVector.getY() * 1.5 - thisMove.yAllowedDistance) * 0.5;
535
            thisMove.zAllowedDistance += viewVector.getZ() * 0.1 + (viewVector.getZ() * 1.5 - thisMove.zAllowedDistance) * 0.5;
536
        }
537
        // Friction here. (TEST)
538
        // Note about inertia: the game assigns the radian pitch to the "f" variable, which is the variable used to apply friction at the end of the tick, _normally_.
539
        // However, with gliding, the game does not use the f variable at the end of the tick, but instead applies the magic value of 0.99.
540
        thisMove.xAllowedDistance *= 0.99;
541
        thisMove.yAllowedDistance *= data.lastFrictionVertical;
542
        thisMove.zAllowedDistance *= 0.99;
543
        // Stuck-speed with the updated multiplier (both at the end)
544
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
545
            thisMove.xAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
546
            thisMove.yAllowedDistance *= (double) data.nextStuckInBlockVertical;
547
            thisMove.zAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
548
        }
549
        // Collisions last.
550
        Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, thisMove.yAllowedDistance, thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround, from.getBoundingBox());
551
        thisMove.collideX = collisionVector.getX() != thisMove.xAllowedDistance;
552
        thisMove.collideY = collisionVector.getY() != thisMove.yAllowedDistance;
553
        thisMove.collideZ = collisionVector.getZ() != thisMove.zAllowedDistance;
554
        thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
555
        thisMove.xAllowedDistance = collisionVector.getX();
556
        thisMove.yAllowedDistance = collisionVector.getY();
557
        thisMove.zAllowedDistance = collisionVector.getZ();
558
559
        // Can a vertical workaround apply? If so, override the prediction.
560
        if (MagicWorkarounds.checkPostPredictWorkaround(data, fromOnGround, toOnGround, from, to, thisMove.yAllowedDistance, player, isNormalOrPacketSplitMove)) {
561
            thisMove.yAllowedDistance = thisMove.yDistance;
562
        }
563
        
564
        ////////////////////////////
565
        /// Calculate offests     //
566
        ////////////////////////////
567
        /* Expected difference from current to allowed */
568
        final double offsetV = thisMove.yDistance - thisMove.yAllowedDistance;
569
        if (Math.abs(offsetV) < Magic.PREDICTION_EPSILON) {
570
            // Accuracy margin.
571
        }
572
        else {
573
            // If velocity can be used for compensation, use it.
574
            if (data.getOrUseVerticalVelocity(thisMove.yDistance).isEmpty()) {
575
                yDistanceAboveLimit = Math.max(yDistanceAboveLimit, Math.abs(offsetV));
576
                tags.add("vdistrel");
577
            }
578
        }
579
580
        thisMove.hAllowedDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance);
581
        final double offsetH = thisMove.hDistance - thisMove.hAllowedDistance;
582
        if (offsetH < Magic.PREDICTION_EPSILON) {
583
            // Accuracy margin.
584
        }
585
        else {
586
            hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offsetH);
587
            if (hDistanceAboveLimit > 0.0) {
588
                tags.add("hdistrel");
589
            }
590
        }
591
        if (debug) {
592
            player.sendMessage(ChatColor.RED + "[SurvivalFly] vdistrel: predict=" + StringUtil.fdec6.format(thisMove.yAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.yDistance) + ", offset=" + StringUtil.fdec6.format(offsetV));
593
            player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] hdistrel: predict=" + StringUtil.fdec6.format(thisMove.hAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.hDistance) + ", offset=" + StringUtil.fdec6.format(offsetH));
594
        }
595
        return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit, thisMove.yAllowedDistance, yDistanceAboveLimit};
596
    }
597
    
598
    /**
599
     * Reset the given speed upon wall collision.
600
     * 
601
     * @param lastMove
602
     * @param thisMove
603
     */
604
    private void doWallCollision(PlayerMoveData lastMove, PlayerMoveData thisMove) {
605
        if (lastMove.collideX) {
606
            thisMove.xAllowedDistance = 0.0;
607
        }
608
        if (lastMove.collideZ) {
609
            thisMove.zAllowedDistance = 0.0;
610
        }
611
    }
612
    
613
    /**
614
     * Check if the allowed speed set in thisMove should be canceled due to it being lower than the negligible speed threshold. <br>
615
     * (Horizontal only)
616
     * 
617
     * @param pData
618
     * @param thisMove
619
     */
620
    private void checkNegligibleMomentum(IPlayerData pData, PlayerMoveData thisMove) {
621
        if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_21_5)) {
622
            // This condition was added on 1.21.5. If the horizontal distance squared is below 0.000009 and the entity is a player, both horizontal momenta are set to 0.0.
623
            // This means that both x/z momenta can be reset even if one of them is above the threshold, as long as the overall horizontal momentum is below the threshold.
624
            // EntityLiving.java -> aiStep
625
            // We use the unchecked hDistance for performance reasons (no sqrt needed).
626
            if (thisMove.hDistance < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
627
                thisMove.xAllowedDistance = 0.0;
628
                thisMove.zAllowedDistance = 0.0;
629
            }
630
        }
631
        else if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_9)) {
632
            if (Math.abs(thisMove.xAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
633
                thisMove.xAllowedDistance = 0.0;
634
            }
635
            if (Math.abs(thisMove.zAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD) {
636
                thisMove.zAllowedDistance = 0.0;
637
            }
638
        }
639
        else {
640
            // In 1.8 and lower, momentum is compared to 0.005 instead.
641
            if (Math.abs(thisMove.xAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY) {
642
                thisMove.xAllowedDistance = 0.0;
643
            }
644
            if (Math.abs(thisMove.zAllowedDistance) < Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY) {
645
                thisMove.zAllowedDistance = 0.0;
646
            }
647
        }
648
    }
649
    
650
    /**
651
     * Check if the allowed speed set in thisMove should be canceled due to it being lower than the negligible speed threshold. <br>
652
     * (Vertical only).
653
     * 
654
     * @param pData
655
     * @param thisMove
656
     * @param yTheoreticalDistance
657
     */
658
    private void checkNegligibleMomentumVertical(IPlayerData pData, PlayerMoveData thisMove, double[] yTheoreticalDistance) {
659
        final double threshold = pData.getClientVersion().isAtLeast(ClientVersion.V_1_9) ? Magic.NEGLIGIBLE_SPEED_THRESHOLD : Magic.NEGLIGIBLE_SPEED_THRESHOLD_LEGACY;
660
        final boolean direct = yTheoreticalDistance == null;
661
        if (direct) {
662
            if (Math.abs(thisMove.yAllowedDistance) < threshold) {
663
                thisMove.yAllowedDistance = 0.0;
664
            }
665
        } else {
666
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
667
                if (Math.abs(yTheoreticalDistance[i]) < threshold) {
668
                    yTheoreticalDistance[i] = 0.0;
669
                }
670
            }
671
        }
672
    }
673
    
674
    /**
675
     * Prepares the estimation for horizontal speed of the player based on various conditions.
676
     *
677
     * @param forceSetOnGround Whether to forcibly consider the ground status of the player (despite being off ground).
678
     * @param forceSetOffGround Whether to forcibly ignore the ground status of the player (despite being on the ground).
679
     * @param isNormalOrPacketSplitMove Whether this movement has been corrected due to a faulty PlayerMoveEvent or is normal (no correction needed)
680
     *
681
     * @return hAllowedDistance, hDistanceAboveLimit
682
     */
683
    private double[] prepareSpeedEstimation(final PlayerLocation from, final PlayerLocation to, final IPlayerData pData, final Player player,
684
                                            final MovingData data, final PlayerMoveData thisMove, final PlayerMoveData lastMove,
685
                                            final boolean fromOnGround, final boolean toOnGround, final boolean debug,
686
                                            final boolean isNormalOrPacketSplitMove, boolean forceSetOnGround, boolean forceSetOffGround) {
687
        double hDistanceAboveLimit;
688
        //////////////////////////
689
        // Early return(s)      //
690
        //////////////////////////
691
        if (!isNormalOrPacketSplitMove) {
692
            // Bukkit-based split move: predicting the next speed is not possible due to coordinates not being reported correctly by Bukkit (and without ProtocolLib, it's nearly impossible to achieve precision here)
693
            thisMove.xAllowedDistance = thisMove.xDistance;
694
            thisMove.zAllowedDistance = thisMove.zDistance;
695
            thisMove.hAllowedDistance = thisMove.hDistance;
696
            hDistanceAboveLimit = 0.0;
697
            return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit};
698
        }
699
        
700
        boolean onGround = PhysicsGroundResolver.resolvePhysicsOnGround(from, thisMove, lastMove, forceSetOnGround, forceSetOffGround);
701
        /* All moves are assumed to be predictable, unless there are technical limitations / bugs / glitches that we cannot solve */
702
        boolean isPredictable;
703
        //////////////////////////////////////////////////////////////
704
        // Estimate the horizontal speed (per-move distance check)  //                      
705
        //////////////////////////////////////////////////////////////
706
        // Determine inertia and acceleration to calculate speed with.
707
        // Only check using the 'from' position because it is the current location of the player (NMS-wise)
708
        if (from.isInWater()) {
709
            data.nextInertia = Bridge1_13.isSwimming(player) ? Magic.HORIZONTAL_SWIMMING_INERTIA : Magic.WATER_HORIZONTAL_INERTIA;
710
            /* Per-tick speed gain. */
711
            float acceleration = Magic.LIQUID_ACCELERATION;
712
            float StriderLevel = attributeAccess.getHandle().getWaterMovementEfficiency(player);
713
            if (!onGround) {
714
                StriderLevel *= Magic.STRIDER_OFF_GROUND_MULTIPLIER;
715
            }
716
            if (StriderLevel > 0.0) {
717
                // (Less speed conservation (or in other words, more friction))
718
                data.nextInertia += (0.54600006f - data.nextInertia) * StriderLevel / (pData.getClientVersion().isAtMost(ClientVersion.V_1_20_6) ? 3.0f : 1.0f); // Mojang removed this / by 3 in 1.21 and switched to the WATER_MOVEMENT_EFFICIENCY attribute
719
                // (More per-tick speed gain)
720
                acceleration += (data.walkSpeed - acceleration) * StriderLevel / (pData.getClientVersion().isAtMost(ClientVersion.V_1_20_6) ? 3.0f : 1.0f);
721
            }
722
            if (!Double.isInfinite(Bridge1_13.getDolphinGraceAmplifier(player))) {
723
                // (Much more speed conservation (or in other words, much less friction))
724
                // (Overrides swimming AND depth strider friction)
725
                data.nextInertia = Magic.DOLPHIN_GRACE_INERTIA;
726
            }
727
            // Run through all operations
728
            isPredictable = estimateNextSpeed(player, acceleration, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
729
        }
730
        else if (from.isInLava()) {
731
            data.nextInertia = Magic.LAVA_HORIZONTAL_INERTIA;
732
            isPredictable = estimateNextSpeed(player, Magic.LIQUID_ACCELERATION, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
733
        }
734
        else {
735
            data.nextInertia = onGround ? data.nextFrictionHorizontal * Magic.AIR_HORIZONTAL_INERTIA : Magic.AIR_HORIZONTAL_INERTIA;
736
            // 1.12 (and below) clients will use cubed inertia, not cubed friction here. The difference isn't significant except for blocking speed and bunnyhopping on soul sand, which are both slower on 1.8
737
            float frictionMediumFactor = pData.getClientVersion().isAtLeast(ClientVersion.V_1_13) ? data.nextFrictionHorizontal : data.nextFrictionHorizontal * Magic.AIR_HORIZONTAL_INERTIA;
738
            float acceleration = onGround ? data.walkSpeed * ((pData.getClientVersion().isAtLeast(ClientVersion.V_1_13) ? Magic.DEFAULT_FRICTION_CUBED : Magic.DEFAULT_FRICTION_MULTIPLIED_BY_091_CUBED) / (frictionMediumFactor * frictionMediumFactor * frictionMediumFactor)) : Magic.AIR_ACCELERATION;
739
            if (pData.isSprinting()) {
740
                // (We don't use the attribute here due to desync issues, just detect when the player is sprinting and apply the multiplier manually)
741
                acceleration += acceleration * 0.3f; // 0.3 is the effective sprinting speed (EntityLiving).
742
            }
743
            isPredictable = estimateNextSpeed(player, acceleration, pData, tags, to, from, debug, fromOnGround, toOnGround, onGround, forceSetOffGround);
744
        }
745
        
746
        /////////////////////////////////////////////////
747
        // Set the combined allowed horizontal speed   //
748
        /////////////////////////////////////////////////
749
        thisMove.hAllowedDistance = MathUtil.dist(thisMove.xAllowedDistance, thisMove.zAllowedDistance);
750
        
751
        ////////////////////////
752
        // Calculate offsets  //
753
        ////////////////////////
754
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
755
        if (isPredictable) {
756
            hDistanceAboveLimit = handlePredictableMove(thisMove, cc.survivalFlyStrictHorizontal); 
757
        }
758
        else hDistanceAboveLimit = handleUnpredictableMove(thisMove, cc.survivalFlyStrictHorizontal);
759
        hDistanceAboveLimit = applyEdgeCornerResolvedTolerance(thisMove, hDistanceAboveLimit, cc.survivalFlyStrictHorizontal);
760
        hDistanceAboveLimit = HiddenMotionReconstructor.applyEdgeSneakBypass(player, pData, data, from, lastMove, thisMove, hDistanceAboveLimit, tags);
761
        if (hDistanceAboveLimit > 0.0) {
762
            tags.add("hdistrel");
763
            if (debug) {
764
                player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] hdistrel: predicted=" + StringUtil.fdec6.format(thisMove.hAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.hDistance));
765
            }
766
        }
767
        return new double[]{thisMove.hAllowedDistance, hDistanceAboveLimit};
768
    }
769
    
770
    
771
    /**
772
     * Estimates the player's horizontal speed based on the given data and Minecraft's movement logic.<br>
773
     * Order of operations is essential. Do not shuffle things around unless you know what you're doing.
774
     *<hr>
775
     * <p>Order of client-movement operations (as per MCP tool):
776
     * <ul>
777
     * <li>{@code EntityLiving.tick()}
778
     * <li>{@code [Entity].tick()}
779
     *   <ul>
780
     *     <li>{@code baseTick()}
781
     *     <li>{@code updateInWaterStateAndDoFluidPushing()}
782
     *   </ul>
783
     * <li>{@code EntityLiving.aiStep()}
784
     *   <ul>
785
     *     <li>Decrease the jump delay counter if it is active ({@code this.noJumpDelay > 0})
786
     *     <li>Negligible speed reset (0.003)
787
     *     <li>Apply liquid motion if the player is pressing the space bar (vertical axis only)
788
     *     <li>Multiply the input vector (= the vector containing the player's WASD impulse) by 0.98</li>
789
     *     <li>{@code jumpFromGround()} is called if the player is on ground and has pressed the space bar.
790
     *   </ul>
791
     * <li>Begin executing {@code EntityLiving.travel()} ({@code In EntityLiving.aiStep()})<p> <b>Note:</b> from 1.21.2 and onwards, Mojang split the travel function into different helper methods to better
792
     * distinguish between media (we now have {@code travelInAir()}, {@code travelInFluid()} and {@code travelFallFlying()})</p><br>
793
     *   <ul>
794
     *     <li>Invoke {@code [Entity].moveRelative()} (WASD inputs are transformed to acceleration vectors, call {@code getInputVector()})
795
     *     <li>If not in liquid or gliding, limit motion when on climbable via {@code handleRelativeFrictionAndCalculateMovement()}
796
     *     <li>Invoke {@code [Entity].move()}
797
     *       <ul>
798
     *         <li>Apply stuck speed multiplier
799
     *         <li>Invoke {@code EntityHuman.maybeBackOffFromEdge()}
800
     *         <li>Handle wall collisions via {@code Entity.collide()} (speed is cut-off and the collision flag is set) <br>
801
     * <em><strong>After {@code [Entity].collide()} is called, the next movement is prepared. Every subsequent operation 
802
     *           applies to the next move for the client.</strong></em>
803
     *         <li>Set the supporting block data; call {@code setGroundWithMovement()}</li>
804
     *         <li>Handle horizontal collisions (speed is now reset to 0 on the colliding axis); <em><strong>NCP STARTS ESTIMATING FROM HERE ON (!)</strong></em>
805
     *         <li>Invoke {@code checkFallDamage()} (apply fluid pushing if not previously in water)
806
     *         <li>Invoke {@code [Block].updateEntityAfterFallOn()} (for slime bouncing)
807
     *         <li>Invoke {@code [Block].stepOn()} (for slime blocks only, currently)
808
     *         <li>Invoke {@code tryCheckInsideBlocks()} (for honey blocks slide-down and bubble columns)
809
     *         <li>Invoke {@code [Entity].getBlockSpeedFactor()} (soul sand, honey blocks)
810
     *       </ul>
811
     *   </ul>
812
     * <li>Complete executing {@code EntityLiving.travel()}
813
     *   <ul>
814
     *     <li>{@code handleRelativeFrictionAndCalculateMovement()} (for snow climbing speed)
815
     *     <li>Apply gravity.
816
     *     <li>Apply friction/inertia.
817
     *     <li>Handle fluid falling function if in liquid (vertical axis only)
818
     *     <li>Handle jumping out of liquids (vertical axis only)
819
     *     <li>Handle entity pushing
820
     *   </ul>
821
     * <li>Complete {@code EntityLiving.aiStep()}
822
     * <li>Complete {@code EntityLiving.tick()}
823
     * <li> Finally, send movement to the server.
824
     * </ul>
825
     * <hr>
826
     * The logic is split into different sections:
827
     * <li>Firstly, we perform some preliminary checks to quickly catch specific ways of cheating.</li>
828
     * <li>If no blatant cheating is detected, the movement speed estimate is calculated starting from the horizontal collision reset, calculating the client’s actions on the next move and then processing the actions performed prior.</li>
829
     * <li>If needed, the player's impulse (acceleration) is brute-forced (see {@link BridgeMisc#isWASDImpulseKnown(Player)}</li>
830
     * @return {@code true}, if the move has been deemed to be predictable. {@code false} otherwise.
831
     */
832
    private boolean estimateNextSpeed(final Player player, float movementSpeed, final IPlayerData pData, final Collection<String> tags,
833
                                      final PlayerLocation to, final PlayerLocation from, final boolean debug,
834
                                      final boolean fromOnGround, final boolean toOnGround, final boolean onGround, boolean forceSetOffGround) {
835
        /*
836
         * TODO: This is a mess, clean-up pending / needed. Get rid of code duplication
837
         */
838
        final MovingData data = pData.getGenericInstance(MovingData.class);
839
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
840
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
841
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
842
        final boolean envelopeFromOnGround = PhysicsGroundResolver.resolveEnvelopeFromOnGround(thisMove, fromOnGround);
843
        final boolean envelopeToOnGround = PhysicsGroundResolver.resolveEnvelopeToOnGround(thisMove, toOnGround);
844
        
845
        // Reference commit of this piece of code: https://github.com/NoCheatPlus/NoCheatPlus/commit/1c024c072c9f6ebe5371c113916c6a2414e635a6
846
        /////////////////////////////////////////////////////
847
        // Horizontal push/pull is put on top priority     //
848
        /////////////////////////////////////////////////////
849
        // With the current implementation, the prediction will run for the axis even if a push/pull is detected on it.
850
        // We'll have to somehow skip predicting that specfic axis, but it requires some refactoring to do it.
851
        // This is not ideal, but it's better than flagging players for being pushed by pistons.
852
        final MovingConfig cc = pData.getGenericInstance(MovingConfig.class);
853
        boolean xPush = false;
854
        boolean zPush = false;
855
        // TODO: Get rid of this config option. Why would someone want to disable piston push detection and cause false positives?
856
        if (cc.trackBlockMove) {
857
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, thisMove.xDistance < 0.0 ? Direction.X_NEG : Direction.X_POS, 0.05)) {
858
                tags.add("blkmv_x");
859
                xPush = true;
860
            }
861
            if (from.matchBlockChange(blockChangeTracker, data.blockChangeRef, thisMove.zDistance < 0.0 ? Direction.Z_NEG : Direction.Z_POS, 0.05)) {
862
                tags.add("blkmv_z");
863
                zPush = true;
864
            }
865
            if (xPush && zPush) {
866
                thisMove.xAllowedDistance = thisMove.xDistance;
867
                thisMove.zAllowedDistance = thisMove.zDistance;
868
                // A push/pull happened on both axes, no need to continue the prediction.
869
                return true;
870
            }
871
        }
872
        
873
        ////////////////////////////////////////////////////////
874
        // Test for specific cheat implementation types first //
875
        ////////////////////////////////////////////////////////
876
        // These checks don't need specific data from the prediction, so they can be performed ex-ante and save some performance.
877
        if (cData.isHackingRI) {
878
            tags.add("noslowpacket");
879
            cData.isHackingRI = false;
880
            Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.noslow", pData);
881
            data.resetHorizontalData();
882
            return true;
883
        }
884
        // If impulses don't need to be inferred from the prediction, illegal sprinting checks can be performed here.
885
        if (BridgeMisc.isWASDImpulseKnown(player) && pData.isSprinting()
886
            && (data.input.getForwardDir() != ForwardDirection.FORWARD && data.input.getStrafeDir() != StrafeDirection.NONE && data.input.getForwardDir() != ForwardDirection.NONE
887
                || player.getFoodLevel() <= 5) // must be checked here as well (besides on toggle sprinting) because players will immediately lose the ability to sprint if food level drops below 5
888
            ) { 
889
            // || inputs[i].getForward() < 0.8 // hasEnoughImpulseToStartSprinting, in LocalPlayer,java -> aiStep()
890
            tags.add("illegalsprint");
891
            Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.illegalsprint", pData);
892
            data.resetHorizontalData();
893
            return true;
894
        }
895
        
896
        
897
        //////////////////////////////////////////
898
        // Setup theoretical inputs, if needed  //
899
        //////////////////////////////////////////
900
        PlayerKeyboardInput input = null; // Precise input
901
        PlayerKeyboardInput[] theorInputs = null; // All brute-forced inputs.
902
        /* Index for accessing speed combinations. If you need to perform an operation for/with each speed, set it to 0 and loop until it 8 */
903
        int i = 0;
904
        if (BridgeMisc.isWASDImpulseKnown(player)) {
905
            // Clone for safety as this data is consumed. 
906
            input = data.input.clone();
907
            // In EntityLiving.java -> aiStep() the game multiplies input values by 0.98 before dispatching them to the travel() function.
908
            input.operationToInt(0.98f, 0.98f, 1);
909
            // From KeyboardInput.java and LocalPlayer.java (MC-Reborn tool)
910
            // Sneaking and item-use aren't directly applied to the player's motion. The game reduces the force of the input instead.
911
            if (pData.isInCrouchingPose()) {
912
                // Note that this is determined by player poses, not shift key presses.
913
                input.operationToInt(attributeAccess.getHandle().getPlayerSneakingFactor(player), attributeAccess.getHandle().getPlayerSneakingFactor(player), 1);
914
                tags.add("crouching");
915
            }
916
            // From LocalPlayer.java.aiStep()
917
            if (BridgeMisc.isSlowedDownByUsingAnItem(player)) {
918
                input.operationToInt(Magic.USING_ITEM_MULTIPLIER, Magic.USING_ITEM_MULTIPLIER, 1);
919
                tags.add("usingitem");
920
            }
921
        }
922
        else {
923
            // The input's matrix is: NONE, LEFT, RIGHT, FORWARD, FORWARD_LEFT, FORWARD_RIGHT, BACKWARD, BACKWARD_LEFT, BACKWARD_RIGHT.
924
            theorInputs = new PlayerKeyboardInput[9];
925
            // Loop through all combinations otherwise.
926
            for (int strafe = -1; strafe <= 1; strafe++) {
927
                for (int forward = -1; forward <= 1; forward++) {
928
                    // Multiply all 
929
                    theorInputs[i] = new PlayerKeyboardInput(strafe * 0.98f, forward * 0.98f);
930
                    i++;
931
                }
932
            }
933
            if (pData.isInCrouchingPose()) {
934
                tags.add("crouching");
935
                for (i = 0; i < 9; i++) {
936
                    // Multiply all combinations
937
                    theorInputs[i].operationToInt(attributeAccess.getHandle().getPlayerSneakingFactor(player), attributeAccess.getHandle().getPlayerSneakingFactor(player), 1);
938
                }
939
            }
940
            // From LocalPlayer.java.aiStep()
941
            if (BridgeMisc.isSlowedDownByUsingAnItem(player)) {
942
                tags.add("usingitem");
943
                for (i = 0; i < 9; i++) {
944
                    theorInputs[i].operationToInt(Magic.USING_ITEM_MULTIPLIER, Magic.USING_ITEM_MULTIPLIER, 1);
945
                }
946
            }
947
        }
948
949
        /*
950
         * This bit of vertical distance computation is needed for the supporting block mechanism, which needs Minecraft-calculated on-ground status.
951
         * Normally, these would be computed at the same time, however, since NCP handles horizontal and vertical speed estimation separately, we need to duplicate this bit of code here.
952
         * TODO: Unify predictions somehow.
953
         */
954
        final boolean slimeYbcChain = from.isOnBouncyBlock();
955
        double yDistanceBeforeCollide;
956
        if (slimeYbcChain) {
957
            yDistanceBeforeCollide = lastMove.motionY;
958
        }
959
        else {
960
            yDistanceBeforeCollide = lastMove.toIsValid ? lastMove.yDistance : 0.0;
961
            if (lastMove.yCorrectedDistancePre != 0.0) {
962
                yDistanceBeforeCollide = lastMove.yCorrectedDistancePre;
963
            }
964
            if (envelopeToOnGround) yDistanceBeforeCollide = 0.0;
965
        }
966
        // Refine yDistanceBeforeCollide (seed set above for edge-sneak momentum carry).
967
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
968
            if (data.lastStuckInBlockVertical != 1.0) {
969
                yDistanceBeforeCollide = 0.0;
970
            }
971
        }
972
        if (!pData.isShiftKeyPressed()) {
973
            if (yDistanceBeforeCollide < 0.0 && thisMove.yDistance >= 0.0) {
974
                if (from.isOnBouncyBlock()) {
975
                    // The effect works by inverting the distance.
976
                    // Beds have a weaker bounce effect (BedBlock.java).
977
                    yDistanceBeforeCollide = from.isOnSlimeBlock() ? -yDistanceBeforeCollide : -yDistanceBeforeCollide * 0.66;
978
                }
979
            }
980
        }
981
        if (lastMove.from.inWater) {
982
            yDistanceBeforeCollide *= data.lastFrictionVertical;
983
            if (BridgeMisc.hasGravity(player)) {
984
                // Legacy: clients older than 1.13 have some kind of gravity effect applied to them even in liquids, if they don't press the space bar.
985
                // On 1.13 and above, only friction gets applied, resulting in a much slower descending speed when not pressing the space bar pressed.
986
                if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
987
                    yDistanceBeforeCollide -= Magic.LEGACY_LIQUID_GRAVITY;
988
                }
989
                else {
990
                    // In 1.13 the gravity effect in liquids was removed and this function got added.
991
                    Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yDistanceBeforeCollide <= 0.0, new Vector(0.0, yDistanceBeforeCollide, 0.0), cData.wasSprinting);
992
                    yDistanceBeforeCollide = fluidFallingAdjustMovement.getY();
993
                }
994
            }
995
        }
996
        else if (lastMove.from.inLava) {
997
            if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) {
998
                yDistanceBeforeCollide *= data.lastFrictionVertical;
999
                if (BridgeMisc.hasGravity(player)) {
1000
                    if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
1001
                        yDistanceBeforeCollide -= Magic.LEGACY_LIQUID_GRAVITY;
1002
                    }
1003
                    else {
1004
                        // In 1.13 the gravity effect in liquids was removed and this function got added.
1005
                        Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yDistanceBeforeCollide <= 0.0, new Vector(0.0, yDistanceBeforeCollide, 0.0), cData.wasSprinting);
1006
                        yDistanceBeforeCollide = fluidFallingAdjustMovement.getY();
1007
                    }
1008
                }
1009
            }
1010
            else {
1011
                yDistanceBeforeCollide *= data.lastFrictionVertical;
1012
            }
1013
            if (data.lastGravity != 0.0) {
1014
                yDistanceBeforeCollide += -data.lastGravity / 4.0;
1015
            }
1016
        }
1017
        else {
1018
            // Air motion
1019
            if (cData.wasLevitating) {
1020
                yDistanceBeforeCollide += (0.05 * data.lastLevitationLevel - yDistanceBeforeCollide) * 0.2;
1021
            }
1022
            else {
1023
                yDistanceBeforeCollide -= data.lastGravity;
1024
            }
1025
            yDistanceBeforeCollide *= data.lastFrictionVertical;
1026
        }
1027
        if (from.isInLiquid() && verticalLiquidPushComponent != 0.0) {
1028
            // Liquid vertical push component calculated in hdistrel.
1029
            yDistanceBeforeCollide += verticalLiquidPushComponent;
1030
        }
1031
        if (from.isInWater() && pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2)) {
1032
            // *----------LocalPlayer.aiStep(), goDownInWater()----------*
1033
            if (pData.isShiftKeyPressed()) {
1034
                yDistanceBeforeCollide -= Magic.LIQUID_SPEED_GAIN;
1035
            }
1036
        }
1037
        if (Math.abs(yDistanceBeforeCollide) < (pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2) ? 0.003 : 0.005)) yDistanceBeforeCollide = 0.0;
1038
        if (!from.isInLiquid() && from.isOnClimbable() && from.canClimbUp(data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier))) {
1039
            // Should replicate the condition: !this.getInBlockState().is(Blocks.SCAFFOLDING)
1040
            final Material typeId = from.getBlockType();
1041
            final long theseFlags = BlockFlags.getBlockFlags(typeId);
1042
            yDistanceBeforeCollide = Math.max(yDistanceBeforeCollide, -Magic.CLIMBABLE_MAX_SPEED);
1043
            if (yDistanceBeforeCollide < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
1044
                && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
1045
                yDistanceBeforeCollide = 0.0;
1046
            }
1047
        }
1048
        thisMove.motionY = yDistanceBeforeCollide;
1049
        //End of yDistanceBeforeCollide getter
1050
1051
        //////////////////////////////////////
1052
        // Next move for the client         //
1053
        //////////////////////////////////////
1054
        /*
1055
          All moves are assumed to be predictable, unless we explicitly state otherwise. 
1056
          A move is considered to be predictable if there aren't any particular client-side issues/limitations that prevent it.
1057
         */
1058
        boolean isPredictable = true;
1059
        final boolean edgeSneakNow = !player.isFlying() && pData.isShiftKeyPressed() && from.isAboveGround() && yDistanceBeforeCollide <= 0.0;
1060
        // Initialize horizontal momentum; at an edge use stored internal momentum while still shift-sneaking.
1061
        if (lastMove.toIsValid) {
1062
            if (edgeSneakNow && lastMove.edgeBackoffApplied) {
1063
                thisMove.xAllowedDistance = lastMove.motionX;
1064
                thisMove.zAllowedDistance = lastMove.motionZ;
1065
            } else if (HiddenMotionReconstructor.shouldUseEdgeHiddenCarry(edgeSneakNow, from, yDistanceBeforeCollide, lastMove)) {
1066
                thisMove.xAllowedDistance = lastMove.motionX;
1067
                thisMove.zAllowedDistance = lastMove.motionZ;
1068
            } else {
1069
                thisMove.xAllowedDistance = lastMove.xDistance;
1070
                thisMove.zAllowedDistance = lastMove.zDistance;
1071
            }
1072
            // Edge: packet may show 0 on a clipped axis while internal momentum (motionX/Z) is still large.
1073
            if (lastMove.edgeBackoffApplied && lastMove.edgeAxisClamped) {
1074
                final double pktSuppressH = HiddenMotionReconstructor.packetSuppressThresholdH(pData);
1075
                if (Math.abs(lastMove.xDistance) < pktSuppressH) {
1076
                    thisMove.xAllowedDistance = lastMove.motionX;
1077
                }
1078
                if (Math.abs(lastMove.zDistance) < pktSuppressH) {
1079
                    thisMove.zAllowedDistance = lastMove.motionZ;
1080
                }
1081
            }
1082
        } else {
1083
            thisMove.xAllowedDistance = 0.0;
1084
            thisMove.zAllowedDistance = 0.0;
1085
        }
1086
        // !lastMove.possibleStopMotion is dummy flag to flip false on failure and retry
1087
        // Check if there had been a hidden move on the prebious tick(s) due to 0.03 threshold.
1088
        // If so, the initial speed is initialized by the corrected distance. xDistance/zDistance would report a wrong speed value.
1089
        if (!lastMove.possibleStopMotion && (lastMove.xCorrectedDistancePre != 0.0 || lastMove.zCorrectedDistancePre != 0.0)) {
1090
            // Edge-sneak internal momentum overrides generic hidden pre-correct when still at an edge.
1091
            if (!(edgeSneakNow && lastMove.edgeBackoffApplied)) {
1092
                thisMove.xAllowedDistance = lastMove.xCorrectedDistancePre;
1093
                thisMove.zAllowedDistance = lastMove.zCorrectedDistancePre;
1094
                // Distinguish source of CorrectedDistance that only come from hidden move not from stop motion
1095
                if (lastMove.hiddenDistanceIndex != -1) {
1096
                    thisMove.possibleStopMotion = true;
1097
                }
1098
                tags.add("hidden");
1099
            }
1100
        }
1101
        // Stuck speed reset (the game resets momentum each tick the player is in a stuck-speed block)
1102
        if (data.lastStuckInBlockHorizontal != 1.0) {
1103
            if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) { // (Vanilla check, don't ask)
1104
                // Throttle speed if stuck in.
1105
                thisMove.xAllowedDistance = thisMove.zAllowedDistance = 0.0;
1106
            }
1107
        }
1108
        // If the player collided with something on the previous tick, start with 0 momentum now.
1109
        doWallCollision(lastMove, thisMove);
1110
        // (The game calls a checkFallDamage() function, which, as you can imagine, handles fall damage. But also handles liquids' flow force, thus we need to apply this 2 times.)
1111
        if (from.isInWater() && !lastMove.from.inWater) {
1112
            Vector liquidFlowVector = from.getLiquidPushingVector(thisMove.xAllowedDistance, thisMove.zAllowedDistance, BlockFlags.F_WATER);
1113
            thisMove.xAllowedDistance += liquidFlowVector.getX();
1114
            thisMove.zAllowedDistance += liquidFlowVector.getZ();
1115
        }
1116
        // Slime stepOn: throttle momentum carried from last tick (client stepOn at end of last tick).
1117
        if (from.isOnSlimeBlock() && thisMove.hasClientFromOnGround && thisMove.clientFromOnGround && Math.abs(lastMove.motionY) < 0.1 && !pData.isShiftKeyPressed()) {
1118
            double slimeStepMul = 0.4 + Math.abs(lastMove.motionY) * 0.2;
1119
            thisMove.xAllowedDistance *= slimeStepMul;
1120
            thisMove.zAllowedDistance *= slimeStepMul;
1121
            tags.add("slime_step");
1122
        }
1123
        // Sliding speed (honey block)
1124
        if (from.isSlidingDown()) { // TODO: lastMove.from.slideDown or something?
1125
            if (lastMove.yDistance < -Magic.SLIDE_START_AT_VERTICAL_MOTION_THRESHOLD) {
1126
                thisMove.xAllowedDistance *= -Magic.SLIDE_SPEED_THROTTLE / lastMove.yDistance;
1127
                thisMove.zAllowedDistance *= -Magic.SLIDE_SPEED_THROTTLE / lastMove.yDistance;
1128
            }
1129
        }
1130
        
1131
        // Block speed
1132
        thisMove.xAllowedDistance *= (double) data.nextBlockSpeedMultiplier;
1133
        thisMove.zAllowedDistance *= (double) data.nextBlockSpeedMultiplier;
1134
        // Friction next, with special case for riptide at the start of the movement tick (when the riptide move is "unified" and not split into two updates; friction of the next move is used here)
1135
        boolean newFriction = false;
1136
        if (lastMove.tridentRelease.decide() && lastMove.toIsValid) {
1137
            final PlayerMoveData secondLastMove = data.playerMoves.getSecondPastMove();
1138
            if (lastMove.from.onGround || secondLastMove.tridentRelease.decideOptimistically() 
1139
                || (secondLastMove.toIsValid && secondLastMove.yDistance <= 0.0 && (secondLastMove.from.onGround || secondLastMove.fromLostGround))) {
1140
                newFriction = true;
1141
            }
1142
        }
1143
        thisMove.xAllowedDistance *= (double) (newFriction ? data.nextInertia : data.lastInertia);
1144
        thisMove.zAllowedDistance *= (double) (newFriction ? data.nextInertia : data.lastInertia);
1145
        // Apply entity-pushing speed
1146
        // From Entity.java.push()
1147
        // The entity's location is in the past.
1148
        if (player.getGameMode() != BridgeMisc.GAME_MODE_SPECTATOR) { // noPhysics check in vanilla.
1149
            Vector push = from.doPush(new Vector(thisMove.xAllowedDistance, 0.0, thisMove.zAllowedDistance));
1150
            thisMove.xAllowedDistance = push.getX();
1151
            thisMove.zAllowedDistance = push.getZ();
1152
            if (data.lastCollidingEntitiesLocations != null && !data.lastCollidingEntitiesLocations.isEmpty()) {
1153
                isPredictable = false;
1154
            }
1155
        }
1156
1157
1158
1159
        //////////////////////////////////
1160
        // Last move for the client     //
1161
        //////////////////////////////////
1162
        // See CombinedListener.java for more details
1163
        // This is done before liquid pushing...
1164
        if (thisMove.hasAttackSlowDown) {
1165
            thisMove.zAllowedDistance *= Magic.ATTACK_SLOWDOWN;
1166
            thisMove.xAllowedDistance *= Magic.ATTACK_SLOWDOWN;
1167
        }
1168
        // Apply liquid pushing speed (2nd call).
1169
        if (from.isInLiquid()) {
1170
            Vector liquidFlowVector = from.getLiquidPushingVector(thisMove.xAllowedDistance, thisMove.zAllowedDistance, from.isInWater() ? BlockFlags.F_WATER : BlockFlags.F_LAVA);
1171
            thisMove.xAllowedDistance += liquidFlowVector.getX();
1172
            verticalLiquidPushComponent = liquidFlowVector.getY();
1173
            thisMove.zAllowedDistance += liquidFlowVector.getZ();
1174
        }
1175
        // Before calculating the acceleration, check if momentum is below the negligible speed threshold and cancel it.
1176
        checkNegligibleMomentum(pData, thisMove);
1177
        // Sprint-jumping...
1178
        // IMPORTANT NOTE: when working **exclusively** with rotations (like in the following cases), you must use the TO location, not the FROM one, as TO contains the most recent rotation. Using FROM lags behind a few ticks, causing false positives when switching looking direction.
1179
        if (PhysicsEnvelope.isBunnyhop(from, to, pData, envelopeFromOnGround, envelopeToOnGround, player, forceSetOffGround)) {
1180
            thisMove.xAllowedDistance += (double) (-TrigUtil.sin(to.getYaw() * TrigUtil.toRadians) * Magic.BUNNYHOP_BOOST);
1181
            thisMove.zAllowedDistance += (double) (TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) * Magic.BUNNYHOP_BOOST);
1182
            thisMove.bunnyHop = true;
1183
            tags.add("bunnyhop");
1184
        }
1185
1186
        // *--------------------------------------------------------------------------------------------------------------------*
1187
        // *--------- If we know the player's impulse, brute-forcing acceleration and everything after it isn't needed ---------* 
1188
        // *--------------------------------------------------------------------------------------------------------------------*
1189
        if (BridgeMisc.isWASDImpulseKnown(player)) {
1190
            // Transform the input into an acceleration vector (getInputVector, entity.java)
1191
            double inputSq = MathUtil.square((double) input.getStrafe()) + MathUtil.square((double) input.getForward()); // Cast to a double because the client does it
1192
            if (inputSq >= 1.0E-7) {
1193
                if (inputSq > 1.0) {
1194
                    double inputForce = Math.sqrt(inputSq);
1195
                    if (inputForce < 1.0E-4) {
1196
                        // Not enough force, reset.
1197
                        input.operationToInt(0, 0, 0);
1198
                    }
1199
                    // Normalize
1200
                    else input.operationToInt(inputForce, inputForce, 2);
1201
                }
1202
                // Multiply the input by movement speed.
1203
                input.operationToInt(movementSpeed, movementSpeed, 1);
1204
                // The acceleration vector is added to the current momentum...
1205
                thisMove.xAllowedDistance += input.getStrafe() * (double) TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) - input.getForward() * (double) TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1206
                thisMove.zAllowedDistance += input.getForward() * (double) TrigUtil.cos(to.getYaw() * TrigUtil.toRadians) + input.getStrafe() * (double) TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1207
            }
1208
            // Minecraft caps horizontal speed if on climbable, for whatever reason.
1209
            if (from.isOnClimbable() && !from.isInLiquid()) {
1210
                //data.clearActiveHorVel(); // Might want to clear ALL horizontal vel.
1211
                thisMove.xAllowedDistance = MathUtil.clamp(thisMove.xAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1212
                thisMove.zAllowedDistance = MathUtil.clamp(thisMove.zAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1213
            }
1214
            // Stuck-speed multiplier.
1215
            if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
1216
                thisMove.xAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
1217
                thisMove.zAllowedDistance *= (double) data.nextStuckInBlockHorizontal;
1218
            }
1219
            // Riptide works by propelling the player after releasing the trident (the effect only pushes the player, unless is on ground)
1220
            if (thisMove.tridentRelease.decideOptimistically()) {
1221
                thisMove.tridentRelease = AlmostBoolean.YES;
1222
                Vector riptideVelocity = to.getRiptideVelocity(onGround);
1223
                thisMove.xAllowedDistance += riptideVelocity.getX();
1224
                thisMove.zAllowedDistance += riptideVelocity.getZ();
1225
            }
1226
            // Lunging forward if applicable: the effect only adds the lunging motion on the current delta.
1227
            // TODO: TOTALLY RANDOM PLACEMENT !
1228
            // The addition is called on any left click, provided the player has a Spear in hand with Lunge enchant.
1229
            // NOTE: Does not need to be brute forced, since lunging is supported only by clients that can send WASD inputs.
1230
            if (thisMove.lungingForward) {
1231
                Vector lungeVelocity = to.tryApplyLungingMotion(); // Use to as we're working with rotations here
1232
                thisMove.xAllowedDistance += lungeVelocity.getX();
1233
                thisMove.zAllowedDistance += lungeVelocity.getZ();
1234
            }
1235
            // Try to back off players from edges, if sneaking.
1236
            // NOTE: this is after the riptiding propelling force.
1237
            // NOTE: here the game uses isShiftKeyDown (so this is shifting not sneaking, using Bukkit's isShift is correct)
1238
            if (edgeSneakNow) {
1239
                thisMove.edgeBackoffApplied = true;
1240
                final double preEdgeX = thisMove.xAllowedDistance;
1241
                final double preEdgeZ = thisMove.zAllowedDistance;
1242
                final double pktSuppressH = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1243
                        ? Magic.Minecraft_minMoveSqDistance_legacy : Math.sqrt(Magic.Minecraft_minMoveSqDist_modern);
1244
                Vector backOff = from.maybeBackOffFromEdge(new Vector(preEdgeX, yDistanceBeforeCollide, preEdgeZ));
1245
                HiddenMotionReconstructor.storeEdgeHiddenMotion(thisMove, preEdgeX, preEdgeZ, backOff.getX(), backOff.getZ(), pktSuppressH);
1246
                thisMove.xAllowedDistance = backOff.getX();
1247
                thisMove.zAllowedDistance = backOff.getZ();
1248
                if (!thisMove.edgeAxisClamped) {
1249
                    thisMove.motionX = thisMove.xDistance;
1250
                    thisMove.motionZ = thisMove.zDistance;
1251
                }
1252
            }
1253
            // Collision next.
1254
            // NOTE: Passing the unchecked y-distance is fine in this case. Vertical collision is checked with vdistrel (just separately).
1255
            // TODO: Perhaps after this use collisionVector to store onGround? Also can not restore minecraft ground state with step and jump movement(like stairs)!
1256
            Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, yDistanceBeforeCollide, thisMove.zAllowedDistance), onGround, from.getBoundingBox());
1257
            // Set the supporting block data.
1258
            if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1259
                // This is called with setOnGroundWithMovement at the same time of setting the ground flag but before setting the horizontal collision flags.
1260
                // NOTE: here the bounding box of the TO location must be used.
1261
                pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(thisMove.xAllowedDistance, thisMove.yDistance, thisMove.zAllowedDistance), to.getBoundingBox(), yDistanceBeforeCollide < 0.0 && yDistanceBeforeCollide != collisionVector.getY()));
1262
            }
1263
            // NOTE: Collision flags must be set before setting speed in thisMove.
1264
            thisMove.collideX = thisMove.xAllowedDistance != collisionVector.getX();
1265
            thisMove.collideZ = thisMove.zAllowedDistance != collisionVector.getZ();
1266
            thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1267
            // Set speed.
1268
            thisMove.xAllowedDistance = collisionVector.getX();
1269
            thisMove.zAllowedDistance = collisionVector.getZ();
1270
            // More edge data...
1271
            thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(thisMove.xAllowedDistance, thisMove.yDistance, thisMove.zAllowedDistance), to, input.getStrafe(), input.getForward());
1272
            // Check for block push.
1273
            // TODO: Unoptimized insertion point... Waste of resources to just override everything at the end. See note at the start of the method.
1274
            if (xPush) {
1275
               thisMove.xAllowedDistance = thisMove.xDistance;
1276
            }
1277
            if (zPush) {
1278
                thisMove.zAllowedDistance = thisMove.zDistance;
1279
            }
1280
            //////////////
1281
            // Set data //
1282
            //////////////
1283
            thisMove.hasImpulse = AlmostBoolean.match(input.getForwardDir() != ForwardDirection.NONE || input.getStrafeDir() != StrafeDirection.NONE);
1284
            thisMove.strafeImpulse = input.getStrafeDir();
1285
            thisMove.forwardImpulse = input.getForwardDir();
1286
            if (debug) {
1287
                player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] (postPredict) Direction: " + input.getForwardDir() +" | "+ input.getStrafeDir());
1288
            }
1289
            // If-else instead of an early return... Matter of preference. This makes code slightly easier to look at, as it avoids yet another indentation
1290
            return isPredictable;
1291
        }
1292
        
1293
        // *----------------------------------------------------------------------------------------------------*
1294
        // *-------Can't know / read player inputs, loop through everything after looping the acceleration------*
1295
        // *----------------------------------------------------------------------------------------------------*
1296
        // Transform theoretical inputs into acceleration vectors (getInputVector, entity.java)
1297
        float sinYaw = TrigUtil.sin(to.getYaw() * TrigUtil.toRadians);
1298
        float cosYaw = TrigUtil.cos(to.getYaw() * TrigUtil.toRadians);
1299
        /* List of predicted X distances. Size is the number of possible inputs (left/right/backwards/forward etc...) */
1300
        double[] xTheoreticalDistance = new double[9];
1301
        /* To keep track which theoretical speed would result in a collision on the X axis */
1302
        boolean[] collideX = new boolean[9];
1303
        /* List of predicted Z distances. Size is the number of possible inputs (left/right/backwards/forward etc...) */
1304
        double[] zTheoreticalDistance = new double[9];
1305
        /* To keep track which theoretical speed would result in a collision on the Z axis */
1306
        boolean[] collideZ = new boolean[9];
1307
        /* To keep track which theoretical speed would result in a collision on the Y axis */
1308
        boolean[] collideY = new boolean[9];
1309
        for (i = 0; i < 9; i++) {
1310
            // Each slot in the array is initialized with the same momentum first.
1311
            xTheoreticalDistance[i] = thisMove.xAllowedDistance;
1312
            zTheoreticalDistance[i] = thisMove.zAllowedDistance;
1313
            // Then we proceed to compute all possible accelerations with all theoretical inputs and apply subsequent modifiers.
1314
            double inputSq = MathUtil.square((double)theorInputs[i].getStrafe()) + MathUtil.square((double)theorInputs[i].getForward());
1315
            if (inputSq >= 1.0E-7) {
1316
                if (inputSq > 1.0) {
1317
                    double inputForce = Math.sqrt(inputSq);
1318
                    if (inputForce < 1.0E-4) {
1319
                        theorInputs[i].operationToInt(0, 0, 0);
1320
                    }
1321
                    else {
1322
                        theorInputs[i].operationToInt(inputForce, inputForce, 2);
1323
                    }
1324
                }
1325
                theorInputs[i].operationToInt(movementSpeed, movementSpeed, 1);
1326
                xTheoreticalDistance[i] += theorInputs[i].getStrafe() * (double)cosYaw - theorInputs[i].getForward() * (double)sinYaw;
1327
                zTheoreticalDistance[i] += theorInputs[i].getForward() * (double)cosYaw + theorInputs[i].getStrafe() * (double)sinYaw;
1328
            }
1329
        }
1330
        // All later modifiers get applied to each theoretical speed...
1331
        if (from.isOnClimbable() && !from.isInLiquid()) {
1332
            for (i = 0; i < 9; i++) {
1333
                xTheoreticalDistance[i] = MathUtil.clamp(xTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1334
                zTheoreticalDistance[i] = MathUtil.clamp(zTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED, Magic.CLIMBABLE_MAX_SPEED);
1335
            }
1336
        }
1337
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
1338
            for (i = 0; i < 9; i++) {
1339
                xTheoreticalDistance[i] *= (double) data.nextStuckInBlockHorizontal;
1340
                zTheoreticalDistance[i] *= (double) data.nextStuckInBlockHorizontal;
1341
            }
1342
        }
1343
        if (thisMove.tridentRelease.decideOptimistically()) {
1344
            thisMove.tridentRelease = AlmostBoolean.YES;
1345
            Vector riptideVelocity = to.getRiptideVelocity(onGround);
1346
            for (i = 0; i < 9; i++) {
1347
                xTheoreticalDistance[i] += riptideVelocity.getX();
1348
                zTheoreticalDistance[i] += riptideVelocity.getZ();
1349
            }
1350
        }
1351
        
1352
        double[] xMotionBeforeEdge = new double[9];
1353
        double[] zMotionBeforeEdge = new double[9];
1354
        double[] xBackOffAfterEdge = new double[9];
1355
        double[] zBackOffAfterEdge = new double[9];
1356
        for (i = 0; i < 9; i++) {
1357
            xMotionBeforeEdge[i] = xTheoreticalDistance[i];
1358
            zMotionBeforeEdge[i] = zTheoreticalDistance[i];
1359
            xBackOffAfterEdge[i] = xTheoreticalDistance[i];
1360
            zBackOffAfterEdge[i] = zTheoreticalDistance[i];
1361
        }        
1362
        
1363
        final double hiddenThresholdSqBrute = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1364
                ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
1365
        final double hiddenThresholdHBrute = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1366
                ? hiddenThresholdSqBrute : Math.sqrt(hiddenThresholdSqBrute);
1367
        boolean activeCornerClamp = false;
1368
        if (edgeSneakNow) {
1369
            thisMove.edgeBackoffApplied = true;
1370
            // Single backoff probe replaces back-to-back edgeStillClampsCorner + edgeStillClamps on the same vector.
1371
            final Vector seedBackOff = from.maybeBackOffFromEdge(new Vector(thisMove.xAllowedDistance, yDistanceBeforeCollide, thisMove.zAllowedDistance));
1372
            activeCornerClamp = HiddenMotionReconstructor.edgeStillClampsCornerCached(thisMove.xAllowedDistance,
1373
                    thisMove.zAllowedDistance, seedBackOff.getX(), seedBackOff.getZ());
1374
            if (!HiddenMotionReconstructor.edgeStillClampsCached(thisMove.xAllowedDistance,
1375
                    thisMove.zAllowedDistance, seedBackOff.getX(), seedBackOff.getZ())) {
1376
                thisMove.motionX = thisMove.xDistance;
1377
                thisMove.motionZ = thisMove.zDistance;
1378
            }
1379
            for (i = 0; i < 9; i++) {
1380
                // TODO: Optimize. Brute forcing collisions with all 9 speed combinations will tank performance.
1381
                final double preEdgeX = xTheoreticalDistance[i];
1382
                final double preEdgeZ = zTheoreticalDistance[i];
1383
                Vector backOff = from.maybeBackOffFromEdge(new Vector(preEdgeX, yDistanceBeforeCollide, preEdgeZ));
1384
                HiddenMotionReconstructor.storeEdgeHiddenMotionCandidate(thisMove, xMotionBeforeEdge, zMotionBeforeEdge, i, preEdgeX, preEdgeZ, backOff.getX(), backOff.getZ(),
1385
                        thisMove.xDistance, thisMove.zDistance, hiddenThresholdHBrute);
1386
                xBackOffAfterEdge[i] = backOff.getX();
1387
                zBackOffAfterEdge[i] = backOff.getZ();
1388
                xTheoreticalDistance[i] = backOff.getX();
1389
                zTheoreticalDistance[i] = backOff.getZ();
1390
            }
1391
            if (HiddenMotionReconstructor.anyEdgeCandidateClipped(xMotionBeforeEdge, zMotionBeforeEdge, xBackOffAfterEdge, zBackOffAfterEdge)) {
1392
                thisMove.edgeAxisClamped = true;
1393
            }
1394
        }
1395
        // TODO: Optimize. Brute forcing collisions with all 9 speed combinations will tank performance.
1396
        // TODO: If sprinting detected correctly, Might not need to loop backward, only 6 left to check
1397
        for (i = 0; i < 9; i++) {
1398
            // TODO: Perhaps after this use collisionVector to store onGround?
1399
            Vector collisionVector = from.collide(new Vector(xTheoreticalDistance[i], yDistanceBeforeCollide, zTheoreticalDistance[i]), onGround, from.getBoundingBox());
1400
            if (xTheoreticalDistance[i] != collisionVector.getX()) {
1401
                // This theoretical speed would result in a collision. Remember it.
1402
                collideX[i] = true;
1403
            }
1404
            if (yDistanceBeforeCollide != collisionVector.getY()) {
1405
                // This theoretical speed would result in a collision. Remember it.
1406
                // Only needed for supporting block detection.
1407
                collideY[i] = true;
1408
            }
1409
            if (zTheoreticalDistance[i] != collisionVector.getZ()) {
1410
                // This theoretical speed would result in a collision. Remember it.
1411
                collideZ[i] = true;
1412
            }
1413
            xTheoreticalDistance[i] = collisionVector.getX();
1414
            zTheoreticalDistance[i] = collisionVector.getZ();
1415
            if (lastMove.xCorrectedDistancePost != 0 || lastMove.zCorrectedDistancePost != 0) {
1416
                xTheoreticalDistance[i] += lastMove.xCorrectedDistancePost;
1417
                zTheoreticalDistance[i] += lastMove.zCorrectedDistancePost;
1418
            }
1419
        }
1420
        // Check for block push.
1421
        // TODO: Unoptimized insertion point... Waste of resources to just override everything at the end. See note at the start of the method.
1422
        if (xPush) {
1423
            for (i = 0; i < 9; i++) {
1424
                // Override all theoretical speeds.
1425
                xTheoreticalDistance[i] = thisMove.xDistance;
1426
            }
1427
        }
1428
        if (zPush) {
1429
            for (i = 0; i < 9; i++) {
1430
                zTheoreticalDistance[i] = thisMove.zDistance;
1431
            }
1432
        }
1433
        /////////////////////////////////////////////////////////////////////////////
1434
        // Determine which (and IF) theoretical speed should be set in this move   //
1435
        /////////////////////////////////////////////////////////////////////////////
1436
        /*
1437
           True, if the offset between predicted and actual speed is smaller than the accuracy margin (0.0001).
1438
        */
1439
        boolean found = false;
1440
        /*
1441
           True will check if BOTH axis have an offset smaller than 0.0001 (against strafe-like cheats and anything of that sort that relies on the specific direction of the move).
1442
           Otherwise, only the combined horizontal distance will be checked against the offset.
1443
        */
1444
        boolean strict = cc.survivalFlyStrictHorizontal;
1445
        final double hiddenThresholdSq = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1446
                ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
1447
        final double hiddenThresholdH = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1448
                ? hiddenThresholdSq : Math.sqrt(hiddenThresholdSq);
1449
        final boolean yDistanceSuppressed = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1450
                ? thisMove.yDistance < hiddenThresholdSq : thisMove.yDistance * thisMove.yDistance < hiddenThresholdSq;
1451
        for (i = 0; i < 9; i++) {
1452
            // If this theoretical candidate results in a post-collision horizontal
1453
            // displacement smaller than the client's packet-suppression threshold,
1454
            // it means that the client may have omitted (suppressed) the intermediate
1455
            // packet(s) for this motion. Record the WASD candidate index so it can
1456
            // be used as a seed for the hidden-tick reconstructor.
1457
            // Note: if multiple candidates match, the last matching index will
1458
            // overwrite earlier ones (thisMove.hiddenDistanceIndex holds only one
1459
            // seed candidate).
1460
            if (!collideX[i] && !collideZ[i] && yDistanceSuppressed) {
1461
                final double postH = MathUtil.dist(xTheoreticalDistance[i], zTheoreticalDistance[i]);
1462
                final boolean suppressedPost = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2)
1463
                        ? postH < hiddenThresholdSq : postH * postH < hiddenThresholdSq;
1464
                final boolean edgeSuppressedPacket = thisMove.edgeBackoffApplied
1465
                        && (thisMove.hDistance < hiddenThresholdH
1466
                                || Math.abs(thisMove.xDistance) < hiddenThresholdH
1467
                                || Math.abs(thisMove.zDistance) < hiddenThresholdH)
1468
                        && i < xBackOffAfterEdge.length
1469
                        && (xBackOffAfterEdge[i] != xMotionBeforeEdge[i] || zBackOffAfterEdge[i] != zMotionBeforeEdge[i]);
1470
                if (suppressedPost || edgeSuppressedPacket) {
1471
                    thisMove.hiddenDistanceIndex = i;
1472
                }
1473
            }
1474
            if (strict) {
1475
                if (MathUtil.almostEqual(thisMove.xDistance, xTheoreticalDistance[i], Magic.PREDICTION_EPSILON) 
1476
                    && MathUtil.almostEqual(thisMove.zDistance, zTheoreticalDistance[i], Magic.PREDICTION_EPSILON)) {
1477
                    found = true;
1478
                }
1479
            }
1480
            else {
1481
                double theoreticalHDistance = MathUtil.dist(xTheoreticalDistance[i], zTheoreticalDistance[i]);
1482
                if (MathUtil.almostEqual(theoreticalHDistance, thisMove.hDistance, Magic.PREDICTION_EPSILON)) {
1483
                    found = true;
1484
                }
1485
            }
1486
            
1487
            /*
1488
               True it will force a violation even if there's a matching theoretical speed.
1489
             */
1490
            boolean forceViolation = false;
1491
            if (found) {
1492
                // These checks must be performed ex-post because they rely on data that is set after the prediction.
1493
                if (pData.isSprinting() 
1494
                    && (theorInputs[i].getForwardDir() != ForwardDirection.FORWARD && theorInputs[i].getStrafeDir() != StrafeDirection.NONE && theorInputs[i].getForwardDir() != ForwardDirection.NONE
1495
                        || player.getFoodLevel() <= 5)) { 
1496
                    tags.add("illegalsprint");
1497
                    Improbable.check(player, (float) thisMove.hDistance, System.currentTimeMillis(), "moving.survivalfly.illegalsprint", pData);
1498
                    // Keep looping
1499
                    forceViolation = true;
1500
                }
1501
                if (thisMove.possibleStopMotion) {
1502
                    double[] result = HiddenMotionReconstructor.simulateStoppingMotion(sinYaw, cosYaw, theorInputs[i], data, pData, from, to, onGround, player.isFlying(), yDistanceBeforeCollide);
1503
                    thisMove.xCorrectedDistancePre = result[0];
1504
                    thisMove.zCorrectedDistancePre = result[1];
1505
                }
1506
                if (!forceViolation) {
1507
                    // Found a candidate to set in this move; these collisions are valid.
1508
                    // Also set the supporting block.
1509
                    if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1510
                        pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to.getBoundingBox(), collideY[i] && yDistanceBeforeCollide < 0.0));
1511
                    }
1512
                    thisMove.collideX = collideX[i];
1513
                    thisMove.collideZ = collideZ[i];
1514
                    thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1515
                    thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to, theorInputs[i].getStrafe(), theorInputs[i].getForward());
1516
                    break;
1517
                }
1518
            }
1519
        }
1520
        if (!found) {
1521
            // If we couldn't find a direct match for the observed movement, but
1522
            // we previously recorded a candidate that would have been suppressed
1523
            // by the client (hiddenDistanceIndex), attempt to reconstruct the
1524
            // missing intermediate ticks. The reconstructor is seeded with the
1525
            // selected WASD candidate and its post-collision displacement and
1526
            // will return cumulative displacements for the hidden ticks. Those
1527
            // results are then folded into the theoretical distances or stored
1528
            // in the "corrected distance" fields for use across ticks.
1529
            int hiddenSeed = thisMove.hiddenDistanceIndex;
1530
            if (hiddenSeed < 0 && thisMove.edgeBackoffApplied
1531
                    && (lastMove.edgeAxisClamped || lastMove.edgeCornerResolved
1532
                            || lastMove.xCorrectedDistancePost != 0.0 || lastMove.zCorrectedDistancePost != 0.0
1533
                            || Math.abs(thisMove.xDistance) < hiddenThresholdH
1534
                            || Math.abs(thisMove.zDistance) < hiddenThresholdH)) {
1535
                hiddenSeed = MathUtil.findClosestHorizontalIndex(xTheoreticalDistance, zTheoreticalDistance, thisMove.xDistance, thisMove.zDistance);
1536
            }
1537
            if (hiddenSeed >= 0 && !thisMove.edgeBackoffApplied) {
1538
                final int hiddenResolved = tryFoldHiddenTickExplanation(player, hiddenSeed, xTheoreticalDistance, zTheoreticalDistance,
1539
                        xMotionBeforeEdge, zMotionBeforeEdge, theorInputs, sinYaw, cosYaw, movementSpeed, data, pData, from, onGround,
1540
                        yDistanceBeforeCollide, strict, tags);
1541
                if (hiddenResolved >= 0) {
1542
                    i = hiddenResolved;
1543
                    found = true;
1544
                    if (thisMove.edgeBackoffApplied) {
1545
                        tags.add("edge_hidden");
1546
                    }
1547
                }
1548
            }
1549
            else if (lastMove.hiddenDistanceIndex != -1 && (lastMove.xCorrectedDistancePre != 0 || lastMove.zCorrectedDistancePre != 0)) {
1550
                // Hidden move was found and sum match lastMove but the component of the sum didn't right as there another direction that also make the sum correct!
1551
                isPredictable = false;
1552
            }
1553
            if (!found && thisMove.edgeBackoffApplied && activeCornerClamp) {
1554
                double cornerRefSpeed = thisMove.hDistance;
1555
                for (int c = 0; c < 9; c++) {
1556
                    cornerRefSpeed = Math.max(cornerRefSpeed, MathUtil.dist(xTheoreticalDistance[c], zTheoreticalDistance[c]));
1557
                    cornerRefSpeed = Math.max(cornerRefSpeed, MathUtil.dist(xBackOffAfterEdge[c], zBackOffAfterEdge[c]));
1558
                }
1559
                final double cornerMatchTolerance = HiddenMotionReconstructor.edgeCornerMatchTolerance(cornerRefSpeed);
1560
                final int cornerIdx = HiddenMotionReconstructor.findBestEdgeCornerCandidate(thisMove.xDistance, thisMove.zDistance, thisMove.hDistance,
1561
                        xTheoreticalDistance, zTheoreticalDistance, xBackOffAfterEdge, zBackOffAfterEdge, strict, cornerMatchTolerance);
1562
                if (cornerIdx >= 0) {
1563
                    i = cornerIdx;
1564
                    found = true;
1565
                    isPredictable = false;
1566
                    thisMove.edgeCornerResolved = true;
1567
                    tags.add("edge_corner");
1568
                    if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1569
                        pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to.getBoundingBox(), collideY[i] && yDistanceBeforeCollide < 0.0));
1570
                    }
1571
                    thisMove.collideX = collideX[i];
1572
                    thisMove.collideZ = collideZ[i];
1573
                    thisMove.collidesHorizontally = thisMove.collideX || thisMove.collideZ;
1574
                    thisMove.negligibleHorizontalCollision = thisMove.collidesHorizontally && CollisionUtil.isHorizontalCollisionNegligible(new Vector(xTheoreticalDistance[i], thisMove.yDistance, zTheoreticalDistance[i]), to, theorInputs[i].getStrafe(), theorInputs[i].getForward());
1575
                }
1576
            }
1577
            // Note: Always set no matter what, prevent desync
1578
            if (pData.getClientVersion().isAtLeast(ClientVersion.V_1_20)) {
1579
                pData.setSupportingBlockData(SupportingBlockUtils.checkSupportingBlock(to.getBlockCache(), player, pData.getSupportingBlockData(), new Vector(thisMove.xDistance, thisMove.yDistance, thisMove.zDistance), to.getBoundingBox(), from.isOnGround()));
1580
            }
1581
        }
1582
        //////////////////////////////////////////////////////////////
1583
        // Finish. Check if the move had been predictable at all    //
1584
        //////////////////////////////////////////////////////////////
1585
        /* The index representing the input associated with the pair of speed to set in this move. */
1586
        int indexPair = i;
1587
        int xIdx = -1;
1588
        int zIdx = -1;
1589
        if (indexPair >= 9) {
1590
            // Cheating: prevent an index out of bounds (we couldn't find the correct pair of speed to set)
1591
            indexPair = 4;
1592
        }
1593
        // If the move is unpredictable, the x/z speeds cannot be associated to a specific input, thus we set them independently.
1594
        // TODO: How can we know the impulse if the move is uncertain? ...
1595
        if (!isPredictable) {
1596
            // In this case, instead of setting the predicted speed with the smallest delta from the actual speed (0.0001), we select the speed that is closest to the current one, effectively allowing for the maximum predicted speed (just limits speed then).
1597
            if (thisMove.edgeBackoffApplied && activeCornerClamp) {
1598
                // Corner: both axes clipped on the actual seed; one combined candidate for packet match.
1599
                xIdx = MathUtil.findClosestHorizontalIndex(xTheoreticalDistance, zTheoreticalDistance, thisMove.xDistance, thisMove.zDistance);
1600
                zIdx = xIdx;
1601
            } else {
1602
                xIdx = MathUtil.findClosestIndex(xTheoreticalDistance, thisMove.xDistance);
1603
                zIdx = MathUtil.findClosestIndex(zTheoreticalDistance, thisMove.zDistance);
1604
            }
1605
        }
1606
        final int motionIdx = !isPredictable ? xIdx : indexPair;
1607
        int momentumStorageIdx = motionIdx;
1608
        if (thisMove.edgeBackoffApplied) {
1609
            if (found && indexPair >= 0 && indexPair < 9) {
1610
                momentumStorageIdx = indexPair;
1611
            } else if (thisMove.hiddenDistanceIndex >= 0) {
1612
                momentumStorageIdx = thisMove.hiddenDistanceIndex;
1613
            } else {
1614
                final int edgeMomIdx = HiddenMotionReconstructor.findBestEdgeMomentumIndex(
1615
                        xMotionBeforeEdge, zMotionBeforeEdge, xBackOffAfterEdge, zBackOffAfterEdge, motionIdx);
1616
                if (edgeMomIdx >= 0) {
1617
                    momentumStorageIdx = edgeMomIdx;
1618
                }
1619
            }
1620
            // Use cached back-off arrays from the brute loop above instead of recomputing.
1621
            final boolean selectedClipped = momentumStorageIdx >= 0 && momentumStorageIdx < 9
1622
                    && HiddenMotionReconstructor.edgeStillClampsCached(xMotionBeforeEdge[momentumStorageIdx],
1623
                            zMotionBeforeEdge[momentumStorageIdx], xBackOffAfterEdge[momentumStorageIdx], zBackOffAfterEdge[momentumStorageIdx]);
1624
            thisMove.edgeAxisClamped = selectedClipped;
1625
            thisMove.edgeCornerClamp = selectedClipped && momentumStorageIdx >= 0 && momentumStorageIdx < 9
1626
                    && HiddenMotionReconstructor.edgeStillClampsCornerCached(xMotionBeforeEdge[momentumStorageIdx],
1627
                            zMotionBeforeEdge[momentumStorageIdx], xBackOffAfterEdge[momentumStorageIdx], zBackOffAfterEdge[momentumStorageIdx]);
1628
        }
1629
        if (thisMove.edgeBackoffApplied && thisMove.edgeAxisClamped) {
1630
            thisMove.motionX = xMotionBeforeEdge[momentumStorageIdx];
1631
            thisMove.motionZ = zMotionBeforeEdge[momentumStorageIdx];
1632
        } else if (!thisMove.edgeBackoffApplied) {
1633
            thisMove.motionX = xMotionBeforeEdge[motionIdx];
1634
            thisMove.motionZ = zMotionBeforeEdge[motionIdx];
1635
        } else {
1636
            thisMove.motionX = thisMove.xDistance;
1637
            thisMove.motionZ = thisMove.zDistance;
1638
        }
1639
        // Done, set in this move.
1640
        thisMove.xAllowedDistance = xTheoreticalDistance[motionIdx];
1641
        thisMove.zAllowedDistance = zTheoreticalDistance[motionIdx];
1642
        thisMove.hasImpulse = !isPredictable ? AlmostBoolean.MAYBE // We don't know the direction in this case.
1643
                              : AlmostBoolean.match(theorInputs[indexPair].getForwardDir() != ForwardDirection.NONE || theorInputs[indexPair].getStrafeDir() != StrafeDirection.NONE);
1644
        thisMove.strafeImpulse = theorInputs[motionIdx].getStrafeDir();
1645
        thisMove.forwardImpulse = theorInputs[motionIdx].getForwardDir();
1646
        if (debug) {
1647
            player.sendMessage(ChatColor.YELLOW + "[SurvivalFly] (postPredict) " + (!isPredictable ? "Uncertain" : "Predicted") + " direction: " + theorInputs[motionIdx].getForwardDir() +" | "+ theorInputs[motionIdx].getStrafeDir());
1648
        }
1649
        return isPredictable;
1650
    }
1651
    
1652
    
1653
    /**
1654
     * Reconstruct suppressed ticks (including {@code maybeBackOffFromEdge} in the simulator) and fold into prediction.
1655
     *
1656
     * @return Matched candidate index, or {@code -1}.
1657
     */
1658
    private int tryFoldHiddenTickExplanation(final Player player, final int hiddenSeed, final double[] xTheoreticalDistance, final double[] zTheoreticalDistance,
1659
            final double[] xMotionBeforeEdge, final double[] zMotionBeforeEdge, final PlayerKeyboardInput[] theorInputs, final float sinYaw,
1660
            final float cosYaw, final float movementSpeed, final MovingData data, final IPlayerData pData, final PlayerLocation from,
1661
            final boolean onGround, final double yDistanceBeforeCollide, final boolean strict, final Collection<String> tags) {
1662
        if (hiddenSeed < 0 || hiddenSeed >= xTheoreticalDistance.length) {
1663
            return -1;
1664
        }
1665
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
1666
        final double seedX = xMotionBeforeEdge[hiddenSeed];
1667
        final double seedZ = zMotionBeforeEdge[hiddenSeed];
1668
        final double[] result = HiddenMotionReconstructor.findBestHiddenTickExplanation(sinYaw, cosYaw, movementSpeed, theorInputs[hiddenSeed],
1669
                seedX, seedZ, data, pData, from, pData.isInCrouchingPose(),
1670
                attributeAccess.getHandle().getPlayerSneakingFactor(player), BridgeMisc.isSlowedDownByUsingAnItem(player), onGround,
1671
                xTheoreticalDistance[hiddenSeed], zTheoreticalDistance[hiddenSeed], yDistanceBeforeCollide, player.isFlying());
1672
        if (thisMove.xDistance == 0 && thisMove.zDistance == 0) {
1673
            thisMove.xCorrectedDistancePost = xTheoreticalDistance[hiddenSeed];
1674
            thisMove.zCorrectedDistancePost = zTheoreticalDistance[hiddenSeed];
1675
            xTheoreticalDistance[hiddenSeed] = 0.0;
1676
            zTheoreticalDistance[hiddenSeed] = 0.0;
1677
            tags.add("hdistzero");
1678
        } else {
1679
            xTheoreticalDistance[hiddenSeed] += result[0];
1680
            zTheoreticalDistance[hiddenSeed] += result[1];
1681
        }
1682
        final double matchTol = thisMove.edgeBackoffApplied
1683
                ? HiddenMotionReconstructor.edgeCornerMatchTolerance(Math.max(thisMove.hDistance, MathUtil.dist(seedX, seedZ)))
1684
                : Magic.PREDICTION_EPSILON;
1685
        if (strict) {
1686
            if (MathUtil.almostEqual(thisMove.xDistance, xTheoreticalDistance[hiddenSeed], matchTol)
1687
                    && MathUtil.almostEqual(thisMove.zDistance, zTheoreticalDistance[hiddenSeed], matchTol)) {
1688
                thisMove.xCorrectedDistancePre = result[0];
1689
                thisMove.zCorrectedDistancePre = result[1];
1690
                return hiddenSeed;
1691
            }
1692
        } else {
1693
            final double theoreticalHDistance = MathUtil.dist(xTheoreticalDistance[hiddenSeed], zTheoreticalDistance[hiddenSeed]);
1694
            if (MathUtil.almostEqual(theoreticalHDistance, thisMove.hDistance, matchTol)) {
1695
                return hiddenSeed;
1696
            }
1697
        }
1698
        return -1;
1699
    }
1700
1701
    /**
1702
     * After a corner candidate is applied, allow only a speed-scaled offset vs the matched allowed distance
1703
     */
1704
    private static double applyEdgeCornerResolvedTolerance(final PlayerMoveData thisMove, final double hDistanceAboveLimit, final boolean strict) {
1705
        if (hDistanceAboveLimit <= 0.0 || !thisMove.edgeCornerResolved) {
1706
            return hDistanceAboveLimit;
1707
        }
1708
        final double tolerance = HiddenMotionReconstructor.edgeCornerMatchTolerance(
1709
                Math.max(thisMove.hAllowedDistance, thisMove.hDistance));
1710
        if (strict) {
1711
            if (Math.abs(thisMove.xDistance - thisMove.xAllowedDistance) <= tolerance
1712
                    && Math.abs(thisMove.zDistance - thisMove.zAllowedDistance) <= tolerance) {
1713
                return 0.0;
1714
            }
1715
        } else if (Math.abs(thisMove.hDistance - thisMove.hAllowedDistance) <= tolerance) {
1716
            return 0.0;
1717
        }
1718
        return hDistanceAboveLimit;
1719
    }
1720
1721
    /**
1722
     * In case we couldn't predict speed, just ensure that actual speed is below what we estimated.
1723
     * This allows for minor deviations below the allowed speed limit, thus players/cheaters may execute movements 
1724
     * that are technically invalid, but do not provide any [significant] gameplay advantage.
1725
     *
1726
     * @param thisMove
1727
     * @param strict If true, only the combined speed (hDistance) is required to be below the allowed one.
1728
     * @return The horizontal distance above limit.
1729
     */
1730
    private double handleUnpredictableMove(final PlayerMoveData thisMove, boolean strict) {
1731
        double hDistanceAboveLimit = 0.0;
1732
        double offset = thisMove.hDistance - thisMove.hAllowedDistance;
1733
        if (strict) {
1734
            // both axes must be below-allowed distance if strict.
1735
            if (MathUtil.exceedsAllowedDistance(thisMove.xDistance, thisMove.xAllowedDistance) 
1736
                || MathUtil.exceedsAllowedDistance(thisMove.zDistance, thisMove.zAllowedDistance)) {
1737
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1738
            }
1739
        } 
1740
        else {
1741
            // Otherwise, only the combined distance needs to be below the limit.
1742
            if (thisMove.hDistance > thisMove.hAllowedDistance) {
1743
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1744
            }
1745
        }
1746
        return hDistanceAboveLimit;
1747
    }
1748
    
1749
    
1750
    /**
1751
     * If the move was predictable, ensure that the difference between actual and allowed speed is below the {@link Magic#PREDICTION_EPSILON}.
1752
     * 
1753
     * @param thisMove
1754
     * @param strict If true, the offset of each axis (x/z) must be below the epsilon, otherwise, only the combined offset (h) will be checked.
1755
     *               Needed against cheats that rely on the specific direction of a move.
1756
     * @return The horizontal distance above limit.
1757
     */
1758
    private double handlePredictableMove(final PlayerMoveData thisMove, boolean strict) {
1759
        double hDistanceAboveLimit = 0.0;
1760
        double offset = thisMove.hDistance - thisMove.hAllowedDistance;
1761
        if (strict) {
1762
            if (!MathUtil.isOffsetWithinPredictionEpsilon(thisMove.xDistance, thisMove.xAllowedDistance) 
1763
                || !MathUtil.isOffsetWithinPredictionEpsilon(thisMove.zDistance, thisMove.zAllowedDistance)) {
1764
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1765
            }
1766
        } 
1767
        else {
1768
            if (!MathUtil.isOffsetWithinPredictionEpsilon(thisMove.hDistance, thisMove.hAllowedDistance)) {
1769
                hDistanceAboveLimit = Math.max(hDistanceAboveLimit, offset);
1770
            }
1771
        }
1772
        return hDistanceAboveLimit;
1773
    }
1774
    
1775
    private enum Operation {
1776
        SET,
1777
        ADD,
1778
        SUBTRACT,
1779
        MULTIPLY,
1780
        DIVIDE
1781
    }
1782
    private void configVerticalAllowedValue(PlayerMoveData thisMove, double[] yTheoreticalDistance, double value, Operation operation) {
1783
        final boolean direct = yTheoreticalDistance == null;
1784
        if (direct) {
1785
            switch (operation) {
1786
            case ADD:
1787
                thisMove.yAllowedDistance += value;
1788
                break;
1789
            case DIVIDE:
1790
                thisMove.yAllowedDistance /= value;
1791
                break;
1792
            case MULTIPLY:
1793
                thisMove.yAllowedDistance *= value;
1794
                break;
1795
            case SET:
1796
                thisMove.yAllowedDistance = value;
1797
                break;
1798
            case SUBTRACT:
1799
                thisMove.yAllowedDistance -= value;
1800
                break;
1801
            }
1802
        } else {
1803
            switch (operation) {
1804
            case ADD:
1805
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1806
                    yTheoreticalDistance[i] += value;
1807
                }
1808
                break;
1809
            case DIVIDE:
1810
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1811
                    yTheoreticalDistance[i] /= value;
1812
                }
1813
                break;
1814
            case MULTIPLY:
1815
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1816
                    yTheoreticalDistance[i] *= value;
1817
                }
1818
                break;
1819
            case SET:
1820
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1821
                    yTheoreticalDistance[i] = value;
1822
                }
1823
                break;
1824
            case SUBTRACT:
1825
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1826
                    yTheoreticalDistance[i] -= value;
1827
                }
1828
                break;
1829
            }
1830
        }
1831
    }
1832
1833
    /**
1834
     * Relative (to workarounds) vertical distance checking.
1835
     *
1836
     * @param forceResetMomentum    Whether the check should start with 0.0 speed on applying air friction.
1837
     * @param useBlockChangeTracker
1838
     */
1839
    private double[] vDistRel(final Player player, final PlayerLocation from,
1840
                              final boolean fromOnGround, final boolean resetFrom, final PlayerLocation to,
1841
                              final boolean toOnGround, final boolean resetTo,
1842
                              final double yDistance, boolean isNormalOrPacketSplitMove,
1843
                              final PlayerMoveData lastMove,
1844
                              final MovingData data, final IPlayerData pData,
1845
                              boolean forceResetMomentum, final boolean debug, boolean useBlockChangeTracker) {
1846
        double yDistanceAboveLimit = 0.0;
1847
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
1848
        final boolean yDirectionSwitch = lastMove.toIsValid && lastMove.yDistance != yDistance && (yDistance <= 0.0 && lastMove.yDistance >= 0.0 || yDistance >= 0.0 && lastMove.yDistance <= 0.0);
1849
        /* Not on ground, not on climbable, not in liquids, not in stuck-speed, no lostground (...) */
1850
        final boolean fullyInAir = !thisMove.touchedGroundWorkaround && !resetFrom && !resetTo;
1851
        final CombinedData cData = pData.getGenericInstance(CombinedData.class);
1852
        final boolean onGround = PhysicsGroundResolver.resolvePhysicsOnGround(from, thisMove, lastMove, false, false);
1853
        /*
1854
         * 1: Simulate the reset of speed that the client should have sent to the server.
1855
         * [Client lands on the ground but does not come to a "rest" on top of the block (and thus, reset the vertical speed), instead they'll immediately descend right after, but with speed that is still based on a previous move of 0.0]
1856
         * Can be noticed when stepping down stair of slabs or noob-towering upwards.
1857
         * See: https://gyazo.com/0f748030296aebc0484564629abe6864
1858
         * After interpolating the ground status, notice how the player immediately proceeds to descend with speed as if they actually landed on the ground with the previous move (-0.0784)
1859
         */
1860
        // After completing a "touch-down" (toOnGround), the next move should always come *from* ground
1861
        // Thus, such cases can be generalised by checking for negative motion and last move landing on ground, but this move not *starting back* from a ground position.
1862
        boolean touchDownIsLost = !thisMove.couldStepUp && thisMove.yDistance < 0.0 && (lastMove.toLostGround || lastMove.to.onGround) && !thisMove.from.onGround;
1863
        
1864
        ///////////////////////////////////////////////////
1865
        // Vertical push/pull is put on top priority     //
1866
        ///////////////////////////////////////////////////
1867
        if (useBlockChangeTracker) {
1868
            double[] res = getVerticalBlockMoveResult(thisMove.yDistance, from, to, data);
1869
            if (res != null) {
1870
                thisMove.yAllowedDistance = res[0];
1871
                yDistanceAboveLimit = res[1];
1872
                // Nothing else to do here; allow the movement as-is.
1873
                return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1874
            }
1875
        }
1876
        
1877
        
1878
        //////////////////////////////////////////////////////////////////////////////
1879
        // Test if this movement can fit into any pre-set envelope                  //
1880
        //////////////////////////////////////////////////////////////////////////////
1881
        // NOTE: order of these checks should be from most common to least common.
1882
        if (thisMove.yDistance == 0.0 && fromOnGround) {
1883
            // No vertical motion in this case, as the player is on ground.
1884
            thisMove.yAllowedDistance = 0.0;
1885
            yDistanceAboveLimit = 0.0;
1886
            tags.add("onground_env");
1887
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1888
        }
1889
        if (PhysicsEnvelope.isJumpMotion(from, to, player, fromOnGround, toOnGround, true)) {
1890
            // After stepping, jumping comes second.
1891
            // Players can jump anywhere through air, so this must be checked before the actual prediction.
1892
            thisMove.yAllowedDistance = thisMove.yDistance;
1893
            yDistanceAboveLimit = 0.0;
1894
            thisMove.isJump = true;
1895
            data.jumpDelay = Magic.MAX_JUMP_DELAY;
1896
            tags.add("jump_env");
1897
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1898
        }
1899
        if (PhysicsEnvelope.isStepUpByNCPDefinition(pData, fromOnGround, toOnGround, player)) {
1900
            // Players can step anywhere, both in liquid and in air, so this must be checked before everything else.
1901
            thisMove.yAllowedDistance = thisMove.yDistance;
1902
            yDistanceAboveLimit = 0.0;
1903
            thisMove.isStepUp = true;
1904
            tags.add("step_env");
1905
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1906
        }
1907
        if (onGround && thisMove.tridentRelease.decideOptimistically() && thisMove.multiMoveCount == 1 
1908
            && !isNormalOrPacketSplitMove && MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, Magic.RIPTIDE_ON_GROUND_MOVE)) {
1909
            // Riptide from ground launch at the end of the movement stack; the actual riptide push will come next. Allowed this move as-is.
1910
            // IMPORTANT NOTE: this move specifically will always cause NCP to fire a Bukkit-based split move on the first split move, no matter what.
1911
            thisMove.yAllowedDistance = Magic.RIPTIDE_ON_GROUND_MOVE;
1912
            // The riptide move was split into two moves: 1.2 upwards from ground and then the actual riptide push.
1913
            // We can therefore set the flag to YES from here on. The push will be handled below.
1914
            data.setTridentReleaseEvent(AlmostBoolean.YES);
1915
            yDistanceAboveLimit = 0.0;
1916
            tags.add("gnd_riptide_pre");
1917
            return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
1918
        }
1919
        
1920
        
1921
        ///////////////////////////////////////////////////////////////////////////////////
1922
        // Estimate the allowed yDistance (per-move distance check)                      //
1923
        ///////////////////////////////////////////////////////////////////////////////////
1924
        /* 
1925
           0: With space bar pressed. 
1926
           1: with space bar not pressed 
1927
           2: swimming not applied at all
1928
         */
1929
        double[] yTheoreticalDistance = null;
1930
        boolean[] collideLiquidY = null;
1931
        // Initialize with momentum (or lack thereof)
1932
        thisMove.yAllowedDistance = forceResetMomentum || touchDownIsLost 
1933
                                    || (lastMove.yDistance < 0.0 && (fromOnGround || thisMove.fromLostGround))
1934
                                    || !lastMove.toIsValid ? 0.0 : lastMove.yDistance;
1935
        if (lastMove.headObstructed) thisMove.yAllowedDistance = 0.0;
1936
        if (lastMove.yCorrectedDistancePre != 0.0) thisMove.yAllowedDistance = lastMove.yCorrectedDistancePre;
1937
        // *----------stuck-speed-momentum-reset----------*
1938
        if (TrigUtil.lengthSquared(data.lastStuckInBlockHorizontal, data.lastStuckInBlockVertical, data.lastStuckInBlockHorizontal) > 1.0E-7) {
1939
            if (data.lastStuckInBlockVertical != 1.0) {
1940
                thisMove.yAllowedDistance = 0.0;
1941
            }
1942
        }
1943
        // TODO: Optimize to only split when need detect jump
1944
        if (!BridgeMisc.isSpaceBarImpulseKnown(player)) {
1945
            // *----------------------------------*
1946
            // *--- Loop the space bar impulse ---*
1947
            // *----------------------------------*
1948
            // Initialize with the momentum that has hitherto been calculated.
1949
            yTheoreticalDistance = new double[3];
1950
            collideLiquidY = new boolean[3];
1951
            // With space bar pressed
1952
            yTheoreticalDistance[0] = thisMove.yAllowedDistance;
1953
            // With space bar not pressed
1954
            yTheoreticalDistance[1] = thisMove.yAllowedDistance;
1955
            // With swimming speed not applied
1956
            yTheoreticalDistance[2] = thisMove.yAllowedDistance;
1957
        }
1958
        // *----------updateEntityAfterFallOn()----------*
1959
        // NOTE: pressing space bar on a bouncy block will override the bounce (in that case, vdistrel will fall back to the jump check above).
1960
        // updateEntityAfterFallOn(), this function is called on the next move
1961
        if (pData.isShiftKeyPressed() && lastMove.collideY) {
1962
            if (yTheoreticalDistance != null) {
1963
                boolean bounceUp = false;
1964
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
1965
                    if (yTheoreticalDistance[i] < 0.0) { // NOTE: Must be the allowed distance, not the actual one (exploit)
1966
                        if (from.isOnBouncyBlock()) {
1967
                            // The effect works by inverting the distance.
1968
                            // Beds have a weaker bounce effect (BedBlock.java).
1969
                            yTheoreticalDistance[i] = from.isOnSlimeBlock() ? -yTheoreticalDistance[i] : -yTheoreticalDistance[i] * 0.66;
1970
                            bounceUp = true;
1971
                        }
1972
                    }
1973
                }
1974
                if (bounceUp) tags.add("bounceup");
1975
            } else {
1976
                if (thisMove.yAllowedDistance < 0.0) { // NOTE: Must be the allowed distance, not the actual one (exploit)
1977
                    if (from.isOnBouncyBlock()) {
1978
                        // The effect works by inverting the distance.
1979
                        // Beds have a weaker bounce effect (BedBlock.java).
1980
                        thisMove.yAllowedDistance = from.isOnSlimeBlock() ? -thisMove.yAllowedDistance : -thisMove.yAllowedDistance * 0.66;
1981
                        tags.add("bounceup");
1982
                    }
1983
                }
1984
            }
1985
        }
1986
        // *----------tryCheckInsideBlocks()----------*
1987
        // Bubble columns are checked in the tryCheckInsideBlocks method, so it comes after updateEntityAfterFallOn()...
1988
        from.tryApplyBubbleColumnMotion(thisMove, yTheoreticalDistance);
1989
        // Honey block sliding mechanic...
1990
        if (from.isSlidingDown()) {
1991
            // Speed is static in this case
1992
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, -Magic.SLIDE_SPEED_THROTTLE, Operation.SET);
1993
        }
1994
        // *----------Finalization of handleRelativeFrictionAndCalculateMovement; this check/condition is called after having called the move() function. The former method is called only when the player is traveling in air, thus the liquid and gliding checks ----------*
1995
        if (!lastMove.from.inLiquid) {
1996
            // TODO: We have to loop the jumping state for 1.21.1 and below... No other way to put it unfortunately. This will make the code an ugly mess than it already is.
1997
            final boolean jumpedOrCollided = lastMove.collidesHorizontally || data.input.wasSpaceBarPressed() && BridgeMisc.isSpaceBarImpulseKnown(player);
1998
            if (thisMove.from.onClimbable || thisMove.from.touchedPowderSnow && BridgeMisc.canStandOnPowderSnow(player)) {
1999
                if (jumpedOrCollided) {
2000
                    configVerticalAllowedValue(thisMove, yTheoreticalDistance, 0.2, Operation.SET);
2001
                } else if (yTheoreticalDistance != null) {
2002
                    yTheoreticalDistance[0] = 0.2;
2003
                }
2004
            }
2005
        }
2006
        // *----------Gravity, friction and other medium-dependent modifiers in LivingEntity.travel() (water first, then lava and finally air)----------*
2007
        data.nextGravity = attributeAccess.getHandle().getGravity(player);
2008
        if (lastMove.from.inWater) {
2009
            if (lastMove.collidesHorizontally && lastMove.from.onClimbable && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2010
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, 0.2, Operation.SET);
2011
            }
2012
            // Water applies friction before calling the fluidFalling function.
2013
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2014
            if (BridgeMisc.hasGravity(player)) {
2015
                // Legacy: clients older than 1.13 have some kind of gravity effect applied to them even in liquids, if they don't press the space bar.
2016
                // On 1.13 and above, only friction gets applied, resulting in a much slower descending speed when not pressing the space bar pressed.
2017
                if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
2018
                    configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LEGACY_LIQUID_GRAVITY, Operation.SUBTRACT);
2019
                } 
2020
                else {
2021
                    // In 1.13 the gravity effect in liquids was removed and this function got added.
2022
                    if (yTheoreticalDistance != null) {
2023
                        for (int i =0; i < yTheoreticalDistance.length; i++) {
2024
                            Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yTheoreticalDistance[i] <= 0.0, new Vector(0.0, yTheoreticalDistance[i], 0.0), cData.wasSprinting);
2025
                            yTheoreticalDistance[i] = fluidFallingAdjustMovement.getY();
2026
                        }
2027
                    }
2028
                }
2029
            }
2030
            tags.add("v_water");
2031
        }
2032
        else if (lastMove.from.inLava) {
2033
            // Lava friction is quite odd. Depending on specified thresholds, it can be 0.5 or 0.8
2034
            if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) { // Note that this condition is not vanilla. It's just a shortcut to avoid replicating the condition contained in BlockProperties.getBlockFrictionFactor.
2035
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2036
                if (BridgeMisc.hasGravity(player)) {
2037
                    if (pData.getClientVersion().isLowerThan(ClientVersion.V_1_13)) {
2038
                        configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LEGACY_LIQUID_GRAVITY, Operation.SUBTRACT);
2039
                    } 
2040
                    else {
2041
                        // getFluidFallingAdjustedMovement is only applied if friction is 0.8.
2042
                        if (yTheoreticalDistance != null) {
2043
                            for (int i =0; i < yTheoreticalDistance.length; i++) {
2044
                                Vector fluidFallingAdjustMovement = from.getFluidFallingAdjustedMovement(data.lastGravity, yTheoreticalDistance[i] <= 0.0, new Vector(0.0, yTheoreticalDistance[i], 0.0), cData.wasSprinting);
2045
                                yTheoreticalDistance[i] = fluidFallingAdjustMovement.getY();
2046
                            }
2047
                        }
2048
                    }
2049
                }
2050
            }
2051
            else {
2052
                // Otherwise, 0.5
2053
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2054
            }
2055
            if (data.lastGravity != 0.0) {
2056
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, -data.lastGravity / 4.0, Operation.ADD);
2057
            }
2058
            tags.add("v_lava");
2059
        }
2060
        else {
2061
            // Air motion
2062
            if (cData.wasLevitating) {
2063
                // Levitation forces players to ascend and does not work in liquids, so thankfully we don't have to account for that, other than stuck-speed.
2064
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, (0.05 * data.lastLevitationLevel - lastMove.yAllowedDistance) * 0.2, Operation.ADD);
2065
            }
2066
            else configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastGravity, Operation.SUBTRACT);
2067
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.lastFrictionVertical, Operation.MULTIPLY);
2068
            tags.add("v_air");
2069
        }
2070
        // *----------Finalize LivingEntity.travel; isFree() check----------*
2071
        // Try making the player jump out of the liquid... 
2072
        // This condition is the same for both lava and water, and is always done at the end of the travel() function.
2073
        //TODO: Still broken as thisMove.collidesHorizontally not working properly!
2074
        if (from.isInLiquid() && lastMove.collidesHorizontally) {
2075
            if (yTheoreticalDistance != null) {
2076
                for (int i =0; i < yTheoreticalDistance.length; i++) {
2077
                    if (from.isUnobstructed(yTheoreticalDistance[i])) yTheoreticalDistance[i] = 0.3;
2078
                }
2079
            } else if (from.isUnobstructed(thisMove.yAllowedDistance)) thisMove.yAllowedDistance = 0.3;
2080
            tags.add("v_exiting_liquid");
2081
        }
2082
        
2083
        
2084
        //////////////////////////////////
2085
        // Last client-tick/move        //
2086
        //////////////////////////////////
2087
        if (from.isInLiquid() && verticalLiquidPushComponent != 0.0) {
2088
            // Liquid vertical push component calculated in hdistrel.
2089
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, verticalLiquidPushComponent, Operation.ADD);
2090
        }
2091
        // *----------TridentItem.releaseUsing(), apply trident motion----------*
2092
        if (thisMove.tridentRelease.decideOptimistically()) {
2093
            thisMove.tridentRelease = AlmostBoolean.YES;
2094
            // Riptide works by propelling the player in air after releasing the trident (the effect only pushes the player, unless is on ground)
2095
            final Vector riptideVelocity = to.getRiptideVelocity(onGround);
2096
            final double fric = getLastYGroundRipTide(from, lastMove, data, cData);
2097
            if (fric != 0.0) {
2098
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, riptideVelocity.getY() + fric, Operation.SET);
2099
            } 
2100
            else {
2101
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, riptideVelocity.getY(), Operation.ADD);
2102
            }
2103
        }
2104
        //  Special case for riptide at the start of the movement tick (when the riptide move is "unified" and not split into two updates; friction of the next move is used here)
2105
        if (lastMove.tridentRelease.decide() && lastMove.toIsValid) {
2106
            final PlayerMoveData secondLastMove = data.playerMoves.getSecondPastMove();
2107
            if (lastMove.from.onGround || (secondLastMove.toIsValid && secondLastMove.yDistance <= 0.0 && (secondLastMove.from.onGround || secondLastMove.fromLostGround))) {
2108
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.RIPTIDE_ON_GROUND_MOVE * data.lastFrictionVertical, Operation.SUBTRACT);
2109
            }
2110
        }
2111
        if (from.isInWater() && pData.getClientVersion().isHigherThan(ClientVersion.V_1_12_2)) {
2112
            // *----------LocalPlayer.aiStep(), goDownInWater()----------*
2113
            if (pData.isShiftKeyPressed()) {
2114
                configVerticalAllowedValue(thisMove, yTheoreticalDistance, Magic.LIQUID_SPEED_GAIN, Operation.SUBTRACT);
2115
            }
2116
        }
2117
        // *----------LivingEntity.aiStep(), negligible speed----------*
2118
        checkNegligibleMomentumVertical(pData, thisMove, yTheoreticalDistance);
2119
        // *----------EntityLiving.aiStep(), apply liquid motion----------*
2120
        if (from.isInLiquid()) {
2121
            // *----------------------------------------------------------------------------------------------------------------------------*
2122
            // *----- When in liquid, the game doesn't care about players being on ground, only if they press the space bar.   -------------*
2123
            // *----- When they do press it, the game sets the jumping field to true.   ----------------------------------------------------*
2124
            // *----- However, up until MC 1.21.2 we couldn't know this, because the player used to not send anything about it -------------*
2125
            // *----- Solution: if the client/server does not support input reading/sending, loop the space bar impulse   ------------------*
2126
            // *----------------------------------------------------------------------------------------------------------------------------* 
2127
            if (yTheoreticalDistance == null) {
2128
                // From: EntityLiving.java -> aiStep() and KeyboardInput.java.
2129
                if (data.input.isSpaceBarPressed()) {
2130
                    boolean isSubmergedInWater = from.isInWater() && thisMove.submergedWaterHeight > 0.0;
2131
                    double fluidJumpThreshold = from.getEyeHeight() < 0.4D ? 0.0D : 0.4D;
2132
                    if (isSubmergedInWater && (!onGround || thisMove.submergedWaterHeight > fluidJumpThreshold)) {
2133
                        thisMove.yAllowedDistance += Magic.LIQUID_SPEED_GAIN; // The game distinguishes liquid tagkeys, but the motion is the same...
2134
                    } 
2135
                    else if (from.isInLava() && (!onGround || thisMove.submergedLavaHeight > fluidJumpThreshold)) {
2136
                        thisMove.yAllowedDistance += Magic.LIQUID_SPEED_GAIN;
2137
                    } 
2138
                    else if ((onGround || isSubmergedInWater && thisMove.submergedWaterHeight <= fluidJumpThreshold) && data.jumpDelay == 0) {
2139
                        thisMove.yAllowedDistance = data.liftOffEnvelope.getJumpGain(data.jumpAmplifier) * attributeAccess.getHandle().getJumpGainMultiplier(player);
2140
                        data.jumpDelay = Magic.MAX_JUMP_DELAY;
2141
                        thisMove.hasImpulse = AlmostBoolean.YES; // Minecraft explicitly tells us that there's impulse in this case.
2142
                        thisMove.isJump = true;
2143
                    }
2144
                } 
2145
                else {
2146
                    data.jumpDelay = 0;
2147
                }
2148
                //*--------Player.java, travel(). Apply swimming speed-------*
2149
                // 1.13 swimming speed depends on the looking direction vector of the player.
2150
                // Small note: the game here does NOT explicitly ensure that the player is also in water. Thus, this should be checked outside the from.isInLiquid() condition
2151
                if (Bridge1_13.isSwimming(player) && from.getEntity() instanceof Player) { // inside vehicle checking would always return false, since Sf doesn't run for vehicles, but in the future, we might merge vehicle checks
2152
                    Vector lookVector = TrigUtil.getLookingDirection(to, player);
2153
                    double swimmingScalar = lookVector.getY() < -0.2 ? 0.085 : 0.06;
2154
                    if (lookVector.getY() <= 0.0 || data.input.isSpaceBarPressed()
2155
                        || BlockProperties.getLiquidHeightAt(from.getBlockCache(), Location.locToBlock(from.getX()), Location.locToBlock(from.getY() + 1.0 - 0.1), Location.locToBlock(from.getZ()), BlockFlags.F_WATER, true) != 0.0) {
2156
                        thisMove.yAllowedDistance += (lookVector.getY() - thisMove.yAllowedDistance) * swimmingScalar;
2157
                    }
2158
                }
2159
            }
2160
            else {
2161
                boolean isSubmergedInWater = from.isInWater() && thisMove.submergedWaterHeight > 0.0;
2162
                double fluidJumpThreshold = from.getEyeHeight() < 0.4D ? 0.0D : 0.4D;
2163
                if (isSubmergedInWater && (!onGround || thisMove.submergedWaterHeight > fluidJumpThreshold)) {
2164
                    yTheoreticalDistance[0] += Magic.LIQUID_SPEED_GAIN;
2165
                }
2166
                else if (from.isInLava() && (!onGround || thisMove.submergedLavaHeight > fluidJumpThreshold)) {
2167
                    yTheoreticalDistance[0] += Magic.LIQUID_SPEED_GAIN;
2168
                }
2169
                else if ((onGround || isSubmergedInWater && thisMove.submergedWaterHeight <= fluidJumpThreshold) && data.jumpDelay == 0) {
2170
                    yTheoreticalDistance[0] = data.liftOffEnvelope.getJumpGain(data.jumpAmplifier) * attributeAccess.getHandle().getJumpGainMultiplier(player);
2171
                    data.jumpDelay = Magic.MAX_JUMP_DELAY;
2172
                    thisMove.hasImpulse = AlmostBoolean.YES;
2173
                    // (Can't set thisMove.isJump yet.)
2174
                }
2175
                if (Bridge1_13.isSwimming(player) && !player.isInsideVehicle()) {
2176
                    Vector lookVector = TrigUtil.getLookingDirection(to, player);
2177
                    double swimmingScalar = lookVector.getY() < -0.2 ? 0.085 : 0.06;
2178
                    // Note: Since thisMove.isJump is always false because not been set yet, make these conditions unusable, result in brute force
2179
                    //if (lookVector.getY() <= 0.0 || thisMove.isJump 
2180
                    //    || BlockProperties.getLiquidHeightAt(from.getBlockCache(), Location.locToBlock(from.getX()), Location.locToBlock(from.getY()+1.0-0.1), Location.locToBlock(from.getZ()), BlockFlags.F_WATER, true) != 0.0) {
2181
                    yTheoreticalDistance[0] += (lookVector.getY() - yTheoreticalDistance[0]) * swimmingScalar;
2182
                    yTheoreticalDistance[1] += (lookVector.getY() - yTheoreticalDistance[1]) * swimmingScalar;
2183
                    //}
2184
                }
2185
            }
2186
        }
2187
        // *----------LivingEntity.travel(), handleRelativeFrictionAndCalculateMovement() -> handleOnClimbable()----------*
2188
        if (!from.isInLiquid() && from.isOnClimbable() && from.canClimbUp(data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier))) {
2189
            // Should replicate the condition: !this.getInBlockState().is(Blocks.SCAFFOLDING)
2190
            final Material typeId = from.getBlockType();
2191
            final long theseFlags = BlockFlags.getBlockFlags(typeId);
2192
            if (yTheoreticalDistance != null) {
2193
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
2194
                    yTheoreticalDistance[i] = Math.max(yTheoreticalDistance[i], -Magic.CLIMBABLE_MAX_SPEED);
2195
                    if (yTheoreticalDistance[i] < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
2196
                        && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2197
                        yTheoreticalDistance[i] = 0.0;
2198
                    }
2199
                }
2200
            } else {
2201
                thisMove.yAllowedDistance = Math.max(thisMove.yAllowedDistance, -Magic.CLIMBABLE_MAX_SPEED);
2202
                if (thisMove.yAllowedDistance < 0.0 && pData.isShiftKeyPressed() && from.getEntity() instanceof Player
2203
                    && (theseFlags & BlockFlags.F_SCAFFOLDING) == 0 && pData.getClientVersion().isAtLeast(ClientVersion.V_1_14)) {
2204
                    thisMove.yAllowedDistance = 0.0;
2205
                }
2206
            }
2207
            tags.add("v_climbable");
2208
        }
2209
        // *----------Beginning call of Entity.move(); apply stuck speed multipliers----------*
2210
        if (TrigUtil.lengthSquared(data.nextStuckInBlockHorizontal, data.nextStuckInBlockVertical, data.nextStuckInBlockHorizontal) > 1.0E-7) {
2211
            // If we looped the space bar impulse, all later modifiers are applied to each speed.
2212
            configVerticalAllowedValue(thisMove, yTheoreticalDistance, data.nextStuckInBlockVertical, Operation.MULTIPLY);
2213
        }
2214
        // *----------Entity.move(), call the collide() function----------*
2215
        // Include horizontal motion to account for stepping: there are cases where NCP's isStep definition fails to catch it.
2216
        // (In which case, isStep will return false and fall-back to friction here)
2217
        // It is imperative that you pass yAllowedDistance as argument here (not the real yDistance), because if the player isn't on ground, the current motion will be used to determine it (collideY && motionY < 0.0). Passing an uncontrolled yDistance will be easily exploitable.
2218
        if (yTheoreticalDistance == null) {
2219
            Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, thisMove.yAllowedDistance, thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround && lastMove.yDistance < 0.0, from.getBoundingBox());
2220
            thisMove.headObstructed = thisMove.yAllowedDistance != collisionVector.getY() && thisMove.yDistance >= 0.0 && !fromOnGround;  // New definition of head obstruction: yDistance is checked because Minecraft considers players to be on ground when motion is explicitly negative
2221
            // If this vertical move resulted in a collision, remember it.
2222
            thisMove.collideY = collisionVector.getY() != thisMove.yAllowedDistance;
2223
            thisMove.yAllowedDistance = collisionVector.getY();
2224
        }
2225
        else {
2226
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
2227
                Vector collisionVector = from.collide(new Vector(thisMove.xAllowedDistance, yTheoreticalDistance[i], thisMove.zAllowedDistance), fromOnGround || thisMove.fromLostGround && lastMove.yDistance < 0.0, from.getBoundingBox());
2228
                if (yTheoreticalDistance[i] != collisionVector.getY()) {
2229
                    // This theoretical speed would result in a collision. Remember it.
2230
                    collideLiquidY[i] = true;
2231
                }
2232
                //TODO: Might wrong if underliquid as not all moves are headObstructed
2233
                thisMove.headObstructed = yTheoreticalDistance[i] != collisionVector.getY() && thisMove.yDistance >= 0.0 && !fromOnGround;
2234
                yTheoreticalDistance[i] = collisionVector.getY();
2235
            }
2236
        }
2237
        
2238
        
2239
        ////////////////////////////////////////////////////////////////////////////
2240
        // Calculate the offset: check for velocity and workarounds on violations // 
2241
        ////////////////////////////////////////////////////////////////////////////
2242
        if (yTheoreticalDistance != null) {
2243
            final double hiddenThreshold = pData.getClientVersion().isLowerThan(ClientVersion.V_1_18_2) ? Magic.Minecraft_minMoveSqDistance_legacy : Magic.Minecraft_minMoveSqDist_modern;
2244
            if (thisMove.hDistance < hiddenThreshold) {
2245
                for (int i = 0; i < yTheoreticalDistance.length; i++) {
2246
                    if (yTheoreticalDistance[i] < hiddenThreshold && !collideLiquidY[i]) {
2247
                        thisMove.hiddenYDistanceIndex = i;
2248
                        break;
2249
                    }
2250
                }
2251
            }
2252
            boolean found = false;
2253
            for (int i = 0; i < yTheoreticalDistance.length; i++) {
2254
                if (MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, yTheoreticalDistance[i])) {
2255
                    thisMove.yAllowedDistance = yTheoreticalDistance[i];
2256
                    thisMove.collideY = collideLiquidY[i];
2257
                    found = true;
2258
                    break;
2259
                }
2260
            }
2261
            if (!found && thisMove.hiddenYDistanceIndex != -1) {
2262
                final double result[] = HiddenMotionReconstructor.findBestHiddenTickExplanation(yTheoreticalDistance[thisMove.hiddenYDistanceIndex], player, data, cData, pData, from, to, attributeAccess.getHandle().getJumpGainMultiplier(player), 
2263
                                                                                                verticalLiquidPushComponent, onGround, yTheoreticalDistance[thisMove.hiddenYDistanceIndex]);
2264
                yTheoreticalDistance[thisMove.hiddenYDistanceIndex] += result[0];
2265
                if (MathUtil.isOffsetWithinPredictionEpsilon(thisMove.yDistance, yTheoreticalDistance[thisMove.hiddenYDistanceIndex])) {
2266
                    thisMove.yAllowedDistance = yTheoreticalDistance[thisMove.hiddenYDistanceIndex];
2267
                    thisMove.collideY = collideLiquidY[thisMove.hiddenYDistanceIndex];
2268
                    thisMove.yCorrectedDistancePre = result[0];
2269
                    found = true;
2270
                    tags.add("v_hidden");
2271
                }
2272
            }
2273
        }
2274
        /* Expected difference from current to allowed */
2275
        final double offset = thisMove.yDistance - thisMove.yAllowedDistance;
2276
        if (Math.abs(offset) < Magic.PREDICTION_EPSILON) {
2277
            // Accuracy margin.
2278
        }
2279
        else {
2280
            // Check for workarounds at the end and override the prediction if needed (just allow the movement in this case.)
2281
            if (MagicWorkarounds.checkPostPredictWorkaround(data, fromOnGround, toOnGround, from, to, thisMove.yAllowedDistance, player, isNormalOrPacketSplitMove)) {
2282
                thisMove.yAllowedDistance = thisMove.yDistance;
2283
                if (debug) {
2284
                    player.sendMessage("[SurvivalFly] Workaround ID used: " + (!justUsedWorkarounds.isEmpty() ? StringUtil.join(justUsedWorkarounds, " , ") : ""));
2285
                }
2286
            }
2287
            else if (data.getOrUseVerticalVelocity(yDistance).isEmpty()) {
2288
                // If velocity can be used for compensation, use it.
2289
                yDistanceAboveLimit = Math.max(yDistanceAboveLimit, Math.abs(offset));
2290
                tags.add("vdistrel");
2291
                if (debug) {
2292
                    player.sendMessage(ChatColor.RED + "[SurvivalFly] vdistrel: predicted=" + StringUtil.fdec6.format(thisMove.yAllowedDistance) + ", actual=" + StringUtil.fdec6.format(thisMove.yDistance) + ", offset=" + StringUtil.fdec6.format(offset));
2293
                }
2294
            }
2295
        }
2296
        return new double[]{thisMove.yAllowedDistance, yDistanceAboveLimit};
2297
    }
2298
2299
    private double getLastYGroundRipTide(PlayerLocation from, PlayerMoveData lastMove, MovingData data, CombinedData cData) {
2300
        double tmp = 0.0;
2301
        if (lastMove.tridentRelease == AlmostBoolean.MAYBE) {
2302
            if (lastMove.from.inWater) {
2303
                return from.getFluidFallingAdjustedMovement(data.lastGravity, true, new Vector(0.0, 0.0, 0.0), false).getY();
2304
            }
2305
            else if (lastMove.from.inLava) {
2306
                // Lava friction is quite odd. Depending on specified thresholds, it can be 0.5 or 0.8
2307
                if (data.lastFrictionVertical != Magic.LAVA_VERTICAL_INERTIA) {
2308
                    tmp = from.getFluidFallingAdjustedMovement(data.lastGravity, true, new Vector(0.0, 0.0, 0.0), false).getY();
2309
                }
2310
                else {
2311
                    // Otherwise, 0.5
2312
                    tmp *= data.lastFrictionVertical;
2313
                }
2314
                if (data.lastGravity != 0.0) {
2315
                    tmp += -data.lastGravity / 4.0;
2316
                }
2317
            }
2318
            else {
2319
                // Air motion
2320
                if (cData.wasLevitating) {
2321
                    // Levitation forces players to ascend and does not work in liquids, so thankfully we don't have to account for that, other than stuck-speed.
2322
                    tmp += (0.05 * data.lastLevitationLevel - lastMove.yAllowedDistance) * 0.2;
2323
                }
2324
                else tmp -= data.lastGravity;
2325
                tmp *= data.lastFrictionVertical;
2326
            }
2327
        }
2328
        return tmp;
2329
    }
2330
2331
2332
    /**
2333
     * After-horizontal-failure checks.
2334
     *
2335
     * @return hAllowedDistance, hDistanceAboveLimit, hFreedom
2336
     */
2337
    private double[] hDistAfterFailure(final Player player,
2338
                                       final PlayerLocation from, final PlayerLocation to,
2339
                                       double hAllowedDistance, double hDistanceAboveLimit,
2340
                                       final PlayerMoveData thisMove, final PlayerMoveData lastMove, final boolean debug,
2341
                                       final MovingData data, final MovingConfig cc, final IPlayerData pData, final int tick,
2342
                                       boolean useBlockChangeTracker, final boolean fromOnGround, final boolean toOnGround,
2343
                                       final boolean isNormalOrPacketSplitMove) {
2344
        /*
2345
         * 0: If we got a speed violation and the player is using an item, assume it to be a "noslowdown" violation.
2346
         */
2347
        if (cc.survivalFlyResetItem && BridgeMisc.isSlowedDownByUsingAnItem(player) && !Bridge1_9.isGliding(player)) {
2348
            // Forcibly release the item in use.
2349
            pData.requestItemUseResync();
2350
            tags.add("itemresync");
2351
            if (!BridgeMisc.isSlowedDownByUsingAnItem(player) && hDistanceAboveLimit > 0.0) {
2352
                // Re-estimate with released item (if it still throws a VL, the player is actually cheating, if the item is still in use, then it wasn't desync'ed).
2353
                double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
2354
                hAllowedDistance = res[0];
2355
                hDistanceAboveLimit = res[1];
2356
            }
2357
        }
2358
        /*
2359
         *  Because this move is not sent by the client and cannot be predicted through normal means, we have to brute force it.
2360
         */
2361
        if (hDistanceAboveLimit > 0.0 && lastMove.possibleStopMotion) {
2362
            lastMove.possibleStopMotion = false;
2363
            tags.add("stop_motion");
2364
            double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, false);
2365
            hAllowedDistance = res[0];
2366
            hDistanceAboveLimit = res[1];
2367
        }
2368
        /*
2369
         * 2: Undetectable jump (must brute force here): player failed with the onGround flag, lets try with off-ground then.
2370
         */
2371
        if (PhysicsEnvelope.isVerticallyConstricted(from, to, pData) && hDistanceAboveLimit > 0.0) {
2372
            tags.add("vert_constricted");
2373
            double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, false, true);
2374
            hAllowedDistance = res[0];
2375
            hDistanceAboveLimit = res[1];
2376
        }
2377
        /*
2378
         * 3: Above limit again? Check for past onGround states caused by block changes (i.e.: ground was pulled off from the player's feet)
2379
         */
2380
        if (useBlockChangeTracker && hDistanceAboveLimit > 0.0) {
2381
            // Be sure to test this only if the player is seemingly off ground
2382
            if (!thisMove.fromLostGround && !from.isOnGround() && from.isOnGroundOpportune(cc.yOnGround, 0L, blockChangeTracker, data.blockChangeRef, tick)) {
2383
                tags.add("onground_tracked");
2384
                double[] res = prepareSpeedEstimation(from, to, pData, player, data, thisMove, lastMove, fromOnGround, toOnGround, debug, isNormalOrPacketSplitMove, true, false);
2385
                hAllowedDistance = res[0];
2386
                hDistanceAboveLimit = res[1];
2387
            }
2388
        }
2389
        /* 
2390
         * 4: Distance is still above limit; last resort: check if the distance above limit can be covered with velocity
2391
         */
2392
        // TODO: Implement Asofold's fix to prevent too easy abuse:
2393
        // See: https://github.com/NoCheatPlus/Issues/issues/374#issuecomment-296172316
2394
        //double hFreedom = 0.0; // Horizontal velocity used.
2395
        //if (hDistanceAboveLimit > 0.0) {
2396
        //    hFreedom = data.getHorizontalFreedom();
2397
        //    if (hFreedom < hDistanceAboveLimit) {
2398
        //        // Distance above limit is still greater. Try using queued velocity if possible.
2399
        //        hFreedom += data.useHorizontalVelocity(hDistanceAboveLimit - hFreedom);
2400
        //    }
2401
        //    if (hFreedom > 0.0) {
2402
        //        tags.add("hvel");
2403
        //        hDistanceAboveLimit = Math.max(0.0, hDistanceAboveLimit - hFreedom);
2404
        //    }
2405
        //}
2406
        return new double[]{hAllowedDistance, hDistanceAboveLimit, 0.0};
2407
    }
2408
    
2409
    /**
2410
     * Handles a violation for Survivalfly.
2411
     * 
2412
     * @return The Location where the player will be set backed to.
2413
     */
2414
    private Location handleViolation(final double result,
2415
                                     final Player player, final PlayerLocation from, final PlayerLocation to,
2416
                                     final MovingData data, final MovingConfig cc) {
2417
        // Increment violation level.
2418
        data.survivalFlyVL += result;
2419
        data.sfVLMoveCount = data.getPlayerMoveCount();
2420
        final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, result, cc.survivalFlyActions);
2421
        if (vd.needsParameters()) {
2422
            vd.setParameter(ParameterName.LOCATION_FROM, String.format(Locale.US, "%.2f, %.2f, %.2f", from.getX(), from.getY(), from.getZ()));
2423
            vd.setParameter(ParameterName.LOCATION_TO, String.format(Locale.US, "%.2f, %.2f, %.2f", to.getX(), to.getY(), to.getZ()));
2424
            vd.setParameter(ParameterName.DISTANCE, String.format(Locale.US, "%.2f", TrigUtil.distance(from, to)));
2425
            vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
2426
        }
2427
        // Some resetting is done in MovingListener.
2428
        if (executeActions(vd).willCancel()) {
2429
            // Set back + view direction of to (more smooth).
2430
            return MovingUtil.getApplicableSetBackLocation(player, to.getYaw(), to.getPitch(), to, data, cc);
2431
        }
2432
        else {
2433
            data.sfJumpPhase = 0;
2434
            // Cancelled by other plugin, or no cancel set by configuration.
2435
            return null;
2436
        }
2437
    }
2438
2439
2440
    /**
2441
     * Hover violations have to be handled in this check, because they are handled as SurvivalFly violations (needs executeActions).
2442
     */
2443
    public final void handleHoverViolation(final Player player, final PlayerLocation loc, final MovingConfig cc, final MovingData data) {
2444
        data.survivalFlyVL += cc.sfHoverViolation;
2445
        // TODO: Extra options for set back / kick, like vl?
2446
        data.sfVLMoveCount = data.getPlayerMoveCount();
2447
        data.sfVLInAir = true;
2448
        final ViolationData vd = new ViolationData(this, player, data.survivalFlyVL, cc.sfHoverViolation, cc.survivalFlyActions);
2449
        if (vd.needsParameters()) {
2450
            vd.setParameter(ParameterName.LOCATION_FROM, String.format(Locale.US, "%.2f, %.2f, %.2f", loc.getX(), loc.getY(), loc.getZ()));
2451
            vd.setParameter(ParameterName.LOCATION_TO, "(HOVER)");
2452
            vd.setParameter(ParameterName.DISTANCE, "0.0(HOVER)");
2453
            vd.setParameter(ParameterName.TAGS, "hover");
2454
        }
2455
        if (executeActions(vd).willCancel()) {
2456
            // Set back or kick.
2457
            final Location newTo = MovingUtil.getApplicableSetBackLocation(player, loc.getYaw(), loc.getPitch(), loc, data, cc);
2458
            if (newTo != null) {
2459
                data.prepareSetBack(newTo);
2460
                SchedulerHelper.teleportEntity(player, newTo, BridgeMisc.TELEPORT_CAUSE_CORRECTION_OF_POSITION);
2461
            }
2462
            else {
2463
                // Solve by extra actions ? Special case (probably never happens)?
2464
                player.kickPlayer("Hovering?");
2465
            }
2466
        }
2467
        else {
2468
            // Ignore.
2469
        }
2470
    }
2471
2472
2473
    /**
2474
     * Debug output.
2475
     */
2476
    private void outputDebug(final Player player, final PlayerLocation to, final PlayerLocation from,
2477
                             final MovingData data,
2478
                             final double hDistance, final double hAllowedDistance, final double hFreedom,
2479
                             final double yDistance, final double yAllowedDistance,
2480
                             final boolean fromOnGround, final boolean resetFrom,
2481
                             final boolean toOnGround, final boolean resetTo,
2482
                             final PlayerMoveData thisMove) {
2483
2484
        // TODO: Show player name once (!)
2485
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
2486
        final double yDistDiffEx = yDistance - yAllowedDistance;
2487
        final double hDistDiffEx = thisMove.hDistance - thisMove.hAllowedDistance;
2488
        final StringBuilder builder = new StringBuilder(500);
2489
        builder.append(CheckUtils.getLogMessagePrefix(player, type));
2490
        final String hVelUsed = hFreedom > 0 ? " / hVelUsed: " + StringUtil.fdec3.format(hFreedom) : "";
2491
        builder.append("\nOnGround: " + (thisMove.headObstructed ? "(head obstr.) " : from.isSlidingDown() ? "(sliding down) " : "") + (thisMove.touchedGroundWorkaround ? "(lost ground) " : "") + (fromOnGround ? "onground -> " : (resetFrom ? "resetcond -> " : "--- -> ")) + (toOnGround ? "onground" : (resetTo ? "resetcond" : "---")) + ", jumpPhase: " + data.sfJumpPhase + ", LiftOff: " + data.liftOffEnvelope.name());
2492
        final String dHDist = lastMove.toIsValid ? "(" + StringUtil.formatDiff(hDistance, lastMove.hDistance) + ")" : "";
2493
        final String dYDist = lastMove.toIsValid ? "(" + StringUtil.formatDiff(yDistance, lastMove.yDistance)+ ")" : "";
2494
        builder.append("\n" + " hDist: " + StringUtil.fdec6.format(hDistance) + dHDist + " / offset: " + hDistDiffEx + " / predicted: " + StringUtil.fdec6.format(hAllowedDistance) + hVelUsed +
2495
                "\n" + " vDist: " + StringUtil.fdec6.format(yDistance) + dYDist + " / offset: " + yDistDiffEx + " / predicted: " + StringUtil.fdec6.format(yAllowedDistance) + " , setBackY: " + (data.hasSetBack() ? (data.getSetBackY() + " (jump height: " + StringUtil.fdec3.format(to.getY() - data.getSetBackY()) + " / max jump height: " + data.liftOffEnvelope.getMaxJumpHeight(data.jumpAmplifier) + ")") : "?"));
2496
        if (lastMove.toIsValid) {
2497
            builder.append("\n fdsq: " + StringUtil.fdec3.format(thisMove.distanceSquared / lastMove.distanceSquared));
2498
        }
2499
        if (!lastMove.toIsValid) {
2500
            builder.append("\n Invalid last move (data reset)");
2501
        }
2502
        if (!lastMove.valid) {
2503
            builder.append("\n Invalid last move (missing data)");
2504
        }
2505
        if (!thisMove.verVelUsed.isEmpty()) {
2506
            builder.append(" , vVelUsed: " + thisMove.verVelUsed + " ");
2507
        }
2508
        data.addVerticalVelocity(builder);
2509
        data.addHorizontalVelocity(builder);
2510
        if (player.isSleeping()) {
2511
            tags.add("sleeping");
2512
        }
2513
        if (Bridge1_9.isWearingElytra(player)) {
2514
            // Just wearing (not isGliding).
2515
            tags.add("elytra_off");
2516
        }
2517
        if (!tags.isEmpty()) {
2518
            builder.append("\n" + " Tags: " + StringUtil.join(tags, "+"));
2519
        }
2520
        if (!justUsedWorkarounds.isEmpty()) {
2521
            builder.append("\n" + " Workaround ID: " + StringUtil.join(justUsedWorkarounds, " , "));
2522
        }
2523
        builder.append("\n");
2524
        NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, builder.toString());
2525
    }
2526
2527
2528
    private void logPostViolationTags(final Player player) {
2529
        debug(player, "SurvivalFly Post violation handling tag update:\n" + StringUtil.join(tags, "+"));
2530
    }
2531
}

How it counteracts this module

SurvivalFly is NoCheatPlus's core survival-movement check, invoked from MovingListener on every resolved move event. It never trusts the client's onGround bit: PhysicsGroundResolver.resolvePhysicsOnGround (SurvivalFly.java line 700) recomputes the ground state from the collision envelope of the move, and the move's horizontal and vertical distances are compared against physics-predicted envelopes (yAllowedDistance/hAllowedDistance built from lift-off/jump physics, friction and air acceleration). Hovering is a separate sub-check: MovingListener.checkHover (line 2593) counts airborne ticks (sfHoverTicks, default 85) while the player is off the ground and not on a ladder, then calls SurvivalFly.handleHoverViolation (line 2441), which adds 200 survivalFly VL and sets back or kicks the player.

Against the movement-rewrite modes the check nullifies the spoofed ground state instead of flagging packets. GhostlyDisabler's forced onGround=true is simply ignored (the envelope resolves the real ground state), and its 1/64 grid snap keeps the Y deltas inside the prediction envelope, so the mode buys nothing while its motion is genuinely vanilla; the moment the player hovers without ground contact, the hover sub-check accumulates the airborne window. MineLandKickDisabler's one-block-above-ground hover with zero movement input is the canonical hover signature: with the default 85-tick threshold the mode's 20-to-100-tick armed window (80 ticks) barely undershoots, but any longer hover or a lower configured sfHoverTicks converts it to a 200-VL hover violation. TeleportDisabler's Up/Down variants send +-1024-2048 block Y offsets that exceed the vertical envelope by orders of magnitude, and NCP's violation path converges on prepareSetBack (MovingListener line 1900) plus a teleportEntity correction; NCP additionally tracks teleports via PlayerTeleportEvent and accepts the server's corrected position (data.hasTeleported/isTeleportedPosition), so the S08 rubber-band the mode provokes is absorbed as a teleport rather than escalating.

The check is envelope-based and setback-first by default, so marginal spoofs degrade into rubber-banding instead of instant flags; its tolerance comes from the physics workaround set (step-up/stairs, slime, water/lava, lost-ground recovery, elytra/trident states) and the configurable hover window. The bypass surface is exactly those workarounds: a mode that keeps real ground contact within the hover window and stays inside the jump envelope (which AbilitiesDisabler's slime-bounce motion must do anyway) stays under SurvivalFly, but only by moving with genuine physics: the check's value is that it forces that.

anticheat MorePackets (moving.morepackets)

MorePackets.java127 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.moving.player;
16
17
import java.util.ArrayList;
18
import java.util.List;
19
20
import org.bukkit.Location;
21
import org.bukkit.entity.Player;
22
23
import fr.neatmonster.nocheatplus.actions.ParameterName;
24
import fr.neatmonster.nocheatplus.checks.Check;
25
import fr.neatmonster.nocheatplus.checks.CheckType;
26
import fr.neatmonster.nocheatplus.checks.ViolationData;
27
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
28
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
29
import fr.neatmonster.nocheatplus.checks.net.NetStatic;
30
import fr.neatmonster.nocheatplus.players.IPlayerData;
31
import fr.neatmonster.nocheatplus.utilities.StringUtil;
32
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
33
34
/**
35
 * The MorePackets check will try to identify players that send more than the usual
36
 * amount of move-packets to the server to be able to move faster than normal, without getting caught by the other
37
 * checks (flying/running).
38
 */
39
public class MorePackets extends Check {
40
41
    private final List<String> tags = new ArrayList<String>();
42
43
    /**
44
     * Instantiates a new more packets check.
45
     */
46
    public MorePackets() {
47
        super(CheckType.MOVING_MOREPACKETS);
48
    }
49
50
    /**
51
     * Check for speeding by sending too many packets. We assume 22 packets per
52
     * second to be legitimate, while 20 would be ideal. See
53
     * PlayerData.morePacketsFreq for the monitored amount of time and the
54
     * resolution. See NetStatic for the actual check code.
55
     * 
56
     * @param player
57
     * @param from
58
     * @param to
59
     * @param allowSetSetBack
60
     *            If to allow setting the set back location.
61
     * @param data
62
     * @param cc
63
     * @return
64
     */
65
    public Location check(final Player player, final PlayerLocation from, final PlayerLocation to, 
66
            final boolean allowSetSetBack, final MovingData data, final MovingConfig cc,
67
            final IPlayerData pData) {
68
        // Take time once, first:
69
        final long time = System.currentTimeMillis();
70
        final boolean debug = pData.isDebugActive(type);
71
72
        //    	if (from.isSamePos(to)) {
73
        //    		// Ignore moves with "just look" for now.
74
        //    		// TODO: Extra ActionFrequency for "just look" + use to burn, maybe also check individually.
75
        //    		return null;
76
        //    	}
77
78
        // Ensure we have a set back location.
79
        if (allowSetSetBack && !data.hasMorePacketsSetBack()){
80
            // TODO: Check if other set back is appropriate or if to set/reset on other events.
81
            if (data.hasSetBack()) {
82
                data.setMorePacketsSetBackFromSurvivalfly();
83
            }
84
            else {
85
                data.setMorePacketsSetBack(from);
86
            }
87
        }
88
89
        // Check for a violation of the set limits.
90
        tags.clear();
91
        final double violation = NetStatic.morePacketsCheck(data.morePacketsFreq, time, 1f, cc.morePacketsEPSMax, cc.morePacketsEPSIdeal, data.morePacketsBurstFreq, cc.morePacketsBurstPackets, cc.morePacketsBurstDirect, cc.morePacketsBurstEPM, tags);
92
93
        // Process violation result.
94
        if (violation > 0.0) {
95
            // Increment violation level.
96
            data.morePacketsVL = violation; // TODO: Accumulate somehow [e.g. always += 1, decrease with continuous moving without violation]?
97
98
            // Violation handling.
99
            final ViolationData vd = new ViolationData(this, player, data.morePacketsVL, violation, cc.morePacketsActions);
100
            if (debug || vd.needsParameters()) {
101
                vd.setParameter(ParameterName.PACKETS, Integer.toString(new Double(violation).intValue()));
102
                vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
103
            }
104
            if (executeActions(vd).willCancel()) {
105
                // Set to cancel the move.
106
                /*
107
                 * TODO: Harmonize with MovingUtil.getApplicableSetBackLocation
108
                 * (somehow include the desired set back type / loc / context).
109
                 */
110
                return data.hasMorePacketsSetBack() ? data.getMorePacketsSetBack() : data.getSetBack(to); // TODO
111
            }
112
        } 
113
        else if (allowSetSetBack && data.getMorePacketsSetBackAge() > cc.morePacketsSetBackAge) {
114
            // Update the set back location. (CHANGED to only update, if not a violation.)
115
            // (Might update whenever newTo == null)
116
            data.setMorePacketsSetBack(from);
117
            if (debug) {
118
                debug(player, "Update set back (morepackets) to from.");
119
            }
120
        }
121
122
        // No set back.
123
        return null;
124
125
    }
126
127
}

How it counteracts this module

MorePackets rate-limits the movement packet stream. MovingData.morePacketsFreq (line 321) is an ActionFrequency with 500ms buckets fed once per move packet, and NetStatic.morePacketsCheck (net/NetStatic.java line 63) computes two violation signals on every add: an EPS-accumulated signal (fullCount over the window, with idle windows 'burnt' at the ideal 20 packets/sec, minus the tolerated 22 EPS max, DefaultConfig lines 458-459) and a burst signal from the most recent 500ms bucket (more than 15 packets in the bucket generates a burst event, 10 burst events in the window is a direct violation, 95 per minute is an EPM violation, DefaultConfig lines 460-462). Default actions cancel from vl>2 and kick from vl>100.

The burst branch is a direct counter to blink/timer dumps. RiseBalanceDisabler's Pulse mode is the check's signature target: BlinkComponent buffers every outbound C03 and dispatch() flushes the queue every 450ms, so a sped-up client (timerSpeed > 1) dumps 15+ movement packets into a single 500ms bucket, tripping the burst window even after the lag divisor, while the sustained rate above 22 EPS trips epsacc across the window. The mode's own ledger is a client-side mirror of the same accounting: balance -= 50ms per sent C03 is exactly the '20 packets per second' cost model NCP enforces, which is why Pulse has to clamp timerSpeed to 0.5 (forceLowTimer) whenever the balance goes negative. Spread-out injection modes fare better: VerusCustomDisabler's three-C04 burst every 100 ticks adds only ~0.6 EPS on average and never fills a 500ms bucket past 15 packets, and DynamicPVPDisabler's cancel-every-third-tick plus one-C04-per-20-ticks keeps the average near the vanilla 20 EPS, so both slide under this check; the counting gap they exploit is that only flying/position packets feed morePacketsFreq, so the C08 placements and C07/C10 dig/drop spam from CubeCraftDisabler and VulcanDisabler are invisible to it.

Tolerance is deliberate: the 500ms buckets absorb lag spikes, the lag divisor (TickTask.getLag) scales the burst threshold under server lag, and the 1.17+ duplicate-position quirk is explicitly ignored (MovingListener line 808 comment). The bypass surface is pacing: keeping any single 500ms window under 15 move packets and the sustained EPS under 22 defeats it, which is why the remaining Rise modes spread their injections across ticks instead of dumping them; the price of dodging it is that a blink/timer cheat cannot flush its buffered packets in one burst, precisely the behavior RiseBalance's Pulse mode depends on.

anticheat KeepAliveFrequency (net.keepalivefrequency)

KeepAliveFrequency.java101 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.net;
16
17
import org.bukkit.entity.Player;
18
19
import fr.neatmonster.nocheatplus.checks.Check;
20
import fr.neatmonster.nocheatplus.checks.CheckType;
21
import fr.neatmonster.nocheatplus.players.IPlayerData;
22
import fr.neatmonster.nocheatplus.utilities.CheckUtils;
23
24
public class KeepAliveFrequency extends Check {
25
26
    public KeepAliveFrequency() {
27
        super(CheckType.NET_KEEPALIVEFREQUENCY);
28
    }
29
    
30
    /**
31
     * Checks hasBypass on violation only.
32
     * @param player
33
     * @param time
34
     * @param data
35
     * @param cc
36
     * @return If to cancel.
37
     */
38
    public boolean check(final Player player, final long time, final NetData data, final NetConfig cc, final IPlayerData pData) {
39
        final long now = System.currentTimeMillis();
40
        final long joinTime = pData.getLastJoinTime();
41
        if (joinTime > 0L && now < joinTime + cc.keepAliveFrequencyStartupDelay) {
42
            return false;
43
        }
44
        if (data.keepAliveExpectedResponse && !data.keepAliveDuplicateId) {
45
            return false;
46
        }
47
        data.keepAliveFreq.add(time, 1f);
48
        final float first = data.keepAliveFreq.bucketScore(0);
49
        
50
        if (first > 1f) {
51
            // Trigger a violation.
52
            final float fullScore = data.keepAliveFreq.score(1f);
53
            if (isModeledBoundaryBurst(data, fullScore, first)) {
54
                return false;
55
            }
56
            final double vl = Math.max(first - getFirstBucketViolationLimit(data), fullScore - data.keepAliveFreq.numberOfBuckets());
57
            final boolean cancel = executeActions(player, vl, 1.0, cc.keepAliveFrequencyActions).willCancel();
58
            return cancel;
59
        }
60
        return false;
61
    }
62
63
    private boolean isModeledBoundaryBurst(final NetData data, final float fullScore, final float first) {
64
        // KeepAlive model: if outgoing tracking is unavailable, only treat small monotonic id bursts as timing leftovers.
65
        if (data.keepAliveDuplicateId || fullScore > data.keepAliveFreq.numberOfBuckets() + 2f) {
66
            return false;
67
        }
68
        // Folia/netty can timestamp two adjacent valid replies in the same millisecond; do not cancel a single pair.
69
        return first <= 2f || isUntrackedMonotonicBurst(data, fullScore, first);
70
    }
71
72
    private boolean isUntrackedMonotonicBurst(final NetData data, final float fullScore, final float first) {
73
        if (data.keepAliveOutgoingSeen || fullScore > data.keepAliveFreq.numberOfBuckets()) {
74
            return false;
75
        }
76
        if (!data.keepAlivePacketIdAvailable || !data.keepAlivePreviousPacketIdAvailable) {
77
            return false;
78
        }
79
        if (data.keepAlivePacketId <= data.keepAlivePreviousPacketId) {
80
            return false;
81
        }
82
        return first <= getFallbackFirstBucketLimit(data);
83
    }
84
85
    private float getFirstBucketViolationLimit(final NetData data) {
86
        if (data.keepAliveDuplicateId) {
87
            return 1f;
88
        }
89
        if (!data.keepAliveOutgoingSeen
90
                && data.keepAlivePacketIdAvailable
91
                && data.keepAlivePreviousPacketIdAvailable
92
                && data.keepAlivePacketId > data.keepAlivePreviousPacketId) {
93
            return getFallbackFirstBucketLimit(data);
94
        }
95
        return 2f;
96
    }
97
98
    private float getFallbackFirstBucketLimit(final NetData data) {
99
        return Math.max(3f, Math.min(6f, data.keepAliveFreq.numberOfBuckets() / 4f));
100
    }
101
}

How it counteracts this module

KeepAliveFrequency is NCP's net-layer keepalive check, fed through the ProtocolLib KeepAliveAdapter. NetData maintains the server's own keepalive ledger: every outgoing S00 is recorded as a KeepAliveRequest (recordOutgoingKeepAlivePacket, pruned by pruneKeepAliveRequests), and every incoming C00 is matched against that ledger before the frequency logic runs. The check only evaluates when no reply is expected or the id is a duplicate: keepAliveExpectedResponse && !keepAliveDuplicateId short-circuits to no violation (KeepAliveFrequency.java line 46), so any reply that matches an outstanding server request (whenever it arrives) is legal. Violations require the most recent bucket to score above one reply (first > 1f), i.e. replies arriving faster than the server asks, with exemptions for small monotonic untracked bursts and a startup delay after join.

This makes it a counter to the keepalive-spoof end of the family rather than to cancellation. A mode that echoes C00s without a matching outstanding request, or sends duplicate ids faster than one per bucket, trips first > 1f and accumulates VL toward the cancel vl>10 actions. The Rise modes that cancel keepalives outright (KeepAliveDisabler, CubeCraftDisabler, DynamicPVPDisabler, LunarDisabler) starve the check's input: with no replies the check never runs, and the effective counter there is the vanilla server keepalive timeout, the disconnect risk the KeepAliveDisabler analysis already flags. WatchdogDisabler's ping-spoof path (PingSpoofComponent delays inbound S00 by a random 0-400ms and replays it) stays inside the model by design: the delayed reply still matches an outstanding request and is non-duplicate, so it hits the expected-response early return.

The check's design goal is lag tolerance: the expected-response passthrough, the startup delay and the boundary-burst exemptions exist so late replies and Folia/netty same-millisecond pairs never false-positive. Its bypass surface is therefore real but narrow: it constrains reply floods (fake-low-ping keepalive spam) while delay-based spoofing and full cancellation both evade the frequency logic itself; the hard floor against cancellation is the server's keepalive timeout, not NCP.

anticheat CreativeFly (moving.creativefly)

CreativeFly.java539 lines · Java
1
/*
2
 * This program is free software: you can redistribute it and/or modify
3
 *   it under the terms of the GNU General Public License as published by
4
 *   the Free Software Foundation, either version 3 of the License, or
5
 *   (at your option) any later version.
6
 *
7
 *   This program is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10
 *   GNU General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU General Public License
13
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
14
 */
15
package fr.neatmonster.nocheatplus.checks.moving.player;
16
17
import java.util.LinkedList;
18
import java.util.List;
19
import java.util.Locale;
20
21
import org.bukkit.GameMode;
22
import org.bukkit.Location;
23
import org.bukkit.World;
24
import org.bukkit.entity.Player;
25
26
import fr.neatmonster.nocheatplus.NCPAPIProvider;
27
import fr.neatmonster.nocheatplus.actions.ParameterName;
28
import fr.neatmonster.nocheatplus.checks.Check;
29
import fr.neatmonster.nocheatplus.checks.CheckType;
30
import fr.neatmonster.nocheatplus.checks.ViolationData;
31
import fr.neatmonster.nocheatplus.checks.moving.MovingConfig;
32
import fr.neatmonster.nocheatplus.checks.moving.MovingData;
33
import fr.neatmonster.nocheatplus.checks.moving.envelope.workaround.LostGround;
34
import fr.neatmonster.nocheatplus.checks.moving.model.LiftOffEnvelope;
35
import fr.neatmonster.nocheatplus.checks.moving.model.ModelFlying;
36
import fr.neatmonster.nocheatplus.checks.moving.model.PlayerMoveData;
37
import fr.neatmonster.nocheatplus.compat.BridgeMisc;
38
import fr.neatmonster.nocheatplus.compat.blocks.changetracker.BlockChangeTracker;
39
import fr.neatmonster.nocheatplus.components.modifier.IAttributeAccess;
40
import fr.neatmonster.nocheatplus.components.registry.event.IGenericInstanceHandle;
41
import fr.neatmonster.nocheatplus.players.IPlayerData;
42
import fr.neatmonster.nocheatplus.utilities.StringUtil;
43
import fr.neatmonster.nocheatplus.utilities.location.PlayerLocation;
44
import fr.neatmonster.nocheatplus.utilities.math.TrigUtil;
45
import fr.neatmonster.nocheatplus.utilities.moving.Magic;
46
import fr.neatmonster.nocheatplus.utilities.moving.MovingUtil;
47
48
49
/**
50
 *  A check designed for players that are either in Creative or Spectator mode
51
 */
52
public class CreativeFly extends Check {
53
54
    private final List<String> tags = new LinkedList<String>();
55
    private final BlockChangeTracker blockChangeTracker;
56
    private final IGenericInstanceHandle<IAttributeAccess> attributeAccess = NCPAPIProvider.getNoCheatPlusAPI().getGenericInstanceHandle(IAttributeAccess.class);
57
58
59
   /**
60
    * Instantiates a new creative fly check.
61
    */
62
    public CreativeFly() {
63
        super(CheckType.MOVING_CREATIVEFLY);
64
        blockChangeTracker = NCPAPIProvider.getNoCheatPlusAPI().getBlockChangeTracker();
65
    }
66
67
68
   /**
69
    * Checks a player
70
    *
71
    * @param player
72
    * @param from
73
    * @param to
74
    * @param data
75
    * @param cc
76
    * @param time Milliseconds.
77
    * @return
78
    */
79
    public Location check(final Player player, final PlayerLocation from, final PlayerLocation to, 
80
                          final MovingData data, final MovingConfig cc, final IPlayerData pData,
81
                          final long time, final int tick,
82
                          final boolean useBlockChangeTracker) {
83
84
        // Reset tags, just in case.
85
        tags.clear();
86
        final boolean debug = pData.isDebugActive(type);
87
        final GameMode gameMode = player.getGameMode();
88
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
89
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
90
        final ModelFlying model = thisMove.modelFlying;
91
        final double yDistance = thisMove.yDistance;
92
        final double hDistance = thisMove.hDistance;
93
        final boolean flying = gameMode == BridgeMisc.GAME_MODE_SPECTATOR || player.isFlying();
94
        final boolean sprinting = player.isSprinting();
95
96
        // Lost ground, if set so.
97
        if (model.getGround()) {
98
            MovingUtil.prepareFullCheck(from, to, thisMove, Math.max(cc.yOnGround, cc.noFallyOnGround));
99
            LostGround.runLostGroundChecks(player, from, to, hDistance, yDistance, lastMove, data, cc, useBlockChangeTracker ? blockChangeTracker : null, tags);
100
        }
101
102
103
        //////////////////////////
104
        // Horizontal move.
105
        //////////////////////////
106
        double[] resH = hDist(player, from, to, hDistance, yDistance, sprinting, flying, thisMove, lastMove, time, model, data, cc);
107
        double limitH = resH[0];
108
        double resultH = resH[1];
109
110
        // Check velocity.
111
        //TODO: Add velocity
112
//        if (resultH > 0) {
113
//            double hFreedom = data.getHorizontalFreedom();
114
//            if (hFreedom < resultH) {
115
//                // Use queued velocity if possible.
116
//                hFreedom += data.useHorizontalVelocity(resultH - hFreedom);
117
//            }
118
//            if (hFreedom > 0.0) {
119
//                resultH = Math.max(0.0, resultH - hFreedom);
120
//                if (resultH <= 0.0) {
121
//                    limitH = hDistance;
122
//                }
123
//                tags.add("hvel");
124
//            }
125
//        }
126
//        else {
127
//            data.clearActiveHorVel(); // TODO: test/check !
128
//        }
129
130
        resultH *= 100.0; // Normalize to % of a block.
131
        if (resultH > 0.0) {
132
            tags.add("hdist");
133
        }
134
135
136
137
138
139
140
        //////////////////////////
141
        // Vertical move.
142
        //////////////////////////
143
144
        double limitV = 0.0; // Limit. For debug only, violation handle on resultV
145
        double resultV = 0.0; // Violation (normalized to 100 * 1 block, applies if > 0.0).
146
147
        // Distinguish checking method by y-direction of the move:
148
        // Ascend.
149
        if (yDistance > 0.0) {
150
            double[] res = vDistAscend(from, to, yDistance, flying, thisMove, lastMove, model, data, cc, debug);
151
            resultV = Math.max(resultV, res[1]);
152
            limitV = res[0];
153
        }
154
        // Descend.
155
        else if (yDistance < 0.0) {
156
            double[] res = vDistDescend(from, to, yDistance, flying, thisMove, lastMove, model, data, cc);
157
            resultV = Math.max(resultV, res[1]);
158
            limitV = res[0];
159
        }
160
        // Keep altitude.
161
        else {
162
            double[] res = vDistZero();
163
            resultV = Math.max(resultV, res[1]);
164
            limitV = res[0];
165
        }
166
167
        // Velocity.
168
        if (resultV > 0.0 && (!thisMove.verVelUsed.isEmpty() || !data.getOrUseVerticalVelocity(yDistance).isEmpty())) {
169
            resultV = 0.0;
170
            tags.add("vvel");
171
        }
172
173
        // Add tag for maximum height check (silent set back).
174
        // TODO: Allow use velocity there (would need a flag to signal the actual check below)?
175
        final double maximumHeight = model.getMaxHeight() + player.getWorld().getMaxHeight();
176
        if (to.getY() > maximumHeight) {
177
            tags.add("maxheight");
178
        }
179
180
        resultV *= 100.0; // Normalize to % of a block.
181
        if (resultV > 0.0) {
182
            tags.add("vdist");
183
        }
184
185
        final double result = Math.max(0.0, resultH) + Math.max(0.0, resultV);
186
187
188
189
        //////////////////////////
190
        // Output debug
191
        //////////////////////////
192
        if (debug) {
193
            outpuDebugMove(player, hDistance, limitH, yDistance, limitV, model, tags, data);
194
        }
195
196
197
198
        ///////////////////////
199
        // Violation handling
200
        ///////////////////////
201
202
        Location setBack = null; // Might get altered below.
203
204
        if (result > 0.0) {
205
            data.creativeFlyVL += result;
206
            // Execute whatever actions are associated with this check and the violation level and find out if we
207
            // should cancel the event.
208
            final ViolationData vd = new ViolationData(this, player, data.creativeFlyVL, result, cc.creativeFlyActions);
209
            if (vd.needsParameters()) {
210
                vd.setParameter(ParameterName.LOCATION_FROM, String.format(Locale.US, "%.2f, %.2f, %.2f", from.getX(), from.getY(), from.getZ()));
211
                vd.setParameter(ParameterName.LOCATION_TO, String.format(Locale.US, "%.2f, %.2f, %.2f", to.getX(), to.getY(), to.getZ()));
212
                vd.setParameter(ParameterName.DISTANCE, String.format(Locale.US, "%.2f", TrigUtil.distance(from,  to)));
213
                if (model != null) {
214
                    vd.setParameter(ParameterName.MODEL, model.getId().toString());
215
                }
216
                if (!tags.isEmpty()) {
217
                    vd.setParameter(ParameterName.TAGS, StringUtil.join(tags, "+"));
218
                }
219
            }
220
            if (executeActions(vd).willCancel()) {
221
                // Compose a new location based on coordinates of "newTo" and viewing direction of "event.getTo()"
222
                // to allow the player to look somewhere else despite getting pulled back by NoCheatPlus.
223
                setBack = data.getSetBack(to); // (OK)
224
            }
225
        }
226
        else {
227
            // Maximum height check (silent set back).
228
            if (to.getY() > maximumHeight) {
229
                setBack = data.getSetBack(to); // (OK)
230
                if (debug) {
231
                    debug(player, "Maximum height exceeded, silent set-back.");
232
                }
233
            }
234
            if (setBack == null) {
235
                // Slowly reduce the violation level with each event.
236
                data.creativeFlyVL *= 0.97;
237
            }
238
        }
239
240
        // Return setBack, if set.
241
        if (setBack != null) {
242
            // Check for max height of the set back.
243
            if (setBack.getY() > maximumHeight) {
244
                // Correct the y position.
245
                setBack.setY(getCorrectedHeight(maximumHeight, setBack.getWorld()));
246
                if (debug) {
247
                    debug(player, "Maximum height exceeded by set back, correct to: " + setBack.getY());
248
                }
249
            }
250
            data.sfJumpPhase = 0;
251
            return setBack;
252
        }
253
        else {
254
            // Adjust the set back and other last distances.
255
            data.setSetBack(to);
256
            // Adjust jump phase.
257
            if (!thisMove.from.onGroundOrResetCond && !thisMove.to.onGroundOrResetCond) {
258
                data.sfJumpPhase ++;
259
            }
260
            else if (thisMove.touchedGround && !thisMove.to.onGroundOrResetCond) {
261
                data.sfJumpPhase = 1;
262
            }
263
            else {
264
                data.sfJumpPhase = 0;
265
            }
266
            return null;
267
        }
268
    }
269
270
271
    /**
272
     * Horizontal distance checking.
273
     * @param player
274
     * @param from
275
     * @param to
276
     * @param hDistance
277
     * @param yDistance
278
     * @param flying
279
     * @param lastMove
280
     * @param time
281
     * @param model
282
     * @param data
283
     * @param cc
284
     * @return limitH, resultH (not normalized).
285
     */
286
    private double[] hDist(final Player player, final PlayerLocation from, final PlayerLocation to, final double hDistance, 
287
                           final double yDistance, final boolean sprinting, final boolean flying, final PlayerMoveData thisMove, 
288
                           final PlayerMoveData lastMove, final long time, final ModelFlying model, final MovingData data, final MovingConfig cc) {
289
290
        // Modifiers.
291
        double fSpeed;
292
        // TODO: Make this configurable ! [Speed effect should not affect flying if not on ground.]
293
        if (model.getApplyModifiers()) {
294
            final double speedModifier = mcAccess.getHandle().getFasterMovementAmplifier(player);
295
            if (Double.isInfinite(speedModifier)) fSpeed = 1.0;
296
            else fSpeed = 1.0 + 0.2 * (speedModifier + 1.0);
297
    
298
            if (flying) {
299
                // TODO: Consider mechanics for flying backwards.
300
                fSpeed *= data.flySpeed / Magic.DEFAULT_FLYSPEED;
301
                if (sprinting) {
302
                    // TODO: Prevent for pre-1.8?
303
                    fSpeed *= model.getHorizontalModSprint();
304
                    tags.add("sprint");
305
                }
306
                tags.add("flying");
307
            }
308
            //  else {
309
            //     // (Ignore sprinting here).
310
            //      final double attrMod = attributeAccess.getHandle().getSpeedAttributeMultiplier(player);
311
            //      if (attrMod != Double.MAX_VALUE) fSpeed *= attrMod;
312
            //      fSpeed *= data.walkSpeed / Magic.CB_DEFAULT_WALKSPEED;
313
            //  }
314
        }
315
        else fSpeed = 1.0;
316
        
317
        // The horizontal limit is now set. 
318
        double limitH = model.getHorizontalModSpeed() / 100.0 * ModelFlying.HORIZONTAL_SPEED * fSpeed;
319
        
320
321
        // Ordinary friction
322
        // TODO: Use last friction (as well)?
323
        // TODO: Test/adjust more.
324
        // it doesn't really make much sense checking for friction as well...
325
        if (lastMove.toIsValid) {
326
            double frictionDist = lastMove.hDistance * Magic.FRICTION_MEDIUM_AIR;
327
            limitH = Math.max(frictionDist, limitH);
328
            tags.add("hfrict");
329
        }
330
331
        // Finally, determine how far the player went beyond the set limits.
332
        double resultH = Math.max(0.0, hDistance - limitH);
333
334
        if (model.getApplyModifiers()) {
335
            data.jumpDelay--;
336
            //TODO: Remove this useless shit.
337
            if (!flying && resultH > 0 && resultH < 0.3) {
338
                // 0: yDistance envelope
339
                if (yDistance >= 0.0 &&
340
                    (
341
                        // 1: Normal jumping.
342
                        yDistance > 0.0 
343
                        && yDistance > LiftOffEnvelope.NORMAL.getJumpGain(data.jumpAmplifier) - Magic.GRAVITY_SPAN
344
                        // 1: Too short with head obstructed.
345
                        || thisMove.headObstructed || lastMove.toIsValid && lastMove.headObstructed && lastMove.yDistance <= 0.0
346
                        // 1: Hop without y distance increase at moderate h-speed.
347
                        // TODO: 2nd below: demand next move to jump. Relate to stored past moves. 
348
                        // TODO: Ensure the gain can only be used once per so and so.
349
                        //|| (cc.sfGroundHop || yDistance == 0.0 && !lastMove.touchedGroundWorkaround && !lastMove.from.onGround)
350
                        //&& limitH > 0.0 && hDistance / limitH < 1.5
351
                        //&& (hDistance / lastMove.hDistance < 1.35 
352
                        //        || hDistance / limitH < 1.35)
353
                    )
354
                    // 0: Ground + jump phase conditions.
355
                    && (data.sfJumpPhase <= 1 && (thisMove.touchedGroundWorkaround || 
356
                        lastMove.touchedGround && !lastMove.bunnyHop))
357
                    // 0: Don't allow bunny to run out of liquid.
358
                    && (!from.isResetCond() && !to.isResetCond()) // TODO: !to.isResetCond() should be reviewed.
359
                    ) {
360
361
                    tags.add("bunnyhop");
362
                    data.jumpDelay = 9;
363
                    thisMove.bunnyHop = true;
364
                    resultH = 0.0;
365
                }
366
                else if (data.jumpDelay <= 0) {
367
                    resultH = 0.0;
368
                    tags.add("bunnyhop");
369
                }
370
            }
371
        }
372
        return new double[] {limitH, resultH};
373
    }
374
375
376
   /**
377
     * Ascending (yDistance > 0.0) check.
378
     * @param from
379
     * @param to
380
     * @param yDistance
381
     * @param flying
382
     * @param lastMove
383
     * @param model
384
     * @param data
385
     * @param cc
386
     * @return limitV, resultV (not normalized).
387
     */
388
    private double[] vDistAscend(final PlayerLocation from, final PlayerLocation to, final double yDistance, 
389
                                 final boolean flying, final PlayerMoveData thisMove, final PlayerMoveData lastMove, 
390
                                 final ModelFlying model, final MovingData data, final MovingConfig cc, final boolean debug) {
391
392
        // Set the vertical limit.
393
        double limitV = model.getVerticalAscendModSpeed() / 100.0 * ModelFlying.VERTICAL_ASCEND_SPEED; 
394
        double resultV = 0.0;
395
        
396
        // Let fly speed apply with moving upwards.
397
        if (model.getApplyModifiers() && flying && yDistance > 0.0) {
398
            limitV *= data.flySpeed / Magic.DEFAULT_FLYSPEED;
399
        }
400
        
401
        // Friction with gravity.
402
        if (model.getGravity()) {
403
            if (yDistance > limitV && lastMove.toIsValid) { 
404
                // (Disregard gravity.)
405
                // TODO: Use last friction (as well)?
406
                double frictionDist = lastMove.yDistance * Magic.FRICTION_MEDIUM_AIR;
407
                if (!flying) {
408
                    frictionDist -= 0.019;
409
                }
410
                if (frictionDist > limitV) {
411
                    limitV = frictionDist;
412
                    tags.add("vfrict_g");
413
                }
414
            }
415
        }
416
417
        if (model.getGround()) {
418
            // Jump lift off gain.
419
            // NOTE: This assumes SurvivalFly busies about moves with from.onGroundOrResetCond.
420
            if (yDistance > limitV && !thisMove.to.onGroundOrResetCond && !thisMove.from.onGroundOrResetCond && (
421
                // Last move touched ground.
422
                lastMove.toIsValid && lastMove.touchedGround && 
423
                (lastMove.yDistance <= 0.0 || lastMove.to.extraPropertiesValid && lastMove.to.onGround)
424
                // This move touched ground by a workaround.
425
                || thisMove.touchedGroundWorkaround
426
                )) {
427
                // Allow normal jumping.
428
                final double maxGain = LiftOffEnvelope.NORMAL.getJumpGain(data.jumpAmplifier);
429
                if (maxGain > limitV) {
430
                    limitV = maxGain;
431
                    tags.add("jump_gain");
432
                }
433
            }
434
        }
435
436
        // Ordinary step up.
437
        // TODO: Might be within a 'if (model.ground)' block?
438
        // TODO: sfStepHeight should be a common modeling parameter?
439
        if (yDistance > limitV && yDistance <= cc.sfStepHeight 
440
            && (lastMove.toIsValid && lastMove.yDistance < 0.0 || from.isOnGroundOrResetCond() || thisMove.touchedGroundWorkaround)
441
            && to.isOnGround()) {
442
            // (Jump effect not checked yet.)
443
            limitV = cc.sfStepHeight;
444
            tags.add("step_up");
445
        }
446
447
        // Determine violation amount.
448
        resultV = Math.max(0.0, yDistance - limitV);
449
        // Post-violation recovery.
450
        return new double[] {limitV, resultV};
451
    }
452
453
454
    /**
455
     * Descending phase vDist check
456
     * @param from
457
     * @param to
458
     * @param yDistance
459
     * @param flying
460
     * @param thisMove
461
     * @param lastMove
462
     * @param model
463
     * @param data
464
     * @param cc
465
     * @return limitV, resultV
466
     */
467
    private double[] vDistDescend(final PlayerLocation from, final PlayerLocation to, final double yDistance, final boolean flying, 
468
                                  final PlayerMoveData thisMove, final PlayerMoveData lastMove, final ModelFlying model, 
469
                                  final MovingData data, final MovingConfig cc) {
470
        double limitV = 0.0;
471
        double resultV = 0.0;
472
        // Note that 'extreme moves' are covered by the extreme move check.
473
        // TODO: if gravity: friction + gravity.
474
        // TODO: ordinary flying (flying: enforce maximum speed at least)
475
        return new double[] {limitV, resultV};
476
    }
477
478
479
    /**
480
     * Keep the altitude
481
     *
482
     * @return limitV, resultV
483
     */
484
    private double[] vDistZero() {
485
        double limitV = 0.0;
486
        double resultV = 0.0;
487
        return new double[] {limitV, resultV};
488
    }
489
490
491
   /**
492
    * 
493
    * @param maximumHeight
494
    * @param world
495
    * @return 
496
    */
497
    private double getCorrectedHeight(final double maximumHeight, final World world) {
498
        return Math.max(maximumHeight - 10.0, world.getMaxHeight());
499
    }
500
501
502
   /**
503
    * Output debug
504
    * @param player
505
    * @param hDistance
506
    * @param limitH
507
    * @param yDistance
508
    * @param limitV
509
    * @param model
510
    * @param tags
511
    * @param data
512
    * @return
513
    */
514
    private void outpuDebugMove(final Player player, final double hDistance, final double limitH, 
515
                                final double yDistance, final double limitV, final ModelFlying model, final List<String> tags, 
516
                                final MovingData data) {
517
518
        final PlayerMoveData lastMove = data.playerMoves.getFirstPastMove();
519
        StringBuilder builder = new StringBuilder(350);
520
        final String dHDist = lastMove.toIsValid ? " (" + StringUtil.formatDiff(hDistance, lastMove.hDistance) + ")" : "";
521
        final String dYDist = lastMove.toIsValid ? " (" + StringUtil.formatDiff(yDistance, lastMove.yDistance)+ ")" : "";
522
        builder.append("hDist: " + hDistance + dHDist + " / " + limitH + " , vDist: " + yDistance + dYDist + " / " + limitV);
523
        final PlayerMoveData thisMove = data.playerMoves.getCurrentMove();
524
        if (lastMove.toIsValid) {
525
            builder.append(" , fdsq: " + StringUtil.fdec3.format(thisMove.distanceSquared / lastMove.distanceSquared));
526
        }
527
        if (thisMove.verVelUsed != null) {
528
            builder.append(" , vVelUsed: " + thisMove.verVelUsed);
529
        }
530
        builder.append(" , model: " + model.getId());
531
        if (!tags.isEmpty()) {
532
            builder.append(" , tags: ");
533
            builder.append(StringUtil.join(tags, "+"));
534
        }
535
        builder.append(" , jumpphase: " + data.sfJumpPhase);
536
        thisMove.addExtraProperties(builder, " , ");
537
        debug(player, builder.toString());
538
    }
539
}

How it counteracts this module

CreativeFly is the flight model NCP applies when the server believes the player is allowed to fly. MovingListener selects it only when shouldCheckSurvivalFly is false (the survival envelope does not apply) and the player is in the flying state, then prepares a CreativeFly model (prepareCreativeFlyCheck) with per-model configuration: horizontal-speed, vertical-speed, max-height and mod-sprint under the creative-model paths, with the LiftOffEnvelope handling takeoff transitions. Each move is measured against the model's allowed distances rather than a single speed threshold, and violations carry the standard moving-actions chain.

Its role against AbilitiesDisabler is to make the C13 spoof pointless at the server boundary. The MCP sources verify processPlayerAbilities as capabilities.isFlying = packetIn.isFlying() && capabilities.allowFlying (NetHandlerPlayServer line 1209): in survival the allowFlying gate is false, so the spoofed isFlying never flips the server's state, CreativeFly never engages, and the slime-bounce motion is measured by SurvivalFly against the jump envelope instead. On servers that do grant allowFlying (creative, spectator, plugin flight), CreativeFly engages and the spoofed flag is redundant with the granted state. The mode contributes nothing the model does not already permit, while the model's horizontal/vertical speed and max-height limits are enforced on the actual motion. The C13's spoofed flySpeed/walkSpeed floats are ignored by the verified handler, so the packet's only server-visible field is the one gated by allowFlying.

The creative models are deliberately generous (per-model speed/height configuration, sprint modifier), so the check only bites motion beyond the granted flight envelope. Its tolerance comes from the model config and the same physics workaround set as SurvivalFly; a mode that keeps flight motion inside the model's limits (which is AbilitiesDisabler's intent on slime) sails under CreativeFly, but it cannot widen those limits by spoofing flags, which is the entire point of the C13 packet it sends.

anticheat Flight (Arc v2)

Flight.java356 lines · Java
1
package me.vrekt.arc.check.moving;
2
3
import me.vrekt.arc.Arc;
4
import me.vrekt.arc.check.Check;
5
import me.vrekt.arc.check.CheckResult;
6
import me.vrekt.arc.check.CheckType;
7
import me.vrekt.arc.data.moving.MovingData;
8
import me.vrekt.arc.utilties.LocationHelper;
9
import org.bukkit.ChatColor;
10
import org.bukkit.Location;
11
import org.bukkit.Material;
12
import org.bukkit.block.Block;
13
import org.bukkit.block.BlockFace;
14
import org.bukkit.entity.Player;
15
import org.bukkit.material.Step;
16
import org.bukkit.potion.PotionEffectType;
17
18
import java.util.List;
19
20
public class Flight extends Check {
21
22
    private double maxAscendSpeed, maxDescendSpeed, maxHeight, maxHover, maxAscendDistance;
23
    private int maxAscendTime;
24
25
    public Flight() {
26
        super(CheckType.FLIGHT);
27
28
        maxAscendSpeed = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "ascend-ladder");
29
        maxDescendSpeed = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "descend-ladder");
30
        maxHeight = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "max-jump");
31
        maxHover = Arc.getCheckManager().getValueInt(CheckType.FLIGHT, "max-hover-time");
32
        maxAscendDistance = Arc.getCheckManager().getValueDouble(CheckType.FLIGHT, "ascend-distance");
33
34
        maxAscendTime = Arc.getCheckManager().getValueInt(CheckType.FLIGHT, "ascend-time");
35
    }
36
37
    private boolean hoverCheck(Player player, MovingData data) {
38
        result.reset();
39
40
        // Check if we are actually hovering.
41
        double vertical = data.getVerticalSpeed();
42
        boolean actuallyHovering = data.getLastVerticalSpeed() == 0.0 && vertical == 0.0 && player.getVehicle() == null;
43
44
        if (actuallyHovering) {
45
            // check how long we've been hovering for.
46
            if (data.getAirTicks() >= maxHover) {
47
                // too long, flag.
48
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Hover)");
49
                result.set(checkViolation(player, "hovering off the ground, hover"));
50
            }
51
        }
52
53
        return result.failed();
54
    }
55
56
    public CheckResult runBlockChecks(Player player, MovingData data) {
57
        result.reset();
58
59
        if (!data.wasOnGround()) {
60
            result.set(hoverCheck(player, data));
61
        }
62
63
        double vertical = data.getVerticalSpeed();
64
65
        // ladder and vertical velocity stuff.
66
        boolean isAscending = data.isAscending();
67
        boolean isDescending = data.isDescending();
68
        boolean isClimbing = data.isClimbing();
69
70
        int airTicks = data.getAirTicks();
71
72
        // make sure we're actually in the air.
73
        boolean actuallyInAir = airTicks >= 20 && data.getLadderTime() >= 8;
74
75
        // fastladder check, make sure were ascending, climbing and in-air.
76
        if (isAscending && isClimbing && actuallyInAir) {
77
            // check if we are climbing too fast.
78
            if (vertical > maxAscendSpeed) {
79
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
80
                result.set(checkViolation(player, "ascending too fast, ladder_ascend"), data.getPreviousLocation());
81
            }
82
        }
83
84
        // patch for instant ladder
85
        double difference = vertical - maxAscendSpeed;
86
        if (isAscending && isClimbing && difference > 1.0) {
87
            getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
88
            result.set(checkViolation(player, "ascending too fast, ladder_instant"), data.getPreviousLocation());
89
        }
90
91
        // descending check.
92
        if (isDescending && isClimbing && actuallyInAir) {
93
            // too fast, flag.
94
            if (vertical > maxDescendSpeed) {
95
                getCheck().setCheckName("Flight " + ChatColor.GRAY + "(FastLadder)");
96
                result.set(checkViolation(player, "descending too fast, ladder_descend"), data.getPreviousLocation());
97
            }
98
        }
99
100
        getCheck().setCheckName("Flight");
101
        return result;
102
    }
103
104
    public CheckResult check(Player player, MovingData data) {
105
        result.reset();
106
107
        Location from = data.getPreviousLocation();
108
        Location to = data.getCurrentLocation();
109
        Location ground = data.getGroundLocation();
110
        if (ground == null) {
111
            ground = from;
112
        }
113
114
115
        double lastVertical = data.getLastVerticalSpeed();
116
        double vertical = data.getVerticalSpeed();
117
118
        boolean onGround = data.isOnGround();
119
        boolean isAscending = data.isAscending();
120
        boolean isDescending = data.isDescending();
121
        boolean isClimbing = data.isClimbing();
122
123
        boolean isOnSlab = to.getBlock().getRelative(BlockFace.DOWN).getType().getData().equals(Step.class);
124
        boolean isOnStep = (LocationHelper.isOnSlab(to) || isOnSlab) || LocationHelper.isOnStair(to);
125
        boolean isOnSlimeblock = LocationHelper.isOnSlimeblock(to);
126
        boolean isInLiquid = LocationHelper.isInLiquid(to);
127
        boolean isOnTrapdoor = to.getBlock().getRelative(BlockFace.SELF).getType() == Material.TRAP_DOOR;
128
        boolean isUnderBlock = LocationHelper.isUnderBlock(to);
129
        boolean velocityBoost = isOnTrapdoor && isUnderBlock;
130
131
        boolean hasVelocity = data.getVelocityData().hasVelocity();
132
        double velocity = data.getVelocityData().getCurrentVelocity();
133
        double lastVelocity = data.getVelocityData().getLastVelocity();
134
135
        boolean wasVerticalMove = (isAscending || isDescending);
136
        boolean validVerticalMove = player.getVehicle() == null && !hasVelocity && !isOnStep && !isClimbing && !isInLiquid;
137
138
        int ascendingMoves = data.getAscendingMoves();
139
        int descendingMoves = data.getDescendingMoves();
140
        int ladderTime = data.getLadderTime();
141
142
        // if we are on ground lets reset some data.
143
        if (onGround) {
144
            ascendingMoves = 0;
145
            descendingMoves = 0;
146
147
            data.setAscendingMoves(ascendingMoves);
148
            data.setDescendingMoves(descendingMoves);
149
            data.getVelocityData().clear();
150
151
            if (hasVelocity) {
152
                hasVelocity = false;
153
                data.getVelocityData().setHasVelocity(false);
154
                validVerticalMove = wasVerticalMove && player.getVehicle() == null && !isOnStep;
155
            }
156
157
            if (isOnSlimeblock) {
158
                // we landed on a slimeblock, lets update our velocity if out vertical has increased.
159
                if (vertical > 0.0 && !data.wasOnGround()) {
160
                    data.getVelocityData().setHasVelocity(true);
161
                    hasVelocity = true;
162
                    validVerticalMove = false;
163
                }
164
            }
165
166
        }
167
168
        // update our ascending data and reset our descending data.
169
        if (isAscending) {
170
            descendingMoves = 0;
171
            data.setDescendingMoves(descendingMoves);
172
            if (!isClimbing) {
173
                ascendingMoves++;
174
                data.setAscendingMoves(ascendingMoves);
175
            }
176
        }
177
178
        // update our descending data and reset the ascending data, also account for slimeblock velocity.
179
        if (isDescending) {
180
            ascendingMoves = 0;
181
            data.setAscendingMoves(ascendingMoves);
182
183
            descendingMoves++;
184
            data.setDescendingMoves(descendingMoves);
185
            data.getVelocityData().clear();
186
        }
187
188
        // update our climbing data.
189
        if (isClimbing) {
190
            if (wasVerticalMove) {
191
                data.setLadderTime(14);
192
            } else {
193
                data.setLadderTime(6);
194
            }
195
        } else {
196
            ladderTime = ladderTime >= 0 ? ladderTime - 1 : 0;
197
            data.setLadderTime(ladderTime);
198
        }
199
200
        if (wasVerticalMove) {
201
            // start with the vclip check, we want this first to make sure nobody is clipping through anything.
202
            if (vertical >= 0.99 && validVerticalMove && !isOnSlimeblock) {
203
                // update our safe location.
204
                Location safeLocation = data.getSafe();
205
                if (safeLocation == null) {
206
                    data.setSafe(from);
207
                    safeLocation = from;
208
                }
209
210
                // get our locations for checking.
211
                int minY = Math.min(safeLocation.getBlockY(), to.getBlockY());
212
                int maxY = Math.max(safeLocation.getBlockY(), to.getBlockY() + 1);
213
                for (int y = minY; y <= maxY; y++) {
214
                    // loop through all the possible y coordinates and get the block at that location.
215
                    Block blockTo = to.getWorld().getBlockAt(to.getBlockX(), y, to.getBlockZ());
216
                    if (blockTo.getType().isSolid()) {
217
                        // if its solid flag.
218
                        getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Vertical Clip)");
219
                        boolean failed = checkViolation(player, "clipped through a solid block, vclip_solid");
220
                        result.set(failed, safeLocation);
221
                    }
222
                }
223
224
            }
225
226
            // reset our safe location.
227
            if (!result.failed()) {
228
                data.setSafe(to);
229
            }
230
231
232
            if (!onGround) {
233
                if (hasVelocity && isAscending && ladderTime == 0) {
234
                    // we were on a slimeblock, watch our velocity.
235
                    data.getVelocityData().addVelocity(velocity);
236
                    if (data.getVelocityData().getSlimeblockVelocity().size() >= maxAscendTime) {
237
                        List<Double> velocityData = data.getVelocityData().getSlimeblockVelocity();
238
239
                        // get our "last" velocities.
240
                        double lastChange = Math.abs(velocity - lastVelocity);
241
                        double lastVelocityMove = lastVelocity;
242
                        int validMoves = 0;
243
244
                        // loop through all of the recent moves.
245
                        for (double move : velocityData) {
246
                            if (move < lastVelocityMove) {
247
                                // get the difference and add a valid move if we are decreasing in velocity.
248
                                double difference = Math.abs(move - lastVelocityMove);
249
                                if (difference < lastChange) {
250
                                    validMoves++;
251
                                }
252
                                lastChange = difference;
253
                            }
254
                            lastVelocityMove = move;
255
                        }
256
257
                        // no valid moves, flag.
258
                        if (validMoves <= 3) {
259
                            getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Glide)");
260
                            result.set(checkViolation(player, "ascending too high after slimeblock velocity, sb_velocity_watch"));
261
                        }
262
                        data.getVelocityData().clear();
263
                    }
264
                }
265
266
                if (isInLiquid) {
267
                    // check if the client is onGround, if so flag.
268
                    boolean ccGround = data.isPositionClientOnGround();
269
                    if (ccGround && vertical > 0.0) {
270
                        getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Jesus)");
271
                        result.set(checkViolation(player, "walking on water, ccground_liquid"));
272
                    }
273
                }
274
275
            }
276
277
            // check how we are ascending.
278
            boolean walkedOnFence = LocationHelper.walkedOnFence(to);
279
            double distanceFrom = LocationHelper.distanceVertical(ground, to);
280
            if (validVerticalMove && isAscending && !walkedOnFence && ladderTime == 0) {
281
                // valid move, check.
282
                // first get our distance we have traveled.
283
                if (distanceFrom >= maxAscendDistance) {
284
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
285
                    result.set(checkViolation(player, "ascending too high, ascending_distance"));
286
                }
287
288
                // ascending for too long.
289
                if (ascendingMoves > maxAscendTime) {
290
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
291
                    result.set(checkViolation(player, "ascending for too long, ascending_time"));
292
                }
293
294
                // ascending too fast.
295
                double max = getMaxJump(player);
296
                if (vertical > max) {
297
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Ascension)");
298
                    result.set(checkViolation(player, "Ascending too fast, ascending_vertical"));
299
                }
300
301
            }
302
303
            // check how we are descending.
304
            if (validVerticalMove && isDescending && ladderTime == 0 && !isOnSlimeblock && !velocityBoost) {
305
                double glideDelta = Math.abs(vertical - lastVertical);
306
307
                // check if we are descending at the same speed.
308
                if (glideDelta == 0.0) {
309
                    getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Glide)");
310
                    result.set(checkViolation(player, "vertical not changing, descend_difference"));
311
                }
312
313
                // check the speed of how we are descending.
314
                int airTicks = data.getAirTicks();
315
                if (distanceFrom > 1.6 && descendingMoves > 2) {
316
                    double expected;
317
                    // calculate our expected difference based on air.
318
                    if (airTicks > 100) {
319
                        expected = -0.9908 * 1e-6 * Math.pow(airTicks, 2) + 3.4538 * 1e-7 * airTicks + 0.0189;
320
                    } else {
321
                        expected = 5.4246 * 1e-6 * Math.pow(airTicks, 2) - 0.0011 * airTicks + 0.0659;
322
                    }
323
324
                    double difference = Math.abs(glideDelta - expected);
325
                    if (difference > 0.02 || difference < 0.001) {
326
                        getCheck().setCheckName("Flight " + ChatColor.GRAY + "(Glide)");
327
                        result.set(checkViolation(player, "vertical not expected, descend_expected"));
328
                    }
329
                }
330
331
            }
332
333
        }
334
335
        getCheck().setCheckName("Flight");
336
        return result;
337
    }
338
339
    /**
340
     * Return max distance we can ascend.
341
     *
342
     * @param player the player
343
     * @return the max jump height.
344
     */
345
    private double getMaxJump(Player player) {
346
347
        double max = maxHeight;
348
349
        if (player.hasPotionEffect(PotionEffectType.JUMP)) {
350
            max += 0.4;
351
        }
352
        return max;
353
354
    }
355
356
}

How it counteracts this module

Arc v2's Flight check runs on the raw movement stream. The PacketListener (HIGHEST priority on FLYING/POSITION/POSITION_LOOK) records the client's onGround bit from every C03 into MovingData.isPositionClientOnGround and feeds the per-second MorePackets accounting, then Flight evaluates each move against config-driven maxima (ascend-ladder, descend-ladder). Its branches: hover (lastVerticalSpeed == 0.0 && vertical == 0.0 with no vehicle -> 'Flight (Hover)'), fast climb/descend vs maxAscendSpeed/maxDescendSpeed, vertical clip (vertical >= 0.99), ascending/descending move counters vs maxAscendTime ('Ascension'/'Glide'), and the Jesus branch: when the server-computed state says the player is not on the ground but the packet's onGround bit is true while vertical speed is positive (Flight.java line 268-270), it flags 'Flight (Jesus)'.

The client-onGround bit is the exposure surface for the Rise movement modes. GhostlyDisabler forces onGround=true on every C03 and snaps Y to the 1/64 grid while the player is airborne: rising with the bit set hits the Jesus branch directly, and consecutive zero-vertical moves in the air hit the Hover branch. Arc reads the raw bit, so the spoof is evidence rather than camouflage. DynamicPVPDisabler's forced-onGround rewrite has the same Jesus exposure whenever it lies about the ground state while moving vertically. TeleportDisabler is stopped before Flight runs: Speed.check returns true immediately when thisMove > 8 blocks (Speed.java line 54), cancelling the horizontal jump, and the Up variant's +-1024-2048 block Y delta is vertical speed far beyond the 0.99 clip threshold. AbilitiesDisabler's slime bounce produces the repeated zero-vertical hover phases between bounces that the Hover branch counts.

The check exempts vehicles, velocity, steps/slabs/stairs and slime (the validVerticalMove gating) and runs configurable thresholds, so legitimate server-side motion sources are tolerated. The bypass surface is honest ground reporting: keep the C03 onGround bit consistent with the server-computed ground state and keep vertical deltas inside the ladder bounds, and Flight has nothing to measure, which is exactly why the ghostly-style modes that lie about onGround while airborne are the ones it catches.

← Back to Analysis Hub