0x2D S2DPacketOpenWindow
Opens an inventory GUI window (chest, crafting table, furnace, enchantment table, etc.) with window ID, type, title, and slot count.
Published 2026-06-18 · Updated 2026-10-14
Fields
| Field | Type | Description |
|---|---|---|
| windowId | unsigned byte | Server-assigned window ID |
| inventoryType | String | GUI type identifier (minecraft:chest, minecraft:crafting_table, etc.) |
| windowTitle | IChatComponent (JSON) | Window title displayed in GUI |
| slotCount | unsigned byte | Number of slots in the window |
| entityId | int | Entity ID for EntityHorse type (only present for horse GUIs) |
Wire Encoding
| Field | Type | Notes |
|---|---|---|
| Window ID | Unsigned Byte | |
| Inventory Type | String | minecraft:chest, etc. |
| Window Title | Chat Component (JSON) | Displayed as window title |
| Slot Count | Unsigned Byte | |
| Entity ID (if horse) | int | Only for EntityHorse type |
MCP References
NetHandlerPlayClient.handleOpenWindow()Handler Interface
INetHandlerPlayClientNotes
Vanilla Source
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
Deobfuscated MCP 1.8.9 source of S2DPacketOpenWindow, fetched directly from Marcelektro/MavenMCP-1.8.9 (net/minecraft/network/play/server/S2DPacketOpenWindow.java) at build time and verified present.
Deep Dive
Role in the protocol
Opens an inventory window on the client. The server assigns a windowId (incrementing per player, wrapping at 256), picks a GUI type string, sends the title as a chat component, the slot count, and for EntityHorse windows the horse's entityId. The client switches on the type string: minecraft:container becomes a chest GUI, minecraft:villager a trade GUI, EntityHorse a horse inventory, anything else a LocalBlockIntercommunication GUI. The windowId must then be echoed back on every C0E click and C0D close.
Vanilla handling
NetHandlerPlayClient.handleOpenWindow matches the type string and calls the matching display method (displayGUIChest, displayVillagerTradeGui, displayGUIHorse, displayGui), then stamps the windowId onto the player's openContainer. The horse branch looks up the entity by id and silently does nothing if the entity is missing. Server-side, EntityPlayerMP.displayGUIChest and openGui build the packet with the player's currentWindowId, which increments on every open.
Why clients touch it
Two Rise 6.x modules, both cancelling the packet for combat-adjacent reasons. WorldGuardRegen suppresses S2D while its regen burst is active (ticks <= 1) so a server-initiated window cannot interrupt the position-desync regen sequence. GodMode cancels every S2D unconditionally, which keeps the server's window state desynced from the client as part of the godmode attack-desync. The context's ChestStealer/AutoArmor/ServerCrasher open-window usage does not exist in this corpus; the 8 clients contain no inventory-stealing S2D consumer.
Exploit surface
The windowId protocol is a state machine: the client must mirror every S2D with an open container and echo the id in later clicks. Cancelling S2D (Rise 6.x) leaves the server believing a window is open while the client never shows it, which is exactly the desync GodMode and WorldGuardRegen exploit. Server-side open-window spam (ServerCrasher style) is a client DoS: each S2D forces a GUI construction, and rapid-fire opens desync the container state. The EntityHorse branch's entity lookup is also a soft spot: a stale id silently drops the window.
Server-Side Handling
EntityPlayerMP.displayGUIChest/openGui increments currentWindowId, opens the container server-side, and sends S2D with the id, GUI type, display name, and slot count (plus entityId for horses). The client must echo the windowId in C0E clicks and C0D closes or the server container stays open with stale state. Vanilla performs no validation that the client actually opened the window, which is the desync window both Rise 6.x modules rely on.
Protocol Analysis
Encoding: unsigned byte windowId, String guiId (minecraft:container, minecraft:villager, EntityHorse, or a block interaction id), IChatComponent title, unsigned byte slotCount, then int entityId only when guiId is EntityHorse. windowId wraps at 256 and the client stamps it on openContainer.windowId. The type string is the discriminator; there is no numeric window-type enum on the wire in 1.8.9.
Anti-Cheat Landscape
Anti-cheats track window state through the C0E/C0D echo trail, not through S2D itself. The Rise 6.x cancels create a server-side phantom container: the server keeps sending window updates (S2F, S30) to a window the client never opened, which is detectable if an anti-cheat correlates window items with click packets. The trade-off is why WorldGuardRegen only cancels during the short regen burst (ticks <= 1) while GodMode accepts the permanent desync.
implementation Implementation Cases
The window-open packet, and the desync hinge for two Rise 6.x combat modules: WorldGuardRegen suppresses it during regen bursts, GodMode cancels it permanently to keep the server-client container state split. No chest-stealing or shop-detection module exists in the corpus; the windowId echo contract is what makes cancellation useful.
Prevent a server-initiated window from interrupting the regen position-desync sequence.
A Regen mode. Its PreMotionEvent handler drops the player y by 0.05 and holds yaw/pitch while health is below the threshold; the PacketSendEvent handler wraps attacks in a C04-teleport/attack/C04-return sandwich. The PacketReceiveEvent handler cancels any S2D while ticks <= 1, i.e. during the active regen burst, so the server cannot open a container mid-sequence and break the state machine.
// ===== FILE: Rise 6.2.4, Client-release2/Client/src/main/java/com/alan/clients/module/impl/combat/regen/WorldGuardRegen.java =====
package com.alan.clients.module.impl.combat.regen;
import com.alan.clients.event.Listener;
import com.alan.clients.event.annotations.EventLink;
import com.alan.clients.event.impl.input.MoveInputEvent;
import com.alan.clients.event.impl.motion.PreMotionEvent;
import com.alan.clients.event.impl.motion.StrafeEvent;
import com.alan.clients.event.impl.packet.PacketReceiveEvent;
import com.alan.clients.event.impl.packet.PacketSendEvent;
import com.alan.clients.module.impl.combat.Regen;
import com.alan.clients.util.packet.PacketUtil;
import com.alan.clients.value.Mode;
import com.alan.clients.value.impl.NumberValue;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C02PacketUseEntity;
import net.minecraft.network.play.client.C03PacketPlayer;
import net.minecraft.network.play.server.S2DPacketOpenWindow;
public final class WorldGuardRegen extends Mode<Regen> {
private final NumberValue health = new NumberValue("Minimum Health", this, 15, 1, 20, 1);
private int ticks;
private float yaw;
private float pitch;
public WorldGuardRegen(String name, Regen parent) {
super(name, parent);
}
@EventLink
public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
if (mc.thePlayer.onGround && mc.thePlayer.getHealth() < this.health.getValue().floatValue()) {
if (ticks <= 1) {
event.setPosY(event.getPosY() - 0.05);
event.setYaw(yaw);
event.setPitch(pitch);
ticks++;
}
} else {
yaw = event.getYaw();
pitch = event.getPitch();
ticks = 0;
}
};
@EventLink
public final Listener<PacketSendEvent> onPacketSend = event -> {
final Packet<?> p = event.getPacket();
if (p instanceof C02PacketUseEntity && mc.thePlayer.onGround && mc.thePlayer.getHealth() < this.health.getValue().floatValue() && ticks <= 1) {
final C02PacketUseEntity wrapper = (C02PacketUseEntity) p;
if (wrapper.getAction().equals(C02PacketUseEntity.Action.ATTACK)) {
event.setCancelled();
PacketUtil.sendNoEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
PacketUtil.sendNoEvent(wrapper);
PacketUtil.sendNoEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY - 0.05, mc.thePlayer.posZ, false));
}
}
};
@EventLink
public final Listener<PacketReceiveEvent> onPacketReceiveEvent = event -> {
if (event.getPacket() instanceof S2DPacketOpenWindow && ticks <= 1) {
event.setCancelled();
}
};
@EventLink
public final Listener<StrafeEvent> onStrafe = event -> {
if (mc.thePlayer.onGround && mc.thePlayer.getHealth() < this.health.getValue().floatValue() && ticks <= 1) {
event.setSpeed(0);
}
};
@EventLink
public final Listener<MoveInputEvent> onMove = event -> {
if (mc.thePlayer.onGround && mc.thePlayer.getHealth() < this.health.getValue().floatValue() && ticks <= 1) {
event.setJump(false);
}
};
}
// NOTE (AI): The S2D cancel (lines ~67-69) is gated on ticks <= 1, the same guard as the position drop and attack sandwich, so the window suppression only lasts for the regen burst.Cancel every open-window packet so the server's container state permanently diverges from the client's.
Cancels all S2D in PacketReceiveEvent. Combined with the module's core trick (drop y by 0.05 every pre-motion, wrap attacks in a position sandwich via PacketUtil.sendNoEvent), the server keeps an open phantom container while the client stays in normal movement. onEnable snapshots yaw/pitch for the desync frames.
// ===== FILE: Rise 6.2.4, Client-release2/Client/src/main/java/com/alan/clients/module/impl/exploit/GodMode.java =====
package com.alan.clients.module.impl.exploit;
import com.alan.clients.event.Listener;
import com.alan.clients.event.annotations.EventLink;
import com.alan.clients.event.impl.input.MoveInputEvent;
import com.alan.clients.event.impl.motion.PreMotionEvent;
import com.alan.clients.event.impl.motion.StrafeEvent;
import com.alan.clients.event.impl.packet.PacketReceiveEvent;
import com.alan.clients.event.impl.packet.PacketSendEvent;
import com.alan.clients.module.Module;
import com.alan.clients.module.api.Category;
import com.alan.clients.module.api.ModuleInfo;
import com.alan.clients.util.packet.PacketUtil;
import net.minecraft.network.Packet;
import net.minecraft.network.play.client.C02PacketUseEntity;
import net.minecraft.network.play.client.C03PacketPlayer;
import net.minecraft.network.play.server.S2DPacketOpenWindow;
@ModuleInfo(aliases = {"module.combat.godmode.name"}, description = "module.exploit.godmode.description", category = Category.EXPLOIT)
public class GodMode extends Module {
private float yaw;
private float pitch;
@EventLink
public final Listener<PreMotionEvent> onPreMotionEvent = event -> {
event.setPosY(event.getPosY() - 0.05);
event.setYaw(yaw);
event.setPitch(pitch);
};
@EventLink
public final Listener<PacketSendEvent> onPacketSend = event -> {
final Packet<?> p = event.getPacket();
if (p instanceof C02PacketUseEntity) {
final C02PacketUseEntity wrapper = (C02PacketUseEntity) p;
if (wrapper.getAction().equals(C02PacketUseEntity.Action.ATTACK)) {
event.setCancelled();
PacketUtil.sendNoEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, true));
PacketUtil.sendNoEvent(wrapper);
PacketUtil.sendNoEvent(new C03PacketPlayer.C04PacketPlayerPosition(mc.thePlayer.posX, mc.thePlayer.posY - 0.05, mc.thePlayer.posZ, false));
}
}
};
@EventLink
public final Listener<PacketReceiveEvent> onPacketReceiveEvent = event -> {
if (event.getPacket() instanceof S2DPacketOpenWindow) {
event.setCancelled();
}
};
@EventLink
public final Listener<StrafeEvent> onStrafe = event -> {
event.setSpeed(0);
};
@EventLink
public final Listener<MoveInputEvent> onMove = event -> {
event.setJump(false);
};
@Override
public void onEnable() {
yaw = mc.thePlayer.rotationYaw;
pitch = mc.thePlayer.rotationPitch;
}
}
// NOTE (AI): The S2D cancel (lines ~51-53) is unconditional, unlike WorldGuardRegen's tick-gated version. The y-drop and attack sandwich above it are the actual godmode mechanism; the window cancel keeps the server-side state desynced.anticheat Anti-Cheat Checks
The open-window packet is the state anchor for inventory anti-cheat: modern anticheats mirror the S2D open into a simulated window state and then validate every C0E click against it. Grim records the container id and type on the send side and rejects impossible click combinations, and its CompensatedInventory runs the full openWindowID state machine. Intave timestamps the open so its inventory-click-analysis check can measure click delay, and Artemis transaction-confirms the open to flip the inventory-open flag. Classic repos stop at wrappers (FlopAC WrappedOutOpenWindow, Kauri PacketHandler, Negativity PacketType).
Reject crafted window-click packets whose button values are impossible for the click type.
PacketSendListener records containerType and containerId from the S2D OPEN_WINDOW packet; PacketReceiveListener then validates every C0E click: button range per click type (PICKUP/QUICK_MOVE/CLONE 0-2, SWAP 0-8 or 40, THROW 0-1, QUICK_CRAFT a fixed set, PICKUP_ALL 0). The verbose line also reports whether the click's window id matches the container opened by S2D, and the packet is cancelled on repeated flags.
// ===== FILE: GrimAnticheat-Grim, common/src/main/java/ac/grim/grimac/checks/impl/badpackets/BadPacketsP.java =====
package ac.grim.grimac.checks.impl.badpackets;
import ac.grim.grimac.api.storage.verbose.Verbose;
import ac.grim.grimac.checks.Check;
import ac.grim.grimac.checks.CheckData;
import ac.grim.grimac.checks.impl.verbose.VerboseCodecs;
import ac.grim.grimac.checks.type.PacketReceiveListener;
import ac.grim.grimac.checks.type.PacketSendListener;
import ac.grim.grimac.player.GrimPlayer;
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientClickWindow;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientClickWindow.WindowClickType;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerOpenWindow;
@CheckData(name = "BadPacketsP", stableKey = "grim.badpackets.invalid_click", description = "Invalid window click packet", experimental = true)
public class BadPacketsP extends Check implements PacketReceiveListener, PacketSendListener {
private static final Verbose V =
Verbose.of("clickType={clicktype_lower}, button={sint}[, container={sint}]");
private int containerType = -1;
private int containerId = -1;
public BadPacketsP(GrimPlayer playerData) {
super(playerData);
}
@Override
public void onPacketSend(final PacketSendEvent event) {
if (event.getPacketType() == PacketType.Play.Server.OPEN_WINDOW) {
WrapperPlayServerOpenWindow window = new WrapperPlayServerOpenWindow(event);
this.containerType = window.getType();
this.containerId = window.getContainerId();
}
}
@Override
public void onPacketReceive(PacketReceiveEvent event) {
if (event.getPacketType() == PacketType.Play.Client.CLICK_WINDOW) {
WrapperPlayClientClickWindow wrapper = new WrapperPlayClientClickWindow(event);
WindowClickType clickType = wrapper.getWindowClickType();
int button = wrapper.getButton();
// TODO: Adjust for containers
boolean flag = switch (clickType) {
case PICKUP, QUICK_MOVE, CLONE -> button > 2 || button < 0;
case SWAP -> (button > 8 || button < 0) && button != 40;
case THROW -> button != 0 && button != 1;
case QUICK_CRAFT -> button == 3 || button == 7 || button > 10 || button < 0;
case PICKUP_ALL -> button != 0;
case UNKNOWN -> true;
};
// Allowing this to false flag to debug and find issues faster
if (flag) {
boolean hasContainer = wrapper.getWindowId() == containerId;
if (flag(V.write(verbose()).uint(VerboseCodecs.enumId(clickType)).sint(button).bool(hasContainer).sint(containerType))
&& shouldModifyPackets()) {
event.setCancelled(true);
player.onPacketCancel();
}
}
}
}
}
// NOTE (AI): The onPacketSend branch is the S2D hook: it records the container id and type from the server open. The flag verbosity includes whether the click's window id matches the opened container.Emulate the server-side inventory and open-window id so click, slot and item packets can be validated against client-visible state.
On the S2D OPEN_WINDOW send it stores openWindowID from the container id (the horse-window variant is handled separately); the S2F set-slot and S30 window-items handlers then route updates to the player inventory (id 0) or the opened menu (id equal to openWindowID). Clicks against a mismatched window id are treated as invalid, and closeActiveInventory resets the menu, carried item and id.
// ===== FILE: GrimAnticheat-Grim, common/src/main/java/ac/grim/grimac/utils/latency/CompensatedInventory.java =====
package ac.grim.grimac.utils.latency;
import ac.grim.grimac.checks.Check;
import ac.grim.grimac.checks.type.PacketReceiveListener;
import ac.grim.grimac.checks.type.PacketSendListener;
import ac.grim.grimac.player.GrimPlayer;
import ac.grim.grimac.utils.anticheat.update.BlockPlace;
import ac.grim.grimac.utils.inventory.EquipmentType;
import ac.grim.grimac.utils.inventory.Inventory;
import ac.grim.grimac.utils.inventory.inventory.AbstractContainerMenu;
import ac.grim.grimac.utils.inventory.inventory.MenuType;
import ac.grim.grimac.utils.inventory.inventory.NotImplementedMenu;
import ac.grim.grimac.utils.lists.CorrectingPlayerInventoryStorage;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.protocol.item.ItemStack;
import com.github.retrooper.packetevents.protocol.item.type.ItemType;
import com.github.retrooper.packetevents.protocol.item.type.ItemTypes;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.protocol.player.DiggingAction;
import com.github.retrooper.packetevents.protocol.player.GameMode;
import com.github.retrooper.packetevents.protocol.player.InteractionHand;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientClickWindow;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientCreativeInventoryAction;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientHeldItemChange;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPlayerDigging;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientUseItem;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerOpenHorseWindow;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerOpenWindow;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPlayerInventory;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetSlot;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowItems;
import lombok.Getter;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
// Updated to support modern 1.17 protocol
public class CompensatedInventory extends Check implements PacketReceiveListener, PacketSendListener {
private static final int PLAYER_INVENTORY_CASE = -1;
private static final int UNSUPPORTED_INVENTORY_CASE = -2;
// "Temporarily" public for debugging
public final Inventory inventory;
// "Temporarily" public for debugging
public AbstractContainerMenu menu;
// Not all inventories are supported due to complexity and version differences
public boolean isPacketInventoryActive = true;
public boolean needResend = false;
public int stateID = 0; // Don't mess up the last sent state ID by changing it
private int openWindowID = 0;
// Special values:
// Player inventory is -1
// Unsupported inventory is -2
private int packetSendingInventorySize = PLAYER_INVENTORY_CASE;
// The item held at the start of the current client tick (processed at the end of the previous tick)
// also updated before slot changes to account for the delay when using hotbar keybinds
// Currently only used by 1.21.11+ players to handle attribute swapping items with the ATTACK_RANGE Component
@Getter
private ItemStack startOfTickStack = ItemStack.EMPTY;
public CompensatedInventory(GrimPlayer playerData) {
super(playerData);
CorrectingPlayerInventoryStorage storage = new CorrectingPlayerInventoryStorage(player, 46);
inventory = new Inventory(playerData, storage);
menu = inventory;
}
// Meant for 1.17+ clients who send changed slots, making the server not send the entire inventory
private void markPlayerSlotAsChanged(int clicked) {
// Player inventory
if (openWindowID == 0) {
inventory.getInventoryStorage().handleClientClaimedSlotSet(clicked);
return;
}
// We don't know size of the inventory, so we can't do anything
// We will resync later.
if (menu instanceof NotImplementedMenu) return;
// 9-45 are the player inventory slots that are used
// There are 36 player slots in each menu that we care about and track.
int nonPlayerInvSize = menu.getSlots().size() - 36 + 9;
int playerInvSlotclicked = clicked - nonPlayerInvSize;
// Bypass player inventory
inventory.getInventoryStorage().handleClientClaimedSlotSet(playerInvSlotclicked);
}
public ItemStack getItemInHand(InteractionHand hand) {
return hand == InteractionHand.MAIN_HAND ? getHeldItem() : getOffHand();
}
/**
* Marks that the server has updated a slot by the specified ID in the specified inventory ID.
* @param clicked the updated slot
* @param windowID the inventory ID
*/
private void markServerForChangingSlot(int clicked, int windowID) {
// Unsupported inventory
if (packetSendingInventorySize == UNSUPPORTED_INVENTORY_CASE) return;
// Player inventory
if (packetSendingInventorySize == PLAYER_INVENTORY_CASE || windowID == 0) {
// Result slot isn't included in storage, we must ignore it
inventory.getInventoryStorage().handleServerCorrectSlot(clicked);
return;
}
// See note in above method.
int nonPlayerInvSize = menu.getSlots().size() - 36 + 9;
int playerInvSlotclicked = clicked - nonPlayerInvSize;
inventory.getInventoryStorage().handleServerCorrectSlot(playerInvSlotclicked);
}
public ItemStack getHeldItem() {
ItemStack item = isPacketInventoryActive || player.platformPlayer == null ? inventory.getHeldItem() :
player.platformPlayer.getInventory().getItemInHand();
return item == null ? ItemStack.EMPTY : item;
}
public ItemStack getOffHand() {
if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_9))
return ItemStack.EMPTY;
ItemStack item = isPacketInventoryActive || player.platformPlayer == null ? inventory.getOffhand() :
player.platformPlayer.getInventory().getItemInOffHand();
return item == null ? ItemStack.EMPTY : item;
}
public ItemStack getHelmet() {
ItemStack item = isPacketInventoryActive || player.platformPlayer == null ? inventory.getHelmet() :
player.platformPlayer.getInventory().getHelmet();
return item == null ? ItemStack.EMPTY : item;
}
public ItemStack getChestplate() {
ItemStack item = isPacketInventoryActive || player.platformPlayer == null ? inventory.getChestplate() :
player.platformPlayer.getInventory().getChestplate();
return item == null ? ItemStack.EMPTY : item;
}
public ItemStack getLeggings() {
ItemStack item = isPacketInventoryActive || player.platformPlayer == null ? inventory.getLeggings() :
player.platformPlayer.getInventory().getLeggings();
return item == null ? ItemStack.EMPTY : item;
}
public ItemStack getBoots() {
ItemStack item = isPacketInventoryActive || player.platformPlayer == null ? inventory.getBoots() :
player.platformPlayer.getInventory().getBoots();
return item == null ? ItemStack.EMPTY : item;
}
private ItemStack getByEquipmentType(EquipmentType type) {
return switch (type) {
case HEAD -> getHelmet();
case CHEST -> getChestplate();
case LEGS -> getLeggings();
case FEET -> getBoots();
case OFFHAND -> getOffHand();
case MAINHAND -> getHeldItem();
};
}
public boolean hasItemType(ItemType type) {
if (isPacketInventoryActive || player.platformPlayer == null)
return inventory.hasItemType(type);
// Fall back to platform inventories
for (ItemStack itemStack : player.platformPlayer.getInventory().getContents()) {
if (itemStack != null && itemStack.getType() == type) return true;
}
return false;
}
@Override
public void onPacketReceive(final PacketReceiveEvent event) {
if (event.getPacketType() == PacketType.Play.Client.USE_ITEM) {
WrapperPlayClientUseItem item = new WrapperPlayClientUseItem(event);
ItemStack use = item.getHand() == InteractionHand.MAIN_HAND ? getHeldItem() : getOffHand();
EquipmentType equipmentType = EquipmentType.getEquipmentSlotForItem(use);
if (equipmentType != null) {
int slot;
switch (equipmentType) {
case HEAD -> slot = Inventory.SLOT_HELMET;
case CHEST -> slot = Inventory.SLOT_CHESTPLATE;
case LEGS -> slot = Inventory.SLOT_LEGGINGS;
case FEET -> slot = Inventory.SLOT_BOOTS;
default -> {
return; // Not armor, therefore we shouldn't run this code
}
}
ItemStack currentEquippedItem = getByEquipmentType(equipmentType);
// Only 1.19.4+ clients support swapping with non-empty items
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_19_4) && !currentEquippedItem.isEmpty())
return;
// 1.19.4+ clients support swapping with non-empty items
int swapItemSlot = item.getHand() == InteractionHand.MAIN_HAND ? inventory.getSelected() + Inventory.HOTBAR_OFFSET : Inventory.SLOT_OFFHAND;
// Mojang implemented this stupidly, I rewrote their item swap code to make it somewhat cleaner.
// Slot in hotbar
inventory.getInventoryStorage().handleClientClaimedSlotSet(swapItemSlot);
inventory.getInventoryStorage().setItem(swapItemSlot, currentEquippedItem);
// Equipment slot
inventory.getInventoryStorage().handleClientClaimedSlotSet(slot);
inventory.getInventoryStorage().setItem(slot, use);
}
} else if (event.getPacketType() == PacketType.Play.Client.PLAYER_DIGGING) {
WrapperPlayClientPlayerDigging dig = new WrapperPlayClientPlayerDigging(event);
// 1.8 clients don't predict dropping items
if (player.getClientVersion().isOlderThanOrEquals(ClientVersion.V_1_8)) return;
if (dig.getAction() == DiggingAction.DROP_ITEM) {
ItemStack heldItem = getHeldItem();
if (heldItem != null) {
heldItem.setAmount(heldItem.getAmount() - 1);
if (heldItem.getAmount() <= 0) {
heldItem = null;
}
}
inventory.setHeldItem(heldItem);
inventory.getInventoryStorage().handleClientClaimedSlotSet(Inventory.HOTBAR_OFFSET + player.packetStateData.lastSlotSelected);
}
if (dig.getAction() == DiggingAction.DROP_ITEM_STACK) {
inventory.setHeldItem(null);
inventory.getInventoryStorage().handleClientClaimedSlotSet(Inventory.HOTBAR_OFFSET + player.packetStateData.lastSlotSelected);
}
} else if (event.getPacketType() == PacketType.Play.Client.HELD_ITEM_CHANGE) {
final int slot = new WrapperPlayClientHeldItemChange(event).getSlot();
// Stop people from spamming the server with an out-of-bounds exception
if (slot > 8 || slot < 0) return;
// set this before we change the selected slot so we get the previous item held
this.startOfTickStack = getHeldItem();
inventory.setSelected(slot);
} else if (event.getPacketType() == PacketType.Play.Client.CREATIVE_INVENTORY_ACTION) {
WrapperPlayClientCreativeInventoryAction action = new WrapperPlayClientCreativeInventoryAction(event);
if (player.gamemode != GameMode.CREATIVE) return;
boolean valid = action.getSlot() >= 1 &&
(PacketEvents.getAPI().getServerManager().getVersion().isNewerThan(ServerVersion.V_1_8) ?
action.getSlot() <= 45 : action.getSlot() < 45);
if (valid) {
inventory.getSlot(action.getSlot()).set(action.getItemStack());
inventory.getInventoryStorage().handleClientClaimedSlotSet(action.getSlot());
}
} else if (event.getPacketType() == PacketType.Play.Client.CLICK_WINDOW && !event.isCancelled()) {
WrapperPlayClientClickWindow click = new WrapperPlayClientClickWindow(event);
// How is this possible? Maybe transaction splitting.
if (click.getWindowId() != openWindowID) {
return;
}
// Don't care about this click since we can't track it.
if (menu instanceof NotImplementedMenu) {
return;
}
// Mark the slots the player has changed as changed, then continue simulating what they changed
Optional<Map<Integer, ItemStack>> slots = click.getSlots();
slots.ifPresent(integerItemStackMap -> integerItemStackMap.keySet().forEach(this::markPlayerSlotAsChanged));
// 0 for left click
// 1 for right click
int button = click.getButton();
// Offset by the number of slots in the inventory actively open
// Is -999 when clicking off the screen
int slot = click.getSlot();
// Self-explanatory, look at the enum's values
WrapperPlayClientClickWindow.WindowClickType clickType = click.getWindowClickType();
if (slot == -1 || slot == -999 || slot < menu.getSlots().size()) {
menu.doClick(button, slot, clickType);
}
} else if (event.getPacketType() == PacketType.Play.Client.CLOSE_WINDOW) {
this.closeActiveInventory();
} else if (isTickPacket(event.getPacketType())) {
this.startOfTickStack = getHeldItem();
}
}
public void markSlotAsResyncing(BlockPlace place) {
// Update held item tracking
if (place.hand == InteractionHand.MAIN_HAND) {
inventory.getInventoryStorage().handleClientClaimedSlotSet(Inventory.HOTBAR_OFFSET + player.packetStateData.lastSlotSelected);
} else {
inventory.getInventoryStorage().handleServerCorrectSlot(Inventory.SLOT_OFFHAND);
}
}
public void onBlockPlace(BlockPlace place) {
if (player.gamemode != GameMode.CREATIVE && place.itemStack.getType() != ItemTypes.POWDER_SNOW_BUCKET) {
markSlotAsResyncing(place);
place.itemStack.setAmount(place.itemStack.getAmount() - 1);
}
}
@Override
public void onPacketSend(final PacketSendEvent event) {
// Not 1:1 MCP, based on Wiki.VG to be simpler as we need less logic...
// For example, we don't need permanent storage, only storing data until the client closes the window
// We also don't need a lot of server-sided only logic
if (event.getPacketType() == PacketType.Play.Server.OPEN_WINDOW) {
WrapperPlayServerOpenWindow open = new WrapperPlayServerOpenWindow(event);
MenuType menuType = MenuType.getMenuType(open.getType());
AbstractContainerMenu newMenu;
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_14)) {
newMenu = MenuType.getMenuFromID(player, inventory, menuType);
} else {
newMenu = MenuType.getMenuFromString(player, inventory, open.getLegacyType(), open.getLegacySlots(), open.getHorseId());
}
packetSendingInventorySize = newMenu instanceof NotImplementedMenu ? UNSUPPORTED_INVENTORY_CASE : newMenu.getSlots().size();
// There doesn't seem to be a check against using 0 as the window ID - let's consider that an invalid packet
// It will probably mess up a TON of logic both client and server sided, so don't do that!
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
openWindowID = open.getContainerId();
menu = newMenu;
isPacketInventoryActive = !(newMenu instanceof NotImplementedMenu);
needResend = newMenu instanceof NotImplementedMenu;
});
}
// I'm not implementing this lol
if (event.getPacketType() == PacketType.Play.Server.OPEN_HORSE_WINDOW) {
WrapperPlayServerOpenHorseWindow open = new WrapperPlayServerOpenHorseWindow(event);
packetSendingInventorySize = UNSUPPORTED_INVENTORY_CASE;
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
isPacketInventoryActive = false;
needResend = true;
openWindowID = open.getWindowId();
});
}
// 1:1 MCP
if (event.getPacketType() == PacketType.Play.Server.CLOSE_WINDOW) {
packetSendingInventorySize = PLAYER_INVENTORY_CASE;
// Disregard provided window ID, client doesn't care...
// We need to do this because the client doesn't send a packet when closing the window
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), this::closeActiveInventory);
}
// Should be 1:1 MCP
if (event.getPacketType() == PacketType.Play.Server.WINDOW_ITEMS) {
WrapperPlayServerWindowItems items = new WrapperPlayServerWindowItems(event);
stateID = items.getStateId();
List<ItemStack> slots = items.getItems();
for (int i = 0; i < slots.size(); i++) {
markServerForChangingSlot(i, items.getWindowId());
}
final int cachedPacketInvSize = packetSendingInventorySize;
final AtomicBoolean updatedValue = new AtomicBoolean();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
// Never true when the inventory is unsupported.
// Vanilla ALWAYS sends the entire inventory to resync, this is a valid thing to check
// 01/07/2025: Somehow, the server sends a window id 0 update when the player is not in their inventory?
// I guess just revert isPacketInventoryActive if the player has a NotImplementedMenu open?
// Regardless, the client does accept this packet and updates its inventory, so we must do the same.
boolean forceUpdate = slots.size() == cachedPacketInvSize || items.getWindowId() == 0;
if (!isPacketInventoryActive && forceUpdate) {
isPacketInventoryActive = true;
updatedValue.set(true);
}
});
if (items.getWindowId() == 0) { // Player inventory
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
if (!isPacketInventoryActive) return;
for (int i = 0; i < slots.size(); i++) {
inventory.getSlot(i).set(slots.get(i));
}
if (items.getCarriedItem().isPresent()) {
inventory.setCarried(items.getCarriedItem().get());
}
});
} else {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
if (!isPacketInventoryActive) return;
if (items.getWindowId() == openWindowID) {
for (int i = 0; i < slots.size(); i++) {
menu.getSlot(i).set(slots.get(i));
}
}
if (items.getCarriedItem().isPresent()) {
inventory.setCarried(items.getCarriedItem().get());
}
});
}
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
// The server sent a packet for the player's inventory when they had another inventory open - revert.
if (updatedValue.get() && !menu.equals(inventory)) {
isPacketInventoryActive = false;
}
});
}
// This packet replaces SET_SLOT for player inventory for 1.21.2+
if (event.getPacketType() == PacketType.Play.Server.SET_PLAYER_INVENTORY) {
WrapperPlayServerSetPlayerInventory slot = new WrapperPlayServerSetPlayerInventory(event);
final int slotID = slot.getSlot();
final ItemStack item = slot.getStack();
inventory.getInventoryStorage().handleServerCorrectSlot(slotID);
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
if (!isPacketInventoryActive) return;
inventory.getSlot(slotID).set(item);
});
}
// Also 1:1 MCP
if (event.getPacketType() == PacketType.Play.Server.SET_SLOT) {
// Only edit hotbar (36 to 44) if window ID is 0
// Set cursor by putting -1 as window ID and as slot
// Window ID -2 means any slot can be used
WrapperPlayServerSetSlot slot = new WrapperPlayServerSetSlot(event);
final int slotID = slot.getSlot();
final int inventoryID = slot.getWindowId();
final ItemStack item = slot.getItem();
if (inventoryID == -2) { // Direct inventory change
inventory.getInventoryStorage().handleServerCorrectSlot(slotID);
} else if (inventoryID == 0) { // Inventory change through window ID, no crafting result
inventory.getInventoryStorage().handleServerCorrectSlot(slotID);
} else {
markServerForChangingSlot(slotID, inventoryID);
}
stateID = slot.getStateId();
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
if (!isPacketInventoryActive) return;
if (inventoryID == -1) { // Carried item
inventory.setCarried(item);
} else if (inventoryID == -2) { // Direct inventory change (only applied if valid slot)
if (inventory.getInventoryStorage().getSize() > slotID && slotID >= 0) {
inventory.getInventoryStorage().setItem(slotID, item);
}
} else if (inventoryID == 0) { // Player inventory
// This packet can only be used to edit the hotbar and offhand of the player's inventory if
// window ID is set to 0 (slots 36 through 45) if the player is in creative, with their inventory open,
// and not in their survival inventory tab. Otherwise, when window ID is 0, it can edit any slot in the player's inventory.
if (slotID >= 0 && slotID <= 45) {
inventory.getSlot(slotID).set(item);
}
} else if (inventoryID == openWindowID) { // Opened inventory (if not valid, client crashes)
menu.getSlot(slotID).set(item);
}
});
}
}
/**
* Closes the player's currently open inventory on the client by resetting to the player's inventory.
*/
private void closeActiveInventory() {
isPacketInventoryActive = true;
openWindowID = 0;
menu = inventory;
menu.setCarried(ItemStack.EMPTY); // Reset carried item
}
}
// NOTE (AI): The OPEN_WINDOW handler stores openWindowID (lines 319-335); click routing keys off openWindowID throughout, so a click whose window id does not match the S2D-opened container is invalid.Flag chest-stealer and auto-inventory modules by measuring click timing and slot distance against the window open.
The openWindowPacket subscription on outbound OPEN_WINDOW records lastWindowOpenTimestamp and marks the window open under tick feedback. The windowClickPacket subscription collects distance-time and slot-time samples per window; on close, if the sample count exceeds 30 it runs statistics (mean, variance, slope, Pearson correlation) and flags constant-speed item taking, excessive speed, and distance-indifferent patterns, nerfing the player's attack damage past 100 VL.
// ===== FILE: intave-intave, src/main/java/de/jpx3/intave/check/other/inventoryclickanalysis/RegrDelayAnalyzer.java =====
/*
* Copyright 2026 Intave
*
* This software is licensed under the PolyForm Perimeter License 1.0.0.
* You may use this software for any purpose, except for providing to
* others any product that competes with the software.
*
* A copy of the license is available at:
* https://polyformproject.org/licenses/perimeter/1.0.0/
*/
package de.jpx3.intave.check.other.inventoryclickanalysis;
import com.comphenix.protocol.events.PacketContainer;
import de.jpx3.intave.check.MetaCheckPart;
import de.jpx3.intave.check.other.InventoryClickAnalysis;
import de.jpx3.intave.math.MathHelper;
import de.jpx3.intave.math.Matrix;
import de.jpx3.intave.module.Modules;
import de.jpx3.intave.module.linker.packet.ListenerPriority;
import de.jpx3.intave.module.linker.packet.PacketId;
import de.jpx3.intave.module.linker.packet.PacketSubscription;
import de.jpx3.intave.module.mitigate.AttackNerfStrategy;
import de.jpx3.intave.module.violation.Violation;
import de.jpx3.intave.module.violation.ViolationContext;
import de.jpx3.intave.module.violation.ViolationProcessor;
import de.jpx3.intave.packet.reader.WindowClickReader;
import de.jpx3.intave.user.User;
import de.jpx3.intave.user.meta.CheckCustomMetadata;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.List;
import static de.jpx3.intave.math.MathHelper.formatDouble;
import static de.jpx3.intave.module.linker.packet.PacketId.Client.CLOSE_WINDOW;
import static de.jpx3.intave.module.linker.packet.PacketId.Client.WINDOW_CLICK;
import static de.jpx3.intave.module.violation.Violation.ViolationFlags.DISPLAY_IN_ALL_VERBOSE_MODES;
public class RegrDelayAnalyzer extends MetaCheckPart<InventoryClickAnalysis, RegrDelayAnalyzer.ClickDelayMeta> {
public RegrDelayAnalyzer(InventoryClickAnalysis parentCheck) {
super(parentCheck, ClickDelayMeta.class);
}
@PacketSubscription(
priority = ListenerPriority.HIGH,
packetsOut = {
PacketId.Server.OPEN_WINDOW
}
)
public void openWindowPacket(Player player, PacketContainer packet) {
User user = userOf(player);
ClickDelayMeta meta = metaOf(user);
user.tickFeedback(() -> {
meta.lastWindowOpenTimestamp = System.currentTimeMillis();
meta.lastClickedTimestamp = System.currentTimeMillis();
meta.firstClickTimestamp = 0;
if (!meta.windowOpen) {
meta.lastSlot = 22;
}
meta.windowOpen = true;
});
}
@PacketSubscription(
priority = ListenerPriority.HIGH,
packetsIn = {
WINDOW_CLICK
}
)
public void windowClickPacket(Player player, WindowClickReader windowClick) {
if (player.getGameMode().equals(GameMode.CREATIVE)) {
return;
}
User user = userOf(player);
ClickDelayMeta meta = metaOf(user);
int slot = windowClick.slot();
ItemStack itemStack = windowClick.itemStack();
Material clickedItemType = itemStack == null ? Material.AIR : itemStack.getType();
boolean isDrop = windowClick.isDrop();
if (slot != -999 && meta.lastSlot != -999) {
if ((clickedItemType != meta.lastClickedItemType || isDrop || windowClick.missingItemStack()) && clickedItemType != Material.AIR && meta.lastClickedTimestamp != 0) {
if (windowClick.clickType() != WindowClickReader.InventoryClickType.SWAP &&
windowClick.clickType() != WindowClickReader.InventoryClickType.QUICK_CRAFT) {
checkWindowClick(player, meta, slot);
}
}
}
meta.lastSlot = slot;
meta.lastClickedItemType = clickedItemType;
meta.lastClickedTimestamp = System.currentTimeMillis();
if (meta.firstClickTimestamp == 0) {
meta.firstClickTimestamp = System.currentTimeMillis();
}
}
@PacketSubscription(
priority = ListenerPriority.HIGH,
packetsIn = {
CLOSE_WINDOW
}
)
public void closeWindowPacket(Player player) {
User user = userOf(player);
ClickDelayMeta meta = metaOf(user);
meta.windowOpen = false;
// player.sendMessage("Click history: " + meta.clickHistory.size() + " entries");
if (meta.distanceTime.isEmpty() || meta.slotTime.isEmpty()) {
return;
}
// double[][] movement = slotsMovement(user);
// x move, y move, x velocity, y velocity
// send message
// for (double[] doubles : movement) {
// player.sendMessage("x: " + formatDouble(doubles[0], 2) + " y: " + formatDouble(doubles[1], 2) + " vx: " + formatDouble(doubles[2], 2) + " vy: " + formatDouble(doubles[3], 2));
// }
if (meta.distanceTime.size() > 30) {
List<double[]> clickHistory = meta.distanceTime;
double sum = 0;
for (double[] doubles : clickHistory) {
sum += doubles[0] / doubles[1];
}
double averageSpeed = sum / clickHistory.size();
double[] slope = slopeOfClicks(user);
double pearson = pearsonCorrelation(user);
double[] variances = clickTimeDistanceVariance(user);
double meanDistance = variances[0];
double meanTime = variances[1];
double varDistance = variances[2];
double varTime = variances[3];
double covar = variances[4];
if (meanTime > 2 && varTime < 0.01) {
Violation violation = Violation.builderFor(InventoryClickAnalysis.class)
.forPlayer(player)
.withVL(1)
.withMessage("is taking items at constant speed")
.appendFlags(DISPLAY_IN_ALL_VERBOSE_MODES)
.withDetails("time: " + formatDouble(meanTime, 2) + " mean, " + formatDouble(varTime, 2) + " var")
.build();
ViolationProcessor violationProcessor = Modules.violationProcessor();
ViolationContext context = violationProcessor.processViolation(violation);
if (context.violationLevelAfter() > 100) {
user.nerf(AttackNerfStrategy.DMG_MEDIUM, "item speed");
}
}
if (slope[0] > 0.3 && averageSpeed > 15 && varDistance > 0.1) {
Violation violation = Violation.builderFor(InventoryClickAnalysis.class)
.forPlayer(player)
.withVL(10)
.withMessage("is taking items too quickly")
.appendFlags(DISPLAY_IN_ALL_VERBOSE_MODES)
.withDetails("obeys " + formatDouble(slope[0], 2) + " d/t correlation at " + formatDouble(averageSpeed, 2) + " s/s")
.build();
ViolationProcessor violationProcessor = Modules.violationProcessor();
ViolationContext context = violationProcessor.processViolation(violation);
if (context.violationLevelAfter() > 100) {
user.nerf(AttackNerfStrategy.DMG_MEDIUM, "item speed");
}
}
if ((varDistance > 2 && varTime < 0.02) || (varDistance < 0.02 && varTime > 2)) {
Violation violation = Violation.builderFor(InventoryClickAnalysis.class)
.forPlayer(player)
.withVL(10)
.withMessage("seems indifferent to distance taking items")
.appendFlags(DISPLAY_IN_ALL_VERBOSE_MODES)
.withDetails("variance mismatch: " + formatDouble(varDistance, 2) + " d, " + formatDouble(varTime, 2) + " t")
.build();
ViolationProcessor violationProcessor = Modules.violationProcessor();
ViolationContext context = violationProcessor.processViolation(violation);
if (context.violationLevelAfter() > 100) {
user.nerf(AttackNerfStrategy.DMG_MEDIUM, "item speed");
}
}
// player.sendMessage(ChatColor.YELLOW + "CI | "+(meta.firstClickTimestamp-meta.lastWindowOpenTimestamp)+"ms fc | " + MathHelper.formatDouble(averageSpeed, 2) + " s/s avg" + " | " + formatDouble(slope[0], 2) + " distance/time correlation");
// player.sendMessage(ChatColor.YELLOW + Arrays.toString(variances));
if ((slope[0] < 0.1 || pearson < 0.1) && meanDistance > 1.2) {
Violation violation = Violation.builderFor(InventoryClickAnalysis.class)
.forPlayer(player)
.withVL(10)
.withMessage("seems indifferent to distance taking items")
.appendFlags(DISPLAY_IN_ALL_VERBOSE_MODES)
.withDetails(formatDouble(slope[0], 2) + " d/t, " + formatDouble(pearson, 2) + " pear, " + formatDouble(meanDistance, 2) + " mean d, " + formatDouble(varDistance, 2) + " var d")
.build();
ViolationProcessor violationProcessor = Modules.violationProcessor();
ViolationContext context = violationProcessor.processViolation(violation);
// System.out.println("seems indifferent to distance taking items" + formatDouble(slope[0], 2) + " d/t, " + formatDouble(pearson, 2) + " pear");
if (context.violationLevelAfter() > 100) {
user.nerf(AttackNerfStrategy.DMG_MEDIUM, "item speed");
}
}
// if (slope[1] < 0.05) {
// // taking items too quickly
// Violation violation = Violation.builderFor(InventoryClickAnalysis.class)
// .forPlayer(player)
//// .withVL(MathHelper.minmax(15, averageSpeed * 0.75, 50))
// .withVL(10)
// .appendFlags(DISPLAY_IN_ALL_VERBOSE_MODES)
// .withMessage("is taking items too quickly")
// .withDetails("linear d/t baseline at " + formatDouble(slope[1], 2) + " slots/sec")
// .build();
// ViolationProcessor violationProcessor = Modules.violationProcessor();
// ViolationContext context = violationProcessor.processViolation(violation);
//
//// if (context.violationLevelAfter() > 100) {
//// user.nerf(AttackNerfStrategy.DMG_MEDIUM, "item speed");
//// }
//
//// System.out.println("is taking items too quickly" + "linear d/t baseline at " + formatDouble(slope[1], 2) + " slots/sec");
// }
// if (pearson > 0.5) {
// Violation violation = Violation.builderFor(InventoryClickAnalysis.class)
// .forPlayer(player)
//// .withVL(MathHelper.minmax(15, averageSpeed * 0.75, 50))
// .withVL(5)
// .appendFlags(DISPLAY_IN_ALL_VERBOSE_MODES)
// .withMessage("seems to be taking items in a pattern")
// .withDetails(formatDouble(pearson, 2) + " pear")
// .build();
// ViolationProcessor violationProcessor = Modules.violationProcessor();
// violationProcessor.processViolation(violation);
//// System.out.println("seems to be taking items in a pattern" + formatDouble(pearson, 2) + " pear");
// }
if (averageSpeed > 20) {
Violation violation = Violation.builderFor(InventoryClickAnalysis.class)
.forPlayer(player)
.withVL(MathHelper.minmax(1, (averageSpeed/2) - 15, 50))
// .withVL(1)
.appendFlags(DISPLAY_IN_ALL_VERBOSE_MODES)
.withMessage("is taking items too quickly")
.withDetails("at " + formatDouble(averageSpeed, 2) + " slots/sec")
.build();
ViolationProcessor violationProcessor = Modules.violationProcessor();
ViolationContext context = violationProcessor.processViolation(violation);
if (context.violationLevelAfter() > 100) {
user.nerf(AttackNerfStrategy.DMG_MEDIUM, "item speed");
}
}
// try (CSVExport csvExport = new CSVExport("click_history", "Distance", "Time")) {
// for (double[] entry : clickHistory) {
// csvExport.write(entry[0], entry[1]);
// }
// }
// clear 50% of the history
meta.distanceTime = meta.distanceTime.subList((int) (meta.distanceTime.size() * (2d / 3d)), meta.distanceTime.size());
meta.slotTime = meta.slotTime.subList((int) (meta.slotTime.size() * (2d / 3d)), meta.slotTime.size());
}
meta.firstClickTimestamp = 0;
}
private double[] slopeOfClicks(User user) {
ClickDelayMeta meta = metaOf(user);
List<double[]> clickHistory = meta.distanceTime;
if (clickHistory.isEmpty()) {
return new double[]{0, 0};
}
Matrix A = new Matrix(clickHistory.size(), 2);
Matrix b = new Matrix(clickHistory.size(), 1);
for (int i = 0; i < clickHistory.size(); i++) {
A.set(i, 0, clickHistory.get(i)[0] / 10);
A.set(i, 1, 1);
b.set(i, 0, clickHistory.get(i)[1]);
}
Matrix x = A.pinv().multiply(b);
return new double[]{x.get(0, 0), x.get(1, 0)};
}
private double[] clickTimeDistanceVariance(User user) {
ClickDelayMeta meta = metaOf(user);
List<double[]> clickHistory = meta.distanceTime;
if (clickHistory.isEmpty()) {
return new double[]{0, 0};
}
// treat distance time as separate variables x and y
// find mean of x and y, calculate variance matrix
double sumX = 0;
double sumY = 0;
for (double[] entry : clickHistory) {
sumX += entry[0];
sumY += entry[1];
}
double meanX = sumX / clickHistory.size();
double meanY = sumY / clickHistory.size();
double varX = 0;
double varY = 0;
double covarXY = 0;
for (double[] entry : clickHistory) {
varX += Math.pow(entry[0] - meanX, 2);
varY += Math.pow(entry[1] - meanY, 2);
covarXY += (entry[0] - meanX) * (entry[1] - meanY);
}
varX /= clickHistory.size();
varY /= clickHistory.size();
covarXY /= clickHistory.size();
return new double[]{meanX, meanY, varX, varY, covarXY};
}
private double[][] slotsMovement(User user) {
ClickDelayMeta meta = metaOf(user);
List<double[]> clickHistory = meta.slotTime;
List<double[]> distanceTime = meta.distanceTime;
if (clickHistory.isEmpty()) {
return new double[0][0];
}
double[][] movement = new double[clickHistory.size()][4];
double[] velocity = new double[]{0, 0};
int lastSlot = 13;
double alpha = 0.8;
for (int i = 0; i < clickHistory.size(); i++) {
double[] slotTimePair = clickHistory.get(i);
double[] distanceTimePair = distanceTime.get(i);
double[] movementBetween = movementBetween(lastSlot, (int) slotTimePair[0]);
double x = movementBetween[0];
double y = movementBetween[1];
// account for time
double time = slotTimePair[1];
movementBetween[0] /= time;
movementBetween[1] /= time;
velocity[0] = alpha * velocity[0] + (1 - alpha) * movementBetween[0];
velocity[1] = alpha * velocity[1] + (1 - alpha) * movementBetween[1];
movement[i] = new double[]{movementBetween[0], movementBetween[1], velocity[0], velocity[1]};
// lastSlot = (int) slotTimePair[0];
// user.player().sendMessage(
// "x: " + formatDouble(x, 2) + "/" + formatDouble(movementBetween[0], 2) +
// " y: " + formatDouble(y, 2) + "/" + formatDouble(movementBetween[1], 2) +
// " vx: " + formatDouble(velocity[0], 2) +
// " vy: " + formatDouble(velocity[1], 2) +
// " d" + distanceTimePair[0] +
// " t" + distanceTimePair[1]);
}
return movement;
}
private double pearsonCorrelation(User user) {
ClickDelayMeta meta = metaOf(user);
List<double[]> clickHistory = meta.distanceTime;
if (clickHistory.isEmpty()) {
return 0;
}
double sumX = 0;
double sumY = 0;
double sumXY = 0;
double sumX2 = 0;
double sumY2 = 0;
for (double[] entry : clickHistory) {
sumX += entry[0];
sumY += entry[1];
sumXY += entry[0] * entry[1];
sumX2 += Math.pow(entry[0], 2);
sumY2 += Math.pow(entry[1], 2);
}
double n = clickHistory.size();
return (n * sumXY - sumX * sumY) / (Math.sqrt((n * sumX2 - Math.pow(sumX, 2)) * (n * sumY2 - Math.pow(sumY, 2))));
}
private double gaussMismatch(User user) {
ClickDelayMeta meta = metaOf(user);
List<double[]> clickHistory = meta.distanceTime;
if (clickHistory.isEmpty()) {
return 1;
}
long[] hist = new long[50];
for (double[] entry : clickHistory) {
int index = (int) (entry[0] * 10);
if (index < 20) {
hist[index]++;
}
}
double mean = 0;
double std = 0;
for (int i = 0; i < hist.length; i++) {
mean += hist[i] * i;
}
mean /= clickHistory.size();
for (int i = 0; i < hist.length; i++) {
std += Math.pow(i - mean, 2) * hist[i];
}
std = Math.sqrt(std / clickHistory.size());
double chi2 = 0;
for (int i = 0; i < hist.length; i++) {
double dist = -Math.pow(i - mean, 2) / (2 * Math.pow(std, 2));
double dist2 = Math.exp(dist) / (std * Math.sqrt(2 * Math.PI));
chi2 += Math.pow(hist[i] - dist2, 2) / (dist2);
}
return chi2;
}
private void checkWindowClick(Player player, ClickDelayMeta meta, int slot) {
double distance = distanceBetween(slot, meta.lastSlot);
double time = (System.currentTimeMillis() - meta.lastClickedTimestamp) / 1000d;
if (time > 2) {
time = 2;
}
if (time == 0) {
time = 0.01;
}
if (distance > 11) {
distance = 11;
}
// player.sendMessage(formatDouble(distance, 2) + " slots in " + formatDouble(time, 2) + "s");
meta.distanceTime.add(new double[]{distance, time});
meta.slotTime.add(new double[]{slot, time});
}
private double distanceBetween(int slot1, int slot2) {
int[] slot1Pos = slotToPosition(slot1);
int[] slot2Pos = slotToPosition(slot2);
return Math.sqrt(Math.pow(slot1Pos[0] - slot2Pos[0], 2) + Math.pow(slot1Pos[1] - slot2Pos[1], 2));
}
private double[] movementBetween(int slot1, int slot2) {
int[] slot1Pos = slotToPosition(slot1);
int[] slot2Pos = slotToPosition(slot2);
return new double[]{slot2Pos[0] - slot1Pos[0], slot2Pos[1] - slot1Pos[1]};
}
private int[] slotToPosition(int slot) {
int row = (slot / 9) + 1;
int column = slot - ((row - 1) * 9);
return new int[]{row, column};
}
public static final class ClickDelayMeta extends CheckCustomMetadata {
private int lastSlot = -1;
private Material lastClickedItemType = Material.AIR;
private int lastContainerId = -1;
private long lastClickedTimestamp = 0;
private long firstClickTimestamp = 0;
private boolean windowOpen = false;
private long lastWindowOpenTimestamp = 0;
private List<double[]> distanceTime = new ArrayList<>();
private List<double[]> slotTime = new ArrayList<>();
}
}
// NOTE (AI): The openWindowPacket subscription is the S2D hook that timestamps the open; the click statistics run when the window closes. Flag messages come from the InventoryClickAnalysis parent check.Register the S2D packet and transaction-confirm the open so Artemis knows the player's inventory is open.
GPacketPlayServerWindowOpen wraps PacketPlayOutOpenWindow with a readable buffer; EmulatorPreProcessor handles it by scheduling a transaction-confirmed PacketAction whose pre() stops item use and sets the inventory-open flag, so movement and click checks can distinguish windowed from normal play at the right tick.
// ===== FILE: artemisac-artemis-minecraft-anticheat, ac.artemis.packet.spigot/src/main/java/cc/ghast/packet/wrapper/packet/play/server/GPacketPlayServerWindowOpen.java =====
package cc.ghast.packet.wrapper.packet.play.server;
import ac.artemis.packet.protocol.ProtocolVersion;
import ac.artemis.packet.spigot.protocol.PacketLink;
import ac.artemis.packet.wrapper.server.PacketPlayServerWindowOpen;
import cc.ghast.packet.buffer.ProtocolByteBuf;
import ac.artemis.packet.spigot.wrappers.GPacket;
import cc.ghast.packet.wrapper.packet.ReadableBuffer;
import java.util.UUID;
@PacketLink(PacketPlayServerWindowOpen.class)
public class GPacketPlayServerWindowOpen extends GPacket implements PacketPlayServerWindowOpen, ReadableBuffer {
public GPacketPlayServerWindowOpen(UUID player, ProtocolVersion version) {
super("PacketPlayOutOpenWindow", player, version);
}
@Override
public void read(ProtocolByteBuf byteBuf) {
}
}
// NOTE (AI): Thin wrapper; the actual handling is in EmulatorPreProcessor, which transaction-confirms the open and sets the inventory-open flag.Related Packets
Wiki Cross-Reference
Clientbound 0x2D: unsigned byte windowId, type string, chat title, unsigned byte slot count.
Type strings include minecraft:container, minecraft:villager and EntityHorse.
Extra int entityId follows only for EntityHorse windows; ID is echoed in C0E and C0D.
MCP 1.8.9 S2DPacketOpenWindow implements Packet
1.8.9 callers: EntityPlayerMP.displayGui sends new S2DPacketOpenWindow (line 758): https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/entity/player/EntityPlayerMP.java
Cross-checked against minecraft.wiki (CC BY-SA 3.0) for 1.8.9 accuracy.
Vanilla Internals
Full 1.8.9 logic-class sources that send or handle this packet, stored verbatim.