Use reflection for multi-version support.

- Switched to using reflection for multi-version support of Minecraft to make supporting it a little easier. Shouldn't require an update for 1.14 anymore now (unless they change the format or something).
- Code style enforced.
This commit is contained in:
Pim van der Loos 2019-04-15 12:04:59 +02:00
parent 07e3b65f2b
commit da224bfc1a
No known key found for this signature in database
GPG Key ID: C16F020ADAE6D5A8
19 changed files with 669 additions and 1272 deletions

View File

@ -16,6 +16,7 @@
</repositories> </repositories>
<dependencies> <dependencies>
<!--
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
<artifactId>spigot-1.9</artifactId> <artifactId>spigot-1.9</artifactId>
@ -39,7 +40,7 @@
<artifactId>spigot-1.11</artifactId> <artifactId>spigot-1.11</artifactId>
<version>1.11.2-R0.1-SNAPSHOT</version> <version>1.11.2-R0.1-SNAPSHOT</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency> -->
<dependency> <dependency>
<groupId>org.spigotmc</groupId> <groupId>org.spigotmc</groupId>
<artifactId>spigot-1.12</artifactId> <artifactId>spigot-1.12</artifactId>

View File

@ -15,23 +15,15 @@ import nl.pim16aap2.armoredElytra.handlers.EventHandlers;
import nl.pim16aap2.armoredElytra.handlers.FlyDurabilityHandler; import nl.pim16aap2.armoredElytra.handlers.FlyDurabilityHandler;
import nl.pim16aap2.armoredElytra.handlers.LoginHandler; import nl.pim16aap2.armoredElytra.handlers.LoginHandler;
import nl.pim16aap2.armoredElytra.handlers.Uninstaller; import nl.pim16aap2.armoredElytra.handlers.Uninstaller;
import nl.pim16aap2.armoredElytra.nms.NBTEditor; import nl.pim16aap2.armoredElytra.nbtEditor.NBTEditor;
import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_10_R1;
import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_11_R1;
import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_12_R1;
import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_13_R1;
import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_13_R2;
import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_9_R1;
import nl.pim16aap2.armoredElytra.nms.NBTEditor_V1_9_R2;
import nl.pim16aap2.armoredElytra.util.ArmorTier; import nl.pim16aap2.armoredElytra.util.ArmorTier;
import nl.pim16aap2.armoredElytra.util.ConfigLoader; import nl.pim16aap2.armoredElytra.util.ConfigLoader;
import nl.pim16aap2.armoredElytra.util.Messages; import nl.pim16aap2.armoredElytra.util.Messages;
import nl.pim16aap2.armoredElytra.util.Metrics; import nl.pim16aap2.armoredElytra.util.Metrics;
import nl.pim16aap2.armoredElytra.util.Update; import nl.pim16aap2.armoredElytra.util.Update;
public class ArmoredElytra extends JavaPlugin implements Listener public class ArmoredElytra extends JavaPlugin implements Listener
{ {
// TODO: Merge EventHandlers and EventHandlers_V1.9.
private NBTEditor nbtEditor; private NBTEditor nbtEditor;
private Messages messages; private Messages messages;
private ConfigLoader config; private ConfigLoader config;
@ -44,86 +36,78 @@ public class ArmoredElytra extends JavaPlugin implements Listener
private boolean upToDate; private boolean upToDate;
private String locale; private String locale;
private boolean is1_9; private boolean is1_9;
@Override @Override
public void onEnable() public void onEnable()
{ {
this.readConfigValues(); readConfigValues();
this.messages = new Messages(this); messages = new Messages(this);
this.readMessages(); readMessages();
// Check if the user allows checking for updates. // Check if the user allows checking for updates.
if (config.getBool("checkForUpdates")) if (config.getBool("checkForUpdates"))
{ {
// Check for updates in a new thread, so the server won't hang when it cannot contact the update servers. // Check for updates in a new thread, so the server won't hang when it cannot contact the update servers.
Thread thread = new Thread(new Runnable() final Thread thread = new Thread(() ->
{ {
@Override final ArmoredElytra plugin = getPlugin();
public void run() final Update update = new Update(278437, plugin);
final String latestVersion = update.getLatestVersion();
if (latestVersion == null)
plugin.myLogger(Level.WARNING, "Encountered problem contacting update servers! Please check manually! The error above does not affect the plugin!");
else
{ {
ArmoredElytra plugin = getPlugin(); final String thisVersion = plugin.getDescription().getVersion();
Update update = new Update(278437, plugin); // Check if this is the latest version or not.
String latestVersion = update.getLatestVersion(); final int updateStatus = update.versionCompare(latestVersion, thisVersion);
if (latestVersion == null) if (updateStatus > 0)
plugin.myLogger(Level.WARNING, "Encountered problem contacting update servers! Please check manually! The error above does not affect the plugin!"); {
// Load the loginHandler to show messages to the user when they join.
Bukkit.getPluginManager().registerEvents(new LoginHandler(plugin, "The Armored Elytra plugin is out of date!"), plugin);
plugin.myLogger(Level.INFO, "Plugin out of date! You are using version " + thisVersion + " but the latest version is version " + latestVersion + "!");
plugin.setUpToDate(false);
}
else else
{ {
String thisVersion = plugin.getDescription().getVersion(); plugin.setUpToDate(true);
// Check if this is the latest version or not. plugin.myLogger(Level.INFO, "You seem to be using the latest version of this plugin!");
int updateStatus = update.versionCompare(latestVersion, thisVersion);
if (updateStatus > 0)
{
// Load the loginHandler to show messages to the user when they join.
Bukkit.getPluginManager().registerEvents(new LoginHandler(plugin, "The Armored Elytra plugin is out of date!"), plugin);
plugin.myLogger(Level.INFO, "Plugin out of date! You are using version " + thisVersion + " but the latest version is version " + latestVersion + "!");
plugin.setUpToDate(false);
}
else
{
plugin.setUpToDate(true);
plugin.myLogger(Level.INFO, "You seem to be using the latest version of this plugin!");
}
} }
} }
}); });
thread.start(); thread.start();
} }
else else
myLogger(Level.INFO, "Plugin update checking not enabled! You will not receive any messages about new updates for this plugin. Please consider turning this on in the config."); myLogger(Level.INFO, "Plugin update checking not enabled! You will not receive any messages about new updates for this plugin. Please consider turning this on in the config.");
// Are stats allowed?
if (config.getBool("allowStats")) if (config.getBool("allowStats"))
{ {
myLogger(Level.INFO, "Enabling stats! Thanks, it really helps!"); myLogger(Level.INFO, "Enabling stats! Thanks, it really helps!");
@SuppressWarnings("unused") @SuppressWarnings("unused")
final
Metrics metrics = new Metrics(this); Metrics metrics = new Metrics(this);
} }
else else
// Y u do dis? :( // Y u do dis? :(
myLogger(Level.INFO, "Stats disabled, not laoding stats :(... Please consider enabling it! I am a simple man, seeing higher user numbers helps me stay motivated!"); myLogger(Level.INFO, "Stats disabled, not loading stats :(... Please consider enabling it! I am a simple man, seeing higher user numbers helps me stay motivated!");
locale = config.getString("languageFile");
this.locale = config.getString("languageFile");
// Load the files for the correct version of Minecraft. // Load the files for the correct version of Minecraft.
if (compatibleMCVer()) if (compatibleMCVer())
{ {
// if (this.is1_9) Bukkit.getPluginManager().registerEvents(new EventHandlers(this, nbtEditor, is1_9), this);
// Bukkit.getPluginManager().registerEvents(new EventHandlers_V1_9(this, nbtEditor), this);
// else
// Bukkit.getPluginManager().registerEvents(new EventHandlers(this, nbtEditor), this);
Bukkit.getPluginManager().registerEvents(new EventHandlers(this, nbtEditor, this.is1_9), this);
getCommand("ArmoredElytra").setExecutor(new CommandHandler(this, nbtEditor)); getCommand("ArmoredElytra").setExecutor(new CommandHandler(this, nbtEditor));
} }
else else
{ {
myLogger(Level.WARNING, "Trying to load the plugin on an incompatible version of Minecraft! This plugin will NOT be enabled!"); Bukkit.getPluginManager().registerEvents(new LoginHandler(this, "The Armored Elytra plugin failed to start correctly! Please send the startup log to pim16aap2!"), this);
myLogger(Level.WARNING, "Plugin failed to load! Either your version isn't supported or something went horribly wrong! Please contact pim16aap2!");
return; return;
} }
// Load the plugin normally if not in uninstall mode. // Load the plugin normally if not in uninstall mode.
if (!uninstallMode) if (!uninstallMode)
{ {
@ -132,198 +116,167 @@ public class ArmoredElytra extends JavaPlugin implements Listener
{ {
Bukkit.getPluginManager().registerEvents(new FlyDurabilityHandler(nbtEditor), this); Bukkit.getPluginManager().registerEvents(new FlyDurabilityHandler(nbtEditor), this);
myLogger(Level.INFO, "Durability penalty for flying disabled!"); myLogger(Level.INFO, "Durability penalty for flying disabled!");
} }
else else
myLogger(Level.INFO, "Durability penalty for flying enabled!"); myLogger(Level.INFO, "Durability penalty for flying enabled!");
// Log all allowed enchantments. // Log all allowed enchantments.
myLogger(Level.INFO, ("Allowed enchantments:")); myLogger(Level.INFO, ("Allowed enchantments:"));
for (String s : config.getStringList("allowedEnchantments")) for (final String s : config.getStringList("allowedEnchantments"))
myLogger(Level.INFO, " - " + s); myLogger(Level.INFO, " - " + s);
} }
else else
{ {
myLogger(Level.WARNING, "Plugin in uninstall mode!"); myLogger(Level.WARNING, "Plugin in uninstall mode!");
Bukkit.getPluginManager().registerEvents(new Uninstaller(this, nbtEditor), this); Bukkit.getPluginManager().registerEvents(new Uninstaller(this, nbtEditor), this);
} }
} }
public void readConfigValues() public void readConfigValues()
{ {
// Load the settings from the config file. // Load the settings from the config file.
this.config = new ConfigLoader(this); config = new ConfigLoader(this);
// Check if the plugin should go into uninstall mode. // Check if the plugin should go into uninstall mode.
this.uninstallMode = config.getBool("uninstallMode"); uninstallMode = config.getBool("uninstallMode");
} }
public Messages getMyMessages() public Messages getMyMessages()
{ {
return this.messages; return messages;
} }
private void readMessages() private void readMessages()
{ {
// Replace color codes by the corresponding colors. // Replace color codes by the corresponding colors.
this.usageDeniedMessage = this.getMyMessages().getString("MESSAGES.UsageDenied" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); usageDeniedMessage = getMyMessages().getString("MESSAGES.UsageDenied" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
this.elytraReceivedMessage = this.getMyMessages().getString("MESSAGES.ElytraReceived").replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); elytraReceivedMessage = getMyMessages().getString("MESSAGES.ElytraReceived").replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
this.elytraLore = this.getMyMessages().getString("MESSAGES.Lore" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1"); elytraLore = getMyMessages().getString("MESSAGES.Lore" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
leatherName = getMyMessages().getString("TIER.Leather" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
goldName = getMyMessages().getString("TIER.Gold" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
chainName = getMyMessages().getString("TIER.Chain" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
ironName = getMyMessages().getString("TIER.Iron" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
diamondName = getMyMessages().getString("TIER.Diamond" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
this.leatherName = this.getMyMessages().getString("TIER.Leather" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
this.goldName = this.getMyMessages().getString("TIER.Gold" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
this.chainName = this.getMyMessages().getString("TIER.Chain" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
this.ironName = this.getMyMessages().getString("TIER.Iron" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
this.diamondName = this.getMyMessages().getString("TIER.Diamond" ).replaceAll("&((?i)[0-9a-fk-or])", "\u00A7$1");
// Change the string to null if it says "NONE". // Change the string to null if it says "NONE".
this.usageDeniedMessage = (Objects.equals(usageDeniedMessage, new String("NONE")) ? null : usageDeniedMessage ); usageDeniedMessage = (Objects.equals(usageDeniedMessage, new String("NONE")) ? null : usageDeniedMessage );
this.elytraReceivedMessage = (Objects.equals(elytraReceivedMessage, new String("NONE")) ? null : elytraReceivedMessage); elytraReceivedMessage = (Objects.equals(elytraReceivedMessage, new String("NONE")) ? null : elytraReceivedMessage);
this.elytraLore = (Objects.equals(elytraLore, new String("NONE")) ? null : elytraLore ); elytraLore = (Objects.equals(elytraLore, new String("NONE")) ? null : elytraLore );
} }
// Returns true if this is the latest version of this plugin. // Returns true if this is the latest version of this plugin.
public boolean isUpToDate() public boolean isUpToDate()
{ {
return upToDate; return upToDate;
} }
// Get this. // Get this.
public ArmoredElytra getPlugin() public ArmoredElytra getPlugin()
{ {
return this; return this;
} }
// Returns the config handler. // Returns the config handler.
public ConfigLoader getConfigLoader() public ConfigLoader getConfigLoader()
{ {
return config; return config;
} }
// Send a message to a player in a specific color. // Send a message to a player in a specific color.
public void messagePlayer(Player player, ChatColor color, String str) public void messagePlayer(Player player, ChatColor color, String str)
{ {
player.sendMessage(color + str); player.sendMessage(color + str);
} }
// Send a message to a player. // Send a message to a player.
public void messagePlayer(Player player, String str) public void messagePlayer(Player player, String str)
{ {
messagePlayer(player, ChatColor.WHITE, str); messagePlayer(player, ChatColor.WHITE, str);
} }
// Send the usageDeniedMessage message to the player. // Send the usageDeniedMessage message to the player.
public void usageDeniedMessage(Player player, ArmorTier armorTier) public void usageDeniedMessage(Player player, ArmorTier armorTier)
{ {
if (usageDeniedMessage != null) if (usageDeniedMessage != null)
{ {
String message = fillInArmorTierInStringNoColor(usageDeniedMessage, armorTier); final String message = fillInArmorTierInStringNoColor(usageDeniedMessage, armorTier);
messagePlayer(player, ChatColor.RED, message); messagePlayer(player, ChatColor.RED, message);
} }
} }
// Send the elytraReceivedMessage message to the player. // Send the elytraReceivedMessage message to the player.
public void elytraReceivedMessage(Player player, ArmorTier armorTier) public void elytraReceivedMessage(Player player, ArmorTier armorTier)
{ {
if (elytraReceivedMessage != null) if (elytraReceivedMessage != null)
{ {
String message = fillInArmorTierInStringNoColor(elytraReceivedMessage, armorTier); final String message = fillInArmorTierInStringNoColor(elytraReceivedMessage, armorTier);
messagePlayer(player, ChatColor.GREEN, message); messagePlayer(player, ChatColor.GREEN, message);
} }
} }
// Replace %ARMOR_TIER% by the name of that armor tier in a string, but strip %ARMOR_TIER% of its color. // Replace %ARMOR_TIER% by the name of that armor tier in a string, but strip %ARMOR_TIER% of its color.
public String fillInArmorTierInStringNoColor(String string, ArmorTier armorTier) public String fillInArmorTierInStringNoColor(String string, ArmorTier armorTier)
{ {
return string.replace("%ARMOR_TIER%", ChatColor.stripColor(getArmoredElytrName(armorTier))); return string.replace("%ARMOR_TIER%", ChatColor.stripColor(getArmoredElytrName(armorTier)));
} }
public String getLocale() public String getLocale()
{ {
return locale == null ? "en_US" : locale; return locale == null ? "en_US" : locale;
} }
// Print a string to the log. // Print a string to the log.
public void myLogger(Level level, String str) public void myLogger(Level level, String str)
{ {
Bukkit.getLogger().log(level, "[" + this.getName() + "] " + str); Bukkit.getLogger().log(level, "[" + getName() + "] " + str);
} }
// Log message that only gets printed when debugging is enabled in the config file. // Log message that only gets printed when debugging is enabled in the config file.
public void debugMsg(Level level, String str) public void debugMsg(Level level, String str)
{ {
if (config.getBool("enableDebug")) if (config.getBool("enableDebug"))
myLogger(level, str); myLogger(level, str);
} }
// Give the provided player the provided item. // Give the provided player the provided item.
public void giveArmoredElytraToPlayer(Player player, ItemStack item) public void giveArmoredElytraToPlayer(Player player, ItemStack item)
{ {
if (item != null) if (item != null)
player.getInventory().addItem(item); player.getInventory().addItem(item);
} }
// Check + initialize for the correct version of Minecraft. // Check + initialize for the correct version of Minecraft.
public boolean compatibleMCVer() public boolean compatibleMCVer()
{ {
String version; nbtEditor = new NBTEditor(this);
return nbtEditor.succes();
try
{
version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
}
catch (ArrayIndexOutOfBoundsException useAVersionMentionedInTheDescriptionPleaseException)
{
return false;
}
if ( version.equals("v1_9_R1"))
{
nbtEditor = new NBTEditor_V1_9_R1(this);
this.is1_9 = true;
}
else if (version.equals("v1_9_R2"))
{
nbtEditor = new NBTEditor_V1_9_R2(this);
this.is1_9 = true;
}
else if (version.equals("v1_10_R1"))
nbtEditor = new NBTEditor_V1_10_R1(this);
else if (version.equals("v1_11_R1"))
nbtEditor = new NBTEditor_V1_11_R1(this);
else if (version.equals("v1_12_R1"))
nbtEditor = new NBTEditor_V1_12_R1(this);
else if (version.equals("v1_13_R1"))
nbtEditor = new NBTEditor_V1_13_R1(this);
else if (version.equals("v1_13_R2"))
nbtEditor = new NBTEditor_V1_13_R2(this);
// Return true if compatible.
return nbtEditor != null;
} }
public String getElytraLore() public String getElytraLore()
{ {
return this.elytraLore; return elytraLore;
} }
public String getArmoredElytrName(ArmorTier tier) public String getArmoredElytrName(ArmorTier tier)
{ {
String ret; String ret;
switch(tier) switch(tier)
{ {
case LEATHER: case LEATHER:
ret = this.leatherName; ret = leatherName;
break; break;
case GOLD: case GOLD:
ret = this.goldName; ret = goldName;
break; break;
case CHAIN: case CHAIN:
ret = this.chainName; ret = chainName;
break; break;
case IRON: case IRON:
ret = this.ironName; ret = ironName;
break; break;
case DIAMOND: case DIAMOND:
ret = this.diamondName; ret = diamondName;
break; break;
default: default:
ret = "NONE"; ret = "NONE";

View File

@ -12,157 +12,148 @@ import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.nms.NBTEditor; import nl.pim16aap2.armoredElytra.nbtEditor.NBTEditor;
import nl.pim16aap2.armoredElytra.util.ArmorTier; import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class CommandHandler implements CommandExecutor public class CommandHandler implements CommandExecutor
{ {
ArmoredElytra plugin; private final ArmoredElytra plugin;
NBTEditor nbtEditor; private final NBTEditor nbtEditor;
public CommandHandler(ArmoredElytra plugin, NBTEditor nbtEditor)
{
this.plugin = plugin;
this.nbtEditor = nbtEditor;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
Player player;
if (sender instanceof Player)
{
player = (Player) sender;
if (plugin.getUninstallMode()) public CommandHandler(ArmoredElytra plugin, NBTEditor nbtEditor)
{ {
plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.UninstallMode")); this.plugin = plugin;
return true; this.nbtEditor = nbtEditor;
} }
@Override
if (cmd.getName().equalsIgnoreCase("ArmoredElytra")) public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{ {
if (args.length == 1 || args.length == 2) Player player;
{
ItemStack newElytra = null; if (sender instanceof Player)
String tier = null; {
Player receiver; player = (Player) sender;
boolean allowed = false;
ArmorTier armorTier = ArmorTier.NONE; if (plugin.getUninstallMode())
if (args.length == 1) {
{ plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.UninstallMode"));
receiver = player; return true;
tier = args[0]; }
}
else
{ if (cmd.getName().equalsIgnoreCase("ArmoredElytra"))
receiver = Bukkit.getPlayer(args[0]); if (args.length == 1 || args.length == 2)
if (receiver == null) {
{ ItemStack newElytra = null;
plugin.messagePlayer(player, ChatColor.RED, "Player \"" + args[0] + "\" not found!"); String tier = null;
return true; Player receiver;
} boolean allowed = false;
tier = args[1]; ArmorTier armorTier = ArmorTier.NONE;
} if (args.length == 1)
{
// Leather armor. receiver = player;
if (tier.equalsIgnoreCase("leather")) tier = args[0];
{ }
armorTier = ArmorTier.LEATHER; else
if (player.hasPermission("armoredelytra.give.leather")) {
allowed = true; receiver = Bukkit.getPlayer(args[0]);
if (receiver == null)
// Gold armor. {
} plugin.messagePlayer(player, ChatColor.RED, "Player \"" + args[0] + "\" not found!");
else if (tier.equalsIgnoreCase("gold")) return true;
{ }
armorTier = ArmorTier.GOLD; tier = args[1];
if (player.hasPermission("armoredelytra.give.gold")) }
allowed = true;
if (tier.equalsIgnoreCase("leather"))
// Chain armor. {
} armorTier = ArmorTier.LEATHER;
else if (tier.equalsIgnoreCase("chain")) if (player.hasPermission("armoredelytra.give.leather"))
{ allowed = true;
armorTier = ArmorTier.CHAIN; }
if (player.hasPermission("armoredelytra.give.chain")) else if (tier.equalsIgnoreCase("gold"))
allowed = true; {
armorTier = ArmorTier.GOLD;
// Iron armor. if (player.hasPermission("armoredelytra.give.gold"))
} allowed = true;
else if (tier.equalsIgnoreCase("iron")) }
{ else if (tier.equalsIgnoreCase("chain"))
armorTier = ArmorTier.IRON; {
if (player.hasPermission("armoredelytra.give.iron")) armorTier = ArmorTier.CHAIN;
allowed = true; if (player.hasPermission("armoredelytra.give.chain"))
allowed = true;
// Diamond armor. }
} else if (tier.equalsIgnoreCase("iron"))
else if (tier.equalsIgnoreCase("diamond")) {
{ armorTier = ArmorTier.IRON;
armorTier = ArmorTier.DIAMOND; if (player.hasPermission("armoredelytra.give.iron"))
if (player.hasPermission("armoredelytra.give.diamond")) allowed = true;
allowed = true; }
} else if (tier.equalsIgnoreCase("diamond"))
else {
plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.UnsupportedTier")); armorTier = ArmorTier.DIAMOND;
if (player.hasPermission("armoredelytra.give.diamond"))
if (allowed) allowed = true;
{ }
plugin.elytraReceivedMessage(receiver, armorTier); else
newElytra = nbtEditor.addArmorNBTTags(new ItemStack(Material.ELYTRA, 1), armorTier, plugin.getConfigLoader().getBool("unbreakable")); plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.UnsupportedTier"));
plugin.giveArmoredElytraToPlayer(receiver, newElytra);
} if (allowed)
else {
plugin.messagePlayer(player, plugin.fillInArmorTierInStringNoColor(plugin.getMyMessages().getString("MESSAGES.UnsupportedTier"), armorTier)); plugin.elytraReceivedMessage(receiver, armorTier);
return true; newElytra = nbtEditor.addArmorNBTTags(new ItemStack(Material.ELYTRA, 1), armorTier, plugin.getConfigLoader().getBool("unbreakable"));
} plugin.giveArmoredElytraToPlayer(receiver, newElytra);
} }
} else
else plugin.messagePlayer(player, plugin.fillInArmorTierInStringNoColor(plugin.getMyMessages().getString("MESSAGES.UnsupportedTier"), armorTier));
{ return true;
if (plugin.getUninstallMode()) }
{ }
plugin.myLogger(Level.INFO, "Plugin in uninstall mode! New Armored Elytras are not allowed!"); else
return true; {
} if (plugin.getUninstallMode())
{
if (args.length == 2) plugin.myLogger(Level.INFO, "Plugin in uninstall mode! New Armored Elytras are not allowed!");
{ return true;
ItemStack newElytra = null; }
String tier = args[1];
if (Bukkit.getPlayer(args[0]) != null) if (args.length == 2)
{ {
player = Bukkit.getPlayer(args[0]); ItemStack newElytra = null;
ArmorTier armorTier = ArmorTier.NONE; String tier = args[1];
if (Bukkit.getPlayer(args[0]) != null)
if (tier.equalsIgnoreCase("leather")) {
armorTier = ArmorTier.LEATHER; player = Bukkit.getPlayer(args[0]);
else if (tier.equalsIgnoreCase("gold")) ArmorTier armorTier = ArmorTier.NONE;
armorTier = ArmorTier.GOLD;
else if (tier.equalsIgnoreCase("chain")) if (tier.equalsIgnoreCase("leather"))
armorTier = ArmorTier.CHAIN; armorTier = ArmorTier.LEATHER;
else if (tier.equalsIgnoreCase("iron")) else if (tier.equalsIgnoreCase("gold"))
armorTier = ArmorTier.IRON; armorTier = ArmorTier.GOLD;
else if (tier.equalsIgnoreCase("diamond")) else if (tier.equalsIgnoreCase("chain"))
armorTier = ArmorTier.DIAMOND; armorTier = ArmorTier.CHAIN;
// TODO: Catch user requesting non-existent tier. else if (tier.equalsIgnoreCase("iron"))
armorTier = ArmorTier.IRON;
plugin.elytraReceivedMessage(player, armorTier); else if (tier.equalsIgnoreCase("diamond"))
newElytra = nbtEditor.addArmorNBTTags(new ItemStack(Material.ELYTRA, 1), armorTier, plugin.getConfigLoader().getBool("unbreakable")); armorTier = ArmorTier.DIAMOND;
plugin.giveArmoredElytraToPlayer(player, newElytra); else
plugin.myLogger(Level.INFO, ("Giving an armored elytra of the " + ArmorTier.getArmor(armorTier) + " armor tier to player " + player.getName())); // TODO: Return a more informative message.
return true; return false;
}
else plugin.elytraReceivedMessage(player, armorTier);
{ newElytra = nbtEditor.addArmorNBTTags(new ItemStack(Material.ELYTRA, 1), armorTier, plugin.getConfigLoader().getBool("unbreakable"));
plugin.myLogger(Level.INFO, ("Player " + args[1] + " not found!")); plugin.giveArmoredElytraToPlayer(player, newElytra);
return true; plugin.myLogger(Level.INFO, ("Giving an armored elytra of the " + ArmorTier.getArmor(armorTier) + " armor tier to player " + player.getName()));
} return true;
} }
} else
return false; {
plugin.myLogger(Level.INFO, ("Player " + args[1] + " not found!"));
return true;
}
}
}
return false;
} }
} }

View File

@ -24,39 +24,39 @@ import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.nms.NBTEditor; import nl.pim16aap2.armoredElytra.nbtEditor.NBTEditor;
import nl.pim16aap2.armoredElytra.util.Action; import nl.pim16aap2.armoredElytra.util.Action;
import nl.pim16aap2.armoredElytra.util.AllowedToWearEnum; import nl.pim16aap2.armoredElytra.util.AllowedToWearEnum;
import nl.pim16aap2.armoredElytra.util.ArmorTier; import nl.pim16aap2.armoredElytra.util.ArmorTier;
import nl.pim16aap2.armoredElytra.util.Util; import nl.pim16aap2.armoredElytra.util.Util;
public class EventHandlers implements Listener public class EventHandlers implements Listener
{ {
private int DIAMONDS_TO_FULL; private final int DIAMONDS_TO_FULL;
private int LEATHER_TO_FULL; private final int LEATHER_TO_FULL;
private int GOLD_TO_FULL; private final int GOLD_TO_FULL;
private int IRON_TO_FULL; private final int IRON_TO_FULL;
private NBTEditor nbtEditor; private final NBTEditor nbtEditor;
private final ArmoredElytra plugin; private final ArmoredElytra plugin;
private List<String> allowedEnchantments; private final List<String> allowedEnchantments;
private boolean is1_9; private final boolean is1_9;
public EventHandlers(ArmoredElytra plugin, NBTEditor nbtEditor, boolean is1_9) public EventHandlers(ArmoredElytra plugin, NBTEditor nbtEditor, boolean is1_9)
{ {
this.plugin = plugin; this.plugin = plugin;
this.nbtEditor = nbtEditor; this.nbtEditor = nbtEditor;
this.is1_9 = is1_9; this.is1_9 = is1_9;
// Get the values of the config options. // Get the values of the config options.
this.allowedEnchantments = plugin.getConfigLoader().getStringList("allowedEnchantments"); allowedEnchantments = plugin.getConfigLoader().getStringList("allowedEnchantments");
this.LEATHER_TO_FULL = plugin.getConfigLoader().getInt("leatherRepair"); LEATHER_TO_FULL = plugin.getConfigLoader().getInt("leatherRepair");
this.GOLD_TO_FULL = plugin.getConfigLoader().getInt("goldRepair"); GOLD_TO_FULL = plugin.getConfigLoader().getInt("goldRepair");
this.IRON_TO_FULL = plugin.getConfigLoader().getInt("ironRepair"); IRON_TO_FULL = plugin.getConfigLoader().getInt("ironRepair");
this.DIAMONDS_TO_FULL = plugin.getConfigLoader().getInt("diamondsRepair"); DIAMONDS_TO_FULL = plugin.getConfigLoader().getInt("diamondsRepair");
} }
// Remove item from player's chestplate slot and puts it in their normal inventory. // Remove item from player's chestplate slot and puts it in their normal inventory.
private void unenquipChestPlayer(Player p) private void unenquipChestPlayer(Player p)
{ {
if (is1_9) if (is1_9)
p.getInventory().getChestplate().setType(Material.AIR); p.getInventory().getChestplate().setType(Material.AIR);
@ -67,7 +67,7 @@ public class EventHandlers implements Listener
p.updateInventory(); p.updateInventory();
} }
} }
// Clear the anvil's inventory (destroy all the items in all 3 slots (second slot is not emptied, when repairing you can safely give multiple items)). // Clear the anvil's inventory (destroy all the items in all 3 slots (second slot is not emptied, when repairing you can safely give multiple items)).
private void cleanAnvil(AnvilInventory anvilInventory) private void cleanAnvil(AnvilInventory anvilInventory)
{ {
@ -85,9 +85,9 @@ public class EventHandlers implements Listener
anvilInventory.getItem(2).setAmount(0); anvilInventory.getItem(2).setAmount(0);
} }
} }
// Check if the enchantment is allowed on elytras. // Check if the enchantment is allowed on elytras.
private boolean isAllowedEnchantment(Enchantment enchant) private boolean isAllowedEnchantment(Enchantment enchant)
{ {
for (String s : allowedEnchantments) for (String s : allowedEnchantments)
if (Enchantment.getByName(s) != null) if (Enchantment.getByName(s) != null)
@ -95,30 +95,30 @@ public class EventHandlers implements Listener
return true; return true;
return false; return false;
} }
// Combine 2 maps of enchantments (and remove any invalid ones). // Combine 2 maps of enchantments (and remove any invalid ones).
private Map<Enchantment, Integer> combineEnchantments(Map<Enchantment, Integer> enchantments0, Map<Enchantment, Integer> enchantments1) private Map<Enchantment, Integer> combineEnchantments(Map<Enchantment, Integer> enchantments0, Map<Enchantment, Integer> enchantments1)
{ {
enchantments0 = fixEnchantments(enchantments0); enchantments0 = fixEnchantments(enchantments0);
Map<Enchantment, Integer> combined = new HashMap<Enchantment, Integer>(fixEnchantments(enchantments0)); Map<Enchantment, Integer> combined = new HashMap<>(fixEnchantments(enchantments0));
// If the second set of enchantments is null, the combined enchantments are just the first enchantments. // If the second set of enchantments is null, the combined enchantments are just the first enchantments.
if (enchantments1 == null) if (enchantments1 == null)
return combined; return combined;
enchantments1 = fixEnchantments(enchantments1); enchantments1 = fixEnchantments(enchantments1);
// Loop through the enchantments of item1. // Loop through the enchantments of item1.
for (Map.Entry<Enchantment, Integer > entry : enchantments1.entrySet()) for (Map.Entry<Enchantment, Integer > entry : enchantments1.entrySet())
{ {
Integer enchantLevel = enchantments0.get(entry.getKey()); Integer enchantLevel = enchantments0.get(entry.getKey());
if (enchantLevel != null) if (enchantLevel != null)
{ {
if (entry.getValue() == enchantLevel && entry.getValue() < entry.getKey().getMaxLevel()) if (entry.getValue() == enchantLevel && entry.getValue() < entry.getKey().getMaxLevel())
enchantLevel = entry.getValue() + 1; enchantLevel = entry.getValue() + 1;
else if (entry.getValue() > enchantLevel) else if (entry.getValue() > enchantLevel)
enchantLevel = entry.getValue(); enchantLevel = entry.getValue();
// If the enchantment level has changed, // If the enchantment level has changed,
if (enchantLevel != enchantments0.get(entry.getKey())) if (enchantLevel != enchantments0.get(entry.getKey()))
{ {
combined.remove(entry.getKey()); combined.remove(entry.getKey());
@ -128,17 +128,16 @@ public class EventHandlers implements Listener
else if (enchantLevel == null) else if (enchantLevel == null)
combined.put(entry.getKey(), entry.getValue()); combined.put(entry.getKey(), entry.getValue());
} }
// Get the protection enchantment rating for both enchantment sets. // Get the protection enchantment rating for both enchantment sets.
int protVal0 = Util.getProtectionEnchantmentsVal(enchantments0); int protVal0 = Util.getProtectionEnchantmentsVal(enchantments0);
int protVal1 = Util.getProtectionEnchantmentsVal(enchantments1); int protVal1 = Util.getProtectionEnchantmentsVal(enchantments1);
// If they have different protection enchantments, keep enchantment1's enchantments // If they have different protection enchantments, keep enchantment1's enchantments
// And remove the protection enchantment from enchantments0. Yes, this system only works // And remove the protection enchantment from enchantments0. Yes, this system only works
// If there is 1 protection enchantment on // If there is 1 protection enchantment on
if (protVal0 != 0 && protVal1 != 0 && protVal0 != protVal1) if (protVal0 != 0 && protVal1 != 0 && protVal0 != protVal1)
{ switch(protVal0)
switch(protVal0)
{ {
case 1: case 1:
combined.remove(Enchantment.PROTECTION_ENVIRONMENTAL); combined.remove(Enchantment.PROTECTION_ENVIRONMENTAL);
@ -156,13 +155,12 @@ public class EventHandlers implements Listener
combined.remove(Enchantment.PROTECTION_PROJECTILE); combined.remove(Enchantment.PROTECTION_PROJECTILE);
break; break;
} }
}
return combined; return combined;
} }
// Repair an Armored Elytra // Repair an Armored Elytra
private short repairItem(short curDur, ItemStack repairItem) private short repairItem(short curDur, ItemStack repairItem)
{ {
// Get the multiplier for the repair items. // Get the multiplier for the repair items.
double mult = 0.01; double mult = 0.01;
if ( repairItem.getType() == Material.LEATHER) if ( repairItem.getType() == Material.LEATHER)
@ -183,9 +181,9 @@ public class EventHandlers implements Listener
} }
// Remove any disallowed enchantments in the map. // Remove any disallowed enchantments in the map.
private Map<Enchantment, Integer> fixEnchantments(Map<Enchantment, Integer> enchantments) private Map<Enchantment, Integer> fixEnchantments(Map<Enchantment, Integer> enchantments)
{ {
Map<Enchantment, Integer> ret = new HashMap<Enchantment, Integer>(enchantments); Map<Enchantment, Integer> ret = new HashMap<>(enchantments);
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet())
if (!isAllowedEnchantment(entry.getKey())) if (!isAllowedEnchantment(entry.getKey()))
ret.remove(entry.getKey()); ret.remove(entry.getKey());
@ -193,7 +191,7 @@ public class EventHandlers implements Listener
} }
// Verify there aren't any disallowed enchantments in the map. // Verify there aren't any disallowed enchantments in the map.
private int verifyEnchantments(Map<Enchantment, Integer> enchantments) private int verifyEnchantments(Map<Enchantment, Integer> enchantments)
{ {
int ret = 0; int ret = 0;
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet())
@ -201,15 +199,15 @@ public class EventHandlers implements Listener
++ret; ++ret;
return ret; return ret;
} }
/* /*
* Valid inputs: * Valid inputs:
* - Elytra (armored or not) + chestplate -> Create Armored Elytra * - Elytra (armored or not) + chestplate -> Create Armored Elytra
* - Elytra (armored) + enchanted book -> Enchant * - Elytra (armored) + enchanted book -> Enchant
* - Elytra (armored) + its repair item -> Repair * - Elytra (armored) + its repair item -> Repair
* - Elytra (armored) + other elytra (armored) -> Combine (Enchant + Repair) * - Elytra (armored) + other elytra (armored) -> Combine (Enchant + Repair)
* ! Elytra (armored, !leather) + leather -> Block * ! Elytra (armored, !leather) + leather -> Block
* *
* Ignoring: * Ignoring:
* - Elytra (not armored) + !chestplate -> None * - Elytra (not armored) + !chestplate -> None
* - * + * -> None * - * + * -> None
@ -218,7 +216,7 @@ public class EventHandlers implements Listener
{ {
if (itemOne == null || itemTwo == null) if (itemOne == null || itemTwo == null)
return Action.NONE; return Action.NONE;
// If itemTwo is the elytra, while itemOne isn't, switch itemOne and itemTwo. // If itemTwo is the elytra, while itemOne isn't, switch itemOne and itemTwo.
if (itemTwo.getType() == Material.ELYTRA && itemOne.getType() != Material.ELYTRA) if (itemTwo.getType() == Material.ELYTRA && itemOne.getType() != Material.ELYTRA)
{ {
@ -226,32 +224,32 @@ public class EventHandlers implements Listener
itemOne = itemTwo; itemOne = itemTwo;
itemTwo = tmp; itemTwo = tmp;
} }
if (itemOne.getType() != Material.ELYTRA) if (itemOne.getType() != Material.ELYTRA)
return Action.NONE; return Action.NONE;
Material matTwo = itemTwo.getType(); Material matTwo = itemTwo.getType();
// If the elytra is to be combined with chest armor... // If the elytra is to be combined with chest armor...
if (Util.isChestPlate(matTwo)) if (Util.isChestPlate(matTwo))
return Action.CREATE; return Action.CREATE;
ArmorTier tier = nbtEditor.getArmorTier(itemOne); ArmorTier tier = nbtEditor.getArmorTier(itemOne);
if (tier != ArmorTier.NONE) if (tier != ArmorTier.NONE)
{ {
// If the armored elytra is to be enchanted using an enchanted book... // If the armored elytra is to be enchanted using an enchanted book...
if (matTwo == Material.ENCHANTED_BOOK) if (matTwo == Material.ENCHANTED_BOOK)
return Action.ENCHANT; return Action.ENCHANT;
// If the armored elytra is to be repaired using its repair item... // If the armored elytra is to be repaired using its repair item...
if (ArmorTier.getRepairItem(tier) == matTwo) if (ArmorTier.getRepairItem(tier) == matTwo)
return Action.REPAIR; return Action.REPAIR;
// If the armored elytra is to be combined with another armored elytra of the same tier... // If the armored elytra is to be combined with another armored elytra of the same tier...
if (nbtEditor.getArmorTier(itemTwo) == tier) if (nbtEditor.getArmorTier(itemTwo) == tier)
return Action.COMBINE; return Action.COMBINE;
// If the armored elytra is not of the leather tier, but itemTwo is leather, // If the armored elytra is not of the leather tier, but itemTwo is leather,
// Pick the block action, as that would repair the elytra by default (vanilla). // Pick the block action, as that would repair the elytra by default (vanilla).
// Also block Armored Elytra + Elytra. // Also block Armored Elytra + Elytra.
@ -260,7 +258,7 @@ public class EventHandlers implements Listener
} }
return Action.NONE; return Action.NONE;
} }
// Handle all anvil related stuff for this plugin. // Handle all anvil related stuff for this plugin.
@EventHandler @EventHandler
private void onAnvilInventoryOpen(PrepareAnvilEvent event) private void onAnvilInventoryOpen(PrepareAnvilEvent event)
@ -269,9 +267,8 @@ public class EventHandlers implements Listener
ItemStack itemA = event.getInventory().getItem(0); ItemStack itemA = event.getInventory().getItem(0);
ItemStack itemB = event.getInventory().getItem(1); ItemStack itemB = event.getInventory().getItem(1);
ItemStack result = null; ItemStack result = null;
if (itemA != null && itemB != null) if (itemA != null && itemB != null)
{
// If itemB is the elytra, while itemA isn't, switch itemA and itemB. // If itemB is the elytra, while itemA isn't, switch itemA and itemB.
if (itemB.getType() == Material.ELYTRA && itemA.getType() != Material.ELYTRA) if (itemB.getType() == Material.ELYTRA && itemA.getType() != Material.ELYTRA)
{ {
@ -280,10 +277,9 @@ public class EventHandlers implements Listener
itemB = result; itemB = result;
result = null; result = null;
} }
}
// Check if there are items in both input slots. // Check if there are items in both input slots.
if (itemA != null && itemB != null) if (itemA != null && itemB != null)
{ {
Action action = isValidInput(itemA, itemB); Action action = isValidInput(itemA, itemB);
ArmorTier newTier = ArmorTier.NONE; ArmorTier newTier = ArmorTier.NONE;
@ -291,7 +287,7 @@ public class EventHandlers implements Listener
short durability = 0; short durability = 0;
Map<Enchantment, Integer> enchantments = itemA.getEnchantments(); Map<Enchantment, Integer> enchantments = itemA.getEnchantments();
enchantments = fixEnchantments(enchantments); enchantments = fixEnchantments(enchantments);
switch (action) switch (action)
{ {
case REPAIR: case REPAIR:
@ -326,40 +322,40 @@ public class EventHandlers implements Listener
case NONE: case NONE:
return; return;
} }
if (Util.playerHasCraftPerm(player, newTier)) if (Util.playerHasCraftPerm(player, newTier))
{ {
result = new ItemStack(Material.ELYTRA, 1); result = new ItemStack(Material.ELYTRA, 1);
if (enchantments != null) if (enchantments != null)
result.addUnsafeEnchantments(enchantments); result.addUnsafeEnchantments(enchantments);
result.setDurability(durability); result.setDurability(durability);
result = nbtEditor.addArmorNBTTags(result, newTier, plugin.getConfigLoader().getBool("unbreakable")); result = nbtEditor.addArmorNBTTags(result, newTier, plugin.getConfigLoader().getBool("unbreakable"));
event.setResult(result); event.setResult(result);
} }
} }
// Check if either itemA or itemB is unoccupied. // Check if either itemA or itemB is unoccupied.
if ((itemA == null || itemB == null) && nbtEditor.getArmorTier(event.getInventory().getItem(2)) != ArmorTier.NONE) if ((itemA == null || itemB == null) && nbtEditor.getArmorTier(event.getInventory().getItem(2)) != ArmorTier.NONE)
// If Item2 is occupied despite itemA or itemB not being occupied. (only for armored elytra)/ // If Item2 is occupied despite itemA or itemB not being occupied. (only for armored elytra)/
event.setResult(null); event.setResult(null);
player.updateInventory(); player.updateInventory();
} }
// Let the player take items out of the anvil. // Let the player take items out of the anvil.
@EventHandler @EventHandler
public void onInventoryClick(InventoryClickEvent e) public void onInventoryClick(InventoryClickEvent e)
{ {
if (!(e.getWhoClicked() instanceof Player)) if (!(e.getWhoClicked() instanceof Player))
return; return;
// Check if the event was a player who interacted with an anvil. // Check if the event was a player who interacted with an anvil.
Player player = (Player) e.getWhoClicked(); Player player = (Player) e.getWhoClicked();
if (e.getView().getType() != InventoryType.ANVIL) if (e.getView().getType() != InventoryType.ANVIL)
return; return;
AnvilInventory anvilInventory; AnvilInventory anvilInventory;
// Try to cast inventory being used in the event to an anvil inventory. // Try to cast inventory being used in the event to an anvil inventory.
// This will throw a ClassCastException when a CraftInventoryCustom is used. // This will throw a ClassCastException when a CraftInventoryCustom is used.
try try
@ -372,36 +368,36 @@ public class EventHandlers implements Listener
plugin.debugMsg(Level.WARNING, "Could not cast inventory to anvilInventory for player " + player.getName() + "! Armored Elytras cannot be crafted!"); plugin.debugMsg(Level.WARNING, "Could not cast inventory to anvilInventory for player " + player.getName() + "! Armored Elytras cannot be crafted!");
return; return;
} }
int slot = e.getRawSlot(); int slot = e.getRawSlot();
if (slot == 2 && anvilInventory.getItem(0) != null && anvilInventory.getItem(1) != null && anvilInventory.getItem(2) != null) if (slot == 2 && anvilInventory.getItem(0) != null && anvilInventory.getItem(1) != null && anvilInventory.getItem(2) != null)
{ {
ArmorTier armortier = nbtEditor.getArmorTier(anvilInventory.getItem(2)); ArmorTier armortier = nbtEditor.getArmorTier(anvilInventory.getItem(2));
// If there's an armored elytra in the final slot... // If there's an armored elytra in the final slot...
if (armortier != ArmorTier.NONE && Util.playerHasCraftPerm(player, armortier)) if (armortier != ArmorTier.NONE && Util.playerHasCraftPerm(player, armortier))
{ {
// Create a new armored elytra and give that one to the player instead of the result. // Create a new armored elytra and give that one to the player instead of the result.
// This is done because after putting item0 in AFTER item1, the first letter of the color code shows up, this gets rid of that problem. // This is done because after putting item0 in AFTER item1, the first letter of the color code shows up, this gets rid of that problem.
ItemStack result = nbtEditor.addArmorNBTTags(anvilInventory.getItem(2), armortier, plugin.getConfigLoader().getBool("unbreakable")); ItemStack result = nbtEditor.addArmorNBTTags(anvilInventory.getItem(2), armortier, plugin.getConfigLoader().getBool("unbreakable"));
// Give the result to the player and clear the anvil's inventory. // Give the result to the player and clear the anvil's inventory.
if (e.isShiftClick()) if (e.isShiftClick())
{ {
// If the player's inventory is full, don't do anything. // If the player's inventory is full, don't do anything.
if (player.getInventory().firstEmpty() == -1) if (player.getInventory().firstEmpty() == -1)
return; return;
player.getInventory().addItem(result); player.getInventory().addItem(result);
} }
else else
player.setItemOnCursor(result); player.setItemOnCursor(result);
// Clean the anvil's inventory after transferring the items. // Clean the anvil's inventory after transferring the items.
this.cleanAnvil(anvilInventory); cleanAnvil(anvilInventory);
player.updateInventory(); player.updateInventory();
return; return;
} }
} }
} }
// Make sure the player has the correct permission and that the item is not broken. // Make sure the player has the correct permission and that the item is not broken.
private AllowedToWearEnum isAllowedToWear(ItemStack elytra, Player player, ArmorTier armorTier) private AllowedToWearEnum isAllowedToWear(ItemStack elytra, Player player, ArmorTier armorTier)
{ {
@ -411,33 +407,33 @@ public class EventHandlers implements Listener
return AllowedToWearEnum.NOPERMISSION; return AllowedToWearEnum.NOPERMISSION;
return AllowedToWearEnum.ALLOWED; return AllowedToWearEnum.ALLOWED;
} }
// Check if the player tries to equip armor by richt clicking it. // Check if the player tries to equip armor by richt clicking it.
@EventHandler @EventHandler
public void onRightClick(PlayerInteractEvent event) public void onRightClick(PlayerInteractEvent event)
{ {
if (!event.getAction().equals(org.bukkit.event.block.Action.RIGHT_CLICK_AIR) && if (!event.getAction().equals(org.bukkit.event.block.Action.RIGHT_CLICK_AIR) &&
!event.getAction().equals(org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK)) !event.getAction().equals(org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK))
return; return;
ItemStack item = event.getItem(); ItemStack item = event.getItem();
if (item == null) if (item == null)
return; return;
Player player = event.getPlayer(); Player player = event.getPlayer();
if (item.getType() == Material.ELYTRA) if (item.getType() == Material.ELYTRA)
{ {
ArmorTier armorTier = nbtEditor.getArmorTier(item); ArmorTier armorTier = nbtEditor.getArmorTier(item);
if (nbtEditor.getArmorTier(item) == ArmorTier.NONE) if (nbtEditor.getArmorTier(item) == ArmorTier.NONE)
return; return;
AllowedToWearEnum allowed = this.isAllowedToWear(item, player, armorTier); AllowedToWearEnum allowed = isAllowedToWear(item, player, armorTier);
if (allowed == AllowedToWearEnum.BROKEN) if (allowed == AllowedToWearEnum.BROKEN)
{ {
plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.RepairNeeded")); plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.RepairNeeded"));
event.setCancelled(true); event.setCancelled(true);
player.updateInventory(); player.updateInventory();
} }
else if (allowed == AllowedToWearEnum.NOPERMISSION) else if (allowed == AllowedToWearEnum.NOPERMISSION)
{ {
plugin.usageDeniedMessage(player, armorTier); plugin.usageDeniedMessage(player, armorTier);
@ -446,7 +442,7 @@ public class EventHandlers implements Listener
} }
} }
} }
// Player closes their inventory. Also checks for whether they are allowed to wear the armored elytra they are wearing. // Player closes their inventory. Also checks for whether they are allowed to wear the armored elytra they are wearing.
// This is done again here because there are ways to bypass permission check when equipping. // This is done again here because there are ways to bypass permission check when equipping.
@EventHandler @EventHandler
@ -454,7 +450,7 @@ public class EventHandlers implements Listener
{ {
verifyArmorInChestSlot((Player) e.getPlayer()); verifyArmorInChestSlot((Player) e.getPlayer());
} }
// Check if the player is allowed to wear the armored elytra based on their permissions. // Check if the player is allowed to wear the armored elytra based on their permissions.
private void verifyArmorInChestSlot(Player player) private void verifyArmorInChestSlot(Player player)
{ {
@ -467,23 +463,23 @@ public class EventHandlers implements Listener
// If that chestplate is an (armored) elytra. // If that chestplate is an (armored) elytra.
if (armorTier == ArmorTier.NONE) if (armorTier == ArmorTier.NONE)
return; return;
AllowedToWearEnum allowed = this.isAllowedToWear(chestplate, player, armorTier); AllowedToWearEnum allowed = isAllowedToWear(chestplate, player, armorTier);
if (allowed == AllowedToWearEnum.BROKEN) if (allowed == AllowedToWearEnum.BROKEN)
{ {
plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.RepairNeeded")); plugin.messagePlayer(player, plugin.getMyMessages().getString("MESSAGES.RepairNeeded"));
this.unenquipChestPlayer(player); unenquipChestPlayer(player);
} }
else if (allowed == AllowedToWearEnum.NOPERMISSION) else if (allowed == AllowedToWearEnum.NOPERMISSION)
{ {
plugin.usageDeniedMessage(player, armorTier); plugin.usageDeniedMessage(player, armorTier);
this.unenquipChestPlayer(player); unenquipChestPlayer(player);
} }
} }
// Because the armored elytra doesn't actually give any armor, the damage received by players wearing an armored elytra is calculated here. // Because the armored elytra doesn't actually give any armor, the damage received by players wearing an armored elytra is calculated here.
@EventHandler(ignoreCancelled = true) @EventHandler(ignoreCancelled = true)
public void onPlayerDamage(EntityDamageEvent e) public void onPlayerDamage(EntityDamageEvent e)
{ {
if(!(e.getEntity() instanceof Player)) if(!(e.getEntity() instanceof Player))
return; return;
@ -492,25 +488,25 @@ public class EventHandlers implements Listener
// If the player didn't die from the damage. // If the player didn't die from the damage.
if ((p.getHealth() - e.getFinalDamage()) > 0) if ((p.getHealth() - e.getFinalDamage()) > 0)
{ {
if (p.getInventory().getChestplate() == null) if (p.getInventory().getChestplate() == null)
return; return;
if (nbtEditor.getArmorTier(p.getInventory().getChestplate()) == ArmorTier.NONE) if (nbtEditor.getArmorTier(p.getInventory().getChestplate()) == ArmorTier.NONE)
return; return;
ItemStack elytra = p.getInventory().getChestplate(); ItemStack elytra = p.getInventory().getChestplate();
DamageCause cause = e.getCause(); DamageCause cause = e.getCause();
// The elytra doesn't receive any damage for these causes: // The elytra doesn't receive any damage for these causes:
if (cause != DamageCause.DROWNING && cause != DamageCause.STARVATION && cause != DamageCause.SUFFOCATION && if (cause != DamageCause.DROWNING && cause != DamageCause.STARVATION && cause != DamageCause.SUFFOCATION &&
cause != DamageCause.SUICIDE && cause != DamageCause.FLY_INTO_WALL && cause != DamageCause.POISON) cause != DamageCause.SUICIDE && cause != DamageCause.FLY_INTO_WALL && cause != DamageCause.POISON)
{ {
int durability = p.getInventory().getChestplate().getDurability(); int durability = p.getInventory().getChestplate().getDurability();
int maxDurability = p.getInventory().getChestplate().getType().getMaxDurability(); int maxDurability = p.getInventory().getChestplate().getType().getMaxDurability();
int newDurability = (int) (durability + ((int) (e.getDamage() / 4) > 1 ? (int) (e.getDamage() / 4) : 1)); int newDurability = durability + ((int) (e.getDamage() / 4) > 1 ? (int) (e.getDamage() / 4) : 1);
// If the elytra has the durability enchantment, we calculate the durability loss ourselves. // If the elytra has the durability enchantment, we calculate the durability loss ourselves.
if (p.getInventory().getChestplate().containsEnchantment(Enchantment.DURABILITY)) if (p.getInventory().getChestplate().containsEnchantment(Enchantment.DURABILITY))
{ {
// Get a random int between 0 and 100 to use in deciding if the durability enchantment will take effect. // Get a random int between 0 and 100 to use in deciding if the durability enchantment will take effect.
Random r = new Random(); Random r = new Random();
@ -519,36 +515,36 @@ public class EventHandlers implements Listener
int durabilityDelta = (100 / (enchantLevel + 1)) < randomInt ? 0 : 1; int durabilityDelta = (100 / (enchantLevel + 1)) < randomInt ? 0 : 1;
// If the durability equals/exceeds maxDurability, it's broken (0 = full item durability). // If the durability equals/exceeds maxDurability, it's broken (0 = full item durability).
if (durability >= maxDurability) if (durability >= maxDurability)
this.unenquipChestPlayer(p); unenquipChestPlayer(p);
else else
newDurability = durability + durabilityDelta; newDurability = durability + durabilityDelta;
} }
// If the item should be broken, make sure it really is broken and unequip it. // If the item should be broken, make sure it really is broken and unequip it.
if (newDurability >= maxDurability) if (newDurability >= maxDurability)
{ {
newDurability = maxDurability; newDurability = maxDurability;
this.unenquipChestPlayer(p); unenquipChestPlayer(p);
} }
elytra.setDurability((short) (newDurability)); elytra.setDurability((short) (newDurability));
} }
} }
} }
// Check if the player is trying to equip a broken elytra (and prevent that). // Check if the player is trying to equip a broken elytra (and prevent that).
@EventHandler @EventHandler
public void playerEquipsArmor(InventoryClickEvent e) public void playerEquipsArmor(InventoryClickEvent e)
{ {
if (!(e.getWhoClicked() instanceof Player)) if (!(e.getWhoClicked() instanceof Player))
return; return;
Player player = (Player) e.getWhoClicked(); Player player = (Player) e.getWhoClicked();
new BukkitRunnable() new BukkitRunnable()
{ {
@Override @Override
public void run() public void run()
{ {
verifyArmorInChestSlot(player); verifyArmorInChestSlot(player);
} }
}.runTaskLater(this.plugin, 1); }.runTaskLater(plugin, 1);
} }
} }

View File

@ -5,22 +5,22 @@ import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener; import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerItemDamageEvent; import org.bukkit.event.player.PlayerItemDamageEvent;
import nl.pim16aap2.armoredElytra.nms.NBTEditor; import nl.pim16aap2.armoredElytra.nbtEditor.NBTEditor;
import nl.pim16aap2.armoredElytra.util.ArmorTier; import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class FlyDurabilityHandler implements Listener public class FlyDurabilityHandler implements Listener
{ {
private NBTEditor nbtEditor; private final NBTEditor nbtEditor;
public FlyDurabilityHandler(NBTEditor nbtEditor) public FlyDurabilityHandler(NBTEditor nbtEditor)
{ {
this.nbtEditor = nbtEditor; this.nbtEditor = nbtEditor;
} }
// Do not decrease elytra durability while flying. // Do not decrease elytra durability while flying. This also cancels durability decrease when
// This also cancels durability decrease when it should while flying, but that shouldn't really matter. // it should (i.e. getting hit) while flying, but I don't really care.
@EventHandler @EventHandler
public void onItemDamage(PlayerItemDamageEvent e) public void onItemDamage(PlayerItemDamageEvent e)
{ {
if (e.getItem().getType() == Material.ELYTRA) if (e.getItem().getType() == Material.ELYTRA)
if (nbtEditor.getArmorTier(e.getItem()) != ArmorTier.NONE) if (nbtEditor.getArmorTier(e.getItem()) != ArmorTier.NONE)

View File

@ -9,33 +9,30 @@ import org.bukkit.scheduler.BukkitRunnable;
import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.ArmoredElytra;
public class LoginHandler implements Listener public class LoginHandler implements Listener
{ {
private final ArmoredElytra plugin;
ArmoredElytra plugin; private final String message;
String message;
public LoginHandler(ArmoredElytra plugin, String message) public LoginHandler(ArmoredElytra plugin, String message)
{ {
this.plugin = plugin; this.plugin = plugin;
this.message = message; this.message = message;
} }
@EventHandler @EventHandler
public void onLogin(PlayerLoginEvent event) public void onLogin(PlayerLoginEvent event)
{ {
Player player = event.getPlayer(); Player player = event.getPlayer();
if (player.hasPermission("armoredElytra.admin")) if (player.hasPermission("armoredElytra.admin"))
{
// Slight delay so the player actually receives the message; // Slight delay so the player actually receives the message;
new BukkitRunnable() new BukkitRunnable()
{ {
@Override @Override
public void run() public void run()
{ {
plugin.messagePlayer(player, ChatColor.AQUA, message); plugin.messagePlayer(player, ChatColor.AQUA, message);
} }
}.runTaskLater(this.plugin, 10); }.runTaskLater(plugin, 10);
}
} }
} }

View File

@ -13,13 +13,13 @@ import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.scheduler.BukkitRunnable;
import nl.pim16aap2.armoredElytra.ArmoredElytra; import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.nms.NBTEditor; import nl.pim16aap2.armoredElytra.nbtEditor.NBTEditor;
import nl.pim16aap2.armoredElytra.util.ArmorTier; import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class Uninstaller implements Listener public class Uninstaller implements Listener
{ {
ArmoredElytra plugin; private final ArmoredElytra plugin;
NBTEditor nbtEditor; private final NBTEditor nbtEditor;
public Uninstaller(ArmoredElytra plugin, NBTEditor nbtEditor) public Uninstaller(ArmoredElytra plugin, NBTEditor nbtEditor)
{ {
@ -45,7 +45,6 @@ public class Uninstaller implements Listener
public void onChestOpen(InventoryOpenEvent event) public void onChestOpen(InventoryOpenEvent event)
{ {
if (event.getInventory().getType().equals(InventoryType.CHEST)) if (event.getInventory().getType().equals(InventoryType.CHEST))
{
// Slight delay so the inventory has time to get loaded. // Slight delay so the inventory has time to get loaded.
new BukkitRunnable() new BukkitRunnable()
{ {
@ -57,8 +56,7 @@ public class Uninstaller implements Listener
if (removed != 0) if (removed != 0)
plugin.messagePlayer((Player) (event.getPlayer()), ChatColor.RED, "Removed " + removed + " armored elytras from your chest!"); plugin.messagePlayer((Player) (event.getPlayer()), ChatColor.RED, "Removed " + removed + " armored elytras from your chest!");
} }
}.runTaskLater(this.plugin, 20); }.runTaskLater(plugin, 20);
}
} }
@EventHandler @EventHandler
@ -73,8 +71,8 @@ public class Uninstaller implements Listener
Inventory inv = event.getPlayer().getInventory(); Inventory inv = event.getPlayer().getInventory();
int removed = removeArmoredElytras(inv); int removed = removeArmoredElytras(inv);
if (removed != 0) if (removed != 0)
plugin.messagePlayer((Player) (event.getPlayer()), ChatColor.RED, "Removed " + removed + " armored elytras from your inventory!"); plugin.messagePlayer(event.getPlayer(), ChatColor.RED, "Removed " + removed + " armored elytras from your inventory!");
} }
}.runTaskLater(this.plugin, 20); }.runTaskLater(plugin, 20);
} }
} }

View File

@ -0,0 +1,6 @@
package nl.pim16aap2.armoredElytra.nbtEditor;
public interface GetArmorValue
{
public int armorValueFromNBTString(String nbtString);
}

View File

@ -0,0 +1,34 @@
package nl.pim16aap2.armoredElytra.nbtEditor;
import java.util.logging.Level;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
public class GetArmorValueNew implements GetArmorValue
{
private final ArmoredElytra plugin;
public GetArmorValueNew(ArmoredElytra plugin)
{
this.plugin = plugin;
}
@Override
public int armorValueFromNBTString(String nbtString)
{
int pos = nbtString.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
if (pos > 0)
try
{
String stringAtPos = nbtString.substring(pos - 4, pos - 1);
return (int) Double.parseDouble(stringAtPos);
}
catch (Exception e)
{
plugin.myLogger(Level.INFO, "Failed to obtain armor value from NBT!");
return 0;
}
else
return 0;
}
}

View File

@ -0,0 +1,28 @@
package nl.pim16aap2.armoredElytra.nbtEditor;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
public class GetArmorValueOld implements GetArmorValue
{
private final ArmoredElytra plugin;
public GetArmorValueOld(ArmoredElytra plugin)
{
this.plugin = plugin;
}
@Override
public int armorValueFromNBTString(String nbtString)
{
int pos = nbtString.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
if (pos > 0)
{
// If so, get the value of the generic.armor attribute.
pos--;
String stringAtPos = nbtString.substring(pos, pos + 1);
return Integer.parseInt(stringAtPos);
}
else
return 0;
}
}

View File

@ -0,0 +1,232 @@
package nl.pim16aap2.armoredElytra.nbtEditor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class NBTEditor
{
private final ArmoredElytra plugin;
private final String NMSbase;
private final String CraftBase;
private Method asNMSCopy;
private Method asBukkitCopy;
private Class<?> NMSItemStack;
private Class<?> CraftItemStack;
private Class<?> NBTTagCompound;
private Class<?> NBTTagList;
private Class<?> NBTBase;
private Class<?> NBTTagString;
private Class<?> NBTTagByte;
private Class<?> NBTTagInt;
private Method hasTag;
private Method getTag;
private Method addCompound;
private Method setTag;
private Method setCompoundByte;
private Method setCompoundTagList;
private Constructor<?> NBTTagStringCtor;
private Constructor<?> NBTTagByteCtor;
private Constructor<?> NBTTagIntCtor;
private boolean success = false;
private GetArmorValue getArmorValue;
public NBTEditor(ArmoredElytra plugin)
{
this.plugin = plugin;
final String versionString = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
NMSbase = "net.minecraft.server." + versionString + ".";
CraftBase = "org.bukkit.craftbukkit." + versionString + ".";
constructNMSClasses();
getTagReadingMethod();
}
private void getTagReadingMethod()
{
if (!success)
return;
String version;
try
{
version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
}
catch (final ArrayIndexOutOfBoundsException useAVersionMentionedInTheDescriptionPleaseException)
{
success = false;
return;
}
// Old versions use the old format. It is assumed here that all versions from 1.13.2 on will use the
// new format. Might want to put this in a nice interface instead of an ugly boolean.
// Spigot's 1.13.1 uses the old format, but 1.13.2 uses the new format. They share the same version number though.
if (version.equals("v1_9_R1" ) || version.equals("v1_9_R2" ) || version.equals("v1_10_R1") ||
version.equals("v1_11_R1") || version.equals("v1_12_R1") || version.equals("v1_13_R1") ||
version.equals("v1_13_R2") && Bukkit.getVersion().split(" ")[2].equals("1.13.1)"))
getArmorValue = new GetArmorValueOld(plugin);
else
getArmorValue = new GetArmorValueNew(plugin);
}
public boolean succes()
{
return success;
}
private void constructNMSClasses()
{
try
{
NMSItemStack = getNMSClass("ItemStack");
hasTag = NMSItemStack.getMethod("hasTag");
getTag = NMSItemStack.getMethod("getTag");
CraftItemStack = getCraftClass("inventory.CraftItemStack");
asNMSCopy = CraftItemStack.getMethod("asNMSCopy", ItemStack.class);
asBukkitCopy = CraftItemStack.getMethod("asBukkitCopy", NMSItemStack);
NBTBase = getNMSClass("NBTBase");
NBTTagString = getNMSClass("NBTTagString");
NBTTagStringCtor = NBTTagString.getConstructor(String.class);
NBTTagByte = getNMSClass("NBTTagByte");
NBTTagByteCtor = NBTTagByte.getConstructor(byte.class);
NBTTagInt = getNMSClass("NBTTagInt");
NBTTagIntCtor = NBTTagInt.getConstructor(int.class);
NBTTagCompound = getNMSClass("NBTTagCompound");
setTag = NBTTagCompound.getMethod("set", String.class, NBTBase);
NBTTagList = getNMSClass("NBTTagList");
addCompound = NBTTagList.getMethod("add", NBTBase);
setCompoundTagList = NBTTagCompound.getMethod("set", String.class, NBTBase);
setCompoundByte = NBTTagCompound.getMethod("set", String.class, NBTBase);
success = true;
}
catch (NoSuchMethodException | SecurityException | ClassNotFoundException e)
{
e.printStackTrace();
success = false;
}
}
// Add armor to the supplied item, based on the armorTier.
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable)
{
try
{
ItemMeta itemmeta = item.getItemMeta();
int armorProtection = ArmorTier.getArmor(armorTier);
int armorToughness = ArmorTier.getToughness(armorTier);
itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier));
if (plugin.getElytraLore() != null)
itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier)));
item.setItemMeta(itemmeta);
Object nmsStack = asNMSCopy.invoke(null, item);
Object compound = ((boolean) hasTag.invoke(nmsStack) ? getTag.invoke(nmsStack) : NBTTagCompound.newInstance());
Object modifiers = NBTTagList.newInstance();
Object armor = NBTTagCompound.newInstance();
setTag.invoke (armor, "AttributeName", NBTTagStringCtor.newInstance("generic.armor"));
setTag.invoke (armor, "Name", NBTTagStringCtor.newInstance("generic.armor"));
setTag.invoke (armor, "Amount", NBTTagIntCtor.newInstance(armorProtection));
setTag.invoke (armor, "Operation", NBTTagIntCtor.newInstance(0));
setTag.invoke (armor, "UUIDLeast", NBTTagIntCtor.newInstance(894654));
setTag.invoke (armor, "UUIDMost", NBTTagIntCtor.newInstance(2872));
setTag.invoke (armor, "Slot", NBTTagStringCtor.newInstance("chest"));
addCompound.invoke(modifiers, armor);
Object armorTough = NBTTagCompound.newInstance();
setTag.invoke (armorTough, "AttributeName", NBTTagStringCtor.newInstance("generic.armorToughness"));
setTag.invoke (armorTough, "Name", NBTTagStringCtor.newInstance("generic.armorToughness"));
setTag.invoke (armorTough, "Amount", NBTTagIntCtor.newInstance(armorToughness));
setTag.invoke (armorTough, "Operation", NBTTagIntCtor.newInstance(0));
setTag.invoke (armorTough, "UUIDLeast", NBTTagIntCtor.newInstance(894654));
setTag.invoke (armorTough, "UUIDMost", NBTTagIntCtor.newInstance(2872));
setTag.invoke (armorTough, "Slot", NBTTagStringCtor.newInstance("chest"));
addCompound.invoke(modifiers, armorTough);
if (unbreakable)
setCompoundByte.invoke(compound, "Unbreakable", NBTTagByteCtor.newInstance((byte) 1));
setCompoundTagList.invoke(compound, "AttributeModifiers", modifiers);
item = (ItemStack) asBukkitCopy.invoke(null, nmsStack);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e)
{
// TODO: Log this or something. Pretty serious issue for a plugin based entirely on this code.
e.printStackTrace();
}
return item;
}
// Get the armor tier of the supplied item.
public ArmorTier getArmorTier(ItemStack item)
{
try
{
if (item == null)
return ArmorTier.NONE;
if (item.getType() != Material.ELYTRA)
return ArmorTier.NONE;
// Get the NBT tags from the item.
Object compound = getTag.invoke(asNMSCopy.invoke(null, item));
if (compound == null)
return ArmorTier.NONE;
switch (getArmorValue.armorValueFromNBTString(compound.toString()))
{
case 3:
return ArmorTier.LEATHER;
case 5:
return ArmorTier.GOLD;
case 6:
return ArmorTier.IRON;
case 8:
return ArmorTier.DIAMOND;
default:
return ArmorTier.NONE;
}
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
{
e.printStackTrace();
return null;
}
}
private Class<?> getNMSClass(String name) throws ClassNotFoundException
{
return Class.forName(NMSbase + name);
}
private Class<?> getCraftClass(String name) throws ClassNotFoundException
{
return Class.forName(CraftBase + name);
}
}

View File

@ -1,12 +0,0 @@
package nl.pim16aap2.armoredElytra.nms;
import org.bukkit.inventory.ItemStack;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public interface NBTEditor
{
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable);
public ArmorTier getArmorTier(ItemStack item);
}

View File

@ -1,117 +0,0 @@
package nl.pim16aap2.armoredElytra.nms;
import java.util.Arrays;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_10_R1.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.minecraft.server.v1_10_R1.NBTTagByte;
import net.minecraft.server.v1_10_R1.NBTTagCompound;
import net.minecraft.server.v1_10_R1.NBTTagInt;
import net.minecraft.server.v1_10_R1.NBTTagList;
import net.minecraft.server.v1_10_R1.NBTTagString;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class NBTEditor_V1_10_R1 implements NBTEditor
{
private ArmoredElytra plugin;
// Get the names and lores for every tier of armor.
public NBTEditor_V1_10_R1(ArmoredElytra plugin)
{
this.plugin = plugin;
}
// Add armor to the supplied item, based on the armorTier.
@Override
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable)
{
ItemMeta itemmeta = item.getItemMeta();
int armorProtection = ArmorTier.getArmor(armorTier);
int armorToughness = ArmorTier.getToughness(armorTier);
itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier));
if (plugin.getElytraLore() != null)
itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier)));
item.setItemMeta(itemmeta);
net.minecraft.server.v1_10_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound();
NBTTagList modifiers = new NBTTagList();
NBTTagCompound armor = new NBTTagCompound();
armor.set("AttributeName", new NBTTagString("generic.armor"));
armor.set("Name", new NBTTagString("generic.armor"));
armor.set("Amount", new NBTTagInt(armorProtection));
armor.set("Operation", new NBTTagInt(0));
armor.set("UUIDLeast", new NBTTagInt(894654));
armor.set("UUIDMost", new NBTTagInt(2872));
armor.set("Slot", new NBTTagString("chest"));
modifiers.add(armor);
NBTTagCompound armorTough = new NBTTagCompound();
armorTough.set("AttributeName", new NBTTagString("generic.armorToughness"));
armorTough.set("Name", new NBTTagString("generic.armorToughness"));
armorTough.set("Amount", new NBTTagInt(armorToughness));
armorTough.set("Operation", new NBTTagInt(0));
armorTough.set("UUIDLeast", new NBTTagInt(894654));
armorTough.set("UUIDMost", new NBTTagInt(2872));
armorTough.set("Slot", new NBTTagString("chest"));
modifiers.add(armorTough);
if (unbreakable)
compound.set("Unbreakable", new NBTTagByte((byte) 1));
compound.set("AttributeModifiers", modifiers);
item = CraftItemStack.asBukkitCopy(nmsStack);
return item;
}
// Get the armor tier of the supplied item.
@Override
public ArmorTier getArmorTier(ItemStack item)
{
if (item == null)
return ArmorTier.NONE;
if (item.getType() != Material.ELYTRA)
return ArmorTier.NONE;
// Get the NBT tags from the item.
NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag();
if (compound == null)
return ArmorTier.NONE;
String nbtTags = compound.toString();
// Check if the item has the generic.armor attribute.
// Format = <level>,Slot:"chest",AttributeName:"generic.armor so get pos of char before
// The start of the string, as that's the value of the generic.armor attribute.
int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
int armorValue = 0;
if (pos > 0)
{
// If so, get the value of the generic.armor attribute.
pos--;
String stringAtPos = nbtTags.substring(pos, pos + 1);
armorValue = Integer.parseInt(stringAtPos);
}
else
// Otherwise, the item has no armor, so return 0;
return ArmorTier.NONE;
switch (armorValue)
{
case 3:
return ArmorTier.LEATHER;
case 5:
return ArmorTier.GOLD;
case 6:
return ArmorTier.IRON;
case 8:
return ArmorTier.DIAMOND;
default:
return ArmorTier.NONE;
}
}
}

View File

@ -1,117 +0,0 @@
package nl.pim16aap2.armoredElytra.nms;
import java.util.Arrays;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_11_R1.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.minecraft.server.v1_11_R1.NBTTagByte;
import net.minecraft.server.v1_11_R1.NBTTagCompound;
import net.minecraft.server.v1_11_R1.NBTTagInt;
import net.minecraft.server.v1_11_R1.NBTTagList;
import net.minecraft.server.v1_11_R1.NBTTagString;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class NBTEditor_V1_11_R1 implements NBTEditor
{
private ArmoredElytra plugin;
// Get the names and lores for every tier of armor.
public NBTEditor_V1_11_R1(ArmoredElytra plugin)
{
this.plugin = plugin;
}
// Add armor to the supplied item, based on the armorTier.
@Override
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable)
{
ItemMeta itemmeta = item.getItemMeta();
int armorProtection = ArmorTier.getArmor(armorTier);
int armorToughness = ArmorTier.getToughness(armorTier);
itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier));
if (plugin.getElytraLore() != null)
itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier)));
item.setItemMeta(itemmeta);
net.minecraft.server.v1_11_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound();
NBTTagList modifiers = new NBTTagList();
NBTTagCompound armor = new NBTTagCompound();
armor.set("AttributeName", new NBTTagString("generic.armor"));
armor.set("Name", new NBTTagString("generic.armor"));
armor.set("Amount", new NBTTagInt(armorProtection));
armor.set("Operation", new NBTTagInt(0));
armor.set("UUIDLeast", new NBTTagInt(894654));
armor.set("UUIDMost", new NBTTagInt(2872));
armor.set("Slot", new NBTTagString("chest"));
modifiers.add(armor);
NBTTagCompound armorTough = new NBTTagCompound();
armorTough.set("AttributeName", new NBTTagString("generic.armorToughness"));
armorTough.set("Name", new NBTTagString("generic.armorToughness"));
armorTough.set("Amount", new NBTTagInt(armorToughness));
armorTough.set("Operation", new NBTTagInt(0));
armorTough.set("UUIDLeast", new NBTTagInt(894654));
armorTough.set("UUIDMost", new NBTTagInt(2872));
armorTough.set("Slot", new NBTTagString("chest"));
modifiers.add(armorTough);
if (unbreakable)
compound.set("Unbreakable", new NBTTagByte((byte) 1));
compound.set("AttributeModifiers", modifiers);
item = CraftItemStack.asBukkitCopy(nmsStack);
return item;
}
// Get the armor tier of the supplied item.
@Override
public ArmorTier getArmorTier(ItemStack item)
{
if (item == null)
return ArmorTier.NONE;
if (item.getType() != Material.ELYTRA)
return ArmorTier.NONE;
// Get the NBT tags from the item.
NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag();
if (compound == null)
return ArmorTier.NONE;
String nbtTags = compound.toString();
// Check if the item has the generic.armor attribute.
// Format = <level>,Slot:"chest",AttributeName:"generic.armor so get pos of char before
// The start of the string, as that's the value of the generic.armor attribute.
int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
int armorValue = 0;
if (pos > 0)
{
// If so, get the value of the generic.armor attribute.
pos--;
String stringAtPos = nbtTags.substring(pos, pos + 1);
armorValue = Integer.parseInt(stringAtPos);
}
else
// Otherwise, the item has no armor, so return 0;
return ArmorTier.NONE;
switch (armorValue)
{
case 3:
return ArmorTier.LEATHER;
case 5:
return ArmorTier.GOLD;
case 6:
return ArmorTier.IRON;
case 8:
return ArmorTier.DIAMOND;
default:
return ArmorTier.NONE;
}
}
}

View File

@ -1,117 +0,0 @@
package nl.pim16aap2.armoredElytra.nms;
import java.util.Arrays;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_12_R1.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.minecraft.server.v1_12_R1.NBTTagByte;
import net.minecraft.server.v1_12_R1.NBTTagCompound;
import net.minecraft.server.v1_12_R1.NBTTagInt;
import net.minecraft.server.v1_12_R1.NBTTagList;
import net.minecraft.server.v1_12_R1.NBTTagString;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class NBTEditor_V1_12_R1 implements NBTEditor
{
private ArmoredElytra plugin;
// Get the names and lores for every tier of armor.
public NBTEditor_V1_12_R1(ArmoredElytra plugin)
{
this.plugin = plugin;
}
// Add armor to the supplied item, based on the armorTier.
@Override
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable)
{
ItemMeta itemmeta = item.getItemMeta();
int armorProtection = ArmorTier.getArmor(armorTier);
int armorToughness = ArmorTier.getToughness(armorTier);
itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier));
if (plugin.getElytraLore() != null)
itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier)));
item.setItemMeta(itemmeta);
net.minecraft.server.v1_12_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound();
NBTTagList modifiers = new NBTTagList();
NBTTagCompound armor = new NBTTagCompound();
armor.set("AttributeName", new NBTTagString("generic.armor"));
armor.set("Name", new NBTTagString("generic.armor"));
armor.set("Amount", new NBTTagInt(armorProtection));
armor.set("Operation", new NBTTagInt(0));
armor.set("UUIDLeast", new NBTTagInt(894654));
armor.set("UUIDMost", new NBTTagInt(2872));
armor.set("Slot", new NBTTagString("chest"));
modifiers.add(armor);
NBTTagCompound armorTough = new NBTTagCompound();
armorTough.set("AttributeName", new NBTTagString("generic.armorToughness"));
armorTough.set("Name", new NBTTagString("generic.armorToughness"));
armorTough.set("Amount", new NBTTagInt(armorToughness));
armorTough.set("Operation", new NBTTagInt(0));
armorTough.set("UUIDLeast", new NBTTagInt(894654));
armorTough.set("UUIDMost", new NBTTagInt(2872));
armorTough.set("Slot", new NBTTagString("chest"));
modifiers.add(armorTough);
if (unbreakable)
compound.set("Unbreakable", new NBTTagByte((byte) 1));
compound.set("AttributeModifiers", modifiers);
item = CraftItemStack.asBukkitCopy(nmsStack);
return item;
}
// Get the armor tier of the supplied item.
@Override
public ArmorTier getArmorTier(ItemStack item)
{
if (item == null)
return ArmorTier.NONE;
if (item.getType() != Material.ELYTRA)
return ArmorTier.NONE;
// Get the NBT tags from the item.
NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag();
if (compound == null)
return ArmorTier.NONE;
String nbtTags = compound.toString();
// Check if the item has the generic.armor attribute.
// Format = <level>,Slot:"chest",AttributeName:"generic.armor so get pos of char before
// The start of the string, as that's the value of the generic.armor attribute.
int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
int armorValue = 0;
if (pos > 0)
{
// If so, get the value of the generic.armor attribute.
pos--;
String stringAtPos = nbtTags.substring(pos, pos + 1);
armorValue = Integer.parseInt(stringAtPos);
}
else
// Otherwise, the item has no armor, so return 0;
return ArmorTier.NONE;
switch (armorValue)
{
case 3:
return ArmorTier.LEATHER;
case 5:
return ArmorTier.GOLD;
case 6:
return ArmorTier.IRON;
case 8:
return ArmorTier.DIAMOND;
default:
return ArmorTier.NONE;
}
}
}

View File

@ -1,121 +0,0 @@
package nl.pim16aap2.armoredElytra.nms;
import java.util.Arrays;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_13_R1.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.minecraft.server.v1_13_R1.NBTTagByte;
import net.minecraft.server.v1_13_R1.NBTTagCompound;
import net.minecraft.server.v1_13_R1.NBTTagInt;
import net.minecraft.server.v1_13_R1.NBTTagList;
import net.minecraft.server.v1_13_R1.NBTTagString;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class NBTEditor_V1_13_R1 implements NBTEditor
{
private ArmoredElytra plugin;
// Get the names and lores for every tier of armor.
public NBTEditor_V1_13_R1(ArmoredElytra plugin)
{
this.plugin = plugin;
}
// Add armor to the supplied item, based on the armorTier.
@Override
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable)
{
ItemMeta itemmeta = item.getItemMeta();
int armorProtection = ArmorTier.getArmor(armorTier);
int armorToughness = ArmorTier.getToughness(armorTier);
itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier));
if (plugin.getElytraLore() != null)
itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier)));
item.setItemMeta(itemmeta);
net.minecraft.server.v1_13_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound();
NBTTagList modifiers = new NBTTagList();
NBTTagCompound armor = new NBTTagCompound();
armor.set("AttributeName", new NBTTagString("generic.armor"));
armor.set("Name", new NBTTagString("generic.armor"));
armor.set("Amount", new NBTTagInt(armorProtection));
armor.set("Operation", new NBTTagInt(0));
armor.set("UUIDLeast", new NBTTagInt(894654));
armor.set("UUIDMost", new NBTTagInt(2872));
armor.set("Slot", new NBTTagString("chest"));
modifiers.add(armor);
NBTTagCompound armorTough = new NBTTagCompound();
armorTough.set("AttributeName", new NBTTagString("generic.armorToughness"));
armorTough.set("Name", new NBTTagString("generic.armorToughness"));
armorTough.set("Amount", new NBTTagInt(armorToughness));
armorTough.set("Operation", new NBTTagInt(0));
armorTough.set("UUIDLeast", new NBTTagInt(894654));
armorTough.set("UUIDMost", new NBTTagInt(2872));
armorTough.set("Slot", new NBTTagString("chest"));
modifiers.add(armorTough);
if (unbreakable)
compound.set("Unbreakable", new NBTTagByte((byte) 1));
compound.set("AttributeModifiers", modifiers);
item = CraftItemStack.asBukkitCopy(nmsStack);
return item;
}
// Get the armor tier of the supplied item.
@Override
public ArmorTier getArmorTier(ItemStack item)
{
if (item == null)
return ArmorTier.NONE;
if (item.getType() != Material.ELYTRA)
return ArmorTier.NONE;
// Get the NBT tags from the item.
NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag();
if (compound == null)
return ArmorTier.NONE;
String nbtTags = compound.toString();
// Check if the item has the generic.armor attribute.
// Format = <level>,Slot:"chest",AttributeName:"generic.armor so get pos of char before
// The start of the string, as that's the value of the generic.armor attribute.
// The level is now formatted as x.xd, e.g. 6.0d.
int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
int armorValue = 0;
if (pos <= 0)
return ArmorTier.NONE;
try
{
String stringAtPos = nbtTags.substring(pos - 4, pos - 1);
armorValue = (int) Double.parseDouble(stringAtPos);
}
catch (Exception e)
{
armorValue = 0;
}
switch (armorValue)
{
case 3:
return ArmorTier.LEATHER;
case 5:
return ArmorTier.GOLD;
case 6:
return ArmorTier.IRON;
case 8:
return ArmorTier.DIAMOND;
default:
return ArmorTier.NONE;
}
}
}

View File

@ -1,121 +0,0 @@
package nl.pim16aap2.armoredElytra.nms;
import java.util.Arrays;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_13_R2.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.minecraft.server.v1_13_R2.NBTTagByte;
import net.minecraft.server.v1_13_R2.NBTTagCompound;
import net.minecraft.server.v1_13_R2.NBTTagInt;
import net.minecraft.server.v1_13_R2.NBTTagList;
import net.minecraft.server.v1_13_R2.NBTTagString;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class NBTEditor_V1_13_R2 implements NBTEditor
{
private ArmoredElytra plugin;
// Get the names and lores for every tier of armor.
public NBTEditor_V1_13_R2(ArmoredElytra plugin)
{
this.plugin = plugin;
}
// Add armor to the supplied item, based on the armorTier.
@Override
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable)
{
ItemMeta itemmeta = item.getItemMeta();
int armorProtection = ArmorTier.getArmor(armorTier);
int armorToughness = ArmorTier.getToughness(armorTier);
itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier));
if (plugin.getElytraLore() != null)
itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier)));
item.setItemMeta(itemmeta);
net.minecraft.server.v1_13_R2.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound();
NBTTagList modifiers = new NBTTagList();
NBTTagCompound armor = new NBTTagCompound();
armor.set("AttributeName", new NBTTagString("generic.armor"));
armor.set("Name", new NBTTagString("generic.armor"));
armor.set("Amount", new NBTTagInt(armorProtection));
armor.set("Operation", new NBTTagInt(0));
armor.set("UUIDLeast", new NBTTagInt(894654));
armor.set("UUIDMost", new NBTTagInt(2872));
armor.set("Slot", new NBTTagString("chest"));
modifiers.add(armor);
NBTTagCompound armorTough = new NBTTagCompound();
armorTough.set("AttributeName", new NBTTagString("generic.armorToughness"));
armorTough.set("Name", new NBTTagString("generic.armorToughness"));
armorTough.set("Amount", new NBTTagInt(armorToughness));
armorTough.set("Operation", new NBTTagInt(0));
armorTough.set("UUIDLeast", new NBTTagInt(894654));
armorTough.set("UUIDMost", new NBTTagInt(2872));
armorTough.set("Slot", new NBTTagString("chest"));
modifiers.add(armorTough);
if (unbreakable)
compound.set("Unbreakable", new NBTTagByte((byte) 1));
compound.set("AttributeModifiers", modifiers);
item = CraftItemStack.asBukkitCopy(nmsStack);
return item;
}
// Get the armor tier of the supplied item.
@Override
public ArmorTier getArmorTier(ItemStack item)
{
if (item == null)
return ArmorTier.NONE;
if (item.getType() != Material.ELYTRA)
return ArmorTier.NONE;
// Get the NBT tags from the item.
NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag();
if (compound == null)
return ArmorTier.NONE;
String nbtTags = compound.toString();
// Check if the item has the generic.armor attribute.
// Format = <level>,Slot:"chest",AttributeName:"generic.armor so get pos of char before
// The start of the string, as that's the value of the generic.armor attribute.
// The level is now formatted as x.xd, e.g. 6.0d.
int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
int armorValue = 0;
if (pos <= 0)
return ArmorTier.NONE;
try
{
String stringAtPos = nbtTags.substring(pos - 4, pos - 1);
armorValue = (int) Double.parseDouble(stringAtPos);
}
catch (Exception e)
{
armorValue = 0;
}
switch (armorValue)
{
case 3:
return ArmorTier.LEATHER;
case 5:
return ArmorTier.GOLD;
case 6:
return ArmorTier.IRON;
case 8:
return ArmorTier.DIAMOND;
default:
return ArmorTier.NONE;
}
}
}

View File

@ -1,117 +0,0 @@
package nl.pim16aap2.armoredElytra.nms;
import java.util.Arrays;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_9_R1.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.minecraft.server.v1_9_R1.NBTTagByte;
import net.minecraft.server.v1_9_R1.NBTTagCompound;
import net.minecraft.server.v1_9_R1.NBTTagInt;
import net.minecraft.server.v1_9_R1.NBTTagList;
import net.minecraft.server.v1_9_R1.NBTTagString;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class NBTEditor_V1_9_R1 implements NBTEditor
{
private ArmoredElytra plugin;
// Get the names and lores for every tier of armor.
public NBTEditor_V1_9_R1(ArmoredElytra plugin)
{
this.plugin = plugin;
}
// Add armor to the supplied item, based on the armorTier.
@Override
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable)
{
ItemMeta itemmeta = item.getItemMeta();
int armorProtection = ArmorTier.getArmor(armorTier);
int armorToughness = ArmorTier.getToughness(armorTier);
itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier));
if (plugin.getElytraLore() != null)
itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier)));
item.setItemMeta(itemmeta);
net.minecraft.server.v1_9_R1.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound();
NBTTagList modifiers = new NBTTagList();
NBTTagCompound armor = new NBTTagCompound();
armor.set("AttributeName", new NBTTagString("generic.armor"));
armor.set("Name", new NBTTagString("generic.armor"));
armor.set("Amount", new NBTTagInt(armorProtection));
armor.set("Operation", new NBTTagInt(0));
armor.set("UUIDLeast", new NBTTagInt(894654));
armor.set("UUIDMost", new NBTTagInt(2872));
armor.set("Slot", new NBTTagString("chest"));
modifiers.add(armor);
NBTTagCompound armorTough = new NBTTagCompound();
armorTough.set("AttributeName", new NBTTagString("generic.armorToughness"));
armorTough.set("Name", new NBTTagString("generic.armorToughness"));
armorTough.set("Amount", new NBTTagInt(armorToughness));
armorTough.set("Operation", new NBTTagInt(0));
armorTough.set("UUIDLeast", new NBTTagInt(894654));
armorTough.set("UUIDMost", new NBTTagInt(2872));
armorTough.set("Slot", new NBTTagString("chest"));
modifiers.add(armorTough);
if (unbreakable)
compound.set("Unbreakable", new NBTTagByte((byte) 1));
compound.set("AttributeModifiers", modifiers);
item = CraftItemStack.asBukkitCopy(nmsStack);
return item;
}
// Get the armor tier of the supplied item.
@Override
public ArmorTier getArmorTier(ItemStack item)
{
if (item == null)
return ArmorTier.NONE;
if (item.getType() != Material.ELYTRA)
return ArmorTier.NONE;
// Get the NBT tags from the item.
NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag();
if (compound == null)
return ArmorTier.NONE;
String nbtTags = compound.toString();
// Check if the item has the generic.armor attribute.
// Format = <level>,Slot:"chest",AttributeName:"generic.armor so get pos of char before
// The start of the string, as that's the value of the generic.armor attribute.
int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
int armorValue = 0;
if (pos > 0)
{
// If so, get the value of the generic.armor attribute.
pos--;
String stringAtPos = nbtTags.substring(pos, pos + 1);
armorValue = Integer.parseInt(stringAtPos);
}
else
// Otherwise, the item has no armor, so return 0;
return ArmorTier.NONE;
switch (armorValue)
{
case 3:
return ArmorTier.LEATHER;
case 5:
return ArmorTier.GOLD;
case 6:
return ArmorTier.IRON;
case 8:
return ArmorTier.DIAMOND;
default:
return ArmorTier.NONE;
}
}
}

View File

@ -1,117 +0,0 @@
package nl.pim16aap2.armoredElytra.nms;
import java.util.Arrays;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_9_R2.inventory.CraftItemStack;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import net.minecraft.server.v1_9_R2.NBTTagByte;
import net.minecraft.server.v1_9_R2.NBTTagCompound;
import net.minecraft.server.v1_9_R2.NBTTagInt;
import net.minecraft.server.v1_9_R2.NBTTagList;
import net.minecraft.server.v1_9_R2.NBTTagString;
import nl.pim16aap2.armoredElytra.ArmoredElytra;
import nl.pim16aap2.armoredElytra.util.ArmorTier;
public class NBTEditor_V1_9_R2 implements NBTEditor
{
private ArmoredElytra plugin;
// Get the names and lores for every tier of armor.
public NBTEditor_V1_9_R2(ArmoredElytra plugin)
{
this.plugin = plugin;
}
// Add armor to the supplied item, based on the armorTier.
@Override
public ItemStack addArmorNBTTags(ItemStack item, ArmorTier armorTier, boolean unbreakable)
{
ItemMeta itemmeta = item.getItemMeta();
int armorProtection = ArmorTier.getArmor(armorTier);
int armorToughness = ArmorTier.getToughness(armorTier);
itemmeta.setDisplayName(plugin.getArmoredElytrName(armorTier));
if (plugin.getElytraLore() != null)
itemmeta.setLore(Arrays.asList(plugin.fillInArmorTierInStringNoColor(plugin.getElytraLore(), armorTier)));
item.setItemMeta(itemmeta);
net.minecraft.server.v1_9_R2.ItemStack nmsStack = CraftItemStack.asNMSCopy(item);
NBTTagCompound compound = (nmsStack.hasTag()) ? nmsStack.getTag() : new NBTTagCompound();
NBTTagList modifiers = new NBTTagList();
NBTTagCompound armor = new NBTTagCompound();
armor.set("AttributeName", new NBTTagString("generic.armor"));
armor.set("Name", new NBTTagString("generic.armor"));
armor.set("Amount", new NBTTagInt(armorProtection));
armor.set("Operation", new NBTTagInt(0));
armor.set("UUIDLeast", new NBTTagInt(894654));
armor.set("UUIDMost", new NBTTagInt(2872));
armor.set("Slot", new NBTTagString("chest"));
modifiers.add(armor);
NBTTagCompound armorTough = new NBTTagCompound();
armorTough.set("AttributeName", new NBTTagString("generic.armorToughness"));
armorTough.set("Name", new NBTTagString("generic.armorToughness"));
armorTough.set("Amount", new NBTTagInt(armorToughness));
armorTough.set("Operation", new NBTTagInt(0));
armorTough.set("UUIDLeast", new NBTTagInt(894654));
armorTough.set("UUIDMost", new NBTTagInt(2872));
armorTough.set("Slot", new NBTTagString("chest"));
modifiers.add(armorTough);
if (unbreakable)
compound.set("Unbreakable", new NBTTagByte((byte) 1));
compound.set("AttributeModifiers", modifiers);
item = CraftItemStack.asBukkitCopy(nmsStack);
return item;
}
// Get the armor tier of the supplied item.
@Override
public ArmorTier getArmorTier(ItemStack item)
{
if (item == null)
return ArmorTier.NONE;
if (item.getType() != Material.ELYTRA)
return ArmorTier.NONE;
// Get the NBT tags from the item.
NBTTagCompound compound = CraftItemStack.asNMSCopy(item).getTag();
if (compound == null)
return ArmorTier.NONE;
String nbtTags = compound.toString();
// Check if the item has the generic.armor attribute.
// Format = <level>,Slot:"chest",AttributeName:"generic.armor so get pos of char before
// The start of the string, as that's the value of the generic.armor attribute.
int pos = nbtTags.indexOf(",Slot:\"chest\",AttributeName:\"generic.armor\"");
int armorValue = 0;
if (pos > 0)
{
// If so, get the value of the generic.armor attribute.
pos--;
String stringAtPos = nbtTags.substring(pos, pos + 1);
armorValue = Integer.parseInt(stringAtPos);
}
else
// Otherwise, the item has no armor, so return 0;
return ArmorTier.NONE;
switch (armorValue)
{
case 3:
return ArmorTier.LEATHER;
case 5:
return ArmorTier.GOLD;
case 6:
return ArmorTier.IRON;
case 8:
return ArmorTier.DIAMOND;
default:
return ArmorTier.NONE;
}
}
}