Compare commits

..
23 Commits
Author SHA1 Message Date
Nassim Jahnke d08f15c095 4.6.2 Release 2023-03-24 22:00:05 +01:00
Nassim Jahnke 8aa7898755 Cherry-pick some changes from dev 2023-03-24 17:58:53 +01:00
RK_01 641171a14f Properly handle dismount in PLAYER_POSITION packet (#3272) 2023-03-21 21:53:44 +01:00
Nassim Jahnke 23f045feee Fix glass pane and iron bars block connections
Fixes #3269
2023-03-20 10:31:13 +01:00
Nassim Jahnke f1bde8ba2a Handle shifted 1.19.4 boat types 2023-03-18 12:28:00 +01:00
Nassim Jahnke 9ccc3aed30 Keep all 1.12 translation mappings cached 2023-03-18 10:01:37 +01:00
Nassim Jahnke ad56caeb88 Double the trouble 2023-03-17 21:47:55 +01:00
Nassim Jahnke 573201c0b1 Only load JoinListener things early 2023-03-17 18:37:48 +01:00
Nassim Jahnke e298a7efac Fix protocol detection on some versions of Spigot
Fixes #3263
2023-03-17 18:36:48 +01:00
Nassim Jahnke 2e59a51734 Add PacketValue toString 2023-03-17 13:26:13 +01:00
Nassim Jahnke d4894ca4b5 Fix #3260 2023-03-17 13:15:56 +01:00
Nassim Jahnke 7f7c6241de Fix 1.12->1.13 stop sound handling
Fixes #3247
2023-03-17 11:37:37 +01:00
Nassim Jahnke 51606eb5ef Bump version to 4.6.2-SNAPSHOT 2023-03-17 11:34:35 +01:00
Nassim Jahnke c9883c2638 4.6.1 Release 2023-03-16 20:44:53 +01:00
Nassim Jahnke 74fb55d96b Update yaml compat checker 2023-03-16 20:41:03 +01:00
Nassim Jahnke 4e844a0095 Small startup time improvements 2023-03-16 12:48:39 +01:00
Nassim Jahnke da7f8ea3b6 Be more safe 2023-03-15 16:21:15 +01:00
Nassim Jahnke 81c4e530e9 Possibly fix joinlistener on 1.19.4 Spigot 2023-03-15 16:15:21 +01:00
Nassim Jahnke b1524642aa Fix protocol detection on 1.19.4 Spigot
Fixes #3241
2023-03-15 10:09:45 +01:00
Nassim Jahnke a828c43f99 Remove ignoreCancelled from ArmorToggleListener, small cleanup
Spigot considers interacting with air "cancelled"
Fixes #3240
2023-03-15 09:20:21 +01:00
Nassim Jahnke fccfadf1b7 Handle falling blocks
Fixes #3244
2023-03-15 09:04:13 +01:00
lixfel 18b41c82c4 1.15.2 Spigot/Paper NoSuchMethodError YamlCompat fix (#3242) 2023-03-14 21:48:40 +01:00
Nassim Jahnke 27ee6f519e Bump version to 4.6.1-SNAPSHOT 2023-03-14 21:48:18 +01:00
33 changed files with 357 additions and 158 deletions

No files matched your search

@@ -131,4 +131,11 @@ public interface ViaManager {
* @param runnable runnable to be executed
*/
void addEnableListener(Runnable runnable);
/**
* Returns whether the manager has been initialized (and protocols have been loaded).
*
* @return whether the manager has been initialized
*/
boolean isInitialized();
}
@@ -256,6 +256,8 @@ public interface ViaVersionConfig {
*/
boolean is1_13TeamColourFix();
boolean shouldRegisterUserConnectionOnJoin();
/**
* Should we fix shift quick move action for 1.12 clients
*
@@ -104,23 +104,22 @@ public interface ViaPlatform<T> {
PlatformTask runSync(Runnable runnable);
/**
* Run a task Sync after a interval
* This must be only used after plugin enable.
* Runs a synchronous task after a delay in ticks.
*
* @param runnable The task to run
* @param ticks The interval to run it after
* @return The Task ID
* @param runnable task to run
* @param delay delay in ticks to run it after
* @return created task
*/
PlatformTask runSync(Runnable runnable, long ticks);
PlatformTask runSync(Runnable runnable, long delay);
/**
* Run a task at a repeating interval.
* Runs a synchronous task at a repeating interval.
*
* @param runnable The task to run
* @param ticks The interval to run it at
* @return The Task ID
* @param runnable task to run
* @param period period in ticks to run at
* @return created task
*/
PlatformTask runRepeatingSync(Runnable runnable, long ticks);
PlatformTask runRepeatingSync(Runnable runnable, long period);
/**
* Get the online players
@@ -237,6 +237,6 @@ public abstract class Type<T> implements ByteBufReader<T>, ByteBufWriter<T> {
@Override
public String toString() {
return "Type|" + typeName;
return typeName;
}
}
@@ -57,10 +57,12 @@ public class ViaBukkitListener extends ViaListener implements Listener {
*/
@Override
public void register() {
if (isRegistered()) return;
if (isRegistered()) {
return;
}
plugin.getServer().getPluginManager().registerEvents(this, plugin);
setRegistered(true);
plugin.getServer().getPluginManager().registerEvents(this, plugin);
}
public Plugin getPlugin() {
@@ -27,6 +27,7 @@ import com.viaversion.viaversion.api.platform.UnsupportedSoftware;
import com.viaversion.viaversion.api.platform.ViaPlatform;
import com.viaversion.viaversion.bukkit.commands.BukkitCommandHandler;
import com.viaversion.viaversion.bukkit.commands.BukkitCommandSender;
import com.viaversion.viaversion.bukkit.listeners.JoinListener;
import com.viaversion.viaversion.bukkit.platform.BukkitViaAPI;
import com.viaversion.viaversion.bukkit.platform.BukkitViaConfig;
import com.viaversion.viaversion.bukkit.platform.BukkitViaInjector;
@@ -79,6 +80,11 @@ public class ViaVersionPlugin extends JavaPlugin implements ViaPlatform<Player>
// Config magic
conf = new BukkitViaConfig();
// Load a bunch of classes early with slow reflection and more classloading
if (conf.shouldRegisterUserConnectionOnJoin()) {
Via.getManager().getScheduler().execute(JoinListener::init);
}
}
@Override
@@ -171,13 +177,13 @@ public class ViaVersionPlugin extends JavaPlugin implements ViaPlatform<Player>
}
@Override
public PlatformTask runSync(Runnable runnable, long ticks) {
return new BukkitViaTask(getServer().getScheduler().runTaskLater(this, runnable, ticks));
public PlatformTask runSync(Runnable runnable, long delay) {
return new BukkitViaTask(getServer().getScheduler().runTaskLater(this, runnable, delay));
}
@Override
public PlatformTask runRepeatingSync(Runnable runnable, long ticks) {
return new BukkitViaTask(getServer().getScheduler().runTaskTimer(this, runnable, 0, ticks));
public PlatformTask runRepeatingSync(Runnable runnable, long period) {
return new BukkitViaTask(getServer().getScheduler().runTaskTimer(this, runnable, 0, period));
}
@Override
@@ -25,6 +25,7 @@ import com.viaversion.viaversion.bukkit.util.NMSUtil;
import io.netty.channel.Channel;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.logging.Level;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
@@ -41,13 +42,13 @@ public class JoinListener implements Listener {
private static final Field CHANNEL;
static {
Method gh = null;
Field conn = null, nm = null, ch = null;
Method getHandleMethod = null;
Field gamePacketListenerField = null, connectionField = null, channelField = null;
try {
gh = NMSUtil.obc("entity.CraftPlayer").getDeclaredMethod("getHandle");
conn = findField(gh.getReturnType(), "PlayerConnection", "ServerGamePacketListenerImpl");
nm = findField(conn.getType(), "NetworkManager", "Connection");
ch = findField(nm.getType(), "Channel");
getHandleMethod = NMSUtil.obc("entity.CraftPlayer").getDeclaredMethod("getHandle");
gamePacketListenerField = findField(getHandleMethod.getReturnType(), "PlayerConnection", "ServerGamePacketListenerImpl");
connectionField = findField(gamePacketListenerField.getType(), "NetworkManager", "Connection");
channelField = findField(connectionField.getType(), Class.forName("io.netty.channel.Channel"));
} catch (NoSuchMethodException | NoSuchFieldException | ClassNotFoundException e) {
Via.getPlatform().getLogger().log(
Level.WARNING,
@@ -55,22 +56,47 @@ public class JoinListener implements Listener {
"Login race condition fixer will be disabled.\n" +
" Some plugins that use ViaAPI on join event may work incorrectly.", e);
}
GET_HANDLE = gh;
CONNECTION = conn;
NETWORK_MANAGER = nm;
CHANNEL = ch;
GET_HANDLE = getHandleMethod;
CONNECTION = gamePacketListenerField;
NETWORK_MANAGER = connectionField;
CHANNEL = channelField;
}
public static void init() {
}
// Loosely search a field with any name, as long as it matches a type name.
private static Field findField(Class<?> cl, String... types) throws NoSuchFieldException {
for (Field field : cl.getDeclaredFields()) {
for (String type : types)
if (field.getType().getSimpleName().equals(type))
return field;
private static Field findField(Class<?> clazz, String... types) throws NoSuchFieldException {
for (Field field : clazz.getDeclaredFields()) {
String fieldTypeName = field.getType().getSimpleName();
for (String type : types) {
if (!fieldTypeName.equals(type)) {
continue;
}
if (!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
}
return field;
}
}
throw new NoSuchFieldException(types[0]);
}
private static Field findField(Class<?> clazz, Class<?> fieldType) throws NoSuchFieldException {
for (Field field : clazz.getDeclaredFields()) {
if (field.getType() != fieldType) {
continue;
}
if (!Modifier.isPublic(field.getModifiers())) {
field.setAccessible(true);
}
return field;
}
throw new NoSuchFieldException(fieldType.getSimpleName());
}
@EventHandler(priority = EventPriority.LOWEST)
public void onJoin(PlayerJoinEvent e) {
if (CHANNEL == null) return;
@@ -27,42 +27,30 @@ import org.bukkit.event.EventPriority;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
public final class ArmorToggleListener extends ViaBukkitListener {
private static final boolean ENABLED = hasEquipmentSlot();
public ArmorToggleListener(final ViaVersionPlugin plugin) {
super(plugin, Protocol1_19_4To1_19_3.class);
}
private static boolean hasEquipmentSlot() {
// Doesn't exist on 1.8
try {
Material.class.getMethod("getEquipmentSlot");
return true;
} catch (final NoSuchMethodException e) {
return false;
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
@EventHandler(priority = EventPriority.MONITOR)
public void itemUse(final PlayerInteractEvent event) {
if (!ENABLED) {
return;
}
final Player player = event.getPlayer();
if (!isOnPipe(player) || event.getItem() == null) {
final ItemStack item = event.getItem();
if (item == null || event.getHand() == null || !isOnPipe(player)) {
return;
}
final EquipmentSlot equipmentSlot = event.getItem().getType().getEquipmentSlot();
if (equipmentSlot != EquipmentSlot.HAND && equipmentSlot != EquipmentSlot.OFF_HAND) {
final ItemStack armor = player.getInventory().getItem(equipmentSlot);
final EquipmentSlot armorItemSlot = item.getType().getEquipmentSlot();
if (armorItemSlot != EquipmentSlot.HAND && armorItemSlot != EquipmentSlot.OFF_HAND) {
final PlayerInventory inventory = player.getInventory();
final ItemStack armor = inventory.getItem(armorItemSlot);
// If two pieces of armor are equal, the client will do nothing.
if (armor != null && armor.getType() != Material.AIR && !armor.equals(event.getItem())) {
player.updateInventory();
if (armor != null && armor.getType() != Material.AIR && !armor.equals(item)) {
inventory.setItem(event.getHand(), inventory.getItem(event.getHand()));
inventory.setItem(armorItemSlot, armor);
}
}
}
@@ -32,6 +32,7 @@ public class BukkitViaConfig extends AbstractViaConfig {
private boolean hitboxFix1_14;
private String blockConnectionMethod;
private boolean armorToggleFix;
private boolean registerUserConnectionOnJoin;
public BukkitViaConfig() {
super(new File(((Plugin) Via.getPlatform()).getDataFolder(), "config.yml"));
@@ -41,6 +42,7 @@ public class BukkitViaConfig extends AbstractViaConfig {
@Override
protected void loadFields() {
super.loadFields();
registerUserConnectionOnJoin = getBoolean("register-userconnections-on-join", true);
quickMoveActionFix = getBoolean("quick-move-action-fix", false);
hitboxFix1_9 = getBoolean("change-1_9-hitbox", false);
hitboxFix1_14 = getBoolean("change-1_14-hitbox", false);
@@ -52,6 +54,11 @@ public class BukkitViaConfig extends AbstractViaConfig {
protected void handleConfig(Map<String, Object> config) {
}
@Override
public boolean shouldRegisterUserConnectionOnJoin() {
return registerUserConnectionOnJoin;
}
@Override
public boolean is1_12QuickMoveActionFix() {
return quickMoveActionFix;
@@ -17,6 +17,7 @@
*/
package com.viaversion.viaversion.bukkit.platform;
import com.google.common.base.Preconditions;
import com.viaversion.viaversion.bukkit.handlers.BukkitChannelInitializer;
import com.viaversion.viaversion.bukkit.util.NMSUtil;
import com.viaversion.viaversion.platform.LegacyViaInjector;
@@ -35,6 +36,10 @@ import org.checkerframework.checker.nullness.qual.Nullable;
public class BukkitViaInjector extends LegacyViaInjector {
private static final boolean HAS_WORLD_VERSION_PROTOCOL_VERSION = PaperViaInjector.hasClass("net.minecraft.SharedConstants")
&& PaperViaInjector.hasClass("net.minecraft.WorldVersion")
&& !PaperViaInjector.hasClass("com.mojang.bridge.game.GameVersion");
@Override
public void inject() throws ReflectiveOperationException {
if (PaperViaInjector.PAPER_INJECTION_METHOD) {
@@ -62,10 +67,37 @@ public class BukkitViaInjector extends LegacyViaInjector {
return Bukkit.getUnsafe().getProtocolVersion();
}
// Time to go on a journey! The protocol version is hidden inside an int in ServerPing.ServerData
return HAS_WORLD_VERSION_PROTOCOL_VERSION ? cursedProtocolDetection() : veryCursedProtocolDetection();
}
private int cursedProtocolDetection() throws ReflectiveOperationException {
// Get the version from SharedConstants.getWorldVersion().getProtocolVersion()
Class<?> sharedConstantsClass = Class.forName("net.minecraft.SharedConstants");
Class<?> worldVersionClass = Class.forName("net.minecraft.WorldVersion");
Method getWorldVersionMethod = null;
for (Method method : sharedConstantsClass.getDeclaredMethods()) {
if (method.getReturnType() == worldVersionClass && method.getParameterTypes().length == 0) {
getWorldVersionMethod = method;
break;
}
}
Preconditions.checkNotNull(getWorldVersionMethod, "Failed to get world version method");
Object worldVersion = getWorldVersionMethod.invoke(null);
for (Method method : worldVersionClass.getDeclaredMethods()) {
if (method.getReturnType() == int.class && method.getParameterTypes().length == 0) {
return (int) method.invoke(worldVersion);
}
}
throw new IllegalAccessException("Failed to find protocol version method in WorldVersion");
}
private int veryCursedProtocolDetection() throws ReflectiveOperationException {
// Time to go on a journey! The protocol version is hidden inside an int in ServerPing.ServerData, that is only set once the server has ticked once
// Grab a static instance of the server
Class<?> serverClazz = NMSUtil.nms("MinecraftServer", "net.minecraft.server.MinecraftServer");
Object server = ReflectionUtil.invokeStatic(serverClazz, "getServer");
Preconditions.checkNotNull(server, "Failed to get server instance");
// Grab the ping class and find the field to access it
Class<?> pingClazz = NMSUtil.nms(
@@ -80,6 +112,7 @@ public class BukkitViaInjector extends LegacyViaInjector {
break;
}
}
Preconditions.checkNotNull(ping, "Failed to get server ping");
// Now get the ServerData inside ServerPing
Class<?> serverDataClass = NMSUtil.nms(
@@ -94,6 +127,7 @@ public class BukkitViaInjector extends LegacyViaInjector {
break;
}
}
Preconditions.checkNotNull(serverData, "Failed to get server data");
// Get protocol version field
for (Field field : serverDataClass.getDeclaredFields()) {
@@ -155,7 +189,7 @@ public class BukkitViaInjector extends LegacyViaInjector {
@Override
public boolean lateProtocolVersionSetting() {
return !PaperViaInjector.PAPER_PROTOCOL_METHOD;
return !(PaperViaInjector.PAPER_PROTOCOL_METHOD || HAS_WORLD_VERSION_PROTOCOL_VERSION);
}
public boolean isBinded() {
@@ -50,17 +50,16 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.scheduler.BukkitTask;
public class BukkitViaLoader implements ViaPlatformLoader {
private final ViaVersionPlugin plugin;
private final Set<Listener> listeners = new HashSet<>();
private final Set<BukkitTask> tasks = new HashSet<>();
private final ViaVersionPlugin plugin;
private HandItemCache handItemCache;
public BukkitViaLoader(ViaVersionPlugin plugin) {
@@ -68,21 +67,21 @@ public class BukkitViaLoader implements ViaPlatformLoader {
}
public void registerListener(Listener listener) {
Bukkit.getPluginManager().registerEvents(storeListener(listener), plugin);
plugin.getServer().getPluginManager().registerEvents(listener, plugin);
}
@Deprecated/*(forRemoval = true)*/
public <T extends Listener> T storeListener(T listener) {
listeners.add(listener);
return listener;
}
@Override
public void load() {
// Update Listener
registerListener(new UpdateListener());
// Login listener
registerListener(new JoinListener());
if (Via.getConfig().shouldRegisterUserConnectionOnJoin()) {
registerListener(new JoinListener());
}
/* Base Protocol */
final ViaVersionPlugin plugin = (ViaVersionPlugin) Bukkit.getPluginManager().getPlugin("ViaVersion");
@@ -92,13 +91,18 @@ public class BukkitViaLoader implements ViaPlatformLoader {
ProtocolSupportCompat.registerPSConnectListener(plugin);
}
if (!Via.getAPI().getServerVersion().isKnown()) {
Via.getPlatform().getLogger().severe("Server version has not been loaded yet, cannot register additional listeners");
return;
}
int serverProtocolVersion = Via.getAPI().getServerVersion().lowestSupportedVersion();
/* 1.9 client to 1.8 server */
if (serverProtocolVersion < ProtocolVersion.v1_9.getVersion()) {
storeListener(new ArmorListener(plugin)).register();
storeListener(new DeathListener(plugin)).register();
storeListener(new BlockListener(plugin)).register();
new ArmorListener(plugin).register();
new DeathListener(plugin).register();
new BlockListener(plugin).register();
if (plugin.getConf().isItemCache()) {
handItemCache = new HandItemCache();
@@ -110,7 +114,7 @@ public class BukkitViaLoader implements ViaPlatformLoader {
boolean use1_9Fix = plugin.getConf().is1_9HitboxFix() && serverProtocolVersion < ProtocolVersion.v1_9.getVersion();
if (use1_9Fix || plugin.getConf().is1_14HitboxFix()) {
try {
storeListener(new PlayerSneakListener(plugin, use1_9Fix, plugin.getConf().is1_14HitboxFix())).register();
new PlayerSneakListener(plugin, use1_9Fix, plugin.getConf().is1_14HitboxFix()).register();
} catch (ReflectiveOperationException e) {
Via.getPlatform().getLogger().warning("Could not load hitbox fix - please report this on our GitHub");
e.printStackTrace();
@@ -121,7 +125,7 @@ public class BukkitViaLoader implements ViaPlatformLoader {
if (serverProtocolVersion < ProtocolVersion.v1_15.getVersion()) {
try {
Class.forName("org.bukkit.event.entity.EntityToggleGlideEvent");
storeListener(new EntityToggleGlideListener(plugin)).register();
new EntityToggleGlideListener(plugin).register();
} catch (ClassNotFoundException ignored) {
}
}
@@ -138,12 +142,12 @@ public class BukkitViaLoader implements ViaPlatformLoader {
}
}
if (paper) {
storeListener(new PaperPatch(plugin)).register();
new PaperPatch(plugin).register();
}
}
if (serverProtocolVersion < ProtocolVersion.v1_19_4.getVersion() && plugin.getConf().isArmorToggleFix()) {
storeListener(new ArmorToggleListener(plugin)).register();
if (serverProtocolVersion < ProtocolVersion.v1_19_4.getVersion() && plugin.getConf().isArmorToggleFix() && hasGetHandMethod()) {
new ArmorToggleListener(plugin).register();
}
/* Providers */
@@ -189,16 +193,22 @@ public class BukkitViaLoader implements ViaPlatformLoader {
}
if (serverProtocolVersion < ProtocolVersion.v1_19.getVersion()) {
Via.getManager().getProviders().use(AckSequenceProvider.class, new BukkitAckSequenceProvider(plugin));
storeListener(new BlockBreakListener(plugin)).register();
new BlockBreakListener(plugin).register();
}
}
private boolean hasGetHandMethod() {
try {
PlayerInteractEvent.class.getDeclaredMethod("getHand");
Material.class.getMethod("getEquipmentSlot");
return true;
} catch (NoSuchMethodException e) {
return false;
}
}
@Override
public void unload() {
for (Listener listener : listeners) {
HandlerList.unregisterAll(listener);
}
listeners.clear();
for (BukkitTask task : tasks) {
task.cancel();
}
@@ -126,13 +126,13 @@ public class BungeePlugin extends Plugin implements ViaServerProxyPlatform<Proxi
}
@Override
public PlatformTask runSync(Runnable runnable, long ticks) {
return new BungeeViaTask(getProxy().getScheduler().schedule(this, runnable, ticks * 50, TimeUnit.MILLISECONDS));
public PlatformTask runSync(Runnable runnable, long delay) {
return new BungeeViaTask(getProxy().getScheduler().schedule(this, runnable, delay * 50, TimeUnit.MILLISECONDS));
}
@Override
public PlatformTask runRepeatingSync(Runnable runnable, long ticks) {
return runRepeatingAsync(runnable, ticks);
public PlatformTask runRepeatingSync(Runnable runnable, long period) {
return runRepeatingAsync(runnable, period);
}
@Override
@@ -63,6 +63,7 @@ public class ViaManagerImpl implements ViaManager {
private final Set<String> subPlatforms = new HashSet<>();
private List<Runnable> enableListeners = new ArrayList<>();
private PlatformTask<?> mappingLoadingTask;
private boolean initialized;
public ViaManagerImpl(ViaPlatform<?> platform, ViaInjector injector, ViaCommandHandler commandHandler, ViaPlatformLoader loader) {
this.platform = platform;
@@ -105,6 +106,8 @@ public class ViaManagerImpl implements ViaManager {
listener.run();
}
enableListeners = null;
initialized = true;
}
public void onServerLoaded() {
@@ -149,9 +152,6 @@ public class ViaManagerImpl implements ViaManager {
// Check for unsupported plugins/software
unsupportedSoftwareWarning();
// Load Listeners / Tasks
protocolManager.onServerLoaded();
// Load Platform
loader.load();
// Common tasks
@@ -324,6 +324,11 @@ public class ViaManagerImpl implements ViaManager {
enableListeners.add(runnable);
}
@Override
public boolean isInitialized() {
return initialized;
}
public static final class ViaManagerBuilder {
private ViaPlatform<?> platform;
private ViaInjector injector;
@@ -383,6 +383,11 @@ public abstract class AbstractViaConfig extends Config implements ViaVersionConf
return nbtArrayFix;
}
@Override
public boolean shouldRegisterUserConnectionOnJoin() {
return false;
}
@Override
public boolean is1_12QuickMoveActionFix() {
return false;
@@ -109,11 +109,10 @@ public class ProtocolManagerImpl implements ProtocolManager {
// Input Version -> Output Version & Protocol (Allows fast lookup)
private final Int2ObjectMap<Int2ObjectMap<Protocol>> registryMap = new Int2ObjectOpenHashMap<>(32);
private final Map<Class<? extends Protocol>, Protocol<?, ?, ?, ?>> protocols = new HashMap<>();
private final Map<Class<? extends Protocol>, Protocol<?, ?, ?, ?>> protocols = new HashMap<>(64);
private final Map<ProtocolPathKey, List<ProtocolPathEntry>> pathCache = new ConcurrentHashMap<>();
private final Set<Integer> supportedVersions = new HashSet<>();
private final List<Pair<Range<Integer>, Protocol>> baseProtocols = Lists.newCopyOnWriteArrayList();
private final List<Protocol> registerList = new ArrayList<>();
private final ReadWriteLock mappingLoaderLock = new ReentrantReadWriteLock();
private Map<Class<? extends Protocol>, CompletableFuture<Void>> mappingLoaderFutures = new HashMap<>();
@@ -208,11 +207,9 @@ public class ProtocolManagerImpl implements ProtocolManager {
protocolMap.put(serverVersion, protocol);
}
if (Via.getPlatform().isPluginEnabled()) {
protocol.register(Via.getManager().getProviders());
protocol.register(Via.getManager().getProviders());
if (Via.getManager().isInitialized()) {
refreshVersions();
} else {
registerList.add(protocol);
}
if (protocol.hasMappingDataToLoad()) {
@@ -232,11 +229,9 @@ public class ProtocolManagerImpl implements ProtocolManager {
baseProtocol.initialize();
baseProtocols.add(new Pair<>(supportedProtocols, baseProtocol));
if (Via.getPlatform().isPluginEnabled()) {
baseProtocol.register(Via.getManager().getProviders());
baseProtocol.register(Via.getManager().getProviders());
if (Via.getManager().isInitialized()) {
refreshVersions();
} else {
registerList.add(baseProtocol);
}
}
@@ -498,16 +493,6 @@ public class ProtocolManagerImpl implements ProtocolManager {
return new PacketWrapperImpl(packetId, buf, connection);
}
/**
* Called when the server is enabled, to register any non-registered listeners.
*/
public void onServerLoaded() {
for (Protocol protocol : registerList) {
protocol.register(Via.getManager().getProviders());
}
registerList.clear();
}
public void shutdownLoaderExecutor() {
Preconditions.checkArgument(!mappingsLoaded);
@@ -39,6 +39,7 @@ import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import org.checkerframework.checker.nullness.qual.Nullable;
public class PacketWrapperImpl implements PacketWrapper {
@@ -508,10 +509,10 @@ public class PacketWrapperImpl implements PacketWrapper {
@Override
public String toString() {
return "PacketWrapper{" +
"packetType=" + packetType +
"type=" + packetType +
", id=" + id +
", packetValues=" + packetValues +
", readableObjects=" + readableObjects +
", values=" + packetValues +
", readable=" + readableObjects +
'}';
}
@@ -535,5 +536,26 @@ public class PacketWrapperImpl implements PacketWrapper {
public void setValue(@Nullable Object value) {
this.value = value;
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final PacketValue that = (PacketValue) o;
if (!type.equals(that.type)) return false;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "{" + type + ": " + value + "}";
}
}
}
@@ -18,6 +18,7 @@
package com.viaversion.viaversion.protocols.protocol1_13to1_12_2;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.viaversion.viaversion.api.Via;
import com.viaversion.viaversion.libs.kyori.adventure.text.Component;
@@ -29,6 +30,16 @@ import com.viaversion.viaversion.libs.kyori.adventure.text.serializer.legacy.Leg
public final class ChatRewriter {
public static final GsonComponentSerializer HOVER_GSON_SERIALIZER = GsonComponentSerializer.builder().emitLegacyHoverEvent().legacyHoverEventSerializer(NBTLegacyHoverEventSerializer.get()).build();
public static JsonObject emptyComponent() {
final JsonObject object = new JsonObject();
object.addProperty("text", "");
return object;
}
public static String emptyComponentString() {
return "{\"text\":\"\"}";
}
public static String legacyTextToJsonString(String message, boolean itemData) {
// Not used for chat messages, so no need for url extraction
Component component = LegacyComponentSerializer.legacySection().deserialize(message);
@@ -115,14 +115,12 @@ public class MappingData extends MappingDataBase {
}
String key = keyAndTranslation[0];
if (!translateData.containsKey(key)) {
String translation = keyAndTranslation[1].replaceAll("%(\\d\\$)?d", "%$1s");
mojangTranslation.put(key, translation);
} else {
String dataValue = translateData.get(key);
if (dataValue != null) {
translateMapping.put(key, dataValue);
}
String translation = keyAndTranslation[1].replaceAll("%(\\d\\$)?d", "%$1s").trim();
mojangTranslation.put(key, translation);
String dataValue = translateData.get(key);
if (dataValue != null) {
translateMapping.put(key, dataValue);
}
}
} catch (IOException e) {
@@ -106,7 +106,7 @@ public class InventoryPackets extends ItemRewriter<ClientboundPackets1_12_1, Ser
// Reset the packet
wrapper.clearPacket();
wrapper.setPacketType(ClientboundPackets1_13.SOUND);
wrapper.setPacketType(ClientboundPackets1_13.STOP_SOUND);
byte flags = 0;
wrapper.write(Type.BYTE, flags); // Placeholder
@@ -26,13 +26,13 @@ import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.api.type.types.minecraft.ParticleType;
import com.viaversion.viaversion.api.type.types.version.Types1_19_4;
import com.viaversion.viaversion.data.entity.EntityTrackerBase;
import com.viaversion.viaversion.libs.kyori.adventure.text.Component;
import com.viaversion.viaversion.libs.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ChatRewriter;
import com.viaversion.viaversion.protocols.protocol1_19_3to1_19_1.ClientboundPackets1_19_3;
import com.viaversion.viaversion.protocols.protocol1_19_3to1_19_1.ServerboundPackets1_19_3;
import com.viaversion.viaversion.protocols.protocol1_19_4to1_19_3.data.MappingData;
import com.viaversion.viaversion.protocols.protocol1_19_4to1_19_3.packets.EntityPackets;
import com.viaversion.viaversion.protocols.protocol1_19_4to1_19_3.packets.InventoryPackets;
import com.viaversion.viaversion.protocols.protocol1_19_4to1_19_3.storage.PlayerVehicleTracker;
import com.viaversion.viaversion.rewriter.CommandRewriter;
import com.viaversion.viaversion.rewriter.SoundRewriter;
import com.viaversion.viaversion.rewriter.TagRewriter;
@@ -42,7 +42,6 @@ import java.util.Base64;
public final class Protocol1_19_4To1_19_3 extends AbstractProtocol<ClientboundPackets1_19_3, ClientboundPackets1_19_4, ServerboundPackets1_19_3, ServerboundPackets1_19_4> {
public static final MappingData MAPPINGS = new MappingData();
private static final JsonElement EMPTY_COMPONENT = GsonComponentSerializer.gson().serializeToTree(Component.empty());
private final EntityPackets entityRewriter = new EntityPackets(this);
private final InventoryPackets itemRewriter = new InventoryPackets(this);
@@ -60,7 +59,6 @@ public final class Protocol1_19_4To1_19_3 extends AbstractProtocol<ClientboundPa
soundRewriter.registerSound(ClientboundPackets1_19_3.ENTITY_SOUND);
soundRewriter.register1_19_3Sound(ClientboundPackets1_19_3.SOUND);
new CommandRewriter<ClientboundPackets1_19_3>(this) {
@Override
public void handleArgument(final PacketWrapper wrapper, final String argumentType) throws Exception {
@@ -78,11 +76,14 @@ public final class Protocol1_19_4To1_19_3 extends AbstractProtocol<ClientboundPa
if (element != null) {
wrapper.write(Type.COMPONENT, element);
} else {
wrapper.write(Type.COMPONENT, EMPTY_COMPONENT);
wrapper.write(Type.COMPONENT, ChatRewriter.emptyComponent());
}
final String iconBase64 = wrapper.read(Type.OPTIONAL_STRING);
final byte[] iconBytes = iconBase64 != null ? Base64.getDecoder().decode(iconBase64.substring("data:image/png;base64,".length()).getBytes(StandardCharsets.UTF_8)) : null;
byte[] iconBytes = null;
if (iconBase64 != null && iconBase64.startsWith("data:image/png;base64,")) {
iconBytes = Base64.getDecoder().decode(iconBase64.substring("data:image/png;base64,".length()).getBytes(StandardCharsets.UTF_8));
}
wrapper.write(Type.OPTIONAL_BYTE_ARRAY_PRIMITIVE, iconBytes);
});
}
@@ -106,6 +107,8 @@ public final class Protocol1_19_4To1_19_3 extends AbstractProtocol<ClientboundPa
@Override
public void init(final UserConnection user) {
addEntityTracker(user, new EntityTrackerBase(user, Entity1_19_4Types.PLAYER));
user.put(new PlayerVehicleTracker(user));
}
@Override
@@ -122,4 +125,4 @@ public final class Protocol1_19_4To1_19_3 extends AbstractProtocol<ClientboundPa
public InventoryPackets getItemRewriter() {
return itemRewriter;
}
}
}
@@ -24,6 +24,7 @@ import com.github.steveice10.opennbt.tag.builtin.StringTag;
import com.github.steveice10.opennbt.tag.builtin.Tag;
import com.viaversion.viaversion.api.minecraft.entities.Entity1_19_4Types;
import com.viaversion.viaversion.api.minecraft.entities.EntityType;
import com.viaversion.viaversion.api.protocol.packet.PacketWrapper;
import com.viaversion.viaversion.api.protocol.remapper.PacketHandlers;
import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.api.type.types.version.Types1_19_3;
@@ -31,6 +32,7 @@ import com.viaversion.viaversion.api.type.types.version.Types1_19_4;
import com.viaversion.viaversion.protocols.protocol1_19_3to1_19_1.ClientboundPackets1_19_3;
import com.viaversion.viaversion.protocols.protocol1_19_4to1_19_3.ClientboundPackets1_19_4;
import com.viaversion.viaversion.protocols.protocol1_19_4to1_19_3.Protocol1_19_4To1_19_3;
import com.viaversion.viaversion.protocols.protocol1_19_4to1_19_3.storage.PlayerVehicleTracker;
import com.viaversion.viaversion.rewriter.EntityRewriter;
public final class EntityPackets extends EntityRewriter<ClientboundPackets1_19_3, Protocol1_19_4To1_19_3> {
@@ -55,6 +57,7 @@ public final class EntityPackets extends EntityRewriter<ClientboundPackets1_19_3
handler(dimensionDataHandler());
handler(biomeSizeTracker());
handler(worldDataTrackerHandlerByKey());
handler(playerTrackerHandler());
handler(wrapper -> {
final CompoundTag registry = wrapper.get(Type.NBT, 0);
final CompoundTag damageTypeRegistry = protocol.getMappingData().damageTypesRegistry();
@@ -82,7 +85,49 @@ public final class EntityPackets extends EntityRewriter<ClientboundPackets1_19_3
map(Type.FLOAT); // Pitch
map(Type.BYTE); // Relative arguments
map(Type.VAR_INT); // Id
read(Type.BOOLEAN); // Dismount vehicle
handler(wrapper -> {
if (wrapper.read(Type.BOOLEAN)) { // Dismount vehicle
final PlayerVehicleTracker playerVehicleTracker = wrapper.user().get(PlayerVehicleTracker.class);
if (playerVehicleTracker.getVehicleId() != -1) {
final PacketWrapper bundleStart = wrapper.create(ClientboundPackets1_19_4.BUNDLE);
bundleStart.send(Protocol1_19_4To1_19_3.class);
final PacketWrapper setPassengers = wrapper.create(ClientboundPackets1_19_4.SET_PASSENGERS);
setPassengers.write(Type.VAR_INT, playerVehicleTracker.getVehicleId()); // vehicle id
setPassengers.write(Type.VAR_INT_ARRAY_PRIMITIVE, new int[0]); // passenger ids
setPassengers.send(Protocol1_19_4To1_19_3.class);
wrapper.send(Protocol1_19_4To1_19_3.class);
wrapper.cancel();
final PacketWrapper bundleEnd = wrapper.create(ClientboundPackets1_19_4.BUNDLE);
bundleEnd.send(Protocol1_19_4To1_19_3.class);
playerVehicleTracker.setVehicleId(-1);
}
}
});
}
});
protocol.registerClientbound(ClientboundPackets1_19_3.SET_PASSENGERS, new PacketHandlers() {
@Override
protected void register() {
map(Type.VAR_INT); // vehicle id
map(Type.VAR_INT_ARRAY_PRIMITIVE); // passenger ids
handler(wrapper -> {
final PlayerVehicleTracker playerVehicleTracker = wrapper.user().get(PlayerVehicleTracker.class);
final int clientEntityId = wrapper.user().getEntityTracker(Protocol1_19_4To1_19_3.class).clientEntityId();
final int vehicleId = wrapper.get(Type.VAR_INT, 0);
if (playerVehicleTracker.getVehicleId() == vehicleId) {
playerVehicleTracker.setVehicleId(-1);
}
final int[] passengerIds = wrapper.get(Type.VAR_INT_ARRAY_PRIMITIVE, 0);
for (int passengerId : passengerIds) {
if (passengerId == clientEntityId) {
playerVehicleTracker.setVehicleId(vehicleId);
break;
}
}
});
}
});
@@ -109,6 +154,7 @@ public final class EntityPackets extends EntityRewriter<ClientboundPackets1_19_3
map(Type.STRING); // Dimension
map(Type.STRING); // World
handler(worldDataTrackerHandlerByKey());
handler(wrapper -> wrapper.user().put(new PlayerVehicleTracker(wrapper.user())));
}
});
@@ -131,7 +177,7 @@ public final class EntityPackets extends EntityRewriter<ClientboundPackets1_19_3
wrapper.write(Type.BYTE, event);
});
registerTrackerWithData1_19(ClientboundPackets1_19_3.SPAWN_ENTITY, null);
registerTrackerWithData1_19(ClientboundPackets1_19_3.SPAWN_ENTITY, Entity1_19_4Types.FALLING_BLOCK);
registerRemoveEntities(ClientboundPackets1_19_3.REMOVE_ENTITIES);
registerMetadataRewriter(ClientboundPackets1_19_3.ENTITY_METADATA, Types1_19_3.METADATA_LIST, Types1_19_4.METADATA_LIST);
}
@@ -169,6 +215,13 @@ public final class EntityPackets extends EntityRewriter<ClientboundPackets1_19_3
meta.setValue(protocol.getMappingData().getNewBlockStateId(blockState));
});
filter().filterFamily(Entity1_19_4Types.BOAT).index(11).handler((event, meta) -> {
final int boatType = meta.value();
if (boatType > 4) { // Cherry added
meta.setValue(boatType + 1);
}
});
filter().filterFamily(Entity1_19_4Types.ABSTRACT_HORSE).removeIndex(18); // Owner UUID
}
@@ -181,4 +234,4 @@ public final class EntityPackets extends EntityRewriter<ClientboundPackets1_19_3
public EntityType typeFromId(final int type) {
return Entity1_19_4Types.getTypeFromId(type);
}
}
}
@@ -30,11 +30,8 @@ public class RecipeRewriter1_19_4<C extends ClientboundPacketType> extends Recip
}
@Override
public void handleCraftingShapeless(final PacketWrapper wrapper) throws Exception {
wrapper.passthrough(Type.STRING); // Group
wrapper.passthrough(Type.VAR_INT); // Crafting book category
handleIngredients(wrapper);
rewrite(wrapper.passthrough(Type.FLAT_VAR_INT_ITEM)); // Result
public void handleCraftingShaped(final PacketWrapper wrapper) throws Exception {
super.handleCraftingShaped(wrapper);
wrapper.passthrough(Type.BOOLEAN); // Show notification
}
}
@@ -0,0 +1,39 @@
/*
* This file is part of ViaVersion - https://github.com/ViaVersion/ViaVersion
* Copyright (C) 2023 ViaVersion and contributors
*
* 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 com.viaversion.viaversion.protocols.protocol1_19_4to1_19_3.storage;
import com.viaversion.viaversion.api.connection.StoredObject;
import com.viaversion.viaversion.api.connection.UserConnection;
public class PlayerVehicleTracker extends StoredObject {
private int vehicleId = -1;
public PlayerVehicleTracker(final UserConnection user) {
super(user);
}
public int getVehicleId() {
return this.vehicleId;
}
public void setVehicleId(final int vehicleId) {
this.vehicleId = vehicleId;
}
}
@@ -30,10 +30,9 @@ import com.viaversion.viaversion.api.type.Type;
import com.viaversion.viaversion.api.type.types.minecraft.ParticleType;
import com.viaversion.viaversion.api.type.types.version.Types1_19;
import com.viaversion.viaversion.data.entity.EntityTrackerBase;
import com.viaversion.viaversion.libs.kyori.adventure.text.Component;
import com.viaversion.viaversion.libs.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import com.viaversion.viaversion.protocols.base.ClientboundLoginPackets;
import com.viaversion.viaversion.protocols.base.ServerboundLoginPackets;
import com.viaversion.viaversion.protocols.protocol1_13to1_12_2.ChatRewriter;
import com.viaversion.viaversion.protocols.protocol1_17to1_16_4.ServerboundPackets1_17;
import com.viaversion.viaversion.protocols.protocol1_18to1_17_1.ClientboundPackets1_18;
import com.viaversion.viaversion.protocols.protocol1_19to1_18_2.data.MappingData;
@@ -124,7 +123,7 @@ public final class Protocol1_19To1_18_2 extends AbstractProtocol<ClientboundPack
if (!isTextComponentNull(component)) {
wrapper.write(Type.COMPONENT, component);
} else {
wrapper.write(Type.COMPONENT, GsonComponentSerializer.gson().serializeToTree(Component.empty()));
wrapper.write(Type.COMPONENT, ChatRewriter.emptyComponent());
}
};
registerClientbound(ClientboundPackets1_18.TITLE_TEXT, titleHandler);
@@ -53,13 +53,10 @@ public class InventoryPackets {
// Send 2 properties, splitting it into enchantID & level
final short level = (short) (value >> 8);
final short enchantID = (short) (value & 0xFF);
wrapper.create(wrapper.getId(), new PacketHandler() {
@Override
public void handle(PacketWrapper wrapper) throws Exception {
wrapper.write(Type.UNSIGNED_BYTE, windowId);
wrapper.write(Type.SHORT, property);
wrapper.write(Type.SHORT, enchantID);
}
wrapper.create(wrapper.getId(), propertyPacket -> {
propertyPacket.write(Type.UNSIGNED_BYTE, windowId);
propertyPacket.write(Type.SHORT, property);
propertyPacket.write(Type.SHORT, enchantID);
}).scheduleSend(Protocol1_9To1_8.class);
wrapper.set(Type.SHORT, 0, (short) (property + 3));
@@ -39,8 +39,9 @@ import org.checkerframework.checker.nullness.qual.Nullable;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
@SuppressWarnings("VulnerableCodeUsages")
public abstract class Config implements ConfigurationProvider {
private static final YamlCompat YAMP_COMPAT = YamlCompat.isVersion2() ? new Yaml2Compat() : new Yaml1Compat();
private static final YamlCompat YAMP_COMPAT = YamlCompat.isVersion1() ? new Yaml1Compat() : new Yaml2Compat();
private static final ThreadLocal<Yaml> YAML = ThreadLocal.withInitial(() -> {
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
@@ -102,6 +102,9 @@ tracking-max-kick-msg: "You are sending too many packets, :("
# MULTIPLE VERSIONS OPTIONS #
#----------------------------------------------------------#
#
# Whether to make sure ViaVersion's UserConnection object is already available in the PlayerJoinEvent.
# You may disable this for faster startup/join time if you are 100% sure no plugin requires this.
register-userconnections-on-join: true
# Should we enable our hologram patch?
# If they're in the wrong place enable this
hologram-patch: false
@@ -71,12 +71,12 @@ public final class TestPlatform implements ViaPlatform {
}
@Override
public PlatformTask runSync(Runnable runnable, long ticks) {
public PlatformTask runSync(Runnable runnable, long delay) {
return null;
}
@Override
public PlatformTask runRepeatingSync(Runnable runnable, long ticks) {
public PlatformTask runRepeatingSync(Runnable runnable, long period) {
return null;
}
@@ -27,9 +27,9 @@ public interface YamlCompat {
SafeConstructor createSafeConstructor();
static boolean isVersion2() {
static boolean isVersion1() {
try {
Representer.class.getDeclaredConstructor(DumperOptions.class);
SafeConstructor.class.getDeclaredConstructor();
return true;
} catch (NoSuchMethodException e) {
return false;
+1 -1
View File
@@ -1,5 +1,5 @@
# Project properties - we put these here so they can be modified without causing a recompile of the build scripts
projectVersion=4.6.0
projectVersion=4.6.2
# Gradle properties
org.gradle.daemon=true
@@ -153,14 +153,14 @@ public class SpongePlugin implements ViaPlatform<Player> {
}
@Override
public PlatformTask runSync(Runnable runnable, long ticks) {
final Task task = Task.builder().plugin(container).execute(runnable).delay(Ticks.of(ticks)).build();
public PlatformTask runSync(Runnable runnable, long delay) {
final Task task = Task.builder().plugin(container).execute(runnable).delay(Ticks.of(delay)).build();
return new SpongeViaTask(game.server().scheduler().submit(task));
}
@Override
public PlatformTask runRepeatingSync(Runnable runnable, long ticks) {
final Task task = Task.builder().plugin(container).execute(runnable).interval(Ticks.of(ticks)).build();
public PlatformTask runRepeatingSync(Runnable runnable, long period) {
final Task task = Task.builder().plugin(container).execute(runnable).interval(Ticks.of(period)).build();
return new SpongeViaTask(game.server().scheduler().submit(task));
}
@@ -155,17 +155,17 @@ public class VelocityPlugin implements ViaServerProxyPlatform<Player> {
}
@Override
public PlatformTask runSync(Runnable runnable, long ticks) {
public PlatformTask runSync(Runnable runnable, long delay) {
return new VelocityViaTask(
PROXY.getScheduler()
.buildTask(this, runnable)
.delay(ticks * 50, TimeUnit.MILLISECONDS).schedule()
.delay(delay * 50, TimeUnit.MILLISECONDS).schedule()
);
}
@Override
public PlatformTask runRepeatingSync(Runnable runnable, long ticks) {
return runRepeatingAsync(runnable, ticks);
public PlatformTask runRepeatingSync(Runnable runnable, long period) {
return runRepeatingAsync(runnable, period);
}
@Override