Compare commits

...
12 Commits
Author SHA1 Message Date
retrooper c7096d8b35 1.8-pre-9, (generate uuid like nms) 2021-03-11 09:58:34 +01:00
retrooper 36b80763e3 WrappedPacketOutNamedEntitySpawn bug fixes,
1.8-pre-9
2021-03-11 09:42:27 +01:00
retrooper bc861089b0 WrappedPacketOutNamedEntitySpawn created,
WrappedEntityPlayer created,
WrappedPacketOutEntity.WrappedPacketOutEntityLook created,
WrappedPacketOutEntity.WrappedPacketOutEntityMove created,
WrappedPacketOutEntity.WrappedPacketOutRelEntityMoveLook created

This commit focussed on supporting NPC spawning and movement.
2021-03-10 20:54:56 +01:00
retrooper e5a43a8826 WrappedPacketOutPlayerInfo created and sendable,
WrappedPacketOutViewDistance created and sendable,
PacketEvents.get().getPlayerUtils().getGameProfile(Player) created
2021-03-09 22:09:58 +01:00
retrooper 1e1b609eb7 WrappedPacketOutRespawn WIP 2021-03-08 20:27:26 +01:00
retrooper 957c8876cc Improved injection failure reverting. 2021-03-07 22:09:09 +01:00
retrooper 2902ef8ba4 Automatically revert to compatibility injector if early injector fails. 2021-03-07 22:05:10 +01:00
retrooper de07adb46a WrappedPacketInEntityAction issues on spigot 1.8.0 fixed 2021-03-07 21:32:05 +01:00
retrooper f3dbb6dd4c PacketEvents#init function without Plugin instance as it is redundant. Old function still exists, but is deprecated. 2021-03-07 12:47:45 +01:00
retrooper b954e68f29 Ejecting players exception when already ejected fix? 2021-03-07 11:52:54 +01:00
retrooper 8e09c54143 Early injector Java 12 support! 2021-03-06 20:55:08 +01:00
retrooper 5e88678c52 PacketTypes are now constants and can be used in switch statements. packetevents-pre-8 update! 2021-03-06 13:32:07 +01:00
30 changed files with 1098 additions and 178 deletions

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>io.github.retrooper</groupId>
<artifactId>packetevents</artifactId>
<version>1.8-pre-7</version>
<version>1.8-pre-9</version>
<build>
<plugins>
<plugin>
@@ -67,7 +67,7 @@ public final class PacketEvents implements Listener, EventManager {
//TODO finish unfinished wrappers
private static PacketEvents instance;
private static Plugin plugin;
private final PEVersion version = new PEVersion(1, 7, 9, 7);
private final PEVersion version = new PEVersion(1, 7, 9, 9);
private final EventManager eventManager = new PEEventManager();
private final PlayerUtils playerUtils = new PlayerUtils();
private final ServerUtils serverUtils = new ServerUtils();
@@ -109,7 +109,6 @@ public final class PacketEvents implements Listener, EventManager {
NMSUtils.version = version;
EntityFinderUtils.version = version;
handlerName = "pe-" + plugin.getName();
try {
NMSUtils.load();
@@ -127,7 +126,12 @@ public final class PacketEvents implements Listener, EventManager {
if (!injectorReady.get()) {
injector.load();
injector.inject();
try {
injector.inject();
}
catch (Exception ex) {
ex.printStackTrace();
}
injectorReady.set(true);
}
@@ -148,11 +152,12 @@ public final class PacketEvents implements Listener, EventManager {
this.settings = settings;
}
public void init(final Plugin plugin) {
init(plugin, settings);
public void init() {
init(getSettings());
}
public void init(final Plugin pl, PacketEventsSettings packetEventsSettings) {
public void init(PacketEventsSettings packetEventsSettings) {
//Load if we haven't loaded already
load();
if (!initialized && !initializing) {
initializing = true;
@@ -173,9 +178,8 @@ public final class PacketEvents implements Listener, EventManager {
getPlayerUtils().injectPlayer(p);
//IT IS NOT RECOMMENDED TO RELOAD!
PacketEvents.get().getEventManager().callEvent(new PostPlayerInjectEvent(p, false));
}
catch (Exception ex) {
p.kickPlayer("Please rejoin!");
} catch (Exception ex) {
p.kickPlayer("Failed to inject... Please rejoin!");
}
}
@@ -184,6 +188,16 @@ public final class PacketEvents implements Listener, EventManager {
}
}
@Deprecated
public void init(Plugin plugin) {
init(plugin, settings);
}
@Deprecated
public void init(Plugin pl, PacketEventsSettings packetEventsSettings) {
init(packetEventsSettings);
}
public void terminate() {
if (initialized && !terminating) {
for (Player player : Bukkit.getOnlinePlayers()) {
@@ -303,8 +317,7 @@ public final class PacketEvents implements Listener, EventManager {
}
PacketEvents.get().getEventManager().callEvent(new PostPlayerInjectEvent(player, true));
}, 1L);
}
else {
} else {
//Dependency isn't available, we can already call the post player inject event.
PacketEvents.get().getEventManager().callEvent(new PostPlayerInjectEvent(e.getPlayer(), false));
}
@@ -317,6 +330,7 @@ public final class PacketEvents implements Listener, EventManager {
UUID uuid = player.getUniqueId();
InetSocketAddress address = player.getAddress();
injector.ejectPlayer(e.getPlayer());
//Cleanup user data
playerUtils.loginTime.remove(uuid);
playerUtils.playerPingMap.remove(uuid);
playerUtils.playerSmoothedPingMap.remove(uuid);
@@ -28,19 +28,18 @@ import io.github.retrooper.packetevents.settings.PacketEventsSettings;
import org.bukkit.plugin.java.JavaPlugin;
public class PacketEventsPlugin extends JavaPlugin {
@Override
public void onLoad() {
PacketEvents.create(this);
PacketEventsSettings settings = PacketEvents.get().getSettings();
settings.compatInjector(true);
settings.compatInjector(false);
settings.checkForUpdates(false);
PacketEvents.get().loadAsyncNewThread();
}
@Override
public void onEnable() {
PacketEvents.get().init(this);
PacketEvents.get().init();
}
@Override
@@ -3,13 +3,16 @@ package io.github.retrooper.packetevents.injector;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.event.impl.PlayerEjectEvent;
import io.github.retrooper.packetevents.event.impl.PlayerInjectEvent;
import io.github.retrooper.packetevents.injector.earlyinjector.EarlyInjector;
import io.github.retrooper.packetevents.injector.earlyinjector.legacy.EarlyChannelInjectorLegacy;
import io.github.retrooper.packetevents.injector.earlyinjector.modern.EarlyChannelInjector;
import io.github.retrooper.packetevents.injector.earlyinjector.modern.EarlyChannelInjectorModern;
import io.github.retrooper.packetevents.injector.lateinjector.legacy.LateChannelInjectorLegacy;
import io.github.retrooper.packetevents.injector.lateinjector.modern.LateChannelInjector;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import org.bukkit.entity.Player;
import java.util.NoSuchElementException;
public class GlobalChannelInjector implements ChannelInjector {
private ChannelInjector injector;
@@ -20,7 +23,7 @@ public class GlobalChannelInjector implements ChannelInjector {
public void load() {
boolean legacy = NMSUtils.legacyNettyImportMode;
if (!PacketEvents.get().getSettings().shouldUseCompatibilityInjector()) {
injector = legacy ? new EarlyChannelInjectorLegacy() : new EarlyChannelInjector();
injector = legacy ? new EarlyChannelInjectorLegacy() : new EarlyChannelInjectorModern();
} else {
injector = legacy ? new LateChannelInjectorLegacy() : new LateChannelInjector();
}
@@ -28,7 +31,18 @@ public class GlobalChannelInjector implements ChannelInjector {
@Override
public void inject() {
injector.inject();
try {
//Try inject...
injector.inject();
} catch (Exception ex) {
//Failed to inject! Let us revert to the compatibility injector and re-inject.
if (injector instanceof EarlyInjector) {
PacketEvents.get().getSettings().compatInjector(true);
load();
injector.inject();
throw new IllegalStateException("PacketEvents failed to inject with the Early Injector. Reverting to the Compatibility/Late Injector... Please report this!", ex);
}
}
}
@Override
@@ -50,7 +64,11 @@ public class GlobalChannelInjector implements ChannelInjector {
PlayerEjectEvent ejectEvent = new PlayerEjectEvent(player);
PacketEvents.get().callEvent(ejectEvent);
if (!ejectEvent.isCancelled()) {
injector.ejectPlayer(player);
try {
injector.ejectPlayer(player);
} catch (NoSuchElementException ignored) {
//We have already ejected them.
}
}
}
@@ -167,9 +167,9 @@ public class EarlyChannelInjectorLegacy implements EarlyInjector {
} catch (IllegalAccessException | NoSuchFieldException e2) {
e2.printStackTrace();
}
System.err.println("PacketEvents failed to inject, because of " + bootstrapAcceptor.getClass().getName() + ", you might want to try running without " + yaml.getName() + "?");
throw new IllegalStateException("PacketEvents failed to inject, because of " + bootstrapAcceptor.getClass().getName() + ", you might want to try running without " + yaml.getName() + "?");
} else {
System.err.println("PacketEvents failed to find core component 'childHandler', please check your plugins. issue: " + bootstrapAcceptor.getClass().getName());
throw new IllegalStateException("PacketEvents failed to find core component 'childHandler', please check your plugins. issue: " + bootstrapAcceptor.getClass().getName());
}
}
@@ -25,7 +25,6 @@
package io.github.retrooper.packetevents.injector.earlyinjector.modern;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.event.impl.PostPlayerInjectEvent;
import io.github.retrooper.packetevents.injector.earlyinjector.EarlyInjector;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
@@ -54,7 +53,7 @@ import java.util.Map;
* @author retrooper, Thomazz, ViaVersion
* @since 1.8
*/
public class EarlyChannelInjector implements EarlyInjector {
public class EarlyChannelInjectorModern implements EarlyInjector {
private final List<ChannelFuture> injectedFutures = new ArrayList<>();
private final List<Map<Field, Object>> injectedLists = new ArrayList<>();
@@ -104,8 +103,7 @@ public class EarlyChannelInjector implements EarlyInjector {
}
}
} catch (Exception ex) {
PacketEvents.get().getPlugin().getLogger().severe("PacketEvents failed to inject!");
ex.printStackTrace();
throw new IllegalStateException("PacketEvents failed to inject!", ex);
}
//Player channels might have been registered already. Let us add our handlers. We are a little late though.
@@ -120,7 +118,7 @@ public class EarlyChannelInjector implements EarlyInjector {
}
if (channel.pipeline().get("packet_handler") != null) {
channel.pipeline().addBefore("packet_handler", PacketEvents.handlerName, new PlayerChannelHandler());
channel.pipeline().addBefore("packet_handler", PacketEvents.handlerName, new PlayerChannelHandlerModern());
}
}
}
@@ -151,7 +149,7 @@ public class EarlyChannelInjector implements EarlyInjector {
try {
oldChannelInitializer = (ChannelInitializer<?>) bootstrapAcceptorField.get(bootstrapAcceptor);
ChannelInitializer<?> channelInitializer = new PEChannelInitializer(oldChannelInitializer);
ChannelInitializer<?> channelInitializer = new PEChannelInitializerModern(oldChannelInitializer);
Reflection.getFieldWithoutFinalModifier(bootstrapAcceptorField);
@@ -167,9 +165,9 @@ public class EarlyChannelInjector implements EarlyInjector {
} catch (IllegalAccessException | NoSuchFieldException e2) {
e2.printStackTrace();
}
System.err.println("PacketEvents failed to inject, because of " + bootstrapAcceptor.getClass().getName() + ", you might want to try running without " + yaml.getName() + "?");
throw new IllegalStateException("PacketEvents failed to inject, because of " + bootstrapAcceptor.getClass().getName() + ", you might want to try running without " + yaml.getName() + "?");
} else {
System.err.println("PacketEvents failed to find core component 'childHandler', please check your plugins. issue: " + bootstrapAcceptor.getClass().getName());
throw new IllegalStateException("PacketEvents failed to find core component 'childHandler', please check your plugins. issue: " + bootstrapAcceptor.getClass().getName());
}
}
@@ -191,7 +189,7 @@ public class EarlyChannelInjector implements EarlyInjector {
}
ChannelInitializer<SocketChannel> oldInit = (ChannelInitializer<SocketChannel>) childHandlerField.get(handler);
if (oldInit instanceof PEChannelInitializer) {
if (oldInit instanceof PEChannelInitializerModern) {
bootstrapAcceptor = handler;
}
} catch (Exception e) {
@@ -206,9 +204,9 @@ public class EarlyChannelInjector implements EarlyInjector {
try {
Reflection.getFieldWithoutFinalModifier(childHandlerField);
ChannelInitializer<SocketChannel> oldInit = (ChannelInitializer<SocketChannel>) childHandlerField.get(bootstrapAcceptor);
if (oldInit instanceof PEChannelInitializer) {
if (oldInit instanceof PEChannelInitializerModern) {
childHandlerField.set(bootstrapAcceptor, oldInit);
childHandlerField.set(bootstrapAcceptor, ((PEChannelInitializer) oldInit).getOldChannelInitializer());
childHandlerField.set(bootstrapAcceptor, ((PEChannelInitializerModern) oldInit).getOldChannelInitializer());
}
} catch (Exception e) {
PacketEvents.get().getPlugin().getLogger().severe("PacketEvents failed to eject the injection handler! Please reboot!");
@@ -258,7 +256,7 @@ public class EarlyChannelInjector implements EarlyInjector {
if (channel == null) {
return false;
}
PlayerChannelHandler handler = getHandler(channel);
PlayerChannelHandlerModern handler = getHandler(channel);
return handler != null && handler.player != null;
}
@@ -268,11 +266,11 @@ public class EarlyChannelInjector implements EarlyInjector {
channel.writeAndFlush(rawNMSPacket);
}
private PlayerChannelHandler getHandler(Object rawChannel) {
private PlayerChannelHandlerModern getHandler(Object rawChannel) {
Channel channel = (Channel) rawChannel;
ChannelHandler handler = channel.pipeline().get(PacketEvents.handlerName);
if (handler instanceof PlayerChannelHandler) {
return (PlayerChannelHandler) handler;
if (handler instanceof PlayerChannelHandlerModern) {
return (PlayerChannelHandlerModern) handler;
} else {
return null;
}
@@ -280,7 +278,7 @@ public class EarlyChannelInjector implements EarlyInjector {
@Override
public void updatePlayerObject(Player player, Object rawChannel) {
PlayerChannelHandler handler = getHandler(rawChannel);
PlayerChannelHandlerModern handler = getHandler(rawChannel);
if (handler != null) {
handler.player = player;
}
@@ -31,11 +31,11 @@ import io.netty.channel.socket.SocketChannel;
import java.lang.reflect.Method;
public class PEChannelInitializer extends ChannelInitializer<SocketChannel> {
public class PEChannelInitializerModern extends ChannelInitializer<SocketChannel> {
private final ChannelInitializer<?> oldChannelInitializer;
private Method initChannelMethod;
public PEChannelInitializer(ChannelInitializer<?> oldChannelInitializer) {
public PEChannelInitializerModern(ChannelInitializer<?> oldChannelInitializer) {
this.oldChannelInitializer = oldChannelInitializer;
load();
}
@@ -51,7 +51,7 @@ public class PEChannelInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
initChannelMethod.invoke(oldChannelInitializer, socketChannel);
PlayerChannelHandler channelHandler = new PlayerChannelHandler();
PlayerChannelHandlerModern channelHandler = new PlayerChannelHandlerModern();
if (socketChannel.pipeline().get("packet_handler") != null) {
socketChannel.pipeline().addBefore("packet_handler", PacketEvents.handlerName, channelHandler);
}
@@ -30,7 +30,7 @@ import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.bukkit.entity.Player;
public class PlayerChannelHandler extends ChannelDuplexHandler {
public class PlayerChannelHandlerModern extends ChannelDuplexHandler {
/**
* Associated player.
* This is null until we inject the player.
@@ -1,5 +1,9 @@
package io.github.retrooper.packetevents.packettype;
/**
* @author retrooper
* @since 1.8
*/
public enum PacketState {
STATUS, HANDSHAKING, LOGIN, PLAY
}
@@ -46,10 +46,9 @@ public class PacketType {
* This value may change over the versions so it is important to use the variable and not hard code its value.
*/
public static final byte INVALID = -128;
public static Map<Class<?>, Byte> packetIDMap = new HashMap<>();
public static final Map<Class<?>, Byte> packetIDMap = new HashMap<>();
public static void load() {
byte byteID = INVALID + 1;//-127
for (Class<?> cls : PacketType.class.getDeclaredClasses()) {
Class<?> packetTypeClassesSubclass = SubclassUtil.getSubClass(PacketTypeClasses.class, cls.getSimpleName());
for (Class<?> boundCls : cls.getDeclaredClasses()) {
@@ -58,23 +57,19 @@ public class PacketType {
String fieldName = f.getName();
Class<?> fieldType = f.getType();
if (fieldType.equals(byte.class)) {
try {
f.set(null, byteID);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
Field packetTypeClassesSubclassBoundField = null;
try {
packetTypeClassesSubclassBoundField = packetTypeClassesSubclassBoundClass.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
try {
byte byteID = f.getByte(null);
packetIDMap.put((Class<?>) packetTypeClassesSubclassBoundField.get(null), byteID);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
byteID++;
}
}
}
@@ -99,7 +94,7 @@ public class PacketType {
* @since 1.8
*/
public static class Client {
public static byte START, PING;
public static final byte START = -127, PING = -126;
}
/**
@@ -110,7 +105,7 @@ public class PacketType {
* @since 1.8
*/
public static class Server {
public static byte PONG, SERVER_INFO;
public static final byte PONG = -125, SERVER_INFO = -124;
}
}
@@ -129,7 +124,7 @@ public class PacketType {
* @since 1.8
*/
public static class Client {
public static byte SET_PROTOCOL;
public static final byte SET_PROTOCOL = -123;
}
}
@@ -149,7 +144,7 @@ public class PacketType {
* @since 1.8
*/
public static class Client {
public static byte CUSTOM_PAYLOAD, START, ENCRYPTION_BEGIN;
public static final byte CUSTOM_PAYLOAD = -122, START = -121, ENCRYPTION_BEGIN = -120;
}
/**
@@ -160,7 +155,7 @@ public class PacketType {
* @since 1.8
*/
public static class Server {
public static byte CUSTOM_PAYLOAD, DISCONNECT, ENCRYPTION_BEGIN, SUCCESS, SET_COMPRESSION;
public static final byte CUSTOM_PAYLOAD = -119, DISCONNECT = -118, ENCRYPTION_BEGIN = -117, SUCCESS = -116, SET_COMPRESSION = -115;
}
}
@@ -180,19 +175,19 @@ public class PacketType {
* @since 1.8
*/
public static class Client {
public static byte TELEPORT_ACCEPT,
TILE_NBT_QUERY, DIFFICULTY_CHANGE, CHAT, CLIENT_COMMAND,
SETTINGS, TAB_COMPLETE, TRANSACTION, ENCHANT_ITEM,
WINDOW_CLICK, CLOSE_WINDOW, CUSTOM_PAYLOAD, B_EDIT,
ENTITY_NBT_QUERY, USE_ENTITY, JIGSAW_GENERATE, KEEP_ALIVE,
DIFFICULTY_LOCK, POSITION, POSITION_LOOK, LOOK,
FLYING, VEHICLE_MOVE, BOAT_MOVE, PICK_ITEM,
AUTO_RECIPE, ABILITIES, BLOCK_DIG, ENTITY_ACTION,
STEER_VEHICLE, RECIPE_DISPLAYED, ITEM_NAME, RESOURCE_PACK_STATUS,
ADVANCEMENTS, TR_SEL, BEACON, HELD_ITEM_SLOT,
SET_COMMAND_BLOCK, SET_COMMAND_MINECART, SET_CREATIVE_SLOT, SET_JIGSAW,
STRUCT, UPDATE_SIGN, ARM_ANIMATION, SPECTATE,
USE_ITEM, BLOCK_PLACE;
public static final byte TELEPORT_ACCEPT = -114,
TILE_NBT_QUERY = -113, DIFFICULTY_CHANGE = -112, CHAT = -111, CLIENT_COMMAND = -110,
SETTINGS = -109, TAB_COMPLETE = -108, TRANSACTION = -107, ENCHANT_ITEM = -106,
WINDOW_CLICK = -105, CLOSE_WINDOW = -104, CUSTOM_PAYLOAD = -103, B_EDIT = -102,
ENTITY_NBT_QUERY = -101, USE_ENTITY = -100, JIGSAW_GENERATE = -99, KEEP_ALIVE = -98,
DIFFICULTY_LOCK = -97, POSITION = -96, POSITION_LOOK = -95, LOOK = -94,
FLYING = -93, VEHICLE_MOVE = -92, BOAT_MOVE = -91, PICK_ITEM = -90,
AUTO_RECIPE = -89, ABILITIES = -88, BLOCK_DIG = -87, ENTITY_ACTION = -86,
STEER_VEHICLE = -85, RECIPE_DISPLAYED = -84, ITEM_NAME = -83, RESOURCE_PACK_STATUS = -82,
ADVANCEMENTS = -81, TR_SEL = -80, BEACON = -79, HELD_ITEM_SLOT = -78,
SET_COMMAND_BLOCK = -77, SET_COMMAND_MINECART = -76, SET_CREATIVE_SLOT = -75, SET_JIGSAW = -74,
STRUCT = -73, UPDATE_SIGN = -72, ARM_ANIMATION = -71, SPECTATE = -70,
USE_ITEM = -69, BLOCK_PLACE = -68;
/**
* Server-bound Play Packet Type utility.
@@ -247,29 +242,29 @@ public class PacketType {
* @since 1.8
*/
public static class Server {
public static byte SPAWN_ENTITY, SPAWN_ENTITY_EXPERIENCE_ORB, SPAWN_ENTITY_WEATHER, SPAWN_ENTITY_LIVING,
SPAWN_ENTITY_PAINTING, SPAWN_ENTITY_SPAWN, ANIMATION, STATISTIC,
BLOCK_BREAK, BLOCK_BREAK_ANIMATION, TILE_ENTITY_DATA, BLOCK_ACTION,
BLOCK_CHANGE, BOSS, SERVER_DIFFICULTY, CHAT, MULTI_BLOCK_CHANGE,
TAB_COMPLETE, COMMANDS, TRANSACTION, CLOSE_WINDOW,
WINDOW_ITEMS, WINDOW_DATA, SET_SLOT, SET_COOLDOWN,
CUSTOM_PAYLOAD, CUSTOM_SOUND_EFFECT, KICK_DISCONNECT, ENTITY_STATUS,
EXPLOSION, UNLOAD_CHUNK, GAME_STATE_CHANGE, OPEN_WINDOW_HORSE,
KEEP_ALIVE, MAP_CHUNK, WORLD_EVENT, WORLD_PARTICLES,
LIGHT_UPDATE, LOGIN, MAP, OPEN_WINDOW_MERCHANT,
REL_ENTITY_MOVE, REL_ENTITY_MOVE_LOOK, ENTITY_LOOK, ENTITY,
VEHICLE_MOVE, OPEN_BOOK, OPEN_WINDOW, OPEN_SIGN_EDITOR,
AUTO_RECIPE, ABILITIES, COMBAT_EVENT, PLAYER_INFO,
LOOK_AT, POSITION, RECIPES, ENTITY_DESTROY,
REMOVE_ENTITY_EFFECT, RESOURCE_PACK_SEND, RESPAWN, ENTITY_HEAD_ROTATION,
SELECT_ADVANCEMENT_TAB, WORLD_BORDER, CAMERA, HELD_ITEM_SLOT,
VIEW_CENTRE, VIEW_DISTANCE, SCOREBOARD_DISPLAY_OBJECTIVE, ENTITY_METADATA,
ATTACH_ENTITY, ENTITY_VELOCITY, ENTITY_EQUIPMENT, EXPERIENCE,
UPDATE_HEALTH, SCOREBOARD_OBJECTIVE, MOUNT, SCOREBOARD_TEAM,
SCOREBOARD_SCORE, SPAWN_POSITION, UPDATE_TIME, TITLE,
ENTITY_SOUND, NAMED_SOUND_EFFECT, STOP_SOUND, PLAYER_LIST_HEADER_FOOTER,
NBT_QUERY, COLLECT, ENTITY_TELEPORT, ADVANCEMENTS, UPDATE_ATTRIBUTES,
ENTITY_EFFECT, RECIPE_UPDATE, TAGS, MAP_CHUNK_BULK, NAMED_ENTITY_SPAWN;
public static final byte SPAWN_ENTITY = -67, SPAWN_ENTITY_EXPERIENCE_ORB = -66, SPAWN_ENTITY_WEATHER = -65, SPAWN_ENTITY_LIVING = -64,
SPAWN_ENTITY_PAINTING = -63, SPAWN_ENTITY_SPAWN = -62, ANIMATION = -61, STATISTIC = -60,
BLOCK_BREAK = -59, BLOCK_BREAK_ANIMATION = -58, TILE_ENTITY_DATA = -57, BLOCK_ACTION = -56,
BLOCK_CHANGE = -55, BOSS = -54, SERVER_DIFFICULTY = -53, CHAT = -52, MULTI_BLOCK_CHANGE = -51,
TAB_COMPLETE = -50, COMMANDS = -49, TRANSACTION = -48, CLOSE_WINDOW = -47,
WINDOW_ITEMS = -46, WINDOW_DATA = -45, SET_SLOT = -44, SET_COOLDOWN = -43,
CUSTOM_PAYLOAD = -42, CUSTOM_SOUND_EFFECT = -41, KICK_DISCONNECT = -40, ENTITY_STATUS = -39,
EXPLOSION = -38, UNLOAD_CHUNK = -37, GAME_STATE_CHANGE = -36, OPEN_WINDOW_HORSE = -35,
KEEP_ALIVE = -34, MAP_CHUNK = -33, WORLD_EVENT = -32, WORLD_PARTICLES = -31,
LIGHT_UPDATE = -30, LOGIN = -29, MAP = -28, OPEN_WINDOW_MERCHANT = -27,
REL_ENTITY_MOVE = -26, REL_ENTITY_MOVE_LOOK = -25, ENTITY_LOOK = -24, ENTITY = -23,
VEHICLE_MOVE = -22, OPEN_BOOK = -21, OPEN_WINDOW = -20, OPEN_SIGN_EDITOR = -19,
AUTO_RECIPE = -18, ABILITIES = -17, COMBAT_EVENT = -16, PLAYER_INFO = -15,
LOOK_AT = -14, POSITION = -13, RECIPES = -12, ENTITY_DESTROY = -11,
REMOVE_ENTITY_EFFECT = -10, RESOURCE_PACK_SEND = -9, RESPAWN = -8, ENTITY_HEAD_ROTATION = -7,
SELECT_ADVANCEMENT_TAB = -6, WORLD_BORDER = -5, CAMERA = -4, HELD_ITEM_SLOT = -3,
VIEW_CENTRE = -2, VIEW_DISTANCE = -1, SCOREBOARD_DISPLAY_OBJECTIVE = 0, ENTITY_METADATA = 1,
ATTACH_ENTITY = 2, ENTITY_VELOCITY = 3, ENTITY_EQUIPMENT = 4, EXPERIENCE = 5,
UPDATE_HEALTH = 6, SCOREBOARD_OBJECTIVE = 7, MOUNT = 8, SCOREBOARD_TEAM = 9,
SCOREBOARD_SCORE = 10, SPAWN_POSITION = 11, UPDATE_TIME = 12, TITLE = 13,
ENTITY_SOUND = 14, NAMED_SOUND_EFFECT = 15, STOP_SOUND = 16, PLAYER_LIST_HEADER_FOOTER = 17,
NBT_QUERY = 18, COLLECT = 19, ENTITY_TELEPORT = 20, ADVANCEMENTS = 21, UPDATE_ATTRIBUTES = 22,
ENTITY_EFFECT = 23, RECIPE_UPDATE = 24, TAGS = 25, MAP_CHUNK_BULK = 26, NAMED_ENTITY_SPAWN = 27;
/**
* Client-bound Play Packet Type utility.
@@ -84,6 +84,7 @@ public class WrappedPacket implements WrapperPacketReader, WrapperPacketWriter {
String wrapperName = ClassUtil.getClassSimpleName(getClass());
PacketEvents.get().getPlugin().getLogger()
.log(Level.SEVERE, "PacketEvents found an exception while loading the " + wrapperName + " packet wrapper. Please report this bug! Tell us about your server version, spigot and code(of you using the wrapper)", ex);
LOADED_WRAPPERS.put(clazz, false);
}
LOADED_WRAPPERS.put(clazz, true);
}
@@ -93,6 +94,10 @@ public class WrappedPacket implements WrapperPacketReader, WrapperPacketWriter {
}
protected boolean hasLoaded() {
return LOADED_WRAPPERS.getOrDefault(getClass(), false);
}
protected void throwUnsupportedOperation(Enum<?> enumConst) throws UnsupportedOperationException {
Class<?> enumConstClass = enumConst.getClass();
Field field = null;
@@ -28,6 +28,7 @@ import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.enums.EnumUtil;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.world.Difficulty;
/**
* Wrapper for the DifficultyChange packet.
@@ -61,11 +62,4 @@ public final class WrappedPacketInDifficultyChange extends WrappedPacket {
Enum<?> enumConstant = EnumUtil.valueByIndex(enumDifficultyClass, difficulty.ordinal());
writeEnumConstant(0, enumConstant);
}
public enum Difficulty {
PEACEFUL,
EASY,
NORMAL,
HARD
}
}
@@ -37,7 +37,6 @@ import org.jetbrains.annotations.Nullable;
public final class WrappedPacketInEntityAction extends WrappedPacket {
private static Class<? extends Enum<?>> enumPlayerActionClass;
private static boolean olderThan_v_1_8;
private static boolean newerThan_v_1_8_8;
private Entity entity;
private int entityID = -1;
@@ -48,11 +47,12 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
@Override
protected void load() {
olderThan_v_1_8 = version.isOlderThan(ServerVersion.v_1_8);
newerThan_v_1_8_8 = version.isNewerThan(ServerVersion.v_1_8_8);
if (!olderThan_v_1_8) {
enumPlayerActionClass = NMSUtils.getNMSEnumClassWithoutException("EnumPlayerAction");
if (enumPlayerActionClass == null) {
enumPlayerActionClass = SubclassUtil.getEnumSubClass(PacketTypeClasses.Play.Client.ENTITY_ACTION, "EnumPlayerAction");
}
}
@Nullable
@@ -86,7 +86,7 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
}
public PlayerAction getAction() {
if (olderThan_v_1_8) {
if (enumPlayerActionClass == null) {
int animationIndex = readInt(1) - 1;
return PlayerAction.getByActionValue((byte) (animationIndex));
} else {
@@ -96,7 +96,7 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
}
public void setAction(PlayerAction action) throws UnsupportedOperationException {
if (olderThan_v_1_8) {
if (enumPlayerActionClass == null) {
byte animationIndex = action.actionID;
writeInt(1, animationIndex + 1);
} else {
@@ -118,7 +118,7 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
}
public int getJumpBoost() {
if (olderThan_v_1_8) {
if (enumPlayerActionClass == null) {
return readInt(2);
} else {
return readInt(1);
@@ -126,7 +126,7 @@ public final class WrappedPacketInEntityAction extends WrappedPacket {
}
public void setJumpBoost(int jumpBoost) {
if (olderThan_v_1_8) {
if (enumPlayerActionClass == null) {
writeInt(2, jumpBoost);
} else {
writeInt(1, jumpBoost);
@@ -189,7 +189,7 @@ public class WrappedPacketOutBlockChange extends WrappedPacket implements Sendab
Vector3i blockPosition = getBlockPosition();
if (version.isOlderThan(ServerVersion.v_1_8)) {
try {
Object nmsWorld = NMSUtils.convertBukkitWorldToNMSWorld(world);
Object nmsWorld = NMSUtils.convertBukkitWorldToWorldServer(world); //TODO civ, is it nms world or world server
nmsPacket = packetConstructor.newInstance(blockPosition.x, blockPosition.y, blockPosition.z, nmsWorld);
blockChange = new WrappedPacketOutBlockChange(new NMSPacket(nmsPacket));
@@ -208,8 +208,8 @@ public class WrappedPacketOutBlockChange extends WrappedPacket implements Sendab
blockChange.setMaterial(material);
} else {
Object nmsBlockPos = NMSUtils.generateNMSBlockPos(blockPosition.x, blockPosition.y, blockPosition.z);
Object nmsWorld = NMSUtils.convertBukkitWorldToNMSWorld(world);
Object nmsBlockData = getNMSWorldTypeMethodCache.invoke(nmsWorld, nmsBlockPos);
Object worldServer = NMSUtils.convertBukkitWorldToWorldServer(world); //TODO civ, is it world server or nms world
Object nmsBlockData = getNMSWorldTypeMethodCache.invoke(worldServer, nmsBlockPos);
blockChange.write(NMSUtils.iBlockDataClass, 0, nmsBlockData);
}
blockChange.setBlockPosition(blockPosition);
@@ -45,19 +45,31 @@ public class WrappedPacketOutEntity extends WrappedPacket implements SendableWra
private static double dXYZDivisor;
private static int yawByteIndex;
private static int pitchByteIndex = 1;
private static Constructor<?> entityPacketConstructor;
private static Constructor<?> entityPacketConstructor, entityRelMovePacketConstructor, entityLookConstructor, entityRelMoveLookConstructor;
private Entity entity;
private int entityID = -1;
private double deltaX, deltaY, deltaZ;
private byte pitch, yaw;
private boolean onGround;
private boolean onGround, isLook;
public WrappedPacketOutEntity(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutEntity(int entityID, double deltaX, double deltaY, double deltaZ,
byte pitch, byte yaw, boolean onGround, boolean isLook) {
this.entityID = entityID;
this.deltaX = deltaX;
this.deltaY = deltaY;
this.deltaZ = deltaZ;
this.pitch = pitch;
this.yaw = yaw;
this.onGround = onGround;
this.isLook = isLook;
}
public WrappedPacketOutEntity(int entityID, double deltaX, double deltaY, double deltaZ,
byte pitch, byte yaw, boolean onGround) {
this.entityID = entityID;
@@ -67,11 +79,17 @@ public class WrappedPacketOutEntity extends WrappedPacket implements SendableWra
this.pitch = pitch;
this.yaw = yaw;
this.onGround = onGround;
this.isLook = false;
}
public WrappedPacketOutEntity(Entity entity, double deltaX, double deltaY, double deltaZ,
byte pitch, byte yaw, boolean onGround, boolean isLook) {
this(entity.getEntityId(), deltaX, deltaY, deltaZ, pitch, yaw, onGround, isLook);
}
public WrappedPacketOutEntity(Entity entity, double deltaX, double deltaY, double deltaZ,
byte pitch, byte yaw, boolean onGround) {
this(entity.getEntityId(), deltaX, deltaY, deltaZ, pitch, yaw, onGround);
this(entity.getEntityId(), deltaX, deltaY, deltaZ, pitch, yaw, onGround, false);
}
@Override
@@ -222,15 +240,18 @@ public class WrappedPacketOutEntity extends WrappedPacket implements SendableWra
}
public void setDeltaZ(double deltaZ) {
int dz = (int) (deltaZ * dXYZDivisor);
if (packet != null) {
int dz = (int) (deltaZ * dXYZDivisor);
switch (mode) {
case 0:
writeByte(2, (byte) dz);
break;
case 1:
writeInt(3, dz);
break;
case 2:
writeShort(2, (short) dz);
break;
}
} else {
this.deltaZ = deltaZ;
@@ -244,10 +265,10 @@ public class WrappedPacketOutEntity extends WrappedPacket implements SendableWra
@Nullable
public Entity getEntity(@Nullable World world) {
if (entity == null) {
entity = NMSUtils.getEntityById(world, getEntityId());
}
return entity;
if (entity == null) {
entity = NMSUtils.getEntityById(world, getEntityId());
}
return entity;
}
public void setEntity(Entity entity) {
@@ -256,16 +277,16 @@ public class WrappedPacketOutEntity extends WrappedPacket implements SendableWra
}
public int getEntityId() {
if (entityID != -1) {
return entityID;
if (packet != null) {
return readInt(0);
} else {
return entityID = readInt(0);
return entityID;
}
}
public void setEntityId(int entityID) {
if (packet != null) {
writeInt(0, this.entityID = entityID);
writeInt(0, entityID);
} else {
this.entityID = entityID;
}
@@ -288,38 +309,155 @@ public class WrappedPacketOutEntity extends WrappedPacket implements SendableWra
}
}
//TODO civ through all versions
public boolean isLook() {
if (packet != null) {
return readBoolean(1);
} else {
return isLook;
}
}
//TODO civ through all versions
public void setLook(boolean isLook) {
if (packet != null) {
writeBoolean(1, isLook);
} else {
this.isLook = isLook;
}
}
@Override
public Object asNMSPacket() {
try {
Object packetInstance = entityPacketConstructor.newInstance(entityID);
int dx = (int) (getDeltaX() * dXYZDivisor);
int dy = (int) (getDeltaY() * dXYZDivisor);
int dz = (int) (getDeltaZ() * dXYZDivisor);
WrappedPacket wrapper = new WrappedPacket(new NMSPacket(packetInstance));
switch (mode) {
case 0:
wrapper.writeByte(0, (byte) dx);
wrapper.writeByte(1, (byte) dy);
wrapper.writeByte(2, (byte) dz);
break;
case 1:
wrapper.writeInt(1, dx);
wrapper.writeInt(2, dy);
wrapper.writeInt(3, dz);
break;
case 2:
wrapper.writeShort(0, (short) dx);
wrapper.writeShort(1, (short) dy);
wrapper.writeShort(2, (short) dz);
break;
}
wrapper.writeByte(yawByteIndex, yaw);
wrapper.writeByte(pitchByteIndex, pitch);
wrapper.writeBoolean(0, onGround);
Object packetInstance = entityPacketConstructor.newInstance(getEntityId());
WrappedPacketOutEntity wrapper = new WrappedPacketOutEntity(new NMSPacket(packetInstance));
wrapper.setDeltaX(getDeltaX());
wrapper.setDeltaY(getDeltaY());
wrapper.setDeltaZ(getDeltaZ());
wrapper.setYaw(getYaw());
wrapper.setPitch(getPitch());
wrapper.setOnGround(isOnGround());
wrapper.setLook(isLook());
return packetInstance;
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
public static class WrappedPacketOutEntityLook extends WrappedPacketOutEntity {
public WrappedPacketOutEntityLook(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutEntityLook(int entityID, byte pitch, byte yaw, boolean onGround) {
super(entityID, 0, 0, 0, pitch, yaw, onGround, true);
}
@Override
protected void load() {
super.load();
try {
entityLookConstructor = PacketTypeClasses.Play.Server.ENTITY_LOOK.getConstructor();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
@Override
public Object asNMSPacket() {
try {
Object packetInstance = entityLookConstructor.newInstance();
WrappedPacketOutEntityLook wrapper = new WrappedPacketOutEntityLook(new NMSPacket(packetInstance));
wrapper.setEntityId(getEntityId());
wrapper.setYaw(getYaw());
wrapper.setPitch(getPitch());
wrapper.setOnGround(isOnGround());
wrapper.setLook(true);
return packetInstance;
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
public static class WrappedPacketOutRelEntityMove extends WrappedPacketOutEntity {
public WrappedPacketOutRelEntityMove(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutRelEntityMove(int entityID, double deltaX, double deltaY, double deltaZ, boolean onGround) {
super(entityID, deltaX, deltaY, deltaZ, (byte) 0, (byte) 0, onGround, false);
}
@Override
protected void load() {
super.load();
try {
entityRelMovePacketConstructor = PacketTypeClasses.Play.Server.REL_ENTITY_MOVE.getConstructor();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
@Override
public Object asNMSPacket() {
try {
Object packetInstance = entityRelMovePacketConstructor.newInstance();
WrappedPacketOutRelEntityMove wrapper = new WrappedPacketOutRelEntityMove(new NMSPacket(packetInstance));
wrapper.setEntityId(getEntityId());
wrapper.setDeltaX(getDeltaX());
wrapper.setDeltaY(getDeltaY());
wrapper.setDeltaZ(getDeltaZ());
wrapper.setOnGround(isOnGround());
wrapper.setLook(false);
return packetInstance;
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
public static class WrappedPacketOutRelEntityMoveLook extends WrappedPacketOutEntity {
public WrappedPacketOutRelEntityMoveLook(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutRelEntityMoveLook(int entityID, double deltaX, double deltaY, double deltaZ, byte yaw, byte pitch, boolean onGround) {
super(entityID, deltaX, deltaY, deltaZ, yaw, pitch, onGround, false);
}
@Override
protected void load() {
super.load();
try {
entityRelMoveLookConstructor = PacketTypeClasses.Play.Server.REL_ENTITY_MOVE_LOOK.getConstructor();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
@Override
public Object asNMSPacket() {
try {
Object packetInstance = entityRelMoveLookConstructor.newInstance();
WrappedPacketOutRelEntityMoveLook wrapper = new WrappedPacketOutRelEntityMoveLook(new NMSPacket(packetInstance));
wrapper.setEntityId(getEntityId());
wrapper.setDeltaX(getDeltaX());
wrapper.setDeltaY(getDeltaY());
wrapper.setDeltaZ(getDeltaZ());
wrapper.setYaw(getYaw());
wrapper.setPitch(getPitch());
wrapper.setOnGround(isOnGround());
wrapper.setLook(true);
return packetInstance;
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
}
@@ -0,0 +1,181 @@
package io.github.retrooper.packetevents.packetwrappers.play.out.namedentityspawn;
import io.github.retrooper.packetevents.packettype.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.reflection.Reflection;
import io.github.retrooper.packetevents.utils.vector.Vector3d;
import org.bukkit.Location;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;
public class WrappedPacketOutNamedEntitySpawn extends WrappedPacket implements SendableWrapper {
private static final float rotationDividend = 256.0F / 360.0F;
private static boolean doublesPresent, dataWatcherPresent;
private static Constructor<?> packetDefaultConstructor;
private int entityID;
private UUID uuid;
private Vector3d position;
private float yaw, pitch;
public WrappedPacketOutNamedEntitySpawn(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutNamedEntitySpawn(int entityID, UUID uuid, Location location) {
this.entityID = entityID;
this.uuid = uuid;
this.position = new Vector3d(location.getX(), location.getY(), location.getZ());
this.yaw = location.getYaw();
this.pitch = location.getPitch();
}
public WrappedPacketOutNamedEntitySpawn(int entityID, UUID uuid, Vector3d position, float yaw, float pitch) {
this.entityID = entityID;
this.uuid = uuid;
this.position = position;
this.yaw = yaw;
this.pitch = pitch;
}
@Override
protected void load() {
doublesPresent = Reflection.getField(PacketTypeClasses.Play.Server.NAMED_ENTITY_SPAWN, double.class, 1) != null;
dataWatcherPresent = Reflection.getField(PacketTypeClasses.Play.Server.NAMED_ENTITY_SPAWN, NMSUtils.dataWatcherClass, 0) != null;
try {
packetDefaultConstructor = PacketTypeClasses.Play.Server.NAMED_ENTITY_SPAWN.getConstructor();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public UUID getUUID() {
if (packet != null) {
return readObject(0, UUID.class);
} else {
return uuid;
}
}
public void setUUID(UUID uuid) {
if (packet != null) {
write(UUID.class, 0, uuid);
} else {
this.uuid = uuid;
}
}
public Vector3d getPosition() {
if (packet != null) {
double x;
double y;
double z;
if (doublesPresent) {
x = readDouble(0);
y = readDouble(1);
z = readDouble(2);
} else {
x = readInt(1) / 32.0D; //TODO fix on 1.16, its doubles
y = readInt(2) / 32.0D;
z = readInt(3) / 32.0D;
}
return new Vector3d(x, y, z);
} else {
return position;
}
}
public void setPosition(Vector3d position) {
if (packet != null) {
if (doublesPresent) {
writeDouble(0, position.x);
writeDouble(1, position.y);
writeDouble(2, position.z);
} else {
writeInt(1, (int) (position.x * 32.0D));
writeInt(2, (int) (position.y * 32.0D));
writeInt(3, (int) (position.z * 32.0D));
}
writeByte(0, (byte) (yaw * rotationDividend));
writeByte(1, (byte) (pitch * rotationDividend));
} else {
this.position = position;
}
}
public float getYaw() {
if (packet != null) {
return readByte(0) / rotationDividend;
} else {
return yaw;
}
}
public void setYaw(float yaw) {
if (packet != null) {
writeByte(0, (byte) (yaw * rotationDividend));
} else {
this.yaw = yaw;
}
}
public float getPitch() {
if (packet != null) {
return readByte(1) / rotationDividend;
} else {
return pitch;
}
}
public void setPitch(float pitch) {
if (packet != null) {
writeByte(1, (byte) (pitch * rotationDividend));
} else {
this.pitch = pitch;
}
}
public int getEntityId() {
if (packet != null) {
return readInt(0);
} else {
return entityID;
}
}
public void setEntityId(int entityID) {
if (packet != null) {
writeInt(0, entityID);
} else {
this.entityID = entityID;
}
}
@Override
public Object asNMSPacket() {
try {
Object packetPlayOutNamedEntitySpawnInstance = packetDefaultConstructor.newInstance();
WrappedPacketOutNamedEntitySpawn wrappedPacketOutNamedEntitySpawn = new WrappedPacketOutNamedEntitySpawn(new NMSPacket(packetPlayOutNamedEntitySpawnInstance));
wrappedPacketOutNamedEntitySpawn.setEntityId(getEntityId());
wrappedPacketOutNamedEntitySpawn.setUUID(getUUID());
wrappedPacketOutNamedEntitySpawn.setPosition(getPosition());
wrappedPacketOutNamedEntitySpawn.setYaw(getYaw());
wrappedPacketOutNamedEntitySpawn.setPitch(getPitch());
if (dataWatcherPresent) {
wrappedPacketOutNamedEntitySpawn.write(NMSUtils.dataWatcherClass, 0, NMSUtils.generateDataWatcher(null));
}
return packetPlayOutNamedEntitySpawnInstance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
@@ -0,0 +1,239 @@
package io.github.retrooper.packetevents.packetwrappers.play.out.playerinfo;
import io.github.retrooper.packetevents.packettype.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.enums.EnumUtil;
import io.github.retrooper.packetevents.utils.gameprofile.GameProfileUtil;
import io.github.retrooper.packetevents.utils.gameprofile.WrappedGameProfile;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.player.GameMode;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
//TODO finish wrapper
public class WrappedPacketOutPlayerInfo extends WrappedPacket implements SendableWrapper {
private static Class<? extends Enum<?>> enumPlayerInfoActionClass;
private static Class<?> playerInfoDataClass;
private static Constructor<?> packetDefaultConstructor, playerInfoDataConstructor;
private static byte constructorMode = 0;
private PlayerInfoAction action;
private List<PlayerInfo> playerInfoList = new ArrayList<>();
public WrappedPacketOutPlayerInfo(NMSPacket packet) {
super(packet);
}
public WrappedPacketOutPlayerInfo(PlayerInfoAction action, List<PlayerInfo> playerInfoList) {
this.action = action;
this.playerInfoList = playerInfoList;
}
@Override
protected void load() {
enumPlayerInfoActionClass = SubclassUtil.getEnumSubClass(PacketTypeClasses.Play.Server.PLAYER_INFO, "EnumPlayerInfoAction");
try {
packetDefaultConstructor = PacketTypeClasses.Play.Server.PLAYER_INFO.getConstructor();
}
catch (NoSuchMethodException e) {
e.printStackTrace();
}
playerInfoDataClass = SubclassUtil.getSubClass(PacketTypeClasses.Play.Server.PLAYER_INFO, "PlayerInfoData");
if (playerInfoDataClass != null) {
try {
playerInfoDataConstructor = playerInfoDataClass.getConstructor(NMSUtils.gameProfileClass, int.class, NMSUtils.enumGameModeClass, NMSUtils.iChatBaseComponentClass);
} catch (NoSuchMethodException e) {
try {
playerInfoDataConstructor = playerInfoDataClass.getConstructor(PacketTypeClasses.Play.Server.PLAYER_INFO, NMSUtils.gameProfileClass, int.class, NMSUtils.enumGameModeClass, NMSUtils.iChatBaseComponentClass);
constructorMode = 1;
} catch (NoSuchMethodException e2) {
e.printStackTrace();
e2.printStackTrace();
}
}
}
}
public PlayerInfoAction getAction() {
if (packet != null) {
int index;
if (version.isOlderThan(ServerVersion.v_1_8)) {
index = readInt(0);
} else {
Enum<?> enumConst = readEnumConstant(0, enumPlayerInfoActionClass);
index = enumConst.ordinal();
}
return PlayerInfoAction.values()[index];
} else {
return action;
}
}
public void setAction(PlayerInfoAction action) {
if (packet != null) {
int index = action.ordinal();
if (version.isOlderThan(ServerVersion.v_1_8)) {
writeInt(0, index);
} else {
Enum<?> enumConst = EnumUtil.valueByIndex(enumPlayerInfoActionClass, action.ordinal());
writeEnumConstant(0, enumConst);
}
} else {
this.action = action;
}
}
public List<PlayerInfo> getPlayerInfo() {
if (packet != null) {
List<PlayerInfo> playerInfoList = new ArrayList<>();
if (version.isOlderThan(ServerVersion.v_1_8)) {
String username = readString(0);
Object mojangGameProfile = readObject(0, NMSUtils.gameProfileClass);
WrappedGameProfile gameProfile = GameProfileUtil.getWrappedGameProfile(mojangGameProfile);
GameMode gameMode = GameMode.values()[readInt(1)];
int ping = readInt(2);
playerInfoList.add(new PlayerInfo(username, gameProfile, gameMode, ping));
} else {
List<Object> nmsPlayerInfoDataList = readObject(0, List.class);
for (Object nmsPlayerInfoData : nmsPlayerInfoDataList) {
WrappedPacket nmsPlayerInfoDataWrapper = new WrappedPacket(new NMSPacket(nmsPlayerInfoData));
Object iChatBaseComponentName = nmsPlayerInfoDataWrapper.readObject(0, NMSUtils.iChatBaseComponentClass);
String username;
if (iChatBaseComponentName== null) {
username = null;
}
else {
username = NMSUtils.readIChatBaseComponent(iChatBaseComponentName);
}
Object mojangGameProfile = nmsPlayerInfoDataWrapper.readObject(0, NMSUtils.gameProfileClass);
WrappedGameProfile gameProfile = GameProfileUtil.getWrappedGameProfile(mojangGameProfile);
Enum<?> nmsGameModeEnumConstant = nmsPlayerInfoDataWrapper.readEnumConstant(0, NMSUtils.enumGameModeClass);
GameMode gameMode = GameMode.valueOf(nmsGameModeEnumConstant.name());
int ping = nmsPlayerInfoDataWrapper.readInt(0);
playerInfoList.add(new PlayerInfo(username, gameProfile, gameMode, ping));
}
}
return playerInfoList;
} else {
return playerInfoList;
}
}
public void setPlayerInfo(List<PlayerInfo> playerInfoList) throws UnsupportedOperationException {
if (version.isOlderThan(ServerVersion.v_1_8) && playerInfoList.size() > 1) {
throw new UnsupportedOperationException("The player info list size cannot be greater than 1 one 1.7.10 server versions!");
}
if (packet != null) {
if (version.isOlderThan(ServerVersion.v_1_8)) {
PlayerInfo playerInfo = playerInfoList.get(0);
writeString(0, playerInfo.username);
Object mojangGameProfile = GameProfileUtil.getGameProfile(playerInfo.gameProfile.id, playerInfo.gameProfile.name);
writeObject(0, mojangGameProfile);
writeInt(1, playerInfo.gameMode.ordinal());
writeInt(2, playerInfo.ping);
} else {
List<Object> nmsPlayerInfoList = new ArrayList<>();
for (PlayerInfo playerInfo : playerInfoList) {
Object usernameIChatBaseComponent = NMSUtils.generateIChatBaseComponent(NMSUtils.fromStringToJSON(playerInfo.username));
Object mojangGameProfile = GameProfileUtil.getGameProfile(playerInfo.gameProfile.id, playerInfo.gameProfile.name);
Enum<?> nmsGameModeEnumConstant = EnumUtil.valueOf(NMSUtils.enumGameModeClass, playerInfo.gameMode.name());
int ping = playerInfo.ping;
try {
if (constructorMode == 0) {
nmsPlayerInfoList.add(playerInfoDataConstructor.newInstance(mojangGameProfile, ping, nmsGameModeEnumConstant, usernameIChatBaseComponent));
} else if (constructorMode == 1) {
nmsPlayerInfoList.add(playerInfoDataConstructor.newInstance(null, mojangGameProfile, ping, nmsGameModeEnumConstant, usernameIChatBaseComponent));
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
write(List.class, 0, nmsPlayerInfoList);
}
} else {
this.playerInfoList = playerInfoList;
}
}
@Override
public Object asNMSPacket() {
try {
Object packetPlayOutPlayerInfoInstance = packetDefaultConstructor.newInstance();
WrappedPacketOutPlayerInfo playerInfoWrapper = new WrappedPacketOutPlayerInfo(new NMSPacket(packetPlayOutPlayerInfoInstance));
List<PlayerInfo> playerInfos = getPlayerInfo();
if (!playerInfos.isEmpty()) {
playerInfoWrapper.setPlayerInfo(playerInfos);
}
playerInfoWrapper.setAction(getAction());
return packetPlayOutPlayerInfoInstance;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public enum PlayerInfoAction {
ADD_PLAYER,
UPDATE_GAME_MODE,
UPDATE_LATENCY,
UPDATE_DISPLAY_NAME,
REMOVE_PLAYER
}
public static class PlayerInfo {
private String username;
private WrappedGameProfile gameProfile;
private GameMode gameMode;
private int ping;
public PlayerInfo(@Nullable String username, WrappedGameProfile gameProfile, GameMode gameMode, int ping) {
this.username = username;
this.gameProfile = gameProfile;
this.gameMode = gameMode;
this.ping = ping;
}
public WrappedGameProfile getGameProfile() {
return gameProfile;
}
public void setGameProfile(WrappedGameProfile gameProfile) {
this.gameProfile = gameProfile;
}
public GameMode getGameMode() {
return gameMode;
}
public void setGameMode(GameMode gameMode) {
this.gameMode = gameMode;
}
public int getPing() {
return ping;
}
public void setPing(int ping) {
this.ping = ping;
}
@Nullable
public String getUsername() {
return username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
}
}
@@ -0,0 +1,91 @@
package io.github.retrooper.packetevents.packetwrappers.play.out.respawn;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.player.GameMode;
import io.github.retrooper.packetevents.utils.reflection.SubclassUtil;
import io.github.retrooper.packetevents.utils.world.Difficulty;
import io.github.retrooper.packetevents.utils.world.Dimension;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import io.github.retrooper.packetevents.utils.world.LevelType;
import org.jetbrains.annotations.Nullable;
//TODO finish
class WrappedPacketOutRespawn extends WrappedPacket implements SendableWrapper {
private static Class<?> dimensionManagerClass;
private static Class<?> worldTypeClass;
private static Class<? extends Enum<?>> enumDifficultyClass;
private Dimension dimension;
private Difficulty difficulty;
private GameMode gameMode;
private LevelType levelType;
public WrappedPacketOutRespawn(NMSPacket packet) {
super(packet);
}
@Override
protected void load() {
dimensionManagerClass = NMSUtils.getNMSClassWithoutException("DimensionManager");
worldTypeClass = NMSUtils.getNMSClassWithoutException("WorldType");
enumDifficultyClass = NMSUtils.getNMSEnumClassWithoutException("EnumDifficulty");
}
public Dimension getDimension() {
if (packet != null) {
int dimensionID;
if (version.isOlderThan(ServerVersion.v_1_13_2)) {
dimensionID = readInt(0);
} else {
Object dimensionManagerObject = readObject(0, dimensionManagerClass);
WrappedPacket dimensionManagerWrapper = new WrappedPacket(new NMSPacket(dimensionManagerObject));
dimensionID = dimensionManagerWrapper.readInt(0) - 1;
}
return Dimension.getById(dimensionID);
} else {
return dimension;
}
}
/*
public Difficulty getDifficulty() {
if (packet != null) {
Enum<?> enumConst = readEnumConstant(0, enumDifficultyClass);
return Difficulty.values()[enumConst.ordinal()];
} else {
return difficulty;
}
}*/
@Nullable
public GameMode getGameMode() {
if (packet != null) {
Enum<?> enumConst = readEnumConstant(0, NMSUtils.enumGameModeClass);
try {
return GameMode.valueOf(enumConst.name());
}
catch (IllegalArgumentException ex) {
return null;
}
} else {
return gameMode;
}
}
/*
public LevelType getLevelType() {
if (packet != null) {
//TODO
Object worldTypeObject = readObject(0, worldTypeClass);
WrappedPacket worldTypeWrapper = new WrappedPacket(new NMSPacket(worldTypeObject));
String worldTypeName = worldTypeWrapper.readString(0);
return LevelType.getByName(worldTypeName);
}
else {
return levelType;
}
}*/
@Override
public Object asNMSPacket() {
return null;
}
}
@@ -0,0 +1,59 @@
package io.github.retrooper.packetevents.packetwrappers.play.out.viewdistance;
import io.github.retrooper.packetevents.packettype.PacketTypeClasses;
import io.github.retrooper.packetevents.packetwrappers.NMSPacket;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.WrappedPacket;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class WrappedPacketOutViewDistance extends WrappedPacket implements SendableWrapper {
private static Constructor<?> packetConstructor;
private int viewDistance;
public WrappedPacketOutViewDistance(NMSPacket packet) {
super(packet);
}
@Override
protected void load() {
try {
packetConstructor = PacketTypeClasses.Play.Server.VIEW_DISTANCE.getConstructor(int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public int getViewDistance() {
if (packet != null) {
return readInt(0);
} else {
return viewDistance;
}
}
public void setViewDistance(int viewDistance) {
if (packet != null) {
writeInt(0, viewDistance);
} else {
this.viewDistance = viewDistance;
}
}
@Override
public Object asNMSPacket() {
try {
return packetConstructor.newInstance(getViewDistance());
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
@Override
public boolean isSupported() {
return version.isNewerThan(ServerVersion.v_1_13_2); //TODO civ
}
}
@@ -188,7 +188,6 @@ public class PacketProcessorInternal {
*/
public void postRead(Player player, Object channel, Object packet) {
if (getPacketState(player, packet) == PacketState.PLAY) {
//Since player != null check is done, status and login packets won't come passed this point.
PostPacketPlayReceiveEvent event = new PostPacketPlayReceiveEvent(player, channel, new NMSPacket(packet));
PacketEvents.get().getEventManager().callEvent(event);
interceptPostPlayReceive(event);
@@ -207,7 +206,6 @@ public class PacketProcessorInternal {
*/
public void postWrite(Player player, Object channel, Object packet) {
if (getPacketState(player, packet) == PacketState.PLAY) {
//Since player != null check is done, status and login packets won't come passed this point.
PostPacketPlaySendEvent event = new PostPacketPlaySendEvent(player, channel, new NMSPacket(packet));
PacketEvents.get().getEventManager().callEvent(event);
interceptPostPlaySend(event);
@@ -220,16 +218,14 @@ public class PacketProcessorInternal {
* @param event PLAY server-bound packet event.
*/
private void interceptPlayReceive(PacketPlayReceiveEvent event) {
if (event.getPlayer() != null) {
if (event.getPacketId() == PacketType.Play.Client.KEEP_ALIVE) {
UUID uuid = event.getPlayer().getUniqueId();
long timestamp = keepAliveMap.getOrDefault(uuid, event.getTimestamp());
long currentTime = event.getTimestamp();
long ping = currentTime - timestamp;
long smoothedPing = (PacketEvents.get().getPlayerUtils().getSmoothedPing(event.getPlayer().getUniqueId()) * 3L + ping) / 4;
PacketEvents.get().getPlayerUtils().playerPingMap.put(uuid, (int) ping);
PacketEvents.get().getPlayerUtils().playerSmoothedPingMap.put(uuid, (int) smoothedPing);
}
if (event.getPacketId() == PacketType.Play.Client.KEEP_ALIVE) {
UUID uuid = event.getPlayer().getUniqueId();
long timestamp = keepAliveMap.getOrDefault(uuid, event.getTimestamp());
long currentTime = event.getTimestamp();
long ping = currentTime - timestamp;
long smoothedPing = (PacketEvents.get().getPlayerUtils().getSmoothedPing(event.getPlayer().getUniqueId()) * 3L + ping) / 4;
PacketEvents.get().getPlayerUtils().playerPingMap.put(uuid, (int) ping);
PacketEvents.get().getPlayerUtils().playerSmoothedPingMap.put(uuid, (int) smoothedPing);
}
}
@@ -45,8 +45,7 @@ public class PacketEventsSettings {
/**
* This boolean stores if PacketEvents should inject a player earlier using the {@code LateInjector}.
* We also call it the "compatibility injector", because it should actually be compatible with everything.
* Using this injector prevents us from listening to packets during the early packet-states. (such as LOGIN and STATUS state)
* PacketEvents requires these early states to be able to detect client versions of players without the help of any dependencies!
* Using this injector prevents us from listening to packets during the early packet-states. (STATUS, HANDSHAKING, LOGIN)
*/
private boolean compatInjector = false;
@@ -43,6 +43,12 @@ public class WrappedGameProfile {
this.legacy = legacy;
}
public WrappedGameProfile(UUID id, String name) {
this.id = id;
this.name = name;
this.legacy = false;
}
public UUID getId() {
return id;
}
@@ -45,20 +45,22 @@ import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
public final class NMSUtils {
private static final String NMS_DIR = ServerVersion.getNMSDirectory() + ".";
private static final String OBC_DIR = ServerVersion.getOBCDirectory() + ".";
public static boolean legacyNettyImportMode;
public static ServerVersion version;
public static Constructor<?> blockPosConstructor, minecraftKeyConstructor, vec3DConstructor;
public static Constructor<?> blockPosConstructor, minecraftKeyConstructor, vec3DConstructor, dataWatcherConstructor;
public static Class<?> nmsEntityClass, minecraftServerClass, craftWorldClass, playerInteractManagerClass, entityPlayerClass, playerConnectionClass, craftServerClass,
craftPlayerClass, serverConnectionClass, craftEntityClass, nmsItemStackClass, networkManagerClass, nettyChannelClass, gameProfileClass, iChatBaseComponentClass,
blockPosClass, vec3DClass, channelFutureClass, blockClass, iBlockDataClass, nmsWorldClass, craftItemStackClass,
soundEffectClass, minecraftKeyClass, chatSerializerClass, craftMagicNumbersClass;
public static Class<? extends Enum<?>> enumDirectionClass, enumHandClass;
soundEffectClass, minecraftKeyClass, chatSerializerClass, craftMagicNumbersClass, worldSettingsClass, worldServerClass, dataWatcherClass, nmsEntityHumanClass, dedicatedServerClass;
public static Class<? extends Enum<?>> enumDirectionClass, enumHandClass, enumGameModeClass;
public static Method getBlockPosX, getBlockPosY, getBlockPosZ;
private static String nettyPrefix;
private static Method getCraftPlayerHandle;
@@ -122,6 +124,10 @@ public final class NMSUtils {
nmsWorldClass = getNMSClass("World");
soundEffectClass = getNMSClassWithoutException("SoundEffect");
minecraftKeyClass = getNMSClassWithoutException("MinecraftKey");
worldServerClass = getNMSClassWithoutException("WorldServer");
dataWatcherClass = getNMSClassWithoutException("DataWatcher");
nmsEntityHumanClass = getNMSClassWithoutException("EntityHuman");
dedicatedServerClass = getNMSClassWithoutException("DedicatedServer");
try {
gameProfileClass = Class.forName("net.minecraft.util.com.mojang.authlib.GameProfile");
} catch (ClassNotFoundException e) {
@@ -142,6 +148,10 @@ public final class NMSUtils {
vec3DConstructor = NMSUtils.vec3DClass.getDeclaredConstructor(double.class, double.class, double.class);
vec3DConstructor.setAccessible(true);
}
if (dataWatcherClass != null) {
dataWatcherConstructor = dataWatcherClass.getConstructor(nmsEntityClass);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
@@ -193,14 +203,20 @@ public final class NMSUtils {
getBlockPosY = Reflection.getMethod(NMSUtils.blockPosClass.getSuperclass(), "getY", 0);
getBlockPosZ = Reflection.getMethod(NMSUtils.blockPosClass.getSuperclass(), "getZ", 0);
}
enumHandClass = (Class<Enum<?>>) getNMSClassWithoutException("EnumHand");
worldSettingsClass = NMSUtils.getNMSClassWithoutException("WorldSettings");
enumHandClass = getNMSEnumClassWithoutException("EnumHand");
enumGameModeClass = NMSUtils.getNMSEnumClassWithoutException("EnumGamemode");
if (enumGameModeClass == null) {
enumGameModeClass = SubclassUtil.getEnumSubClass(worldSettingsClass, "EnumGamemode");
}
}
public static Object getMinecraftServerInstance() {
public static Object getMinecraftServerInstance(Server server) {
if (minecraftServer == null) {
try {
minecraftServer = Reflection.getField(craftServerClass, minecraftServerClass, 0)
.get(Bukkit.getServer());
.get(server);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
@@ -211,7 +227,7 @@ public final class NMSUtils {
public static Object getMinecraftServerConnection() {
if (minecraftServerConnection == null) {
try {
minecraftServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0).get(getMinecraftServerInstance());
minecraftServerConnection = Reflection.getField(minecraftServerClass, serverConnectionClass, 0).get(getMinecraftServerInstance(Bukkit.getServer()));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
@@ -220,7 +236,7 @@ public final class NMSUtils {
}
public static double[] recentTPS() {
return new WrappedPacket(new NMSPacket(getMinecraftServerInstance()), minecraftServerClass).readDoubleArray(0);
return new WrappedPacket(new NMSPacket(getMinecraftServerInstance(Bukkit.getServer())), minecraftServerClass).readDoubleArray(0);
}
public static Class<?> getNMSClass(String name) throws ClassNotFoundException {
@@ -273,8 +289,7 @@ public final class NMSUtils {
}
}
return entity;
}
catch(Exception ex){
} catch (Exception ex) {
return null;
}
}
@@ -384,10 +399,15 @@ public final class NMSUtils {
public static Object convertBukkitServerToNMSServer(Server server) {
Object craftServer = craftServerClass.cast(server);
WrappedPacket wrapper = new WrappedPacket(new NMSPacket(craftServer));
return wrapper.readObject(0, minecraftServerClass);
try {
return wrapper.readObject(0, minecraftServerClass);
} catch (Exception ex) {
wrapper.readObject(0, dedicatedServerClass);
}
return null;
}
public static Object convertBukkitWorldToNMSWorld(World world) {
public static Object convertBukkitWorldToWorldServer(World world) {
Object craftWorld = craftWorldClass.cast(world);
try {
return getCraftWorldHandle.invoke(craftWorld);
@@ -397,7 +417,11 @@ public final class NMSUtils {
return null;
}
@Nullable
public static Object generateIChatBaseComponent(String text) {
if (text == null) {
return null;
}
try {
return chatFromStringMethod.invoke(null, text);
} catch (IllegalAccessException | InvocationTargetException e) {
@@ -406,6 +430,7 @@ public final class NMSUtils {
return null;
}
public static Object[] generateIChatBaseComponents(String... texts) {
Object[] components = new Object[texts.length];
for (int i = 0; i < components.length; i++) {
@@ -414,7 +439,11 @@ public final class NMSUtils {
return components;
}
@Nullable
public static String readIChatBaseComponent(Object iChatBaseComponent) {
if (iChatBaseComponent == null) {
return null;
}
try {
return getMessageMethod.invoke(iChatBaseComponent).toString();
} catch (IllegalAccessException | InvocationTargetException e) {
@@ -441,6 +470,9 @@ public final class NMSUtils {
}
public static String fromStringToJSON(String message) {
if (message == null) {
return null;
}
return "{\"text\": \"" + message + "\"}";
}
@@ -493,4 +525,40 @@ public final class NMSUtils {
}
return null;
}
public static Object generateDataWatcher(Entity entity) {
Object nmsEntity = null;
try {
return dataWatcherConstructor.newInstance(nmsEntity);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
private static final ThreadLocal<Random> randomThreadLocal = ThreadLocal.withInitial(Random::new);
public static UUID generateUUID() {
long var1 = randomThreadLocal.get().nextLong() & -61441L | 16384L;
long var3 = randomThreadLocal.get().nextLong() & 4611686018427387903L | -9223372036854775808L;
return new UUID(var1, var3);
}
public static int generateEntityId() {
Field field = Reflection.getField(nmsEntityClass, "entityCount");
try {
if (field.getType().equals(AtomicInteger.class)) {
//Newer versions
AtomicInteger atomicInteger = (AtomicInteger) field.get(null);
return atomicInteger.incrementAndGet();
} else {
int id = field.getInt(null) + 1;
field.set(null, id);
return id;
}
} catch (IllegalAccessException ex) {
ex.printStackTrace();
}
throw new IllegalStateException("Failed to generate a new unique entity ID!");
}
}
@@ -0,0 +1,13 @@
package io.github.retrooper.packetevents.utils.player;
/**
* Representation of a player's game mode.
* @author retrooper
* @since 1.8
*/
public enum GameMode {
SURVIVAL,
CREATIVE,
ADVENTURE,
SPECTATOR
}
@@ -26,10 +26,14 @@ package io.github.retrooper.packetevents.utils.player;
import io.github.retrooper.packetevents.PacketEvents;
import io.github.retrooper.packetevents.packetwrappers.SendableWrapper;
import io.github.retrooper.packetevents.packetwrappers.play.out.playerinfo.WrappedPacketOutPlayerInfo;
import io.github.retrooper.packetevents.utils.gameprofile.WrappedGameProfile;
import io.github.retrooper.packetevents.utils.nms.NMSUtils;
import io.github.retrooper.packetevents.utils.server.ServerVersion;
import io.github.retrooper.packetevents.utils.vector.Vector3d;
import io.github.retrooper.packetevents.utils.versionlookup.VersionLookupUtils;
import io.github.retrooper.packetevents.utils.versionlookup.v_1_7_10.SpigotVersionLookup_1_7;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@@ -60,6 +64,11 @@ public final class PlayerUtils {
*/
public final Map<UUID, Integer> playerSmoothedPingMap = new ConcurrentHashMap<>();
/**
* This map stores the wrapped game profiles for all users.
*/
public final Map<UUID, WrappedGameProfile> gameProfileMap= new ConcurrentHashMap<>();
/**
* This map stores the client version of a player only when it has been confirmed.
* Since some plugins like ViaBackwards take around one tick from the PlayerJoinEvent to resolve a player's
@@ -165,7 +174,7 @@ public final class PlayerUtils {
public ClientVersion getClientVersion(final Player player) {
ClientVersion version = clientVersionsMap.get(player.getAddress());
if (version == null) {
//Prioritize ViaVersion and ProtocolSupport as they modify the protocol version in the packet we access it from.
//Prioritize asking ViaVersion and ProtocolSupport as they modify the protocol version in the packet we access it from.
if (VersionLookupUtils.isDependencyAvailable()) {
try {
version = ClientVersion.getClientVersion(VersionLookupUtils.getProtocolVersion(player));
@@ -179,13 +188,16 @@ public final class PlayerUtils {
//We can trust the version we retrieved from the packet.
version = tempClientVersionMap.get(player.getAddress());
if (version == null) {
//We couldn't snatch that version from the packet.
short protocolVersion;
//Handle 1.7.10, luckily 1.7.10 provides a method for us to access a player's protocol version(1.7.10 servers support 1.8 clients too)
if (PacketEvents.get().getServerUtils().getVersion().equals(ServerVersion.v_1_7_10)) {
//Handle 1.7.10, luckily 1.7.10 provides a method for us to access a player's protocol version(because 1.7.10 servers support 1.8 clients too)
if (PacketEvents.get().getServerUtils().getVersion().isOlderThan(ServerVersion.v_1_8)) {
protocolVersion = (short) SpigotVersionLookup_1_7.getProtocolVersion(player);
} else {
//We failed to retrieve the version from the packet and no dependency is available.
//No dependency available, couldn't snatch the version from the packet AND server version is not 1.7.10
//We are pretty safe to assume the version is the same as the server, as ViaVersion AND ProtocolSupport could not be found.
//If you aren't using ViaVersion or ProtocolSupport, how are you supporting multiple protocol versions?
//(WE DONT SUPPORT CUSTOM PROTOCOL VERSION HACKS other than viaversion & protocolsupport)
protocolVersion = PacketEvents.get().getServerUtils().getVersion().getProtocolVersion();
}
version = ClientVersion.getClientVersion(protocolVersion);
@@ -261,4 +273,14 @@ public final class PlayerUtils {
public void sendNMSPacket(Object channel, Object packet) {
PacketEvents.get().injector.sendPacket(channel, packet);
}
public WrappedGameProfile getGameProfile(Player player) {
UUID uuid = player.getUniqueId();
WrappedGameProfile gameProfile = gameProfileMap.get(uuid);
if (gameProfile == null) {
gameProfile = new WrappedGameProfile(player.getUniqueId(), player.getName(), false);
gameProfileMap.put(uuid, gameProfile);
}
return gameProfile;
}
}
@@ -196,7 +196,7 @@ public final class Reflection {
//Remove final modifier
Field modifiersField = null;
try {
modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField = getModifiersField();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
@@ -207,4 +207,26 @@ public final class Reflection {
e.printStackTrace();
}
}
private static Field getModifiersField() throws NoSuchFieldException {
try {
//This should work on Java 8 - 11
return Field.class.getDeclaredField("modifiers");
} catch (NoSuchFieldException e) {
//Java 12 support!
try {
Method getDeclaredFields0 = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
getDeclaredFields0.setAccessible(true);
Field[] fields = (Field[]) getDeclaredFields0.invoke(Field.class, false);
for (Field field : fields) {
if ("modifiers".equals(field.getName())) {
return field;
}
}
} catch (ReflectiveOperationException ex) {
e.addSuppressed(ex);
}
throw e;
}
}
}
@@ -40,7 +40,7 @@ public class SubclassUtil {
return null;
}
for (Class<?> subClass : cls.getDeclaredClasses()) {
if (ClassUtil.getClassSimpleName(subClass).equals(name)) {
if (subClass.getSimpleName().equals(name)) {
return subClass;
}
}
@@ -0,0 +1,12 @@
package io.github.retrooper.packetevents.utils.world;
public enum Difficulty {
PEACEFUL,
EASY,
NORMAL,
HARD;
public String getName() {
return name().toLowerCase();
}
}
@@ -0,0 +1,19 @@
package io.github.retrooper.packetevents.utils.world;
public enum Dimension {
NETHER(-1),
OVERWORLD(0),
END(1);
private final int id;
Dimension(int id) {
this.id = id;
}
public int getId() {
return id;
}
public static Dimension getById(int id) {
return values()[id + 1];
}
}
@@ -0,0 +1,28 @@
package io.github.retrooper.packetevents.utils.world;
import org.jetbrains.annotations.Nullable;
public enum LevelType {
DEFAULT, FLAT, LARGE_BIOMES("largeBiomes"), AMPLIFIED, CUSTOMIZED, DEBUG_ALL_BLOCK_STATES, DEFAULT_1_1;
private final String name;
LevelType() {
this.name = name().toLowerCase();
}
LevelType(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Nullable
public static LevelType getByName(String name) {
for (LevelType type : values()) {
if (type.getName().equals(name)) {
return type;
}
}
return null;
}
}