From 1262847a0e43fabcad2979d776ce2616cf5f281a Mon Sep 17 00:00:00 2001 From: Phenomax Date: Mon, 7 Mar 2016 15:43:31 +0100 Subject: [PATCH] [+] added lombok in order to smaller code by removing unnecessary getter, setter and constructors [~] switched to bytecode version 1.8 (lambda expressions) [~] general code cleanup (lambda expressions, for each, collapsed catch blocks, diamond maps) --- pom.xml | 39 +- .../data/game/chunk/BlockStorage.java | 14 +- .../mc/protocol/data/game/chunk/Column.java | 6 +- .../us/myles/ViaVersion/ConnectionInfo.java | 31 +- .../us/myles/ViaVersion/ViaVersionPlugin.java | 54 ++- .../us/myles/ViaVersion/api/ViaVersion.java | 18 +- .../us/myles/ViaVersion/api/boss/BossBar.java | 35 +- .../myles/ViaVersion/api/boss/BossColor.java | 13 +- .../myles/ViaVersion/api/boss/BossFlag.java | 13 +- .../myles/ViaVersion/api/boss/BossStyle.java | 13 +- .../myles/ViaVersion/armor/ArmorListener.java | 54 ++- .../us/myles/ViaVersion/armor/ArmorType.java | 44 +-- .../us/myles/ViaVersion/boss/ViaBossBar.java | 32 +- .../myles/ViaVersion/chunks/ByteWriter.java | 23 +- .../myles/ViaVersion/chunks/MagicBitSet.java | 10 +- .../myles/ViaVersion/chunks/PacketChunk.java | 21 +- .../commands/ViaVersionCommand.java | 10 +- .../ViaVersion/handlers/ViaDecodeHandler.java | 1 + .../ViaVersion/handlers/ViaEncodeHandler.java | 36 +- .../handlers/ViaVersionInitializer.java | 1 + .../listeners/CommandBlockListener.java | 7 +- .../myles/ViaVersion/metadata/MetaIndex.java | 36 +- .../ViaVersion/metadata/MetadataRewriter.java | 25 +- .../us/myles/ViaVersion/metadata/NewType.java | 13 +- .../us/myles/ViaVersion/metadata/Type.java | 13 +- .../ViaVersion/slot/ItemSlotRewriter.java | 351 +++++++++--------- .../ViaVersion/sounds/SoundCategory.java | 22 +- .../myles/ViaVersion/sounds/SoundEffect.java | 35 +- .../transformers/IncomingTransformer.java | 68 ++-- .../transformers/OutgoingTransformer.java | 70 ++-- .../ViaVersion/update/UpdateListener.java | 10 +- .../us/myles/ViaVersion/update/Version.java | 33 +- .../us/myles/ViaVersion/util/EntityUtil.java | 1 + .../us/myles/ViaVersion/util/PacketUtil.java | 16 +- 34 files changed, 506 insertions(+), 662 deletions(-) diff --git a/pom.xml b/pom.xml index cf7925a8a..99d101a23 100644 --- a/pom.xml +++ b/pom.xml @@ -53,13 +53,13 @@ - + --> @@ -68,12 +68,12 @@ maven-compiler-plugin 3.5.1 - ${jdkVersion} - ${jdkVersion} - + --> + spacehq-repo https://repo.spacehq.org/content/repositories/releases/ @@ -153,16 +153,16 @@ - + org.spacehq opennbt 1.0 - compile + compile true - + io.netty netty-all @@ -170,5 +170,12 @@ provided true + + + org.projectlombok + lombok + 1.16.6 + provided + diff --git a/src/main/java/org/spacehq/mc/protocol/data/game/chunk/BlockStorage.java b/src/main/java/org/spacehq/mc/protocol/data/game/chunk/BlockStorage.java index 055991c5f..7ce493c28 100644 --- a/src/main/java/org/spacehq/mc/protocol/data/game/chunk/BlockStorage.java +++ b/src/main/java/org/spacehq/mc/protocol/data/game/chunk/BlockStorage.java @@ -17,7 +17,7 @@ public class BlockStorage { public BlockStorage() { this.bitsPerEntry = 4; - this.states = new ArrayList(); + this.states = new ArrayList<>(); this.states.add(0); this.storage = new FlexibleStorage(this.bitsPerEntry, 4096); @@ -26,7 +26,7 @@ public class BlockStorage { public BlockStorage(ByteBuf in) throws IOException { this.bitsPerEntry = in.readUnsignedByte(); - this.states = new ArrayList(); + this.states = new ArrayList<>(); int stateCount = PacketUtil.readVarInt(in); for (int i = 0; i < stateCount; i++) { this.states.add(PacketUtil.readVarInt(in)); @@ -35,6 +35,10 @@ public class BlockStorage { this.storage = new FlexibleStorage(this.bitsPerEntry, PacketUtil.readLongs(PacketUtil.readVarInt(in), in)); } + private static int index(int x, int y, int z) { + return y << 8 | z << 4 | x; + } + public void write(ByteBuf out) throws IOException { out.writeByte(this.bitsPerEntry); @@ -78,7 +82,7 @@ public class BlockStorage { List oldStates = this.states; if (this.bitsPerEntry > 8) { - oldStates = new ArrayList(this.states); + oldStates = new ArrayList<>(this.states); this.states.clear(); this.bitsPerEntry = 13; } @@ -107,10 +111,6 @@ public class BlockStorage { return true; } - private static int index(int x, int y, int z) { - return y << 8 | z << 4 | x; - } - @Override public boolean equals(Object o) { return this == o || (o instanceof BlockStorage && this.bitsPerEntry == ((BlockStorage) o).bitsPerEntry && this.states.equals(((BlockStorage) o).states) && this.storage.equals(((BlockStorage) o).storage)); diff --git a/src/main/java/org/spacehq/mc/protocol/data/game/chunk/Column.java b/src/main/java/org/spacehq/mc/protocol/data/game/chunk/Column.java index 1c7ff1464..cf90c45b5 100644 --- a/src/main/java/org/spacehq/mc/protocol/data/game/chunk/Column.java +++ b/src/main/java/org/spacehq/mc/protocol/data/game/chunk/Column.java @@ -23,9 +23,9 @@ public class Column { this.skylight = false; boolean noSkylight = false; - for(int index = 0; index < chunks.length; index++) { - if(chunks[index] != null) { - if(chunks[index].getSkyLight() == null) { + for (Chunk chunk : chunks) { + if (chunk != null) { + if (chunk.getSkyLight() == null) { noSkylight = true; } else { this.skylight = true; diff --git a/src/main/java/us/myles/ViaVersion/ConnectionInfo.java b/src/main/java/us/myles/ViaVersion/ConnectionInfo.java index e89d3460a..7db4361bd 100644 --- a/src/main/java/us/myles/ViaVersion/ConnectionInfo.java +++ b/src/main/java/us/myles/ViaVersion/ConnectionInfo.java @@ -40,30 +40,30 @@ public class ConnectionInfo { this.state = state; } - public void setCompression(int compression) { - this.compression = compression; - } - public int getCompression() { return compression; } - public void setLastPacket(Object lastPacket) { - this.lastPacket = lastPacket; + public void setCompression(int compression) { + this.compression = compression; } public Object getLastPacket() { return lastPacket; } - public void setUUID(UUID UUID) { - this.UUID = UUID; + public void setLastPacket(Object lastPacket) { + this.lastPacket = lastPacket; } public java.util.UUID getUUID() { return UUID; } + public void setUUID(UUID UUID) { + this.UUID = UUID; + } + public Player getPlayer() { return UUID == null ? null : Bukkit.getPlayer(UUID); } @@ -82,12 +82,7 @@ public class ConnectionInfo { public void sendRawPacket(final ByteBuf packet) { final ChannelHandler handler = channel.pipeline().get("encoder"); - channel.eventLoop().submit(new Runnable() { - @Override - public void run() { - channel.pipeline().context(handler).writeAndFlush(packet); - } - }); + channel.eventLoop().submit((Runnable) () -> channel.pipeline().context(handler).writeAndFlush(packet)); } public String getOpenWindow() { @@ -102,11 +97,11 @@ public class ConnectionInfo { this.openWindow = null; } - public void setUsername(String username) { - this.username = username; - } - public String getUsername() { return username; } + + public void setUsername(String username) { + this.username = username; + } } diff --git a/src/main/java/us/myles/ViaVersion/ViaVersionPlugin.java b/src/main/java/us/myles/ViaVersion/ViaVersionPlugin.java index 872e7f2a1..63389b9ed 100644 --- a/src/main/java/us/myles/ViaVersion/ViaVersionPlugin.java +++ b/src/main/java/us/myles/ViaVersion/ViaVersionPlugin.java @@ -28,20 +28,33 @@ import us.myles.ViaVersion.update.UpdateUtil; import us.myles.ViaVersion.util.ReflectionUtil; import java.lang.reflect.Field; -import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; -import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI { - private final Map portedPlayers = new ConcurrentHashMap(); + private final Map portedPlayers = new ConcurrentHashMap<>(); private boolean debug = false; + public static ItemStack getHandItem(final ConnectionInfo info) { + try { + return Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), () -> { + if (info.getPlayer() != null) { + return info.getPlayer().getItemInHand(); + } + return null; + }).get(10, TimeUnit.SECONDS); + } catch (Exception e) { + System.out.println("Error fetching hand item "); + e.printStackTrace(); + return null; + } + } + @Override public void onEnable() { ViaVersion.setInstance(this); @@ -154,6 +167,10 @@ public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI { return this.debug; } + public void setDebug(boolean value) { + this.debug = value; + } + @Override public boolean isSyncedChunks() { return getConfig().getBoolean("sync-chunks", true); @@ -169,10 +186,6 @@ public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI { return getConfig().getBoolean("auto-team", true); } - public void setDebug(boolean value) { - this.debug = value; - } - public void addPortedClient(ConnectionInfo info) { portedPlayers.put(info.getUUID(), info); } @@ -181,32 +194,11 @@ public class ViaVersionPlugin extends JavaPlugin implements ViaVersionAPI { portedPlayers.remove(clientID); } - public static ItemStack getHandItem(final ConnectionInfo info) { - try { - return Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), new Callable() { - @Override - public ItemStack call() throws Exception { - if (info.getPlayer() != null) { - return info.getPlayer().getItemInHand(); - } - return null; - } - }).get(10, TimeUnit.SECONDS); - } catch (Exception e) { - System.out.println("Error fetching hand item "); - e.printStackTrace(); - return null; - } - } - public void run(final Runnable runnable, boolean wait) { try { - Future f = Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), new Callable() { - @Override - public Boolean call() throws Exception { - runnable.run(); - return true; - } + Future f = Bukkit.getScheduler().callSyncMethod(Bukkit.getPluginManager().getPlugin("ViaVersion"), () -> { + runnable.run(); + return true; }); if (wait) { f.get(10, TimeUnit.SECONDS); diff --git a/src/main/java/us/myles/ViaVersion/api/ViaVersion.java b/src/main/java/us/myles/ViaVersion/api/ViaVersion.java index 857e2ab86..f5507d4d2 100644 --- a/src/main/java/us/myles/ViaVersion/api/ViaVersion.java +++ b/src/main/java/us/myles/ViaVersion/api/ViaVersion.java @@ -1,17 +1,11 @@ package us.myles.ViaVersion.api; +import lombok.Getter; +import lombok.Setter; + public class ViaVersion { - private static ViaVersionAPI INSTANCE; - - public static void setInstance(ViaVersionAPI api) { - if (INSTANCE != null) { - throw new IllegalStateException("Instance already set."); - } - INSTANCE = api; - } - - public static ViaVersionAPI getInstance() { - return INSTANCE; - } + @Getter + @Setter + private static ViaVersionAPI instance; } diff --git a/src/main/java/us/myles/ViaVersion/api/boss/BossBar.java b/src/main/java/us/myles/ViaVersion/api/boss/BossBar.java index da9010cd6..58ccf9020 100644 --- a/src/main/java/us/myles/ViaVersion/api/boss/BossBar.java +++ b/src/main/java/us/myles/ViaVersion/api/boss/BossBar.java @@ -13,13 +13,6 @@ public interface BossBar { */ void setTitle(String title); - /** - * Get the current title - * - * @return the title - */ - String getTitle(); - /** * Change the health * @@ -27,20 +20,6 @@ public interface BossBar { */ void setHealth(float health); - /** - * Get the health - * - * @return float between 0F - 1F - */ - float getHealth(); - - /** - * Yay colors! - * - * @param color Whatever color you want! - */ - void setColor(BossColor color); - /** * Get the bossbar color * @@ -48,6 +27,13 @@ public interface BossBar { */ BossColor getColor(); + /** + * Yay colors! + * + * @param color Whatever color you want! + */ + void setColor(BossColor color); + /** * Change the bosbar style * @@ -55,13 +41,6 @@ public interface BossBar { */ void setStyle(BossStyle style); - /** - * Get the bosbar style - * - * @return BossStyle - */ - BossStyle getStyle(); - /** * Show the bossbar to a player. * diff --git a/src/main/java/us/myles/ViaVersion/api/boss/BossColor.java b/src/main/java/us/myles/ViaVersion/api/boss/BossColor.java index 802f93b3a..fef66641a 100644 --- a/src/main/java/us/myles/ViaVersion/api/boss/BossColor.java +++ b/src/main/java/us/myles/ViaVersion/api/boss/BossColor.java @@ -1,5 +1,10 @@ package us.myles.ViaVersion.api.boss; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@Getter public enum BossColor { PINK(0), BLUE(1), @@ -10,12 +15,4 @@ public enum BossColor { WHITE(6); private final int id; - - BossColor(int id) { - this.id = id; - } - - public int getId() { - return id; - } } diff --git a/src/main/java/us/myles/ViaVersion/api/boss/BossFlag.java b/src/main/java/us/myles/ViaVersion/api/boss/BossFlag.java index 5b72fd69a..3c3afd0ef 100644 --- a/src/main/java/us/myles/ViaVersion/api/boss/BossFlag.java +++ b/src/main/java/us/myles/ViaVersion/api/boss/BossFlag.java @@ -1,16 +1,13 @@ package us.myles.ViaVersion.api.boss; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@Getter public enum BossFlag { DARKEN_SKY(1), PLAY_BOSS_MUSIC(2); private final int id; - - BossFlag(int id) { - this.id = id; - } - - public int getId() { - return id; - } } diff --git a/src/main/java/us/myles/ViaVersion/api/boss/BossStyle.java b/src/main/java/us/myles/ViaVersion/api/boss/BossStyle.java index 60dd209ea..712e25e7a 100644 --- a/src/main/java/us/myles/ViaVersion/api/boss/BossStyle.java +++ b/src/main/java/us/myles/ViaVersion/api/boss/BossStyle.java @@ -1,5 +1,10 @@ package us.myles.ViaVersion.api.boss; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@Getter public enum BossStyle { SOLID(0), SEGMENTED_6(1), @@ -8,12 +13,4 @@ public enum BossStyle { SEGMENTED_20(4); private final int id; - - BossStyle(int id) { - this.id = id; - } - - public int getId() { - return id; - } } diff --git a/src/main/java/us/myles/ViaVersion/armor/ArmorListener.java b/src/main/java/us/myles/ViaVersion/armor/ArmorListener.java index a86542f5d..2614591b3 100644 --- a/src/main/java/us/myles/ViaVersion/armor/ArmorListener.java +++ b/src/main/java/us/myles/ViaVersion/armor/ArmorListener.java @@ -2,6 +2,7 @@ package us.myles.ViaVersion.armor; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; @@ -21,14 +22,27 @@ import java.util.UUID; import static us.myles.ViaVersion.util.PacketUtil.*; +@RequiredArgsConstructor public class ArmorListener implements Listener { + private static final UUID ARMOR_ATTRIBUTE = UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150"); private final ViaVersionPlugin plugin; - private static UUID armorAttribute = UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150"); + public static void sendArmorUpdate(Player player) { + int armor = ArmorType.calculateArmorPoints(player.getInventory().getArmorContents()); - public ArmorListener(ViaVersionPlugin plugin) { - this.plugin = plugin; + ByteBuf buf = Unpooled.buffer(); + writeVarInt(PacketType.PLAY_ENTITY_PROPERTIES.getNewPacketID(), buf); + writeVarInt(player.getEntityId(), buf); + buf.writeInt(1); // only 1 property + writeString("generic.armor", buf); + buf.writeDouble(0); //default 0 armor + writeVarInt(1, buf); // 1 modifier + writeUUID(ARMOR_ATTRIBUTE, buf); // armor modifier uuid + buf.writeDouble((double) armor); // the modifier value + buf.writeByte(0); // the modifier operation, 0 is add number + + ViaVersion.getInstance().sendRawPacket(player, buf); } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) @@ -45,7 +59,6 @@ public class ArmorListener implements Listener { } if (e.getRawSlot() >= 5 && e.getRawSlot() <= 8) { sendDelayedArmorUpdate(player); - return; } } } @@ -58,12 +71,9 @@ public class ArmorListener implements Listener { if (ArmorType.isArmor(e.getMaterial())) { final Player player = e.getPlayer(); // Due to odd bugs it's 3 ticks later - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - public void run() { - if (ViaVersion.getInstance().isPorted(player)) { - sendArmorUpdate(player); - } + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { + if (ViaVersion.getInstance().isPorted(player)) { + sendArmorUpdate(player); } }, 3L); } @@ -77,30 +87,12 @@ public class ArmorListener implements Listener { } public void sendDelayedArmorUpdate(final Player player) { - Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { - @Override - public void run() { + Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> { + if (ViaVersion.getInstance().isPorted(player)) { sendArmorUpdate(player); } - } + }); } - - public static void sendArmorUpdate(Player player) { - int armor = ArmorType.calculateArmorPoints(player.getInventory().getArmorContents()); - - ByteBuf buf = Unpooled.buffer(); - writeVarInt(PacketType.PLAY_ENTITY_PROPERTIES.getNewPacketID(), buf); - writeVarInt(player.getEntityId(), buf); - buf.writeInt(1); // only 1 property - writeString("generic.armor", buf); - buf.writeDouble(0); //default 0 armor - writeVarInt(1, buf); // 1 modifier - writeUUID(armorAttribute, buf); // armor modifier uuid - buf.writeDouble((double) armor); // the modifier value - buf.writeByte(0); // the modifier operation, 0 is add number - - ViaVersion.getInstance().sendRawPacket(player, buf); - } } \ No newline at end of file diff --git a/src/main/java/us/myles/ViaVersion/armor/ArmorType.java b/src/main/java/us/myles/ViaVersion/armor/ArmorType.java index 23f0bda44..3069d3784 100644 --- a/src/main/java/us/myles/ViaVersion/armor/ArmorType.java +++ b/src/main/java/us/myles/ViaVersion/armor/ArmorType.java @@ -1,8 +1,12 @@ package us.myles.ViaVersion.armor; +import lombok.Getter; +import lombok.RequiredArgsConstructor; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; +@RequiredArgsConstructor +@Getter public enum ArmorType { LEATHER_HELMET(1, 298, Material.LEATHER_HELMET), @@ -27,27 +31,9 @@ public enum ArmorType { GOLD_BOOTS(1, 317, Material.GOLD_BOOTS), NONE(0, 0, Material.AIR); - private int armorpoints; - private int id; - private Material type; - - ArmorType(int armor, int id, Material type) { - this.armorpoints = armor; - this.id = id; - this.type = type; - } - - public int getArmorPoints() { - return this.armorpoints; - } - - public int getId() { - return this.id; - } - - public Material getType() { - return this.type; - } + private final int armorPoints; + private final int id; + private final Material type; public static ArmorType findByType(Material type) { for(ArmorType a : ArmorType.values()) @@ -58,9 +44,9 @@ public enum ArmorType { public static int calculateArmorPoints(ItemStack[] armor) { int total = 0; - for(int i = 0; i < armor.length; i++) { - if(armor[i] != null) - total += findByType(armor[i].getType()).getArmorPoints(); + for (ItemStack anArmor : armor) { + if (anArmor != null) + total += findByType(anArmor.getType()).getArmorPoints(); } return total; } @@ -81,11 +67,15 @@ public enum ArmorType { public static int calculateArmorPoints(int[] armor) { int total = 0; - for(int i = 0; i < armor.length; i++) { - if(armor[i] != -1) - total += findById(armor[i]).getArmorPoints(); + for (int anArmor : armor) { + if (anArmor != -1) + total += findById(anArmor).getArmorPoints(); } return total; } + public Material getType() { + return this.type; + } + } \ No newline at end of file diff --git a/src/main/java/us/myles/ViaVersion/boss/ViaBossBar.java b/src/main/java/us/myles/ViaVersion/boss/ViaBossBar.java index 94cd6fb56..e398cdee9 100644 --- a/src/main/java/us/myles/ViaVersion/boss/ViaBossBar.java +++ b/src/main/java/us/myles/ViaVersion/boss/ViaBossBar.java @@ -2,6 +2,8 @@ package us.myles.ViaVersion.boss; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import lombok.Getter; +import lombok.RequiredArgsConstructor; import org.apache.commons.lang.Validate; import org.bukkit.entity.Player; import us.myles.ViaVersion.api.ViaVersion; @@ -18,6 +20,7 @@ import java.util.HashSet; import java.util.Set; import java.util.UUID; +@Getter public class ViaBossBar implements BossBar { private UUID uuid; private String title; @@ -48,11 +51,6 @@ public class ViaBossBar implements BossBar { sendPacket(UpdateAction.UPDATE_TITLE); } - @Override - public String getTitle() { - return title; - } - @Override public void setHealth(float health) { Validate.isTrue((health >= 0 && health <= 1), "Health must be between 0 and 1"); @@ -61,8 +59,8 @@ public class ViaBossBar implements BossBar { } @Override - public float getHealth() { - return health; + public BossColor getColor() { + return color; } @Override @@ -72,11 +70,6 @@ public class ViaBossBar implements BossBar { sendPacket(UpdateAction.UPDATE_STYLE); } - @Override - public BossColor getColor() { - return color; - } - @Override public void setStyle(BossStyle style) { Validate.notNull(style, "Style cannot be null"); @@ -84,11 +77,6 @@ public class ViaBossBar implements BossBar { sendPacket(UpdateAction.UPDATE_STYLE); } - @Override - public BossStyle getStyle() { - return style; - } - @Override public void addPlayer(Player player) { if (player != null && !players.contains(player.getUniqueId())) { @@ -210,6 +198,8 @@ public class ViaBossBar implements BossBar { return OutgoingTransformer.fixJson(text); } + @RequiredArgsConstructor + @Getter private enum UpdateAction { ADD(0), REMOVE(1), @@ -219,13 +209,5 @@ public class ViaBossBar implements BossBar { UPDATE_FLAGS(5); private final int id; - - UpdateAction(int id) { - this.id = id; - } - - public int getId() { - return id; - } } } diff --git a/src/main/java/us/myles/ViaVersion/chunks/ByteWriter.java b/src/main/java/us/myles/ViaVersion/chunks/ByteWriter.java index d3939c2ec..eca189d66 100644 --- a/src/main/java/us/myles/ViaVersion/chunks/ByteWriter.java +++ b/src/main/java/us/myles/ViaVersion/chunks/ByteWriter.java @@ -1,20 +1,19 @@ package us.myles.ViaVersion.chunks; +import lombok.Getter; + +@Getter public class ByteWriter { - private final byte[] bytes; + + private final byte[] output; private int byteIndex; private int bitIndex; public ByteWriter(int size) { - this.bytes = new byte[size]; + this.output = new byte[size]; this.byteIndex = 0; this.bitIndex = 0; } - - public byte[] getOutput() { - return this.bytes; - } - public void writeFullByte(int b){ writeByte(b, 8); } @@ -28,8 +27,8 @@ public class ByteWriter { int space = (8 - bitIndex); int written = space > length ? length : space; System.out.println("Written is " + written); - bytes[byteIndex] = (byte) (current | (extractRange(byteB, 0, written) >> (bitIndex - 1))); - System.out.println("output value: " + bytes[byteIndex]); + output[byteIndex] = (byte) (current | (extractRange(byteB, 0, written) >> (bitIndex - 1))); + System.out.println("output value: " + output[byteIndex]); this.bitIndex += length; if(this.bitIndex >= 8) { this.byteIndex += 1; @@ -37,7 +36,7 @@ public class ByteWriter { // write remaining into this System.out.println("Writing from " + written + " to " + (written + bitIndex)); System.out.println("Value: " + extractRange(byteB, written, written + bitIndex)); - bytes[byteIndex] = (byte) (extractRange(byteB, written, written + bitIndex) << written); + output[byteIndex] = (byte) (extractRange(byteB, written, written + bitIndex) << written); } } @@ -45,8 +44,8 @@ public class ByteWriter { return (byte) ((in >> begin) & ((1 << (end - begin)) - 1)); } public byte getCurrentByte() { - if(byteIndex == bytes.length) throw new RuntimeException("ByteWriter overflow!"); + if (byteIndex == output.length) throw new RuntimeException("ByteWriter overflow!"); - return bytes[byteIndex]; + return output[byteIndex]; } } diff --git a/src/main/java/us/myles/ViaVersion/chunks/MagicBitSet.java b/src/main/java/us/myles/ViaVersion/chunks/MagicBitSet.java index 9b61c611d..64b454086 100644 --- a/src/main/java/us/myles/ViaVersion/chunks/MagicBitSet.java +++ b/src/main/java/us/myles/ViaVersion/chunks/MagicBitSet.java @@ -1,15 +1,13 @@ package us.myles.ViaVersion.chunks; +import lombok.RequiredArgsConstructor; + import java.util.BitSet; -public class MagicBitSet extends BitSet{ +@RequiredArgsConstructor +public class MagicBitSet extends BitSet { private final int initLength; - public MagicBitSet(int nbits) { - super(nbits); - this.initLength = nbits; - } - public int getTrueLength() { return length() == 0 ? initLength : length(); } diff --git a/src/main/java/us/myles/ViaVersion/chunks/PacketChunk.java b/src/main/java/us/myles/ViaVersion/chunks/PacketChunk.java index 549ef6d59..f0c235615 100644 --- a/src/main/java/us/myles/ViaVersion/chunks/PacketChunk.java +++ b/src/main/java/us/myles/ViaVersion/chunks/PacketChunk.java @@ -1,19 +1,14 @@ package us.myles.ViaVersion.chunks; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@AllArgsConstructor public class PacketChunk { + private PacketChunkData[] chunkData; private byte[] biomeData; - - public PacketChunk(PacketChunkData[] chunkData, byte[] biomeData) { - this.chunkData = chunkData; - this.biomeData = biomeData; - } - - public PacketChunkData[] getChunkData() { - return chunkData; - } - - public byte[] getBiomeData() { - return biomeData; - } } diff --git a/src/main/java/us/myles/ViaVersion/commands/ViaVersionCommand.java b/src/main/java/us/myles/ViaVersion/commands/ViaVersionCommand.java index 1e53ce862..e8e8f8e4e 100644 --- a/src/main/java/us/myles/ViaVersion/commands/ViaVersionCommand.java +++ b/src/main/java/us/myles/ViaVersion/commands/ViaVersionCommand.java @@ -1,5 +1,6 @@ package us.myles.ViaVersion.commands; +import lombok.RequiredArgsConstructor; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; @@ -14,12 +15,11 @@ import java.util.List; /** * Created by fillefilip8 on 2016-03-03. */ +@RequiredArgsConstructor public class ViaVersionCommand implements CommandExecutor { + private final ViaVersionPlugin plugin; - public ViaVersionCommand(ViaVersionPlugin plugin) { - this.plugin = plugin; - } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { @@ -32,8 +32,8 @@ public class ViaVersionCommand implements CommandExecutor { sender.sendMessage(color("&2/viaversion dontbugme &7- &6Toggle checking for updates.")); } else if (args.length == 1) { if (args[0].equalsIgnoreCase("list")) { - List portedPlayers = new ArrayList(); - List normalPlayers = new ArrayList(); + List portedPlayers = new ArrayList<>(); + List normalPlayers = new ArrayList<>(); for (Player p : Bukkit.getOnlinePlayers()) { if (ViaVersion.getInstance().isPorted(p)) { portedPlayers.add(p.getName()); diff --git a/src/main/java/us/myles/ViaVersion/handlers/ViaDecodeHandler.java b/src/main/java/us/myles/ViaVersion/handlers/ViaDecodeHandler.java index 590a9539a..a599f1883 100644 --- a/src/main/java/us/myles/ViaVersion/handlers/ViaDecodeHandler.java +++ b/src/main/java/us/myles/ViaVersion/handlers/ViaDecodeHandler.java @@ -11,6 +11,7 @@ import us.myles.ViaVersion.util.PacketUtil; import java.util.List; public class ViaDecodeHandler extends ByteToMessageDecoder { + private final IncomingTransformer incomingTransformer; private final ByteToMessageDecoder minecraftDecoder; private final ConnectionInfo info; diff --git a/src/main/java/us/myles/ViaVersion/handlers/ViaEncodeHandler.java b/src/main/java/us/myles/ViaVersion/handlers/ViaEncodeHandler.java index 872d6ad7e..e13a3e154 100644 --- a/src/main/java/us/myles/ViaVersion/handlers/ViaEncodeHandler.java +++ b/src/main/java/us/myles/ViaVersion/handlers/ViaEncodeHandler.java @@ -5,8 +5,6 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import us.myles.ViaVersion.CancelException; import us.myles.ViaVersion.ConnectionInfo; -import us.myles.ViaVersion.ViaVersionPlugin; -import us.myles.ViaVersion.api.ViaVersion; import us.myles.ViaVersion.transformers.OutgoingTransformer; import us.myles.ViaVersion.util.PacketUtil; import us.myles.ViaVersion.util.ReflectionUtil; @@ -39,30 +37,18 @@ public class ViaEncodeHandler extends MessageToByteEncoder { final Object world = ReflectionUtil.get(o, "world", ReflectionUtil.nms("World")); Class mapChunk = ReflectionUtil.nms("PacketPlayOutMapChunk"); final Constructor constructor = mapChunk.getDeclaredConstructor(ReflectionUtil.nms("Chunk"), boolean.class, int.class); - Runnable chunks = new Runnable() { + Runnable chunks = () -> { - @Override - public void run() { - - for (int i = 0; i < locX.length; i++) { - int x = locX[i]; - int z = locZ[i]; - // world invoke function - try { - Object chunk = ReflectionUtil.nms("World").getDeclaredMethod("getChunkAt", int.class, int.class).invoke(world, x, z); - Object packet = constructor.newInstance(chunk, true, 65535); - ctx.pipeline().writeAndFlush(packet); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { - e.printStackTrace(); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } + for (int i = 0; i < locX.length; i++) { + int x = locX[i]; + int z = locZ[i]; + // world invoke function + try { + Object chunk = ReflectionUtil.nms("World").getDeclaredMethod("getChunkAt", int.class, int.class).invoke(world, x, z); + Object packet = constructor.newInstance(chunk, true, 65535); + ctx.pipeline().writeAndFlush(packet); + } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException e) { + e.printStackTrace(); } } }; diff --git a/src/main/java/us/myles/ViaVersion/handlers/ViaVersionInitializer.java b/src/main/java/us/myles/ViaVersion/handlers/ViaVersionInitializer.java index 585ce7c48..a2b077a86 100644 --- a/src/main/java/us/myles/ViaVersion/handlers/ViaVersionInitializer.java +++ b/src/main/java/us/myles/ViaVersion/handlers/ViaVersionInitializer.java @@ -10,6 +10,7 @@ import us.myles.ViaVersion.ConnectionInfo; import java.lang.reflect.Method; public class ViaVersionInitializer extends ChannelInitializer { + private final ChannelInitializer oldInit; private Method method; diff --git a/src/main/java/us/myles/ViaVersion/listeners/CommandBlockListener.java b/src/main/java/us/myles/ViaVersion/listeners/CommandBlockListener.java index 870d6d4f6..afb6878a7 100644 --- a/src/main/java/us/myles/ViaVersion/listeners/CommandBlockListener.java +++ b/src/main/java/us/myles/ViaVersion/listeners/CommandBlockListener.java @@ -2,6 +2,7 @@ package us.myles.ViaVersion.listeners; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import lombok.RequiredArgsConstructor; import org.bukkit.block.Block; import org.bukkit.block.CommandBlock; import org.bukkit.entity.Player; @@ -19,12 +20,10 @@ import us.myles.ViaVersion.util.ReflectionUtil; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +@RequiredArgsConstructor public class CommandBlockListener implements Listener { - private final ViaVersionPlugin plugin; - public CommandBlockListener(ViaVersionPlugin plugin) { - this.plugin = plugin; - } + private final ViaVersionPlugin plugin; @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) public void onJoin(final PlayerJoinEvent e) { diff --git a/src/main/java/us/myles/ViaVersion/metadata/MetaIndex.java b/src/main/java/us/myles/ViaVersion/metadata/MetaIndex.java index 462c4f7fa..38f75d6a1 100644 --- a/src/main/java/us/myles/ViaVersion/metadata/MetaIndex.java +++ b/src/main/java/us/myles/ViaVersion/metadata/MetaIndex.java @@ -1,7 +1,11 @@ package us.myles.ViaVersion.metadata; +import lombok.AllArgsConstructor; +import lombok.Getter; import org.bukkit.entity.*; +@AllArgsConstructor +@Getter public enum MetaIndex { // entity @@ -136,34 +140,6 @@ public enum MetaIndex { this.newType = newType; } - MetaIndex(Class type, int index, Type oldType, int newIndex, NewType newType) { - this.clazz = type; - this.index = index; - this.oldType = oldType; - this.newIndex = newIndex; - this.newType = newType; - } - - public int getNewIndex() { - return newIndex; - } - - public NewType getNewType() { - return newType; - } - - public Type getOldType() { - return oldType; - } - - public int getIndex() { - return index; - } - - public Class getApplicableClass() { - return this.clazz; - } - public static MetaIndex getIndex(EntityType type, int index) { Class entityClass = type.getEntityClass(); if (entityClass == null) { @@ -192,5 +168,9 @@ public enum MetaIndex { } return null; } + + public Class getApplicableClass() { + return this.clazz; + } } diff --git a/src/main/java/us/myles/ViaVersion/metadata/MetadataRewriter.java b/src/main/java/us/myles/ViaVersion/metadata/MetadataRewriter.java index 3b3090cae..15483099f 100644 --- a/src/main/java/us/myles/ViaVersion/metadata/MetadataRewriter.java +++ b/src/main/java/us/myles/ViaVersion/metadata/MetadataRewriter.java @@ -1,6 +1,8 @@ package us.myles.ViaVersion.metadata; import io.netty.buffer.ByteBuf; +import lombok.Getter; +import lombok.Setter; import org.bukkit.entity.EntityType; import org.bukkit.util.EulerAngle; import org.bukkit.util.Vector; @@ -10,7 +12,6 @@ import us.myles.ViaVersion.transformers.OutgoingTransformer; import us.myles.ViaVersion.util.PacketUtil; import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.UUID; @@ -19,9 +20,7 @@ public class MetadataRewriter { public static void writeMetadata1_9(EntityType type, List list, ByteBuf output) { short id = -1; int data = -1; - Iterator iterator = list.iterator(); - while (iterator.hasNext()) { - Entry entry = iterator.next(); // + for (Entry entry : list) { MetaIndex metaIndex = entry.index; try { if (metaIndex.getNewType() != NewType.Discontinued) { @@ -34,7 +33,7 @@ public class MetadataRewriter { case Byte: // convert from int, byte if (metaIndex.getOldType() == Type.Byte) { - output.writeByte(((Byte) value).byteValue()); + output.writeByte((Byte) value); } if (metaIndex.getOldType() == Type.Int) { output.writeByte(((Integer) value).byteValue()); @@ -56,10 +55,10 @@ public class MetadataRewriter { case BlockID: // if we have both sources :)) if (metaIndex.getOldType() == Type.Byte) { - data = ((Byte) value).byteValue(); + data = (Byte) value; } if (metaIndex.getOldType() == Type.Short) { - id = ((Short) value).shortValue(); + id = (Short) value; } if (id != -1 && data != -1) { int combined = id << 4 | data; @@ -77,20 +76,20 @@ public class MetadataRewriter { PacketUtil.writeVarInt(((Short) value).intValue(), output); } if (metaIndex.getOldType() == Type.Int) { - PacketUtil.writeVarInt(((Integer) value).intValue(), output); + PacketUtil.writeVarInt((Integer) value, output); } break; case Float: - output.writeFloat(((Float) value).floatValue()); + output.writeFloat((Float) value); break; case String: PacketUtil.writeString((String) value, output); break; case Boolean: if (metaIndex == MetaIndex.AGEABLE_AGE) - output.writeBoolean(((Byte) value).byteValue() < 0); + output.writeBoolean((Byte) value < 0); else - output.writeBoolean(((Byte) value).byteValue() != 0); + output.writeBoolean((Byte) value != 0); break; case Slot: ItemStack item = (ItemStack) value; @@ -186,7 +185,9 @@ public class MetadataRewriter { return entries; } - public static class Entry { + @Getter + @Setter + public static final class Entry { private final int oldID; private MetaIndex index; diff --git a/src/main/java/us/myles/ViaVersion/metadata/NewType.java b/src/main/java/us/myles/ViaVersion/metadata/NewType.java index 375e8c61a..3fbb1aa70 100644 --- a/src/main/java/us/myles/ViaVersion/metadata/NewType.java +++ b/src/main/java/us/myles/ViaVersion/metadata/NewType.java @@ -1,5 +1,10 @@ package us.myles.ViaVersion.metadata; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@Getter public enum NewType { Byte(0), VarInt(1), @@ -15,13 +20,7 @@ public enum NewType { OptUUID(11), BlockID(12), Discontinued(99); + private final int typeID; - NewType(int typeID){ - this.typeID = typeID; - } - - public int getTypeID() { - return typeID; - } } diff --git a/src/main/java/us/myles/ViaVersion/metadata/Type.java b/src/main/java/us/myles/ViaVersion/metadata/Type.java index 94c2300a0..b5cb8a967 100644 --- a/src/main/java/us/myles/ViaVersion/metadata/Type.java +++ b/src/main/java/us/myles/ViaVersion/metadata/Type.java @@ -1,5 +1,10 @@ package us.myles.ViaVersion.metadata; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@Getter public enum Type { Byte(0), Short(1), @@ -11,14 +16,6 @@ public enum Type { Rotation(7); private final int typeID; - Type(int typeID){ - this.typeID = typeID; - } - - public int getTypeID() { - return typeID; - } - public static Type byId(int id) { return values()[id]; } diff --git a/src/main/java/us/myles/ViaVersion/slot/ItemSlotRewriter.java b/src/main/java/us/myles/ViaVersion/slot/ItemSlotRewriter.java index 00b225b1d..ef04eb164 100644 --- a/src/main/java/us/myles/ViaVersion/slot/ItemSlotRewriter.java +++ b/src/main/java/us/myles/ViaVersion/slot/ItemSlotRewriter.java @@ -17,182 +17,10 @@ import java.util.Map; public class ItemSlotRewriter { - public static void rewrite1_9To1_8(ByteBuf input, ByteBuf output) throws CancelException { - try { - ItemStack item = readItemStack(input); - fixIdsFrom1_9To1_8(item); - writeItemStack(item, output); - } catch (Exception e) { - System.out.println("Error while rewriting an item slot."); - e.printStackTrace(); - throw new CancelException(); - } - } - - public static void rewrite1_8To1_9(ByteBuf input, ByteBuf output) throws CancelException { - try { - ItemStack item = readItemStack(input); - fixIdsFrom1_8To1_9(item); - writeItemStack(item, output); - } catch (Exception e) { - System.out.println("Error while rewriting an item slot."); - e.printStackTrace(); - throw new CancelException(); - } - } - - public static void fixIdsFrom1_9To1_8(ItemStack item) { - if (item != null) { - if (item.id == Material.MONSTER_EGG.getId() && item.data == 0) { - CompoundTag tag = item.tag; - int data = 0; - if (tag != null && tag.get("EntityTag") instanceof CompoundTag) { - CompoundTag entityTag = tag.get("EntityTag"); - if (entityTag.get("id") instanceof StringTag) { - StringTag id = entityTag.get("id"); - if (ENTTIY_NAME_TO_ID.containsKey(id.getValue())) - data = ENTTIY_NAME_TO_ID.get(id.getValue()); - } - } - item.tag = null; - item.data = (short) data; - } - if (item.id == Material.POTION.getId()) { - CompoundTag tag = item.tag; - int data = 0; - if (tag != null && tag.get("Potion") instanceof StringTag) { - StringTag potion = tag.get("Potion"); - String potionName = potion.getValue().replace("minecraft:", ""); - if (POTION_NAME_TO_ID.containsKey(potionName)) { - data = POTION_NAME_TO_ID.get(potionName); - } - } - item.tag = null; - item.data = (short) data; - } - if (item.id == 438) { - CompoundTag tag = item.tag; - int data = 0; - item.id = (short) Material.POTION.getId(); - if (tag != null && tag.get("Potion") instanceof StringTag) { - StringTag potion = tag.get("Potion"); - String potionName = potion.getValue().replace("minecraft:", ""); - if (POTION_NAME_TO_ID.containsKey(potionName)) { - data = POTION_NAME_TO_ID.get(potionName) + 8192; - } - } - item.tag = null; - item.data = (short) data; - } - } - } - - public static void fixIdsFrom1_8To1_9(ItemStack item) { - if (item != null) { - if (item.id == Material.MONSTER_EGG.getId() && item.data != 0) { - CompoundTag tag = item.tag; - if (tag == null) { - tag = new CompoundTag("tag"); - } - CompoundTag entityTag = new CompoundTag("EntityTag"); - if (ENTTIY_ID_TO_NAME.containsKey(Integer.valueOf(item.data))) { - StringTag id = new StringTag("id", ENTTIY_ID_TO_NAME.get(Integer.valueOf(item.data))); - entityTag.put(id); - tag.put(entityTag); - } - item.tag = tag; - item.data = 0; - } - if (item.id == Material.POTION.getId()) { - CompoundTag tag = item.tag; - if (tag == null) { - tag = new CompoundTag("tag"); - } - if (item.data >= 16384) { - item.id = 438; // splash id - item.data = (short) (item.data - 8192); - } - if (POTION_ID_TO_NAME.containsKey(Integer.valueOf(item.data))) { - String name = POTION_ID_TO_NAME.get(Integer.valueOf(item.data)); - StringTag potion = new StringTag("Potion", "minecraft:" + name); - tag.put(potion); - } - item.tag = tag; - item.data = 0; - } - if (item.id == Material.WRITTEN_BOOK.getId()) { - CompoundTag tag = item.tag; - if (tag == null) { - tag = new CompoundTag("tag"); - } - ListTag pages = tag.get("pages"); - if (pages == null) { - pages = new ListTag("pages", Collections.singletonList(new StringTag(OutgoingTransformer.fixJson("")))); - tag.put(pages); - item.tag = tag; - return; - } - - for (int i = 0; i < pages.size(); i++) { - if (!(pages.get(i) instanceof StringTag)) - continue; - StringTag page = pages.get(i); - page.setValue(OutgoingTransformer.fixJson(page.getValue())); - } - item.tag = tag; - } - } - } - - public static ItemStack readItemStack(ByteBuf input) throws IOException { - short id = input.readShort(); - if (id < 0) { - - return null; - } else { - ItemStack item = new ItemStack(); - item.id = id; - item.amount = input.readByte(); - item.data = input.readShort(); - item.tag = PacketUtil.readNBT(input); - return item; - } - } - - public static void writeItemStack(ItemStack item, ByteBuf output) throws IOException { - if (item == null) { - output.writeShort(-1); - } else { - output.writeShort(item.id); - output.writeByte(item.amount); - output.writeShort(item.data); - PacketUtil.writeNBT(output, item.tag); - } - } - - public static class ItemStack { - - public short id; - public byte amount; - public short data; - public CompoundTag tag; - - public static ItemStack fromBukkit(org.bukkit.inventory.ItemStack stack) { - if(stack == null) return null; - ItemStack item = new ItemStack(); - item.id = (short) stack.getTypeId(); - item.amount = (byte) stack.getAmount(); - item.data = stack.getData().getData(); - // TODO: nbt - return item; - } - } - - private static Map ENTTIY_NAME_TO_ID = new HashMap<>(); - private static Map ENTTIY_ID_TO_NAME = new HashMap<>(); - - private static Map POTION_NAME_TO_ID = new HashMap<>(); - private static Map POTION_ID_TO_NAME = new HashMap<>(); + private static final Map ENTTIY_NAME_TO_ID = new HashMap<>(); + private static final Map ENTTIY_ID_TO_NAME = new HashMap<>(); + private static final Map POTION_NAME_TO_ID = new HashMap<>(); + private static final Map POTION_ID_TO_NAME = new HashMap<>(); static { /* Entities */ @@ -311,6 +139,159 @@ public class ItemSlotRewriter { } + public static void rewrite1_9To1_8(ByteBuf input, ByteBuf output) throws CancelException { + try { + ItemStack item = readItemStack(input); + fixIdsFrom1_9To1_8(item); + writeItemStack(item, output); + } catch (Exception e) { + System.out.println("Error while rewriting an item slot."); + e.printStackTrace(); + throw new CancelException(); + } + } + + public static void rewrite1_8To1_9(ByteBuf input, ByteBuf output) throws CancelException { + try { + ItemStack item = readItemStack(input); + fixIdsFrom1_8To1_9(item); + writeItemStack(item, output); + } catch (Exception e) { + System.out.println("Error while rewriting an item slot."); + e.printStackTrace(); + throw new CancelException(); + } + } + + public static void fixIdsFrom1_9To1_8(ItemStack item) { + if (item != null) { + if (item.id == Material.MONSTER_EGG.getId() && item.data == 0) { + CompoundTag tag = item.tag; + int data = 0; + if (tag != null && tag.get("EntityTag") instanceof CompoundTag) { + CompoundTag entityTag = tag.get("EntityTag"); + if (entityTag.get("id") instanceof StringTag) { + StringTag id = entityTag.get("id"); + if (ENTTIY_NAME_TO_ID.containsKey(id.getValue())) + data = ENTTIY_NAME_TO_ID.get(id.getValue()); + } + } + item.tag = null; + item.data = (short) data; + } + if (item.id == Material.POTION.getId()) { + CompoundTag tag = item.tag; + int data = 0; + if (tag != null && tag.get("Potion") instanceof StringTag) { + StringTag potion = tag.get("Potion"); + String potionName = potion.getValue().replace("minecraft:", ""); + if (POTION_NAME_TO_ID.containsKey(potionName)) { + data = POTION_NAME_TO_ID.get(potionName); + } + } + item.tag = null; + item.data = (short) data; + } + if (item.id == 438) { + CompoundTag tag = item.tag; + int data = 0; + item.id = (short) Material.POTION.getId(); + if (tag != null && tag.get("Potion") instanceof StringTag) { + StringTag potion = tag.get("Potion"); + String potionName = potion.getValue().replace("minecraft:", ""); + if (POTION_NAME_TO_ID.containsKey(potionName)) { + data = POTION_NAME_TO_ID.get(potionName) + 8192; + } + } + item.tag = null; + item.data = (short) data; + } + } + } + + public static void fixIdsFrom1_8To1_9(ItemStack item) { + if (item != null) { + if (item.id == Material.MONSTER_EGG.getId() && item.data != 0) { + CompoundTag tag = item.tag; + if (tag == null) { + tag = new CompoundTag("tag"); + } + CompoundTag entityTag = new CompoundTag("EntityTag"); + if (ENTTIY_ID_TO_NAME.containsKey((int) item.data)) { + StringTag id = new StringTag("id", ENTTIY_ID_TO_NAME.get((int) item.data)); + entityTag.put(id); + tag.put(entityTag); + } + item.tag = tag; + item.data = 0; + } + if (item.id == Material.POTION.getId()) { + CompoundTag tag = item.tag; + if (tag == null) { + tag = new CompoundTag("tag"); + } + if (item.data >= 16384) { + item.id = 438; // splash id + item.data = (short) (item.data - 8192); + } + if (POTION_ID_TO_NAME.containsKey((int) item.data)) { + String name = POTION_ID_TO_NAME.get((int) item.data); + StringTag potion = new StringTag("Potion", "minecraft:" + name); + tag.put(potion); + } + item.tag = tag; + item.data = 0; + } + if (item.id == Material.WRITTEN_BOOK.getId()) { + CompoundTag tag = item.tag; + if (tag == null) { + tag = new CompoundTag("tag"); + } + ListTag pages = tag.get("pages"); + if (pages == null) { + pages = new ListTag("pages", Collections.singletonList(new StringTag(OutgoingTransformer.fixJson("")))); + tag.put(pages); + item.tag = tag; + return; + } + + for (int i = 0; i < pages.size(); i++) { + if (!(pages.get(i) instanceof StringTag)) + continue; + StringTag page = pages.get(i); + page.setValue(OutgoingTransformer.fixJson(page.getValue())); + } + item.tag = tag; + } + } + } + + public static ItemStack readItemStack(ByteBuf input) throws IOException { + short id = input.readShort(); + if (id < 0) { + + return null; + } else { + ItemStack item = new ItemStack(); + item.id = id; + item.amount = input.readByte(); + item.data = input.readShort(); + item.tag = PacketUtil.readNBT(input); + return item; + } + } + + public static void writeItemStack(ItemStack item, ByteBuf output) throws IOException { + if (item == null) { + output.writeShort(-1); + } else { + output.writeShort(item.id); + output.writeByte(item.amount); + output.writeShort(item.data); + PacketUtil.writeNBT(output, item.tag); + } + } + private static void registerEntity(Integer id, String name) { ENTTIY_ID_TO_NAME.put(id, name); ENTTIY_NAME_TO_ID.put(name, id); @@ -320,4 +301,22 @@ public class ItemSlotRewriter { POTION_ID_TO_NAME.put(id, name); POTION_NAME_TO_ID.put(name, id); } + + public static class ItemStack { + + public short id; + public byte amount; + public short data; + public CompoundTag tag; + + public static ItemStack fromBukkit(org.bukkit.inventory.ItemStack stack) { + if(stack == null) return null; + ItemStack item = new ItemStack(); + item.id = (short) stack.getTypeId(); + item.amount = (byte) stack.getAmount(); + item.data = stack.getData().getData(); + // TODO: nbt + return item; + } + } } diff --git a/src/main/java/us/myles/ViaVersion/sounds/SoundCategory.java b/src/main/java/us/myles/ViaVersion/sounds/SoundCategory.java index 6e8c97e20..e32ebdcd7 100644 --- a/src/main/java/us/myles/ViaVersion/sounds/SoundCategory.java +++ b/src/main/java/us/myles/ViaVersion/sounds/SoundCategory.java @@ -1,5 +1,10 @@ package us.myles.ViaVersion.sounds; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +@RequiredArgsConstructor +@Getter public enum SoundCategory { @@ -14,20 +19,7 @@ public enum SoundCategory { AMBIENT("ambient", 8), VOICE("voice", 9); - private String name; - private int id; - - SoundCategory(String name, int id) { - this.name = name; - this.id = id; - } - - public String getName() { - return name; - } - - public int getId() { - return id; - } + private final String name; + private final int id; } diff --git a/src/main/java/us/myles/ViaVersion/sounds/SoundEffect.java b/src/main/java/us/myles/ViaVersion/sounds/SoundEffect.java index fc53ba660..2c544b3e0 100644 --- a/src/main/java/us/myles/ViaVersion/sounds/SoundEffect.java +++ b/src/main/java/us/myles/ViaVersion/sounds/SoundEffect.java @@ -1,5 +1,8 @@ package us.myles.ViaVersion.sounds; +import lombok.Getter; + +@Getter public enum SoundEffect { MOB_HORSE_ZOMBIE_IDLE("mob.horse.zombie.idle", "entity.zombie_horse.ambient", SoundCategory.NEUTRAL), @@ -249,21 +252,21 @@ public enum SoundEffect { MUSIC_GAME_END_CREDITS("music.game.end.credits", "music.credits", SoundCategory.MUSIC), MUSIC_GAME_CREATIVE("music.game.creative", "music.creative", SoundCategory.MUSIC); - private String name; - private String newname; - private SoundCategory cat; - private boolean breaksound; + private final String name; + private final String newName; + private final SoundCategory category; + private final boolean breaksound; SoundEffect(String name, String newname, SoundCategory cat) { - this.cat = cat; - this.newname = newname; + this.category = cat; + this.newName = newname; this.name = name; this.breaksound = name.startsWith("dig."); } SoundEffect(String name, String newname, SoundCategory cat, boolean shouldIgnore) { - this.cat = cat; - this.newname = newname; + this.category = cat; + this.newName = newname; this.name = name; this.breaksound = name.startsWith("dig.") || shouldIgnore; } @@ -277,20 +280,4 @@ public enum SoundEffect { return null; } - public String getNewName() { - return newname; - } - - public String getName() { - return name; - } - - public SoundCategory getCategory() { - return cat; - } - - public boolean isBreakPlaceSound() { - return breaksound; - } - } diff --git a/src/main/java/us/myles/ViaVersion/transformers/IncomingTransformer.java b/src/main/java/us/myles/ViaVersion/transformers/IncomingTransformer.java index 3eb763d21..0c4ae36ee 100644 --- a/src/main/java/us/myles/ViaVersion/transformers/IncomingTransformer.java +++ b/src/main/java/us/myles/ViaVersion/transformers/IncomingTransformer.java @@ -188,40 +188,44 @@ public class IncomingTransformer { byte[] b = new byte[input.readableBytes()]; input.readBytes(b); // patch books - if (name.equals("MC|BSign")) { - ByteBuf in = Unpooled.wrappedBuffer(b); - try { - ItemSlotRewriter.ItemStack stack = ItemSlotRewriter.readItemStack(in); - stack.id = (short) Material.WRITTEN_BOOK.getId(); - // write - ItemSlotRewriter.writeItemStack(stack, output); - } catch (IOException e) { - e.printStackTrace(); + switch (name) { + case "MC|BSign": { + ByteBuf in = Unpooled.wrappedBuffer(b); + try { + ItemSlotRewriter.ItemStack stack = ItemSlotRewriter.readItemStack(in); + stack.id = (short) Material.WRITTEN_BOOK.getId(); + // write + ItemSlotRewriter.writeItemStack(stack, output); + } catch (IOException e) { + e.printStackTrace(); + } + return; } - return; - } else if (name.equals("MC|AutoCmd")) { - ByteBuf in = Unpooled.wrappedBuffer(b); - int x = in.readInt(); - int y = in.readInt(); - int z = in.readInt(); - String command = PacketUtil.readString(in); - boolean flag = in.readBoolean(); + case "MC|AutoCmd": { + ByteBuf in = Unpooled.wrappedBuffer(b); + int x = in.readInt(); + int y = in.readInt(); + int z = in.readInt(); + String command = PacketUtil.readString(in); + boolean flag = in.readBoolean(); - output.clear(); - PacketUtil.writeVarInt(PacketType.PLAY_PLUGIN_MESSAGE_REQUEST.getPacketID(), output); - PacketUtil.writeString("MC|AdvCdm", output); - output.writeByte(0); - output.writeInt(x); - output.writeInt(y); - output.writeInt(z); - PacketUtil.writeString(command, output); - output.writeBoolean(flag); - return; - } else if (name.equals("MC|AdvCmd")) { - output.clear(); - PacketUtil.writeVarInt(PacketType.PLAY_PLUGIN_MESSAGE_REQUEST.getPacketID(), output); - PacketUtil.writeString("MC|AdvCdm", output); - output.writeBytes(b); + output.clear(); + PacketUtil.writeVarInt(PacketType.PLAY_PLUGIN_MESSAGE_REQUEST.getPacketID(), output); + PacketUtil.writeString("MC|AdvCdm", output); + output.writeByte(0); + output.writeInt(x); + output.writeInt(y); + output.writeInt(z); + PacketUtil.writeString(command, output); + output.writeBoolean(flag); + return; + } + case "MC|AdvCmd": + output.clear(); + PacketUtil.writeVarInt(PacketType.PLAY_PLUGIN_MESSAGE_REQUEST.getPacketID(), output); + PacketUtil.writeString("MC|AdvCdm", output); + output.writeBytes(b); + break; } output.writeBytes(b); } diff --git a/src/main/java/us/myles/ViaVersion/transformers/OutgoingTransformer.java b/src/main/java/us/myles/ViaVersion/transformers/OutgoingTransformer.java index 265f16c42..8432f040f 100644 --- a/src/main/java/us/myles/ViaVersion/transformers/OutgoingTransformer.java +++ b/src/main/java/us/myles/ViaVersion/transformers/OutgoingTransformer.java @@ -3,6 +3,7 @@ package us.myles.ViaVersion.transformers; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; +import lombok.RequiredArgsConstructor; import org.bukkit.entity.EntityType; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @@ -33,18 +34,38 @@ import java.util.*; import static us.myles.ViaVersion.util.PacketUtil.*; +@RequiredArgsConstructor public class OutgoingTransformer { - private final ConnectionInfo info; + private final ViaVersionPlugin plugin = (ViaVersionPlugin) ViaVersion.getInstance(); + + private final ConnectionInfo info; + private final Map uuidMap = new HashMap<>(); + private final Map clientEntityTypes = new HashMap<>(); + private final Map vehicleMap = new HashMap<>(); private boolean cancel = false; private boolean autoTeam = false; - private Map uuidMap = new HashMap(); - private Map clientEntityTypes = new HashMap(); - private Map vehicleMap = new HashMap<>(); - - public OutgoingTransformer(ConnectionInfo info) { - this.info = info; + public static String fixJson(String line) { + if (line == null || line.equalsIgnoreCase("null")) { + line = "{\"text\":\"\"}"; + } else { + if ((!line.startsWith("\"") || !line.endsWith("\"")) && (!line.startsWith("{") || !line.endsWith("}"))) { + JSONObject obj = new JSONObject(); + obj.put("text", line); + return obj.toJSONString(); + } + if (line.startsWith("\"") && line.endsWith("\"")) { + line = "{\"text\":" + line + "}"; + } + } + try { + new JSONParser().parse(line); + } catch (Exception e) { + System.out.println("Invalid JSON String: \"" + line + "\" Please report this issue to the ViaVersion Github: " + e.getMessage()); + return "{\"text\":\"\"}"; + } + return line; } public void transform(int packetID, ByteBuf input, ByteBuf output) throws CancelException { @@ -75,7 +96,7 @@ public class OutgoingTransformer { int catid = 0; String newname = name; if (effect != null) { - if (effect.isBreakPlaceSound()) { + if (effect.isBreaksound()) { throw new CancelException(); } catid = effect.getCategory().getId(); @@ -633,12 +654,7 @@ public class OutgoingTransformer { if (autoTeam && name.equalsIgnoreCase(info.getUsername())) { if (mode == 4) { // since removing add to auto team - plugin.run(new Runnable() { - @Override - public void run() { - sendTeamPacket(true); - } - }, false); + plugin.run(() -> sendTeamPacket(true), false); } else { // since adding remove from auto team sendTeamPacket(false); @@ -730,9 +746,7 @@ public class OutgoingTransformer { if (info.getLastPacket().getClass().getName().endsWith("PacketPlayOutMapChunkBulk")) { try { sk = ReflectionUtil.get(info.getLastPacket(), "d", boolean.class); - } catch (NoSuchFieldException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { + } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } } @@ -774,28 +788,6 @@ public class OutgoingTransformer { info.sendRawPacket(buf); } - public static String fixJson(String line) { - if (line == null || line.equalsIgnoreCase("null")) { - line = "{\"text\":\"\"}"; - } else { - if ((!line.startsWith("\"") || !line.endsWith("\"")) && (!line.startsWith("{") || !line.endsWith("}"))) { - JSONObject obj = new JSONObject(); - obj.put("text", line); - return obj.toJSONString(); - } - if (line.startsWith("\"") && line.endsWith("\"")) { - line = "{\"text\":" + line + "}"; - } - } - try { - new JSONParser().parse(line); - } catch (Exception e) { - System.out.println("Invalid JSON String: \"" + line + "\" Please report this issue to the ViaVersion Github: " + e.getMessage()); - return "{\"text\":\"\"}"; - } - return line; - } - private void transformMetadata(int entityID, ByteBuf input, ByteBuf output) throws CancelException { EntityType type = clientEntityTypes.get(entityID); if (type == null) { diff --git a/src/main/java/us/myles/ViaVersion/update/UpdateListener.java b/src/main/java/us/myles/ViaVersion/update/UpdateListener.java index 62f488e48..b57cb5dd2 100644 --- a/src/main/java/us/myles/ViaVersion/update/UpdateListener.java +++ b/src/main/java/us/myles/ViaVersion/update/UpdateListener.java @@ -1,17 +1,15 @@ package us.myles.ViaVersion.update; +import lombok.RequiredArgsConstructor; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.plugin.Plugin; +@RequiredArgsConstructor public class UpdateListener implements Listener { - - private Plugin plugin; - - public UpdateListener(Plugin plugin) { - this.plugin = plugin; - } + + private final Plugin plugin; @EventHandler public void onJoin(PlayerJoinEvent e) { diff --git a/src/main/java/us/myles/ViaVersion/update/Version.java b/src/main/java/us/myles/ViaVersion/update/Version.java index 6a36fcceb..118f45de7 100644 --- a/src/main/java/us/myles/ViaVersion/update/Version.java +++ b/src/main/java/us/myles/ViaVersion/update/Version.java @@ -9,7 +9,7 @@ public class Version implements Comparable { if (value == null) throw new IllegalArgumentException("Version can not be null"); - if (value.matches("^[0-9]+(\\.[0-9]+)*$") == false) + if (!value.matches("^[0-9]+(\\.[0-9]+)*$")) throw new IllegalArgumentException("Invalid version format"); String[] split = value.split("\\."); @@ -19,16 +19,6 @@ public class Version implements Comparable { parts[i] = Integer.parseInt(split[i]); } - @Override - public String toString() { - String[] split = new String[parts.length]; - - for (int i = 0; i < parts.length; i += 1) - split[i] = String.valueOf(parts[i]); - - return StringUtils.join(split, "."); - } - public static int compare(Version verA, Version verB) { if (verA == verB) return 0; if (verA == null) return -1; @@ -46,18 +36,25 @@ public class Version implements Comparable { return 0; } + public static boolean equals(Version verA, Version verB) { + return verA == verB || verA != null && verB != null && compare(verA, verB) == 0; + } + + @Override + public String toString() { + String[] split = new String[parts.length]; + + for (int i = 0; i < parts.length; i += 1) + split[i] = String.valueOf(parts[i]); + + return StringUtils.join(split, "."); + } + @Override public int compareTo(Version that) { return compare(this, that); } - public static boolean equals(Version verA, Version verB) { - if (verA == verB) return true; - if (verA == null) return false; - if (verB == null) return false; - return compare(verA, verB) == 0; - } - @Override public boolean equals(Object that) { return that instanceof Version && equals(this, (Version) that); diff --git a/src/main/java/us/myles/ViaVersion/util/EntityUtil.java b/src/main/java/us/myles/ViaVersion/util/EntityUtil.java index 8095e4722..696f8a576 100644 --- a/src/main/java/us/myles/ViaVersion/util/EntityUtil.java +++ b/src/main/java/us/myles/ViaVersion/util/EntityUtil.java @@ -3,6 +3,7 @@ package us.myles.ViaVersion.util; import org.bukkit.entity.EntityType; public class EntityUtil { + public static EntityType getTypeFromID(int typeID, boolean isObject) { if (isObject) { return getObjectFromID(typeID); diff --git a/src/main/java/us/myles/ViaVersion/util/PacketUtil.java b/src/main/java/us/myles/ViaVersion/util/PacketUtil.java index a2442fec3..d1e74f88d 100644 --- a/src/main/java/us/myles/ViaVersion/util/PacketUtil.java +++ b/src/main/java/us/myles/ViaVersion/util/PacketUtil.java @@ -69,12 +69,10 @@ public class PacketUtil { } public static List callDecode(ByteToMessageDecoder decoder, ChannelHandlerContext ctx, Object input) { - List output = new ArrayList(); + List output = new ArrayList<>(); try { PacketUtil.DECODE_METHOD.invoke(decoder, ctx, input, output); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } return output; @@ -83,9 +81,7 @@ public class PacketUtil { public static void callEncode(MessageToByteEncoder encoder, ChannelHandlerContext ctx, Object msg, ByteBuf output) { try { PacketUtil.ENCODE_METHOD.invoke(encoder, ctx, msg, output); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } @@ -169,7 +165,7 @@ public class PacketUtil { public static List readStringArray(ByteBuf buf) { int len = readVarInt(buf); - List ret = new ArrayList(len); + List ret = new ArrayList<>(len); for (int i = 0; i < len; i++) { ret.add(readString(buf)); } @@ -258,8 +254,8 @@ public class PacketUtil { } public static void writeLongs(long[] data, ByteBuf output) { - for (int index = 0; index < data.length; index++) { - output.writeLong(data[index]); + for (long aData : data) { + output.writeLong(aData); } }