0x01 S01PacketJoinGame
Welcomes the player into the world. Sends entity ID, gamemode, dimension, difficulty, max players, world type, and reduced debug info.
Published 2026-06-18 · Updated 2026-10-14
Fields
| Field | Type | Description |
|---|---|---|
| entityId | int | The player's own entity ID |
| gamemode | unsigned byte | 0=survival, 1=creative, 2=adventure, 3=spectator |
| dimension | byte | -1=nether, 0=overworld, 1=end |
| difficulty | unsigned byte | Server difficulty (0-3) |
| maxPlayers | unsigned byte | Max players (used to draw tab player list) |
| worldType | String | 'default', 'flat', 'largeBiomes', 'amplified', 'customized' |
| reducedDebugInfo | boolean | Whether to hide coordinates in F3 debug screen |
Wire Encoding
| Field | Type | Notes |
|---|---|---|
| Entity ID | int | Player's own entity ID on the server |
| Gamemode | unsigned byte | 0=survival, 1=creative, 2=adventure, 3=spectator |
| Dimension | byte | -1=nether, 0=overworld, 1=end |
| Difficulty | unsigned byte | 0=peaceful, 1=easy, 2=normal, 3=hard |
| Max Players | unsigned byte | Used for tab list rendering |
| Level Type | String | 'default', 'flat', 'largeBiomes', 'amplified', 'customized' |
| Reduced Debug Info | boolean | If true, hides coords from F3 |
MCP References
NetHandlerPlayClient.handleJoinGame()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 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
Deobfuscated MCP 1.8.9 source of S01PacketJoinGame, fetched directly from Marcelektro/MavenMCP-1.8.9 (net/minecraft/network/play/server/S01PacketJoinGame.java) at build time and verified present.
Deep Dive
Role in the protocol
The first PLAY-state packet and the world-join trigger. ServerConfigurationManager sends it as the final step of player placement: new S01PacketJoinGame(entityId, gameType, hardcore, dimension, difficulty, maxPlayers, worldType, reducedDebugInfo). The client handler is where the world is born: NetHandlerPlayClient.handleJoinGame creates the PlayerControllerMP and WorldClient from the packet's world type and dimension, calls loadWorld, sets the player's entity id and dimension, shows GuiDownloadTerrain, and replies with the MC|Brand custom payload. Everything that needs mc.theWorld or mc.thePlayer non-null waits on this packet.
Vanilla handling
handleJoinGame first runs PacketThreadUtil.checkThreadAndEnqueue, which in the Rise 6.x and Tenacity trees special-cases S01PacketJoinGame in clientPreProcessPacket so the world creation is guaranteed on the main thread. Then: this.gameController.playerController = new PlayerControllerMP(...), this.clientWorldController = new WorldClient(this, new WorldSettings(...), ...), loadWorld, dimension and entity id assignment, currentServerMaxPlayers, reduced-debug flag, game type set, settings re-sent, and the C17PacketCustomPayload MC|Brand reply. After that the server streams chunks and the respawn/spawn chain.
Why clients touch it
Three non-vanilla references exist in the corpus. NetworkAPI (script api) lists S01PacketJoinGame.class at index 1 of its clientbound packet table, so JavaScript scripts can construct and inject it and can key script logic off world join. VulcanSpeed (movement/speed) imports the class but never uses it: the reference is a dead import. LiquidSense Dev's MixinNetHandlerPlayClient injects at handleJoinGame HEAD, cancellable, and re-runs the whole world-creation sequence itself when AntiForge blockFML is enabled, so the stock (Forge-aware) handler never executes. The clients that need join-time resets (Rise 5.99's WorldChangedEvent, Sigma's event system) fire their own world-change events from elsewhere rather than hooking this packet.
Exploit surface
S01PacketJoinGame carries no movement data, so anti-cheats ignore it; its value is state. A module that misorders its join handling can inherit stale state: old entity id, wrong dimension, or a game type that contradicts the client's PlayerControllerMP. The vanilla handler is also the moment the client reveals its brand via MC|Brand, which server plugins use for client detection. Script-injected S01 packets (NetworkAPI receivePacket) let a script replay a join outside the normal flow, which desynchronizes client and server state; none of the 8 clients ships a module that does this.
Server-Side Handling
ServerConfigurationManager.initializeConnectionToPlayer builds the S01 payload from the player's game type, hardcore flag, the world provider's dimension id, difficulty, server max players, terrain type, and the reducedDebugInfo gamerule, then sends it as the first packet of the PLAY stream. The server then follows with S41PacketServerDifficulty, spawn position, and the chunk bulk. The client's MC|Brand reply arrives as C17PacketCustomPayload and is how vanilla records the client mod name.
Protocol Analysis
Wire layout: int entityId, unsigned byte gamemode, byte dimension (signed: -1 nether, 0 overworld, 1 end), unsigned byte difficulty, unsigned byte maxPlayers, String worldType, boolean reducedDebugInfo. Ordering constraint: S01 is the very first PLAY-state packet; the client transitions the connection into PLAY on login success and expects S01 before any world-bearing packet. Re-sent on dimension change only via the respawn path, never as a plain re-join.
Anti-Cheat Landscape
No anti-cheat measures this packet; it precedes position tracking. The security-relevant detail is the MC|Brand exchange immediately after it: brand-based client detection is a server plugin reading the C17 reply, and clients that want to hide their brand forge that packet, not this one. State-reset discipline after S01 matters for movement modules (fresh timer baselines), which is the reason Rise 6.x scripts hook it.
implementation Implementation Cases
The world-join packet: vanilla handleJoinGame constructs the entire client world from its fields. Module interest is minimal in the corpus: Rise 6.x exposes it to scripts via NetworkAPI, one Rise 6.2.4 speed mode carries a dead import, and LiquidSense Dev re-implements the handler in a cancellable mixin for AntiForge blockFML. World-change events in the other clients fire from their own infrastructure.
Expose S01PacketJoinGame to JavaScript scripts: scripts can detect world join and inject or read the packet through the Network API object.
NetworkAPI keeps two Class arrays indexed by packet id (serverbound and clientbound). S01PacketJoinGame sits at clientbound index 1. instantiatePacket picks the constructor matching the argument count and either sends the packet through addToSendQueue or injects it into the receive queue via addToReceiveQueue; scripts call Network.receivePacket(1, params) to synthesize a join packet client-side.
// ===== FILE: Rise 6.2.4, Client-release2/Client/src/main/java/com/alan/clients/script/api/NetworkAPI.java =====
package com.alan.clients.script.api;
import com.alan.clients.util.chat.ChatUtil;
import lombok.SneakyThrows;
import net.minecraft.network.EnumPacketDirection;
import net.minecraft.network.Packet;
import net.minecraft.network.play.INetHandlerPlayClient;
import net.minecraft.network.play.INetHandlerPlayServer;
import net.minecraft.network.play.client.*;
import net.minecraft.network.play.server.*;
import javax.script.ScriptException;
import java.util.Arrays;
public class NetworkAPI extends API {
public final static Class<Packet<INetHandlerPlayServer>>[] serverbound = new Class[]{
C00PacketKeepAlive.class,
C01PacketChatMessage.class,
C02PacketUseEntity.class,
C03PacketPlayer.class,
C03PacketPlayer.C04PacketPlayerPosition.class,
C03PacketPlayer.C05PacketPlayerLook.class,
C03PacketPlayer.C06PacketPlayerPosLook.class,
C07PacketPlayerDigging.class,
C08PacketPlayerBlockPlacement.class,
C09PacketHeldItemChange.class,
C0APacketAnimation.class,
C0BPacketEntityAction.class,
C0CPacketInput.class,
C0DPacketCloseWindow.class,
C0EPacketClickWindow.class,
C0FPacketConfirmTransaction.class,
C10PacketCreativeInventoryAction.class,
C11PacketEnchantItem.class,
C12PacketUpdateSign.class,
C13PacketPlayerAbilities.class,
C14PacketTabComplete.class,
C15PacketClientSettings.class,
C16PacketClientStatus.class,
C17PacketCustomPayload.class,
C18PacketSpectate.class,
C19PacketResourcePackStatus.class,
};
public final static Class<Packet<INetHandlerPlayClient>>[] clientbound = new Class[]{
S00PacketKeepAlive.class,
S01PacketJoinGame.class,
S02PacketChat.class,
S03PacketTimeUpdate.class,
S04PacketEntityEquipment.class,
S05PacketSpawnPosition.class,
S06PacketUpdateHealth.class,
S07PacketRespawn.class,
S08PacketPlayerPosLook.class,
S09PacketHeldItemChange.class,
S0APacketUseBed.class,
S0BPacketAnimation.class,
S0CPacketSpawnPlayer.class,
S0DPacketCollectItem.class,
S0EPacketSpawnObject.class,
S0FPacketSpawnMob.class,
S10PacketSpawnPainting.class,
S11PacketSpawnExperienceOrb.class,
S12PacketEntityVelocity.class,
S13PacketDestroyEntities.class,
S14PacketEntity.class,
S18PacketEntityTeleport.class,
S19PacketEntityHeadLook.class,
S19PacketEntityStatus.class,
S1BPacketEntityAttach.class,
S1CPacketEntityMetadata.class,
S1DPacketEntityEffect.class,
S1EPacketRemoveEntityEffect.class,
S1FPacketSetExperience.class,
S20PacketEntityProperties.class,
S21PacketChunkData.class,
S22PacketMultiBlockChange.class,
S23PacketBlockChange.class,
S24PacketBlockAction.class,
S25PacketBlockBreakAnim.class,
S26PacketMapChunkBulk.class,
S27PacketExplosion.class,
S28PacketEffect.class,
S29PacketSoundEffect.class,
S2APacketParticles.class,
S2BPacketChangeGameState.class,
S2CPacketSpawnGlobalEntity.class,
S2DPacketOpenWindow.class,
S2EPacketCloseWindow.class,
S2FPacketSetSlot.class,
S30PacketWindowItems.class,
S31PacketWindowProperty.class,
S32PacketConfirmTransaction.class,
S33PacketUpdateSign.class,
S34PacketMaps.class,
S35PacketUpdateTileEntity.class,
S36PacketSignEditorOpen.class,
S37PacketStatistics.class,
S38PacketPlayerListItem.class,
S39PacketPlayerAbilities.class,
S3APacketTabComplete.class,
S3BPacketScoreboardObjective.class,
S3CPacketUpdateScore.class,
S3DPacketDisplayScoreboard.class,
S3EPacketTeams.class,
S3FPacketCustomPayload.class,
S40PacketDisconnect.class,
S41PacketServerDifficulty.class,
S42PacketCombatEvent.class,
S43PacketCamera.class,
S44PacketWorldBorder.class,
S45PacketTitle.class,
S46PacketSetCompressionLevel.class,
S47PacketPlayerListHeaderFooter.class,
S48PacketResourcePackSend.class,
S49PacketUpdateEntityNBT.class
};
@SneakyThrows
private static Packet<?> instantiatePacket(final EnumPacketDirection direction, final int id, final Object... params) {
Packet<?> packet = null;
try {
if (direction == EnumPacketDirection.CLIENTBOUND) {
packet = (Packet<?>) Arrays.stream(clientbound[id].getConstructors()).filter(x -> x.getParameterCount() == params.length).findFirst().get().newInstance(params);
} else if (direction == EnumPacketDirection.SERVERBOUND) {
packet = (Packet<?>) Arrays.stream(serverbound[id].getConstructors()).filter(x -> x.getParameterCount() == params.length).findFirst().get().newInstance(params);
}
} catch (Exception ex) {
ChatUtil.display("Failed to instantiate packet!");
throw new ScriptException(ex);
}
return packet;
}
public void sendPacket(final int id, final Object... params) {
final Packet<?> packet = instantiatePacket(EnumPacketDirection.SERVERBOUND, id, params);
MC.getNetHandler().addToSendQueue(packet);
}
public void receivePacket(final int id, final Object... params) {
final Packet<?> packet = instantiatePacket(EnumPacketDirection.CLIENTBOUND, id, params);
MC.getNetHandler().addToReceiveQueue(packet);
}
public boolean isSingleplayer() {
return MC.isSingleplayer();
}
public boolean isMultiplayer() {
return !MC.isSingleplayer() && MC.getCurrentServerData() != null;
}
public String getServerIP() {
return MC.getCurrentServerData() != null
? MC.getCurrentServerData().serverIP
: null;
}
public String getServerName() {
return MC.getCurrentServerData() != null
? MC.getCurrentServerData().serverName
: null;
}
public String getServerMOTD() {
return MC.getCurrentServerData() != null
? MC.getCurrentServerData().serverMOTD
: null;
}
}
// NOTE (AI): The clientbound Class array is indexed by packet id, so S01PacketJoinGame sits at index 1 and scripts can construct or inject it via Network.receivePacket(1, params).
// NOTE (AI): This is the only functional (non-import) module reference to S01PacketJoinGame in the 8-client corpus. The same API file also lists S02PacketChat at index 2, which is why it appears in both corpora.
// NOTE (AI): instantiatePacket resolves the constructor by parameter count and reflects a new instance; failures surface as a ScriptException after a ChatUtil.display error line, keeping script errors off the critical path.
A Vulcan-server speed mode; its only link to this packet is an unused import.
The corpus hit is line 28, `import net.minecraft.network.play.server.S01PacketJoinGame;`, and a grep of the whole file confirms no other occurrence: the import is dead. The mode itself implements a Vulcan bypass via block-placement tricks (C08PacketPlayerBlockPlacement against BlockAir checks) and never reads join state.
Re-implement NetHandlerPlayClient.handleJoinGame at the mixin level so LiquidBounce joins without the stock handler, backing the AntiForge blockFML mode.
handleJoinGameWithAntiForge injects at handleJoinGame HEAD, cancellable. When AntiForge.enabled and blockFML are on (and the world is not singleplayer) it runs the entire vanilla world-creation sequence itself: new PlayerControllerMP, new WorldClient from packetIn's dimension/difficulty/world type, loadWorld, entity id and dimension assignment, max players, reduced-debug flag, game type, settings re-sent, then the MC|Brand C17PacketCustomPayload reply, and cancels the vanilla method so the default handler never runs.
// ===== FILE: LiquidSense Dev, net/ccbluex/liquidbounce/injection/forge/mixins/network/MixinNetHandlerPlayClient.java =====
/*
* LiquidBounce Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
* https://github.com/CCBlueX/LiquidBounce/
*/
package net.ccbluex.liquidbounce.injection.forge.mixins.network;
import io.netty.buffer.Unpooled;
import net.ccbluex.liquidbounce.LiquidBounce;
import net.ccbluex.liquidbounce.event.EntityMovementEvent;
import net.ccbluex.liquidbounce.event.PacketSenEvent;
import net.ccbluex.liquidbounce.features.module.modules.movement.Fly;
import net.ccbluex.liquidbounce.features.special.AntiForge;
import net.ccbluex.liquidbounce.utils.ClientUtils;
import net.minecraft.client.ClientBrandRetriever;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiDownloadTerrain;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.client.multiplayer.WorldClient;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.network.*;
import net.minecraft.network.play.client.C0FPacketConfirmTransaction;
import net.minecraft.network.play.client.C17PacketCustomPayload;
import net.minecraft.network.play.client.C19PacketResourcePackStatus;
import net.minecraft.network.play.server.S01PacketJoinGame;
import net.minecraft.network.play.server.S14PacketEntity;
import net.minecraft.network.play.server.S32PacketConfirmTransaction;
import net.minecraft.network.play.server.S48PacketResourcePackSend;
import net.minecraft.world.WorldSettings;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import java.net.URI;
import java.net.URISyntaxException;
@Mixin(NetHandlerPlayClient.class)
public abstract class MixinNetHandlerPlayClient {
@Shadow
@Final
private NetworkManager netManager;
@Shadow
private Minecraft gameController;
@Shadow
private WorldClient clientWorldController;
@Shadow
public int currentServerMaxPlayers;
@Inject(method = "handleResourcePack", at = @At("HEAD"), cancellable = true)
private void handleResourcePack(final S48PacketResourcePackSend p_handleResourcePack_1_, final CallbackInfo callbackInfo) {
final String url = p_handleResourcePack_1_.getURL();
final String hash = p_handleResourcePack_1_.getHash();
try {
final String scheme = new URI(url).getScheme();
final boolean isLevelProtocol = "level".equals(scheme);
if(!"http".equals(scheme) && !"https".equals(scheme) && !isLevelProtocol)
throw new URISyntaxException(url, "Wrong protocol");
if(isLevelProtocol && (url.contains("..") || !url.endsWith("/resources.zip")))
throw new URISyntaxException(url, "Invalid levelstorage resourcepack path");
}catch(final URISyntaxException e) {
ClientUtils.getLogger().error("Failed to handle resource pack", e);
netManager.sendPacket(new C19PacketResourcePackStatus(hash, C19PacketResourcePackStatus.Action.FAILED_DOWNLOAD));
callbackInfo.cancel();
}
}
@Inject(method = "handleJoinGame", at = @At("HEAD"), cancellable = true)
private void handleJoinGameWithAntiForge(S01PacketJoinGame packetIn, final CallbackInfo callbackInfo) {
if(!AntiForge.enabled || !AntiForge.blockFML || Minecraft.getMinecraft().isIntegratedServerRunning())
return;
PacketThreadUtil.checkThreadAndEnqueue(packetIn, (NetHandlerPlayClient) (Object) this, gameController);
this.gameController.playerController = new PlayerControllerMP(gameController, (NetHandlerPlayClient) (Object) this);
this.clientWorldController = new WorldClient((NetHandlerPlayClient) (Object) this, new WorldSettings(0L, packetIn.getGameType(), false, packetIn.isHardcoreMode(), packetIn.getWorldType()), packetIn.getDimension(), packetIn.getDifficulty(), this.gameController.mcProfiler);
this.gameController.gameSettings.difficulty = packetIn.getDifficulty();
this.gameController.loadWorld(this.clientWorldController);
this.gameController.thePlayer.dimension = packetIn.getDimension();
this.gameController.displayGuiScreen(new GuiDownloadTerrain((NetHandlerPlayClient) (Object) this));
this.gameController.thePlayer.setEntityId(packetIn.getEntityId());
this.currentServerMaxPlayers = packetIn.getMaxPlayers();
this.gameController.thePlayer.setReducedDebug(packetIn.isReducedDebugInfo());
this.gameController.playerController.setGameType(packetIn.getGameType());
this.gameController.gameSettings.sendSettingsToServer();
this.netManager.sendPacket(new C17PacketCustomPayload("MC|Brand", (new PacketBuffer(Unpooled.buffer())).writeString(ClientBrandRetriever.getClientModName())));
callbackInfo.cancel();
}
@Inject(method = "handleEntityMovement", at = @At(value = "FIELD", target = "Lnet/minecraft/entity/Entity;onGround:Z"))
private void handleEntityMovementEvent(S14PacketEntity packetIn, final CallbackInfo callbackInfo) {
final Entity entity = packetIn.getEntity(this.clientWorldController);
if(entity != null)
LiquidBounce.eventManager.callEvent(new EntityMovementEvent(entity));
}
@Inject(method = "addToSendQueue", at = @At("HEAD"), cancellable = true)
private void senpacket(Packet<?> packet, final CallbackInfo callbackInfo) {
final PacketSenEvent event = new PacketSenEvent(packet);
LiquidBounce.eventManager.callEvent(event);
if (event.isCancelled()) {
callbackInfo.cancel();
}
}
@Overwrite
public void handleConfirmTransaction(S32PacketConfirmTransaction packetIn) {
PacketThreadUtil.checkThreadAndEnqueue((Packet)packetIn, (INetHandler)this, this.gameController);
Container container = null;
EntityPlayerSP entityplayer = Minecraft.getMinecraft().thePlayer;
if (packetIn.getWindowId() == 0) {
container = entityplayer.inventoryContainer;
} else if (packetIn.getWindowId() == entityplayer.openContainer.windowId) {
container = entityplayer.openContainer;
}
if (container != null && !packetIn.func_148888_e()) {
Minecraft.getMinecraft().getNetHandler().addToSendQueue(new C0FPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true));
}
}
}
// NOTE (AI): The mixin duplicates vanilla handleJoinGame field-for-field and cancels the original, which is how LiquidBounce joins Forge servers with blockFML without tripping the FML handshake. The same file carries the client's generic packet pipeline (PacketSenEvent on addToSendQueue, PacketEvent on channelRead0) and an @Overwrite of handleConfirmTransaction that acks window-0 and open-container transactions directly.anticheat Anti-Cheat Checks
Server-side anticheats treat the join-game packet as the state anchor of a play session. It carries no movement or combat data, so no check flags it; instead the packet re-reads the player model (entity id, gamemode, dimension, world name) in modern simulation anticheats, while classic anticheats watch the login events that surround the join. The security-relevant detail is what the packet resets: any anticheat that keeps per-player state must re-arm it here or every later check inherits stale data.
Re-sync the simulated player model to the join-game payload: entity id, gamemode, dimension, world name and the death-screen flag.
PacketPlayerRespawn listens on PacketSendEvent with HIGH priority. The JOIN_GAME branch wraps the packet as WrapperPlayServerJoinGame, copies entityId, gamemode, dimensionType and worldName into the GrimPlayer, sets showsDeathScreen from isRespawnScreenEnabled on 1.15+ clients, and re-arms the compensated world dimension on 1.17+ servers. The same listener owns the respawn and update-health branches, so this file is the single state-reset point for the whole session lifecycle.
// ===== FILE: GrimAnticheat-Grim, common/src/main/java/ac/grim/grimac/events/packets/PacketPlayerRespawn.java =====
package ac.grim.grimac.events.packets;
import ac.grim.grimac.GrimAPI;
import ac.grim.grimac.checks.impl.badpackets.*;
import ac.grim.grimac.checks.impl.elytra.ElytraC;
import ac.grim.grimac.player.GrimPlayer;
import ac.grim.grimac.utils.data.KnownInput;
import ac.grim.grimac.utils.data.SprintingState;
import ac.grim.grimac.utils.data.TrackerData;
import ac.grim.grimac.utils.data.packetentity.PacketEntitySelf;
import ac.grim.grimac.utils.enums.Pose;
import ac.grim.grimac.utils.math.Vector3dm;
import com.github.retrooper.packetevents.PacketEvents;
import com.github.retrooper.packetevents.event.PacketListenerAbstract;
import com.github.retrooper.packetevents.event.PacketListenerPriority;
import com.github.retrooper.packetevents.event.PacketSendEvent;
import com.github.retrooper.packetevents.manager.server.ServerVersion;
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.player.ClientVersion;
import com.github.retrooper.packetevents.util.Vector3d;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerJoinGame;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerRespawn;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerUpdateHealth;
import java.util.Objects;
/**
* PlayerRespawnS2CPacket info (1.20.2+):
* If the world is different (check via registry key), world is recreated (all entities etc destroyed).
* <p>
* Client player is ALWAYS recreated
* <p>
* If the packet has the `KEEP_TRACKED_DATA` flag:
* Sneaking and Sprinting fields are kept on the new client player.
* <p>
* If the packet has the `KEEP_ATTRIBUTES` flag:
* Attributes are kept.
* <p>
* New client player is initialised:
* Pose is set to standing.
* Velocity is set to zero.
* Pitch is set to 0.
* Yaw is set to -180.
*/
// TODO update for 1.20.2-
public class PacketPlayerRespawn extends PacketListenerAbstract {
private static final byte KEEP_ATTRIBUTES = 1;
private static final byte KEEP_TRACKED_DATA = 2;
private static final byte KEEP_ALL = 3;
public PacketPlayerRespawn() {
super(PacketListenerPriority.HIGH);
}
private boolean hasFlag(WrapperPlayServerRespawn respawn, byte flag) {
// This packet was added in 1.16
if (flag == KEEP_ATTRIBUTES) {
// On versions older than 1.15, via does not keep all attributes.
// https://github.com/ViaVersion/ViaVersion/blob/master/common/src/main/java/com/viaversion/viaversion/protocols/v1_15_2to1_16/rewriter/EntityPacketRewriter1_16.java#L124
if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_15)) {
return false;
}
} else if (flag == KEEP_TRACKED_DATA) {
// But for metadata, via DOES keep all data
if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_15)) {
return true;
}
}
return (respawn.getKeptData() & flag) != 0;
}
@Override
public void onPacketSend(PacketSendEvent event) {
if (event.getPacketType() == PacketType.Play.Server.UPDATE_HEALTH) {
WrapperPlayServerUpdateHealth health = new WrapperPlayServerUpdateHealth(event);
GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getUser());
if (player == null) return;
//
if (player.packetStateData.lastFood == health.getFood()
&& player.packetStateData.lastHealth == health.getHealth()
&& player.packetStateData.lastSaturation == health.getFoodSaturation()
&& PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_9))
return;
player.packetStateData.lastFood = health.getFood();
player.packetStateData.lastHealth = health.getHealth();
player.packetStateData.lastSaturation = health.getFoodSaturation();
player.sendTransaction();
if (health.getFood() == 20) { // Split so transaction before packet
player.latencyUtils.addRealTimeTask(player.lastTransactionReceived.get(), () -> player.food = 20);
} else { // Split so transaction after packet
player.latencyUtils.addRealTimeTask(player.lastTransactionReceived.get() + 1, () -> player.food = health.getFood());
}
if (health.getHealth() <= 0) {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get(), () -> {
player.compensatedEntities.self.isDead = true;
player.checkManager.getCheck(BadPacketsM.class).onDeath();
});
} else {
player.latencyUtils.addRealTimeTask(player.lastTransactionSent.get() + 1, () -> player.compensatedEntities.self.isDead = false);
}
event.getTasksAfterSend().add(player::sendTransaction);
}
if (event.getPacketType() == PacketType.Play.Server.JOIN_GAME) {
GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getUser());
if (player == null) return;
WrapperPlayServerJoinGame joinGame = new WrapperPlayServerJoinGame(event);
player.gamemode = joinGame.getGameMode();
player.entityID = joinGame.getEntityId();
player.dimensionType = joinGame.getDimensionType();
player.worldName = joinGame.getWorldName();
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_15)
&& event.getServerVersion().isNewerThanOrEquals(ServerVersion.V_1_15)) {
player.packetStateData.showsDeathScreen = joinGame.isRespawnScreenEnabled();
}
if (PacketEvents.getAPI().getServerManager().getVersion().isOlderThan(ServerVersion.V_1_17))
return;
player.compensatedWorld.setDimension(joinGame.getDimensionType(), event.getUser());
}
if (event.getPacketType() == PacketType.Play.Server.RESPAWN) {
WrapperPlayServerRespawn respawn = new WrapperPlayServerRespawn(event);
GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getUser());
if (player == null) return;
player.sendTransaction();
event.getTasksAfterSend().add(player::sendTransaction);
// Force the player to accept a teleport before respawning
// (We won't process movements until they accept a teleport, we won't let movements though either)
// Also invalidate previous positions
player.getSetbackTeleportUtil().hasAcceptedSpawnTeleport = false;
player.getSetbackTeleportUtil().lastKnownGoodPosition = null;
// clear server entity positions when the world changes
if (isWorldChange(player, respawn)) {
player.compensatedEntities.serverPositionsMap.clear();
}
player.addRealTimeTaskNow(player.cameraEntity::reset);
player.addRealTimeTaskNext(() -> {
// From 1.16 to 1.19, this doesn't get set to false for whatever reason
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_16) || player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_20)) {
player.isSneaking = false;
}
player.lastOnGround = false;
player.clientClaimsLastOnGround = false;
player.onGround = false;
player.isInBed = false;
player.packetStateData.setSlowedByUsingItem(false);
player.packetStateData.packetPlayerOnGround = false; // If somewhere else pulls last ground to fix other issues
player.packetStateData.lastClaimedPosition = new Vector3d();
player.filterMojangStupidityOnMojangStupidity.zero();
player.checkManager.getCheck(BadPacketsM.class).onRespawn();
final boolean keepTrackedData = this.hasFlag(respawn, KEEP_TRACKED_DATA);
if (!keepTrackedData) {
player.food = 20;
player.powderSnowFrozenTicks = 0;
player.compensatedEntities.self.hasGravity = true;
player.playerEntityHasGravity = true;
player.packetStateData.knownInput = KnownInput.DEFAULT;
player.checkManager.getCheck(ElytraC.class).exempt = true;
// 1.19.4 uses current sprinting, older versions use last sprinting
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_19_4)) {
player.isSprinting = false;
player.vehicleData.camelSprintingState = SprintingState.STOPPED;
} else {
player.lastSprintingForSpeed = false;
}
}
player.checkManager.getCheck(BadPacketsE.class).handleRespawn(); // Reminder ticks reset
player.checkManager.getCheck(BadPacketsG.class).handleRespawn();
// compensate for immediate respawn gamerule
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_15)) {
player.checkManager.getCheck(BadPacketsF.class).exemptNext = true;
}
// EVERYTHING gets reset on a cross dimensional teleport, clear chunks and entities!
if (isWorldChange(player, respawn)) {
player.compensatedEntities.entityMap.clear();
player.compensatedWorld.activePistons.clear();
player.compensatedWorld.openShulkerBoxes.clear();
player.compensatedWorld.chunks.clear();
player.compensatedGeysers.clear();
player.compensatedWorld.isRaining = false;
player.checkManager.getCheck(BadPacketsH.class).onWorldChange();
}
player.dimensionType = respawn.getDimensionType();
player.worldName = respawn.getWorldName().orElse(null);
player.compensatedEntities.serverPlayerVehicle = null; // All entities get removed on respawn
player.compensatedEntities.self = new PacketEntitySelf(player, player.compensatedEntities.self);
player.compensatedEntities.selfTrackedEntity = new TrackerData(0, 0, 0, 0, 0, EntityTypes.PLAYER, player.lastTransactionSent.get());
player.cameraEntity.reset();
if (player.getClientVersion().isOlderThan(ClientVersion.V_1_14)) { // 1.14+ players send a packet for this, listen for it instead
player.isSprinting = false;
player.vehicleData.camelSprintingState = SprintingState.STOPPED;
player.checkManager.getCheck(BadPacketsF.class).lastSprinting = false; // Pre 1.14 clients set this to false when creating new entity
// TODO: What the fuck viaversion, why do you throw out keep all metadata?
// The server doesn't even use it... what do we do?
player.compensatedEntities.hasSprintingAttributeEnabled = false;
}
player.pose = Pose.STANDING;
if (!keepTrackedData || player.getClientVersion().isOlderThan(ClientVersion.V_1_21_2)) {
player.clientVelocity = new Vector3dm();
}
if (!GrimAPI.INSTANCE.getSpectateManager().isSpectating(player.uuid)) {
player.gamemode = respawn.getGameMode();
}
if (PacketEvents.getAPI().getServerManager().getVersion().isNewerThanOrEquals(ServerVersion.V_1_17)) {
player.compensatedWorld.setDimension(respawn.getDimensionType(), event.getUser());
}
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_16) && !this.hasFlag(respawn, KEEP_ATTRIBUTES)) {
// Reset attributes if not kept
player.compensatedEntities.self.resetAttributes();
player.compensatedEntities.hasSprintingAttributeEnabled = false;
}
});
}
}
private boolean isWorldChange(GrimPlayer player, WrapperPlayServerRespawn respawn) {
if (player.getClientVersion().isNewerThanOrEquals(ClientVersion.V_1_16) && PacketEvents.getAPI().getServerManager().getVersion().isNewerThan(ServerVersion.V_1_16)) {
return !Objects.equals(respawn.getWorldName().orElse(null), player.worldName);
}
ClientVersion version = PacketEvents.getAPI().getServerManager().getVersion().toClientVersion();
return respawn.getDimensionType().getId(version) != player.dimensionType.getId(version)
|| !Objects.equals(respawn.getDimensionType().getName(), player.dimensionType.getName());
}
}
// NOTE (AI): The JOIN_GAME branch is lines 113-131 of this listener. The same class also owns UPDATE_HEALTH (77-111) and RESPAWN (133-243); the S01 story is the state-copy block plus the dimension re-arm on 1.17+.
Initialize the per-player packet state when the play session starts: entity id, gamemode and a clean compensated entity list.
PacketListener.onPacketSend switches on Play.Server packet types. JOIN_GAME is wrapped as WrapperPlayServerJoinGame and passed to handleJoinGame, which stores the entity id and gamemode on the ShardPlayer and clears compensatedEntities. The same dispatch routes RESPAWN, the SPAWN_* family and DESTROY_ENTITIES, so the join handler is one branch of the packet-state machine that all simulation checks consume.
// ===== FILE: KaelusAI-Shard, src/main/kotlin/ac/shard/packet/PacketListener.kt =====
/*
* This file is part of Shard - https://github.com/KaelusAI/Shard
* Copyright (C) 2026 KaelusAI
*
* This file contains code derived from GrimAC.
* The original authors of GrimAC are credited below.
*
* Copyright (c) 2021-2026 GrimAC, DefineOutside and contributors.
*
* Shard is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Shard is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ac.shard.packet
import ac.shard.player.PlayerDataManager
import ac.shard.player.ShardPlayer
import ac.shard.player.TransactionStamp
import com.github.retrooper.packetevents.PacketEvents
import com.github.retrooper.packetevents.event.PacketListenerAbstract
import com.github.retrooper.packetevents.event.PacketReceiveEvent
import com.github.retrooper.packetevents.event.PacketSendEvent
import com.github.retrooper.packetevents.event.ProtocolPacketEvent
import com.github.retrooper.packetevents.event.UserDisconnectEvent
import com.github.retrooper.packetevents.event.UserLoginEvent
import com.github.retrooper.packetevents.manager.server.ServerVersion
import com.github.retrooper.packetevents.protocol.entity.type.EntityTypes
import com.github.retrooper.packetevents.protocol.packettype.PacketType
import com.github.retrooper.packetevents.protocol.player.ClientVersion
import com.github.retrooper.packetevents.protocol.teleport.RelativeFlag
import com.github.retrooper.packetevents.protocol.world.Location
import com.github.retrooper.packetevents.util.Vector3d
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPlayerFlying
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientPong
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientWindowConfirmation
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerDestroyEntities
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerJoinGame
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPing
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerPositionAndLook
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerPlayerRotation
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSetPassengers
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnEntity
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnLivingEntity
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPainting
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerSpawnPlayer
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerWindowConfirmation
import org.bukkit.entity.Player
private const val FULL_CIRCLE_DEGREES = 360f
private const val MAX_PITCH = 90f
class PacketListener(private val playerDataManager: PlayerDataManager) : PacketListenerAbstract() {
override fun onUserLogin(event: UserLoginEvent) {
val user: com.github.retrooper.packetevents.protocol.player.User? = event.user
if (user == null) {
return
}
val player: Player? = event.getPlayer()
if (player == null) {
return
}
playerDataManager.handleUserLogin(user, player)
}
override fun onUserDisconnect(event: UserDisconnectEvent) {
playerDataManager.handleUserDisconnect(event.user)
}
private fun checkTeleportQueue(
player: ShardPlayer,
flying: WrapperPlayClientPlayerFlying,
): Boolean {
if (!flying.hasPositionChanged() || player.pendingTeleports.isEmpty()) {
return false
}
val movement = player.movement
while (player.pendingTeleports.isNotEmpty()) {
val teleport = player.pendingTeleports.peek() ?: break
val lastTransaction = player.transactions.lastTransactionReceived.get()
if (lastTransaction < teleport.transactionId) {
return false
}
val flyingLocation = flying.location
val flags = teleport.flags
val expectedX =
if (flags.has(RelativeFlag.X)) {
movement.x + teleport.location.x
} else {
teleport.location.x
}
val expectedY =
if (flags.has(RelativeFlag.Y)) {
movement.y + teleport.location.y
} else {
teleport.location.y
}
val expectedZ =
if (flags.has(RelativeFlag.Z)) {
movement.z + teleport.location.z
} else {
teleport.location.z
}
val epsilon = 1.0E-7
if (
kotlin.math.abs(flyingLocation.x - expectedX) < epsilon &&
kotlin.math.abs(flyingLocation.y - expectedY) < epsilon &&
kotlin.math.abs(flyingLocation.z - expectedZ) < epsilon
) {
player.pendingTeleports.poll()
return true
}
if (lastTransaction > teleport.transactionId) {
player.pendingTeleports.poll()
continue
}
return false
}
return false
}
private fun checkRotationQueue(
player: ShardPlayer,
flying: WrapperPlayClientPlayerFlying,
): Boolean {
if (
!flying.hasRotationChanged() ||
flying.hasPositionChanged() ||
player.pendingRotations.isEmpty()
) {
return false
}
while (player.pendingRotations.isNotEmpty()) {
val rotation = player.pendingRotations.peek() ?: break
val lastTransaction = player.transactions.lastTransactionReceived.get()
if (lastTransaction < rotation.transactionId) {
return false
}
if (matchesServerRotation(rotation, flying)) {
player.pendingRotations.poll()
return true
}
if (lastTransaction > rotation.transactionId) {
player.pendingRotations.poll()
continue
}
return false
}
return false
}
override fun onPacketReceive(event: PacketReceiveEvent) {
val player: Player? = event.getPlayer<Player>()
if (player == null) {
return
}
val shardPlayer = playerDataManager.getPlayer(player) ?: return
if (handleTransaction(event, shardPlayer)) {
dropWrapperUnlessRewritten(event)
return
}
if (WrapperPlayClientPlayerFlying.isFlying(event.packetType)) {
handleFlying(event, shardPlayer)
}
if (event.isCancelled) {
resetFlags(shardPlayer)
return
}
if (
shardPlayer.packetStateData.lastPacketWasTeleport ||
shardPlayer.packetStateData.lastPacketWasServerRotation
) {
updatePlayerState(shardPlayer, WrapperPlayClientPlayerFlying(event))
}
if (
WrapperPlayClientPlayerFlying.isFlying(event.packetType) &&
!shardPlayer.packetStateData.shouldIgnoreFlyingTick
) {
shardPlayer.combat.ticksSinceAttack = shardPlayer.combat.ticksSinceAttack + 1
}
shardPlayer.checkManager.onPacketReceive(event)
resetFlags(shardPlayer)
dropWrapperUnlessRewritten(event)
}
private fun dropWrapperUnlessRewritten(event: ProtocolPacketEvent) {
if (!event.needsReEncode()) {
event.setLastUsedWrapper(null)
}
}
private fun handleTransaction(event: PacketReceiveEvent, shardPlayer: ShardPlayer): Boolean {
if (event.packetType == PacketType.Play.Client.WINDOW_CONFIRMATION) {
val transaction = WrapperPlayClientWindowConfirmation(event)
val id = transaction.actionId
if (id <= 0 && addTransactionResponse(shardPlayer, id)) {
event.isCancelled = true
}
return true
} else if (event.packetType == PacketType.Play.Client.PONG) {
val pong = WrapperPlayClientPong(event)
val id = pong.id.toShort()
if (addTransactionResponse(shardPlayer, id)) {
event.isCancelled = true
}
return true
}
return false
}
private fun matchesServerRotation(
rotation: ShardPlayer.RotationData,
flying: WrapperPlayClientPlayerFlying,
): Boolean {
val yawMatches = rotation.relativeYaw || flying.location.yaw == rotation.yaw
val pitchMatches = rotation.relativePitch || flying.location.pitch == rotation.pitch
return yawMatches && pitchMatches
}
private fun handleFlying(event: PacketReceiveEvent, shardPlayer: ShardPlayer) {
val flying = WrapperPlayClientPlayerFlying(event)
val teleported = checkTeleportQueue(shardPlayer, flying)
val serverRotated = !teleported && checkRotationQueue(shardPlayer, flying)
shardPlayer.packetStateData.lastPacketWasTeleport = teleported
shardPlayer.packetStateData.lastPacketWasServerRotation = serverRotated
isMojangStupid(shardPlayer, flying, event)
if (!event.isCancelled && !teleported && !serverRotated) {
processRotation(shardPlayer, flying)
}
if (!teleported) {
shardPlayer.packetStateData.packetPlayerOnGround = flying.isOnGround
}
}
private fun processRotation(shardPlayer: ShardPlayer, packet: WrapperPlayClientPlayerFlying) {
val ignoreRotation =
shardPlayer.packetStateData.lastPacketWasOnePointSeventeenDuplicate &&
shardPlayer.isIgnoreDuplicatePacketRotation()
val movement = shardPlayer.movement
if (packet.hasPositionChanged()) {
movement.x = packet.location.x
movement.y = packet.location.y
movement.z = packet.location.z
if (!shardPlayer.packetStateData.lastPacketWasOnePointSeventeenDuplicate) {
shardPlayer.packetStateData.duplicatePacketFilterPosition = packet.location.position
}
}
if (packet.hasRotationChanged() && !ignoreRotation) {
val newYaw = packet.location.yaw
val newPitch = packet.location.pitch
movement.lastYaw = movement.yaw
movement.lastPitch = movement.pitch
movement.yaw = newYaw
movement.pitch = newPitch
}
}
private fun updatePlayerState(shardPlayer: ShardPlayer, flying: WrapperPlayClientPlayerFlying) {
val movement = shardPlayer.movement
if (flying.hasPositionChanged()) {
movement.x = flying.location.x
movement.y = flying.location.y
movement.z = flying.location.z
shardPlayer.packetStateData.duplicatePacketFilterPosition = flying.location.position
}
if (flying.hasRotationChanged()) {
movement.yaw = flying.location.yaw
movement.pitch = flying.location.pitch
movement.lastYaw = movement.yaw
movement.lastPitch = movement.pitch
}
}
private fun resetFlags(shardPlayer: ShardPlayer) {
shardPlayer.packetStateData.lastPacketWasOnePointSeventeenDuplicate = false
shardPlayer.packetStateData.lastPacketWasTeleport = false
shardPlayer.packetStateData.lastPacketWasServerRotation = false
}
override fun onPacketSend(event: PacketSendEvent) {
val player: Player? = event.getPlayer<Player>()
if (player != null) {
val shardPlayer = playerDataManager.getPlayer(player) ?: return
(event.packetType as? PacketType.Play.Server)?.let { packetType ->
when (packetType) {
PacketType.Play.Server.WINDOW_CONFIRMATION ->
handleWindowConfirmation(WrapperPlayServerWindowConfirmation(event), shardPlayer)
PacketType.Play.Server.PING -> handlePing(WrapperPlayServerPing(event), shardPlayer)
PacketType.Play.Server.SPAWN_ENTITY ->
handleSpawnEntity(WrapperPlayServerSpawnEntity(event), shardPlayer)
PacketType.Play.Server.SPAWN_LIVING_ENTITY ->
handleSpawnLivingEntity(WrapperPlayServerSpawnLivingEntity(event), shardPlayer)
PacketType.Play.Server.SPAWN_PAINTING ->
handleSpawnPainting(WrapperPlayServerSpawnPainting(event), shardPlayer)
PacketType.Play.Server.SPAWN_PLAYER ->
handleSpawnPlayer(WrapperPlayServerSpawnPlayer(event), shardPlayer)
PacketType.Play.Server.SET_PASSENGERS ->
handleSetPassengers(WrapperPlayServerSetPassengers(event), shardPlayer)
PacketType.Play.Server.DESTROY_ENTITIES ->
handleDestroyEntities(WrapperPlayServerDestroyEntities(event), shardPlayer)
PacketType.Play.Server.JOIN_GAME ->
handleJoinGame(WrapperPlayServerJoinGame(event), shardPlayer)
PacketType.Play.Server.RESPAWN -> handleRespawn(shardPlayer)
PacketType.Play.Server.PLAYER_POSITION_AND_LOOK ->
handlePositionAndLook(WrapperPlayServerPlayerPositionAndLook(event), shardPlayer)
PacketType.Play.Server.PLAYER_ROTATION ->
handlePlayerRotation(WrapperPlayServerPlayerRotation(event), shardPlayer)
else -> Unit
}
}
dropWrapperUnlessRewritten(event)
}
}
private fun handleWindowConfirmation(
confirmation: WrapperPlayServerWindowConfirmation,
shardPlayer: ShardPlayer,
) {
val id = confirmation.actionId
val transactions = shardPlayer.transactions
if (id <= 0 && transactions.didWeSendThatTrans.remove(id)) {
transactions.transactionsSent.add(TransactionStamp(id, System.nanoTime()))
transactions.lastTransactionSent.getAndIncrement()
}
}
private fun handlePing(ping: WrapperPlayServerPing, shardPlayer: ShardPlayer) {
val id = ping.id
val transactions = shardPlayer.transactions
if (id == id.toShort().toInt() && transactions.didWeSendThatTrans.remove(id.toShort())) {
transactions.transactionsSent.add(TransactionStamp(id.toShort(), System.nanoTime()))
transactions.lastTransactionSent.getAndIncrement()
}
}
private fun handleSpawnEntity(spawn: WrapperPlayServerSpawnEntity, shardPlayer: ShardPlayer) {
shardPlayer.compensatedEntities.addEntity(
spawn.entityId,
spawn.uuid.orElse(null),
spawn.entityType,
)
}
private fun handleSpawnLivingEntity(
spawn: WrapperPlayServerSpawnLivingEntity,
shardPlayer: ShardPlayer,
) {
shardPlayer.compensatedEntities.addEntity(spawn.entityId, spawn.entityUUID, spawn.entityType)
}
private fun handleSpawnPainting(spawn: WrapperPlayServerSpawnPainting, shardPlayer: ShardPlayer) {
shardPlayer.compensatedEntities.addEntity(spawn.entityId, spawn.uuid, EntityTypes.PAINTING)
}
private fun handleSpawnPlayer(spawn: WrapperPlayServerSpawnPlayer, shardPlayer: ShardPlayer) {
shardPlayer.compensatedEntities.addEntity(spawn.entityId, spawn.uuid, EntityTypes.PLAYER)
}
private fun handleSetPassengers(
wrapper: WrapperPlayServerSetPassengers,
shardPlayer: ShardPlayer,
) {
val self = shardPlayer.compensatedEntities.self
val vehicle = shardPlayer.compensatedEntities.getEntity(wrapper.entityId) ?: return
if (wrapper.passengers.contains(shardPlayer.entityId)) {
self.mount(vehicle)
} else if (self.riding === vehicle) {
self.eject()
}
}
private fun handleDestroyEntities(
destroy: WrapperPlayServerDestroyEntities,
shardPlayer: ShardPlayer,
) {
val self = shardPlayer.compensatedEntities.self
for (id in destroy.entityIds) {
if (self.riding === shardPlayer.compensatedEntities.getEntity(id)) {
self.eject()
}
shardPlayer.compensatedEntities.removeEntity(id)
}
}
private fun handleJoinGame(join: WrapperPlayServerJoinGame, shardPlayer: ShardPlayer) {
shardPlayer.entityId = join.entityId
shardPlayer.gameMode = join.gameMode
shardPlayer.compensatedEntities.clear()
}
private fun handleRespawn(shardPlayer: ShardPlayer) {
shardPlayer.compensatedEntities.clear()
}
private fun handlePositionAndLook(
wrapper: WrapperPlayServerPlayerPositionAndLook,
shardPlayer: ShardPlayer,
) {
shardPlayer.sendTransaction()
val transactionId = shardPlayer.transactions.lastTransactionSent.get()
val location = Vector3d(wrapper.x, wrapper.y, wrapper.z)
val flags = wrapper.relativeFlags
shardPlayer.pendingTeleports.add(ShardPlayer.TeleportData(location, flags, transactionId))
}
private fun handlePlayerRotation(
wrapper: WrapperPlayServerPlayerRotation,
shardPlayer: ShardPlayer,
) {
shardPlayer.sendTransaction()
val transactionId = shardPlayer.transactions.lastTransactionSent.get()
val storedPitch =
if (wrapper.isRelativePitch) {
wrapper.pitch
} else {
(wrapper.pitch % FULL_CIRCLE_DEGREES).coerceIn(-MAX_PITCH, MAX_PITCH)
}
shardPlayer.pendingRotations.add(
ShardPlayer.RotationData(
wrapper.yaw,
storedPitch,
wrapper.isRelativeYaw,
wrapper.isRelativePitch,
transactionId,
)
)
}
private fun addTransactionResponse(player: ShardPlayer, id: Short): Boolean {
var data: TransactionStamp? = null
var hasId = false
for (entry in player.transactions.transactionsSent) {
if (entry.id == id) {
hasId = true
break
}
}
if (hasId) {
do {
data = player.transactions.transactionsSent.poll()
if (data == null) break
player.transactions.lastTransactionReceived.incrementAndGet()
} while (data.id != id)
player.latencyUtils.handleNettySyncTransaction(
player.transactions.lastTransactionReceived.get()
)
}
return data != null
}
private fun isMojangStupid(
player: ShardPlayer,
flying: WrapperPlayClientPlayerFlying,
event: PacketReceiveEvent,
) {
if (
player.packetStateData.lastPacketWasTeleport ||
player.user.clientVersion.isNewerThanOrEquals(ClientVersion.V_1_21)
) {
return
}
val location: Location = flying.location
if (shouldProcessDuplicate(player, flying, location)) {
handleDuplicatePacketAction(player, flying, location, event)
player.packetStateData.lastPacketWasOnePointSeventeenDuplicate = true
applyDuplicateRotation(player, location)
}
}
private fun shouldProcessDuplicate(
player: ShardPlayer,
flying: WrapperPlayClientPlayerFlying,
location: Location,
): Boolean {
val threshold = player.getMovementThreshold()
val inVehicle = player.compensatedEntities.self.riding != null
val hasMovementAndRotation = flying.hasPositionChanged() && flying.hasRotationChanged()
val sameGroundAndCloseClaim =
flying.isOnGround == player.packetStateData.packetPlayerOnGround &&
player.user.clientVersion.isNewerThanOrEquals(ClientVersion.V_1_17) &&
player.packetStateData.duplicatePacketFilterPosition.distanceSquared(location.position) <
threshold * threshold
return hasMovementAndRotation && (sameGroundAndCloseClaim || inVehicle)
}
private fun handleDuplicatePacketAction(
player: ShardPlayer,
flying: WrapperPlayClientPlayerFlying,
location: Location,
event: PacketReceiveEvent,
) {
val serverVersion = PacketEvents.getAPI().serverManager.version
if (player.isForceCancelDuplicatePacket()) {
event.isCancelled = true
return
}
if (serverVersion.isOlderThanOrEquals(ServerVersion.V_1_9)) {
if (player.isCancelDuplicatePacket()) {
event.isCancelled = true
}
return
}
flying.location =
Location(player.packetStateData.duplicatePacketFilterPosition, location.yaw, location.pitch)
event.markForReEncode(true)
}
private fun applyDuplicateRotation(player: ShardPlayer, location: Location) {
if (player.isIgnoreDuplicatePacketRotation()) return
val movement = player.movement
if (movement.yaw != location.yaw || movement.pitch != location.pitch) {
movement.lastYaw = movement.yaw
movement.lastPitch = movement.pitch
}
movement.yaw = location.yaw
movement.pitch = location.pitch
}
}
// NOTE (AI): The JOIN_GAME dispatch is line 333-334 and handleJoinGame spans 417-421: it stores entityId and gameMode, then calls compensatedEntities.clear(). The SPAWN_* and DESTROY_ENTITIES branches (321-332, 404-415) are the same listener's entity bookkeeping.
Rate-limit simultaneous logins to blunt login-flood spam bots that join and disconnect repeatedly.
A CHAT_LOGINS check driven by ChatListener.onPlayerLogin. It buckets login timestamps into a six-slot ActionFrequency ring per world (or globally when per-world counting is off), scores the bucket sum against cc.loginsLimit and cancels the login when the rate exceeds it. The join-game packet itself is never parsed; the check keys off the Bukkit PlayerLoginEvent that fires around the join handshake, which is how 1.8-generation anticheats watch the join domain without touching packet code.
// ===== FILE: Updated-NoCheatPlus-NoCheatPlus, NCPCore/src/main/java/fr/neatmonster/nocheatplus/checks/chat/Logins.java =====
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.neatmonster.nocheatplus.checks.chat;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.entity.Player;
import fr.neatmonster.nocheatplus.checks.Check;
import fr.neatmonster.nocheatplus.checks.CheckType;
import fr.neatmonster.nocheatplus.components.data.IData;
import fr.neatmonster.nocheatplus.components.registry.feature.IRemoveData;
import fr.neatmonster.nocheatplus.utilities.TickTask;
import fr.neatmonster.nocheatplus.utilities.ds.count.ActionFrequency;
public class Logins extends Check implements IRemoveData{
/** Per world count (if set in the config, only "" is used). */
private final Map<String, ActionFrequency> counts = new HashMap<String, ActionFrequency>();
public Logins() {
super(CheckType.CHAT_LOGINS);
}
private ActionFrequency getActionFrequency(String worldName, int buckets, long durBucket, boolean perWorldCount) {
if (!perWorldCount) worldName = "";
ActionFrequency freq = counts.get(worldName);
if (freq == null) freq = new ActionFrequency(buckets, durBucket);
counts.put(worldName, freq);
return freq;
}
public boolean check(final Player player, final ChatConfig cc, final ChatData data) {
final long now = System.currentTimeMillis();
// Skip if is too close to the startup time.
if (now - TickTask.getTimeStart() < cc.loginsStartupDelay) return false;
// Split into 6 buckets always.
final long durBucket = 1000L * cc.loginsSeconds / 6;
final ActionFrequency freq = getActionFrequency(player.getWorld().getName(), 6, durBucket, cc.loginsPerWorldCount);
freq.update(now);
final boolean cancel = freq.score(1f) > cc.loginsLimit; // TODO: >= ... This will be 1 after the first login (!).
if (!cancel) freq.add(1f);
return cancel;
}
/**
* Called by ChatListener
*/
public void onReload() {
counts.clear();
}
@Override
public IData removeData(final String playerName) {
// Ignore
return null;
}
@Override
public void removeAllData() {
counts.clear();
}
}
// NOTE (AI): The corpus hit for this file is the 'Login' keyword, not the packet class: NCP never references S01PacketJoinGame. The check fires from Bukkit's PlayerLoginEvent inside ChatListener.onPlayerLogin, so it belongs to the join domain by event, not by packet.
Related Packets
Wiki Cross-Reference
First PLAY packet (id 0x01): int entityId, gamemode byte, signed dimension byte -1/0/1, difficulty, maxPlayers, level-type string, reducedDebug bool.
Handler builds WorldClient and PlayerControllerMP, sets entity id and dimension, shows terrain GUI and replies MC|Brand C17.
MCP 1.8.9 S01PacketJoinGame implements Packet
1.8.9 callers: ServerConfigurationManager.initializeConnectionToPlayer sends new S01PacketJoinGame (line 143): https://github.com/Marcelektro/MavenMCP-1.8.9/blob/master/src/main/java/net/minecraft/server/management/ServerConfigurationManager.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.