From 78558107b33a1575b18d795ba8cd409d9197c91e Mon Sep 17 00:00:00 2001 From: nossr50 Date: Thu, 2 May 2024 06:28:20 -0700 Subject: [PATCH 01/34] WIP 1.20.6 support --- Changelog.txt | 7 + pom.xml | 33 +- .../nossr50/commands/skills/MacesCommand.java | 56 +++ .../nossr50/config/LegacyConfigLoader.java | 17 +- .../config/skills/alchemy/PotionConfig.java | 211 ++++++--- .../treasure/FishingTreasureConfig.java | 43 +- .../config/treasure/TreasureConfig.java | 35 +- .../database/FlatFileDataProcessor.java | 82 +--- .../database/FlatFileDatabaseManager.java | 24 +- .../nossr50/database/SQLDatabaseManager.java | 52 +- .../database/flatfile/FlatFileDataUtil.java | 84 +--- .../nossr50/datatypes/player/McMMOPlayer.java | 8 + .../datatypes/skills/PrimarySkillType.java | 1 + .../datatypes/skills/SubSkillType.java | 3 + .../datatypes/skills/SuperAbilityType.java | 32 +- .../nossr50/datatypes/skills/ToolType.java | 5 +- .../skills/alchemy/AlchemyPotion.java | 211 ++++----- .../datatypes/skills/alchemy/PotionStage.java | 27 +- .../skills/subskills/acrobatics/Roll.java | 3 +- .../nossr50/listeners/EntityListener.java | 2 +- src/main/java/com/gmail/nossr50/mcMMO.java | 38 +- .../nossr50/metadata/ItemMetadataService.java | 7 +- .../skills/alchemy/AlchemyManager.java | 4 +- .../skills/alchemy/AlchemyPotionBrewer.java | 14 +- .../skills/archery/ArcheryManager.java | 7 +- .../skills/fishing/FishingManager.java | 6 +- .../nossr50/skills/maces/MacesManager.java | 21 + .../nossr50/skills/taming/TamingManager.java | 2 +- .../gmail/nossr50/util/AttributeMapper.java | 45 ++ .../gmail/nossr50/util/EnchantmentMapper.java | 149 ++++++ .../gmail/nossr50/util/EnchantmentUtils.java | 61 +-- .../com/gmail/nossr50/util/ItemUtils.java | 40 +- .../gmail/nossr50/util/MaterialMapStore.java | 17 + .../com/gmail/nossr50/util/Permissions.java | 8 + .../nossr50/util/PotionCompatibilityType.java | 6 + .../nossr50/util/PotionEffectMapper.java | 142 ++++++ .../com/gmail/nossr50/util/PotionUtil.java | 447 ++++++++++++++++++ .../commands/CommandRegistrationManager.java | 9 +- .../util/compat/CompatibilityManager.java | 3 +- .../nossr50/util/skills/CombatUtils.java | 36 ++ .../gmail/nossr50/util/skills/SkillTools.java | 1 + .../gmail/nossr50/util/skills/SkillUtils.java | 25 +- src/main/resources/experience.yml | 20 +- .../resources/locale/locale_en_US.properties | 7 +- src/main/resources/plugin.yml | 3 + src/main/resources/skillranks.yml | 24 + .../com/gmail/nossr50/MMOTestEnvironment.java | 61 ++- .../skills/alchemy/PotionConfigTest.java | 69 +++ .../database/FlatFileDatabaseManagerTest.java | 345 ++++++-------- .../gmail/nossr50/util/PotionUtilTest.java | 51 ++ src/test/resources/healthydb.users | 6 +- 51 files changed, 1874 insertions(+), 736 deletions(-) create mode 100644 src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java create mode 100644 src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java create mode 100644 src/main/java/com/gmail/nossr50/util/AttributeMapper.java create mode 100644 src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java create mode 100644 src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java create mode 100644 src/main/java/com/gmail/nossr50/util/PotionEffectMapper.java create mode 100644 src/main/java/com/gmail/nossr50/util/PotionUtil.java create mode 100644 src/test/java/com/gmail/nossr50/config/skills/alchemy/PotionConfigTest.java create mode 100644 src/test/java/com/gmail/nossr50/util/PotionUtilTest.java diff --git a/Changelog.txt b/Changelog.txt index 698739102..eb01a4712 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,6 +1,13 @@ Version 2.2.007 + Compatibility with the 1.20.5 MC Update + Alchemy now has more warning/errors that will print out to help debug Fixed bug where Green Thumb did not replant if seed was in the off hand + NOTES: + I did my best to keep mcMMO compatible with older versions of Minecraft for this update. + This update to MC was quite large, with breaking changes to a lot of code relating to Alchemy, and some other things. + I expect there to be bugs, please report them on GitHub or Discord, but preferably GitHub. + I will be working on fixing these bugs as they come in, so please be patient. Version 2.2.006 Added new config custom_item_support.yml Added support for hex color codes in the locale file, uses the format &#RRGGBB (see notes) diff --git a/pom.xml b/pom.xml index 9bdddf369..136deebdf 100644 --- a/pom.xml +++ b/pom.xml @@ -254,8 +254,11 @@ devmart-other https://nexuslite.gcnt.net/repos/other/ - - + + + papermc + https://repo.papermc.io/repository/maven-public/ + @@ -361,7 +364,7 @@ org.spigotmc spigot-api - 1.20.4-R0.1-SNAPSHOT + 1.20.5-R0.1-SNAPSHOT provided @@ -435,5 +438,29 @@ 0.3.1 compile + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java new file mode 100644 index 000000000..757c8dcf1 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java @@ -0,0 +1,56 @@ +//package com.gmail.nossr50.commands.skills; +// +//import com.gmail.nossr50.datatypes.player.McMMOPlayer; +//import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +//import com.gmail.nossr50.util.player.UserManager; +//import com.gmail.nossr50.util.skills.CombatUtils; +//import com.gmail.nossr50.util.skills.SkillUtils; +//import com.gmail.nossr50.util.text.TextComponentFactory; +//import net.kyori.adventure.text.Component; +//import org.bukkit.ChatColor; +//import org.bukkit.entity.Player; +// +//import java.util.ArrayList; +//import java.util.List; +// +//import static com.gmail.nossr50.datatypes.skills.SubSkillType.MACES_MACES_LIMIT_BREAK; +// +//public class MacesCommand extends SkillCommand { +// +// public MacesCommand() { +// super(PrimarySkillType.MACES); +// } +// +// @Override +// protected void dataCalculations(Player player, float skillValue) {} +// +// @Override +// protected void permissionsCheck(Player player) {} +// +// @Override +// protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { +// List messages = new ArrayList<>(); +// McMMOPlayer mmoPlayer = UserManager.getPlayer(player); +// if (mmoPlayer == null) { +// return messages; +// } +// +// if(SkillUtils.canUseSubskill(player, MACES_MACES_LIMIT_BREAK)) { +// messages.add(getStatMessage(MACES_MACES_LIMIT_BREAK, +// String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, MACES_MACES_LIMIT_BREAK, 1000)))); +// } +// +// messages.add(ChatColor.GRAY + "The Maces skill is a work in progress and is still being developed," + +// " feedback would be appreciated in the mcMMO discord server."); +// return messages; +// } +// +// @Override +// protected List getTextComponents(Player player) { +// List textComponents = new ArrayList<>(); +// +// TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.MACES); +// +// return textComponents; +// } +//} diff --git a/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java b/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java index 6a917b3fd..c9d808e01 100644 --- a/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java +++ b/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java @@ -4,31 +4,40 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.VisibleForTesting; import java.io.File; import java.util.List; @Deprecated public abstract class LegacyConfigLoader { - protected final File configFile; + protected final @NotNull File configFile; protected final @NotNull File dataFolder; - protected String fileName; + protected @NotNull String fileName; protected YamlConfiguration config; - public LegacyConfigLoader(String relativePath, String fileName, @NotNull File dataFolder) { + public LegacyConfigLoader(@NotNull String relativePath, @NotNull String fileName, @NotNull File dataFolder) { this.fileName = fileName; this.dataFolder = dataFolder; configFile = new File(dataFolder, relativePath + File.separator + fileName); loadFile(); } - public LegacyConfigLoader(String fileName, @NotNull File dataFolder) { + public LegacyConfigLoader(@NotNull String fileName, @NotNull File dataFolder) { this.fileName = fileName; this.dataFolder = dataFolder; configFile = new File(dataFolder, fileName); loadFile(); } + @VisibleForTesting + public LegacyConfigLoader(@NotNull File file) { + this.fileName = file.getName(); + this.dataFolder = file.getParentFile(); + configFile = new File(dataFolder, fileName); + loadFile(); + } + @Deprecated public LegacyConfigLoader(String relativePath, String fileName) { this.fileName = fileName; diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 3b21589c6..37b992dad 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -2,22 +2,30 @@ package com.gmail.nossr50.config.skills.alchemy; import com.gmail.nossr50.config.LegacyConfigLoader; import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion; +import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.LogUtils; +import com.gmail.nossr50.util.ItemUtils; +import com.gmail.nossr50.util.PotionUtil; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.*; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.potion.PotionType; +import org.jetbrains.annotations.VisibleForTesting; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import static com.gmail.nossr50.util.PotionUtil.*; + public class PotionConfig extends LegacyConfigLoader { - private static PotionConfig instance; private final List concoctionsIngredientsTierOne = new ArrayList<>(); private final List concoctionsIngredientsTierTwo = new ArrayList<>(); @@ -28,30 +36,34 @@ public class PotionConfig extends LegacyConfigLoader { private final List concoctionsIngredientsTierSeven = new ArrayList<>(); private final List concoctionsIngredientsTierEight = new ArrayList<>(); - private final Map potionMap = new HashMap<>(); + /** + * Map of potion names to AlchemyPotion objects. + */ + private final Map loadedPotions = new HashMap<>(); - private PotionConfig() { + public PotionConfig() { super("potions.yml"); - loadKeys(); } - public static PotionConfig getInstance() { - if (instance == null) { - instance = new PotionConfig(); - } - - return instance; + @VisibleForTesting + PotionConfig(File file) { + super(file); } @Override protected void loadKeys() { + } + + public void loadPotions() { loadConcoctions(); loadPotionMap(); } - private void loadConcoctions() { - ConfigurationSection concoctionSection = config.getConfigurationSection("Concoctions"); + @VisibleForTesting + void loadConcoctions() { + final ConfigurationSection concoctionSection = config.getConfigurationSection("Concoctions"); + // Load the ingredients for each tier loadConcoctionsTier(concoctionsIngredientsTierOne, concoctionSection.getStringList("Tier_One_Ingredients")); loadConcoctionsTier(concoctionsIngredientsTierTwo, concoctionSection.getStringList("Tier_Two_Ingredients")); loadConcoctionsTier(concoctionsIngredientsTierThree, concoctionSection.getStringList("Tier_Three_Ingredients")); @@ -71,7 +83,7 @@ public class PotionConfig extends LegacyConfigLoader { } private void loadConcoctionsTier(List ingredientList, List ingredientStrings) { - if (ingredientStrings != null && ingredientStrings.size() > 0) { + if (ingredientStrings != null && !ingredientStrings.isEmpty()) { for (String ingredientString : ingredientStrings) { ItemStack ingredient = loadIngredient(ingredientString); @@ -85,23 +97,24 @@ public class PotionConfig extends LegacyConfigLoader { /** * Find the Potions configuration section and load all defined potions. */ - private void loadPotionMap() { + int loadPotionMap() { ConfigurationSection potionSection = config.getConfigurationSection("Potions"); - int pass = 0; - int fail = 0; + int potionsLoaded = 0; + int failures = 0; for (String potionName : potionSection.getKeys(false)) { AlchemyPotion potion = loadPotion(potionSection.getConfigurationSection(potionName)); if (potion != null) { - potionMap.put(potionName, potion); - pass++; + loadedPotions.put(potionName, potion); + potionsLoaded++; } else { - fail++; + failures++; } } - LogUtils.debug(mcMMO.p.getLogger(), "Loaded " + pass + " Alchemy potions, skipped " + fail + "."); + mcMMO.p.getLogger().info("Loaded " + potionsLoaded + " Alchemy potions, skipped " + failures + "."); + return potionsLoaded; } /** @@ -114,37 +127,88 @@ public class PotionConfig extends LegacyConfigLoader { */ private AlchemyPotion loadPotion(ConfigurationSection potion_section) { try { + final String key = potion_section.getName(); + final String displayName = potion_section.getString("Name") != null + ? LocaleLoader.addColors(potion_section.getString("Name")) + : null; + final ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData"); + boolean extended = false; + boolean upgraded = false; - String name = potion_section.getString("Name"); - if (name != null) { - name = ChatColor.translateAlternateColorCodes('&', name); + if (potionData != null) { + extended = potionData.getBoolean("Extended", false); + upgraded = potionData.getBoolean("Upgraded", false); } - PotionData data; - if (!potion_section.contains("PotionData")) { // Backwards config compatability - short dataValue = Short.parseShort(potion_section.getName()); - Potion potion = Potion.fromDamage(dataValue); - data = new PotionData(potion.getType(), potion.hasExtendedDuration(), potion.getLevel() == 2); + Material material; + final String materialString = potion_section.getString("Material", null); + if (materialString != null) { + material = ItemUtils.exhaustiveMaterialLookup(materialString); + if (material == null) { + mcMMO.p.getLogger().warning("PotionConfig: Failed to parse material for potion " + key + ": " + materialString); + mcMMO.p.getLogger().warning("PotionConfig: Defaulting to POTION"); + material = Material.POTION; + } } else { - ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData"); - data = new PotionData(PotionType.valueOf(potionData.getString("PotionType", "WATER")), potionData.getBoolean("Extended", false), potionData.getBoolean("Upgraded", false)); + mcMMO.p.getLogger().warning("PotionConfig: Missing Material config entry for potion " + key + "," + + " from configuration section: " + potion_section + ", defaulting to POTION"); + material = Material.POTION; } - Material material = Material.POTION; - String mat = potion_section.getString("Material", null); - if (mat != null) { - material = Material.valueOf(mat); + final ItemStack itemStack = new ItemStack(material, 1); + final PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); + + if (potionMeta == null) { + mcMMO.p.getLogger().severe("PotionConfig: Failed to get PotionMeta for " + displayName + ", from configuration section:" + + " " + potion_section); + return null; } + // extended and upgraded seem to be mutually exclusive + if (extended && upgraded) { + mcMMO.p.getLogger().warning("Potion " + key + " has both Extended and Upgraded set to true," + + " defaulting to Extended."); + upgraded = false; + } + String potionTypeStr = potionData.getString("PotionType", null); + if (potionTypeStr == null) { + mcMMO.p.getLogger().severe("PotionConfig: Missing PotionType for " + displayName + ", from configuration section:" + + " " + potion_section); + return null; + } + + PotionType potionType = matchPotionType(potionTypeStr, upgraded, extended); + if (potionType == null) { + // try matching to key + mcMMO.p.getLogger().warning("Failed to match potion type, trying to match with config key..."); + matchPotionType(key, upgraded, extended); + } + + if (potionType == null) { + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr); + return null; + } + + // Set base potion type + // NOTE: extended/ignored are effectively ignored here on 1.20.5 and later + PotionUtil.setBasePotionType(potionMeta, potionType, extended, upgraded); + +// // Use the name of the potion to indicate upgrade status if not set in PotionData +// if(convertPotionConfigName(key).toUpperCase().contains("STRONG")) +// upgraded = true; +// +// if(convertPotionConfigName(key).toUpperCase().contains("LONG")) +// extended = true; + List lore = new ArrayList<>(); if (potion_section.contains("Lore")) { for (String line : potion_section.getStringList("Lore")) { lore.add(ChatColor.translateAlternateColorCodes('&', line)); } } + potionMeta.setLore(lore); - List effects = new ArrayList<>(); if (potion_section.contains("Effects")) { for (String effect : potion_section.getStringList("Effects")) { String[] parts = effect.split(" "); @@ -154,9 +218,9 @@ public class PotionConfig extends LegacyConfigLoader { int duration = parts.length > 2 ? Integer.parseInt(parts[2]) : 0; if (type != null) { - effects.add(new PotionEffect(type, duration, amplifier)); + potionMeta.addCustomEffect(new PotionEffect(type, duration, amplifier), true); } else { - mcMMO.p.getLogger().warning("Failed to parse effect for potion " + name + ": " + effect); + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse effect for potion " + displayName + ": " + effect); } } } @@ -165,8 +229,9 @@ public class PotionConfig extends LegacyConfigLoader { if (potion_section.contains("Color")) { color = Color.fromRGB(potion_section.getInt("Color")); } else { - color = this.generateColor(effects); + color = this.generateColor(potionMeta.getCustomEffects()); } + potionMeta.setColor(color); Map children = new HashMap<>(); if (potion_section.contains("Children")) { @@ -175,14 +240,15 @@ public class PotionConfig extends LegacyConfigLoader { if (ingredient != null) { children.put(ingredient, potion_section.getConfigurationSection("Children").getString(child)); } else { - mcMMO.p.getLogger().warning("Failed to parse child for potion " + name + ": " + child); + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse child for potion " + displayName + ": " + child); } } } - - return new AlchemyPotion(material, data, name, lore, effects, color, children); + // TODO: Might not need to .setItemMeta + itemStack.setItemMeta(potionMeta); + return new AlchemyPotion(itemStack, children); } catch (Exception e) { - mcMMO.p.getLogger().warning("Failed to load Alchemy potion: " + potion_section.getName()); + mcMMO.p.getLogger().warning("PotionConfig: Failed to load Alchemy potion: " + potion_section.getName()); return null; } } @@ -210,39 +276,52 @@ public class PotionConfig extends LegacyConfigLoader { return null; } + /** + * Get the ingredients for the given tier. + * @param tier Tier to get ingredients for. + * @return List of ingredients for the given tier. + */ public List getIngredients(int tier) { - switch (tier) { - case 8: - return concoctionsIngredientsTierEight; - case 7: - return concoctionsIngredientsTierSeven; - case 6: - return concoctionsIngredientsTierSix; - case 5: - return concoctionsIngredientsTierFive; - case 4: - return concoctionsIngredientsTierFour; - case 3: - return concoctionsIngredientsTierThree; - case 2: - return concoctionsIngredientsTierTwo; - case 1: - default: - return concoctionsIngredientsTierOne; - } + return switch (tier) { + case 8 -> concoctionsIngredientsTierEight; + case 7 -> concoctionsIngredientsTierSeven; + case 6 -> concoctionsIngredientsTierSix; + case 5 -> concoctionsIngredientsTierFive; + case 4 -> concoctionsIngredientsTierFour; + case 3 -> concoctionsIngredientsTierThree; + case 2 -> concoctionsIngredientsTierTwo; + default -> concoctionsIngredientsTierOne; + }; } + /** + * Check if the given ItemStack is a valid potion. + * @param item ItemStack to be checked. + * @return True if the given ItemStack is a valid potion, false otherwise. + */ public boolean isValidPotion(ItemStack item) { return getPotion(item) != null; } + /** + * Get the AlchemyPotion that corresponds to the given name. + * @param name Name of the potion to be checked. + * @return AlchemyPotion that corresponds to the given name. + */ public AlchemyPotion getPotion(String name) { - return potionMap.get(name); + return loadedPotions.get(name); } + /** + * Get the AlchemyPotion that corresponds to the given ItemStack. + * + * @param item ItemStack to be checked. + * + * @return AlchemyPotion that corresponds to the given ItemStack. + */ public AlchemyPotion getPotion(ItemStack item) { - for (AlchemyPotion potion : potionMap.values()) { - if (potion.isSimilar(item)) { + for (AlchemyPotion potion : loadedPotions.values()) { + if (potion.isSimilarPotion(item)) { return potion; } } diff --git a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java index a02e0bd3f..5ffbb74da 100755 --- a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java @@ -5,6 +5,7 @@ import com.gmail.nossr50.datatypes.treasure.*; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.EnchantmentUtils; import com.gmail.nossr50.util.LogUtils; +import com.gmail.nossr50.util.PotionUtil; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; @@ -13,12 +14,13 @@ import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionType; import org.jetbrains.annotations.NotNull; import java.util.*; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; + public class FishingTreasureConfig extends BukkitConfig { public static final String FILENAME = "fishing_treasures.yml"; @@ -204,30 +206,40 @@ public class FishingTreasureConfig extends BukkitConfig { } if (materialName.contains("POTION")) { + // Update for 1.20.5 + Material mat = Material.matchMaterial(materialName); if (mat == null) { reason.add("Potion format for " + FILENAME + " has changed"); + continue; } else { item = new ItemStack(mat, amount, data); - PotionMeta itemMeta = (PotionMeta) item.getItemMeta(); + PotionMeta potionMeta = (PotionMeta) item.getItemMeta(); - if (itemMeta == null) { - mcMMO.p.getLogger().severe("Item meta when adding potion to fishing treasure was null, contact the mcMMO devs!"); + if (potionMeta == null) { + mcMMO.p.getLogger().severe("FishingConfig: Item meta when adding potion to fishing treasure was null," + + " contact the mcMMO devs!"); + reason.add("FishingConfig: Item meta when adding potion to fishing treasure was null"); continue; } - PotionType potionType = null; - try { - potionType = PotionType.valueOf(config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER")); - } catch (IllegalArgumentException ex) { - reason.add("Invalid Potion_Type: " + config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER")); - } + String potionTypeStr; + potionTypeStr = config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER"); boolean extended = config.getBoolean(type + "." + treasureName + ".PotionData.Extended", false); boolean upgraded = config.getBoolean(type + "." + treasureName + ".PotionData.Upgraded", false); - itemMeta.setBasePotionData(new PotionData(potionType, extended, upgraded)); + final PotionType potionType = matchPotionType(potionTypeStr, extended, upgraded); + + if (potionType == null) { + reason.add("FishingConfig: Could not derive potion type from: " + potionTypeStr +", " + extended + ", " + upgraded); + continue; + } + + // Set the base potion type + // NOTE: Upgraded/Extended are ignored in 1.20.5 and later + PotionUtil.setBasePotionType(potionMeta, potionType, upgraded, extended); if (customName != null) { - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', customName)); + potionMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', customName)); } if (config.contains(type + "." + treasureName + ".Lore")) { @@ -235,9 +247,9 @@ public class FishingTreasureConfig extends BukkitConfig { for (String s : config.getStringList(type + "." + treasureName + ".Lore")) { lore.add(ChatColor.translateAlternateColorCodes('&', s)); } - itemMeta.setLore(lore); + potionMeta.setLore(lore); } - item.setItemMeta(itemMeta); + item.setItemMeta(potionMeta); } } else if (material == Material.ENCHANTED_BOOK) { //If any whitelisted enchants exist we use whitelist-based matching @@ -355,7 +367,8 @@ public class FishingTreasureConfig extends BukkitConfig { Enchantment enchantment = EnchantmentUtils.getByName(enchantmentName); if (enchantment == null) { - mcMMO.p.getLogger().warning("Skipping invalid enchantment in " + FILENAME + ": " + enchantmentName); + mcMMO.p.getLogger().info("Skipping invalid enchantment in '" + FILENAME + "', named:" + + enchantmentName); continue; } diff --git a/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java index 97967a131..bed8ed059 100755 --- a/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java @@ -6,6 +6,7 @@ import com.gmail.nossr50.datatypes.treasure.HylianTreasure; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.BlockUtils; import com.gmail.nossr50.util.LogUtils; +import com.gmail.nossr50.util.PotionUtil; import com.gmail.nossr50.util.text.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -14,7 +15,6 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionType; import java.io.IOException; @@ -165,22 +165,33 @@ public class TreasureConfig extends BukkitConfig { Material mat = Material.matchMaterial(materialName); if (mat == null) { reason.add("Potion format for " + FILENAME + " has changed"); + continue; } else { item = new ItemStack(mat, amount, data); - PotionMeta itemMeta = (PotionMeta) item.getItemMeta(); - - PotionType potionType = null; - try { - potionType = PotionType.valueOf(config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER")); - } catch (IllegalArgumentException ex) { - reason.add("Invalid Potion_Type: " + config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER")); + PotionMeta potionMeta = (PotionMeta) item.getItemMeta(); + if (potionMeta == null) { + mcMMO.p.getLogger().severe("Item meta when adding potion to treasure was null, contact the mcMMO devs!"); + reason.add("Item meta when adding potion to treasure was null, contact the mcMMO devs!"); + continue; } + + String potionTypeStr; + potionTypeStr = config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER"); boolean extended = config.getBoolean(type + "." + treasureName + ".PotionData.Extended", false); boolean upgraded = config.getBoolean(type + "." + treasureName + ".PotionData.Upgraded", false); - itemMeta.setBasePotionData(new PotionData(potionType, extended, upgraded)); + PotionType potionType = PotionUtil.matchPotionType(potionTypeStr, extended, upgraded); + + if (potionType == null) { + reason.add("Could not derive potion type from: " + potionTypeStr +", " + extended + ", " + upgraded); + continue; + } + + // Set the base potion type + // NOTE: extended/upgraded are ignored in 1.20.5 and later + PotionUtil.setBasePotionType(potionMeta, potionType, extended, upgraded); if (config.contains(type + "." + treasureName + ".Custom_Name")) { - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(type + "." + treasureName + ".Custom_Name"))); + potionMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(type + "." + treasureName + ".Custom_Name"))); } if (config.contains(type + "." + treasureName + ".Lore")) { @@ -188,9 +199,9 @@ public class TreasureConfig extends BukkitConfig { for (String s : config.getStringList(type + "." + treasureName + ".Lore")) { lore.add(ChatColor.translateAlternateColorCodes('&', s)); } - itemMeta.setLore(lore); + potionMeta.setLore(lore); } - item.setItemMeta(itemMeta); + item.setItemMeta(potionMeta); } } else if (material != null) { item = new ItemStack(material, amount, data); diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java index 6f8c397e3..36e6c784c 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java @@ -253,68 +253,26 @@ public class FlatFileDataProcessor { } public static @NotNull ExpectedType getExpectedValueType(int dataIndex) throws IndexOutOfBoundsException { - switch(dataIndex) { - case USERNAME_INDEX: - return ExpectedType.STRING; - case 2: //Assumption: Used to be for something, no longer used - case 3: //Assumption: Used to be for something, no longer used - case 23: //Assumption: Used to be used for something, no longer used - case 33: //Assumption: Used to be used for something, no longer used - case HEALTHBAR: - case LEGACY_LAST_LOGIN: - return ExpectedType.IGNORED; - case SKILLS_MINING: - case SKILLS_REPAIR: - case SKILLS_UNARMED: - case SKILLS_HERBALISM: - case SKILLS_EXCAVATION: - case SKILLS_ARCHERY: - case SKILLS_SWORDS: - case SKILLS_AXES: - case SKILLS_WOODCUTTING: - case SKILLS_ACROBATICS: - case SKILLS_TAMING: - case SKILLS_FISHING: - case SKILLS_ALCHEMY: - case SKILLS_CROSSBOWS: - case SKILLS_TRIDENTS: - case COOLDOWN_BERSERK: - case COOLDOWN_GIGA_DRILL_BREAKER: - case COOLDOWN_TREE_FELLER: - case COOLDOWN_GREEN_TERRA: - case COOLDOWN_SERRATED_STRIKES: - case COOLDOWN_SKULL_SPLITTER: - case COOLDOWN_SUPER_BREAKER: - case COOLDOWN_BLAST_MINING: - case SCOREBOARD_TIPS: - case COOLDOWN_CHIMAERA_WING: - case COOLDOWN_SUPER_SHOTGUN: - case COOLDOWN_TRIDENTS: - case COOLDOWN_ARCHERY: - return ExpectedType.INTEGER; - case EXP_MINING: - case EXP_WOODCUTTING: - case EXP_REPAIR: - case EXP_UNARMED: - case EXP_HERBALISM: - case EXP_EXCAVATION: - case EXP_ARCHERY: - case EXP_SWORDS: - case EXP_AXES: - case EXP_ACROBATICS: - case EXP_TAMING: - case EXP_FISHING: - case EXP_ALCHEMY: - case EXP_CROSSBOWS: - case EXP_TRIDENTS: - return ExpectedType.FLOAT; - case UUID_INDEX: - return ExpectedType.UUID; - case OVERHAUL_LAST_LOGIN: - return ExpectedType.LONG; - } - - throw new IndexOutOfBoundsException(); + return switch (dataIndex) { + case USERNAME_INDEX -> ExpectedType.STRING; //Assumption: Used to be for something, no longer used + //Assumption: Used to be for something, no longer used + //Assumption: Used to be used for something, no longer used + //Assumption: Used to be used for something, no longer used + case 2, 3, 23, 33, HEALTHBAR, LEGACY_LAST_LOGIN -> ExpectedType.IGNORED; + case SKILLS_MINING, SKILLS_REPAIR, SKILLS_UNARMED, SKILLS_HERBALISM, SKILLS_EXCAVATION, SKILLS_ARCHERY, + SKILLS_SWORDS, SKILLS_AXES, SKILLS_WOODCUTTING, SKILLS_ACROBATICS, SKILLS_TAMING, SKILLS_FISHING, + SKILLS_ALCHEMY, SKILLS_CROSSBOWS, SKILLS_TRIDENTS, SKILLS_MACES, COOLDOWN_BERSERK, + COOLDOWN_GIGA_DRILL_BREAKER, COOLDOWN_TREE_FELLER, COOLDOWN_GREEN_TERRA, COOLDOWN_SERRATED_STRIKES, + COOLDOWN_SKULL_SPLITTER, COOLDOWN_SUPER_BREAKER, COOLDOWN_BLAST_MINING, SCOREBOARD_TIPS, + COOLDOWN_CHIMAERA_WING, COOLDOWN_SUPER_SHOTGUN, COOLDOWN_TRIDENTS, COOLDOWN_ARCHERY, COOLDOWN_MACES -> + ExpectedType.INTEGER; + case EXP_MINING, EXP_WOODCUTTING, EXP_REPAIR, EXP_UNARMED, EXP_HERBALISM, EXP_EXCAVATION, EXP_ARCHERY, + EXP_SWORDS, EXP_AXES, EXP_ACROBATICS, EXP_TAMING, EXP_FISHING, EXP_ALCHEMY, EXP_CROSSBOWS, + EXP_TRIDENTS, EXP_MACES -> ExpectedType.FLOAT; + case UUID_INDEX -> ExpectedType.UUID; + case OVERHAUL_LAST_LOGIN -> ExpectedType.LONG; + default -> throw new IndexOutOfBoundsException(); + }; } public @NotNull List getFlatFileDataContainers() { diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java index d4d2e51b6..cd11065da 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java @@ -87,8 +87,11 @@ public final class FlatFileDatabaseManager implements DatabaseManager { public static final int COOLDOWN_SUPER_SHOTGUN = 49; public static final int COOLDOWN_TRIDENTS = 50; public static final int COOLDOWN_ARCHERY = 51; + public static final int EXP_MACES = 52; + public static final int SKILLS_MACES = 53; + public static final int COOLDOWN_MACES = 54; //Update this everytime new data is added - public static final int DATA_ENTRY_COUNT = COOLDOWN_ARCHERY + 1; + public static final int DATA_ENTRY_COUNT = COOLDOWN_MACES + 1; FlatFileDatabaseManager(@NotNull File usersFile, @NotNull Logger logger, long purgeTime, int startingLevel, boolean testing) { this.usersFile = usersFile; @@ -478,6 +481,18 @@ public final class FlatFileDatabaseManager implements DatabaseManager { appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.CROSSBOWS))).append(":"); appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.TRIDENTS))).append(":"); appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.TRIDENTS))).append(":"); + // public static final int COOLDOWN_SUPER_SHOTGUN = 49; + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SUPER_SHOTGUN))).append(":"); + // public static final int COOLDOWN_TRIDENTS = 50; + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.TRIDENTS_SUPER_ABILITY))).append(":"); + // public static final int COOLDOWN_ARCHERY = 51; + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.EXPLOSIVE_SHOT))).append(":"); + // public static final int EXP_MACES = 52; + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.MACES))).append(":"); + // public static final int SKILLS_MACES = 53; + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.MACES))).append(":"); + // public static final int COOLDOWN_MACES = 54; + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.MACES_SUPER_ABILITY))).append(":"); appendable.append("\r\n"); } @@ -987,6 +1002,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { List alchemy = new ArrayList<>(); List crossbows = new ArrayList<>(); List tridents = new ArrayList<>(); + List maces = new ArrayList<>(); BufferedReader in = null; String playerName = null; @@ -1022,6 +1038,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { powerLevel += putStat(woodcutting, playerName, skills.get(PrimarySkillType.WOODCUTTING)); powerLevel += putStat(crossbows, playerName, skills.get(PrimarySkillType.CROSSBOWS)); powerLevel += putStat(tridents, playerName, skills.get(PrimarySkillType.TRIDENTS)); + powerLevel += putStat(maces, playerName, skills.get(PrimarySkillType.MACES)); putStat(powerLevels, playerName, powerLevel); } @@ -1059,6 +1076,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { alchemy.sort(c); crossbows.sort(c); tridents.sort(c); + maces.sort(c); powerLevels.sort(c); playerStatHash.put(PrimarySkillType.MINING, mining); @@ -1076,6 +1094,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { playerStatHash.put(PrimarySkillType.ALCHEMY, alchemy); playerStatHash.put(PrimarySkillType.CROSSBOWS, crossbows); playerStatHash.put(PrimarySkillType.TRIDENTS, tridents); + playerStatHash.put(PrimarySkillType.MACES, maces); return LeaderboardStatus.UPDATED; } @@ -1239,6 +1258,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.ALCHEMY, EXP_ALCHEMY, username); tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.CROSSBOWS, EXP_CROSSBOWS, username); tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.TRIDENTS, EXP_TRIDENTS, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.MACES, EXP_MACES, username); // Taming - Unused tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SUPER_BREAKER, COOLDOWN_SUPER_BREAKER, username); @@ -1254,6 +1274,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.BLAST_MINING, COOLDOWN_BLAST_MINING, username); tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SUPER_SHOTGUN, COOLDOWN_SUPER_SHOTGUN, username); tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.TRIDENTS_SUPER_ABILITY, COOLDOWN_TRIDENTS, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.MACES_SUPER_ABILITY, COOLDOWN_MACES, username); UUID uuid; try { @@ -1343,6 +1364,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.ALCHEMY, SKILLS_ALCHEMY, username); tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.CROSSBOWS, SKILLS_CROSSBOWS, username); tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.TRIDENTS, SKILLS_TRIDENTS, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.MACES, SKILLS_MACES, username); return skills; } diff --git a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java index 892a43721..3525f7211 100644 --- a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java @@ -169,7 +169,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + "taming = 0 AND mining = 0 AND woodcutting = 0 AND repair = 0 " + "AND unarmed = 0 AND herbalism = 0 AND excavation = 0 AND " + "archery = 0 AND swords = 0 AND axes = 0 AND acrobatics = 0 " - + "AND fishing = 0 AND alchemy = 0 AND crossbows = 0 AND tridents = 0;"); + + "AND fishing = 0 AND alchemy = 0 AND crossbows = 0 AND tridents = 0 AND maces = 0;"); statement.executeUpdate("DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "experience`.`user_id` = `s`.`user_id`)"); statement.executeUpdate("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "huds`.`user_id` = `s`.`user_id`)"); @@ -291,7 +291,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + " taming = ?, mining = ?, repair = ?, woodcutting = ?" + ", unarmed = ?, herbalism = ?, excavation = ?" + ", archery = ?, swords = ?, axes = ?, acrobatics = ?" - + ", fishing = ?, alchemy = ?, crossbows = ?, tridents = ?, total = ? WHERE user_id = ?"); + + ", fishing = ?, alchemy = ?, crossbows = ?, tridents = ?, maces = ?, total = ? WHERE user_id = ?"); statement.setInt(1, profile.getSkillLevel(PrimarySkillType.TAMING)); statement.setInt(2, profile.getSkillLevel(PrimarySkillType.MINING)); statement.setInt(3, profile.getSkillLevel(PrimarySkillType.REPAIR)); @@ -307,11 +307,12 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setInt(13, profile.getSkillLevel(PrimarySkillType.ALCHEMY)); statement.setInt(14, profile.getSkillLevel(PrimarySkillType.CROSSBOWS)); statement.setInt(15, profile.getSkillLevel(PrimarySkillType.TRIDENTS)); + statement.setInt(16, profile.getSkillLevel(PrimarySkillType.MACES)); int total = 0; for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) total += profile.getSkillLevel(primarySkillType); - statement.setInt(16, total); - statement.setInt(17, id); + statement.setInt(17, total); + statement.setInt(18, id); success &= (statement.executeUpdate() != 0); statement.close(); if (!success) { @@ -323,7 +324,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + " taming = ?, mining = ?, repair = ?, woodcutting = ?" + ", unarmed = ?, herbalism = ?, excavation = ?" + ", archery = ?, swords = ?, axes = ?, acrobatics = ?" - + ", fishing = ?, alchemy = ?, crossbows = ?, tridents = ? WHERE user_id = ?"); + + ", fishing = ?, alchemy = ?, crossbows = ?, tridents = ?, maces = ? WHERE user_id = ?"); statement.setInt(1, profile.getSkillXpLevel(PrimarySkillType.TAMING)); statement.setInt(2, profile.getSkillXpLevel(PrimarySkillType.MINING)); statement.setInt(3, profile.getSkillXpLevel(PrimarySkillType.REPAIR)); @@ -339,7 +340,8 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setInt(13, profile.getSkillXpLevel(PrimarySkillType.ALCHEMY)); statement.setInt(14, profile.getSkillXpLevel(PrimarySkillType.CROSSBOWS)); statement.setInt(15, profile.getSkillXpLevel(PrimarySkillType.TRIDENTS)); - statement.setInt(16, id); + statement.setInt(16, profile.getSkillXpLevel(PrimarySkillType.MACES)); + statement.setInt(17, id); success &= (statement.executeUpdate() != 0); statement.close(); if (!success) { @@ -350,7 +352,8 @@ public final class SQLDatabaseManager implements DatabaseManager { statement = connection.prepareStatement("UPDATE " + tablePrefix + "cooldowns SET " + " mining = ?, woodcutting = ?, unarmed = ?" + ", herbalism = ?, excavation = ?, swords = ?" - + ", axes = ?, blast_mining = ?, chimaera_wing = ?, crossbows = ?, tridents = ? WHERE user_id = ?"); + + ", axes = ?, blast_mining = ?, chimaera_wing = ?, crossbows = ?" + + ", tridents = ?, maces = ? WHERE user_id = ?"); statement.setLong(1, profile.getAbilityDATS(SuperAbilityType.SUPER_BREAKER)); statement.setLong(2, profile.getAbilityDATS(SuperAbilityType.TREE_FELLER)); statement.setLong(3, profile.getAbilityDATS(SuperAbilityType.BERSERK)); @@ -362,7 +365,8 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setLong(9, profile.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS)); statement.setLong(10, profile.getAbilityDATS(SuperAbilityType.SUPER_SHOTGUN)); statement.setLong(11, profile.getAbilityDATS(SuperAbilityType.TRIDENTS_SUPER_ABILITY)); - statement.setInt(12, id); + statement.setLong(12, profile.getAbilityDATS(SuperAbilityType.MACES_SUPER_ABILITY)); + statement.setInt(13, id); success = (statement.executeUpdate() != 0); statement.close(); if (!success) { @@ -648,9 +652,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement = connection.prepareStatement( "SELECT " + - "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, s.crossbows, s.tridents, " + - "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, e.crossbows, e.tridents, " + - "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, c.crossbows, c.tridents, " + + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, s.crossbows, s.tridents, s.maces, " + + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, e.crossbows, e.tridents, e.maces, " + + "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, c.crossbows, c.tridents, c.maces, " + "h.mobhealthbar, h.scoreboardtips, u.uuid, u.`user` " + "FROM " + tablePrefix + "users u " + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " @@ -922,6 +926,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + "`chimaera_wing` int(32) unsigned NOT NULL DEFAULT '0'," + "`crossbows` int(32) unsigned NOT NULL DEFAULT '0'," + "`tridents` int(32) unsigned NOT NULL DEFAULT '0'," + + "`maces` int(32) unsigned NOT NULL DEFAULT '0'," + "PRIMARY KEY (`user_id`)) " + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); tryClose(createStatement); @@ -950,6 +955,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + "`alchemy` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," + "`crossbows` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," + "`tridents` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," + + "`maces` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," + "`total` int(10) unsigned NOT NULL DEFAULT "+totalLevel+"," + "PRIMARY KEY (`user_id`)) " + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); @@ -1017,20 +1023,24 @@ public final class SQLDatabaseManager implements DatabaseManager { tryClose(connection); } - String skills = "skills"; - String crossbows = "crossbows"; - String tridents = "tridents"; - String experience = "experience"; - String cooldowns = "cooldowns"; + final String skills = "skills"; + final String crossbows = "crossbows"; + final String tridents = "tridents"; + final String maces = "maces"; + final String experience = "experience"; + final String cooldowns = "cooldowns"; updateStructure(skills, crossbows, String.valueOf(32)); updateStructure(skills, tridents, String.valueOf(32)); + updateStructure(skills, maces, String.valueOf(32)); updateStructure(experience, crossbows, String.valueOf(10)); updateStructure(experience, tridents, String.valueOf(10)); + updateStructure(experience, maces, String.valueOf(10)); updateStructure(cooldowns, crossbows, String.valueOf(10)); updateStructure(cooldowns, tridents, String.valueOf(10)); + updateStructure(cooldowns, maces, String.valueOf(10)); } private void updateStructure(String tableName, String columnName, String columnSize) { @@ -1213,15 +1223,14 @@ public final class SQLDatabaseManager implements DatabaseManager { Map skillsXp = new EnumMap<>(PrimarySkillType.class); // Skill & XP Map skillsDATS = new EnumMap<>(SuperAbilityType.class); // Ability & Cooldown Map uniqueData = new EnumMap<>(UniqueDataType.class); //Chimaera wing cooldown and other misc info - MobHealthbarType mobHealthbarType; UUID uuid; int scoreboardTipsShown; final int OFFSET_SKILLS = 0; // TODO update these numbers when the query // changes (a new skill is added) - final int OFFSET_XP = 15; - final int OFFSET_DATS = 28; - final int OFFSET_OTHER = 41; + final int OFFSET_XP = 16; + final int OFFSET_DATS = 29; + final int OFFSET_OTHER = 42; skills.put(PrimarySkillType.TAMING, result.getInt(OFFSET_SKILLS + 1)); skills.put(PrimarySkillType.MINING, result.getInt(OFFSET_SKILLS + 2)); @@ -1238,6 +1247,7 @@ public final class SQLDatabaseManager implements DatabaseManager { skills.put(PrimarySkillType.ALCHEMY, result.getInt(OFFSET_SKILLS + 13)); skills.put(PrimarySkillType.CROSSBOWS, result.getInt(OFFSET_SKILLS + 14)); skills.put(PrimarySkillType.TRIDENTS, result.getInt(OFFSET_SKILLS + 15)); + skills.put(PrimarySkillType.MACES, result.getInt(OFFSET_SKILLS + 16)); skillsXp.put(PrimarySkillType.TAMING, result.getFloat(OFFSET_XP + 1)); skillsXp.put(PrimarySkillType.MINING, result.getFloat(OFFSET_XP + 2)); @@ -1254,6 +1264,7 @@ public final class SQLDatabaseManager implements DatabaseManager { skillsXp.put(PrimarySkillType.ALCHEMY, result.getFloat(OFFSET_XP + 13)); skillsXp.put(PrimarySkillType.CROSSBOWS, result.getFloat(OFFSET_XP + 14)); skillsXp.put(PrimarySkillType.TRIDENTS, result.getFloat(OFFSET_XP + 15)); + skillsXp.put(PrimarySkillType.MACES, result.getFloat(OFFSET_XP + 16)); // Taming - Unused - result.getInt(OFFSET_DATS + 1) skillsDATS.put(SuperAbilityType.SUPER_BREAKER, result.getInt(OFFSET_DATS + 2)); @@ -1270,6 +1281,7 @@ public final class SQLDatabaseManager implements DatabaseManager { uniqueData.put(UniqueDataType.CHIMAERA_WING_DATS, result.getInt(OFFSET_DATS + 13)); skillsDATS.put(SuperAbilityType.SUPER_SHOTGUN, result.getInt(OFFSET_DATS + 14)); skillsDATS.put(SuperAbilityType.TRIDENTS_SUPER_ABILITY, result.getInt(OFFSET_DATS + 15)); + skillsDATS.put(SuperAbilityType.MACES_SUPER_ABILITY, result.getInt(OFFSET_DATS + 16)); try { scoreboardTipsShown = result.getInt(OFFSET_OTHER + 2); diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java index 285c501fd..bc1c19cb6 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java @@ -56,67 +56,29 @@ public class FlatFileDataUtil { * @return the "zero" initialized data corresponding to the index */ public static @NotNull String getZeroInitialisedData(int index, int startingLevel) throws IndexOutOfBoundsException { - switch(index) { - case USERNAME_INDEX: - return LEGACY_INVALID_OLD_USERNAME; //We'll keep using this value for legacy compatibility reasons (not sure if needed but don't care) - case 2: //Assumption: Used to be for something, no longer used - case 3: //Assumption: Used to be for something, no longer used - case 23: //Assumption: Used to be used for something, no longer used - case 33: //Assumption: Used to be used for something, no longer used - case LEGACY_LAST_LOGIN: - case HEALTHBAR: - return "IGNORED"; - case SKILLS_MINING: - case SKILLS_REPAIR: - case SKILLS_UNARMED: - case SKILLS_HERBALISM: - case SKILLS_EXCAVATION: - case SKILLS_ARCHERY: - case SKILLS_SWORDS: - case SKILLS_AXES: - case SKILLS_WOODCUTTING: - case SKILLS_ACROBATICS: - case SKILLS_TAMING: - case SKILLS_FISHING: - case SKILLS_ALCHEMY: - case SKILLS_CROSSBOWS: - case SKILLS_TRIDENTS: - return String.valueOf(startingLevel); - case OVERHAUL_LAST_LOGIN: - return String.valueOf(-1L); - case COOLDOWN_BERSERK: - case COOLDOWN_GIGA_DRILL_BREAKER: - case COOLDOWN_TREE_FELLER: - case COOLDOWN_GREEN_TERRA: - case COOLDOWN_SERRATED_STRIKES: - case COOLDOWN_SKULL_SPLITTER: - case COOLDOWN_SUPER_BREAKER: - case COOLDOWN_BLAST_MINING: - case COOLDOWN_SUPER_SHOTGUN: - case COOLDOWN_TRIDENTS: - case COOLDOWN_ARCHERY: - case SCOREBOARD_TIPS: - case COOLDOWN_CHIMAERA_WING: - case EXP_MINING: - case EXP_WOODCUTTING: - case EXP_REPAIR: - case EXP_UNARMED: - case EXP_HERBALISM: - case EXP_EXCAVATION: - case EXP_ARCHERY: - case EXP_SWORDS: - case EXP_AXES: - case EXP_ACROBATICS: - case EXP_TAMING: - case EXP_FISHING: - case EXP_ALCHEMY: - case EXP_CROSSBOWS: - case EXP_TRIDENTS: - return "0"; - case UUID_INDEX: - throw new IndexOutOfBoundsException(); //TODO: Add UUID recovery? Might not even be worth it. - } + //TODO: Add UUID recovery? Might not even be worth it. + return switch (index) { + case USERNAME_INDEX -> + LEGACY_INVALID_OLD_USERNAME; //We'll keep using this value for legacy compatibility reasons (not sure if needed but don't care) + //Assumption: Used to be for something, no longer used + //Assumption: Used to be for something, no longer used + //Assumption: Used to be used for something, no longer used + //Assumption: Used to be used for something, no longer used + case 2, 3, 23, 33, LEGACY_LAST_LOGIN, HEALTHBAR -> "IGNORED"; + case SKILLS_MINING, SKILLS_REPAIR, SKILLS_UNARMED, SKILLS_HERBALISM, SKILLS_EXCAVATION, SKILLS_ARCHERY, + SKILLS_SWORDS, SKILLS_AXES, SKILLS_WOODCUTTING, SKILLS_ACROBATICS, SKILLS_TAMING, SKILLS_FISHING, + SKILLS_ALCHEMY, SKILLS_CROSSBOWS, SKILLS_TRIDENTS, SKILLS_MACES -> String.valueOf(startingLevel); + case OVERHAUL_LAST_LOGIN -> String.valueOf(-1L); + case COOLDOWN_BERSERK, COOLDOWN_GIGA_DRILL_BREAKER, COOLDOWN_TREE_FELLER, COOLDOWN_GREEN_TERRA, + COOLDOWN_SERRATED_STRIKES, COOLDOWN_SKULL_SPLITTER, COOLDOWN_SUPER_BREAKER, COOLDOWN_BLAST_MINING, + COOLDOWN_SUPER_SHOTGUN, COOLDOWN_TRIDENTS, COOLDOWN_ARCHERY, COOLDOWN_MACES, SCOREBOARD_TIPS, COOLDOWN_CHIMAERA_WING, + EXP_MINING, EXP_WOODCUTTING, EXP_REPAIR, EXP_UNARMED, EXP_HERBALISM, EXP_EXCAVATION, EXP_ARCHERY, + EXP_SWORDS, EXP_AXES, EXP_ACROBATICS, EXP_TAMING, EXP_FISHING, EXP_ALCHEMY, EXP_CROSSBOWS, + EXP_TRIDENTS, EXP_MACES -> "0"; + case UUID_INDEX -> + throw new IndexOutOfBoundsException(); //TODO: Add UUID recovery? Might not even be worth it. + default -> throw new IndexOutOfBoundsException(); + }; - throw new IndexOutOfBoundsException(); } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java index ea9b09f15..d2653718f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java @@ -32,6 +32,7 @@ import com.gmail.nossr50.skills.crossbows.CrossbowsManager; import com.gmail.nossr50.skills.excavation.ExcavationManager; import com.gmail.nossr50.skills.fishing.FishingManager; import com.gmail.nossr50.skills.herbalism.HerbalismManager; +import com.gmail.nossr50.skills.maces.MacesManager; import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.repair.RepairManager; import com.gmail.nossr50.skills.salvage.SalvageManager; @@ -220,6 +221,9 @@ public class McMMOPlayer implements Identified { case WOODCUTTING: skillManagers.put(primarySkillType, new WoodcuttingManager(this)); break; + case MACES: + skillManagers.put(primarySkillType, new MacesManager(this)); + break; default: throw new InvalidSkillException("The skill named has no manager! Contact the devs!"); } @@ -313,6 +317,10 @@ public class McMMOPlayer implements Identified { return (TridentsManager) skillManagers.get(PrimarySkillType.TRIDENTS); } + public MacesManager getMacesManager() { + return (MacesManager) skillManagers.get(PrimarySkillType.MACES); + } + public ExcavationManager getExcavationManager() { return (ExcavationManager) skillManagers.get(PrimarySkillType.EXCAVATION); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java index 9dfecd55b..31f315c1f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java @@ -20,6 +20,7 @@ public enum PrimarySkillType { EXCAVATION, FISHING, HERBALISM, + MACES, MINING, REPAIR, SALVAGE, diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java index 48910bb77..1cf028e88 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java @@ -57,6 +57,9 @@ public enum SubSkillType { HERBALISM_HYLIAN_LUCK, HERBALISM_SHROOM_THUMB, + /* Maces */ + MACES_MACES_LIMIT_BREAK(10), + /* Mining */ MINING_BIGGER_BOMBS(1), MINING_BLAST_MINING(8), diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java index f876ce53e..f83bce316 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java @@ -72,19 +72,26 @@ public enum SuperAbilityType { "Swords.Skills.SS.Other.Off", "Swords.SubSkill.SerratedStrikes.Name"), SUPER_SHOTGUN( - null, - null, - "Crossbows.Skills.SSG.Other.On", - "Crossbows.Skills.SSG.Refresh", - null, - "Crossbows.SubSkill.SuperShotgun.Name"), + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder"), TRIDENTS_SUPER_ABILITY( - "Tridents.Skills.TA.On", - "Tridents.Skills.TA.Off", - "Tridents.Skills.TA.Other.On", - "Tridents.Skills.TA.Refresh", - "Tridents.Skills.TA.Other.Off", - "Tridents.SubSkill.TridentAbility.Name"), + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder"), + MACES_SUPER_ABILITY( + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder"), /** * Has cooldown - but has to share a skill with Super Breaker, so needs special treatment @@ -209,6 +216,7 @@ public enum SuperAbilityType { case SUPER_SHOTGUN -> Permissions.superShotgun(player); case TREE_FELLER -> Permissions.treeFeller(player); case TRIDENTS_SUPER_ABILITY -> Permissions.tridentsSuper(player); + case MACES_SUPER_ABILITY -> Permissions.macesSuper(player); }; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/ToolType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/ToolType.java index dd61867d5..69422c1a2 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/ToolType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/ToolType.java @@ -13,7 +13,8 @@ public enum ToolType { SWORD("Swords.Ability.Lower", "Swords.Ability.Ready"), CROSSBOW("Crossbows.Ability.Lower", "Crossbows.Ability.Ready"), BOW("Archery.Ability.Lower", "Archery.Ability.Ready"), - TRIDENTS("Tridents.Ability.Lower", "Tridents.Ability.Ready"); + TRIDENTS("Tridents.Ability.Lower", "Tridents.Ability.Ready"), + MACES("Maces.Ability.Lower", "Maces.Ability.Ready"); private final String lowerTool; private final String raiseTool; @@ -45,6 +46,8 @@ public enum ToolType { return ItemUtils.isCrossbow(itemStack); case TRIDENTS: return ItemUtils.isTrident(itemStack); + case MACES: + return ItemUtils.isMace(itemStack); case FISTS: return itemStack.getType() == Material.AIR; diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java index c767004df..c2e2ee656 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java @@ -1,167 +1,120 @@ package com.gmail.nossr50.datatypes.skills.alchemy; -import com.gmail.nossr50.config.skills.alchemy.PotionConfig; -import org.bukkit.Color; +import com.gmail.nossr50.mcMMO; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.Potion; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.List; +import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; + +import static com.gmail.nossr50.util.PotionUtil.samePotionType; +import static java.util.Objects.requireNonNull; public class AlchemyPotion { - private final Material material; - private PotionData data; - private String name; - private List lore; - private List effects; - private Color color; - private Map children; + private final ItemStack potion; + private final Map alchemyPotionChildren; - public AlchemyPotion(Material material, PotionData data, String name, List lore, List effects, Color color, Map children) { - this.material = material; - this.data = data; - this.lore = lore; - this.name = name; - this.effects = effects; - this.children = children; - this.color = color; + public AlchemyPotion(ItemStack potion, Map alchemyPotionChildren) { + this.potion = requireNonNull(potion, "potion cannot be null"); + this.alchemyPotionChildren = requireNonNull(alchemyPotionChildren, "alchemyPotionChildren cannot be null"); } - public String toString() { - return "AlchemyPotion{" + data + ", " + name + ", Effects[" + effects.size() + "], Children[" + children.size() + "]}"; - } - - public ItemStack toItemStack(int amount) { - ItemStack potion = new ItemStack(material, amount); - PotionMeta meta = (PotionMeta) potion.getItemMeta(); - - meta.setBasePotionData(data); - if (this.getName() != null) { - meta.setDisplayName(this.getName()); - } - - if (this.getLore() != null && !this.getLore().isEmpty()) { - meta.setLore(this.getLore()); - } - - if (!this.getEffects().isEmpty()) { - for (PotionEffect effect : this.getEffects()) { - meta.addCustomEffect(effect, true); - } - } - - if (this.getColor() != null) { - meta.setColor(this.getColor()); - } - - potion.setItemMeta(meta); + public @NotNull ItemStack toItemStack(int amount) { + final ItemStack potion = new ItemStack(this.potion); + potion.setAmount(Math.max(1, amount)); return potion; } - public Material getMaterial() { - return material; + public Map getAlchemyPotionChildren() { + return alchemyPotionChildren; } - public Potion toPotion(int amount) { - return Potion.fromItemStack(this.toItemStack(amount)); - } - - public PotionData getData() { - return data; - } - - public void setData(PotionData data) { - this.data = data; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getLore() { - return lore; - } - - public void setLore(List lore) { - this.lore = lore; - } - - public List getEffects() { - return effects; - } - - public void setEffects(List effects) { - this.effects = effects; - } - - public Color getColor() { - return color; - } - - public void setColor(Color color) { - this.color = color; - } - - public Map getChildren() { - return children; - } - - public void setChildren(Map children) { - this.children = children; - } - - public AlchemyPotion getChild(ItemStack ingredient) { - if (!children.isEmpty()) { - for (Entry child : children.entrySet()) { + public @Nullable AlchemyPotion getChild(@NotNull ItemStack ingredient) { + if (!alchemyPotionChildren.isEmpty()) { + for (Entry child : alchemyPotionChildren.entrySet()) { if (ingredient.isSimilar(child.getKey())) { - return PotionConfig.getInstance().getPotion(child.getValue()); + return mcMMO.p.getPotionConfig().getPotion(child.getValue()); } } } return null; } - public boolean isSimilar(ItemStack item) { - if (item.getType() != material) { + public boolean isSimilarPotion(@NotNull ItemStack otherPotion) { + requireNonNull(otherPotion, "otherPotion cannot be null"); + // TODO: Investigate? + // We currently don't compare base potion effects, likely because they are derived from the potion type + if (otherPotion.getType() != potion.getType() || !otherPotion.hasItemMeta()) { return false; } - if (!item.hasItemMeta()) { - return false; - } - PotionMeta meta = (PotionMeta) item.getItemMeta(); - PotionData that = meta.getBasePotionData(); - if (data.getType() != that.getType()) { - return false; - } - if (data.isExtended() != that.isExtended()) { - return false; - } - if (data.isUpgraded() != that.isUpgraded()) { - return false; - } - for (PotionEffect effect : effects) { - if (!meta.hasCustomEffect(effect.getType())) { + + final PotionMeta otherPotionMeta = (PotionMeta) otherPotion.getItemMeta(); + + // all custom effects must be present + for (var effect : getAlchemyPotionMeta().getCustomEffects()) { + if (!otherPotionMeta.hasCustomEffect(effect.getType())) { return false; } } - if (!meta.hasLore() && !lore.isEmpty()) { + + if (!samePotionType(getAlchemyPotionMeta(), otherPotionMeta)) { return false; } - if (!(lore.isEmpty() && !meta.hasLore()) && !meta.getLore().equals(lore)) { + + if (!otherPotionMeta.hasLore() && getAlchemyPotionMeta().hasLore() + || !getAlchemyPotionMeta().hasLore() && otherPotionMeta.hasLore()) { return false; } - if (!meta.hasDisplayName() && name != null) { + + if (otherPotionMeta.hasLore() && getAlchemyPotionMeta().hasLore() + && !otherPotionMeta.getLore().equals(getAlchemyPotionMeta().getLore())) { return false; } - return (name == null && !meta.hasDisplayName()) || meta.getDisplayName().equals(name); + + if (!otherPotionMeta.hasDisplayName() && getAlchemyPotionMeta().hasDisplayName()) { + return false; + } + + var alchemyPotionName = getAlchemyPotionMeta().hasDisplayName() ? getAlchemyPotionMeta().getDisplayName() : null; + + return (alchemyPotionName == null && !otherPotionMeta.hasDisplayName()) || otherPotionMeta.getDisplayName().equals(alchemyPotionName); + } + + public PotionMeta getAlchemyPotionMeta() { + return (PotionMeta) potion.getItemMeta(); + } + + public boolean isSplash() { + return potion.getType() == Material.SPLASH_POTION; + } + + public boolean isLingering() { + return potion.getType() == Material.LINGERING_POTION; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AlchemyPotion that = (AlchemyPotion) o; + return Objects.equals(potion, that.potion) && Objects.equals(alchemyPotionChildren, that.alchemyPotionChildren); + } + + @Override + public int hashCode() { + return Objects.hash(potion, alchemyPotionChildren); + } + + @Override + public String toString() { + return "AlchemyPotion{" + + "potion=" + potion + + ", alchemyPotionChildren=" + alchemyPotionChildren + + '}'; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java index fe2778eed..4515835d1 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java @@ -1,11 +1,10 @@ package com.gmail.nossr50.datatypes.skills.alchemy; -import org.bukkit.Material; -import org.bukkit.potion.PotionData; +import com.gmail.nossr50.util.PotionUtil; +import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionType; -import java.util.List; +import static com.gmail.nossr50.util.PotionUtil.*; public enum PotionStage { FIVE(5), @@ -43,27 +42,27 @@ public enum PotionStage { return potionStage; } - private static boolean isWaterBottle(AlchemyPotion input) { - return input.getData().getType() == PotionType.WATER; + private static boolean isWaterBottle(AlchemyPotion alchemyPotion) { + return isPotionTypeWater(alchemyPotion.getAlchemyPotionMeta()); } public static PotionStage getPotionStage(AlchemyPotion alchemyPotion) { - PotionData data = alchemyPotion.getData(); - List effects = alchemyPotion.getEffects(); + final PotionMeta potionMeta = alchemyPotion.getAlchemyPotionMeta(); int stage = 1; // Check if potion has an effect of any sort - if (data.getType().getEffectType() != null || !effects.isEmpty()) { + if (!potionMeta.getCustomEffects().isEmpty() + || PotionUtil.hasBasePotionEffects(potionMeta)) { stage++; } // Check if potion has a glowstone dust amplifier // Else check if the potion has a custom effect with an amplifier added by mcMMO - if (data.isUpgraded()) { + if (isStrong(potionMeta)) { stage++; - } else if(!effects.isEmpty()) { - for (PotionEffect effect : effects){ + } else if (!potionMeta.getCustomEffects().isEmpty()) { + for (PotionEffect effect : potionMeta.getCustomEffects()){ if(effect.getAmplifier() > 0){ stage++; break; @@ -72,12 +71,12 @@ public enum PotionStage { } // Check if potion has a redstone dust amplifier - if (data.isExtended()) { + if (isLong(potionMeta)) { stage++; } // Check if potion has a gunpowder amplifier - if (alchemyPotion.getMaterial() == Material.SPLASH_POTION || alchemyPotion.getMaterial() == Material.LINGERING_POTION) { + if (alchemyPotion.isSplash() || alchemyPotion.isLingering()) { stage++; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java index 15ea49679..1ea4692a0 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java @@ -26,7 +26,6 @@ import net.kyori.adventure.text.TextComponent; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.SoundCategory; -import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventPriority; @@ -317,7 +316,7 @@ public class Roll extends AcrobaticsSubSkill { ItemStack boots = player.getInventory().getBoots(); float xp = (float) (damage * (isRoll ? ExperienceConfig.getInstance().getRollXPModifier() : ExperienceConfig.getInstance().getFallXPModifier())); - if (boots != null && boots.containsEnchantment(Enchantment.PROTECTION_FALL)) { + if (boots != null && boots.containsEnchantment(mcMMO.p.getEnchantmentMapper().getFeatherFalling())) { xp *= ExperienceConfig.getInstance().getFeatherFallXPModifier(); } diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index 18edee783..d309669fc 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -120,7 +120,7 @@ public class EntityListener implements Listener { if (bow == null) return; - if (bow.containsEnchantment(Enchantment.ARROW_INFINITE)) { + if (bow.containsEnchantment(mcMMO.p.getEnchantmentMapper().getInfinity())) { projectile.setMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); } diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index a8c1c8601..3a806e8be 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -78,8 +78,6 @@ import java.util.ArrayList; import java.util.List; public class mcMMO extends JavaPlugin { - - /* Managers & Services */ private static PlatformManager platformManager; private static MetadataService metadataService; @@ -140,21 +138,14 @@ public class mcMMO extends JavaPlugin { private GeneralConfig generalConfig; private AdvancedConfig advancedConfig; private PartyConfig partyConfig; + private PotionConfig potionConfig; private CustomItemSupportConfig customItemSupportConfig; + private EnchantmentMapper enchantmentMapper; + private AttributeMapper attributeMapper; private FoliaLib foliaLib; private PartyManager partyManager; -// private RepairConfig repairConfig; -// private SalvageConfig salvageConfig; -// private PersistentDataConfig persistentDataConfig; -// private ChatConfig chatConfig; -// private CoreSkillsConfig coreSkillsConfig; -// private RankConfig rankConfig; -// private TreasureConfig treasureConfig; -// private FishingTreasureConfig fishingTreasureConfig; -// private SoundConfig soundConfig; - public mcMMO() { p = this; } @@ -207,8 +198,11 @@ public class mcMMO extends JavaPlugin { modManager = new ModManager(); - //Init Material Maps + // Init Material Maps materialMapStore = new MaterialMapStore(); + // Init compatibility mappers + enchantmentMapper = new EnchantmentMapper(this); + attributeMapper = new AttributeMapper(this); loadConfigFiles(); @@ -567,7 +561,11 @@ public class mcMMO extends JavaPlugin { FishingTreasureConfig.getInstance(); HiddenConfig.getInstance(); mcMMO.p.getAdvancedConfig(); - PotionConfig.getInstance(); + + // init potion config + potionConfig = new PotionConfig(); + potionConfig.loadPotions(); + CoreSkillsConfig.getInstance(); SoundConfig.getInstance(); RankConfig.getInstance(); @@ -812,6 +810,18 @@ public class mcMMO extends JavaPlugin { return customItemSupportConfig; } + public PotionConfig getPotionConfig() { + return potionConfig; + } + + public EnchantmentMapper getEnchantmentMapper() { + return enchantmentMapper; + } + + public AttributeMapper getAttributeMapper() { + return attributeMapper; + } + public @NotNull FoliaLib getFoliaLib() { return foliaLib; } diff --git a/src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java b/src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java index f1d1e9471..a6734a53e 100644 --- a/src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java +++ b/src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java @@ -1,7 +1,6 @@ package com.gmail.nossr50.metadata; import com.gmail.nossr50.mcMMO; -import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataContainer; @@ -74,12 +73,12 @@ public class ItemMetadataService { if(itemMeta != null) { //TODO: can be optimized - if (itemMeta.hasEnchant(Enchantment.DIG_SPEED)) { - itemMeta.removeEnchant(Enchantment.DIG_SPEED); + if (itemMeta.hasEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency())) { + itemMeta.removeEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency()); } if (originalSpeed > 0) { - itemMeta.addEnchant(Enchantment.DIG_SPEED, originalSpeed, true); + itemMeta.addEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency(), originalSpeed, true); } PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer(); diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java index 16b1dd2ac..4224ad123 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java @@ -1,13 +1,13 @@ package com.gmail.nossr50.skills.alchemy; import com.gmail.nossr50.config.experience.ExperienceConfig; -import com.gmail.nossr50.config.skills.alchemy.PotionConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.experience.XPGainSource; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.alchemy.PotionStage; +import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.SkillManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.StringUtils; @@ -27,7 +27,7 @@ public class AlchemyManager extends SkillManager { } public List getIngredients() { - return PotionConfig.getInstance().getIngredients(getTier()); + return mcMMO.p.getPotionConfig().getIngredients(getTier()); } public String getIngredientList() { diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index 2a11b0159..a41ea2f2f 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -1,6 +1,5 @@ package com.gmail.nossr50.skills.alchemy; -import com.gmail.nossr50.config.skills.alchemy.PotionConfig; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion; import com.gmail.nossr50.datatypes.skills.alchemy.PotionStage; @@ -36,7 +35,7 @@ public final class AlchemyPotionBrewer { continue; } - if (getChildPotion(PotionConfig.getInstance().getPotion(contents[i]), contents[Alchemy.INGREDIENT_SLOT]) != null) { + if (getChildPotion(mcMMO.p.getPotionConfig().getPotion(contents[i]), contents[Alchemy.INGREDIENT_SLOT]) != null) { return true; } } @@ -94,12 +93,11 @@ public final class AlchemyPotionBrewer { } private static List getValidIngredients(Player player) { - if(player == null || UserManager.getPlayer(player) == null) - { - return PotionConfig.getInstance().getIngredients(1); + if(player == null || UserManager.getPlayer(player) == null) { + return mcMMO.p.getPotionConfig().getIngredients(1); } - return PotionConfig.getInstance().getIngredients(!Permissions.isSubSkillEnabled(player, SubSkillType.ALCHEMY_CONCOCTIONS) ? 1 : UserManager.getPlayer(player).getAlchemyManager().getTier()); + return mcMMO.p.getPotionConfig().getIngredients(!Permissions.isSubSkillEnabled(player, SubSkillType.ALCHEMY_CONCOCTIONS) ? 1 : UserManager.getPlayer(player).getAlchemyManager().getTier()); } public static void finishBrewing(BlockState brewingStand, Player player, boolean forced) { @@ -120,11 +118,11 @@ public final class AlchemyPotionBrewer { for (int i = 0; i < 3; i++) { ItemStack item = inventory.getItem(i); - if (isEmpty(item) || item.getType() == Material.GLASS_BOTTLE || !PotionConfig.getInstance().isValidPotion(item)) { + if (isEmpty(item) || item.getType() == Material.GLASS_BOTTLE || !mcMMO.p.getPotionConfig().isValidPotion(item)) { continue; } - AlchemyPotion input = PotionConfig.getInstance().getPotion(item); + AlchemyPotion input = mcMMO.p.getPotionConfig().getPotion(item); AlchemyPotion output = input.getChild(ingredient); inputList.set(i, input); diff --git a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java index 7cc028e8f..16237f548 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java @@ -18,7 +18,8 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; + +import static com.gmail.nossr50.util.PotionEffectMapper.getNausea; public class ArcheryManager extends SkillManager { public ArcheryManager(McMMOPlayer mcMMOPlayer) { @@ -95,10 +96,8 @@ public class ArcheryManager extends SkillManager { Location dazedLocation = defender.getLocation(); dazedLocation.setPitch(90 - Misc.getRandom().nextInt(181)); -// defender.teleport(dazedLocation); mcMMO.p.getFoliaLib().getImpl().teleportAsync(defender, dazedLocation); - defender.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 20 * 10, 10)); - + defender.addPotionEffect(new PotionEffect(getNausea(), 20 * 10, 10)); if (NotificationManager.doesPlayerUseNotifications(defender)) { NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Combat.TouchedFuzzy"); diff --git a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java index 6063add73..5d0e24314 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java @@ -573,11 +573,13 @@ public class FishingManager extends SkillManager { int luck; if (getPlayer().getInventory().getItemInMainHand().getType() == Material.FISHING_ROD) { - luck = getPlayer().getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.LUCK); + luck = getPlayer().getInventory().getItemInMainHand().getEnchantmentLevel( + mcMMO.p.getEnchantmentMapper().getLuckOfTheSea()); } else { // We know something was caught, so if the rod wasn't in the main hand it must be in the offhand - luck = getPlayer().getInventory().getItemInOffHand().getEnchantmentLevel(Enchantment.LUCK); + luck = getPlayer().getInventory().getItemInOffHand().getEnchantmentLevel( + mcMMO.p.getEnchantmentMapper().getLuckOfTheSea()); } // Rather than subtracting luck (and causing a minimum 3% chance for every drop), scale by luck. diff --git a/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java new file mode 100644 index 000000000..194c1400b --- /dev/null +++ b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java @@ -0,0 +1,21 @@ +package com.gmail.nossr50.skills.maces; + +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.datatypes.skills.ToolType; +import com.gmail.nossr50.skills.SkillManager; +import com.gmail.nossr50.util.Permissions; + +public class MacesManager extends SkillManager { + public MacesManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.MACES); + } + + /** + * Checks if the player can activate the Super Ability for Maces + * @return true if the player can activate the Super Ability, false otherwise + */ + public boolean canActivateAbility() { + return mmoPlayer.getToolPreparationMode(ToolType.MACES) && Permissions.macesSuper(getPlayer()); + } +} diff --git a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java index dcee2e0bd..cd793aa71 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java @@ -233,7 +233,7 @@ public class TamingManager extends SkillManager { // Bred mules & donkeys can actually have horse-like stats, but llamas cannot. if (beast instanceof AbstractHorse horseLikeCreature && !(beast instanceof Llama)) { - AttributeInstance jumpAttribute = horseLikeCreature.getAttribute(Attribute.HORSE_JUMP_STRENGTH); + AttributeInstance jumpAttribute = horseLikeCreature.getAttribute(mcMMO.p.getAttributeMapper().getHorseJumpStrength()); if(jumpAttribute != null) { double jumpStrength = jumpAttribute.getValue(); diff --git a/src/main/java/com/gmail/nossr50/util/AttributeMapper.java b/src/main/java/com/gmail/nossr50/util/AttributeMapper.java new file mode 100644 index 000000000..2d15d55bd --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/AttributeMapper.java @@ -0,0 +1,45 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.Registry; +import org.bukkit.attribute.Attribute; + +public class AttributeMapper { + private final mcMMO pluginRef; + private static final String GENERIC_JUMP_STRENGTH = "generic.jump_strength"; + private static final String HORSE_JUMP_STRENGTH = "horse.jump_strength"; + private final Attribute horseJumpStrength; + + public AttributeMapper(mcMMO pluginRef) { + this.pluginRef = pluginRef; + this.horseJumpStrength = initHorseJumpStrength(); + } + + private Attribute initHorseJumpStrength() { + // TODO: Use modern matching? +// if (Registry.ATTRIBUTE.match(GENERIC_JUMP_STRENGTH) != null) { +// return Registry.ATTRIBUTE.match(GENERIC_JUMP_STRENGTH); +// } +// +// if (Registry.ATTRIBUTE.match(HORSE_JUMP_STRENGTH) != null) { +// return Registry.ATTRIBUTE.match(HORSE_JUMP_STRENGTH); +// } + + for (Attribute attr : Registry.ATTRIBUTE) { + if (attr.getKey().getKey().equalsIgnoreCase(HORSE_JUMP_STRENGTH) + || attr.getKey().getKey().equalsIgnoreCase(GENERIC_JUMP_STRENGTH) + || attr.name().equalsIgnoreCase(HORSE_JUMP_STRENGTH) + || attr.name().equalsIgnoreCase(GENERIC_JUMP_STRENGTH)) { + return attr; + } + } + + pluginRef.getLogger().severe("Unable to find the Generic Jump Strength or Horse Jump Strength attribute, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Generic Jump Strength or Horse Jump Strength attribute"); + } + + public Attribute getHorseJumpStrength() { + return horseJumpStrength; + } +} diff --git a/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java b/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java new file mode 100644 index 000000000..798ad289e --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java @@ -0,0 +1,149 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.Registry; +import org.bukkit.enchantments.Enchantment; + +public class EnchantmentMapper { + private final mcMMO pluginRef; + private final Enchantment efficiency; + private final Enchantment unbreaking; + private final Enchantment infinity; + private final Enchantment featherFalling; + private final Enchantment luckOfTheSea; + + public EnchantmentMapper(mcMMO pluginRef) { + this.pluginRef = pluginRef; + this.efficiency = initEfficiency(); + this.unbreaking = initUnbreaking(); + this.infinity = initInfinity(); + this.featherFalling = initFeatherFalling(); + this.luckOfTheSea = initLuckOfTheSea(); + } + + private Enchantment initLuckOfTheSea() { + // TODO: Make use of match if present +// if (Registry.ENCHANTMENT.match("luck_of_the_sea") != null) { +// return Registry.ENCHANTMENT.match("luck_of_the_sea"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("LUCK_OF_THE_SEA") + || enchantment.getKey().getKey().equalsIgnoreCase("LUCK") + || enchantment.getName().equalsIgnoreCase("LUCK_OF_THE_SEA") + || enchantment.getName().equalsIgnoreCase("LUCK")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Luck of the Sea enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Luck of the Sea enchantment"); + } + + private Enchantment initFeatherFalling() { +// if (Registry.ENCHANTMENT.match("feather_falling") != null) { +// return Registry.ENCHANTMENT.match("feather_falling"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("FEATHER_FALLING") + || enchantment.getKey().getKey().equalsIgnoreCase("PROTECTION_FALL") + || enchantment.getName().equalsIgnoreCase("FEATHER_FALLING") + || enchantment.getName().equalsIgnoreCase("PROTECTION_FALL")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Feather Falling enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Feather Falling enchantment"); + } + + private Enchantment initInfinity() { +// if(Registry.ENCHANTMENT.match("infinity") != null) { +// return Registry.ENCHANTMENT.match("infinity"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("INFINITY") + || enchantment.getKey().getKey().equalsIgnoreCase("ARROW_INFINITE") + || enchantment.getName().equalsIgnoreCase("INFINITY") + || enchantment.getName().equalsIgnoreCase("ARROW_INFINITE")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Infinity enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Infinity enchantment"); + } + + private Enchantment initEfficiency() { +// if (Registry.ENCHANTMENT.match("efficiency") != null) { +// return Registry.ENCHANTMENT.match("efficiency"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("EFFICIENCY") + || enchantment.getKey().getKey().equalsIgnoreCase("DIG_SPEED") + || enchantment.getName().equalsIgnoreCase("EFFICIENCY") + || enchantment.getName().equalsIgnoreCase("DIG_SPEED")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Efficiency enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Efficiency enchantment"); + } + + private Enchantment initUnbreaking() { +// if (Registry.ENCHANTMENT.match("unbreaking") != null) { +// return Registry.ENCHANTMENT.match("unbreaking"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("UNBREAKING") + || enchantment.getKey().getKey().equalsIgnoreCase("DURABILITY") + || enchantment.getName().equalsIgnoreCase("UNBREAKING") + || enchantment.getName().equalsIgnoreCase("DURABILITY")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Unbreaking enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Unbreaking enchantment"); + } + + /** + * Get the efficiency enchantment + * + * @return The efficiency enchantment + */ + public Enchantment getEfficiency() { + return efficiency; + } + + public Enchantment getUnbreaking() { + return unbreaking; + } + + public Enchantment getInfinity() { + return infinity; + } + + public Enchantment getFeatherFalling() { + return featherFalling; + } + + public Enchantment getLuckOfTheSea() { + return luckOfTheSea; + } +} diff --git a/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java b/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java index 6aab49b3d..9e0850ed7 100644 --- a/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java @@ -1,39 +1,34 @@ package com.gmail.nossr50.util; import org.bukkit.enchantments.Enchantment; +import org.jetbrains.annotations.Nullable; import java.util.HashMap; public class EnchantmentUtils { - private static final HashMap enchants = new HashMap<>(); + private static final HashMap legacyEnchantments = new HashMap<>(); static { - enchants.put("SHARPNESS", Enchantment.DAMAGE_ALL); - enchants.put("POWER", Enchantment.ARROW_DAMAGE); - enchants.put("FIRE_PROTECTION", Enchantment.PROTECTION_FIRE); - enchants.put("FEATHER_FALLING", Enchantment.PROTECTION_FALL); - enchants.put("PROTECTION", Enchantment.PROTECTION_ENVIRONMENTAL); - enchants.put("BLAST_PROTECTION", Enchantment.PROTECTION_EXPLOSIONS); - enchants.put("PROJECTILE_PROTECTION", Enchantment.PROTECTION_PROJECTILE); - enchants.put("RESPIRATION", Enchantment.OXYGEN); - enchants.put("INFINITY", Enchantment.ARROW_INFINITE); - enchants.put("AQUA_AFFINITY", Enchantment.WATER_WORKER); - enchants.put("UNBREAKING", Enchantment.DURABILITY); - enchants.put("SMITE", Enchantment.DAMAGE_UNDEAD); - enchants.put("BANE_OF_ARTHROPODS", Enchantment.DAMAGE_ARTHROPODS); - enchants.put("EFFICIENCY", Enchantment.DIG_SPEED); - enchants.put("FIRE_ASPECT", Enchantment.FIRE_ASPECT); - enchants.put("SILK_TOUCH", Enchantment.SILK_TOUCH); - enchants.put("FORTUNE", Enchantment.LOOT_BONUS_BLOCKS); - enchants.put("LOOTING", Enchantment.LOOT_BONUS_MOBS); - enchants.put("PUNCH", Enchantment.ARROW_KNOCKBACK); - enchants.put("FLAME", Enchantment.ARROW_FIRE); - enchants.put("KNOCKBACK", Enchantment.KNOCKBACK); - enchants.put("THORNS", Enchantment.THORNS); - enchants.put("MENDING", Enchantment.MENDING); - enchants.put("DEPTH_STRIDER", Enchantment.DEPTH_STRIDER); - enchants.put("FROST_WALKER", Enchantment.FROST_WALKER); + // backwards compatibility for looking up legacy bukkit enums + addLegacyEnchantmentLookup("SHARPNESS", "DAMAGE_ALL"); + addLegacyEnchantmentLookup("POWER", "ARROW_DAMAGE"); + addLegacyEnchantmentLookup("FIRE_PROTECTION", "PROTECTION_FIRE"); + addLegacyEnchantmentLookup("FEATHER_FALLING", "PROTECTION_FALL"); + addLegacyEnchantmentLookup("PROTECTION", "PROTECTION_ENVIRONMENTAL"); + addLegacyEnchantmentLookup("BLAST_PROTECTION", "PROTECTION_EXPLOSIONS"); + addLegacyEnchantmentLookup("PROJECTILE_PROTECTION", "PROTECTION_PROJECTILE"); + addLegacyEnchantmentLookup("RESPIRATION", "OXYGEN"); + addLegacyEnchantmentLookup("INFINITY", "ARROW_INFINITE"); + addLegacyEnchantmentLookup("AQUA_AFFINITY", "WATER_WORKER"); + addLegacyEnchantmentLookup("UNBREAKING", "DURABILITY"); + addLegacyEnchantmentLookup("SMITE", "DAMAGE_UNDEAD"); + addLegacyEnchantmentLookup("BANE_OF_ARTHROPODS", "DAMAGE_ARTHROPODS"); + addLegacyEnchantmentLookup("EFFICIENCY", "DIG_SPEED"); + addLegacyEnchantmentLookup("FORTUNE", "LOOT_BONUS_BLOCKS"); + addLegacyEnchantmentLookup("LOOTING", "LOOT_BONUS_MOBS"); + addLegacyEnchantmentLookup("PUNCH", "ARROW_KNOCKBACK"); + addLegacyEnchantmentLookup("FLAME", "ARROW_FIRE"); } /** @@ -43,11 +38,19 @@ public class EnchantmentUtils { * * @return Enchantment or null if no enchantment was found */ - public static Enchantment getByName(String enchantmentName) { - if (enchants.containsKey(enchantmentName)) { - return enchants.get(enchantmentName); + @SuppressWarnings("deprecation") + public static @Nullable Enchantment getByName(String enchantmentName) { + if (legacyEnchantments.containsKey(enchantmentName)) { + return legacyEnchantments.get(enchantmentName); } return Enchantment.getByName(enchantmentName); } + + @SuppressWarnings("deprecation") + private static void addLegacyEnchantmentLookup(String enchantmentName, String legacyBukkitName) { + if (Enchantment.getByName(legacyBukkitName) != null) { + legacyEnchantments.put(enchantmentName, Enchantment.getByName(legacyBukkitName)); + } + } } diff --git a/src/main/java/com/gmail/nossr50/util/ItemUtils.java b/src/main/java/com/gmail/nossr50/util/ItemUtils.java index 6055582e3..2b7cccc48 100644 --- a/src/main/java/com/gmail/nossr50/util/ItemUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ItemUtils.java @@ -23,6 +23,8 @@ import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; +import static java.util.Objects.requireNonNull; + public final class ItemUtils { /** * This is a static utility class, therefore we don't want any instances of @@ -41,6 +43,37 @@ public final class ItemUtils { return mcMMO.getMaterialMapStore().isBow(item.getType().getKey().getKey()); } + /** + * Exhaustive lookup for a Material by name. + *

+ * This method will first try a normal lookup, then a legacy lookup, then a lookup by ENUM name, + * and finally a lookup by ENUM name with legacy name. + * @param materialName The name of the material to lookup + * @return The Material if found, or null if not found + */ + public static @Nullable Material exhaustiveMaterialLookup(@NotNull String materialName) { + requireNonNull(materialName, "materialName cannot be null"); + + // First try a normal lookup + Material material = Material.matchMaterial(materialName); + + // If that fails, try a legacy lookup + if (material == null) { + material = Material.matchMaterial(materialName, true); + } + + // try to match to Material ENUM + if (material == null) { + material = Material.getMaterial(materialName.toUpperCase()); + } + + // try to match to Material ENUM with legacy name + if (material == null) { + material = Material.getMaterial(materialName.toUpperCase(), true); + } + return material; + } + /** * Checks if a player has an item in their inventory or offhand. * @@ -100,6 +133,10 @@ public final class ItemUtils { return mcMMO.getMaterialMapStore().isTrident(item.getType().getKey().getKey()); } + public static boolean isMace(@NotNull ItemStack item) { + return mcMMO.getMaterialMapStore().isMace(item.getType().getKey().getKey()); + } + public static boolean hasItemInEitherHand(@NotNull Player player, Material material) { return player.getInventory().getItemInMainHand().getType() == material || player.getInventory().getItemInOffHand().getType() == material; } @@ -681,7 +718,8 @@ public final class ItemUtils { if(itemMeta == null) return; - itemMeta.addEnchant(Enchantment.DIG_SPEED, existingEnchantLevel + mcMMO.p.getAdvancedConfig().getEnchantBuff(), true); + itemMeta.addEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency(), + existingEnchantLevel + mcMMO.p.getAdvancedConfig().getEnchantBuff(), true); itemStack.setItemMeta(itemMeta); } diff --git a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java index b0f623602..a0ad84326 100644 --- a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java +++ b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java @@ -50,6 +50,7 @@ public class MaterialMapStore { private final @NotNull HashSet crossbows; private final @NotNull HashSet tools; private final @NotNull HashSet enchantables; + private final @NotNull HashSet maces; private final @NotNull HashSet ores; private final @NotNull HashSet intendedToolPickAxe; @@ -97,6 +98,7 @@ public class MaterialMapStore { shovels = new HashSet<>(); hoes = new HashSet<>(); tridents = new HashSet<>(); + maces = new HashSet<>(); enchantables = new HashSet<>(); @@ -453,6 +455,7 @@ public class MaterialMapStore { enchantables.addAll(tridents); enchantables.addAll(bows); enchantables.addAll(crossbows); + enchantables.addAll(maces); enchantables.add("shears"); enchantables.add("fishing_rod"); @@ -476,6 +479,7 @@ public class MaterialMapStore { fillHoes(); fillShovels(); fillTridents(); + fillMaces(); fillStringTools(); fillBows(); fillCrossbows(); @@ -491,6 +495,7 @@ public class MaterialMapStore { tools.addAll(stringTools); tools.addAll(bows); tools.addAll(crossbows); + tools.addAll(maces); } private void fillBows() { @@ -507,6 +512,10 @@ public class MaterialMapStore { stringTools.add("carrot_on_a_stick"); } + private void fillMaces() { + maces.add("mace"); + } + private void fillTridents() { tridents.add("trident"); } @@ -824,6 +833,14 @@ public class MaterialMapStore { return tridents.contains(id); } + public boolean isMace(@NotNull Material material) { + return isMace(material.getKey().getKey()); + } + + public boolean isMace(@NotNull String id) { + return maces.contains(id); + } + public boolean isLeatherArmor(@NotNull Material material) { return isLeatherArmor(material.getKey().getKey()); } diff --git a/src/main/java/com/gmail/nossr50/util/Permissions.java b/src/main/java/com/gmail/nossr50/util/Permissions.java index 6dcd9b800..5a78bcf18 100644 --- a/src/main/java/com/gmail/nossr50/util/Permissions.java +++ b/src/main/java/com/gmail/nossr50/util/Permissions.java @@ -246,6 +246,14 @@ public final class Permissions { } public static boolean tridentsLimitBreak(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.tridents.superability"); } + /* MACES */ + public static boolean macesSuper(Permissible permissible) { + // TODO: When a super is added, change this + return false; + } + + public static boolean macesLimitBreak(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.maces.limitbreak"); } + /* * PARTY */ diff --git a/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java b/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java new file mode 100644 index 000000000..ea070814d --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java @@ -0,0 +1,6 @@ +package com.gmail.nossr50.util; + +public enum PotionCompatibilityType { + PRE_1_20_5, + POST_1_20_5 +} diff --git a/src/main/java/com/gmail/nossr50/util/PotionEffectMapper.java b/src/main/java/com/gmail/nossr50/util/PotionEffectMapper.java new file mode 100644 index 000000000..f58c66834 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/PotionEffectMapper.java @@ -0,0 +1,142 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.potion.PotionEffectType; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +final public class PotionEffectMapper { + private static final PotionEffectType haste; + private static final PotionEffectType nausea; + private static final Method potionEffectTypeWrapperGetPotionEffectType; + private static final Class classPotionEffectTypeWrapper; + + private PotionEffectMapper() { + // Utility class + } + + static { + potionEffectTypeWrapperGetPotionEffectType = getPotionEffectTypeWrapperGetPotionEffectType(); + classPotionEffectTypeWrapper = getClassPotionEffectTypeWrapper(); + + haste = initHaste(); + nausea = initNausea(); + } + + private static Method getPotionEffectTypeWrapperGetPotionEffectType() { + try { + return classPotionEffectTypeWrapper.getMethod("getType"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Class getClassPotionEffectTypeWrapper() { + try { + return Class.forName("org.bukkit.potion.PotionEffectTypeWrapper"); + } catch (ClassNotFoundException e) { + return null; + } + } + + private static PotionEffectType initNausea() { + if (classPotionEffectTypeWrapper != null) { + return getNauseaLegacy(); + } else { + return getNauseaModern(); + } + } + + private static PotionEffectType getNauseaModern() { +// PotionEffectType potionEffectType = Registry.EFFECT.match("nausea"); +// if (potionEffectType != null) { +// return potionEffectType; +// } +// +// // Look for the potion effect type by name +// for (PotionEffectType pet : Registry.EFFECT) { +// if (pet.getKey().getKey().equalsIgnoreCase("CONFUSION") +// || pet.getKey().getKey().equalsIgnoreCase("NAUSEA") +// || pet.getName().equalsIgnoreCase("CONFUSION") +// || pet.getName().equalsIgnoreCase("NAUSEA")) { +// return pet; +// } +// } + + try { + return (PotionEffectType) PotionEffectType.class.getField("NAUSEA").get(null); + } catch (NoSuchFieldException | IllegalAccessException e) { + mcMMO.p.getLogger().severe("Unable to find the Nausea potion effect type, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Nausea potion effect type"); + } + } + + private static PotionEffectType getNauseaLegacy() { + try { + Object potionEffectTypeWrapper = PotionEffectType.class.getField("CONFUSION").get(null); + PotionEffectType potionEffectType = (PotionEffectType) potionEffectTypeWrapperGetPotionEffectType + .invoke(potionEffectTypeWrapper); + return potionEffectType; + } catch (IllegalAccessException | NoSuchFieldException | InvocationTargetException e) { + mcMMO.p.getLogger().severe("Unable to find the Nausea potion effect type, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Nausea potion effect type"); + } + } + + private static PotionEffectType initHaste() { + + + mcMMO.p.getLogger().severe("Unable to find the Haste potion effect type, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Haste potion effect type"); + } + + private static PotionEffectType getHasteLegacy() { + try { + Object potionEffectTypeWrapper = PotionEffectType.class.getField("FAST_DIGGING").get(null); + PotionEffectType potionEffectType = (PotionEffectType) potionEffectTypeWrapperGetPotionEffectType + .invoke(potionEffectTypeWrapper); + return potionEffectType; + } catch (IllegalAccessException | NoSuchFieldException | InvocationTargetException e) { + mcMMO.p.getLogger().severe("Unable to find the Haste potion effect type, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Haste potion effect type"); + } + } + + private static PotionEffectType getHasteModern() { +// PotionEffectType potionEffectType = Registry.EFFECT.match("haste"); +// if (potionEffectType != null) { +// return potionEffectType; +// } +// +// // Look for the potion effect type by name +// for (PotionEffectType pet : Registry.EFFECT) { +// if (pet.getKey().getKey().equalsIgnoreCase("HASTE") +// || pet.getKey().getKey().equalsIgnoreCase("FAST_DIGGING") +// || pet.getName().equalsIgnoreCase("HASTE") +// || pet.getName().equalsIgnoreCase("FAST_DIGGING")) { +// return pet; +// } +// } + + try { + return (PotionEffectType) PotionEffectType.class.getField("HASTE").get(null); + } catch (NoSuchFieldException | IllegalAccessException e) { + mcMMO.p.getLogger().severe("Unable to find the Haste potion effect type, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Haste potion effect type"); + } + } + + public static PotionEffectType getHaste() { + return haste; + } + + public static PotionEffectType getNausea() { + return nausea; + } +} diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java new file mode 100644 index 000000000..d1e255bde --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -0,0 +1,447 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.potion.PotionType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PotionUtil { + // Some of the old potion types got renamed, our configs can still contain these old names + private static final Map legacyPotionTypes = new HashMap<>(); + private static final Method methodPotionTypeGetKey; + private static final Method methodPotionTypeGetEffectType; + private static final Method methodPotionTypeGetPotionEffects; + private static final Method methodPotionDataIsUpgraded; + private static final Method methodPotionDataIsExtended; + private static final Method methodPotionDataGetType; + private static final Method methodPotionMetaGetBasePotionData; + private static final Method methodPotionMetaGetBasePotionType; + private static final Method methodPotionMetaSetBasePotionType; + private static final Method methodSetBasePotionData; + private static final Class potionDataClass; + + public static final String STRONG = "STRONG"; + public static final String LONG = "LONG"; + public static final String LEGACY_WATER_POTION_TYPE = "WATER"; + + private static final PotionCompatibilityType COMPATIBILITY_MODE; + + static { + // We used to use uncraftable as the potion type + // this type isn't available anymore, so water will do + legacyPotionTypes.put("UNCRAFTABLE", "WATER"); + legacyPotionTypes.put("JUMP", "LEAPING"); + legacyPotionTypes.put("SPEED", "SWIFTNESS"); + legacyPotionTypes.put("INSTANT_HEAL", "HEALING"); + legacyPotionTypes.put("INSTANT_DAMAGE", "HARMING"); + legacyPotionTypes.put("REGEN", "REGENERATION"); + methodPotionTypeGetKey = getKeyMethod(); + methodPotionDataIsUpgraded = getPotionDataIsUpgraded(); + methodPotionDataIsExtended = getIsExtended(); + methodPotionMetaGetBasePotionData = getBasePotionData(); + methodPotionMetaGetBasePotionType = getBasePotionType(); + methodPotionMetaSetBasePotionType = getMethodPotionMetaSetBasePotionType(); + methodPotionDataGetType = getPotionDataGetType(); + methodPotionTypeGetEffectType = getPotionTypeEffectType(); + methodPotionTypeGetPotionEffects = getPotionTypeGetPotionEffects(); + methodSetBasePotionData = getSetBasePotionData(); + potionDataClass = getPotionDataClass(); + + if (methodPotionMetaGetBasePotionData != null) { + COMPATIBILITY_MODE = PotionCompatibilityType.PRE_1_20_5; + } else { + COMPATIBILITY_MODE = PotionCompatibilityType.POST_1_20_5; + } + } + + /** + * Derive a potion from a partial name, and whether it should be upgraded or extended. + * @param partialName potion type as a string, can be a substring of the potion type but must match exactly + * @return The potion type + */ + public static PotionType matchPotionType(String partialName, boolean isUpgraded, boolean isExtended) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return matchLegacyPotionType(partialName); + } else { + String updatedName = convertLegacyNames(partialName); + return Arrays.stream(PotionType.values()) + .filter(potionType -> getKeyGetKey(potionType).toUpperCase().contains(partialName) + || getKeyGetKey(potionType).toUpperCase().contains(convertLegacyNames(updatedName))) + .filter(potionType -> !isUpgraded || potionType.name().toUpperCase().contains(STRONG)) + .filter(potionType -> !isExtended || potionType.name().toUpperCase().contains(LONG)) + .findAny().orElse(null); + } + } + + public static String getKeyGetKey(PotionType potionType) { + try { + if (getKeyMethod() != null) { + NamespacedKey key = (NamespacedKey) methodPotionTypeGetKey.invoke(potionType); + return key.getKey(); + } else { + return potionType.name(); + } + } catch (InvocationTargetException | IllegalAccessException e) { + mcMMO.p.getLogger().warning("Failed to get potion key for " + potionType.name()); + return potionType.name(); + } + } + + private static Class getPotionDataClass() { + try { + return Class.forName("org.bukkit.potion.PotionData"); + } catch (ClassNotFoundException e) { + return null; + } + } + + /** + * Older versions of Spigot do not have getKey() in PotionType + * We need to check for the existence of this method before calling it + * @return The getKey method + */ + private static @Nullable Method getKeyMethod() { + try { + return PotionType.class.getMethod("getKey"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getMethodPotionMetaSetBasePotionType() { + try { + return PotionMeta.class.getMethod("setBasePotionType", PotionType.class); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getSetBasePotionData() { + try { + return PotionMeta.class.getMethod("setBasePotionData", potionDataClass); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static @Nullable Method getPotionDataIsUpgraded() { + try { + // TODO: Needed? + final Class clazz = Class.forName("org.bukkit.potion.PotionData"); + return clazz.getMethod("isUpgraded"); + } catch (NoSuchMethodException | ClassNotFoundException e) { + return null; + } + } + + private static @Nullable Method getIsExtended() { + try { + // TODO: Needed? + final Class clazz = Class.forName("org.bukkit.potion.PotionData"); + return clazz.getMethod("isExtended"); + } catch (NoSuchMethodException | ClassNotFoundException e) { + return null; + } + } + + /** + * Newer versions of Spigot do not have getBasePotionData() in PotionMeta + * + * @return the getBasePotionData method, or null if it does not exist + */ + private static @Nullable Method getBasePotionData() { + try { + return PotionType.class.getMethod("getBasePotionData"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getBasePotionType() { + try { + return PotionMeta.class.getMethod("getBasePotionType"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getPotionDataGetType() { + try { + final Class clazz = Class.forName("org.bukkit.potion.PotionData"); + return clazz.getMethod("getType"); + } catch (NoSuchMethodException | ClassNotFoundException e) { + return null; + } + } + + private static Method getPotionTypeEffectType() { + try { + return PotionType.class.getMethod("getEffectType"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getPotionTypeGetPotionEffects() { + try { + return PotionType.class.getMethod("getPotionEffects"); + } catch (NoSuchMethodException e) { + return null; + } + } + + /** + * Legacy matching for {@link PotionType} + * + * @param partialName The partial name of the potion + * @return The potion type + */ + private static PotionType matchLegacyPotionType(String partialName) { + String updatedName = convertLegacyNames(partialName); + + return Arrays.stream(PotionType.values()) + .filter(potionType -> getKeyGetKey(potionType).equalsIgnoreCase(partialName) + || getKeyGetKey(potionType).equalsIgnoreCase(convertLegacyNames(updatedName)) + || potionType.name().equalsIgnoreCase(partialName) + || potionType.name().equalsIgnoreCase(convertLegacyNames(updatedName))) + .findAny().orElse(null); + } + + public static String convertPotionConfigName(String legacyName) { + String replacementName = legacyName; + + // Remove generated potions.yml config naming convention + if (replacementName.contains("POTION_OF_")) { + replacementName = replacementName.replace("POTION_OF_", ""); + } + + if (replacementName.contains("_II")) { + replacementName = replacementName.replace("_II", ""); + replacementName = "STRONG_" + replacementName; + } else if (replacementName.contains("_EXTENDED")) { + replacementName = replacementName.replace("_EXTENDED", ""); + replacementName = "LONG_" + replacementName; + } + return replacementName; + } + + public static String convertLegacyNames(String legacyPotionType) { + String modernized = legacyPotionType; + // check for legacy names + for (var key : legacyPotionTypes.keySet()) { + if (modernized.contains(key)) { + // Replace the legacy name with the new name + modernized = modernized.replace(key, legacyPotionTypes.get(key)); + break; + } + } + return modernized; + } + + public static boolean hasLegacyName(String potionType) { + for (var key : legacyPotionTypes.keySet()) { + if (potionType.contains(key)) { + return true; + } + } + return false; + } + + public static boolean isStrong(PotionMeta potionMeta) { + if (methodPotionMetaGetBasePotionData == null) { + return isStrongModern(potionMeta); + } else { + return isStrongLegacy(potionMeta); + } + + } + + public static boolean isLong(PotionMeta potionMeta) { + if (methodPotionMetaGetBasePotionData == null) { + return isLongModern(potionMeta); + } else { + return isLongLegacy(potionMeta); + } + } + + private static boolean isLongLegacy(PotionMeta potionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + return (boolean) methodPotionDataIsExtended.invoke(potionData); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private static boolean isLongModern(PotionMeta potionMeta) { + try { + return getModernPotionTypeKey(potionMeta).getKey().startsWith(LONG); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private static boolean isStrongLegacy(PotionMeta potionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + return (boolean) methodPotionDataIsUpgraded.invoke(potionData); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private static boolean isStrongModern(PotionMeta potionMeta) { + try { + return getModernPotionTypeKey(potionMeta).getKey().startsWith(STRONG); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private static NamespacedKey getModernPotionTypeKey(PotionMeta potionMeta) throws IllegalAccessException, InvocationTargetException { + PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); + return (NamespacedKey) methodPotionTypeGetKey.invoke(potionType); + } + + public static boolean isPotionTypeWater(@NotNull PotionMeta potionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return isPotionTypeWaterLegacy(potionMeta); + } else { + return isPotionTypeWaterModern(potionMeta); + } + } + + private static boolean isPotionTypeWaterLegacy(@NotNull PotionMeta potionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); + return potionType.name().equalsIgnoreCase(LEGACY_WATER_POTION_TYPE) + || PotionType.valueOf(LEGACY_WATER_POTION_TYPE) == potionType; + } catch (InvocationTargetException | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean isPotionTypeWaterModern(@NotNull PotionMeta potionMeta) { + try { + return getModernPotionTypeKey(potionMeta).getKey().equalsIgnoreCase(LEGACY_WATER_POTION_TYPE); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + public static boolean samePotionType(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return samePotionTypeLegacy(potionMeta, otherPotionMeta); + } else { + return samePotionTypeModern(potionMeta, otherPotionMeta); + } + } + + private static boolean samePotionTypeLegacy(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + Object otherPotionData = methodPotionMetaGetBasePotionData.invoke(otherPotionMeta); + PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); + PotionType otherPotionType = (PotionType) methodPotionDataGetType.invoke(otherPotionData); + return potionType == otherPotionType; + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean samePotionTypeModern(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + try { + PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); + PotionType otherPotionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(otherPotionMeta); + return potionType == otherPotionType; + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + public static boolean samePotionEffects(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return true; + } else { + return samePotionEffectsModern(potionMeta, otherPotionMeta); + } + } + + private static boolean samePotionEffectsModern(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + return potionMeta.getCustomEffects().equals(otherPotionMeta.getCustomEffects()); + } + + public static boolean hasBasePotionEffects(PotionMeta potionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return hasBasePotionEffectsLegacy(potionMeta); + } else { + return hasBasePotionEffectsModern(potionMeta); + } + } + + private static boolean hasBasePotionEffectsLegacy(PotionMeta potionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); + return methodPotionTypeGetEffectType.invoke(potionType) != null; + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean hasBasePotionEffectsModern(PotionMeta potionMeta) { + try { + PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); + List potionEffectTypeList = (List) methodPotionTypeGetPotionEffects.invoke(potionType); + return potionEffectTypeList != null || !potionEffectTypeList.isEmpty(); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Set the base potion type of a potion meta. + * Note that extended/upgraded are ignored in 1.20.5 and later. + * + * @param potionMeta the potion meta + * @param extended true if the potion is extended + * @param upgraded true if the potion is upgraded + */ + public static void setBasePotionType(PotionMeta potionMeta, PotionType potionType, boolean extended, boolean upgraded) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + setBasePotionTypeLegacy(potionMeta, potionType, extended, upgraded); + } else { + setBasePotionTypeModern(potionMeta, potionType); + } + } + + private static void setBasePotionTypeLegacy(PotionMeta potionMeta, PotionType potionType, boolean extended, + boolean upgraded) { + try { + Object potionData = potionDataClass.getConstructor(PotionType.class, boolean.class, boolean.class) + .newInstance(potionType, extended, upgraded); + methodSetBasePotionData.invoke(potionMeta, potionData); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException | NoSuchMethodException ex) { + throw new RuntimeException(ex); + } + } + + private static void setBasePotionTypeModern(PotionMeta potionMeta, PotionType potionType) { + try { + methodPotionMetaSetBasePotionType.invoke(potionMeta, potionType); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } +} diff --git a/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java b/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java index 0946b4cc5..ced2cbf25 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java @@ -33,6 +33,9 @@ public final class CommandRegistrationManager { private static void registerSkillCommands() { for (PrimarySkillType skill : PrimarySkillType.values()) { + if (skill == PrimarySkillType.MACES) + continue; + String commandName = skill.toString().toLowerCase(Locale.ENGLISH); String localizedName = mcMMO.p.getSkillTools().getLocalizedSkillName(skill).toLowerCase(Locale.ENGLISH); @@ -77,6 +80,10 @@ public final class CommandRegistrationManager { command.setExecutor(new HerbalismCommand()); break; + case MACES: + // command.setExecutor(new MacesCommand()); + break; + case MINING: command.setExecutor(new MiningCommand()); break; @@ -113,7 +120,7 @@ public final class CommandRegistrationManager { break; default: - break; + throw new IllegalStateException("Unexpected value: " + skill); } } } diff --git a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java index 11d4a6d68..012524adb 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java +++ b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java @@ -23,7 +23,6 @@ import java.util.HashMap; * In 2.2 we are switching to modules and that will clean things up significantly * */ -//TODO: I need to delete this crap public class CompatibilityManager { private @NotNull HashMap supportedLayers; private boolean isFullyCompatibleServerSoftware = true; //true if all compatibility layers load successfully @@ -159,7 +158,7 @@ public class CompatibilityManager { return masterAnglerCompatibility; } - public @Nullable MinecraftGameVersion getMinecraftGameVersion() { + public @NotNull MinecraftGameVersion getMinecraftGameVersion() { return minecraftGameVersion; } } diff --git a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java index fd2d240c2..168d778a3 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java @@ -111,6 +111,7 @@ public final class CombatUtils { } } } + private static void processTridentCombatMelee(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; @@ -214,6 +215,32 @@ public final class CombatUtils { delayArrowMetaCleanup(arrow); } + private static void processMacesCombat(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { + if (event.getCause() == DamageCause.THORNS) { + return; + } + + double boostedDamage = event.getDamage(); + + McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + + //Make sure the profiles been loaded + if(mcMMOPlayer == null) { + return; + } + + // MacesManager macesManager = mcMMOPlayer.getMacesManager(); + + if(canUseLimitBreak(player, target, SubSkillType.MACES_MACES_LIMIT_BREAK)) { + boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.MACES_MACES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); + } + + event.setDamage(boostedDamage); + processCombatXP(mcMMOPlayer, target, PrimarySkillType.MACES); + + printFinalDamageDebug(player, event, mcMMOPlayer); + } + private static void processAxeCombat(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; @@ -498,6 +525,15 @@ public final class CombatUtils { processTridentCombatMelee(target, player, event); } } + else if (ItemUtils.isMace(heldItem)) { + if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.MACES, target)) { + return; + } + + if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.MACES)) { + processMacesCombat(target, player, event); + } + } } else if (entityType == EntityType.WOLF) { diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java b/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java index 39ddfbd24..d9f25db2c 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java @@ -198,6 +198,7 @@ public class SkillTools { case SUPER_SHOTGUN -> PrimarySkillType.CROSSBOWS; case TRIDENTS_SUPER_ABILITY -> PrimarySkillType.TRIDENTS; case EXPLOSIVE_SHOT -> PrimarySkillType.ARCHERY; + case MACES_SUPER_ABILITY -> PrimarySkillType.MACES; }; } diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java index b0d406ae6..17589c2fa 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java @@ -20,7 +20,6 @@ import com.gmail.nossr50.util.text.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; @@ -28,12 +27,13 @@ import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Iterator; +import static com.gmail.nossr50.util.PotionEffectMapper.getHaste; + public final class SkillUtils { /** * This is a static utility class, therefore we don't want any instances of @@ -148,13 +148,8 @@ public final class SkillUtils { return; } - int originalDigSpeed = heldItem.getEnchantmentLevel(Enchantment.DIG_SPEED); - - //Add dig speed - - //Lore no longer gets added, no point to it afaik - //ItemUtils.addAbilityLore(heldItem); //lore can be a secondary failsafe for 1.13 and below - ItemUtils.addDigSpeedToItem(heldItem, heldItem.getEnchantmentLevel(Enchantment.DIG_SPEED)); + int originalDigSpeed = heldItem.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getEfficiency()); + ItemUtils.addDigSpeedToItem(heldItem, heldItem.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getEfficiency())); //1.13.2+ will have persistent metadata for this item mcMMO.getMetadataService().getItemMetadataService().setSuperAbilityBoostedItem(heldItem, originalDigSpeed); @@ -162,9 +157,9 @@ public final class SkillUtils { int duration = 0; int amplifier = 0; - if (player.hasPotionEffect(PotionEffectType.FAST_DIGGING)) { + if (player.hasPotionEffect(getHaste())) { for (PotionEffect effect : player.getActivePotionEffects()) { - if (effect.getType() == PotionEffectType.FAST_DIGGING) { + if (effect.getType() == getHaste()) { duration = effect.getDuration(); amplifier = effect.getAmplifier(); break; @@ -194,7 +189,7 @@ public final class SkillUtils { mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR; } - PotionEffect abilityBuff = new PotionEffect(PotionEffectType.FAST_DIGGING, duration + ticks, amplifier + 10); + PotionEffect abilityBuff = new PotionEffect(getHaste(), duration + ticks, amplifier + 10); player.addPotionEffect(abilityBuff, true); } } @@ -221,7 +216,7 @@ public final class SkillUtils { if(itemMeta != null) { // This is safe to call without prior checks. - itemMeta.removeEnchant(Enchantment.DIG_SPEED); + itemMeta.removeEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency()); itemStack.setItemMeta(itemMeta); ItemUtils.removeAbilityLore(itemStack); @@ -251,7 +246,7 @@ public final class SkillUtils { Material type = itemStack.getType(); short maxDurability = mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager().getRepairable(type).getMaximumDurability() : type.getMaxDurability(); - durabilityModifier = (int) Math.min(durabilityModifier / (itemStack.getEnchantmentLevel(Enchantment.DURABILITY) + 1), maxDurability * maxDamageModifier); + durabilityModifier = (int) Math.min(durabilityModifier / (itemStack.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getUnbreaking()) + 1), maxDurability * maxDamageModifier); itemStack.setDurability((short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability)); } @@ -281,7 +276,7 @@ public final class SkillUtils { Material type = itemStack.getType(); short maxDurability = mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager().getRepairable(type).getMaximumDurability() : type.getMaxDurability(); - durabilityModifier = (int) Math.min(durabilityModifier * (0.6 + 0.4/ (itemStack.getEnchantmentLevel(Enchantment.DURABILITY) + 1)), maxDurability * maxDamageModifier); + durabilityModifier = (int) Math.min(durabilityModifier * (0.6 + 0.4/ (itemStack.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getUnbreaking()) + 1)), maxDurability * maxDamageModifier); itemStack.setDurability((short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability)); } diff --git a/src/main/resources/experience.yml b/src/main/resources/experience.yml index a41609521..a4838cd67 100644 --- a/src/main/resources/experience.yml +++ b/src/main/resources/experience.yml @@ -1,13 +1,3 @@ -# -# Experience configuration -# Last updated on ${project.version}-b${BUILD_NUMBER} -# -# Configure the experience formula and experience settings here. -# -##### - - - # https://hub.spigotmc.org/javadocs/spigot/org/bukkit/boss/BarColor.html # These are the only valid colors for Experience Bars, use the exact name found here # BLUE, GREEN, PINK, PURPLE, RED, WHITE, YELLOW (As of the time of this update these are the only Bar colors available, this could change in the future so check the BarColor enum to see if it has) @@ -48,7 +38,7 @@ Fishing_ExploitFix_Options: MoveRange: 3 OverFishLimit: 10 Experience_Bars: - # Turn this to false if you wanna disable XP bars + # Turn this to false if you want to disable XP bars Enable: true Update: # XP that you gained from your party but not yourself @@ -98,6 +88,10 @@ Experience_Bars: Enable: true Color: YELLOW BarStyle: SEGMENTED_6 + Maces: + Enable: true + Color: BLUE + BarStyle: SEGMENTED_6 Repair: Enable: true Color: PURPLE @@ -170,6 +164,7 @@ Experience_Formula: # Experience gained will get multiplied by these values. 1.0 by default, 0.5 means half XP gained. This happens right before multiplying the XP by the global multiplier. Skill_Multiplier: + Maces: 1.0 Crossbows: 1.0 Tridents: 1.0 Swords: 1.0 @@ -217,6 +212,9 @@ Diminished_Returns: Repair: 20000 Fishing: 20000 Alchemy: 20000 + Crossbows: 20000 + Tridents: 20000 + Maces: 20000 Time_Interval: 10 diff --git a/src/main/resources/locale/locale_en_US.properties b/src/main/resources/locale/locale_en_US.properties index 11e550b20..f2fcc7a26 100644 --- a/src/main/resources/locale/locale_en_US.properties +++ b/src/main/resources/locale/locale_en_US.properties @@ -1,3 +1,4 @@ +Placeholder= This value is for any WIP locale entries that will not be displayed to users JSON.Rank=Rank JSON.DescriptionHeader=Description: JSON.JWrapper.Header=Details @@ -26,6 +27,7 @@ JSON.Salvage=Salvage JSON.Swords=Swords JSON.Taming=Taming JSON.Tridents=Tridents +JSON.Maces=Maces JSON.Unarmed=Unarmed JSON.Woodcutting=Woodcutting JSON.URL.Website=The official mcMMO Website! @@ -96,6 +98,7 @@ Overhaul.Name.Smelting=Smelting Overhaul.Name.Swords=Swords Overhaul.Name.Taming=Taming Overhaul.Name.Tridents=Tridents +Overhaul.Name.Maces=Maces Overhaul.Name.Unarmed=Unarmed Overhaul.Name.Woodcutting=Woodcutting # /mcMMO Command Style Stuff @@ -122,6 +125,7 @@ XPBar.Smelting=Smelting Lv.&6{0} XPBar.Swords=Swords Lv.&6{0} XPBar.Taming=Taming Lv.&6{0} XPBar.Tridents=Tridents Lv.&6{0} +XPBar.Maces=Maces Lv.&6{0} XPBar.Unarmed=Unarmed Lv.&6{0} XPBar.Woodcutting=Woodcutting Lv.&6{0} #This is just a preset template that gets used if the 'ExtraDetails' setting is turned on in experience.yml (off by default), you can ignore this template and just edit the strings above @@ -457,9 +461,6 @@ Tridents.Listener=Tridents: Maces.SkillName=MACES Maces.Ability.Lower=&7You lower your mace. Maces.Ability.Ready=&3You &6ready&3 your Mace. -Maces.Skills.MaceSmash.Refresh=&aYour &eGiga Smash &aability is refreshed! -Maces.Skills.MaceSmash.Other.On=&a{0}&2 used &cGiga Smash! -Maces.SubSkill.GigaSmash.Name=Giga Smash Maces.SubSkill.MacesLimitBreak.Name=Maces Limit Break Maces.SubSkill.MacesLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE. Maces.SubSkill.MacesLimitBreak.Stat=Limit Break Max DMG diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 198d465fc..457a7e54b 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -154,6 +154,9 @@ commands: salvage: description: Detailed mcMMO skill info permission: mcmmo.commands.salvage + maces: + description: Detailed mcMMO skill info + permission: mcmmo.commands.maces mmopower: description: Shows skill mastery and power level info permission: mcmmo.commands.mmopower diff --git a/src/main/resources/skillranks.yml b/src/main/resources/skillranks.yml index 590ddde11..2df17807a 100644 --- a/src/main/resources/skillranks.yml +++ b/src/main/resources/skillranks.yml @@ -443,6 +443,30 @@ Salvage: Rank_6: 750 Rank_7: 850 Rank_8: 1000 +Maces: + TridentsLimitBreak: + Standard: + Rank_1: 10 + Rank_2: 20 + Rank_3: 30 + Rank_4: 40 + Rank_5: 50 + Rank_6: 60 + Rank_7: 70 + Rank_8: 80 + Rank_9: 90 + Rank_10: 100 + RetroMode: + Rank_1: 100 + Rank_2: 200 + Rank_3: 300 + Rank_4: 400 + Rank_5: 500 + Rank_6: 600 + Rank_7: 700 + Rank_8: 800 + Rank_9: 900 + Rank_10: 1000 Mining: MotherLode: Standard: diff --git a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java index d995ed569..47e2126aa 100644 --- a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java +++ b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java @@ -16,13 +16,12 @@ import com.gmail.nossr50.util.blockmeta.ChunkManager; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillTools; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFactory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; +import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.PluginManager; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -31,9 +30,10 @@ import java.util.UUID; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; public abstract class MMOTestEnvironment { + protected MockedStatic mockedBukkit; protected MockedStatic mockedMcMMO; protected MockedStatic mockedChatConfig; protected MockedStatic experienceConfig; @@ -63,26 +63,27 @@ public abstract class MMOTestEnvironment { protected PlayerProfile playerProfile; protected McMMOPlayer mmoPlayer; protected String playerName = "testPlayer"; + protected ItemFactory itemFactory; protected ChunkManager chunkManager; protected MaterialMapStore materialMapStore; protected void mockBaseEnvironment(Logger logger) throws InvalidSkillException { - mockedMcMMO = Mockito.mockStatic(mcMMO.class); - mcMMO.p = Mockito.mock(mcMMO.class); + mockedMcMMO = mockStatic(mcMMO.class); + mcMMO.p = mock(mcMMO.class); when(mcMMO.p.getLogger()).thenReturn(logger); // place store - chunkManager = Mockito.mock(ChunkManager.class); + chunkManager = mock(ChunkManager.class); when(mcMMO.getPlaceStore()).thenReturn(chunkManager); // shut off mod manager for woodcutting - when(mcMMO.getModManager()).thenReturn(Mockito.mock(ModManager.class)); + when(mcMMO.getModManager()).thenReturn(mock(ModManager.class)); when(mcMMO.getModManager().isCustomLog(any())).thenReturn(false); // chat config - mockedChatConfig = Mockito.mockStatic(ChatConfig.class); - when(ChatConfig.getInstance()).thenReturn(Mockito.mock(ChatConfig.class)); + mockedChatConfig = mockStatic(ChatConfig.class); + when(ChatConfig.getInstance()).thenReturn(mock(ChatConfig.class)); // general config mockGeneralConfig(); @@ -108,29 +109,34 @@ public abstract class MMOTestEnvironment { mockPermissions(); - mockedRankUtils = Mockito.mockStatic(RankUtils.class); + mockedRankUtils = mockStatic(RankUtils.class); // wire server - this.server = Mockito.mock(Server.class); + this.server = mock(Server.class); when(mcMMO.p.getServer()).thenReturn(server); + mockedBukkit = mockStatic(Bukkit.class); + when(Bukkit.getItemFactory()).thenReturn(itemFactory); + itemFactory = mock(ItemFactory.class); + // when(itemFactory.getItemMeta(any())).thenReturn(mock(ItemMeta.class)); + // wire plugin manager - this.pluginManager = Mockito.mock(PluginManager.class); + this.pluginManager = mock(PluginManager.class); when(server.getPluginManager()).thenReturn(pluginManager); // wire world - this.world = Mockito.mock(World.class); + this.world = mock(World.class); // wire Misc - this.mockedMisc = Mockito.mockStatic(Misc.class); + this.mockedMisc = mockStatic(Misc.class); when(Misc.getBlockCenter(any())).thenReturn(new Location(world, 0, 0, 0)); // setup player and player related mocks after everything else - this.player = Mockito.mock(Player.class); + this.player = mock(Player.class); when(player.getUniqueId()).thenReturn(playerUUID); // wire inventory - this.playerInventory = Mockito.mock(PlayerInventory.class); + this.playerInventory = mock(PlayerInventory.class); when(player.getInventory()).thenReturn(playerInventory); // PlayerProfile and McMMOPlayer are partially mocked @@ -138,7 +144,7 @@ public abstract class MMOTestEnvironment { mmoPlayer = Mockito.spy(new McMMOPlayer(player, playerProfile)); // wire user manager - this.mockedUserManager = Mockito.mockStatic(UserManager.class); + this.mockedUserManager = mockStatic(UserManager.class); when(UserManager.getPlayer(player)).thenReturn(mmoPlayer); this.materialMapStore = new MaterialMapStore(); @@ -146,7 +152,7 @@ public abstract class MMOTestEnvironment { } private void mockPermissions() { - mockedPermissions = Mockito.mockStatic(Permissions.class); + mockedPermissions = mockStatic(Permissions.class); when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(true); when(Permissions.canUseSubSkill(any(Player.class), any(SubSkillType.class))).thenReturn(true); when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(true); @@ -155,16 +161,16 @@ public abstract class MMOTestEnvironment { } private void mockRankConfig() { - rankConfig = Mockito.mock(RankConfig.class); + rankConfig = mock(RankConfig.class); } private void mockAdvancedConfig() { - this.advancedConfig = Mockito.mock(AdvancedConfig.class); + this.advancedConfig = mock(AdvancedConfig.class); when(mcMMO.p.getAdvancedConfig()).thenReturn(advancedConfig); } private void mockGeneralConfig() { - generalConfig = Mockito.mock(GeneralConfig.class); + generalConfig = mock(GeneralConfig.class); when(generalConfig.getTreeFellerThreshold()).thenReturn(100); when(generalConfig.getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, Material.OAK_LOG)).thenReturn(true); when(generalConfig.getLocale()).thenReturn("en_US"); @@ -172,15 +178,15 @@ public abstract class MMOTestEnvironment { } private void mockPartyConfig() { - partyConfig = Mockito.mock(PartyConfig.class); + partyConfig = mock(PartyConfig.class); when(partyConfig.isPartyEnabled()).thenReturn(false); when(mcMMO.p.getPartyConfig()).thenReturn(partyConfig); } private void mockExperienceConfig() { - experienceConfig = Mockito.mockStatic(ExperienceConfig.class); + experienceConfig = mockStatic(ExperienceConfig.class); - when(ExperienceConfig.getInstance()).thenReturn(Mockito.mock(ExperienceConfig.class)); + when(ExperienceConfig.getInstance()).thenReturn(mock(ExperienceConfig.class)); // Combat when(ExperienceConfig.getInstance().getCombatXP("Cow")).thenReturn(1D); @@ -212,5 +218,8 @@ public abstract class MMOTestEnvironment { if (mockedEventUtils != null) { mockedEventUtils.close(); } + if (mockedBukkit != null) { + mockedBukkit.close(); + } } } diff --git a/src/test/java/com/gmail/nossr50/config/skills/alchemy/PotionConfigTest.java b/src/test/java/com/gmail/nossr50/config/skills/alchemy/PotionConfigTest.java new file mode 100644 index 000000000..b9b648046 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/config/skills/alchemy/PotionConfigTest.java @@ -0,0 +1,69 @@ +//package com.gmail.nossr50.config.skills.alchemy; +// +//import com.gmail.nossr50.MMOTestEnvironment; +//import org.bukkit.inventory.meta.ItemMeta; +//import org.bukkit.inventory.meta.PotionMeta; +//import org.junit.jupiter.api.AfterEach; +//import org.junit.jupiter.api.BeforeEach; +//import org.junit.jupiter.api.Test; +// +//import java.io.File; +//import java.net.URL; +//import java.util.logging.Logger; +// +//import static org.junit.jupiter.api.Assertions.assertNotNull; +//import static org.mockito.ArgumentMatchers.any; +//import static org.mockito.Mockito.mock; +//import static org.mockito.Mockito.when; +// +//class PotionConfigTest extends MMOTestEnvironment { +// +// public static final String POTION_LEGACY_POTION_YML = "potion/legacy_potion.yml"; +// public static final String POTION_MODERN_YML = "potion/modern_potion.yml"; +// public static final Logger logger = Logger.getLogger(PotionConfigTest.class.getName()); +// +// @BeforeEach +// void setUp() { +// mockBaseEnvironment(logger); +// final PotionMeta potionMeta = mock(PotionMeta.class); +// when(itemFactory.getItemMeta(any())).thenReturn(potionMeta); +// } +// +// @AfterEach +// void tearDown() { +// cleanupBaseEnvironment(); +// } +// +// @Test +// void testLoadLegacyConfig() { +// final PotionConfig potionConfig = getPotionConfig(POTION_LEGACY_POTION_YML); +// assertNotNull(potionConfig); +// +// potionConfig.loadConcoctions(); +// int loaded = potionConfig.loadPotionMap(); +// System.out.println("Loaded " + loaded + " potions"); +// } +// +// @Test +// void testModernConfig() { +// final PotionConfig potionConfig = getPotionConfig(POTION_MODERN_YML); +// assertNotNull(potionConfig); +// +// potionConfig.loadConcoctions(); +// int loaded = potionConfig.loadPotionMap(); +// System.out.println("Loaded " + loaded + " potions"); +// } +// +// private PotionConfig getPotionConfig(String path) { +// // Get the file URL using the class loader +// final URL resource = getClass().getClassLoader().getResource(path); +// if (resource == null) { +// throw new IllegalArgumentException("file not found!"); +// } else { +// // Convert URL to a File object +// final File potionFile = new File(resource.getFile()); +// System.out.println("File path: " + potionFile.getAbsolutePath()); +// return new PotionConfig(potionFile); +// } +// } +//} \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java b/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java index 23463cbdb..8e6d04c2a 100644 --- a/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java +++ b/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java @@ -10,7 +10,6 @@ import com.gmail.nossr50.util.skills.SkillTools; import com.google.common.io.Files; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -38,32 +37,30 @@ class FlatFileDatabaseManagerTest { public static final @NotNull String BAD_DATA_FILE_LINE_TWENTY_THREE = "nossr51:baddata:::baddata:baddata:640:baddata:1000:1000:1000:baddata:baddata:baddata:baddata:16:0:500:20273:0:0:0:0::1000:0:0:baddata:1593543012:0:0:0:0::1000:0:0:baddata:IGNORED:1000:0:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1:0:"; public static final @NotNull String DB_BADDATA = "baddatadb.users"; public static final @NotNull String DB_HEALTHY = "healthydb.users"; - public static final @NotNull String HEALTHY_DB_LINE_1 = "nossr50:1:IGNORED:IGNORED:10:2:20:3:4:5:6:7:8:9:10:30:40:50:60:70:80:90:100:IGNORED:11:110:111:222:333:444:555:666:777:IGNORED:12:120:888:IGNORED:HEARTS:13:130:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1111:999:2020:140:14:150:15:1111:2222:3333"; public static final @NotNull String HEALTHY_DB_LINE_ONE_UUID_STR = "588fe472-1c82-4c4e-9aa1-7eefccb277e3"; public static final String DB_MISSING_LAST_LOGIN = "missinglastlogin.users"; - public static final String LINE_TWO_FROM_MISSING_DB = "nossr50:1:IGNORED:IGNORED:10:2:20:3:4:5:6:7:8:9:10:30:40:50:60:70:80:90:100:IGNORED:11:110:111:222:333:444:555:666:777:IGNORED:12:120:888:0:HEARTS:13:130:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1111:999:"; private static File tempDir; private final static @NotNull Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); private final long PURGE_TIME = 2630000000L; - private static @Nullable FlatFileDatabaseManager db; //Making them all unique makes it easier on us to edit this stuff later int expectedLvlMining = 1, expectedLvlWoodcutting = 2, expectedLvlRepair = 3, expectedLvlUnarmed = 4, expectedLvlHerbalism = 5, expectedLvlExcavation = 6, expectedLvlArchery = 7, expectedLvlSwords = 8, expectedLvlAxes = 9, expectedLvlAcrobatics = 10, expectedLvlTaming = 11, expectedLvlFishing = 12, expectedLvlAlchemy = 13, expectedLvlCrossbows = 14, - expectedLvlTridents = 15; + expectedLvlTridents = 15, expectedLvlMaces = 16; float expectedExpMining = 10, expectedExpWoodcutting = 20, expectedExpRepair = 30, expectedExpUnarmed = 40, expectedExpHerbalism = 50, expectedExpExcavation = 60, expectedExpArchery = 70, expectedExpSwords = 80, expectedExpAxes = 90, expectedExpAcrobatics = 100, expectedExpTaming = 110, expectedExpFishing = 120, expectedExpAlchemy = 130, expectedExpCrossbows = 140, - expectedExpTridents = 150; + expectedExpTridents = 150, expectedExpMaces = 160; long expectedBerserkCd = 111, expectedGigaDrillBreakerCd = 222, expectedTreeFellerCd = 333, expectedGreenTerraCd = 444, expectedSerratedStrikesCd = 555, expectedSkullSplitterCd = 666, expectedSuperBreakerCd = 777, expectedBlastMiningCd = 888, expectedChimaeraWingCd = 999, - expectedSuperShotgunCd = 1111, expectedTridentSuperCd = 2222, expectedExplosiveShotCd = 3333; + expectedSuperShotgunCd = 1111, expectedTridentSuperCd = 2222, expectedExplosiveShotCd = 3333, + expectedMacesSuperCd = 4444; int expectedScoreboardTips = 1111; Long expectedLastLogin = 2020L; @@ -75,10 +72,8 @@ class FlatFileDatabaseManagerTest { @BeforeEach void init() { - assertNull(db); //noinspection UnstableApiUsage tempDir = Files.createTempDir(); - db = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); } private @NotNull String getTemporaryUserFilePath() { @@ -88,7 +83,6 @@ class FlatFileDatabaseManagerTest { @AfterEach void tearDown() { recursiveDelete(tempDir); - db = null; } //Nothing wrong with this database @@ -150,17 +144,19 @@ class FlatFileDatabaseManagerTest { @Test void testDefaultInit() { - db = new FlatFileDatabaseManager(getTemporaryUserFilePath(), logger, PURGE_TIME, 0); + new FlatFileDatabaseManager(getTemporaryUserFilePath(), logger, PURGE_TIME, 0); } @Test void testUpdateLeaderboards() { - assertNotNull(db); - assertEquals(LeaderboardStatus.UPDATED, db.updateLeaderboards()); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + assertNotNull(flatFileDatabaseManager); + assertEquals(LeaderboardStatus.UPDATED, flatFileDatabaseManager.updateLeaderboards()); } @Test void testSaveUser() { + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); //Make a Profile to save and check to see if it worked UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); String playerName = "nossr50"; @@ -168,15 +164,15 @@ class FlatFileDatabaseManagerTest { //The above profile should be "zero" initialized //Save the zero version and see if it looks correct - assertNotNull(db); - assertTrue(db.getUsersFile().exists()); //Users file should have been created from the above com.gmail.nossr50.database.FlatFileDatabaseManager.checkFileHealthAndStructure - assertNotNull(db.getUsersFile()); + assertNotNull(flatFileDatabaseManager); + assertTrue(flatFileDatabaseManager.getUsersFile().exists()); //Users file should have been created from the above com.gmail.nossr50.database.FlatFileDatabaseManager.checkFileHealthAndStructure + assertNotNull(flatFileDatabaseManager.getUsersFile()); - //The DB is empty at this point, add our user - assertTrue(db.saveUser(testProfile)); //True means we saved the user + //The flatFileDatabaseManager is empty at this point, add our user + assertTrue(flatFileDatabaseManager.saveUser(testProfile)); //True means we saved the user //Check for the empty profile - PlayerProfile retrievedFromData = db.loadPlayerProfile(uuid); + PlayerProfile retrievedFromData = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned assertEquals(uuid, retrievedFromData.getUniqueId()); assertEquals(playerName, retrievedFromData.getPlayerName()); @@ -187,9 +183,9 @@ class FlatFileDatabaseManagerTest { String alteredName = "changedmyname"; PlayerProfile changedNameProfile = new PlayerProfile(alteredName, uuid, 0); - assertTrue(db.saveUser(changedNameProfile)); //True means we saved the user + assertTrue(flatFileDatabaseManager.saveUser(changedNameProfile)); //True means we saved the user - retrievedFromData = db.loadPlayerProfile(uuid); + retrievedFromData = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned assertEquals(uuid, retrievedFromData.getUniqueId()); assertEquals(alteredName, retrievedFromData.getPlayerName()); @@ -198,49 +194,27 @@ class FlatFileDatabaseManagerTest { @Test void testAddedMissingLastLoginValues() { File dbFile = prepareDatabaseTestResource(DB_MISSING_LAST_LOGIN); - - //This makes sure our private method is working before the tests run afterwards - ArrayList dataFromFile = getSplitDataFromFile(dbFile); - logger.info("File Path: "+ dbFile.getAbsolutePath()); - assertArrayEquals(LINE_TWO_FROM_MISSING_DB.split(":"), dataFromFile.get(1)); - assertEquals(dataFromFile.get(1)[FlatFileDatabaseManager.UUID_INDEX], HEALTHY_DB_LINE_ONE_UUID_STR); - - db = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); - List flagsFound = db.checkFileHealthAndStructure(); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNotNull(flagsFound); assertTrue(flagsFound.contains(FlatFileDataFlag.LAST_LOGIN_SCHEMA_UPGRADE)); //Check for the fixed value - PlayerProfile profile = db.loadPlayerProfile("nossr50"); + PlayerProfile profile = flatFileDatabaseManager.loadPlayerProfile("nossr50"); assertEquals(-1, (long) profile.getLastLogin()); } @Test void testLoadByName() { File healthyDB = prepareDatabaseTestResource(DB_HEALTHY); - - /* - * We have established the files are in good order, so now for the actual testing - */ - - //This makes sure our private method is working before the tests run afterwards - ArrayList dataFromFile = getSplitDataFromFile(healthyDB); - logger.info("File Path: "+healthyDB.getAbsolutePath()); - assertArrayEquals(HEALTHY_DB_LINE_1.split(":"), dataFromFile.get(0)); - assertEquals(dataFromFile.get(0)[FlatFileDatabaseManager.UUID_INDEX], HEALTHY_DB_LINE_ONE_UUID_STR); - - db = new FlatFileDatabaseManager(healthyDB, logger, PURGE_TIME, 0, true); - List flagsFound = db.checkFileHealthAndStructure(); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(healthyDB, logger, PURGE_TIME, 0, true); + List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found - /* - * Once the DB looks fine load the profile - */ - String playerName = "nossr50"; UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); - PlayerProfile profile = db.loadPlayerProfile(playerName); + PlayerProfile profile = flatFileDatabaseManager.loadPlayerProfile(playerName); testHealthyDataProfileValues(playerName, uuid, profile); } @@ -251,16 +225,16 @@ class FlatFileDatabaseManagerTest { String playerName = "nossr50"; int newUserTestStartingLvl = 1337; - db = new FlatFileDatabaseManager(new File(tempDir.getPath() + File.separator + TEST_FILE_NAME), logger, PURGE_TIME, newUserTestStartingLvl, true); - db.checkFileHealthAndStructure(); + var flatFileDatabaseManager = new FlatFileDatabaseManager(new File(tempDir.getPath() + File.separator + TEST_FILE_NAME), logger, PURGE_TIME, newUserTestStartingLvl, true); + flatFileDatabaseManager.checkFileHealthAndStructure(); - PlayerProfile playerProfile = db.newUser(playerName, uuid); + PlayerProfile playerProfile = flatFileDatabaseManager.newUser(playerName, uuid); assertTrue(playerProfile.isLoaded()); assertEquals(playerName, playerProfile.getPlayerName()); assertEquals(uuid, playerProfile.getUniqueId()); - PlayerProfile retrievedFromDisk = db.loadPlayerProfile(uuid); + PlayerProfile retrievedFromDisk = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(retrievedFromDisk.isLoaded()); assertEquals(playerName, retrievedFromDisk.getPlayerName()); assertEquals(uuid, retrievedFromDisk.getUniqueId()); @@ -270,11 +244,11 @@ class FlatFileDatabaseManagerTest { checkNewUserValues(retrievedFromDisk, newUserTestStartingLvl); //TODO: Should we do any dupe checking? Probably not needed as it would be caught on the next load - db.newUser("disco", new UUID(3, 3)); - db.newUser("dingus", new UUID(3, 4)); - db.newUser("duped_dingus", new UUID(3, 4)); + flatFileDatabaseManager.newUser("disco", new UUID(3, 3)); + flatFileDatabaseManager.newUser("dingus", new UUID(3, 4)); + flatFileDatabaseManager.newUser("duped_dingus", new UUID(3, 4)); - assertEquals(5, getSplitDataFromFile(db.getUsersFile()).size()); + assertEquals(5, getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()).size()); } @Test @@ -286,16 +260,16 @@ class FlatFileDatabaseManagerTest { File file = prepareDatabaseTestResource(DB_HEALTHY); //Existing DB int newUserTestStartingLvl = 1337; - db = new FlatFileDatabaseManager(file, logger, PURGE_TIME, newUserTestStartingLvl, true); - db.checkFileHealthAndStructure(); + var flatFileDatabaseManager = new FlatFileDatabaseManager(file, logger, PURGE_TIME, newUserTestStartingLvl, true); + flatFileDatabaseManager.checkFileHealthAndStructure(); - PlayerProfile playerProfile = db.newUser(playerName, uuid); + PlayerProfile playerProfile = flatFileDatabaseManager.newUser(playerName, uuid); assertTrue(playerProfile.isLoaded()); assertEquals(playerName, playerProfile.getPlayerName()); assertEquals(uuid, playerProfile.getUniqueId()); - PlayerProfile retrievedFromDisk = db.loadPlayerProfile(uuid); + PlayerProfile retrievedFromDisk = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(retrievedFromDisk.isLoaded()); assertEquals(playerName, retrievedFromDisk.getPlayerName()); assertEquals(uuid, retrievedFromDisk.getUniqueId()); @@ -305,15 +279,15 @@ class FlatFileDatabaseManagerTest { checkNewUserValues(retrievedFromDisk, newUserTestStartingLvl); //TODO: Should we do any dupe checking? Probably not needed as it would be caught on the next load - db.newUser("bidoof", new UUID(3, 3)); - db.newUser("derp", new UUID(3, 4)); - db.newUser("pizza", new UUID(3, 4)); + flatFileDatabaseManager.newUser("bidoof", new UUID(3, 3)); + flatFileDatabaseManager.newUser("derp", new UUID(3, 4)); + flatFileDatabaseManager.newUser("pizza", new UUID(3, 4)); - assertEquals(7, getSplitDataFromFile(db.getUsersFile()).size()); + assertEquals(7, getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()).size()); - //Now we *fix* the DB and there should be one less - db.checkFileHealthAndStructure(); - assertEquals(6, getSplitDataFromFile(db.getUsersFile()).size()); + //Now we *fix* the flatFileDatabaseManager and there should be one less + flatFileDatabaseManager.checkFileHealthAndStructure(); + assertEquals(6, getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()).size()); } private void checkNewUserValues(@NotNull PlayerProfile playerProfile, int startingLevel) { @@ -338,71 +312,45 @@ class FlatFileDatabaseManagerTest { @Test void testLoadByUUID() { File dbFile = prepareDatabaseTestResource(DB_HEALTHY); - - /* - * We have established the files are in good order, so now for the actual testing - */ - - //This makes sure our private method is working before the tests run afterwards - ArrayList dataFromFile = getSplitDataFromFile(dbFile); - logger.info("File Path: " + dbFile.getAbsolutePath()); - assertArrayEquals(HEALTHY_DB_LINE_1.split(":"), dataFromFile.get(0)); - assertEquals(dataFromFile.get(0)[FlatFileDatabaseManager.UUID_INDEX], HEALTHY_DB_LINE_ONE_UUID_STR); - - db = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); - List flagsFound = db.checkFileHealthAndStructure(); + var flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found /* - * Once the DB looks fine load the profile + * Once the flatFileDatabaseManager looks fine load the profile */ String playerName = "nossr50"; UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); - PlayerProfile profile1 = db.loadPlayerProfile(uuid); + PlayerProfile profile1 = flatFileDatabaseManager.loadPlayerProfile(uuid); testHealthyDataProfileValues(playerName, uuid, profile1); - assertFalse(db.loadPlayerProfile(new UUID(0, 1)).isLoaded()); //This profile should not exist and therefor will return unloaded + assertFalse(flatFileDatabaseManager.loadPlayerProfile(new UUID(0, 1)).isLoaded()); //This profile should not exist and therefor will return unloaded } @Test void testLoadByUUIDAndName() { File dbFile = prepareDatabaseTestResource(DB_HEALTHY); - - /* - * We have established the files are in good order, so now for the actual testing - */ - - //This makes sure our private method is working before the tests run afterwards - ArrayList dataFromFile = getSplitDataFromFile(dbFile); - logger.info("File Path: " + dbFile.getAbsolutePath()); - assertArrayEquals(HEALTHY_DB_LINE_1.split(":"), dataFromFile.get(0)); - assertEquals(dataFromFile.get(0)[FlatFileDatabaseManager.UUID_INDEX], HEALTHY_DB_LINE_ONE_UUID_STR); - - db = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); - List flagsFound = db.checkFileHealthAndStructure(); + var flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found - /* - * Once the DB looks fine load the profile - */ - String playerName = "nossr50"; UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); Player player = initMockPlayer(playerName, uuid); - PlayerProfile profile1 = db.loadPlayerProfile(player); + PlayerProfile profile1 = flatFileDatabaseManager.loadPlayerProfile(player); testHealthyDataProfileValues(playerName, uuid, profile1); String updatedName = "updatedName"; Player updatedNamePlayer = initMockPlayer(updatedName, uuid); - PlayerProfile updatedNameProfile = db.loadPlayerProfile(updatedNamePlayer); + PlayerProfile updatedNameProfile = flatFileDatabaseManager.loadPlayerProfile(updatedNamePlayer); testHealthyDataProfileValues(updatedName, uuid, updatedNameProfile); Player shouldNotExist = initMockPlayer("doesntexist", new UUID(0, 1)); - PlayerProfile profile3 = db.loadPlayerProfile(shouldNotExist); + PlayerProfile profile3 = flatFileDatabaseManager.loadPlayerProfile(shouldNotExist); assertFalse(profile3.isLoaded()); } @@ -484,6 +432,7 @@ class FlatFileDatabaseManagerTest { case BLAST_MINING -> expectedBlastMiningCd; case TRIDENTS_SUPER_ABILITY -> expectedTridentSuperCd; case EXPLOSIVE_SHOT -> expectedExplosiveShotCd; + case MACES_SUPER_ABILITY -> expectedMacesSuperCd; default -> throw new RuntimeException("Values not defined for super ability please add " + "values for " + superAbilityType.toString() + " to the test"); }; @@ -491,165 +440,147 @@ class FlatFileDatabaseManagerTest { } private float getExpectedExperienceHealthyDBEntryOne(@NotNull PrimarySkillType primarySkillType) { - switch(primarySkillType) { - case ACROBATICS: - return expectedExpAcrobatics; - case ALCHEMY: - return expectedExpAlchemy; - case ARCHERY: - return expectedExpArchery; - case AXES: - return expectedExpAxes; - case CROSSBOWS: - return expectedExpCrossbows; - case EXCAVATION: - return expectedExpExcavation; - case FISHING: - return expectedExpFishing; - case HERBALISM: - return expectedExpHerbalism; - case MINING: - return expectedExpMining; - case REPAIR: - return expectedExpRepair; - case SALVAGE: - case SMELTING: - return 0; - case SWORDS: - return expectedExpSwords; - case TAMING: - return expectedExpTaming; - case TRIDENTS: - return expectedExpTridents; - case UNARMED: - return expectedExpUnarmed; - case WOODCUTTING: - return expectedExpWoodcutting; - } + return switch (primarySkillType) { + case ACROBATICS -> expectedExpAcrobatics; + case ALCHEMY -> expectedExpAlchemy; + case ARCHERY -> expectedExpArchery; + case AXES -> expectedExpAxes; + case CROSSBOWS -> expectedExpCrossbows; + case EXCAVATION -> expectedExpExcavation; + case FISHING -> expectedExpFishing; + case HERBALISM -> expectedExpHerbalism; + case MINING -> expectedExpMining; + case REPAIR -> expectedExpRepair; + case SALVAGE, SMELTING -> 0; + case SWORDS -> expectedExpSwords; + case TAMING -> expectedExpTaming; + case TRIDENTS -> expectedExpTridents; + case UNARMED -> expectedExpUnarmed; + case WOODCUTTING -> expectedExpWoodcutting; + case MACES -> expectedExpMaces; + default -> + throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); + }; - throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); } private int getExpectedLevelHealthyDBEntryOne(@NotNull PrimarySkillType primarySkillType) { - switch(primarySkillType) { - case ACROBATICS: - return expectedLvlAcrobatics; - case ALCHEMY: - return expectedLvlAlchemy; - case ARCHERY: - return expectedLvlArchery; - case AXES: - return expectedLvlAxes; - case CROSSBOWS: - return expectedLvlCrossbows; - case EXCAVATION: - return expectedLvlExcavation; - case FISHING: - return expectedLvlFishing; - case HERBALISM: - return expectedLvlHerbalism; - case MINING: - return expectedLvlMining; - case REPAIR: - return expectedLvlRepair; - case SALVAGE: - case SMELTING: - return 0; - case SWORDS: - return expectedLvlSwords; - case TAMING: - return expectedLvlTaming; - case TRIDENTS: - return expectedLvlTridents; - case UNARMED: - return expectedLvlUnarmed; - case WOODCUTTING: - return expectedLvlWoodcutting; - } + return switch (primarySkillType) { + case ACROBATICS -> expectedLvlAcrobatics; + case ALCHEMY -> expectedLvlAlchemy; + case ARCHERY -> expectedLvlArchery; + case AXES -> expectedLvlAxes; + case CROSSBOWS -> expectedLvlCrossbows; + case EXCAVATION -> expectedLvlExcavation; + case FISHING -> expectedLvlFishing; + case HERBALISM -> expectedLvlHerbalism; + case MINING -> expectedLvlMining; + case REPAIR -> expectedLvlRepair; + case SALVAGE, SMELTING -> 0; + case SWORDS -> expectedLvlSwords; + case TAMING -> expectedLvlTaming; + case TRIDENTS -> expectedLvlTridents; + case UNARMED -> expectedLvlUnarmed; + case WOODCUTTING -> expectedLvlWoodcutting; + case MACES -> expectedLvlMaces; + default -> + throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); + }; - throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); } @Test void testOverwriteName() { - overwriteDataAndCheckForFlag(db, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); - ArrayList splitDataLines = getSplitDataFromFile(db.getUsersFile()); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); + ArrayList splitDataLines = getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()); assertNotEquals(splitDataLines.get(1)[0], splitDataLines.get(0)[0]); //Name comparison } @Test void testDataNotFound() { + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); //Save the zero version and see if it looks correct - assertNotNull(db); - assertTrue(db.getUsersFile().exists()); - assertNotNull(db.getUsersFile()); + assertNotNull(flatFileDatabaseManager); + assertTrue(flatFileDatabaseManager.getUsersFile().exists()); + assertNotNull(flatFileDatabaseManager.getUsersFile()); //Check for the "unloaded" profile - PlayerProfile retrievedFromData = db.loadPlayerProfile("nossr50"); + PlayerProfile retrievedFromData = flatFileDatabaseManager.loadPlayerProfile("nossr50"); assertFalse(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns false if data doesn't exist for the user } @Test void testPurgePowerlessUsers() { - replaceDataInFile(db, normalDatabaseData); - int purgeCount = db.purgePowerlessUsers(); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + replaceDataInFile(flatFileDatabaseManager, normalDatabaseData); + int purgeCount = flatFileDatabaseManager.purgePowerlessUsers(); assertEquals(purgeCount, 1); //1 User should have been purged } @Test void testCheckFileHealthAndStructure() { - replaceDataInFile(db, badDatabaseData); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + replaceDataInFile(flatFileDatabaseManager, badDatabaseData); - List dataFlags = db.checkFileHealthAndStructure(); + List dataFlags = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNotNull(dataFlags); assertNotEquals(dataFlags.size(), 0); } @Test void testFindFixableDuplicateNames() { - overwriteDataAndCheckForFlag(db, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); } @Test void testFindDuplicateUUIDs() { - overwriteDataAndCheckForFlag(db, duplicateUUIDDatabaseData, FlatFileDataFlag.DUPLICATE_UUID); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateUUIDDatabaseData, FlatFileDataFlag.DUPLICATE_UUID); } @Test() void findBadUUIDData() { - overwriteDataAndCheckForFlag(db, badUUIDDatabaseData, FlatFileDataFlag.BAD_UUID_DATA); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, badUUIDDatabaseData, FlatFileDataFlag.BAD_UUID_DATA); } @Test void testFindCorruptData() { - overwriteDataAndCheckForFlag(db, corruptDatabaseData, FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, corruptDatabaseData, FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); } @Test void testFindEmptyNames() { - overwriteDataAndCheckForFlag(db, emptyNameDatabaseData, FlatFileDataFlag.MISSING_NAME); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, emptyNameDatabaseData, FlatFileDataFlag.MISSING_NAME); } @Test void testFindBadValues() { - overwriteDataAndCheckForFlag(db, badDatabaseData, FlatFileDataFlag.BAD_VALUES); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, badDatabaseData, FlatFileDataFlag.BAD_VALUES); } @Test void testFindOutdatedData() { - overwriteDataAndCheckForFlag(db, outdatedDatabaseData, FlatFileDataFlag.INCOMPLETE); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, outdatedDatabaseData, FlatFileDataFlag.INCOMPLETE); } @Test void testGetDatabaseType() { - assertNotNull(db); - assertEquals(db.getDatabaseType(), DatabaseType.FLATFILE); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + assertNotNull(flatFileDatabaseManager); + assertEquals(flatFileDatabaseManager.getDatabaseType(), DatabaseType.FLATFILE); } @Test void testReadRank() { //This is an empty DB - assertNotNull(db); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); String rankBoyName = "rankBoy"; UUID rankBoyUUID = new UUID(1337, 1337); String rankGirlName = "rankGirl"; @@ -658,9 +589,9 @@ class FlatFileDatabaseManagerTest { PlayerProfile rankGirlProfile = addPlayerProfileWithLevelsAndSave(rankGirlName, rankGirlUUID, 100); //Rank 1 PlayerProfile rankBoyProfile = addPlayerProfileWithLevelsAndSave(rankBoyName, rankBoyUUID, 10); //Rank 2 - assertEquals(LeaderboardStatus.UPDATED, db.updateLeaderboards()); - Map rankGirlPositions = db.readRank(rankGirlName); - Map rankBoyPositions = db.readRank(rankBoyName); + assertEquals(LeaderboardStatus.UPDATED, flatFileDatabaseManager.updateLeaderboards()); + Map rankGirlPositions = flatFileDatabaseManager.readRank(rankGirlName); + Map rankBoyPositions = flatFileDatabaseManager.readRank(rankBoyName); for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { if(primarySkillType.isChildSkill()) { @@ -672,8 +603,8 @@ class FlatFileDatabaseManagerTest { } } - assertEquals(1, db.readRank(rankGirlName).get(null)); //Girl should be position 1 - assertEquals(2, db.readRank(rankBoyName).get(null)); //Boy should be position 2 + assertEquals(1, flatFileDatabaseManager.readRank(rankGirlName).get(null)); //Girl should be position 1 + assertEquals(2, flatFileDatabaseManager.readRank(rankBoyName).get(null)); //Boy should be position 2 } @Test @@ -741,11 +672,11 @@ class FlatFileDatabaseManagerTest { } private @NotNull PlayerProfile addPlayerProfileWithLevelsAndSave(String playerName, UUID uuid, int levels) { - assertNotNull(db); - assertFalse(db.loadPlayerProfile(uuid).isLoaded()); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + assertFalse(flatFileDatabaseManager.loadPlayerProfile(uuid).isLoaded()); - db.newUser(playerName, uuid); - PlayerProfile leveledProfile = db.loadPlayerProfile(uuid); + flatFileDatabaseManager.newUser(playerName, uuid); + PlayerProfile leveledProfile = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(leveledProfile.isLoaded()); assertEquals(playerName, leveledProfile.getPlayerName()); @@ -758,8 +689,8 @@ class FlatFileDatabaseManagerTest { leveledProfile.modifySkill(primarySkillType, levels); //TODO: This method also resets XP, not cool } - db.saveUser(leveledProfile); - leveledProfile = db.loadPlayerProfile(uuid); + flatFileDatabaseManager.saveUser(leveledProfile); + leveledProfile = flatFileDatabaseManager.loadPlayerProfile(uuid); for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { if(SkillTools.isChildSkill(primarySkillType)) { diff --git a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java new file mode 100644 index 000000000..8b01720f7 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java @@ -0,0 +1,51 @@ +package com.gmail.nossr50.util; + +import org.bukkit.potion.PotionType; +import org.junit.jupiter.api.Test; + +import static com.gmail.nossr50.util.PotionUtil.convertLegacyNames; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PotionUtilTest { + + @Test + void testDisplay() { +// System.out.println("\n"); +// System.out.println("\n"); +// System.out.println("\n"); +// System.out.println("\n"); +// for(var s : PotionType.values()) { +// System.out.println("PotionType.getKey().getKey(): " + s.getKey().getKey()); +// System.out.println("PotionType.name(): " + s.name()); +// System.out.println("PotionType.toString():" + s.toString()); +// System.out.println("\n"); +// } + } + + @Test + void testMatchPotionType() { + String potionTypeStr = "UNCRAFTABLE"; + PotionType potionType = matchPotionType(potionTypeStr, false, false); + assertEquals(PotionType.WATER, potionType); + + String potionTypeStr2 = "NIGHT_VISION"; + PotionType potionType2 = matchPotionType(potionTypeStr2, false, false); + assertEquals(PotionType.NIGHT_VISION, potionType2); + + String nightVisionLong = "NIGHT_VISION"; + PotionType potionType3 = matchPotionType(nightVisionLong, false, true); + assertEquals(PotionType.LONG_NIGHT_VISION, potionType3); + + nightVisionLong = "LONG_NIGHT_VISION"; + potionType3 = matchPotionType(nightVisionLong, false, true); + assertEquals(PotionType.LONG_NIGHT_VISION, potionType3); + } + + @Test + void testConvertLegacyNames() { + final String potionTypeStr = "UNCRAFTABLE"; + final String converted = convertLegacyNames(potionTypeStr); + assertEquals("WATER", converted); + } +} \ No newline at end of file diff --git a/src/test/resources/healthydb.users b/src/test/resources/healthydb.users index 79a2c7e70..c2561b38d 100644 --- a/src/test/resources/healthydb.users +++ b/src/test/resources/healthydb.users @@ -1,3 +1,3 @@ -nossr50:1:IGNORED:IGNORED:10:2:20:3:4:5:6:7:8:9:10:30:40:50:60:70:80:90:100:IGNORED:11:110:111:222:333:444:555:666:777:IGNORED:12:120:888:IGNORED:HEARTS:13:130:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1111:999:2020:140:14:150:15:1111:2222:3333: -mrfloris:2420:::0:2452:0:1983:1937:1790:3042:1138:3102:2408:3411:0:0:0:0:0:0:0:0::642:0:1617583171:0:1617165043:0:1617583004:1617563189:1616785408::2184:0:0:1617852413:HEARTS:415:0:631e3896-da2a-4077-974b-d047859d76bc:5:1600906906:3030:0:0:0:0:0:0:0: -powerless:0:::0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0::0:0:0:0:0:0:0:0:0::0:0:0:1337:HEARTS:0:0:e0d07db8-f7e8-43c7-9ded-864dfc6f3b7c:5:1600906906:4040:0:0:0:0:0:0:0: \ No newline at end of file +nossr50:1:IGNORED:IGNORED:10:2:20:3:4:5:6:7:8:9:10:30:40:50:60:70:80:90:100:IGNORED:11:110:111:222:333:444:555:666:777:IGNORED:12:120:888:IGNORED:HEARTS:13:130:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1111:999:2020:140:14:150:15:1111:2222:3333:160:16:4444: +mrfloris:2420:::0:2452:0:1983:1937:1790:3042:1138:3102:2408:3411:0:0:0:0:0:0:0:0::642:0:1617583171:0:1617165043:0:1617583004:1617563189:1616785408::2184:0:0:1617852413:HEARTS:415:0:631e3896-da2a-4077-974b-d047859d76bc:5:1600906906:3030:0:0:0:0:0:0:0:0:0:0: +powerless:0:::0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0::0:0:0:0:0:0:0:0:0::0:0:0:1337:HEARTS:0:0:e0d07db8-f7e8-43c7-9ded-864dfc6f3b7c:5:1600906906:4040:0:0:0:0:0:0:0:0:0:0: \ No newline at end of file From e29a977b9a074025169980f471b340d7b9c301d1 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Thu, 2 May 2024 06:32:47 -0700 Subject: [PATCH 02/34] fix mistake in skillranks.yml --- src/main/resources/skillranks.yml | 45 +++++++++++++++---------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/src/main/resources/skillranks.yml b/src/main/resources/skillranks.yml index 2df17807a..e6cea3643 100644 --- a/src/main/resources/skillranks.yml +++ b/src/main/resources/skillranks.yml @@ -444,29 +444,28 @@ Salvage: Rank_7: 850 Rank_8: 1000 Maces: - TridentsLimitBreak: - Standard: - Rank_1: 10 - Rank_2: 20 - Rank_3: 30 - Rank_4: 40 - Rank_5: 50 - Rank_6: 60 - Rank_7: 70 - Rank_8: 80 - Rank_9: 90 - Rank_10: 100 - RetroMode: - Rank_1: 100 - Rank_2: 200 - Rank_3: 300 - Rank_4: 400 - Rank_5: 500 - Rank_6: 600 - Rank_7: 700 - Rank_8: 800 - Rank_9: 900 - Rank_10: 1000 + Standard: + Rank_1: 10 + Rank_2: 20 + Rank_3: 30 + Rank_4: 40 + Rank_5: 50 + Rank_6: 60 + Rank_7: 70 + Rank_8: 80 + Rank_9: 90 + Rank_10: 100 + RetroMode: + Rank_1: 100 + Rank_2: 200 + Rank_3: 300 + Rank_4: 400 + Rank_5: 500 + Rank_6: 600 + Rank_7: 700 + Rank_8: 800 + Rank_9: 900 + Rank_10: 1000 Mining: MotherLode: Standard: From 5b822bc62609ea4476dcacd6cc0d32b2d687dbc0 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Thu, 2 May 2024 06:39:20 -0700 Subject: [PATCH 03/34] add armadillos to xp --- Changelog.txt | 4 +++- src/main/resources/experience.yml | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Changelog.txt b/Changelog.txt index eb01a4712..504a6e766 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,5 +1,7 @@ Version 2.2.007 - Compatibility with the 1.20.5 MC Update + Compatibility with the 1.20.5 / 1.20.6 MC Update + Added armadillo to combat experience in experience.yml + Fixed bug where Alchemy was not brewing certain potions (haste, etc) Alchemy now has more warning/errors that will print out to help debug Fixed bug where Green Thumb did not replant if seed was in the off hand diff --git a/src/main/resources/experience.yml b/src/main/resources/experience.yml index a4838cd67..13fe09386 100644 --- a/src/main/resources/experience.yml +++ b/src/main/resources/experience.yml @@ -580,6 +580,7 @@ Experience_Values: Combat: Multiplier: Animals: 1.0 + Armadillo: 1.1 Creeper: 4.0 Skeleton: 3.0 Spider: 2.0 From 75561350c1d4cb05a45e6c1d6b439dbb6495833a Mon Sep 17 00:00:00 2001 From: nossr50 Date: Fri, 3 May 2024 13:53:53 -0700 Subject: [PATCH 04/34] fix issues with Alchemy and older MC versions --- Changelog.txt | 4 +- pom.xml | 13 +++- .../config/skills/alchemy/PotionConfig.java | 18 +++--- .../skills/alchemy/AlchemyPotion.java | 37 +++++------ .../skills/subskills/acrobatics/Roll.java | 4 +- .../protocollib/ProtocolLibManager.java | 18 ++++++ .../skills/AlchemyBrewCheckTask.java | 4 +- .../runnables/skills/AlchemyBrewTask.java | 61 ++++++++++++++----- .../gmail/nossr50/skills/alchemy/Alchemy.java | 34 ----------- .../skills/alchemy/AlchemyPotionBrewer.java | 33 ++++++++-- .../com/gmail/nossr50/util/PotionUtil.java | 8 +-- .../gmail/nossr50/util/text/StringUtils.java | 5 ++ src/main/resources/plugin.yml | 2 +- .../gmail/nossr50/util/PotionUtilTest.java | 52 ++++++---------- 14 files changed, 165 insertions(+), 128 deletions(-) create mode 100644 src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java diff --git a/Changelog.txt b/Changelog.txt index 504a6e766..4e3d3c86d 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,8 +1,8 @@ Version 2.2.007 Compatibility with the 1.20.5 / 1.20.6 MC Update - Added armadillo to combat experience in experience.yml Fixed bug where Alchemy was not brewing certain potions (haste, etc) - Alchemy now has more warning/errors that will print out to help debug + Fixed bug where the probability of success of Graceful Roll was not being calculated correctly + Added armadillo to combat experience in experience.yml Fixed bug where Green Thumb did not replant if seed was in the off hand NOTES: diff --git a/pom.xml b/pom.xml index 136deebdf..466d48791 100644 --- a/pom.xml +++ b/pom.xml @@ -222,6 +222,11 @@ + + + dmulloy2-repo + https://repo.dmulloy2.net/repository/public/ + spigot-repo https://hub.spigotmc.org/nexus/content/repositories/snapshots/ @@ -268,6 +273,12 @@ 3.25.3 test + + com.comphenix.protocol + ProtocolLib + LATEST + compile + com.h2database h2 @@ -364,7 +375,7 @@ org.spigotmc spigot-api - 1.20.5-R0.1-SNAPSHOT + 1.19.2-R0.1-SNAPSHOT provided diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 37b992dad..9df3115b8 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -15,15 +15,14 @@ import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionType; +import org.codehaus.plexus.util.StringUtils; import org.jetbrains.annotations.VisibleForTesting; import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; import static com.gmail.nossr50.util.PotionUtil.*; +import static com.gmail.nossr50.util.text.StringUtils.convertKeyToName; public class PotionConfig extends LegacyConfigLoader { @@ -130,7 +129,7 @@ public class PotionConfig extends LegacyConfigLoader { final String key = potion_section.getName(); final String displayName = potion_section.getString("Name") != null ? LocaleLoader.addColors(potion_section.getString("Name")) - : null; + : convertKeyToName(key); final ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData"); boolean extended = false; @@ -165,12 +164,16 @@ public class PotionConfig extends LegacyConfigLoader { return null; } + // Set the name of the potion + potionMeta.setDisplayName(displayName); + // extended and upgraded seem to be mutually exclusive if (extended && upgraded) { mcMMO.p.getLogger().warning("Potion " + key + " has both Extended and Upgraded set to true," + " defaulting to Extended."); upgraded = false; } + String potionTypeStr = potionData.getString("PotionType", null); if (potionTypeStr == null) { mcMMO.p.getLogger().severe("PotionConfig: Missing PotionType for " + displayName + ", from configuration section:" + @@ -186,7 +189,9 @@ public class PotionConfig extends LegacyConfigLoader { } if (potionType == null) { - mcMMO.p.getLogger().severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr); + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr + + ", upgraded: " + upgraded + ", extended: " + extended + " for potion " + displayName + + ", from configuration section: " + potion_section); return null; } @@ -357,5 +362,4 @@ public class PotionConfig extends LegacyConfigLoader { } return Color.fromRGB(red / colors.size(), green / colors.size(), blue / colors.size()); } - } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java index c2e2ee656..c7b7fd442 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java @@ -7,7 +7,6 @@ import org.bukkit.inventory.meta.PotionMeta; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; @@ -16,18 +15,18 @@ import static com.gmail.nossr50.util.PotionUtil.samePotionType; import static java.util.Objects.requireNonNull; public class AlchemyPotion { - private final ItemStack potion; - private final Map alchemyPotionChildren; + private final @NotNull ItemStack potionItemstack; + private final @NotNull Map alchemyPotionChildren; - public AlchemyPotion(ItemStack potion, Map alchemyPotionChildren) { - this.potion = requireNonNull(potion, "potion cannot be null"); + public AlchemyPotion(@NotNull ItemStack potionItemStack, @NotNull Map alchemyPotionChildren) { + this.potionItemstack = requireNonNull(potionItemStack, "potionItemStack cannot be null"); this.alchemyPotionChildren = requireNonNull(alchemyPotionChildren, "alchemyPotionChildren cannot be null"); } public @NotNull ItemStack toItemStack(int amount) { - final ItemStack potion = new ItemStack(this.potion); - potion.setAmount(Math.max(1, amount)); - return potion; + final ItemStack clone = potionItemstack.clone(); + clone.setAmount(Math.max(1, amount)); + return clone; } public Map getAlchemyPotionChildren() { @@ -49,7 +48,7 @@ public class AlchemyPotion { requireNonNull(otherPotion, "otherPotion cannot be null"); // TODO: Investigate? // We currently don't compare base potion effects, likely because they are derived from the potion type - if (otherPotion.getType() != potion.getType() || !otherPotion.hasItemMeta()) { + if (otherPotion.getType() != potionItemstack.getType() || !otherPotion.hasItemMeta()) { return false; } @@ -76,25 +75,19 @@ public class AlchemyPotion { return false; } - if (!otherPotionMeta.hasDisplayName() && getAlchemyPotionMeta().hasDisplayName()) { - return false; - } - - var alchemyPotionName = getAlchemyPotionMeta().hasDisplayName() ? getAlchemyPotionMeta().getDisplayName() : null; - - return (alchemyPotionName == null && !otherPotionMeta.hasDisplayName()) || otherPotionMeta.getDisplayName().equals(alchemyPotionName); + return true; } public PotionMeta getAlchemyPotionMeta() { - return (PotionMeta) potion.getItemMeta(); + return (PotionMeta) potionItemstack.getItemMeta(); } public boolean isSplash() { - return potion.getType() == Material.SPLASH_POTION; + return potionItemstack.getType() == Material.SPLASH_POTION; } public boolean isLingering() { - return potion.getType() == Material.LINGERING_POTION; + return potionItemstack.getType() == Material.LINGERING_POTION; } @Override @@ -102,18 +95,18 @@ public class AlchemyPotion { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlchemyPotion that = (AlchemyPotion) o; - return Objects.equals(potion, that.potion) && Objects.equals(alchemyPotionChildren, that.alchemyPotionChildren); + return Objects.equals(potionItemstack, that.potionItemstack) && Objects.equals(alchemyPotionChildren, that.alchemyPotionChildren); } @Override public int hashCode() { - return Objects.hash(potion, alchemyPotionChildren); + return Objects.hash(potionItemstack, alchemyPotionChildren); } @Override public String toString() { return "AlchemyPotion{" + - "potion=" + potion + + "potion=" + potionItemstack + ", alchemyPotionChildren=" + alchemyPotionChildren + '}'; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java index 1ea4692a0..e4fece3c4 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java @@ -136,7 +136,7 @@ public class Roll extends AcrobaticsSubSkill { * Graceful is double the odds of a normal roll */ Probability probability = getRollProbability(player); - Probability gracefulProbability = Probability.ofPercent(probability.getValue() * 2); + Probability gracefulProbability = Probability.ofValue(probability.getValue() * 2); String[] gracefulRollStrings = ProbabilityUtil.getRNGDisplayValues(gracefulProbability); gracefulRollChance = gracefulRollStrings[0]; gracefulRollChanceLucky = gracefulRollStrings[1]; @@ -274,7 +274,7 @@ public class Roll extends AcrobaticsSubSkill { @NotNull public static Probability getGracefulProbability(Player player) { double gracefulOdds = ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, player).getValue() * 2; - return Probability.ofPercent(gracefulOdds); + return Probability.ofValue(gracefulOdds); } /** diff --git a/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java b/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java new file mode 100644 index 000000000..7b82ac9d9 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java @@ -0,0 +1,18 @@ +package com.gmail.nossr50.protocollib; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.plugin.Plugin; + +// TODO: Finish this class +public class ProtocolLibManager { + Plugin protocolLibPluginRef; + mcMMO pluginRef; + public ProtocolLibManager(mcMMO pluginRef) { + this.pluginRef = pluginRef; + } + + public boolean isProtocolLibPresent() { + protocolLibPluginRef = pluginRef.getServer().getPluginManager().getPlugin("ProtocolLib"); + return protocolLibPluginRef != null; + } +} diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java index 68de298f5..f0121fa8e 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java @@ -3,6 +3,7 @@ package com.gmail.nossr50.runnables.skills; import com.gmail.nossr50.skills.alchemy.Alchemy; import com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer; import com.gmail.nossr50.util.CancellableRunnable; +import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.BrewingStand; import org.bukkit.entity.Player; @@ -31,8 +32,7 @@ public class AlchemyBrewCheckTask extends CancellableRunnable { if (oldInventory[Alchemy.INGREDIENT_SLOT] == null || newInventory[Alchemy.INGREDIENT_SLOT] == null || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) || !validBrew) { Alchemy.brewingStandMap.get(location).cancelBrew(); } - } - else if (validBrew) { + } else if (validBrew) { Alchemy.brewingStandMap.put(location, new AlchemyBrewTask(brewingStand, player)); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java index de5ea2adb..73e415f53 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java @@ -11,6 +11,7 @@ import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; +import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.BlockState; @@ -67,33 +68,65 @@ public class AlchemyBrewTask extends CancellableRunnable { @Override public void run() { - if (player == null || !player.isValid() || brewingStand == null || brewingStand.getType() != Material.BREWING_STAND || !AlchemyPotionBrewer.isValidIngredient(player, ((BrewingStand) brewingStand).getInventory().getContents()[Alchemy.INGREDIENT_SLOT])) { + // Check if preconditions for brewing are not met + if (shouldCancelBrewing()) { if (Alchemy.brewingStandMap.containsKey(location)) { Alchemy.brewingStandMap.remove(location); } - this.cancel(); - return; } + // Initialize the brewing stand on the first run + initializeBrewing(); + + // Update the brewing process timer + brewTimer -= brewSpeed; + + // Check if the brewing process should finish + if (isBrewingComplete()) { + this.cancel(); + finish(); + } else { + updateBrewingTime(); + } + } + + private boolean shouldCancelBrewing() { + if (player == null) { + return true; + } + if (!player.isValid()) { + return true; + } + if (brewingStand == null) { + return true; + } + if (brewingStand.getType() != Material.BREWING_STAND) { + return true; + } + if (!AlchemyPotionBrewer.isValidIngredient(player, ((BrewingStand) brewingStand).getInventory().getContents()[Alchemy.INGREDIENT_SLOT])) { + return true; + } + return false; + } + + private void initializeBrewing() { if (firstRun) { firstRun = false; ((BrewingStand) brewingStand).setFuelLevel(fuel); } - - brewTimer -= brewSpeed; - - // Vanilla potion brewing completes when BrewingTime == 1 - if (brewTimer < Math.max(brewSpeed, 2)) { - this.cancel(); - finish(); - } - else { - ((BrewingStand) brewingStand).setBrewingTime((int) brewTimer); - } } + private boolean isBrewingComplete() { + return brewTimer < Math.max(brewSpeed, 2); + } + + private void updateBrewingTime() { + ((BrewingStand) brewingStand).setBrewingTime((int) brewTimer); + } + + private void finish() { McMMOPlayerBrewEvent event = new McMMOPlayerBrewEvent(player, brewingStand); mcMMO.p.getServer().getPluginManager().callEvent(event); diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java b/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java index c6c5470a3..d921bc3a2 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java @@ -11,40 +11,6 @@ import java.util.List; import java.util.Map; public final class Alchemy { - /*public enum Tier { - EIGHT(8), - SEVEN(7), - SIX(6), - FIVE(5), - FOUR(4), - THREE(3), - TWO(2), - ONE(1); - - int numerical; - - private Tier(int numerical) { - this.numerical = numerical; - } - - public int toNumerical() { - return numerical; - } - - public static Tier fromNumerical(int numerical) { - for (Tier tier : Tier.values()) { - if (tier.toNumerical() == numerical) { - return tier; - } - } - return null; - } - - protected int getLevel() { - return mcMMO.p.getAdvancedConfig().getConcoctionsTierLevel(this); - } - }*/ - public static final int INGREDIENT_SLOT = 3; public static int catalysisMaxBonusLevel = mcMMO.p.getAdvancedConfig().getCatalysisMaxBonusLevel(); diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index a41ea2f2f..1b5ee9850 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -9,6 +9,7 @@ import com.gmail.nossr50.runnables.player.PlayerUpdateInventoryTask; import com.gmail.nossr50.runnables.skills.AlchemyBrewCheckTask; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; +import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; @@ -31,7 +32,9 @@ public final class AlchemyPotionBrewer { } for (int i = 0; i < 3; i++) { - if (contents[i] == null || contents[i].getType() != Material.POTION && contents[i].getType() != Material.SPLASH_POTION && contents[i].getType() != Material.LINGERING_POTION) { + if (contents[i] == null || contents[i].getType() != Material.POTION + && contents[i].getType() != Material.SPLASH_POTION + && contents[i].getType() != Material.LINGERING_POTION) { continue; } @@ -101,52 +104,71 @@ public final class AlchemyPotionBrewer { } public static void finishBrewing(BlockState brewingStand, Player player, boolean forced) { + // Check if the brewing stand block state is an actual brewing stand if (!(brewingStand instanceof BrewingStand)) { return; } - BrewerInventory inventory = ((BrewingStand) brewingStand).getInventory(); - ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); + // Retrieve the inventory of the brewing stand and clone the current ingredient for safe manipulation + final BrewerInventory inventory = ((BrewingStand) brewingStand).getInventory(); + final ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); + // Check if the brewing stand has a valid ingredient; if not, exit the method if (!hasIngredient(inventory, player)) { + // debug return; } + // Initialize lists to hold the potions before and after brewing, initially setting them to null List inputList = new ArrayList<>(Collections.nCopies(3, null)); List outputList = new ArrayList<>(Collections.nCopies(3, null)); + // Process each of the three slots in the brewing stand for (int i = 0; i < 3; i++) { ItemStack item = inventory.getItem(i); - if (isEmpty(item) || item.getType() == Material.GLASS_BOTTLE || !mcMMO.p.getPotionConfig().isValidPotion(item)) { + // Skip the slot if it's empty, contains a glass bottle, or holds an invalid potion + if (isEmpty(item) + || item.getType() == Material.GLASS_BOTTLE + || !mcMMO.p.getPotionConfig().isValidPotion(item)) { + // debug continue; } + // Retrieve the potion configurations for the input and resulting output potion AlchemyPotion input = mcMMO.p.getPotionConfig().getPotion(item); AlchemyPotion output = input.getChild(ingredient); + // Update the input list with the current potion inputList.set(i, input); + // If there is a valid output potion, add it to the output list if (output != null) { outputList.set(i, output.toItemStack(item.getAmount()).clone()); } } + // Create a fake brewing event and pass it to the plugin's event system FakeBrewEvent event = new FakeBrewEvent(brewingStand.getBlock(), inventory, outputList, ((BrewingStand) brewingStand).getFuelLevel()); mcMMO.p.getServer().getPluginManager().callEvent(event); + // If the event is cancelled or there are no potions processed, exit the method if (event.isCancelled() || inputList.isEmpty()) { + // debug return; } + // Update the brewing inventory with the new potions for (int i = 0; i < 3; i++) { if(outputList.get(i) != null) { inventory.setItem(i, outputList.get(i)); } } + // Remove the used ingredient from the brewing inventory removeIngredient(inventory, player); + // Handle potion brewing success and related effects for each potion processed for (AlchemyPotion input : inputList) { if (input == null) continue; @@ -155,13 +177,14 @@ public final class AlchemyPotionBrewer { if (output != null && player != null) { PotionStage potionStage = PotionStage.getPotionStage(input, output); - //TODO: hmm + // Update player alchemy skills or effects based on brewing success if (UserManager.hasPlayerDataKey(player)) { UserManager.getPlayer(player).getAlchemyManager().handlePotionBrewSuccesses(potionStage, 1); } } } + // If the brewing was not forced by external conditions, schedule a new update if (!forced) { scheduleUpdate(inventory); } diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java index d1e255bde..fb1c9289b 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionUtil.java +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -39,6 +39,7 @@ public class PotionUtil { static { // We used to use uncraftable as the potion type // this type isn't available anymore, so water will do + potionDataClass = getPotionDataClass(); legacyPotionTypes.put("UNCRAFTABLE", "WATER"); legacyPotionTypes.put("JUMP", "LEAPING"); legacyPotionTypes.put("SPEED", "SWIFTNESS"); @@ -55,9 +56,8 @@ public class PotionUtil { methodPotionTypeGetEffectType = getPotionTypeEffectType(); methodPotionTypeGetPotionEffects = getPotionTypeGetPotionEffects(); methodSetBasePotionData = getSetBasePotionData(); - potionDataClass = getPotionDataClass(); - if (methodPotionMetaGetBasePotionData != null) { + if (potionDataClass != null) { COMPATIBILITY_MODE = PotionCompatibilityType.PRE_1_20_5; } else { COMPATIBILITY_MODE = PotionCompatibilityType.POST_1_20_5; @@ -161,7 +161,7 @@ public class PotionUtil { */ private static @Nullable Method getBasePotionData() { try { - return PotionType.class.getMethod("getBasePotionData"); + return PotionMeta.class.getMethod("getBasePotionData"); } catch (NoSuchMethodException e) { return null; } @@ -419,7 +419,7 @@ public class PotionUtil { * @param upgraded true if the potion is upgraded */ public static void setBasePotionType(PotionMeta potionMeta, PotionType potionType, boolean extended, boolean upgraded) { - if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + if (methodPotionMetaSetBasePotionType == null) { setBasePotionTypeLegacy(potionMeta, potionType, extended, upgraded); } else { setBasePotionTypeModern(potionMeta, potionType); diff --git a/src/main/java/com/gmail/nossr50/util/text/StringUtils.java b/src/main/java/com/gmail/nossr50/util/text/StringUtils.java index d0252a846..a6fa01180 100644 --- a/src/main/java/com/gmail/nossr50/util/text/StringUtils.java +++ b/src/main/java/com/gmail/nossr50/util/text/StringUtils.java @@ -186,4 +186,9 @@ public class StringUtils { } } + public static String convertKeyToName(@NotNull String key) { + // used when no display name is given for a potion + final String noUnderscores = key.replace("_", " ").toLowerCase(Locale.ENGLISH); + return org.codehaus.plexus.util.StringUtils.capitalise(noUnderscores); + } } diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 457a7e54b..52500d4cb 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -14,7 +14,7 @@ author: nossr50 authors: [GJ, NuclearW, bm01, Glitchfinder, TfT_02, t00thpick1, Riking, electronicboy, kashike] website: https://www.mcmmo.org main: com.gmail.nossr50.mcMMO -softdepend: [WorldGuard, CombatTag, HealthBar, PlaceholderAPI] +softdepend: [WorldGuard, CombatTag, HealthBar, PlaceholderAPI, ProtocolLib] load: POSTWORLD folia-supported: true api-version: 1.13 diff --git a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java index 8b01720f7..caa3a1218 100644 --- a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java @@ -1,46 +1,30 @@ package com.gmail.nossr50.util; -import org.bukkit.potion.PotionType; import org.junit.jupiter.api.Test; import static com.gmail.nossr50.util.PotionUtil.convertLegacyNames; -import static com.gmail.nossr50.util.PotionUtil.matchPotionType; import static org.junit.jupiter.api.Assertions.assertEquals; class PotionUtilTest { - @Test - void testDisplay() { -// System.out.println("\n"); -// System.out.println("\n"); -// System.out.println("\n"); -// System.out.println("\n"); -// for(var s : PotionType.values()) { -// System.out.println("PotionType.getKey().getKey(): " + s.getKey().getKey()); -// System.out.println("PotionType.name(): " + s.name()); -// System.out.println("PotionType.toString():" + s.toString()); -// System.out.println("\n"); -// } - } - - @Test - void testMatchPotionType() { - String potionTypeStr = "UNCRAFTABLE"; - PotionType potionType = matchPotionType(potionTypeStr, false, false); - assertEquals(PotionType.WATER, potionType); - - String potionTypeStr2 = "NIGHT_VISION"; - PotionType potionType2 = matchPotionType(potionTypeStr2, false, false); - assertEquals(PotionType.NIGHT_VISION, potionType2); - - String nightVisionLong = "NIGHT_VISION"; - PotionType potionType3 = matchPotionType(nightVisionLong, false, true); - assertEquals(PotionType.LONG_NIGHT_VISION, potionType3); - - nightVisionLong = "LONG_NIGHT_VISION"; - potionType3 = matchPotionType(nightVisionLong, false, true); - assertEquals(PotionType.LONG_NIGHT_VISION, potionType3); - } +// @Test +// void testMatchPotionType() { +// String potionTypeStr = "UNCRAFTABLE"; +// PotionType potionType = matchPotionType(potionTypeStr, false, false); +// assertEquals(PotionType.WATER, potionType); +// +// String potionTypeStr2 = "NIGHT_VISION"; +// PotionType potionType2 = matchPotionType(potionTypeStr2, false, false); +// assertEquals(PotionType.NIGHT_VISION, potionType2); +// +// String nightVisionLong = "NIGHT_VISION"; +// PotionType potionType3 = matchPotionType(nightVisionLong, false, true); +// assertEquals(PotionType.LONG_NIGHT_VISION, potionType3); +// +// nightVisionLong = "LONG_NIGHT_VISION"; +// potionType3 = matchPotionType(nightVisionLong, false, true); +// assertEquals(PotionType.LONG_NIGHT_VISION, potionType3); +// } @Test void testConvertLegacyNames() { From 5ba6305ad4d5047cd22fdf6614a73c8dd4953ed6 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 4 May 2024 10:26:43 -0700 Subject: [PATCH 05/34] 2.2.007 --- Changelog.txt | 7 ++- pom.xml | 18 +++--- .../config/experience/ExperienceConfig.java | 2 +- src/main/java/com/gmail/nossr50/mcMMO.java | 8 +++ .../nossr50/protocollib/ProtocolHandler.java | 36 ++++++++++++ .../protocollib/ProtocolLibManager.java | 58 +++++++++++++------ .../skills/alchemy/AlchemyPotionBrewer.java | 2 +- .../woodcutting/WoodcuttingManager.java | 10 +++- .../com/gmail/nossr50/util/PotionUtil.java | 3 +- src/main/resources/experience.yml | 23 ++++---- 10 files changed, 122 insertions(+), 45 deletions(-) create mode 100644 src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java diff --git a/Changelog.txt b/Changelog.txt index 4e3d3c86d..fe6f1b950 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,11 +1,16 @@ Version 2.2.007 Compatibility with the 1.20.5 / 1.20.6 MC Update Fixed bug where Alchemy was not brewing certain potions (haste, etc) + Tree Feller no longer restricts how many saplings can drop + Tree Feller now drops leaves 25% of the time (up from 10%) + Alchemy XP has been DRAMATICALLY increased, it was extremely grindy by default + Alchemy experience values in experience.yml are now found under 'Experience_Values.Alchemy.Potion_Brewing' Fixed bug where the probability of success of Graceful Roll was not being calculated correctly - Added armadillo to combat experience in experience.yml Fixed bug where Green Thumb did not replant if seed was in the off hand + Added armadillo to combat experience in experience.yml NOTES: + While fixing various Alchemy bugs, I noticed Alchemy leveled SUPER slow, I have increased it dramatically. Feel free to change it back by modifying the new values in experience.yml I did my best to keep mcMMO compatible with older versions of Minecraft for this update. This update to MC was quite large, with breaking changes to a lot of code relating to Alchemy, and some other things. I expect there to be bugs, please report them on GitHub or Discord, but preferably GitHub. diff --git a/pom.xml b/pom.xml index 466d48791..8693a420f 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.007-SNAPSHOT + 2.2.007 mcMMO https://github.com/mcMMO-Dev/mcMMO @@ -304,37 +304,37 @@ net.kyori adventure-text-serializer-gson - 4.15.0 + 4.16.0 net.kyori adventure-text-serializer-gson-legacy-impl - 4.15.0 + 4.16.0 net.kyori adventure-text-serializer-json - 4.15.0 + 4.16.0 net.kyori adventure-text-serializer-json-legacy-impl - 4.15.0 + 4.16.0 net.kyori adventure-api - 4.15.0 + 4.16.0 net.kyori adventure-nbt - 4.15.0 + 4.16.0 net.kyori adventure-key - 4.15.0 + 4.16.0 net.kyori @@ -375,7 +375,7 @@ org.spigotmc spigot-api - 1.19.2-R0.1-SNAPSHOT + 1.20.5-R0.1-SNAPSHOT provided diff --git a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java index b64e3b62b..4eddee5db 100644 --- a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java +++ b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java @@ -467,7 +467,7 @@ public class ExperienceConfig extends BukkitConfig { /* Alchemy */ public double getPotionXP(PotionStage stage) { - return config.getDouble("Experience_Values.Alchemy.Potion_Stage_" + stage.toNumerical(), 10D); + return config.getDouble("Experience_Values.Alchemy.Potion_Brewing.Stage_" + stage.toNumerical(), 10D); } /* Archery */ diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 3a806e8be..423a46333 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -95,6 +95,7 @@ public class mcMMO extends JavaPlugin { private static ChatManager chatManager; private static CommandManager commandManager; //ACF private static TransientEntityTracker transientEntityTracker; +// private static ProtocolLibManager protocolLibManager; private SkillTools skillTools; @@ -364,6 +365,9 @@ public class mcMMO extends JavaPlugin { if(getServer().getPluginManager().getPlugin("WorldGuard") != null) { WorldGuardManager.getInstance().registerFlags(); } + + // ProtocolLib + // protocolLibManager = new ProtocolLibManager(this); } /** @@ -825,4 +829,8 @@ public class mcMMO extends JavaPlugin { public @NotNull FoliaLib getFoliaLib() { return foliaLib; } + +// public ProtocolLibManager getProtocolLibManager() { +// return protocolLibManager; +// } } diff --git a/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java b/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java new file mode 100644 index 000000000..bae3793f9 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java @@ -0,0 +1,36 @@ +//package com.gmail.nossr50.protocollib; +// +//import com.comphenix.protocol.PacketType; +//import com.comphenix.protocol.ProtocolLibrary; +//import com.comphenix.protocol.ProtocolManager; +//import com.comphenix.protocol.events.ListenerPriority; +//import com.comphenix.protocol.events.PacketAdapter; +//import com.comphenix.protocol.events.PacketContainer; +//import com.comphenix.protocol.events.PacketEvent; +//import com.gmail.nossr50.mcMMO; +//import org.bukkit.entity.Player; +// +//public class ProtocolHandler { +// private final mcMMO pluginRef; +// private final ProtocolManager protocolManager; +// +// public ProtocolHandler(mcMMO pluginRef) { +// this.pluginRef = pluginRef; +// this.protocolManager = ProtocolLibrary.getProtocolManager(); +// // TODO: encapsulate this in a method +// protocolManager.addPacketListener(new PacketAdapter(pluginRef, ListenerPriority.NORMAL, PacketType.Play.Server.WINDOW_DATA) { +// @Override +// public void onPacketSending(PacketEvent event) { +// Player player = event.getPlayer(); +// PacketContainer packet = event.getPacket(); +// if (packet.getIntegers().read(0) == 400) { +// event.setCancelled(true); +// } +// } +// }); +// } +// public void sendPacketToPlayer(Player player) { +// final PacketContainer packet = protocolManager.createPacket(PacketType.Play.Server.WINDOW_DATA); +// protocolManager.sendServerPacket(player, packet); +// } +//} diff --git a/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java b/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java index 7b82ac9d9..77f3c21bf 100644 --- a/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java +++ b/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java @@ -1,18 +1,40 @@ -package com.gmail.nossr50.protocollib; - -import com.gmail.nossr50.mcMMO; -import org.bukkit.plugin.Plugin; - -// TODO: Finish this class -public class ProtocolLibManager { - Plugin protocolLibPluginRef; - mcMMO pluginRef; - public ProtocolLibManager(mcMMO pluginRef) { - this.pluginRef = pluginRef; - } - - public boolean isProtocolLibPresent() { - protocolLibPluginRef = pluginRef.getServer().getPluginManager().getPlugin("ProtocolLib"); - return protocolLibPluginRef != null; - } -} +//package com.gmail.nossr50.protocollib; +// +//import com.gmail.nossr50.mcMMO; +//import org.bukkit.Bukkit; +//import org.bukkit.entity.Player; +//import org.bukkit.plugin.Plugin; +// +//public class ProtocolLibManager { +// final Plugin protocolLibPluginRef; +// final mcMMO pluginRef; +// final ProtocolHandler protocolHandler; +// +// public ProtocolLibManager(mcMMO pluginRef) { +// this.pluginRef = pluginRef; +// +// if (isProtocolLibPresent()) { +// protocolLibPluginRef = pluginRef.getServer().getPluginManager().getPlugin("ProtocolLib"); +// protocolHandler = new ProtocolHandler(pluginRef); +// pluginRef.getLogger().info("ProtocolLib found, enabling ProtocolLib features."); +// } else { +// protocolLibPluginRef = null; +// protocolHandler = null; +// pluginRef.getLogger().info("No ProtocolLib found, some completely optional cosmetic features will not be enabled."); +// } +// } +// +// public boolean usingProtocolLib() { +// return protocolLibPluginRef != null && protocolHandler != null; +// } +// +// private boolean isProtocolLibPresent() { +// return Bukkit.getServer().getPluginManager().getPlugin("ProtocolLib") != null; +// } +// +// public void sendPacketToPlayer(Player player) { +// if (usingProtocolLib()) { +// protocolHandler.sendPacketToPlayer(player); +// } +// } +//} diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index 1b5ee9850..82b2e0e85 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -178,7 +178,7 @@ public final class AlchemyPotionBrewer { PotionStage potionStage = PotionStage.getPotionStage(input, output); // Update player alchemy skills or effects based on brewing success - if (UserManager.hasPlayerDataKey(player)) { + if (UserManager.getPlayer(player) != null) { UserManager.getPlayer(player).getAlchemyManager().handlePotionBrewSuccesses(potionStage, 1); } } diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java index dd198131e..c4ee8e41c 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java @@ -323,9 +323,13 @@ public class WoodcuttingManager extends SkillManager { //Bonus Drops / Harvest lumber checks processBonusDropCheck(blockState); } else if (BlockUtils.isNonWoodPartOfTree(blockState)) { - // 90% of the time do not drop leaf blocks - if (ThreadLocalRandom.current().nextInt(100) > 90) { - Misc.spawnItemsFromCollection(getPlayer(), Misc.getBlockCenter(blockState), block.getDrops(itemStack), ItemSpawnReason.TREE_FELLER_DISPLACED_BLOCK); + // 75% of the time do not drop leaf blocks + if (blockState.getType().getKey().getKey().toLowerCase().contains("sapling") + || ThreadLocalRandom.current().nextInt(100) > 75) { + Misc.spawnItemsFromCollection(getPlayer(), + Misc.getBlockCenter(blockState), + block.getDrops(itemStack), + ItemSpawnReason.TREE_FELLER_DISPLACED_BLOCK); } //Drop displaced non-woodcutting XP blocks diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java index fb1c9289b..a83897a5f 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionUtil.java +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.mcMMO; +import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffectType; @@ -404,7 +405,7 @@ public class PotionUtil { try { PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); List potionEffectTypeList = (List) methodPotionTypeGetPotionEffects.invoke(potionType); - return potionEffectTypeList != null || !potionEffectTypeList.isEmpty(); + return potionEffectTypeList != null && !potionEffectTypeList.isEmpty(); } catch (IllegalAccessException | InvocationTargetException ex) { throw new RuntimeException(ex); } diff --git a/src/main/resources/experience.yml b/src/main/resources/experience.yml index 13fe09386..84df0e214 100644 --- a/src/main/resources/experience.yml +++ b/src/main/resources/experience.yml @@ -239,17 +239,18 @@ Experience_Values: # FeatherFall_Multiplier: Multiply Acrobatics XP by this value when wearing boots with the Feather Fall enchant FeatherFall_Multiplier: 2.0 Alchemy: - # Alchemy potion stages are based on the number of ingredients added - # Potion_Stage_1 represents a base potion - # Potion_Stage_2 represents a base potion with one ingredient - # Potion_Stage_3 represents a base potion with one ingredient and one amplifier - # Potion_Stage_4 represents a base potion with one ingredient and two amplifiers - # Potion_Stage_5 represents a base potion with one ingredient where the amplifiers are swapped - Potion_Stage_1: 15 - Potion_Stage_2: 30 - Potion_Stage_3: 60 - Potion_Stage_4: 120 - Potion_Stage_5: 0 + Potion_Brewing: + # Alchemy potion stages are based on the number of ingredients added + # Stage_1 represents a base potion + # Stage_2 represents a base potion with one ingredient + # Stage_3 represents a base potion with one ingredient and one amplifier + # Stage_4 represents a base potion with one ingredient and two amplifiers + # Stage_5 represents a base potion with one ingredient where the amplifiers are swapped + Stage_1: 120 + Stage_2: 240 + Stage_3: 480 + Stage_4: 960 + Stage_5: 0 Archery: Distance_Multiplier: 0.025 Fishing: From fb0c8ec9347839affa9f5b7f9cac5e0326d3953c Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 11 May 2024 15:05:27 -0700 Subject: [PATCH 06/34] Fix potions not brewing as the correct type --- Changelog.txt | 6 +++ pom.xml | 2 +- .../config/skills/alchemy/PotionConfig.java | 39 +++++++++----- .../skills/alchemy/AlchemyPotion.java | 30 ++++++++--- .../datatypes/skills/alchemy/PotionStage.java | 9 ++-- .../nossr50/listeners/InventoryListener.java | 13 +++++ .../skills/AlchemyBrewCheckTask.java | 5 +- .../skills/alchemy/AlchemyManager.java | 5 ++ .../skills/alchemy/AlchemyPotionBrewer.java | 3 +- .../com/gmail/nossr50/util/PotionUtil.java | 54 ++++++++++++++++--- .../gmail/nossr50/util/PotionUtilTest.java | 2 +- .../util/random/ProbabilityTestUtils.java | 2 +- 12 files changed, 135 insertions(+), 35 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index fe6f1b950..2bbd5e969 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,3 +1,9 @@ +Version 2.2.008 + Fixed alchemy potions not upgrading correctly (See notes) + + NOTES: + Alchemy potions will now be brewed as type "Mundane" behind the scenes, this used to be Uncraftable/Water. This led to some issues. So I've changed it to be Mundane. + Version 2.2.007 Compatibility with the 1.20.5 / 1.20.6 MC Update Fixed bug where Alchemy was not brewing certain potions (haste, etc) diff --git a/pom.xml b/pom.xml index 8693a420f..99c18b60d 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.007 + 2.2.008-SNAPSHOT mcMMO https://github.com/mcMMO-Dev/mcMMO diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 9df3115b8..50466ced4 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -127,9 +127,6 @@ public class PotionConfig extends LegacyConfigLoader { private AlchemyPotion loadPotion(ConfigurationSection potion_section) { try { final String key = potion_section.getName(); - final String displayName = potion_section.getString("Name") != null - ? LocaleLoader.addColors(potion_section.getString("Name")) - : convertKeyToName(key); final ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData"); boolean extended = false; @@ -159,14 +156,11 @@ public class PotionConfig extends LegacyConfigLoader { final PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); if (potionMeta == null) { - mcMMO.p.getLogger().severe("PotionConfig: Failed to get PotionMeta for " + displayName + ", from configuration section:" + + mcMMO.p.getLogger().severe("PotionConfig: Failed to get PotionMeta for " + key + ", from configuration section:" + " " + potion_section); return null; } - // Set the name of the potion - potionMeta.setDisplayName(displayName); - // extended and upgraded seem to be mutually exclusive if (extended && upgraded) { mcMMO.p.getLogger().warning("Potion " + key + " has both Extended and Upgraded set to true," + @@ -176,7 +170,7 @@ public class PotionConfig extends LegacyConfigLoader { String potionTypeStr = potionData.getString("PotionType", null); if (potionTypeStr == null) { - mcMMO.p.getLogger().severe("PotionConfig: Missing PotionType for " + displayName + ", from configuration section:" + + mcMMO.p.getLogger().severe("PotionConfig: Missing PotionType for " + key + ", from configuration section:" + " " + potion_section); return null; } @@ -190,7 +184,7 @@ public class PotionConfig extends LegacyConfigLoader { if (potionType == null) { mcMMO.p.getLogger().severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr - + ", upgraded: " + upgraded + ", extended: " + extended + " for potion " + displayName + + ", upgraded: " + upgraded + ", extended: " + extended + " for potion " + key + ", from configuration section: " + potion_section); return null; } @@ -225,7 +219,7 @@ public class PotionConfig extends LegacyConfigLoader { if (type != null) { potionMeta.addCustomEffect(new PotionEffect(type, duration, amplifier), true); } else { - mcMMO.p.getLogger().severe("PotionConfig: Failed to parse effect for potion " + displayName + ": " + effect); + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse effect for potion " + key + ": " + effect); } } } @@ -238,17 +232,21 @@ public class PotionConfig extends LegacyConfigLoader { } potionMeta.setColor(color); - Map children = new HashMap<>(); + final Map children = new HashMap<>(); if (potion_section.contains("Children")) { for (String child : potion_section.getConfigurationSection("Children").getKeys(false)) { ItemStack ingredient = loadIngredient(child); if (ingredient != null) { children.put(ingredient, potion_section.getConfigurationSection("Children").getString(child)); } else { - mcMMO.p.getLogger().severe("PotionConfig: Failed to parse child for potion " + displayName + ": " + child); + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse child for potion " + key + ": " + child); } } } + + // Set the name of the potion + setPotionDisplayName(potion_section, potionMeta); + // TODO: Might not need to .setItemMeta itemStack.setItemMeta(potionMeta); return new AlchemyPotion(itemStack, children); @@ -258,6 +256,23 @@ public class PotionConfig extends LegacyConfigLoader { } } + private void setPotionDisplayName(ConfigurationSection section, PotionMeta potionMeta) { + String configuredName = section.getString("Name", null); + if (configuredName != null) { + potionMeta.setDisplayName(configuredName); + return; + } + + // Potion is water, but has effects + if (isPotionTypeWater(potionMeta) + && (PotionUtil.hasBasePotionEffects(potionMeta) || !potionMeta.getCustomEffects().isEmpty())) { + // If we don't set a name for these potions, they will simply be called "Water Potion" + final String name = section.getName().toUpperCase().replace("_", " "); + potionMeta.setDisplayName(name); + System.out.println("DEBUG: Renaming potion to " + name); + } + } + /** * Parse a string representation of an ingredient. * Format: '<MATERIAL>[:data]' diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java index c7b7fd442..fb5ea7899 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java @@ -53,12 +53,11 @@ public class AlchemyPotion { } final PotionMeta otherPotionMeta = (PotionMeta) otherPotion.getItemMeta(); - - // all custom effects must be present - for (var effect : getAlchemyPotionMeta().getCustomEffects()) { - if (!otherPotionMeta.hasCustomEffect(effect.getType())) { - return false; - } + // compare custom effects on both potions, this has to be done in two traversals + // comparing thisPotionMeta -> otherPotionMeta and otherPotionMeta -> thisPotionMeta + if (hasDifferingCustomEffects(getAlchemyPotionMeta(), otherPotionMeta) + || hasDifferingCustomEffects(otherPotionMeta, getAlchemyPotionMeta())) { + return false; } if (!samePotionType(getAlchemyPotionMeta(), otherPotionMeta)) { @@ -78,6 +77,25 @@ public class AlchemyPotion { return true; } + private boolean hasDifferingCustomEffects(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + for (int i = 0; i < potionMeta.getCustomEffects().size(); i++) { + var effect = potionMeta.getCustomEffects().get(i); + + // One has an effect the other does not, they are not the same potion + if (!otherPotionMeta.hasCustomEffect(effect.getType())) { + return true; + } + + var otherEffect = otherPotionMeta.getCustomEffects().get(i); + // Amplifier or duration are not equal, they are not the same potion + if (effect.getAmplifier() != otherEffect.getAmplifier() + || effect.getDuration() != otherEffect.getDuration()) { + return true; + } + } + return false; + } + public PotionMeta getAlchemyPotionMeta() { return (PotionMeta) potionItemstack.getItemMeta(); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java index 4515835d1..303cf3b19 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java @@ -34,12 +34,13 @@ public enum PotionStage { } public static PotionStage getPotionStage(AlchemyPotion input, AlchemyPotion output) { - PotionStage potionStage = getPotionStage(output); - if (!isWaterBottle(input) && getPotionStage(input) == potionStage) { - potionStage = PotionStage.FIVE; + PotionStage outputPotionStage = getPotionStage(output); + PotionStage inputPotionStage = getPotionStage(input); + if (!isWaterBottle(input) && inputPotionStage == outputPotionStage) { + outputPotionStage = PotionStage.FIVE; } - return potionStage; + return outputPotionStage; } private static boolean isWaterBottle(AlchemyPotion alchemyPotion) { diff --git a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java index 4467ff723..879fbb820 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java @@ -5,6 +5,7 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.events.fake.FakeBrewEvent; +import com.gmail.nossr50.events.fake.FakeEvent; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.player.PlayerUpdateInventoryTask; import com.gmail.nossr50.skills.alchemy.Alchemy; @@ -28,6 +29,7 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; +import org.bukkit.event.block.BrewingStartEvent; import org.bukkit.event.inventory.*; import org.bukkit.inventory.*; @@ -343,6 +345,7 @@ public class InventoryListener implements Listener { if (event instanceof FakeBrewEvent) return; + Location location = event.getBlock().getLocation(); if (Alchemy.brewingStandMap.containsKey(location)) { Alchemy.brewingStandMap.get(location).finishImmediately(); @@ -350,6 +353,16 @@ public class InventoryListener implements Listener { } } +// @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) +// public void onBrewStart(BrewingStartEvent event) { +// /* WORLD BLACKLIST CHECK */ +// if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) +// return; +// +// if (event instanceof FakeEvent) +// return; +// } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) { /* WORLD BLACKLIST CHECK */ diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java index f0121fa8e..224538244 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java @@ -29,7 +29,10 @@ public class AlchemyBrewCheckTask extends CancellableRunnable { boolean validBrew = brewingStand.getFuelLevel() > 0 && AlchemyPotionBrewer.isValidBrew(player, newInventory); if (Alchemy.brewingStandMap.containsKey(location)) { - if (oldInventory[Alchemy.INGREDIENT_SLOT] == null || newInventory[Alchemy.INGREDIENT_SLOT] == null || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) || !validBrew) { + if (oldInventory[Alchemy.INGREDIENT_SLOT] == null + || newInventory[Alchemy.INGREDIENT_SLOT] == null + || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) + || !validBrew) { Alchemy.brewingStandMap.get(location).cancelBrew(); } } else if (validBrew) { diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java index 4224ad123..8cc53bc5b 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java @@ -52,6 +52,11 @@ public class AlchemyManager extends SkillManager { return Math.min(Alchemy.catalysisMaxSpeed, Alchemy.catalysisMinSpeed + (Alchemy.catalysisMaxSpeed - Alchemy.catalysisMinSpeed) * (skillLevel - RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS)) / (Alchemy.catalysisMaxBonusLevel - RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS))) * (isLucky ? LUCKY_MODIFIER : 1.0); } + /** + * Handle the XP gain for a successful potion brew. + * @param potionStage The potion stage, this is used to determine the XP gain. + * @param amount The amount of potions brewed. + */ public void handlePotionBrewSuccesses(PotionStage potionStage, int amount) { applyXpGain((float) (ExperienceConfig.getInstance().getPotionXP(potionStage) * amount), XPGainReason.PVE, XPGainSource.PASSIVE); } diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index 82b2e0e85..1060e3f5c 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -38,7 +38,8 @@ public final class AlchemyPotionBrewer { continue; } - if (getChildPotion(mcMMO.p.getPotionConfig().getPotion(contents[i]), contents[Alchemy.INGREDIENT_SLOT]) != null) { + final AlchemyPotion potion = mcMMO.p.getPotionConfig().getPotion(contents[i]); + if (getChildPotion(potion, contents[Alchemy.INGREDIENT_SLOT]) != null) { return true; } } diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java index a83897a5f..0661cd487 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionUtil.java +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -1,7 +1,6 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.mcMMO; -import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffectType; @@ -33,15 +32,16 @@ public class PotionUtil { public static final String STRONG = "STRONG"; public static final String LONG = "LONG"; - public static final String LEGACY_WATER_POTION_TYPE = "WATER"; + public static final String WATER_POTION_TYPE_STR = "WATER"; private static final PotionCompatibilityType COMPATIBILITY_MODE; static { - // We used to use uncraftable as the potion type - // this type isn't available anymore, so water will do potionDataClass = getPotionDataClass(); - legacyPotionTypes.put("UNCRAFTABLE", "WATER"); + // Uncraftable doesn't exist in modern versions + // It served as a potion that didn't craft into anything else so it didn't conflict with vanilla systems + // Instead we will use Mundane, which doesn't make anything in vanilla systems + legacyPotionTypes.put("UNCRAFTABLE", "MUNDANE"); legacyPotionTypes.put("JUMP", "LEAPING"); legacyPotionTypes.put("SPEED", "SWIFTNESS"); legacyPotionTypes.put("INSTANT_HEAL", "HEALING"); @@ -314,6 +314,12 @@ public class PotionUtil { return (NamespacedKey) methodPotionTypeGetKey.invoke(potionType); } + public static boolean isPotionJustWater(PotionMeta potionMeta) { + return isPotionTypeWater(potionMeta) + && !hasBasePotionEffects(potionMeta) + && potionMeta.getCustomEffects().isEmpty(); + } + public static boolean isPotionTypeWater(@NotNull PotionMeta potionMeta) { if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { return isPotionTypeWaterLegacy(potionMeta); @@ -322,12 +328,44 @@ public class PotionUtil { } } + public static boolean isPotionType(@NotNull PotionMeta potionMeta, String potionType) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return isPotionTypeLegacy(potionMeta, potionType); + } else { + return isPotionTypeModern(potionMeta, potionType); + } + } + + public static boolean isPotionTypeWithoutEffects(@NotNull PotionMeta potionMeta, String potionType) { + return isPotionType(potionMeta, potionType) + && !hasBasePotionEffects(potionMeta) + && potionMeta.getCustomEffects().isEmpty(); + } + + private static boolean isPotionTypeModern(@NotNull PotionMeta potionMeta, String potionType) { + try { + return getModernPotionTypeKey(potionMeta).getKey().equalsIgnoreCase(potionType); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean isPotionTypeLegacy(@NotNull PotionMeta potionMeta, String potionType) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + PotionType potionTypeObj = (PotionType) methodPotionDataGetType.invoke(potionData); + return potionTypeObj.name().equalsIgnoreCase(potionType); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + private static boolean isPotionTypeWaterLegacy(@NotNull PotionMeta potionMeta) { try { Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); - return potionType.name().equalsIgnoreCase(LEGACY_WATER_POTION_TYPE) - || PotionType.valueOf(LEGACY_WATER_POTION_TYPE) == potionType; + return potionType.name().equalsIgnoreCase(WATER_POTION_TYPE_STR) + || PotionType.valueOf(WATER_POTION_TYPE_STR) == potionType; } catch (InvocationTargetException | IllegalAccessException ex) { throw new RuntimeException(ex); } @@ -335,7 +373,7 @@ public class PotionUtil { private static boolean isPotionTypeWaterModern(@NotNull PotionMeta potionMeta) { try { - return getModernPotionTypeKey(potionMeta).getKey().equalsIgnoreCase(LEGACY_WATER_POTION_TYPE); + return getModernPotionTypeKey(potionMeta).getKey().equalsIgnoreCase(WATER_POTION_TYPE_STR); } catch (IllegalAccessException | InvocationTargetException ex) { throw new RuntimeException(ex); } diff --git a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java index caa3a1218..d60c0f7cb 100644 --- a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java @@ -30,6 +30,6 @@ class PotionUtilTest { void testConvertLegacyNames() { final String potionTypeStr = "UNCRAFTABLE"; final String converted = convertLegacyNames(potionTypeStr); - assertEquals("WATER", converted); + assertEquals("MUNDANE", converted); } } \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java index e97119be6..0e41b4649 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java @@ -16,7 +16,7 @@ public class ProbabilityTestUtils { System.out.println("Wins: " + winCount); System.out.println("Fails: " + (iterations - winCount)); System.out.println("Percentage succeeded: " + successPercent + ", Expected: " + expectedWinPercent); - assertEquals(expectedWinPercent, successPercent, 0.025D); + assertEquals(expectedWinPercent, successPercent, 0.035D); System.out.println("Variance is within tolerance levels!"); } } From df6ddd6faa7ce7e3168a4a5f1e250eda7d36d73a Mon Sep 17 00:00:00 2001 From: IAISI <126729304+IAISI@users.noreply.github.com> Date: Sun, 12 May 2024 00:07:01 +0200 Subject: [PATCH 07/34] CombatUtils: Don't run checks against party features if parties are disabled (#5005) Co-authored-by: Dieu --- .../java/com/gmail/nossr50/util/skills/CombatUtils.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java index 168d778a3..35057f1f9 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java @@ -968,8 +968,10 @@ public final class CombatUtils { return false; } - if ((mcMMO.p.getPartyManager().inSameParty(player, defender) || mcMMO.p.getPartyManager().areAllies(player, defender)) && !(Permissions.friendlyFire(player) && Permissions.friendlyFire(defender))) { - return false; + if(mcMMO.p.getPartyConfig().isPartyEnabled()) { + if ((mcMMO.p.getPartyManager().inSameParty(player, defender) || mcMMO.p.getPartyManager().areAllies(player, defender)) && !(Permissions.friendlyFire(player) && Permissions.friendlyFire(defender))) { + return false; + } } // Vanished players should not be able to get hit by AoE effects @@ -1019,7 +1021,7 @@ public final class CombatUtils { if (tamer instanceof Player owner) { - return (owner == attacker || mcMMO.p.getPartyManager().inSameParty(attacker, owner) || mcMMO.p.getPartyManager().areAllies(attacker, owner)); + return (owner == attacker || (mcMMO.p.getPartyConfig().isPartyEnabled() && (mcMMO.p.getPartyManager().inSameParty(attacker, owner) || mcMMO.p.getPartyManager().areAllies(attacker, owner)))); } } From 07b4736be34384bacf59993a5de3ecf1188f56d8 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 11 May 2024 15:07:45 -0700 Subject: [PATCH 08/34] update changelog --- Changelog.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Changelog.txt b/Changelog.txt index 2bbd5e969..42a122124 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,5 +1,6 @@ Version 2.2.008 Fixed alchemy potions not upgrading correctly (See notes) + Fixed some exceptions that could happen with parties disabled (thanks IAISI) NOTES: Alchemy potions will now be brewed as type "Mundane" behind the scenes, this used to be Uncraftable/Water. This led to some issues. So I've changed it to be Mundane. From b3edca530418b6a6ac0c3d91de594ed8aae82d04 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 11 May 2024 15:27:47 -0700 Subject: [PATCH 09/34] Fix italicized potion names --- Changelog.txt | 4 +++- .../config/skills/alchemy/PotionConfig.java | 21 +++++++++---------- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index 42a122124..8b9f0d1cb 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,8 +1,10 @@ Version 2.2.008 - Fixed alchemy potions not upgrading correctly (See notes) + Fixed alchemy potions not upgrading correctly (This will only affect new potions made, see notes) + Fixed a bug where alchemy potions had italicized names Fixed some exceptions that could happen with parties disabled (thanks IAISI) NOTES: + mcMMO-exclusive Potions (haste, etc) made on version 2.2.007 of mcMMO will not upgrade correctly, you'll just have to make new ones. Sorry for the inconvenience. Alchemy potions will now be brewed as type "Mundane" behind the scenes, this used to be Uncraftable/Water. This led to some issues. So I've changed it to be Mundane. Version 2.2.007 diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 50466ced4..dd6fdb4aa 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -259,18 +259,17 @@ public class PotionConfig extends LegacyConfigLoader { private void setPotionDisplayName(ConfigurationSection section, PotionMeta potionMeta) { String configuredName = section.getString("Name", null); if (configuredName != null) { - potionMeta.setDisplayName(configuredName); - return; - } - - // Potion is water, but has effects - if (isPotionTypeWater(potionMeta) - && (PotionUtil.hasBasePotionEffects(potionMeta) || !potionMeta.getCustomEffects().isEmpty())) { - // If we don't set a name for these potions, they will simply be called "Water Potion" - final String name = section.getName().toUpperCase().replace("_", " "); - potionMeta.setDisplayName(name); - System.out.println("DEBUG: Renaming potion to " + name); + potionMeta.setItemName(configuredName); } +// +// // Potion is water, but has effects +// if (isPotionTypeWater(potionMeta) +// && (PotionUtil.hasBasePotionEffects(potionMeta) || !potionMeta.getCustomEffects().isEmpty())) { +// // If we don't set a name for these potions, they will simply be called "Water Potion" +// final String name = section.getName().toUpperCase().replace("_", " "); +// potionMeta.setDisplayName(name); +// System.out.println("DEBUG: Renaming potion to " + name); +// } } /** From 0bf1bbe6ac1e57d240e6e847eb6239886f29724e Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 11 May 2024 15:48:11 -0700 Subject: [PATCH 10/34] Fixed messages not being sent to the action bar --- Changelog.txt | 1 + pom.xml | 27 +++++++++---------- .../util/player/NotificationManager.java | 9 +++---- 3 files changed, 18 insertions(+), 19 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index 8b9f0d1cb..4ae37c396 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,6 +1,7 @@ Version 2.2.008 Fixed alchemy potions not upgrading correctly (This will only affect new potions made, see notes) Fixed a bug where alchemy potions had italicized names + Fixed a bug where messages were not being sent to the action bar in 1.20.6 Fixed some exceptions that could happen with parties disabled (thanks IAISI) NOTES: diff --git a/pom.xml b/pom.xml index 99c18b60d..127b2d219 100644 --- a/pom.xml +++ b/pom.xml @@ -140,23 +140,22 @@ org.bstats:bstats-base org.bstats:bstats-bukkit net.kyori:adventure-api - net.kyori:adventure-text-serializer-gson - net.kyori:adventure-platform-bukkit - net.kyori:adventure-platform-api - net.kyori:adventure-platform-viaversion - net.kyori:adventure-platform-facet - net.kyori:adventure-nbt net.kyori:adventure-key + net.kyori:adventure-nbt + net.kyori:adventure-platform-api + net.kyori:adventure-platform-bukkit + net.kyori:adventure-platform-facet + net.kyori:adventure-platform-viaversion + net.kyori:adventure-text-serializer-bungeecord + net.kyori:adventure-text-serializer-gson + net.kyori:adventure-text-serializer-gson-legacy-impl + net.kyori:adventure-text-serializer-json + net.kyori:adventure-text-serializer-json-legacy-impl + net.kyori:adventure-text-serializer-legacy net.kyori:examination-api net.kyori:examination-string - net.kyori:adventure-text-serializer-legacy - net.kyori:adventure-text-serializer-gson - net.kyori:adventure-text-serializer-json - net.kyori:adventure-text-serializer-bungeecord - net.kyori:adventure-text-serializer-craftbukkit - net.kyori:adventure-text-serializer-gson-legacy-impl - net.kyori:adventure-text-serializer-json-legacy-impl net.kyori:option + net.kyori:adventure-text-serializer-craftbukkit co.aikar:acf-bukkit com.tcoded:FoliaLib @@ -344,7 +343,7 @@ net.kyori adventure-platform-bukkit - 4.3.2 + LATEST net.kyori diff --git a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java index 615ae3fbb..f41d740b7 100644 --- a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java @@ -121,14 +121,13 @@ public class NotificationManager { final Audience audience = mcMMO.getAudiences().player(player); - //If the message is being sent to the action bar we need to check if the copy if a copy is sent to the chat system + Component notificationTextComponent = customEvent.getNotificationTextComponent(); - if(customEvent.getChatMessageType() == McMMOMessageType.ACTION_BAR) - { + if(customEvent.getChatMessageType() == McMMOMessageType.ACTION_BAR) { audience.sendActionBar(notificationTextComponent); - if(customEvent.isMessageAlsoBeingSentToChat()) - { + // If the message is being sent to the action bar we need to check if a copy is also sent to the chat system + if(customEvent.isMessageAlsoBeingSentToChat()) { //Send copy to chat system audience.sendMessage(notificationTextComponent); } From 64206c3ac88f7549fe46619a637d6a6ba1899e78 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 11 May 2024 15:58:49 -0700 Subject: [PATCH 11/34] Fixed mccooldowns on SQL not working Fixes #5006 --- Changelog.txt | 1 + src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java | 1 + 2 files changed, 2 insertions(+) diff --git a/Changelog.txt b/Changelog.txt index 4ae37c396..feb4f4788 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -2,6 +2,7 @@ Version 2.2.008 Fixed alchemy potions not upgrading correctly (This will only affect new potions made, see notes) Fixed a bug where alchemy potions had italicized names Fixed a bug where messages were not being sent to the action bar in 1.20.6 + (SQL) Fixed bug that broke /mccooldowns and /archery in some circumstances Fixed some exceptions that could happen with parties disabled (thanks IAISI) NOTES: diff --git a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java index 3525f7211..a21f2fced 100644 --- a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java @@ -1273,6 +1273,7 @@ public final class SQLDatabaseManager implements DatabaseManager { skillsDATS.put(SuperAbilityType.BERSERK, result.getInt(OFFSET_DATS + 5)); skillsDATS.put(SuperAbilityType.GREEN_TERRA, result.getInt(OFFSET_DATS + 6)); skillsDATS.put(SuperAbilityType.GIGA_DRILL_BREAKER, result.getInt(OFFSET_DATS + 7)); + skillsDATS.put(SuperAbilityType.EXPLOSIVE_SHOT, result.getInt(OFFSET_DATS + 8)); // Archery - Unused - result.getInt(OFFSET_DATS + 8) skillsDATS.put(SuperAbilityType.SERRATED_STRIKES, result.getInt(OFFSET_DATS + 9)); skillsDATS.put(SuperAbilityType.SKULL_SPLITTER, result.getInt(OFFSET_DATS + 10)); From ed0c9469e2aeda445d6d974d060233dd945f9232 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 11 May 2024 16:01:47 -0700 Subject: [PATCH 12/34] don't show unimplemented supers for mccooldowns --- .../nossr50/datatypes/skills/SuperAbilityType.java | 6 ++---- .../gmail/nossr50/skills/maces/MacesManager.java | 8 -------- .../nossr50/skills/tridents/TridentsManager.java | 8 -------- .../java/com/gmail/nossr50/util/Permissions.java | 13 ------------- 4 files changed, 2 insertions(+), 33 deletions(-) diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java index f83bce316..3fcf2992c 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java @@ -206,17 +206,15 @@ public enum SuperAbilityType { public boolean getPermissions(Player player) { return switch (this) { case BERSERK -> Permissions.berserk(player); - case EXPLOSIVE_SHOT -> Permissions.explosiveShot(player); case BLAST_MINING -> Permissions.remoteDetonation(player); case GIGA_DRILL_BREAKER -> Permissions.gigaDrillBreaker(player); case GREEN_TERRA -> Permissions.greenTerra(player); case SERRATED_STRIKES -> Permissions.serratedStrikes(player); case SKULL_SPLITTER -> Permissions.skullSplitter(player); case SUPER_BREAKER -> Permissions.superBreaker(player); - case SUPER_SHOTGUN -> Permissions.superShotgun(player); case TREE_FELLER -> Permissions.treeFeller(player); - case TRIDENTS_SUPER_ABILITY -> Permissions.tridentsSuper(player); - case MACES_SUPER_ABILITY -> Permissions.macesSuper(player); + // TODO: once implemented, return permissions for the following abilities + case EXPLOSIVE_SHOT, TRIDENTS_SUPER_ABILITY, SUPER_SHOTGUN, MACES_SUPER_ABILITY -> false; }; } diff --git a/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java index 194c1400b..0e8b2e69b 100644 --- a/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java @@ -10,12 +10,4 @@ public class MacesManager extends SkillManager { public MacesManager(McMMOPlayer mmoPlayer) { super(mmoPlayer, PrimarySkillType.MACES); } - - /** - * Checks if the player can activate the Super Ability for Maces - * @return true if the player can activate the Super Ability, false otherwise - */ - public boolean canActivateAbility() { - return mmoPlayer.getToolPreparationMode(ToolType.MACES) && Permissions.macesSuper(getPlayer()); - } } diff --git a/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java b/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java index bd4296d0f..92d5d829b 100644 --- a/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java @@ -13,14 +13,6 @@ public class TridentsManager extends SkillManager { super(mmoPlayer, PrimarySkillType.TRIDENTS); } - /** - * Checks if the player can activate the Super Ability for Tridents - * @return true if the player can activate the Super Ability, false otherwise - */ - public boolean canActivateAbility() { - return mmoPlayer.getToolPreparationMode(ToolType.TRIDENTS) && Permissions.tridentsSuper(getPlayer()); - } - public double impaleDamageBonus() { int rank = RankUtils.getRank(getPlayer(), SubSkillType.TRIDENTS_IMPALE); diff --git a/src/main/java/com/gmail/nossr50/util/Permissions.java b/src/main/java/com/gmail/nossr50/util/Permissions.java index 5a78bcf18..66e6bab70 100644 --- a/src/main/java/com/gmail/nossr50/util/Permissions.java +++ b/src/main/java/com/gmail/nossr50/util/Permissions.java @@ -185,7 +185,6 @@ public final class Permissions { public static boolean concoctions(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.alchemy.concoctions"); } /* ARCHERY */ - public static boolean explosiveShot(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.archery.explosiveshot"); } public static boolean arrowRetrieval(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.archery.trackarrows"); } public static boolean daze(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.archery.daze"); } @@ -233,25 +232,13 @@ public final class Permissions { public static boolean treeFeller(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.woodcutting.treefeller"); } /* CROSSBOWS */ - public static boolean superShotgun(Permissible permissible) { - return permissible.hasPermission("mcmmo.ability.crossbows.supershotgun"); - } public static boolean trickShot(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.crossbows.trickshot"); } public static boolean poweredShot(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.crossbows.poweredshot"); } /* TRIDENTS */ - public static boolean tridentsSuper(Permissible permissible) { - return false; - // return permissible.hasPermission("mcmmo.ability.tridents.superability"); - } public static boolean tridentsLimitBreak(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.tridents.superability"); } /* MACES */ - public static boolean macesSuper(Permissible permissible) { - // TODO: When a super is added, change this - return false; - } - public static boolean macesLimitBreak(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.maces.limitbreak"); } /* From cae2132d8da2a4b855dc07ede7054b29bc59e4a4 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 11 May 2024 16:08:05 -0700 Subject: [PATCH 13/34] 2.2.008 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 127b2d219..ec3de8d6d 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.008-SNAPSHOT + 2.2.008 mcMMO https://github.com/mcMMO-Dev/mcMMO From 17052861d168ccb90778dcd1e22cac7f7405e77d Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 12 May 2024 09:33:42 -0700 Subject: [PATCH 14/34] 2.2.009 --- Changelog.txt | 14 +++++++ pom.xml | 2 +- .../config/skills/alchemy/PotionConfig.java | 22 +++++------ .../com/gmail/nossr50/util/ItemUtils.java | 39 +++++++++++++++++++ src/main/resources/experience.yml | 8 ++-- 5 files changed, 67 insertions(+), 18 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index feb4f4788..bed5117f4 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,3 +1,17 @@ +Version 2.2.009 + Fixed a bug that prevented mcMMO from loading on MC versions older than 1.20.6 + Dramatically increased the base XP for Alchemy again (see notes) + + NOTES: + Alchemy leveling still felt too slow, so I've increased it again. You can either delete experience.yml to get the new values or adjust them manually. + If you haven't updated mcMMO since 2.2.006 or older you don't need to do anything to get these new values. + The new default values are... + Potion_Brewing: + Stage_1: 666 + Stage_2: 1111 + Stage_3: 1750 + Stage_4: 2250 + Version 2.2.008 Fixed alchemy potions not upgrading correctly (This will only affect new potions made, see notes) Fixed a bug where alchemy potions had italicized names diff --git a/pom.xml b/pom.xml index ec3de8d6d..bda11611b 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.008 + 2.2.009 mcMMO https://github.com/mcMMO-Dev/mcMMO diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index dd6fdb4aa..bdfd1d40a 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -2,7 +2,6 @@ package com.gmail.nossr50.config.skills.alchemy; import com.gmail.nossr50.config.LegacyConfigLoader; import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion; -import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.PotionUtil; @@ -21,6 +20,7 @@ import org.jetbrains.annotations.VisibleForTesting; import java.io.File; import java.util.*; +import static com.gmail.nossr50.util.ItemUtils.setItemName; import static com.gmail.nossr50.util.PotionUtil.*; import static com.gmail.nossr50.util.text.StringUtils.convertKeyToName; @@ -257,19 +257,15 @@ public class PotionConfig extends LegacyConfigLoader { } private void setPotionDisplayName(ConfigurationSection section, PotionMeta potionMeta) { - String configuredName = section.getString("Name", null); - if (configuredName != null) { - potionMeta.setItemName(configuredName); + // If a potion doesn't have any custom effects, there is no reason to override the vanilla name + if (potionMeta.getCustomEffects().isEmpty()) { + return; + } + + final String configuredName = section.getString("Name", null); + if (configuredName != null) { + setItemName(potionMeta, configuredName); } -// -// // Potion is water, but has effects -// if (isPotionTypeWater(potionMeta) -// && (PotionUtil.hasBasePotionEffects(potionMeta) || !potionMeta.getCustomEffects().isEmpty())) { -// // If we don't set a name for these potions, they will simply be called "Water Potion" -// final String name = section.getName().toUpperCase().replace("_", " "); -// potionMeta.setDisplayName(name); -// System.out.println("DEBUG: Renaming potion to " + name); -// } } /** diff --git a/src/main/java/com/gmail/nossr50/util/ItemUtils.java b/src/main/java/com/gmail/nossr50/util/ItemUtils.java index 2b7cccc48..d8b34f9ae 100644 --- a/src/main/java/com/gmail/nossr50/util/ItemUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ItemUtils.java @@ -20,6 +20,8 @@ import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.Collections; import java.util.List; @@ -32,6 +34,43 @@ public final class ItemUtils { */ private ItemUtils() {} + private static final Method setItemName; + + static { + setItemName = getSetItemName(); + } + + private static Method getSetItemName() { + try { + return ItemMeta.class.getMethod("setItemName", String.class); + } catch (NoSuchMethodException e) { + return null; + } + } + + /** + * Sets the item name using the new API if available + * or falls back to the old API. + * @param itemMeta The item meta to set the name on + * @param name The name to set + */ + public static void setItemName(ItemMeta itemMeta, String name) { + if (setItemName != null) { + setItemNameModern(itemMeta, name); + } else { + itemMeta.setDisplayName(ChatColor.RESET + name); + } + } + + private static void setItemNameModern(ItemMeta itemMeta, String name) { + try { + setItemName.invoke(itemMeta, name); + } catch (IllegalAccessException | InvocationTargetException e) { + mcMMO.p.getLogger().severe("Failed to set item name: " + e.getMessage()); + throw new RuntimeException(e); + } + } + /** * Checks if the item is a bow. * diff --git a/src/main/resources/experience.yml b/src/main/resources/experience.yml index 84df0e214..e010c8d65 100644 --- a/src/main/resources/experience.yml +++ b/src/main/resources/experience.yml @@ -246,10 +246,10 @@ Experience_Values: # Stage_3 represents a base potion with one ingredient and one amplifier # Stage_4 represents a base potion with one ingredient and two amplifiers # Stage_5 represents a base potion with one ingredient where the amplifiers are swapped - Stage_1: 120 - Stage_2: 240 - Stage_3: 480 - Stage_4: 960 + Stage_1: 666 + Stage_2: 1111 + Stage_3: 1750 + Stage_4: 2250 Stage_5: 0 Archery: Distance_Multiplier: 0.025 From 3ba6b931355a9b22899cdc6d165bd30b6121c9da Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 12 May 2024 14:09:00 -0700 Subject: [PATCH 15/34] Fixed possible NPE in our events, and BrewingStands now remember who last interacted with them, this allows for hoppers to be used with Alchemy Fixes #5004 Fixes #4958 Fixes #4641 --- Changelog.txt | 39 +++ pom.xml | 2 +- .../commands/skills/AcrobaticsCommand.java | 4 +- .../commands/skills/AlchemyCommand.java | 12 +- .../commands/skills/ArcheryCommand.java | 4 +- .../nossr50/commands/skills/AxesCommand.java | 5 +- .../commands/skills/CrossbowsCommand.java | 3 - .../commands/skills/ExcavationCommand.java | 3 +- .../commands/skills/FishingCommand.java | 3 +- .../commands/skills/HerbalismCommand.java | 10 +- .../nossr50/commands/skills/MacesCommand.java | 4 - .../commands/skills/MiningCommand.java | 7 +- .../commands/skills/RepairCommand.java | 5 +- .../commands/skills/SalvageCommand.java | 3 +- .../nossr50/commands/skills/SkillCommand.java | 9 +- .../commands/skills/SmeltingCommand.java | 7 +- .../commands/skills/SwordsCommand.java | 5 +- .../commands/skills/TamingCommand.java | 2 +- .../commands/skills/TridentsCommand.java | 6 - .../commands/skills/UnarmedCommand.java | 9 +- .../commands/skills/WoodcuttingCommand.java | 4 +- .../config/skills/alchemy/PotionConfig.java | 9 +- .../nossr50/datatypes/player/McMMOPlayer.java | 11 +- .../skills/subskills/AbstractSubSkill.java | 7 +- .../skills/subskills/acrobatics/Roll.java | 215 ++++++---------- .../skills/subskills/interfaces/SubSkill.java | 13 +- .../events/skills/McMMOPlayerSkillEvent.java | 26 ++ .../McMMOPlayerAbilityActivateEvent.java | 12 +- .../McMMOPlayerAbilityDeactivateEvent.java | 14 +- .../abilities/McMMOPlayerAbilityEvent.java | 24 +- .../skills/alchemy/McMMOPlayerBrewEvent.java | 14 +- .../alchemy/McMMOPlayerCatalysisEvent.java | 13 +- .../fishing/McMMOPlayerFishingEvent.java | 10 +- .../McMMOPlayerFishingTreasureEvent.java | 17 +- .../fishing/McMMOPlayerMagicHunterEvent.java | 24 +- .../secondaryabilities/SubSkillEvent.java | 45 +++- .../nossr50/listeners/BlockListener.java | 17 +- .../nossr50/listeners/EntityListener.java | 27 +- .../nossr50/listeners/InventoryListener.java | 100 ++++---- src/main/java/com/gmail/nossr50/mcMMO.java | 19 -- .../metadata/BlockMetadataService.java | 49 ---- .../nossr50/metadata/MetadataService.java | 71 ------ .../skills/AlchemyBrewCheckTask.java | 35 ++- .../runnables/skills/AlchemyBrewTask.java | 88 ++++--- .../skills/acrobatics/AcrobaticsManager.java | 3 +- .../skills/alchemy/AlchemyPotionBrewer.java | 64 ++++- .../skills/archery/ArcheryManager.java | 4 +- .../nossr50/skills/axes/AxesManager.java | 16 +- .../skills/crossbows/CrossbowsManager.java | 2 +- .../skills/excavation/ExcavationManager.java | 6 +- .../skills/fishing/FishingManager.java | 6 +- .../skills/herbalism/HerbalismManager.java | 37 ++- .../nossr50/skills/maces/MacesManager.java | 2 - .../nossr50/skills/mining/MiningManager.java | 4 +- .../nossr50/skills/repair/RepairManager.java | 6 +- .../skills/salvage/SalvageManager.java | 8 +- .../skills/smelting/SmeltingManager.java | 2 +- .../nossr50/skills/swords/SwordsManager.java | 4 +- .../nossr50/skills/taming/TamingManager.java | 8 +- .../skills/tridents/TridentsManager.java | 2 - .../skills/unarmed/UnarmedManager.java | 10 +- .../woodcutting/WoodcuttingManager.java | 6 +- .../com/gmail/nossr50/util/BlockUtils.java | 29 ++- .../nossr50/util/ContainerMetadataUtils.java | 116 +++++++++ .../com/gmail/nossr50/util/EventUtils.java | 65 +++-- .../ItemMetadataUtils.java} | 27 +- .../gmail/nossr50/util/MetadataConstants.java | 5 +- .../gmail/nossr50/util/MetadataService.java | 48 ++++ .../MobMetadataUtils.java} | 37 +-- .../com/gmail/nossr50/util/Permissions.java | 13 +- .../nossr50/util/TransientEntityTracker.java | 4 +- .../nossr50/util/TransientMetadataTools.java | 4 +- .../nossr50/util/random/ProbabilityUtil.java | 232 ++++++++++++++---- .../nossr50/util/skills/CombatUtils.java | 19 +- .../gmail/nossr50/util/skills/PerksUtils.java | 16 ++ .../gmail/nossr50/util/skills/SkillUtils.java | 13 +- .../nossr50/util/skills/SmeltingTracker.java | 102 -------- .../util/text/TextComponentFactory.java | 4 +- .../com/gmail/nossr50/MMOTestEnvironment.java | 1 - .../util/random/ProbabilityUtilTest.java | 3 +- 80 files changed, 1137 insertions(+), 797 deletions(-) delete mode 100644 src/main/java/com/gmail/nossr50/metadata/BlockMetadataService.java delete mode 100644 src/main/java/com/gmail/nossr50/metadata/MetadataService.java create mode 100644 src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java rename src/main/java/com/gmail/nossr50/{metadata/ItemMetadataService.java => util/ItemMetadataUtils.java} (77%) create mode 100644 src/main/java/com/gmail/nossr50/util/MetadataService.java rename src/main/java/com/gmail/nossr50/{metadata/MobMetadataService.java => util/MobMetadataUtils.java} (83%) delete mode 100644 src/main/java/com/gmail/nossr50/util/skills/SmeltingTracker.java diff --git a/Changelog.txt b/Changelog.txt index bed5117f4..6ce59e238 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,3 +1,42 @@ +Version 2.2.010 + Fixed rare NPE in mcMMO events when player data was unable to be retrieved + Fixed a NPE that could happen when damaging armor with Axes + Fixed a bug where Alchemy brewing would be cancelled if the player died + (API) Added getMcMMOPlayer() to McMMOPlayerSkillEvent + (API) Added new ctor McMMOPlayerSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType) + (API) Deprecated ctor McMMOPlayerSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Added ctor McMMOPlayerAbilityEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated ctor McMMOPlayerAbilityEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated ctor McMMOPlayerAbilityActivateEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Added ctor McMMOPlayerAbilityActivateEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated ctor McMMOPlayerCatalysisEvent(org.bukkit.entity.Player, double) + (API) Added ctor McMMOPlayerCatalysisEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, double) + (API) Deprecated util method EventUtils.callPlayerAbilityActivateEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Added util method EventUtils.callPlayerAbilityActivateEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated ctor McMMOPlayerFishingEvent(org.bukkit.entity.Player) + (API) Added ctor McMMOPlayerFishingEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer) + (API) Deprecated ctor McMMOPlayerFishingTreasureEvent.McMMOPlayerFishingTreasureEvent(org.bukkit.entity.Player, org.bukkit.inventory.ItemStack, int) + (API) Added ctor McMMOPlayerFishingTreasureEvent.McMMOPlayerFishingTreasureEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, org.bukkit.inventory.ItemStack, int) + (API) Deprecated ctor McMMOPlayerMagicHunterEvent(org.bukkit.entity.Player, org.bukkit.inventory.ItemStack, int, java.util.Map) + (API) Added ctor McMMOPlayerMagicHunterEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, org.bukkit.inventory.ItemStack, int, java.util.Map) + (API) Deprecated ctor McMMOPlayerAbilityDeactivateEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Added ctor McMMOPlayerAbilityDeactivateEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated util method EventUtils.callAbilityDeactivateEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.SuperAbilityType) + (API) Added util method EventUtils.callAbilityDeactivateEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.SuperAbilityType) + (API) Deprecated util EventUtils.callSubSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.SubSkillType) + (API) Added util EventUtils.callSubSkillEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.SubSkillType) + (API) Deprecated ctor SubSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.SubSkillType) + (API) Added ctor SubSkillEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.SubSkillType) + (API) Deprecated ctor SubSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.SubSkillType, double) + (API) Added ctor SubSkillEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.SubSkillType, double) + (API) Deprecated ctor SubSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill) + (API) Added ctor SubSkillEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill) + (API) Deprecated ctor AlchemyBrewCheckTask(org.bukkit.entity.Player, org.bukkit.block.BrewingStand) + (API) Added ctor AlchemyBrewCheckTask(org.bukkit.block.BrewingStand) + + NOTES: + This is not an exhaustive list of API changes in this update, but most of them should be documented here. + Version 2.2.009 Fixed a bug that prevented mcMMO from loading on MC versions older than 1.20.6 Dramatically increased the base XP for Alchemy again (see notes) diff --git a/pom.xml b/pom.xml index bda11611b..294edc426 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.009 + 2.2.010-SNAPSHOT mcMMO https://github.com/mcMMO-Dev/mcMMO diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java index 64950211c..d1bb3d864 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java @@ -29,7 +29,7 @@ public class AcrobaticsCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // ACROBATICS_DODGE if (canDodge) { - String[] dodgeStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ACROBATICS_DODGE); + final String[] dodgeStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_DODGE); dodgeChance = dodgeStrings[0]; dodgeChanceLucky = dodgeStrings[1]; } @@ -56,7 +56,7 @@ public class AcrobaticsCommand extends SkillCommand { if(abstractSubSkill != null) { - String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ACROBATICS_ROLL); + String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_ROLL); messages.add(getStatMessage(SubSkillType.ACROBATICS_ROLL, rollStrings[0]) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", rollStrings[1]) : "")); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java index be34ebe2f..9fa9281a7 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.alchemy.AlchemyManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; import net.kyori.adventure.text.Component; @@ -30,14 +29,7 @@ public class AlchemyCommand extends SkillCommand { } protected String[] calculateAbilityDisplayValues(Player player) { - //TODO: Needed? - if(UserManager.getPlayer(player) == null) - { - player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); - return new String[] {"DATA NOT LOADED", "DATA NOT LOADED"}; - } - - AlchemyManager alchemyManager = UserManager.getPlayer(player).getAlchemyManager(); + AlchemyManager alchemyManager = mmoPlayer.getAlchemyManager(); String[] displayValues = new String[2]; boolean isLucky = Permissions.lucky(player, PrimarySkillType.ALCHEMY); @@ -59,7 +51,7 @@ public class AlchemyCommand extends SkillCommand { // ALCHEMY_CONCOCTIONS if (canConcoctions) { - AlchemyManager alchemyManager = UserManager.getPlayer(player).getAlchemyManager(); + AlchemyManager alchemyManager = mmoPlayer.getAlchemyManager(); tier = alchemyManager.getTier(); ingredientCount = alchemyManager.getIngredients().size(); ingredientList = alchemyManager.getIngredientList(); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java index dd7bf8d4b..4e2726a79 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java @@ -33,14 +33,14 @@ public class ArcheryCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // ARCHERY_ARROW_RETRIEVAL if (canRetrieve) { - String[] retrieveStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ARCHERY_ARROW_RETRIEVAL); + String[] retrieveStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ARCHERY_ARROW_RETRIEVAL); retrieveChance = retrieveStrings[0]; retrieveChanceLucky = retrieveStrings[1]; } // ARCHERY_DAZE if (canDaze) { - String[] dazeStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ARCHERY_DAZE); + String[] dazeStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ARCHERY_DAZE); dazeChance = dazeStrings[0]; dazeChanceLucky = dazeStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java index bcfb38ed0..f83063522 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.axes.Axes; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; @@ -38,7 +37,7 @@ public class AxesCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // ARMOR IMPACT if (canImpact) { - impactDamage = UserManager.getPlayer(player).getAxesManager().getImpactDurabilityDamage(); + impactDamage = mmoPlayer.getAxesManager().getImpactDurabilityDamage(); } // AXE MASTERY @@ -48,7 +47,7 @@ public class AxesCommand extends SkillCommand { // CRITICAL HIT if (canCritical) { - String[] criticalHitStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.AXES_CRITICAL_STRIKES); + String[] criticalHitStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.AXES_CRITICAL_STRIKES); critChance = criticalHitStrings[0]; critChanceLucky = criticalHitStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java index bbf29caaf..716c1dded 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java @@ -1,9 +1,7 @@ package com.gmail.nossr50.commands.skills; -import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -42,7 +40,6 @@ public class CrossbowsCommand extends SkillCommand { protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (mmoPlayer == null) { return messages; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java index 952766b15..a40c3aba4 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.excavation.ExcavationManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; import net.kyori.adventure.text.Component; @@ -45,7 +44,7 @@ public class ExcavationCommand extends SkillCommand { protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - ExcavationManager excavationManager = UserManager.getPlayer(player).getExcavationManager(); + ExcavationManager excavationManager = mmoPlayer.getExcavationManager(); if (canGigaDrill) { messages.add(getStatMessage(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, gigaDrillBreakerLength) diff --git a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java index 6b188d2d7..ff01b92ac 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java @@ -8,7 +8,6 @@ import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.fishing.FishingManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.Probability; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; @@ -50,7 +49,7 @@ public class FishingCommand extends SkillCommand { @Override protected void dataCalculations(Player player, float skillValue) { - FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager(); + FishingManager fishingManager = mmoPlayer.getFishingManager(); // TREASURE HUNTER if (canTreasureHunt) { diff --git a/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java index 8a5ce8d33..5c9028897 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java @@ -49,13 +49,13 @@ public class HerbalismCommand extends SkillCommand { // DOUBLE DROPS if (canDoubleDrop) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_DOUBLE_DROPS); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_DOUBLE_DROPS); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } if (canTripleDrop) { - String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_VERDANT_BOUNTY); + String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_VERDANT_BOUNTY); tripleDropChance = tripleDropStrings[0]; tripleDropChanceLucky = tripleDropStrings[1]; } @@ -76,21 +76,21 @@ public class HerbalismCommand extends SkillCommand { if (canGreenThumbBlocks || canGreenThumbPlants) { greenThumbStage = RankUtils.getRank(player, SubSkillType.HERBALISM_GREEN_THUMB); - String[] greenThumbStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_GREEN_THUMB); + String[] greenThumbStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_GREEN_THUMB); greenThumbChance = greenThumbStrings[0]; greenThumbChanceLucky = greenThumbStrings[1]; } // HYLIAN LUCK if (hasHylianLuck) { - String[] hylianLuckStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_HYLIAN_LUCK); + String[] hylianLuckStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_HYLIAN_LUCK); hylianLuckChance = hylianLuckStrings[0]; hylianLuckChanceLucky = hylianLuckStrings[1]; } // SHROOM THUMB if (canShroomThumb) { - String[] shroomThumbStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_SHROOM_THUMB); + String[] shroomThumbStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_SHROOM_THUMB); shroomThumbChance = shroomThumbStrings[0]; shroomThumbChanceLucky = shroomThumbStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java index 757c8dcf1..9eed83e16 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java @@ -30,10 +30,6 @@ // @Override // protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { // List messages = new ArrayList<>(); -// McMMOPlayer mmoPlayer = UserManager.getPlayer(player); -// if (mmoPlayer == null) { -// return messages; -// } // // if(SkillUtils.canUseSubskill(player, MACES_MACES_LIMIT_BREAK)) { // messages.add(getStatMessage(MACES_MACES_LIMIT_BREAK, diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java index b756dd282..b96d43c23 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -45,7 +44,7 @@ public class MiningCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // BLAST MINING if (canBlast || canDemoExpert || canBiggerBombs) { - MiningManager miningManager = UserManager.getPlayer(player).getMiningManager(); + MiningManager miningManager = mmoPlayer.getMiningManager(); blastMiningRank = miningManager.getBlastMiningTier(); bonusTNTDrops = miningManager.getDropMultiplier(); @@ -57,14 +56,14 @@ public class MiningCommand extends SkillCommand { // Mastery TRIPLE DROPS if (canTripleDrop) { - String[] masteryTripleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.MINING_MOTHER_LODE); + String[] masteryTripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.MINING_MOTHER_LODE); tripleDropChance = masteryTripleDropStrings[0]; tripleDropChanceLucky = masteryTripleDropStrings[1]; } // DOUBLE DROPS if (canDoubleDrop) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.MINING_DOUBLE_DROPS); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.MINING_DOUBLE_DROPS); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java index 32927ddcf..af23a880d 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java @@ -10,7 +10,6 @@ import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.repair.RepairManager; import com.gmail.nossr50.skills.repair.repairables.Repairable; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -68,7 +67,7 @@ public class RepairCommand extends SkillCommand { // SUPER REPAIR if (canSuperRepair) { - String[] superRepairStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.REPAIR_SUPER_REPAIR); + String[] superRepairStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.REPAIR_SUPER_REPAIR); superRepairChance = superRepairStrings[0]; superRepairChanceLucky = superRepairStrings[1]; } @@ -94,7 +93,7 @@ public class RepairCommand extends SkillCommand { List messages = new ArrayList<>(); if (canArcaneForge) { - RepairManager repairManager = UserManager.getPlayer(player).getRepairManager(); + RepairManager repairManager = mmoPlayer.getRepairManager(); messages.add(getStatMessage(false, true, SubSkillType.REPAIR_ARCANE_FORGING, diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java index 93a748023..80b12108e 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java @@ -6,7 +6,6 @@ import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.salvage.Salvage; import com.gmail.nossr50.skills.salvage.SalvageManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; import net.kyori.adventure.text.Component; @@ -38,7 +37,7 @@ public class SalvageCommand extends SkillCommand { @Override protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - SalvageManager salvageManager = UserManager.getPlayer(player).getSalvageManager(); + SalvageManager salvageManager = mmoPlayer.getSalvageManager(); if (canScrapCollector) { messages.add(getStatMessage(false, true, diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java index e8ab95e02..9ff449f8f 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java @@ -34,6 +34,7 @@ public abstract class SkillCommand implements TabExecutor { protected DecimalFormat percent = new DecimalFormat("##0.00%"); protected DecimalFormat decimal = new DecimalFormat("##0.00"); + protected McMMOPlayer mmoPlayer; private final CommandExecutor skillGuideCommand; @@ -53,9 +54,9 @@ public abstract class SkillCommand implements TabExecutor { } Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + mmoPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -63,7 +64,7 @@ public abstract class SkillCommand implements TabExecutor { if (args.length == 0) { boolean isLucky = Permissions.lucky(player, skill); boolean hasEndurance = PerksUtils.handleActivationPerks(player, 0, 0) != 0; - float skillValue = mcMMOPlayer.getSkillLevel(skill); + float skillValue = mmoPlayer.getSkillLevel(skill); //Send the players a few blank lines to make finding the top of the skill command easier if (mcMMO.p.getAdvancedConfig().doesSkillCommandSendBlankLines()) @@ -75,7 +76,7 @@ public abstract class SkillCommand implements TabExecutor { dataCalculations(player, skillValue); sendSkillCommandHeader(mcMMO.p.getSkillTools().getLocalizedSkillName(skill), - player, mcMMOPlayer, (int) skillValue); + player, mmoPlayer, (int) skillValue); //Make JSON text components List subskillTextComponents = getTextComponents(player); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java index 297662e10..0ca68a964 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java @@ -4,7 +4,6 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -34,7 +33,7 @@ public class SmeltingCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // FUEL EFFICIENCY if (canFuelEfficiency) { - burnTimeModifier = String.valueOf(UserManager.getPlayer(player).getSmeltingManager().getFuelEfficiencyMultiplier()); + burnTimeModifier = String.valueOf(mmoPlayer.getSmeltingManager().getFuelEfficiencyMultiplier()); } // FLUX MINING @@ -46,7 +45,7 @@ public class SmeltingCommand extends SkillCommand { // SECOND SMELT if (canSecondSmelt) { - String[] secondSmeltStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.SMELTING_SECOND_SMELT); + String[] secondSmeltStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.SMELTING_SECOND_SMELT); str_secondSmeltChance = secondSmeltStrings[0]; str_secondSmeltChanceLucky = secondSmeltStrings[1]; } @@ -81,7 +80,7 @@ public class SmeltingCommand extends SkillCommand { if (canUnderstandTheArt) { messages.add(getStatMessage(false, true, SubSkillType.SMELTING_UNDERSTANDING_THE_ART, - String.valueOf(UserManager.getPlayer(player).getSmeltingManager().getVanillaXpMultiplier()))); + String.valueOf(mmoPlayer.getSmeltingManager().getVanillaXpMultiplier()))); } return messages; diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java index 03d15d4ce..6c5518270 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; @@ -39,7 +38,7 @@ public class SwordsCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // SWORDS_COUNTER_ATTACK if (canCounter) { - String[] counterStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.SWORDS_COUNTER_ATTACK); + String[] counterStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.SWORDS_COUNTER_ATTACK); counterChance = counterStrings[0]; counterChanceLucky = counterStrings[1]; } @@ -105,7 +104,7 @@ public class SwordsCommand extends SkillCommand { if(SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_STAB)) { messages.add(getStatMessage(SubSkillType.SWORDS_STAB, - String.valueOf(UserManager.getPlayer(player).getSwordsManager().getStabDamage()))); + String.valueOf(mmoPlayer.getSwordsManager().getStabDamage()))); } if(SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { diff --git a/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java index fc6fd2e46..12430fc02 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java @@ -35,7 +35,7 @@ public class TamingCommand extends SkillCommand { @Override protected void dataCalculations(Player player, float skillValue) { if (canGore) { - String[] goreStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.TAMING_GORE); + String[] goreStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.TAMING_GORE); goreChance = goreStrings[0]; goreChanceLucky = goreStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java index ff4165659..706adf80a 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java @@ -1,8 +1,6 @@ package com.gmail.nossr50.commands.skills; -import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -32,10 +30,6 @@ public class TridentsCommand extends SkillCommand { @Override protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mmoPlayer == null) { - return messages; - } if(SkillUtils.canUseSubskill(player, TRIDENTS_TRIDENTS_LIMIT_BREAK)) { messages.add(getStatMessage(TRIDENTS_TRIDENTS_LIMIT_BREAK, diff --git a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java index 554eca6b3..deb536b10 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java @@ -4,7 +4,6 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; @@ -40,7 +39,7 @@ public class UnarmedCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // UNARMED_ARROW_DEFLECT if (canDeflect) { - String[] deflectStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.UNARMED_ARROW_DEFLECT); + String[] deflectStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_ARROW_DEFLECT); deflectChance = deflectStrings[0]; deflectChanceLucky = deflectStrings[1]; } @@ -54,19 +53,19 @@ public class UnarmedCommand extends SkillCommand { // UNARMED_DISARM if (canDisarm) { - String[] disarmStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.UNARMED_DISARM); + String[] disarmStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_DISARM); disarmChance = disarmStrings[0]; disarmChanceLucky = disarmStrings[1]; } // IRON ARM if (canIronArm) { - ironArmBonus = UserManager.getPlayer(player).getUnarmedManager().getSteelArmStyleDamage(); + ironArmBonus = mmoPlayer.getUnarmedManager().getSteelArmStyleDamage(); } // IRON GRIP if (canIronGrip) { - String[] ironGripStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.UNARMED_IRON_GRIP); + String[] ironGripStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_IRON_GRIP); ironGripChance = ironGripStrings[0]; ironGripChanceLucky = ironGripStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java index 1dd4beeb0..8efacee64 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java @@ -41,7 +41,7 @@ public class WoodcuttingCommand extends SkillCommand { //Clean Cuts if(canTripleDrop) { - String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.WOODCUTTING_CLEAN_CUTS); + String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.WOODCUTTING_CLEAN_CUTS); tripleDropChance = tripleDropStrings[0]; tripleDropChanceLucky = tripleDropStrings[1]; } @@ -55,7 +55,7 @@ public class WoodcuttingCommand extends SkillCommand { } private void setDoubleDropClassicChanceStrings(Player player) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.WOODCUTTING_HARVEST_LUMBER); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.WOODCUTTING_HARVEST_LUMBER); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index bdfd1d40a..774ff511c 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -14,15 +14,16 @@ import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.potion.PotionType; -import org.codehaus.plexus.util.StringUtils; import org.jetbrains.annotations.VisibleForTesting; import java.io.File; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static com.gmail.nossr50.util.ItemUtils.setItemName; -import static com.gmail.nossr50.util.PotionUtil.*; -import static com.gmail.nossr50.util.text.StringUtils.convertKeyToName; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; public class PotionConfig extends LegacyConfigLoader { diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java index d2653718f..d8b6199c4 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java @@ -72,6 +72,9 @@ import java.util.EnumMap; import java.util.Map; import java.util.UUID; +import static com.gmail.nossr50.util.EventUtils.callPlayerAbilityActivateEvent; +import static java.util.Objects.requireNonNull; + public class McMMOPlayer implements Identified { private final @NotNull Identity identity; @@ -120,6 +123,8 @@ public class McMMOPlayer implements Identified { private PrimarySkillType lastSkillShownScoreboard = PrimarySkillType.values()[0]; public McMMOPlayer(Player player, PlayerProfile profile) { + requireNonNull(player, "player cannot be null"); + requireNonNull(profile, "profile cannot be null"); this.playerName = player.getName(); UUID uuid = player.getUniqueId(); identity = Identity.identity(uuid); @@ -747,11 +752,11 @@ public class McMMOPlayer implements Identified { * Players & Profiles */ - public Player getPlayer() { + public @NotNull Player getPlayer() { return player; } - public PlayerProfile getProfile() { + public @NotNull PlayerProfile getProfile() { return profile; } @@ -925,7 +930,7 @@ public class McMMOPlayer implements Identified { return; } - if (EventUtils.callPlayerAbilityActivateEvent(player, primarySkillType).isCancelled()) { + if (callPlayerAbilityActivateEvent(this, primarySkillType).isCancelled()) { return; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java index 109ece783..a2d90aaa7 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.datatypes.skills.subskills; import com.gmail.nossr50.config.CoreSkillsConfig; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.subskills.interfaces.Interaction; import com.gmail.nossr50.datatypes.skills.subskills.interfaces.Rank; @@ -48,13 +49,13 @@ public abstract class AbstractSubSkill implements SubSkill, Interaction, Rank, S /** * Prints detailed info about this subskill to the player * - * @param player the target player + * @param mmoPlayer the target player */ @Override - public void printInfo(Player player) { + public void printInfo(McMMOPlayer mmoPlayer) { /* DEFAULT SETTINGS PRINT THE BARE MINIMUM */ - //TextComponentFactory.sendPlayerUrlHeader(player); + final Player player = mmoPlayer.getPlayer(); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", getConfigKeyName())); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java index e4fece3c4..bb0ea4267 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java @@ -4,7 +4,6 @@ import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.player.McMMOPlayer; -import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; @@ -13,7 +12,6 @@ import com.gmail.nossr50.util.EventUtils; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.Probability; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.PerksUtils; @@ -67,25 +65,25 @@ public class Roll extends AcrobaticsSubSkill { return false; if (entityDamageEvent.getCause() == EntityDamageEvent.DamageCause.FALL) {//Grab the player - McMMOPlayer mcMMOPlayer = EventUtils.getMcMMOPlayer(entityDamageEvent.getEntity()); + McMMOPlayer mmoPlayer = EventUtils.getMcMMOPlayer(entityDamageEvent.getEntity()); - if (mcMMOPlayer == null) + if (mmoPlayer == null) return false; /* * Check for success */ - Player player = (Player) ((EntityDamageEvent) event).getEntity(); - if (canRoll(player)) { - entityDamageEvent.setDamage(rollCheck(player, mcMMOPlayer, entityDamageEvent.getFinalDamage())); + + if (canRoll(mmoPlayer)) { + entityDamageEvent.setDamage(rollCheck(mmoPlayer, entityDamageEvent.getFinalDamage())); if (entityDamageEvent.getFinalDamage() == 0) { entityDamageEvent.setCancelled(true); return true; } - } else if(mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.ACROBATICS)) { + } else if(mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(mmoPlayer.getPlayer(), PrimarySkillType.ACROBATICS)) { //Give XP Anyways - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, ((EntityDamageEvent) event).getFinalDamage(), false), XPGainReason.PVE); + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, ((EntityDamageEvent) event).getFinalDamage(), false), XPGainReason.PVE); } } @@ -117,25 +115,24 @@ public class Roll extends AcrobaticsSubSkill { * Adds detailed stats specific to this skill * * @param componentBuilder target component builder - * @param player target player + * @param mmoPlayer target player */ @Override - public void addStats(TextComponent.Builder componentBuilder, Player player) { + public void addStats(TextComponent.Builder componentBuilder, McMMOPlayer mmoPlayer) { String rollChance, rollChanceLucky, gracefulRollChance, gracefulRollChanceLucky; /* Values related to the player */ - PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile(); - float skillValue = playerProfile.getSkillLevel(getPrimarySkill()); - boolean isLucky = Permissions.lucky(player, getPrimarySkill()); + float skillValue = mmoPlayer.getSkillLevel(getPrimarySkill()); + boolean isLucky = Permissions.lucky(mmoPlayer.getPlayer(), getPrimarySkill()); - String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ACROBATICS_ROLL); + String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_ROLL); rollChance = rollStrings[0]; rollChanceLucky = rollStrings[1]; /* * Graceful is double the odds of a normal roll */ - Probability probability = getRollProbability(player); + Probability probability = getRollProbability(mmoPlayer); Probability gracefulProbability = Probability.ofValue(probability.getValue() * 2); String[] gracefulRollStrings = ProbabilityUtil.getRNGDisplayValues(gracefulProbability); gracefulRollChance = gracefulRollStrings[0]; @@ -169,8 +166,8 @@ public class Roll extends AcrobaticsSubSkill { } @NotNull - private Probability getRollProbability(Player player) { - return ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, player); + private Probability getRollProbability(McMMOPlayer mmoPlayer) { + return ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, mmoPlayer); } @Override @@ -188,8 +185,9 @@ public class Roll extends AcrobaticsSubSkill { return true; } - private boolean canRoll(Player player) { - return RankUtils.hasUnlockedSubskill(player, SubSkillType.ACROBATICS_ROLL) && Permissions.isSubSkillEnabled(player, SubSkillType.ACROBATICS_ROLL); + private boolean canRoll(McMMOPlayer mmoPlayer) { + return RankUtils.hasUnlockedSubskill(mmoPlayer.getPlayer(), SubSkillType.ACROBATICS_ROLL) + && Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), SubSkillType.ACROBATICS_ROLL); } /** @@ -199,43 +197,42 @@ public class Roll extends AcrobaticsSubSkill { * @return the modified event damage if the ability was successful, the original event damage otherwise */ @VisibleForTesting - public double rollCheck(Player player, McMMOPlayer mcMMOPlayer, double damage) { + public double rollCheck(McMMOPlayer mmoPlayer, double damage) { + int skillLevel = mmoPlayer.getSkillLevel(getPrimarySkill()); - int skillLevel = mcMMOPlayer.getSkillLevel(getPrimarySkill()); - - if (player.isSneaking()) { - return gracefulRollCheck(player, mcMMOPlayer, damage, skillLevel); + if (mmoPlayer.getPlayer().isSneaking()) { + return gracefulRollCheck(mmoPlayer, damage, skillLevel); } double modifiedDamage = calculateModifiedRollDamage(damage, mcMMO.p.getAdvancedConfig().getRollDamageThreshold()); - if (!isFatal(player, modifiedDamage) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_ROLL, player)) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Roll.Text"); - SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS); - //player.sendMessage(LocaleLoader.getString("Acrobatics.Roll.Text")); + if (!isFatal(mmoPlayer, modifiedDamage) + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_ROLL, mmoPlayer)) { + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Roll.Text"); + SoundManager.sendCategorizedSound(mmoPlayer.getPlayer(), mmoPlayer.getPlayer().getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS); + //mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Acrobatics.Roll.Text")); - //if (!SkillUtils.cooldownExpired((long) mcMMOPlayer.getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { - if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); + //if (!SkillUtils.cooldownExpired((long) mcMMOmmoPlayer.getPlayer().getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { + if(!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, true), XPGainReason.PVE); //} - addFallLocation(player); + addFallLocation(mmoPlayer); return modifiedDamage; } - else if (!isFatal(player, damage)) { - //if (!SkillUtils.cooldownExpired((long) mcMMOPlayer.getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { - if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, false), XPGainReason.PVE); + else if (!isFatal(mmoPlayer, damage)) { + //if (!SkillUtils.cooldownExpired((long) mmoPlayer.getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { + if(!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, false), XPGainReason.PVE); //} } - addFallLocation(player); + addFallLocation(mmoPlayer); return damage; } - private int getActivationChance(McMMOPlayer mcMMOPlayer) { - return PerksUtils.handleLuckyPerks(mcMMOPlayer.getPlayer(), getPrimarySkill()); + private int getActivationChance(McMMOPlayer mmoPlayer) { + return PerksUtils.handleLuckyPerks(mmoPlayer, getPrimarySkill()); } /** @@ -244,36 +241,36 @@ public class Roll extends AcrobaticsSubSkill { * @param damage The amount of damage initially dealt by the event * @return the modified event damage if the ability was successful, the original event damage otherwise */ - private double gracefulRollCheck(Player player, McMMOPlayer mcMMOPlayer, double damage, int skillLevel) { + private double gracefulRollCheck(McMMOPlayer mmoPlayer, double damage, int skillLevel) { double modifiedDamage = calculateModifiedRollDamage(damage, mcMMO.p.getAdvancedConfig().getRollDamageThreshold() * 2); - Probability gracefulProbability = getGracefulProbability(player); + final Probability gracefulProbability = getGracefulProbability(mmoPlayer); - if (!isFatal(player, modifiedDamage) + if (!isFatal(mmoPlayer, modifiedDamage) //TODO: Graceful isn't sending out an event - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.ACROBATICS, player, gracefulProbability)) + && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.ACROBATICS, mmoPlayer, gracefulProbability)) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Ability.Proc"); - SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS,0.5F); - if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Ability.Proc"); + SoundManager.sendCategorizedSound(mmoPlayer.getPlayer(), mmoPlayer.getPlayer().getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS,0.5F); + if(!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, true), XPGainReason.PVE); - addFallLocation(player); + addFallLocation(mmoPlayer); return modifiedDamage; } - else if (!isFatal(player, damage)) { - if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, false), XPGainReason.PVE); + else if (!isFatal(mmoPlayer, damage)) { + if(!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, false), XPGainReason.PVE); - addFallLocation(player); + addFallLocation(mmoPlayer); } return damage; } @NotNull - public static Probability getGracefulProbability(Player player) { - double gracefulOdds = ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, player).getValue() * 2; + public static Probability getGracefulProbability(McMMOPlayer mmoPlayer) { + double gracefulOdds = ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, mmoPlayer).getValue() * 2; return Probability.ofValue(gracefulOdds); } @@ -283,24 +280,22 @@ public class Roll extends AcrobaticsSubSkill { * * @return true if exploits are detected, false otherwise */ - private boolean isExploiting(Player player) { + private boolean isExploiting(McMMOPlayer mmoPlayer) { if (!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { return false; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - - if (ItemUtils.hasItemInEitherHand(player, Material.ENDER_PEARL) || player.isInsideVehicle()) { - if(mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Ender Pearl or Inside Vehicle"); + if (ItemUtils.hasItemInEitherHand(mmoPlayer.getPlayer(), Material.ENDER_PEARL) || mmoPlayer.getPlayer().isInsideVehicle()) { + if(mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Ender Pearl or Inside Vehicle"); } return true; } - if(UserManager.getPlayer(player).getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(player))) + if(mmoPlayer.getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(mmoPlayer))) { - if(mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Fallen in location before"); + if(mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Fallen in location before"); } return true; @@ -309,11 +304,11 @@ public class Roll extends AcrobaticsSubSkill { return false; //NOT EXPLOITING } - private float calculateRollXP(Player player, double damage, boolean isRoll) { + private float calculateRollXP(McMMOPlayer mmoPlayer, double damage, boolean isRoll) { //Clamp Damage to account for insane DRs damage = Math.min(20, damage); - ItemStack boots = player.getInventory().getBoots(); + ItemStack boots = mmoPlayer.getPlayer().getInventory().getBoots(); float xp = (float) (damage * (isRoll ? ExperienceConfig.getInstance().getRollXPModifier() : ExperienceConfig.getInstance().getFallXPModifier())); if (boots != null && boots.containsEnchantment(mcMMO.p.getEnchantmentMapper().getFeatherFalling())) { @@ -327,8 +322,8 @@ public class Roll extends AcrobaticsSubSkill { return Math.max(damage - damageThreshold, 0.0); } - private boolean isFatal(Player player, double damage) { - return player.getHealth() - damage <= 0; + private boolean isFatal(McMMOPlayer mmoPlayer, double damage) { + return mmoPlayer.getPlayer().getHealth() - damage <= 0; } /** @@ -344,103 +339,51 @@ public class Roll extends AcrobaticsSubSkill { /** * Prints detailed info about this subskill to the player * - * @param player the target player + * @param mmoPlayer the target player */ @Override - public void printInfo(Player player) { + public void printInfo(McMMOPlayer mmoPlayer) { //Header - super.printInfo(player); + super.printInfo(mmoPlayer); //Start the description string. //player.sendMessage(getDescription()); //Player stats - player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Stats", - LocaleLoader.getString("Acrobatics.SubSkill.Roll.Stats", getStats(player)))); + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.MmoInfo.Stats", + LocaleLoader.getString("Acrobatics.SubSkill.Roll.Stats", getStats(mmoPlayer)))); //Mechanics - player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mechanics")); - player.sendMessage(getMechanics()); + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mechanics")); + mmoPlayer.getPlayer().sendMessage(getMechanics()); } - /** - * Returns a collection of strings about how a skill works - * Used in the MMO Info command - * - * @return - */ @Override public String getMechanics() { - //Vars passed to locale - //0 = chance to roll at half max level - //1 = chance to roll with grace at half max level - //2 = level where maximum bonus is reached - //3 = additive chance to succeed per level - //4 = damage threshold when rolling - //5 = damage threshold when rolling with grace - //6 = half of level where maximum bonus is reached - /* - Roll: - # ChanceMax: Maximum chance of rolling when on or higher - # MaxBonusLevel: On this level or higher, the roll chance will not go higher than - # DamageThreshold: The max damage a player can negate with a roll - ChanceMax: 100.0 - MaxBonusLevel: 100 - DamageThreshold: 7.0 - */ - return "Under Construction: This will work in a future update."; -// -// double rollChanceHalfMax, graceChanceHalfMax, damageThreshold, chancePerLevel; -// -// //Chance to roll at half max skill -// RandomChanceSkill rollHalfMaxSkill = new RandomChanceSkill(null, subSkillType); -// int halfMaxSkillValue = mcMMO.p.getAdvancedConfig().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL)/2; -// rollHalfMaxSkill.setSkillLevel(halfMaxSkillValue); -// -// //Chance to graceful roll at full skill -// RandomChanceSkill rollGraceHalfMaxSkill = new RandomChanceSkill(null, subSkillType); -// rollGraceHalfMaxSkill.setSkillLevel(halfMaxSkillValue * 2); //Double the effective odds -// -// //Chance to roll per level -// RandomChanceSkill rollOneSkillLevel = new RandomChanceSkill(null, subSkillType); -// rollGraceHalfMaxSkill.setSkillLevel(1); //Level 1 skill -// -// //Chance Stat Calculations -// rollChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollHalfMaxSkill); -// graceChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollGraceHalfMaxSkill); -// damageThreshold = mcMMO.p.getAdvancedConfig().getRollDamageThreshold(); -// -// chancePerLevel = RandomChanceUtil.getRandomChanceExecutionChance(rollOneSkillLevel); -// -// double maxLevel = mcMMO.p.getAdvancedConfig().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL); -// -// return LocaleLoader.getString("Acrobatics.SubSkill.Roll.Mechanics", rollChanceHalfMax, graceChanceHalfMax, maxLevel, chancePerLevel, damageThreshold, damageThreshold * 2,halfMaxSkillValue); } /** * Get an array of various stats for a player * - * @param player target player + * @param mmoPlayer target player * @return stat array for target player for this skill */ @Override - public Double[] getStats(Player player) + public Double[] getStats(McMMOPlayer mmoPlayer) { - double playerChanceRoll = ProbabilityUtil.getSubSkillProbability(subSkillType, player).getValue(); + double playerChanceRoll = ProbabilityUtil.getSubSkillProbability(subSkillType, mmoPlayer).getValue(); double playerChanceGrace = playerChanceRoll * 2; - double gracefulOdds = ProbabilityUtil.getSubSkillProbability(subSkillType, player).getValue() * 2; + double gracefulOdds = ProbabilityUtil.getSubSkillProbability(subSkillType, mmoPlayer).getValue() * 2; return new Double[]{ playerChanceRoll, playerChanceGrace }; } - public void addFallLocation(@NotNull Player player) - { - UserManager.getPlayer(player).getAcrobaticsManager().addLocationToFallMap(getBlockLocation(player)); + public void addFallLocation(@NotNull McMMOPlayer mmoPlayer) { + mmoPlayer.getAcrobaticsManager().addLocationToFallMap(getBlockLocation(mmoPlayer)); } - public @NotNull Location getBlockLocation(@NotNull Player player) - { - return player.getLocation().getBlock().getLocation(); + public @NotNull Location getBlockLocation(@NotNull McMMOPlayer mmoPlayer) { + return mmoPlayer.getPlayer().getLocation().getBlock().getLocation(); } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java index 33d0e9874..9a3c49e30 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java @@ -1,5 +1,6 @@ package com.gmail.nossr50.datatypes.skills.subskills.interfaces; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.interfaces.Skill; import net.kyori.adventure.text.TextComponent; import org.bukkit.entity.Player; @@ -19,10 +20,10 @@ public interface SubSkill extends Skill { /** * Get an array of various stats for a player - * @param player target player + * @param mmoPlayer target player * @return stat array for target player for this skill */ - Double[] getStats(Player player); + Double[] getStats(McMMOPlayer mmoPlayer); /** * Checks if a player has permission to use this skill @@ -59,9 +60,9 @@ public interface SubSkill extends Skill { /** * Adds detailed stats specific to this skill * @param componentBuilder target component builder - * @param player owner of this skill + * @param mmoPlayer owner of this skill */ - void addStats(TextComponent.Builder componentBuilder, Player player); + void addStats(TextComponent.Builder componentBuilder, McMMOPlayer mmoPlayer); /** * Whether this subskill is enabled @@ -71,7 +72,7 @@ public interface SubSkill extends Skill { /** * Prints detailed info about this subskill to the player - * @param player the target player + * @param mmoPlayer the target player */ - void printInfo(Player player); + void printInfo(McMMOPlayer mmoPlayer); } diff --git a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java index 6238886c0..99059ff19 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java @@ -1,5 +1,6 @@ package com.gmail.nossr50.events.skills; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; @@ -7,19 +8,35 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.jetbrains.annotations.NotNull; +import static java.util.Objects.requireNonNull; + /** * Generic event for mcMMO skill handling. */ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { protected @NotNull PrimarySkillType skill; protected int skillLevel; + protected McMMOPlayer mmoPlayer; + @Deprecated(forRemoval = true, since = "2.2.010") protected McMMOPlayerSkillEvent(@NotNull Player player, @NotNull PrimarySkillType skill) { super(player); + McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + requireNonNull(mmoPlayer, "Player not found in UserManager," + + "contact the dev and tell them to use the constructor for" + + " McMMOPlayerSkillEvent(McMMOPlayer, PrimarySkillType) instead"); this.skill = skill; this.skillLevel = UserManager.getPlayer(player).getSkillLevel(skill); } + protected McMMOPlayerSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType) { + super(mmoPlayer.getPlayer()); + requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); + requireNonNull(primarySkillType, "primarySkillType cannot be null"); + this.skill = primarySkillType; + this.skillLevel = mmoPlayer.getSkillLevel(primarySkillType); + } + /** * @return The skill involved in this event */ @@ -37,6 +54,15 @@ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { /** Rest of file is required boilerplate for custom events **/ private static final HandlerList handlers = new HandlerList(); + /** + * Returns the {@link McMMOPlayer} associated with this event. + * + * @return The {@link McMMOPlayer} associated with this event. + */ + public @NotNull McMMOPlayer getMcMMOPlayer() { + return mmoPlayer; + } + @Override public @NotNull HandlerList getHandlers() { return handlers; diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java index 7b0db958b..707981c9c 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java @@ -1,14 +1,24 @@ package com.gmail.nossr50.events.skills.abilities; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; +import java.util.Objects; + public class McMMOPlayerAbilityActivateEvent extends McMMOPlayerAbilityEvent implements Cancellable { private boolean cancelled; + @Deprecated(forRemoval = true, since = "2.2.010") public McMMOPlayerAbilityActivateEvent(Player player, PrimarySkillType skill) { - super(player, skill); + super(Objects.requireNonNull(UserManager.getPlayer(player)), skill); + cancelled = false; + } + + public McMMOPlayerAbilityActivateEvent(McMMOPlayer mmoPlayer, PrimarySkillType skill) { + super(mmoPlayer, skill); cancelled = false; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java index 384b61c92..bf55a43ab 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java @@ -1,10 +1,20 @@ package com.gmail.nossr50.events.skills.abilities; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import static java.util.Objects.requireNonNull; public class McMMOPlayerAbilityDeactivateEvent extends McMMOPlayerAbilityEvent { - public McMMOPlayerAbilityDeactivateEvent(Player player, PrimarySkillType skill) { - super(player, skill); + @Deprecated(forRemoval = true, since = "2.2.010") + public McMMOPlayerAbilityDeactivateEvent(@NotNull Player player, @NotNull PrimarySkillType skill) { + this(requireNonNull(UserManager.getPlayer(player)), skill); + } + + public McMMOPlayerAbilityDeactivateEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType skill) { + super(mmoPlayer, skill); } } diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java index 08d7dc2b2..42e5fd9a5 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java @@ -1,16 +1,38 @@ package com.gmail.nossr50.events.skills.abilities; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; +import java.util.Objects; + public class McMMOPlayerAbilityEvent extends McMMOPlayerSkillEvent { private final SuperAbilityType ability; + /** + * Create a new McMMOPlayerAbilityEvent. + * + * @param player The player involved in this event + * @param skill The skill involved in this event + * @deprecated Use {@link #McMMOPlayerAbilityEvent(McMMOPlayer, PrimarySkillType)} instead + */ + @Deprecated(forRemoval = true, since = "2.2.010") protected McMMOPlayerAbilityEvent(Player player, PrimarySkillType skill) { - super(player, skill); + super(Objects.requireNonNull(UserManager.getPlayer(player)), skill); + ability = mcMMO.p.getSkillTools().getSuperAbility(skill); + } + + /** + * Create a new McMMOPlayerAbilityEvent. + * @param mmoPlayer The McMMOPlayer involved in this event + * @param skill The skill involved in this event + */ + protected McMMOPlayerAbilityEvent(McMMOPlayer mmoPlayer, PrimarySkillType skill) { + super(mmoPlayer, skill); ability = mcMMO.p.getSkillTools().getSuperAbility(skill); } diff --git a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java index ca62829cb..cd3dd032a 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java @@ -1,24 +1,36 @@ package com.gmail.nossr50.events.skills.alchemy; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; +import org.jetbrains.annotations.NotNull; + +import static java.util.Objects.requireNonNull; public class McMMOPlayerBrewEvent extends McMMOPlayerSkillEvent implements Cancellable { private final BlockState brewingStand; private boolean cancelled; + @Deprecated(forRemoval = true, since = "2.2.010") public McMMOPlayerBrewEvent(Player player, BlockState brewingStand) { - super(player, PrimarySkillType.ALCHEMY); + super(requireNonNull(UserManager.getPlayer(player)), PrimarySkillType.ALCHEMY); this.brewingStand = brewingStand; cancelled = false; } + public McMMOPlayerBrewEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull BlockState brewingStand) { + super(mmoPlayer, PrimarySkillType.ALCHEMY); + this.brewingStand = requireNonNull(brewingStand); + cancelled = false; + } + public boolean isCancelled() { return cancelled; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java index c4dbcc7d3..385cbaec0 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java @@ -1,17 +1,28 @@ package com.gmail.nossr50.events.skills.alchemy; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; +import static java.util.Objects.requireNonNull; + public class McMMOPlayerCatalysisEvent extends McMMOPlayerSkillEvent implements Cancellable { private double speed; private boolean cancelled; + @Deprecated(forRemoval = true, since = "2.2.010") public McMMOPlayerCatalysisEvent(Player player, double speed) { - super(player, PrimarySkillType.ALCHEMY); + super(requireNonNull(UserManager.getPlayer(player)), PrimarySkillType.ALCHEMY); + this.speed = speed; + cancelled = false; + } + + public McMMOPlayerCatalysisEvent(McMMOPlayer mmoPlayer, double speed) { + super(mmoPlayer, PrimarySkillType.ALCHEMY); this.speed = speed; cancelled = false; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingEvent.java index 96cde8b6b..363b10927 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingEvent.java @@ -1,15 +1,23 @@ package com.gmail.nossr50.events.skills.fishing; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; public class McMMOPlayerFishingEvent extends McMMOPlayerSkillEvent implements Cancellable { private boolean cancelled; + @Deprecated(forRemoval = true, since = "2.2.010") protected McMMOPlayerFishingEvent(Player player) { - super(player, PrimarySkillType.FISHING); + super(UserManager.getPlayer(player), PrimarySkillType.FISHING); + cancelled = false; + } + + protected McMMOPlayerFishingEvent(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.FISHING); cancelled = false; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java index dba01b751..0437e2fc8 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java @@ -1,23 +1,34 @@ package com.gmail.nossr50.events.skills.fishing; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; public class McMMOPlayerFishingTreasureEvent extends McMMOPlayerFishingEvent { private ItemStack treasure; private int xp; + @Deprecated(forRemoval = true, since = "2.2.010") public McMMOPlayerFishingTreasureEvent(Player player, ItemStack treasure, int xp) { - super(player); + this(requireNonNull(UserManager.getPlayer(player)), treasure, xp); + } + + public McMMOPlayerFishingTreasureEvent(@NotNull McMMOPlayer mmoPlayer, @Nullable ItemStack treasure, int xp) { + super(mmoPlayer); this.treasure = treasure; this.xp = xp; } - public ItemStack getTreasure() { + public @Nullable ItemStack getTreasure() { return treasure; } - public void setTreasure(ItemStack item) { + public void setTreasure(@Nullable ItemStack item) { this.treasure = item; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java index decd27ad5..93cc5c8c8 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java @@ -1,20 +1,32 @@ package com.gmail.nossr50.events.skills.fishing; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import java.util.HashMap; import java.util.Map; -public class McMMOPlayerMagicHunterEvent extends McMMOPlayerFishingTreasureEvent { - private final Map enchants; +import static java.util.Objects.requireNonNull; - public McMMOPlayerMagicHunterEvent(Player player, ItemStack treasure, int xp, Map enchants) { - super(player, treasure, xp); - this.enchants = enchants; +public class McMMOPlayerMagicHunterEvent extends McMMOPlayerFishingTreasureEvent { + private final Map enchants = new HashMap<>(); + + @Deprecated(forRemoval = true, since = "2.2.010") + public McMMOPlayerMagicHunterEvent(@NotNull Player player, @NotNull ItemStack treasure, int xp, @NotNull Map enchants) { + this(requireNonNull(UserManager.getPlayer(player)), treasure, xp, enchants); } - public Map getEnchantments() { + public McMMOPlayerMagicHunterEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull ItemStack treasure, int xp, @NotNull Map enchants) { + super(mmoPlayer, treasure, xp); + requireNonNull(enchants, "enchants cannot be null"); + this.enchants.putAll(enchants); + } + + public @NotNull Map getEnchantments() { return enchants; } } diff --git a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java index 5445bbfcd..273a6e442 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java @@ -1,11 +1,16 @@ package com.gmail.nossr50.events.skills.secondaryabilities; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; +import org.jetbrains.annotations.NotNull; + +import static java.util.Objects.requireNonNull; public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable { private SubSkillType subSkillType; @@ -16,9 +21,20 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable * Only skills using the old system will fire this event * @param player target player * @param subSkillType target subskill + * @deprecated Use {@link #SubSkillEvent(McMMOPlayer, SubSkillType)} instead */ - public SubSkillEvent(Player player, SubSkillType subSkillType) { - super(player, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType)); + @Deprecated(forRemoval = true, since = "2.2.010") + public SubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType) { + this(requireNonNull(UserManager.getPlayer(player)), subSkillType); + } + + /** + * Only skills using the old system will fire this event + * @param mmoPlayer target player + * @param subSkillType target subskill + */ + public SubSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType) { + super(mmoPlayer, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType)); this.subSkillType = subSkillType; } @@ -28,15 +44,30 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable * @param subSkillType target subskill * @param resultModifier a value multiplied against the final result of the dice roll, typically between 0-1.0 */ - public SubSkillEvent(Player player, SubSkillType subSkillType, double resultModifier) { + @Deprecated(forRemoval = true, since = "2.2.010") + public SubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType, double resultModifier) { + this(requireNonNull(UserManager.getPlayer(player)), subSkillType, resultModifier); + } + + /** + * Only skills using the old system will fire this event + * @param player target player + * @param subSkillType target subskill + * @param resultModifier a value multiplied against the final result of the dice roll, typically between 0-1.0 + */ + public SubSkillEvent(@NotNull McMMOPlayer player, @NotNull SubSkillType subSkillType, double resultModifier) { super(player, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType)); - this.subSkillType = subSkillType; + this.subSkillType = requireNonNull(subSkillType, "subSkillType cannot be null"); this.resultModifier = resultModifier; } - public SubSkillEvent(Player player, AbstractSubSkill abstractSubSkill) - { - super(player, abstractSubSkill.getPrimarySkill()); + @Deprecated(forRemoval = true, since = "2.2.010") + public SubSkillEvent(@NotNull Player player, @NotNull AbstractSubSkill abstractSubSkill) { + this(requireNonNull(UserManager.getPlayer(player)), abstractSubSkill); + } + + public SubSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull AbstractSubSkill abstractSubSkill) { + super(mmoPlayer, abstractSubSkill.getPrimarySkill()); } public double getResultModifier() { diff --git a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java index 63585b917..3b3e3ba7e 100644 --- a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java @@ -708,19 +708,16 @@ public class BlockListener implements Listener { player.sendMessage("[mcMMO DEBUG] World Guard xp flag is not permitted for this player in this region"); } - if(blockState instanceof Furnace furnace) - { - if(mcMMO.getSmeltingTracker().isFurnaceOwned(furnace)) - { - player.sendMessage("[mcMMO DEBUG] This furnace has a registered owner"); - OfflinePlayer furnacePlayer = mcMMO.getSmeltingTracker().getFurnaceOwner(furnace); - if(furnacePlayer != null) - { - player.sendMessage("[mcMMO DEBUG] This furnace is owned by player "+furnacePlayer.getName()); + if(blockState instanceof Furnace || blockState instanceof BrewingStand) { + if(ContainerMetadataUtils.isContainerOwned(blockState)) { + player.sendMessage("[mcMMO DEBUG] This container has a registered owner"); + final OfflinePlayer furnacePlayer = ContainerMetadataUtils.getContainerOwner(blockState); + if(furnacePlayer != null) { + player.sendMessage("[mcMMO DEBUG] This container is owned by player "+furnacePlayer.getName()); } } else - player.sendMessage("[mcMMO DEBUG] This furnace does not have a registered owner"); + player.sendMessage("[mcMMO DEBUG] This container does not have a registered owner"); } if(ExperienceConfig.getInstance().isExperienceBarsEnabled()) diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index d309669fc..9bad702f2 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -8,7 +8,6 @@ import com.gmail.nossr50.datatypes.skills.subskills.interfaces.InteractType; import com.gmail.nossr50.events.fake.FakeEntityTameEvent; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.metadata.MobMetaFlagType; -import com.gmail.nossr50.metadata.MobMetadataService; import com.gmail.nossr50.runnables.TravelingBlockMetaCleanup; import com.gmail.nossr50.skills.archery.Archery; import com.gmail.nossr50.skills.crossbows.Crossbows; @@ -47,9 +46,10 @@ import org.bukkit.potion.PotionEffectType; import org.bukkit.projectiles.ProjectileSource; import org.jetbrains.annotations.NotNull; +import static com.gmail.nossr50.util.MobMetadataUtils.*; + public class EntityListener implements Listener { private final mcMMO pluginRef; - private final @NotNull MobMetadataService mobMetadataService; /** * We can use this {@link NamespacedKey} for {@link Enchantment} comparisons to @@ -59,7 +59,6 @@ public class EntityListener implements Listener { public EntityListener(final mcMMO pluginRef) { this.pluginRef = pluginRef; - mobMetadataService = mcMMO.getMetadataService().getMobMetadataService(); } @EventHandler(priority = EventPriority.MONITOR) @@ -67,10 +66,10 @@ public class EntityListener implements Listener { if(event.getEntity() instanceof LivingEntity livingEntity) { //Transfer metadata keys from mob-spawned mobs to new mobs - if(mobMetadataService.hasMobFlags(livingEntity)) { + if(hasMobFlags(livingEntity)) { for(Entity entity : event.getTransformedEntities()) { if(entity instanceof LivingEntity transformedEntity) { - mobMetadataService.addMobFlags(livingEntity, transformedEntity); + addMobFlags(livingEntity, transformedEntity); } } } @@ -93,8 +92,8 @@ public class EntityListener implements Listener { { if(event.getEntity() instanceof Enderman enderman) { - if(!mobMetadataService.hasMobFlag(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman)) { - mobMetadataService.flagMetadata(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman); + if(!hasMobFlag(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman)) { + flagMetadata(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman); } } } @@ -168,7 +167,7 @@ public class EntityListener implements Listener { return; } - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_ARROW_RETRIEVAL, player)) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_ARROW_RETRIEVAL, UserManager.getPlayer(player))) { arrow.setMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); } } @@ -730,11 +729,11 @@ public class EntityListener implements Listener { } private void trackSpawnedAndPassengers(LivingEntity livingEntity, MobMetaFlagType mobMetaFlagType) { - mobMetadataService.flagMetadata(mobMetaFlagType, livingEntity); + flagMetadata(mobMetaFlagType, livingEntity); for(Entity passenger : livingEntity.getPassengers()) { if(passenger != null) { - mobMetadataService.flagMetadata(mobMetaFlagType, livingEntity); + flagMetadata(mobMetaFlagType, livingEntity); } } } @@ -742,7 +741,7 @@ public class EntityListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onEntityBreed(EntityBreedEvent event) { if(ExperienceConfig.getInstance().isCOTWBreedingPrevented()) { - if(mobMetadataService.hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getFather()) || mobMetadataService.hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getMother())) { + if(hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getFather()) || hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getMother())) { event.setCancelled(true); Animals mom = (Animals) event.getMother(); Animals father = (Animals) event.getFather(); @@ -1005,12 +1004,12 @@ public class EntityListener implements Listener { if (!UserManager.hasPlayerDataKey(player) || (ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(livingEntity)) - || mobMetadataService.hasMobFlag(MobMetaFlagType.EGG_MOB, livingEntity) - || mobMetadataService.hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, livingEntity)) { + || hasMobFlag(MobMetaFlagType.EGG_MOB, livingEntity) + || hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, livingEntity)) { return; } - mobMetadataService.flagMetadata(MobMetaFlagType.PLAYER_TAMED_MOB, livingEntity); + flagMetadata(MobMetaFlagType.PLAYER_TAMED_MOB, livingEntity); //Profile not loaded if(UserManager.getPlayer(player) == null) diff --git a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java index 879fbb820..08dfb6c4a 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java @@ -5,11 +5,11 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.events.fake.FakeBrewEvent; -import com.gmail.nossr50.events.fake.FakeEvent; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.player.PlayerUpdateInventoryTask; import com.gmail.nossr50.skills.alchemy.Alchemy; import com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer; +import com.gmail.nossr50.util.ContainerMetadataUtils; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.Permissions; @@ -29,7 +29,6 @@ import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.block.BrewingStartEvent; import org.bukkit.event.inventory.*; import org.bukkit.inventory.*; @@ -55,7 +54,7 @@ public class InventoryListener implements Listener { } Furnace furnace = (Furnace) furnaceState; - OfflinePlayer offlinePlayer = mcMMO.getSmeltingTracker().getFurnaceOwner(furnace); + OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(furnace); Player player; if(offlinePlayer != null && offlinePlayer.isOnline() && offlinePlayer instanceof Player) { @@ -101,7 +100,7 @@ public class InventoryListener implements Listener { } if(blockState instanceof Furnace furnace) { - OfflinePlayer offlinePlayer = mcMMO.getSmeltingTracker().getFurnaceOwner(furnace); + OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(furnace); if(offlinePlayer != null) { @@ -167,16 +166,16 @@ public class InventoryListener implements Listener { Inventory inventory = event.getInventory(); Player player = ((Player) event.getWhoClicked()).getPlayer(); + McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(event.getInventory() instanceof FurnaceInventory) - { - Furnace furnace = mcMMO.getSmeltingTracker().getFurnaceFromInventory(event.getInventory()); + if(event.getInventory() instanceof FurnaceInventory furnaceInventory) { + //Switch owners + ContainerMetadataUtils.processContainerOwnership(furnaceInventory.getHolder(), player); + } - if (furnace != null) - { - //Switch owners - mcMMO.getSmeltingTracker().processFurnaceOwnership(furnace, player); - } + if(event.getInventory() instanceof BrewerInventory brewerInventory) { + // switch owners + ContainerMetadataUtils.processContainerOwnership(brewerInventory.getHolder(), player); } if (!(inventory instanceof BrewerInventory)) { @@ -191,10 +190,11 @@ public class InventoryListener implements Listener { HumanEntity whoClicked = event.getWhoClicked(); - if (!UserManager.hasPlayerDataKey(event.getWhoClicked()) || !Permissions.isSubSkillEnabled(whoClicked, SubSkillType.ALCHEMY_CONCOCTIONS)) { + if (mmoPlayer == null || !Permissions.isSubSkillEnabled(whoClicked, SubSkillType.ALCHEMY_CONCOCTIONS)) { return; } + // TODO: Investigate why this WG check is all the way down here? /* WORLD GUARD MAIN FLAG CHECK */ if(WorldGuardUtils.isWorldGuardLoaded()) { @@ -202,11 +202,16 @@ public class InventoryListener implements Listener { return; } - ItemStack clicked = event.getCurrentItem(); - ItemStack cursor = event.getCursor(); + final ItemStack clicked = event.getCurrentItem(); + final ItemStack cursor = event.getCursor(); - if ((clicked != null && (clicked.getType() == Material.POTION || clicked.getType() == Material.SPLASH_POTION || clicked.getType() == Material.LINGERING_POTION)) || (cursor != null && (cursor.getType() == Material.POTION || cursor.getType() == Material.SPLASH_POTION || cursor.getType() == Material.LINGERING_POTION))) { - AlchemyPotionBrewer.scheduleCheck(player, stand); + if ((clicked != null && (clicked.getType() == Material.POTION + || clicked.getType() == Material.SPLASH_POTION + || clicked.getType() == Material.LINGERING_POTION)) + || (cursor != null && (cursor.getType() == Material.POTION + || cursor.getType() == Material.SPLASH_POTION + || cursor.getType() == Material.LINGERING_POTION))) { + AlchemyPotionBrewer.scheduleCheck(stand); return; } @@ -216,11 +221,11 @@ public class InventoryListener implements Listener { if (click.isShiftClick()) { switch (slot) { case FUEL: - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); return; case CONTAINER: case QUICKBAR: - if (!AlchemyPotionBrewer.isValidIngredient(player, clicked)) { + if (!AlchemyPotionBrewer.isValidIngredientByPlayer(player, clicked)) { return; } @@ -230,7 +235,7 @@ public class InventoryListener implements Listener { event.setCancelled(true); AlchemyPotionBrewer.scheduleUpdate(inventory); - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); return; default: } @@ -240,14 +245,14 @@ public class InventoryListener implements Listener { if (AlchemyPotionBrewer.isEmpty(cursor)) { if (emptyClicked && click == ClickType.NUMBER_KEY) { - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); return; } - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); } else if (emptyClicked) { - if (AlchemyPotionBrewer.isValidIngredient(player, cursor)) { + if (AlchemyPotionBrewer.isValidIngredientByPlayer(player, cursor)) { int amount = cursor.getAmount(); if (click == ClickType.LEFT || (click == ClickType.RIGHT && amount == 1)) { @@ -256,7 +261,7 @@ public class InventoryListener implements Listener { event.setCursor(null); AlchemyPotionBrewer.scheduleUpdate(inventory); - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); } else if (click == ClickType.RIGHT) { event.setCancelled(true); @@ -271,7 +276,7 @@ public class InventoryListener implements Listener { event.setCursor(rest); AlchemyPotionBrewer.scheduleUpdate(inventory); - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); } } } @@ -324,9 +329,9 @@ public class InventoryListener implements Listener { return; } - if (AlchemyPotionBrewer.isValidIngredient(player, cursor)) { + if (AlchemyPotionBrewer.isValidIngredientByPlayer(player, cursor)) { // Not handled: dragging custom ingredients over ingredient slot (does not trigger any event) - AlchemyPotionBrewer.scheduleCheck(player, (BrewingStand) holder); + AlchemyPotionBrewer.scheduleCheck((BrewingStand) holder); return; } @@ -371,32 +376,41 @@ public class InventoryListener implements Listener { if(WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) return; - Inventory inventory = event.getDestination(); + final Inventory inventory = event.getDestination(); if (!(inventory instanceof BrewerInventory)) { return; } - InventoryHolder holder = inventory.getHolder(); + final InventoryHolder holder = inventory.getHolder(); - if (!(holder instanceof BrewingStand)) { - return; - } + if (holder instanceof BrewingStand brewingStand) { - ItemStack item = event.getItem(); + ItemStack item = event.getItem(); - if (mcMMO.p.getGeneralConfig().getPreventHopperTransferIngredients() && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION && item.getType() != Material.LINGERING_POTION) { - event.setCancelled(true); - return; - } + if (mcMMO.p.getGeneralConfig().getPreventHopperTransferIngredients() && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION && item.getType() != Material.LINGERING_POTION) { + event.setCancelled(true); + return; + } - if (mcMMO.p.getGeneralConfig().getPreventHopperTransferBottles() && (item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION)) { - event.setCancelled(true); - return; - } + if (mcMMO.p.getGeneralConfig().getPreventHopperTransferBottles() && (item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION)) { + event.setCancelled(true); + return; + } + int ingredientLevel = 1; - if (mcMMO.p.getGeneralConfig().getEnabledForHoppers() && AlchemyPotionBrewer.isValidIngredient(null, item)) { - AlchemyPotionBrewer.scheduleCheck(null, (BrewingStand) holder); + OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(brewingStand); + if (offlinePlayer != null && offlinePlayer.isOnline()) { + McMMOPlayer mmoPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + if (mmoPlayer != null) { + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); + } + } + + if (mcMMO.p.getGeneralConfig().getEnabledForHoppers() + && AlchemyPotionBrewer.isValidIngredientByLevel(ingredientLevel, item)) { + AlchemyPotionBrewer.scheduleCheck(brewingStand); + } } } diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 423a46333..61df1f745 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -19,7 +19,6 @@ import com.gmail.nossr50.database.DatabaseManagerFactory; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.subskills.acrobatics.Roll; import com.gmail.nossr50.listeners.*; -import com.gmail.nossr50.metadata.MetadataService; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.placeholders.PapiExpansion; import com.gmail.nossr50.runnables.SaveTimerTask; @@ -50,7 +49,6 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillTools; -import com.gmail.nossr50.util.skills.SmeltingTracker; import com.gmail.nossr50.util.upgrade.UpgradeManager; import com.gmail.nossr50.worldguard.WorldGuardManager; import com.tcoded.folialib.FoliaLib; @@ -80,7 +78,6 @@ import java.util.List; public class mcMMO extends JavaPlugin { /* Managers & Services */ private static PlatformManager platformManager; - private static MetadataService metadataService; private static ChunkManager placeStore; private static RepairableManager repairableManager; private static SalvageableManager salvageableManager; @@ -90,12 +87,10 @@ public class mcMMO extends JavaPlugin { private static UpgradeManager upgradeManager; private static MaterialMapStore materialMapStore; private static PlayerLevelUtils playerLevelUtils; - private static SmeltingTracker smeltingTracker; private static TransientMetadataTools transientMetadataTools; private static ChatManager chatManager; private static CommandManager commandManager; //ACF private static TransientEntityTracker transientEntityTracker; -// private static ProtocolLibManager protocolLibManager; private SkillTools skillTools; @@ -186,9 +181,6 @@ public class mcMMO extends JavaPlugin { //Platform Manager platformManager = new PlatformManager(); - //metadata service - metadataService = new MetadataService(this); - MetadataConstants.MCMMO_METADATA_VALUE = new FixedMetadataValue(this, true); PluginManager pluginManager = getServer().getPluginManager(); @@ -319,9 +311,6 @@ public class mcMMO extends JavaPlugin { //Init the blacklist worldBlacklist = new WorldBlacklist(this); - //Init smelting tracker - smeltingTracker = new SmeltingTracker(); - //Set up Adventure's audiences audiences = BukkitAudiences.create(this); @@ -482,10 +471,6 @@ public class mcMMO extends JavaPlugin { return platformManager.getCompatibilityManager(); } - public static MetadataService getMetadataService() { - return metadataService; - } - @Deprecated public static void setDatabaseManager(DatabaseManager databaseManager) { mcMMO.databaseManager = databaseManager; @@ -741,10 +726,6 @@ public class mcMMO extends JavaPlugin { return platformManager; } - public static SmeltingTracker getSmeltingTracker() { - return smeltingTracker; - } - public static BukkitAudiences getAudiences() { return audiences; } diff --git a/src/main/java/com/gmail/nossr50/metadata/BlockMetadataService.java b/src/main/java/com/gmail/nossr50/metadata/BlockMetadataService.java deleted file mode 100644 index 1545cd608..000000000 --- a/src/main/java/com/gmail/nossr50/metadata/BlockMetadataService.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.gmail.nossr50.metadata; - -import com.gmail.nossr50.mcMMO; -import org.bukkit.block.Furnace; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataHolder; -import org.bukkit.persistence.PersistentDataType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.UUID; - -import static com.gmail.nossr50.metadata.MetadataService.NSK_FURNACE_UUID_LEAST_SIG; -import static com.gmail.nossr50.metadata.MetadataService.NSK_FURNACE_UUID_MOST_SIG; - -public class BlockMetadataService { - - private final @NotNull mcMMO pluginRef; - - public BlockMetadataService(@NotNull mcMMO pluginRef) { - this.pluginRef = pluginRef; - } - - public @Nullable UUID getFurnaceOwner(@NotNull Furnace furnace) { - //Get container from entity - PersistentDataContainer dataContainer = ((PersistentDataHolder) furnace).getPersistentDataContainer(); - - //Too lazy to make a custom data type for this stuff - Long mostSigBits = dataContainer.get(NSK_FURNACE_UUID_MOST_SIG, PersistentDataType.LONG); - Long leastSigBits = dataContainer.get(NSK_FURNACE_UUID_LEAST_SIG, PersistentDataType.LONG); - - if (mostSigBits != null && leastSigBits != null) { - return new UUID(mostSigBits, leastSigBits); - } else { - return null; - } - } - - public void setFurnaceOwner(@NotNull Furnace furnace, @NotNull UUID uuid) { - PersistentDataContainer dataContainer = ((PersistentDataHolder) furnace).getPersistentDataContainer(); - - dataContainer.set(NSK_FURNACE_UUID_MOST_SIG, PersistentDataType.LONG, uuid.getMostSignificantBits()); - dataContainer.set(NSK_FURNACE_UUID_LEAST_SIG, PersistentDataType.LONG, uuid.getLeastSignificantBits()); - - furnace.update(); - } - - -} diff --git a/src/main/java/com/gmail/nossr50/metadata/MetadataService.java b/src/main/java/com/gmail/nossr50/metadata/MetadataService.java deleted file mode 100644 index d38726737..000000000 --- a/src/main/java/com/gmail/nossr50/metadata/MetadataService.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.gmail.nossr50.metadata; - -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.MetadataConstants; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -public class MetadataService { - private final @NotNull mcMMO pluginRef; - - protected static final @NotNull NamespacedKey NSK_SUPER_ABILITY_BOOSTED_ITEM; - protected static final @NotNull NamespacedKey NSK_MOB_SPAWNER_MOB; - protected static final @NotNull NamespacedKey NSK_EGG_MOB; - protected static final @NotNull NamespacedKey NSK_NETHER_GATE_MOB; - protected static final @NotNull NamespacedKey NSK_COTW_SUMMONED_MOB; - protected static final @NotNull NamespacedKey NSK_PLAYER_BRED_MOB; - protected static final @NotNull NamespacedKey NSK_PLAYER_TAMED_MOB; - protected static final @NotNull NamespacedKey NSK_VILLAGER_TRADE_ORIGIN_ITEM; - protected static final @NotNull NamespacedKey NSK_EXPLOITED_ENDERMEN; - protected static final @NotNull NamespacedKey NSK_FURNACE_UUID_MOST_SIG; - protected static final @NotNull NamespacedKey NSK_FURNACE_UUID_LEAST_SIG; - - static { - NSK_SUPER_ABILITY_BOOSTED_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_SUPER_ABILITY_BOOSTED_ITEM); - NSK_MOB_SPAWNER_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_MOB_SPAWNER_MOB); - NSK_EGG_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_EGG_MOB); - NSK_NETHER_GATE_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_NETHER_PORTAL_MOB); - NSK_COTW_SUMMONED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_COTW_SUMMONED_MOB); - NSK_PLAYER_BRED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_BRED_MOB); - NSK_PLAYER_TAMED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_TAMED_MOB); - NSK_VILLAGER_TRADE_ORIGIN_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_VILLAGER_TRADE_ORIGIN_ITEM); - NSK_EXPLOITED_ENDERMEN = getNamespacedKey(MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN); - NSK_FURNACE_UUID_MOST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_FURNACE_UUID_MOST_SIG); - NSK_FURNACE_UUID_LEAST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_FURNACE_UUID_LEAST_SIG); - } - - private final @NotNull ItemMetadataService itemMetadataService; - private final @NotNull MobMetadataService mobMetadataService; - private final @NotNull BlockMetadataService blockMetadataService; - - public MetadataService(@NotNull mcMMO pluginRef) { - this.pluginRef = pluginRef; - - blockMetadataService = new BlockMetadataService(pluginRef); - mobMetadataService = new MobMetadataService(pluginRef); - itemMetadataService = new ItemMetadataService(pluginRef); - } - - /** - * Helper method to simplify generating namespaced keys - * - * @param key the {@link String} value of the key - * - * @return the generated {@link NamespacedKey} - */ - public static @NotNull NamespacedKey getNamespacedKey(@NotNull String key) { - return new NamespacedKey(mcMMO.p, key); - } - - public @NotNull ItemMetadataService getItemMetadataService() { - return itemMetadataService; - } - - public @NotNull MobMetadataService getMobMetadataService() { - return mobMetadataService; - } - - public @NotNull BlockMetadataService getBlockMetadataService() { - return blockMetadataService; - } -} diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java index 224538244..11618147e 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java @@ -1,32 +1,51 @@ package com.gmail.nossr50.runnables.skills; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.skills.alchemy.Alchemy; import com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer; import com.gmail.nossr50.util.CancellableRunnable; -import org.bukkit.Bukkit; +import com.gmail.nossr50.util.ContainerMetadataUtils; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.Location; +import org.bukkit.OfflinePlayer; import org.bukkit.block.BrewingStand; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Arrays; +import static com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer.isValidBrew; +import static com.gmail.nossr50.util.EventUtils.getMcMMOPlayer; + public class AlchemyBrewCheckTask extends CancellableRunnable { - private final Player player; private final BrewingStand brewingStand; private final ItemStack[] oldInventory; - public AlchemyBrewCheckTask(Player player, BrewingStand brewingStand) { - this.player = player; + @Deprecated(forRemoval = true, since = "2.2.010") + public AlchemyBrewCheckTask(@Nullable Player ignored, BrewingStand brewingStand) { + this(brewingStand); + } + + public AlchemyBrewCheckTask(@NotNull BrewingStand brewingStand) { this.brewingStand = brewingStand; this.oldInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4); } @Override public void run() { - Location location = brewingStand.getLocation(); - ItemStack[] newInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4); - boolean validBrew = brewingStand.getFuelLevel() > 0 && AlchemyPotionBrewer.isValidBrew(player, newInventory); + OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(brewingStand); + int ingredientLevel = 1; + if (offlinePlayer != null && offlinePlayer.isOnline()) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + if (mmoPlayer != null) { + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); + } + } + final Location location = brewingStand.getLocation(); + final ItemStack[] newInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4); + boolean validBrew = brewingStand.getFuelLevel() > 0 && isValidBrew(ingredientLevel, newInventory); if (Alchemy.brewingStandMap.containsKey(location)) { if (oldInventory[Alchemy.INGREDIENT_SLOT] == null @@ -36,7 +55,7 @@ public class AlchemyBrewCheckTask extends CancellableRunnable { Alchemy.brewingStandMap.get(location).cancelBrew(); } } else if (validBrew) { - Alchemy.brewingStandMap.put(location, new AlchemyBrewTask(brewingStand, player)); + Alchemy.brewingStandMap.put(location, new AlchemyBrewTask(brewingStand)); } } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java index 73e415f53..34c192852 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java @@ -1,5 +1,6 @@ package com.gmail.nossr50.runnables.skills; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.events.skills.alchemy.McMMOPlayerBrewEvent; @@ -8,44 +9,56 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.alchemy.Alchemy; import com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer; import com.gmail.nossr50.util.CancellableRunnable; +import com.gmail.nossr50.util.ContainerMetadataUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; -import org.bukkit.Bukkit; -import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.OfflinePlayer; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; public class AlchemyBrewTask extends CancellableRunnable { private static final double DEFAULT_BREW_SPEED = 1.0; private static final int DEFAULT_BREW_TICKS = 400; private final BlockState brewingStand; - private final Location location; + private final OfflinePlayer offlinePlayer; + private McMMOPlayer mmoPlayer; private double brewSpeed; private double brewTimer; - private final Player player; private int fuel; private boolean firstRun = true; + private int ingredientLevel = 1; + + @Deprecated(forRemoval = true, since = "2.2.010") + public AlchemyBrewTask(@NotNull BlockState brewingStand, Player ignored) { + this(brewingStand); + } + + public AlchemyBrewTask(@NotNull BlockState brewingStand) { + offlinePlayer = ContainerMetadataUtils.getContainerOwner(brewingStand); + McMMOPlayer mmoPlayer = null; + if (offlinePlayer != null && offlinePlayer.isOnline()) { + mmoPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + } - public AlchemyBrewTask(BlockState brewingStand, Player player) { this.brewingStand = brewingStand; - this.location = brewingStand.getLocation(); - this.player = player; brewSpeed = DEFAULT_BREW_SPEED; brewTimer = DEFAULT_BREW_TICKS; - if (player != null - && !Misc.isNPCEntityExcludingVillagers(player) - && Permissions.isSubSkillEnabled(player, SubSkillType.ALCHEMY_CATALYSIS) - && UserManager.getPlayer(player) != null) { + if (mmoPlayer != null + && !Misc.isNPCEntityExcludingVillagers(mmoPlayer.getPlayer()) + && Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), SubSkillType.ALCHEMY_CATALYSIS)) { + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); - double catalysis = UserManager.getPlayer(player).getAlchemyManager().calculateBrewSpeed(Permissions.lucky(player, PrimarySkillType.ALCHEMY)); + double catalysis = mmoPlayer.getAlchemyManager().calculateBrewSpeed(Permissions.lucky(mmoPlayer.getPlayer(), + PrimarySkillType.ALCHEMY)); - McMMOPlayerCatalysisEvent event = new McMMOPlayerCatalysisEvent(player, catalysis); + McMMOPlayerCatalysisEvent event = new McMMOPlayerCatalysisEvent(mmoPlayer, catalysis); mcMMO.p.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { @@ -53,8 +66,8 @@ public class AlchemyBrewTask extends CancellableRunnable { } } - if (Alchemy.brewingStandMap.containsKey(location)) { - Alchemy.brewingStandMap.get(location).cancel(); + if (Alchemy.brewingStandMap.containsKey(brewingStand.getLocation())) { + Alchemy.brewingStandMap.get(brewingStand.getLocation()).cancel(); } fuel = ((BrewingStand) brewingStand).getFuelLevel(); @@ -62,16 +75,16 @@ public class AlchemyBrewTask extends CancellableRunnable { if (((BrewingStand) brewingStand).getBrewingTime() == -1) // Only decrement on our end if it isn't a vanilla ingredient. fuel--; - Alchemy.brewingStandMap.put(location, this); - mcMMO.p.getFoliaLib().getImpl().runAtLocationTimer(location, this, 1, 1); + Alchemy.brewingStandMap.put(brewingStand.getLocation(), this); + mcMMO.p.getFoliaLib().getImpl().runAtLocationTimer(brewingStand.getLocation(), this, 1, 1); } @Override public void run() { // Check if preconditions for brewing are not met if (shouldCancelBrewing()) { - if (Alchemy.brewingStandMap.containsKey(location)) { - Alchemy.brewingStandMap.remove(location); + if (Alchemy.brewingStandMap.containsKey(brewingStand.getLocation())) { + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); } this.cancel(); return; @@ -93,10 +106,7 @@ public class AlchemyBrewTask extends CancellableRunnable { } private boolean shouldCancelBrewing() { - if (player == null) { - return true; - } - if (!player.isValid()) { + if (offlinePlayer == null) { return true; } if (brewingStand == null) { @@ -105,10 +115,24 @@ public class AlchemyBrewTask extends CancellableRunnable { if (brewingStand.getType() != Material.BREWING_STAND) { return true; } - if (!AlchemyPotionBrewer.isValidIngredient(player, ((BrewingStand) brewingStand).getInventory().getContents()[Alchemy.INGREDIENT_SLOT])) { - return true; + return !AlchemyPotionBrewer.isValidIngredientByLevel( + getIngredientLevelUpdated(), ((BrewingStand) brewingStand).getInventory().getContents()[Alchemy.INGREDIENT_SLOT]); + } + + private int getIngredientLevelUpdated() { + if (mmoPlayer != null) { + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); + return ingredientLevel; + } else if (offlinePlayer.isOnline() && mmoPlayer == null) { + final McMMOPlayer fetchedMMOPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + if (fetchedMMOPlayer != null) { + this.mmoPlayer = fetchedMMOPlayer; + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); + } + return ingredientLevel; + } else { + return ingredientLevel; } - return false; } private void initializeBrewing() { @@ -128,27 +152,27 @@ public class AlchemyBrewTask extends CancellableRunnable { private void finish() { - McMMOPlayerBrewEvent event = new McMMOPlayerBrewEvent(player, brewingStand); + final McMMOPlayerBrewEvent event = new McMMOPlayerBrewEvent(mmoPlayer, brewingStand); mcMMO.p.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { - AlchemyPotionBrewer.finishBrewing(brewingStand, player, false); + AlchemyPotionBrewer.finishBrewing(brewingStand, mmoPlayer.getPlayer(), false); } - Alchemy.brewingStandMap.remove(location); + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); } public void finishImmediately() { this.cancel(); - AlchemyPotionBrewer.finishBrewing(brewingStand, player, true); - Alchemy.brewingStandMap.remove(location); + AlchemyPotionBrewer.finishBrewing(brewingStand, mmoPlayer.getPlayer(), true); + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); } public void cancelBrew() { this.cancel(); ((BrewingStand) brewingStand).setBrewingTime(-1); - Alchemy.brewingStandMap.remove(location); + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); } } diff --git a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java index 08fd39ab4..7ffbdbb34 100644 --- a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java @@ -14,6 +14,7 @@ import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; +import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.ParticleEffectUtils; import com.gmail.nossr50.util.skills.RankUtils; @@ -94,7 +95,7 @@ public class AcrobaticsManager extends SkillManager { Player player = getPlayer(); if (!isFatal(modifiedDamage) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_DODGE, player)) { + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_DODGE, UserManager.getPlayer(player))) { ParticleEffectUtils.playDodgeEffect(player); if (mmoPlayer.useChatNotifications()) { diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index 1060e3f5c..6c28f64f9 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -1,5 +1,6 @@ package com.gmail.nossr50.skills.alchemy; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion; import com.gmail.nossr50.datatypes.skills.alchemy.PotionStage; @@ -9,7 +10,6 @@ import com.gmail.nossr50.runnables.player.PlayerUpdateInventoryTask; import com.gmail.nossr50.runnables.skills.AlchemyBrewCheckTask; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; -import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; @@ -20,14 +20,39 @@ import org.bukkit.inventory.BrewerInventory; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; +// TODO: Update to use McMMOPlayer public final class AlchemyPotionBrewer { + @Deprecated(forRemoval = true, since = "2.2.010") public static boolean isValidBrew(Player player, ItemStack[] contents) { - if (!isValidIngredient(player, contents[Alchemy.INGREDIENT_SLOT])) { + if (!isValidIngredientByPlayer(player, contents[Alchemy.INGREDIENT_SLOT])) { + return false; + } + + for (int i = 0; i < 3; i++) { + if (contents[i] == null || contents[i].getType() != Material.POTION + && contents[i].getType() != Material.SPLASH_POTION + && contents[i].getType() != Material.LINGERING_POTION) { + continue; + } + + final AlchemyPotion potion = mcMMO.p.getPotionConfig().getPotion(contents[i]); + if (getChildPotion(potion, contents[Alchemy.INGREDIENT_SLOT]) != null) { + return true; + } + } + + return false; + } + + public static boolean isValidBrew(int ingredientLevel, ItemStack[] contents) { + if (!isValidIngredientByLevel(ingredientLevel, contents[Alchemy.INGREDIENT_SLOT])) { return false; } @@ -65,7 +90,7 @@ public final class AlchemyPotionBrewer { ItemStack ingredient = inventory.getIngredient().clone(); - if (!isEmpty(ingredient) && isValidIngredient(player, ingredient)) { + if (!isEmpty(ingredient) && isValidIngredientByPlayer(player, ingredient)) { if (ingredient.getAmount() <= 1) { inventory.setIngredient(null); } @@ -79,15 +104,15 @@ public final class AlchemyPotionBrewer { private static boolean hasIngredient(BrewerInventory inventory, Player player) { ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); - return !isEmpty(ingredient) && isValidIngredient(player, ingredient); + return !isEmpty(ingredient) && isValidIngredientByPlayer(player, ingredient); } - public static boolean isValidIngredient(Player player, ItemStack item) { + public static boolean isValidIngredientByPlayer(Player player, ItemStack item) { if (isEmpty(item)) { return false; } - for (ItemStack ingredient : getValidIngredients(player)) { + for (ItemStack ingredient : getValidIngredients(UserManager.getPlayer(player))) { if (item.isSimilar(ingredient)) { return true; } @@ -96,12 +121,28 @@ public final class AlchemyPotionBrewer { return false; } - private static List getValidIngredients(Player player) { - if(player == null || UserManager.getPlayer(player) == null) { + public static boolean isValidIngredientByLevel(int ingredientLevel, ItemStack item) { + if (isEmpty(item)) { + return false; + } + + // TODO: Update this when we fix loading from hoppers + for (ItemStack ingredient : mcMMO.p.getPotionConfig().getIngredients(ingredientLevel)) { + if (item.isSimilar(ingredient)) { + return true; + } + } + + return false; + } + + private static List getValidIngredients(@Nullable McMMOPlayer mmoPlayer) { + if(mmoPlayer == null) { return mcMMO.p.getPotionConfig().getIngredients(1); } - return mcMMO.p.getPotionConfig().getIngredients(!Permissions.isSubSkillEnabled(player, SubSkillType.ALCHEMY_CONCOCTIONS) ? 1 : UserManager.getPlayer(player).getAlchemyManager().getTier()); + return mcMMO.p.getPotionConfig().getIngredients(!Permissions.isSubSkillEnabled(mmoPlayer, SubSkillType.ALCHEMY_CONCOCTIONS) + ? 1 : mmoPlayer.getAlchemyManager().getTier()); } public static void finishBrewing(BlockState brewingStand, Player player, boolean forced) { @@ -280,8 +321,9 @@ public final class AlchemyPotionBrewer { return false; } - public static void scheduleCheck(Player player, BrewingStand brewingStand) { - mcMMO.p.getFoliaLib().getImpl().runAtEntity(player, new AlchemyBrewCheckTask(player, brewingStand)); + public static void scheduleCheck(@NotNull BrewingStand brewingStand) { + mcMMO.p.getFoliaLib().getImpl().runAtLocation( + brewingStand.getLocation(), new AlchemyBrewCheckTask(brewingStand)); } public static void scheduleUpdate(Inventory inventory) { diff --git a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java index 16237f548..6aef4f92a 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java @@ -89,7 +89,7 @@ public class ArcheryManager extends SkillManager { * @param defender The {@link Player} being affected by the ability */ public double daze(Player defender) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_DAZE, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_DAZE, mmoPlayer)) { return 0; } @@ -116,7 +116,7 @@ public class ArcheryManager extends SkillManager { * @param oldDamage The raw damage value of this arrow before we modify it */ public double skillShot(double oldDamage) { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.ARCHERY_SKILL_SHOT, getPlayer())) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.ARCHERY_SKILL_SHOT, mmoPlayer)) { return Archery.getSkillShotBonusDamage(getPlayer(), oldDamage); } else { return oldDamage; diff --git a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java index d80f7292f..edabb1a52 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java @@ -18,6 +18,7 @@ import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @@ -69,7 +70,7 @@ public class AxesManager extends SkillManager { * Handle the effects of the Axe Mastery ability */ public double axeMastery() { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.AXES_AXE_MASTERY, getPlayer())) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.AXES_AXE_MASTERY, mmoPlayer)) { return Axes.getAxeMasteryBonusDamage(getPlayer()); } @@ -83,7 +84,7 @@ public class AxesManager extends SkillManager { * @param damage The amount of damage initially dealt by the event */ public double criticalHit(LivingEntity target, double damage) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_CRITICAL_STRIKES, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_CRITICAL_STRIKES, mmoPlayer)) { return 0; } @@ -115,10 +116,15 @@ public class AxesManager extends SkillManager { */ public void impactCheck(@NotNull LivingEntity target) { double durabilityDamage = getImpactDurabilityDamage(); + final EntityEquipment equipment = target.getEquipment(); - for (ItemStack armor : target.getEquipment().getArmorContents()) { + if (equipment == null) { + return; + } + + for (ItemStack armor : equipment.getArmorContents()) { if (armor != null && ItemUtils.isArmor(armor)) { - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_ARMOR_IMPACT, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_ARMOR_IMPACT, mmoPlayer)) { SkillUtils.handleArmorDurabilityChange(armor, durabilityDamage, 1); } } @@ -136,7 +142,7 @@ public class AxesManager extends SkillManager { */ public double greaterImpact(@NotNull LivingEntity target) { //static chance (3rd param) - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_GREATER_IMPACT, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_GREATER_IMPACT, mmoPlayer)) { return 0; } diff --git a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java index 75d7e5d23..671435d98 100644 --- a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java @@ -100,7 +100,7 @@ public class CrossbowsManager extends SkillManager { } public double poweredShot(double oldDamage) { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.CROSSBOWS_POWERED_SHOT, getPlayer())) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.CROSSBOWS_POWERED_SHOT, mmoPlayer)) { return getPoweredShotBonusDamage(getPlayer(), oldDamage); } else { return oldDamage; diff --git a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java index e3cf20fd3..3735cfb8c 100644 --- a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java +++ b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java @@ -46,7 +46,8 @@ public class ExcavationManager extends SkillManager { for (ExcavationTreasure treasure : treasures) { if (skillLevel >= treasure.getDropLevel() - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.EXCAVATION, getPlayer(), treasure.getDropProbability())) { + && ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.EXCAVATION, mmoPlayer, treasure.getDropProbability())) { processExcavationBonusesOnBlock(blockState, treasure, location); } } @@ -65,7 +66,8 @@ public class ExcavationManager extends SkillManager { @VisibleForTesting public void processExcavationBonusesOnBlock(BlockState blockState, ExcavationTreasure treasure, Location location) { //Spawn Vanilla XP orbs if a dice roll succeeds - if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.EXCAVATION, getPlayer(), getArchaelogyExperienceOrbChance())) { + if(ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.EXCAVATION, mmoPlayer, getArchaelogyExperienceOrbChance())) { Misc.spawnExperienceOrb(location, getExperienceOrbsReward()); } diff --git a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java index 5d0e24314..8274cb1dc 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java @@ -412,13 +412,13 @@ public class FishingManager extends SkillManager { enchants.putAll(treasureDrop.getItemMeta().getEnchants()); } - event = EventUtils.callFishingTreasureEvent(player, treasureDrop, treasure.getXp(), enchants); + event = EventUtils.callFishingTreasureEvent(mmoPlayer, treasureDrop, treasure.getXp(), enchants); } else { if (isMagicHunterEnabled() && ItemUtils.isEnchantable(treasureDrop)) { enchants = processMagicHunter(treasureDrop); } - event = EventUtils.callFishingTreasureEvent(player, treasureDrop, treasure.getXp(), enchants); + event = EventUtils.callFishingTreasureEvent(mmoPlayer, treasureDrop, treasure.getXp(), enchants); } if (!event.isCancelled()) { @@ -480,7 +480,7 @@ public class FishingManager extends SkillManager { * @param target The {@link LivingEntity} affected by the ability */ public void shakeCheck(@NotNull LivingEntity target) { - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.FISHING, getPlayer(), getShakeChance())) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.FISHING, mmoPlayer, getShakeChance())) { List possibleDrops = Fishing.findPossibleDrops(target); if (possibleDrops == null || possibleDrops.isEmpty()) { diff --git a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java index c75f03a1a..34c990351 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java @@ -33,7 +33,6 @@ import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.data.Ageable; import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.ItemStack; @@ -44,6 +43,7 @@ import java.util.*; import static com.gmail.nossr50.util.ItemUtils.hasItemIncludingOffHand; import static com.gmail.nossr50.util.ItemUtils.removeItemIncludingOffHand; +import static java.util.Objects.requireNonNull; public class HerbalismManager extends SkillManager { public HerbalismManager(McMMOPlayer mcMMOPlayer) { @@ -637,12 +637,13 @@ public class HerbalismManager extends SkillManager { /** * Check for success on herbalism double drops + * * @param blockState target block state - * @return true if double drop succeeds + * @return true if the double drop succeeds */ - private boolean checkDoubleDrop(BlockState blockState) - { - return BlockUtils.checkDoubleDrops(getPlayer(), blockState, skill, SubSkillType.HERBALISM_DOUBLE_DROPS); + private boolean checkDoubleDrop(@NotNull BlockState blockState) { + requireNonNull(blockState, "BlockState cannot be null"); + return BlockUtils.checkDoubleDrops(mmoPlayer, blockState, SubSkillType.HERBALISM_DOUBLE_DROPS); } /** @@ -652,7 +653,7 @@ public class HerbalismManager extends SkillManager { * @return true if the ability was successful, false otherwise */ public boolean processGreenThumbBlocks(BlockState blockState) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, mmoPlayer)) { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.GTh.Fail"); return false; } @@ -667,7 +668,7 @@ public class HerbalismManager extends SkillManager { * @return true if the ability was successful, false otherwise */ public boolean processHylianLuck(BlockState blockState) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_HYLIAN_LUCK, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_HYLIAN_LUCK, mmoPlayer)) { return false; } @@ -676,7 +677,6 @@ public class HerbalismManager extends SkillManager { return false; List treasures = TreasureConfig.getInstance().hylianMap.get(friendly); - Player player = getPlayer(); if (treasures.isEmpty()) { return false; @@ -686,13 +686,13 @@ public class HerbalismManager extends SkillManager { for (HylianTreasure treasure : treasures) { if (skillLevel >= treasure.getDropLevel() - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.HERBALISM, player, treasure.getDropChance())) { - if (!EventUtils.simulateBlockBreak(blockState.getBlock(), player)) { + && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.HERBALISM, mmoPlayer, treasure.getDropChance())) { + if (!EventUtils.simulateBlockBreak(blockState.getBlock(), mmoPlayer.getPlayer())) { return false; } blockState.setType(Material.AIR); Misc.spawnItem(getPlayer(), location, treasure.getDrop(), ItemSpawnReason.HYLIAN_LUCK_TREASURE); - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Herbalism.HylianLuck"); + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Herbalism.HylianLuck"); return true; } } @@ -706,25 +706,24 @@ public class HerbalismManager extends SkillManager { * @return true if the ability was successful, false otherwise */ public boolean processShroomThumb(BlockState blockState) { - Player player = getPlayer(); - PlayerInventory playerInventory = player.getInventory(); + PlayerInventory playerInventory = getPlayer().getInventory(); if (!playerInventory.contains(Material.BROWN_MUSHROOM, 1)) { - NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.BROWN_MUSHROOM)); + NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.BROWN_MUSHROOM)); return false; } if (!playerInventory.contains(Material.RED_MUSHROOM, 1)) { - NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.RED_MUSHROOM)); + NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.RED_MUSHROOM)); return false; } playerInventory.removeItem(new ItemStack(Material.BROWN_MUSHROOM)); playerInventory.removeItem(new ItemStack(Material.RED_MUSHROOM)); - player.updateInventory(); + getPlayer().updateInventory(); - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_SHROOM_THUMB, player)) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.ShroomThumb.Fail"); + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_SHROOM_THUMB, mmoPlayer)) { + NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.ShroomThumb.Fail"); return false; } @@ -789,7 +788,7 @@ public class HerbalismManager extends SkillManager { return false; } - if (!greenTerra && !ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, player)) { + if (!greenTerra && !ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, mmoPlayer)) { return false; } diff --git a/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java index 0e8b2e69b..d309ad9cb 100644 --- a/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java @@ -2,9 +2,7 @@ package com.gmail.nossr50.skills.maces; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; -import com.gmail.nossr50.datatypes.skills.ToolType; import com.gmail.nossr50.skills.SkillManager; -import com.gmail.nossr50.util.Permissions; public class MacesManager extends SkillManager { public MacesManager(McMMOPlayer mmoPlayer) { diff --git a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java index b91274ce4..231941acc 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java @@ -115,7 +115,7 @@ public class MiningManager extends SkillManager { private boolean processTripleDrops(@NotNull BlockState blockState) { //TODO: Make this readable - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.MINING_MOTHER_LODE, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.MINING_MOTHER_LODE, mmoPlayer)) { BlockUtils.markDropsAsBonus(blockState, 2); return true; } else { @@ -125,7 +125,7 @@ public class MiningManager extends SkillManager { private void processDoubleDrops(@NotNull BlockState blockState) { //TODO: Make this readable - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.MINING_DOUBLE_DROPS, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.MINING_DOUBLE_DROPS, mmoPlayer)) { boolean useTriple = mmoPlayer.getAbilityMode(SuperAbilityType.SUPER_BREAKER) && mcMMO.p.getAdvancedConfig().getAllowMiningTripleDrops(); BlockUtils.markDropsAsBonus(blockState, useTriple); } diff --git a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java index 08a6ce8e8..8186723cf 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java @@ -329,7 +329,7 @@ public class RepairManager extends SkillManager { if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.REPAIR_SUPER_REPAIR)) return false; - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.REPAIR_SUPER_REPAIR, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.REPAIR_SUPER_REPAIR, mmoPlayer)) { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Repair.Skills.FeltEasy"); return true; } @@ -380,10 +380,10 @@ public class RepairManager extends SkillManager { Enchantment enchantment = enchant.getKey(); - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, getPlayer(), getKeepEnchantChance())) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, mmoPlayer, getKeepEnchantChance())) { if (ArcaneForging.arcaneForgingDowngrades && enchantLevel > 1 - && (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, getPlayer(), 100 - getDowngradeEnchantChance()))) { + && (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, mmoPlayer, 100 - getDowngradeEnchantChance()))) { item.addUnsafeEnchantment(enchantment, enchantLevel - 1); downgraded = true; } diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java index cffd2bf37..5e477825d 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java @@ -125,7 +125,7 @@ public class SalvageManager extends SkillManager { for(int x = 0; x < potentialSalvageYield-1; x++) { - if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, player, chanceOfSuccess)) { + if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, mmoPlayer, chanceOfSuccess)) { chanceOfSuccess-=3; chanceOfSuccess = Math.max(chanceOfSuccess, 90); @@ -232,12 +232,14 @@ public class SalvageManager extends SkillManager { if (!Salvage.arcaneSalvageEnchantLoss || Permissions.hasSalvageEnchantBypassPerk(player) - || ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, player, getExtractFullEnchantChance())) { + || ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.SALVAGE, mmoPlayer, getExtractFullEnchantChance())) { enchantMeta.addStoredEnchant(enchant.getKey(), enchantLevel, true); } else if (enchantLevel > 1 && Salvage.arcaneSalvageDowngrades - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, player, getExtractPartialEnchantChance())) { + && ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.SALVAGE, mmoPlayer, getExtractPartialEnchantChance())) { enchantMeta.addStoredEnchant(enchant.getKey(), enchantLevel - 1, true); downgraded = true; } else { diff --git a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java index 9bb4a6e39..7fae80419 100644 --- a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java @@ -24,7 +24,7 @@ public class SmeltingManager extends SkillManager { public boolean isSecondSmeltSuccessful() { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SMELTING_SECOND_SMELT) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SMELTING_SECOND_SMELT, getPlayer()); + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SMELTING_SECOND_SMELT, mmoPlayer); } /** diff --git a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java index d68d98e8d..66c16f77d 100644 --- a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java @@ -76,7 +76,7 @@ public class SwordsManager extends SkillManager { } double ruptureOdds = mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(getRuptureRank()); - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SWORDS, this.getPlayer(), ruptureOdds)) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SWORDS, mmoPlayer, ruptureOdds)) { if (target instanceof Player defender) { @@ -142,7 +142,7 @@ public class SwordsManager extends SkillManager { */ public void counterAttackChecks(@NotNull LivingEntity attacker, double damage) { - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SWORDS_COUNTER_ATTACK, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SWORDS_COUNTER_ATTACK, mmoPlayer)) { CombatUtils.dealDamage(attacker, damage / Swords.counterAttackModifier, getPlayer()); NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Countered"); diff --git a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java index cd793aa71..927c51e1b 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java @@ -31,6 +31,8 @@ import org.jetbrains.annotations.NotNull; import java.util.HashMap; +import static com.gmail.nossr50.util.MobMetadataUtils.flagMetadata; + public class TamingManager extends SkillManager { //TODO: Temporary static cache, will be changed in 2.2 private static HashMap summoningItems; @@ -143,7 +145,7 @@ public class TamingManager extends SkillManager { * @param damage The damage being absorbed by the wolf */ public void fastFoodService(@NotNull Wolf wolf, double damage) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.TAMING_FAST_FOOD_SERVICE, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.TAMING_FAST_FOOD_SERVICE, mmoPlayer)) { return; } @@ -262,7 +264,7 @@ public class TamingManager extends SkillManager { if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) return; - if(!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.TAMING, getPlayer(), mcMMO.p.getAdvancedConfig().getPummelChance())) + if(!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.TAMING, mmoPlayer, mcMMO.p.getAdvancedConfig().getPummelChance())) return; ParticleEffectUtils.playGreaterImpactEffect(target); @@ -459,7 +461,7 @@ public class TamingManager extends SkillManager { private void applyMetaDataToCOTWEntity(LivingEntity summonedEntity) { //This helps identify the entity as being summoned by COTW - mcMMO.getMetadataService().getMobMetadataService().flagMetadata(MobMetaFlagType.COTW_SUMMONED_MOB, summonedEntity); + flagMetadata(MobMetaFlagType.COTW_SUMMONED_MOB, summonedEntity); } /** diff --git a/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java b/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java index 92d5d829b..23a8a1330 100644 --- a/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java @@ -3,9 +3,7 @@ package com.gmail.nossr50.skills.tridents; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; -import com.gmail.nossr50.datatypes.skills.ToolType; import com.gmail.nossr50.skills.SkillManager; -import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.skills.RankUtils; public class TridentsManager extends SkillManager { diff --git a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java index dbc8060ef..d4dc4faf9 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java @@ -67,7 +67,7 @@ public class UnarmedManager extends SkillManager { } public boolean blockCrackerCheck(@NotNull BlockState blockState) { - if (!ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_BLOCK_CRACKER, getPlayer())) { + if (!ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_BLOCK_CRACKER, mmoPlayer)) { return false; } @@ -98,7 +98,7 @@ public class UnarmedManager extends SkillManager { * @param defender The defending player */ public void disarmCheck(@NotNull Player defender) { - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_DISARM, getPlayer()) && !hasIronGrip(defender)) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_DISARM, mmoPlayer) && !hasIronGrip(defender)) { if (EventUtils.callDisarmEvent(defender).isCancelled()) { return; } @@ -121,7 +121,7 @@ public class UnarmedManager extends SkillManager { * Check for arrow deflection. */ public boolean deflectCheck() { - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_ARROW_DEFLECT, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_ARROW_DEFLECT, mmoPlayer)) { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Combat.ArrowDeflect"); return true; } @@ -144,7 +144,7 @@ public class UnarmedManager extends SkillManager { * Handle the effects of the Iron Arm ability */ public double calculateSteelArmStyleDamage() { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_STEEL_ARM_STYLE, getPlayer())) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_STEEL_ARM_STYLE, mmoPlayer)) { return getSteelArmStyleDamage(); } @@ -178,7 +178,7 @@ public class UnarmedManager extends SkillManager { private boolean hasIronGrip(@NotNull Player defender) { if (!Misc.isNPCEntityExcludingVillagers(defender) && Permissions.isSubSkillEnabled(defender, SubSkillType.UNARMED_IRON_GRIP) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_IRON_GRIP, defender)) { + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_IRON_GRIP, UserManager.getPlayer(defender))) { NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Unarmed.Ability.IronGrip.Defender"); NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Unarmed.Ability.IronGrip.Attacker"); diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java index c4ee8e41c..66270dfc6 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java @@ -72,14 +72,14 @@ public class WoodcuttingManager extends SkillManager { private boolean checkHarvestLumberActivation(Material material) { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) && RankUtils.hasReachedRank(1, getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_HARVEST_LUMBER, getPlayer()) + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_HARVEST_LUMBER, mmoPlayer) && mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material); } private boolean checkCleanCutsActivation(Material material) { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) && RankUtils.hasReachedRank(1, getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_CLEAN_CUTS, getPlayer()) + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_CLEAN_CUTS, mmoPlayer) && mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material); } @@ -336,7 +336,7 @@ public class WoodcuttingManager extends SkillManager { if(RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { if(RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { if(mcMMO.p.getAdvancedConfig().isKnockOnWoodXPOrbEnabled()) { - if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.WOODCUTTING, player, 10)) { + if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.WOODCUTTING, mmoPlayer, 10)) { int randOrbCount = Math.max(1, Misc.getRandom().nextInt(100)); Misc.spawnExperienceOrb(blockState.getLocation(), randOrbCount); } diff --git a/src/main/java/com/gmail/nossr50/util/BlockUtils.java b/src/main/java/com/gmail/nossr50/util/BlockUtils.java index 6edb342a5..d18a0e6d6 100644 --- a/src/main/java/com/gmail/nossr50/util/BlockUtils.java +++ b/src/main/java/com/gmail/nossr50/util/BlockUtils.java @@ -2,11 +2,13 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.meta.BonusDropMeta; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.salvage.Salvage; +import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import org.bukkit.Material; import org.bukkit.World; @@ -16,9 +18,12 @@ import org.bukkit.block.data.Ageable; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.HashSet; +import static java.util.Objects.requireNonNull; + public final class BlockUtils { public static final String SHORT_GRASS = "SHORT_GRASS"; @@ -94,10 +99,28 @@ public final class BlockUtils { * * @param blockState the blockstate * @return true if the player succeeded in the check + * @deprecated Use {@link #checkDoubleDrops(McMMOPlayer, BlockState, SubSkillType)} instead */ - public static boolean checkDoubleDrops(Player player, BlockState blockState, PrimarySkillType skillType, SubSkillType subSkillType) { - if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(skillType, blockState.getType()) && Permissions.isSubSkillEnabled(player, subSkillType)) { - return ProbabilityUtil.isSkillRNGSuccessful(subSkillType, player); + @Deprecated(forRemoval = true, since = "2.2.010") + public static boolean checkDoubleDrops(Player player, BlockState blockState, PrimarySkillType ignored, SubSkillType subSkillType) { + return checkDoubleDrops(UserManager.getPlayer(player), blockState, subSkillType); + } + + /** + * Checks if a player successfully passed the double drop check + * + * @param mmoPlayer the player involved in the check + * @param blockState the blockstate of the block + * @param subSkillType the subskill involved + * @return true if the player succeeded in the check + */ + public static boolean checkDoubleDrops(@Nullable McMMOPlayer mmoPlayer, @NotNull BlockState blockState, + @NotNull SubSkillType subSkillType) { + requireNonNull(blockState, "blockState cannot be null"); + requireNonNull(subSkillType, "subSkillType cannot be null"); + if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(subSkillType.getParentSkill(), blockState.getType()) + && Permissions.isSubSkillEnabled(mmoPlayer, subSkillType)) { + return ProbabilityUtil.isSkillRNGSuccessful(subSkillType, mmoPlayer); } return false; diff --git a/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java b/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java new file mode 100644 index 000000000..1183466db --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java @@ -0,0 +1,116 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.player.UserManager; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataHolder; +import org.bukkit.persistence.PersistentDataType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.UUID; + +import static com.gmail.nossr50.util.MetadataService.NSK_CONTAINER_UUID_LEAST_SIG; +import static com.gmail.nossr50.util.MetadataService.NSK_CONTAINER_UUID_MOST_SIG; +import static java.util.Objects.requireNonNull; + +public class ContainerMetadataUtils { + + public static void changeContainerOwnership(@NotNull BlockState blockState, @NotNull Player player) { + requireNonNull(blockState, "blockState cannot be null"); + requireNonNull(player, "Player cannot be null"); + + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + + /* + Debug output + */ + printOwnershipGainDebug(blockState, mmoPlayer); + printOwnershipLossDebug(blockState); + setOwner(blockState, player.getUniqueId()); + } + + public static void printOwnershipGainDebug(@NotNull BlockState blockState, @Nullable McMMOPlayer mmoPlayer) { + if(mmoPlayer != null && mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage("Container ownership " + + ChatColor.GREEN +"gained " + ChatColor.RESET + + "at location: " + blockState.getLocation().toString()); + } + } + + public static void printOwnershipLossDebug(BlockState blockState) { + OfflinePlayer containerOwner = getContainerOwner(blockState); + + if(containerOwner != null && containerOwner.isOnline()) { + final McMMOPlayer mmoContainerOwner = UserManager.getPlayer(containerOwner.getPlayer()); + + if(mmoContainerOwner != null) { + if(mmoContainerOwner.isDebugMode()) { + mmoContainerOwner.getPlayer().sendMessage("Container ownership " + + ChatColor.RED + "lost " + ChatColor.RESET + + "at location: " + blockState.getLocation().toString()); + } + } + } + } + + public static @Nullable OfflinePlayer getContainerOwner(BlockState container) { + if (container instanceof PersistentDataHolder persistentDataHolder) { + final UUID uuid = getOwner(persistentDataHolder); + + if(uuid != null) { + return Bukkit.getOfflinePlayer(uuid); + } + } + + return null; + } + + + public static boolean isContainerOwned(BlockState blockState) { + return getContainerOwner(blockState) != null; + } + + public static void processContainerOwnership(BlockState blockState, Player player) { + if(!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING)) + return; + + if(getContainerOwner(blockState) != null) { + if(getContainerOwner(blockState).getUniqueId().equals(player.getUniqueId())) + return; + } + + changeContainerOwnership(blockState, player); + } + + public static @Nullable UUID getOwner(@NotNull PersistentDataHolder persistentDataHolder) { + //Get container from entity + final PersistentDataContainer dataContainer = persistentDataHolder.getPersistentDataContainer(); + + //Too lazy to make a custom data type for this stuff + final Long mostSigBits = dataContainer.get(NSK_CONTAINER_UUID_MOST_SIG, PersistentDataType.LONG); + final Long leastSigBits = dataContainer.get(NSK_CONTAINER_UUID_LEAST_SIG, PersistentDataType.LONG); + + if (mostSigBits != null && leastSigBits != null) { + return new UUID(mostSigBits, leastSigBits); + } else { + return null; + } + } + + public static void setOwner(@NotNull BlockState blockState, @NotNull UUID uuid) { + PersistentDataContainer dataContainer = ((PersistentDataHolder) blockState).getPersistentDataContainer(); + + dataContainer.set(NSK_CONTAINER_UUID_MOST_SIG, PersistentDataType.LONG, uuid.getMostSignificantBits()); + dataContainer.set(NSK_CONTAINER_UUID_LEAST_SIG, PersistentDataType.LONG, uuid.getLeastSignificantBits()); + + blockState.update(); + } +} diff --git a/src/main/java/com/gmail/nossr50/util/EventUtils.java b/src/main/java/com/gmail/nossr50/util/EventUtils.java index f53fde6df..4cb7f7703 100644 --- a/src/main/java/com/gmail/nossr50/util/EventUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EventUtils.java @@ -10,7 +10,6 @@ import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; -import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.events.experience.McMMOPlayerLevelChangeEvent; import com.gmail.nossr50.events.experience.McMMOPlayerLevelDownEvent; import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent; @@ -59,6 +58,8 @@ import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; +import static java.util.Objects.requireNonNull; + /** * This class is meant to help make event related code less boilerplate */ @@ -163,8 +164,17 @@ public final class EventUtils { * Others */ - public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent(@NotNull Player player, @NotNull PrimarySkillType skill) { - McMMOPlayerAbilityActivateEvent event = new McMMOPlayerAbilityActivateEvent(player, skill); + @Deprecated(forRemoval = true, since = "2.2.010") + public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent(@NotNull Player player, + @NotNull PrimarySkillType skill) { + return callPlayerAbilityActivateEvent(requireNonNull(UserManager.getPlayer(player)), skill); + } + + public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent(@NotNull McMMOPlayer mmoPlayer, + @NotNull PrimarySkillType skill) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); + requireNonNull(skill, "skill cannot be null"); + McMMOPlayerAbilityActivateEvent event = new McMMOPlayerAbilityActivateEvent(mmoPlayer, skill); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; @@ -183,8 +193,21 @@ public final class EventUtils { * @param subSkillType target subskill * @return the event after it has been fired */ + @Deprecated(forRemoval = true, since = "2.2.010") public static @NotNull SubSkillEvent callSubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType) { - SubSkillEvent event = new SubSkillEvent(player, subSkillType); + return callSubSkillEvent(requireNonNull(UserManager.getPlayer(player)), subSkillType); + } + + /** + * Calls a new SubSkillEvent for this SubSkill and then returns it + * @param mmoPlayer target mmoPlayer + * @param subSkillType target subskill + * @return the event after it has been fired + */ + public static @NotNull SubSkillEvent callSubSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); + requireNonNull(subSkillType, "subSkillType cannot be null"); + final SubSkillEvent event = new SubSkillEvent(mmoPlayer, subSkillType); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; @@ -204,26 +227,6 @@ public final class EventUtils { return event; } - /** - * Calls a new SubSkillEvent for this SubSkill and then returns it - * @param player target player - * @param abstractSubSkill target subskill - * @return the event after it has been fired - */ - public static SubSkillEvent callSubSkillEvent(Player player, AbstractSubSkill abstractSubSkill) { - SubSkillEvent event = new SubSkillEvent(player, abstractSubSkill); - mcMMO.p.getServer().getPluginManager().callEvent(event); - - return event; - } - -// public static Event callFakeArmSwingEvent(@NotNull Player player) { -// PlayerAnimationEvent event = new FakePlayerAnimationEvent(player, PlayerAnimationType.ARM_SWING); -// mcMMO.p.getServer().getPluginManager().callEvent(event); -// -// return event; -// } - public static boolean tryLevelChangeEvent(Player player, PrimarySkillType skill, int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason) { McMMOPlayerLevelChangeEvent event = isLevelUp ? new McMMOPlayerLevelUpEvent(player, skill, levelsChanged, xpGainReason) : new McMMOPlayerLevelDownEvent(player, skill, levelsChanged, xpGainReason); mcMMO.p.getServer().getPluginManager().callEvent(event); @@ -497,15 +500,25 @@ public final class EventUtils { return !isCancelled; } + @Deprecated(forRemoval = true, since = "2.2.010") public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent(Player player, SuperAbilityType ability) { - McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent(player, mcMMO.p.getSkillTools().getPrimarySkillBySuperAbility(ability)); + return callAbilityDeactivateEvent(requireNonNull(UserManager.getPlayer(player)), ability); + } + + public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull SuperAbilityType ability) { + final McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent(mmoPlayer, mcMMO.p.getSkillTools().getPrimarySkillBySuperAbility(ability)); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; } + @Deprecated(forRemoval = true, since = "2.2.010") public static McMMOPlayerFishingTreasureEvent callFishingTreasureEvent(Player player, ItemStack treasureDrop, int treasureXp, Map enchants) { - McMMOPlayerFishingTreasureEvent event = enchants.isEmpty() ? new McMMOPlayerFishingTreasureEvent(player, treasureDrop, treasureXp) : new McMMOPlayerMagicHunterEvent(player, treasureDrop, treasureXp, enchants); + return callFishingTreasureEvent(requireNonNull(UserManager.getPlayer(player)), treasureDrop, treasureXp, enchants); + } + + public static McMMOPlayerFishingTreasureEvent callFishingTreasureEvent(McMMOPlayer mmoPlayer, ItemStack treasureDrop, int treasureXp, Map enchants) { + final McMMOPlayerFishingTreasureEvent event = enchants.isEmpty() ? new McMMOPlayerFishingTreasureEvent(mmoPlayer, treasureDrop, treasureXp) : new McMMOPlayerMagicHunterEvent(mmoPlayer, treasureDrop, treasureXp, enchants); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; diff --git a/src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java b/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java similarity index 77% rename from src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java rename to src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java index a6734a53e..e6074692e 100644 --- a/src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java +++ b/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java @@ -1,4 +1,4 @@ -package com.gmail.nossr50.metadata; +package com.gmail.nossr50.util; import com.gmail.nossr50.mcMMO; import org.bukkit.inventory.ItemStack; @@ -9,18 +9,17 @@ import org.jetbrains.annotations.NotNull; import java.util.List; -import static com.gmail.nossr50.metadata.MetadataService.NSK_SUPER_ABILITY_BOOSTED_ITEM; +import static com.gmail.nossr50.util.MetadataService.NSK_SUPER_ABILITY_BOOSTED_ITEM; -public class ItemMetadataService { +public final class ItemMetadataUtils { - public final @NotNull String LEGACY_ABILITY_TOOL_LORE = "mcMMO Ability Tool"; - public final @NotNull mcMMO pluginRef; + public static final @NotNull String LEGACY_ABILITY_TOOL_LORE = "mcMMO Ability Tool"; - public ItemMetadataService(@NotNull mcMMO pluginRef) { - this.pluginRef = pluginRef; + private ItemMetadataUtils() { + // private ctor } - public void setSuperAbilityBoostedItem(@NotNull ItemStack itemStack, int originalDigSpeed) { + public static void setSuperAbilityBoostedItem(@NotNull ItemStack itemStack, int originalDigSpeed) { if (itemStack.getItemMeta() == null) { mcMMO.p.getLogger().severe("Can not assign persistent data to an item with null item metadata"); return; @@ -34,7 +33,7 @@ public class ItemMetadataService { itemStack.setItemMeta(itemMeta); } - public boolean isSuperAbilityBoosted(@NotNull ItemStack itemStack) { + public static boolean isSuperAbilityBoosted(@NotNull ItemStack itemStack) { if (itemStack.getItemMeta() == null) return false; @@ -48,7 +47,7 @@ public class ItemMetadataService { return boostValue != null; } - public int getSuperAbilityToolOriginalDigSpeed(@NotNull ItemStack itemStack) { + public static int getSuperAbilityToolOriginalDigSpeed(@NotNull ItemStack itemStack) { //Get container from entity ItemMeta itemMeta = itemStack.getItemMeta(); @@ -67,7 +66,7 @@ public class ItemMetadataService { } } - public void removeBonusDigSpeedOnSuperAbilityTool(@NotNull ItemStack itemStack) { + public static void removeBonusDigSpeedOnSuperAbilityTool(@NotNull ItemStack itemStack) { int originalSpeed = getSuperAbilityToolOriginalDigSpeed(itemStack); ItemMeta itemMeta = itemStack.getItemMeta(); @@ -89,7 +88,7 @@ public class ItemMetadataService { } } - public boolean isLegacyAbilityTool(@NotNull ItemStack itemStack) { + public static boolean isLegacyAbilityTool(@NotNull ItemStack itemStack) { ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta == null) @@ -102,8 +101,4 @@ public class ItemMetadataService { return lore.contains(LEGACY_ABILITY_TOOL_LORE); } - - public @NotNull String getLegacyAbilityToolLore() { - return LEGACY_ABILITY_TOOL_LORE; - } } diff --git a/src/main/java/com/gmail/nossr50/util/MetadataConstants.java b/src/main/java/com/gmail/nossr50/util/MetadataConstants.java index 39f9479ce..d3145e42c 100644 --- a/src/main/java/com/gmail/nossr50/util/MetadataConstants.java +++ b/src/main/java/com/gmail/nossr50/util/MetadataConstants.java @@ -34,8 +34,9 @@ public class MetadataConstants { public static final @NotNull String METADATA_KEY_DISARMED_ITEM = "mcMMO: Disarmed Item"; public static final @NotNull String METADATA_KEY_PLAYER_DATA = "mcMMO: Player Data"; public static final @NotNull String METADATA_KEY_DATABASE_COMMAND = "mcMMO: Processing Database Command"; - public static final @NotNull String METADATA_KEY_FURNACE_UUID_MOST_SIG = "furnace_uuid_most_sig"; - public static final @NotNull String METADATA_KEY_FURNACE_UUID_LEAST_SIG = "furnace_uuid_least_sig"; + // the value of these two keys have "furnace" to keep supporting legacy data + public static final @NotNull String METADATA_KEY_CONTAINER_UUID_MOST_SIG = "furnace_uuid_most_sig"; + public static final @NotNull String METADATA_KEY_CONTAINER_UUID_LEAST_SIG = "furnace_uuid_least_sig"; public static final @NotNull String METADATA_KEY_SUPER_ABILITY_BOOSTED_ITEM = "super_ability_boosted"; public static final @NotNull String METADATA_KEY_MOB_SPAWNER_MOB = "mcmmo_mob_spawner_mob"; public static final @NotNull String METADATA_KEY_EGG_MOB = "mcmmo_egg_mob"; diff --git a/src/main/java/com/gmail/nossr50/util/MetadataService.java b/src/main/java/com/gmail/nossr50/util/MetadataService.java new file mode 100644 index 000000000..fac2b83a3 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/MetadataService.java @@ -0,0 +1,48 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.NamespacedKey; +import org.jetbrains.annotations.NotNull; + +public final class MetadataService { + static final @NotNull NamespacedKey NSK_SUPER_ABILITY_BOOSTED_ITEM; + static final @NotNull NamespacedKey NSK_MOB_SPAWNER_MOB; + static final @NotNull NamespacedKey NSK_EGG_MOB; + static final @NotNull NamespacedKey NSK_NETHER_GATE_MOB; + static final @NotNull NamespacedKey NSK_COTW_SUMMONED_MOB; + static final @NotNull NamespacedKey NSK_PLAYER_BRED_MOB; + static final @NotNull NamespacedKey NSK_PLAYER_TAMED_MOB; + static final @NotNull NamespacedKey NSK_VILLAGER_TRADE_ORIGIN_ITEM; + static final @NotNull NamespacedKey NSK_EXPLOITED_ENDERMEN; + static final @NotNull NamespacedKey NSK_CONTAINER_UUID_MOST_SIG; + static final @NotNull NamespacedKey NSK_CONTAINER_UUID_LEAST_SIG; + + private MetadataService() { + // private ctor + } + + static { + NSK_SUPER_ABILITY_BOOSTED_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_SUPER_ABILITY_BOOSTED_ITEM); + NSK_MOB_SPAWNER_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_MOB_SPAWNER_MOB); + NSK_EGG_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_EGG_MOB); + NSK_NETHER_GATE_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_NETHER_PORTAL_MOB); + NSK_COTW_SUMMONED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_COTW_SUMMONED_MOB); + NSK_PLAYER_BRED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_BRED_MOB); + NSK_PLAYER_TAMED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_TAMED_MOB); + NSK_VILLAGER_TRADE_ORIGIN_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_VILLAGER_TRADE_ORIGIN_ITEM); + NSK_EXPLOITED_ENDERMEN = getNamespacedKey(MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN); + NSK_CONTAINER_UUID_MOST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_CONTAINER_UUID_MOST_SIG); + NSK_CONTAINER_UUID_LEAST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_CONTAINER_UUID_LEAST_SIG); + } + + /** + * Helper method to simplify generating namespaced keys + * + * @param key the {@link String} value of the key + * + * @return the generated {@link NamespacedKey} + */ + public static @NotNull NamespacedKey getNamespacedKey(@NotNull String key) { + return new NamespacedKey(mcMMO.p, key); + } +} diff --git a/src/main/java/com/gmail/nossr50/metadata/MobMetadataService.java b/src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java similarity index 83% rename from src/main/java/com/gmail/nossr50/metadata/MobMetadataService.java rename to src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java index e78b056c9..4e0ad1924 100644 --- a/src/main/java/com/gmail/nossr50/metadata/MobMetadataService.java +++ b/src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java @@ -1,9 +1,8 @@ -package com.gmail.nossr50.metadata; +package com.gmail.nossr50.util; import com.gmail.nossr50.api.exceptions.IncompleteNamespacedKeyRegister; import com.gmail.nossr50.config.PersistentDataConfig; -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.metadata.MobMetaFlagType; import org.bukkit.NamespacedKey; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -15,17 +14,19 @@ import java.util.EnumMap; import java.util.HashSet; import java.util.WeakHashMap; -import static com.gmail.nossr50.metadata.MetadataService.*; +import static com.gmail.nossr50.util.MetadataService.*; //TODO: Use SpawnReason where appropriate instead of MobMetaFlagType -public class MobMetadataService { - private final @NotNull WeakHashMap> mobRegistry; //transient data - private final @NotNull EnumMap mobFlagKeyMap; //used for persistent data - private final @NotNull mcMMO pluginRef; - private boolean isUsingPersistentData = false; +public final class MobMetadataUtils { + private static final @NotNull WeakHashMap> mobRegistry; //transient data + private static final @NotNull EnumMap mobFlagKeyMap; //used for persistent data + private static boolean isUsingPersistentData = false; - public MobMetadataService(@NotNull mcMMO pluginRef) { - this.pluginRef = pluginRef; + private MobMetadataUtils() { + // private ctor + } + + static { mobFlagKeyMap = new EnumMap<>(MobMetaFlagType.class); mobRegistry = new WeakHashMap<>(); initMobFlagKeyMap(); @@ -40,7 +41,7 @@ public class MobMetadataService { * Registers the namespaced keys required by the API (CB/Spigot) * Used primarily for persistent data */ - private void initMobFlagKeyMap() throws IncompleteNamespacedKeyRegister { + private static void initMobFlagKeyMap() throws IncompleteNamespacedKeyRegister { for (MobMetaFlagType mobMetaFlagType : MobMetaFlagType.values()) { switch (mobMetaFlagType) { case MOB_SPAWNER_MOB -> mobFlagKeyMap.put(mobMetaFlagType, NSK_MOB_SPAWNER_MOB); @@ -63,7 +64,7 @@ public class MobMetadataService { * * @return true if the mob has metadata values for target {@link MobMetaFlagType} */ - public boolean hasMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static boolean hasMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { return livingEntity.getPersistentDataContainer().has(mobFlagKeyMap.get(flag), PersistentDataType.BYTE); } else { @@ -82,7 +83,7 @@ public class MobMetadataService { * * @return true if the mob has any mcMMO mob related metadata values */ - public boolean hasMobFlags(@NotNull LivingEntity livingEntity) { + public static boolean hasMobFlags(@NotNull LivingEntity livingEntity) { if (isUsingPersistentData) { for (MobMetaFlagType metaFlagType : MobMetaFlagType.values()) { if (hasMobFlag(metaFlagType, livingEntity)) @@ -102,7 +103,7 @@ public class MobMetadataService { * @param sourceEntity entity to copy from * @param targetEntity entity to copy to */ - public void addMobFlags(@NotNull LivingEntity sourceEntity, @NotNull LivingEntity targetEntity) { + public static void addMobFlags(@NotNull LivingEntity sourceEntity, @NotNull LivingEntity targetEntity) { if (!hasMobFlags(sourceEntity)) return; @@ -125,7 +126,7 @@ public class MobMetadataService { * @param flag the desired flag to assign * @param livingEntity the target living entity */ - public void flagMetadata(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static void flagMetadata(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { if (!hasMobFlag(flag, livingEntity)) { PersistentDataContainer persistentDataContainer = livingEntity.getPersistentDataContainer(); @@ -144,7 +145,7 @@ public class MobMetadataService { * @param flag desired flag to remove * @param livingEntity the target living entity */ - public void removeMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static void removeMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { if (hasMobFlag(flag, livingEntity)) { PersistentDataContainer persistentDataContainer = livingEntity.getPersistentDataContainer(); @@ -165,7 +166,7 @@ public class MobMetadataService { * * @param livingEntity target entity */ - public void removeMobFlags(@NotNull LivingEntity livingEntity) { + public static void removeMobFlags(@NotNull LivingEntity livingEntity) { if (isUsingPersistentData) { for (MobMetaFlagType flag : MobMetaFlagType.values()) { removeMobFlag(flag, livingEntity); diff --git a/src/main/java/com/gmail/nossr50/util/Permissions.java b/src/main/java/com/gmail/nossr50/util/Permissions.java index 66e6bab70..03fcae47a 100644 --- a/src/main/java/com/gmail/nossr50/util/Permissions.java +++ b/src/main/java/com/gmail/nossr50/util/Permissions.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.commands.party.PartySubcommandType; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.ItemType; import com.gmail.nossr50.datatypes.skills.MaterialType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; @@ -17,6 +18,7 @@ import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.PluginManager; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Locale; @@ -171,10 +173,19 @@ public final class Permissions { } public static boolean vanillaXpBoost(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase(Locale.ENGLISH) + ".vanillaxpboost"); } - public static boolean isSubSkillEnabled(Permissible permissible, SubSkillType subSkillType) { + public static boolean isSubSkillEnabled(@Nullable Permissible permissible, @NotNull SubSkillType subSkillType) { + if (permissible == null) + return false; return permissible.hasPermission(subSkillType.getPermissionNodeAddress()); } + public static boolean isSubSkillEnabled(@Nullable McMMOPlayer permissible, @NotNull SubSkillType subSkillType) { + if (permissible == null) + return false; + + return isSubSkillEnabled(permissible.getPlayer(), subSkillType); + } + /* ACROBATICS */ public static boolean dodge(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.acrobatics.dodge"); } public static boolean gracefulRoll(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.acrobatics.gracefulroll"); } diff --git a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java index 8b258d03a..d6bed4509 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java +++ b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java @@ -18,6 +18,8 @@ import org.jetbrains.annotations.Nullable; import java.util.*; +import static com.gmail.nossr50.util.MobMetadataUtils.removeMobFlags; + public class TransientEntityTracker { //These two are updated in step with each other private final @NotNull HashMap>> perPlayerTransientEntityMap; @@ -273,7 +275,7 @@ public class TransientEntityTracker { } //Remove our metadata - mcMMO.getMetadataService().getMobMetadataService().removeMobFlags(livingEntity); + removeMobFlags(livingEntity); //Clean from trackers unregisterEntity(livingEntity); diff --git a/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java b/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java index 8b21e9d1a..7fb29ed60 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java +++ b/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java @@ -4,6 +4,8 @@ import com.gmail.nossr50.mcMMO; import org.bukkit.entity.LivingEntity; import org.jetbrains.annotations.NotNull; +import static com.gmail.nossr50.util.MobMetadataUtils.removeMobFlags; + public class TransientMetadataTools { private final mcMMO pluginRef; @@ -30,7 +32,7 @@ public class TransientMetadataTools { } //Cleanup mob metadata - mcMMO.getMetadataService().getMobMetadataService().removeMobFlags(entity); + removeMobFlags(entity); //TODO: This loop has some redundancy, this whole method needs to be rewritten for(String key : MetadataConstants.MOB_METADATA_KEYS) { diff --git a/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java b/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java index 4836efedc..093b631f5 100644 --- a/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java +++ b/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java @@ -11,26 +11,37 @@ import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.VisibleForTesting; import java.text.DecimalFormat; +import static java.util.Objects.requireNonNull; + public class ProbabilityUtil { public static final @NotNull DecimalFormat percent = new DecimalFormat("##0.00%"); public static final double LUCKY_MODIFIER = 1.333D; /** - * Return a chance of success in "percentage" format, show to the player in UI elements + * Return a chance of success in "percentage" format, shown to the player in UI elements * * @param player target player * @param subSkillType target subskill * @param isLucky whether to apply luck modifiers * * @return "percentage" representation of success + * @deprecated use {@link #chanceOfSuccessPercentage(McMMOPlayer, SubSkillType, boolean)} instead */ - public static double chanceOfSuccessPercentage(@NotNull Player player, + @Deprecated(forRemoval = true, since = "2.2.010") + public static double chanceOfSuccessPercentage(@Nullable Player player, @NotNull SubSkillType subSkillType, boolean isLucky) { - Probability probability = getSubSkillProbability(subSkillType, player); + return chanceOfSuccessPercentage(requireNonNull(UserManager.getPlayer(player)), subSkillType, isLucky); + } + + public static double chanceOfSuccessPercentage(@Nullable McMMOPlayer mmoPlayer, + @NotNull SubSkillType subSkillType, + boolean isLucky) { + Probability probability = getSubSkillProbability(subSkillType, mmoPlayer); //Probability values are on a 0-1 scale and need to be "transformed" into a 1-100 scale double percentageValue = probability.getValue(); //Doesn't need to be scaled @@ -42,6 +53,13 @@ public class ProbabilityUtil { return percentageValue; } + /** + * Return a chance of success as a double representing a "percentage". + * + * @param probability the probability of success + * @param isLucky whether to apply luck modifiers + * @return a double as a "percentage" representation of success + */ public static double chanceOfSuccessPercentage(@NotNull Probability probability, boolean isLucky) { //Probability values are on a 0-1 scale and need to be "transformed" into a 1-100 scale double percentageValue = probability.getValue(); @@ -54,6 +72,7 @@ public class ProbabilityUtil { return percentageValue; } + @VisibleForTesting static Probability getStaticRandomChance(@NotNull SubSkillType subSkillType) throws InvalidStaticChance { return switch (subSkillType) { case AXES_ARMOR_IMPACT -> Probability.ofPercent(mcMMO.p.getAdvancedConfig().getImpactChance()); @@ -74,19 +93,20 @@ public class ProbabilityUtil { return skillProbabilityType; } - static @NotNull Probability ofSubSkill(@Nullable Player player, - @NotNull SubSkillType subSkillType) { + @Deprecated(forRemoval = true, since = "2.2.010") + private static @NotNull Probability ofSubSkill(@Nullable Player player, @NotNull SubSkillType subSkillType) { + // no null check needed here + return ofSubSkill(UserManager.getPlayer(player), subSkillType); + } + + private static @NotNull Probability ofSubSkill(@Nullable McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType) { switch (getProbabilityType(subSkillType)) { case DYNAMIC_CONFIGURABLE: double probabilityCeiling; double skillLevel; double maxBonusLevel; // If a skill level is equal to the cap, it has the full probability - if (player != null) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mmoPlayer == null) { - return Probability.ofPercent(0); - } + if (mmoPlayer != null) { skillLevel = mmoPlayer.getSkillLevel(subSkillType.getParentSkill()); } else { skillLevel = 0; @@ -101,10 +121,10 @@ public class ProbabilityUtil { try { return getStaticRandomChance(subSkillType); } catch (InvalidStaticChance invalidStaticChance) { - invalidStaticChance.printStackTrace(); + throw new RuntimeException(invalidStaticChance); } default: - throw new RuntimeException("No case in switch statement for Skill Probability Type!"); + throw new IllegalStateException("No case in switch statement for Skill Probability Type!"); } } @@ -123,14 +143,43 @@ public class ProbabilityUtil { * The outcome of the probability can also be modified by this event that is called * * @param subSkillType target subskill - * @param player target player, can be null (null players are given odds equivalent to a player with no levels or luck) + * @param player target player + * can be null (null players are given odds equivalent to a player with no levels or luck) + * @return true if the Skill RNG succeeds, false if it fails + * @deprecated use {@link #isSkillRNGSuccessful(SubSkillType, McMMOPlayer)} instead + */ + @Deprecated(forRemoval = true, since = "2.2.010") + public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @Nullable Player player) { + return isSkillRNGSuccessful(subSkillType, UserManager.getPlayer(player)); + } + + /** + * This is one of several Skill RNG check methods + * This helper method is for specific {@link SubSkillType}, + * which help mcMMO understand where the RNG values used in our calculations come from this {@link SubSkillType} + *

+ * 1) Determine where the RNG values come from for the passed {@link SubSkillType} + * NOTE: In the config file, there are values which are static and which are more dynamic, + * this is currently a bit hardcoded and will need to be updated manually + *

+ * 2) Determine whether to use Lucky multiplier and influence the outcome + *

+ * 3) + * Creates a {@link Probability} and pipes it to {@link ProbabilityUtil} which processes the result and returns it + *

+ * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will return false + * The outcome of the probability can also be modified by this event that is called + * + * @param subSkillType target subskill + * @param mmoPlayer target player + * can be null (null players are given odds equivalent to a player with no levels or luck) * @return true if the Skill RNG succeeds, false if it fails */ - public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @NotNull Player player) { - final Probability probability = getSkillProbability(subSkillType, player); + public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @Nullable McMMOPlayer mmoPlayer) { + final Probability probability = getSkillProbability(subSkillType, mmoPlayer); //Luck - boolean isLucky = Permissions.lucky(player, subSkillType.getParentSkill()); + boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), subSkillType.getParentSkill()); if(isLucky) { return probability.evaluate(LUCKY_MODIFIER); @@ -143,29 +192,50 @@ public class ProbabilityUtil { * Returns the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player}. * This does not take into account perks such as lucky for the player. * This is affected by other plugins who can listen to the {@link SubSkillEvent} and cancel it or mutate it. + * Null players will be treated as zero skill players. * * @param subSkillType the target subskill * @param player the target player + * can be null (null players have the worst odds) + * @return the probability for this skill + * @deprecated use {@link #getSkillProbability(SubSkillType, McMMOPlayer)} instead + */ + @Deprecated(forRemoval = true) + public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, @Nullable Player player) { + return getSkillProbability(subSkillType, UserManager.getPlayer(player)); + } + + /** + * Returns the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player}. + * This does not take into account perks such as lucky for the player. + * This is affected by other plugins who can listen to the {@link SubSkillEvent} and cancel it or mutate it. + * Null players will be treated as zero skill players. + * + * @param subSkillType the target subskill + * @param mmoPlayer the target player + * can be null (null players have the worst odds) * @return the probability for this skill */ - public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, @NotNull Player player) { - //Process probability - Probability probability = getSubSkillProbability(subSkillType, player); + public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, @Nullable McMMOPlayer mmoPlayer) { + // Process probability + Probability probability = getSubSkillProbability(subSkillType, mmoPlayer); - //Send out event - SubSkillEvent subSkillEvent = EventUtils.callSubSkillEvent(player, subSkillType); + // Send out event + if (mmoPlayer != null) { + SubSkillEvent subSkillEvent = EventUtils.callSubSkillEvent(mmoPlayer, subSkillType); - if(subSkillEvent.isCancelled()) { - return Probability.ALWAYS_FAILS; + if(subSkillEvent.isCancelled()) { + return Probability.ALWAYS_FAILS; + } + + // Result modifier + double resultModifier = subSkillEvent.getResultModifier(); + + // Mutate probability + if(resultModifier != 1.0D) + probability = Probability.ofPercent(probability.getValue() * resultModifier); } - //Result modifier - double resultModifier = subSkillEvent.getResultModifier(); - - //Mutate probability - if(resultModifier != 1.0D) - probability = Probability.ofPercent(probability.getValue() * resultModifier); - return probability; } @@ -177,12 +247,11 @@ public class ProbabilityUtil { * @param player the target player can be null (null players have the worst odds) * @param probabilityPercentage the probability of this player succeeding in "percentage" format (0-100 inclusive) * @return true if the RNG succeeds, false if it fails + * @deprecated use {@link #isStaticSkillRNGSuccessful(PrimarySkillType, McMMOPlayer, double)} instead */ + @Deprecated(forRemoval = true, since = "2.2.010") public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, @Nullable Player player, double probabilityPercentage) { - //Grab a probability converted from a "percentage" value - Probability probability = Probability.ofPercent(probabilityPercentage); - - return isStaticSkillRNGSuccessful(primarySkillType, player, probability); + return isStaticSkillRNGSuccessful(primarySkillType, player, Probability.ofPercent(probabilityPercentage)); } /** @@ -190,12 +259,49 @@ public class ProbabilityUtil { * This helper method is specific to static value RNG, which can be influenced by a player's Luck * * @param primarySkillType the related primary skill - * @param player the target player, can be null (null players have the worst odds) - * @param probability the probability of this player succeeding + * @param mmoPlayer the target player can be null (null players have the worst odds) + * @param probabilityPercentage the probability of this player succeeding in "percentage" format (0-100 inclusive) * @return true if the RNG succeeds, false if it fails */ - public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, @Nullable Player player, @NotNull Probability probability) { - boolean isLucky = player != null && Permissions.lucky(player, primarySkillType); + public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, + @Nullable McMMOPlayer mmoPlayer, double probabilityPercentage) { + //Grab a probability converted from a "percentage" value + final Probability probability = Probability.ofPercent(probabilityPercentage); + + return isStaticSkillRNGSuccessful(primarySkillType, mmoPlayer, probability); + } + + /** + * This is one of several Skill RNG check methods + * This helper method is specific to static value RNG, which can be influenced by a player's Luck + * + * @param primarySkillType the related primary skill + * @param player the target player + * can be null (null players have the worst odds) + * @param probability the probability of this player succeeding + * @return true if the RNG succeeds, false if it fails + * @deprecated use {@link #isStaticSkillRNGSuccessful(PrimarySkillType, McMMOPlayer, Probability)} instead, this + * method is redundant and will be removed. + */ + @Deprecated(forRemoval = true, since = "2.2.010") + public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, + @Nullable Player player, @NotNull Probability probability) { + return isStaticSkillRNGSuccessful(primarySkillType, UserManager.getPlayer(player), probability); + } + + /** + * This is one of several Skill RNG check methods + * This helper method is specific to static value RNG, which can be influenced by a mmoPlayer's Luck + * + * @param primarySkillType the related primary skill + * @param mmoPlayer the target mmoPlayer + * can be null (null players have the worst odds) + * @param probability the probability of this mmoPlayer succeeding + * @return true if the RNG succeeds, false if it fails + */ + public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, + @Nullable McMMOPlayer mmoPlayer, @NotNull Probability probability) { + boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), primarySkillType); if(isLucky) { return probability.evaluate(LUCKY_MODIFIER); @@ -209,25 +315,57 @@ public class ProbabilityUtil { * @param subSkillType target subskill * @param player target player * @return true if the skill succeeds (wasn't cancelled by any other plugin) + * @deprecated use {@link #isNonRNGSkillActivationSuccessful(SubSkillType, McMMOPlayer)} instead */ + @Deprecated(forRemoval = true, since = "2.2.010") public static boolean isNonRNGSkillActivationSuccessful(@NotNull SubSkillType subSkillType, @NotNull Player player) { - return !EventUtils.callSubSkillEvent(player, subSkillType).isCancelled(); + return isNonRNGSkillActivationSuccessful(subSkillType, requireNonNull(UserManager.getPlayer(player))); } /** - * Grab the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player} - * + * Skills activate without RNG, this allows other plugins to prevent that activation * @param subSkillType target subskill - * @param player target player - * @return the Probability of this skill succeeding + * @param mmoPlayer target player + * @return true if the skill succeeds (wasn't cancelled by any other plugin) */ - public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, @Nullable Player player) { + public static boolean isNonRNGSkillActivationSuccessful(@NotNull SubSkillType subSkillType, + @NotNull McMMOPlayer mmoPlayer) { + return !EventUtils.callSubSkillEvent(mmoPlayer, subSkillType).isCancelled(); + } + + /** + * Retrieves the {@link Probability} of success for a specified {@link SubSkillType} for a given {@link Player}. + * + * @param subSkillType The targeted subskill. + * @param player The player in question. + * If null, the method treats it as a player with no levels or luck and calculates the probability + * accordingly. + * @return The probability that the specified skill will succeed. + * @deprecated use {@link #getSubSkillProbability(SubSkillType, McMMOPlayer)} instead + */ + @Deprecated(forRemoval = true, since = "2.2.010") + public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, + @Nullable Player player) { return ProbabilityUtil.ofSubSkill(player, subSkillType); } - public static @NotNull String[] getRNGDisplayValues(@NotNull Player player, @NotNull SubSkillType subSkill) { - double firstValue = chanceOfSuccessPercentage(player, subSkill, false); - double secondValue = chanceOfSuccessPercentage(player, subSkill, true); + /** + * Retrieves the {@link Probability} of success for a specified {@link SubSkillType} for a given {@link Player}. + * + * @param subSkillType The targeted subskill. + * @param mmoPlayer The player in question. + * If null, the method treats it as a player with no levels or luck and calculates the probability + * accordingly. + * @return The probability that the specified skill will succeed. + */ + public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, + @Nullable McMMOPlayer mmoPlayer) { + return ProbabilityUtil.ofSubSkill(mmoPlayer, subSkillType); + } + + public static @NotNull String[] getRNGDisplayValues(@Nullable McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkill) { + double firstValue = chanceOfSuccessPercentage(mmoPlayer, subSkill, false); + double secondValue = chanceOfSuccessPercentage(mmoPlayer, subSkill, true); return new String[]{percent.format(firstValue), percent.format(secondValue)}; } diff --git a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java index 35057f1f9..8be5e4195 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java @@ -9,7 +9,6 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.metadata.MobMetaFlagType; -import com.gmail.nossr50.metadata.MobMetadataService; import com.gmail.nossr50.runnables.skills.AwardCombatXpTask; import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager; import com.gmail.nossr50.skills.archery.ArcheryManager; @@ -37,14 +36,12 @@ import org.jetbrains.annotations.Nullable; import java.util.List; +import static com.gmail.nossr50.util.MobMetadataUtils.hasMobFlag; + public final class CombatUtils { private CombatUtils() {} - private static @NotNull MobMetadataService getMobMetadataService() { - return mcMMO.getMetadataService().getMobMetadataService(); - } - public static boolean isDamageLikelyFromNormalCombat(@NotNull DamageCause damageCause) { return switch (damageCause) { case ENTITY_ATTACK, ENTITY_SWEEP_ATTACK, PROJECTILE -> true; @@ -926,17 +923,17 @@ public final class CombatUtils { } } - if(getMobMetadataService().hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) { + if(hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) { baseXP = 0; - } else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) { + } else if(hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) { baseXP *= ExperienceConfig.getInstance().getSpawnedMobXpMultiplier(); - } else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) { + } else if(hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getNetherPortalXpMultiplier(); - } else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.EGG_MOB, target)) { + } else if(hasMobFlag(MobMetaFlagType.EGG_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getEggXpMultiplier(); - } else if (getMobMetadataService().hasMobFlag(MobMetaFlagType.PLAYER_BRED_MOB, target)) { + } else if (hasMobFlag(MobMetaFlagType.PLAYER_BRED_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getBredMobXpMultiplier(); - } else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.PLAYER_TAMED_MOB, target)) { + } else if(hasMobFlag(MobMetaFlagType.PLAYER_TAMED_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getTamedMobXpMultiplier(); } diff --git a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java index 2d83cb063..ca651cd52 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.util.skills; import com.gmail.nossr50.config.experience.ExperienceConfig; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.SkillActivationPerkEvent; import com.gmail.nossr50.util.Permissions; @@ -106,4 +107,19 @@ public final class PerksUtils { return NORMAL_SKILL_ACTIVATION_CHANCE; } + + /** + * Calculate activation chance for a skill. + * + * @param mmoPlayer Player to check the activation chance for + * @param skill PrimarySkillType to check the activation chance of + * @return the activation chance with "lucky perk" accounted for + */ + public static int handleLuckyPerks(McMMOPlayer mmoPlayer, PrimarySkillType skill) { + if (Permissions.lucky(mmoPlayer.getPlayer(), skill)) { + return LUCKY_SKILL_ACTIVATION_CHANCE; + } + + return NORMAL_SKILL_ACTIVATION_CHANCE; + } } diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java index 17589c2fa..20b9afd3d 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java @@ -10,7 +10,7 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.metadata.ItemMetadataService; +import com.gmail.nossr50.util.ItemMetadataUtils; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; @@ -32,6 +32,7 @@ import org.jetbrains.annotations.Nullable; import java.util.Iterator; +import static com.gmail.nossr50.util.ItemMetadataUtils.*; import static com.gmail.nossr50.util.PotionEffectMapper.getHaste; public final class SkillUtils { @@ -152,7 +153,7 @@ public final class SkillUtils { ItemUtils.addDigSpeedToItem(heldItem, heldItem.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getEfficiency())); //1.13.2+ will have persistent metadata for this item - mcMMO.getMetadataService().getItemMetadataService().setSuperAbilityBoostedItem(heldItem, originalDigSpeed); + ItemMetadataUtils.setSuperAbilityBoostedItem(heldItem, originalDigSpeed); } else { int duration = 0; int amplifier = 0; @@ -209,9 +210,7 @@ public final class SkillUtils { //1.13.2+ will have persistent metadata for this itemStack - ItemMetadataService itemMetadataService = mcMMO.getMetadataService().getItemMetadataService(); - - if(itemMetadataService.isLegacyAbilityTool(itemStack)) { + if(isLegacyAbilityTool(itemStack)) { ItemMeta itemMeta = itemStack.getItemMeta(); if(itemMeta != null) { @@ -223,8 +222,8 @@ public final class SkillUtils { } } - if(itemMetadataService.isSuperAbilityBoosted(itemStack)) { - itemMetadataService.removeBonusDigSpeedOnSuperAbilityTool(itemStack); + if(isSuperAbilityBoosted(itemStack)) { + removeBonusDigSpeedOnSuperAbilityTool(itemStack); } } diff --git a/src/main/java/com/gmail/nossr50/util/skills/SmeltingTracker.java b/src/main/java/com/gmail/nossr50/util/skills/SmeltingTracker.java deleted file mode 100644 index 83e993a10..000000000 --- a/src/main/java/com/gmail/nossr50/util/skills/SmeltingTracker.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.gmail.nossr50.util.skills; - -import com.gmail.nossr50.datatypes.player.McMMOPlayer; -import com.gmail.nossr50.datatypes.skills.PrimarySkillType; -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.player.UserManager; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.bukkit.block.Furnace; -import org.bukkit.entity.Player; -import org.bukkit.inventory.FurnaceInventory; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.Nullable; - -import java.util.UUID; - -public class SmeltingTracker { - -// private final HashMap furnaceOwners; - - private void changeFurnaceOwnership(Furnace furnace, Player player) { - - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - - /* - Debug output - */ - printOwnershipGainDebug(furnace, mcMMOPlayer); - - printOwnershipLossDebug(furnace); - - setFurnaceOwner(furnace, player); - } - - private void setFurnaceOwner(Furnace furnace, Player player) { - mcMMO.getMetadataService().getBlockMetadataService().setFurnaceOwner(furnace, player.getUniqueId()); - } - - private void printOwnershipGainDebug(Furnace furnace, McMMOPlayer mcMMOPlayer) { - if(mcMMOPlayer != null) { - if(mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("Furnace ownership " + - ChatColor.GREEN +"gained " + ChatColor.RESET + - "at location: " + furnace.getLocation().toString()); - } - - } - } - - private void printOwnershipLossDebug(Furnace furnace) { - OfflinePlayer furnaceOwner = getFurnaceOwner(furnace); - - if(furnaceOwner != null && furnaceOwner.isOnline()) { - McMMOPlayer furnaceOwnerProfile = UserManager.getPlayer(furnaceOwner.getPlayer()); - - if(furnaceOwnerProfile != null) { - if(furnaceOwnerProfile.isDebugMode()) { - furnaceOwnerProfile.getPlayer().sendMessage("Furnace ownership " + - ChatColor.RED + "lost " + ChatColor.RESET + - "at location: " + furnace.getLocation().toString()); - } - } - } - } - - public @Nullable OfflinePlayer getFurnaceOwner(Furnace furnace) { - UUID uuid = mcMMO.getMetadataService().getBlockMetadataService().getFurnaceOwner(furnace); - - if(uuid != null) { - return Bukkit.getOfflinePlayer(uuid); - } else { - return null; - } - } - - @Nullable - public Furnace getFurnaceFromInventory(Inventory inventory) { - if (!(inventory instanceof FurnaceInventory)) { - return null; - } - - return (Furnace) inventory.getHolder(); - } - - public boolean isFurnaceOwned(Furnace furnace) { - return getFurnaceOwner(furnace) != null; - } - - public void processFurnaceOwnership(Furnace furnace, Player player) { - if(!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING)) - return; - - //Don't swap ownership if its the same player - if(getFurnaceOwner(furnace) != null) { - if(getFurnaceOwner(furnace).getUniqueId().equals(player.getUniqueId())) - return; - } - - changeFurnaceOwnership(furnace, player); - } -} diff --git a/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java b/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java index 89981bb85..2cbfe4b1a 100644 --- a/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java +++ b/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java @@ -10,6 +10,7 @@ import com.gmail.nossr50.listeners.InteractionManager; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; +import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; @@ -345,7 +346,8 @@ public class TextComponentFactory { componentBuilder.append(Component.newline()); //Finally, add details to the tooltip - abstractSubSkill.addStats(componentBuilder, player); + // TODO: pass in McMMOPlayer instead + abstractSubSkill.addStats(componentBuilder, UserManager.getPlayer(player)); } return componentBuilder.build(); diff --git a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java index 47e2126aa..68561c936 100644 --- a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java +++ b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java @@ -21,7 +21,6 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFactory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; -import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.PluginManager; import org.mockito.MockedStatic; import org.mockito.Mockito; diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java index 4994f8053..44420a093 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java @@ -62,7 +62,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { when(advancedConfig.getMaximumProbability(UNARMED_ARROW_DEFLECT)).thenReturn(20D); when(advancedConfig.getMaxBonusLevel(UNARMED_ARROW_DEFLECT)).thenReturn(0); - final Probability probability = ProbabilityUtil.getSkillProbability(UNARMED_ARROW_DEFLECT, player); + @SuppressWarnings("all") + final Probability probability = ProbabilityUtil.getSkillProbability(UNARMED_ARROW_DEFLECT, mmoPlayer); assertEquals(0.2D, probability.getValue()); assertProbabilityExpectations(20, probability); } From 435a6fde346b0e75f998989155c13e05671e1cc8 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 12 May 2024 14:11:59 -0700 Subject: [PATCH 16/34] update Changelog.txt --- Changelog.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Changelog.txt b/Changelog.txt index 6ce59e238..c8c2107ae 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,4 +1,7 @@ Version 2.2.010 + # TODO: Fix not moving mcMMO custom ingredients from hopper -> brewing stand + # TODO: Fix some potions are not rewarding XP ( strength 2, etc ) + BrewingStand now remember who owns them, this persists across restarts (see notes) Fixed rare NPE in mcMMO events when player data was unable to be retrieved Fixed a NPE that could happen when damaging armor with Axes Fixed a bug where Alchemy brewing would be cancelled if the player died @@ -35,6 +38,7 @@ Version 2.2.010 (API) Added ctor AlchemyBrewCheckTask(org.bukkit.block.BrewingStand) NOTES: + You can now use hoppers and brewing stands and not have to worry about having to re-interact with the brewing stand over and over again This is not an exhaustive list of API changes in this update, but most of them should be documented here. Version 2.2.009 From 291effdbc840fe8aed5f4b67d270663e25fc25dc Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 12 May 2024 14:13:34 -0700 Subject: [PATCH 17/34] if( -> if ( --- .../com/gmail/nossr50/api/AbilityAPI.java | 4 +- .../com/gmail/nossr50/api/ExperienceAPI.java | 10 +- .../java/com/gmail/nossr50/api/PartyAPI.java | 24 +-- .../com/gmail/nossr50/chat/ChatManager.java | 10 +- .../nossr50/chat/SamePartyPredicate.java | 6 +- .../chat/author/AbstractPlayerAuthor.java | 8 +- .../nossr50/chat/mailer/AdminChatMailer.java | 4 +- .../nossr50/chat/mailer/PartyChatMailer.java | 8 +- .../chat/message/PartyChatMessage.java | 6 +- .../nossr50/commands/CommandManager.java | 24 +-- .../gmail/nossr50/commands/McmmoCommand.java | 2 +- .../nossr50/commands/McscoreboardCommand.java | 4 +- .../gmail/nossr50/commands/XprateCommand.java | 10 +- .../commands/admin/DropTreasureCommand.java | 8 +- .../commands/admin/PlayerDebugCommand.java | 2 +- .../commands/chat/AdminChatCommand.java | 8 +- .../commands/chat/PartyChatCommand.java | 10 +- .../database/ConvertDatabaseCommand.java | 2 +- .../commands/experience/AddlevelsCommand.java | 6 +- .../commands/experience/AddxpCommand.java | 6 +- .../experience/ExperienceCommand.java | 14 +- .../commands/experience/MmoeditCommand.java | 6 +- .../experience/SkillresetCommand.java | 2 +- .../party/PartyChangePasswordCommand.java | 2 +- .../nossr50/commands/party/PartyCommand.java | 4 +- .../commands/party/PartyCreateCommand.java | 2 +- .../commands/party/PartyInfoCommand.java | 2 +- .../commands/party/PartyItemShareCommand.java | 2 +- .../commands/party/PartyJoinCommand.java | 4 +- .../commands/party/PartyLockCommand.java | 2 +- .../commands/party/PartyXpShareCommand.java | 2 +- .../party/alliance/PartyAllianceCommand.java | 2 +- .../party/teleport/PtpAcceptCommand.java | 2 +- .../commands/party/teleport/PtpCommand.java | 12 +- .../commands/player/McrankCommand.java | 2 +- .../nossr50/commands/player/XPBarCommand.java | 18 +- .../commands/skills/AcrobaticsCommand.java | 2 +- .../commands/skills/ArcheryCommand.java | 2 +- .../nossr50/commands/skills/AxesCommand.java | 2 +- .../commands/skills/CrossbowsCommand.java | 2 +- .../commands/skills/ExcavationCommand.java | 2 +- .../commands/skills/FishingCommand.java | 2 +- .../nossr50/commands/skills/MacesCommand.java | 2 +- .../commands/skills/MiningCommand.java | 2 +- .../commands/skills/MmoInfoCommand.java | 10 +- .../nossr50/commands/skills/SkillCommand.java | 10 +- .../commands/skills/SwordsCommand.java | 4 +- .../commands/skills/TridentsCommand.java | 4 +- .../commands/skills/UnarmedCommand.java | 2 +- .../commands/skills/WoodcuttingCommand.java | 6 +- .../gmail/nossr50/config/BukkitConfig.java | 4 +- .../gmail/nossr50/config/WorldBlacklist.java | 2 +- .../config/skills/alchemy/PotionConfig.java | 4 +- .../skills/repair/RepairConfigManager.java | 2 +- .../skills/salvage/SalvageConfigManager.java | 2 +- .../treasure/FishingTreasureConfig.java | 2 +- .../database/FlatFileDataProcessor.java | 36 ++-- .../database/FlatFileDatabaseManager.java | 70 +++---- .../nossr50/database/SQLDatabaseManager.java | 10 +- .../flatfile/FlatFileDataBuilder.java | 2 +- .../database/flatfile/FlatFileDataUtil.java | 8 +- .../datatypes/LevelUpBroadcastPredicate.java | 24 +-- .../PowerLevelUpBroadcastPredicate.java | 24 +-- .../gmail/nossr50/datatypes/party/Party.java | 6 +- .../nossr50/datatypes/player/McMMOPlayer.java | 36 ++-- .../datatypes/player/PlayerProfile.java | 14 +- .../datatypes/skills/MaterialType.java | 2 +- .../datatypes/skills/SubSkillType.java | 2 +- .../datatypes/skills/alchemy/PotionStage.java | 2 +- .../skills/subskills/acrobatics/Roll.java | 20 +- .../skills/subskills/taming/TamingSummon.java | 2 +- .../treasure/FishingTreasureBook.java | 6 +- .../nossr50/datatypes/treasure/Rarity.java | 2 +- .../McMMOPlayerExperienceEvent.java | 2 +- .../nossr50/listeners/BlockListener.java | 124 ++++++------ .../nossr50/listeners/EntityListener.java | 188 +++++++++--------- .../nossr50/listeners/InteractionManager.java | 10 +- .../nossr50/listeners/InventoryListener.java | 66 +++--- .../nossr50/listeners/PlayerListener.java | 130 ++++++------ .../gmail/nossr50/listeners/SelfListener.java | 36 ++-- .../nossr50/listeners/WorldListener.java | 6 +- .../gmail/nossr50/locale/LocaleLoader.java | 2 +- src/main/java/com/gmail/nossr50/mcMMO.java | 24 +-- .../com/gmail/nossr50/party/PartyManager.java | 2 +- .../com/gmail/nossr50/party/ShareHandler.java | 4 +- .../runnables/MobDodgeMetaCleanup.java | 2 +- .../nossr50/runnables/SaveTimerTask.java | 2 +- .../runnables/TravelingBlockMetaCleanup.java | 2 +- .../commands/MctopCommandDisplayTask.java | 8 +- .../commands/NotifySquelchReminderTask.java | 4 +- .../player/PlayerProfileLoadingTask.java | 2 +- .../runnables/skills/AbilityDisableTask.java | 2 +- .../runnables/skills/AwardCombatXpTask.java | 2 +- .../runnables/skills/BleedTimerTask.java | 14 +- .../runnables/skills/DelayedCropReplant.java | 22 +- .../skills/ExperienceBarHideTask.java | 2 +- .../nossr50/runnables/skills/RuptureTask.java | 16 +- .../skills/acrobatics/AcrobaticsManager.java | 14 +- .../skills/alchemy/AlchemyPotionBrewer.java | 6 +- .../skills/archery/ArcheryManager.java | 12 +- .../com/gmail/nossr50/skills/axes/Axes.java | 4 +- .../nossr50/skills/axes/AxesManager.java | 10 +- .../nossr50/skills/crossbows/Crossbows.java | 2 +- .../skills/crossbows/CrossbowsManager.java | 2 +- .../skills/excavation/ExcavationManager.java | 2 +- .../skills/fishing/FishingManager.java | 38 ++-- .../skills/herbalism/HerbalismManager.java | 108 +++++----- .../nossr50/skills/mining/BlastMining.java | 6 +- .../nossr50/skills/mining/MiningManager.java | 20 +- .../nossr50/skills/repair/RepairManager.java | 10 +- .../repair/repairables/SimpleRepairable.java | 2 +- .../skills/salvage/SalvageManager.java | 12 +- .../skills/smelting/SmeltingManager.java | 2 +- .../nossr50/skills/swords/SwordsManager.java | 22 +- .../nossr50/skills/taming/TamingManager.java | 36 ++-- .../skills/tridents/TridentsManager.java | 4 +- .../gmail/nossr50/skills/unarmed/Unarmed.java | 14 +- .../skills/unarmed/UnarmedManager.java | 14 +- .../woodcutting/WoodcuttingManager.java | 28 +-- .../com/gmail/nossr50/util/BlockUtils.java | 6 +- .../com/gmail/nossr50/util/ChimaeraWing.java | 2 +- .../nossr50/util/ContainerMetadataUtils.java | 16 +- .../gmail/nossr50/util/EnchantmentMapper.java | 2 +- .../com/gmail/nossr50/util/EventUtils.java | 16 +- .../util/FixSpellingNetheriteUtil.java | 6 +- .../gmail/nossr50/util/HardcoreManager.java | 12 +- .../gmail/nossr50/util/HolidayManager.java | 8 +- .../gmail/nossr50/util/ItemMetadataUtils.java | 2 +- .../com/gmail/nossr50/util/ItemUtils.java | 34 ++-- .../java/com/gmail/nossr50/util/Misc.java | 8 +- .../gmail/nossr50/util/MobHealthbarUtils.java | 2 +- .../nossr50/util/TransientEntityTracker.java | 18 +- .../nossr50/util/TransientMetadataTools.java | 4 +- .../nossr50/util/commands/CommandUtils.java | 4 +- .../util/compat/CompatibilityManager.java | 18 +- .../PlayerAttackCooldownToolLayer.java | 6 +- .../util/experience/ExperienceBarManager.java | 16 +- .../util/experience/ExperienceBarWrapper.java | 12 +- .../util/experience/FormulaManager.java | 4 +- .../util/platform/MajorMinorPatchVersion.java | 2 +- .../util/platform/MinecraftGameVersion.java | 8 +- .../util/platform/PlatformManager.java | 4 +- .../util/player/NotificationManager.java | 40 ++-- .../nossr50/util/player/PlayerLevelUtils.java | 2 +- .../nossr50/util/player/UserManager.java | 16 +- .../nossr50/util/random/ProbabilityUtil.java | 14 +- .../util/scoreboards/ScoreboardManager.java | 66 +++--- .../util/scoreboards/ScoreboardWrapper.java | 16 +- .../nossr50/util/skills/CombatUtils.java | 90 ++++----- .../util/skills/ParticleEffectUtils.java | 4 +- .../gmail/nossr50/util/skills/PerksUtils.java | 4 +- .../nossr50/util/skills/ProjectileUtils.java | 22 +- .../gmail/nossr50/util/skills/RankUtils.java | 30 +-- .../gmail/nossr50/util/skills/SkillTools.java | 6 +- .../gmail/nossr50/util/skills/SkillUtils.java | 30 +-- .../nossr50/util/sounds/SoundManager.java | 12 +- .../gmail/nossr50/util/text/StringUtils.java | 2 +- .../gmail/nossr50/util/text/TextUtils.java | 14 +- .../nossr50/worldguard/WorldGuardManager.java | 8 +- .../nossr50/worldguard/WorldGuardUtils.java | 14 +- .../database/FlatFileDatabaseManagerTest.java | 14 +- .../nossr50/util/random/ProbabilityTest.java | 2 +- .../util/random/ProbabilityTestUtils.java | 2 +- 163 files changed, 1116 insertions(+), 1116 deletions(-) diff --git a/src/main/java/com/gmail/nossr50/api/AbilityAPI.java b/src/main/java/com/gmail/nossr50/api/AbilityAPI.java index 3ad6d43e7..1597fbb20 100644 --- a/src/main/java/com/gmail/nossr50/api/AbilityAPI.java +++ b/src/main/java/com/gmail/nossr50/api/AbilityAPI.java @@ -83,8 +83,8 @@ public final class AbilityAPI { } public static boolean isBleeding(LivingEntity entity) { - if(entity.isValid()) { - if(entity.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { + if (entity.isValid()) { + if (entity.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { return true; } } diff --git a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java index c626810ec..fd928fdee 100644 --- a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java +++ b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java @@ -516,7 +516,7 @@ public final class ExperienceAPI { } public static float getOfflineXPRaw(@NotNull OfflinePlayer offlinePlayer, @NotNull PrimarySkillType skillType) throws InvalidPlayerException, UnsupportedOperationException { - if(SkillTools.isChildSkill(skillType)) + if (SkillTools.isChildSkill(skillType)) throw new UnsupportedOperationException(); return getOfflineProfile(offlinePlayer).getSkillXpLevelRaw(skillType); @@ -1149,7 +1149,7 @@ public final class ExperienceAPI { { for(PrimarySkillType skillType : PrimarySkillType.values()) { - if(ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) + if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), XPGainReason.PVE, XPGainSource.SELF); } @@ -1167,7 +1167,7 @@ public final class ExperienceAPI { { for(BlockState bs : blockStates) { - if(ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) + if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), XPGainReason.PVE, XPGainSource.SELF); } @@ -1183,7 +1183,7 @@ public final class ExperienceAPI { { for(PrimarySkillType skillType : PrimarySkillType.values()) { - if(ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) + if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), XPGainReason.PVE, XPGainSource.SELF); } @@ -1198,7 +1198,7 @@ public final class ExperienceAPI { */ public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) { - if(ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) + if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), XPGainReason.PVE, XPGainSource.SELF); } diff --git a/src/main/java/com/gmail/nossr50/api/PartyAPI.java b/src/main/java/com/gmail/nossr50/api/PartyAPI.java index e86bf4619..246131408 100644 --- a/src/main/java/com/gmail/nossr50/api/PartyAPI.java +++ b/src/main/java/com/gmail/nossr50/api/PartyAPI.java @@ -50,7 +50,7 @@ public final class PartyAPI { * @return true if the player is in a party, false otherwise */ public static boolean inParty(Player player) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) return false; return UserManager.getPlayer(player).inParty(); @@ -94,14 +94,14 @@ public final class PartyAPI { */ @Deprecated public static void addToParty(Player player, String partyName) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) { + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return; } //Check if player profile is loaded final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer == null) + if (mmoPlayer == null) return; Party party = mcMMO.p.getPartyManager().getParty(partyName); @@ -109,7 +109,7 @@ public final class PartyAPI { if (party == null) { party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName); } else { - if(mcMMO.p.getPartyManager().isPartyFull(player, party)) + if (mcMMO.p.getPartyManager().isPartyFull(player, party)) { NotificationManager.sendPlayerInformation(player, NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull", party.toString()); return; @@ -140,7 +140,7 @@ public final class PartyAPI { */ public static void addToParty(Player player, String partyName, boolean bypassLimit) { //Check if player profile is loaded - if(!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) return; Party party = mcMMO.p.getPartyManager().getParty(partyName); @@ -161,7 +161,7 @@ public final class PartyAPI { */ public static void removeFromParty(Player player) { //Check if player profile is loaded - if(!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) return; mcMMO.p.getPartyManager().removeFromParty(UserManager.getPlayer(player)); @@ -176,7 +176,7 @@ public final class PartyAPI { * @return the leader of the party */ public static @Nullable String getPartyLeader(String partyName) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return null; return mcMMO.p.getPartyManager().getPartyLeaderName(partyName); @@ -192,7 +192,7 @@ public final class PartyAPI { */ @Deprecated public static void setPartyLeader(String partyName, String playerName) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return; mcMMO.p.getPartyManager().setPartyLeader(mcMMO.p.getServer().getOfflinePlayer(playerName).getUniqueId(), mcMMO.p.getPartyManager().getParty(partyName)); @@ -208,7 +208,7 @@ public final class PartyAPI { */ @Deprecated public static List getOnlineAndOfflineMembers(Player player) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) { + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return null; } @@ -230,7 +230,7 @@ public final class PartyAPI { */ @Deprecated public static LinkedHashSet getMembers(Player player) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return null; return (LinkedHashSet) mcMMO.p.getPartyManager().getAllMembers(player).values(); @@ -245,7 +245,7 @@ public final class PartyAPI { * @return all the player names and uuids in the player's party */ public static LinkedHashMap getMembersMap(Player player) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return null; return mcMMO.p.getPartyManager().getAllMembers(player); @@ -260,7 +260,7 @@ public final class PartyAPI { * @return all online players in this party */ public static List getOnlineMembers(String partyName) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return null; return mcMMO.p.getPartyManager().getOnlineMembers(partyName); diff --git a/src/main/java/com/gmail/nossr50/chat/ChatManager.java b/src/main/java/com/gmail/nossr50/chat/ChatManager.java index 658f4dd16..0d7c21c65 100644 --- a/src/main/java/com/gmail/nossr50/chat/ChatManager.java +++ b/src/main/java/com/gmail/nossr50/chat/ChatManager.java @@ -125,7 +125,7 @@ public class ChatManager { * @param targetChatChannel target chat channel */ public void setOrToggleChatChannel(@NotNull McMMOPlayer mmoPlayer, @NotNull ChatChannel targetChatChannel) { - if(targetChatChannel == mmoPlayer.getChatChannel()) { + if (targetChatChannel == mmoPlayer.getChatChannel()) { //Disabled message mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Chat.Channel.Off", StringUtils.getCapitalized(targetChatChannel.toString()))); mmoPlayer.setChatMode(ChatChannel.NONE); @@ -144,7 +144,7 @@ public class ChatManager { StringBuilder stringBuilder = new StringBuilder(); for(int i = 0; i < args.length; i++) { - if(i + 1 >= args.length) { + if (i + 1 >= args.length) { stringBuilder.append(args[i]); } else { stringBuilder.append(args[i]).append(" "); @@ -162,12 +162,12 @@ public class ChatManager { public boolean isMessageAllowed(@NotNull McMMOPlayer mmoPlayer) { switch (mmoPlayer.getChatChannel()) { case ADMIN: - if(mmoPlayer.getPlayer().isOp() || Permissions.adminChat(mmoPlayer.getPlayer())) { + if (mmoPlayer.getPlayer().isOp() || Permissions.adminChat(mmoPlayer.getPlayer())) { return true; } break; case PARTY: - if(mmoPlayer.getParty() != null && Permissions.partyChat(mmoPlayer.getPlayer())) { + if (mmoPlayer.getParty() != null && Permissions.partyChat(mmoPlayer.getPlayer())) { return true; } break; @@ -206,7 +206,7 @@ public class ChatManager { * @return true if the chat channel is enabled */ public boolean isChatChannelEnabled(@NotNull ChatChannel chatChannel) { - if(!isChatEnabled) { + if (!isChatEnabled) { return false; } else { switch(chatChannel) { diff --git a/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java b/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java index 226eab83d..318460222 100644 --- a/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java +++ b/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java @@ -20,12 +20,12 @@ public class SamePartyPredicate implements Predicate @Override public boolean test(T t) { //Include the console in the audience - if(t instanceof ConsoleCommandSender) { + if (t instanceof ConsoleCommandSender) { return false; //Party audiences are special, we exclude console from them to avoid double messaging since we send a more verbose version to consoles } else { - if(t instanceof Player player) { + if (t instanceof Player player) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer != null) { + if (mcMMOPlayer != null) { return mcMMOPlayer.getParty() == party; } } diff --git a/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java b/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java index eb606af6d..2b9344f51 100644 --- a/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java +++ b/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java @@ -48,15 +48,15 @@ public abstract class AbstractPlayerAuthor implements Author { */ protected @NotNull String getSanitizedName(@NotNull ChatChannel chatChannel, boolean useDisplayName) { //Already in cache - if(sanitizedNameCache.containsKey(chatChannel)) { + if (sanitizedNameCache.containsKey(chatChannel)) { //Update cache - if(useDisplayName && hasPlayerDisplayNameChanged()) { + if (useDisplayName && hasPlayerDisplayNameChanged()) { updateLastKnownDisplayName(); updateSanitizedNameCache(chatChannel, true); } } else { //Update last known display name - if(useDisplayName && hasPlayerDisplayNameChanged()) { + if (useDisplayName && hasPlayerDisplayNameChanged()) { updateLastKnownDisplayName(); } @@ -76,7 +76,7 @@ public abstract class AbstractPlayerAuthor implements Author { * @param useDisplayName whether to use this authors display name */ private void updateSanitizedNameCache(@NotNull ChatChannel chatChannel, boolean useDisplayName) { - if(useDisplayName) { + if (useDisplayName) { sanitizedNameCache.put(chatChannel, TextUtils.sanitizeForSerializer(player.getDisplayName())); } else { //No need to sanitize a basic String diff --git a/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java b/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java index 5ec0f5c37..96c7ad1a6 100644 --- a/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java +++ b/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java @@ -57,7 +57,7 @@ public class AdminChatMailer extends AbstractChatMailer { * @return the styled string, based on a locale entry */ public @NotNull TextComponent addStyle(@NotNull Author author, @NotNull String message, boolean canColor) { - if(canColor) { + if (canColor) { return LocaleLoader.getTextComponent("Chat.Style.Admin", author.getAuthoredName(ChatChannel.ADMIN), message); } else { return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Admin", author.getAuthoredName(ChatChannel.ADMIN), message)); @@ -83,7 +83,7 @@ public class AdminChatMailer extends AbstractChatMailer { McMMOChatEvent chatEvent = new McMMOAdminChatEvent(pluginRef, chatMessage, isAsync); Bukkit.getPluginManager().callEvent(chatEvent); - if(!chatEvent.isCancelled()) { + if (!chatEvent.isCancelled()) { sendMail(chatMessage); } } diff --git a/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java b/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java index ad8d8992d..e4edb0320 100644 --- a/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java +++ b/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java @@ -36,7 +36,7 @@ public class PartyChatMailer extends AbstractChatMailer { McMMOChatEvent chatEvent = new McMMOPartyChatEvent(pluginRef, chatMessage, party, isAsync); Bukkit.getPluginManager().callEvent(chatEvent); - if(!chatEvent.isCancelled()) { + if (!chatEvent.isCancelled()) { sendMail(chatMessage); } } @@ -60,14 +60,14 @@ public class PartyChatMailer extends AbstractChatMailer { * @return the styled string, based on a locale entry */ public @NotNull TextComponent addStyle(@NotNull Author author, @NotNull String message, boolean canColor, boolean isLeader) { - if(canColor) { - if(isLeader) { + if (canColor) { + if (isLeader) { return LocaleLoader.getTextComponent("Chat.Style.Party.Leader", author.getAuthoredName(ChatChannel.PARTY), message); } else { return LocaleLoader.getTextComponent("Chat.Style.Party", author.getAuthoredName(ChatChannel.PARTY), message); } } else { - if(isLeader) { + if (isLeader) { return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Party.Leader", author.getAuthoredName(ChatChannel.PARTY), message)); } else { return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Party", author.getAuthoredName(ChatChannel.PARTY), message)); diff --git a/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java b/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java index 756c3d457..02b2499ea 100644 --- a/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java +++ b/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java @@ -52,7 +52,7 @@ public class PartyChatMessage extends AbstractChatMessage { messagePartyChatSpies(spyMessage); //Console message - if(ChatConfig.getInstance().isConsoleIncludedInAudience(ChatChannel.PARTY)) + if (ChatConfig.getInstance().isConsoleIncludedInAudience(ChatChannel.PARTY)) mcMMO.p.getChatManager().sendConsoleMessage(author, spyMessage); } @@ -67,11 +67,11 @@ public class PartyChatMessage extends AbstractChatMessage { Player player = mcMMOPlayer.getPlayer(); //Check for toggled players - if(mcMMOPlayer.isPartyChatSpying()) { + if (mcMMOPlayer.isPartyChatSpying()) { Party adminParty = mcMMOPlayer.getParty(); //Only message admins not part of this party - if(adminParty == null || adminParty != getParty()) { + if (adminParty == null || adminParty != getParty()) { //TODO: Hacky, rewrite later Audience audience = mcMMO.getAudiences().player(player); audience.sendMessage(spyMessage); diff --git a/src/main/java/com/gmail/nossr50/commands/CommandManager.java b/src/main/java/com/gmail/nossr50/commands/CommandManager.java index 3b9d8516e..d870baed0 100644 --- a/src/main/java/com/gmail/nossr50/commands/CommandManager.java +++ b/src/main/java/com/gmail/nossr50/commands/CommandManager.java @@ -47,7 +47,7 @@ public class CommandManager { } private void registerSkillCommands() { - if(mcMMO.p.getGeneralConfig().isMasterySystemEnabled()) { + if (mcMMO.p.getGeneralConfig().isMasterySystemEnabled()) { bukkitCommandManager.registerCommand(new PowerLevelCommand(pluginRef)); } } @@ -56,11 +56,11 @@ public class CommandManager { * Registers chat commands if the chat system is enabled */ private void registerChatCommands() { - if(ChatConfig.getInstance().isChatEnabled()) { - if(ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.ADMIN)) { + if (ChatConfig.getInstance().isChatEnabled()) { + if (ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.ADMIN)) { bukkitCommandManager.registerCommand(new AdminChatCommand(pluginRef)); } - if(pluginRef.getPartyConfig().isPartyEnabled() && ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.PARTY)) { + if (pluginRef.getPartyConfig().isPartyEnabled() && ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.PARTY)) { bukkitCommandManager.registerCommand(new PartyChatCommand(pluginRef)); } } @@ -75,7 +75,7 @@ public class CommandManager { bukkitCommandManager.getCommandConditions().addCondition(POWER_LEVEL_CONDITION, (context) -> { BukkitCommandIssuer issuer = context.getIssuer(); - if(issuer.getIssuer() instanceof Player) { + if (issuer.getIssuer() instanceof Player) { validateLoadedData(issuer.getPlayer()); } else { throw new ConditionFailedException(LocaleLoader.getString("Commands.NoConsole")); @@ -88,7 +88,7 @@ public class CommandManager { bukkitCommandManager.getCommandConditions().addCondition(ADMIN_CONDITION, (context) -> { BukkitCommandIssuer issuer = context.getIssuer(); - if(issuer.getIssuer() instanceof Player) { + if (issuer.getIssuer() instanceof Player) { validateLoadedData(issuer.getPlayer()); validateAdmin(issuer.getPlayer()); } @@ -97,7 +97,7 @@ public class CommandManager { bukkitCommandManager.getCommandConditions().addCondition(MMO_DATA_LOADED, (context) -> { BukkitCommandIssuer bukkitCommandIssuer = context.getIssuer(); - if(bukkitCommandIssuer.getIssuer() instanceof Player) { + if (bukkitCommandIssuer.getIssuer() instanceof Player) { validateLoadedData(bukkitCommandIssuer.getPlayer()); } }); @@ -105,7 +105,7 @@ public class CommandManager { bukkitCommandManager.getCommandConditions().addCondition(PARTY_CONDITION, (context) -> { BukkitCommandIssuer bukkitCommandIssuer = context.getIssuer(); - if(bukkitCommandIssuer.getIssuer() instanceof Player) { + if (bukkitCommandIssuer.getIssuer() instanceof Player) { validateLoadedData(bukkitCommandIssuer.getPlayer()); validatePlayerParty(bukkitCommandIssuer.getPlayer()); //TODO: Is there even a point in validating permission? look into this later @@ -115,20 +115,20 @@ public class CommandManager { } private void validatePermission(@NotNull String permissionNode, @NotNull Permissible permissible) { - if(!permissible.hasPermission(permissionNode)) { + if (!permissible.hasPermission(permissionNode)) { throw new ConditionFailedException(LocaleLoader.getString("mcMMO.NoPermission")); } } public void validateAdmin(@NotNull Player player) { - if(!player.isOp() && !Permissions.adminChat(player)) { + if (!player.isOp() && !Permissions.adminChat(player)) { throw new ConditionFailedException("You are lacking the correct permissions to use this command."); } } public void validateLoadedData(@NotNull Player player) { - if(UserManager.getPlayer(player) == null) { + if (UserManager.getPlayer(player) == null) { throw new ConditionFailedException(LocaleLoader.getString("Profile.PendingLoad")); } } @@ -136,7 +136,7 @@ public class CommandManager { public void validatePlayerParty(@NotNull Player player) { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(!pluginRef.getPartyConfig().isPartyEnabled() || mmoPlayer.getParty() == null) { + if (!pluginRef.getPartyConfig().isPartyEnabled() || mmoPlayer.getParty() == null) { throw new ConditionFailedException(LocaleLoader.getString("Commands.Party.None")); } } diff --git a/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java b/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java index 838722131..3d683b800 100644 --- a/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java @@ -72,7 +72,7 @@ public class McmmoCommand implements CommandExecutor { private void displayOtherCommands(CommandSender sender) { //Don't show them this category if they have none of the permissions - if(!Permissions.skillreset(sender) && !Permissions.mmoedit(sender) && !Permissions.adminChat(sender) && !Permissions.mcgod(sender)) + if (!Permissions.skillreset(sender) && !Permissions.mmoedit(sender) && !Permissions.adminChat(sender) && !Permissions.mcgod(sender)) return; sender.sendMessage(LocaleLoader.getString("Commands.Other")); diff --git a/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java b/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java index ff5b4ab2d..8bcdde1ad 100644 --- a/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java @@ -23,12 +23,12 @@ public class McscoreboardCommand implements TabExecutor { return true; } - if(!mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + if (!mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { sender.sendMessage(LocaleLoader.getString("Scoreboard.Disabled")); return true; } - if(!ScoreboardManager.isPlayerBoardSetup(sender.getName())) { + if (!ScoreboardManager.isPlayerBoardSetup(sender.getName())) { sender.sendMessage(LocaleLoader.getString("Scoreboard.NotSetupYet")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java index f5ad2641c..a32ba1979 100644 --- a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java @@ -37,7 +37,7 @@ public class XprateCommand implements TabExecutor { if (mcMMO.p.isXPEventEnabled()) { - if(mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) + if (mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Stop"), @@ -45,7 +45,7 @@ public class XprateCommand implements TabExecutor { 10, 10*20, 20); } - if(mcMMO.p.getGeneralConfig().broadcastEventMessages()) + if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) { mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop.Subtitle")); @@ -82,7 +82,7 @@ public class XprateCommand implements TabExecutor { int newXpRate = Integer.parseInt(args[0]); - if(newXpRate < 0) + if (newXpRate < 0) { sender.sendMessage(ChatColor.RED+LocaleLoader.getString("Commands.NegativeNumberWarn")); return true; @@ -90,7 +90,7 @@ public class XprateCommand implements TabExecutor { ExperienceConfig.getInstance().setExperienceGainsGlobalMultiplier(newXpRate); - if(mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) + if (mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Start"), @@ -98,7 +98,7 @@ public class XprateCommand implements TabExecutor { 10, 10*20, 20); } - if(mcMMO.p.getGeneralConfig().broadcastEventMessages()) + if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) { mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Start")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.XP", newXpRate)); diff --git a/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java b/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java index 5a60d9bee..e793a60f8 100644 --- a/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java @@ -17,8 +17,8 @@ //public class DropTreasureCommand implements CommandExecutor { // @Override // public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { -// if(sender instanceof Player) { -// if(!sender.isOp()) { +// if (sender instanceof Player) { +// if (!sender.isOp()) { // sender.sendMessage("This command is for Operators only"); // return false; // } @@ -27,13 +27,13 @@ // Location location = player.getLocation(); // McMMOPlayer mmoPlayer = UserManager.getPlayer(player); // -// if(mmoPlayer == null) { +// if (mmoPlayer == null) { // //TODO: Localize // player.sendMessage("Your player data is not loaded yet"); // return false; // } // -// if(args.length == 0) { +// if (args.length == 0) { // mcMMO.p.getLogger().info(player.toString() +" is dropping all mcMMO treasures via admin command at location "+location.toString()); // for(Rarity rarity : FishingTreasureConfig.getInstance().fishingRewards.keySet()) { // for(FishingTreasure fishingTreasure : FishingTreasureConfig.getInstance().fishingRewards.get(rarity)) { diff --git a/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java b/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java index 25a87ceb3..767d544f6 100644 --- a/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java @@ -13,7 +13,7 @@ public class PlayerDebugCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if(sender instanceof Player) { + if (sender instanceof Player) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); mcMMOPlayer.toggleDebugMode(); //Toggle debug mode NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.Mmodebug.Toggle", String.valueOf(mcMMOPlayer.isDebugMode())); diff --git a/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java b/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java index 3c6f93d11..2e71b238d 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java @@ -25,9 +25,9 @@ public class AdminChatCommand extends BaseCommand { @Default @Conditions(CommandManager.ADMIN_CONDITION) public void processCommand(String[] args) { BukkitCommandIssuer bukkitCommandIssuer = (BukkitCommandIssuer) getCurrentCommandIssuer(); - if(args == null || args.length == 0) { + if (args == null || args.length == 0) { //Process with no arguments - if(bukkitCommandIssuer.isPlayer()) { + if (bukkitCommandIssuer.isPlayer()) { McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); pluginRef.getChatManager().setOrToggleChatChannel(mmoPlayer, ChatChannel.ADMIN); } else { @@ -35,10 +35,10 @@ public class AdminChatCommand extends BaseCommand { mcMMO.p.getLogger().info("You cannot switch chat channels as console, please provide full arguments."); } } else { - if(bukkitCommandIssuer.isPlayer()) { + if (bukkitCommandIssuer.isPlayer()) { McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); - if(mmoPlayer == null) + if (mmoPlayer == null) return; //Message contains the original command so it needs to be passed to this method to trim it diff --git a/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java b/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java index cfdbc61d8..369b4a58b 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java @@ -30,9 +30,9 @@ public class PartyChatCommand extends BaseCommand { public void processCommand(String[] args) { BukkitCommandIssuer bukkitCommandIssuer = (BukkitCommandIssuer) getCurrentCommandIssuer(); - if(args == null || args.length == 0) { + if (args == null || args.length == 0) { //Process with no arguments - if(bukkitCommandIssuer.isPlayer()) { + if (bukkitCommandIssuer.isPlayer()) { McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); pluginRef.getChatManager().setOrToggleChatChannel(mmoPlayer, ChatChannel.PARTY); } else { @@ -45,7 +45,7 @@ public class PartyChatCommand extends BaseCommand { /* * Player Logic */ - if(bukkitCommandIssuer.getIssuer() instanceof Player) { + if (bukkitCommandIssuer.getIssuer() instanceof Player) { McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); processCommandArgsPlayer(mmoPlayer, args); /* @@ -72,14 +72,14 @@ public class PartyChatCommand extends BaseCommand { * @param args command arguments */ private void processCommandArgsConsole(@NotNull String[] args) { - if(args.length <= 1) { + if (args.length <= 1) { //Only specific a party and not the message mcMMO.p.getLogger().severe("You need to specify a party name and then write a message afterwards."); } else { //Grab party Party targetParty = mcMMO.p.getPartyManager().getParty(args[0]); - if(targetParty != null) { + if (targetParty != null) { pluginRef.getChatManager().processConsoleMessage(StringUtils.buildStringAfterNthElement(args, 1), targetParty); } else { mcMMO.p.getLogger().severe("A party with that name doesn't exist!"); diff --git a/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java b/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java index 571f1ae35..258242115 100644 --- a/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java @@ -28,7 +28,7 @@ public class ConvertDatabaseCommand implements CommandExecutor { } DatabaseManager oldDatabase = DatabaseManagerFactory.createDatabaseManager(previousType, mcMMO.getUsersFilePath(), mcMMO.p.getLogger(), mcMMO.p.getPurgeTime(), mcMMO.p.getAdvancedConfig().getStartingLevel()); - if(oldDatabase == null) { + if (oldDatabase == null) { sender.sendMessage("Unable to load the old database! Check your log for errors."); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java index ca54d293a..b9fb64d25 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java @@ -35,7 +35,7 @@ public class AddlevelsCommand extends ExperienceCommand { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer == null) { + if (mmoPlayer == null) { EventUtils.tryLevelChangeEvent(player, skill, value, xpRemoved, true, XPGainReason.COMMAND); } else { EventUtils.tryLevelChangeEvent(mmoPlayer, skill, value, xpRemoved, true, XPGainReason.COMMAND); @@ -45,7 +45,7 @@ public class AddlevelsCommand extends ExperienceCommand { @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.1", value)); @@ -53,7 +53,7 @@ public class AddlevelsCommand extends ExperienceCommand { @Override protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", value, mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); diff --git a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java index 25d77e5c0..259b6c7aa 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java @@ -26,7 +26,7 @@ public class AddxpCommand extends ExperienceCommand { protected void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, int value) { if (player != null) { //Check if player profile is loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; UserManager.getPlayer(player).applyXpGain(skill, value, XPGainReason.COMMAND, XPGainSource.COMMAND); @@ -39,7 +39,7 @@ public class AddxpCommand extends ExperienceCommand { @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardAll", value)); @@ -47,7 +47,7 @@ public class AddxpCommand extends ExperienceCommand { @Override protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", value, mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); diff --git a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java index 4bd6b4eeb..6ee6673de 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java @@ -24,16 +24,16 @@ public abstract class ExperienceCommand implements TabExecutor { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { PrimarySkillType skill; - if(args.length < 2) { + if (args.length < 2) { return false; } else { - if(args.length == 2 && !isSilent(args) || args.length == 3 && isSilent(args)) { + if (args.length == 2 && !isSilent(args) || args.length == 3 && isSilent(args)) { if (CommandUtils.noConsoleUsage(sender)) { return true; } if (!permissionsCheckSelf(sender)) { - if(command.getPermissionMessage() != null) + if (command.getPermissionMessage() != null) sender.sendMessage(command.getPermissionMessage()); sender.sendMessage("(mcMMO) No permission!"); return true; @@ -56,7 +56,7 @@ public abstract class ExperienceCommand implements TabExecutor { } //Profile not loaded - if(UserManager.getPlayer(sender.getName()) == null) + if (UserManager.getPlayer(sender.getName()) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; @@ -65,7 +65,7 @@ public abstract class ExperienceCommand implements TabExecutor { editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), skill, Integer.parseInt(args[1]), isSilent(args)); return true; - } else if((args.length == 3 && !isSilent(args)) + } else if ((args.length == 3 && !isSilent(args)) || (args.length == 4 && isSilent(args))) { if (!permissionsCheckOthers(sender)) { sender.sendMessage(command.getPermissionMessage()); @@ -104,7 +104,7 @@ public abstract class ExperienceCommand implements TabExecutor { //Check loading by name profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); - if(CommandUtils.unloadedProfile(sender, profile)) { + if (CommandUtils.unloadedProfile(sender, profile)) { return true; } } @@ -126,7 +126,7 @@ public abstract class ExperienceCommand implements TabExecutor { private boolean isSilent(String[] args) { int length = args.length; - if(length == 0) + if (length == 0) return false; return args[length-1].equalsIgnoreCase("-s"); diff --git a/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java index 93089ac69..737d7f40a 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java @@ -41,7 +41,7 @@ public class MmoeditCommand extends ExperienceCommand { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer != null) { + if (mmoPlayer != null) { EventUtils.tryLevelEditEvent(mmoPlayer, skill, value, xpRemoved, value > skillLevel, XPGainReason.COMMAND, skillLevel); } else { EventUtils.tryLevelEditEvent(player, skill, value, xpRemoved, value > skillLevel, XPGainReason.COMMAND, skillLevel); @@ -51,7 +51,7 @@ public class MmoeditCommand extends ExperienceCommand { @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.mmoedit.AllSkills.1", value)); @@ -59,7 +59,7 @@ public class MmoeditCommand extends ExperienceCommand { @Override protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), value)); diff --git a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java index edc99e2ad..33b2f311f 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java @@ -87,7 +87,7 @@ public class SkillresetCommand implements TabExecutor { profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); //Check if it was present in DB - if(CommandUtils.unloadedProfile(sender, profile)) { + if (CommandUtils.unloadedProfile(sender, profile)) { return true; } } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java index b8d835ef3..4f1743a02 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java @@ -12,7 +12,7 @@ import org.jetbrains.annotations.NotNull; public class PartyChangePasswordCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java index 52e99bd3c..3f59fe184 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java @@ -90,7 +90,7 @@ public class PartyCommand implements TabExecutor { } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; @@ -207,7 +207,7 @@ public class PartyCommand implements TabExecutor { final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Not Loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return ImmutableList.of(); diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java index 75a7c785c..debe0ce45 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java @@ -19,7 +19,7 @@ public class PartyCreateCommand implements CommandExecutor { Player player = (Player) sender; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java index 3e34078e8..74ef9d8ae 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java @@ -23,7 +23,7 @@ public class PartyInfoCommand implements CommandExecutor { switch (args.length) { case 0: case 1: - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java index 44822d82f..f5e58c529 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java @@ -20,7 +20,7 @@ import java.util.Locale; public class PartyItemShareCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java index a5474d355..b88bfa757 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java @@ -34,7 +34,7 @@ public class PartyJoinCommand implements CommandExecutor { Player player = (Player) sender; - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; @@ -62,7 +62,7 @@ public class PartyJoinCommand implements CommandExecutor { return true; } - if(mcMMO.p.getPartyManager().isPartyFull(player, targetParty)) + if (mcMMO.p.getPartyManager().isPartyFull(player, targetParty)) { player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull", targetParty.toString())); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java index eb87e0843..130f43d7e 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java @@ -55,7 +55,7 @@ public class PartyLockCommand implements CommandExecutor { } private void togglePartyLock(CommandSender sender, boolean lock) { - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java index 8322beecf..c96792385 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java @@ -17,7 +17,7 @@ import org.jetbrains.annotations.NotNull; public class PartyXpShareCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java index e39e7c3e2..e839011ea 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java @@ -37,7 +37,7 @@ public class PartyAllianceCommand implements TabExecutor { return true; } - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java index 19c98ad6a..15c6ca281 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java @@ -21,7 +21,7 @@ public class PtpAcceptCommand implements CommandExecutor { return true; } - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java index 10f0f1d98..14c9b57b9 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java @@ -45,21 +45,21 @@ public class PtpCommand implements TabExecutor { Player player = (Player) sender; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return true; } /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(player.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(player.getWorld())) return true; if (!UserManager.hasPlayerDataKey(player)) { return true; } - if(UserManager.getPlayer((Player) sender) == null) + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; @@ -228,13 +228,13 @@ public class PtpCommand implements TabExecutor { } protected static void handleTeleportWarmup(Player teleportingPlayer, Player targetPlayer) { - if(UserManager.getPlayer(targetPlayer) == null) + if (UserManager.getPlayer(targetPlayer) == null) { targetPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } - if(UserManager.getPlayer(teleportingPlayer) == null) + if (UserManager.getPlayer(teleportingPlayer) == null) { teleportingPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; diff --git a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java index dcfcdcdbe..e50dbac27 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java @@ -85,7 +85,7 @@ public class McrankCommand implements TabExecutor { if (sender instanceof Player) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; diff --git a/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java b/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java index e780fa19d..7fa7d04ff 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java @@ -24,22 +24,22 @@ public class XPBarCommand implements TabExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if(sender instanceof Player) { + if (sender instanceof Player) { McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) sender); - if(mmoPlayer == null) { + if (mmoPlayer == null) { NotificationManager.sendPlayerInformationChatOnlyPrefixed(mmoPlayer.getPlayer(), "Profile.PendingLoad"); return false; } - if(args.length == 0) { + if (args.length == 0) { return false; - } else if(args.length < 2) { + } else if (args.length < 2) { String option = args[0]; - if(option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) { + if (option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) { mmoPlayer.getExperienceBarManager().xpBarSettingToggle(ExperienceBarManager.XPBarSettingTarget.RESET, null); return true; - } else if(option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.DISABLE.toString())) { + } else if (option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.DISABLE.toString())) { mmoPlayer.getExperienceBarManager().disableAllBars(); return true; } else { @@ -50,7 +50,7 @@ public class XPBarCommand implements TabExecutor { } else if (args.length == 2) { String skillName = args[1]; - if(SkillUtils.isSkill(skillName)) { + if (SkillUtils.isSkill(skillName)) { PrimarySkillType targetSkill = mcMMO.p.getSkillTools().matchSkill(skillName); @@ -58,7 +58,7 @@ public class XPBarCommand implements TabExecutor { String option = args[0].toLowerCase(); ExperienceBarManager.XPBarSettingTarget settingTarget = getSettingTarget(option); - if(settingTarget != null && settingTarget != ExperienceBarManager.XPBarSettingTarget.RESET) { + if (settingTarget != null && settingTarget != ExperienceBarManager.XPBarSettingTarget.RESET) { //Change setting mmoPlayer.getExperienceBarManager().xpBarSettingToggle(settingTarget, targetSkill); return true; @@ -103,7 +103,7 @@ public class XPBarCommand implements TabExecutor { return StringUtil.copyPartialMatches(args[0], options, new ArrayList<>(ExperienceBarManager.XPBarSettingTarget.values().length)); case 2: - if(!args[0].equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) + if (!args[0].equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) return StringUtil.copyPartialMatches(args[1], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); default: return ImmutableList.of(); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java index d1bb3d864..fc5938f34 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java @@ -54,7 +54,7 @@ public class AcrobaticsCommand extends SkillCommand { AbstractSubSkill abstractSubSkill = InteractionManager.getAbstractByName("Roll"); - if(abstractSubSkill != null) + if (abstractSubSkill != null) { String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_ROLL); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java index 4e2726a79..d916f458a 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java @@ -76,7 +76,7 @@ public class ArcheryCommand extends SkillCommand { messages.add(getStatMessage(SubSkillType.ARCHERY_SKILL_SHOT, skillShotBonus)); } - if(Permissions.canUseSubSkill(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { + if (Permissions.canUseSubSkill(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java index f83063522..ce1907c39 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java @@ -95,7 +95,7 @@ public class AxesCommand extends SkillCommand { + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", skullSplitterLengthEndurance) : "")); } - if(Permissions.canUseSubSkill(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { + if (Permissions.canUseSubSkill(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.AXES_AXES_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.AXES_AXES_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java index 716c1dded..e5f78ac91 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java @@ -54,7 +54,7 @@ public class CrossbowsCommand extends SkillCommand { String.valueOf(mmoPlayer.getCrossbowsManager().getTrickShotMaxBounceCount()))); } - if(Permissions.canUseSubSkill(player, CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { + if (Permissions.canUseSubSkill(player, CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { messages.add(getStatMessage(CROSSBOWS_CROSSBOWS_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, CROSSBOWS_CROSSBOWS_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java index a40c3aba4..829e4644f 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java @@ -53,7 +53,7 @@ public class ExcavationCommand extends SkillCommand { //messages.add(LocaleLoader.getString("Excavation.Effect.Length", gigaDrillBreakerLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", gigaDrillBreakerLengthEndurance) : "")); } - if(Permissions.canUseSubSkill(player, SubSkillType.EXCAVATION_ARCHAEOLOGY)) { + if (Permissions.canUseSubSkill(player, SubSkillType.EXCAVATION_ARCHAEOLOGY)) { messages.add(getStatMessage(false, false, SubSkillType.EXCAVATION_ARCHAEOLOGY, percent.format(excavationManager.getArchaelogyExperienceOrbChance() / 100.0D))); messages.add(getStatMessage(true, false, SubSkillType.EXCAVATION_ARCHAEOLOGY, diff --git a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java index ff01b92ac..c955fdf18 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java @@ -72,7 +72,7 @@ public class FishingCommand extends SkillCommand { } } - if(totalEnchantChance >= 1) + if (totalEnchantChance >= 1) magicChance = percent.format(totalEnchantChance / 100.0); else magicChance = percent.format(0); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java index 9eed83e16..176a9e9a4 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java @@ -31,7 +31,7 @@ // protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { // List messages = new ArrayList<>(); // -// if(SkillUtils.canUseSubskill(player, MACES_MACES_LIMIT_BREAK)) { +// if (SkillUtils.canUseSubskill(player, MACES_MACES_LIMIT_BREAK)) { // messages.add(getStatMessage(MACES_MACES_LIMIT_BREAK, // String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, MACES_MACES_LIMIT_BREAK, 1000)))); // } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java index b96d43c23..9247cee3c 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java @@ -111,7 +111,7 @@ public class MiningCommand extends SkillCommand { //messages.add(LocaleLoader.getString("Mining.Effect.DropChance", doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); } - if(canTripleDrop) { + if (canTripleDrop) { messages.add(getStatMessage(SubSkillType.MINING_MOTHER_LODE, tripleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) : "")); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java index 3a085a5cf..64152af8a 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java @@ -26,14 +26,14 @@ public class MmoInfoCommand implements TabExecutor { /* * Only allow players to use this command */ - if(commandSender instanceof Player player) + if (commandSender instanceof Player player) { - if(args == null || args.length < 1 || args[0] == null || args[0].isEmpty()) + if (args == null || args.length < 1 || args[0] == null || args[0].isEmpty()) return false; - if(Permissions.mmoinfo(player)) + if (Permissions.mmoinfo(player)) { - if(args[0].equalsIgnoreCase( "???")) + if (args[0].equalsIgnoreCase( "???")) { player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", "???")); @@ -59,7 +59,7 @@ public class MmoInfoCommand implements TabExecutor { public SubSkillType matchSubSkill(String name) { for(SubSkillType subSkillType : SubSkillType.values()) { - if(subSkillType.getNiceNameNoSpaces(subSkillType).equalsIgnoreCase(name) + if (subSkillType.getNiceNameNoSpaces(subSkillType).equalsIgnoreCase(name) || subSkillType.name().equalsIgnoreCase(name)) return subSkillType; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java index 9ff449f8f..f49542304 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java @@ -149,7 +149,7 @@ public abstract class SkillCommand implements TabExecutor { // send header player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", skillName)); - if(!SkillTools.isChildSkill(skill)) + if (!SkillTools.isChildSkill(skill)) { /* * NON-CHILD SKILLS @@ -177,7 +177,7 @@ public abstract class SkillCommand implements TabExecutor { for(int i = 0; i < parentList.size(); i++) { - if(i+1 < parentList.size()) + if (i+1 < parentList.size()) { parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), mcMMOPlayer.getSkillLevel(parentList.get(i)))); parentMessage.append(ChatColor.GRAY).append(", "); @@ -237,7 +237,7 @@ public abstract class SkillCommand implements TabExecutor { int length; - if(abilityLengthCap <= 0) + if (abilityLengthCap <= 0) { length = 2 + (int) (skillValue / abilityLengthVar); } @@ -264,7 +264,7 @@ public abstract class SkillCommand implements TabExecutor { String templateKey = isCustom ? "Ability.Generic.Template.Custom" : "Ability.Generic.Template"; String statDescriptionKey = !isExtra ? subSkillType.getLocaleKeyStatDescription() : subSkillType.getLocaleKeyStatExtraDescription(); - if(isCustom) + if (isCustom) return LocaleLoader.getString(templateKey, LocaleLoader.getString(statDescriptionKey, vars)); else { @@ -274,7 +274,7 @@ public abstract class SkillCommand implements TabExecutor { } protected String getLimitBreakDescriptionParameter() { - if(mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { + if (mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { return "(PVP/PVE)"; } else { return "(PVP)"; diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java index 6c5518270..1de2a9c38 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java @@ -101,13 +101,13 @@ public class SwordsCommand extends SkillCommand { + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", serratedStrikesLengthEndurance) : "")); } - if(SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_STAB)) + if (SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_STAB)) { messages.add(getStatMessage(SubSkillType.SWORDS_STAB, String.valueOf(mmoPlayer.getSwordsManager().getStabDamage()))); } - if(SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { + if (SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java index 706adf80a..21d37eb7e 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java @@ -31,12 +31,12 @@ public class TridentsCommand extends SkillCommand { protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - if(SkillUtils.canUseSubskill(player, TRIDENTS_TRIDENTS_LIMIT_BREAK)) { + if (SkillUtils.canUseSubskill(player, TRIDENTS_TRIDENTS_LIMIT_BREAK)) { messages.add(getStatMessage(TRIDENTS_TRIDENTS_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, TRIDENTS_TRIDENTS_LIMIT_BREAK, 1000)))); } - if(SkillUtils.canUseSubskill(player, TRIDENTS_IMPALE)) { + if (SkillUtils.canUseSubskill(player, TRIDENTS_IMPALE)) { messages.add(getStatMessage(TRIDENTS_IMPALE, String.valueOf(mmoPlayer.getTridentsManager().impaleDamageBonus()))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java index deb536b10..6a85468c8 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java @@ -113,7 +113,7 @@ public class UnarmedCommand extends SkillCommand { //messages.add(LocaleLoader.getString("Unarmed.Ability.Chance.IronGrip", ironGripChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", ironGripChanceLucky) : "")); } - if(Permissions.canUseSubSkill(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { + if (Permissions.canUseSubSkill(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java index 8efacee64..33dd0f071 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java @@ -40,7 +40,7 @@ public class WoodcuttingCommand extends SkillCommand { } //Clean Cuts - if(canTripleDrop) { + if (canTripleDrop) { String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.WOODCUTTING_CLEAN_CUTS); tripleDropChance = tripleDropStrings[0]; tripleDropChanceLucky = tripleDropStrings[1]; @@ -80,7 +80,7 @@ public class WoodcuttingCommand extends SkillCommand { + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); } - if(canTripleDrop) { + if (canTripleDrop) { messages.add(getStatMessage(SubSkillType.WOODCUTTING_CLEAN_CUTS, tripleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) : "")); } @@ -89,7 +89,7 @@ public class WoodcuttingCommand extends SkillCommand { if (canKnockOnWood) { String lootNote; - if(RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { + if (RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { lootNote = LocaleLoader.getString("Woodcutting.SubSkill.KnockOnWood.Loot.Rank2"); } else { lootNote = LocaleLoader.getString("Woodcutting.SubSkill.KnockOnWood.Loot.Normal"); diff --git a/src/main/java/com/gmail/nossr50/config/BukkitConfig.java b/src/main/java/com/gmail/nossr50/config/BukkitConfig.java index 23d50b6b2..028a3e3bc 100644 --- a/src/main/java/com/gmail/nossr50/config/BukkitConfig.java +++ b/src/main/java/com/gmail/nossr50/config/BukkitConfig.java @@ -52,7 +52,7 @@ public abstract class BukkitConfig { try { config.save(configFile); - if(copyDefaults && !savedDefaults) { + if (copyDefaults && !savedDefaults) { copyMissingDefaultsFromResource(); savedDefaults = true; } @@ -84,7 +84,7 @@ public abstract class BukkitConfig { YamlConfiguration saveDefaultConfigToDisk() { LogUtils.debug(mcMMO.p.getLogger(), "Copying default config to disk: " + fileName + " to defaults/" + fileName); try(InputStream inputStream = mcMMO.p.getResource(fileName)) { - if(inputStream == null) { + if (inputStream == null) { mcMMO.p.getLogger().severe("Unable to copy default config: " + fileName); return null; } diff --git a/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java b/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java index 7b93ebd89..d92d2778f 100644 --- a/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java +++ b/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java @@ -73,7 +73,7 @@ public class WorldBlacklist { closeRead(fileReader); } - if(blacklist.size() > 0) + if (blacklist.size() > 0) plugin.getLogger().info(blacklist.size() + " entries in mcMMO World Blacklist"); } diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 774ff511c..9aadac89f 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -195,10 +195,10 @@ public class PotionConfig extends LegacyConfigLoader { PotionUtil.setBasePotionType(potionMeta, potionType, extended, upgraded); // // Use the name of the potion to indicate upgrade status if not set in PotionData -// if(convertPotionConfigName(key).toUpperCase().contains("STRONG")) +// if (convertPotionConfigName(key).toUpperCase().contains("STRONG")) // upgraded = true; // -// if(convertPotionConfigName(key).toUpperCase().contains("LONG")) +// if (convertPotionConfigName(key).toUpperCase().contains("LONG")) // extended = true; List lore = new ArrayList<>(); diff --git a/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java b/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java index 1a54906a7..491a511ed 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java +++ b/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java @@ -20,7 +20,7 @@ public class RepairConfigManager { repairables.addAll(mainRepairConfig.getLoadedRepairables()); for (String fileName : dataFolder.list()) { - if(fileName.equals(REPAIR_VANILLA_YML)) + if (fileName.equals(REPAIR_VANILLA_YML)) continue; if (!pattern.matcher(fileName).matches()) { diff --git a/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java b/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java index 77348e8d3..1832da789 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java +++ b/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java @@ -21,7 +21,7 @@ public class SalvageConfigManager { salvageables.addAll(mainSalvageConfig.getLoadedSalvageables()); for (String fileName : dataFolder.list()) { - if(fileName.equals(SALVAGE_VANILLA_YML)) + if (fileName.equals(SALVAGE_VANILLA_YML)) continue; if (!pattern.matcher(fileName).matches()) { diff --git a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java index 5ffbb74da..95788896c 100755 --- a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java @@ -50,7 +50,7 @@ public class FishingTreasureConfig extends BukkitConfig { List reason = new ArrayList<>(); ConfigurationSection enchantment_drop_rates = config.getConfigurationSection("Enchantment_Drop_Rates"); - if(enchantment_drop_rates != null) { + if (enchantment_drop_rates != null) { for (String tier : enchantment_drop_rates.getKeys(false)) { double totalEnchantDropRate = 0; double totalItemDropRate = 0; diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java index 36e6c784c..e64deaae7 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java @@ -33,7 +33,7 @@ public class FlatFileDataProcessor { assert !lineData.isEmpty(); //Make sure the data line is "correct" - if(lineData.charAt(lineData.length() - 1) != ':') { + if (lineData.charAt(lineData.length() - 1) != ':') { // Length checks depend on last rawSplitData being ':' // We add it here if it is missing lineData = lineData.concat(":"); @@ -48,9 +48,9 @@ public class FlatFileDataProcessor { boolean anyBadData = false; //This is the minimum size of the split array needed to be considered proper data - if(splitDataLine.length < getMinimumSplitDataLength()) { + if (splitDataLine.length < getMinimumSplitDataLength()) { //Data is considered junk - if(!corruptDataFound) { + if (!corruptDataFound) { logger.severe("Some corrupt data was found in mcmmo.users and has been repaired, it is possible that some player data has been lost in this process."); corruptDataFound = true; } @@ -59,9 +59,9 @@ public class FlatFileDataProcessor { builder.appendFlag(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); //TODO: This block here is probably pointless - if(splitDataLine.length >= 10 //The value here is kind of arbitrary, it shouldn't be too low to avoid false positives, but also we aren't really going to correctly identify when player data has been corrupted or not with 100% accuracy ever + if (splitDataLine.length >= 10 //The value here is kind of arbitrary, it shouldn't be too low to avoid false positives, but also we aren't really going to correctly identify when player data has been corrupted or not with 100% accuracy ever && splitDataLine[0] != null && !splitDataLine[0].isEmpty()) { - if(splitDataLine[0].length() <= 16 && splitDataLine[0].length() >= 3) { + if (splitDataLine[0].length() <= 16 && splitDataLine[0].length() >= 3) { logger.severe("Not enough data found to recover corrupted player data for user: "+splitDataLine[0]); registerData(builder.appendFlag(FlatFileDataFlag.TOO_INCOMPLETE)); return; @@ -81,14 +81,14 @@ public class FlatFileDataProcessor { String name = splitDataLine[USERNAME_INDEX]; String strOfUUID = splitDataLine[UUID_INDEX]; - if(name.isEmpty()) { + if (name.isEmpty()) { reportBadDataLine("No name found for data", "[MISSING NAME]", lineData); builder.appendFlag(FlatFileDataFlag.MISSING_NAME); anyBadData = true; badDataValues[USERNAME_INDEX] = true; } - if(strOfUUID.isEmpty() || strOfUUID.equalsIgnoreCase("NULL")) { + if (strOfUUID.isEmpty() || strOfUUID.equalsIgnoreCase("NULL")) { invalidUUID = true; badDataValues[UUID_INDEX] = true; reportBadDataLine("Empty/null UUID for user", "Empty/null", lineData); @@ -110,20 +110,20 @@ public class FlatFileDataProcessor { } //Duplicate UUID is no good, reject them - if(!invalidUUID && uuid != null && uuids.contains(uuid)) { + if (!invalidUUID && uuid != null && uuids.contains(uuid)) { registerData(builder.appendFlag(FlatFileDataFlag.DUPLICATE_UUID)); return; } uuids.add(uuid); - if(names.contains(name)) { + if (names.contains(name)) { builder.appendFlag(FlatFileDataFlag.DUPLICATE_NAME); anyBadData = true; badDataValues[USERNAME_INDEX] = true; } - if(!name.isEmpty()) + if (!name.isEmpty()) names.add(name); //Make sure the data is up to date schema wise, if it isn't we adjust it to the correct size and flag it for repair @@ -136,9 +136,9 @@ public class FlatFileDataProcessor { //Check each data for bad values for(int i = 0; i < DATA_ENTRY_COUNT; i++) { - if(shouldNotBeEmpty(splitDataLine[i], i)) { + if (shouldNotBeEmpty(splitDataLine[i], i)) { - if(i == OVERHAUL_LAST_LOGIN) { + if (i == OVERHAUL_LAST_LOGIN) { builder.appendFlag(FlatFileDataFlag.LAST_LOGIN_SCHEMA_UPGRADE); } @@ -149,13 +149,13 @@ public class FlatFileDataProcessor { boolean isCorrectType = isOfExpectedType(splitDataLine[i], getExpectedValueType(i)); - if(!isCorrectType) { + if (!isCorrectType) { anyBadData = true; badDataValues[i] = true; } } - if(anyBadData) { + if (anyBadData) { builder.appendFlag(FlatFileDataFlag.BAD_VALUES); builder.appendBadDataValues(badDataValues); } @@ -166,7 +166,7 @@ public class FlatFileDataProcessor { public @NotNull String[] isDataSchemaUpToDate(@NotNull String[] splitDataLine, @NotNull FlatFileDataBuilder builder, boolean[] badDataValues) { assert splitDataLine.length <= DATA_ENTRY_COUNT; //should NEVER be higher - if(splitDataLine.length < DATA_ENTRY_COUNT) { + if (splitDataLine.length < DATA_ENTRY_COUNT) { int oldLength = splitDataLine.length; splitDataLine = Arrays.copyOf(splitDataLine, DATA_ENTRY_COUNT); int newLength = splitDataLine.length; @@ -184,7 +184,7 @@ public class FlatFileDataProcessor { public boolean shouldNotBeEmpty(@Nullable String data, int index) { - if(getExpectedValueType(index) == ExpectedType.IGNORED) { + if (getExpectedValueType(index) == ExpectedType.IGNORED) { return false; } else { return data == null || data.isEmpty(); @@ -248,7 +248,7 @@ public class FlatFileDataProcessor { FlatFileDataContainer flatFileDataContainer = builder.build(); flatFileDataContainers.add(flatFileDataContainer); - if(flatFileDataContainer.getDataFlags() != null) + if (flatFileDataContainer.getDataFlags() != null) flatFileDataFlags.addAll(flatFileDataContainer.getDataFlags()); } @@ -295,7 +295,7 @@ public class FlatFileDataProcessor { for(FlatFileDataContainer dataContainer : flatFileDataContainers) { String[] splitData = FlatFileDataUtil.getPreparedSaveDataLine(dataContainer); - if(splitData == null) + if (splitData == null) continue; //We add a trailing : as it is needed for some reason (is it?) diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java index cd11065da..10dca3354 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java @@ -101,15 +101,15 @@ public final class FlatFileDatabaseManager implements DatabaseManager { this.startingLevel = startingLevel; this.testing = testing; - if(!usersFile.exists()) { + if (!usersFile.exists()) { initEmptyDB(); } - if(!testing) { + if (!testing) { List flatFileDataFlags = checkFileHealthAndStructure(); - if(flatFileDataFlags != null) { - if(!flatFileDataFlags.isEmpty()) { + if (flatFileDataFlags != null) { + if (!flatFileDataFlags.isEmpty()) { logger.info("Detected "+flatFileDataFlags.size() + " data entries which need correction."); } } @@ -222,7 +222,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (lastPlayed == -1) { OfflinePlayer player = mcMMO.p.getServer().getOfflinePlayer(uuid); - if(player.getLastPlayed() != 0) { + if (player.getLastPlayed() != 0) { lastPlayed = player.getLastPlayed(); rewrite = true; } @@ -246,7 +246,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); out.write(writer.toString()); - if(testing) { + if (testing) { System.out.println(writer); } } @@ -354,15 +354,15 @@ public final class FlatFileDatabaseManager implements DatabaseManager { boolean wroteUser = false; // While not at the end of the file while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { writer.append(line).append("\r\n"); continue; } //Check for incomplete or corrupted data - if(!line.contains(":")) { + if (!line.contains(":")) { - if(!corruptDataFound) { + if (!corruptDataFound) { logger.severe("mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); corruptDataFound = true; } @@ -373,9 +373,9 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String[] splitData = line.split(":"); //This would be rare, but check the splitData for having enough entries to contain a UUID - if(splitData.length < UUID_INDEX) { //UUID have been in mcMMO DB for a very long time so any user without + if (splitData.length < UUID_INDEX) { //UUID have been in mcMMO DB for a very long time so any user without - if(!corruptDataFound) { + if (!corruptDataFound) { logger.severe("mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); corruptDataFound = true; } @@ -397,7 +397,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { /* * If we couldn't find the user in the DB we need to add him */ - if(!wroteUser) { + if (!wroteUser) { writeUserToLine(profile, writer); } @@ -498,7 +498,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { public @NotNull List readLeaderboard(@Nullable PrimarySkillType primarySkillType, int pageNumber, int statsPerPage) throws InvalidSkillException { //Fix for a plugin that people are using that is throwing SQL errors - if(primarySkillType != null && SkillTools.isChildSkill(primarySkillType)) { + if (primarySkillType != null && SkillTools.isChildSkill(primarySkillType)) { logger.severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); } @@ -572,11 +572,11 @@ public final class FlatFileDatabaseManager implements DatabaseManager { private @NotNull UserQuery getUserQuery(@Nullable UUID uuid, @Nullable String playerName) throws NullPointerException { boolean hasName = playerName != null && !playerName.equalsIgnoreCase("null"); - if(hasName && uuid != null) { + if (hasName && uuid != null) { return new UserQueryFull(playerName, uuid); } else if (uuid != null) { return new UserQueryUUIDImpl(uuid); - } else if(hasName) { + } else if (hasName) { return new UserQueryNameImpl(playerName); } else { throw new NullPointerException("Both name and UUID cannot be null, at least one must be non-null!"); @@ -610,7 +610,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { continue; } @@ -620,12 +620,12 @@ public final class FlatFileDatabaseManager implements DatabaseManager { /* Don't read corrupt data */ - if(rawSplitData.length < (USERNAME_INDEX + 1)) { + if (rawSplitData.length < (USERNAME_INDEX + 1)) { continue; } // we found the player - if(playerName.equalsIgnoreCase(rawSplitData[USERNAME_INDEX])) { + if (playerName.equalsIgnoreCase(rawSplitData[USERNAME_INDEX])) { return loadFromLine(rawSplitData); } } @@ -660,24 +660,24 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String line; while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { continue; } // Find if the line contains the player we want. String[] rawSplitData = line.split(":"); /* Don't read corrupt data */ - if(rawSplitData.length < (UUID_INDEX + 1)) { + if (rawSplitData.length < (UUID_INDEX + 1)) { continue; } try { UUID fromDataUUID = UUID.fromString(rawSplitData[UUID_INDEX]); - if(fromDataUUID.equals(uuid)) { + if (fromDataUUID.equals(uuid)) { return loadFromLine(rawSplitData); } } catch (Exception e) { - if(testing) { + if (testing) { e.printStackTrace(); } } @@ -716,20 +716,20 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String line; while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { continue; } // Find if the line contains the player we want. String[] rawSplitData = line.split(":"); /* Don't read corrupt data */ - if(rawSplitData.length < (UUID_INDEX + 1)) { + if (rawSplitData.length < (UUID_INDEX + 1)) { continue; } try { UUID fromDataUUID = UUID.fromString(rawSplitData[UUID_INDEX]); - if(fromDataUUID.equals(uuid)) { + if (fromDataUUID.equals(uuid)) { //Matched UUID, now check if name matches String dbPlayerName = rawSplitData[USERNAME_INDEX]; @@ -746,7 +746,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { return loadFromLine(rawSplitData); } } catch (Exception e) { - if(testing) { + if (testing) { e.printStackTrace(); } } @@ -774,7 +774,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } private @NotNull PlayerProfile grabUnloadedProfile(@NotNull UUID uuid, @Nullable String playerName) { - if(playerName == null) { + if (playerName == null) { playerName = ""; //No name for you boy! } @@ -793,7 +793,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String line; while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { continue; } @@ -1014,7 +1014,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { while ((line = in.readLine()) != null) { - if(line.startsWith("#")) + if (line.startsWith("#")) continue; String[] data = line.split(":"); @@ -1145,12 +1145,12 @@ public final class FlatFileDatabaseManager implements DatabaseManager { //Analyze the data while ((currentLine = bufferedReader.readLine()) != null) { //Commented lines - if(currentLine.startsWith("#") && dbCommentDate == null) { //The first commented line in the file is likely to be our note about when the file was created + if (currentLine.startsWith("#") && dbCommentDate == null) { //The first commented line in the file is likely to be our note about when the file was created dbCommentDate = currentLine; continue; } - if(currentLine.isEmpty()) + if (currentLine.isEmpty()) continue; //TODO: We are never passing empty lines, should we remove the flag for them? @@ -1158,12 +1158,12 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } //Only update the file if needed - if(!dataProcessor.getFlatFileDataFlags().isEmpty()) { + if (!dataProcessor.getFlatFileDataFlags().isEmpty()) { flagsFound = new ArrayList<>(dataProcessor.getFlatFileDataFlags()); logger.info("Updating FlatFile Database..."); fileWriter = new FileWriter(usersFilePath); //Write data to file - if(dbCommentDate != null) + if (dbCommentDate != null) fileWriter.write(dbCommentDate + "\r\n"); fileWriter.write(dataProcessor.processDataForSave().toString()); @@ -1176,7 +1176,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } } - if(flagsFound == null || flagsFound.isEmpty()) { + if (flagsFound == null || flagsFound.isEmpty()) { return null; } else { return flagsFound; @@ -1184,7 +1184,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } private void closeResources(BufferedReader bufferedReader, FileWriter fileWriter) { - if(bufferedReader != null) { + if (bufferedReader != null) { try { bufferedReader.close(); } diff --git a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java index a21f2fced..aef90e48c 100644 --- a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java @@ -59,7 +59,7 @@ public final class SQLDatabaseManager implements DatabaseManager { this.h2 = h2; String connectionString = getConnectionString(h2); - if(!h2 && mcMMO.p.getGeneralConfig().getMySQLPublicKeyRetrieval()) { + if (!h2 && mcMMO.p.getGeneralConfig().getMySQLPublicKeyRetrieval()) { connectionString+= "&allowPublicKeyRetrieval=true"; } @@ -140,7 +140,7 @@ public final class SQLDatabaseManager implements DatabaseManager { String connectionString = "jdbc:mysql://" + mcMMO.p.getGeneralConfig().getMySQLServerName() + ":" + mcMMO.p.getGeneralConfig().getMySQLServerPort() + "/" + mcMMO.p.getGeneralConfig().getMySQLDatabaseName(); - if(!mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 17, 0) //Temporary hack for SQL and 1.17 support + if (!mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 17, 0) //Temporary hack for SQL and 1.17 support && mcMMO.p.getGeneralConfig().getMySQLSSL()) connectionString += "?verifyServerCertificate=false"+ @@ -247,7 +247,7 @@ public final class SQLDatabaseManager implements DatabaseManager { } if (success) { - if(uuid != null) + if (uuid != null) cleanupUser(uuid); Misc.profileCleanup(playerName); @@ -400,7 +400,7 @@ public final class SQLDatabaseManager implements DatabaseManager { List stats = new ArrayList<>(); //Fix for a plugin that people are using that is throwing SQL errors - if(skill != null && SkillTools.isChildSkill(skill)) { + if (skill != null && SkillTools.isChildSkill(skill)) { logger.severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); } @@ -631,7 +631,7 @@ public final class SQLDatabaseManager implements DatabaseManager { } private PlayerProfile loadPlayerFromDB(@Nullable UUID uuid, @Nullable String playerName) throws RuntimeException { - if(uuid == null && playerName == null) { + if (uuid == null && playerName == null) { throw new RuntimeException("Error looking up player, both UUID and playerName are null and one must not be."); } diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java index ed048d5e1..eb6e3dd2a 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java @@ -28,7 +28,7 @@ public class FlatFileDataBuilder { } public @NotNull FlatFileDataContainer build() { - if(dataFlags.contains(FlatFileDataFlag.BAD_VALUES)) { + if (dataFlags.contains(FlatFileDataFlag.BAD_VALUES)) { return new BadCategorizedFlatFileData(uniqueProcessingId, dataFlags, splitStringData, badDataValues); } diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java index bc1c19cb6..a3c78685f 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java @@ -10,14 +10,14 @@ import static com.gmail.nossr50.database.FlatFileDatabaseManager.*; public class FlatFileDataUtil { public static @Nullable String[] getPreparedSaveDataLine(@NotNull FlatFileDataContainer dataContainer) { - if(dataContainer.getDataFlags() == null) { + if (dataContainer.getDataFlags() == null) { return dataContainer.getSplitData(); } //Data of this type is not salvageable //TODO: Test that we ignore the things we are supposed to ignore //TODO: Should we even keep track of the bad data or just not even build data containers for it? Making containers for it is only really useful for debugging.. well I suppose operations are typically async so it shouldn't matter - if(dataContainer.getDataFlags().contains(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE) + if (dataContainer.getDataFlags().contains(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE) || dataContainer.getDataFlags().contains(FlatFileDataFlag.DUPLICATE_UUID) //For now we will not try to fix any issues with UUIDs || dataContainer.getDataFlags().contains(FlatFileDataFlag.BAD_UUID_DATA) //For now we will not try to fix any issues with UUIDs || dataContainer.getDataFlags().contains(FlatFileDataFlag.TOO_INCOMPLETE)) { @@ -29,7 +29,7 @@ public class FlatFileDataUtil { /* * First fix the bad data values if they exist */ - if(dataContainer instanceof BadCategorizedFlatFileData badData) { + if (dataContainer instanceof BadCategorizedFlatFileData badData) { splitData = repairBadData(dataContainer.getSplitData(), badData.getBadDataIndexes()); } else { splitData = dataContainer.getSplitData(); @@ -42,7 +42,7 @@ public class FlatFileDataUtil { public static @NotNull String[] repairBadData(@NotNull String[] splitData, boolean[] badDataValues) { for(int i = 0; i < FlatFileDatabaseManager.DATA_ENTRY_COUNT; i++) { - if(badDataValues[i]) { + if (badDataValues[i]) { //This data value was marked as bad so we zero initialize it splitData[i] = getZeroInitialisedData(i, 0); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java b/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java index f19ec041e..32109deac 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java +++ b/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java @@ -25,56 +25,56 @@ public class LevelUpBroadcastPredicate implements Predi Player broadcastingPlayer = (Player) broadcaster; //Always a player no need to check cast //Broadcaster should be online - if(!broadcastingPlayer.isOnline()) { + if (!broadcastingPlayer.isOnline()) { return false; } McMMOPlayer mmoBroadcastingPlayer = UserManager.getPlayer(broadcastingPlayer); - if(mmoBroadcastingPlayer == null) { + if (mmoBroadcastingPlayer == null) { //This should never be null, but just in case... mcMMO.p.getLogger().severe("McMMOPlayer was null for broadcaster in LevelUpBroadcastPredicate when it should never be null!"); return false; } - if(t instanceof Player listeningPlayer) { + if (t instanceof Player listeningPlayer) { //Party Member Check - if(mcMMO.p.getGeneralConfig().isLevelUpBroadcastsPartyMembersOnly()) { + if (mcMMO.p.getGeneralConfig().isLevelUpBroadcastsPartyMembersOnly()) { McMMOPlayer mmoListeningPlayer = UserManager.getPlayer(listeningPlayer); - if(mmoListeningPlayer == null) { + if (mmoListeningPlayer == null) { return false; //No profile so therefor no party } Party playerWhoLeveledParty = mmoBroadcastingPlayer.getParty(); Party broadcastRecipientParty = mmoListeningPlayer.getParty(); - if(playerWhoLeveledParty == null || broadcastRecipientParty == null) { + if (playerWhoLeveledParty == null || broadcastRecipientParty == null) { return false; //No party on either player when being in the same party is required } - if(!playerWhoLeveledParty.equals(broadcastRecipientParty)) { + if (!playerWhoLeveledParty.equals(broadcastRecipientParty)) { return false; //Not in the same party when it is required } } //Same world check - if(isLevelUpBroadcastsSameWorldOnly()) { - if(!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { + if (isLevelUpBroadcastsSameWorldOnly()) { + if (!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { return false; //Not in the same world when its required } //Distance checks - if(mcMMO.p.getGeneralConfig().shouldLevelUpBroadcastsRestrictDistance()) { - if(!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getLevelUpBroadcastRadius())) { + if (mcMMO.p.getGeneralConfig().shouldLevelUpBroadcastsRestrictDistance()) { + if (!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getLevelUpBroadcastRadius())) { return false; } } } //Visibility checks - if(!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { + if (!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { return false; //Player who leveled should be invisible to this player so don't send the message } diff --git a/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java b/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java index 05e7a3a1a..1e6b278a8 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java +++ b/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java @@ -25,56 +25,56 @@ public class PowerLevelUpBroadcastPredicate implements Player broadcastingPlayer = (Player) broadcaster; //Always a player no need to check cast //Broadcaster should be online - if(!broadcastingPlayer.isOnline()) { + if (!broadcastingPlayer.isOnline()) { return false; } McMMOPlayer mmoBroadcastingPlayer = UserManager.getPlayer(broadcastingPlayer); - if(mmoBroadcastingPlayer == null) { + if (mmoBroadcastingPlayer == null) { //This should never be null, but just in case... mcMMO.p.getLogger().severe("McMMOPlayer was null for broadcaster in LevelUpBroadcastPredicate when it should never be null!"); return false; } - if(t instanceof Player listeningPlayer) { + if (t instanceof Player listeningPlayer) { //Party Member Check - if(mcMMO.p.getGeneralConfig().isPowerLevelUpBroadcastsPartyMembersOnly()) { + if (mcMMO.p.getGeneralConfig().isPowerLevelUpBroadcastsPartyMembersOnly()) { McMMOPlayer mmoListeningPlayer = UserManager.getPlayer(listeningPlayer); - if(mmoListeningPlayer == null) { + if (mmoListeningPlayer == null) { return false; //No profile so therefor no party } Party playerWhoLeveledParty = mmoBroadcastingPlayer.getParty(); Party broadcastRecipientParty = mmoListeningPlayer.getParty(); - if(playerWhoLeveledParty == null || broadcastRecipientParty == null) { + if (playerWhoLeveledParty == null || broadcastRecipientParty == null) { return false; //No party on either player when being in the same party is required } - if(!playerWhoLeveledParty.equals(broadcastRecipientParty)) { + if (!playerWhoLeveledParty.equals(broadcastRecipientParty)) { return false; //Not in the same party when it is required } } //Same world check - if(isPowerLevelUpBroadcastsSameWorldOnly()) { - if(!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { + if (isPowerLevelUpBroadcastsSameWorldOnly()) { + if (!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { return false; //Not in the same world when its required } //Distance checks - if(mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcastsRestrictDistance()) { - if(!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastRadius())) { + if (mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcastsRestrictDistance()) { + if (!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastRadius())) { return false; } } } //Visibility checks - if(!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { + if (!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { return false; //Player who leveled should be invisible to this player so don't send the message } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java index 78ffb9966..ddec901d8 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java @@ -91,7 +91,7 @@ public class Party { for(Player p : onlineMembers) { - if(player.canSee(p)) + if (player.canSee(p)) visibleMembers.add(p); } @@ -347,7 +347,7 @@ public class Party { for(UUID playerUUID : members.keySet()) { OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playerUUID); - if(offlinePlayer.isOnline() && player.canSee((Player) offlinePlayer)) { + if (offlinePlayer.isOnline() && player.canSee((Player) offlinePlayer)) { ChatColor onlineColor = leader.getUniqueId().equals(playerUUID) ? ChatColor.GOLD : ChatColor.GREEN; coloredNames.add(onlineColor + offlinePlayer.getName()); } else { @@ -361,7 +361,7 @@ public class Party { private void buildChatMessage(@NotNull StringBuilder stringBuilder, String @NotNull [] names) { for(int i = 0; i < names.length; i++) { - if(i + 1 >= names.length) { + if (i + 1 >= names.length) { stringBuilder .append(names[i]); } else { diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java index d8b6199c4..c465e55dc 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java @@ -157,7 +157,7 @@ public class McMMOPlayer implements Identified { this.chatChannel = ChatChannel.NONE; - if(ChatConfig.getInstance().isSpyingAutomatic() && Permissions.adminChatSpy(getPlayer())) { + if (ChatConfig.getInstance().isSpyingAutomatic() && Permissions.adminChatSpy(getPlayer())) { chatSpy = true; } } @@ -253,20 +253,20 @@ public class McMMOPlayer implements Identified { public void processPostXpEvent(PrimarySkillType primarySkillType, Plugin plugin, XPGainSource xpGainSource) { //Check if they've reached the power level cap just now - if(hasReachedPowerLevelCap()) { + if (hasReachedPowerLevelCap()) { NotificationManager.sendPlayerInformationChatOnly(player, "LevelCap.PowerLevel", String.valueOf(mcMMO.p.getGeneralConfig().getPowerLevelCap())); - } else if(hasReachedLevelCap(primarySkillType)) { + } else if (hasReachedLevelCap(primarySkillType)) { NotificationManager.sendPlayerInformationChatOnly(player, "LevelCap.Skill", String.valueOf(mcMMO.p.getSkillTools().getLevelCap(primarySkillType)), mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType)); } //Updates from Party sources - if(xpGainSource == XPGainSource.PARTY_MEMBERS && !ExperienceConfig.getInstance().isPartyExperienceBarsEnabled()) + if (xpGainSource == XPGainSource.PARTY_MEMBERS && !ExperienceConfig.getInstance().isPartyExperienceBarsEnabled()) return; //Updates from passive sources (Alchemy, Smelting, etc...) - if(xpGainSource == XPGainSource.PASSIVE && !ExperienceConfig.getInstance().isPassiveGainsExperienceBarsEnabled()) + if (xpGainSource == XPGainSource.PASSIVE && !ExperienceConfig.getInstance().isPassiveGainsExperienceBarsEnabled()) return; updateXPBar(primarySkillType, plugin); @@ -285,7 +285,7 @@ public class McMMOPlayer implements Identified { public double getProgressInCurrentSkillLevel(PrimarySkillType primarySkillType) { - if(SkillTools.isChildSkill(primarySkillType)) { + if (SkillTools.isChildSkill(primarySkillType)) { return 1.0D; } @@ -602,7 +602,7 @@ public class McMMOPlayer implements Identified { * @return */ public boolean hasReachedLevelCap(PrimarySkillType primarySkillType) { - if(hasReachedPowerLevelCap()) + if (hasReachedPowerLevelCap()) return true; return getSkillLevel(primarySkillType) >= mcMMO.p.getSkillTools().getLevelCap(primarySkillType); @@ -624,7 +624,7 @@ public class McMMOPlayer implements Identified { * @param xp Experience amount to process */ public void beginXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { - if(xp <= 0) { + if (xp <= 0) { return; } @@ -656,7 +656,7 @@ public class McMMOPlayer implements Identified { * @param xp Experience amount to process */ public void beginUnsharedXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { - if(player.getGameMode() == GameMode.CREATIVE) + if (player.getGameMode() == GameMode.CREATIVE) return; applyXpGain(skill, modifyXpGain(skill, xp), xpGainReason, xpGainSource); @@ -709,7 +709,7 @@ public class McMMOPlayer implements Identified { * @param primarySkillType The skill to check */ private void checkXp(PrimarySkillType primarySkillType, XPGainReason xpGainReason, XPGainSource xpGainSource) { - if(hasReachedLevelCap(primarySkillType)) + if (hasReachedLevelCap(primarySkillType)) return; if (getSkillXpLevelRaw(primarySkillType) < getXpToLevel(primarySkillType)) { @@ -906,7 +906,7 @@ public class McMMOPlayer implements Identified { //TODO: This is hacky and temporary solution until skills are move to the new system //Potential problems with this include skills with two super abilities (ie mining) - if(!RankUtils.hasUnlockedSubskill(player, subSkillType)) + if (!RankUtils.hasUnlockedSubskill(player, subSkillType)) { int diff = RankUtils.getSuperAbilityUnlockRequirement(superAbilityType) - getSkillLevel(primarySkillType); @@ -941,7 +941,7 @@ public class McMMOPlayer implements Identified { int ticks; //Ability cap of 0 or below means no cap - if(abilityLengthCap > 0) + if (abilityLengthCap > 0) { ticks = PerksUtils.handleActivationPerks(player, 2 + (Math.min(abilityLengthCap, getSkillLevel(primarySkillType)) / abilityLengthVar), superAbilityType.getMaxLength()); } else { @@ -1024,7 +1024,7 @@ public class McMMOPlayer implements Identified { * IF THE TOOL IS AN AXE * */ - if(tool == ToolType.AXE) { + if (tool == ToolType.AXE) { processAxeToolMessages(); } else { NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, tool.getRaiseTool()); @@ -1045,20 +1045,20 @@ public class McMMOPlayer implements Identified { /* * IF BOTH TREE FELLER & SKULL SPLITTER ARE ON CD */ - if(isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { + if (isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { tooTiredMultiple(PrimarySkillType.WOODCUTTING, SubSkillType.WOODCUTTING_TREE_FELLER, SuperAbilityType.TREE_FELLER, SubSkillType.AXES_SKULL_SPLITTER, SuperAbilityType.SKULL_SPLITTER); /* * IF TREE FELLER IS ON CD * AND PLAYER IS LOOKING AT TREE */ - } else if(isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) + } else if (isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && BlockUtils.isPartOfTree(rayCast)) { raiseToolWithCooldowns(SubSkillType.WOODCUTTING_TREE_FELLER, SuperAbilityType.TREE_FELLER); /* * IF SKULL SPLITTER IS ON CD */ - } else if(isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { + } else if (isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { raiseToolWithCooldowns(SubSkillType.AXES_SKULL_SPLITTER, SuperAbilityType.SKULL_SPLITTER); } else { NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, ToolType.AXE.getRaiseTool()); @@ -1156,7 +1156,7 @@ public class McMMOPlayer implements Identified { */ public void logout(boolean syncSave) { Player thisPlayer = getPlayer(); - if(getPlayer().hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { + if (getPlayer().hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { RuptureTaskMeta ruptureTaskMeta = (RuptureTaskMeta) getPlayer().getMetadata(MetadataConstants.METADATA_KEY_RUPTURE).get(0); //Punish a logout @@ -1175,7 +1175,7 @@ public class McMMOPlayer implements Identified { UserManager.remove(thisPlayer); - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) ScoreboardManager.teardownPlayer(thisPlayer); if (inParty()) { diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java index 71abb6418..1087fca48 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java @@ -100,7 +100,7 @@ public class PlayerProfile { loaded = true; - if(lastLogin != null) + if (lastLogin != null) this.lastLogin = lastLogin; } @@ -130,17 +130,17 @@ public class PlayerProfile { if (changed) { mcMMO.p.getLogger().severe("PlayerProfile saving failed for player: " + playerName + " " + uuid); - if(saveAttempts > 0) { + if (saveAttempts > 0) { mcMMO.p.getLogger().severe("Attempted to save profile for player "+getPlayerName() + " resulted in failure. "+saveAttempts+" have been made so far."); } - if(saveAttempts < 10) + if (saveAttempts < 10) { saveAttempts++; //Back out of async saving if we detect a server shutdown, this is not always going to be caught - if(mcMMO.isServerShutdownExecuted() || useSync) + if (mcMMO.isServerShutdownExecuted() || useSync) mcMMO.p.getFoliaLib().getImpl().runNextTick(new PlayerProfileSaveTask(this, true)); else scheduleAsyncSave(); @@ -271,7 +271,7 @@ public class PlayerProfile { } public int getSkillXpLevel(PrimarySkillType skill) { - if(SkillTools.isChildSkill(skill)) { + if (SkillTools.isChildSkill(skill)) { return 0; } @@ -339,7 +339,7 @@ public class PlayerProfile { markProfileDirty(); //Don't allow levels to be negative - if(level < 0) + if (level < 0) level = 0; skills.put(skill, level); @@ -424,7 +424,7 @@ public class PlayerProfile { * @return the total amount of Xp until next level */ public int getXpToLevel(PrimarySkillType primarySkillType) { - if(SkillTools.isChildSkill(primarySkillType)) { + if (SkillTools.isChildSkill(primarySkillType)) { return 0; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java index 26e0f17d9..85952bac7 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java @@ -37,7 +37,7 @@ public enum MaterialType { return Material.DIAMOND; case NETHERITE: - if(Material.getMaterial("NETHERITE_SCRAP") != null) + if (Material.getMaterial("NETHERITE_SCRAP") != null) return Material.getMaterial("NETHERITE_SCRAP"); else return Material.DIAMOND; diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java index 1cf028e88..a43e56c38 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java @@ -201,7 +201,7 @@ public enum SubSkillType { * Split the string up so we can capitalize each part */ String subskillNameWithoutPrefix = subSkillName.substring(subStringIndex); - if(subskillNameWithoutPrefix.contains("_")) + if (subskillNameWithoutPrefix.contains("_")) { String[] splitStrings = subskillNameWithoutPrefix.split("_"); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java index 303cf3b19..7825c717f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java @@ -64,7 +64,7 @@ public enum PotionStage { stage++; } else if (!potionMeta.getCustomEffects().isEmpty()) { for (PotionEffect effect : potionMeta.getCustomEffects()){ - if(effect.getAmplifier() > 0){ + if (effect.getAmplifier() > 0){ stage++; break; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java index bb0ea4267..6b91d31b3 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java @@ -61,7 +61,7 @@ public class Roll extends AcrobaticsSubSkill { EntityDamageEvent entityDamageEvent = (EntityDamageEvent) event; //Make sure a real player was damaged in this event - if(!EventUtils.isRealPlayerDamaged(entityDamageEvent)) + if (!EventUtils.isRealPlayerDamaged(entityDamageEvent)) return false; if (entityDamageEvent.getCause() == EntityDamageEvent.DamageCause.FALL) {//Grab the player @@ -81,7 +81,7 @@ public class Roll extends AcrobaticsSubSkill { entityDamageEvent.setCancelled(true); return true; } - } else if(mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(mmoPlayer.getPlayer(), PrimarySkillType.ACROBATICS)) { + } else if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(mmoPlayer.getPlayer(), PrimarySkillType.ACROBATICS)) { //Give XP Anyways SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, ((EntityDamageEvent) event).getFinalDamage(), false), XPGainReason.PVE); } @@ -156,7 +156,7 @@ public class Roll extends AcrobaticsSubSkill { //Advanced //Lucky Notice - if(isLucky) + if (isLucky) { componentBuilder.append(Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Header"))); componentBuilder.append(Component.newline()); @@ -213,7 +213,7 @@ public class Roll extends AcrobaticsSubSkill { //mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Acrobatics.Roll.Text")); //if (!SkillUtils.cooldownExpired((long) mcMMOmmoPlayer.getPlayer().getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { - if(!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, true), XPGainReason.PVE); //} @@ -222,7 +222,7 @@ public class Roll extends AcrobaticsSubSkill { } else if (!isFatal(mmoPlayer, damage)) { //if (!SkillUtils.cooldownExpired((long) mmoPlayer.getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { - if(!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, false), XPGainReason.PVE); //} } @@ -252,14 +252,14 @@ public class Roll extends AcrobaticsSubSkill { { NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Ability.Proc"); SoundManager.sendCategorizedSound(mmoPlayer.getPlayer(), mmoPlayer.getPlayer().getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS,0.5F); - if(!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, true), XPGainReason.PVE); addFallLocation(mmoPlayer); return modifiedDamage; } else if (!isFatal(mmoPlayer, damage)) { - if(!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, false), XPGainReason.PVE); addFallLocation(mmoPlayer); @@ -286,15 +286,15 @@ public class Roll extends AcrobaticsSubSkill { } if (ItemUtils.hasItemInEitherHand(mmoPlayer.getPlayer(), Material.ENDER_PEARL) || mmoPlayer.getPlayer().isInsideVehicle()) { - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Ender Pearl or Inside Vehicle"); } return true; } - if(mmoPlayer.getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(mmoPlayer))) + if (mmoPlayer.getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(mmoPlayer))) { - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Fallen in location before"); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java index f92155a6a..1c39fed2f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java @@ -36,7 +36,7 @@ public class TamingSummon { entityType = EntityType.HORSE; break; case CAT: - if(shouldSpawnCatInsteadOfOcelot()) { + if (shouldSpawnCatInsteadOfOcelot()) { //Server is on 1.14 or above entityType = EntityType.CAT; } else { diff --git a/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java b/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java index 69feb7b9b..efe7d1f9c 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java @@ -30,7 +30,7 @@ public class FishingTreasureBook extends FishingTreasure { LogUtils.debug(mcMMO.p.getLogger(), "Registering enchantments for Fishing Book..."); for(Enchantment enchantment : Enchantment.values()) { - if(isEnchantAllowed(enchantment)) { + if (isEnchantAllowed(enchantment)) { addAllLegalEnchants(enchantment); } } @@ -66,9 +66,9 @@ public class FishingTreasureBook extends FishingTreasure { } private boolean isEnchantAllowed(@NotNull Enchantment enchantment) { - if(whiteListedEnchantments != null && !whiteListedEnchantments.isEmpty()) { + if (whiteListedEnchantments != null && !whiteListedEnchantments.isEmpty()) { return whiteListedEnchantments.contains(enchantment); - } else if(blackListedEnchantments != null && !blackListedEnchantments.isEmpty()) { + } else if (blackListedEnchantments != null && !blackListedEnchantments.isEmpty()) { return !blackListedEnchantments.contains(enchantment); } else { return true; diff --git a/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java b/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java index 4666b32b1..0ff04bdbd 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java @@ -12,7 +12,7 @@ public enum Rarity { COMMON; public static @NotNull Rarity getRarity(@NotNull String string) { - if(string.equalsIgnoreCase("Records")) { + if (string.equalsIgnoreCase("Records")) { mcMMO.p.getLogger().severe("Entries in fishing treasures have Records set as rarity, however Records was renamed to Mythic. Please update your treasures to read MYTHIC instead of RECORDS for rarity, or delete the config file to regenerate a new one."); return Rarity.MYTHIC; //People that copy paste their configs will have Records interpretted as Mythic } diff --git a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java index 44ad7d078..f278143cd 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java @@ -30,7 +30,7 @@ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements super(player); this.skill = skill; - if(UserManager.getPlayer(player) != null) { + if (UserManager.getPlayer(player) != null) { this.skillLevel = UserManager.getPlayer(player).getSkillLevel(skill); } else { this.skillLevel = 0; diff --git a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java index 3b3e3ba7e..5e6ea6a78 100644 --- a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java @@ -50,8 +50,8 @@ public class BlockListener implements Listener { public void onBlockDropItemEvent(BlockDropItemEvent event) { //Make sure we clean up metadata on these blocks - if(event.isCancelled()) { - if(event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (event.isCancelled()) { + if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) event.getBlock().removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, plugin); return; } @@ -59,7 +59,7 @@ public class BlockListener implements Listener { int tileEntityTolerance = 1; // beetroot hotfix, potentially other plants may need this fix - if(event.getBlockState().getType() == Material.BEETROOTS) + if (event.getBlockState().getType() == Material.BEETROOTS) tileEntityTolerance = 2; //Track how many "things" are being dropped @@ -72,34 +72,34 @@ public class BlockListener implements Listener { uniqueMaterials.add(item.getItemStack().getType()); //Count blocks as a second failsafe - if(item.getItemStack().getType().isBlock()) + if (item.getItemStack().getType().isBlock()) blockCount++; } - if(uniqueMaterials.size() > tileEntityTolerance) { + if (uniqueMaterials.size() > tileEntityTolerance) { //Too many things are dropping, assume tile entities might be duped //Technically this would also prevent something like coal from being bonus dropped if you placed a TE above a coal ore when mining it but that's pretty edge case and this is a good solution for now dontRewardTE = true; } //If there are more than one block in the item list we can't really trust it and will back out of rewarding bonus drops - if(blockCount <= 1) { + if (blockCount <= 1) { for(Item item : event.getItems()) { ItemStack is = new ItemStack(item.getItemStack()); - if(is.getAmount() <= 0) + if (is.getAmount() <= 0) continue; //TODO: Ignore this abomination its rewritten in 2.2 - if(!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, is.getType()) + if (!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, is.getType()) && !mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.HERBALISM, is.getType()) && !mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, is.getType())) continue; //If we suspect TEs might be duped only reward block - if(dontRewardTE) { - if(!is.getType().isBlock()) { + if (dontRewardTE) { + if (!is.getType().isBlock()) { continue; } } @@ -115,7 +115,7 @@ public class BlockListener implements Listener { } } - if(event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) event.getBlock().removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, plugin); } @@ -127,10 +127,10 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonExtend(BlockPistonExtendEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; - if(!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { + if (!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { return; } @@ -155,10 +155,10 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonRetract(BlockPistonRetractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; - if(!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { + if (!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { return; } @@ -167,12 +167,12 @@ public class BlockListener implements Listener { Block movedBlock = event.getBlock().getRelative(direction); //Spigot makes bad things happen in its API - if(BlockUtils.isWithinWorldBounds(movedBlock)) { + if (BlockUtils.isWithinWorldBounds(movedBlock)) { BlockUtils.setUnnaturalBlock(movedBlock); } for (Block block : event.getBlocks()) { - if(BlockUtils.isWithinWorldBounds(block) && BlockUtils.isWithinWorldBounds(block.getRelative(direction))) { + if (BlockUtils.isWithinWorldBounds(block) && BlockUtils.isWithinWorldBounds(block.getRelative(direction))) { Block relativeBlock = block.getRelative(direction); BlockUtils.setUnnaturalBlock(relativeBlock); } @@ -189,15 +189,15 @@ public class BlockListener implements Listener { public void onEntityBlockFormEvent(EntityBlockFormEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; BlockState blockState = event.getNewState(); - if(ExperienceConfig.getInstance().isSnowExploitPrevented() && BlockUtils.shouldBeWatched(blockState)) { + if (ExperienceConfig.getInstance().isSnowExploitPrevented() && BlockUtils.shouldBeWatched(blockState)) { Block block = blockState.getBlock(); - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { BlockUtils.setUnnaturalBlock(block); } } @@ -212,15 +212,15 @@ public class BlockListener implements Listener { World world = event.getBlock().getWorld(); /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(world)) + if (WorldBlacklist.isWorldBlacklisted(world)) return; - if(ExperienceConfig.getInstance().preventStoneLavaFarming()) { + if (ExperienceConfig.getInstance().preventStoneLavaFarming()) { BlockState newState = event.getNewState(); - if(newState.getType() != Material.OBSIDIAN && ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, newState.getBlockData())) { + if (newState.getType() != Material.OBSIDIAN && ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, newState.getBlockData())) { Block block = newState.getBlock(); - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { BlockUtils.setUnnaturalBlock(block); } } @@ -241,11 +241,11 @@ public class BlockListener implements Listener { // if (!Tag.LOGS.isTagged(event.getBlockReplacedState().getType()) || !Tag.LOGS.isTagged(event.getBlockPlaced().getType())) /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(block.getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(block.getWorld())) { return; } - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { //NOTE: BlockMultiPlace has its own logic so don't handle anything that would overlap if (!(event instanceof BlockMultiPlaceEvent)) { BlockUtils.setUnnaturalBlock(block); @@ -261,7 +261,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; if (blockState.getType() == Repair.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR)) { @@ -284,10 +284,10 @@ public class BlockListener implements Listener { Block block = blockState.getBlock(); /* Check if the blocks placed should be monitored so they do not give out XP in the future */ - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { //Updated: 10/5/2021 //Note: For some reason Azalea trees trigger this event but no other tree does (as of 10/5/2021) but if this changes in the future we may need to update this - if(BlockUtils.isPartOfTree(event.getBlockPlaced())) { + if (BlockUtils.isPartOfTree(event.getBlockPlaced())) { return; } @@ -305,11 +305,11 @@ public class BlockListener implements Listener { World world = block.getWorld(); /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(world)) + if (WorldBlacklist.isWorldBlacklisted(world)) return; // Minecraft is dumb, the events still throw when a plant "grows" higher than the max block height. Even though no new block is created - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { mcMMO.getPlaceStore().setFalse(block); } } @@ -328,15 +328,15 @@ public class BlockListener implements Listener { return; } - if(WorldBlacklist.isWorldBlacklisted(block.getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(block.getWorld())) { BlockUtils.cleanupBlockMetadata(block); return; } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { BlockUtils.cleanupBlockMetadata(block); return; } @@ -364,7 +364,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Check if profile is loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { /* Remove metadata from placed watched blocks */ BlockUtils.cleanupBlockMetadata(block); @@ -442,17 +442,17 @@ public class BlockListener implements Listener { */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBreakHigher(BlockBreakEvent event) { - if(event instanceof FakeEvent) + if (event instanceof FakeEvent) return; /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -463,7 +463,7 @@ public class BlockListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -509,13 +509,13 @@ public class BlockListener implements Listener { BlockState blockState = event.getBlock().getState(); /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -529,7 +529,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) { return; } @@ -560,11 +560,11 @@ public class BlockListener implements Listener { || BlockUtils.affectedByBlockCracker(blockState) && Permissions.berserk(player))) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.UNARMED); - if(mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK)) { + if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK)) { if (SuperAbilityType.BERSERK.blockCheck(blockState) && EventUtils.simulateBlockBreak(blockState.getBlock(), player)) { event.setInstaBreak(true); - if(blockState.getType().getKey().getKey().contains("glass")) { + if (blockState.getType().getKey().getKey().contains("glass")) { SoundManager.worldSendSound(player.getWorld(), blockState.getLocation(), SoundType.GLASS); } else { SoundManager.sendSound(player, blockState.getLocation(), SoundType.POP); @@ -592,13 +592,13 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockDamageHigher(BlockDamageEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -615,7 +615,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -643,7 +643,7 @@ public class BlockListener implements Listener { else if (!event.getInstaBreak() && SuperAbilityType.BERSERK.blockCheck(blockState) && EventUtils.simulateBlockBreak(block, player)) { event.setInstaBreak(true); - if(blockState.getType().getKey().getKey().contains("glass")) { + if (blockState.getType().getKey().getKey().contains("glass")) { SoundManager.worldSendSound(player.getWorld(), block.getLocation(), SoundType.GLASS); } else { SoundManager.sendSound(player, block.getLocation(), SoundType.POP); @@ -662,7 +662,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -680,14 +680,14 @@ public class BlockListener implements Listener { //TODO: Convert into locale strings private void debugStickDump(Player player, BlockState blockState) { //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } - if(UserManager.getPlayer(player).isDebugMode()) + if (UserManager.getPlayer(player).isDebugMode()) { - if(mcMMO.getPlaceStore().isTrue(blockState)) + if (mcMMO.getPlaceStore().isTrue(blockState)) player.sendMessage("[mcMMO DEBUG] This block is not natural and does not reward treasures/XP"); else { @@ -695,24 +695,24 @@ public class BlockListener implements Listener { UserManager.getPlayer(player).getExcavationManager().printExcavationDebug(player, blockState); } - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardManager.getInstance().hasMainFlag(player)) player.sendMessage("[mcMMO DEBUG] World Guard main flag is permitted for this player in this region"); else player.sendMessage("[mcMMO DEBUG] World Guard main flag is DENIED for this player in this region"); - if(WorldGuardManager.getInstance().hasXPFlag(player)) + if (WorldGuardManager.getInstance().hasXPFlag(player)) player.sendMessage("[mcMMO DEBUG] World Guard xp flag is permitted for this player in this region"); else player.sendMessage("[mcMMO DEBUG] World Guard xp flag is not permitted for this player in this region"); } - if(blockState instanceof Furnace || blockState instanceof BrewingStand) { - if(ContainerMetadataUtils.isContainerOwned(blockState)) { + if (blockState instanceof Furnace || blockState instanceof BrewingStand) { + if (ContainerMetadataUtils.isContainerOwned(blockState)) { player.sendMessage("[mcMMO DEBUG] This container has a registered owner"); final OfflinePlayer furnacePlayer = ContainerMetadataUtils.getContainerOwner(blockState); - if(furnacePlayer != null) { + if (furnacePlayer != null) { player.sendMessage("[mcMMO DEBUG] This container is owned by player "+furnacePlayer.getName()); } } @@ -720,7 +720,7 @@ public class BlockListener implements Listener { player.sendMessage("[mcMMO DEBUG] This container does not have a registered owner"); } - if(ExperienceConfig.getInstance().isExperienceBarsEnabled()) + if (ExperienceConfig.getInstance().isExperienceBarsEnabled()) player.sendMessage("[mcMMO DEBUG] XP bars are enabled, however you should check per-skill settings to make sure those are enabled."); player.sendMessage(ChatColor.RED+"You can turn this debug info off by typing "+ChatColor.GOLD+"/mmodebug"); diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index 9bad702f2..5e3002a15 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -63,12 +63,12 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onEntityTransform(EntityTransformEvent event) { - if(event.getEntity() instanceof LivingEntity livingEntity) { + if (event.getEntity() instanceof LivingEntity livingEntity) { //Transfer metadata keys from mob-spawned mobs to new mobs - if(hasMobFlags(livingEntity)) { + if (hasMobFlags(livingEntity)) { for(Entity entity : event.getTransformedEntities()) { - if(entity instanceof LivingEntity transformedEntity) { + if (entity instanceof LivingEntity transformedEntity) { addMobFlags(livingEntity, transformedEntity); } } @@ -78,21 +78,21 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityTargetEntity(EntityTargetLivingEntityEvent event) { - if(!ExperienceConfig.getInstance().isEndermanEndermiteFarmingPrevented()) + if (!ExperienceConfig.getInstance().isEndermanEndermiteFarmingPrevented()) return; //It's rare but targets can be null sometimes - if(event.getTarget() == null) + if (event.getTarget() == null) { return; } //Prevent entities from giving XP if they target endermite - if(event.getTarget() instanceof Endermite) + if (event.getTarget() instanceof Endermite) { - if(event.getEntity() instanceof Enderman enderman) { + if (event.getEntity() instanceof Enderman enderman) { - if(!hasMobFlag(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman)) { + if (!hasMobFlag(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman)) { flagMetadata(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman); } } @@ -102,10 +102,10 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) public void onEntityShootBow(EntityShootBowEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity() instanceof Player player) + if (event.getEntity() instanceof Player player) { Entity projectile = event.getProjectile(); @@ -135,35 +135,35 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onProjectileLaunch(ProjectileLaunchEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity().getShooter() instanceof Player player) + if (event.getEntity().getShooter() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } - if(event.getEntity() instanceof Arrow arrow) { + if (event.getEntity() instanceof Arrow arrow) { // Delayed metadata cleanup in case other cleanup hooks fail CombatUtils.delayArrowMetaCleanup(arrow); // If fired from an item with multi-shot, we need to track - if(ItemUtils.doesPlayerHaveEnchantmentInHands(player, "multishot")) { + if (ItemUtils.doesPlayerHaveEnchantmentInHands(player, "multishot")) { arrow.setMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); } - if(!arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) arrow.setMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, new FixedMetadataValue(pluginRef, 1.0)); - if(!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) arrow.setMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, new FixedMetadataValue(pluginRef, arrow.getLocation())); //Check both hands - if(ItemUtils.doesPlayerHaveEnchantmentInHands(player, "piercing")) { + if (ItemUtils.doesPlayerHaveEnchantmentInHands(player, "piercing")) { return; } @@ -183,7 +183,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityChangeBlock(EntityChangeBlockEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Block block = event.getBlock(); @@ -232,16 +232,16 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityCombustByEntityEvent(EntityCombustByEntityEvent event) { //Prevent players from setting fire to each other if they are in the same party - if(event.getEntity() instanceof Player defender) { + if (event.getEntity() instanceof Player defender) { - if(event.getCombuster() instanceof Projectile projectile) { - if(projectile.getShooter() instanceof Player attacker) { - if(checkIfInPartyOrSamePlayer(event, defender, attacker)) { + if (event.getCombuster() instanceof Projectile projectile) { + if (projectile.getShooter() instanceof Player attacker) { + if (checkIfInPartyOrSamePlayer(event, defender, attacker)) { event.setCancelled(true); } } - } else if(event.getCombuster() instanceof Player attacker) { - if(checkIfInPartyOrSamePlayer(event, defender, attacker)) { + } else if (event.getCombuster() instanceof Player attacker) { + if (checkIfInPartyOrSamePlayer(event, defender, attacker)) { event.setCancelled(true); } } @@ -266,18 +266,18 @@ public class EntityListener implements Listener { Entity defender = event.getEntity(); Entity attacker = event.getDamager(); - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(attacker instanceof Player) { + if (attacker instanceof Player) { - if(!WorldGuardManager.getInstance().hasMainFlag((Player) attacker)) { + if (!WorldGuardManager.getInstance().hasMainFlag((Player) attacker)) { return; } - } else if(attacker instanceof Projectile projectile) { + } else if (attacker instanceof Projectile projectile) { - if(projectile.getShooter() instanceof Player) { - if(!WorldGuardManager.getInstance().hasMainFlag((Player) projectile.getShooter())) { + if (projectile.getShooter() instanceof Player) { + if (!WorldGuardManager.getInstance().hasMainFlag((Player) projectile.getShooter())) { return; } } @@ -286,7 +286,7 @@ public class EntityListener implements Listener { } /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { return; } @@ -335,8 +335,8 @@ public class EntityListener implements Listener { //Friendly fire checks if (defender instanceof Player defendingPlayer) { //If the attacker is a Player or a projectile belonging to a player - if(attacker instanceof Projectile projectile) { - if(projectile.getShooter() instanceof Player attackingPlayer && !attackingPlayer.equals(defendingPlayer)) { + if (attacker instanceof Projectile projectile) { + if (projectile.getShooter() instanceof Player attackingPlayer && !attackingPlayer.equals(defendingPlayer)) { //Check for friendly fire and cancel the event if (checkIfInPartyOrSamePlayer(event, defendingPlayer, attackingPlayer)) { return; @@ -362,9 +362,9 @@ public class EntityListener implements Listener { } //Required setup for processCombatAttack - if(attacker instanceof Projectile) { + if (attacker instanceof Projectile) { ProjectileSource shooter = ((Projectile) attacker).getShooter(); - if(shooter instanceof LivingEntity) { + if (shooter instanceof LivingEntity) { attacker = (LivingEntity) shooter; } } @@ -378,8 +378,8 @@ public class EntityListener implements Listener { * Surprising this kind of thing * */ - if(mcMMO.isProjectKorraEnabled()) { - if(event.getFinalDamage() == 0) { + if (mcMMO.isProjectKorraEnabled()) { + if (event.getFinalDamage() == 0) { return; } } @@ -390,22 +390,22 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) public void onEntityDamageMonitor(EntityDamageByEntityEvent entityDamageEvent) { - if(entityDamageEvent.getEntity() instanceof LivingEntity livingEntity) { + if (entityDamageEvent.getEntity() instanceof LivingEntity livingEntity) { - if(entityDamageEvent.getFinalDamage() >= livingEntity.getHealth()) { + if (entityDamageEvent.getFinalDamage() >= livingEntity.getHealth()) { //This sets entity names back to whatever they are supposed to be CombatUtils.fixNames(livingEntity); } } - if(entityDamageEvent.getDamager() instanceof Arrow arrow) { + if (entityDamageEvent.getDamager() instanceof Arrow arrow) { CombatUtils.delayArrowMetaCleanup(arrow); } - if(entityDamageEvent.getEntity() instanceof Player player && entityDamageEvent.getDamager() instanceof Player) { + if (entityDamageEvent.getEntity() instanceof Player player && entityDamageEvent.getDamager() instanceof Player) { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer != null) { - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer != null) { + if (mmoPlayer.isDebugMode()) { player.sendMessage(ChatColor.GOLD + "(mmodebug start of combat report) EntityDamageByEntityEvent DEBUG Info:"); player.sendMessage("You are being damaged by another player in this event"); player.sendMessage("Raw Damage: " + entityDamageEvent.getDamage()); @@ -419,7 +419,7 @@ public class EntityListener implements Listener { player.sendMessage("Final damage: " + entityDamageEvent.getFinalDamage()); - if(entityDamageEvent.isCancelled()) { + if (entityDamageEvent.isCancelled()) { player.sendMessage("Event was cancelled, which means no damage should be done."); } @@ -428,10 +428,10 @@ public class EntityListener implements Listener { } } - if(entityDamageEvent.getDamager() instanceof Player player && entityDamageEvent.getEntity() instanceof Player otherPlayer) { + if (entityDamageEvent.getDamager() instanceof Player player && entityDamageEvent.getEntity() instanceof Player otherPlayer) { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer != null) { - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer != null) { + if (mmoPlayer.isDebugMode()) { player.sendMessage(ChatColor.GOLD + "(mmodebug start of combat report) EntityDamageByEntityEvent DEBUG Info:"); player.sendMessage("You are dealing damage to another player in this event"); player.sendMessage("Raw Damage: " + entityDamageEvent.getDamage()); @@ -445,7 +445,7 @@ public class EntityListener implements Listener { player.sendMessage("Target players max health: "+otherPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()); player.sendMessage("Target players current health: "+otherPlayer.getHealth()); - if(entityDamageEvent.isCancelled()) { + if (entityDamageEvent.isCancelled()) { player.sendMessage("Event was cancelled, which means no damage should be done."); } @@ -461,7 +461,7 @@ public class EntityListener implements Listener { return true; } - if(!pluginRef.isPartySystemEnabled()) { + if (!pluginRef.isPartySystemEnabled()) { return false; } @@ -470,7 +470,7 @@ public class EntityListener implements Listener { } //Party Friendly Fire - if(!mcMMO.p.getGeneralConfig().getPartyFriendlyFire()) + if (!mcMMO.p.getGeneralConfig().getPartyFriendlyFire()) if ((mcMMO.p.getPartyManager().inSameParty(defendingPlayer, attackingPlayer) || mcMMO.p.getPartyManager().areAllies(defendingPlayer, attackingPlayer)) && !(Permissions.friendlyFire(attackingPlayer) @@ -490,19 +490,19 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity().hasMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE)) { + if (event.getEntity().hasMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE)) { event.getEntity().removeMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE, mcMMO.p); } - if(event.getEntity() instanceof Player player) + if (event.getEntity() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -559,7 +559,7 @@ public class EntityListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; /* Check for invincibility */ @@ -577,12 +577,12 @@ public class EntityListener implements Listener { else if (livingEntity instanceof Tameable pet) { AnimalTamer owner = pet.getOwner(); - if(owner instanceof Player player) + if (owner instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -592,7 +592,7 @@ public class EntityListener implements Listener { Wolf wolf = (Wolf) pet; //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -679,12 +679,12 @@ public class EntityListener implements Listener { public void onEntityDeath(EntityDeathEvent event) { LivingEntity entity = event.getEntity(); - if(mcMMO.getTransientEntityTracker().isTransientSummon(entity)) { + if (mcMMO.getTransientEntityTracker().isTransientSummon(entity)) { mcMMO.getTransientEntityTracker().removeSummon(entity, null, false); } /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { return; } @@ -704,7 +704,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onCreatureSpawn(CreatureSpawnEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; LivingEntity livingEntity = event.getEntity(); @@ -732,7 +732,7 @@ public class EntityListener implements Listener { flagMetadata(mobMetaFlagType, livingEntity); for(Entity passenger : livingEntity.getPassengers()) { - if(passenger != null) { + if (passenger != null) { flagMetadata(mobMetaFlagType, livingEntity); } } @@ -740,8 +740,8 @@ public class EntityListener implements Listener { @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onEntityBreed(EntityBreedEvent event) { - if(ExperienceConfig.getInstance().isCOTWBreedingPrevented()) { - if(hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getFather()) || hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getMother())) { + if (ExperienceConfig.getInstance().isCOTWBreedingPrevented()) { + if (hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getFather()) || hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getMother())) { event.setCancelled(true); Animals mom = (Animals) event.getMother(); Animals father = (Animals) event.getFather(); @@ -751,7 +751,7 @@ public class EntityListener implements Listener { father.setLoveModeTicks(0); //Inform the player - if(event.getBreeder() instanceof Player player) { + if (event.getBreeder() instanceof Player player) { NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.BreedingDisallowed"); } } @@ -767,7 +767,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onExplosionPrime(ExplosionPrimeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -785,15 +785,15 @@ public class EntityListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -813,7 +813,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEnitityExplode(EntityExplodeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -831,14 +831,14 @@ public class EntityListener implements Listener { } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -860,7 +860,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onFoodLevelChange(FoodLevelChangeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -870,15 +870,15 @@ public class EntityListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -898,9 +898,9 @@ public class EntityListener implements Listener { //The main hand is used over the off hand if they both have food, so check the main hand first Material foodInHand; - if(mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInMainHand().getType())) { + if (mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInMainHand().getType())) { foodInHand = player.getInventory().getItemInMainHand().getType(); - } else if(mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInOffHand().getType())) { + } else if (mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInOffHand().getType())) { foodInHand = player.getInventory().getItemInOffHand().getType(); } else { return; //Not Food @@ -913,7 +913,7 @@ public class EntityListener implements Listener { */ //Hacky 1.17 support - if(foodInHand.getKey().getKey().equalsIgnoreCase("glow_berries")) { + if (foodInHand.getKey().getKey().equalsIgnoreCase("glow_berries")) { if (Permissions.isSubSkillEnabled(player, SubSkillType.HERBALISM_FARMERS_DIET)) { event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(newFoodLevel)); } @@ -984,7 +984,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityTame(EntityTameEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; if (event instanceof FakeEntityTameEvent) { @@ -994,9 +994,9 @@ public class EntityListener implements Listener { Player player = (Player) event.getOwner(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -1012,7 +1012,7 @@ public class EntityListener implements Listener { flagMetadata(MobMetaFlagType.PLAYER_TAMED_MOB, livingEntity); //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -1029,7 +1029,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityTarget(EntityTargetEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -1040,9 +1040,9 @@ public class EntityListener implements Listener { } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -1068,7 +1068,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPotionSplash(PotionSplashEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; ItemMeta meta = event.getPotion().getItem().getItemMeta(); @@ -1095,8 +1095,8 @@ public class EntityListener implements Listener { if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity() instanceof Arrow arrow) { - if(arrow.isShotFromCrossbow()) { + if (event.getEntity() instanceof Arrow arrow) { + if (arrow.isShotFromCrossbow()) { Crossbows.processCrossbows(event, pluginRef, arrow); } } diff --git a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java index 348ba2af0..6bc7cca44 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java +++ b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java @@ -19,13 +19,13 @@ public class InteractionManager { public static void initMaps() { /* INIT MAPS */ - if(interactRegister == null) + if (interactRegister == null) interactRegister = new HashMap<>(); - if(subSkillList == null) + if (subSkillList == null) subSkillList = new ArrayList<>(); - if(subSkillNameMap == null) + if (subSkillNameMap == null) subSkillNameMap = new HashMap<>(); } @@ -36,7 +36,7 @@ public class InteractionManager { public static void registerSubSkill(AbstractSubSkill abstractSubSkill) { //Store a unique copy of each subskill - if(!subSkillList.contains(abstractSubSkill)) + if (!subSkillList.contains(abstractSubSkill)) subSkillList.add(abstractSubSkill); //Init ArrayList @@ -75,7 +75,7 @@ public class InteractionManager { */ public static void processEvent(Event event, mcMMO plugin, InteractType curInteractType) { - if(interactRegister.get(curInteractType) == null) + if (interactRegister.get(curInteractType) == null) return; for(Interaction interaction : interactRegister.get(curInteractType)) diff --git a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java index 08dfb6c4a..9da7a0605 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java @@ -42,7 +42,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceBurnEvent(FurnaceBurnEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; Block furnaceBlock = event.getBlock(); @@ -57,7 +57,7 @@ public class InventoryListener implements Listener { OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(furnace); Player player; - if(offlinePlayer != null && offlinePlayer.isOnline() && offlinePlayer instanceof Player) { + if (offlinePlayer != null && offlinePlayer.isOnline() && offlinePlayer instanceof Player) { player = (Player) offlinePlayer; if (!Permissions.isSubSkillEnabled(player, SubSkillType.SMELTING_FUEL_EFFICIENCY)) { @@ -66,10 +66,10 @@ public class InventoryListener implements Listener { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer != null) { + if (mmoPlayer != null) { boolean debugMode = mmoPlayer.isDebugMode(); - if(debugMode) { + if (debugMode) { player.sendMessage("FURNACE FUEL EFFICIENCY DEBUG REPORT"); player.sendMessage("Furnace - "+furnace.hashCode()); player.sendMessage("Furnace Type: "+furnaceBlock.getType()); @@ -78,7 +78,7 @@ public class InventoryListener implements Listener { event.setBurnTime(mmoPlayer.getSmeltingManager().fuelEfficiency(event.getBurnTime())); - if(debugMode) { + if (debugMode) { player.sendMessage("New Furnace Burn Length (after applying fuel efficiency) "+event.getBurnTime()); player.sendMessage(""); } @@ -89,7 +89,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceSmeltEvent(FurnaceSmeltEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; BlockState blockState = event.getBlock().getState(); //Furnaces can only be cast from a BlockState not a Block @@ -99,15 +99,15 @@ public class InventoryListener implements Listener { return; } - if(blockState instanceof Furnace furnace) { + if (blockState instanceof Furnace furnace) { OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(furnace); - if(offlinePlayer != null) { + if (offlinePlayer != null) { McMMOPlayer offlineProfile = UserManager.getOfflinePlayer(offlinePlayer); //Profile doesn't exist - if(offlineProfile != null) { + if (offlineProfile != null) { //Process smelting offlineProfile.getSmeltingManager().smeltProcessing(event, furnace); } @@ -118,7 +118,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceExtractEvent(FurnaceExtractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; BlockState furnaceBlock = event.getBlock().getState(); @@ -129,11 +129,11 @@ public class InventoryListener implements Listener { Player player = event.getPlayer(); - if(furnaceBlock instanceof Furnace) { + if (furnaceBlock instanceof Furnace) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -142,7 +142,7 @@ public class InventoryListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -156,11 +156,11 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryClickEventNormal(InventoryClickEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; //We should never care to do processing if the player clicks outside the window -// if(isOutsideWindowClick(event)) +// if (isOutsideWindowClick(event)) // return; Inventory inventory = event.getInventory(); @@ -168,12 +168,12 @@ public class InventoryListener implements Listener { Player player = ((Player) event.getWhoClicked()).getPlayer(); McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(event.getInventory() instanceof FurnaceInventory furnaceInventory) { + if (event.getInventory() instanceof FurnaceInventory furnaceInventory) { //Switch owners ContainerMetadataUtils.processContainerOwnership(furnaceInventory.getHolder(), player); } - if(event.getInventory() instanceof BrewerInventory brewerInventory) { + if (event.getInventory() instanceof BrewerInventory brewerInventory) { // switch owners ContainerMetadataUtils.processContainerOwnership(brewerInventory.getHolder(), player); } @@ -196,9 +196,9 @@ public class InventoryListener implements Listener { // TODO: Investigate why this WG check is all the way down here? /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -291,7 +291,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryDragEvent(InventoryDragEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; Inventory inventory = event.getInventory(); @@ -323,9 +323,9 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -345,7 +345,7 @@ public class InventoryListener implements Listener { public void onBrew(BrewEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; if (event instanceof FakeBrewEvent) @@ -361,7 +361,7 @@ public class InventoryListener implements Listener { // @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) // public void onBrewStart(BrewingStartEvent event) { // /* WORLD BLACKLIST CHECK */ -// if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) +// if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) // return; // // if (event instanceof FakeEvent) @@ -372,8 +372,8 @@ public class InventoryListener implements Listener { public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(event.getSource().getLocation() != null) - if(WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) + if (event.getSource().getLocation() != null) + if (WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) return; final Inventory inventory = event.getDestination(); @@ -416,19 +416,19 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryClickEvent(InventoryClickEvent event) { - if(event.getCurrentItem() == null) { + if (event.getCurrentItem() == null) { return; } SkillUtils.removeAbilityBuff(event.getCurrentItem()); if (event.getAction() == InventoryAction.HOTBAR_SWAP) { - if(isOutsideWindowClick(event)) + if (isOutsideWindowClick(event)) return; PlayerInventory playerInventory = event.getWhoClicked().getInventory(); - if(playerInventory.getItem(event.getHotbarButton()) != null) + if (playerInventory.getItem(event.getHotbarButton()) != null) SkillUtils.removeAbilityBuff(playerInventory.getItem(event.getHotbarButton())); } } @@ -441,7 +441,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCraftItem(CraftItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; final HumanEntity whoClicked = event.getWhoClicked(); @@ -460,9 +460,9 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } diff --git a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java index ab1526382..28a321f88 100644 --- a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java @@ -71,13 +71,13 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerTeleport(PlayerTeleportEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) { //Remove scoreboards - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { ScoreboardManager.teardownPlayer(event.getPlayer()); } return; - } else if(WorldBlacklist.isWorldBlacklisted(event.getFrom().getWorld()) && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + } else if (WorldBlacklist.isWorldBlacklisted(event.getFrom().getWorld()) && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { //This only fires if they are travelling to a non-blacklisted world from a blacklisted world //Setup scoreboards @@ -87,9 +87,9 @@ public class PlayerListener implements Listener { Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -98,7 +98,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -164,7 +164,7 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDeathMonitor(PlayerDeathEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; boolean statLossEnabled = HardcoreManager.isStatLossEnabled(); @@ -183,9 +183,9 @@ public class PlayerListener implements Listener { Player killer = killedPlayer.getKiller(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) + if (!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) return; } @@ -227,7 +227,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -250,13 +250,13 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDropItem(PlayerDropItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -281,15 +281,15 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerFishHighest(PlayerFishEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -298,7 +298,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -308,7 +308,7 @@ public class PlayerListener implements Listener { switch (event.getState()) { case CAUGHT_FISH: //TODO Update to new API once available! Waiting for case CAUGHT_TREASURE - if(event.getCaught() != null) { + if (event.getCaught() != null) { Item fishingCatch = (Item) event.getCaught(); if (mcMMO.p.getGeneralConfig().getFishingOverrideTreasures() && @@ -329,7 +329,7 @@ public class PlayerListener implements Listener { if (Permissions.vanillaXpBoost(player, PrimarySkillType.FISHING)) { //Don't modify XP below vanilla values - if(fishingManager.handleVanillaXpBoost(event.getExpToDrop()) > 1) + if (fishingManager.handleVanillaXpBoost(event.getExpToDrop()) > 1) event.setExpToDrop(fishingManager.handleVanillaXpBoost(event.getExpToDrop())); } } @@ -367,15 +367,15 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerFishMonitor(PlayerFishEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -384,7 +384,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -393,19 +393,19 @@ public class PlayerListener implements Listener { FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager(); //Track the hook - if(ExperienceConfig.getInstance().isFishingExploitingPrevented()) + if (ExperienceConfig.getInstance().isFishingExploitingPrevented()) { - if(event.getHook().getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() == 0) + if (event.getHook().getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() == 0) { fishingManager.setFishHookReference(event.getHook()); } //Spam Fishing - if(event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) + if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) { event.setExpToDrop(0); - if(caught instanceof Item caughtItem) + if (caught instanceof Item caughtItem) { caughtItem.remove(); } @@ -421,19 +421,19 @@ public class PlayerListener implements Listener { ItemStack inHand = player.getInventory().getItemInMainHand(); //Grab lure level - if(inHand != null + if (inHand != null && inHand.getItemMeta() != null && inHand.getType().getKey().getKey().equalsIgnoreCase("fishing_rod")) { - if(inHand.getItemMeta().hasEnchants()) { + if (inHand.getItemMeta().hasEnchants()) { for(Enchantment enchantment : inHand.getItemMeta().getEnchants().keySet()) { - if(enchantment.toString().toLowerCase().contains("lure")) { + if (enchantment.toString().toLowerCase().contains("lure")) { lureLevel = inHand.getEnchantmentLevel(enchantment); } } } // Prevent any potential odd behavior by only processing if no offhand fishing rod is present - if(!player.getInventory().getItemInOffHand().getType().getKey().getKey().equalsIgnoreCase("fishing_rod")) { + if (!player.getInventory().getItemInOffHand().getType().getKey().getKey().equalsIgnoreCase("fishing_rod")) { // In case of offhand fishing rod, don't process anything fishingManager.masterAngler(event.getHook(), lureLevel); fishingManager.setFishingTarget(); @@ -442,8 +442,8 @@ public class PlayerListener implements Listener { } return; case CAUGHT_FISH: - if(caught instanceof Item) { - if(ExperienceConfig.getInstance().isFishingExploitingPrevented()) { + if (caught instanceof Item) { + if (ExperienceConfig.getInstance().isFishingExploitingPrevented()) { fishingManager.processExploiting(event.getHook().getLocation().toVector()); @@ -482,20 +482,20 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerPickupItem(EntityPickupItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(Misc.isNPCEntityExcludingVillagers(event.getEntity())) { + if (Misc.isNPCEntityExcludingVillagers(event.getEntity())) { return; } - if(event.getEntity() instanceof Player player) + if (event.getEntity() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -505,7 +505,7 @@ public class PlayerListener implements Listener { //Profile not loaded McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -513,7 +513,7 @@ public class PlayerListener implements Listener { ItemStack dropStack = drop.getItemStack(); //Remove tracking - if(drop.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { + if (drop.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { drop.removeMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, mcMMO.p); } @@ -566,7 +566,7 @@ public class PlayerListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -618,7 +618,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -634,28 +634,28 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerInteractLowest(PlayerInteractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } - if(event.getClickedBlock() == null) + if (event.getClickedBlock() == null) return; Block clickedBlock = event.getClickedBlock(); Material clickedBlockType = clickedBlock.getType(); //The blacklist contains interactable blocks so its a convenient filter - if(clickedBlockType == Repair.anvilMaterial || clickedBlockType == Salvage.anvilMaterial) { + if (clickedBlockType == Repair.anvilMaterial || clickedBlockType == Salvage.anvilMaterial) { event.setUseItemInHand(Event.Result.ALLOW); - if(!event.getPlayer().isSneaking() && mcMMO.getMaterialMapStore().isToolActivationBlackListed(clickedBlockType)) { + if (!event.getPlayer().isSneaking() && mcMMO.getMaterialMapStore().isToolActivationBlackListed(clickedBlockType)) { event.setUseInteractedBlock(Event.Result.DENY); } } @@ -665,7 +665,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -764,15 +764,15 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onPlayerInteractMonitor(PlayerInteractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -781,7 +781,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) { return; } @@ -793,12 +793,12 @@ public class PlayerListener implements Listener { ItemStack heldItem = player.getInventory().getItemInMainHand(); //Spam Fishing Detection - if(event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) + if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { - if(ExperienceConfig.getInstance().isFishingExploitingPrevented() + if (ExperienceConfig.getInstance().isFishingExploitingPrevented() && (heldItem.getType() == Material.FISHING_ROD || player.getInventory().getItemInOffHand().getType() == Material.FISHING_ROD)) { - if(player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) + if (player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) { player.getVehicle().eject(); } @@ -809,12 +809,12 @@ public class PlayerListener implements Listener { switch (event.getAction()) { case RIGHT_CLICK_BLOCK: - if(player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { + if (player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { break; } //Hmm - if(event.getClickedBlock() == null) + if (event.getClickedBlock() == null) return; Block block = event.getClickedBlock(); @@ -841,7 +841,7 @@ public class PlayerListener implements Listener { HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager(); // FakePlayerAnimationEvent fakeSwing = new FakePlayerAnimationEvent(event.getPlayer(), PlayerAnimationType.ARM_SWING); //PlayerAnimationEvent compat - if(!event.isCancelled() || event.useInteractedBlock() != Event.Result.DENY) { + if (!event.isCancelled() || event.useInteractedBlock() != Event.Result.DENY) { //TODO: Is this code to set false from bone meal even needed? I'll have to double check later. if (heldItem.getType() == Material.BONE_MEAL) { switch (blockState.getType().toString()) { @@ -859,7 +859,7 @@ public class PlayerListener implements Listener { if (herbalismManager.canGreenThumbBlock(blockState)) { //call event for Green Thumb Block - if(!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, block).isCancelled()) { + if (!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, block).isCancelled()) { // Bukkit.getPluginManager().callEvent(fakeSwing); player.getInventory().getItemInMainHand().setAmount(heldItem.getAmount() - 1); player.updateInventory(); @@ -870,7 +870,7 @@ public class PlayerListener implements Listener { } /* SHROOM THUMB CHECK */ else if (herbalismManager.canUseShroomThumb(blockState)) { - if(!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_SHROOM_THUMB, block).isCancelled()) { + if (!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_SHROOM_THUMB, block).isCancelled()) { // Bukkit.getPluginManager().callEvent(fakeSwing); event.setCancelled(true); if (herbalismManager.processShroomThumb(blockState) @@ -885,7 +885,7 @@ public class PlayerListener implements Listener { break; case RIGHT_CLICK_AIR: - if(player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { + if (player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { break; } @@ -960,9 +960,9 @@ public class PlayerListener implements Listener { return; } - if(plugin.getChatManager().isChatChannelEnabled(mcMMOPlayer.getChatChannel())) { - if(mcMMOPlayer.getChatChannel() != ChatChannel.NONE) { - if(plugin.getChatManager().isMessageAllowed(mcMMOPlayer)) { + if (plugin.getChatManager().isChatChannelEnabled(mcMMOPlayer.getChatChannel())) { + if (mcMMOPlayer.getChatChannel() != ChatChannel.NONE) { + if (plugin.getChatManager().isMessageAllowed(mcMMOPlayer)) { //If the message is allowed we cancel this event to avoid double sending messages plugin.getChatManager().processPlayerMessage(mcMMOPlayer, event.getMessage(), event.isAsynchronous()); event.setCancelled(true); diff --git a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java index 0fe8eec9f..42303ef90 100644 --- a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java @@ -37,10 +37,10 @@ public class SelfListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //TODO: Handle proper validation at the event level - if(mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) + if (mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) return; - if(player.isOnline()) { + if (player.isOnline()) { //Players can gain multiple levels especially during xprate events for(int i = 0; i < event.getLevelsGained(); i++) { @@ -52,7 +52,7 @@ public class SelfListener implements Listener { //Reset the delay timer RankUtils.resetUnlockDelayTimer(); - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) ScoreboardManager.handleLevelUp(player, skill); } } @@ -61,8 +61,8 @@ public class SelfListener implements Listener { public void onPlayerXp(McMMOPlayerXpGainEvent event) { Player player = event.getPlayer(); - if(player.isOnline()) { - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (player.isOnline()) { + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) ScoreboardManager.handleXp(player, event.getSkill()); } } @@ -70,8 +70,8 @@ public class SelfListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onAbility(McMMOPlayerAbilityActivateEvent event) { Player player = event.getPlayer(); - if(player.isOnline()) { - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (player.isOnline()) { + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) ScoreboardManager.cooldownUpdate(event.getPlayer(), event.getSkill()); } } @@ -82,30 +82,30 @@ public class SelfListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //TODO: Handle proper validation at the event level - if(mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) + if (mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) return; PrimarySkillType primarySkillType = event.getSkill(); - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { mcMMOPlayer.getPlayer().sendMessage(event.getSkill().toString() + " XP Gained"); mcMMOPlayer.getPlayer().sendMessage("Incoming Raw XP: "+event.getRawXpGained()); } //WorldGuard XP Check - if(event.getXpGainReason() == XPGainReason.PVE || + if (event.getXpGainReason() == XPGainReason.PVE || event.getXpGainReason() == XPGainReason.PVP || event.getXpGainReason() == XPGainReason.SHARED_PVE || event.getXpGainReason() == XPGainReason.SHARED_PVP) { - if(WorldGuardUtils.isWorldGuardLoaded()) + if (WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasXPFlag(player)) + if (!WorldGuardManager.getInstance().hasXPFlag(player)) { event.setRawXpGained(0); event.setCancelled(true); - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { mcMMOPlayer.getPlayer().sendMessage("No WG XP Flag - New Raw XP: "+event.getRawXpGained()); } } @@ -117,13 +117,13 @@ public class SelfListener implements Listener { return; } - if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled()) + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled()) { int earlyGameBonusXP = 0; //Give some bonus XP for low levels - if(PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) + if (PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { earlyGameBonusXP += (mcMMOPlayer.getXpToLevel(primarySkillType) * 0.05); event.setRawXpGained(event.getRawXpGained() + earlyGameBonusXP); @@ -133,7 +133,7 @@ public class SelfListener implements Listener { int threshold = ExperienceConfig.getInstance().getDiminishedReturnsThreshold(primarySkillType); if (threshold <= 0 || !ExperienceConfig.getInstance().getDiminishedReturnsEnabled()) { - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { mcMMOPlayer.getPlayer().sendMessage("Final Raw XP: "+event.getRawXpGained()); } // Diminished returns is turned off @@ -167,7 +167,7 @@ public class SelfListener implements Listener { * Make sure players get a guaranteed minimum of XP */ //If there is no guaranteed minimum proceed, otherwise only proceed if newValue would be higher than our guaranteed minimum - if(guaranteedMinimum <= 0 || newValue > guaranteedMinimum) + if (guaranteedMinimum <= 0 || newValue > guaranteedMinimum) { if (newValue > 0) { event.setRawXpGained(newValue); @@ -181,7 +181,7 @@ public class SelfListener implements Listener { } - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { mcMMOPlayer.getPlayer().sendMessage("Final Raw XP: "+event.getRawXpGained()); } } diff --git a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java index 4c24930c6..aedecfea1 100644 --- a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java @@ -26,7 +26,7 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onStructureGrow(StructureGrowEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; // Using 50 ms later as I do not know of a way to run one tick later (safely) @@ -45,7 +45,7 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onWorldUnload(WorldUnloadEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; mcMMO.getPlaceStore().unloadWorld(event.getWorld()); @@ -59,7 +59,7 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onChunkUnload(ChunkUnloadEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; Chunk chunk = event.getChunk(); diff --git a/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java b/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java index e6a37d924..81ab06625 100644 --- a/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java +++ b/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java @@ -380,7 +380,7 @@ public final class LocaleLoader { * @return The message with the hex color codes translated to Minecraft color codes */ public static String translateHexColorCodes(String messageWithHex) { - if(messageWithHex == null) { + if (messageWithHex == null) { return null; } diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 61df1f745..0b3fe222b 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -207,7 +207,7 @@ public class mcMMO extends JavaPlugin { checkModConfigs(); } - if(projectKorraEnabled) { + if (projectKorraEnabled) { getLogger().info("ProjectKorra was detected, this can cause some issues with weakness potions and combat skills for mcMMO"); } @@ -228,7 +228,7 @@ public class mcMMO extends JavaPlugin { //Check for the newer API and tell them what to do if its missing checkForOutdatedAPI(); - if(serverAPIOutdated) + if (serverAPIOutdated) { foliaLib .getImpl() @@ -237,7 +237,7 @@ public class mcMMO extends JavaPlugin { 20, 20*60*30 ); - if(platformManager.getServerSoftware() == ServerSoftwareType.CRAFT_BUKKIT) + if (platformManager.getServerSoftware() == ServerSoftwareType.CRAFT_BUKKIT) { foliaLib .getImpl() @@ -280,11 +280,11 @@ public class mcMMO extends JavaPlugin { //If anonymous statistics are enabled then use them Metrics metrics; - if(generalConfig.getIsMetricsEnabled()) { + if (generalConfig.getIsMetricsEnabled()) { metrics = new Metrics(this, 3894); metrics.addCustomChart(new SimplePie("version", () -> getDescription().getVersion())); - if(generalConfig.getIsRetroMode()) + if (generalConfig.getIsRetroMode()) metrics.addCustomChart(new SimplePie("leveling_system", () -> "Retro")); else metrics.addCustomChart(new SimplePie("leveling_system", () -> "Standard")); @@ -323,7 +323,7 @@ public class mcMMO extends JavaPlugin { transientEntityTracker = new TransientEntityTracker(); setServerShutdown(false); //Reset flag, used to make decisions about async saves - if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { + if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { new PapiExpansion().register(); } } @@ -351,7 +351,7 @@ public class mcMMO extends JavaPlugin { @Override public void onLoad() { - if(getServer().getPluginManager().getPlugin("WorldGuard") != null) { + if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { WorldGuardManager.getInstance().registerFlags(); } @@ -372,11 +372,11 @@ public class mcMMO extends JavaPlugin { UserManager.saveAll(); // Make sure to save player information if the server shuts down UserManager.clearAll(); Alchemy.finishAllBrews(); // Finish all partially complete AlchemyBrewTasks to prevent vanilla brewing continuation on restart - if(partyConfig.isPartyEnabled()) + if (partyConfig.isPartyEnabled()) getPartyManager().saveParties(); // Save our parties //TODO: Needed? - if(generalConfig.getScoreboardsEnabled()) + if (generalConfig.getScoreboardsEnabled()) ScoreboardManager.teardownAll(); formulaManager.saveFormula(); @@ -615,7 +615,7 @@ public class mcMMO extends JavaPlugin { InteractionManager.initMaps(); //Init maps - if(CoreSkillsConfig.getInstance().isPrimarySkillEnabled(PrimarySkillType.ACROBATICS)) + if (CoreSkillsConfig.getInstance().isPrimarySkillEnabled(PrimarySkillType.ACROBATICS)) { LogUtils.debug(mcMMO.p.getLogger(), "Enabling Acrobatics Skills"); @@ -657,7 +657,7 @@ public class mcMMO extends JavaPlugin { } // Automatically remove old members from parties - if(partyConfig.isPartyEnabled()) { + if (partyConfig.isPartyEnabled()) { long kickIntervalTicks = generalConfig.getAutoPartyKickInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; if (kickIntervalTicks == 0) { @@ -675,7 +675,7 @@ public class mcMMO extends JavaPlugin { getFoliaLib().getImpl().runTimer(new ClearRegisteredXPGainTask(), 60, 60); } - if(mcMMO.p.getAdvancedConfig().allowPlayerTips()) + if (mcMMO.p.getAdvancedConfig().allowPlayerTips()) { getFoliaLib().getImpl().runTimer(new NotifySquelchReminderTask(), 60, ((20 * 60) * 60)); } diff --git a/src/main/java/com/gmail/nossr50/party/PartyManager.java b/src/main/java/com/gmail/nossr50/party/PartyManager.java index beff259d2..1a6300ac5 100644 --- a/src/main/java/com/gmail/nossr50/party/PartyManager.java +++ b/src/main/java/com/gmail/nossr50/party/PartyManager.java @@ -243,7 +243,7 @@ public final class PartyManager { } final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer == null) + if (mmoPlayer == null) return null; return mmoPlayer.getParty(); diff --git a/src/main/java/com/gmail/nossr50/party/ShareHandler.java b/src/main/java/com/gmail/nossr50/party/ShareHandler.java index 24392e6b1..77e905002 100644 --- a/src/main/java/com/gmail/nossr50/party/ShareHandler.java +++ b/src/main/java/com/gmail/nossr50/party/ShareHandler.java @@ -51,7 +51,7 @@ public final class ShareHandler { for (Player member : nearMembers) { //Profile not loaded - if(UserManager.getPlayer(member) == null) + if (UserManager.getPlayer(member) == null) { continue; } @@ -115,7 +115,7 @@ public final class ShareHandler { McMMOPlayer mcMMOMember = UserManager.getPlayer(member); //Profile not loaded - if(UserManager.getPlayer(member) == null) + if (UserManager.getPlayer(member) == null) { continue; } diff --git a/src/main/java/com/gmail/nossr50/runnables/MobDodgeMetaCleanup.java b/src/main/java/com/gmail/nossr50/runnables/MobDodgeMetaCleanup.java index 8087d3c65..cc0682910 100644 --- a/src/main/java/com/gmail/nossr50/runnables/MobDodgeMetaCleanup.java +++ b/src/main/java/com/gmail/nossr50/runnables/MobDodgeMetaCleanup.java @@ -17,7 +17,7 @@ public class MobDodgeMetaCleanup extends CancellableRunnable { @Override public void run() { - if(!mob.isValid() || mob.getTarget() == null) { + if (!mob.isValid() || mob.getTarget() == null) { mob.removeMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER, pluginRef); this.cancel(); } else if (!mob.hasMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER)) { diff --git a/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java b/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java index 613f3ecee..953c7d9ed 100644 --- a/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java @@ -19,7 +19,7 @@ public class SaveTimerTask extends CancellableRunnable { count++; } - if(mcMMO.p.getPartyConfig().isPartyEnabled()) + if (mcMMO.p.getPartyConfig().isPartyEnabled()) mcMMO.p.getPartyManager().saveParties(); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/TravelingBlockMetaCleanup.java b/src/main/java/com/gmail/nossr50/runnables/TravelingBlockMetaCleanup.java index 366fb2967..e982201dc 100644 --- a/src/main/java/com/gmail/nossr50/runnables/TravelingBlockMetaCleanup.java +++ b/src/main/java/com/gmail/nossr50/runnables/TravelingBlockMetaCleanup.java @@ -17,7 +17,7 @@ public class TravelingBlockMetaCleanup extends CancellableRunnable { @Override public void run() { - if(!entity.isValid()) { + if (!entity.isValid()) { entity.removeMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, pluginRef); this.cancel(); } else if (!entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK)) { diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java index ed1a2f73c..7ed51f3ad 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java @@ -45,14 +45,14 @@ public class MctopCommandDisplayTask extends CancellableRunnable { if (sender instanceof Player) { ((Player) sender).removeMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, mcMMO.p); } - if(sender instanceof Player) + if (sender instanceof Player) sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip")); } private void displayChat() { if (skill == null) { - if(sender instanceof Player) { + if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); } else { @@ -60,7 +60,7 @@ public class MctopCommandDisplayTask extends CancellableRunnable { } } else { - if(sender instanceof Player) { + if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); } else { @@ -74,7 +74,7 @@ public class MctopCommandDisplayTask extends CancellableRunnable { // Format: // 01. Playername - skill value // 12. Playername - skill value - if(sender instanceof Player) { + if (sender instanceof Player) { sender.sendMessage(String.format("%2d. %s%s - %s%s", place, ChatColor.GREEN, stat.name, ChatColor.WHITE, stat.statVal)); } else { diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java index 9b9fcd6fe..b9931d44e 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java @@ -11,9 +11,9 @@ public class NotifySquelchReminderTask extends CancellableRunnable { @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { - if(UserManager.getPlayer(player) != null) + if (UserManager.getPlayer(player) != null) { - if(!UserManager.getPlayer(player).useChatNotifications()) + if (!UserManager.getPlayer(player).useChatNotifications()) { player.sendMessage(LocaleLoader.getString("Reminder.Squelched")); } diff --git a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java index 6cd865055..e62df151f 100644 --- a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java @@ -44,7 +44,7 @@ public class PlayerProfileLoadingTask extends CancellableRunnable { PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(player); - if(!profile.isLoaded()) { + if (!profile.isLoaded()) { LogUtils.debug(mcMMO.p.getLogger(), "Creating new data for player: "+player.getName()); //Profile isn't loaded so add as new user profile = mcMMO.getDatabaseManager().newUser(player); diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java index a789171e0..3e63e5a89 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java @@ -62,7 +62,7 @@ public class AbilityDisableTask extends CancellableRunnable { if (mcMMO.p.getAdvancedConfig().sendAbilityNotificationToOtherPlayers()) { SkillUtils.sendSkillMessage(player, NotificationType.SUPER_ABILITY_ALERT_OTHERS, ability.getAbilityPlayerOff()); } - if(!mcMMO.isServerShutdownExecuted()) { + if (!mcMMO.isServerShutdownExecuted()) { mcMMO.p.getFoliaLib().getImpl().runAtEntityLater(player, new AbilityCooldownTask(mcMMOPlayer, ability), (long) PerksUtils.handleCooldownPerks(player, ability.getCooldown()) * Misc.TICK_CONVERSION_FACTOR); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java index 6ced4c66a..bd2e4ae1c 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java @@ -40,7 +40,7 @@ public class AwardCombatXpTask extends CancellableRunnable { damage += health; } - if(ExperienceConfig.getInstance().useCombatHPCeiling()) { + if (ExperienceConfig.getInstance().useCombatHPCeiling()) { damage = Math.min(damage, ExperienceConfig.getInstance().getCombatHPCeiling()); } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java index 0cb4d3d13..f67fa1e86 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java @@ -43,7 +43,7 @@ //// debugMessage+="RemainingTicks=["+containerEntry.getValue().bleedTicks+"], "; // // if (containerEntry.getValue().bleedTicks <= 0 || !target.isValid()) { -// if(target instanceof Player) +// if (target instanceof Player) // { // NotificationManager.sendPlayerInformation((Player) target, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Bleeding.Stopped"); // } @@ -96,7 +96,7 @@ // //// debugMessage+="FullArmor=["+String.valueOf(armorCount > 3)+"], "; // -// if(armorCount > 3) +// if (armorCount > 3) // { // damage = damage * .75; // } @@ -104,13 +104,13 @@ //// debugMessage+="AfterRankAndArmorChecks["+damage+"], "; // // //Weapons below Diamond get damage cut in half -// if(toolTier < 4) +// if (toolTier < 4) // damage = damage / 2; // //// debugMessage+="AfterDiamondCheck=["+String.valueOf(damage)+"], "; // // //Wood weapons get damage cut in half again -// if(toolTier < 2) +// if (toolTier < 2) // damage = damage / 2; // //// debugMessage+="AfterWoodenCheck=["+String.valueOf(damage)+"], "; @@ -129,7 +129,7 @@ // //// debugMessage+="TargetHealthAfterDMG=["+String.valueOf(target.getHealth())+"], "; // -// if(victimHealthAftermath <= 0 || victimHealth != victimHealthAftermath) +// if (victimHealthAftermath <= 0 || victimHealth != victimHealthAftermath) // { // //Play Bleed Sound // SoundManager.worldSendSound(target.getWorld(), target.getLocation(), SoundType.BLEED); @@ -187,7 +187,7 @@ // throw new IllegalStateException("Cannot add bleed task async!"); // } // -// if(isIterating) { +// if (isIterating) { // //Used to throw an error here, but in reality all we are really doing is preventing concurrency issues from other plugins being naughty and its not really needed // //I'm not really a fan of silent errors, but I'm sick of seeing people using crazy enchantments come in and report this "bug" // return; @@ -195,7 +195,7 @@ // //// if (isIterating) throw new IllegalStateException("Cannot add task while iterating timers!"); // -// if(toolTier < 4) +// if (toolTier < 4) // ticks = Math.max(1, (ticks / 3)); // // ticks+=1; diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java b/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java index 927e9a3f8..ecbe6e43f 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java @@ -35,7 +35,7 @@ public class DelayedCropReplant extends CancellableRunnable { public DelayedCropReplant(BlockBreakEvent blockBreakEvent, BlockState cropState, int desiredCropAge, boolean wasImmaturePlant) { BlockData cropData = cropState.getBlockData(); - if(cropData instanceof Directional cropDir) { + if (cropData instanceof Directional cropDir) { cropFace = cropDir.getFacing(); } @@ -56,13 +56,13 @@ public class DelayedCropReplant extends CancellableRunnable { //Remove the metadata marking the block as recently replanted mcMMO.p.getFoliaLib().getImpl().runAtLocationLater(blockBreakEvent.getBlock().getLocation(), new markPlantAsOld(blockBreakEvent.getBlock().getLocation()), 10); - if(blockBreakEvent.isCancelled()) { + if (blockBreakEvent.isCancelled()) { wasImmaturePlant = true; } //Two kinds of air in Minecraft - if(currentState.getType().equals(cropMaterial) || currentState.getType().equals(Material.AIR) || currentState.getType().equals(Material.CAVE_AIR)) { -// if(currentState.getBlock().getRelative(BlockFace.DOWN)) + if (currentState.getType().equals(cropMaterial) || currentState.getType().equals(Material.AIR) || currentState.getType().equals(Material.CAVE_AIR)) { +// if (currentState.getBlock().getRelative(BlockFace.DOWN)) //The space is not currently occupied by a block so we can fill it cropBlock.setType(cropMaterial); @@ -74,19 +74,19 @@ public class DelayedCropReplant extends CancellableRunnable { int age = 0; //Crop age should always be 0 if the plant was immature - if(!wasImmaturePlant) { + if (!wasImmaturePlant) { age = desiredCropAge; //Otherwise make the plant the desired age } - if(newData instanceof Directional) { + if (newData instanceof Directional) { //Cocoa Version Directional directional = (Directional) newState.getBlockData(); directional.setFacing(cropFace); newState.setBlockData(directional); - if(newData instanceof Cocoa) { + if (newData instanceof Cocoa) { plantAnchorType = PlantAnchorType.COCOA; } } @@ -119,7 +119,7 @@ public class DelayedCropReplant extends CancellableRunnable { this.plantBlock = plantBlock; this.plantAnchorType = plantAnchorType; - if(plantFace != null) { + if (plantFace != null) { this.plantFace = plantFace; } } @@ -140,8 +140,8 @@ public class DelayedCropReplant extends CancellableRunnable { private void checkPlantIntegrity(@NotNull BlockFace blockFace) { Block neighbor = plantBlock.getRelative(blockFace); - if(plantAnchorType == PlantAnchorType.COCOA) { - if(!neighbor.getType().toString().toLowerCase().contains("jungle")) { + if (plantAnchorType == PlantAnchorType.COCOA) { + if (!neighbor.getType().toString().toLowerCase().contains("jungle")) { plantBlock.breakNaturally(); } } else { @@ -171,7 +171,7 @@ public class DelayedCropReplant extends CancellableRunnable { @Override public void run() { Block cropBlock = cropLoc.getBlock(); - if(cropBlock.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() > 0) + if (cropBlock.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() > 0) cropBlock.setMetadata(MetadataConstants.METADATA_KEY_REPLANT, new RecentlyReplantedCropMeta(mcMMO.p, false)); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java index 34c87b0d4..816257f96 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java @@ -30,7 +30,7 @@ public class ExperienceBarHideTask extends CancellableRunnable { */ @Override public void run() { - if(experienceBarManagerRef == null || mcMMOPlayer == null) + if (experienceBarManagerRef == null || mcMMOPlayer == null) return; experienceBarManagerRef.hideExperienceBar(primarySkillType); diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java index 432d5a296..56dc1b406 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java @@ -42,15 +42,15 @@ public class RuptureTask extends CancellableRunnable { @Override public void run() { //Check validity - if(targetEntity.isValid()) { + if (targetEntity.isValid()) { ruptureTick += 1; //Advance rupture tick by 1. damageTickTracker += 1; //Increment damage tick tracker //TODO: Clean this code up, applyRupture() is a confusing name for something that returns boolean //Rupture hasn't ended yet - if(ruptureTick < expireTick) { + if (ruptureTick < expireTick) { //Is it time to damage? - if(damageTickTracker >= DAMAGE_TICK_INTERVAL) { + if (damageTickTracker >= DAMAGE_TICK_INTERVAL) { damageTickTracker = 0; //Reset timer if (applyRupture()) return; @@ -58,7 +58,7 @@ public class RuptureTask extends CancellableRunnable { playAnimation(); } } else { - if(!applyRupture()) { + if (!applyRupture()) { playAnimation(); } @@ -71,7 +71,7 @@ public class RuptureTask extends CancellableRunnable { } private void playAnimation() { - if(animationTick >= ANIMATION_TICK_INTERVAL) { + if (animationTick >= ANIMATION_TICK_INTERVAL) { ParticleEffectUtils.playBleedEffect(targetEntity); //Animate animationTick = 0; } else { @@ -114,7 +114,7 @@ public class RuptureTask extends CancellableRunnable { // // ParticleEffectUtils.playGreaterImpactEffect(targetEntity); //Animate // -// if(ruptureSource.getPlayer() != null && ruptureSource.getPlayer().isValid()) { +// if (ruptureSource.getPlayer() != null && ruptureSource.getPlayer().isValid()) { // targetEntity.damage(getExplosionDamage(), ruptureSource.getPlayer()); // } else { // targetEntity.damage(getExplosionDamage(), null); @@ -129,10 +129,10 @@ public class RuptureTask extends CancellableRunnable { private double calculateAdjustedTickDamage() { double tickDamage = pureTickDamage; - if(targetEntity.getHealth() <= tickDamage) { + if (targetEntity.getHealth() <= tickDamage) { tickDamage = targetEntity.getHealth() - 0.01; - if(tickDamage <= 0) { + if (tickDamage <= 0) { tickDamage = 0; } } diff --git a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java index 7ffbdbb34..a7d646df6 100644 --- a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java @@ -51,10 +51,10 @@ public class AcrobaticsManager extends SkillManager { public boolean canGainRollXP() { - if(!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) + if (!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) return true; - if(System.currentTimeMillis() >= rollXPCooldown) + if (System.currentTimeMillis() >= rollXPCooldown) { rollXPCooldown = System.currentTimeMillis() + rollXPInterval; rollXPIntervalLengthen = (1000 * 10); //5 Seconds @@ -67,10 +67,10 @@ public class AcrobaticsManager extends SkillManager { } public boolean canDodge(Entity damager) { - if(getPlayer().isBlocking()) + if (getPlayer().isBlocking()) return false; - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ACROBATICS_DODGE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ACROBATICS_DODGE)) return false; if (Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ACROBATICS_DODGE)) { @@ -103,14 +103,14 @@ public class AcrobaticsManager extends SkillManager { } if (SkillUtils.cooldownExpired(mmoPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { - if(attacker instanceof Mob mob) { + if (attacker instanceof Mob mob) { //Check to see how many dodge XP rewards this mob has handed out - if(mob.hasMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER) && ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { + if (mob.hasMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER) && ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { //If Dodge XP has been handed out 5 times then consider it being exploited MetadataValue metadataValue = mob.getMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER).get(0); int count = metadataValue.asInt(); - if(count <= 5) { + if (count <= 5) { applyXpGain((float) (damage * Acrobatics.dodgeXpModifier), XPGainReason.PVE); mob.setMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER, new FixedMetadataValue(mcMMO.p, count + 1)); MobDodgeMetaCleanup metaCleanupTask = new MobDodgeMetaCleanup(mob, mcMMO.p); diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index 6c28f64f9..223a1dd5b 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -85,7 +85,7 @@ public final class AlchemyPotionBrewer { } private static void removeIngredient(BrewerInventory inventory, Player player) { - if(inventory.getIngredient() == null) + if (inventory.getIngredient() == null) return; ItemStack ingredient = inventory.getIngredient().clone(); @@ -137,7 +137,7 @@ public final class AlchemyPotionBrewer { } private static List getValidIngredients(@Nullable McMMOPlayer mmoPlayer) { - if(mmoPlayer == null) { + if (mmoPlayer == null) { return mcMMO.p.getPotionConfig().getIngredients(1); } @@ -202,7 +202,7 @@ public final class AlchemyPotionBrewer { // Update the brewing inventory with the new potions for (int i = 0; i < 3; i++) { - if(outputList.get(i) != null) { + if (outputList.get(i) != null) { inventory.setItem(i, outputList.get(i)); } } diff --git a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java index 6aef4f92a..16574621b 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java @@ -27,21 +27,21 @@ public class ArcheryManager extends SkillManager { } public boolean canDaze(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_DAZE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_DAZE)) return false; return target instanceof Player && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_DAZE); } public boolean canSkillShot() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT); } public boolean canRetrieveArrows() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL); @@ -55,13 +55,13 @@ public class ArcheryManager extends SkillManager { */ public static double distanceXpBonusMultiplier(LivingEntity target, Entity arrow) { //Hacky Fix - some plugins spawn arrows and assign them to players after the ProjectileLaunchEvent fires - if(!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) return 1; Location firedLocation = (Location) arrow.getMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE).get(0).value(); Location targetLocation = target.getLocation(); - if(firedLocation == null || firedLocation.getWorld() == null) + if (firedLocation == null || firedLocation.getWorld() == null) return 1; if (firedLocation.getWorld() != targetLocation.getWorld()) { @@ -77,7 +77,7 @@ public class ArcheryManager extends SkillManager { * @param target The {@link LivingEntity} damaged by the arrow */ public void retrieveArrows(LivingEntity target, Projectile projectile) { - if(projectile.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { + if (projectile.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { Archery.incrementTrackerValue(target); projectile.removeMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, mcMMO.p); //Only 1 entity per projectile } diff --git a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java index 47d95be3f..b3eb84473 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java @@ -23,11 +23,11 @@ public class Axes { public static double skullSplitterModifier = mcMMO.p.getAdvancedConfig().getSkullSplitterModifier(); protected static boolean hasArmor(LivingEntity target) { - if(target == null || !target.isValid() || target.getEquipment() == null) + if (target == null || !target.isValid() || target.getEquipment() == null) return false; for (ItemStack itemStack : target.getEquipment().getArmorContents()) { - if(itemStack == null) + if (itemStack == null) continue; if (ItemUtils.isArmor(itemStack)) { diff --git a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java index edabb1a52..36abb05ff 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java @@ -28,35 +28,35 @@ public class AxesManager extends SkillManager { } public boolean canUseAxeMastery() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_AXE_MASTERY)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_AXE_MASTERY)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_AXE_MASTERY); } public boolean canCriticalHit(@NotNull LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES); } public boolean canImpact(@NotNull LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT) && Axes.hasArmor(target); } public boolean canGreaterImpact(@NotNull LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_GREATER_IMPACT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_GREATER_IMPACT)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_GREATER_IMPACT) && !Axes.hasArmor(target); } public boolean canUseSkullSplitter(@NotNull LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_SKULL_SPLITTER)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_SKULL_SPLITTER)) return false; return target.isValid() && mmoPlayer.getAbilityMode(SuperAbilityType.SKULL_SPLITTER) && Permissions.skullSplitter(getPlayer()); diff --git a/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java b/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java index a64b023af..1a60efd7d 100644 --- a/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java +++ b/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java @@ -31,7 +31,7 @@ public class Crossbows { } private static void processTrickShot(ProjectileHitEvent event, Plugin pluginRef, Arrow arrow, McMMOPlayer mmoPlayer) { - if(event.getHitBlock() != null && event.getHitBlockFace() != null) { + if (event.getHitBlock() != null && event.getHitBlockFace() != null) { mmoPlayer.getCrossbowsManager().handleRicochet( pluginRef, arrow, diff --git a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java index 671435d98..cde03fb72 100644 --- a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java @@ -28,7 +28,7 @@ public class CrossbowsManager extends SkillManager { } public void handleRicochet(@NotNull Plugin pluginRef, @NotNull Arrow arrow, @NotNull Vector hitBlockNormal) { - if(!arrow.isShotFromCrossbow()) + if (!arrow.isShotFromCrossbow()) return; // Check player permission diff --git a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java index 3735cfb8c..eadd72fea 100644 --- a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java +++ b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java @@ -66,7 +66,7 @@ public class ExcavationManager extends SkillManager { @VisibleForTesting public void processExcavationBonusesOnBlock(BlockState blockState, ExcavationTreasure treasure, Location location) { //Spawn Vanilla XP orbs if a dice roll succeeds - if(ProbabilityUtil.isStaticSkillRNGSuccessful( + if (ProbabilityUtil.isStaticSkillRNGSuccessful( PrimarySkillType.EXCAVATION, mmoPlayer, getArchaelogyExperienceOrbChance())) { Misc.spawnExperienceOrb(location, getExperienceOrbsReward()); } diff --git a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java index 8274cb1dc..9037ca280 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java @@ -74,15 +74,15 @@ public class FishingManager extends SkillManager { // { // long currentTime = System.currentTimeMillis(); // //Only track spam casting if the fishing hook is fresh -// if(currentTime > fishHookSpawnTimestamp + 1000) +// if (currentTime > fishHookSpawnTimestamp + 1000) // return; // -// if(currentTime < fishingRodCastTimestamp + FISHING_ROD_CAST_CD_MILLISECONDS) +// if (currentTime < fishingRodCastTimestamp + FISHING_ROD_CAST_CD_MILLISECONDS) // { // ItemStack fishingRod = getPlayer().getInventory().getItemInMainHand(); // // //Ensure correct hand item is damaged -// if(fishingRod.getType() != Material.FISHING_ROD) { +// if (fishingRod.getType() != Material.FISHING_ROD) { // fishingRod = getPlayer().getInventory().getItemInOffHand(); // } // @@ -90,7 +90,7 @@ public class FishingManager extends SkillManager { // fishingRod.setDurability((short) (fishingRod.getDurability() + 5)); // getPlayer().updateInventory(); // -// if(lastWarnedExhaust + (1000) < currentTime) +// if (lastWarnedExhaust + (1000) < currentTime) // { // getPlayer().sendMessage(LocaleLoader.getString("Fishing.Exhausting")); // lastWarnedExhaust = currentTime; @@ -103,7 +103,7 @@ public class FishingManager extends SkillManager { public void setFishHookReference(FishHook fishHook) { - if(fishHook.getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() > 0) + if (fishHook.getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() > 0) return; fishHook.setMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF, MetadataConstants.MCMMO_METADATA_VALUE); @@ -119,7 +119,7 @@ public class FishingManager extends SkillManager { long fishHookSpawnCD = fishHookSpawnTimestamp + 1000; boolean hasFished = (currentTime < fishHookSpawnCD); - if(hasFished && (lastWarned + (1000) < currentTime)) + if (hasFished && (lastWarned + (1000) < currentTime)) { getPlayer().sendMessage(LocaleLoader.getString("Fishing.Scared")); lastWarned = System.currentTimeMillis(); @@ -257,7 +257,7 @@ public class FishingManager extends SkillManager { public void processMasterAngler(@NotNull FishHook fishHook, int lureLevel) { MasterAnglerCompatibilityLayer masterAnglerCompatibilityLayer = (MasterAnglerCompatibilityLayer) mcMMO.getCompatibilityManager().getMasterAnglerCompatibilityLayer(); - if(masterAnglerCompatibilityLayer != null) { + if (masterAnglerCompatibilityLayer != null) { int maxWaitTicks = masterAnglerCompatibilityLayer.getMaxWaitTime(fishHook); int minWaitTicks = masterAnglerCompatibilityLayer.getMinWaitTime(fishHook); @@ -265,7 +265,7 @@ public class FishingManager extends SkillManager { int convertedLureBonus = 0; //This avoids a Minecraft bug where lure levels above 3 break fishing - if(lureLevel > 0) { + if (lureLevel > 0) { masterAnglerCompatibilityLayer.setApplyLure(fishHook, false); convertedLureBonus = lureLevel * 100; } @@ -284,15 +284,15 @@ public class FishingManager extends SkillManager { boolean badValuesFix = false; //If we find bad values correct it - if(reducedMaxWaitTime < reducedMinWaitTime) { + if (reducedMaxWaitTime < reducedMinWaitTime) { reducedMaxWaitTime = reducedMinWaitTime + 100; badValuesFix = true; } - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage(ChatColor.GOLD + "Master Angler Debug"); - if(badValuesFix) { + if (badValuesFix) { mmoPlayer.getPlayer().sendMessage(ChatColor.RED + "Bad values were applied and corrected, check your configs, max wait should never be lower than min wait."); } @@ -301,7 +301,7 @@ public class FishingManager extends SkillManager { mmoPlayer.getPlayer().sendMessage("MAX TICK REDUCTION: " + maxWaitReduction); mmoPlayer.getPlayer().sendMessage("BOAT BONUS: " + boatBonus); - if(boatBonus) { + if (boatBonus) { mmoPlayer.getPlayer().sendMessage("BOAT MAX TICK REDUCTION: " + maxWaitReduction); mmoPlayer.getPlayer().sendMessage("BOAT MIN TICK REDUCTION: " + maxWaitReduction); } @@ -341,7 +341,7 @@ public class FishingManager extends SkillManager { public int getMasterAnglerTickMaxWaitReduction(int masterAnglerRank, boolean boatBonus, int emulatedLureBonus) { int totalBonus = mcMMO.p.getAdvancedConfig().getFishingReductionMaxWaitTicks() * masterAnglerRank; - if(boatBonus) { + if (boatBonus) { totalBonus += getFishingBoatMaxWaitReduction(); } @@ -353,7 +353,7 @@ public class FishingManager extends SkillManager { public int getMasterAnglerTickMinWaitReduction(int masterAnglerRank, boolean boatBonus) { int totalBonus = mcMMO.p.getAdvancedConfig().getFishingReductionMinWaitTicks() * masterAnglerRank; - if(boatBonus) { + if (boatBonus) { totalBonus += getFishingBoatMinWaitReduction(); } @@ -394,7 +394,7 @@ public class FishingManager extends SkillManager { } if (treasure != null) { - if(treasure instanceof FishingTreasureBook) { + if (treasure instanceof FishingTreasureBook) { treasureDrop = ItemUtils.createEnchantBook((FishingTreasureBook) treasure); } else { treasureDrop = treasure.getDrop().clone(); // Not cloning is bad, m'kay? @@ -406,9 +406,9 @@ public class FishingManager extends SkillManager { /* * Books get some special treatment */ - if(treasure instanceof FishingTreasureBook) { + if (treasure instanceof FishingTreasureBook) { //Skip the magic hunter stuff - if(treasureDrop.getItemMeta() != null) { + if (treasureDrop.getItemMeta() != null) { enchants.putAll(treasureDrop.getItemMeta().getEnchants()); } @@ -430,7 +430,7 @@ public class FishingManager extends SkillManager { fishingSucceeds = true; boolean enchanted = false; - if(treasure instanceof FishingTreasureBook) { + if (treasure instanceof FishingTreasureBook) { enchanted = true; } else if (!enchants.isEmpty()) { treasureDrop.addUnsafeEnchantments(enchants); @@ -448,7 +448,7 @@ public class FishingManager extends SkillManager { } } - if(fishingSucceeds) { + if (fishingSucceeds) { if (mcMMO.p.getGeneralConfig().getFishingExtraFish()) { Misc.spawnItem(getPlayer(), player.getEyeLocation(), fishingCatch.getItemStack(), ItemSpawnReason.FISHING_EXTRA_FISH); } diff --git a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java index 34c990351..b60c33b7f 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java @@ -51,7 +51,7 @@ public class HerbalismManager extends SkillManager { } public boolean canGreenThumbBlock(BlockState blockState) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB)) return false; Player player = getPlayer(); @@ -61,11 +61,11 @@ public class HerbalismManager extends SkillManager { } public boolean canUseShroomThumb(BlockState blockState) { - if(!BlockUtils.canMakeShroomy(blockState)) { + if (!BlockUtils.canMakeShroomy(blockState)) { return false; } - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_SHROOM_THUMB)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_SHROOM_THUMB)) return false; Player player = getPlayer(); @@ -81,29 +81,29 @@ public class HerbalismManager extends SkillManager { public void processBerryBushHarvesting(@NotNull BlockState blockState) { /* Check if the player is harvesting a berry bush */ - if(blockState.getType().toString().equalsIgnoreCase("sweet_berry_bush")) { - if(mmoPlayer.isDebugMode()) { + if (blockState.getType().toString().equalsIgnoreCase("sweet_berry_bush")) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Processing sweet berry bush rewards"); } //Check the age - if(blockState.getBlockData() instanceof Ageable ageable) { + if (blockState.getBlockData() instanceof Ageable ageable) { int rewardByAge = 0; - if(ageable.getAge() == 2) { + if (ageable.getAge() == 2) { rewardByAge = 1; //Normal XP - } else if(ageable.getAge() == 3) { + } else if (ageable.getAge() == 3) { rewardByAge = 2; //Double XP } else { return; //Not old enough, back out of processing } - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Bush Reward Multiplier: " + rewardByAge); } int xpReward = ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, blockState) * rewardByAge; - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Bush XP: " + xpReward); } @@ -129,10 +129,10 @@ public class HerbalismManager extends SkillManager { public void run() { BlockState blockState = block.getState(); - if(blockState.getType().toString().equalsIgnoreCase("sweet_berry_bush")) { - if(blockState.getBlockData() instanceof Ageable ageable) { + if (blockState.getType().toString().equalsIgnoreCase("sweet_berry_bush")) { + if (blockState.getBlockData() instanceof Ageable ageable) { - if(ageable.getAge() <= 1) { + if (ageable.getAge() <= 1) { applyXpGain(xpReward, XPGainReason.PVE, XPGainSource.SELF); } } @@ -142,7 +142,7 @@ public class HerbalismManager extends SkillManager { public boolean canUseHylianLuck() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK); @@ -207,17 +207,17 @@ public class HerbalismManager extends SkillManager { Block block = blockBreakEvent.getBlock(); if (mcMMO.p.getGeneralConfig().getHerbalismPreventAFK() && player.isInsideVehicle()) { - if(block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) { + if (block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) { block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p); } return; } //Check if the plant was recently replanted - if(block.getBlockData() instanceof Ageable ageableCrop) { - if(block.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() >= 1) { - if(block.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).get(0).asBoolean()) { - if(isAgeableMature(ageableCrop)) { + if (block.getBlockData() instanceof Ageable ageableCrop) { + if (block.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() >= 1) { + if (block.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).get(0).asBoolean()) { + if (isAgeableMature(ageableCrop)) { block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p); } else { //Crop is recently replanted to back out of destroying it @@ -236,7 +236,7 @@ public class HerbalismManager extends SkillManager { //Grab all broken blocks HashSet brokenBlocks = getBrokenHerbalismBlocks(blockBreakEvent); - if(brokenBlocks.size() == 0) + if (brokenBlocks.size() == 0) return; //Handle rewards, xp, ability interactions, etc @@ -249,16 +249,16 @@ public class HerbalismManager extends SkillManager { * @param brokenPlants plant blocks to process */ private void processHerbalismOnBlocksBroken(BlockBreakEvent blockBreakEvent, HashSet brokenPlants) { - if(blockBreakEvent.isCancelled()) + if (blockBreakEvent.isCancelled()) return; BlockState originalBreak = blockBreakEvent.getBlock().getState(); boolean greenThumbActivated = false; //TODO: The design of Green Terra needs to change, this is a mess - if(Permissions.greenThumbPlant(getPlayer(), originalBreak.getType())) { - if(mcMMO.p.getGeneralConfig().isGreenThumbReplantableCrop(originalBreak.getType())) { - if(!getPlayer().isSneaking()) { + if (Permissions.greenThumbPlant(getPlayer(), originalBreak.getType())) { + if (mcMMO.p.getGeneralConfig().isGreenThumbReplantableCrop(originalBreak.getType())) { + if (!getPlayer().isSneaking()) { greenThumbActivated = processGreenThumbPlants(originalBreak, blockBreakEvent, isGreenTerraActive()); } } @@ -279,21 +279,21 @@ public class HerbalismManager extends SkillManager { /* * This check is to make XP bars appear to work properly with Chorus Trees by giving XP for the originalBreak immediately instead of later */ - if(brokenPlant.getLocation().equals(originalBreak.getBlock().getLocation())) { + if (brokenPlant.getLocation().equals(originalBreak.getBlock().getLocation())) { //If its the same block as the original, we are going to directly check it for being a valid XP gain and add it to the nonChorusBlocks list even if its a chorus block //This stops a delay from happening when bringing up the XP bar for chorus trees - if(!mcMMO.getPlaceStore().isTrue(originalBreak)) { + if (!mcMMO.getPlaceStore().isTrue(originalBreak)) { //Even if its a chorus block, the original break will be moved to nonChorusBlocks for immediate XP rewards noDelayPlantBlocks.add(brokenPlant); } else { - if(isChorusTree(brokenPlant.getType())) { + if (isChorusTree(brokenPlant.getType())) { //If its a chorus tree AND it was marked as true in the placestore then we add this block to the list of chorus blocks delayedChorusBlocks.add(new BlockSnapshot(brokenPlant.getType(), brokenPlant)); } else { noDelayPlantBlocks.add(brokenPlant); //If its not a chorus plant that was marked as unnatural but it was marked unnatural, put it in the nodelay list to be handled } } - } else if(isChorusTree(brokenPlant.getType())) { + } else if (isChorusTree(brokenPlant.getType())) { //Chorus Blocks get checked for XP several ticks later to avoid expensive calculations delayedChorusBlocks.add(new BlockSnapshot(brokenPlant.getType(), brokenPlant)); } else { @@ -302,12 +302,12 @@ public class HerbalismManager extends SkillManager { } //Give out XP to the non-chorus blocks - if(noDelayPlantBlocks.size() > 0) { + if (noDelayPlantBlocks.size() > 0) { //Note: Will contain 1 chorus block if the original block was a chorus block, this is to prevent delays for the XP bar awardXPForPlantBlocks(noDelayPlantBlocks); } - if(delayedChorusBlocks.size() > 0) { + if (delayedChorusBlocks.size() > 0) { //Check XP for chorus blocks DelayedHerbalismXPCheckTask delayedHerbalismXPCheckTask = new DelayedHerbalismXPCheckTask(mmoPlayer, delayedChorusBlocks); @@ -335,7 +335,7 @@ public class HerbalismManager extends SkillManager { BlockData plantData = brokenPlantState.getBlockData(); //Check for double drops - if(!mcMMO.getPlaceStore().isTrue(brokenPlant)) { + if (!mcMMO.getPlaceStore().isTrue(brokenPlant)) { /* * @@ -346,14 +346,14 @@ public class HerbalismManager extends SkillManager { */ //Not all things that are natural should give double drops, make sure its fully mature as well - if(plantData instanceof Ageable ageable) { + if (plantData instanceof Ageable ageable) { - if(isAgeableMature(ageable) || isBizarreAgeable(plantData)) { - if(checkDoubleDrop(brokenPlantState)) { + if (isAgeableMature(ageable) || isBizarreAgeable(plantData)) { + if (checkDoubleDrop(brokenPlantState)) { markForBonusDrops(brokenPlantState); } } - } else if(checkDoubleDrop(brokenPlantState)) { + } else if (checkDoubleDrop(brokenPlantState)) { //Add metadata to mark this block for double or triple drops markForBonusDrops(brokenPlantState); } @@ -366,7 +366,7 @@ public class HerbalismManager extends SkillManager { */ //If it's a Crop we need to reward XP when its fully grown - if(isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { + if (isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { //Add metadata to mark this block for double or triple drops markForBonusDrops(brokenPlantState); } @@ -380,7 +380,7 @@ public class HerbalismManager extends SkillManager { * @return returns true if the BlockData is a bizarre ageable for Herbalism XP / Rewards */ public boolean isBizarreAgeable(BlockData blockData) { - if(blockData instanceof Ageable) { + if (blockData instanceof Ageable) { //Catcus and Sugar Canes cannot be trusted return switch (blockData.getMaterial()) { case CACTUS, KELP, SUGAR_CANE, BAMBOO -> true; @@ -413,7 +413,7 @@ public class HerbalismManager extends SkillManager { BlockState brokenBlockNewState = brokenPlantBlock.getState(); BlockData plantData = brokenBlockNewState.getBlockData(); - if(mcMMO.getPlaceStore().isTrue(brokenBlockNewState)) { + if (mcMMO.getPlaceStore().isTrue(brokenBlockNewState)) { /* * * Unnatural Blocks @@ -422,7 +422,7 @@ public class HerbalismManager extends SkillManager { */ //If its a Crop we need to reward XP when its fully grown - if(isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { + if (isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { xpToReward += ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, brokenBlockNewState.getType()); } @@ -437,9 +437,9 @@ public class HerbalismManager extends SkillManager { */ //Calculate XP - if(plantData instanceof Ageable plantAgeable) { + if (plantData instanceof Ageable plantAgeable) { - if(isAgeableMature(plantAgeable) || isBizarreAgeable(plantData)) { + if (isAgeableMature(plantAgeable) || isBizarreAgeable(plantData)) { xpToReward += ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, brokenBlockNewState.getType()); } @@ -449,12 +449,12 @@ public class HerbalismManager extends SkillManager { } } - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Plants processed: "+brokenPlants.size()); } //Reward XP - if(xpToReward > 0) { + if (xpToReward > 0) { applyXpGain(xpToReward, XPGainReason.PVE, XPGainSource.SELF); } } @@ -480,16 +480,16 @@ public class HerbalismManager extends SkillManager { BlockState brokenBlockNewState = blockSnapshot.getBlockRef().getState(); //Remove metadata from the snapshot of blocks - if(brokenBlockNewState.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) { + if (brokenBlockNewState.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) { brokenBlockNewState.removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, mcMMO.p); } //If the block is not AIR that means it wasn't broken - if(brokenBlockNewState.getType() != Material.AIR) { + if (brokenBlockNewState.getType() != Material.AIR) { continue; } - if(mcMMO.getPlaceStore().isTrue(brokenBlockNewState)) { + if (mcMMO.getPlaceStore().isTrue(brokenBlockNewState)) { //Mark it as natural again as it is being broken mcMMO.getPlaceStore().setFalse(brokenBlockNewState); } else { @@ -500,13 +500,13 @@ public class HerbalismManager extends SkillManager { } } - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Chorus Plants checked for XP: "+brokenPlants.size()); mmoPlayer.getPlayer().sendMessage("Valid Chorus Plant XP Gains: "+blocksGivingXP); } //Reward XP - if(xpToReward > 0) { + if (xpToReward > 0) { applyXpGain(xpToReward, XPGainReason.PVE, XPGainSource.SELF); } } @@ -525,7 +525,7 @@ public class HerbalismManager extends SkillManager { //Add the initial block blocksBroken.add(originBlockState.getBlock()); - if(!isOneBlockPlant(originBlockMaterial)) { + if (!isOneBlockPlant(originBlockMaterial)) { //If the block is a multi-block structure, capture a set of all blocks broken and return that blocksBroken = getBrokenBlocksMultiBlockPlants(originBlockState); } @@ -602,7 +602,7 @@ public class HerbalismManager extends SkillManager { Block block = originBlock.getBlock(); //Add the initial block to the set - if(inclusive) + if (inclusive) brokenBlocks.add(block); //Limit our search @@ -796,7 +796,7 @@ public class HerbalismManager extends SkillManager { return false; } - if(EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, blockState.getBlock()) + if (EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, blockState.getBlock()) .isCancelled()) { return false; } else { @@ -815,7 +815,7 @@ public class HerbalismManager extends SkillManager { private boolean processGrowingPlants(BlockState blockState, Ageable ageable, BlockBreakEvent blockBreakEvent, boolean greenTerra) { //This check is needed - if(isBizarreAgeable(ageable)) { + if (isBizarreAgeable(ageable)) { return false; } @@ -823,7 +823,7 @@ public class HerbalismManager extends SkillManager { int greenThumbStage = getGreenThumbStage(greenTerra); //Immature plants will start over at 0 - if(!isAgeableMature(ageable)) { + if (!isAgeableMature(ageable)) { // blockBreakEvent.setCancelled(true); startReplantTask(0, blockBreakEvent, blockState, true); // blockState.setType(Material.AIR); @@ -875,7 +875,7 @@ public class HerbalismManager extends SkillManager { } private int getGreenThumbStage(boolean greenTerraActive) { - if(greenTerraActive) + if (greenTerraActive) return Math.min(RankUtils.getHighestRank(SubSkillType.HERBALISM_GREEN_THUMB), RankUtils.getRank(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB) + 1); diff --git a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java index 98b8cf8b6..281831295 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java @@ -64,7 +64,7 @@ public class BlastMining { for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) { - if(getBlastDamageDecrease(i+1) > 0) + if (getBlastDamageDecrease(i+1) > 0) return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i+1); } @@ -83,7 +83,7 @@ public class BlastMining { for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) { - if(getBlastRadiusModifier(i+1) > 0) + if (getBlastRadiusModifier(i+1) > 0) return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i+1); } @@ -102,7 +102,7 @@ public class BlastMining { return false; } - if(UserManager.getPlayer(defender) == null) + if (UserManager.getPlayer(defender) == null) { return false; } diff --git a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java index 231941acc..1d8738de2 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java @@ -40,7 +40,7 @@ public class MiningManager extends SkillManager { } public boolean canUseDemolitionsExpertise() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_DEMOLITIONS_EXPERTISE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_DEMOLITIONS_EXPERTISE)) return false; return getSkillLevel() >= BlastMining.getDemolitionExpertUnlockLevel() && Permissions.demolitionsExpertise(getPlayer()); @@ -60,7 +60,7 @@ public class MiningManager extends SkillManager { } public boolean canUseBiggerBombs() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_BIGGER_BOMBS)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_BIGGER_BOMBS)) return false; return getSkillLevel() >= BlastMining.getBiggerBombsUnlockLevel() && Permissions.biggerBombs(getPlayer()); @@ -93,18 +93,18 @@ public class MiningManager extends SkillManager { SkillUtils.handleDurabilityChange(getPlayer().getInventory().getItemInMainHand(), mcMMO.p.getGeneralConfig().getAbilityToolDamage()); } - if(!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, blockState.getType()) || !canDoubleDrop()) + if (!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, blockState.getType()) || !canDoubleDrop()) return; boolean silkTouch = player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH); - if(silkTouch && !mcMMO.p.getAdvancedConfig().getDoubleDropSilkTouchEnabled()) + if (silkTouch && !mcMMO.p.getAdvancedConfig().getDoubleDropSilkTouchEnabled()) return; //Mining mastery allows for a chance of triple drops - if(canMotherLode()) { + if (canMotherLode()) { //Triple Drops failed so do a normal double drops check - if(!processTripleDrops(blockState)) { + if (!processTripleDrops(blockState)) { processDoubleDrops(blockState); } } else { @@ -182,7 +182,7 @@ public class MiningManager extends SkillManager { if (ExperienceConfig.getInstance().getXp(PrimarySkillType.MINING, targetBlock) != 0 && !(targetBlock instanceof Container) && !mcMMO.getPlaceStore().isTrue(targetBlock)) { - if(BlockUtils.isOre(blockState)) { + if (BlockUtils.isOre(blockState)) { ores.add(blockState); } else { notOres.add(blockState); @@ -199,16 +199,16 @@ public class MiningManager extends SkillManager { //Drop "debris" based on skill modifiers for(BlockState blockState : notOres) { - if(isDropIllegal(blockState.getType())) + if (isDropIllegal(blockState.getType())) continue; - if(RandomUtils.nextFloat() < debrisYield) { + if (RandomUtils.nextFloat() < debrisYield) { Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_DEBRIS_NON_ORES); // Initial block that would have been dropped } } for (BlockState blockState : ores) { - if(isDropIllegal(blockState.getType())) + if (isDropIllegal(blockState.getType())) continue; if (RandomUtils.nextFloat() < (yield + oreBonus)) { diff --git a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java index 8186723cf..555d17313 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java @@ -66,8 +66,8 @@ public class RepairManager extends SkillManager { Player player = getPlayer(); Repairable repairable = mcMMO.getRepairableManager().getRepairable(item.getType()); if (item.getItemMeta() != null) { - if(item.getItemMeta().hasCustomModelData()) { - if(!mcMMO.p.getCustomItemSupportConfig().isCustomRepairAllowed()) { + if (item.getItemMeta().hasCustomModelData()) { + if (!mcMMO.p.getCustomItemSupportConfig().isCustomRepairAllowed()) { NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Anvil.Repair.Reject.CustomModelData"); return; @@ -326,7 +326,7 @@ public class RepairManager extends SkillManager { * @return true if bonus granted, false otherwise */ private boolean checkPlayerProcRepair() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.REPAIR_SUPER_REPAIR)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.REPAIR_SUPER_REPAIR)) return false; if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.REPAIR_SUPER_REPAIR, mmoPlayer)) { @@ -370,8 +370,8 @@ public class RepairManager extends SkillManager { for (Entry enchant : enchants.entrySet()) { int enchantLevel = enchant.getValue(); - if(!ExperienceConfig.getInstance().allowUnsafeEnchantments()) { - if(enchantLevel > enchant.getKey().getMaxLevel()) { + if (!ExperienceConfig.getInstance().allowUnsafeEnchantments()) { + if (enchantLevel > enchant.getKey().getMaxLevel()) { enchantLevel = enchant.getKey().getMaxLevel(); item.addEnchantment(enchant.getKey(), enchantLevel); diff --git a/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java b/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java index de201456d..2849c9dae 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java @@ -67,7 +67,7 @@ public class SimpleRepairable implements Repairable { @Override public int getMinimumQuantity() { - if(minQuantity == -1) + if (minQuantity == -1) return Math.max(SkillUtils.getRepairAndSalvageQuantities(itemMaterial, repairMaterial), 1); else return minQuantity; diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java index 5e477825d..fe8e132c9 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java @@ -125,7 +125,7 @@ public class SalvageManager extends SkillManager { for(int x = 0; x < potentialSalvageYield-1; x++) { - if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, mmoPlayer, chanceOfSuccess)) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, mmoPlayer, chanceOfSuccess)) { chanceOfSuccess-=3; chanceOfSuccess = Math.max(chanceOfSuccess, 90); @@ -196,7 +196,7 @@ public class SalvageManager extends SkillManager { } public double getExtractFullEnchantChance() { - if(Permissions.hasSalvageEnchantBypassPerk(getPlayer())) + if (Permissions.hasSalvageEnchantBypassPerk(getPlayer())) return 100.0D; return mcMMO.p.getAdvancedConfig().getArcaneSalvageExtractFullEnchantsChance(getArcaneSalvageRank()); @@ -224,8 +224,8 @@ public class SalvageManager extends SkillManager { int enchantLevel = enchant.getValue(); - if(!ExperienceConfig.getInstance().allowUnsafeEnchantments()) { - if(enchantLevel > enchant.getKey().getMaxLevel()) { + if (!ExperienceConfig.getInstance().allowUnsafeEnchantments()) { + if (enchantLevel > enchant.getKey().getMaxLevel()) { enchantLevel = enchant.getKey().getMaxLevel(); } } @@ -247,11 +247,11 @@ public class SalvageManager extends SkillManager { } } - if(failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) + if (failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) { NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcaneFailed"); return null; - } else if(downgraded) + } else if (downgraded) { NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcanePartial"); } diff --git a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java index 7fae80419..4b667d86e 100644 --- a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java @@ -73,7 +73,7 @@ public class SmeltingManager extends SkillManager { FurnaceInventory furnaceInventory = furnace.getInventory(); ItemStack furnaceResult = furnaceInventory.getResult(); - if(furnaceResult == null) + if (furnaceResult == null) return true; //This actually means there is nothing yet in the resulting item slot, which means it should always be okay to double smelt int resultAmount = furnaceResult.getAmount(); //Amount before double smelt diff --git a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java index 66c16f77d..5e02747b8 100644 --- a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java @@ -41,14 +41,14 @@ public class SwordsManager extends SkillManager { } public boolean canUseCounterAttack(Entity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK)) return false; return target instanceof LivingEntity && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK); } public boolean canUseSerratedStrike() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_SERRATED_STRIKES)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_SERRATED_STRIKES)) return false; return mmoPlayer.getAbilityMode(SuperAbilityType.SERRATED_STRIKES); @@ -60,13 +60,13 @@ public class SwordsManager extends SkillManager { * @param target The defending entity */ public void processRupture(@NotNull LivingEntity target) { - if(!canUseRupture()) + if (!canUseRupture()) return; - if(target.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { + if (target.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { RuptureTaskMeta ruptureTaskMeta = (RuptureTaskMeta) target.getMetadata(MetadataConstants.METADATA_KEY_RUPTURE).get(0); - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Rupture task ongoing for target " + target.toString()); mmoPlayer.getPlayer().sendMessage(ruptureTaskMeta.getRuptureTimerTask().toString()); } @@ -81,7 +81,7 @@ public class SwordsManager extends SkillManager { if (target instanceof Player defender) { //Don't start or add to a bleed if they are blocking - if(defender.isBlocking()) + if (defender.isBlocking()) return; if (NotificationManager.doesPlayerUseNotifications(defender)) { @@ -112,7 +112,7 @@ public class SwordsManager extends SkillManager { { int rank = RankUtils.getRank(getPlayer(), SubSkillType.SWORDS_STAB); - if(rank > 0) + if (rank > 0) { return (1.0D + (rank * 1.5)); } @@ -122,13 +122,13 @@ public class SwordsManager extends SkillManager { public int getToolTier(@NotNull ItemStack itemStack) { - if(ItemUtils.isNetheriteTool(itemStack)) + if (ItemUtils.isNetheriteTool(itemStack)) return 5; - if(ItemUtils.isDiamondTool(itemStack)) + if (ItemUtils.isDiamondTool(itemStack)) return 4; - else if(ItemUtils.isIronTool(itemStack) || ItemUtils.isGoldTool(itemStack)) + else if (ItemUtils.isIronTool(itemStack) || ItemUtils.isGoldTool(itemStack)) return 3; - else if(ItemUtils.isStoneTool(itemStack)) + else if (ItemUtils.isStoneTool(itemStack)) return 2; else return 1; diff --git a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java index 927c51e1b..9cb609e94 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java @@ -59,7 +59,7 @@ public class TamingManager extends SkillManager { private void initStaticCaches() { //TODO: Temporary static cache, will be changed in 2.2 //This is shared between instances of TamingManager - if(summoningItems == null) { + if (summoningItems == null) { summoningItems = new HashMap<>(); summoningItems.put(mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry()), CallOfTheWildType.CAT); @@ -69,7 +69,7 @@ public class TamingManager extends SkillManager { //TODO: Temporary static cache, will be changed in 2.2 //This is shared between instances of TamingManager - if(cotwSummonDataProperties == null) { + if (cotwSummonDataProperties == null) { cotwSummonDataProperties = new HashMap<>(); for(CallOfTheWildType callOfTheWildType : CallOfTheWildType.values()) { @@ -116,14 +116,14 @@ public class TamingManager extends SkillManager { } public boolean canUseGore() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_GORE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_GORE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.TAMING_GORE); } public boolean canUseBeastLore() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_BEAST_LORE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_BEAST_LORE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.TAMING_BEAST_LORE); @@ -178,7 +178,7 @@ public class TamingManager extends SkillManager { * Summon an ocelot to your side. */ public void summonOcelot() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.OCELOT)) { @@ -192,7 +192,7 @@ public class TamingManager extends SkillManager { * Summon a wolf to your side. */ public void summonWolf() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.WOLF)) { @@ -206,7 +206,7 @@ public class TamingManager extends SkillManager { * Summon a horse to your side. */ public void summonHorse() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.HORSE)) { @@ -237,7 +237,7 @@ public class TamingManager extends SkillManager { if (beast instanceof AbstractHorse horseLikeCreature && !(beast instanceof Llama)) { AttributeInstance jumpAttribute = horseLikeCreature.getAttribute(mcMMO.p.getAttributeMapper().getHorseJumpStrength()); - if(jumpAttribute != null) { + if (jumpAttribute != null) { double jumpStrength = jumpAttribute.getValue(); // Taken from https://minecraft.wiki/w/Horse#Jump_strength jumpStrength = -0.1817584952 * Math.pow(jumpStrength, 3) + 3.689713992 * Math.pow(jumpStrength, 2) + 2.128599134 * jumpStrength - 0.343930367; @@ -261,10 +261,10 @@ public class TamingManager extends SkillManager { } public void pummel(LivingEntity target, Wolf wolf) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) return; - if(!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.TAMING, mmoPlayer, mcMMO.p.getAdvancedConfig().getPummelChance())) + if (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.TAMING, mmoPlayer, mcMMO.p.getAdvancedConfig().getPummelChance())) return; ParticleEffectUtils.playGreaterImpactEffect(target); @@ -279,9 +279,9 @@ public class TamingManager extends SkillManager { } public void attackTarget(LivingEntity target) { - if(target instanceof Tameable tameable) + if (target instanceof Tameable tameable) { - if(tameable.getOwner() == getPlayer()) + if (tameable.getOwner() == getPlayer()) { return; } @@ -307,7 +307,7 @@ public class TamingManager extends SkillManager { private void processCallOfTheWild() { //Prevent summoning too many things accidentally if a player holds down the button - if(lastSummonTimeStamp + 150 > System.currentTimeMillis()) { + if (lastSummonTimeStamp + 150 > System.currentTimeMillis()) { return; } else { lastSummonTimeStamp = System.currentTimeMillis(); @@ -317,7 +317,7 @@ public class TamingManager extends SkillManager { ItemStack itemInMainHand = player.getInventory().getItemInMainHand(); //Check if the item the player is currently holding is a COTW item - if(isCOTWItem(itemInMainHand)) { + if (isCOTWItem(itemInMainHand)) { //Get the summoning type CallOfTheWildType callOfTheWildType = summoningItems.get(itemInMainHand.getType()); TamingSummon tamingSummon = cotwSummonDataProperties.get(callOfTheWildType); @@ -326,7 +326,7 @@ public class TamingManager extends SkillManager { int amountSummoned = 0; //Check to see if players have the correct amount of the item required to summon - if(itemInMainHand.getAmount() >= tamingSummon.getItemAmountRequired()) { + if (itemInMainHand.getAmount() >= tamingSummon.getItemAmountRequired()) { //Initial Spawn location Location spawnLocation = Misc.getLocationOffset(player.getLocation(), 1); @@ -358,7 +358,7 @@ public class TamingManager extends SkillManager { } //Remove items from the player if they had at least one entity summoned successfully - if(amountSummoned >= 1) { + if (amountSummoned >= 1) { //Remove the items used to summon int itemAmountAfterPayingCost = itemInMainHand.getAmount() - tamingSummon.getItemAmountRequired(); itemInMainHand.setAmount(itemAmountAfterPayingCost); @@ -412,11 +412,11 @@ public class TamingManager extends SkillManager { addToTracker(callOfWildEntity, CallOfTheWildType.CAT); //Randomize the cat - if(callOfWildEntity instanceof Ocelot) { + if (callOfWildEntity instanceof Ocelot) { int numberOfTypes = Ocelot.Type.values().length; ((Ocelot) callOfWildEntity).setCatType(Ocelot.Type.values()[Misc.getRandom().nextInt(numberOfTypes)]); ((Ocelot) callOfWildEntity).setAdult(); - } else if(callOfWildEntity instanceof Cat) { + } else if (callOfWildEntity instanceof Cat) { int numberOfTypes = Cat.Type.values().length; ((Cat) callOfWildEntity).setCatType(Cat.Type.values()[Misc.getRandom().nextInt(numberOfTypes)]); ((Cat) callOfWildEntity).setAdult(); diff --git a/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java b/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java index 23a8a1330..fcacc014c 100644 --- a/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java @@ -14,9 +14,9 @@ public class TridentsManager extends SkillManager { public double impaleDamageBonus() { int rank = RankUtils.getRank(getPlayer(), SubSkillType.TRIDENTS_IMPALE); - if(rank > 1) { + if (rank > 1) { return (1.0D + (rank * .5D)); - } else if(rank == 1) { + } else if (rank == 1) { return 1.0D; } diff --git a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java index cb1124dd4..d81957ae1 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java @@ -21,24 +21,24 @@ public class Unarmed { for(int i = 0; i <= storageContents.length-1; i++) { - if(amount <= 0) + if (amount <= 0) break; - if(i == heldItemSlotID) + if (i == heldItemSlotID) continue; //EMPTY SLOT! - if(storageContents[i] == null) + if (storageContents[i] == null) { player.getInventory().setItem(i, itemDrop); amount = 0; grabbedItem = true; break; } - else if(itemDrop.isSimilar(storageContents[i]) && storageContents[i].getAmount() < storageContents[i].getMaxStackSize()) + else if (itemDrop.isSimilar(storageContents[i]) && storageContents[i].getAmount() < storageContents[i].getMaxStackSize()) { //If we can fit this whole itemstack into this item - if(amount + storageContents[i].getAmount() <= storageContents[i].getMaxStackSize()) + if (amount + storageContents[i].getAmount() <= storageContents[i].getMaxStackSize()) { ItemStack modifiedAmount = storageContents[i]; modifiedAmount.setAmount(amount + storageContents[i].getAmount()); @@ -61,14 +61,14 @@ public class Unarmed { } } - if(amount <= 0) + if (amount <= 0) event.getItem().remove(); //Cleanup Item else event.getItem().getItemStack().setAmount(amount); event.setCancelled(true); - if(grabbedItem) + if (grabbedItem) { SoundManager.sendSound(player, player.getLocation(), SoundType.POP); player.updateInventory(); diff --git a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java index d4dc4faf9..933dbb8f4 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java @@ -33,7 +33,7 @@ public class UnarmedManager extends SkillManager { } public boolean canUseSteelArm() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE); @@ -44,14 +44,14 @@ public class UnarmedManager extends SkillManager { } public boolean canDisarm(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_DISARM)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_DISARM)) return false; return target instanceof Player && ((Player) target).getInventory().getItemInMainHand().getType() != Material.AIR && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_DISARM); } public boolean canDeflect() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_ARROW_DEFLECT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_ARROW_DEFLECT)) return false; Player player = getPlayer(); @@ -60,7 +60,7 @@ public class UnarmedManager extends SkillManager { } public boolean canUseBlockCracker() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER); @@ -103,7 +103,7 @@ public class UnarmedManager extends SkillManager { return; } - if(UserManager.getPlayer(defender) == null) + if (UserManager.getPlayer(defender) == null) return; Item item = Misc.spawnItem(getPlayer(), defender.getLocation(), defender.getInventory().getItemInMainHand(), ItemSpawnReason.UNARMED_DISARMED_ITEM); @@ -156,13 +156,13 @@ public class UnarmedManager extends SkillManager { double bonus = 0; - if(rank >= 18) + if (rank >= 18) bonus = 1 + rank - 18; double finalBonus = bonus + 0.5 + (rank / 2); - if(mcMMO.p.getAdvancedConfig().isSteelArmDamageCustom()) { + if (mcMMO.p.getAdvancedConfig().isSteelArmDamageCustom()) { return mcMMO.p.getAdvancedConfig().getSteelArmOverride(RankUtils.getRank(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE), finalBonus); } else { return finalBonus; diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java index 66270dfc6..877f0cc24 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java @@ -90,22 +90,22 @@ public class WoodcuttingManager extends SkillManager { */ public void processBonusDropCheck(@NotNull BlockState blockState) { //TODO: Why isn't this using the item drop event? Potentially because of Tree Feller? This should be adjusted either way. - if(mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, blockState.getType())) { + if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, blockState.getType())) { //Mastery enabled for player - if(Permissions.canUseSubSkill(getPlayer(), SubSkillType.WOODCUTTING_CLEAN_CUTS)) { - if(checkCleanCutsActivation(blockState.getType())) { + if (Permissions.canUseSubSkill(getPlayer(), SubSkillType.WOODCUTTING_CLEAN_CUTS)) { + if (checkCleanCutsActivation(blockState.getType())) { //Triple drops spawnHarvestLumberBonusDrops(blockState); spawnHarvestLumberBonusDrops(blockState); } else { //Harvest Lumber Check - if(checkHarvestLumberActivation(blockState.getType())) { + if (checkHarvestLumberActivation(blockState.getType())) { spawnHarvestLumberBonusDrops(blockState); } } //No Mastery (no Clean Cuts) } else if (Permissions.canUseSubSkill(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER)) { - if(checkHarvestLumberActivation(blockState.getType())) { + if (checkHarvestLumberActivation(blockState.getType())) { spawnHarvestLumberBonusDrops(blockState); } } @@ -113,7 +113,7 @@ public class WoodcuttingManager extends SkillManager { } public void processWoodcuttingBlockXP(@NotNull BlockState blockState) { - if(mcMMO.getPlaceStore().isTrue(blockState)) + if (mcMMO.getPlaceStore().isTrue(blockState)) return; int xp = getExperienceFromLog(blockState); @@ -333,10 +333,10 @@ public class WoodcuttingManager extends SkillManager { } //Drop displaced non-woodcutting XP blocks - if(RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { - if(RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { - if(mcMMO.p.getAdvancedConfig().isKnockOnWoodXPOrbEnabled()) { - if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.WOODCUTTING, mmoPlayer, 10)) { + if (RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { + if (RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { + if (mcMMO.p.getAdvancedConfig().isKnockOnWoodXPOrbEnabled()) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.WOODCUTTING, mmoPlayer, 10)) { int randOrbCount = Math.max(1, Misc.getRandom().nextInt(100)); Misc.spawnExperienceOrb(blockState.getLocation(), randOrbCount); } @@ -356,7 +356,7 @@ public class WoodcuttingManager extends SkillManager { } private int updateProcessedLogCount(int xp, int processedLogCount, int beforeXP) { - if(beforeXP != xp) + if (beforeXP != xp) processedLogCount+=1; return processedLogCount; @@ -373,15 +373,15 @@ public class WoodcuttingManager extends SkillManager { * @return Amount of experience */ private static int processTreeFellerXPGains(BlockState blockState, int woodCount) { - if(mcMMO.getPlaceStore().isTrue(blockState)) + if (mcMMO.getPlaceStore().isTrue(blockState)) return 0; int rawXP = ExperienceConfig.getInstance().getXp(PrimarySkillType.WOODCUTTING, blockState.getType()); - if(rawXP <= 0) + if (rawXP <= 0) return 0; - if(ExperienceConfig.getInstance().isTreeFellerXPReduced()) { + if (ExperienceConfig.getInstance().isTreeFellerXPReduced()) { int reducedXP = rawXP - (woodCount * 5); rawXP = Math.max(1, reducedXP); return rawXP; diff --git a/src/main/java/com/gmail/nossr50/util/BlockUtils.java b/src/main/java/com/gmail/nossr50/util/BlockUtils.java index d18a0e6d6..56d1d698d 100644 --- a/src/main/java/com/gmail/nossr50/util/BlockUtils.java +++ b/src/main/java/com/gmail/nossr50/util/BlockUtils.java @@ -68,7 +68,7 @@ public final class BlockUtils { mcMMO.getPlaceStore().setTrue(block); // Failsafe against lingering metadata - if(block.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (block.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) block.removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, mcMMO.p); } @@ -78,7 +78,7 @@ public final class BlockUtils { * @param block target block */ public static void cleanupBlockMetadata(Block block) { - if(block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) { + if (block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) { block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p); } @@ -207,7 +207,7 @@ public final class BlockUtils { * otherwise */ public static boolean affectedBySuperBreaker(BlockState blockState) { - if(mcMMO.getMaterialMapStore().isIntendedToolPickaxe(blockState.getType())) + if (mcMMO.getMaterialMapStore().isIntendedToolPickaxe(blockState.getType())) return true; if (ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, blockState.getBlockData())) diff --git a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java index e6ea0582c..aa2b4380e 100644 --- a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java +++ b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java @@ -54,7 +54,7 @@ public final class ChimaeraWing { mcMMOPlayer = UserManager.getPlayer(player); //Not loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; if (mcMMOPlayer.getTeleportCommenceLocation() != null) { diff --git a/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java b/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java index 1183466db..b06c1fcdc 100644 --- a/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java @@ -38,7 +38,7 @@ public class ContainerMetadataUtils { } public static void printOwnershipGainDebug(@NotNull BlockState blockState, @Nullable McMMOPlayer mmoPlayer) { - if(mmoPlayer != null && mmoPlayer.isDebugMode()) { + if (mmoPlayer != null && mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Container ownership " + ChatColor.GREEN +"gained " + ChatColor.RESET + "at location: " + blockState.getLocation().toString()); @@ -48,11 +48,11 @@ public class ContainerMetadataUtils { public static void printOwnershipLossDebug(BlockState blockState) { OfflinePlayer containerOwner = getContainerOwner(blockState); - if(containerOwner != null && containerOwner.isOnline()) { + if (containerOwner != null && containerOwner.isOnline()) { final McMMOPlayer mmoContainerOwner = UserManager.getPlayer(containerOwner.getPlayer()); - if(mmoContainerOwner != null) { - if(mmoContainerOwner.isDebugMode()) { + if (mmoContainerOwner != null) { + if (mmoContainerOwner.isDebugMode()) { mmoContainerOwner.getPlayer().sendMessage("Container ownership " + ChatColor.RED + "lost " + ChatColor.RESET + "at location: " + blockState.getLocation().toString()); @@ -65,7 +65,7 @@ public class ContainerMetadataUtils { if (container instanceof PersistentDataHolder persistentDataHolder) { final UUID uuid = getOwner(persistentDataHolder); - if(uuid != null) { + if (uuid != null) { return Bukkit.getOfflinePlayer(uuid); } } @@ -79,11 +79,11 @@ public class ContainerMetadataUtils { } public static void processContainerOwnership(BlockState blockState, Player player) { - if(!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING)) + if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING)) return; - if(getContainerOwner(blockState) != null) { - if(getContainerOwner(blockState).getUniqueId().equals(player.getUniqueId())) + if (getContainerOwner(blockState) != null) { + if (getContainerOwner(blockState).getUniqueId().equals(player.getUniqueId())) return; } diff --git a/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java b/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java index 798ad289e..f4be9209c 100644 --- a/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java +++ b/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java @@ -63,7 +63,7 @@ public class EnchantmentMapper { } private Enchantment initInfinity() { -// if(Registry.ENCHANTMENT.match("infinity") != null) { +// if (Registry.ENCHANTMENT.match("infinity") != null) { // return Registry.ENCHANTMENT.match("infinity"); // } diff --git a/src/main/java/com/gmail/nossr50/util/EventUtils.java b/src/main/java/com/gmail/nossr50/util/EventUtils.java index 4cb7f7703..a4a501da3 100644 --- a/src/main/java/com/gmail/nossr50/util/EventUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EventUtils.java @@ -123,7 +123,7 @@ public final class EventUtils { Entity entity = entityDamageEvent.getEntity(); //Check to make sure the entity is not an NPC - if(Misc.isNPCEntityExcludingVillagers(entity)) + if (Misc.isNPCEntityExcludingVillagers(entity)) return false; if (!entity.isValid() || !(entity instanceof LivingEntity livingEntity)) { @@ -143,7 +143,7 @@ public final class EventUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) { return true; } @@ -350,7 +350,7 @@ public final class EventUtils { public static void handlePartyTeleportEvent(Player teleportingPlayer, Player targetPlayer) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; McMMOPartyTeleportEvent event = new McMMOPartyTeleportEvent(teleportingPlayer, targetPlayer, mcMMOPlayer.getParty().getName()); @@ -398,7 +398,7 @@ public final class EventUtils { public static boolean handleXpGainEvent(Player player, PrimarySkillType skill, float xpGained, XPGainReason xpGainReason) { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer == null) + if (mmoPlayer == null) return true; McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skill, xpGained, xpGainReason); @@ -415,7 +415,7 @@ public final class EventUtils { } public static boolean handleStatsLossEvent(Player player, HashMap levelChanged, HashMap experienceChanged) { - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return true; McMMOPlayerStatLossEvent event = new McMMOPlayerStatLossEvent(player, levelChanged, experienceChanged); @@ -432,7 +432,7 @@ public final class EventUtils { String skillName = primarySkillType.toString(); int playerSkillLevel = playerProfile.getSkillLevel(primarySkillType); int threshold = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyLevelThreshold(); - if(playerSkillLevel > threshold) { + if (playerSkillLevel > threshold) { playerProfile.modifySkill(primarySkillType, Math.max(threshold, playerSkillLevel - levelChanged.get(skillName))); playerProfile.removeXp(primarySkillType, experienceChanged.get(skillName)); @@ -468,11 +468,11 @@ public final class EventUtils { McMMOPlayer killerPlayer = UserManager.getPlayer(killer); //Not loaded - if(killerPlayer == null) + if (killerPlayer == null) return true; //Not loaded - if(UserManager.getPlayer(victim) == null) + if (UserManager.getPlayer(victim) == null) return true; PlayerProfile victimProfile = UserManager.getPlayer(victim).getProfile(); diff --git a/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java b/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java index a9e6b4bea..9f5b9dd52 100644 --- a/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java +++ b/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java @@ -11,7 +11,7 @@ public class FixSpellingNetheriteUtil { LogUtils.debug(mcMMO.p.getLogger(), "Checking " + fileName + " config material names..."); File configFile = new File(pluginRef.getDataFolder(), fileName); - if(configFile.exists()) { + if (configFile.exists()) { BufferedReader bufferedReader = null; FileWriter fileWriter = null; try { @@ -35,14 +35,14 @@ public class FixSpellingNetheriteUtil { } catch (IOException e) { e.printStackTrace(); } finally { - if(bufferedReader != null) { + if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } - if(fileWriter != null) { + if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { diff --git a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java index 491074a5e..37d807db0 100644 --- a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java +++ b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java @@ -18,15 +18,15 @@ public final class HardcoreManager { public static void invokeStatPenalty(Player player) { - if(WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasHardcoreFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasHardcoreFlag(player)) return; } double statLossPercentage = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyPercentage(); int levelThreshold = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyLevelThreshold(); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile(); @@ -69,15 +69,15 @@ public final class HardcoreManager { public static void invokeVampirism(Player killer, Player victim) { - if(WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasHardcoreFlag(killer) || !WorldGuardManager.getInstance().hasHardcoreFlag(victim)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasHardcoreFlag(killer) || !WorldGuardManager.getInstance().hasHardcoreFlag(victim)) return; } double vampirismStatLeechPercentage = mcMMO.p.getGeneralConfig().getHardcoreVampirismStatLeechPercentage(); int levelThreshold = mcMMO.p.getGeneralConfig().getHardcoreVampirismLevelThreshold(); - if(UserManager.getPlayer(killer) == null || UserManager.getPlayer(victim) == null) + if (UserManager.getPlayer(killer) == null || UserManager.getPlayer(victim) == null) return; PlayerProfile killerProfile = UserManager.getPlayer(killer).getProfile(); diff --git a/src/main/java/com/gmail/nossr50/util/HolidayManager.java b/src/main/java/com/gmail/nossr50/util/HolidayManager.java index 6ea18317b..37adbbc1b 100644 --- a/src/main/java/com/gmail/nossr50/util/HolidayManager.java +++ b/src/main/java/com/gmail/nossr50/util/HolidayManager.java @@ -313,7 +313,7 @@ // } // // public boolean isAprilFirst() { -// if(!Config.getInstance().isAprilFoolsAllowed()) +// if (!Config.getInstance().isAprilFoolsAllowed()) // return false; // // GregorianCalendar aprilFirst = new GregorianCalendar(currentYear, Calendar.APRIL, 1); @@ -323,7 +323,7 @@ // } // // public boolean nearingAprilFirst() { -// if(!Config.getInstance().isAprilFoolsAllowed()) +// if (!Config.getInstance().isAprilFoolsAllowed()) // return false; // // GregorianCalendar start = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.MARCH, 28); @@ -366,7 +366,7 @@ // } // // public void levelUpApril(Player player, FakeSkillType fakeSkillType) { -// if(!Config.getInstance().isAprilFoolsAllowed()) +// if (!Config.getInstance().isAprilFoolsAllowed()) // return; // // final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); @@ -379,7 +379,7 @@ // } // // public void registerAprilCommand() { -// if(!Config.getInstance().isAprilFoolsAllowed()) +// if (!Config.getInstance().isAprilFoolsAllowed()) // return; // // PluginCommand command = mcMMO.p.getCommand("crafting"); diff --git a/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java b/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java index e6074692e..ff565f71d 100644 --- a/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java @@ -70,7 +70,7 @@ public final class ItemMetadataUtils { int originalSpeed = getSuperAbilityToolOriginalDigSpeed(itemStack); ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta != null) { + if (itemMeta != null) { //TODO: can be optimized if (itemMeta.hasEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency())) { itemMeta.removeEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency()); diff --git a/src/main/java/com/gmail/nossr50/util/ItemUtils.java b/src/main/java/com/gmail/nossr50/util/ItemUtils.java index d8b34f9ae..e80bf3053 100644 --- a/src/main/java/com/gmail/nossr50/util/ItemUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ItemUtils.java @@ -183,7 +183,7 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentOnArmor(@NotNull Player player, @NotNull String enchantmentByName) { Enchantment enchantment = getEnchantment(enchantmentByName); - if(enchantment == null) + if (enchantment == null) return false; return doesPlayerHaveEnchantmentOnArmor(player, enchantment); @@ -191,8 +191,8 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentOnArmor(@NotNull Player player, @NotNull Enchantment enchantment) { for(ItemStack itemStack : player.getInventory().getArmorContents()) { - if(itemStack != null) { - if(hasEnchantment(itemStack, enchantment)) + if (itemStack != null) { + if (hasEnchantment(itemStack, enchantment)) return true; } } @@ -203,17 +203,17 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentOnArmorOrHands(@NotNull Player player, @NotNull String enchantmentName) { Enchantment enchantment = getEnchantment(enchantmentName); - if(enchantment == null) + if (enchantment == null) return false; return doesPlayerHaveEnchantmentOnArmorOrHands(player, enchantment); } public static boolean doesPlayerHaveEnchantmentOnArmorOrHands(@NotNull Player player, @NotNull Enchantment enchantment) { - if(doesPlayerHaveEnchantmentOnArmor(player, enchantment)) + if (doesPlayerHaveEnchantmentOnArmor(player, enchantment)) return true; - if(doesPlayerHaveEnchantmentInHands(player, enchantment)) + if (doesPlayerHaveEnchantmentInHands(player, enchantment)) return true; return false; @@ -222,7 +222,7 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, @NotNull NamespacedKey enchantmentNameKey) { Enchantment enchantment = Enchantment.getByKey(enchantmentNameKey); - if(enchantment == null) + if (enchantment == null) return false; return doesPlayerHaveEnchantmentInHands(player, enchantment); @@ -231,7 +231,7 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, @NotNull String enchantmentName) { Enchantment enchantment = getEnchantment(enchantmentName); - if(enchantment == null) + if (enchantment == null) return false; return doesPlayerHaveEnchantmentInHands(player, enchantment); @@ -243,7 +243,7 @@ public final class ItemUtils { } public static boolean hasEnchantment(@NotNull ItemStack itemStack, @NotNull Enchantment enchantment) { - if(itemStack.getItemMeta() != null) { + if (itemStack.getItemMeta() != null) { return itemStack.getItemMeta().hasEnchant(enchantment); } @@ -252,7 +252,7 @@ public final class ItemUtils { public static @Nullable Enchantment getEnchantment(@NotNull String enchantmentName) { for(Enchantment enchantment : Enchantment.values()) { - if(enchantment.getKey().getKey().equalsIgnoreCase(enchantmentName)) { + if (enchantment.getKey().getKey().equalsIgnoreCase(enchantmentName)) { return enchantment; } } @@ -695,7 +695,7 @@ public final class ItemUtils { ItemMeta itemMeta = item.getItemMeta(); - if(itemMeta == null) + if (itemMeta == null) return false; return itemMeta.getLore() != null @@ -709,7 +709,7 @@ public final class ItemUtils { ItemMeta itemMeta = item.getItemMeta(); - if(itemMeta == null) + if (itemMeta == null) return false; return itemMeta.hasDisplayName() && itemMeta.getDisplayName().equals(ChatColor.GOLD + LocaleLoader.getString("Item.ChimaeraWing.Name")); @@ -719,7 +719,7 @@ public final class ItemUtils { // ItemMeta itemMeta = itemStack.getItemMeta(); // List itemLore = new ArrayList<>(); // -// if(itemMeta == null) +// if (itemMeta == null) // return; // // if (itemMeta.hasLore()) { @@ -735,13 +735,13 @@ public final class ItemUtils { public static void removeAbilityLore(@NotNull ItemStack itemStack) { ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta == null) + if (itemMeta == null) return; if (itemMeta.hasLore()) { List itemLore = itemMeta.getLore(); - if(itemLore == null) + if (itemLore == null) return; if (itemLore.remove("mcMMO Ability Tool")) { @@ -754,7 +754,7 @@ public final class ItemUtils { public static void addDigSpeedToItem(@NotNull ItemStack itemStack, int existingEnchantLevel) { ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta == null) + if (itemMeta == null) return; itemMeta.addEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency(), @@ -771,7 +771,7 @@ public final class ItemUtils { EnchantmentWrapper enchantmentWrapper = getRandomEnchantment(fishingTreasureBook.getLegalEnchantments()); ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta == null) { + if (itemMeta == null) { return itemStack; } diff --git a/src/main/java/com/gmail/nossr50/util/Misc.java b/src/main/java/com/gmail/nossr50/util/Misc.java index 2467a5540..a289315cb 100644 --- a/src/main/java/com/gmail/nossr50/util/Misc.java +++ b/src/main/java/com/gmail/nossr50/util/Misc.java @@ -223,7 +223,7 @@ public final class Misc { Location spawnLocation = fromLocation.clone(); Location targetLocation = toLocation.clone(); - if(spawnLocation.getWorld() == null) + if (spawnLocation.getWorld() == null) return null; // We can't get the item until we spawn it and we want to make it cancellable, so we have a custom event. @@ -318,7 +318,7 @@ public final class Misc { // } public static void spawnExperienceOrb(@NotNull Location location, int experienceValue) { - if(location.getWorld() == null) + if (location.getWorld() == null) return; ExperienceOrb experienceOrb = (ExperienceOrb) location.getWorld().spawnEntity(location, EntityType.EXPERIENCE_ORB); @@ -336,7 +336,7 @@ public final class Misc { @Override public void run() { - if(location == null || location.getWorld() == null) + if (location == null || location.getWorld() == null) return; ExperienceOrb experienceOrb = (ExperienceOrb) location.getWorld().spawnEntity(location, EntityType.EXPERIENCE_ORB); @@ -352,7 +352,7 @@ public final class Misc { // // double win = 0, loss = 0; // for(int x = 0; x < iterations; x++) { -// if(RandomChanceUtil.checkRandomChanceExecutionSuccess(normalPlayer.getPlayer(), SubSkillType.MINING_MOTHER_LODE, true)) { +// if (RandomChanceUtil.checkRandomChanceExecutionSuccess(normalPlayer.getPlayer(), SubSkillType.MINING_MOTHER_LODE, true)) { // win++; // } else { // loss++; diff --git a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java index 5da29a656..7d19e1979 100644 --- a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java +++ b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java @@ -54,7 +54,7 @@ public final class MobHealthbarUtils { /* * Store the name in metadata */ - if(target.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY).size() <= 0) + if (target.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY).size() <= 0) target.setMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY, new OldName(originalName, plugin)); if (oldName == null) { diff --git a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java index d6bed4509..ba410788d 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java +++ b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java @@ -147,7 +147,7 @@ public class TransientEntityTracker { private synchronized @Nullable HashSet getTrackedEntities(@NotNull UUID playerUUID, @NotNull CallOfTheWildType callOfTheWildType) { HashMap> playerEntityMap = getPlayerTrackedEntityMap(playerUUID); - if(playerEntityMap == null) + if (playerEntityMap == null) return null; return playerEntityMap.get(callOfTheWildType); @@ -196,12 +196,12 @@ public class TransientEntityTracker { HashSet trackedEntities = getTrackedEntities(uuid, callOfTheWildType); - if(trackedEntities == null) + if (trackedEntities == null) continue; Iterator iterator = trackedEntities.iterator(); while (iterator.hasNext()) { - if(iterator.next().getLivingEntity().equals(livingEntity)) { + if (iterator.next().getLivingEntity().equals(livingEntity)) { iterator.remove(); return; } @@ -220,7 +220,7 @@ public class TransientEntityTracker { ArrayList matchingEntities = new ArrayList<>(); for(LivingEntity livingEntity : getChunkLookupCache()) { - if(livingEntity.getLocation().getChunk().equals(chunk)) { + if (livingEntity.getLocation().getChunk().equals(chunk)) { matchingEntities.add(livingEntity); } } @@ -238,7 +238,7 @@ public class TransientEntityTracker { public synchronized int getAmountCurrentlySummoned(@NotNull UUID playerUUID, @NotNull CallOfTheWildType callOfTheWildType) { HashSet trackedEntities = getTrackedEntities(playerUUID, callOfTheWildType); - if(trackedEntities == null) + if (trackedEntities == null) return 0; return trackedEntities.size(); @@ -253,7 +253,7 @@ public class TransientEntityTracker { */ public synchronized void removeSummon(@NotNull LivingEntity livingEntity, @Nullable Player player, boolean timeExpired) { //Kill the summon & remove it - if(livingEntity.isValid()) { + if (livingEntity.isValid()) { livingEntity.setHealth(0); //Should trigger entity death events livingEntity.remove(); @@ -265,8 +265,8 @@ public class TransientEntityTracker { } //Inform player of summon death - if(player != null && player.isOnline()) { - if(timeExpired) { + if (player != null && player.isOnline()) { + if (timeExpired) { NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.TimeExpired", StringUtils.getPrettyEntityTypeString(livingEntity.getType())); } else { NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.Removed", StringUtils.getPrettyEntityTypeString(livingEntity.getType())); @@ -302,7 +302,7 @@ public class TransientEntityTracker { for(CallOfTheWildType callOfTheWildType : CallOfTheWildType.values()) { HashSet trackedEntities = getTrackedEntities(playerUUID, callOfTheWildType); - if(trackedEntities == null) { + if (trackedEntities == null) { continue; } diff --git a/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java b/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java index 7fb29ed60..c7f1e335a 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java +++ b/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java @@ -27,7 +27,7 @@ public class TransientMetadataTools { } //Gets assigned to endermen, potentially doesn't get cleared before this point - if(entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK)) { + if (entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK)) { entity.removeMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, pluginRef); } @@ -36,7 +36,7 @@ public class TransientMetadataTools { //TODO: This loop has some redundancy, this whole method needs to be rewritten for(String key : MetadataConstants.MOB_METADATA_KEYS) { - if(entity.hasMetadata(key)) { + if (entity.hasMetadata(key)) { entity.removeMetadata(key, pluginRef); } } diff --git a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java index fcbd2fdbe..e2716aede 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java @@ -36,7 +36,7 @@ public final class CommandUtils { } public static boolean tooFar(CommandSender sender, Player target, boolean hasPermission) { - if(!target.isOnline() && !hasPermission) { + if (!target.isOnline() && !hasPermission) { sender.sendMessage(LocaleLoader.getString("Inspect.Offline")); return true; } else if (sender instanceof Player && !Misc.isNear(((Player) sender).getLocation(), target.getLocation(), mcMMO.p.getGeneralConfig().getInspectDistance()) && !hasPermission) { @@ -217,7 +217,7 @@ public final class CommandUtils { } private static void printGroupedSkillData(Player inspectTarget, CommandSender display, String header, List skillGroup) { - if(UserManager.getPlayer(inspectTarget) == null) + if (UserManager.getPlayer(inspectTarget) == null) return; PlayerProfile profile = UserManager.getPlayer(inspectTarget).getProfile(); diff --git a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java index 012524adb..db6de7825 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java +++ b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java @@ -66,7 +66,7 @@ public class CompatibilityManager { } private void initMasterAnglerLayer() { - if(minecraftGameVersion.isAtLeast(1, 16, 3)) { + if (minecraftGameVersion.isAtLeast(1, 16, 3)) { masterAnglerCompatibility = new MasterAnglerCompatibilityLayer(); } else { masterAnglerCompatibility = null; @@ -74,7 +74,7 @@ public class CompatibilityManager { } private void initBungeeSerializerLayer() { - if(minecraftGameVersion.isAtLeast(1, 16, 0)) { + if (minecraftGameVersion.isAtLeast(1, 16, 0)) { bungeeSerializerCompatibilityLayer = new BungeeModernSerializerCompatibilityLayer(); } else { bungeeSerializerCompatibilityLayer = new BungeeLegacySerializerCompatibilityLayer(); @@ -85,13 +85,13 @@ public class CompatibilityManager { //TODO: move to text manager public void reportCompatibilityStatus(@NotNull CommandSender commandSender) { - if(isFullyCompatibleServerSoftware) { + if (isFullyCompatibleServerSoftware) { commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix", "mcMMO is fully compatible with the currently running server software.")); } else { //TODO: Better messages for each incompatible layer for(CompatibilityType compatibilityType : CompatibilityType.values()) { - if(!supportedLayers.get(compatibilityType)) { + if (!supportedLayers.get(compatibilityType)) { commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix", LocaleLoader.getString("Compatibility.Layer.Unsupported", StringUtils.getCapitalized(compatibilityType.toString())))); } @@ -115,7 +115,7 @@ public class CompatibilityManager { private @NotNull NMSVersion determineNMSVersion() { //This bit here helps prevent mcMMO breaking if it isn't updated but the game continues to update - if(minecraftGameVersion.isAtLeast(1, 17, 0)) { + if (minecraftGameVersion.isAtLeast(1, 17, 0)) { return NMSVersion.NMS_1_17; } @@ -133,13 +133,13 @@ public class CompatibilityManager { case 16: if (minecraftGameVersion.getPatchVersion().asInt() == 1) { return NMSVersion.NMS_1_16_1; - } else if(minecraftGameVersion.getPatchVersion().asInt() == 2) { + } else if (minecraftGameVersion.getPatchVersion().asInt() == 2) { return NMSVersion.NMS_1_16_2; - } else if(minecraftGameVersion.getPatchVersion().asInt() == 3) { + } else if (minecraftGameVersion.getPatchVersion().asInt() == 3) { return NMSVersion.NMS_1_16_3; - } else if(minecraftGameVersion.getPatchVersion().asInt() == 4) { + } else if (minecraftGameVersion.getPatchVersion().asInt() == 4) { return NMSVersion.NMS_1_16_4; - } else if(minecraftGameVersion.getPatchVersion().asInt() >= 5) { + } else if (minecraftGameVersion.getPatchVersion().asInt() >= 5) { return NMSVersion.NMS_1_16_5; } case 17: diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java index 5b0026198..7a870c27a 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java @@ -37,15 +37,15 @@ // public PlayerAttackCooldownToolLayer(@NotNull NMSVersion nmsVersion) { // super(nmsVersion); // mcMMO.p.getLogger().info("Loading Compatibility Layer... (Player Attack Cooldown Exploit Prevention)"); -// if(!isCompatibleWithMinecraftVersion(nmsVersion)) { +// if (!isCompatibleWithMinecraftVersion(nmsVersion)) { // mcMMO.p.getLogger().severe("this version of mcMMO does not support NMS for this version of Minecraft, try updating mcMMO or updating Minecraft. Not all versions of Minecraft will have NMS support built into mcMMO."); // cbNMSVersionPath = ""; // } else { -// if(NMSConstants.getCraftBukkitVersionPath(nmsVersion) != null) { +// if (NMSConstants.getCraftBukkitVersionPath(nmsVersion) != null) { // cbNMSVersionPath = NMSConstants.getCraftBukkitVersionPath(nmsVersion); // noErrorsOnInitialize = initializeLayer(); // -// if(noErrorsOnInitialize) { +// if (noErrorsOnInitialize) { // mcMMO.p.getLogger().info("Successfully Loaded Compatibility Layer! (Player Attack Cooldown Exploit Prevention)"); // } // } else { diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java index c4617bd69..3a2065f75 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java @@ -46,13 +46,13 @@ public class ExperienceBarManager { public void updateExperienceBar(PrimarySkillType primarySkillType, Plugin plugin) { - if(disabledBars.contains(primarySkillType) + if (disabledBars.contains(primarySkillType) || !ExperienceConfig.getInstance().isExperienceBarsEnabled() || !ExperienceConfig.getInstance().isExperienceBarEnabled(primarySkillType)) return; //Init Bar - if(experienceBars.get(primarySkillType) == null) + if (experienceBars.get(primarySkillType) == null) experienceBars.put(primarySkillType, new ExperienceBarWrapper(primarySkillType, mcMMOPlayer)); //Get Bar @@ -65,7 +65,7 @@ public class ExperienceBarManager { experienceBarWrapper.showExperienceBar(); //Setup Hide Bar Task - if(experienceBarHideTaskHashMap.get(primarySkillType) != null) + if (experienceBarHideTaskHashMap.get(primarySkillType) != null) { experienceBarHideTaskHashMap.get(primarySkillType).cancel(); } @@ -74,7 +74,7 @@ public class ExperienceBarManager { } private void scheduleHideTask(PrimarySkillType primarySkillType, Plugin plugin) { - if(alwaysVisible.contains(primarySkillType)) + if (alwaysVisible.contains(primarySkillType)) return; ExperienceBarHideTask experienceBarHideTask = new ExperienceBarHideTask(this, mcMMOPlayer, primarySkillType); @@ -84,7 +84,7 @@ public class ExperienceBarManager { public void hideExperienceBar(PrimarySkillType primarySkillType) { - if(experienceBars.containsKey(primarySkillType)) + if (experienceBars.containsKey(primarySkillType)) experienceBars.get(primarySkillType).hideExperienceBar(); } @@ -108,7 +108,7 @@ public class ExperienceBarManager { alwaysVisible.add(skillType); //Remove lingering tasks - if(experienceBarHideTaskHashMap.containsKey(skillType)) { + if (experienceBarHideTaskHashMap.containsKey(skillType)) { experienceBarHideTaskHashMap.get(skillType).cancel(); } @@ -119,7 +119,7 @@ public class ExperienceBarManager { disabledBars.add(skillType); //Remove lingering tasks - if(experienceBarHideTaskHashMap.containsKey(skillType)) { + if (experienceBarHideTaskHashMap.containsKey(skillType)) { experienceBarHideTaskHashMap.get(skillType).cancel(); } @@ -149,7 +149,7 @@ public class ExperienceBarManager { private void informPlayer(@NotNull ExperienceBarManager.@NotNull XPBarSettingTarget settingTarget, @Nullable PrimarySkillType primarySkillType) { //Inform player of setting change - if(settingTarget != XPBarSettingTarget.RESET) { + if (settingTarget != XPBarSettingTarget.RESET) { NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.SettingChanged", mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType), settingTarget.toString()); } else { NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.Reset"); diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java index 185026ed9..4f2fc97fb 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java @@ -57,9 +57,9 @@ public class ExperienceBarWrapper { private String getTitleTemplate() { //If they are using extra details - if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { return LocaleLoader.getString("XPBar.Template.EarlyGameBoost"); - } else if(ExperienceConfig.getInstance().getAddExtraDetails()) + } else if (ExperienceConfig.getInstance().getAddExtraDetails()) return LocaleLoader.getString("XPBar.Complex.Template", LocaleLoader.getString("XPBar."+niceSkillName, getLevel()), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); return LocaleLoader.getString("XPBar."+niceSkillName, getLevel(), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); @@ -99,23 +99,23 @@ public class ExperienceBarWrapper { public void setProgress(double v) { //Clamp Values - if(v < 0) + if (v < 0) bossBar.setProgress(0.0D); - else if(v > 1) + else if (v > 1) bossBar.setProgress(1.0D); else bossBar.setProgress(v); //Check player level - if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { setColor(BarColor.YELLOW); } else { setColor(ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType)); } //Every time progress updates we need to check for a title update - if(getLevel() != lastLevelUpdated || ExperienceConfig.getInstance().getDoExperienceBarsAlwaysUpdateTitle()) + if (getLevel() != lastLevelUpdated || ExperienceConfig.getInstance().getDoExperienceBarsAlwaysUpdateTitle()) { updateTitle(); lastLevelUpdated = getLevel(); diff --git a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java index 6685e816b..f2e20c597 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java @@ -135,7 +135,7 @@ public class FormulaManager { * @param formulaType target formulaType */ private int processXPToNextLevel(int level, FormulaType formulaType) { - if(mcMMO.isRetroModeEnabled()) + if (mcMMO.isRetroModeEnabled()) { return processXPRetroToNextLevel(level, formulaType); } else { @@ -151,7 +151,7 @@ public class FormulaManager { private int processStandardXPToNextLevel(int level, FormulaType formulaType) { Map experienceMapRef = formulaType == FormulaType.LINEAR ? experienceNeededStandardLinear : experienceNeededStandardExponential; - if(!experienceMapRef.containsKey(level)) { + if (!experienceMapRef.containsKey(level)) { int experienceSum = 0; int retroIndex = (level * 10) + 1; diff --git a/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java b/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java index 47f41a82e..ea114508e 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java +++ b/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java @@ -73,7 +73,7 @@ public abstract class MajorMinorPatchVersion implements Versioned { @Override public String getVersionStr() { - if(isPatch()) { + if (isPatch()) { return majorVersion.getVersionString() + "." + minorVersion + "." + patchVersion; diff --git a/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java b/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java index 387d831d1..34ccdede9 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java +++ b/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java @@ -38,21 +38,21 @@ public class MinecraftGameVersion extends MajorMinorPatchVersion { public boolean isAtLeast(int majorVerNumber, int minorVerNumber, int patchVerNumber) { //First check if the major version is higher, if it is we have no need to check minor version or patch version - if(getMajorVersion().asInt() > majorVerNumber) { + if (getMajorVersion().asInt() > majorVerNumber) { return true; //Major version is one higher and hierarchically more important than the other versions } - if(getMajorVersion().asInt() < majorVerNumber) { + if (getMajorVersion().asInt() < majorVerNumber) { return false; //Major version is below, so return false } //Major version meets the requirement, check minor version - if(getMinorVersion().asInt() > minorVerNumber) { + if (getMinorVersion().asInt() > minorVerNumber) { return true; //Minor version is one higher and hierarchically more important than patch version, so exit here } - if(getMinorVersion().asInt() < minorVerNumber) { + if (getMinorVersion().asInt() < minorVerNumber) { return false; //Minor version is at least one version behind, return false } diff --git a/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java b/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java index e68ff1912..5ecf557b0 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java +++ b/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java @@ -72,9 +72,9 @@ public class PlatformManager { //TODO: Rewrite this properly once we actually support a not-bukkit platform private @NotNull ServerSoftwareType determinePlatformType() { - if(Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("paper")) + if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("paper")) return ServerSoftwareType.PAPER; - else if(Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("spigot")) + else if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("spigot")) return ServerSoftwareType.SPIGOT; else return ServerSoftwareType.CRAFT_BUKKIT; diff --git a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java index f41d740b7..156c17e46 100644 --- a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java @@ -45,7 +45,7 @@ public class NotificationManager { */ public static void sendPlayerInformation(Player player, NotificationType notificationType, String key) { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; McMMOMessageType destination @@ -61,7 +61,7 @@ public class NotificationManager { public static boolean doesPlayerUseNotifications(Player player) { - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return false; else return UserManager.getPlayer(player).useChatNotifications(); @@ -84,7 +84,7 @@ public class NotificationManager { public static void sendPlayerInformationChatOnly(Player player, String key, String... values) { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; String preColoredString = LocaleLoader.getString(key, (Object[]) values); @@ -93,7 +93,7 @@ public class NotificationManager { public static void sendPlayerInformationChatOnlyPrefixed(Player player, String key, String... values) { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; String preColoredString = LocaleLoader.getString(key, (Object[]) values); @@ -104,7 +104,7 @@ public class NotificationManager { public static void sendPlayerInformation(Player player, NotificationType notificationType, String key, String... values) { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; McMMOMessageType destination = mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM; @@ -123,11 +123,11 @@ public class NotificationManager { Component notificationTextComponent = customEvent.getNotificationTextComponent(); - if(customEvent.getChatMessageType() == McMMOMessageType.ACTION_BAR) { + if (customEvent.getChatMessageType() == McMMOMessageType.ACTION_BAR) { audience.sendActionBar(notificationTextComponent); // If the message is being sent to the action bar we need to check if a copy is also sent to the chat system - if(customEvent.isMessageAlsoBeingSentToChat()) { + if (customEvent.isMessageAlsoBeingSentToChat()) { //Send copy to chat system audience.sendMessage(notificationTextComponent); } @@ -158,7 +158,7 @@ public class NotificationManager { public static void sendPlayerLevelUpNotification(McMMOPlayer mcMMOPlayer, PrimarySkillType skillName, int levelsGained, int newLevel) { - if(!mcMMOPlayer.useChatNotifications()) + if (!mcMMOPlayer.useChatNotifications()) return; McMMOMessageType destination @@ -186,7 +186,7 @@ public class NotificationManager { public static void sendPlayerUnlockNotification(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType) { - if(!mcMMOPlayer.useChatNotifications()) + if (!mcMMOPlayer.useChatNotifications()) return; //CHAT MESSAGE @@ -205,12 +205,12 @@ public class NotificationManager { */ private static void sendAdminNotification(String msg) { //If its not enabled exit - if(!mcMMO.p.getGeneralConfig().adminNotifications()) + if (!mcMMO.p.getGeneralConfig().adminNotifications()) return; for(Player player : Bukkit.getServer().getOnlinePlayers()) { - if(player.isOp() || Permissions.adminChat(player)) + if (player.isOp() || Permissions.adminChat(player)) { player.sendMessage(LocaleLoader.getString("Notifications.Admin.Format.Others", msg)); } @@ -241,7 +241,7 @@ public class NotificationManager { */ String senderName = LocaleLoader.getString("Server.ConsoleName"); - if(commandSender instanceof Player) + if (commandSender instanceof Player) { senderName = ((Player) commandSender).getDisplayName() + ChatColor.RESET + "-" + ((Player) commandSender).getUniqueId(); @@ -284,20 +284,20 @@ public class NotificationManager { } public static void processLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType, int level) { - if(level <= 0) + if (level <= 0) return; //Check if broadcasting is enabled - if(mcMMO.p.getGeneralConfig().shouldLevelUpBroadcasts()) { + if (mcMMO.p.getGeneralConfig().shouldLevelUpBroadcasts()) { //Permission check - if(!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) { + if (!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) { return; } int levelInterval = mcMMO.p.getGeneralConfig().getLevelUpBroadcastInterval(); int remainder = level % levelInterval; - if(remainder == 0) { + if (remainder == 0) { //Grab appropriate audience Audience audience = mcMMO.getAudiences().filter(getLevelUpBroadcastPredicate(mmoPlayer.getPlayer())); //TODO: Make prettier @@ -328,20 +328,20 @@ public class NotificationManager { //TODO: Remove the code duplication, am lazy atm //TODO: Fix broadcasts being skipped for situations where a player skips over the milestone like with the addlevels command public static void processPowerLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, int powerLevel) { - if(powerLevel <= 0) + if (powerLevel <= 0) return; //Check if broadcasting is enabled - if(mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcasts()) { + if (mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcasts()) { //Permission check - if(!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) { + if (!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) { return; } int levelInterval = mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastInterval(); int remainder = powerLevel % levelInterval; - if(remainder == 0) { + if (remainder == 0) { //Grab appropriate audience Audience audience = mcMMO.getAudiences().filter(getPowerLevelUpBroadcastPredicate(mmoPlayer.getPlayer())); //TODO: Make prettier diff --git a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java index 1f0cba2f1..72ad26c4e 100644 --- a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java +++ b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java @@ -19,7 +19,7 @@ public class PlayerLevelUtils { // int levelCap = Config.getInstance().getLevelCap(primarySkillType); // int cap; // -// if(levelCap == Integer.MAX_VALUE || levelCap <= 0) +// if (levelCap == Integer.MAX_VALUE || levelCap <= 0) // { // cap = Config.getInstance().getIsRetroMode() ? 50 : 5; // } else { diff --git a/src/main/java/com/gmail/nossr50/util/player/UserManager.java b/src/main/java/com/gmail/nossr50/util/player/UserManager.java index a7f4a840b..8d3044bfc 100644 --- a/src/main/java/com/gmail/nossr50/util/player/UserManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/UserManager.java @@ -30,14 +30,14 @@ public final class UserManager { public static void track(@NotNull McMMOPlayer mcMMOPlayer) { mcMMOPlayer.getPlayer().setMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, new FixedMetadataValue(mcMMO.p, mcMMOPlayer)); - if(playerDataSet == null) + if (playerDataSet == null) playerDataSet = new HashSet<>(); playerDataSet.add(mcMMOPlayer); //for sync saves on shutdown } public static void cleanupPlayer(McMMOPlayer mcMMOPlayer) { - if(playerDataSet != null) + if (playerDataSet != null) playerDataSet.remove(mcMMOPlayer); } @@ -49,13 +49,13 @@ public final class UserManager { public static void remove(@NotNull Player player) { McMMOPlayer mcMMOPlayer = getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; mcMMOPlayer.cleanup(); player.removeMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, mcMMO.p); - if(playerDataSet != null) { + if (playerDataSet != null) { playerDataSet.remove(mcMMOPlayer); //Clear sync save tracking } } @@ -68,7 +68,7 @@ public final class UserManager { remove(player); } - if(playerDataSet != null) + if (playerDataSet != null) playerDataSet.clear(); //Clear sync save tracking } @@ -76,7 +76,7 @@ public final class UserManager { * Save all users ON THIS THREAD. */ public static void saveAll() { - if(playerDataSet == null) + if (playerDataSet == null) return; ImmutableList trackedSyncData = ImmutableList.copyOf(playerDataSet); @@ -139,14 +139,14 @@ public final class UserManager { */ public static @Nullable McMMOPlayer getPlayer(@Nullable Player player) { //Avoid Array Index out of bounds - if(player != null && player.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA)) + if (player != null && player.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA)) return (McMMOPlayer) player.getMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA).get(0).value(); else return null; } private static @Nullable McMMOPlayer retrieveMcMMOPlayer(@Nullable String playerName, boolean offlineValid) { - if(playerName == null) + if (playerName == null) return null; Player player = mcMMO.p.getServer().getPlayerExact(playerName); diff --git a/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java b/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java index 093b631f5..ca4a67de8 100644 --- a/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java +++ b/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java @@ -46,7 +46,7 @@ public class ProbabilityUtil { double percentageValue = probability.getValue(); //Doesn't need to be scaled //Apply lucky modifier - if(isLucky) { + if (isLucky) { percentageValue *= LUCKY_MODIFIER; } @@ -65,7 +65,7 @@ public class ProbabilityUtil { double percentageValue = probability.getValue(); //Apply lucky modifier - if(isLucky) { + if (isLucky) { percentageValue *= LUCKY_MODIFIER; } @@ -85,7 +85,7 @@ public class ProbabilityUtil { static SkillProbabilityType getProbabilityType(@NotNull SubSkillType subSkillType) { SkillProbabilityType skillProbabilityType = SkillProbabilityType.DYNAMIC_CONFIGURABLE; - if(subSkillType == SubSkillType.TAMING_FAST_FOOD_SERVICE + if (subSkillType == SubSkillType.TAMING_FAST_FOOD_SERVICE || subSkillType == SubSkillType.AXES_ARMOR_IMPACT || subSkillType == SubSkillType.AXES_GREATER_IMPACT) skillProbabilityType = SkillProbabilityType.STATIC_CONFIGURABLE; @@ -181,7 +181,7 @@ public class ProbabilityUtil { //Luck boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), subSkillType.getParentSkill()); - if(isLucky) { + if (isLucky) { return probability.evaluate(LUCKY_MODIFIER); } else { return probability.evaluate(); @@ -224,7 +224,7 @@ public class ProbabilityUtil { if (mmoPlayer != null) { SubSkillEvent subSkillEvent = EventUtils.callSubSkillEvent(mmoPlayer, subSkillType); - if(subSkillEvent.isCancelled()) { + if (subSkillEvent.isCancelled()) { return Probability.ALWAYS_FAILS; } @@ -232,7 +232,7 @@ public class ProbabilityUtil { double resultModifier = subSkillEvent.getResultModifier(); // Mutate probability - if(resultModifier != 1.0D) + if (resultModifier != 1.0D) probability = Probability.ofPercent(probability.getValue() * resultModifier); } @@ -303,7 +303,7 @@ public class ProbabilityUtil { @Nullable McMMOPlayer mmoPlayer, @NotNull Probability probability) { boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), primarySkillType); - if(isLucky) { + if (isLucky) { return probability.evaluate(LUCKY_MODIFIER); } else { return probability.evaluate(); diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java index 331d3f5b3..ff952b658 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java @@ -185,18 +185,18 @@ public class ScoreboardManager { // Called by PlayerQuitEvent listener and OnPlayerTeleport under certain circumstances public static void teardownPlayer(Player player) { - if(player == null) + if (player == null) return; //Hacky world blacklist fix - if(player.isOnline() && player.isValid()) { - if(Bukkit.getServer().getScoreboardManager() != null) + if (player.isOnline() && player.isValid()) { + if (Bukkit.getServer().getScoreboardManager() != null) player.setScoreboard(Bukkit.getServer().getScoreboardManager().getMainScoreboard()); } - if(getWrapper(player) != null) { + if (getWrapper(player) != null) { ScoreboardWrapper wrapper = PLAYER_SCOREBOARDS.remove(player.getName()); - if(wrapper.revertTask != null) { + if (wrapper.revertTask != null) { wrapper.revertTask.cancel(); } } @@ -225,12 +225,12 @@ public class ScoreboardManager { // Selfboards ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { if ((wrapper.isSkillScoreboard() && wrapper.targetSkill == skill) || (wrapper.isStatsScoreboard()) && wrapper.isBoardShown()) { wrapper.doSidebarUpdateSoon(); } @@ -270,12 +270,12 @@ public class ScoreboardManager { // Selfboards ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { if ((wrapper.isCooldownScoreboard() || wrapper.isSkillScoreboard() && wrapper.targetSkill == skill) && wrapper.isBoardShown()) { wrapper.doSidebarUpdateSoon(); } @@ -290,12 +290,12 @@ public class ScoreboardManager { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeSkill(skill); @@ -309,12 +309,12 @@ public class ScoreboardManager { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeSkill(primarySkillType); @@ -328,7 +328,7 @@ public class ScoreboardManager { // Do NOT run if already shown if (wrapper != null && wrapper.isBoardShown()) { - if(wrapper.isBoardShown()) + if (wrapper.isBoardShown()) return; wrapper.setOldScoreboard(); @@ -340,7 +340,7 @@ public class ScoreboardManager { public static void enablePlayerStatsScoreboard(Player player) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) + if (wrapper == null) return; @@ -353,12 +353,12 @@ public class ScoreboardManager { public static void enablePlayerInspectScoreboard(@NotNull Player player, @NotNull PlayerProfile targetProfile) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeInspectStats(targetProfile); @@ -369,12 +369,12 @@ public class ScoreboardManager { public static void enablePlayerInspectScoreboard(@NotNull Player player, @NotNull McMMOPlayer targetMcMMOPlayer) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeInspectStats(targetMcMMOPlayer); @@ -385,12 +385,12 @@ public class ScoreboardManager { public static void enablePlayerCooldownScoreboard(Player player) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeCooldowns(); @@ -401,12 +401,12 @@ public class ScoreboardManager { public static void showPlayerRankScoreboard(Player player, Map rank) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeSelfRank(); wrapper.acceptRankData(rank); @@ -418,12 +418,12 @@ public class ScoreboardManager { public static void showPlayerRankScoreboardOthers(Player player, String targetName, Map rank) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeInspectRank(targetName); wrapper.acceptRankData(rank); @@ -436,12 +436,12 @@ public class ScoreboardManager { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeTop(skill, pageNumber); wrapper.acceptLeaderboardData(stats); @@ -453,12 +453,12 @@ public class ScoreboardManager { public static void showTopPowerScoreboard(Player player, int pageNumber, List stats) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeTopPower(pageNumber); wrapper.acceptLeaderboardData(stats); @@ -468,7 +468,7 @@ public class ScoreboardManager { } public static @Nullable ScoreboardWrapper getWrapper(Player player) { - if(PLAYER_SCOREBOARDS.get(player.getName()) == null) { + if (PLAYER_SCOREBOARDS.get(player.getName()) == null) { makeNewScoreboard(player); } @@ -518,7 +518,7 @@ public class ScoreboardManager { */ public static @Nullable Objective getPowerLevelObjective() { if (!mcMMO.p.getGeneralConfig().getPowerLevelTagsEnabled()) { - if(getScoreboardManager() == null) + if (getScoreboardManager() == null) return null; Objective objective = getScoreboardManager().getMainScoreboard().getObjective(POWER_OBJECTIVE); @@ -532,7 +532,7 @@ public class ScoreboardManager { } - if(getScoreboardManager() == null) + if (getScoreboardManager() == null) return null; Objective powerObjective = getScoreboardManager().getMainScoreboard().getObjective(POWER_OBJECTIVE); @@ -580,7 +580,7 @@ public class ScoreboardManager { } public static @Nullable ScoreboardWrapper makeNewScoreboard(Player player) { - if(getScoreboardManager() == null) + if (getScoreboardManager() == null) return null; //Call our custom event diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java index 4d2d51560..c6e5377fb 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java @@ -62,7 +62,7 @@ public class ScoreboardWrapper { private void initBoard() { sidebarType = SidebarType.NONE; - if(registered) { + if (registered) { //Make sure our references are pointed at the right things sidebarObjective = scoreboard.getObjective(ScoreboardManager.SIDEBAR_OBJECTIVE); powerObjective = scoreboard.getObjective(ScoreboardManager.POWER_OBJECTIVE); @@ -175,7 +175,7 @@ public class ScoreboardWrapper { if (previousBoard == scoreboard) { // Already displaying it if (this.oldBoard == null) { // (Shouldn't happen) Use failsafe value - we're already displaying our board, but we don't have the one we should revert to - if(mcMMO.p.getServer().getScoreboardManager() != null) + if (mcMMO.p.getServer().getScoreboardManager() != null) this.oldBoard = mcMMO.p.getServer().getScoreboardManager().getMainScoreboard(); } } @@ -218,7 +218,7 @@ public class ScoreboardWrapper { // TODO is there any way to do the time that looks acceptable? // player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Timer", StringUtils.capitalize(sidebarType.toString().toLowerCase(Locale.ENGLISH)), ticks / 20F)); - if(UserManager.getPlayer(playerName) == null) + if (UserManager.getPlayer(playerName) == null) return; PlayerProfile profile = UserManager.getPlayer(player).getProfile(); @@ -411,7 +411,7 @@ public class ScoreboardWrapper { protected void loadObjective(String displayName) { //Unregister objective McMMOScoreboardObjectiveEvent unregisterEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.UNREGISTER_THIS_OBJECTIVE); - if(!unregisterEvent.isCancelled()) { + if (!unregisterEvent.isCancelled()) { try { sidebarObjective.unregister(); } catch (IllegalStateException e) { @@ -419,7 +419,7 @@ public class ScoreboardWrapper { LogUtils.debug(mcMMO.p.getLogger(), "Recovering scoreboard for player: " + player.getName()); - if(mmoPlayer.isDebugMode()) + if (mmoPlayer.isDebugMode()) NotificationManager.sendPlayerInformationChatOnlyPrefixed(player, "Scoreboard.Recovery"); initBoard(); //Start over @@ -429,7 +429,7 @@ public class ScoreboardWrapper { //Register objective McMMOScoreboardObjectiveEvent registerEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.REGISTER_NEW_OBJECTIVE); - if(!registerEvent.isCancelled()) + if (!registerEvent.isCancelled()) sidebarObjective = registerEvent.getTargetBoard().registerNewObjective(ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy", SIDE_OBJECTIVE); if (displayName.length() > 32) { @@ -453,7 +453,7 @@ public class ScoreboardWrapper { * Load new values into the sidebar. */ private void updateSidebar() { - if(updateTask != null) { + if (updateTask != null) { try { updateTask.cancel(); } catch (Exception e) { @@ -477,7 +477,7 @@ public class ScoreboardWrapper { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; switch (sidebarType) { diff --git a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java index 8be5e4195..55d02ba31 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java @@ -61,7 +61,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -72,12 +72,12 @@ public final class CombatUtils { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.SWORDS); } - if(target.getHealth() - event.getFinalDamage() > 0) { + if (target.getHealth() - event.getFinalDamage() > 0) { swordsManager.processRupture(target); } //Add Stab Damage - if(swordsManager.canUseStab()) + if (swordsManager.canUseStab()) { boostedDamage += (swordsManager.getStabDamage() * mcMMOPlayer.getAttackStrength()); } @@ -86,7 +86,7 @@ public final class CombatUtils { swordsManager.serratedStrikes(target, event.getDamage()); } - if(canUseLimitBreak(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) + if (canUseLimitBreak(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -98,11 +98,11 @@ public final class CombatUtils { } private static void printFinalDamageDebug(@NotNull Player player, @NotNull EntityDamageByEntityEvent event, @NotNull McMMOPlayer mcMMOPlayer, @Nullable String @Nullable ... extraInfoLines) { - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { player.sendMessage("Final Damage value after mcMMO modifiers: "+ event.getFinalDamage()); - if(extraInfoLines != null) { + if (extraInfoLines != null) { for(String str : extraInfoLines) { - if(str != null) + if (str != null) player.sendMessage(str); } } @@ -119,7 +119,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -133,7 +133,7 @@ public final class CombatUtils { boostedDamage += (tridentsManager.impaleDamageBonus() * mcMMOPlayer.getAttackStrength()); } - if(canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { + if (canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -153,7 +153,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -163,7 +163,7 @@ public final class CombatUtils { boostedDamage += (tridentsManager.impaleDamageBonus() * mcMMOPlayer.getAttackStrength()); } - if(canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { + if (canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -180,7 +180,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { delayArrowMetaCleanup(arrow); return; } @@ -192,7 +192,7 @@ public final class CombatUtils { boostedDamage = mcMMOPlayer.getCrossbowsManager().poweredShot(initialDamage); } - if(canUseLimitBreak(player, target, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { + if (canUseLimitBreak(player, target, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { boostedDamage+=getLimitBreakDamage(player, target, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK); } @@ -222,13 +222,13 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } // MacesManager macesManager = mcMMOPlayer.getMacesManager(); - if(canUseLimitBreak(player, target, SubSkillType.MACES_MACES_LIMIT_BREAK)) { + if (canUseLimitBreak(player, target, SubSkillType.MACES_MACES_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.MACES_MACES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -248,7 +248,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -277,7 +277,7 @@ public final class CombatUtils { boostedDamage+=(axesManager.criticalHit(target, boostedDamage) * mcMMOPlayer.getAttackStrength()); } - if(canUseLimitBreak(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK)) + if (canUseLimitBreak(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK)) { boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -298,7 +298,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -320,7 +320,7 @@ public final class CombatUtils { unarmedManager.disarmCheck((Player) target); } - if(canUseLimitBreak(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) + if (canUseLimitBreak(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -335,11 +335,11 @@ public final class CombatUtils { double initialDamage = event.getDamage(); double boostedDamage = initialDamage; - if(master != null && master.isOnline() && master.isValid()) { + if (master != null && master.isOnline() && master.isValid()) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -372,7 +372,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { delayArrowMetaCleanup(arrow); return; } @@ -394,7 +394,7 @@ public final class CombatUtils { archeryManager.retrieveArrows(target, arrow); } - if(canUseLimitBreak(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) + if (canUseLimitBreak(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { boostedDamage+=getLimitBreakDamage(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK); } @@ -402,7 +402,7 @@ public final class CombatUtils { double distanceMultiplier = ArcheryManager.distanceXpBonusMultiplier(target, arrow); double forceMultiplier = 1.0; //Hacky Fix - some plugins spawn arrows and assign them to players after the ProjectileLaunchEvent fires - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) forceMultiplier = arrow.getMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE).get(0).asDouble(); event.setDamage(boostedDamage); @@ -431,7 +431,7 @@ public final class CombatUtils { } if (target instanceof Player player) { - if(ExperienceConfig.getInstance().isNPCInteractionPrevented()) { + if (ExperienceConfig.getInstance().isNPCInteractionPrevented()) { if (Misc.isNPCEntityExcludingVillagers(target)) { return; } @@ -549,7 +549,7 @@ public final class CombatUtils { if (projectileSource instanceof Player player) { if (!Misc.isNPCEntityExcludingVillagers(player)) { - if(mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { + if (mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { processTridentCombatRanged(trident, target, player, event); } } @@ -561,9 +561,9 @@ public final class CombatUtils { if (projectileSource instanceof Player player) { if (!Misc.isNPCEntityExcludingVillagers(player)) { - if(!isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.ARCHERY, target)) { + if (!isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.ARCHERY, target)) { processArcheryCombat(target, player, event, arrow); - } else if(isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.CROSSBOWS, target)) { + } else if (isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.CROSSBOWS, target)) { processCrossbowsCombat(target, player, event, arrow); } } else { @@ -576,7 +576,7 @@ public final class CombatUtils { && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.TAMING)) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; TamingManager tamingManager = mcMMOPlayer.getTamingManager(); @@ -594,7 +594,7 @@ public final class CombatUtils { { List metadataValue = entity.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY); - if(metadataValue.size() <= 0) + if (metadataValue.size() <= 0) return; OldName oldName = (OldName) metadataValue.get(0); @@ -612,7 +612,7 @@ public final class CombatUtils { * @return the RAW damage bonus from Limit Break which is applied before reductions */ public static int getLimitBreakDamage(@NotNull Player attacker, @NotNull LivingEntity defender, @NotNull SubSkillType subSkillType) { - if(defender instanceof Player playerDefender) { + if (defender instanceof Player playerDefender) { return getLimitBreakDamageAgainstQuality(attacker, subSkillType, getArmorQualityLevel(playerDefender)); } else { return getLimitBreakDamageAgainstQuality(attacker, subSkillType, 1000); @@ -630,11 +630,11 @@ public final class CombatUtils { public static int getLimitBreakDamageAgainstQuality(@NotNull Player attacker, @NotNull SubSkillType subSkillType, int armorQualityLevel) { int rawDamageBoost = RankUtils.getRank(attacker, subSkillType); - if(armorQualityLevel <= 4) { + if (armorQualityLevel <= 4) { rawDamageBoost *= .25; //75% Nerf - } else if(armorQualityLevel <= 8) { + } else if (armorQualityLevel <= 8) { rawDamageBoost *= .50; //50% Nerf - } else if(armorQualityLevel <= 12) { + } else if (armorQualityLevel <= 12) { rawDamageBoost *= .75; //25% Nerf } @@ -650,7 +650,7 @@ public final class CombatUtils { int armorQualityLevel = 0; for(ItemStack itemStack : defender.getInventory().getArmorContents()) { - if(itemStack != null) { + if (itemStack != null) { armorQualityLevel += getArmorQuality(itemStack); } } @@ -673,7 +673,7 @@ public final class CombatUtils { * @return true if the player has access to the limit break */ public static boolean canUseLimitBreak(@NotNull Player player, LivingEntity target, @NotNull SubSkillType subSkillType) { - if(target instanceof Player || mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { + if (target instanceof Player || mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { return RankUtils.hasUnlockedSubskill(player, subSkillType) && Permissions.isSubSkillEnabled(player, subSkillType); } else { @@ -826,7 +826,7 @@ public final class CombatUtils { McMMOPlayer mmoAttacker = UserManager.getPlayer(attacker); - if(mmoAttacker != null) { + if (mmoAttacker != null) { mmoAttacker.getSwordsManager().processRupture(livingEntity); } @@ -923,17 +923,17 @@ public final class CombatUtils { } } - if(hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) { + if (hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) { baseXP = 0; - } else if(hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) { + } else if (hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) { baseXP *= ExperienceConfig.getInstance().getSpawnedMobXpMultiplier(); - } else if(hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) { + } else if (hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getNetherPortalXpMultiplier(); - } else if(hasMobFlag(MobMetaFlagType.EGG_MOB, target)) { + } else if (hasMobFlag(MobMetaFlagType.EGG_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getEggXpMultiplier(); } else if (hasMobFlag(MobMetaFlagType.PLAYER_BRED_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getBredMobXpMultiplier(); - } else if(hasMobFlag(MobMetaFlagType.PLAYER_TAMED_MOB, target)) { + } else if (hasMobFlag(MobMetaFlagType.PLAYER_TAMED_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getTamedMobXpMultiplier(); } @@ -958,14 +958,14 @@ public final class CombatUtils { private static boolean shouldBeAffected(@NotNull Player player, @NotNull Entity entity) { if (entity instanceof Player defender) { //TODO: NPC Interaction? - if(UserManager.getPlayer(defender) == null) + if (UserManager.getPlayer(defender) == null) return true; if (!defender.getWorld().getPVP() || defender == player || UserManager.getPlayer(defender).getGodMode()) { return false; } - if(mcMMO.p.getPartyConfig().isPartyEnabled()) { + if (mcMMO.p.getPartyConfig().isPartyEnabled()) { if ((mcMMO.p.getPartyManager().inSameParty(player, defender) || mcMMO.p.getPartyManager().areAllies(player, defender)) && !(Permissions.friendlyFire(player) && Permissions.friendlyFire(defender))) { return false; } @@ -1077,7 +1077,7 @@ public final class CombatUtils { public static void modifyMoveSpeed(@NotNull LivingEntity livingEntity, double multiplier) { AttributeInstance attributeInstance = livingEntity.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED); - if(attributeInstance != null) { + if (attributeInstance != null) { double normalSpeed = attributeInstance.getBaseValue(); attributeInstance.setBaseValue(normalSpeed * multiplier); } diff --git a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java index 48265d03f..7cd22a75f 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java @@ -82,7 +82,7 @@ public final class ParticleEffectUtils { return; } - if(location.getWorld() == null) + if (location.getWorld() == null) return; location.getWorld().playEffect(location, Effect.MOBSPAWNER_FLAMES, 1); @@ -91,7 +91,7 @@ public final class ParticleEffectUtils { public static void playSmokeEffect(Location location) { World world = location.getWorld(); - if(world == null) + if (world == null) return; // Have to do it this way, because not all block directions are valid for smoke diff --git a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java index ca651cd52..9891582f9 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java @@ -54,7 +54,7 @@ public final class PerksUtils { double modifier = 1.0F; if (Permissions.customXpBoost(player, skill)) { - if(UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { + if (UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.DARK_GRAY + "XP Perk Multiplier IS CUSTOM! "); } @@ -84,7 +84,7 @@ public final class PerksUtils { float modifiedXP = (float) (xp * modifier); - if(UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { + if (UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "XP Perk Multiplier - " + ChatColor.GOLD + modifier); player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "Original XP before perk boosts " + ChatColor.RED + (double) xp); player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "XP AFTER PERKS " + ChatColor.DARK_RED + modifiedXP); diff --git a/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java b/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java index f64bac7a3..4835afc47 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java @@ -29,54 +29,54 @@ public class ProjectileUtils { */ // TODO: Add test public static void cleanupProjectileMetadata(@NotNull Arrow arrow) { - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT, mcMMO.p); } } public static void copyArrowMetadata(@NotNull Plugin pluginRef, @NotNull Arrow arrowToCopy, @NotNull Arrow newArrow) { - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_INF_ARROW).get(0)); } - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, new FixedMetadataValue(pluginRef, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE).get(0).asDouble())); } - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE).get(0)); } - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW).get(0)); } - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW).get(0)); } diff --git a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java index e06497128..38a730d7b 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java @@ -36,15 +36,15 @@ public class RankUtils { HashMap innerMap = subSkillRanks.get(subSkillType.toString()); //If the skill doesn't have registered ranks gtfo - if(innerMap == null || innerMap.get(playerRankInSkill) == null) + if (innerMap == null || innerMap.get(playerRankInSkill) == null) continue; //Don't send notifications if the player lacks the permission node - if(!Permissions.isSubSkillEnabled(mcMMOPlayer.getPlayer(), subSkillType)) + if (!Permissions.isSubSkillEnabled(mcMMOPlayer.getPlayer(), subSkillType)) continue; //The players level is the exact level requirement for this skill - if(newLevel == innerMap.get(playerRankInSkill)) + if (newLevel == innerMap.get(playerRankInSkill)) { SkillUnlockNotificationTask skillUnlockNotificationTask = new SkillUnlockNotificationTask(mcMMOPlayer, subSkillType, newLevel); @@ -180,19 +180,19 @@ public class RankUtils { String skillName = subSkillType.toString(); int numRanks = subSkillType.getNumRanks(); - if(subSkillRanks == null) + if (subSkillRanks == null) subSkillRanks = new HashMap<>(); - if(numRanks == 0) + if (numRanks == 0) return -1; //-1 Means the skill doesn't have ranks - if(subSkillRanks.get(skillName) == null && numRanks > 0) + if (subSkillRanks.get(skillName) == null && numRanks > 0) addRanks(subSkillType); //Get our rank map HashMap rankMap = subSkillRanks.get(skillName); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return 0; //Skill level of parent skill @@ -205,11 +205,11 @@ public class RankUtils { int unlockLevel = getRankUnlockLevel(subSkillType, rank); //If we check all ranks and still cannot unlock the skill, we return rank 0 - if(rank == 0) + if (rank == 0) return 0; //True if our skill level can unlock the current rank - if(currentSkillLevel >= unlockLevel) + if (currentSkillLevel >= unlockLevel) return rank; } @@ -227,19 +227,19 @@ public class RankUtils { String skillName = abstractSubSkill.getConfigKeyName(); int numRanks = abstractSubSkill.getNumRanks(); - if(subSkillRanks == null) + if (subSkillRanks == null) subSkillRanks = new HashMap<>(); - if(numRanks == 0) + if (numRanks == 0) return -1; //-1 Means the skill doesn't have ranks - if(subSkillRanks.get(skillName) == null && numRanks > 0) + if (subSkillRanks.get(skillName) == null && numRanks > 0) addRanks(abstractSubSkill); //Get our rank map HashMap rankMap = subSkillRanks.get(skillName); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return 0; //Skill level of parent skill @@ -252,11 +252,11 @@ public class RankUtils { int unlockLevel = getRankUnlockLevel(abstractSubSkill, rank); //If we check all ranks and still cannot unlock the skill, we return rank 0 - if(rank == 0) + if (rank == 0) return 0; //True if our skill level can unlock the current rank - if(currentSkillLevel >= unlockLevel) + if (currentSkillLevel >= unlockLevel) return rank; } diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java b/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java index d9f25db2c..151c7e649 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java @@ -69,7 +69,7 @@ public class SkillTools { for(SubSkillType subSkillType : SubSkillType.values()) { String[] splitSubSkillName = subSkillType.toString().split("_"); - if(primarySkillType1.toString().equalsIgnoreCase(splitSubSkillName[0])) { + if (primarySkillType1.toString().equalsIgnoreCase(splitSubSkillName[0])) { //Parent Skill Found tempSubParentMap.put(subSkillType, primarySkillType1); } @@ -127,7 +127,7 @@ public class SkillTools { PrimarySkillType parent = getSuperAbilityParent(superAbilityType); tempAbilityParentRelationshipMap.put(superAbilityType, parent); - if(superAbilityType != SuperAbilityType.BLAST_MINING) { + if (superAbilityType != SuperAbilityType.BLAST_MINING) { //This map is used only for abilities that have a tool readying phase, so blast mining is ignored tempMainActivatedAbilityChildMap.put(parent, superAbilityType); } @@ -296,7 +296,7 @@ public class SkillTools { } public SuperAbilityType getSuperAbility(PrimarySkillType primarySkillType) { - if(mainActivatedAbilityChildMap.get(primarySkillType) == null) + if (mainActivatedAbilityChildMap.get(primarySkillType) == null) return null; return mainActivatedAbilityChildMap.get(primarySkillType); diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java index 20b9afd3d..c83389f8b 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java @@ -61,7 +61,7 @@ public final class SkillUtils { int length; - if(abilityLengthCap > 0) + if (abilityLengthCap > 0) { length = (int) Math.min(abilityLengthCap, 2 + (skillValue / abilityLengthVar)); } else { @@ -142,7 +142,7 @@ public final class SkillUtils { if (HiddenConfig.getInstance().useEnchantmentBuffs()) { ItemStack heldItem = player.getInventory().getItemInMainHand(); - if(heldItem == null) + if (heldItem == null) return; if (!ItemUtils.canBeSuperAbilityDigBoosted(heldItem)) { @@ -171,7 +171,7 @@ public final class SkillUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Not Loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; PrimarySkillType skill = mcMMOPlayer.getAbilityMode(SuperAbilityType.SUPER_BREAKER) ? PrimarySkillType.MINING : PrimarySkillType.EXCAVATION; @@ -181,7 +181,7 @@ public final class SkillUtils { int ticks; - if(abilityLengthCap > 0) + if (abilityLengthCap > 0) { ticks = PerksUtils.handleActivationPerks(player, Math.min(abilityLengthCap, 2 + (mcMMOPlayer.getSkillLevel(skill) / abilityLengthVar)), mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR; @@ -202,18 +202,18 @@ public final class SkillUtils { } public static void removeAbilityBuff(@Nullable ItemStack itemStack) { - if(itemStack == null) + if (itemStack == null) return; - if(!ItemUtils.canBeSuperAbilityDigBoosted(itemStack)) + if (!ItemUtils.canBeSuperAbilityDigBoosted(itemStack)) return; //1.13.2+ will have persistent metadata for this itemStack - if(isLegacyAbilityTool(itemStack)) { + if (isLegacyAbilityTool(itemStack)) { ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta != null) { + if (itemMeta != null) { // This is safe to call without prior checks. itemMeta.removeEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency()); @@ -222,7 +222,7 @@ public final class SkillUtils { } } - if(isSuperAbilityBoosted(itemStack)) { + if (isSuperAbilityBoosted(itemStack)) { removeBonusDigSpeedOnSuperAbilityTool(itemStack); } } @@ -239,7 +239,7 @@ public final class SkillUtils { * @param maxDamageModifier the amount to adjust the max damage by */ public static void handleDurabilityChange(ItemStack itemStack, double durabilityModifier, double maxDamageModifier) { - if(itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { + if (itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { return; } @@ -269,7 +269,7 @@ public final class SkillUtils { * @param maxDamageModifier the amount to adjust the max damage by */ public static void handleArmorDurabilityChange(ItemStack itemStack, double durabilityModifier, double maxDamageModifier) { - if(itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { + if (itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { return; } @@ -315,7 +315,7 @@ public final class SkillUtils { public static int getRepairAndSalvageQuantities(Material itemMaterial, Material recipeMaterial) { int quantity = 0; - if(mcMMO.getMaterialMapStore().isNetheriteTool(itemMaterial) || mcMMO.getMaterialMapStore().isNetheriteArmor(itemMaterial)) { + if (mcMMO.getMaterialMapStore().isNetheriteTool(itemMaterial) || mcMMO.getMaterialMapStore().isNetheriteArmor(itemMaterial)) { //One netherite bar requires 4 netherite scraps return 4; } @@ -323,10 +323,10 @@ public final class SkillUtils { for(Iterator recipeIterator = Bukkit.getServer().recipeIterator(); recipeIterator.hasNext();) { Recipe bukkitRecipe = recipeIterator.next(); - if(bukkitRecipe.getResult().getType() != itemMaterial) + if (bukkitRecipe.getResult().getType() != itemMaterial) continue; - if(bukkitRecipe instanceof ShapelessRecipe) { + if (bukkitRecipe instanceof ShapelessRecipe) { for (ItemStack ingredient : ((ShapelessRecipe) bukkitRecipe).getIngredientList()) { if (ingredient != null && (recipeMaterial == null || ingredient.getType() == recipeMaterial) @@ -334,7 +334,7 @@ public final class SkillUtils { quantity += ingredient.getAmount(); } } - } else if(bukkitRecipe instanceof ShapedRecipe) { + } else if (bukkitRecipe instanceof ShapedRecipe) { for (ItemStack ingredient : ((ShapedRecipe) bukkitRecipe).getIngredientMap().values()) { if (ingredient != null && (recipeMaterial == null || ingredient.getType() == recipeMaterial) diff --git a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java index e3b21da03..8cfa7da25 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java @@ -15,13 +15,13 @@ public class SoundManager { */ public static void sendSound(Player player, Location location, SoundType soundType) { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), SoundCategory.MASTER, getVolume(soundType), getPitch(soundType)); } public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory) { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), getPitch(soundType)); } @@ -29,18 +29,18 @@ public class SoundManager { { float totalPitch = Math.min(2.0F, (getPitch(soundType) + pitchModifier)); - if(SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), totalPitch); } public static void worldSendSound(World world, Location location, SoundType soundType) { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) world.playSound(location, getSound(soundType), getVolume(soundType), getPitch(soundType)); } public static void worldSendSoundMaxPitch(World world, Location location, SoundType soundType) { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) world.playSound(location, getSound(soundType), getVolume(soundType), 2.0F); } @@ -56,7 +56,7 @@ public class SoundManager { private static float getPitch(SoundType soundType) { - if(soundType == SoundType.FIZZ) + if (soundType == SoundType.FIZZ) return getFizzPitch(); else if (soundType == SoundType.POP) return getPopPitch(); diff --git a/src/main/java/com/gmail/nossr50/util/text/StringUtils.java b/src/main/java/com/gmail/nossr50/util/text/StringUtils.java index a6fa01180..b906058fa 100644 --- a/src/main/java/com/gmail/nossr50/util/text/StringUtils.java +++ b/src/main/java/com/gmail/nossr50/util/text/StringUtils.java @@ -71,7 +71,7 @@ public class StringUtils { StringBuilder trimMessage = new StringBuilder(); for (int i = index; i < args.length; i++) { - if(i + 1 >= args.length) + if (i + 1 >= args.length) trimMessage.append(args[i]); else trimMessage.append(args[i]).append(" "); diff --git a/src/main/java/com/gmail/nossr50/util/text/TextUtils.java b/src/main/java/com/gmail/nossr50/util/text/TextUtils.java index 1d3c001d5..782bd5ccc 100644 --- a/src/main/java/com/gmail/nossr50/util/text/TextUtils.java +++ b/src/main/java/com/gmail/nossr50/util/text/TextUtils.java @@ -31,15 +31,15 @@ public class TextUtils { TextComponent.Builder componentBuilder = Component.text(); for(Component component : componentsArray) { - if(component == null) //Individual elements can be null + if (component == null) //Individual elements can be null continue; - if(prefixComponent != null) + if (prefixComponent != null) componentBuilder.append(prefixComponent); componentBuilder.append(component); - if(suffixComponent != null) + if (suffixComponent != null) componentBuilder.append(suffixComponent); } @@ -68,14 +68,14 @@ public class TextUtils { int indexOfPotentialMember = i + (groupsFinished * 3); //Groups don't always fill all members neatly //Some groups won't have entirely non-null elements - if(indexOfPotentialMember > components.size()-1) { + if (indexOfPotentialMember > components.size()-1) { break; } Component potentialMember = components.get(indexOfPotentialMember); //Make sure the potential member exists because of rounding - if(potentialMember != null) { + if (potentialMember != null) { splitGroups[groupsFinished][i] = potentialMember; } } @@ -113,7 +113,7 @@ public class TextUtils { } public static @NotNull TextComponent colorizeText(@NotNull String rawtext) { - if(customLegacySerializer == null) { + if (customLegacySerializer == null) { customLegacySerializer = getSerializer(); } @@ -139,7 +139,7 @@ public class TextUtils { } public static @NotNull String sanitizeForSerializer(@NotNull String string) { - if(customLegacySerializer == null) { + if (customLegacySerializer == null) { customLegacySerializer = getSerializer(); } diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java index 29b4e89c2..f95671275 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java @@ -19,7 +19,7 @@ public class WorldGuardManager { private WorldGuardPlugin worldGuardPluginRef; public static WorldGuardManager getInstance() { - if(instance == null) + if (instance == null) instance = new WorldGuardManager(); return instance; @@ -27,7 +27,7 @@ public class WorldGuardManager { public boolean hasMainFlag(Player player) { - if(player == null) + if (player == null) return false; BukkitPlayer localPlayer = BukkitAdapter.adapt(player); @@ -43,7 +43,7 @@ public class WorldGuardManager { public boolean hasXPFlag(Player player) { - if(player == null) + if (player == null) return false; BukkitPlayer localPlayer = BukkitAdapter.adapt(player); @@ -59,7 +59,7 @@ public class WorldGuardManager { public boolean hasHardcoreFlag(Player player) { - if(player == null) + if (player == null) return false; BukkitPlayer localPlayer = BukkitAdapter.adapt(player); diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java index d37f0a50c..82cf426da 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java @@ -43,7 +43,7 @@ public class WorldGuardUtils { public static boolean isWorldGuardLoaded() { - if(detectedIncompatibleWG) + if (detectedIncompatibleWG) return false; worldGuardPluginRef = getWorldGuard(); @@ -59,21 +59,21 @@ public class WorldGuardUtils { private static WorldGuardPlugin getWorldGuard() { //WG plugin reference is already cached so just return it - if(isLoaded) + if (isLoaded) return worldGuardPluginRef; //Grab WG if it exists Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard"); - if(plugin == null) { + if (plugin == null) { //WG is not present detectedIncompatibleWG = true; LogUtils.debug(mcMMO.p.getLogger(), "WorldGuard was not detected."); } else { //Check that its actually of class WorldGuardPlugin - if(plugin instanceof WorldGuardPlugin) + if (plugin instanceof WorldGuardPlugin) { - if(isCompatibleVersion(plugin)) + if (isCompatibleVersion(plugin)) { worldGuardPluginRef = (WorldGuardPlugin) plugin; isLoaded = true; @@ -119,8 +119,8 @@ public class WorldGuardUtils { * If WG appears to have all of its classes we can then check to see if its been initialized properly */ try { - if(allClassesFound) { - if(!((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).isInitialized()) { + if (allClassesFound) { + if (!((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).isInitialized()) { markWGIncompatible(); mcMMO.p.getLogger().severe("WG did not initialize properly, this can cause errors with mcMMO so mcMMO is disabling certain features."); } diff --git a/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java b/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java index 8e6d04c2a..c0c448bc7 100644 --- a/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java +++ b/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java @@ -293,7 +293,7 @@ class FlatFileDatabaseManagerTest { private void checkNewUserValues(@NotNull PlayerProfile playerProfile, int startingLevel) { //Checking a new user for being zero initialized for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(SkillTools.isChildSkill(primarySkillType)) + if (SkillTools.isChildSkill(primarySkillType)) continue; assertEquals(startingLevel, playerProfile.getSkillLevel(primarySkillType)); @@ -369,7 +369,7 @@ class FlatFileDatabaseManagerTest { assertNotNull(resourceFileURI); File copyOfFile = new File(tempDir.getPath() + File.separator + dbFileName); - if(copyOfFile.exists()) { + if (copyOfFile.exists()) { //noinspection ResultOfMethodCallIgnored copyOfFile.delete(); } @@ -397,7 +397,7 @@ class FlatFileDatabaseManagerTest { */ for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(SkillTools.isChildSkill(primarySkillType)) + if (SkillTools.isChildSkill(primarySkillType)) continue; int expectedLevelHealthyDBEntryOne = getExpectedLevelHealthyDBEntryOne(primarySkillType); @@ -594,7 +594,7 @@ class FlatFileDatabaseManagerTest { Map rankBoyPositions = flatFileDatabaseManager.readRank(rankBoyName); for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(primarySkillType.isChildSkill()) { + if (primarySkillType.isChildSkill()) { assertNull(rankBoyPositions.get(primarySkillType)); assertNull(rankGirlPositions.get(primarySkillType)); } else { @@ -623,7 +623,7 @@ class FlatFileDatabaseManagerTest { assertNotNull(resourceFileURI); File copyOfFile = new File(tempDir.getPath() + File.separator + DB_BADDATA); - if(copyOfFile.exists()) { + if (copyOfFile.exists()) { copyOfFile.delete(); } @@ -683,7 +683,7 @@ class FlatFileDatabaseManagerTest { assertEquals(uuid, leveledProfile.getUniqueId()); for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(SkillTools.isChildSkill(primarySkillType)) + if (SkillTools.isChildSkill(primarySkillType)) continue; leveledProfile.modifySkill(primarySkillType, levels); //TODO: This method also resets XP, not cool @@ -693,7 +693,7 @@ class FlatFileDatabaseManagerTest { leveledProfile = flatFileDatabaseManager.loadPlayerProfile(uuid); for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(SkillTools.isChildSkill(primarySkillType)) { + if (SkillTools.isChildSkill(primarySkillType)) { continue; } diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java index e114313ba..0a128cd52 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java @@ -93,7 +93,7 @@ class ProbabilityTest { double winCount = 0; for (int i = 0; i < iterations; i++) { - if(probability.evaluate()) { + if (probability.evaluate()) { winCount++; } } diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java index 0e41b4649..32dadfbbd 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java @@ -7,7 +7,7 @@ public class ProbabilityTestUtils { double iterations = 2.0e7; //20 million double winCount = 0; for (int i = 0; i < iterations; i++) { - if(probability.evaluate()) { + if (probability.evaluate()) { winCount++; } } From 8d2a08c421df133509f4f5d2f5ec2947d65a8296 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Mon, 13 May 2024 10:59:57 -0700 Subject: [PATCH 18/34] fix REGEN potion not loading --- Changelog.txt | 3 +- pom.xml | 2 +- .../com/gmail/nossr50/util/PotionUtil.java | 36 ++++++++-------- .../gmail/nossr50/util/PotionUtilTest.java | 42 ++++++++++--------- 4 files changed, 43 insertions(+), 40 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index c8c2107ae..0cd3c8ce6 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,6 +1,7 @@ Version 2.2.010 # TODO: Fix not moving mcMMO custom ingredients from hopper -> brewing stand # TODO: Fix some potions are not rewarding XP ( strength 2, etc ) + Fixed being unable to load REGEN potion type on new versions of Paper/Spigot 1.20.6 BrewingStand now remember who owns them, this persists across restarts (see notes) Fixed rare NPE in mcMMO events when player data was unable to be retrieved Fixed a NPE that could happen when damaging armor with Axes @@ -39,7 +40,7 @@ Version 2.2.010 NOTES: You can now use hoppers and brewing stands and not have to worry about having to re-interact with the brewing stand over and over again - This is not an exhaustive list of API changes in this update, but most of them should be documented here. + This is not an exhaustive list of API changes in this update, but most of the important ones should be documented here. Version 2.2.009 Fixed a bug that prevented mcMMO from loading on MC versions older than 1.20.6 diff --git a/pom.xml b/pom.xml index 294edc426..38bb18f62 100644 --- a/pom.xml +++ b/pom.xml @@ -374,7 +374,7 @@ org.spigotmc spigot-api - 1.20.5-R0.1-SNAPSHOT + 1.20.6-R0.1-SNAPSHOT provided diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java index 0661cd487..739059787 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionUtil.java +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -71,10 +71,10 @@ public class PotionUtil { * @return The potion type */ public static PotionType matchPotionType(String partialName, boolean isUpgraded, boolean isExtended) { + String updatedName = convertLegacyNames(partialName).toUpperCase(); if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { - return matchLegacyPotionType(partialName); + return matchLegacyPotionType(updatedName); } else { - String updatedName = convertLegacyNames(partialName); return Arrays.stream(PotionType.values()) .filter(potionType -> getKeyGetKey(potionType).toUpperCase().contains(partialName) || getKeyGetKey(potionType).toUpperCase().contains(convertLegacyNames(updatedName))) @@ -84,6 +84,21 @@ public class PotionUtil { } } + /** + * Legacy matching for {@link PotionType} + * + * @param name The partial name of the potion + * @return The potion type + */ + private static PotionType matchLegacyPotionType(String name) { + return Arrays.stream(PotionType.values()) + .filter(potionType -> getKeyGetKey(potionType).equalsIgnoreCase(name) + || getKeyGetKey(potionType).equalsIgnoreCase(convertLegacyNames(name)) + || potionType.name().equalsIgnoreCase(name) + || potionType.name().equalsIgnoreCase(convertLegacyNames(name))) + .findAny().orElse(null); + } + public static String getKeyGetKey(PotionType potionType) { try { if (getKeyMethod() != null) { @@ -201,23 +216,6 @@ public class PotionUtil { } } - /** - * Legacy matching for {@link PotionType} - * - * @param partialName The partial name of the potion - * @return The potion type - */ - private static PotionType matchLegacyPotionType(String partialName) { - String updatedName = convertLegacyNames(partialName); - - return Arrays.stream(PotionType.values()) - .filter(potionType -> getKeyGetKey(potionType).equalsIgnoreCase(partialName) - || getKeyGetKey(potionType).equalsIgnoreCase(convertLegacyNames(updatedName)) - || potionType.name().equalsIgnoreCase(partialName) - || potionType.name().equalsIgnoreCase(convertLegacyNames(updatedName))) - .findAny().orElse(null); - } - public static String convertPotionConfigName(String legacyName) { String replacementName = legacyName; diff --git a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java index d60c0f7cb..e3e5dae20 100644 --- a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java @@ -1,35 +1,39 @@ package com.gmail.nossr50.util; +import org.bukkit.potion.PotionType; import org.junit.jupiter.api.Test; import static com.gmail.nossr50.util.PotionUtil.convertLegacyNames; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; import static org.junit.jupiter.api.Assertions.assertEquals; class PotionUtilTest { -// @Test -// void testMatchPotionType() { -// String potionTypeStr = "UNCRAFTABLE"; -// PotionType potionType = matchPotionType(potionTypeStr, false, false); -// assertEquals(PotionType.WATER, potionType); -// -// String potionTypeStr2 = "NIGHT_VISION"; -// PotionType potionType2 = matchPotionType(potionTypeStr2, false, false); -// assertEquals(PotionType.NIGHT_VISION, potionType2); -// -// String nightVisionLong = "NIGHT_VISION"; -// PotionType potionType3 = matchPotionType(nightVisionLong, false, true); -// assertEquals(PotionType.LONG_NIGHT_VISION, potionType3); -// -// nightVisionLong = "LONG_NIGHT_VISION"; -// potionType3 = matchPotionType(nightVisionLong, false, true); -// assertEquals(PotionType.LONG_NIGHT_VISION, potionType3); -// } + @Test + void testMatchPotionTypeRegen() { + final String potionTypeStr = "REGEN"; + final PotionType potionType = matchPotionType(potionTypeStr, false, false); + assertEquals(PotionType.REGENERATION, potionType); + } @Test - void testConvertLegacyNames() { + void testMatchPotionTypeUncraftable() { + final String potionTypeStr = "UNCRAFTABLE"; + final PotionType potionType = matchPotionType(potionTypeStr, false, false); + assertEquals(PotionType.MUNDANE, potionType); + } + + @Test + void testConvertLegacyNamesUncraftable() { final String potionTypeStr = "UNCRAFTABLE"; final String converted = convertLegacyNames(potionTypeStr); assertEquals("MUNDANE", converted); } + + @Test + void testConvertLegacyNamesRegen() { + final String potionTypeStr = "REGEN"; + final String converted = convertLegacyNames(potionTypeStr); + assertEquals("REGENERATION", converted); + } } \ No newline at end of file From fc66c9f3fd67f1501a13e786a21b1cd1004f2e22 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Wed, 15 May 2024 15:56:50 -0700 Subject: [PATCH 19/34] 2.2.010 --- Changelog.txt | 6 ++-- pom.xml | 2 +- .../config/skills/alchemy/PotionConfig.java | 22 ++++++++----- .../skills/alchemy/AlchemyPotion.java | 33 +++++++++++-------- .../datatypes/skills/alchemy/PotionStage.java | 1 + .../nossr50/util/PotionCompatibilityType.java | 2 +- .../com/gmail/nossr50/util/PotionUtil.java | 23 +++++++++---- .../gmail/nossr50/util/PotionUtilTest.java | 31 +++++++++++++++++ 8 files changed, 87 insertions(+), 33 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index 0cd3c8ce6..9f85db54e 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,8 +1,7 @@ Version 2.2.010 - # TODO: Fix not moving mcMMO custom ingredients from hopper -> brewing stand - # TODO: Fix some potions are not rewarding XP ( strength 2, etc ) Fixed being unable to load REGEN potion type on new versions of Paper/Spigot 1.20.6 - BrewingStand now remember who owns them, this persists across restarts (see notes) + Fixed some potions not gaining XP when brewed (Level 2 potions, etc) + BrewingStands will now remember who owns them, this persists across restarts (see notes) Fixed rare NPE in mcMMO events when player data was unable to be retrieved Fixed a NPE that could happen when damaging armor with Axes Fixed a bug where Alchemy brewing would be cancelled if the player died @@ -40,6 +39,7 @@ Version 2.2.010 NOTES: You can now use hoppers and brewing stands and not have to worry about having to re-interact with the brewing stand over and over again + Ownership of a brewing stand is whoever last interacted with it, this persists across restarts This is not an exhaustive list of API changes in this update, but most of the important ones should be documented here. Version 2.2.009 diff --git a/pom.xml b/pom.xml index 38bb18f62..8567d1d1b 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.010-SNAPSHOT + 2.2.010 mcMMO https://github.com/mcMMO-Dev/mcMMO diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 9aadac89f..5c9e023b7 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; import static com.gmail.nossr50.util.ItemUtils.setItemName; import static com.gmail.nossr50.util.PotionUtil.matchPotionType; @@ -39,7 +40,7 @@ public class PotionConfig extends LegacyConfigLoader { /** * Map of potion names to AlchemyPotion objects. */ - private final Map loadedPotions = new HashMap<>(); + private final Map alchemyPotions = new HashMap<>(); public PotionConfig() { super("potions.yml"); @@ -106,7 +107,7 @@ public class PotionConfig extends LegacyConfigLoader { AlchemyPotion potion = loadPotion(potionSection.getConfigurationSection(potionName)); if (potion != null) { - loadedPotions.put(potionName, potion); + alchemyPotions.put(potionName, potion); potionsLoaded++; } else { failures++; @@ -250,7 +251,7 @@ public class PotionConfig extends LegacyConfigLoader { // TODO: Might not need to .setItemMeta itemStack.setItemMeta(potionMeta); - return new AlchemyPotion(itemStack, children); + return new AlchemyPotion(potion_section.getName(), itemStack, children); } catch (Exception e) { mcMMO.p.getLogger().warning("PotionConfig: Failed to load Alchemy potion: " + potion_section.getName()); return null; @@ -325,7 +326,7 @@ public class PotionConfig extends LegacyConfigLoader { * @return AlchemyPotion that corresponds to the given name. */ public AlchemyPotion getPotion(String name) { - return loadedPotions.get(name); + return alchemyPotions.get(name); } /** @@ -336,12 +337,15 @@ public class PotionConfig extends LegacyConfigLoader { * @return AlchemyPotion that corresponds to the given ItemStack. */ public AlchemyPotion getPotion(ItemStack item) { - for (AlchemyPotion potion : loadedPotions.values()) { - if (potion.isSimilarPotion(item)) { - return potion; - } + final List potionList = alchemyPotions.values() + .stream() + .filter(potion -> potion.isSimilarPotion(item)) + .toList(); + if(potionList.size() > 1) { + mcMMO.p.getLogger().severe("Multiple child potions matched for item, when there should only be one: " + item); } - return null; + + return potionList.isEmpty() ? null : potionList.get(0); } public Color generateColor(List effects) { diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java index fb5ea7899..51be1cde9 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java @@ -15,16 +15,19 @@ import static com.gmail.nossr50.util.PotionUtil.samePotionType; import static java.util.Objects.requireNonNull; public class AlchemyPotion { - private final @NotNull ItemStack potionItemstack; + private final @NotNull String potionConfigName; + private final @NotNull ItemStack potionItemStack; private final @NotNull Map alchemyPotionChildren; - public AlchemyPotion(@NotNull ItemStack potionItemStack, @NotNull Map alchemyPotionChildren) { - this.potionItemstack = requireNonNull(potionItemStack, "potionItemStack cannot be null"); + public AlchemyPotion(@NotNull String potionConfigName, @NotNull ItemStack potionItemStack, @NotNull Map alchemyPotionChildren) { + this.potionConfigName = requireNonNull(potionConfigName, "potionConfigName cannot be null"); + this.potionItemStack = requireNonNull(potionItemStack, "potionItemStack cannot be null"); this.alchemyPotionChildren = requireNonNull(alchemyPotionChildren, "alchemyPotionChildren cannot be null"); + // mcMMO.p.getLogger().info("AlchemyPotion created: " + potionConfigName + ", with children: " + alchemyPotionChildren); } public @NotNull ItemStack toItemStack(int amount) { - final ItemStack clone = potionItemstack.clone(); + final ItemStack clone = potionItemStack.clone(); clone.setAmount(Math.max(1, amount)); return clone; } @@ -46,9 +49,12 @@ public class AlchemyPotion { public boolean isSimilarPotion(@NotNull ItemStack otherPotion) { requireNonNull(otherPotion, "otherPotion cannot be null"); - // TODO: Investigate? - // We currently don't compare base potion effects, likely because they are derived from the potion type - if (otherPotion.getType() != potionItemstack.getType() || !otherPotion.hasItemMeta()) { + if (otherPotion.getType() != potionItemStack.getType()) { + return false; + } + + // no potion meta, no match + if (!otherPotion.hasItemMeta()) { return false; } @@ -97,15 +103,15 @@ public class AlchemyPotion { } public PotionMeta getAlchemyPotionMeta() { - return (PotionMeta) potionItemstack.getItemMeta(); + return (PotionMeta) potionItemStack.getItemMeta(); } public boolean isSplash() { - return potionItemstack.getType() == Material.SPLASH_POTION; + return potionItemStack.getType() == Material.SPLASH_POTION; } public boolean isLingering() { - return potionItemstack.getType() == Material.LINGERING_POTION; + return potionItemStack.getType() == Material.LINGERING_POTION; } @Override @@ -113,18 +119,19 @@ public class AlchemyPotion { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlchemyPotion that = (AlchemyPotion) o; - return Objects.equals(potionItemstack, that.potionItemstack) && Objects.equals(alchemyPotionChildren, that.alchemyPotionChildren); + return Objects.equals(potionConfigName, that.potionConfigName) && Objects.equals(potionItemStack, that.potionItemStack) && Objects.equals(alchemyPotionChildren, that.alchemyPotionChildren); } @Override public int hashCode() { - return Objects.hash(potionItemstack, alchemyPotionChildren); + return Objects.hash(potionConfigName, potionItemStack, alchemyPotionChildren); } @Override public String toString() { return "AlchemyPotion{" + - "potion=" + potionItemstack + + "potionConfigName='" + potionConfigName + '\'' + + ", potionItemStack=" + potionItemStack + ", alchemyPotionChildren=" + alchemyPotionChildren + '}'; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java index 7825c717f..64bf65009 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.datatypes.skills.alchemy; import com.gmail.nossr50.util.PotionUtil; +import org.bukkit.Bukkit; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; diff --git a/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java b/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java index ea070814d..0b19748a5 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java +++ b/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java @@ -2,5 +2,5 @@ package com.gmail.nossr50.util; public enum PotionCompatibilityType { PRE_1_20_5, - POST_1_20_5 + POST_1_20_6 } diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java index 739059787..0debc5ab8 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionUtil.java +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -58,10 +58,11 @@ public class PotionUtil { methodPotionTypeGetPotionEffects = getPotionTypeGetPotionEffects(); methodSetBasePotionData = getSetBasePotionData(); - if (potionDataClass != null) { + if (potionDataClass != null + && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 20, 5)) { COMPATIBILITY_MODE = PotionCompatibilityType.PRE_1_20_5; } else { - COMPATIBILITY_MODE = PotionCompatibilityType.POST_1_20_5; + COMPATIBILITY_MODE = PotionCompatibilityType.POST_1_20_6; } } @@ -71,13 +72,13 @@ public class PotionUtil { * @return The potion type */ public static PotionType matchPotionType(String partialName, boolean isUpgraded, boolean isExtended) { - String updatedName = convertLegacyNames(partialName).toUpperCase(); + // updatedName = convertUpgradedOrExtended(updatedName, isUpgraded, isExtended); if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { - return matchLegacyPotionType(updatedName); + return matchLegacyPotionType(partialName); } else { + String updatedName = convertLegacyNames(partialName).toUpperCase(); return Arrays.stream(PotionType.values()) - .filter(potionType -> getKeyGetKey(potionType).toUpperCase().contains(partialName) - || getKeyGetKey(potionType).toUpperCase().contains(convertLegacyNames(updatedName))) + .filter(potionType -> getKeyGetKey(potionType).toUpperCase().contains(updatedName)) .filter(potionType -> !isUpgraded || potionType.name().toUpperCase().contains(STRONG)) .filter(potionType -> !isExtended || potionType.name().toUpperCase().contains(LONG)) .findAny().orElse(null); @@ -99,6 +100,16 @@ public class PotionUtil { .findAny().orElse(null); } + private static String convertUpgradedOrExtended(String potionType, boolean isUpgraded, boolean isExtended) { + if (isUpgraded) { + potionType = STRONG + "_" + potionType; + } + if (isExtended) { + potionType = LONG + "_" + potionType; + } + return potionType; + } + public static String getKeyGetKey(PotionType potionType) { try { if (getKeyMethod() != null) { diff --git a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java index e3e5dae20..299496320 100644 --- a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java @@ -1,14 +1,45 @@ package com.gmail.nossr50.util; +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.compat.CompatibilityManager; +import com.gmail.nossr50.util.platform.MinecraftGameVersion; import org.bukkit.potion.PotionType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; import static com.gmail.nossr50.util.PotionUtil.convertLegacyNames; import static com.gmail.nossr50.util.PotionUtil.matchPotionType; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; class PotionUtilTest { + MockedStatic mockedStaticMcMMO; + + @BeforeEach + void setUp() { + mockedStaticMcMMO = mockStatic(mcMMO.class); + CompatibilityManager compatibilityManager = mock(CompatibilityManager.class); + MinecraftGameVersion minecraftGameVersion = mock(MinecraftGameVersion.class); + when(compatibilityManager.getMinecraftGameVersion()).thenReturn(minecraftGameVersion); + when(minecraftGameVersion.isAtLeast(1, 20, 5)).thenReturn(true); + when(mcMMO.getCompatibilityManager()).thenReturn(compatibilityManager); + } + + @AfterEach + void tearDown() { + mockedStaticMcMMO.close(); + } + + @Test + void testMatchPotionTypeStrengthII() { + final String potionTypeStr = "STRENGTH"; + final PotionType potionType = matchPotionType(potionTypeStr, true, false); + assertEquals(PotionType.STRONG_STRENGTH, potionType); + } + @Test void testMatchPotionTypeRegen() { final String potionTypeStr = "REGEN"; From e6ff219a5c92d899ee417532bf9f690f700c58cd Mon Sep 17 00:00:00 2001 From: nossr50 Date: Fri, 17 May 2024 11:59:24 -0700 Subject: [PATCH 20/34] more verbose logging for alchemy potion lookups --- Changelog.txt | 7 ++++++ pom.xml | 2 +- .../config/skills/alchemy/PotionConfig.java | 6 ++++- .../skills/alchemy/AlchemyPotion.java | 23 +++++++++++-------- 4 files changed, 27 insertions(+), 11 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index 9f85db54e..0b4b870d6 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,3 +1,10 @@ +Version 2.2.011 + Improved logging for Alchemy potion look up (see notes) + +NOTES: + Added detailed logging when multiple configured potions match an ItemStack. + This will help identify issues with potion configuration. + Version 2.2.010 Fixed being unable to load REGEN potion type on new versions of Paper/Spigot 1.20.6 Fixed some potions not gaining XP when brewed (Level 2 potions, etc) diff --git a/pom.xml b/pom.xml index 8567d1d1b..7feea2206 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.010 + 2.2.011-SNAPSHOT mcMMO https://github.com/mcMMO-Dev/mcMMO diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 5c9e023b7..626719921 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -342,7 +342,11 @@ public class PotionConfig extends LegacyConfigLoader { .filter(potion -> potion.isSimilarPotion(item)) .toList(); if(potionList.size() > 1) { - mcMMO.p.getLogger().severe("Multiple child potions matched for item, when there should only be one: " + item); + mcMMO.p.getLogger().severe("Multiple potions defined in config have match this potion, for mcMMO to behave" + + " properly there should only be one match found."); + mcMMO.p.getLogger().severe("Potion ItemStack:" + item.toString()); + mcMMO.p.getLogger().severe("Alchemy Potions from config matching this item: " + + potionList.stream().map(AlchemyPotion::toString).collect(Collectors.joining(", "))); } return potionList.isEmpty() ? null : potionList.get(0); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java index 51be1cde9..146894008 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java @@ -19,11 +19,11 @@ public class AlchemyPotion { private final @NotNull ItemStack potionItemStack; private final @NotNull Map alchemyPotionChildren; - public AlchemyPotion(@NotNull String potionConfigName, @NotNull ItemStack potionItemStack, @NotNull Map alchemyPotionChildren) { + public AlchemyPotion(@NotNull String potionConfigName, @NotNull ItemStack potionItemStack, + @NotNull Map alchemyPotionChildren) { this.potionConfigName = requireNonNull(potionConfigName, "potionConfigName cannot be null"); this.potionItemStack = requireNonNull(potionItemStack, "potionItemStack cannot be null"); this.alchemyPotionChildren = requireNonNull(alchemyPotionChildren, "alchemyPotionChildren cannot be null"); - // mcMMO.p.getLogger().info("AlchemyPotion created: " + potionConfigName + ", with children: " + alchemyPotionChildren); } public @NotNull ItemStack toItemStack(int amount) { @@ -32,7 +32,7 @@ public class AlchemyPotion { return clone; } - public Map getAlchemyPotionChildren() { + public @NotNull Map getAlchemyPotionChildren() { return alchemyPotionChildren; } @@ -58,6 +58,10 @@ public class AlchemyPotion { return false; } + /* + * Compare custom effects on both potions. + */ + final PotionMeta otherPotionMeta = (PotionMeta) otherPotion.getItemMeta(); // compare custom effects on both potions, this has to be done in two traversals // comparing thisPotionMeta -> otherPotionMeta and otherPotionMeta -> thisPotionMeta @@ -70,17 +74,18 @@ public class AlchemyPotion { return false; } + /* + * If one potion has lore and the other does not, then they are not the same potion. + * If both have lore, compare the lore. + * If neither have lore, they may be the same potion. + */ if (!otherPotionMeta.hasLore() && getAlchemyPotionMeta().hasLore() || !getAlchemyPotionMeta().hasLore() && otherPotionMeta.hasLore()) { return false; } - if (otherPotionMeta.hasLore() && getAlchemyPotionMeta().hasLore() - && !otherPotionMeta.getLore().equals(getAlchemyPotionMeta().getLore())) { - return false; - } - - return true; + return !otherPotionMeta.hasLore() || !getAlchemyPotionMeta().hasLore() + || otherPotionMeta.getLore().equals(getAlchemyPotionMeta().getLore()); } private boolean hasDifferingCustomEffects(PotionMeta potionMeta, PotionMeta otherPotionMeta) { From 46c9ea5a25647befa56c502aa9989e2099118584 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Fri, 17 May 2024 17:22:58 -0700 Subject: [PATCH 21/34] 2.2.011 --- Changelog.txt | 1 + pom.xml | 2 +- .../config/skills/alchemy/PotionConfig.java | 50 ++++++------ .../skills/alchemy/AlchemyPotion.java | 6 ++ .../nossr50/util/PotionCompatibilityType.java | 2 +- .../com/gmail/nossr50/util/PotionUtil.java | 81 +++++++++++++++---- 6 files changed, 98 insertions(+), 44 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index 0b4b870d6..fa2ac2762 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,4 +1,5 @@ Version 2.2.011 + Fixed bug where some potions on older versions (1.20.4 and older) were not brewable (night vision extended, etc) Improved logging for Alchemy potion look up (see notes) NOTES: diff --git a/pom.xml b/pom.xml index 7feea2206..51cac0c77 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.011-SNAPSHOT + 2.2.011 mcMMO https://github.com/mcMMO-Dev/mcMMO diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 626719921..ecc16e66e 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -24,7 +24,7 @@ import java.util.Map; import java.util.stream.Collectors; import static com.gmail.nossr50.util.ItemUtils.setItemName; -import static com.gmail.nossr50.util.PotionUtil.matchPotionType; +import static com.gmail.nossr50.util.PotionUtil.*; public class PotionConfig extends LegacyConfigLoader { @@ -177,32 +177,14 @@ public class PotionConfig extends LegacyConfigLoader { return null; } - PotionType potionType = matchPotionType(potionTypeStr, upgraded, extended); - if (potionType == null) { - // try matching to key - mcMMO.p.getLogger().warning("Failed to match potion type, trying to match with config key..."); - matchPotionType(key, upgraded, extended); - } - - if (potionType == null) { - mcMMO.p.getLogger().severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr - + ", upgraded: " + upgraded + ", extended: " + extended + " for potion " + key - + ", from configuration section: " + potion_section); + // This works via side effects + // TODO: Redesign later, side effects are stupid + if(!setPotionType(potionMeta, potionTypeStr, upgraded, extended)) { + mcMMO.p.getLogger().severe("PotionConfig: Failed to set parameters of potion for " + key + ": " + potionTypeStr); return null; } - // Set base potion type - // NOTE: extended/ignored are effectively ignored here on 1.20.5 and later - PotionUtil.setBasePotionType(potionMeta, potionType, extended, upgraded); - -// // Use the name of the potion to indicate upgrade status if not set in PotionData -// if (convertPotionConfigName(key).toUpperCase().contains("STRONG")) -// upgraded = true; -// -// if (convertPotionConfigName(key).toUpperCase().contains("LONG")) -// extended = true; - - List lore = new ArrayList<>(); + final List lore = new ArrayList<>(); if (potion_section.contains("Lore")) { for (String line : potion_section.getStringList("Lore")) { lore.add(ChatColor.translateAlternateColorCodes('&', line)); @@ -245,7 +227,6 @@ public class PotionConfig extends LegacyConfigLoader { } } } - // Set the name of the potion setPotionDisplayName(potion_section, potionMeta); @@ -254,10 +235,27 @@ public class PotionConfig extends LegacyConfigLoader { return new AlchemyPotion(potion_section.getName(), itemStack, children); } catch (Exception e) { mcMMO.p.getLogger().warning("PotionConfig: Failed to load Alchemy potion: " + potion_section.getName()); + e.printStackTrace(); return null; } } + private boolean setPotionType(PotionMeta potionMeta, String potionTypeStr, boolean upgraded, boolean extended) { + final PotionType potionType = matchPotionType(potionTypeStr, upgraded, extended); + + if (potionType == null) { + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr); + return false; + } + + // set base + setBasePotionType(potionMeta, potionType, extended, upgraded); + + // Legacy only + setUpgradedAndExtendedProperties(potionType, potionMeta, upgraded, extended); + return true; + } + private void setPotionDisplayName(ConfigurationSection section, PotionMeta potionMeta) { // If a potion doesn't have any custom effects, there is no reason to override the vanilla name if (potionMeta.getCustomEffects().isEmpty()) { @@ -342,7 +340,7 @@ public class PotionConfig extends LegacyConfigLoader { .filter(potion -> potion.isSimilarPotion(item)) .toList(); if(potionList.size() > 1) { - mcMMO.p.getLogger().severe("Multiple potions defined in config have match this potion, for mcMMO to behave" + + mcMMO.p.getLogger().severe("Multiple potions defined in config have matched this potion, for mcMMO to behave" + " properly there should only be one match found."); mcMMO.p.getLogger().severe("Potion ItemStack:" + item.toString()); mcMMO.p.getLogger().severe("Alchemy Potions from config matching this item: " diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java index 146894008..0b0654dda 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.datatypes.skills.alchemy; import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.PotionUtil; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.PotionMeta; @@ -74,6 +75,11 @@ public class AlchemyPotion { return false; } + // Legacy only comparison, compare PotionData + if (!PotionUtil.isPotionDataEqual(getAlchemyPotionMeta(), otherPotionMeta)) { + return false; + } + /* * If one potion has lore and the other does not, then they are not the same potion. * If both have lore, compare the lore. diff --git a/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java b/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java index 0b19748a5..6981644b3 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java +++ b/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java @@ -2,5 +2,5 @@ package com.gmail.nossr50.util; public enum PotionCompatibilityType { PRE_1_20_5, - POST_1_20_6 + MODERN } diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java index 0debc5ab8..b369250fe 100644 --- a/src/main/java/com/gmail/nossr50/util/PotionUtil.java +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -25,9 +25,9 @@ public class PotionUtil { private static final Method methodPotionDataIsExtended; private static final Method methodPotionDataGetType; private static final Method methodPotionMetaGetBasePotionData; + private static final Method methodPotionMetaSetBasePotionData; private static final Method methodPotionMetaGetBasePotionType; private static final Method methodPotionMetaSetBasePotionType; - private static final Method methodSetBasePotionData; private static final Class potionDataClass; public static final String STRONG = "STRONG"; @@ -49,20 +49,20 @@ public class PotionUtil { legacyPotionTypes.put("REGEN", "REGENERATION"); methodPotionTypeGetKey = getKeyMethod(); methodPotionDataIsUpgraded = getPotionDataIsUpgraded(); - methodPotionDataIsExtended = getIsExtended(); - methodPotionMetaGetBasePotionData = getBasePotionData(); - methodPotionMetaGetBasePotionType = getBasePotionType(); + methodPotionDataIsExtended = getPotionDataIsExtended(); + methodPotionMetaGetBasePotionData = getGetBasePotionDataMethod(); + methodPotionMetaGetBasePotionType = getGetBasePotionTypeMethod(); methodPotionMetaSetBasePotionType = getMethodPotionMetaSetBasePotionType(); - methodPotionDataGetType = getPotionDataGetType(); - methodPotionTypeGetEffectType = getPotionTypeEffectType(); - methodPotionTypeGetPotionEffects = getPotionTypeGetPotionEffects(); - methodSetBasePotionData = getSetBasePotionData(); + methodPotionDataGetType = getPotionDataGetTypeMethod(); + methodPotionTypeGetEffectType = getPotionTypeEffectTypeMethod(); + methodPotionTypeGetPotionEffects = getPotionTypeGetPotionEffectsMethod(); + methodPotionMetaSetBasePotionData = setBasePotionData(); if (potionDataClass != null && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 20, 5)) { COMPATIBILITY_MODE = PotionCompatibilityType.PRE_1_20_5; } else { - COMPATIBILITY_MODE = PotionCompatibilityType.POST_1_20_6; + COMPATIBILITY_MODE = PotionCompatibilityType.MODERN; } } @@ -145,6 +145,14 @@ public class PotionUtil { } } + private static @Nullable Method setBasePotionData() { + try { + return PotionMeta.class.getMethod("setBasePotionData", potionDataClass); + } catch (NoSuchMethodException e) { + return null; + } + } + private static Method getMethodPotionMetaSetBasePotionType() { try { return PotionMeta.class.getMethod("setBasePotionType", PotionType.class); @@ -171,7 +179,7 @@ public class PotionUtil { } } - private static @Nullable Method getIsExtended() { + private static @Nullable Method getPotionDataIsExtended() { try { // TODO: Needed? final Class clazz = Class.forName("org.bukkit.potion.PotionData"); @@ -186,7 +194,7 @@ public class PotionUtil { * * @return the getBasePotionData method, or null if it does not exist */ - private static @Nullable Method getBasePotionData() { + private static @Nullable Method getGetBasePotionDataMethod() { try { return PotionMeta.class.getMethod("getBasePotionData"); } catch (NoSuchMethodException e) { @@ -194,7 +202,7 @@ public class PotionUtil { } } - private static Method getBasePotionType() { + private static Method getGetBasePotionTypeMethod() { try { return PotionMeta.class.getMethod("getBasePotionType"); } catch (NoSuchMethodException e) { @@ -202,7 +210,7 @@ public class PotionUtil { } } - private static Method getPotionDataGetType() { + private static Method getPotionDataGetTypeMethod() { try { final Class clazz = Class.forName("org.bukkit.potion.PotionData"); return clazz.getMethod("getType"); @@ -211,7 +219,7 @@ public class PotionUtil { } } - private static Method getPotionTypeEffectType() { + private static Method getPotionTypeEffectTypeMethod() { try { return PotionType.class.getMethod("getEffectType"); } catch (NoSuchMethodException e) { @@ -219,7 +227,7 @@ public class PotionUtil { } } - private static Method getPotionTypeGetPotionEffects() { + private static Method getPotionTypeGetPotionEffectsMethod() { try { return PotionType.class.getMethod("getPotionEffects"); } catch (NoSuchMethodException e) { @@ -474,12 +482,28 @@ public class PotionUtil { } } + public static void setUpgradedAndExtendedProperties(PotionType potionType, PotionMeta potionMeta, + boolean isUpgraded, boolean isExtended) { + if (potionDataClass == null || mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 20, 5)) { + return; + } + + try { + final Object potionData = potionDataClass.getConstructor(PotionType.class, boolean.class, boolean.class) + .newInstance(potionType, isExtended, isUpgraded); + methodPotionMetaSetBasePotionData.invoke(potionMeta, potionData); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException + | NoSuchMethodException ex) { + throw new RuntimeException(ex); + } + } + private static void setBasePotionTypeLegacy(PotionMeta potionMeta, PotionType potionType, boolean extended, boolean upgraded) { try { Object potionData = potionDataClass.getConstructor(PotionType.class, boolean.class, boolean.class) .newInstance(potionType, extended, upgraded); - methodSetBasePotionData.invoke(potionMeta, potionData); + methodPotionMetaSetBasePotionData.invoke(potionMeta, potionData); } catch (IllegalAccessException | InvocationTargetException | InstantiationException | NoSuchMethodException ex) { throw new RuntimeException(ex); } @@ -492,4 +516,29 @@ public class PotionUtil { throw new RuntimeException(ex); } } + + public static boolean isPotionDataEqual(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.MODERN) { + return true; // we don't compare data on newer versions + } else { + try { + final Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + final Object otherPotionData = methodPotionMetaGetBasePotionData.invoke(otherPotionMeta); + final PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); + final PotionType otherPotionType = (PotionType) methodPotionDataGetType.invoke(otherPotionData); + if (potionType != otherPotionType) { + return false; + } + if (methodPotionDataIsExtended.invoke(potionData) != methodPotionDataIsExtended.invoke(otherPotionData)) { + return false; + } + if (methodPotionDataIsUpgraded.invoke(potionData) != methodPotionDataIsUpgraded.invoke(otherPotionData)) { + return false; + } + return true; + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + } } From c2054a5d456cb1648f1cea9183ddcec69b1442f7 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sat, 18 May 2024 12:30:44 -0700 Subject: [PATCH 22/34] 2.2.012 fix for daze in 1.20.4 and older --- Changelog.txt | 3 + pom.xml | 3 +- .../skills/archery/ArcheryManager.java | 4 +- .../nossr50/util/PotionEffectMapper.java | 142 ------------------ .../gmail/nossr50/util/PotionEffectUtil.java | 92 ++++++++++++ .../gmail/nossr50/util/skills/SkillUtils.java | 8 +- .../nossr50/util/PotionEffectUtilTest.java | 58 +++++++ 7 files changed, 161 insertions(+), 149 deletions(-) delete mode 100644 src/main/java/com/gmail/nossr50/util/PotionEffectMapper.java create mode 100644 src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java create mode 100644 src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java diff --git a/Changelog.txt b/Changelog.txt index fa2ac2762..4641b529d 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,3 +1,6 @@ +Version 2.2.012 + Fixed a bug where Daze would cause an exception in older game versions (1.20.4 and older) + Version 2.2.011 Fixed bug where some potions on older versions (1.20.4 and older) were not brewable (night vision extended, etc) Improved logging for Alchemy potion look up (see notes) diff --git a/pom.xml b/pom.xml index 51cac0c77..a8ce46efc 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.011 + 2.2.012 mcMMO https://github.com/mcMMO-Dev/mcMMO @@ -80,6 +80,7 @@ org.junit.jupiter:junit-jupiter false + skip diff --git a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java index 16574621b..785fafd46 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java @@ -19,7 +19,7 @@ import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.potion.PotionEffect; -import static com.gmail.nossr50.util.PotionEffectMapper.getNausea; +import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; public class ArcheryManager extends SkillManager { public ArcheryManager(McMMOPlayer mcMMOPlayer) { @@ -97,7 +97,7 @@ public class ArcheryManager extends SkillManager { dazedLocation.setPitch(90 - Misc.getRandom().nextInt(181)); mcMMO.p.getFoliaLib().getImpl().teleportAsync(defender, dazedLocation); - defender.addPotionEffect(new PotionEffect(getNausea(), 20 * 10, 10)); + defender.addPotionEffect(new PotionEffect(getNauseaPotionEffectType(), 20 * 10, 10)); if (NotificationManager.doesPlayerUseNotifications(defender)) { NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Combat.TouchedFuzzy"); diff --git a/src/main/java/com/gmail/nossr50/util/PotionEffectMapper.java b/src/main/java/com/gmail/nossr50/util/PotionEffectMapper.java deleted file mode 100644 index f58c66834..000000000 --- a/src/main/java/com/gmail/nossr50/util/PotionEffectMapper.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.gmail.nossr50.util; - -import com.gmail.nossr50.mcMMO; -import org.bukkit.potion.PotionEffectType; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -final public class PotionEffectMapper { - private static final PotionEffectType haste; - private static final PotionEffectType nausea; - private static final Method potionEffectTypeWrapperGetPotionEffectType; - private static final Class classPotionEffectTypeWrapper; - - private PotionEffectMapper() { - // Utility class - } - - static { - potionEffectTypeWrapperGetPotionEffectType = getPotionEffectTypeWrapperGetPotionEffectType(); - classPotionEffectTypeWrapper = getClassPotionEffectTypeWrapper(); - - haste = initHaste(); - nausea = initNausea(); - } - - private static Method getPotionEffectTypeWrapperGetPotionEffectType() { - try { - return classPotionEffectTypeWrapper.getMethod("getType"); - } catch (NoSuchMethodException e) { - return null; - } - } - - private static Class getClassPotionEffectTypeWrapper() { - try { - return Class.forName("org.bukkit.potion.PotionEffectTypeWrapper"); - } catch (ClassNotFoundException e) { - return null; - } - } - - private static PotionEffectType initNausea() { - if (classPotionEffectTypeWrapper != null) { - return getNauseaLegacy(); - } else { - return getNauseaModern(); - } - } - - private static PotionEffectType getNauseaModern() { -// PotionEffectType potionEffectType = Registry.EFFECT.match("nausea"); -// if (potionEffectType != null) { -// return potionEffectType; -// } -// -// // Look for the potion effect type by name -// for (PotionEffectType pet : Registry.EFFECT) { -// if (pet.getKey().getKey().equalsIgnoreCase("CONFUSION") -// || pet.getKey().getKey().equalsIgnoreCase("NAUSEA") -// || pet.getName().equalsIgnoreCase("CONFUSION") -// || pet.getName().equalsIgnoreCase("NAUSEA")) { -// return pet; -// } -// } - - try { - return (PotionEffectType) PotionEffectType.class.getField("NAUSEA").get(null); - } catch (NoSuchFieldException | IllegalAccessException e) { - mcMMO.p.getLogger().severe("Unable to find the Nausea potion effect type, " + - "mcMMO will not function properly."); - throw new IllegalStateException("Unable to find the Nausea potion effect type"); - } - } - - private static PotionEffectType getNauseaLegacy() { - try { - Object potionEffectTypeWrapper = PotionEffectType.class.getField("CONFUSION").get(null); - PotionEffectType potionEffectType = (PotionEffectType) potionEffectTypeWrapperGetPotionEffectType - .invoke(potionEffectTypeWrapper); - return potionEffectType; - } catch (IllegalAccessException | NoSuchFieldException | InvocationTargetException e) { - mcMMO.p.getLogger().severe("Unable to find the Nausea potion effect type, " + - "mcMMO will not function properly."); - throw new IllegalStateException("Unable to find the Nausea potion effect type"); - } - } - - private static PotionEffectType initHaste() { - - - mcMMO.p.getLogger().severe("Unable to find the Haste potion effect type, " + - "mcMMO will not function properly."); - throw new IllegalStateException("Unable to find the Haste potion effect type"); - } - - private static PotionEffectType getHasteLegacy() { - try { - Object potionEffectTypeWrapper = PotionEffectType.class.getField("FAST_DIGGING").get(null); - PotionEffectType potionEffectType = (PotionEffectType) potionEffectTypeWrapperGetPotionEffectType - .invoke(potionEffectTypeWrapper); - return potionEffectType; - } catch (IllegalAccessException | NoSuchFieldException | InvocationTargetException e) { - mcMMO.p.getLogger().severe("Unable to find the Haste potion effect type, " + - "mcMMO will not function properly."); - throw new IllegalStateException("Unable to find the Haste potion effect type"); - } - } - - private static PotionEffectType getHasteModern() { -// PotionEffectType potionEffectType = Registry.EFFECT.match("haste"); -// if (potionEffectType != null) { -// return potionEffectType; -// } -// -// // Look for the potion effect type by name -// for (PotionEffectType pet : Registry.EFFECT) { -// if (pet.getKey().getKey().equalsIgnoreCase("HASTE") -// || pet.getKey().getKey().equalsIgnoreCase("FAST_DIGGING") -// || pet.getName().equalsIgnoreCase("HASTE") -// || pet.getName().equalsIgnoreCase("FAST_DIGGING")) { -// return pet; -// } -// } - - try { - return (PotionEffectType) PotionEffectType.class.getField("HASTE").get(null); - } catch (NoSuchFieldException | IllegalAccessException e) { - mcMMO.p.getLogger().severe("Unable to find the Haste potion effect type, " + - "mcMMO will not function properly."); - throw new IllegalStateException("Unable to find the Haste potion effect type"); - } - } - - public static PotionEffectType getHaste() { - return haste; - } - - public static PotionEffectType getNausea() { - return nausea; - } -} diff --git a/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java b/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java new file mode 100644 index 000000000..706cc8c9f --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java @@ -0,0 +1,92 @@ +package com.gmail.nossr50.util; + +import org.bukkit.potion.PotionEffectType; + +/** + * This util class is responsible for mapping the correct potion effect types for the server version. + * This is necessary because the potion effect types have changed between versions. + * This util class will provide the correct potion effect types for the server version. + */ +final public class PotionEffectUtil { + private static final PotionEffectType haste; + private static final PotionEffectType nausea; + + static { + haste = findHastePotionEffectType(); + nausea = findNauseaPotionEffectType(); + } + + private PotionEffectUtil() { + // Utility class + } + + private static PotionEffectType findNauseaPotionEffectType() { + if (getNauseaLegacy() != null) { + return getNauseaLegacy(); + } else { + return getNauseaModern(); + } + } + + private static PotionEffectType getNauseaModern() { + try { + return (PotionEffectType) PotionEffectType.class.getField("NAUSEA").get(null); + } catch (NoSuchFieldException | IllegalAccessException e) { + return null; + } + } + + private static PotionEffectType getNauseaLegacy() { + try { + Object potionEffectTypeWrapper = PotionEffectType.class.getField("CONFUSION").get(null); + return (PotionEffectType) potionEffectTypeWrapper; + } catch (IllegalAccessException | NoSuchFieldException e) { + return null; + } + } + + private static PotionEffectType findHastePotionEffectType() { + if (getHasteLegacy() != null) { + return getHasteLegacy(); + } else if (getHasteModern() != null) { + return getHasteModern(); + } else { + throw new IllegalStateException("Unable to find the Haste PotionEffectType"); + } + } + + private static PotionEffectType getHasteLegacy() { + try { + Object potionEffectTypeWrapper = PotionEffectType.class.getField("FAST_DIGGING").get(null); + return (PotionEffectType) potionEffectTypeWrapper; + } catch (IllegalAccessException | NoSuchFieldException e) { + return null; + } + } + + private static PotionEffectType getHasteModern() { + try { + return (PotionEffectType) PotionEffectType.class.getField("HASTE").get(null); + } catch (NoSuchFieldException | IllegalAccessException e) { + return null; + } + } + + /** + * Get the Haste potion effect type. + * This will return the correct potion effect type for the server version. + * @return The Haste potion effect type. + */ + public static PotionEffectType getHastePotionEffectType() { + return haste; + } + + /** + * Get the Nausea potion effect type. + * This will return the correct potion effect type for the server version. + * @return The Nausea potion effect type. + */ + public static PotionEffectType getNauseaPotionEffectType() { + return nausea; + } +} diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java index c83389f8b..02c6c47cb 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java @@ -33,7 +33,7 @@ import org.jetbrains.annotations.Nullable; import java.util.Iterator; import static com.gmail.nossr50.util.ItemMetadataUtils.*; -import static com.gmail.nossr50.util.PotionEffectMapper.getHaste; +import static com.gmail.nossr50.util.PotionEffectUtil.getHastePotionEffectType; public final class SkillUtils { /** @@ -158,9 +158,9 @@ public final class SkillUtils { int duration = 0; int amplifier = 0; - if (player.hasPotionEffect(getHaste())) { + if (player.hasPotionEffect(getHastePotionEffectType())) { for (PotionEffect effect : player.getActivePotionEffects()) { - if (effect.getType() == getHaste()) { + if (effect.getType() == getHastePotionEffectType()) { duration = effect.getDuration(); amplifier = effect.getAmplifier(); break; @@ -190,7 +190,7 @@ public final class SkillUtils { mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR; } - PotionEffect abilityBuff = new PotionEffect(getHaste(), duration + ticks, amplifier + 10); + PotionEffect abilityBuff = new PotionEffect(getHastePotionEffectType(), duration + ticks, amplifier + 10); player.addPotionEffect(abilityBuff, true); } } diff --git a/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java new file mode 100644 index 000000000..1618988e9 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java @@ -0,0 +1,58 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.compat.CompatibilityManager; +import com.gmail.nossr50.util.platform.MinecraftGameVersion; +import org.bukkit.potion.PotionEffectType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; +import static java.util.logging.Logger.getLogger; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; + +class PotionEffectUtilTest { + private MockedStatic mockedStaticMcMMO; + private static final java.util.logging.Logger logger = getLogger(PotionEffectUtilTest.class.getName()); + + @BeforeEach + void setUp() { + mockedStaticMcMMO = mockStatic(mcMMO.class); + mcMMO.p = mock(mcMMO.class); + when(mcMMO.p.getLogger()).thenReturn(logger); + CompatibilityManager compatibilityManager = mock(CompatibilityManager.class); + MinecraftGameVersion minecraftGameVersion = mock(MinecraftGameVersion.class); + when(compatibilityManager.getMinecraftGameVersion()).thenReturn(minecraftGameVersion); + when(minecraftGameVersion.isAtLeast(1, 20, 5)).thenReturn(false); + when(mcMMO.getCompatibilityManager()).thenReturn(compatibilityManager); + } + + @AfterEach + void tearDown() { + mockedStaticMcMMO.close(); + } + + @Test + @Tag("skip") + void testGetNauseaPotionEffectType() { + // TODO: Test only works on older versions since we aren't properly mocking the spigot registry + final PotionEffectType nausea = getNauseaPotionEffectType(); + assertNotNull(nausea); + assertThat(nausea).isEqualTo(PotionEffectType.NAUSEA); + } + + @Test + @Tag("skip") + void testGetHastePotionEffectType() { + // TODO: Test only works on older versions since we aren't properly mocking the spigot registry + final PotionEffectType haste = PotionEffectUtil.getHastePotionEffectType(); + assertNotNull(haste); + assertThat(haste).isEqualTo(PotionEffectType.HASTE); + } +} \ No newline at end of file From 8b82163e3d06d9dc827202cd223ba15c61e0c73f Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 12:44:34 -0700 Subject: [PATCH 23/34] update UserBlockTracker API --- Changelog.txt | 8 + pom.xml | 2 +- .../config/skills/alchemy/PotionConfig.java | 1 - .../datatypes/skills/alchemy/PotionStage.java | 1 - .../nossr50/listeners/BlockListener.java | 10 +- .../nossr50/listeners/EntityListener.java | 9 +- .../nossr50/listeners/PlayerListener.java | 2 +- .../nossr50/listeners/WorldListener.java | 2 +- .../nossr50/runnables/PistonTrackerTask.java | 47 --- .../runnables/StickyPistonTrackerTask.java | 4 +- .../skills/AlchemyBrewCheckTask.java | 2 - .../skills/herbalism/HerbalismManager.java | 12 +- .../nossr50/skills/mining/MiningManager.java | 4 +- .../woodcutting/WoodcuttingManager.java | 6 +- .../com/gmail/nossr50/util/BlockUtils.java | 4 +- .../nossr50/util/TransientEntityTracker.java | 1 - .../util/blockmeta/HashChunkManager.java | 28 +- .../util/blockmeta/NullChunkManager.java | 22 +- .../util/blockmeta/UserBlockTracker.java | 118 +++++- .../nossr50/util/PotionEffectUtilTest.java | 3 +- .../util/blockmeta/BitSetChunkStoreTest.java | 121 ++++++ .../util/blockmeta/BlockStoreTestUtils.java | 49 +++ .../util/blockmeta/ChunkStoreTest.java | 378 +----------------- .../util/blockmeta/LegacyChunkStore.java | 127 ++++++ .../blockmeta/UnitTestObjectOutputStream.java | 23 ++ .../util/blockmeta/UserBlockTrackerTest.java | 192 +++++++++ 26 files changed, 708 insertions(+), 468 deletions(-) delete mode 100644 src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java create mode 100644 src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java create mode 100644 src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java create mode 100644 src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java create mode 100644 src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java create mode 100644 src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java diff --git a/Changelog.txt b/Changelog.txt index 4641b529d..4515641b0 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,3 +1,11 @@ +Version 2.2.013 + (API) Added new methods to com.gmail.nossr50.util.blockmeta.UserBlockTracker for easier readability + (API) Deprecated the old poorly named methods in UserBlockTracker + (Codebase) Cleaned up and organized unit tests relating to UserBlockTracker + + NOTES: + Not planning to delete the deprecated methods in UserBlockTracker anytime soon, as nothing has really changed other than the names + Version 2.2.012 Fixed a bug where Daze would cause an exception in older game versions (1.20.4 and older) diff --git a/pom.xml b/pom.xml index a8ce46efc..dbfe0175c 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.012 + 2.2.013-SNAPSHOT mcMMO https://github.com/mcMMO-Dev/mcMMO diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index ecc16e66e..d0cad88b5 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -4,7 +4,6 @@ import com.gmail.nossr50.config.LegacyConfigLoader; import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.ItemUtils; -import com.gmail.nossr50.util.PotionUtil; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java index 64bf65009..7825c717f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java @@ -1,7 +1,6 @@ package com.gmail.nossr50.datatypes.skills.alchemy; import com.gmail.nossr50.util.PotionUtil; -import org.bukkit.Bukkit; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; diff --git a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java index 5e6ea6a78..23e17af53 100644 --- a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java @@ -310,7 +310,7 @@ public class BlockListener implements Listener { // Minecraft is dumb, the events still throw when a plant "grows" higher than the max block height. Even though no new block is created if (BlockUtils.isWithinWorldBounds(block)) { - mcMMO.getPlaceStore().setFalse(block); + mcMMO.getPlaceStore().setEligible(block); } } @@ -400,14 +400,14 @@ public class BlockListener implements Listener { else if (BlockUtils.affectedBySuperBreaker(blockState) && (ItemUtils.isPickaxe(heldItem) || ItemUtils.isHoe(heldItem)) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.MINING) - && !mcMMO.getPlaceStore().isTrue(blockState)) { + && !mcMMO.getPlaceStore().isIneligible(blockState)) { MiningManager miningManager = mcMMOPlayer.getMiningManager(); miningManager.miningBlockCheck(blockState); } /* WOOD CUTTING */ else if (BlockUtils.hasWoodcuttingXP(blockState) && ItemUtils.isAxe(heldItem) - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) && !mcMMO.getPlaceStore().isTrue(blockState)) { + && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) && !mcMMO.getPlaceStore().isIneligible(blockState)) { WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager(); if (woodcuttingManager.canUseTreeFeller(heldItem)) { woodcuttingManager.processTreeFeller(blockState); @@ -422,7 +422,7 @@ public class BlockListener implements Listener { } /* EXCAVATION */ - else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) && !mcMMO.getPlaceStore().isTrue(blockState)) { + else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) && !mcMMO.getPlaceStore().isIneligible(blockState)) { ExcavationManager excavationManager = mcMMOPlayer.getExcavationManager(); excavationManager.excavationBlockCheck(blockState); @@ -687,7 +687,7 @@ public class BlockListener implements Listener { if (UserManager.getPlayer(player).isDebugMode()) { - if (mcMMO.getPlaceStore().isTrue(blockState)) + if (mcMMO.getPlaceStore().isIneligible(blockState)) player.sendMessage("[mcMMO DEBUG] This block is not natural and does not reward treasures/XP"); else { diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index 5e3002a15..fb36629de 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -44,7 +44,6 @@ import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.projectiles.ProjectileSource; -import org.jetbrains.annotations.NotNull; import static com.gmail.nossr50.util.MobMetadataUtils.*; @@ -207,8 +206,8 @@ public class EntityListener implements Listener { if (entity instanceof FallingBlock || entity instanceof Enderman) { boolean isTracked = entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK); - if (mcMMO.getPlaceStore().isTrue(block) && !isTracked) { - mcMMO.getPlaceStore().setFalse(block); + if (mcMMO.getPlaceStore().isIneligible(block) && !isTracked) { + mcMMO.getPlaceStore().setEligible(block); entity.setMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, MetadataConstants.MCMMO_METADATA_VALUE); TravelingBlockMetaCleanup metaCleanupTask = new TravelingBlockMetaCleanup(entity, pluginRef); @@ -222,8 +221,8 @@ public class EntityListener implements Listener { //Redstone ore fire this event and should be ignored } else { - if (mcMMO.getPlaceStore().isTrue(block)) { - mcMMO.getPlaceStore().setFalse(block); + if (mcMMO.getPlaceStore().isIneligible(block)) { + mcMMO.getPlaceStore().setEligible(block); } } } diff --git a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java index 28a321f88..e9b8daf62 100644 --- a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java @@ -852,7 +852,7 @@ public class PlayerListener implements Listener { case "NETHER_WART_BLOCK": case "POTATO": case "MANGROVE_PROPAGULE": - mcMMO.getPlaceStore().setFalse(blockState); + mcMMO.getPlaceStore().setEligible(blockState); break; } } diff --git a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java index aedecfea1..010185e9e 100644 --- a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java @@ -32,7 +32,7 @@ public class WorldListener implements Listener { // Using 50 ms later as I do not know of a way to run one tick later (safely) plugin.getFoliaLib().getImpl().runLater(() -> { for (BlockState blockState : event.getBlocks()) { - mcMMO.getPlaceStore().setFalse(blockState); + mcMMO.getPlaceStore().setEligible(blockState); } }, 1); } diff --git a/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java b/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java deleted file mode 100644 index d4e69c5bc..000000000 --- a/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gmail.nossr50.runnables; - -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.BlockUtils; -import com.gmail.nossr50.util.CancellableRunnable; -import com.gmail.nossr50.util.MetadataConstants; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; - -import java.util.List; - -public class PistonTrackerTask extends CancellableRunnable { - private final List blocks; - private final BlockFace direction; - private final Block futureEmptyBlock; - - public PistonTrackerTask(List blocks, BlockFace direction, Block futureEmptyBlock) { - this.blocks = blocks; - this.direction = direction; - this.futureEmptyBlock = futureEmptyBlock; - } - - @Override - public void run() { - // Check to see if futureEmptyBlock is empty - if it isn't; the blocks didn't move - if (!BlockUtils.isPistonPiece(futureEmptyBlock.getState())) { - return; - } - - if (mcMMO.getPlaceStore().isTrue(futureEmptyBlock)) { - mcMMO.getPlaceStore().setFalse(futureEmptyBlock); - } - - for (Block b : blocks) { - Block nextBlock = b.getRelative(direction); - - if (nextBlock.hasMetadata(MetadataConstants.METADATA_KEY_PISTON_TRACKING)) { - BlockUtils.setUnnaturalBlock(nextBlock); - nextBlock.removeMetadata(MetadataConstants.METADATA_KEY_PISTON_TRACKING, mcMMO.p); - } - else if (mcMMO.getPlaceStore().isTrue(nextBlock)) { - // Block doesn't have metadatakey but isTrue - set it to false - mcMMO.getPlaceStore().setFalse(nextBlock); - } - } - } -} diff --git a/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java b/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java index d8f52ae30..02590c53f 100644 --- a/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java @@ -19,7 +19,7 @@ public class StickyPistonTrackerTask extends CancellableRunnable { @Override public void run() { - if (!mcMMO.getPlaceStore().isTrue(movedBlock.getRelative(direction))) { + if (!mcMMO.getPlaceStore().isIneligible(movedBlock.getRelative(direction))) { return; } @@ -29,7 +29,7 @@ public class StickyPistonTrackerTask extends CancellableRunnable { } // The sticky piston actually pulled the block so move the PlaceStore data - mcMMO.getPlaceStore().setFalse(movedBlock.getRelative(direction)); + mcMMO.getPlaceStore().setEligible(movedBlock.getRelative(direction)); BlockUtils.setUnnaturalBlock(movedBlock); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java index 11618147e..640b498e8 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java @@ -2,7 +2,6 @@ package com.gmail.nossr50.runnables.skills; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.skills.alchemy.Alchemy; -import com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer; import com.gmail.nossr50.util.CancellableRunnable; import com.gmail.nossr50.util.ContainerMetadataUtils; import com.gmail.nossr50.util.player.UserManager; @@ -17,7 +16,6 @@ import org.jetbrains.annotations.Nullable; import java.util.Arrays; import static com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer.isValidBrew; -import static com.gmail.nossr50.util.EventUtils.getMcMMOPlayer; public class AlchemyBrewCheckTask extends CancellableRunnable { private final BrewingStand brewingStand; diff --git a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java index b60c33b7f..a93f6b3f7 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java @@ -282,7 +282,7 @@ public class HerbalismManager extends SkillManager { if (brokenPlant.getLocation().equals(originalBreak.getBlock().getLocation())) { //If its the same block as the original, we are going to directly check it for being a valid XP gain and add it to the nonChorusBlocks list even if its a chorus block //This stops a delay from happening when bringing up the XP bar for chorus trees - if (!mcMMO.getPlaceStore().isTrue(originalBreak)) { + if (!mcMMO.getPlaceStore().isIneligible(originalBreak)) { //Even if its a chorus block, the original break will be moved to nonChorusBlocks for immediate XP rewards noDelayPlantBlocks.add(brokenPlant); } else { @@ -335,7 +335,7 @@ public class HerbalismManager extends SkillManager { BlockData plantData = brokenPlantState.getBlockData(); //Check for double drops - if (!mcMMO.getPlaceStore().isTrue(brokenPlant)) { + if (!mcMMO.getPlaceStore().isIneligible(brokenPlant)) { /* * @@ -413,7 +413,7 @@ public class HerbalismManager extends SkillManager { BlockState brokenBlockNewState = brokenPlantBlock.getState(); BlockData plantData = brokenBlockNewState.getBlockData(); - if (mcMMO.getPlaceStore().isTrue(brokenBlockNewState)) { + if (mcMMO.getPlaceStore().isIneligible(brokenBlockNewState)) { /* * * Unnatural Blocks @@ -427,7 +427,7 @@ public class HerbalismManager extends SkillManager { } //Mark it as natural again as it is being broken - mcMMO.getPlaceStore().setFalse(brokenBlockNewState); + mcMMO.getPlaceStore().setEligible(brokenBlockNewState); } else { /* * @@ -489,9 +489,9 @@ public class HerbalismManager extends SkillManager { continue; } - if (mcMMO.getPlaceStore().isTrue(brokenBlockNewState)) { + if (mcMMO.getPlaceStore().isIneligible(brokenBlockNewState)) { //Mark it as natural again as it is being broken - mcMMO.getPlaceStore().setFalse(brokenBlockNewState); + mcMMO.getPlaceStore().setEligible(brokenBlockNewState); } else { //TODO: Do we care about chorus flower age? //Calculate XP for the old type diff --git a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java index 1d8738de2..a4c8eade0 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java @@ -181,7 +181,7 @@ public class MiningManager extends SkillManager { //Containers usually have 0 XP unless someone edited their config in a very strange way if (ExperienceConfig.getInstance().getXp(PrimarySkillType.MINING, targetBlock) != 0 && !(targetBlock instanceof Container) - && !mcMMO.getPlaceStore().isTrue(targetBlock)) { + && !mcMMO.getPlaceStore().isIneligible(targetBlock)) { if (BlockUtils.isOre(blockState)) { ores.add(blockState); } else { @@ -216,7 +216,7 @@ public class MiningManager extends SkillManager { Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_ORES); // Initial block that would have been dropped - if (mcMMO.p.getAdvancedConfig().isBlastMiningBonusDropsEnabled() && !mcMMO.getPlaceStore().isTrue(blockState)) { + if (mcMMO.p.getAdvancedConfig().isBlastMiningBonusDropsEnabled() && !mcMMO.getPlaceStore().isIneligible(blockState)) { for (int i = 1; i < dropMultiplier; i++) { // Bukkit.broadcastMessage("Bonus Drop on Ore: "+blockState.getType().toString()); Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_ORES_BONUS_DROP); // Initial block that would have been dropped diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java index 877f0cc24..b68cedad7 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java @@ -113,7 +113,7 @@ public class WoodcuttingManager extends SkillManager { } public void processWoodcuttingBlockXP(@NotNull BlockState blockState) { - if (mcMMO.getPlaceStore().isTrue(blockState)) + if (mcMMO.getPlaceStore().isIneligible(blockState)) return; int xp = getExperienceFromLog(blockState); @@ -269,7 +269,7 @@ public class WoodcuttingManager extends SkillManager { * in treeFellerBlocks. */ private boolean processTreeFellerTargetBlock(@NotNull BlockState blockState, @NotNull List futureCenterBlocks, @NotNull Set treeFellerBlocks) { - if (treeFellerBlocks.contains(blockState) || mcMMO.getPlaceStore().isTrue(blockState)) { + if (treeFellerBlocks.contains(blockState) || mcMMO.getPlaceStore().isIneligible(blockState)) { return false; } @@ -373,7 +373,7 @@ public class WoodcuttingManager extends SkillManager { * @return Amount of experience */ private static int processTreeFellerXPGains(BlockState blockState, int woodCount) { - if (mcMMO.getPlaceStore().isTrue(blockState)) + if (mcMMO.getPlaceStore().isIneligible(blockState)) return 0; int rawXP = ExperienceConfig.getInstance().getXp(PrimarySkillType.WOODCUTTING, blockState.getType()); diff --git a/src/main/java/com/gmail/nossr50/util/BlockUtils.java b/src/main/java/com/gmail/nossr50/util/BlockUtils.java index 56d1d698d..59245fc9d 100644 --- a/src/main/java/com/gmail/nossr50/util/BlockUtils.java +++ b/src/main/java/com/gmail/nossr50/util/BlockUtils.java @@ -65,7 +65,7 @@ public final class BlockUtils { * @param block target block */ public static void setUnnaturalBlock(@NotNull Block block) { - mcMMO.getPlaceStore().setTrue(block); + mcMMO.getPlaceStore().setIneligible(block); // Failsafe against lingering metadata if (block.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) @@ -82,7 +82,7 @@ public final class BlockUtils { block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p); } - mcMMO.getPlaceStore().setFalse(block); + mcMMO.getPlaceStore().setEligible(block); } /** diff --git a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java index ba410788d..c463077db 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java +++ b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java @@ -1,7 +1,6 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.datatypes.skills.subskills.taming.CallOfTheWildType; -import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.taming.TrackedTamingEntity; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.skills.ParticleEffectUtils; diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java index 5f38022d5..d572ec518 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java @@ -152,7 +152,7 @@ public class HashChunkManager implements ChunkManager { } } - private synchronized boolean isTrue(int x, int y, int z, @NotNull World world) { + private synchronized boolean isIneligible(int x, int y, int z, @NotNull World world) { CoordinateKey chunkKey = blockCoordinateToChunkKey(world.getUID(), x, y, z); // Get chunk, load from file if necessary @@ -178,32 +178,42 @@ public class HashChunkManager implements ChunkManager { } @Override - public synchronized boolean isTrue(@NotNull Block block) { - return isTrue(block.getX(), block.getY(), block.getZ(), block.getWorld()); + public synchronized boolean isIneligible(@NotNull Block block) { + return isIneligible(block.getX(), block.getY(), block.getZ(), block.getWorld()); } @Override - public synchronized boolean isTrue(@NotNull BlockState blockState) { - return isTrue(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld()); + public synchronized boolean isIneligible(@NotNull BlockState blockState) { + return isIneligible(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld()); } @Override - public synchronized void setTrue(@NotNull Block block) { + public synchronized boolean isEligible(@NotNull Block block) { + return !isIneligible(block); + } + + @Override + public synchronized boolean isEligible(@NotNull BlockState blockState) { + return !isIneligible(blockState); + } + + @Override + public synchronized void setIneligible(@NotNull Block block) { set(block.getX(), block.getY(), block.getZ(), block.getWorld(), true); } @Override - public synchronized void setTrue(@NotNull BlockState blockState) { + public synchronized void setIneligible(@NotNull BlockState blockState) { set(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld(), true); } @Override - public synchronized void setFalse(@NotNull Block block) { + public synchronized void setEligible(@NotNull Block block) { set(block.getX(), block.getY(), block.getZ(), block.getWorld(), false); } @Override - public synchronized void setFalse(@NotNull BlockState blockState) { + public synchronized void setEligible(@NotNull BlockState blockState) { set(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld(), false); } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java index 203376780..bc700b6e4 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java @@ -17,24 +17,34 @@ public class NullChunkManager implements ChunkManager { public void unloadWorld(@NotNull World world) {} @Override - public boolean isTrue(@NotNull Block block) { + public boolean isIneligible(@NotNull Block block) { return false; } @Override - public boolean isTrue(@NotNull BlockState blockState) { + public boolean isIneligible(@NotNull BlockState blockState) { return false; } @Override - public void setTrue(@NotNull Block block) {} + public boolean isEligible(@NotNull Block block) { + return false; + } @Override - public void setTrue(@NotNull BlockState blockState) {} + public boolean isEligible(@NotNull BlockState blockState) { + return false; + } @Override - public void setFalse(@NotNull Block block) {} + public void setIneligible(@NotNull Block block) {} @Override - public void setFalse(@NotNull BlockState blockState) {} + public void setIneligible(@NotNull BlockState blockState) {} + + @Override + public void setEligible(@NotNull Block block) {} + + @Override + public void setEligible(@NotNull BlockState blockState) {} } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java b/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java index e5428b0c1..501b16cfa 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java @@ -11,46 +11,136 @@ import org.jetbrains.annotations.NotNull; */ public interface UserBlockTracker { /** - * Check to see if a given block location is set to true + * Check to see if a given {@link Block} is ineligible for rewards. + * This is a location-based lookup, and the other properties of the {@link Block} do not matter. * - * @param block Block location to check - * @return true if the given block location is set to true, false if otherwise + * @param block Block to check + * @return true if the given block should not give rewards, false if otherwise */ - boolean isTrue(@NotNull Block block); + boolean isIneligible(@NotNull Block block); /** - * Check to see if a given BlockState location is set to true + * Check to see if a given {@link Block} is eligible for rewards. + * This is a location-based lookup, and the other properties of the {@link Block} do not matter. + * + * @param block Block to check + * @return true if the given block should give rewards, false if otherwise + */ + boolean isEligible(@NotNull Block block); + + /** + * Check to see if a given {@link BlockState} is eligible for rewards. + * This is a location-based lookup, and the other properties of the {@link BlockState} do not matter. * * @param blockState BlockState to check * @return true if the given BlockState location is set to true, false if otherwise */ - boolean isTrue(@NotNull BlockState blockState); + boolean isEligible(@NotNull BlockState blockState); /** - * Set a given block location to true + * Check to see if a given {@link BlockState} is ineligible for rewards. + * This is a location-based lookup, and the other properties of the {@link BlockState} do not matter. * - * @param block Block location to set + * @param blockState BlockState to check + * @return true if the given BlockState location is set to true, false if otherwise */ - void setTrue(@NotNull Block block); + boolean isIneligible(@NotNull BlockState blockState); + + /** + * Set a given {@link Block} as ineligible for rewards. + * This is a location-based lookup, and the other properties of the {@link Block} do not matter. + * + * @param block block whose location to set as ineligible + */ + void setIneligible(@NotNull Block block); /** * Set a given BlockState location to true * * @param blockState BlockState location to set */ - void setTrue(@NotNull BlockState blockState); + void setIneligible(@NotNull BlockState blockState); /** - * Set a given block location to false + * Set a given {@link Block} as eligible for rewards. + * This is a location-based lookup, and the other properties of the {@link Block} do not matter. * - * @param block Block location to set + * @param block block whose location to set as eligible */ - void setFalse(@NotNull Block block); + void setEligible(@NotNull Block block); /** * Set a given BlockState location to false * * @param blockState BlockState location to set */ - void setFalse(@NotNull BlockState blockState); + void setEligible(@NotNull BlockState blockState); + + /** + * Check to see if a given block location is set to true + * + * @param block Block location to check + * @return true if the given block location is set to true, false if otherwise + * @deprecated Use {@link #isIneligible(Block)} instead + */ + @Deprecated(since = "2.2.013") + default boolean isTrue(@NotNull Block block) { + return isIneligible(block); + } + + /** + * Check to see if a given BlockState location is set to true + * + * @param blockState BlockState to check + * @return true if the given BlockState location is set to true, false if otherwise + * @deprecated Use {@link #isIneligible(BlockState)} instead + */ + @Deprecated(since = "2.2.013") + default boolean isTrue(@NotNull BlockState blockState) { + return isIneligible(blockState); + } + + /** + * Set a given block location to true + * + * @param block Block location to set + * @deprecated Use {@link #setIneligible(Block)} instead + */ + @Deprecated(since = "2.2.013") + default void setTrue(@NotNull Block block) { + setIneligible(block); + } + + /** + * Set a given BlockState location to true + * + * @param blockState BlockState location to set + * @deprecated Use {@link #setIneligible(BlockState)} instead + */ + @Deprecated(since = "2.2.013") + default void setTrue(@NotNull BlockState blockState) { + setIneligible(blockState); + } + + /** + * Set a given block location to false + * + * @param block Block location to set + * @deprecated Use {@link #setEligible(Block)} instead + */ + @Deprecated(since = "2.2.013") + default void setFalse(@NotNull Block block) { + setEligible(block); + } + + /** + * Set a given BlockState location to false + * + * @param blockState BlockState location to set + * @deprecated Use {@link #setEligible(BlockState)} instead + */ + @Deprecated(since = "2.2.013") + default void setFalse(@NotNull BlockState blockState) { + setEligible(blockState); + } } diff --git a/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java index 1618988e9..c8125b763 100644 --- a/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java @@ -13,9 +13,8 @@ import org.mockito.MockedStatic; import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; import static java.util.logging.Logger.getLogger; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.*; -import static org.mockito.Mockito.when; class PotionEffectUtilTest { private MockedStatic mockedStaticMcMMO; diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java new file mode 100644 index 000000000..9e266d8d6 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java @@ -0,0 +1,121 @@ +package com.gmail.nossr50.util.blockmeta; + +import com.gmail.nossr50.mcMMO; +import com.google.common.io.Files; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.junit.jupiter.api.*; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.*; +import static com.gmail.nossr50.util.blockmeta.UserBlockTrackerTest.recursiveDelete; +import static org.bukkit.Bukkit.getWorld; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +class BitSetChunkStoreTest { + private static File tempDir; + + @BeforeAll + public static void setUpClass() { + tempDir = Files.createTempDir(); + } + + @AfterAll + public static void tearDownClass() { + recursiveDelete(tempDir); + } + + private World mockWorld; + + private MockedStatic bukkitMock; + private MockedStatic mcMMOMock; + + @BeforeEach + void setUpMock() { + UUID worldUUID = UUID.randomUUID(); + mockWorld = Mockito.mock(World.class); + when(mockWorld.getUID()).thenReturn(worldUUID); + when(mockWorld.getMaxHeight()).thenReturn(256); + when(mockWorld.getWorldFolder()).thenReturn(tempDir); + + bukkitMock = mockStatic(Bukkit.class); + bukkitMock.when(() -> getWorld(worldUUID)).thenReturn(mockWorld); + + mcMMOMock = mockStatic(mcMMO.class); + + when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); + when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); + } + + @AfterEach + void teardownMock() { + bukkitMock.close(); + mcMMOMock.close(); + } + + @Test + void testSetValue() { + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 0, 0); + original.setTrue(0, 0, 0); + assertTrue(original.isTrue(0, 0, 0)); + original.setFalse(0, 0, 0); + assertFalse(original.isTrue(0, 0, 0)); + } + + @Test + void testIsEmpty() { + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 0, 0); + assertTrue(original.isEmpty()); + original.setTrue(0, 0, 0); + original.setFalse(0, 0, 0); + assertTrue(original.isEmpty()); + } + + @Test + void testRoundTrip() throws IOException { + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); + original.setTrue(14, 89, 12); + original.setTrue(14, 90, 12); + original.setTrue(13, 89, 12); + byte[] serializedBytes = serializeChunkStore(original); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + assertChunkStoreEquals(original, deserialized); + } + + @Test + void testNegativeWorldMin() throws IOException { + when(mockWorld.getMinHeight()).thenReturn(-64); + + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); + original.setTrue(14, -32, 12); + original.setTrue(14, -64, 12); + original.setTrue(13, -63, 12); + byte[] serializedBytes = serializeChunkStore(original); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + assertChunkStoreEquals(original, deserialized); + } + + @Test + void testNegativeWorldMinUpgrade() throws IOException { + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); + original.setTrue(14, 1, 12); + original.setTrue(14, 2, 12); + original.setTrue(13, 3, 12); + byte[] serializedBytes = serializeChunkStore(original); + + when(mockWorld.getMinHeight()).thenReturn(-64); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + assert deserialized != null; + assertEqualIgnoreMinMax(original, deserialized); + } +} \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java b/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java new file mode 100644 index 000000000..709a7b57f --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java @@ -0,0 +1,49 @@ +package com.gmail.nossr50.util.blockmeta; + +import org.jetbrains.annotations.NotNull; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class BlockStoreTestUtils { + public static final int LEGACY_WORLD_HEIGHT_MAX = 256; + public static final int LEGACY_WORLD_HEIGHT_MIN = 0; + + /** + * Asserts that the two ChunkStores are equal. + * @param expected The expected ChunkStore + * @param actual The actual ChunkStore + */ + static void assertChunkStoreEquals(ChunkStore expected, ChunkStore actual) { + assertEquals(expected.getChunkMin(), actual.getChunkMin()); + assertEquals(expected.getChunkMax(), actual.getChunkMax()); + assertEqualIgnoreMinMax(expected, actual); + } + + static byte[] serializeChunkStore(@NotNull ChunkStore chunkStore) throws IOException { + final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + if (chunkStore instanceof BitSetChunkStore) + BitSetChunkStore.Serialization.writeChunkStore(new DataOutputStream(byteArrayOutputStream), chunkStore); + else + new UnitTestObjectOutputStream(byteArrayOutputStream).writeObject(chunkStore); // Serializes the class as if + // it were the old + // PrimitiveChunkStore + return byteArrayOutputStream.toByteArray(); + } + + static void assertEqualIgnoreMinMax(ChunkStore expected, ChunkStore actual) { + assertEquals(expected.getChunkX(), actual.getChunkX()); + assertEquals(expected.getChunkZ(), actual.getChunkZ()); + assertEquals(expected.getWorldId(), actual.getWorldId()); + for (int y = Math.min(actual.getChunkMin(), expected.getChunkMin()); y < Math.max(actual.getChunkMax(), expected.getChunkMax()); y++) { + if (expected.getChunkMin() > y || actual.getChunkMin() > y || expected.getChunkMax() <= y || actual.getChunkMax() <= y) + continue; // Ignore + for (int x = 0; x < 16; x++) + for (int z = 0; z < 16; z++) + assertEquals(expected.isTrue(x, y, z), actual.isTrue(x, y, z)); + } + } +} diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java index 969de6ec4..f7f369076 100644 --- a/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java @@ -1,13 +1,9 @@ package com.gmail.nossr50.util.blockmeta; - import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.BlockUtils; import com.google.common.io.Files; import org.bukkit.Bukkit; import org.bukkit.World; -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.*; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -15,14 +11,13 @@ import org.mockito.Mockito; import java.io.*; import java.util.UUID; -/** - * Could be a lot better. But some tests are better than none! Tests the major things, still kinda unit-testy. Verifies - * that the serialization isn't completely broken. - */ -class ChunkStoreTest { +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.*; +import static com.gmail.nossr50.util.blockmeta.UserBlockTrackerTest.recursiveDelete; +import static org.bukkit.Bukkit.getWorld; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; - public static final int LEGACY_WORLD_HEIGHT_MAX = 256; - public static final int LEGACY_WORLD_HEIGHT_MIN = 0; +class ChunkStoreTest { private static File tempDir; @BeforeAll @@ -44,151 +39,39 @@ class ChunkStoreTest { void setUpMock() { UUID worldUUID = UUID.randomUUID(); mockWorld = Mockito.mock(World.class); - Mockito.when(mockWorld.getUID()).thenReturn(worldUUID); - Mockito.when(mockWorld.getMaxHeight()).thenReturn(256); - Mockito.when(mockWorld.getWorldFolder()).thenReturn(tempDir); + when(mockWorld.getUID()).thenReturn(worldUUID); + when(mockWorld.getMaxHeight()).thenReturn(256); + when(mockWorld.getWorldFolder()).thenReturn(tempDir); - bukkitMock = Mockito.mockStatic(Bukkit.class); - bukkitMock.when(() -> Bukkit.getWorld(worldUUID)).thenReturn(mockWorld); + bukkitMock = mockStatic(Bukkit.class); + bukkitMock.when(() -> getWorld(worldUUID)).thenReturn(mockWorld); - mcMMOMock = Mockito.mockStatic(mcMMO.class); + mcMMOMock = mockStatic(mcMMO.class); - Mockito.when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); - Mockito.when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); + when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); + when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); } - + @AfterEach void teardownMock() { bukkitMock.close(); mcMMOMock.close(); } - @Test - void testIndexOutOfBounds() { - Mockito.when(mockWorld.getMinHeight()).thenReturn(-64); - HashChunkManager hashChunkManager = new HashChunkManager(); - - // Top Block - Block illegalHeightBlock = initMockBlock(1337, 256, -1337); - Assertions.assertFalse(hashChunkManager.isTrue(illegalHeightBlock)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> hashChunkManager.setTrue(illegalHeightBlock)); - } - - @Test - void testSetTrue() { - Mockito.when(mockWorld.getMinHeight()).thenReturn(-64); - HashChunkManager hashChunkManager = new HashChunkManager(); - int radius = 2; // Could be anything but drastically changes test time - - for (int x = -radius; x <= radius; x++) { - for (int y = mockWorld.getMinHeight(); y < mockWorld.getMaxHeight(); y++) { - for (int z = -radius; z <= radius; z++) { - Block testBlock = initMockBlock(x, y, z); - - hashChunkManager.setTrue(testBlock); - Assertions.assertTrue(hashChunkManager.isTrue(testBlock)); - hashChunkManager.setFalse(testBlock); - Assertions.assertFalse(hashChunkManager.isTrue(testBlock)); - } - } - } - - // Bot Block - Block bottomBlock = initMockBlock(1337, 0, -1337); - Assertions.assertFalse(hashChunkManager.isTrue(bottomBlock)); - - Assertions.assertTrue(BlockUtils.isWithinWorldBounds(bottomBlock)); - hashChunkManager.setTrue(bottomBlock); - Assertions.assertTrue(hashChunkManager.isTrue(bottomBlock)); - - // Top Block - Block topBlock = initMockBlock(1337, 255, -1337); - Assertions.assertFalse(hashChunkManager.isTrue(topBlock)); - - Assertions.assertTrue(BlockUtils.isWithinWorldBounds(topBlock)); - hashChunkManager.setTrue(topBlock); - Assertions.assertTrue(hashChunkManager.isTrue(topBlock)); - } - - @Test - void testSetValue() { - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 0, 0); - original.setTrue(0, 0, 0); - Assertions.assertTrue(original.isTrue(0, 0, 0)); - original.setFalse(0, 0, 0); - Assertions.assertFalse(original.isTrue(0, 0, 0)); - } - - @Test - void testIsEmpty() { - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 0, 0); - Assertions.assertTrue(original.isEmpty()); - original.setTrue(0, 0, 0); - original.setFalse(0, 0, 0); - Assertions.assertTrue(original.isEmpty()); - } - - @Test - void testRoundTrip() throws IOException { - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); - original.setTrue(14, 89, 12); - original.setTrue(14, 90, 12); - original.setTrue(13, 89, 12); - byte[] serializedBytes = serializeChunkstore(original); - ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); - assertEqual(original, deserialized); - } - - @Test - void testNegativeWorldMin() throws IOException { - Mockito.when(mockWorld.getMinHeight()).thenReturn(-64); - - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); - original.setTrue(14, -32, 12); - original.setTrue(14, -64, 12); - original.setTrue(13, -63, 12); - byte[] serializedBytes = serializeChunkstore(original); - ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); - assertEqual(original, deserialized); - } - - @Test - void testNegativeWorldMinUpgrade() throws IOException { - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); - original.setTrue(14, 1, 12); - original.setTrue(14, 2, 12); - original.setTrue(13, 3, 12); - byte[] serializedBytes = serializeChunkstore(original); - - Mockito.when(mockWorld.getMinHeight()).thenReturn(-64); - ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); - assert deserialized != null; - assertEqualIgnoreMinMax(original, deserialized); - } - - @Test - void testChunkCoords() throws IOException { - for (int x = -96; x < 0; x++) { - int cx = x >> 4; - int ix = Math.abs(x) % 16; - //System.out.print(cx + ":" + ix + " "); - } - } - @Test void testUpgrade() throws IOException { LegacyChunkStore original = new LegacyChunkStore(mockWorld, 12, 32); original.setTrue(14, 89, 12); original.setTrue(14, 90, 12); original.setTrue(13, 89, 12); - byte[] serializedBytes = serializeChunkstore(original); + byte[] serializedBytes = serializeChunkStore(original); ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); assert deserialized != null; - assertEqual(original, deserialized); + assertChunkStoreEquals(original, deserialized); } @Test - void testSimpleRegionRoundtrip() throws IOException { + void testSimpleRegionRoundTrip() throws IOException { LegacyChunkStore original = new LegacyChunkStore(mockWorld, 12, 12); original.setTrue(14, 89, 12); original.setTrue(14, 90, 12); @@ -196,7 +79,7 @@ class ChunkStoreTest { File file = new File(tempDir, "SimpleRegionRoundTrip.region"); McMMOSimpleRegionFile region = new McMMOSimpleRegionFile(file, 0, 0); try (DataOutputStream outputStream = region.getOutputStream(12, 12)) { - outputStream.write(serializeChunkstore(original)); + outputStream.write(serializeChunkStore(original)); } region.close(); region = new McMMOSimpleRegionFile(file, 0, 0); @@ -204,229 +87,10 @@ class ChunkStoreTest { Assertions.assertNotNull(is); ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(is); assert deserialized != null; - assertEqual(original, deserialized); + assertChunkStoreEquals(original, deserialized); } region.close(); file.delete(); } - @Test - void testSimpleRegionRejectsOutOfBounds() { - File file = new File(tempDir, "SimpleRegionRoundTrip.region"); - McMMOSimpleRegionFile region = new McMMOSimpleRegionFile(file, 0, 0); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(-1, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, -1)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(32, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, 32)); - region.close(); - } - - @Test - void testChunkStoreRejectsOutOfBounds() { - ChunkStore chunkStore = new BitSetChunkStore(mockWorld, 0, 0); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(-1, 0, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, -1, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, -1)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(16, 0, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, mockWorld.getMaxHeight(), 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, 16)); - } - - @Test - void testRegressionChunkMirrorBug() { - ChunkManager chunkManager = new HashChunkManager(); - Block mockBlockA = Mockito.mock(Block.class); - Mockito.when(mockBlockA.getX()).thenReturn(15); - Mockito.when(mockBlockA.getZ()).thenReturn(15); - Mockito.when(mockBlockA.getY()).thenReturn(0); - Mockito.when(mockBlockA.getWorld()).thenReturn(mockWorld); - Block mockBlockB = Mockito.mock(Block.class); - Mockito.when(mockBlockB.getX()).thenReturn(-15); - Mockito.when(mockBlockB.getZ()).thenReturn(-15); - Mockito.when(mockBlockB.getY()).thenReturn(0); - Mockito.when(mockBlockB.getWorld()).thenReturn(mockWorld); - - chunkManager.setTrue(mockBlockA); - chunkManager.setFalse(mockBlockB); - Assertions.assertTrue(chunkManager.isTrue(mockBlockA)); - } - - private void assertEqual(ChunkStore expected, ChunkStore actual) { - Assertions.assertEquals(expected.getChunkMin(), actual.getChunkMin()); - Assertions.assertEquals(expected.getChunkMax(), actual.getChunkMax()); - assertEqualIgnoreMinMax(expected, actual); - } - - private void assertEqualIgnoreMinMax(ChunkStore expected, ChunkStore actual) { - Assertions.assertEquals(expected.getChunkX(), actual.getChunkX()); - Assertions.assertEquals(expected.getChunkZ(), actual.getChunkZ()); - Assertions.assertEquals(expected.getWorldId(), actual.getWorldId()); - for (int y = Math.min(actual.getChunkMin(), expected.getChunkMin()); y < Math.max(actual.getChunkMax(), expected.getChunkMax()); y++) { - if (expected.getChunkMin() > y || actual.getChunkMin() > y || expected.getChunkMax() <= y || actual.getChunkMax() <= y) - continue; // Ignore - for (int x = 0; x < 16; x++) - for (int z = 0; z < 16; z++) - Assertions.assertEquals(expected.isTrue(x, y, z), actual.isTrue(x, y, z)); - } - } - - private static byte[] serializeChunkstore(@NotNull ChunkStore chunkStore) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - if (chunkStore instanceof BitSetChunkStore) - BitSetChunkStore.Serialization.writeChunkStore(new DataOutputStream(byteArrayOutputStream), chunkStore); - else - new UnitTestObjectOutputStream(byteArrayOutputStream).writeObject(chunkStore); // Serializes the class as if - // it were the old - // PrimitiveChunkStore - return byteArrayOutputStream.toByteArray(); - } - - public static class LegacyChunkStore implements ChunkStore, Serializable { - private static final long serialVersionUID = -1L; - transient private boolean dirty = false; - public boolean[][][] store; - private static final int CURRENT_VERSION = 7; - private static final int MAGIC_NUMBER = 0xEA5EDEBB; - private final int cx; - private final int cz; - private final @NotNull UUID worldUid; - - public LegacyChunkStore(@NotNull World world, int cx, int cz) { - this.cx = cx; - this.cz = cz; - this.worldUid = world.getUID(); - this.store = new boolean[16][16][world.getMaxHeight()]; - } - - @Override - public boolean isDirty() { - return dirty; - } - - @Override - public void setDirty(boolean dirty) { - this.dirty = dirty; - } - - @Override - public int getChunkX() { - return cx; - } - - @Override - public int getChunkZ() { - return cz; - } - - @Override - public int getChunkMin() { - return 0; - } - - @Override - public int getChunkMax() { - return store[0][0].length; - } - - @Override - public @NotNull UUID getWorldId() { - return worldUid; - } - - @Override - public boolean isTrue(int x, int y, int z) { - return store[x][z][y]; - } - - @Override - public void setTrue(int x, int y, int z) { - if (y >= store[0][0].length || y < 0) - return; - store[x][z][y] = true; - dirty = true; - } - - @Override - public void setFalse(int x, int y, int z) { - if (y >= store[0][0].length || y < 0) - return; - store[x][z][y] = false; - dirty = true; - } - - @Override - public void set(int x, int y, int z, boolean value) { - if (y >= store[0][0].length || y < 0) - return; - store[x][z][y] = value; - dirty = true; - } - - @Override - public boolean isEmpty() { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = 0; y < store[0][0].length; y++) { - if (store[x][z][y]) { - return false; - } - } - } - } - return true; - } - - private void writeObject(@NotNull ObjectOutputStream out) throws IOException { - out.writeInt(MAGIC_NUMBER); - out.writeInt(CURRENT_VERSION); - - out.writeLong(worldUid.getLeastSignificantBits()); - out.writeLong(worldUid.getMostSignificantBits()); - out.writeInt(cx); - out.writeInt(cz); - out.writeObject(store); - - dirty = false; - } - - private void readObject(@NotNull ObjectInputStream in) throws IOException, ClassNotFoundException { - throw new UnsupportedOperationException(); - } - - } - - private static class UnitTestObjectOutputStream extends ObjectOutputStream { - - public UnitTestObjectOutputStream(@NotNull OutputStream outputStream) throws IOException { - super(outputStream); - } - - @Override - public void writeUTF(@NotNull String str) throws IOException { - // Pretend to be the old class - if (str.equals(LegacyChunkStore.class.getName())) - str = "com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore"; - super.writeUTF(str); - } - - } - - @NotNull - private Block initMockBlock(int x, int y, int z) { - Block mockBlock = Mockito.mock(Block.class); - Mockito.when(mockBlock.getX()).thenReturn(x); - Mockito.when(mockBlock.getY()).thenReturn(y); - Mockito.when(mockBlock.getZ()).thenReturn(z); - Mockito.when(mockBlock.getWorld()).thenReturn(mockWorld); - return mockBlock; - } - - public static void recursiveDelete(@NotNull File directoryToBeDeleted) { - if (directoryToBeDeleted.isDirectory()) { - for (File file : directoryToBeDeleted.listFiles()) { - recursiveDelete(file); - } - } - directoryToBeDeleted.delete(); - } -} +} \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java b/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java new file mode 100644 index 000000000..b21cf2594 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java @@ -0,0 +1,127 @@ +package com.gmail.nossr50.util.blockmeta; + +import org.bukkit.World; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.UUID; + +/** + * Used for unit testing upgrades from the old ChunkStore class. + */ +class LegacyChunkStore implements ChunkStore, Serializable { + private static final long serialVersionUID = -1L; + transient private boolean dirty = false; + public boolean[][][] store; + private static final int CURRENT_VERSION = 7; + private static final int MAGIC_NUMBER = 0xEA5EDEBB; + private final int cx; + private final int cz; + private final @NotNull UUID worldUid; + + public LegacyChunkStore(@NotNull World world, int cx, int cz) { + this.cx = cx; + this.cz = cz; + this.worldUid = world.getUID(); + this.store = new boolean[16][16][world.getMaxHeight()]; + } + + @Override + public boolean isDirty() { + return dirty; + } + + @Override + public void setDirty(boolean dirty) { + this.dirty = dirty; + } + + @Override + public int getChunkX() { + return cx; + } + + @Override + public int getChunkZ() { + return cz; + } + + @Override + public int getChunkMin() { + return 0; + } + + @Override + public int getChunkMax() { + return store[0][0].length; + } + + @Override + public @NotNull UUID getWorldId() { + return worldUid; + } + + @Override + public boolean isTrue(int x, int y, int z) { + return store[x][z][y]; + } + + @Override + public void setTrue(int x, int y, int z) { + if (y >= store[0][0].length || y < 0) + return; + store[x][z][y] = true; + dirty = true; + } + + @Override + public void setFalse(int x, int y, int z) { + if (y >= store[0][0].length || y < 0) + return; + store[x][z][y] = false; + dirty = true; + } + + @Override + public void set(int x, int y, int z, boolean value) { + if (y >= store[0][0].length || y < 0) + return; + store[x][z][y] = value; + dirty = true; + } + + @Override + public boolean isEmpty() { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < store[0][0].length; y++) { + if (store[x][z][y]) { + return false; + } + } + } + } + return true; + } + + private void writeObject(@NotNull ObjectOutputStream out) throws IOException { + out.writeInt(MAGIC_NUMBER); + out.writeInt(CURRENT_VERSION); + + out.writeLong(worldUid.getLeastSignificantBits()); + out.writeLong(worldUid.getMostSignificantBits()); + out.writeInt(cx); + out.writeInt(cz); + out.writeObject(store); + + dirty = false; + } + + private void readObject(@NotNull ObjectInputStream in) throws IOException, ClassNotFoundException { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java b/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java new file mode 100644 index 000000000..d7eb1c140 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java @@ -0,0 +1,23 @@ +package com.gmail.nossr50.util.blockmeta; + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; + +class UnitTestObjectOutputStream extends ObjectOutputStream { + + public UnitTestObjectOutputStream(@NotNull OutputStream outputStream) throws IOException { + super(outputStream); + } + + @Override + public void writeUTF(@NotNull String str) throws IOException { + // Pretend to be the old class + if (str.equals(LegacyChunkStore.class.getName())) + str = "com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore"; + super.writeUTF(str); + } + +} diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java new file mode 100644 index 000000000..89a2f63ff --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java @@ -0,0 +1,192 @@ +package com.gmail.nossr50.util.blockmeta; + +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.BlockUtils; +import com.google.common.io.Files; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.*; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MAX; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MIN; +import static org.bukkit.Bukkit.getWorld; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +/** + * Could be a lot better. But some tests are better than none! Tests the major things, still kinda unit-testy. Verifies + * that the serialization isn't completely broken. + */ +class UserBlockTrackerTest { + private static File tempDir; + + @BeforeAll + public static void setUpClass() { + tempDir = Files.createTempDir(); + } + + @AfterAll + public static void tearDownClass() { + recursiveDelete(tempDir); + } + + private World mockWorld; + + private MockedStatic bukkitMock; + private MockedStatic mcMMOMock; + + @BeforeEach + void setUpMock() { + UUID worldUUID = UUID.randomUUID(); + mockWorld = Mockito.mock(World.class); + when(mockWorld.getUID()).thenReturn(worldUUID); + when(mockWorld.getMaxHeight()).thenReturn(256); + when(mockWorld.getWorldFolder()).thenReturn(tempDir); + + bukkitMock = mockStatic(Bukkit.class); + bukkitMock.when(() -> getWorld(worldUUID)).thenReturn(mockWorld); + + mcMMOMock = mockStatic(mcMMO.class); + + when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); + when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); + } + + @AfterEach + void teardownMock() { + bukkitMock.close(); + mcMMOMock.close(); + } + + @Test + void setIneligibleShouldThrowIndexOutOfBoundsException() { + when(mockWorld.getMinHeight()).thenReturn(-64); + final HashChunkManager hashChunkManager = new HashChunkManager(); + + // Top Block + final Block illegalHeightBlock = initMockBlock(1337, 256, -1337); + assertFalse(hashChunkManager.isIneligible(illegalHeightBlock)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> hashChunkManager.setIneligible(illegalHeightBlock)); + } + + @Test + void testSetEligibility() { + when(mockWorld.getMinHeight()).thenReturn(-64); + final HashChunkManager hashChunkManager = new HashChunkManager(); + int radius = 2; // Could be anything but drastically changes test time + + for (int x = -radius; x <= radius; x++) { + for (int y = mockWorld.getMinHeight(); y < mockWorld.getMaxHeight(); y++) { + for (int z = -radius; z <= radius; z++) { + final Block testBlock = initMockBlock(x, y, z); + // mark ineligible + hashChunkManager.setIneligible(testBlock); + assertTrue(hashChunkManager.isIneligible(testBlock)); + + // mark eligible + hashChunkManager.setEligible(testBlock); + // Might as well test both isIneligible and isEligible while we are here + assertFalse(hashChunkManager.isIneligible(testBlock)); + assertTrue(hashChunkManager.isEligible(testBlock)); + } + } + } + + // TODO: Whatever is going on down here should be in its own test + // Bot Block + final Block bottomBlock = initMockBlock(1337, 0, -1337); + assertFalse(hashChunkManager.isIneligible(bottomBlock)); + + assertTrue(BlockUtils.isWithinWorldBounds(bottomBlock)); + hashChunkManager.setIneligible(bottomBlock); + assertTrue(hashChunkManager.isIneligible(bottomBlock)); + + // Top Block + final Block topBlock = initMockBlock(1337, 255, -1337); + assertFalse(hashChunkManager.isIneligible(topBlock)); + + assertTrue(BlockUtils.isWithinWorldBounds(topBlock)); + hashChunkManager.setIneligible(topBlock); + assertTrue(hashChunkManager.isIneligible(topBlock)); + } + + @Test + void testChunkCoords() throws IOException { + // TODO: Unfinished test? + for (int x = -96; x < 0; x++) { + int cx = x >> 4; + int ix = Math.abs(x) % 16; + //System.out.print(cx + ":" + ix + " "); + } + } + + @Test + void testSimpleRegionRejectsOutOfBounds() { + File file = new File(tempDir, "SimpleRegionRoundTrip.region"); + McMMOSimpleRegionFile region = new McMMOSimpleRegionFile(file, 0, 0); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(-1, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, -1)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(32, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, 32)); + region.close(); + } + + @Test + void testChunkStoreRejectsOutOfBounds() { + ChunkStore chunkStore = new BitSetChunkStore(mockWorld, 0, 0); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(-1, 0, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, -1, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, -1)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(16, 0, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, mockWorld.getMaxHeight(), 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, 16)); + } + + @Test + void testRegressionChunkMirrorBug() { + final UserBlockTracker chunkManager = new HashChunkManager(); + Block mockBlockA = Mockito.mock(Block.class); + when(mockBlockA.getX()).thenReturn(15); + when(mockBlockA.getZ()).thenReturn(15); + when(mockBlockA.getY()).thenReturn(0); + when(mockBlockA.getWorld()).thenReturn(mockWorld); + Block mockBlockB = Mockito.mock(Block.class); + when(mockBlockB.getX()).thenReturn(-15); + when(mockBlockB.getZ()).thenReturn(-15); + when(mockBlockB.getY()).thenReturn(0); + when(mockBlockB.getWorld()).thenReturn(mockWorld); + + chunkManager.setIneligible(mockBlockA); + chunkManager.setEligible(mockBlockB); + assertTrue(chunkManager.isIneligible(mockBlockA)); + } + + @NotNull + private Block initMockBlock(int x, int y, int z) { + final Block mockBlock = Mockito.mock(Block.class); + when(mockBlock.getX()).thenReturn(x); + when(mockBlock.getY()).thenReturn(y); + when(mockBlock.getZ()).thenReturn(z); + when(mockBlock.getWorld()).thenReturn(mockWorld); + return mockBlock; + } + + public static void recursiveDelete(@NotNull File directoryToBeDeleted) { + if (directoryToBeDeleted.isDirectory()) { + for (File file : directoryToBeDeleted.listFiles()) { + recursiveDelete(file); + } + } + directoryToBeDeleted.delete(); + } +} From 9b09f06ad8b077c2a610b3d72da152aa275366eb Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 12:58:13 -0700 Subject: [PATCH 24/34] add more sensibly named API for grabbing the UserBlockTracker --- Changelog.txt | 3 +++ .../nossr50/listeners/BlockListener.java | 10 ++++---- .../nossr50/listeners/ChunkListener.java | 3 ++- .../nossr50/listeners/EntityListener.java | 8 +++---- .../nossr50/listeners/PlayerListener.java | 2 +- .../nossr50/listeners/WorldListener.java | 6 ++--- src/main/java/com/gmail/nossr50/mcMMO.java | 23 +++++++++++++++++++ .../runnables/StickyPistonTrackerTask.java | 4 ++-- .../skills/herbalism/HerbalismManager.java | 12 +++++----- .../nossr50/skills/mining/MiningManager.java | 4 ++-- .../woodcutting/WoodcuttingManager.java | 6 ++--- .../com/gmail/nossr50/util/BlockUtils.java | 4 ++-- .../util/blockmeta/UserBlockTracker.java | 2 +- .../com/gmail/nossr50/MMOTestEnvironment.java | 2 +- 14 files changed, 58 insertions(+), 31 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index 4515641b0..d858a14f1 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,4 +1,7 @@ Version 2.2.013 + (API) Deprecated com.gmail.nossr50.mcMMO.getPlaceStore + (API) Added com.gmail.nossr50.mcMMO.getUserBlockTracker + (API) Added com.gmail.nossr50.mcMMO.getChunkManager (API) Added new methods to com.gmail.nossr50.util.blockmeta.UserBlockTracker for easier readability (API) Deprecated the old poorly named methods in UserBlockTracker (Codebase) Cleaned up and organized unit tests relating to UserBlockTracker diff --git a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java index 23e17af53..40e419e0c 100644 --- a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java @@ -310,7 +310,7 @@ public class BlockListener implements Listener { // Minecraft is dumb, the events still throw when a plant "grows" higher than the max block height. Even though no new block is created if (BlockUtils.isWithinWorldBounds(block)) { - mcMMO.getPlaceStore().setEligible(block); + mcMMO.getUserBlockTracker().setEligible(block); } } @@ -400,14 +400,14 @@ public class BlockListener implements Listener { else if (BlockUtils.affectedBySuperBreaker(blockState) && (ItemUtils.isPickaxe(heldItem) || ItemUtils.isHoe(heldItem)) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.MINING) - && !mcMMO.getPlaceStore().isIneligible(blockState)) { + && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { MiningManager miningManager = mcMMOPlayer.getMiningManager(); miningManager.miningBlockCheck(blockState); } /* WOOD CUTTING */ else if (BlockUtils.hasWoodcuttingXP(blockState) && ItemUtils.isAxe(heldItem) - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) && !mcMMO.getPlaceStore().isIneligible(blockState)) { + && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager(); if (woodcuttingManager.canUseTreeFeller(heldItem)) { woodcuttingManager.processTreeFeller(blockState); @@ -422,7 +422,7 @@ public class BlockListener implements Listener { } /* EXCAVATION */ - else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) && !mcMMO.getPlaceStore().isIneligible(blockState)) { + else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { ExcavationManager excavationManager = mcMMOPlayer.getExcavationManager(); excavationManager.excavationBlockCheck(blockState); @@ -687,7 +687,7 @@ public class BlockListener implements Listener { if (UserManager.getPlayer(player).isDebugMode()) { - if (mcMMO.getPlaceStore().isIneligible(blockState)) + if (mcMMO.getUserBlockTracker().isIneligible(blockState)) player.sendMessage("[mcMMO DEBUG] This block is not natural and does not reward treasures/XP"); else { diff --git a/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java b/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java index 761516deb..defdd6a01 100644 --- a/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java @@ -12,7 +12,8 @@ public class ChunkListener implements Listener { @EventHandler(ignoreCancelled = true) public void onChunkUnload(ChunkUnloadEvent event) { - List matchingEntities = mcMMO.getTransientEntityTracker().getAllTransientEntitiesInChunk(event.getChunk()); + List matchingEntities + = mcMMO.getTransientEntityTracker().getAllTransientEntitiesInChunk(event.getChunk()); for(LivingEntity livingEntity : matchingEntities) { mcMMO.getTransientEntityTracker().removeSummon(livingEntity, null, false); } diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index fb36629de..b3eec6fb0 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -206,8 +206,8 @@ public class EntityListener implements Listener { if (entity instanceof FallingBlock || entity instanceof Enderman) { boolean isTracked = entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK); - if (mcMMO.getPlaceStore().isIneligible(block) && !isTracked) { - mcMMO.getPlaceStore().setEligible(block); + if (mcMMO.getUserBlockTracker().isIneligible(block) && !isTracked) { + mcMMO.getUserBlockTracker().setEligible(block); entity.setMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, MetadataConstants.MCMMO_METADATA_VALUE); TravelingBlockMetaCleanup metaCleanupTask = new TravelingBlockMetaCleanup(entity, pluginRef); @@ -221,8 +221,8 @@ public class EntityListener implements Listener { //Redstone ore fire this event and should be ignored } else { - if (mcMMO.getPlaceStore().isIneligible(block)) { - mcMMO.getPlaceStore().setEligible(block); + if (mcMMO.getUserBlockTracker().isIneligible(block)) { + mcMMO.getUserBlockTracker().setEligible(block); } } } diff --git a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java index e9b8daf62..5a7c9a695 100644 --- a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java @@ -852,7 +852,7 @@ public class PlayerListener implements Listener { case "NETHER_WART_BLOCK": case "POTATO": case "MANGROVE_PROPAGULE": - mcMMO.getPlaceStore().setEligible(blockState); + mcMMO.getUserBlockTracker().setEligible(blockState); break; } } diff --git a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java index 010185e9e..54fa2a379 100644 --- a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java @@ -32,7 +32,7 @@ public class WorldListener implements Listener { // Using 50 ms later as I do not know of a way to run one tick later (safely) plugin.getFoliaLib().getImpl().runLater(() -> { for (BlockState blockState : event.getBlocks()) { - mcMMO.getPlaceStore().setEligible(blockState); + mcMMO.getUserBlockTracker().setEligible(blockState); } }, 1); } @@ -48,7 +48,7 @@ public class WorldListener implements Listener { if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; - mcMMO.getPlaceStore().unloadWorld(event.getWorld()); + mcMMO.getChunkManager().unloadWorld(event.getWorld()); } /** @@ -64,6 +64,6 @@ public class WorldListener implements Listener { Chunk chunk = event.getChunk(); - mcMMO.getPlaceStore().chunkUnloaded(chunk.getX(), chunk.getZ(), event.getWorld()); + mcMMO.getChunkManager().chunkUnloaded(chunk.getX(), chunk.getZ(), event.getWorld()); } } diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 0b3fe222b..058d93b1c 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -39,6 +39,7 @@ import com.gmail.nossr50.skills.salvage.salvageables.SimpleSalvageableManager; import com.gmail.nossr50.util.*; import com.gmail.nossr50.util.blockmeta.ChunkManager; import com.gmail.nossr50.util.blockmeta.ChunkManagerFactory; +import com.gmail.nossr50.util.blockmeta.UserBlockTracker; import com.gmail.nossr50.util.commands.CommandRegistrationManager; import com.gmail.nossr50.util.compat.CompatibilityManager; import com.gmail.nossr50.util.experience.FormulaManager; @@ -443,6 +444,28 @@ public class mcMMO extends JavaPlugin { return formulaManager; } + /** + * Get the {@link UserBlockTracker}. + * @return the {@link UserBlockTracker} + */ + public static UserBlockTracker getUserBlockTracker() { + return placeStore; + } + + /** + * Get the chunk manager. + * @return the chunk manager + */ + public static ChunkManager getChunkManager() { + return placeStore; + } + + /** + * Get the chunk manager. + * @deprecated Use {@link #getChunkManager()} or {@link #getUserBlockTracker()} instead. + * @return the chunk manager + */ + @Deprecated(since = "2.2.013", forRemoval = true) public static ChunkManager getPlaceStore() { return placeStore; } diff --git a/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java b/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java index 02590c53f..bf5c77269 100644 --- a/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java @@ -19,7 +19,7 @@ public class StickyPistonTrackerTask extends CancellableRunnable { @Override public void run() { - if (!mcMMO.getPlaceStore().isIneligible(movedBlock.getRelative(direction))) { + if (!mcMMO.getUserBlockTracker().isIneligible(movedBlock.getRelative(direction))) { return; } @@ -29,7 +29,7 @@ public class StickyPistonTrackerTask extends CancellableRunnable { } // The sticky piston actually pulled the block so move the PlaceStore data - mcMMO.getPlaceStore().setEligible(movedBlock.getRelative(direction)); + mcMMO.getUserBlockTracker().setEligible(movedBlock.getRelative(direction)); BlockUtils.setUnnaturalBlock(movedBlock); } } diff --git a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java index a93f6b3f7..21cd85274 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java @@ -282,7 +282,7 @@ public class HerbalismManager extends SkillManager { if (brokenPlant.getLocation().equals(originalBreak.getBlock().getLocation())) { //If its the same block as the original, we are going to directly check it for being a valid XP gain and add it to the nonChorusBlocks list even if its a chorus block //This stops a delay from happening when bringing up the XP bar for chorus trees - if (!mcMMO.getPlaceStore().isIneligible(originalBreak)) { + if (!mcMMO.getUserBlockTracker().isIneligible(originalBreak)) { //Even if its a chorus block, the original break will be moved to nonChorusBlocks for immediate XP rewards noDelayPlantBlocks.add(brokenPlant); } else { @@ -335,7 +335,7 @@ public class HerbalismManager extends SkillManager { BlockData plantData = brokenPlantState.getBlockData(); //Check for double drops - if (!mcMMO.getPlaceStore().isIneligible(brokenPlant)) { + if (!mcMMO.getUserBlockTracker().isIneligible(brokenPlant)) { /* * @@ -413,7 +413,7 @@ public class HerbalismManager extends SkillManager { BlockState brokenBlockNewState = brokenPlantBlock.getState(); BlockData plantData = brokenBlockNewState.getBlockData(); - if (mcMMO.getPlaceStore().isIneligible(brokenBlockNewState)) { + if (mcMMO.getUserBlockTracker().isIneligible(brokenBlockNewState)) { /* * * Unnatural Blocks @@ -427,7 +427,7 @@ public class HerbalismManager extends SkillManager { } //Mark it as natural again as it is being broken - mcMMO.getPlaceStore().setEligible(brokenBlockNewState); + mcMMO.getUserBlockTracker().setEligible(brokenBlockNewState); } else { /* * @@ -489,9 +489,9 @@ public class HerbalismManager extends SkillManager { continue; } - if (mcMMO.getPlaceStore().isIneligible(brokenBlockNewState)) { + if (mcMMO.getUserBlockTracker().isIneligible(brokenBlockNewState)) { //Mark it as natural again as it is being broken - mcMMO.getPlaceStore().setEligible(brokenBlockNewState); + mcMMO.getUserBlockTracker().setEligible(brokenBlockNewState); } else { //TODO: Do we care about chorus flower age? //Calculate XP for the old type diff --git a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java index a4c8eade0..aaac5e7fc 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java @@ -181,7 +181,7 @@ public class MiningManager extends SkillManager { //Containers usually have 0 XP unless someone edited their config in a very strange way if (ExperienceConfig.getInstance().getXp(PrimarySkillType.MINING, targetBlock) != 0 && !(targetBlock instanceof Container) - && !mcMMO.getPlaceStore().isIneligible(targetBlock)) { + && !mcMMO.getUserBlockTracker().isIneligible(targetBlock)) { if (BlockUtils.isOre(blockState)) { ores.add(blockState); } else { @@ -216,7 +216,7 @@ public class MiningManager extends SkillManager { Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_ORES); // Initial block that would have been dropped - if (mcMMO.p.getAdvancedConfig().isBlastMiningBonusDropsEnabled() && !mcMMO.getPlaceStore().isIneligible(blockState)) { + if (mcMMO.p.getAdvancedConfig().isBlastMiningBonusDropsEnabled() && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { for (int i = 1; i < dropMultiplier; i++) { // Bukkit.broadcastMessage("Bonus Drop on Ore: "+blockState.getType().toString()); Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_ORES_BONUS_DROP); // Initial block that would have been dropped diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java index b68cedad7..19412523e 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java @@ -113,7 +113,7 @@ public class WoodcuttingManager extends SkillManager { } public void processWoodcuttingBlockXP(@NotNull BlockState blockState) { - if (mcMMO.getPlaceStore().isIneligible(blockState)) + if (mcMMO.getUserBlockTracker().isIneligible(blockState)) return; int xp = getExperienceFromLog(blockState); @@ -269,7 +269,7 @@ public class WoodcuttingManager extends SkillManager { * in treeFellerBlocks. */ private boolean processTreeFellerTargetBlock(@NotNull BlockState blockState, @NotNull List futureCenterBlocks, @NotNull Set treeFellerBlocks) { - if (treeFellerBlocks.contains(blockState) || mcMMO.getPlaceStore().isIneligible(blockState)) { + if (treeFellerBlocks.contains(blockState) || mcMMO.getUserBlockTracker().isIneligible(blockState)) { return false; } @@ -373,7 +373,7 @@ public class WoodcuttingManager extends SkillManager { * @return Amount of experience */ private static int processTreeFellerXPGains(BlockState blockState, int woodCount) { - if (mcMMO.getPlaceStore().isIneligible(blockState)) + if (mcMMO.getUserBlockTracker().isIneligible(blockState)) return 0; int rawXP = ExperienceConfig.getInstance().getXp(PrimarySkillType.WOODCUTTING, blockState.getType()); diff --git a/src/main/java/com/gmail/nossr50/util/BlockUtils.java b/src/main/java/com/gmail/nossr50/util/BlockUtils.java index 59245fc9d..da52b9f20 100644 --- a/src/main/java/com/gmail/nossr50/util/BlockUtils.java +++ b/src/main/java/com/gmail/nossr50/util/BlockUtils.java @@ -65,7 +65,7 @@ public final class BlockUtils { * @param block target block */ public static void setUnnaturalBlock(@NotNull Block block) { - mcMMO.getPlaceStore().setIneligible(block); + mcMMO.getUserBlockTracker().setIneligible(block); // Failsafe against lingering metadata if (block.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) @@ -82,7 +82,7 @@ public final class BlockUtils { block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p); } - mcMMO.getPlaceStore().setEligible(block); + mcMMO.getUserBlockTracker().setEligible(block); } /** diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java b/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java index 501b16cfa..8979e9125 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java @@ -7,7 +7,7 @@ import org.jetbrains.annotations.NotNull; /** * Contains blockstore methods that are safe for external plugins to access. - * An instance can be retrieved via {@link mcMMO#getPlaceStore() mcMMO.getPlaceStore()} + * An instance can be retrieved via {@link mcMMO#getUserBlockTracker() mcMMO.getPlaceStore()} */ public interface UserBlockTracker { /** diff --git a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java index 68561c936..984c5f123 100644 --- a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java +++ b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java @@ -74,7 +74,7 @@ public abstract class MMOTestEnvironment { // place store chunkManager = mock(ChunkManager.class); - when(mcMMO.getPlaceStore()).thenReturn(chunkManager); + when(mcMMO.getUserBlockTracker()).thenReturn(chunkManager); // shut off mod manager for woodcutting when(mcMMO.getModManager()).thenReturn(mock(ModManager.class)); From b65247cbb082f2ec1c1d2fba2bae3b3a12c12fbd Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:05:00 -0700 Subject: [PATCH 25/34] require java 21 --- Changelog.txt | 3 +++ pom.xml | 8 ++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Changelog.txt b/Changelog.txt index d858a14f1..3eb574ec4 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,4 +1,5 @@ Version 2.2.013 + mcMMO now requires Java 21 (see notes) (API) Deprecated com.gmail.nossr50.mcMMO.getPlaceStore (API) Added com.gmail.nossr50.mcMMO.getUserBlockTracker (API) Added com.gmail.nossr50.mcMMO.getChunkManager @@ -7,6 +8,8 @@ Version 2.2.013 (Codebase) Cleaned up and organized unit tests relating to UserBlockTracker NOTES: + mcMMO is now compiled for Java 21, Java 21 will be requires to run mcMMO. + This should not pose an issue as there are Java 21 server JARs for the versions of MC that mcMMO currently supports. Not planning to delete the deprecated methods in UserBlockTracker anytime soon, as nothing has really changed other than the names Version 2.2.012 diff --git a/pom.xml b/pom.xml index dbfe0175c..adde2f8ca 100644 --- a/pom.xml +++ b/pom.xml @@ -14,9 +14,9 @@ UTF-8 - 17 - 17 - 17 + 21 + 21 + 21 @@ -103,7 +103,7 @@ maven-compiler-plugin 3.10.1 - 17 + 21 -parameters From d38404927b647638a441d9db49039fcb7f373bfa Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:05:10 -0700 Subject: [PATCH 26/34] minor refactor --- src/main/java/com/gmail/nossr50/mcMMO.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 058d93b1c..2acb95925 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -79,7 +79,7 @@ import java.util.List; public class mcMMO extends JavaPlugin { /* Managers & Services */ private static PlatformManager platformManager; - private static ChunkManager placeStore; + private static ChunkManager chunkManager; private static RepairableManager repairableManager; private static SalvageableManager salvageableManager; private static ModManager modManager; @@ -268,7 +268,7 @@ public class mcMMO extends JavaPlugin { scheduleTasks(); CommandRegistrationManager.registerCommands(); - placeStore = ChunkManagerFactory.getChunkManager(); // Get our ChunkletManager + chunkManager = ChunkManagerFactory.getChunkManager(); // Get our ChunkletManager if (generalConfig.getPTPCommandWorldPermissions()) { Permissions.generateWorldTeleportPermissions(); @@ -381,7 +381,7 @@ public class mcMMO extends JavaPlugin { ScoreboardManager.teardownAll(); formulaManager.saveFormula(); - placeStore.closeAll(); + chunkManager.closeAll(); } catch (Exception e) { e.printStackTrace(); @@ -449,7 +449,7 @@ public class mcMMO extends JavaPlugin { * @return the {@link UserBlockTracker} */ public static UserBlockTracker getUserBlockTracker() { - return placeStore; + return chunkManager; } /** @@ -457,7 +457,7 @@ public class mcMMO extends JavaPlugin { * @return the chunk manager */ public static ChunkManager getChunkManager() { - return placeStore; + return chunkManager; } /** @@ -467,7 +467,7 @@ public class mcMMO extends JavaPlugin { */ @Deprecated(since = "2.2.013", forRemoval = true) public static ChunkManager getPlaceStore() { - return placeStore; + return chunkManager; } public static RepairableManager getRepairableManager() { From ab8ba8acbe400333037bf7a2067b5c7ee667d446 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:11:12 -0700 Subject: [PATCH 27/34] update maven shade plugin --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index adde2f8ca..4338e1008 100644 --- a/pom.xml +++ b/pom.xml @@ -131,7 +131,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.3.0 + 3.5.3 From 19a8a9ff5219e2cbf57a8b3410b86e27198edfd0 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:14:39 -0700 Subject: [PATCH 28/34] update maven compiler plugin --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 4338e1008..a772bbef9 100644 --- a/pom.xml +++ b/pom.xml @@ -101,7 +101,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.10.1 + 3.13.0 21 From db9f8e46d1947af5dfc5b0a4a9f09de070192278 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:18:39 -0700 Subject: [PATCH 29/34] update github workflow runner to use 21 --- .github/workflows/maven.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index ddd132071..9641dde68 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -31,13 +31,13 @@ jobs: - name: Checkout repository uses: actions/checkout@v2 - # 2. Setup Java 17 JDK (Adopt) - - name: Java 17 setup + # 2. Setup Java 21 JDK (Adopt) + - name: Java 21 setup uses: actions/setup-java@v2 with: distribution: 'adopt' java-package: jdk - java-version: '17' + java-version: '21' # 3. Setup local Maven package cache to speed up building - name: Cache Maven packages From fc600796ca6b63817e3cac9003d5534ef1de7829 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:24:06 -0700 Subject: [PATCH 30/34] minor refactor --- src/main/java/com/gmail/nossr50/mcMMO.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 2acb95925..81ad266ca 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -80,12 +80,12 @@ public class mcMMO extends JavaPlugin { /* Managers & Services */ private static PlatformManager platformManager; private static ChunkManager chunkManager; - private static RepairableManager repairableManager; + private static RepairableManager repairableManager; private static SalvageableManager salvageableManager; - private static ModManager modManager; - private static DatabaseManager databaseManager; - private static FormulaManager formulaManager; - private static UpgradeManager upgradeManager; + private static ModManager modManager; + private static DatabaseManager databaseManager; + private static FormulaManager formulaManager; + private static UpgradeManager upgradeManager; private static MaterialMapStore materialMapStore; private static PlayerLevelUtils playerLevelUtils; private static TransientMetadataTools transientMetadataTools; From 32ff8c68188d9931d28d9a9bf538f3de6e27cc4d Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:24:14 -0700 Subject: [PATCH 31/34] update maven-release-plugin --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index a772bbef9..e713003b6 100644 --- a/pom.xml +++ b/pom.xml @@ -96,7 +96,7 @@ org.apache.maven.plugins maven-release-plugin - 3.0.0-M6 + 3.0.1 org.apache.maven.plugins From 364d4cd6e7f576088dc58209dff73aafc1fd6146 Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:48:25 -0700 Subject: [PATCH 32/34] spring-cleaning, update all the dependencies --- Changelog.txt | 1 + pom.xml | 41 +++++++++--------- .../commands/player/McrankCommand.java | 4 +- .../nossr50/commands/player/MctopCommand.java | 4 +- .../config/mods/CustomEntityLegacyConfig.java | 3 +- .../database/FlatFileDataProcessor.java | 2 +- .../database/FlatFileDatabaseManager.java | 4 +- .../placeholders/PartyLeaderPlaceholder.java | 4 +- .../placeholders/PartyNamePlaceholder.java | 4 +- ...cTask.java => McRankCommandAsyncTask.java} | 6 +-- ...ncTask.java => McTopCommandAsyncTask.java} | 6 +-- .../commands/MctopCommandDisplayTask.java | 2 +- .../nossr50/skills/mining/MiningManager.java | 5 ++- .../util/scoreboards/ScoreboardWrapper.java | 5 ++- .../util/skills/ParticleEffectUtils.java | 43 ++++++++----------- 15 files changed, 64 insertions(+), 70 deletions(-) rename src/main/java/com/gmail/nossr50/runnables/commands/{McrankCommandAsyncTask.java => McRankCommandAsyncTask.java} (88%) rename src/main/java/com/gmail/nossr50/runnables/commands/{MctopCommandAsyncTask.java => McTopCommandAsyncTask.java} (89%) diff --git a/Changelog.txt b/Changelog.txt index 3eb574ec4..f3b117d01 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,5 +1,6 @@ Version 2.2.013 mcMMO now requires Java 21 (see notes) + Modified the RNG for dropping non-ore blocks from Blast Mining to yield about 50% of what was destroyed (API) Deprecated com.gmail.nossr50.mcMMO.getPlaceStore (API) Added com.gmail.nossr50.mcMMO.getUserBlockTracker (API) Added com.gmail.nossr50.mcMMO.getChunkManager diff --git a/pom.xml b/pom.xml index e713003b6..851f41b8a 100644 --- a/pom.xml +++ b/pom.xml @@ -75,7 +75,7 @@ maven-surefire-plugin - 3.0.0-M7 + 3.2.5 org.junit.jupiter:junit-jupiter @@ -85,7 +85,7 @@ maven-failsafe-plugin - 3.0.0-M7 + 3.2.5 org.junit.jupiter:junit-jupiter @@ -113,6 +113,7 @@ maven-assembly-plugin + 3.7.1 src/main/assembly/package.xml @@ -304,42 +305,42 @@ net.kyori adventure-text-serializer-gson - 4.16.0 + 4.17.0 net.kyori adventure-text-serializer-gson-legacy-impl - 4.16.0 + 4.17.0 net.kyori adventure-text-serializer-json - 4.16.0 + 4.17.0 net.kyori adventure-text-serializer-json-legacy-impl - 4.16.0 + 4.17.0 net.kyori adventure-api - 4.16.0 + 4.17.0 net.kyori adventure-nbt - 4.16.0 + 4.17.0 net.kyori adventure-key - 4.16.0 + 4.17.0 net.kyori adventure-platform-api - 4.3.2 + 4.3.3-SNAPSHOT net.kyori @@ -349,12 +350,12 @@ net.kyori adventure-platform-facet - 4.3.2 + 4.3.3-SNAPSHOT net.kyori adventure-platform-viaversion - 4.3.2 + 4.3.3-SNAPSHOT net.kyori @@ -364,12 +365,12 @@ org.apache.maven.scm maven-scm-provider-gitexe - 2.0.0-M1 + 2.1.0 org.bstats bstats-bukkit - 3.0.0 + 3.0.2 compile @@ -411,36 +412,36 @@ org.junit.jupiter junit-jupiter - 5.9.0 + 5.11.0-M2 test org.mockito mockito-core - 4.6.1 + 5.12.0 test org.mockito mockito-inline - 4.6.1 + 5.2.0 test org.apache.tomcat tomcat-jdbc - 10.1.0-M17 + 10.1.24 compile org.jetbrains annotations - 23.0.0 + 24.1.0 com.google.guava guava - 32.1.1-jre + 33.2.0-jre compile diff --git a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java index e50dbac27..2902c7445 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java @@ -3,7 +3,7 @@ package com.gmail.nossr50.commands.player; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.runnables.commands.McrankCommandAsyncTask; +import com.gmail.nossr50.runnables.commands.McRankCommandAsyncTask; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.commands.CommandUtils; @@ -111,7 +111,7 @@ public class McrankCommand implements TabExecutor { boolean useBoard = mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getRankUseBoard()); boolean useChat = !useBoard || mcMMO.p.getGeneralConfig().getRankUseChat(); - mcMMO.p.getFoliaLib().getImpl().runAsync(new McrankCommandAsyncTask(playerName, sender, useBoard, useChat)); + mcMMO.p.getFoliaLib().getImpl().runAsync(new McRankCommandAsyncTask(playerName, sender, useBoard, useChat)); } private long getCDSeconds(McMMOPlayer mcMMOPlayer, long cooldownMillis) { diff --git a/src/main/java/com/gmail/nossr50/commands/player/MctopCommand.java b/src/main/java/com/gmail/nossr50/commands/player/MctopCommand.java index 86b1757e9..12e966a6c 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/MctopCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/MctopCommand.java @@ -4,7 +4,7 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask; +import com.gmail.nossr50.runnables.commands.McTopCommandAsyncTask; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.commands.CommandUtils; @@ -115,7 +115,7 @@ public class MctopCommand implements TabExecutor { boolean useBoard = (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getTopUseBoard()); boolean useChat = !useBoard || mcMMO.p.getGeneralConfig().getTopUseChat(); - mcMMO.p.getFoliaLib().getImpl().runAsync(new MctopCommandAsyncTask(page, skill, sender, useBoard, useChat)); + mcMMO.p.getFoliaLib().getImpl().runAsync(new McTopCommandAsyncTask(page, skill, sender, useBoard, useChat)); } private PrimarySkillType extractSkill(CommandSender sender, String skillName) { diff --git a/src/main/java/com/gmail/nossr50/config/mods/CustomEntityLegacyConfig.java b/src/main/java/com/gmail/nossr50/config/mods/CustomEntityLegacyConfig.java index 37244835c..99b3b0761 100644 --- a/src/main/java/com/gmail/nossr50/config/mods/CustomEntityLegacyConfig.java +++ b/src/main/java/com/gmail/nossr50/config/mods/CustomEntityLegacyConfig.java @@ -3,7 +3,6 @@ package com.gmail.nossr50.config.mods; import com.gmail.nossr50.config.LegacyConfigLoader; import com.gmail.nossr50.datatypes.mods.CustomEntity; import com.gmail.nossr50.mcMMO; -import org.apache.commons.lang.ClassUtils; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -30,7 +29,7 @@ public class CustomEntityLegacyConfig extends LegacyConfigLoader { String className = config.getString(entityName + ".Class", ""); try { - clazz = ClassUtils.getClass(className); + clazz = Class.forName(className); } catch (ClassNotFoundException e) { mcMMO.p.getLogger().warning("Invalid class (" + className + ") detected for " + entityName + "."); mcMMO.p.getLogger().warning("This custom entity may not function properly."); diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java index e64deaae7..8f68b7bcf 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java @@ -300,7 +300,7 @@ public class FlatFileDataProcessor { //We add a trailing : as it is needed for some reason (is it?) //TODO: Is the trailing ":" actually necessary? - String fromSplit = org.apache.commons.lang.StringUtils.join(splitData, ":") + ":"; + String fromSplit = org.apache.commons.lang3.StringUtils.join(splitData, ":") + ":"; stringBuilder.append(fromSplit).append("\r\n"); } diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java index 10dca3354..9cd09710d 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java @@ -234,7 +234,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (rewrite) { // Rewrite their data with a valid time character[OVERHAUL_LAST_LOGIN] = Long.toString(lastPlayed); - String newLine = org.apache.commons.lang.StringUtils.join(character, ":"); + String newLine = org.apache.commons.lang3.StringUtils.join(character, ":"); writer.append(newLine).append("\r\n"); } else { writer.append(line).append("\r\n"); @@ -905,7 +905,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } character[UUID_INDEX] = fetchedUUIDs.remove(character[USERNAME_INDEX]).toString(); - line = org.apache.commons.lang.StringUtils.join(character, ":") + ":"; + line = org.apache.commons.lang3.StringUtils.join(character, ":") + ":"; } i++; diff --git a/src/main/java/com/gmail/nossr50/placeholders/PartyLeaderPlaceholder.java b/src/main/java/com/gmail/nossr50/placeholders/PartyLeaderPlaceholder.java index 3f753bed9..bd301b52d 100644 --- a/src/main/java/com/gmail/nossr50/placeholders/PartyLeaderPlaceholder.java +++ b/src/main/java/com/gmail/nossr50/placeholders/PartyLeaderPlaceholder.java @@ -1,6 +1,6 @@ package com.gmail.nossr50.placeholders; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.bukkit.entity.Player; public class PartyLeaderPlaceholder implements Placeholder { @@ -12,7 +12,7 @@ public class PartyLeaderPlaceholder implements Placeholder { @Override public String process(Player player, String params) { - return StringUtils.stripToEmpty(papiExpansion.getPartyLeader(player)); + return StringUtils.trimToEmpty(papiExpansion.getPartyLeader(player)); } @Override diff --git a/src/main/java/com/gmail/nossr50/placeholders/PartyNamePlaceholder.java b/src/main/java/com/gmail/nossr50/placeholders/PartyNamePlaceholder.java index 2cec030d6..e35346887 100644 --- a/src/main/java/com/gmail/nossr50/placeholders/PartyNamePlaceholder.java +++ b/src/main/java/com/gmail/nossr50/placeholders/PartyNamePlaceholder.java @@ -1,6 +1,6 @@ package com.gmail.nossr50.placeholders; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.bukkit.entity.Player; public class PartyNamePlaceholder implements Placeholder { @@ -12,7 +12,7 @@ public class PartyNamePlaceholder implements Placeholder { @Override public String process(Player player, String params) { - return StringUtils.stripToEmpty(papiExpansion.getPartyName(player)); + return StringUtils.trimToEmpty(papiExpansion.getPartyName(player)); } @Override diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandAsyncTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java similarity index 88% rename from src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandAsyncTask.java rename to src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java index 2897b4388..4b24b329a 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandAsyncTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java @@ -3,18 +3,18 @@ package com.gmail.nossr50.runnables.commands; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; -import org.apache.commons.lang.Validate; +import org.apache.commons.lang3.Validate; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Map; -public class McrankCommandAsyncTask extends CancellableRunnable { +public class McRankCommandAsyncTask extends CancellableRunnable { private final String playerName; private final CommandSender sender; private final boolean useBoard, useChat; - public McrankCommandAsyncTask(String playerName, CommandSender sender, boolean useBoard, boolean useChat) { + public McRankCommandAsyncTask(String playerName, CommandSender sender, boolean useBoard, boolean useChat) { Validate.isTrue(useBoard || useChat, "Attempted to start a rank retrieval with both board and chat off"); Validate.notNull(sender, "Attempted to start a rank retrieval with no recipient"); diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java similarity index 89% rename from src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java rename to src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java index a343bc810..f0f0bc05e 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java @@ -4,19 +4,19 @@ import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; -import org.apache.commons.lang.Validate; +import org.apache.commons.lang3.Validate; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; -public class MctopCommandAsyncTask extends CancellableRunnable { +public class McTopCommandAsyncTask extends CancellableRunnable { private final CommandSender sender; private final PrimarySkillType skill; private final int page; private final boolean useBoard, useChat; - public MctopCommandAsyncTask(int page, PrimarySkillType skill, CommandSender sender, boolean useBoard, boolean useChat) { + public McTopCommandAsyncTask(int page, PrimarySkillType skill, CommandSender sender, boolean useBoard, boolean useChat) { Validate.isTrue(useBoard || useChat, "Attempted to start a rank retrieval with both board and chat off"); Validate.notNull(sender, "Attempted to start a rank retrieval with no recipient"); diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java index 7ed51f3ad..3cb06bff0 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java @@ -14,7 +14,7 @@ import org.bukkit.entity.Player; import java.util.List; /** - * Display the results of {@link MctopCommandAsyncTask} to the sender. + * Display the results of {@link McTopCommandAsyncTask} to the sender. */ public class MctopCommandDisplayTask extends CancellableRunnable { private final List userStats; diff --git a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java index aaac5e7fc..3bb866cdd 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java @@ -13,10 +13,11 @@ import com.gmail.nossr50.runnables.skills.AbilityCooldownTask; import com.gmail.nossr50.skills.SkillManager; import com.gmail.nossr50.util.*; import com.gmail.nossr50.util.player.NotificationManager; +import com.gmail.nossr50.util.random.Probability; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; -import org.apache.commons.lang.math.RandomUtils; +import org.apache.commons.lang3.RandomUtils; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -202,7 +203,7 @@ public class MiningManager extends SkillManager { if (isDropIllegal(blockState.getType())) continue; - if (RandomUtils.nextFloat() < debrisYield) { + if (Probability.ofPercent(50).evaluate()) { Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_DEBRIS_NON_ORES); // Initial block that would have been dropped } } diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java index c6e5377fb..881ea31e4 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java @@ -18,7 +18,6 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager.SidebarType; import com.gmail.nossr50.util.skills.SkillTools; import com.tcoded.folialib.wrapper.task.WrappedTask; -import org.apache.commons.lang.Validate; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; @@ -30,6 +29,8 @@ import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; +import static java.util.Objects.requireNonNull; + public class ScoreboardWrapper { public static final String SIDE_OBJECTIVE = "mcMMO_sideObjective"; public static final String POWER_OBJECTIVE = "mcMMO_powerObjective"; @@ -485,7 +486,7 @@ public class ScoreboardWrapper { break; case SKILL_BOARD: - Validate.notNull(targetSkill); + requireNonNull(targetSkill); if (!SkillTools.isChildSkill(targetSkill)) { int currentXP = mcMMOPlayer.getSkillXpLevel(targetSkill); diff --git a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java index 7cd22a75f..c0e17bbe8 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java @@ -3,7 +3,7 @@ package com.gmail.nossr50.util.skills; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; -import org.apache.commons.lang.math.RandomUtils; +import org.apache.commons.lang3.RandomUtils; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; @@ -42,31 +42,22 @@ public final class ParticleEffectUtils { double offSetVal = 0.3D; - switch(RandomUtils.nextInt(10)) { - - case 0: - return new Location(world, x - offSetVal, y, z); - case 1: - return new Location(world, x + offSetVal, y, z); - case 2: - return new Location(world, x, y + offSetVal, z); - case 3: - return new Location(world, x, y - offSetVal, z); - case 4: Location locE = new Location(world, x, y, z + offSetVal); - return new Location(world, x, y, z - offSetVal); - case 5: - return new Location(world, x + offSetVal, y, z + offSetVal); - case 6: - return new Location(world, x - offSetVal, y, z - offSetVal); - case 7: - return new Location(world, x - offSetVal, y - offSetVal, z - offSetVal); - case 8: - return new Location(world, x + offSetVal, y - offSetVal, z + offSetVal); - case 9: - return new Location(world, x - offSetVal, y + offSetVal, z - offSetVal); - default: - return new Location(world, x + offSetVal, y + offSetVal, z - offSetVal); - } + return switch (RandomUtils.nextInt(0, 10)) { + case 0 -> new Location(world, x - offSetVal, y, z); + case 1 -> new Location(world, x + offSetVal, y, z); + case 2 -> new Location(world, x, y + offSetVal, z); + case 3 -> new Location(world, x, y - offSetVal, z); + case 4 -> { + Location locE = new Location(world, x, y, z + offSetVal); + yield new Location(world, x, y, z - offSetVal); + } + case 5 -> new Location(world, x + offSetVal, y, z + offSetVal); + case 6 -> new Location(world, x - offSetVal, y, z - offSetVal); + case 7 -> new Location(world, x - offSetVal, y - offSetVal, z - offSetVal); + case 8 -> new Location(world, x + offSetVal, y - offSetVal, z + offSetVal); + case 9 -> new Location(world, x - offSetVal, y + offSetVal, z - offSetVal); + default -> new Location(world, x + offSetVal, y + offSetVal, z - offSetVal); + }; } public static void playDodgeEffect(Player player) { From 7266563ca95f0855b5cae5c2483b08f9ef4d1e5b Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 13:53:22 -0700 Subject: [PATCH 33/34] Back to Java 17 for now --- .github/workflows/maven.yml | 6 +++--- Changelog.txt | 3 --- pom.xml | 8 ++++---- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 9641dde68..ddd132071 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -31,13 +31,13 @@ jobs: - name: Checkout repository uses: actions/checkout@v2 - # 2. Setup Java 21 JDK (Adopt) - - name: Java 21 setup + # 2. Setup Java 17 JDK (Adopt) + - name: Java 17 setup uses: actions/setup-java@v2 with: distribution: 'adopt' java-package: jdk - java-version: '21' + java-version: '17' # 3. Setup local Maven package cache to speed up building - name: Cache Maven packages diff --git a/Changelog.txt b/Changelog.txt index f3b117d01..103344b54 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,5 +1,4 @@ Version 2.2.013 - mcMMO now requires Java 21 (see notes) Modified the RNG for dropping non-ore blocks from Blast Mining to yield about 50% of what was destroyed (API) Deprecated com.gmail.nossr50.mcMMO.getPlaceStore (API) Added com.gmail.nossr50.mcMMO.getUserBlockTracker @@ -9,8 +8,6 @@ Version 2.2.013 (Codebase) Cleaned up and organized unit tests relating to UserBlockTracker NOTES: - mcMMO is now compiled for Java 21, Java 21 will be requires to run mcMMO. - This should not pose an issue as there are Java 21 server JARs for the versions of MC that mcMMO currently supports. Not planning to delete the deprecated methods in UserBlockTracker anytime soon, as nothing has really changed other than the names Version 2.2.012 diff --git a/pom.xml b/pom.xml index 851f41b8a..c0de518e0 100644 --- a/pom.xml +++ b/pom.xml @@ -14,9 +14,9 @@ UTF-8 - 21 - 21 - 21 + 17 + 17 + 17 @@ -103,7 +103,7 @@ maven-compiler-plugin 3.13.0 - 21 + 17 -parameters From d0ab2bdb2f781eab7f45e72e73d4fe48bc256a7a Mon Sep 17 00:00:00 2001 From: nossr50 Date: Sun, 19 May 2024 14:09:00 -0700 Subject: [PATCH 34/34] clean up if/else formatting --- .../com/gmail/nossr50/api/ExperienceAPI.java | 36 +++----- .../java/com/gmail/nossr50/api/PartyAPI.java | 6 +- .../nossr50/commands/McImportCommand.java | 36 +++----- .../gmail/nossr50/commands/XprateCommand.java | 21 ++--- .../commands/experience/AddxpCommand.java | 3 +- .../experience/ExperienceCommand.java | 18 ++-- .../experience/SkillresetCommand.java | 15 ++-- .../party/PartyChangePasswordCommand.java | 3 +- .../nossr50/commands/party/PartyCommand.java | 6 +- .../commands/party/PartyCreateCommand.java | 3 +- .../commands/party/PartyInfoCommand.java | 6 +- .../commands/party/PartyItemShareCommand.java | 9 +- .../commands/party/PartyJoinCommand.java | 6 +- .../commands/party/PartyLockCommand.java | 12 +-- .../commands/party/PartySubcommandType.java | 15 ++-- .../commands/party/PartyXpShareCommand.java | 3 +- .../party/alliance/PartyAllianceCommand.java | 3 +- .../party/teleport/PtpAcceptAnyCommand.java | 3 +- .../party/teleport/PtpAcceptCommand.java | 6 +- .../commands/party/teleport/PtpCommand.java | 18 ++-- .../party/teleport/PtpToggleCommand.java | 3 +- .../commands/player/McrankCommand.java | 3 +- .../commands/skills/AcrobaticsCommand.java | 3 +- .../commands/skills/MmoInfoCommand.java | 15 ++-- .../nossr50/commands/skills/SkillCommand.java | 27 ++---- .../commands/skills/SkillGuideCommand.java | 3 +- .../commands/skills/SwordsCommand.java | 3 +- .../gmail/nossr50/config/AdvancedConfig.java | 39 +++----- .../database/FlatFileDatabaseManager.java | 3 +- .../datatypes/database/DatabaseType.java | 3 +- .../datatypes/experience/SkillXpGain.java | 3 +- .../nossr50/datatypes/json/McMMOUrl.java | 6 +- .../nossr50/datatypes/json/McMMOWebLinks.java | 12 +-- .../gmail/nossr50/datatypes/meta/OldName.java | 3 +- .../datatypes/party/ItemShareType.java | 12 +-- .../gmail/nossr50/datatypes/party/Party.java | 6 +- .../nossr50/datatypes/party/ShareMode.java | 3 +- .../nossr50/datatypes/player/McMMOPlayer.java | 18 ++-- .../datatypes/player/PlayerProfile.java | 6 +- .../datatypes/skills/ModConfigType.java | 6 +- .../datatypes/skills/SubSkillType.java | 42 +++------ .../skills/subskills/AbstractSubSkill.java | 3 +- .../skills/subskills/acrobatics/Roll.java | 18 ++-- .../scoreboard/McMMOScoreboardEvent.java | 3 +- .../nossr50/listeners/BlockListener.java | 83 +++++++---------- .../nossr50/listeners/EntityListener.java | 66 +++++--------- .../nossr50/listeners/InteractionManager.java | 21 ++--- .../nossr50/listeners/InventoryListener.java | 27 ++---- .../nossr50/listeners/PlayerListener.java | 85 +++++++----------- .../gmail/nossr50/listeners/SelfListener.java | 30 +++---- src/main/java/com/gmail/nossr50/mcMMO.java | 24 ++--- .../com/gmail/nossr50/party/ShareHandler.java | 12 +-- .../runnables/backups/CleanBackupsTask.java | 6 +- .../commands/McrankCommandDisplayTask.java | 3 +- .../commands/MctopCommandDisplayTask.java | 15 ++-- .../commands/NotifySquelchReminderTask.java | 6 +- .../database/FormulaConversionTask.java | 3 +- .../runnables/items/TeleportationWarmup.java | 3 +- .../player/PlayerProfileLoadingTask.java | 3 +- .../runnables/skills/BleedContainer.java | 3 +- .../skills/ExperienceBarHideTask.java | 3 +- .../skills/SkillUnlockNotificationTask.java | 3 +- .../skills/acrobatics/AcrobaticsManager.java | 12 +-- .../skills/alchemy/AlchemyPotionBrewer.java | 18 ++-- .../gmail/nossr50/skills/archery/Archery.java | 3 +- .../com/gmail/nossr50/skills/axes/Axes.java | 3 +- .../nossr50/skills/axes/AxesManager.java | 3 +- .../skills/crossbows/CrossbowsManager.java | 3 +- .../skills/excavation/ExcavationManager.java | 3 +- .../skills/fishing/FishingManager.java | 18 ++-- .../skills/herbalism/HerbalismManager.java | 9 +- .../nossr50/skills/mining/BlastMining.java | 9 +- .../nossr50/skills/repair/RepairManager.java | 9 +- .../skills/salvage/SalvageManager.java | 9 +- .../skills/smelting/SmeltingManager.java | 3 +- .../nossr50/skills/swords/SwordsManager.java | 9 +- .../nossr50/skills/taming/TamingManager.java | 6 +- .../gmail/nossr50/skills/unarmed/Unarmed.java | 16 ++-- .../woodcutting/WoodcuttingManager.java | 6 +- .../com/gmail/nossr50/util/ChimaeraWing.java | 9 +- .../com/gmail/nossr50/util/EventUtils.java | 9 +- .../gmail/nossr50/util/HardcoreManager.java | 3 +- .../gmail/nossr50/util/MaterialMapStore.java | 54 ++++------- .../gmail/nossr50/util/MobHealthbarUtils.java | 18 ++-- .../com/gmail/nossr50/util/ModManager.java | 6 +- .../util/blockmeta/BitSetChunkStore.java | 26 +++--- .../util/blockmeta/HashChunkManager.java | 10 +-- .../util/blockmeta/McMMOSimpleRegionFile.java | 3 +- .../nossr50/util/commands/CommandUtils.java | 3 +- .../util/experience/ExperienceBarManager.java | 15 ++-- .../util/experience/ExperienceBarWrapper.java | 21 ++--- .../util/experience/FormulaManager.java | 3 +- .../util/platform/PlatformManager.java | 9 +- .../util/player/NotificationManager.java | 42 +++------ .../nossr50/util/player/PlayerLevelUtils.java | 3 +- .../nossr50/util/player/UserManager.java | 6 +- .../util/scoreboards/ScoreboardManager.java | 6 +- .../util/scoreboards/ScoreboardWrapper.java | 30 +++---- .../nossr50/util/skills/CombatUtils.java | 78 ++++++---------- .../gmail/nossr50/util/skills/PerksUtils.java | 33 +++---- .../gmail/nossr50/util/skills/RankUtils.java | 90 +++++++------------ .../gmail/nossr50/util/skills/SkillUtils.java | 27 ++---- .../nossr50/util/sounds/SoundManager.java | 21 ++--- .../gmail/nossr50/util/sounds/SoundType.java | 3 +- .../nossr50/worldguard/WorldGuardManager.java | 12 +-- .../nossr50/worldguard/WorldGuardUtils.java | 12 +-- .../shatt/backup/ZipLibrary.java | 6 +- 107 files changed, 526 insertions(+), 1038 deletions(-) diff --git a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java index fd928fdee..a32873a29 100644 --- a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java +++ b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java @@ -1143,14 +1143,10 @@ public final class ExperienceAPI { * @param blockStates the blocks to reward XP for * @param mcMMOPlayer the target player */ - public static void addXpFromBlocks(ArrayList blockStates, McMMOPlayer mcMMOPlayer) - { - for(BlockState bs : blockStates) - { - for(PrimarySkillType skillType : PrimarySkillType.values()) - { - if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) - { + public static void addXpFromBlocks(ArrayList blockStates, McMMOPlayer mcMMOPlayer) { + for(BlockState bs : blockStates) { + for(PrimarySkillType skillType : PrimarySkillType.values()) { + if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1163,12 +1159,9 @@ public final class ExperienceAPI { * @param mcMMOPlayer the target player * @param skillType target primary skill */ - public static void addXpFromBlocksBySkill(ArrayList blockStates, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) - { - for(BlockState bs : blockStates) - { - if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) - { + public static void addXpFromBlocksBySkill(ArrayList blockStates, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) { + for(BlockState bs : blockStates) { + if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1179,12 +1172,9 @@ public final class ExperienceAPI { * @param blockState The target blockstate * @param mcMMOPlayer The target player */ - public static void addXpFromBlock(BlockState blockState, McMMOPlayer mcMMOPlayer) - { - for(PrimarySkillType skillType : PrimarySkillType.values()) - { - if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) - { + public static void addXpFromBlock(BlockState blockState, McMMOPlayer mcMMOPlayer) { + for(PrimarySkillType skillType : PrimarySkillType.values()) { + if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1196,10 +1186,8 @@ public final class ExperienceAPI { * @param mcMMOPlayer The target player * @param skillType target primary skill */ - public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) - { - if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) - { + public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) { + if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), XPGainReason.PVE, XPGainSource.SELF); } } diff --git a/src/main/java/com/gmail/nossr50/api/PartyAPI.java b/src/main/java/com/gmail/nossr50/api/PartyAPI.java index 246131408..f18dcf6fe 100644 --- a/src/main/java/com/gmail/nossr50/api/PartyAPI.java +++ b/src/main/java/com/gmail/nossr50/api/PartyAPI.java @@ -109,8 +109,7 @@ public final class PartyAPI { if (party == null) { party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName); } else { - if (mcMMO.p.getPartyManager().isPartyFull(player, party)) - { + if (mcMMO.p.getPartyManager().isPartyFull(player, party)) { NotificationManager.sendPlayerInformation(player, NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull", party.toString()); return; } @@ -124,8 +123,7 @@ public final class PartyAPI { * 0 or less for no size limit * @return the max party size on this server */ - public static int getMaxPartySize() - { + public static int getMaxPartySize() { return mcMMO.p.getGeneralConfig().getPartyMaxSize(); } diff --git a/src/main/java/com/gmail/nossr50/commands/McImportCommand.java b/src/main/java/com/gmail/nossr50/commands/McImportCommand.java index 3c913ea47..d19247d0d 100644 --- a/src/main/java/com/gmail/nossr50/commands/McImportCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McImportCommand.java @@ -200,14 +200,11 @@ public class McImportCommand implements CommandExecutor { String skillName = "UNIDENTIFIED"; if (materialName.contains("ORE")) { skillName = "Mining"; - } - else if (materialName.contains("LOG") || materialName.contains("LEAVES")) { + } else if (materialName.contains("LOG") || materialName.contains("LEAVES")) { skillName = "Woodcutting"; - } - else if (materialName.contains("GRASS") || materialName.contains("SHORT_GRASS") || materialName.contains("FLOWER") || materialName.contains("CROP")) { + } else if (materialName.contains("GRASS") || materialName.contains("SHORT_GRASS") || materialName.contains("FLOWER") || materialName.contains("CROP")) { skillName = "Herbalism"; - } - else if (materialName.contains("DIRT") || materialName.contains("SAND")) { + } else if (materialName.contains("DIRT") || materialName.contains("SAND")) { skillName = "Excavation"; } @@ -222,8 +219,7 @@ public class McImportCommand implements CommandExecutor { if (skillName.equals("Mining")) { skillContents.add(" " + " " + "Smelting_XP_Gain: 9"); - } - else if (skillName.equals("Woodcutting")) { + } else if (skillName.equals("Woodcutting")) { skillContents.add(" " + " " + "Is_Log: " + materialName.contains("LOG")); } } @@ -239,20 +235,15 @@ public class McImportCommand implements CommandExecutor { String toolType = "UNIDENTIFIED"; if (materialName.contains("PICKAXE")) { toolType = "Pickaxes"; - } - else if (materialName.contains("AXE")) { + } else if (materialName.contains("AXE")) { toolType = "Axes"; - } - else if (materialName.contains("BOW")) { + } else if (materialName.contains("BOW")) { toolType = "Bows"; - } - else if (materialName.contains("HOE")) { + } else if (materialName.contains("HOE")) { toolType = "Hoes"; - } - else if (materialName.contains("SHOVEL") || materialName.contains("SPADE")) { + } else if (materialName.contains("SHOVEL") || materialName.contains("SPADE")) { toolType = "Shovels"; - } - else if (materialName.contains("SWORD")) { + } else if (materialName.contains("SWORD")) { toolType = "Swords"; } @@ -279,14 +270,11 @@ public class McImportCommand implements CommandExecutor { String toolType = "UNIDENTIFIED"; if (materialName.contains("BOOT") || materialName.contains("SHOE")) { toolType = "Boots"; - } - else if (materialName.contains("CHESTPLATE") || materialName.contains("CHEST")) { + } else if (materialName.contains("CHESTPLATE") || materialName.contains("CHEST")) { toolType = "Chestplates"; - } - else if (materialName.contains("HELM") || materialName.contains("HAT")) { + } else if (materialName.contains("HELM") || materialName.contains("HAT")) { toolType = "Helmets"; - } - else if (materialName.contains("LEGGINGS") || materialName.contains("LEGS") || materialName.contains("PANTS")) { + } else if (materialName.contains("LEGGINGS") || materialName.contains("LEGS") || materialName.contains("PANTS")) { toolType = "Leggings"; } diff --git a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java index a32ba1979..2eb487826 100644 --- a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java @@ -37,16 +37,14 @@ public class XprateCommand implements TabExecutor { if (mcMMO.p.isXPEventEnabled()) { - if (mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) - { + if (mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Stop"), LocaleLoader.getString("Commands.Event.Stop.Subtitle"), 10, 10*20, 20); } - if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) - { + if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) { mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop.Subtitle")); } @@ -72,34 +70,29 @@ public class XprateCommand implements TabExecutor { if (CommandUtils.shouldDisableToggle(args[1])) { mcMMO.p.setXPEventEnabled(false); - } - else if (CommandUtils.shouldEnableToggle(args[1])) { + } else if (CommandUtils.shouldEnableToggle(args[1])) { mcMMO.p.setXPEventEnabled(true); - } - else { + } else { return false; } int newXpRate = Integer.parseInt(args[0]); - if (newXpRate < 0) - { + if (newXpRate < 0) { sender.sendMessage(ChatColor.RED+LocaleLoader.getString("Commands.NegativeNumberWarn")); return true; } ExperienceConfig.getInstance().setExperienceGainsGlobalMultiplier(newXpRate); - if (mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) - { + if (mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Start"), LocaleLoader.getString("Commands.Event.XP", newXpRate), 10, 10*20, 20); } - if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) - { + if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) { mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Start")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.XP", newXpRate)); } diff --git a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java index 259b6c7aa..953ad7436 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java @@ -30,8 +30,7 @@ public class AddxpCommand extends ExperienceCommand { return; UserManager.getPlayer(player).applyXpGain(skill, value, XPGainReason.COMMAND, XPGainSource.COMMAND); - } - else { + } else { profile.addXp(skill, value); profile.scheduleAsyncSave(); } diff --git a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java index 6ee6673de..37e1d6c17 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java @@ -49,15 +49,13 @@ public abstract class ExperienceCommand implements TabExecutor { skill = null; } - if (skill != null && SkillTools.isChildSkill(skill)) - { + if (skill != null && SkillTools.isChildSkill(skill)) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill")); return true; } //Profile not loaded - if (UserManager.getPlayer(sender.getName()) == null) - { + if (UserManager.getPlayer(sender.getName()) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -82,8 +80,7 @@ public abstract class ExperienceCommand implements TabExecutor { skill = null; } - if (skill != null && SkillTools.isChildSkill(skill)) - { + if (skill != null && SkillTools.isChildSkill(skill)) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill")); return true; } @@ -110,8 +107,7 @@ public abstract class ExperienceCommand implements TabExecutor { } editValues(null, profile, skill, value, isSilent(args)); - } - else { + } else { editValues(mcMMOPlayer.getPlayer(), mcMMOPlayer.getProfile(), skill, value, isSilent(args)); } @@ -159,8 +155,7 @@ public abstract class ExperienceCommand implements TabExecutor { protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { if (skill == null) { sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName)); } } @@ -174,8 +169,7 @@ public abstract class ExperienceCommand implements TabExecutor { if (player != null) { handlePlayerMessageAll(player, value, isSilent); } - } - else { + } else { handleCommand(player, profile, skill, value); if (player != null) { diff --git a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java index 33b2f311f..e2fcd38ec 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java @@ -48,8 +48,7 @@ public class SkillresetCommand implements TabExecutor { if (args[0].equalsIgnoreCase("all")) { skill = null; - } - else { + } else { skill = mcMMO.p.getSkillTools().matchSkill(args[0]); } @@ -68,8 +67,7 @@ public class SkillresetCommand implements TabExecutor { if (args[1].equalsIgnoreCase("all")) { skill = null; - } - else { + } else { skill = mcMMO.p.getSkillTools().matchSkill(args[1]); } @@ -93,8 +91,7 @@ public class SkillresetCommand implements TabExecutor { } editValues(null, profile, skill); - } - else { + } else { editValues(mcMMOPlayer.getPlayer(), mcMMOPlayer.getProfile(), skill); } @@ -156,8 +153,7 @@ public class SkillresetCommand implements TabExecutor { protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { if (skill == null) { sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName)); } } @@ -171,8 +167,7 @@ public class SkillresetCommand implements TabExecutor { if (player != null) { handlePlayerMessageAll(player); } - } - else { + } else { handleCommand(player, profile, skill); if (player != null) { diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java index 4f1743a02..7ef2dc560 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java @@ -12,8 +12,7 @@ import org.jetbrains.annotations.NotNull; public class PartyChangePasswordCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java index 3f59fe184..06691c171 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java @@ -90,8 +90,7 @@ public class PartyCommand implements TabExecutor { } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -207,8 +206,7 @@ public class PartyCommand implements TabExecutor { final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Not Loaded - if (mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return ImmutableList.of(); } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java index debe0ce45..b11ac69ff 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java @@ -19,8 +19,7 @@ public class PartyCreateCommand implements CommandExecutor { Player player = (Player) sender; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java index 74ef9d8ae..892256cdb 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java @@ -23,8 +23,7 @@ public class PartyInfoCommand implements CommandExecutor { switch (args.length) { case 0: case 1: - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -70,8 +69,7 @@ public class PartyInfoCommand implements CommandExecutor { if (isUnlockedFeature(party, partyFeature)) { unlockedPartyFeatures.add(partyFeature.getLocaleString()); - } - else { + } else { lockedPartyFeatures.add(partyFeature.getFeatureLockedLocaleString()); } } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java index f5e58c529..38a3e3a24 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java @@ -20,8 +20,7 @@ import java.util.Locale; public class PartyItemShareCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -50,11 +49,9 @@ public class PartyItemShareCommand implements CommandExecutor { if (CommandUtils.shouldEnableToggle(args[2])) { toggle = true; - } - else if (CommandUtils.shouldDisableToggle(args[2])) { + } else if (CommandUtils.shouldDisableToggle(args[2])) { toggle = false; - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", " ")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java index b88bfa757..79b14b915 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java @@ -34,8 +34,7 @@ public class PartyJoinCommand implements CommandExecutor { Player player = (Player) sender; - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -62,8 +61,7 @@ public class PartyJoinCommand implements CommandExecutor { return true; } - if (mcMMO.p.getPartyManager().isPartyFull(player, targetParty)) - { + if (mcMMO.p.getPartyManager().isPartyFull(player, targetParty)) { player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull", targetParty.toString())); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java index 130f43d7e..745fba90f 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java @@ -18,8 +18,7 @@ public class PartyLockCommand implements CommandExecutor { case 1: if (args[0].equalsIgnoreCase("lock")) { togglePartyLock(sender, true); - } - else if (args[0].equalsIgnoreCase("unlock")) { + } else if (args[0].equalsIgnoreCase("unlock")) { togglePartyLock(sender, false); } @@ -33,11 +32,9 @@ public class PartyLockCommand implements CommandExecutor { if (CommandUtils.shouldEnableToggle(args[1])) { togglePartyLock(sender, true); - } - else if (CommandUtils.shouldDisableToggle(args[1])) { + } else if (CommandUtils.shouldDisableToggle(args[1])) { togglePartyLock(sender, false); - } - else { + } else { sendUsageStrings(sender); } @@ -55,8 +52,7 @@ public class PartyLockCommand implements CommandExecutor { } private void togglePartyLock(CommandSender sender, boolean lock) { - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java b/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java index f4ebdb510..c9c45453d 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java @@ -30,20 +30,15 @@ public enum PartySubcommandType { if (commandName.equalsIgnoreCase("?")) { return HELP; - } - else if (commandName.equalsIgnoreCase("q") || commandName.equalsIgnoreCase("leave")) { + } else if (commandName.equalsIgnoreCase("q") || commandName.equalsIgnoreCase("leave")) { return QUIT; - } - else if (commandName.equalsIgnoreCase("leader")) { + } else if (commandName.equalsIgnoreCase("leader")) { return OWNER; - } - else if (commandName.equalsIgnoreCase("xpshare") || commandName.equalsIgnoreCase("shareexp") || commandName.equalsIgnoreCase("sharexp")) { + } else if (commandName.equalsIgnoreCase("xpshare") || commandName.equalsIgnoreCase("shareexp") || commandName.equalsIgnoreCase("sharexp")) { return XPSHARE; - } - else if (commandName.equalsIgnoreCase("shareitem") || commandName.equalsIgnoreCase("shareitems")) { + } else if (commandName.equalsIgnoreCase("shareitem") || commandName.equalsIgnoreCase("shareitems")) { return ITEMSHARE; - } - else if (commandName.equalsIgnoreCase("ally")) { + } else if (commandName.equalsIgnoreCase("ally")) { return ALLIANCE; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java index c96792385..098cdc3a2 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java @@ -17,8 +17,7 @@ import org.jetbrains.annotations.NotNull; public class PartyXpShareCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java index e839011ea..231f85456 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java @@ -37,8 +37,7 @@ public class PartyAllianceCommand implements TabExecutor { return true; } - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java index 9822860f6..3b589ad0b 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java @@ -21,8 +21,7 @@ public class PtpAcceptAnyCommand implements CommandExecutor { if (ptpRecord.isConfirmRequired()) { sender.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled")); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Enabled")); } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java index 15c6ca281..c5c22aad3 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java @@ -21,8 +21,7 @@ public class PtpAcceptCommand implements CommandExecutor { return true; } - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -56,8 +55,7 @@ public class PtpAcceptCommand implements CommandExecutor { if (!Permissions.partyTeleportWorld(target, targetWorld)) { target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return true; - } - else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) { + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) { target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", playerWorld.getName())); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java index 14c9b57b9..fee032c17 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java @@ -45,8 +45,7 @@ public class PtpCommand implements TabExecutor { Player player = (Player) sender; /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return true; } @@ -59,8 +58,7 @@ public class PtpCommand implements TabExecutor { return true; } - if (UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -171,8 +169,7 @@ public class PtpCommand implements TabExecutor { if (!Permissions.partyTeleportWorld(target, targetWorld)) { player.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return; - } - else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(player, targetWorld)) { + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(player, targetWorld)) { player.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return; } @@ -228,14 +225,12 @@ public class PtpCommand implements TabExecutor { } protected static void handleTeleportWarmup(Player teleportingPlayer, Player targetPlayer) { - if (UserManager.getPlayer(targetPlayer) == null) - { + if (UserManager.getPlayer(targetPlayer) == null) { targetPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } - if (UserManager.getPlayer(teleportingPlayer) == null) - { + if (UserManager.getPlayer(teleportingPlayer) == null) { teleportingPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } @@ -250,8 +245,7 @@ public class PtpCommand implements TabExecutor { if (warmup > 0) { teleportingPlayer.sendMessage(LocaleLoader.getString("Teleport.Commencing", warmup)); mcMMO.p.getFoliaLib().getImpl().runAtEntityLater(teleportingPlayer, new TeleportationWarmup(mcMMOPlayer, mcMMOTarget), 20 * warmup); - } - else { + } else { EventUtils.handlePartyTeleportEvent(teleportingPlayer, targetPlayer); } } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java index aad4df9b9..e3ef50491 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java @@ -21,8 +21,7 @@ public class PtpToggleCommand implements CommandExecutor { if (ptpRecord.isEnabled()) { sender.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled")); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.ptp.Enabled")); } diff --git a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java index 2902c7445..48586ef59 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java @@ -85,8 +85,7 @@ public class McrankCommand implements TabExecutor { if (sender instanceof Player) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); - if (mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java index fc5938f34..d04d3d4d4 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java @@ -54,8 +54,7 @@ public class AcrobaticsCommand extends SkillCommand { AbstractSubSkill abstractSubSkill = InteractionManager.getAbstractByName("Roll"); - if (abstractSubSkill != null) - { + if (abstractSubSkill != null) { String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_ROLL); messages.add(getStatMessage(SubSkillType.ACROBATICS_ROLL, rollStrings[0]) diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java index 64152af8a..795f4005c 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java @@ -26,15 +26,12 @@ public class MmoInfoCommand implements TabExecutor { /* * Only allow players to use this command */ - if (commandSender instanceof Player player) - { + if (commandSender instanceof Player player) { if (args == null || args.length < 1 || args[0] == null || args[0].isEmpty()) return false; - if (Permissions.mmoinfo(player)) - { - if (args[0].equalsIgnoreCase( "???")) - { + if (Permissions.mmoinfo(player)) { + if (args[0].equalsIgnoreCase( "???")) { player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", "???")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); @@ -57,8 +54,7 @@ public class MmoInfoCommand implements TabExecutor { } public SubSkillType matchSubSkill(String name) { - for(SubSkillType subSkillType : SubSkillType.values()) - { + for(SubSkillType subSkillType : SubSkillType.values()) { if (subSkillType.getNiceNameNoSpaces(subSkillType).equalsIgnoreCase(name) || subSkillType.name().equalsIgnoreCase(name)) return subSkillType; @@ -74,8 +70,7 @@ public class MmoInfoCommand implements TabExecutor { return ImmutableList.of(); } - private void displayInfo(Player player, SubSkillType subSkillType) - { + private void displayInfo(Player player, SubSkillType subSkillType) { player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", subSkillType.getLocaleName())); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java index f49542304..4e20a761b 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java @@ -88,8 +88,7 @@ public abstract class SkillCommand implements TabExecutor { TextComponentFactory.sendPlayerSubSkillList(player, subskillTextComponents); - /*for(TextComponent tc : subskillTextComponents) - { + /*for(TextComponent tc : subskillTextComponents) { player.spigot().sendMessage(new TextComponent[]{tc, new TextComponent(": TESTING")}); }*/ @@ -149,8 +148,7 @@ public abstract class SkillCommand implements TabExecutor { // send header player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", skillName)); - if (!SkillTools.isChildSkill(skill)) - { + if (!SkillTools.isChildSkill(skill)) { /* * NON-CHILD SKILLS */ @@ -175,10 +173,8 @@ public abstract class SkillCommand implements TabExecutor { StringBuilder parentMessage = new StringBuilder(); - for(int i = 0; i < parentList.size(); i++) - { - if (i+1 < parentList.size()) - { + for(int i = 0; i < parentList.size(); i++) { + if (i+1 < parentList.size()) { parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), mcMMOPlayer.getSkillLevel(parentList.get(i)))); parentMessage.append(ChatColor.GRAY).append(", "); } else { @@ -237,11 +233,9 @@ public abstract class SkillCommand implements TabExecutor { int length; - if (abilityLengthCap <= 0) - { + if (abilityLengthCap <= 0) { length = 2 + (int) (skillValue / abilityLengthVar); - } - else { + } else { length = 2 + (int) (Math.min(abilityLengthCap, skillValue) / abilityLengthVar); } @@ -254,20 +248,17 @@ public abstract class SkillCommand implements TabExecutor { return new String[] { String.valueOf(length), String.valueOf(enduranceLength) }; } - protected String getStatMessage(SubSkillType subSkillType, String... vars) - { + protected String getStatMessage(SubSkillType subSkillType, String... vars) { return getStatMessage(false, false, subSkillType, vars); } - protected String getStatMessage(boolean isExtra, boolean isCustom, SubSkillType subSkillType, String... vars) - { + protected String getStatMessage(boolean isExtra, boolean isCustom, SubSkillType subSkillType, String... vars) { String templateKey = isCustom ? "Ability.Generic.Template.Custom" : "Ability.Generic.Template"; String statDescriptionKey = !isExtra ? subSkillType.getLocaleKeyStatDescription() : subSkillType.getLocaleKeyStatExtraDescription(); if (isCustom) return LocaleLoader.getString(templateKey, LocaleLoader.getString(statDescriptionKey, vars)); - else - { + else { String[] mergedList = NotificationManager.addItemToFirstPositionOfArray(LocaleLoader.getString(statDescriptionKey), vars); return LocaleLoader.getString(templateKey, mergedList); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java index ed471f188..6b9342598 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java @@ -77,8 +77,7 @@ public class SkillGuideCommand implements CommandExecutor { while (allStrings.size() < 9) { if (pageIndexStart + allStrings.size() > guide.size()) { allStrings.add(""); - } - else { + } else { allStrings.add(guide.get(pageIndexStart + (allStrings.size() - 1))); } } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java index 1de2a9c38..c44af71ef 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java @@ -101,8 +101,7 @@ public class SwordsCommand extends SkillCommand { + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", serratedStrikesLengthEndurance) : "")); } - if (SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_STAB)) - { + if (SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_STAB)) { messages.add(getStatMessage(SubSkillType.SWORDS_STAB, String.valueOf(mmoPlayer.getSwordsManager().getStabDamage()))); } diff --git a/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java b/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java index da882f098..15b7d74c8 100644 --- a/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java +++ b/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java @@ -504,8 +504,7 @@ public class AdvancedConfig extends BukkitConfig { */ - /*public ChatColor getJSONStatHoverElementColor(StatType statType, boolean isPrefix) - { + /*public ChatColor getJSONStatHoverElementColor(StatType statType, boolean isPrefix) { String keyAddress = isPrefix ? "Prefix" : "Value"; String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Color"; @@ -517,50 +516,41 @@ public class AdvancedConfig extends BukkitConfig { * * @return the ChatColor for this element */ - /*public ChatColor getJSONStatHoverDetailsColor() - { + /*public ChatColor getJSONStatHoverDetailsColor() { String keyLocation = "Style.JSON.Hover.Details.Header.Color"; return getChatColorFromKey(keyLocation); } - public boolean isJSONDetailsHeaderBold() - { + public boolean isJSONDetailsHeaderBold() { return config.getBoolean("Style.JSON.Hover.Details.Header.Bold"); } - public boolean isJSONDetailsHeaderItalic() - { + public boolean isJSONDetailsHeaderItalic() { return config.getBoolean("Style.JSON.Hover.Details.Header.Italics"); } - public boolean isJSONDetailsHeaderUnderlined() - { + public boolean isJSONDetailsHeaderUnderlined() { return config.getBoolean("Style.JSON.Hover.Details.Header.Underlined"); } - public ChatColor getJSONStatHoverDescriptionColor() - { + public ChatColor getJSONStatHoverDescriptionColor() { String keyLocation = "Style.JSON.Hover.Details.Description.Color"; return getChatColorFromKey(keyLocation); } - public boolean isJSONDetailsDescriptionBold() - { + public boolean isJSONDetailsDescriptionBold() { return config.getBoolean("Style.JSON.Hover.Details.Description.Bold"); } - public boolean isJSONDetailsDescriptionItalic() - { + public boolean isJSONDetailsDescriptionItalic() { return config.getBoolean("Style.JSON.Hover.Details.Description.Italics"); } - public boolean isJSONDetailsDescriptionUnderlined() - { + public boolean isJSONDetailsDescriptionUnderlined() { return config.getBoolean("Style.JSON.Hover.Details.Description.Underlined"); } - public ChatColor getJSONActionBarColor(NotificationType notificationType) - { + public ChatColor getJSONActionBarColor(NotificationType notificationType) { return getChatColor(config.getString("Style.JSON.Notification."+notificationType.toString()+".Color")); }*/ private ChatColor getChatColorFromKey(String keyLocation) { @@ -580,22 +570,19 @@ public class AdvancedConfig extends BukkitConfig { return ChatColor.WHITE; } - /*public boolean isJSONStatHoverElementBold(StatType statType, boolean isPrefix) - { + /*public boolean isJSONStatHoverElementBold(StatType statType, boolean isPrefix) { String keyAddress = isPrefix ? "Prefix" : "Value"; String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Bold"; return config.getBoolean(keyLocation); } - public boolean isJSONStatHoverElementItalic(StatType statType, boolean isPrefix) - { + public boolean isJSONStatHoverElementItalic(StatType statType, boolean isPrefix) { String keyAddress = isPrefix ? "Prefix" : "Value"; String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Italics"; return config.getBoolean(keyLocation); } - public boolean isJSONStatHoverElementUnderlined(StatType statType, boolean isPrefix) - { + public boolean isJSONStatHoverElementUnderlined(StatType statType, boolean isPrefix) { String keyAddress = isPrefix ? "Prefix" : "Value"; String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Underline"; return config.getBoolean(keyLocation); diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java index 9cd09710d..a73be51ad 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java @@ -152,8 +152,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { // If they're still around, rewrite them to the file. if (!powerless) { writer.append(line).append("\r\n"); - } - else { + } else { purgedUsers++; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java b/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java index c8e089ab6..11a01cdec 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java @@ -14,8 +14,7 @@ public enum DatabaseType { if (typeName.equalsIgnoreCase("file")) { return FLATFILE; - } - else if (typeName.equalsIgnoreCase("mysql")) { + } else if (typeName.equalsIgnoreCase("mysql")) { return SQL; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java b/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java index 3ffb1cd94..2725daafe 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java +++ b/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java @@ -33,8 +33,7 @@ public class SkillXpGain implements Delayed { public int compareTo(SkillXpGain other) { if (this.expiryTime < other.expiryTime) { return -1; - } - else if (this.expiryTime > other.expiryTime) { + } else if (this.expiryTime > other.expiryTime) { return 1; } return 0; diff --git a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java index 4cac6d1e5..252644820 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java +++ b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java @@ -8,10 +8,8 @@ public class McMMOUrl { public static final String urlSpigot = "https://spigot.mcmmo.org"; public static final String urlTranslate = "https://translate.mcmmo.org/"; - public static String getUrl(McMMOWebLinks webLinks) - { - switch(webLinks) - { + public static String getUrl(McMMOWebLinks webLinks) { + switch(webLinks) { case WIKI: return urlWiki; case PATREON: diff --git a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java index 9648883fb..2e7eb887b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java +++ b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java @@ -11,20 +11,16 @@ public enum McMMOWebLinks { HELP_TRANSLATE, WIKI; - public String getUrl() - { + public String getUrl() { return McMMOUrl.getUrl(this); } - public String getNiceTitle() - { + public String getNiceTitle() { return StringUtils.getCapitalized(toString()); } - public String getLocaleDescription() - { - switch (this) - { + public String getLocaleDescription() { + switch (this) { case WEBSITE: return LocaleLoader.getString( "JSON.URL.Website"); case DISCORD: diff --git a/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java b/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java index 137399009..9aac9b224 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java +++ b/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java @@ -8,8 +8,7 @@ import org.bukkit.metadata.FixedMetadataValue; */ public class OldName extends FixedMetadataValue { - public OldName(String oldName, mcMMO plugin) - { + public OldName(String oldName, mcMMO plugin) { super(plugin, oldName); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java b/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java index 270421f14..8089e025e 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java @@ -15,17 +15,13 @@ public enum ItemShareType { public static ItemShareType getShareType(ItemStack itemStack) { if (ItemUtils.isMobDrop(itemStack)) { return LOOT; - } - else if (ItemUtils.isMiningDrop(itemStack)) { + } else if (ItemUtils.isMiningDrop(itemStack)) { return MINING; - } - else if (ItemUtils.isHerbalismDrop(itemStack)) { + } else if (ItemUtils.isHerbalismDrop(itemStack)) { return HERBALISM; - } - else if (ItemUtils.isWoodcuttingDrop(itemStack)) { + } else if (ItemUtils.isWoodcuttingDrop(itemStack)) { return WOODCUTTING; - } - else if (ItemUtils.isMiscDrop(itemStack)) { + } else if (ItemUtils.isMiscDrop(itemStack)) { return MISC; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java index ddec901d8..d1983507b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java @@ -85,12 +85,10 @@ public class Party { return onlineMembers; } - public List getVisibleMembers(Player player) - { + public List getVisibleMembers(Player player) { ArrayList visibleMembers = new ArrayList<>(); - for(Player p : onlineMembers) - { + for(Player p : onlineMembers) { if (player.canSee(p)) visibleMembers.add(p); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java b/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java index 778ed08e6..3c136711b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java @@ -14,8 +14,7 @@ public enum ShareMode { catch (IllegalArgumentException ex) { if (string.equalsIgnoreCase("even")) { return EQUAL; - } - else if (CommandUtils.shouldDisableToggle(string)) { + } else if (CommandUtils.shouldDisableToggle(string)) { return NONE; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java index c465e55dc..464719ce0 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java @@ -250,8 +250,7 @@ public class McMMOPlayer implements Identified { this.lastSkillShownScoreboard = primarySkillType; } - public void processPostXpEvent(PrimarySkillType primarySkillType, Plugin plugin, XPGainSource xpGainSource) - { + public void processPostXpEvent(PrimarySkillType primarySkillType, Plugin plugin, XPGainSource xpGainSource) { //Check if they've reached the power level cap just now if (hasReachedPowerLevelCap()) { NotificationManager.sendPlayerInformationChatOnly(player, "LevelCap.PowerLevel", String.valueOf(mcMMO.p.getGeneralConfig().getPowerLevelCap())); @@ -272,19 +271,16 @@ public class McMMOPlayer implements Identified { updateXPBar(primarySkillType, plugin); } - public void processUnlockNotifications(mcMMO plugin, PrimarySkillType primarySkillType, int skillLevel) - { + public void processUnlockNotifications(mcMMO plugin, PrimarySkillType primarySkillType, int skillLevel) { RankUtils.executeSkillUnlockNotifications(plugin, this, primarySkillType, skillLevel); } - public void updateXPBar(PrimarySkillType primarySkillType, Plugin plugin) - { + public void updateXPBar(PrimarySkillType primarySkillType, Plugin plugin) { //XP BAR UPDATES experienceBarManager.updateExperienceBar(primarySkillType, plugin); } - public double getProgressInCurrentSkillLevel(PrimarySkillType primarySkillType) - { + public double getProgressInCurrentSkillLevel(PrimarySkillType primarySkillType) { if (SkillTools.isChildSkill(primarySkillType)) { return 1.0D; } @@ -906,8 +902,7 @@ public class McMMOPlayer implements Identified { //TODO: This is hacky and temporary solution until skills are move to the new system //Potential problems with this include skills with two super abilities (ie mining) - if (!RankUtils.hasUnlockedSubskill(player, subSkillType)) - { + if (!RankUtils.hasUnlockedSubskill(player, subSkillType)) { int diff = RankUtils.getSuperAbilityUnlockRequirement(superAbilityType) - getSkillLevel(primarySkillType); //Inform the player they are not yet skilled enough @@ -941,8 +936,7 @@ public class McMMOPlayer implements Identified { int ticks; //Ability cap of 0 or below means no cap - if (abilityLengthCap > 0) - { + if (abilityLengthCap > 0) { ticks = PerksUtils.handleActivationPerks(player, 2 + (Math.min(abilityLengthCap, getSkillLevel(primarySkillType)) / abilityLengthVar), superAbilityType.getMaxLength()); } else { ticks = PerksUtils.handleActivationPerks(player, 2 + (getSkillLevel(primarySkillType) / abilityLengthVar), superAbilityType.getMaxLength()); diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java index 1087fca48..80f94427d 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java @@ -135,8 +135,7 @@ public class PlayerProfile { + " resulted in failure. "+saveAttempts+" have been made so far."); } - if (saveAttempts < 10) - { + if (saveAttempts < 10) { saveAttempts++; //Back out of async saving if we detect a server shutdown, this is not always going to be caught @@ -372,8 +371,7 @@ public class PlayerProfile { for (PrimarySkillType parentSkill : parentSkills) { skillsXp.put(parentSkill, skillsXp.get(parentSkill) + dividedXP); } - } - else { + } else { skillsXp.put(skill, skillsXp.get(skill) + xp); } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java index df951d783..e6f0da0c5 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java @@ -9,11 +9,9 @@ public enum ModConfigType { public static ModConfigType getModConfigType(String materialName) { if (materialName.contains("HELM") || (materialName.contains("CHEST") && !materialName.contains("CHESTNUT")) || materialName.contains("LEGS") || materialName.contains("LEGGINGS") || materialName.contains("BOOT")) { return ARMOR; - } - else if (materialName.contains("PICKAXE") || materialName.contains("AXE") || (materialName.contains("BOW") && !materialName.contains("BOWL")) || materialName.contains("HOE") || materialName.contains("SHOVEL") || materialName.contains("SWORD")) { + } else if (materialName.contains("PICKAXE") || materialName.contains("AXE") || (materialName.contains("BOW") && !materialName.contains("BOWL")) || materialName.contains("HOE") || materialName.contains("SHOVEL") || materialName.contains("SWORD")) { return TOOLS; - } - else if (materialName.contains("LOG") || materialName.contains("LEAVES") || materialName.contains("FLOWER") || materialName.contains("PLANT") || materialName.contains("CROP") || materialName.contains("ORE") || materialName.contains("DIRT") || materialName.contains("SAND") || materialName.contains("GRASS")) { + } else if (materialName.contains("LOG") || materialName.contains("LEAVES") || materialName.contains("FLOWER") || materialName.contains("PLANT") || materialName.contains("CROP") || materialName.contains("ORE") || materialName.contains("DIRT") || materialName.contains("SAND") || materialName.contains("GRASS")) { return BLOCKS; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java index a43e56c38..53e84ec5d 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java @@ -128,18 +128,15 @@ public enum SubSkillType { * If our SubSkillType has more than 1 rank define it * @param numRanks The number of ranks our SubSkillType has */ - SubSkillType(int numRanks) - { + SubSkillType(int numRanks) { this.numRanks = numRanks; } - SubSkillType() - { + SubSkillType() { this.numRanks = 0; } - public int getNumRanks() - { + public int getNumRanks() { return numRanks; } @@ -170,8 +167,7 @@ public enum SubSkillType { * Get the string representation of the permission node for this subskill * @return the permission node for this subskill */ - public String getPermissionNodeAddress() - { + public String getPermissionNodeAddress() { //TODO: This could be optimized return "mcmmo.ability." + getParentSkill().toString().toLowerCase(Locale.ENGLISH) + "." + getConfigName(toString()).toLowerCase(Locale.ENGLISH); } @@ -201,12 +197,10 @@ public enum SubSkillType { * Split the string up so we can capitalize each part */ String subskillNameWithoutPrefix = subSkillName.substring(subStringIndex); - if (subskillNameWithoutPrefix.contains("_")) - { + if (subskillNameWithoutPrefix.contains("_")) { String[] splitStrings = subskillNameWithoutPrefix.split("_"); - for(String string : splitStrings) - { + for(String string : splitStrings) { endResult.append(StringUtils.getCapitalized(string)); } } else { @@ -228,8 +222,7 @@ public enum SubSkillType { * Returns the name of the parent skill from the Locale file * @return The parent skill as defined in the locale */ - public String getParentNiceNameLocale() - { + public String getParentNiceNameLocale() { return LocaleLoader.getString(StringUtils.getCapitalized(getParentSkill().toString())+".SkillName"); } @@ -238,8 +231,7 @@ public enum SubSkillType { * @param subSkillType target subskill * @return the "nice" name without spaces */ - public String getNiceNameNoSpaces(SubSkillType subSkillType) - { + public String getNiceNameNoSpaces(SubSkillType subSkillType) { return getConfigName(subSkillType.toString()); } @@ -263,18 +255,15 @@ public enum SubSkillType { return subStringIndex; } - public String getLocaleKeyRoot() - { + public String getLocaleKeyRoot() { return StringUtils.getCapitalized(getParentSkill().toString())+".SubSkill."+getConfigName(toString()); } - public String getLocaleName() - { + public String getLocaleName() { return getFromLocaleSubAddress(".Name"); } - public String getLocaleDescription() - { + public String getLocaleDescription() { return getFromLocaleSubAddress(".Description"); } @@ -284,13 +273,11 @@ public enum SubSkillType { public String getLocaleStatExtraDescription() { return getFromLocaleSubAddress(".Stat.Extra"); } public String getLocaleKeyStatExtraDescription() { return getLocaleKeyFromSubAddress(".Stat.Extra"); } - public String getLocaleStat(String... vars) - { + public String getLocaleStat(String... vars) { return LocaleLoader.getString("Ability.Generic.Template", (Object[]) vars); } - public String getCustomLocaleStat(String... vars) - { + public String getCustomLocaleStat(String... vars) { return LocaleLoader.getString("Ability.Generic.Template.Custom", (Object[]) vars); } @@ -298,8 +285,7 @@ public enum SubSkillType { return LocaleLoader.getString(getLocaleKeyRoot() + s); } - private String getLocaleKeyFromSubAddress(String s) - { + private String getLocaleKeyFromSubAddress(String s) { return getLocaleKeyRoot() + s; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java index a2d90aaa7..7a933f010 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java @@ -18,8 +18,7 @@ public abstract class AbstractSubSkill implements SubSkill, Interaction, Rank, S protected String configKeyPrimary; protected SubSkillType subSkillType; - public AbstractSubSkill(String configKeySubSkill, String configKeyPrimary, SubSkillType subSkillType) - { + public AbstractSubSkill(String configKeySubSkill, String configKeyPrimary, SubSkillType subSkillType) { this.configKeySubSkill = configKeySubSkill; this.configKeyPrimary = configKeyPrimary; this.subSkillType = subSkillType; diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java index 6b91d31b3..3c2bc1d66 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java @@ -156,8 +156,7 @@ public class Roll extends AcrobaticsSubSkill { //Advanced //Lucky Notice - if (isLucky) - { + if (isLucky) { componentBuilder.append(Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Header"))); componentBuilder.append(Component.newline()); componentBuilder.append(Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Lucky", "33"))); @@ -219,8 +218,7 @@ public class Roll extends AcrobaticsSubSkill { addFallLocation(mmoPlayer); return modifiedDamage; - } - else if (!isFatal(mmoPlayer, damage)) { + } else if (!isFatal(mmoPlayer, damage)) { //if (!SkillUtils.cooldownExpired((long) mmoPlayer.getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, false), XPGainReason.PVE); @@ -248,8 +246,7 @@ public class Roll extends AcrobaticsSubSkill { if (!isFatal(mmoPlayer, modifiedDamage) //TODO: Graceful isn't sending out an event - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.ACROBATICS, mmoPlayer, gracefulProbability)) - { + && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.ACROBATICS, mmoPlayer, gracefulProbability)) { NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Ability.Proc"); SoundManager.sendCategorizedSound(mmoPlayer.getPlayer(), mmoPlayer.getPlayer().getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS,0.5F); if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) @@ -257,8 +254,7 @@ public class Roll extends AcrobaticsSubSkill { addFallLocation(mmoPlayer); return modifiedDamage; - } - else if (!isFatal(mmoPlayer, damage)) { + } else if (!isFatal(mmoPlayer, damage)) { if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, false), XPGainReason.PVE); @@ -292,8 +288,7 @@ public class Roll extends AcrobaticsSubSkill { return true; } - if (mmoPlayer.getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(mmoPlayer))) - { + if (mmoPlayer.getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(mmoPlayer))) { if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Fallen in location before"); } @@ -369,8 +364,7 @@ public class Roll extends AcrobaticsSubSkill { * @return stat array for target player for this skill */ @Override - public Double[] getStats(McMMOPlayer mmoPlayer) - { + public Double[] getStats(McMMOPlayer mmoPlayer) { double playerChanceRoll = ProbabilityUtil.getSubSkillProbability(subSkillType, mmoPlayer).getValue(); double playerChanceGrace = playerChanceRoll * 2; diff --git a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java index e03a8a4f7..a3f31598b 100644 --- a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java +++ b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java @@ -18,8 +18,7 @@ abstract public class McMMOScoreboardEvent extends Event { private final ScoreboardEventReason scoreboardEventReason; - public McMMOScoreboardEvent(Scoreboard targetBoard, Scoreboard currentBoard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) - { + public McMMOScoreboardEvent(Scoreboard targetBoard, Scoreboard currentBoard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { this.scoreboardEventReason = scoreboardEventReason; this.targetBoard = targetBoard; this.currentBoard = currentBoard; diff --git a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java index 40e419e0c..1c648b767 100644 --- a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java @@ -47,8 +47,7 @@ public class BlockListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) - public void onBlockDropItemEvent(BlockDropItemEvent event) - { + public void onBlockDropItemEvent(BlockDropItemEvent event) { //Make sure we clean up metadata on these blocks if (event.isCancelled()) { if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) @@ -84,8 +83,7 @@ public class BlockListener implements Listener { //If there are more than one block in the item list we can't really trust it and will back out of rewarding bonus drops if (blockCount <= 1) { - for(Item item : event.getItems()) - { + for(Item item : event.getItems()) { ItemStack is = new ItemStack(item.getItemStack()); if (is.getAmount() <= 0) @@ -186,8 +184,7 @@ public class BlockListener implements Listener { * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityBlockFormEvent(EntityBlockFormEvent event) - { + public void onEntityBlockFormEvent(EntityBlockFormEvent event) { /* WORLD BLACKLIST CHECK */ if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; @@ -207,8 +204,7 @@ public class BlockListener implements Listener { * Does not monitor stuff like a falling block replacing a liquid */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockFormEvent(BlockFormEvent event) - { + public void onBlockFormEvent(BlockFormEvent event) { World world = event.getBlock().getWorld(); /* WORLD BLACKLIST CHECK */ @@ -266,8 +262,7 @@ public class BlockListener implements Listener { if (blockState.getType() == Repair.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR)) { mcMMOPlayer.getRepairManager().placedAnvilCheck(); - } - else if (blockState.getType() == Salvage.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE)) { + } else if (blockState.getType() == Salvage.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE)) { mcMMOPlayer.getSalvageManager().placedAnvilCheck(); } } @@ -334,8 +329,7 @@ public class BlockListener implements Listener { } /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { BlockUtils.cleanupBlockMetadata(block); return; @@ -411,8 +405,7 @@ public class BlockListener implements Listener { WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager(); if (woodcuttingManager.canUseTreeFeller(heldItem)) { woodcuttingManager.processTreeFeller(blockState); - } - else { + } else { //Check for XP woodcuttingManager.processWoodcuttingBlockXP(blockState); @@ -422,7 +415,10 @@ public class BlockListener implements Listener { } /* EXCAVATION */ - else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { + else if (BlockUtils.affectedByGigaDrillBreaker(blockState) + && ItemUtils.isShovel(heldItem) + && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) + && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { ExcavationManager excavationManager = mcMMOPlayer.getExcavationManager(); excavationManager.excavationBlockCheck(blockState); @@ -450,8 +446,7 @@ public class BlockListener implements Listener { return; /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -463,8 +458,7 @@ public class BlockListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -478,8 +472,7 @@ public class BlockListener implements Listener { if (herbalismManager.processHylianLuck(blockState)) { blockState.update(true); event.setCancelled(true); - } - else if (blockState.getType() == Material.FLOWER_POT) { + } else if (blockState.getType() == Material.FLOWER_POT) { blockState.setType(Material.AIR); blockState.update(true); event.setCancelled(true); @@ -513,8 +506,7 @@ public class BlockListener implements Listener { return; /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -529,8 +521,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if (mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { return; } @@ -544,17 +535,13 @@ public class BlockListener implements Listener { if (mcMMOPlayer.getToolPreparationMode(ToolType.HOE) && ItemUtils.isHoe(heldItem) && (BlockUtils.affectedByGreenTerra(blockState) || BlockUtils.canMakeMossy(blockState)) && Permissions.greenTerra(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.HERBALISM); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) && BlockUtils.hasWoodcuttingXP(blockState) && Permissions.treeFeller(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) && BlockUtils.hasWoodcuttingXP(blockState) && Permissions.treeFeller(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.WOODCUTTING); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe(heldItem) && BlockUtils.affectedBySuperBreaker(blockState) && Permissions.superBreaker(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe(heldItem) && BlockUtils.affectedBySuperBreaker(blockState) && Permissions.superBreaker(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.MINING); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel(heldItem) && BlockUtils.affectedByGigaDrillBreaker(blockState) && Permissions.gigaDrillBreaker(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel(heldItem) && BlockUtils.affectedByGigaDrillBreaker(blockState) && Permissions.gigaDrillBreaker(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.EXCAVATION); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.FISTS) && heldItem.getType() == Material.AIR && (BlockUtils.affectedByGigaDrillBreaker(blockState) + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.FISTS) && heldItem.getType() == Material.AIR && (BlockUtils.affectedByGigaDrillBreaker(blockState) || mcMMO.getMaterialMapStore().isGlass(blockState.getType()) || blockState.getType() == Material.SNOW || BlockUtils.affectedByBlockCracker(blockState) && Permissions.berserk(player))) { @@ -596,8 +583,7 @@ public class BlockListener implements Listener { return; /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -615,8 +601,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -633,14 +618,12 @@ public class BlockListener implements Listener { if (mcMMOPlayer.getHerbalismManager().processGreenTerraBlockConversion(blockState)) { blockState.update(true); } - } - else if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK) && (heldItem.getType() == Material.AIR || mcMMO.p.getGeneralConfig().getUnarmedItemsAsUnarmed())) { + } else if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK) && (heldItem.getType() == Material.AIR || mcMMO.p.getGeneralConfig().getUnarmedItemsAsUnarmed())) { if (mcMMOPlayer.getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(blockState)) { if (EventUtils.simulateBlockBreak(block, player) && mcMMOPlayer.getUnarmedManager().blockCrackerCheck(blockState)) { blockState.update(); } - } - else if (!event.getInstaBreak() && SuperAbilityType.BERSERK.blockCheck(blockState) && EventUtils.simulateBlockBreak(block, player)) { + } else if (!event.getInstaBreak() && SuperAbilityType.BERSERK.blockCheck(blockState) && EventUtils.simulateBlockBreak(block, player)) { event.setInstaBreak(true); if (blockState.getType().getKey().getKey().contains("glass")) { @@ -649,8 +632,7 @@ public class BlockListener implements Listener { SoundManager.sendSound(player, block.getLocation(), SoundType.POP); } } - } - else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isNonWoodPartOfTree(blockState) && EventUtils.simulateBlockBreak(block, player)) { + } else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isNonWoodPartOfTree(blockState) && EventUtils.simulateBlockBreak(block, player)) { event.setInstaBreak(true); SoundManager.sendSound(player, block.getLocation(), SoundType.POP); } @@ -662,8 +644,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -680,23 +661,19 @@ public class BlockListener implements Listener { //TODO: Convert into locale strings private void debugStickDump(Player player, BlockState blockState) { //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } - if (UserManager.getPlayer(player).isDebugMode()) - { + if (UserManager.getPlayer(player).isDebugMode()) { if (mcMMO.getUserBlockTracker().isIneligible(blockState)) player.sendMessage("[mcMMO DEBUG] This block is not natural and does not reward treasures/XP"); - else - { + else { player.sendMessage("[mcMMO DEBUG] This block is considered natural by mcMMO"); UserManager.getPlayer(player).getExcavationManager().printExcavationDebug(player, blockState); } - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (WorldGuardManager.getInstance().hasMainFlag(player)) player.sendMessage("[mcMMO DEBUG] World Guard main flag is permitted for this player in this region"); else diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index b3eec6fb0..8c3e746ac 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -81,14 +81,12 @@ public class EntityListener implements Listener { return; //It's rare but targets can be null sometimes - if (event.getTarget() == null) - { + if (event.getTarget() == null) { return; } //Prevent entities from giving XP if they target endermite - if (event.getTarget() instanceof Endermite) - { + if (event.getTarget() instanceof Endermite) { if (event.getEntity() instanceof Enderman enderman) { if (!hasMobFlag(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman)) { @@ -104,8 +102,7 @@ public class EntityListener implements Listener { if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if (event.getEntity() instanceof Player player) - { + if (event.getEntity() instanceof Player player) { Entity projectile = event.getProjectile(); //Should be noted that there are API changes regarding Arrow from 1.13.2 to current versions of the game @@ -137,8 +134,7 @@ public class EntityListener implements Listener { if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if (event.getEntity().getShooter() instanceof Player player) - { + if (event.getEntity().getShooter() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ if (WorldGuardUtils.isWorldGuardLoaded()) { @@ -212,15 +208,13 @@ public class EntityListener implements Listener { entity.setMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, MetadataConstants.MCMMO_METADATA_VALUE); TravelingBlockMetaCleanup metaCleanupTask = new TravelingBlockMetaCleanup(entity, pluginRef); mcMMO.p.getFoliaLib().getImpl().runAtEntityTimer(entity, metaCleanupTask, 20, 20*60); //6000 ticks is 5 minutes - } - else if (isTracked) { + } else if (isTracked) { BlockUtils.setUnnaturalBlock(block); entity.removeMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, pluginRef); } } else if ((block.getType() == Material.REDSTONE_ORE || block.getType().getKey().getKey().equalsIgnoreCase("deepslate_redstone_ore"))) { //Redstone ore fire this event and should be ignored - } - else { + } else { if (mcMMO.getUserBlockTracker().isIneligible(block)) { mcMMO.getUserBlockTracker().setEligible(block); } @@ -265,8 +259,7 @@ public class EntityListener implements Listener { Entity defender = event.getEntity(); Entity attacker = event.getDamager(); - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (attacker instanceof Player) { if (!WorldGuardManager.getInstance().hasMainFlag((Player) attacker)) { @@ -324,8 +317,7 @@ public class EntityListener implements Listener { if (animalTamer != null && ((OfflinePlayer) animalTamer).isOnline()) { attacker = (Entity) animalTamer; } - } - else if (attacker instanceof TNTPrimed && defender instanceof Player) { + } else if (attacker instanceof TNTPrimed && defender instanceof Player) { if (BlastMining.processBlastMiningExplosion(event, (TNTPrimed) attacker, (Player) defender)) { return; } @@ -496,11 +488,9 @@ public class EntityListener implements Listener { event.getEntity().removeMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE, mcMMO.p); } - if (event.getEntity() instanceof Player player) - { + if (event.getEntity() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -576,11 +566,9 @@ public class EntityListener implements Listener { else if (livingEntity instanceof Tameable pet) { AnimalTamer owner = pet.getOwner(); - if (owner instanceof Player player) - { + if (owner instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -591,8 +579,7 @@ public class EntityListener implements Listener { Wolf wolf = (Wolf) pet; //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -784,14 +771,12 @@ public class EntityListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -830,15 +815,13 @@ public class EntityListener implements Listener { } /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -869,14 +852,12 @@ public class EntityListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -993,8 +974,7 @@ public class EntityListener implements Listener { Player player = (Player) event.getOwner(); /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -1011,8 +991,7 @@ public class EntityListener implements Listener { flagMetadata(MobMetaFlagType.PLAYER_TAMED_MOB, livingEntity); //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -1039,8 +1018,7 @@ public class EntityListener implements Listener { } /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } diff --git a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java index 6bc7cca44..0422d1064 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java +++ b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java @@ -33,8 +33,7 @@ public class InteractionManager { * Registers subskills with the Interaction registration * @param abstractSubSkill the target subskill to register */ - public static void registerSubSkill(AbstractSubSkill abstractSubSkill) - { + public static void registerSubSkill(AbstractSubSkill abstractSubSkill) { //Store a unique copy of each subskill if (!subSkillList.contains(abstractSubSkill)) subSkillList.add(abstractSubSkill); @@ -62,8 +61,7 @@ public class InteractionManager { * @param name name of subskill, not case sensitive * @return null if the subskill is not registered */ - public static AbstractSubSkill getAbstractByName(String name) - { + public static AbstractSubSkill getAbstractByName(String name) { return subSkillNameMap.get(name.toLowerCase(Locale.ENGLISH)); } @@ -73,13 +71,11 @@ public class InteractionManager { * @param plugin instance of mcMMO plugin * @param curInteractType the associated interaction type */ - public static void processEvent(Event event, mcMMO plugin, InteractType curInteractType) - { + public static void processEvent(Event event, mcMMO plugin, InteractType curInteractType) { if (interactRegister.get(curInteractType) == null) return; - for(Interaction interaction : interactRegister.get(curInteractType)) - { + for(Interaction interaction : interactRegister.get(curInteractType)) { interaction.doInteraction(event, plugin); } } @@ -89,18 +85,15 @@ public class InteractionManager { * Interactions are extensions of abstract classes that represent modifying behaviours in Minecraft through events * @return the unique collection of all registered Interaction classes */ - public static ArrayList getSubSkillList() - { + public static ArrayList getSubSkillList() { return subSkillList; } - public static boolean hasSubSkill(String name) - { + public static boolean hasSubSkill(String name) { return getAbstractByName(name) != null; } - public static boolean hasSubSkill(SubSkillType subSkillType) - { + public static boolean hasSubSkill(SubSkillType subSkillType) { return hasSubSkill(subSkillType.getNiceNameNoSpaces(subSkillType)); } diff --git a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java index 9da7a0605..116e41f0c 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java @@ -131,8 +131,7 @@ public class InventoryListener implements Listener { if (furnaceBlock instanceof Furnace) { /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -142,8 +141,7 @@ public class InventoryListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -196,8 +194,7 @@ public class InventoryListener implements Listener { // TODO: Investigate why this WG check is all the way down here? /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -239,8 +236,7 @@ public class InventoryListener implements Listener { return; default: } - } - else if (slot == InventoryType.SlotType.FUEL) { + } else if (slot == InventoryType.SlotType.FUEL) { boolean emptyClicked = AlchemyPotionBrewer.isEmpty(clicked); if (AlchemyPotionBrewer.isEmpty(cursor)) { @@ -250,8 +246,7 @@ public class InventoryListener implements Listener { } AlchemyPotionBrewer.scheduleCheck(stand); - } - else if (emptyClicked) { + } else if (emptyClicked) { if (AlchemyPotionBrewer.isValidIngredientByPlayer(player, cursor)) { int amount = cursor.getAmount(); @@ -262,8 +257,7 @@ public class InventoryListener implements Listener { AlchemyPotionBrewer.scheduleUpdate(inventory); AlchemyPotionBrewer.scheduleCheck(stand); - } - else if (click == ClickType.RIGHT) { + } else if (click == ClickType.RIGHT) { event.setCancelled(true); ItemStack one = cursor.clone(); @@ -323,8 +317,7 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -342,8 +335,7 @@ public class InventoryListener implements Listener { // Apparently sometimes vanilla brewing beats our task listener to the actual brew. We handle this by cancelling the vanilla event and finishing our brew ourselves. @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onBrew(BrewEvent event) - { + public void onBrew(BrewEvent event) { /* WORLD BLACKLIST CHECK */ if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; @@ -460,8 +452,7 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } diff --git a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java index 5a7c9a695..74f262289 100644 --- a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java @@ -87,8 +87,7 @@ public class PlayerListener implements Listener { Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -98,8 +97,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -183,8 +181,7 @@ public class PlayerListener implements Listener { Player killer = killedPlayer.getKiller(); /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) return; } @@ -227,8 +224,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -254,8 +250,7 @@ public class PlayerListener implements Listener { return; /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -287,8 +282,7 @@ public class PlayerListener implements Listener { Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -298,8 +292,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -373,8 +366,7 @@ public class PlayerListener implements Listener { Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -384,8 +376,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -393,20 +384,16 @@ public class PlayerListener implements Listener { FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager(); //Track the hook - if (ExperienceConfig.getInstance().isFishingExploitingPrevented()) - { - if (event.getHook().getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() == 0) - { + if (ExperienceConfig.getInstance().isFishingExploitingPrevented()) { + if (event.getHook().getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() == 0) { fishingManager.setFishHookReference(event.getHook()); } //Spam Fishing - if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) - { + if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) { event.setExpToDrop(0); - if (caught instanceof Item caughtItem) - { + if (caught instanceof Item caughtItem) { caughtItem.remove(); } @@ -489,12 +476,10 @@ public class PlayerListener implements Listener { return; } - if (event.getEntity() instanceof Player player) - { + if (event.getEntity() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -618,8 +603,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -640,8 +624,7 @@ public class PlayerListener implements Listener { Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -665,8 +648,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -715,8 +697,7 @@ public class PlayerListener implements Listener { else if (miningManager.canDetonate()) { if (type == Material.TNT) { event.setCancelled(true); // Don't detonate the TNT if they're too close - } - else { + } else { miningManager.remoteDetonation(); } } @@ -770,19 +751,19 @@ public class PlayerListener implements Listener { Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if (WorldGuardUtils.isWorldGuardLoaded()) - { + if (WorldGuardUtils.isWorldGuardLoaded()) { if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } - if (event.getHand() != EquipmentSlot.HAND || !UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) { + if (event.getHand() != EquipmentSlot.HAND + || !UserManager.hasPlayerDataKey(player) + || player.getGameMode() == GameMode.CREATIVE) { return; } //Profile not loaded - if (UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -793,13 +774,10 @@ public class PlayerListener implements Listener { ItemStack heldItem = player.getInventory().getItemInMainHand(); //Spam Fishing Detection - if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) - { + if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { if (ExperienceConfig.getInstance().isFishingExploitingPrevented() - && (heldItem.getType() == Material.FISHING_ROD || player.getInventory().getItemInOffHand().getType() == Material.FISHING_ROD)) - { - if (player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) - { + && (heldItem.getType() == Material.FISHING_ROD || player.getInventory().getItemInOffHand().getType() == Material.FISHING_ROD)) { + if (player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) { player.getVehicle().eject(); } @@ -924,11 +902,9 @@ public class PlayerListener implements Listener { if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.WOLF.getConfigEntityTypeEntry())) { tamingManager.summonWolf(); - } - else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry())) { + } else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry())) { tamingManager.summonOcelot(); - } - else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry())) { + } else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry())) { tamingManager.summonHorse(); } @@ -1028,8 +1004,7 @@ public class PlayerListener implements Listener { if (event.getHand() == EquipmentSlot.OFF_HAND) { itemInHand = event.getPlayer().getInventory().getItemInOffHand(); - } - else { + } else { itemInHand = event.getPlayer().getInventory().getItemInMainHand(); } diff --git a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java index 42303ef90..3d5bb1e0e 100644 --- a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java @@ -24,8 +24,7 @@ public class SelfListener implements Listener { //Used in task scheduling and other things private final mcMMO plugin; - public SelfListener(mcMMO plugin) - { + public SelfListener(mcMMO plugin) { this.plugin = plugin; } @@ -42,8 +41,7 @@ public class SelfListener implements Listener { if (player.isOnline()) { //Players can gain multiple levels especially during xprate events - for(int i = 0; i < event.getLevelsGained(); i++) - { + for(int i = 0; i < event.getLevelsGained(); i++) { int previousLevelGained = event.getSkillLevel() - i; //Send player skill unlock notifications UserManager.getPlayer(player).processUnlockNotifications(plugin, event.getSkill(), previousLevelGained); @@ -96,12 +94,9 @@ public class SelfListener implements Listener { if (event.getXpGainReason() == XPGainReason.PVE || event.getXpGainReason() == XPGainReason.PVP || event.getXpGainReason() == XPGainReason.SHARED_PVE || - event.getXpGainReason() == XPGainReason.SHARED_PVP) - { - if (WorldGuardUtils.isWorldGuardLoaded()) - { - if (!WorldGuardManager.getInstance().hasXPFlag(player)) - { + event.getXpGainReason() == XPGainReason.SHARED_PVP) { + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasXPFlag(player)) { event.setRawXpGained(0); event.setCancelled(true); @@ -112,19 +107,16 @@ public class SelfListener implements Listener { } } - if (event.getXpGainReason() == XPGainReason.COMMAND) - { + if (event.getXpGainReason() == XPGainReason.COMMAND) { return; } - if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled()) - { + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled()) { int earlyGameBonusXP = 0; //Give some bonus XP for low levels - if (PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) - { + if (PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { earlyGameBonusXP += (mcMMOPlayer.getXpToLevel(primarySkillType) * 0.05); event.setRawXpGained(event.getRawXpGained() + earlyGameBonusXP); } @@ -167,12 +159,10 @@ public class SelfListener implements Listener { * Make sure players get a guaranteed minimum of XP */ //If there is no guaranteed minimum proceed, otherwise only proceed if newValue would be higher than our guaranteed minimum - if (guaranteedMinimum <= 0 || newValue > guaranteedMinimum) - { + if (guaranteedMinimum <= 0 || newValue > guaranteedMinimum) { if (newValue > 0) { event.setRawXpGained(newValue); - } - else { + } else { event.setCancelled(true); } } else { diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index 81ad266ca..3f23597ba 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -148,8 +148,7 @@ public class mcMMO extends JavaPlugin { } - protected mcMMO(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) - { + protected mcMMO(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { super(loader, description, dataFolder, file); } @@ -229,8 +228,7 @@ public class mcMMO extends JavaPlugin { //Check for the newer API and tell them what to do if its missing checkForOutdatedAPI(); - if (serverAPIOutdated) - { + if (serverAPIOutdated) { foliaLib .getImpl() .runTimer( @@ -238,8 +236,7 @@ public class mcMMO extends JavaPlugin { 20, 20*60*30 ); - if (platformManager.getServerSoftware() == ServerSoftwareType.CRAFT_BUKKIT) - { + if (platformManager.getServerSoftware() == ServerSoftwareType.CRAFT_BUKKIT) { foliaLib .getImpl() .runTimer( @@ -295,8 +292,7 @@ public class mcMMO extends JavaPlugin { if (!(t instanceof ExceptionInInitializerError)) { t.printStackTrace(); - } - else { + } else { getLogger().info("Please do not replace the mcMMO jar while the server is running."); } @@ -350,8 +346,7 @@ public class mcMMO extends JavaPlugin { } @Override - public void onLoad() - { + public void onLoad() { if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { WorldGuardManager.getInstance().registerFlags(); } @@ -638,8 +633,7 @@ public class mcMMO extends JavaPlugin { InteractionManager.initMaps(); //Init maps - if (CoreSkillsConfig.getInstance().isPrimarySkillEnabled(PrimarySkillType.ACROBATICS)) - { + if (CoreSkillsConfig.getInstance().isPrimarySkillEnabled(PrimarySkillType.ACROBATICS)) { LogUtils.debug(mcMMO.p.getLogger(), "Enabling Acrobatics Skills"); //TODO: Should do this differently @@ -674,8 +668,7 @@ public class mcMMO extends JavaPlugin { if (purgeIntervalTicks == 0) { getFoliaLib().getImpl().runLaterAsync(new UserPurgeTask(), 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. - } - else if (purgeIntervalTicks > 0) { + } else if (purgeIntervalTicks > 0) { getFoliaLib().getImpl().runTimerAsync(new UserPurgeTask(), purgeIntervalTicks, purgeIntervalTicks); } @@ -698,8 +691,7 @@ public class mcMMO extends JavaPlugin { getFoliaLib().getImpl().runTimer(new ClearRegisteredXPGainTask(), 60, 60); } - if (mcMMO.p.getAdvancedConfig().allowPlayerTips()) - { + if (mcMMO.p.getAdvancedConfig().allowPlayerTips()) { getFoliaLib().getImpl().runTimer(new NotifySquelchReminderTask(), 60, ((20 * 60) * 60)); } } diff --git a/src/main/java/com/gmail/nossr50/party/ShareHandler.java b/src/main/java/com/gmail/nossr50/party/ShareHandler.java index 77e905002..4719ebc36 100644 --- a/src/main/java/com/gmail/nossr50/party/ShareHandler.java +++ b/src/main/java/com/gmail/nossr50/party/ShareHandler.java @@ -51,8 +51,7 @@ public final class ShareHandler { for (Player member : nearMembers) { //Profile not loaded - if (UserManager.getPlayer(member) == null) - { + if (UserManager.getPlayer(member) == null) { continue; } @@ -115,8 +114,7 @@ public final class ShareHandler { McMMOPlayer mcMMOMember = UserManager.getPlayer(member); //Profile not loaded - if (UserManager.getPlayer(member) == null) - { + if (UserManager.getPlayer(member) == null) { continue; } @@ -161,11 +159,9 @@ public final class ShareHandler { public static XPGainReason getSharedXpGainReason(XPGainReason xpGainReason) { if (xpGainReason == XPGainReason.PVE) { return XPGainReason.SHARED_PVE; - } - else if (xpGainReason == XPGainReason.PVP) { + } else if (xpGainReason == XPGainReason.PVP) { return XPGainReason.SHARED_PVP; - } - else { + } else { return xpGainReason; } } diff --git a/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java b/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java index c4de1183d..f94295580 100644 --- a/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java @@ -51,13 +51,11 @@ public class CleanBackupsTask extends CancellableRunnable { if (isPast24Hours(date) && mcMMO.p.getGeneralConfig().getKeepLast24Hours()) { // Keep all files from the last 24 hours continue; - } - else if (isLastWeek(date) && !savedDays.contains(dayOfWeek) && mcMMO.p.getGeneralConfig().getKeepDailyLastWeek()) { + } else if (isLastWeek(date) && !savedDays.contains(dayOfWeek) && mcMMO.p.getGeneralConfig().getKeepDailyLastWeek()) { // Keep daily backups of the past week savedDays.add(dayOfWeek); continue; - } - else { + } else { List savedWeeks = savedYearsWeeks.computeIfAbsent(year, k -> new ArrayList<>()); if (!savedWeeks.contains(weekOfYear) && mcMMO.p.getGeneralConfig().getKeepWeeklyPastMonth()) { diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java index c1067ecf1..18fbb8854 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java @@ -64,8 +64,7 @@ public class McrankCommandDisplayTask extends CancellableRunnable { public void displayBoard() { if (sender.getName().equalsIgnoreCase(playerName)) { ScoreboardManager.showPlayerRankScoreboard((Player) sender, skills); - } - else { + } else { ScoreboardManager.showPlayerRankScoreboardOthers((Player) sender, playerName, skills); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java index 3cb06bff0..e2e491611 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java @@ -54,16 +54,13 @@ public class MctopCommandDisplayTask extends CancellableRunnable { if (skill == null) { if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); - } - else { + } else { sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"))); } - } - else { + } else { if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); - } - else { + } else { sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill)))); } } @@ -76,8 +73,7 @@ public class MctopCommandDisplayTask extends CancellableRunnable { // 12. Playername - skill value if (sender instanceof Player) { sender.sendMessage(String.format("%2d. %s%s - %s%s", place, ChatColor.GREEN, stat.name, ChatColor.WHITE, stat.statVal)); - } - else { + } else { sender.sendMessage(String.format("%2d. %s - %s", place, stat.name, stat.statVal)); } @@ -88,8 +84,7 @@ public class MctopCommandDisplayTask extends CancellableRunnable { private void displayBoard() { if (skill == null) { ScoreboardManager.showTopPowerScoreboard((Player) sender, page, userStats); - } - else { + } else { ScoreboardManager.showTopScoreboard((Player) sender, skill, page, userStats); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java index b9931d44e..83faca3dd 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java @@ -11,10 +11,8 @@ public class NotifySquelchReminderTask extends CancellableRunnable { @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { - if (UserManager.getPlayer(player) != null) - { - if (!UserManager.getPlayer(player).useChatNotifications()) - { + if (UserManager.getPlayer(player) != null) { + if (!UserManager.getPlayer(player).useChatNotifications()) { player.sendMessage(LocaleLoader.getString("Reminder.Squelched")); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java b/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java index 214d4e58b..71ea24ea1 100644 --- a/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java @@ -44,8 +44,7 @@ public class FormulaConversionTask extends CancellableRunnable { editValues(profile); // Since this is a temporary profile, we save it here. profile.scheduleAsyncSave(); - } - else { + } else { profile = mcMMOPlayer.getProfile(); editValues(profile); } diff --git a/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java b/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java index 25d809f59..362731101 100644 --- a/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java +++ b/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java @@ -60,8 +60,7 @@ public class TeleportationWarmup extends CancellableRunnable { if (!Permissions.partyTeleportWorld(targetPlayer, targetWorld)) { teleportingPlayer.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return; - } - else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(teleportingPlayer, targetWorld)) { + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(teleportingPlayer, targetWorld)) { teleportingPlayer.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return; } diff --git a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java index e62df151f..42bcad967 100644 --- a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java @@ -58,8 +58,7 @@ public class PlayerProfileLoadingTask extends CancellableRunnable { } // Print errors to console/logs if we're failing at least 2 times in a row to load the profile - if (attempt >= 3) - { + if (attempt >= 3) { //Log the error mcMMO.p.getLogger().severe(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName(), String.valueOf(attempt))); diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java b/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java index 32b4b9eca..3dd31ad93 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java @@ -9,8 +9,7 @@ public class BleedContainer { public LivingEntity target; public LivingEntity damageSource; - public BleedContainer(LivingEntity target, int bleedTicks, int bleedRank, int toolTier, LivingEntity damageSource) - { + public BleedContainer(LivingEntity target, int bleedTicks, int bleedRank, int toolTier, LivingEntity damageSource) { this.target = target; this.bleedTicks = bleedTicks; this.bleedRank = bleedRank; diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java index 816257f96..e5da7e81b 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java @@ -10,8 +10,7 @@ public class ExperienceBarHideTask extends CancellableRunnable { public final PrimarySkillType primarySkillType; public final ExperienceBarManager experienceBarManagerRef; - public ExperienceBarHideTask(ExperienceBarManager experienceBarManagerRef, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType) - { + public ExperienceBarHideTask(ExperienceBarManager experienceBarManagerRef, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType) { this.experienceBarManagerRef = experienceBarManagerRef; this.mcMMOPlayer = mcMMOPlayer; this.primarySkillType = primarySkillType; diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java index c9b6d87a5..eea79ed31 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java @@ -16,8 +16,7 @@ public class SkillUnlockNotificationTask extends CancellableRunnable { * @param subSkillType the subskill that they just unlocked * @param rank the rank of the subskill */ - public SkillUnlockNotificationTask(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType, int rank) - { + public SkillUnlockNotificationTask(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType, int rank) { this.mcMMOPlayer = mcMMOPlayer; this.subSkillType = subSkillType; this.rank = rank; diff --git a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java index a7d646df6..e9529751f 100644 --- a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java @@ -39,23 +39,19 @@ public class AcrobaticsManager extends SkillManager { private long rollXPIntervalLengthen = (1000 * 10); //10 Seconds private final BlockLocationHistory fallLocationMap; - public boolean hasFallenInLocationBefore(Location location) - { + public boolean hasFallenInLocationBefore(Location location) { return fallLocationMap.contains(location); } - public void addLocationToFallMap(Location location) - { + public void addLocationToFallMap(Location location) { fallLocationMap.add(location); } - public boolean canGainRollXP() - { + public boolean canGainRollXP() { if (!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) return true; - if (System.currentTimeMillis() >= rollXPCooldown) - { + if (System.currentTimeMillis() >= rollXPCooldown) { rollXPCooldown = System.currentTimeMillis() + rollXPInterval; rollXPIntervalLengthen = (1000 * 10); //5 Seconds return true; diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index 223a1dd5b..573dbd4c6 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -93,8 +93,7 @@ public final class AlchemyPotionBrewer { if (!isEmpty(ingredient) && isValidIngredientByPlayer(player, ingredient)) { if (ingredient.getAmount() <= 1) { inventory.setIngredient(null); - } - else { + } else { ingredient.setAmount(ingredient.getAmount() - 1); inventory.setIngredient(ingredient); } @@ -237,8 +236,7 @@ public final class AlchemyPotionBrewer { if (click.isLeftClick()) { success = transferItems(view, fromSlot); - } - else if (click.isRightClick()) { + } else if (click.isRightClick()) { success = transferOneItem(view, fromSlot); } @@ -258,13 +256,11 @@ public final class AlchemyPotionBrewer { if (!emptyTo && fromAmount >= from.getType().getMaxStackSize()) { return false; - } - else if (emptyTo || from.isSimilar(to)) { + } else if (emptyTo || from.isSimilar(to)) { if (emptyTo) { to = from.clone(); to.setAmount(1); - } - else { + } else { to.setAmount(to.getAmount() + 1); } @@ -287,14 +283,12 @@ public final class AlchemyPotionBrewer { if (isEmpty(from)) { return false; - } - else if (isEmpty(to)) { + } else if (isEmpty(to)) { view.setItem(Alchemy.INGREDIENT_SLOT, from); view.setItem(fromSlot, null); return true; - } - else if (from.isSimilar(to)) { + } else if (from.isSimilar(to)) { int fromAmount = from.getAmount(); int toAmount = to.getAmount(); int maxSize = to.getType().getMaxStackSize(); diff --git a/src/main/java/com/gmail/nossr50/skills/archery/Archery.java b/src/main/java/com/gmail/nossr50/skills/archery/Archery.java index 3ad317287..d5cf998e8 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/Archery.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/Archery.java @@ -64,8 +64,7 @@ public class Archery { } } - public static double getSkillShotBonusDamage(Player player, double oldDamage) - { + public static double getSkillShotBonusDamage(Player player, double oldDamage) { double damageBonusPercent = getDamageBonusPercent(player); double newDamage = oldDamage + (oldDamage * damageBonusPercent); return Math.min(newDamage, (oldDamage + Archery.skillShotMaxBonusDamage)); diff --git a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java index b3eb84473..0ea49854c 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java @@ -43,8 +43,7 @@ public class Axes { * @param player The target player * @return The axe mastery bonus damage which will be added to their attack */ - public static double getAxeMasteryBonusDamage(Player player) - { + public static double getAxeMasteryBonusDamage(Player player) { return RankUtils.getRank(player, SubSkillType.AXES_AXE_MASTERY) * Axes.axeMasteryRankDamageMultiplier; } } diff --git a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java index 36abb05ff..9fc75038a 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java @@ -101,8 +101,7 @@ public class AxesManager extends SkillManager { } damage = (damage * Axes.criticalHitPVPModifier) - damage; - } - else { + } else { damage = (damage * Axes.criticalHitPVEModifier) - damage; } diff --git a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java index cde03fb72..1858f6368 100644 --- a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java @@ -88,8 +88,7 @@ public class CrossbowsManager extends SkillManager { return RankUtils.getRank(mmoPlayer, SubSkillType.CROSSBOWS_TRICK_SHOT); } - public double getPoweredShotBonusDamage(Player player, double oldDamage) - { + public double getPoweredShotBonusDamage(Player player, double oldDamage) { double damageBonusPercent = getDamageBonusPercent(player); double newDamage = oldDamage + (oldDamage * damageBonusPercent); return Math.min(newDamage, (oldDamage + mcMMO.p.getAdvancedConfig().getPoweredShotDamageMax())); diff --git a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java index eadd72fea..434b675b1 100644 --- a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java +++ b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java @@ -91,8 +91,7 @@ public class ExcavationManager extends SkillManager { return RankUtils.getRank(getPlayer(), SubSkillType.EXCAVATION_ARCHAEOLOGY); } - public void printExcavationDebug(Player player, BlockState blockState) - { + public void printExcavationDebug(Player player, BlockState blockState) { if (Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.EXCAVATION_ARCHAEOLOGY)) { List treasures = Excavation.getTreasures(blockState); diff --git a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java index 9037ca280..7dbf66221 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java @@ -101,8 +101,7 @@ public class FishingManager extends SkillManager { // fishingRodCastTimestamp = System.currentTimeMillis(); // } - public void setFishHookReference(FishHook fishHook) - { + public void setFishHookReference(FishHook fishHook) { if (fishHook.getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() > 0) return; @@ -113,14 +112,12 @@ public class FishingManager extends SkillManager { } - public boolean isFishingTooOften() - { + public boolean isFishingTooOften() { long currentTime = System.currentTimeMillis(); long fishHookSpawnCD = fishHookSpawnTimestamp + 1000; boolean hasFished = (currentTime < fishHookSpawnCD); - if (hasFished && (lastWarned + (1000) < currentTime)) - { + if (hasFished && (lastWarned + (1000) < currentTime)) { getPlayer().sendMessage(LocaleLoader.getString("Fishing.Scared")); lastWarned = System.currentTimeMillis(); } @@ -134,8 +131,7 @@ public class FishingManager extends SkillManager { if (this.sameTarget) { fishCaughtCounter++; - } - else { + } else { fishCaughtCounter = 1; } @@ -520,8 +516,7 @@ public class FishingManager extends SkillManager { if (FishingTreasureConfig.getInstance().getInventoryStealStacks()) { inventory.setItem(slot, null); - } - else { + } else { inventory.setItem(slot, (drop.getAmount() > 1) ? new ItemStack(drop.getType(), drop.getAmount() - 1) : null); drop.setAmount(1); } @@ -575,8 +570,7 @@ public class FishingManager extends SkillManager { if (getPlayer().getInventory().getItemInMainHand().getType() == Material.FISHING_ROD) { luck = getPlayer().getInventory().getItemInMainHand().getEnchantmentLevel( mcMMO.p.getEnchantmentMapper().getLuckOfTheSea()); - } - else { + } else { // We know something was caught, so if the rod wasn't in the main hand it must be in the offhand luck = getPlayer().getInventory().getItemInOffHand().getEnchantmentLevel( mcMMO.p.getEnchantmentMapper().getLuckOfTheSea()); diff --git a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java index 21cd85274..adbdf2a84 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java @@ -845,11 +845,9 @@ public class HerbalismManager extends SkillManager { if (greenTerra || greenThumbStage > 2) { finalAge = 2; - } - else if (greenThumbStage == 2) { + } else if (greenThumbStage == 2) { finalAge = 1; - } - else { + } else { finalAge = 0; } break; @@ -858,8 +856,7 @@ public class HerbalismManager extends SkillManager { if (getGreenThumbStage(greenTerra) >= 2) { finalAge = 1; - } - else { + } else { finalAge = 0; } break; diff --git a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java index 281831295..76cf6f8c6 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java @@ -62,8 +62,7 @@ public class BlastMining { return tier == Tier.EIGHT ? tier.getLevel() : tierList.get(tierList.indexOf(tier) - 1).getLevel(); }*/ - for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) - { + for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) { if (getBlastDamageDecrease(i+1) > 0) return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i+1); } @@ -81,8 +80,7 @@ public class BlastMining { return tier == Tier.EIGHT ? tier.getLevel() : tierList.get(tierList.indexOf(tier) - 1).getLevel(); }*/ - for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) - { + for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) { if (getBlastRadiusModifier(i+1) > 0) return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i+1); } @@ -102,8 +100,7 @@ public class BlastMining { return false; } - if (UserManager.getPlayer(defender) == null) - { + if (UserManager.getPlayer(defender) == null) { return false; } diff --git a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java index 555d17313..0e022ec86 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java @@ -387,8 +387,7 @@ public class RepairManager extends SkillManager { item.addUnsafeEnchantment(enchantment, enchantLevel - 1); downgraded = true; } - } - else { + } else { item.removeEnchantment(enchantment); } } @@ -397,11 +396,9 @@ public class RepairManager extends SkillManager { if (newEnchants.isEmpty()) { NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Fail"); - } - else if (downgraded || newEnchants.size() < enchants.size()) { + } else if (downgraded || newEnchants.size() < enchants.size()) { NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Downgrade"); - } - else { + } else { NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Perfect"); } } diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java index fe8e132c9..b80160c89 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java @@ -235,8 +235,7 @@ public class SalvageManager extends SkillManager { || ProbabilityUtil.isStaticSkillRNGSuccessful( PrimarySkillType.SALVAGE, mmoPlayer, getExtractFullEnchantChance())) { enchantMeta.addStoredEnchant(enchant.getKey(), enchantLevel, true); - } - else if (enchantLevel > 1 + } else if (enchantLevel > 1 && Salvage.arcaneSalvageDowngrades && ProbabilityUtil.isStaticSkillRNGSuccessful( PrimarySkillType.SALVAGE, mmoPlayer, getExtractPartialEnchantChance())) { @@ -247,12 +246,10 @@ public class SalvageManager extends SkillManager { } } - if (failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) - { + if (failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) { NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcaneFailed"); return null; - } else if (downgraded) - { + } else if (downgraded) { NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcanePartial"); } diff --git a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java index 4b667d86e..f8c43c0ca 100644 --- a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java @@ -36,8 +36,7 @@ public class SmeltingManager extends SkillManager { return Math.min(Short.MAX_VALUE, Math.max(1, burnTime * getFuelEfficiencyMultiplier())); } - public int getFuelEfficiencyMultiplier() - { + public int getFuelEfficiencyMultiplier() { return switch (RankUtils.getRank(getPlayer(), SubSkillType.SMELTING_FUEL_EFFICIENCY)) { case 1 -> 2; case 2 -> 3; diff --git a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java index 5e02747b8..48957df91 100644 --- a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java @@ -108,20 +108,17 @@ public class SwordsManager extends SkillManager { return RankUtils.getRank(getPlayer(), SubSkillType.SWORDS_RUPTURE); } - public double getStabDamage() - { + public double getStabDamage() { int rank = RankUtils.getRank(getPlayer(), SubSkillType.SWORDS_STAB); - if (rank > 0) - { + if (rank > 0) { return (1.0D + (rank * 1.5)); } return 0; } - public int getToolTier(@NotNull ItemStack itemStack) - { + public int getToolTier(@NotNull ItemStack itemStack) { if (ItemUtils.isNetheriteTool(itemStack)) return 5; if (ItemUtils.isDiamondTool(itemStack)) diff --git a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java index 9cb609e94..42ed59a9e 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java @@ -279,10 +279,8 @@ public class TamingManager extends SkillManager { } public void attackTarget(LivingEntity target) { - if (target instanceof Tameable tameable) - { - if (tameable.getOwner() == getPlayer()) - { + if (target instanceof Tameable tameable) { + if (tameable.getOwner() == getPlayer()) { return; } } diff --git a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java index d81957ae1..2e759f7df 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java @@ -19,8 +19,7 @@ public class Unarmed { int amount = itemDrop.getAmount(); boolean grabbedItem = false; - for(int i = 0; i <= storageContents.length-1; i++) - { + for(int i = 0; i <= storageContents.length-1; i++) { if (amount <= 0) break; @@ -28,18 +27,14 @@ public class Unarmed { continue; //EMPTY SLOT! - if (storageContents[i] == null) - { + if (storageContents[i] == null) { player.getInventory().setItem(i, itemDrop); amount = 0; grabbedItem = true; break; - } - else if (itemDrop.isSimilar(storageContents[i]) && storageContents[i].getAmount() < storageContents[i].getMaxStackSize()) - { + } else if (itemDrop.isSimilar(storageContents[i]) && storageContents[i].getAmount() < storageContents[i].getMaxStackSize()) { //If we can fit this whole itemstack into this item - if (amount + storageContents[i].getAmount() <= storageContents[i].getMaxStackSize()) - { + if (amount + storageContents[i].getAmount() <= storageContents[i].getMaxStackSize()) { ItemStack modifiedAmount = storageContents[i]; modifiedAmount.setAmount(amount + storageContents[i].getAmount()); @@ -68,8 +63,7 @@ public class Unarmed { event.setCancelled(true); - if (grabbedItem) - { + if (grabbedItem) { SoundManager.sendSound(player, player.getLocation(), SoundType.POP); player.updateInventory(); } diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java index 19412523e..e9d4623f3 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java @@ -191,8 +191,7 @@ public class WoodcuttingManager extends SkillManager { return; } } - } - else { + } else { // Cover DOWN processTreeFellerTargetBlock(blockState.getBlock().getRelative(BlockFace.DOWN).getState(), futureCenterBlocks, treeFellerBlocks); // Search in a cube @@ -282,8 +281,7 @@ public class WoodcuttingManager extends SkillManager { treeFellerBlocks.add(blockState); futureCenterBlocks.add(blockState); return true; - } - else if (BlockUtils.isNonWoodPartOfTree(blockState)) { + } else if (BlockUtils.isNonWoodPartOfTree(blockState)) { treeFellerBlocks.add(blockState); return false; } diff --git a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java index aa2b4380e..849728d9b 100644 --- a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java +++ b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java @@ -113,8 +113,7 @@ public final class ChimaeraWing { if (warmup > 0) { NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, "Teleport.Commencing", String.valueOf(warmup)); mcMMO.p.getFoliaLib().getImpl().runAtEntityLater(player, new ChimaeraWingWarmup(mcMMOPlayer), 20 * warmup); - } - else { + } else { chimaeraExecuteTeleport(); } } @@ -125,14 +124,12 @@ public final class ChimaeraWing { if (mcMMO.p.getGeneralConfig().getChimaeraUseBedSpawn() && player.getBedSpawnLocation() != null) { // player.teleport(player.getBedSpawnLocation()); mcMMO.p.getFoliaLib().getImpl().teleportAsync(player, player.getBedSpawnLocation()); - } - else { + } else { Location spawnLocation = player.getWorld().getSpawnLocation(); if (spawnLocation.getBlock().getType() == Material.AIR) { // player.teleport(spawnLocation); mcMMO.p.getFoliaLib().getImpl().teleportAsync(player, spawnLocation); - } - else { + } else { // player.teleport(player.getWorld().getHighestBlockAt(spawnLocation).getLocation()); mcMMO.p.getFoliaLib().getImpl().teleportAsync(player, player.getWorld().getHighestBlockAt(spawnLocation).getLocation()); } diff --git a/src/main/java/com/gmail/nossr50/util/EventUtils.java b/src/main/java/com/gmail/nossr50/util/EventUtils.java index a4a501da3..de0cb1340 100644 --- a/src/main/java/com/gmail/nossr50/util/EventUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EventUtils.java @@ -93,8 +93,7 @@ public final class EventUtils { * @param entity target entity * @return the associated McMMOPlayer for this entity */ - public static McMMOPlayer getMcMMOPlayer(@NotNull Entity entity) - { + public static McMMOPlayer getMcMMOPlayer(@NotNull Entity entity) { return UserManager.getPlayer((Player)entity); } @@ -111,8 +110,7 @@ public final class EventUtils { * @param entityDamageEvent * @return */ - public static boolean isRealPlayerDamaged(@NotNull EntityDamageEvent entityDamageEvent) - { + public static boolean isRealPlayerDamaged(@NotNull EntityDamageEvent entityDamageEvent) { //Make sure the damage is above 0 double damage = entityDamageEvent.getFinalDamage(); @@ -143,8 +141,7 @@ public final class EventUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { return true; } diff --git a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java index 37d807db0..01b085952 100644 --- a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java +++ b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java @@ -121,8 +121,7 @@ public final class HardcoreManager { if (totalLevelsStolen > 0) { NotificationManager.sendPlayerInformation(killer, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Killer.Success", String.valueOf(totalLevelsStolen), victim.getName()); NotificationManager.sendPlayerInformation(victim, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Victim.Success", killer.getName(), String.valueOf(totalLevelsStolen)); - } - else { + } else { NotificationManager.sendPlayerInformation(killer, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Killer.Failure", victim.getName()); NotificationManager.sendPlayerInformation(victim, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Victim.Failure", killer.getName()); } diff --git a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java index a0ad84326..01c6bf8fe 100644 --- a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java +++ b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java @@ -59,8 +59,7 @@ public class MaterialMapStore { private final @NotNull HashMap tierValue; - public MaterialMapStore() - { + public MaterialMapStore() { abilityBlackList = new HashSet<>(); toolBlackList = new HashSet<>(); mossyWhiteList = new HashSet<>(); @@ -133,8 +132,7 @@ public class MaterialMapStore { fillTierMap(); } - public boolean isMultiBlockPlant(@NotNull Material material) - { + public boolean isMultiBlockPlant(@NotNull Material material) { return multiBlockPlant.contains(material.getKey().getKey()); } @@ -142,38 +140,31 @@ public class MaterialMapStore { return multiBlockHangingPlant.contains(material.getKey().getKey()); } - public boolean isAbilityActivationBlackListed(@NotNull Material material) - { + public boolean isAbilityActivationBlackListed(@NotNull Material material) { return abilityBlackList.contains(material.getKey().getKey()); } - public boolean isToolActivationBlackListed(@NotNull Material material) - { + public boolean isToolActivationBlackListed(@NotNull Material material) { return toolBlackList.contains(material.getKey().getKey()); } - public boolean isMossyWhiteListed(@NotNull Material material) - { + public boolean isMossyWhiteListed(@NotNull Material material) { return mossyWhiteList.contains(material.getKey().getKey()); } - public boolean isTreeFellerDestructible(@NotNull Material material) - { + public boolean isTreeFellerDestructible(@NotNull Material material) { return treeFellerDestructibleWhiteList.contains(material.getKey().getKey()); } - public boolean isHerbalismAbilityWhiteListed(@NotNull Material material) - { + public boolean isHerbalismAbilityWhiteListed(@NotNull Material material) { return herbalismAbilityBlackList.contains(material.getKey().getKey()); } - public boolean isBlockCrackerWhiteListed(@NotNull Material material) - { + public boolean isBlockCrackerWhiteListed(@NotNull Material material) { return blockCrackerWhiteList.contains(material.getKey().getKey()); } - public boolean isShroomyWhiteListed(@NotNull Material material) - { + public boolean isShroomyWhiteListed(@NotNull Material material) { return canMakeShroomyWhiteList.contains(material.getKey().getKey()); } @@ -993,8 +984,7 @@ public class MaterialMapStore { return foodItemWhiteList.contains(material.getKey().getKey()); } - private void fillMultiBlockPlantSet() - { + private void fillMultiBlockPlantSet() { //Multi-Block Plants multiBlockPlant.add("cactus"); multiBlockPlant.add("chorus_plant"); @@ -1014,30 +1004,26 @@ public class MaterialMapStore { multiBlockHangingPlant.add("cave_vines_plant"); } - private void fillShroomyWhiteList() - { + private void fillShroomyWhiteList() { canMakeShroomyWhiteList.add("dirt"); canMakeShroomyWhiteList.add("grass_block"); canMakeShroomyWhiteList.add("dirt_path"); } - private void fillBlockCrackerWhiteList() - { + private void fillBlockCrackerWhiteList() { blockCrackerWhiteList.add("stone_bricks"); blockCrackerWhiteList.add("infested_stone_bricks"); } - private void fillHerbalismAbilityBlackList() - { + private void fillHerbalismAbilityBlackList() { herbalismAbilityBlackList.add("dirt"); herbalismAbilityBlackList.add("grass_block"); herbalismAbilityBlackList.add("dirt_path"); herbalismAbilityBlackList.add("farmland"); } - private void fillTreeFellerDestructibleWhiteList() - { + private void fillTreeFellerDestructibleWhiteList() { treeFellerDestructibleWhiteList.add("oak_leaves"); treeFellerDestructibleWhiteList.add("cherry_leaves"); treeFellerDestructibleWhiteList.add("acacia_leaves"); @@ -1055,8 +1041,7 @@ public class MaterialMapStore { treeFellerDestructibleWhiteList.add("red_mushroom_block"); } - private void fillMossyWhiteList() - { + private void fillMossyWhiteList() { mossyWhiteList.add("cobblestone"); mossyWhiteList.add("dirt"); mossyWhiteList.add("grass_path"); @@ -1064,8 +1049,7 @@ public class MaterialMapStore { mossyWhiteList.add("cobblestone_wall"); } - private void fillAbilityBlackList() - { + private void fillAbilityBlackList() { abilityBlackList.add("warped_fence_gate"); abilityBlackList.add("crimson_fence_gate"); abilityBlackList.add("warped_pressure_plate"); @@ -1192,8 +1176,7 @@ public class MaterialMapStore { abilityBlackList.add("respawn_anchor"); } - private void fillToolBlackList() - { + private void fillToolBlackList() { toolBlackList.add("chiseled_bookshelf"); toolBlackList.add("black_bed"); toolBlackList.add("blue_bed"); @@ -1371,8 +1354,7 @@ public class MaterialMapStore { return tierValue.getOrDefault(id, 1); //1 for unknown items } - private void addToHashSet(@NotNull String string, @NotNull HashSet stringHashSet) - { + private void addToHashSet(@NotNull String string, @NotNull HashSet stringHashSet) { stringHashSet.add(string.toLowerCase(Locale.ENGLISH)); } } diff --git a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java index 7d19e1979..02f80a306 100644 --- a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java +++ b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java @@ -75,8 +75,7 @@ public final class MobHealthbarUtils { if (updateName) { target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, new FixedMetadataValue(mcMMO.p, oldName)); target.setMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, new FixedMetadataValue(mcMMO.p, oldNameVisible)); - } - else if (!target.hasMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME)) { + } else if (!target.hasMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME)) { target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, new FixedMetadataValue(mcMMO.p, "")); target.setMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, new FixedMetadataValue(mcMMO.p, false)); } @@ -106,20 +105,15 @@ public final class MobHealthbarUtils { if (healthPercentage >= 85) { color = ChatColor.DARK_GREEN; - } - else if (healthPercentage >= 70) { + } else if (healthPercentage >= 70) { color = ChatColor.GREEN; - } - else if (healthPercentage >= 55) { + } else if (healthPercentage >= 55) { color = ChatColor.GOLD; - } - else if (healthPercentage >= 40) { + } else if (healthPercentage >= 40) { color = ChatColor.YELLOW; - } - else if (healthPercentage >= 25) { + } else if (healthPercentage >= 25) { color = ChatColor.RED; - } - else if (healthPercentage >= 0) { + } else if (healthPercentage >= 0) { color = ChatColor.DARK_RED; } diff --git a/src/main/java/com/gmail/nossr50/util/ModManager.java b/src/main/java/com/gmail/nossr50/util/ModManager.java index 19e1202ed..f70e356dd 100644 --- a/src/main/java/com/gmail/nossr50/util/ModManager.java +++ b/src/main/java/com/gmail/nossr50/util/ModManager.java @@ -215,8 +215,7 @@ public class ModManager { catch (Exception e) { if (e instanceof NoSuchFieldException || e instanceof IllegalArgumentException || e instanceof IllegalAccessException) { customEntity = customEntityClassMap.get(entity.getClass().getName()); - } - else { + } else { e.printStackTrace(); } } @@ -256,8 +255,7 @@ public class ModManager { catch (Exception e) { if (e instanceof NoSuchFieldException || e instanceof IllegalArgumentException || e instanceof IllegalAccessException) { className = entity.getClass().getName(); - } - else { + } else { e.printStackTrace(); } } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java b/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java index bdee4a3b9..a25f60beb 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java @@ -118,8 +118,7 @@ public class BitSetChunkStore implements ChunkStore { return world.getMinHeight(); } - private static int getWorldMax(@NotNull UUID worldUid) - { + private static int getWorldMax(@NotNull UUID worldUid) { World world = Bukkit.getWorld(worldUid); // Not sure how this case could come up, but might as well handle it gracefully. Loading a chunkstore for an unloaded world? @@ -181,8 +180,7 @@ public class BitSetChunkStore implements ChunkStore { if (currentWorldMin > worldMin) stored = stored.get(currentWorldMin, stored.length()); // Because BitSet's aren't fixed size, a "substring" operation is equivalent to a left shift // Right shift store if world min has expanded - if (currentWorldMin < worldMin) - { + if (currentWorldMin < worldMin) { int offset = (worldMin - currentWorldMin) * 16 * 16; // We are adding this many bits to the front // This isn't the most efficient way to do this, however, its a rare case to occur, and in the grand scheme of things, the small performance we could gain would cost us significant reduced readability of the code BitSet shifted = new BitSet(); @@ -207,13 +205,12 @@ public class BitSetChunkStore implements ChunkStore { inputStream.mark(2); short magicNumber = inputStream.readShort(); - if (magicNumber == ObjectStreamConstants.STREAM_MAGIC) // Java serializable, use legacy serialization - { + // Java serializable, use legacy serialization + if (magicNumber == ObjectStreamConstants.STREAM_MAGIC) { // "Un-read" the magic number for Serializables, they need it to still be in the stream - if (inputStream.markSupported()) + if (inputStream.markSupported()) { inputStream.reset(); // Pretend we never read those bytes - else - { + } else { // Creates a new stream with the two magic number bytes and then the rest of the original stream... Java is so dumb. I just wanted to look at two bytes. PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, 2); pushbackInputStream.unread((magicNumber) & 0xFF); @@ -221,9 +218,8 @@ public class BitSetChunkStore implements ChunkStore { inputStream = new DataInputStream(pushbackInputStream); } return new LegacyDeserializationInputStream(inputStream).readLegacyChunkStore(); - } - else if (magicNumber == STREAM_MAGIC) // Pure bytes format - { + } else if (magicNumber == STREAM_MAGIC) { + // Pure bytes format return BitSetChunkStore.deserialize(inputStream); } throw new IOException("Bad Data Format"); @@ -238,8 +234,7 @@ public class BitSetChunkStore implements ChunkStore { // Handles loading the old serialized class private static class LegacyDeserializationInputStream extends ObjectInputStream { - private static class LegacyChunkStoreDeserializer implements Serializable - { + private static class LegacyChunkStoreDeserializer implements Serializable { private static final long serialVersionUID = -1L; private int cx; @@ -270,8 +265,7 @@ public class BitSetChunkStore implements ChunkStore { worldMax = store[0][0].length; } - public @NotNull BitSetChunkStore convert() - { + public @NotNull BitSetChunkStore convert() { int currentWorldMin = getWorldMin(worldUid); int currentWorldMax = getWorldMax(worldUid); diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java index d572ec518..203c71e71 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java @@ -21,8 +21,7 @@ public class HashChunkManager implements ChunkManager { @Override public synchronized void closeAll() { // Save all dirty chunkstores - for (ChunkStore chunkStore : chunkMap.values()) - { + for (ChunkStore chunkStore : chunkMap.values()) { if (!chunkStore.isDirty()) continue; World world = Bukkit.getWorld(chunkStore.getWorldId()); @@ -113,8 +112,8 @@ public class HashChunkManager implements ChunkManager { CoordinateKey regionKey = toRegionKey(world.getUID(), cx, cz); HashSet chunkKeys = chunkUsageMap.get(regionKey); chunkKeys.remove(chunkKey); // remove from region file in-use set - if (chunkKeys.isEmpty()) // If it was last chunk in region, close the region file and remove it from memory - { + // If it was last chunk in region, close the region file and remove it from memory + if (chunkKeys.isEmpty()) { chunkUsageMap.remove(regionKey); regionMap.remove(regionKey).close(); } @@ -224,8 +223,7 @@ public class HashChunkManager implements ChunkManager { ChunkStore cStore = chunkMap.computeIfAbsent(chunkKey, k -> { // Load from file ChunkStore loaded = loadChunk(chunkKey.x, chunkKey.z, world); - if (loaded != null) - { + if (loaded != null) { chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), j -> new HashSet<>()).add(chunkKey); return loaded; } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java b/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java index 80f15699b..1e5f860fa 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java @@ -181,8 +181,7 @@ public class McMMOSimpleRegionFile { int end = start + chunkNumSegments[index]; // If we are writing, assert we don't write over any in-use segments - if (inUse) - { + if (inUse) { int nextSetBit = segments.nextSetBit(start); if (nextSetBit != -1 && nextSetBit < end) throw new IllegalStateException("Attempting to overwrite an in-use segment"); diff --git a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java index e2716aede..be38e4f9c 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java @@ -265,8 +265,7 @@ public final class CommandUtils { if (matches.size() == 1) { partialName = matches.get(0); } - } - else { + } else { Player player = mcMMO.p.getServer().getPlayer(partialName); if (player != null) { diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java index 3a2065f75..d114ea026 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java @@ -28,8 +28,7 @@ public class ExperienceBarManager { private HashSet alwaysVisible; private HashSet disabledBars; - public ExperienceBarManager(McMMOPlayer mcMMOPlayer) - { + public ExperienceBarManager(McMMOPlayer mcMMOPlayer) { this.mcMMOPlayer = mcMMOPlayer; init(); } @@ -44,8 +43,7 @@ public class ExperienceBarManager { disabledBars = new HashSet<>(); } - public void updateExperienceBar(PrimarySkillType primarySkillType, Plugin plugin) - { + public void updateExperienceBar(PrimarySkillType primarySkillType, Plugin plugin) { if (disabledBars.contains(primarySkillType) || !ExperienceConfig.getInstance().isExperienceBarsEnabled() || !ExperienceConfig.getInstance().isExperienceBarEnabled(primarySkillType)) @@ -65,8 +63,7 @@ public class ExperienceBarManager { experienceBarWrapper.showExperienceBar(); //Setup Hide Bar Task - if (experienceBarHideTaskHashMap.get(primarySkillType) != null) - { + if (experienceBarHideTaskHashMap.get(primarySkillType) != null) { experienceBarHideTaskHashMap.get(primarySkillType).cancel(); } @@ -82,14 +79,12 @@ public class ExperienceBarManager { experienceBarHideTaskHashMap.put(primarySkillType, experienceBarHideTask); } - public void hideExperienceBar(PrimarySkillType primarySkillType) - { + public void hideExperienceBar(PrimarySkillType primarySkillType) { if (experienceBars.containsKey(primarySkillType)) experienceBars.get(primarySkillType).hideExperienceBar(); } - public void clearTask(PrimarySkillType primarySkillType) - { + public void clearTask(PrimarySkillType primarySkillType) { experienceBarHideTaskHashMap.remove(primarySkillType); } diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java index 4f2fc97fb..d90eae7b2 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java @@ -29,8 +29,7 @@ public class ExperienceBarWrapper { protected String niceSkillName; protected String title; - public ExperienceBarWrapper(PrimarySkillType primarySkillType, McMMOPlayer mcMMOPlayer) - { + public ExperienceBarWrapper(PrimarySkillType primarySkillType, McMMOPlayer mcMMOPlayer) { this.mcMMOPlayer = mcMMOPlayer; this.primarySkillType = primarySkillType; title = ""; @@ -43,8 +42,7 @@ public class ExperienceBarWrapper { initBar(); } - private void initBar() - { + private void initBar() { title = getTitleTemplate(); createBossBar(); } @@ -115,8 +113,7 @@ public class ExperienceBarWrapper { } //Every time progress updates we need to check for a title update - if (getLevel() != lastLevelUpdated || ExperienceConfig.getInstance().getDoExperienceBarsAlwaysUpdateTitle()) - { + if (getLevel() != lastLevelUpdated || ExperienceConfig.getInstance().getDoExperienceBarsAlwaysUpdateTitle()) { updateTitle(); lastLevelUpdated = getLevel(); } @@ -134,23 +131,19 @@ public class ExperienceBarWrapper { return bossBar.isVisible(); } - public void hideExperienceBar() - { + public void hideExperienceBar() { bossBar.setVisible(false); } - public void showExperienceBar() - { + public void showExperienceBar() { bossBar.setVisible(true); } - /*public NamespacedKey getKey() - { + /*public NamespacedKey getKey() { return bossBar }*/ - private void createBossBar() - { + private void createBossBar() { bossBar = mcMMOPlayer.getPlayer().getServer().createBossBar( title, ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType), diff --git a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java index f2e20c597..01964d0a8 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java @@ -135,8 +135,7 @@ public class FormulaManager { * @param formulaType target formulaType */ private int processXPToNextLevel(int level, FormulaType formulaType) { - if (mcMMO.isRetroModeEnabled()) - { + if (mcMMO.isRetroModeEnabled()) { return processXPRetroToNextLevel(level, formulaType); } else { return processStandardXPToNextLevel(level, formulaType); diff --git a/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java b/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java index 5ecf557b0..721df8091 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java +++ b/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java @@ -80,15 +80,12 @@ public class PlatformManager { return ServerSoftwareType.CRAFT_BUKKIT; } - public ServerSoftwareType getServerSoftware() - { + public ServerSoftwareType getServerSoftware() { return platform.getServerSoftwareType(); } - public String getServerSoftwareStr() - { - switch(getServerSoftware()) - { + public String getServerSoftwareStr() { + switch(getServerSoftware()) { case PAPER: return "Paper"; case SPIGOT: diff --git a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java index 156c17e46..4750c5c48 100644 --- a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java @@ -43,8 +43,7 @@ public class NotificationManager { * @param notificationType notifications defined type * @param key the locale key for the notifications defined message */ - public static void sendPlayerInformation(Player player, NotificationType notificationType, String key) - { + public static void sendPlayerInformation(Player player, NotificationType notificationType, String key) { if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; @@ -59,8 +58,7 @@ public class NotificationManager { } - public static boolean doesPlayerUseNotifications(Player player) - { + public static boolean doesPlayerUseNotifications(Player player) { if (UserManager.getPlayer(player) == null) return false; else @@ -77,13 +75,11 @@ public class NotificationManager { * @param values values to be injected into the locale string */ public static void sendNearbyPlayersInformation(Player targetPlayer, NotificationType notificationType, String key, - String... values) - { + String... values) { sendPlayerInformation(targetPlayer, notificationType, key, values); } - public static void sendPlayerInformationChatOnly(Player player, String key, String... values) - { + public static void sendPlayerInformationChatOnly(Player player, String key, String... values) { if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; @@ -91,8 +87,7 @@ public class NotificationManager { player.sendMessage(preColoredString); } - public static void sendPlayerInformationChatOnlyPrefixed(Player player, String key, String... values) - { + public static void sendPlayerInformationChatOnlyPrefixed(Player player, String key, String... values) { if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; @@ -102,8 +97,7 @@ public class NotificationManager { } public static void sendPlayerInformation(Player player, NotificationType notificationType, String key, - String... values) - { + String... values) { if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; @@ -156,8 +150,7 @@ public class NotificationManager { * @param newLevel new level of that skill */ public static void sendPlayerLevelUpNotification(McMMOPlayer mcMMOPlayer, PrimarySkillType skillName, - int levelsGained, int newLevel) - { + int levelsGained, int newLevel) { if (!mcMMOPlayer.useChatNotifications()) return; @@ -176,16 +169,13 @@ public class NotificationManager { sendNotification(mcMMOPlayer.getPlayer(), customEvent); } - public static void broadcastTitle(Server server, String title, String subtitle, int i1, int i2, int i3) - { - for(Player player : server.getOnlinePlayers()) - { + public static void broadcastTitle(Server server, String title, String subtitle, int i1, int i2, int i3) { + for(Player player : server.getOnlinePlayers()) { player.sendTitle(title, subtitle, i1, i2, i3); } } - public static void sendPlayerUnlockNotification(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType) - { + public static void sendPlayerUnlockNotification(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType) { if (!mcMMOPlayer.useChatNotifications()) return; @@ -208,10 +198,8 @@ public class NotificationManager { if (!mcMMO.p.getGeneralConfig().adminNotifications()) return; - for(Player player : Bukkit.getServer().getOnlinePlayers()) - { - if (player.isOp() || Permissions.adminChat(player)) - { + for(Player player : Bukkit.getServer().getOnlinePlayers()) { + if (player.isOp() || Permissions.adminChat(player)) { player.sendMessage(LocaleLoader.getString("Notifications.Admin.Format.Others", msg)); } } @@ -241,15 +229,13 @@ public class NotificationManager { */ String senderName = LocaleLoader.getString("Server.ConsoleName"); - if (commandSender instanceof Player) - { + if (commandSender instanceof Player) { senderName = ((Player) commandSender).getDisplayName() + ChatColor.RESET + "-" + ((Player) commandSender).getUniqueId(); } //Send the notification - switch(sensitiveCommandType) - { + switch(sensitiveCommandType) { case XPRATE_MODIFY: sendAdminNotification(LocaleLoader.getString("Notifications.Admin.XPRate.Start.Others", addItemToFirstPositionOfArray(senderName, args))); diff --git a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java index 72ad26c4e..5a0d5f3de 100644 --- a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java +++ b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java @@ -30,8 +30,7 @@ public class PlayerLevelUtils { // } // } - public int getEarlyGameCutoff(PrimarySkillType primarySkillType) - { + public int getEarlyGameCutoff(PrimarySkillType primarySkillType) { return 1; } diff --git a/src/main/java/com/gmail/nossr50/util/player/UserManager.java b/src/main/java/com/gmail/nossr50/util/player/UserManager.java index 8d3044bfc..04457d103 100644 --- a/src/main/java/com/gmail/nossr50/util/player/UserManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/UserManager.java @@ -84,13 +84,11 @@ public final class UserManager { mcMMO.p.getLogger().info("Saving mcMMOPlayers... (" + trackedSyncData.size() + ")"); for (McMMOPlayer playerData : trackedSyncData) { - try - { + try { LogUtils.debug(mcMMO.p.getLogger(), "Saving data for player: "+playerData.getPlayerName()); playerData.getProfile().save(true); } - catch (Exception e) - { + catch (Exception e) { mcMMO.p.getLogger().warning("Could not save mcMMO player data for player: " + playerData.getPlayerName()); } } diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java index ff952b658..7bb64188d 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java @@ -155,8 +155,7 @@ public class ScoreboardManager { private static String formatAbility(ChatColor color, String abilityName) { if (mcMMO.p.getGeneralConfig().getShowAbilityNames()) { return getShortenedName(color + abilityName); - } - else { + } else { return color + LocaleLoader.getString("Scoreboard.Misc.Ability"); } } @@ -553,8 +552,7 @@ public class ScoreboardManager { public static void changeScoreboard(ScoreboardWrapper wrapper, int displayTime) { if (displayTime == -1) { wrapper.showBoardWithNoRevert(); - } - else { + } else { wrapper.showBoardAndScheduleRevert(displayTime * Misc.TICK_CONVERSION_FACTOR); } } diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java index 881ea31e4..f9988fb21 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java @@ -112,8 +112,7 @@ public class ScoreboardWrapper { // Stop updating if it's no longer something displaying cooldowns if (isBoardShown() && (isSkillScoreboard() || isCooldownScoreboard())) { doSidebarUpdateSoon(); - } - else { + } else { stopCooldownUpdating(); } } @@ -179,8 +178,7 @@ public class ScoreboardWrapper { if (mcMMO.p.getServer().getScoreboardManager() != null) this.oldBoard = mcMMO.p.getServer().getScoreboardManager().getMainScoreboard(); } - } - else { + } else { this.oldBoard = previousBoard; } } @@ -231,8 +229,7 @@ public class ScoreboardWrapper { if (!tippedKeep) { tippedKeep = true; player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Tip.Keep")); - } - else if (!tippedClear) { + } else if (!tippedClear) { tippedClear = true; player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Tip.Clear")); profile.increaseTipsShown(); @@ -257,8 +254,7 @@ public class ScoreboardWrapper { //Modify the player based on the event event.getTargetPlayer().setScoreboard(event.getTargetBoard()); oldBoard = null; - } - else { + } else { LogUtils.debug(mcMMO.p.getLogger(), "Not reverting targetBoard for " + playerName + " - targetBoard was changed by another plugin (Consider disabling the mcMMO scoreboards if you don't want them!)"); } } @@ -493,8 +489,7 @@ public class ScoreboardWrapper { sidebarObjective.getScore(ScoreboardManager.LABEL_CURRENT_XP).setScore(currentXP); sidebarObjective.getScore(ScoreboardManager.LABEL_REMAINING_XP).setScore(mcMMOPlayer.getXpToLevel(targetSkill) - currentXP); - } - else { + } else { for (PrimarySkillType parentSkill : mcMMO.p.getSkillTools().getChildSkillParents(targetSkill)) { sidebarObjective.getScore(ScoreboardManager.skillLabels.get(parentSkill)).setScore(mcMMOPlayer.getSkillLevel(parentSkill)); } @@ -516,8 +511,7 @@ public class ScoreboardWrapper { cooldownBM.setScore(secondsBM); stopUpdating = (secondsSB == 0 && secondsBM == 0); - } - else { + } else { SuperAbilityType ability = mcMMO.p.getSkillTools().getSuperAbility(targetSkill); Score cooldown = sidebarObjective.getScore(ScoreboardManager.abilityLabelsSkill.get(ability)); int seconds = Math.max(mcMMOPlayer.calculateTimeRemaining(ability), 0); @@ -529,8 +523,7 @@ public class ScoreboardWrapper { if (stopUpdating) { stopCooldownUpdating(); - } - else { + } else { startCooldownUpdating(); } } @@ -551,8 +544,7 @@ public class ScoreboardWrapper { if (anyCooldownsActive) { startCooldownUpdating(); - } - else { + } else { stopCooldownUpdating(); } break; @@ -563,11 +555,9 @@ public class ScoreboardWrapper { if (targetProfile != null) { newProfile = targetProfile; // offline - } - else if (targetPlayer == null) { + } else if (targetPlayer == null) { newProfile = mcMMOPlayer.getProfile(); // self - } - else { + } else { newProfile = UserManager.getPlayer(targetPlayer).getProfile(); // online } diff --git a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java index 55d02ba31..fb5834ad9 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java @@ -77,8 +77,7 @@ public final class CombatUtils { } //Add Stab Damage - if (swordsManager.canUseStab()) - { + if (swordsManager.canUseStab()) { boostedDamage += (swordsManager.getStabDamage() * mcMMOPlayer.getAttackStrength()); } @@ -86,8 +85,7 @@ public final class CombatUtils { swordsManager.serratedStrikes(target, event.getDamage()); } - if (canUseLimitBreak(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) - { + if (canUseLimitBreak(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -264,8 +262,7 @@ public final class CombatUtils { if (axesManager.canImpact(target)) { axesManager.impactCheck(target); - } - else if (axesManager.canGreaterImpact(target)) { + } else if (axesManager.canGreaterImpact(target)) { boostedDamage+=axesManager.greaterImpact(target); } @@ -277,8 +274,7 @@ public final class CombatUtils { boostedDamage+=(axesManager.criticalHit(target, boostedDamage) * mcMMOPlayer.getAttackStrength()); } - if (canUseLimitBreak(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK)) - { + if (canUseLimitBreak(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK)) { boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -320,8 +316,7 @@ public final class CombatUtils { unarmedManager.disarmCheck((Player) target); } - if (canUseLimitBreak(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) - { + if (canUseLimitBreak(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -394,8 +389,7 @@ public final class CombatUtils { archeryManager.retrieveArrows(target, arrow); } - if (canUseLimitBreak(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) - { + if (canUseLimitBreak(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { boostedDamage+=getLimitBreakDamage(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK); } @@ -494,8 +488,7 @@ public final class CombatUtils { processSwordCombat(target, player, event); } - } - else if (ItemUtils.isAxe(heldItem)) { + } else if (ItemUtils.isAxe(heldItem)) { if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.AXES, target)) { return; } @@ -503,8 +496,7 @@ public final class CombatUtils { if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.AXES)) { processAxeCombat(target, player, event); } - } - else if (ItemUtils.isUnarmed(heldItem)) { + } else if (ItemUtils.isUnarmed(heldItem)) { if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.UNARMED, target)) { return; } @@ -512,8 +504,7 @@ public final class CombatUtils { if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.UNARMED)) { processUnarmedCombat(target, player, event); } - } - else if (ItemUtils.isTrident(heldItem)) { + } else if (ItemUtils.isTrident(heldItem)) { if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { return; } @@ -521,8 +512,7 @@ public final class CombatUtils { if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.TRIDENTS)) { processTridentCombatMelee(target, player, event); } - } - else if (ItemUtils.isMace(heldItem)) { + } else if (ItemUtils.isMace(heldItem)) { if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.MACES, target)) { return; } @@ -543,8 +533,7 @@ public final class CombatUtils { processTamingCombat(target, master, wolf, event); } } - } - else if (painSource instanceof Trident trident) { + } else if (painSource instanceof Trident trident) { ProjectileSource projectileSource = trident.getShooter(); if (projectileSource instanceof Player player) { @@ -554,8 +543,7 @@ public final class CombatUtils { } } } - } - else if (painSource instanceof Arrow arrow) { + } else if (painSource instanceof Arrow arrow) { ProjectileSource projectileSource = arrow.getShooter(); boolean isCrossbow = arrow.isShotFromCrossbow(); if (projectileSource instanceof Player player) { @@ -590,8 +578,7 @@ public final class CombatUtils { * This cleans up names from displaying in chat as hearts * @param entity target entity */ - public static void fixNames(@NotNull LivingEntity entity) - { + public static void fixNames(@NotNull LivingEntity entity) { List metadataValue = entity.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY); if (metadataValue.size() <= 0) @@ -887,37 +874,27 @@ public final class CombatUtils { && SkillUtils.cooldownExpired(mcMMOPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { baseXP = 20 * ExperienceConfig.getInstance().getPlayerVersusPlayerXP(); } - } - else { + } else { if (mcMMO.getModManager().isCustomEntity(target)) { baseXP = mcMMO.getModManager().getEntity(target).getXpMultiplier(); - } - else if (target instanceof Animals) { + } else if (target instanceof Animals) { EntityType type = target.getType(); baseXP = ExperienceConfig.getInstance().getAnimalsXP(type); - } - else if (target instanceof Monster) - { + } else if (target instanceof Monster) { EntityType type = target.getType(); baseXP = ExperienceConfig.getInstance().getCombatXP(type); - } - else { + } else { EntityType type = target.getType(); if (ExperienceConfig.getInstance().hasCombatXP(type)) { - if (type == EntityType.IRON_GOLEM) - { + if (type == EntityType.IRON_GOLEM) { if (!((IronGolem) target).isPlayerCreated()) { baseXP = ExperienceConfig.getInstance().getCombatXP(type); } - } - else - { + } else { baseXP = ExperienceConfig.getInstance().getCombatXP(type); } - } - else - { + } else { baseXP = 1.0; mcMMO.getModManager().addCustomEntity(target); } @@ -1036,22 +1013,17 @@ public final class CombatUtils { if (ItemUtils.isWoodTool(inHand)) { tier = 1; - } - else if (ItemUtils.isStoneTool(inHand)) { + } else if (ItemUtils.isStoneTool(inHand)) { tier = 2; - } - else if (ItemUtils.isIronTool(inHand)) { + } else if (ItemUtils.isIronTool(inHand)) { tier = 3; - } - else if (ItemUtils.isGoldTool(inHand)) { + } else if (ItemUtils.isGoldTool(inHand)) { tier = 1; - } - else if (ItemUtils.isDiamondTool(inHand)) { + } else if (ItemUtils.isDiamondTool(inHand)) { tier = 4; } else if (ItemUtils.isNetheriteTool(inHand)) { tier = 5; - } - else if (mcMMO.getModManager().isCustomTool(inHand)) { + } else if (mcMMO.getModManager().isCustomTool(inHand)) { tier = mcMMO.getModManager().getTool(inHand).getTier(); } diff --git a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java index 9891582f9..44320b37a 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java @@ -19,11 +19,9 @@ public final class PerksUtils { public static int handleCooldownPerks(Player player, int cooldown) { if (Permissions.halvedCooldowns(player)) { cooldown *= 0.5; - } - else if (Permissions.thirdedCooldowns(player)) { + } else if (Permissions.thirdedCooldowns(player)) { cooldown *= (2.0 / 3.0); - } - else if (Permissions.quarteredCooldowns(player)) { + } else if (Permissions.quarteredCooldowns(player)) { cooldown *= 0.75; } @@ -37,11 +35,9 @@ public final class PerksUtils { if (Permissions.twelveSecondActivationBoost(player)) { ticks += 12; - } - else if (Permissions.eightSecondActivationBoost(player)) { + } else if (Permissions.eightSecondActivationBoost(player)) { ticks += 8; - } - else if (Permissions.fourSecondActivationBoost(player)) { + } else if (Permissions.fourSecondActivationBoost(player)) { ticks += 4; } @@ -59,26 +55,19 @@ public final class PerksUtils { } modifier = ExperienceConfig.getInstance().getCustomXpPerkBoost(); - } - else if (Permissions.quadrupleXp(player, skill)) { + } else if (Permissions.quadrupleXp(player, skill)) { modifier = 4; - } - else if (Permissions.tripleXp(player, skill)) { + } else if (Permissions.tripleXp(player, skill)) { modifier = 3; - } - else if (Permissions.doubleAndOneHalfXp(player, skill)) { + } else if (Permissions.doubleAndOneHalfXp(player, skill)) { modifier = 2.5; - } - else if (Permissions.doubleXp(player, skill)) { + } else if (Permissions.doubleXp(player, skill)) { modifier = 2; - } - else if (Permissions.oneAndOneHalfXp(player, skill)) { + } else if (Permissions.oneAndOneHalfXp(player, skill)) { modifier = 1.5; - } - else if (Permissions.oneAndAQuarterXp(player, skill)) { + } else if (Permissions.oneAndAQuarterXp(player, skill)) { modifier = 1.25; - } - else if (Permissions.oneAndOneTenthXp(player, skill)) { + } else if (Permissions.oneAndOneTenthXp(player, skill)) { modifier = 1.1; } diff --git a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java index 38a730d7b..398cb579b 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java @@ -27,10 +27,8 @@ public class RankUtils { * @param primarySkillType the skill to check * @param newLevel the new level of this skill */ - public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, int newLevel) - { - for(SubSkillType subSkillType : mcMMO.p.getSkillTools().getSubSkills(primarySkillType)) - { + public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, int newLevel) { + for(SubSkillType subSkillType : mcMMO.p.getSkillTools().getSubSkills(primarySkillType)) { int playerRankInSkill = getRank(mcMMOPlayer.getPlayer(), subSkillType); HashMap innerMap = subSkillRanks.get(subSkillType.toString()); @@ -44,8 +42,7 @@ public class RankUtils { continue; //The players level is the exact level requirement for this skill - if (newLevel == innerMap.get(playerRankInSkill)) - { + if (newLevel == innerMap.get(playerRankInSkill)) { SkillUnlockNotificationTask skillUnlockNotificationTask = new SkillUnlockNotificationTask(mcMMOPlayer, subSkillType, newLevel); mcMMO.p.getFoliaLib().getImpl().runAtEntityLater(mcMMOPlayer.getPlayer(), skillUnlockNotificationTask, (count * 100L)); @@ -58,17 +55,14 @@ public class RankUtils { /** * Reset the interval between skill unlock notifications */ - public static void resetUnlockDelayTimer() - { + public static void resetUnlockDelayTimer() { count = 0; } /* NEW SYSTEM */ - private static void addRanks(AbstractSubSkill abstractSubSkill) - { + private static void addRanks(AbstractSubSkill abstractSubSkill) { //Fill out the rank array - for(int i = 0; i < abstractSubSkill.getNumRanks(); i++) - { + for(int i = 0; i < abstractSubSkill.getNumRanks(); i++) { //This adds the highest ranks first addRank(abstractSubSkill, abstractSubSkill.getNumRanks()-i); @@ -77,11 +71,9 @@ public class RankUtils { } } - private static void addRanks(SubSkillType subSkillType) - { + private static void addRanks(SubSkillType subSkillType) { //Fill out the rank array - for(int i = 0; i < subSkillType.getNumRanks(); i++) - { + for(int i = 0; i < subSkillType.getNumRanks(); i++) { //This adds the highest ranks first addRank(subSkillType, subSkillType.getNumRanks()-i); @@ -93,15 +85,12 @@ public class RankUtils { /** * Populates the ranks for every skill we know about */ - public static void populateRanks() - { - for(SubSkillType subSkillType : SubSkillType.values()) - { + public static void populateRanks() { + for(SubSkillType subSkillType : SubSkillType.values()) { addRanks(subSkillType); } - for(AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) - { + for(AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) { addRanks(abstractSubSkill); } } @@ -112,8 +101,7 @@ public class RankUtils { * @param subSkillType the target subskill * @return true if the player has at least one rank in the skill */ - public static boolean hasUnlockedSubskill(Player player, SubSkillType subSkillType) - { + public static boolean hasUnlockedSubskill(Player player, SubSkillType subSkillType) { int curRank = getRank(player, subSkillType); //-1 means the skill has no unlockable levels and is therefor unlocked @@ -126,8 +114,7 @@ public class RankUtils { * @param abstractSubSkill the target subskill * @return true if the player has at least one rank in the skill */ - public static boolean hasUnlockedSubskill(Player player, AbstractSubSkill abstractSubSkill) - { + public static boolean hasUnlockedSubskill(Player player, AbstractSubSkill abstractSubSkill) { int curRank = getRank(player, abstractSubSkill); //-1 means the skill has no unlockable levels and is therefor unlocked @@ -141,8 +128,7 @@ public class RankUtils { * @param subSkillType the target subskill * @return true if the player is at least that rank in this subskill */ - public static boolean hasReachedRank(int rank, Player player, SubSkillType subSkillType) - { + public static boolean hasReachedRank(int rank, Player player, SubSkillType subSkillType) { return getRank(player, subSkillType) >= rank; } @@ -153,8 +139,7 @@ public class RankUtils { * @param abstractSubSkill the target subskill * @return true if the player is at least that rank in this subskill */ - public static boolean hasReachedRank(int rank, Player player, AbstractSubSkill abstractSubSkill) - { + public static boolean hasReachedRank(int rank, Player player, AbstractSubSkill abstractSubSkill) { return getRank(player, abstractSubSkill) >= rank; } @@ -164,8 +149,7 @@ public class RankUtils { * @param subSkillType Target subskill * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. */ - public static int getRank(McMMOPlayer mmoPlayer, SubSkillType subSkillType) - { + public static int getRank(McMMOPlayer mmoPlayer, SubSkillType subSkillType) { return getRank(mmoPlayer.getPlayer(), subSkillType); } @@ -175,8 +159,7 @@ public class RankUtils { * @param subSkillType Target subskill * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. */ - public static int getRank(Player player, SubSkillType subSkillType) - { + public static int getRank(Player player, SubSkillType subSkillType) { String skillName = subSkillType.toString(); int numRanks = subSkillType.getNumRanks(); @@ -198,8 +181,7 @@ public class RankUtils { //Skill level of parent skill int currentSkillLevel = UserManager.getPlayer(player).getSkillLevel(subSkillType.getParentSkill()); - for(int i = 0; i < numRanks; i++) - { + for(int i = 0; i < numRanks; i++) { //Compare against the highest to lowest rank in that order int rank = numRanks-i; int unlockLevel = getRankUnlockLevel(subSkillType, rank); @@ -222,8 +204,7 @@ public class RankUtils { * @param abstractSubSkill Target subskill * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. */ - public static int getRank(Player player, AbstractSubSkill abstractSubSkill) - { + public static int getRank(Player player, AbstractSubSkill abstractSubSkill) { String skillName = abstractSubSkill.getConfigKeyName(); int numRanks = abstractSubSkill.getNumRanks(); @@ -245,8 +226,7 @@ public class RankUtils { //Skill level of parent skill int currentSkillLevel = UserManager.getPlayer(player).getSkillLevel(abstractSubSkill.getPrimarySkill()); - for(int i = 0; i < numRanks; i++) - { + for(int i = 0; i < numRanks; i++) { //Compare against the highest to lowest rank in that order int rank = numRanks-i; int unlockLevel = getRankUnlockLevel(abstractSubSkill, rank); @@ -268,8 +248,7 @@ public class RankUtils { * @param abstractSubSkill The subskill to add ranks for * @param rank The rank to add */ - private static void addRank(AbstractSubSkill abstractSubSkill, int rank) - { + private static void addRank(AbstractSubSkill abstractSubSkill, int rank) { initMaps(abstractSubSkill.getConfigKeyName()); HashMap rankMap = subSkillRanks.get(abstractSubSkill.getConfigKeyName()); @@ -278,8 +257,7 @@ public class RankUtils { } @Deprecated - private static void addRank(SubSkillType subSkillType, int rank) - { + private static void addRank(SubSkillType subSkillType, int rank) { initMaps(subSkillType.toString()); HashMap rankMap = subSkillRanks.get(subSkillType.toString()); @@ -300,13 +278,11 @@ public class RankUtils { * @param rank The target rank * @return The level at which this rank unlocks */ - public static int getRankUnlockLevel(SubSkillType subSkillType, int rank) - { + public static int getRankUnlockLevel(SubSkillType subSkillType, int rank) { return RankConfig.getInstance().getSubSkillUnlockLevel(subSkillType, rank); } - public static int getRankUnlockLevel(AbstractSubSkill abstractSubSkill, int rank) - { + public static int getRankUnlockLevel(AbstractSubSkill abstractSubSkill, int rank) { return RankConfig.getInstance().getSubSkillUnlockLevel(abstractSubSkill, rank); } @@ -315,8 +291,7 @@ public class RankUtils { * @param subSkillType target subskill * @return The unlock requirements for rank 1 in this skill */ - public static int getUnlockLevel(SubSkillType subSkillType) - { + public static int getUnlockLevel(SubSkillType subSkillType) { return RankConfig.getInstance().getSubSkillUnlockLevel(subSkillType, 1); } @@ -325,8 +300,7 @@ public class RankUtils { * @param abstractSubSkill target subskill * @return The unlock requirements for rank 1 in this skill */ - public static int getUnlockLevel(AbstractSubSkill abstractSubSkill) - { + public static int getUnlockLevel(AbstractSubSkill abstractSubSkill) { return RankConfig.getInstance().getSubSkillUnlockLevel(abstractSubSkill, 1); } @@ -335,13 +309,11 @@ public class RankUtils { * @param subSkillType target subskill * @return the last rank of a subskill */ - public static int getHighestRank(SubSkillType subSkillType) - { + public static int getHighestRank(SubSkillType subSkillType) { return subSkillType.getNumRanks(); } - public static String getHighestRankStr(SubSkillType subSkillType) - { + public static String getHighestRankStr(SubSkillType subSkillType) { return String.valueOf(subSkillType.getNumRanks()); } @@ -350,13 +322,11 @@ public class RankUtils { * @param abstractSubSkill target subskill * @return the last rank of a subskill */ - public static int getHighestRank(AbstractSubSkill abstractSubSkill) - { + public static int getHighestRank(AbstractSubSkill abstractSubSkill) { return abstractSubSkill.getNumRanks(); } - public static int getSuperAbilityUnlockRequirement(SuperAbilityType superAbilityType) - { + public static int getSuperAbilityUnlockRequirement(SuperAbilityType superAbilityType) { return getRankUnlockLevel(superAbilityType.getSubSkillTypeDefinition(), 1); } diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java index 02c6c47cb..a6186d369 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java @@ -61,8 +61,7 @@ public final class SkillUtils { int length; - if (abilityLengthCap > 0) - { + if (abilityLengthCap > 0) { length = (int) Math.min(abilityLengthCap, 2 + (skillValue / abilityLengthVar)); } else { length = 2 + (int) (skillValue / abilityLengthVar); @@ -181,8 +180,7 @@ public final class SkillUtils { int ticks; - if (abilityLengthCap > 0) - { + if (abilityLengthCap > 0) { ticks = PerksUtils.handleActivationPerks(player, Math.min(abilityLengthCap, 2 + (mcMMOPlayer.getSkillLevel(skill) / abilityLengthVar)), mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR; } else { @@ -284,26 +282,19 @@ public final class SkillUtils { public static Material getRepairAndSalvageItem(@NotNull ItemStack inHand) { if (ItemUtils.isDiamondTool(inHand) || ItemUtils.isDiamondArmor(inHand)) { return Material.DIAMOND; - } - else if (ItemUtils.isGoldTool(inHand) || ItemUtils.isGoldArmor(inHand)) { + } else if (ItemUtils.isGoldTool(inHand) || ItemUtils.isGoldArmor(inHand)) { return Material.GOLD_INGOT; - } - else if (ItemUtils.isIronTool(inHand) || ItemUtils.isIronArmor(inHand)) { + } else if (ItemUtils.isIronTool(inHand) || ItemUtils.isIronArmor(inHand)) { return Material.IRON_INGOT; - } - else if (ItemUtils.isStoneTool(inHand)) { + } else if (ItemUtils.isStoneTool(inHand)) { return Material.COBBLESTONE; - } - else if (ItemUtils.isWoodTool(inHand)) { + } else if (ItemUtils.isWoodTool(inHand)) { return Material.OAK_WOOD; - } - else if (ItemUtils.isLeatherArmor(inHand)) { + } else if (ItemUtils.isLeatherArmor(inHand)) { return Material.LEATHER; - } - else if (ItemUtils.isStringTool(inHand)) { + } else if (ItemUtils.isStringTool(inHand)) { return Material.STRING; - } - else { + } else { return null; } } diff --git a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java index 8cfa7da25..c809444fa 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java @@ -13,28 +13,24 @@ public class SoundManager { * Sends a sound to the player * @param soundType the type of sound */ - public static void sendSound(Player player, Location location, SoundType soundType) - { + public static void sendSound(Player player, Location location, SoundType soundType) { if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), SoundCategory.MASTER, getVolume(soundType), getPitch(soundType)); } - public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory) - { + public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory) { if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), getPitch(soundType)); } - public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory, float pitchModifier) - { + public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory, float pitchModifier) { float totalPitch = Math.min(2.0F, (getPitch(soundType) + pitchModifier)); if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), totalPitch); } - public static void worldSendSound(World world, Location location, SoundType soundType) - { + public static void worldSendSound(World world, Location location, SoundType soundType) { if (SoundConfig.getInstance().getIsEnabled(soundType)) world.playSound(location, getSound(soundType), getVolume(soundType), getPitch(soundType)); } @@ -49,13 +45,11 @@ public class SoundManager { * @param soundType target soundtype * @return the volume for this soundtype */ - private static float getVolume(SoundType soundType) - { + private static float getVolume(SoundType soundType) { return SoundConfig.getInstance().getVolume(soundType) * SoundConfig.getInstance().getMasterVolume(); } - private static float getPitch(SoundType soundType) - { + private static float getPitch(SoundType soundType) { if (soundType == SoundType.FIZZ) return getFizzPitch(); else if (soundType == SoundType.POP) @@ -64,8 +58,7 @@ public class SoundManager { return SoundConfig.getInstance().getPitch(soundType); } - private static Sound getSound(SoundType soundType) - { + private static Sound getSound(SoundType soundType) { return switch (soundType) { case ANVIL -> Sound.BLOCK_ANVIL_PLACE; case ITEM_BREAK -> Sound.ENTITY_ITEM_BREAK; diff --git a/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java b/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java index 67e9b0e0b..5b4a083f3 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java @@ -18,8 +18,7 @@ public enum SoundType { ITEM_CONSUMED, TIRED; - public boolean usesCustomPitch() - { + public boolean usesCustomPitch() { switch(this){ case POP: case FIZZ: diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java index f95671275..f3ccd14ec 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java @@ -25,8 +25,7 @@ public class WorldGuardManager { return instance; } - public boolean hasMainFlag(Player player) - { + public boolean hasMainFlag(Player player) { if (player == null) return false; @@ -41,8 +40,7 @@ public class WorldGuardManager { return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), WorldGuardFlags.MCMMO_ENABLE_WG_FLAG); } - public boolean hasXPFlag(Player player) - { + public boolean hasXPFlag(Player player) { if (player == null) return false; @@ -57,8 +55,7 @@ public class WorldGuardManager { return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), WorldGuardFlags.MCMMO_XP_WG_FLAG); } - public boolean hasHardcoreFlag(Player player) - { + public boolean hasHardcoreFlag(Player player) { if (player == null) return false; @@ -85,8 +82,7 @@ public class WorldGuardManager { return worldGuardPluginRef; } - public void registerFlags() - { + public void registerFlags() { try { FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java index 82cf426da..9cc190b7d 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java @@ -41,8 +41,7 @@ public class WorldGuardUtils { WGClassList.add("com.sk89q.worldguard.protection.regions.RegionQuery"); } - public static boolean isWorldGuardLoaded() - { + public static boolean isWorldGuardLoaded() { if (detectedIncompatibleWG) return false; @@ -56,8 +55,7 @@ public class WorldGuardUtils { * Results are cached * @return the instance of WG plugin, null if its not compatible or isn't present */ - private static WorldGuardPlugin getWorldGuard() - { + private static WorldGuardPlugin getWorldGuard() { //WG plugin reference is already cached so just return it if (isLoaded) return worldGuardPluginRef; @@ -71,10 +69,8 @@ public class WorldGuardUtils { LogUtils.debug(mcMMO.p.getLogger(), "WorldGuard was not detected."); } else { //Check that its actually of class WorldGuardPlugin - if (plugin instanceof WorldGuardPlugin) - { - if (isCompatibleVersion(plugin)) - { + if (plugin instanceof WorldGuardPlugin) { + if (isCompatibleVersion(plugin)) { worldGuardPluginRef = (WorldGuardPlugin) plugin; isLoaded = true; } diff --git a/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java b/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java index 4ce8fee08..4c4879610 100644 --- a/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java +++ b/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java @@ -73,8 +73,7 @@ public class ZipLibrary { for (File source : sources) { if (source.isDirectory()) { zipDir(zipOut, "", source); - } - else { + } else { zipFile(zipOut, "", source); } } @@ -104,8 +103,7 @@ public class ZipLibrary { for (File source : files) { if (source.isDirectory()) { zipDir(zos, path, source); - } - else { + } else { zipFile(zos, path, source); } }