{"id":"76mqCJkjqA","url":"https://pastebin.ca/76mqCJkjqA","raw_url":"https://raw.anybin.ca/76mqCJkjqA","visibility":"public","access":"public","created_at":1794812924387,"expires_at":1795417724387,"fetch_limit":null,"fetches_used":0,"reads_remaining":null,"size_bytes":14378,"syntax_hint":null,"title":null,"filename":null,"change_note":null,"cipher":null,"cipher_meta":null,"parent_id":null,"root_id":"76mqCJkjqA","version":1,"owner_id":null,"recipient_id":null,"body":"package dev.nexo.module.combat.velocity;\n\nimport dev.nexo.client.Chat;\nimport dev.nexo.module.combat.VelocityModule;\nimport java.util.ArrayList;\nimport java.util.List;\nimport net.minecraft.client.entity.EntityPlayerSP;\nimport net.minecraft.client.multiplayer.WorldClient;\nimport net.minecraft.network.Packet;\nimport net.minecraft.network.play.server.S02PacketChat;\nimport net.minecraft.network.play.server.S03PacketTimeUpdate;\nimport net.minecraft.network.play.server.S06PacketUpdateHealth;\nimport net.minecraft.network.play.server.S07PacketRespawn;\nimport net.minecraft.network.play.server.S08PacketPlayerPosLook;\nimport net.minecraft.network.play.server.S12PacketEntityVelocity;\nimport net.minecraft.network.play.server.S13PacketDestroyEntities;\nimport net.minecraft.network.play.server.S18PacketEntityTeleport;\nimport net.minecraft.network.play.server.S25PacketBlockBreakAnim;\nimport net.minecraft.network.play.server.S27PacketExplosion;\nimport net.minecraft.network.play.server.S29PacketSoundEffect;\nimport net.minecraft.network.play.server.S2BPacketChangeGameState;\nimport net.minecraft.network.play.server.S2CPacketSpawnGlobalEntity;\nimport net.minecraft.network.play.server.S2FPacketSetSlot;\n\n/**\n * 1:1 port of Boop's {@code BufferVelocity}.\n *\n * <p>Nothing happens until a knockback actually arrives. At that moment the mode starts\n * <em>blinking</em>: every packet that reaches the client from then on is held instead of processed.\n * The client briefly stops seeing the world, so the server's movement prediction for us keeps\n * running against a state it already accepted - and when the batch is replayed, the knockback lands\n * into a prediction that no longer matches, which cancels most of its effect.\n *\n * <p>There is no timer: once it starts blinking, the batch is only released when the module is\n * switched off (or the world changes). That is deliberate - the whole point is that the server's\n * prediction runs against a stale state for as long as the hold lasts.\n *\n * <p>An exact allow-list runs first and is never held, even mid-blinking. Those packets either\n * carry state the client cannot reconstruct out of order (health, time, chat, inventory, position\n * corrections, teleports) or would look wrong if delayed (thunder, game-state change).\n */\npublic class BufferVelocity extends VelocityMode {\n    protected final List<Packet<?>> heldPackets = new ArrayList<Packet<?>>();\n    protected WorldClient packetWorld;\n    protected boolean blinking;\n\n    /** Wall-clock time the current hold began, for the timeout. */\n    protected long holdStartMs;\n    /** Highest countdown number already announced, so each number prints once. */\n    private int announcedCountdown;\n\n    /**\n     * Hard limit on how long packets may stay held.\n     *\n     * <p>Holding without a timer means the client stops acknowledging inbound state entirely. The\n     * server eventually gives up on it - keepalive or transaction timeouts - and drops the\n     * connection. Releasing before that happens keeps the hold usable for as long as it is useful\n     * and no longer.\n     */\n    /** Configured warning length, clamped to a sane range. */\n    protected static int releaseWarningSeconds() {\n        int seconds = dev.nexo.config.NexoConfig.velocityreleaseSeconds;\n        if (seconds < 1) {\n            seconds = 1;\n        }\n        if (seconds > 10) {\n            seconds = 10;\n        }\n        return seconds;\n    }\n\n    /**\n     * Configured hold limit in milliseconds.\n     *\n     * @return the limit, or {@code 0} when the timeout is disabled\n     */\n    protected static long holdTimeoutMs() {\n        int tenths = dev.nexo.config.NexoConfig.velocityholdTimeout;\n        if (tenths <= 0) {\n            return 0L;\n        }\n        if (tenths > 300) {\n            tenths = 300;\n        }\n        // tenths of a second -> milliseconds\n        return tenths * 100L;\n    }\n    protected boolean pendingJump;\n\n    public BufferVelocity(VelocityModule parent) {\n        super(parent);\n    }\n\n    @Override\n    public void onPacketReceive(Packet<?> packet, boolean[] cancelled) {\n        EntityPlayerSP player = VelocityModule.mc().thePlayer;\n        if (player == null || VelocityModule.mc().theWorld == null) {\n            return;\n        }\n        // A respawn invalidates the world the batch belongs to.\n        if (packet instanceof S07PacketRespawn) {\n            clearHold();\n            return;\n        }\n        // Allow-list first: these are never delayed, blinking or not.\n        if (isAlwaysAllowed(packet)) {\n            return;\n        }\n        // Only packets the play handler can actually accept may be held. A status or login packet\n        // mixed into the stream (some proxies emit S00PacketServerInfo on the play connection) is\n        // not playable at all, and replaying it later casts the play handler to the status handler\n        // and crashes the client. Letting them straight through is both safer and closer to vanilla.\n        if (!isPlayPacket(packet)) {\n            return;\n        }\n        if (!blinking && isKnockbackPacket(packet)) {\n            if (!parent.canActOnSwing()) {\n                VelocityTrace.log(\"hold\", \"knockback ignored (canActOnSwing=false) \"\n                        + packet.getClass().getSimpleName());\n                return;\n            }\n            // Decide whether this particular knockback should be suppressed at all. The source has\n            // to be inferred from what is in the world, because the packet does not carry it.\n            KnockbackSource.Type source = KnockbackSource.classify();\n            if (!suppresses(source)) {\n                VelocityTrace.log(\"hold\", \"knockback allowed through, source=\" + source);\n                return;\n            }\n            VelocityTrace.log(\"hold\", \"knockback suppressed, source=\" + source);\n            if (packet instanceof S12PacketEntityVelocity\n                    && ((S12PacketEntityVelocity) packet).getMotionY() > 0) {\n                pendingJump = true;\n            }\n            blinking = true;\n            packetWorld = VelocityModule.mc().theWorld;\n            holdStartMs = System.currentTimeMillis();\n            announcedCountdown = 0;\n            VelocityTrace.log(\"hold\", \"START by \" + packet.getClass().getSimpleName()\n                    + String.format(\" timeout=%.1fs\", holdTimeoutMs() / 1000.0));\n        }\n        if (blinking) {\n            cancelled[0] = true;\n            heldPackets.add(packet);\n            VelocityTrace.log(\"hold\", \"held \" + packet.getClass().getSimpleName()\n                    + \" n=\" + heldPackets.size());\n        }\n    }\n\n    /**\n     * Whether a knockback from this source should be suppressed.\n     *\n     * <p>Each source has its own switch so a rod pull can be allowed through (being reeled in\n     * repeatedly is far more disruptive than the push itself) while melee stays suppressed.\n     */\n    private static boolean suppresses(KnockbackSource.Type source) {\n        switch (source) {\n            case ROD:\n                return dev.nexo.config.NexoConfig.velocitykbRod;\n            case BOW:\n                return dev.nexo.config.NexoConfig.velocitykbBow;\n            case MELEE:\n            default:\n                return dev.nexo.config.NexoConfig.velocitykbMelee;\n        }\n    }\n\n    /**\n     * Whether this packet belongs to the play phase and can be replayed through the play handler.\n     *\n     * <p>Deliberately a name check rather than an exhaustive allow-list: the goal is only to keep\n     * packets from the other connection phases out of the hold, not to police which play packets are\n     * held. Anything whose handler lives outside {@code network.play} or {@code network.status} /\n     * {@code network.login} is passed through untouched.\n     */\n    private static boolean isPlayPacket(Packet<?> packet) {\n        String name = packet.getClass().getName();\n        // Status and login packets have handlers of a different type; replaying them is a cast\n        // error by construction.\n        if (name.startsWith(\"net.minecraft.network.status.\")\n                || name.startsWith(\"net.minecraft.network.login.\")) {\n            return false;\n        }\n        // Handshake is connection setup and never has a play handler.\n        if (name.startsWith(\"net.minecraft.network.handshake.\")) {\n            return false;\n        }\n        return true;\n    }\n\n    /**\n     * Packets that are never held.\n     *\n     * <p>Transcribed from the reference build; each entry is there because delaying it desyncs\n     * something the client cannot repair later.\n     */\n    protected boolean isAlwaysAllowed(Packet<?> packet) {\n        if (packet instanceof S03PacketTimeUpdate\n                || packet instanceof S06PacketUpdateHealth\n                || packet instanceof S13PacketDestroyEntities\n                || packet instanceof S02PacketChat\n                || packet instanceof S25PacketBlockBreakAnim\n                || packet instanceof S2FPacketSetSlot\n                || packet instanceof S08PacketPlayerPosLook\n                || packet instanceof S18PacketEntityTeleport) {\n            return true;\n        }\n        if (packet instanceof S2BPacketChangeGameState) {\n            int state = ((S2BPacketChangeGameState) packet).getGameState();\n            // 1 = begin raining, 2 = end raining, 7 = rain fade value, 8 = rain fade time.\n            if (state == 1 || state == 2 || state == 7 || state == 8) {\n                return true;\n            }\n        }\n        if (packet instanceof S2CPacketSpawnGlobalEntity) {\n            // 1.8.9 exposes no accessor for the type field, so every global entity spawn is let\n            // through instead of only lightning. The difference is a few cosmetic entities.\n            return true;\n        }\n        if (packet instanceof S29PacketSoundEffect\n                && \"ambient.weather.thunder\".equalsIgnoreCase(\n                        ((S29PacketSoundEffect) packet).getSoundName())) {\n            return true;\n        }\n        return false;\n    }\n\n    @Override\n    public void onPostPlayerUpdate() {\n        if (!blinking) {\n            return;\n        }\n        if (holdStartMs <= 0L) {\n            // Defensive: a hold without a start time would compute an enormous elapsed and release\n            // on the very next tick, then repeat - the countdown would spam chat every second.\n            // Re-stamp it instead so the timeout measures from now.\n            holdStartMs = System.currentTimeMillis();\n            return;\n        }\n        long timeout = holdTimeoutMs();\n        if (timeout <= 0L) {\n            // Timeout disabled: the hold only ends when the module is switched off or the world\n            // changes. Useful when a longer silence is wanted, at the risk of the server timing the\n            // connection out.\n            return;\n        }\n        long elapsed = System.currentTimeMillis() - holdStartMs;\n        long remaining = timeout - elapsed;\n        // Count down the last few seconds in chat so the release is never a surprise: the client\n        // freezes for a moment when the backlog goes out, and without warning that looks like a\n        // hang.\n        if (dev.nexo.config.NexoConfig.velocityreleaseCountdown\n                && remaining > 0 && remaining <= releaseWarningSeconds() * 1000L) {\n            int seconds = (int) ((remaining + 999L) / 1000L);\n            if (seconds > 0 && seconds <= releaseWarningSeconds() && seconds != announcedCountdown) {\n                announcedCountdown = seconds;\n                if (dev.nexo.config.NexoConfig.velocitydebug) {\n                    dev.nexo.client.Chat.print(\"&ereleasing in &f\" + seconds + \"&e...\");\n                }\n            }\n        }\n        if (remaining > 0) {\n            return;\n        }\n        // Timed out. Hand everything over before the server decides we are gone.\n        if (dev.nexo.config.NexoConfig.velocitydebug) {\n            dev.nexo.client.Chat.print(\"&ereleased (timeout)\");\n        }\n        announcedCountdown = 0;\n        flushAll();\n    }\n\n    @Override\n    public void onPostPlayerInput() {\n        // The jump is issued from flushAll() instead: with no timer the release only happens when\n        // the module is turned off, so there is no tick to wait for here.\n    }\n\n    @Override\n    public void reset(boolean release) {\n        if (release) {\n            // flushAll() reads and clears pendingJump itself, so it must run first.\n            flushAll();\n        } else {\n            pendingJump = false;\n            clearHold();\n        }\n    }\n\n    private boolean isKnockbackPacket(Packet<?> packet) {\n        EntityPlayerSP player = VelocityModule.mc().thePlayer;\n        if (player == null) {\n            return false;\n        }\n        if (packet instanceof S12PacketEntityVelocity) {\n            return ((S12PacketEntityVelocity) packet).getEntityID() == player.getEntityId();\n        }\n        if (packet instanceof S27PacketExplosion) {\n            S27PacketExplosion explosion = (S27PacketExplosion) packet;\n            return explosion.func_149149_c() != 0.0f\n                    || explosion.func_149144_d() != 0.0f\n                    || explosion.func_149147_e() != 0.0f;\n        }\n        return false;\n    }\n\n    protected void flushAll() {\n        List<Packet<?>> batch = new ArrayList<Packet<?>>(heldPackets);\n        WorldClient world = packetWorld;\n        int count = batch.size();\n        boolean jump = pendingJump;\n        VelocityTrace.log(\"release\", \"FLUSH \" + count + \" packets\"\n                + String.format(\" held=%.1fs\", (System.currentTimeMillis() - holdStartMs) / 1000.0));\n        clearHold();\n        parent.replayPackets(batch, world);\n        // The knockback packet is inside the batch, so jumping has to happen after the replay.\n        if (jump) {\n            EntityPlayerSP player = VelocityModule.mc().thePlayer;\n            if (player != null && player.movementInput != null) {\n                player.movementInput.jump = true;\n            }\n        }\n    }\n\n    protected void clearHold() {\n        heldPackets.clear();\n        packetWorld = null;\n        blinking = false;\n        holdStartMs = 0L;\n        announcedCountdown = 0;\n    }\n\n    /** Packets currently held, for the HUD. */\n    public int heldCount() {\n        return heldPackets.size();\n    }\n\n    public boolean isBlinking() {\n        return blinking;\n    }\n}\n"}