Merge master into endgame branch to prepare merge for beta 2.2.000 update

This commit is contained in:
nossr50
2022-12-04 15:58:23 -08:00
283 changed files with 24630 additions and 17228 deletions

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.meta.BonusDropMeta;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
@@ -8,8 +7,10 @@ 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.skills.SkillUtils;
import com.gmail.nossr50.util.random.RandomChanceSkill;
import com.gmail.nossr50.util.random.RandomChanceUtil;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.Ageable;
@@ -30,11 +31,24 @@ public final class BlockUtils {
* @param blockState target blockstate
* @param triple marks the block to give triple drops
*/
public static void markDropsAsBonus(@NotNull BlockState blockState, boolean triple) {
public static void markDropsAsBonus(BlockState blockState, boolean triple) {
if (triple)
blockState.setMetadata(mcMMO.BONUS_DROPS_METAKEY, new BonusDropMeta(2, mcMMO.p));
blockState.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(2, mcMMO.p));
else
blockState.setMetadata(mcMMO.BONUS_DROPS_METAKEY, new BonusDropMeta(1, mcMMO.p));
blockState.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(1, mcMMO.p));
}
/**
* Cleans up some block metadata when a block breaks and the metadata is no longer needed
* This also sets the blocks coords to false in our chunk store
* @param block target block
*/
public static void cleanupBlockMetadata(Block block) {
if(block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) {
block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p);
}
mcMMO.getPlaceStore().setFalse(block);
}
/**
@@ -42,8 +56,8 @@ public final class BlockUtils {
* @param blockState target blockstate
* @param amount amount of extra items to drop
*/
public static void markDropsAsBonus(@NotNull BlockState blockState, int amount) {
blockState.setMetadata(mcMMO.BONUS_DROPS_METAKEY, new BonusDropMeta(amount, mcMMO.p));
public static void markDropsAsBonus(BlockState blockState, int amount) {
blockState.setMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, new BonusDropMeta(amount, mcMMO.p));
}
/**
@@ -52,9 +66,9 @@ public final class BlockUtils {
* @param blockState the blockstate
* @return true if the player succeeded in the check
*/
public static boolean checkDoubleDrops(@NotNull Player player, @NotNull BlockState blockState, @NotNull PrimarySkillType skillType, @NotNull SubSkillType subSkillType) {
if (Config.getInstance().getDoubleDropsEnabled(skillType, blockState.getType()) && Permissions.isSubSkillEnabled(player, subSkillType)) {
return SkillUtils.isSkillRNGSuccessful(subSkillType, player);
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 RandomChanceUtil.checkRandomChanceExecutionSuccess(new RandomChanceSkill(player, subSkillType, true));
}
return false;
@@ -68,10 +82,10 @@ public final class BlockUtils {
*/
public static boolean shouldBeWatched(BlockState blockState) {
return affectedByGigaDrillBreaker(blockState) || affectedByGreenTerra(blockState) || affectedBySuperBreaker(blockState) || hasWoodcuttingXP(blockState)
|| Config.getInstance().getDoubleDropsEnabled(PrimarySkillType.MINING, blockState.getType())
|| Config.getInstance().getDoubleDropsEnabled(PrimarySkillType.EXCAVATION, blockState.getType())
|| Config.getInstance().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, blockState.getType())
|| Config.getInstance().getDoubleDropsEnabled(PrimarySkillType.SMELTING, blockState.getType());
|| mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, blockState.getType())
|| mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.EXCAVATION, blockState.getType())
|| mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, blockState.getType())
|| mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.SMELTING, blockState.getType());
}
/**
@@ -157,7 +171,7 @@ public final class BlockUtils {
* @return true if the block should affected by Giga Drill Breaker, false
* otherwise
*/
public static boolean affectedByGigaDrillBreaker(BlockState blockState) {
public static boolean affectedByGigaDrillBreaker(@NotNull BlockState blockState) {
if (ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.EXCAVATION, blockState.getBlockData()))
return true;
return mcMMO.getModManager().isCustomExcavationBlock(blockState);
@@ -169,7 +183,7 @@ public final class BlockUtils {
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is a log, false otherwise
*/
public static boolean hasWoodcuttingXP(BlockState blockState) {
public static boolean hasWoodcuttingXP(@NotNull BlockState blockState) {
return ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.WOODCUTTING, blockState.getBlockData());
}
@@ -179,11 +193,11 @@ public final class BlockUtils {
* @param blockState The {@link BlockState} of the block to check
* @return true if the block is a leaf, false otherwise
*/
public static boolean isNonWoodPartOfTree(BlockState blockState) {
public static boolean isNonWoodPartOfTree(@NotNull BlockState blockState) {
return mcMMO.getMaterialMapStore().isTreeFellerDestructible(blockState.getType());
}
public static boolean isNonWoodPartOfTree(Material material) {
public static boolean isNonWoodPartOfTree(@NotNull Material material) {
return mcMMO.getMaterialMapStore().isTreeFellerDestructible(material);
}
@@ -276,14 +290,27 @@ public final class BlockUtils {
if (data.getMaterial() == Material.CACTUS || data.getMaterial() == Material.SUGAR_CANE) {
return true;
}
if (data instanceof Ageable) {
Ageable ageable = (Ageable) data;
if (data instanceof Ageable ageable) {
return ageable.getAge() == ageable.getMaximumAge();
}
return true;
}
public static boolean isPartOfTree(Block rayCast) {
return hasWoodcuttingXP(rayCast.getState()) || isNonWoodPartOfTree(rayCast.getType());
public static boolean isPartOfTree(Block block) {
return hasWoodcuttingXP(block.getState()) || isNonWoodPartOfTree(block.getType());
}
/**
* Checks to see if a Block is within the world bounds
* Prevent processing blocks from other plugins (or perhaps odd spigot anomalies) from sending blocks that can't exist within the world
* @param block
* @return
*/
public static boolean isWithinWorldBounds(@NotNull Block block) {
World world = block.getWorld();
//World min height = inclusive | World max height = exclusive
return block.getY() >= world.getMinHeight() && block.getY() < world.getMaxHeight();
}
}

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.interactions.NotificationType;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
@@ -37,7 +36,7 @@ public final class ChimaeraWing {
* @param player Player whose item usage to check
*/
public static void activationCheck(Player player) {
if (!Config.getInstance().getChimaeraEnabled()) {
if (!mcMMO.p.getGeneralConfig().getChimaeraEnabled()) {
return;
}
@@ -64,13 +63,13 @@ public final class ChimaeraWing {
int amount = inHand.getAmount();
if (amount < Config.getInstance().getChimaeraUseCost()) {
NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Item.ChimaeraWing.NotEnough",String.valueOf(Config.getInstance().getChimaeraUseCost() - amount), "Item.ChimaeraWing.Name");
if (amount < mcMMO.p.getGeneralConfig().getChimaeraUseCost()) {
NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Item.ChimaeraWing.NotEnough",String.valueOf(mcMMO.p.getGeneralConfig().getChimaeraUseCost() - amount), "Item.ChimaeraWing.Name");
return;
}
long lastTeleport = mcMMOPlayer.getChimeraWingLastUse();
int cooldown = Config.getInstance().getChimaeraCooldown();
int cooldown = mcMMO.p.getGeneralConfig().getChimaeraCooldown();
if (cooldown > 0) {
int timeRemaining = SkillUtils.calculateTimeLeft(lastTeleport * Misc.TIME_CONVERSION_FACTOR, cooldown, player);
@@ -82,7 +81,7 @@ public final class ChimaeraWing {
}
long recentlyHurt = mcMMOPlayer.getRecentlyHurt();
int hurtCooldown = Config.getInstance().getChimaeraRecentlyHurtCooldown();
int hurtCooldown = mcMMO.p.getGeneralConfig().getChimaeraRecentlyHurtCooldown();
if (hurtCooldown > 0) {
int timeRemaining = SkillUtils.calculateTimeLeft(recentlyHurt * Misc.TIME_CONVERSION_FACTOR, hurtCooldown, player);
@@ -95,9 +94,9 @@ public final class ChimaeraWing {
location = player.getLocation();
if (Config.getInstance().getChimaeraPreventUseUnderground()) {
if (mcMMO.p.getGeneralConfig().getChimaeraPreventUseUnderground()) {
if (location.getY() < player.getWorld().getHighestBlockYAt(location)) {
player.getInventory().setItemInMainHand(new ItemStack(getChimaeraWing(amount - Config.getInstance().getChimaeraUseCost())));
player.getInventory().setItemInMainHand(new ItemStack(getChimaeraWing(amount - mcMMO.p.getGeneralConfig().getChimaeraUseCost())));
NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Item.ChimaeraWing.Fail");
player.updateInventory();
player.setVelocity(new Vector(0, 0.5D, 0));
@@ -109,7 +108,7 @@ public final class ChimaeraWing {
mcMMOPlayer.actualizeTeleportCommenceLocation(player);
long warmup = Config.getInstance().getChimaeraWarmup();
long warmup = mcMMO.p.getGeneralConfig().getChimaeraWarmup();
if (warmup > 0) {
NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, "Teleport.Commencing", String.valueOf(warmup));
@@ -123,7 +122,7 @@ public final class ChimaeraWing {
public static void chimaeraExecuteTeleport() {
Player player = mcMMOPlayer.getPlayer();
if (Config.getInstance().getChimaeraUseBedSpawn() && player.getBedSpawnLocation() != null) {
if (mcMMO.p.getGeneralConfig().getChimaeraUseBedSpawn() && player.getBedSpawnLocation() != null) {
player.teleport(player.getBedSpawnLocation());
}
else {
@@ -136,12 +135,12 @@ public final class ChimaeraWing {
}
}
player.getInventory().setItemInMainHand(new ItemStack(getChimaeraWing(player.getInventory().getItemInMainHand().getAmount() - Config.getInstance().getChimaeraUseCost())));
player.getInventory().setItemInMainHand(new ItemStack(getChimaeraWing(player.getInventory().getItemInMainHand().getAmount() - mcMMO.p.getGeneralConfig().getChimaeraUseCost())));
player.updateInventory();
mcMMOPlayer.actualizeChimeraWingLastUse();
mcMMOPlayer.setTeleportCommenceLocation(null);
if (Config.getInstance().getChimaeraSoundEnabled()) {
if (mcMMO.p.getGeneralConfig().getChimaeraSoundEnabled()) {
SoundManager.sendSound(player, location, SoundType.CHIMAERA_WING);
}
@@ -149,7 +148,7 @@ public final class ChimaeraWing {
}
public static ItemStack getChimaeraWing(int amount) {
ItemStack itemStack = new ItemStack(Config.getInstance().getChimaeraItem(), amount);
ItemStack itemStack = new ItemStack(mcMMO.p.getGeneralConfig().getChimaeraItem(), amount);
ItemMeta itemMeta = itemStack.getItemMeta();
//noinspection ConstantConditions
@@ -165,8 +164,8 @@ public final class ChimaeraWing {
}
public static ShapelessRecipe getChimaeraWingRecipe() {
Material ingredient = Config.getInstance().getChimaeraItem();
int amount = Config.getInstance().getChimaeraRecipeCost();
Material ingredient = mcMMO.p.getGeneralConfig().getChimaeraItem();
int amount = mcMMO.p.getGeneralConfig().getChimaeraRecipeCost();
ShapelessRecipe chimeraWing = new ShapelessRecipe(new NamespacedKey(mcMMO.p, "Chimera"), getChimaeraWing(1));
chimeraWing.addIngredient(amount, ingredient);

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.experience.XPGainReason;
import com.gmail.nossr50.datatypes.experience.XPGainSource;
import com.gmail.nossr50.datatypes.party.Party;
@@ -9,6 +8,7 @@ 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;
@@ -35,6 +35,7 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.CombatUtils;
import com.gmail.nossr50.util.skills.SkillTools;
import org.bukkit.block.Block;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
@@ -43,6 +44,8 @@ import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerAnimationEvent;
import org.bukkit.event.player.PlayerAnimationType;
import org.bukkit.event.player.PlayerFishEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
@@ -129,12 +132,10 @@ public final class EventUtils {
if(Misc.isNPCEntityExcludingVillagers(entity))
return false;
if (!entity.isValid() || !(entity instanceof LivingEntity)) {
if (!entity.isValid() || !(entity instanceof LivingEntity livingEntity)) {
return false;
}
LivingEntity livingEntity = (LivingEntity) entity;
if (CombatUtils.isInvincible(livingEntity, damage)) {
return false;
}
@@ -211,13 +212,26 @@ public final class EventUtils {
return event;
}
public static FakePlayerAnimationEvent callFakeArmSwingEvent(Player player) {
FakePlayerAnimationEvent event = new FakePlayerAnimationEvent(player);
/**
* 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);
@@ -301,9 +315,9 @@ public final class EventUtils {
PluginManager pluginManager = mcMMO.p.getServer().getPluginManager();
// Support for NoCheat
if (shouldArmSwing) {
callFakeArmSwingEvent(player);
}
//if (shouldArmSwing) {
// callFakeArmSwingEvent(player);
//}
FakeBlockDamageEvent damageEvent = new FakeBlockDamageEvent(player, block, player.getInventory().getItemInMainHand(), true);
pluginManager.callEvent(damageEvent);
@@ -355,7 +369,6 @@ public final class EventUtils {
boolean isCancelled = event.isCancelled();
if (isCancelled) {
party.setLevel(party.getLevel() + levelsChanged);
party.addXp(xpRemoved);
}
@@ -364,14 +377,18 @@ public final class EventUtils {
}
public static boolean handleXpGainEvent(Player player, PrimarySkillType skill, float xpGained, XPGainReason xpGainReason) {
McMMOPlayer mmoPlayer = UserManager.getPlayer(player);
if(mmoPlayer == null)
return true;
McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skill, xpGained, xpGainReason);
mcMMO.p.getServer().getPluginManager().callEvent(event);
boolean isCancelled = event.isCancelled();
if (!isCancelled) {
UserManager.getPlayer(player).addXp(skill, event.getRawXpGained());
UserManager.getPlayer(player).getProfile().registerXpGain(skill, event.getRawXpGained());
mmoPlayer.addXp(skill, event.getRawXpGained());
mmoPlayer.getProfile().registerXpGain(skill, event.getRawXpGained());
}
return !isCancelled;
@@ -391,10 +408,10 @@ public final class EventUtils {
experienceChanged = event.getExperienceChanged();
PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile();
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) {
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
String skillName = primarySkillType.toString();
int playerSkillLevel = playerProfile.getSkillLevel(primarySkillType);
int threshold = Config.getInstance().getHardcoreDeathStatPenaltyLevelThreshold();
int threshold = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyLevelThreshold();
if(playerSkillLevel > threshold) {
playerProfile.modifySkill(primarySkillType, Math.max(threshold, playerSkillLevel - levelChanged.get(skillName)));
playerProfile.removeXp(primarySkillType, experienceChanged.get(skillName));
@@ -440,7 +457,7 @@ public final class EventUtils {
PlayerProfile victimProfile = UserManager.getPlayer(victim).getProfile();
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) {
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
String skillName = primarySkillType.toString();
int victimSkillLevel = victimProfile.getSkillLevel(primarySkillType);
@@ -464,7 +481,7 @@ public final class EventUtils {
}
public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent(Player player, SuperAbilityType ability) {
McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent(player, PrimarySkillType.byAbility(ability));
McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent(player, mcMMO.p.getSkillTools().getPrimarySkillBySuperAbility(ability));
mcMMO.p.getServer().getPluginManager().callEvent(event);
return event;

View File

@@ -1,11 +1,12 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.interactions.NotificationType;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.worldguard.WorldGuardManager;
import com.gmail.nossr50.worldguard.WorldGuardUtils;
import org.bukkit.entity.Player;
@@ -22,8 +23,8 @@ public final class HardcoreManager {
return;
}
double statLossPercentage = Config.getInstance().getHardcoreDeathStatPenaltyPercentage();
int levelThreshold = Config.getInstance().getHardcoreDeathStatPenaltyLevelThreshold();
double statLossPercentage = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyPercentage();
int levelThreshold = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyLevelThreshold();
if(UserManager.getPlayer(player) == null)
return;
@@ -34,8 +35,8 @@ public final class HardcoreManager {
HashMap<String, Integer> levelChanged = new HashMap<>();
HashMap<String, Float> experienceChanged = new HashMap<>();
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) {
if (!primarySkillType.getHardcoreStatLossEnabled()) {
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
if (!mcMMO.p.getGeneralConfig().getHardcoreStatLossEnabled(primarySkillType)) {
levelChanged.put(primarySkillType.toString(), 0);
experienceChanged.put(primarySkillType.toString(), 0F);
continue;
@@ -73,8 +74,8 @@ public final class HardcoreManager {
return;
}
double vampirismStatLeechPercentage = Config.getInstance().getHardcoreVampirismStatLeechPercentage();
int levelThreshold = Config.getInstance().getHardcoreVampirismLevelThreshold();
double vampirismStatLeechPercentage = mcMMO.p.getGeneralConfig().getHardcoreVampirismStatLeechPercentage();
int levelThreshold = mcMMO.p.getGeneralConfig().getHardcoreVampirismLevelThreshold();
if(UserManager.getPlayer(killer) == null || UserManager.getPlayer(victim) == null)
return;
@@ -86,8 +87,8 @@ public final class HardcoreManager {
HashMap<String, Integer> levelChanged = new HashMap<>();
HashMap<String, Float> experienceChanged = new HashMap<>();
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) {
if (!primarySkillType.getHardcoreVampirismEnabled()) {
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
if (!mcMMO.p.getGeneralConfig().getHardcoreVampirismEnabled(primarySkillType)) {
levelChanged.put(primarySkillType.toString(), 0);
experienceChanged.put(primarySkillType.toString(), 0F);
continue;
@@ -135,8 +136,8 @@ public final class HardcoreManager {
public static boolean isStatLossEnabled() {
boolean enabled = false;
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) {
if (primarySkillType.getHardcoreStatLossEnabled()) {
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
if (mcMMO.p.getGeneralConfig().getHardcoreStatLossEnabled(primarySkillType)) {
enabled = true;
break;
}
@@ -153,8 +154,8 @@ public final class HardcoreManager {
public static boolean isVampirismEnabled() {
boolean enabled = false;
for (PrimarySkillType primarySkillType : PrimarySkillType.NON_CHILD_SKILLS) {
if (primarySkillType.getHardcoreVampirismEnabled()) {
for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) {
if (mcMMO.p.getGeneralConfig().getHardcoreVampirismEnabled(primarySkillType)) {
enabled = true;
break;
}

View File

@@ -1,388 +1,388 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.commands.skills.AprilCommand;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.interactions.NotificationType;
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.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.sounds.SoundManager;
import com.gmail.nossr50.util.sounds.SoundType;
import com.gmail.nossr50.util.text.StringUtils;
import com.google.common.collect.ImmutableList;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Statistic;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerStatisticIncrementEvent;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
public final class HolidayManager {
private final ArrayList<String> hasCelebrated;
private final int currentYear;
private static final int START_YEAR = 2011;
private static final List<Color> ALL_COLORS;
private static final List<ChatColor> ALL_CHAT_COLORS;
private static final List<ChatColor> CHAT_FORMATS;
public enum FakeSkillType {
MACHO,
JUMPING,
THROWING,
WRECKING,
CRAFTING,
WALKING,
SWIMMING,
FALLING,
CLIMBING,
FLYING,
DIVING,
PIGGY,
UNKNOWN;
public static FakeSkillType getByName(String skillName) {
for (FakeSkillType type : values()) {
if (type.name().equalsIgnoreCase(skillName)) {
return type;
}
}
return null;
}
public static FakeSkillType getByStatistic(Statistic statistic) {
switch (statistic) {
case DAMAGE_TAKEN:
return FakeSkillType.MACHO;
case JUMP:
return FakeSkillType.JUMPING;
case DROP:
return FakeSkillType.THROWING;
case MINE_BLOCK:
case BREAK_ITEM:
return FakeSkillType.WRECKING;
case CRAFT_ITEM:
return FakeSkillType.CRAFTING;
case WALK_ONE_CM:
return FakeSkillType.WALKING;
case SWIM_ONE_CM:
return FakeSkillType.SWIMMING;
case FALL_ONE_CM:
return FakeSkillType.FALLING;
case CLIMB_ONE_CM:
return FakeSkillType.CLIMBING;
case FLY_ONE_CM:
return FakeSkillType.FLYING;
case WALK_UNDER_WATER_ONE_CM:
return FakeSkillType.DIVING;
case PIG_ONE_CM:
return FakeSkillType.PIGGY;
default:
return FakeSkillType.UNKNOWN;
}
}
}
public final Set<Statistic> movementStatistics = EnumSet.of(
Statistic.WALK_ONE_CM, Statistic.SWIM_ONE_CM, Statistic.FALL_ONE_CM,
Statistic.CLIMB_ONE_CM, Statistic.FLY_ONE_CM, Statistic.WALK_UNDER_WATER_ONE_CM,
Statistic.PIG_ONE_CM);
static {
List<Color> colors = new ArrayList<>();
List<ChatColor> chatColors = new ArrayList<>();
List<ChatColor> chatFormats = new ArrayList<>();
for (ChatColor color : ChatColor.values()) {
if (color.isColor()) {
chatColors.add(color);
}
else {
chatFormats.add(color);
}
}
// for (DyeColor color : DyeColor.values()) {
// colors.add(color.getFireworkColor());
// }
Collections.shuffle(chatColors, Misc.getRandom());
Collections.shuffle(colors, Misc.getRandom());
Collections.shuffle(chatFormats, Misc.getRandom());
ALL_CHAT_COLORS = ImmutableList.copyOf(chatColors);
ALL_COLORS = ImmutableList.copyOf(colors);
CHAT_FORMATS = ImmutableList.copyOf(chatFormats);
}
// This gets called onEnable
public HolidayManager() {
currentYear = Calendar.getInstance().get(Calendar.YEAR);
File anniversaryFile = new File(mcMMO.getFlatFileDirectory(), "anniversary." + currentYear + ".yml");
if (!anniversaryFile.exists()) {
try {
anniversaryFile.createNewFile();
}
catch (IOException ex) {
mcMMO.p.getLogger().severe(ex.toString());
}
}
hasCelebrated = new ArrayList<>();
try {
hasCelebrated.clear();
BufferedReader reader = new BufferedReader(new FileReader(anniversaryFile.getPath()));
String line = reader.readLine();
while (line != null) {
hasCelebrated.add(line);
line = reader.readLine();
}
reader.close();
}
catch (Exception ex) {
mcMMO.p.getLogger().severe(ex.toString());
}
cleanupFiles();
}
private void cleanupFiles() {
File FlatFileDir = new File(mcMMO.getFlatFileDirectory());
File legacy = new File(FlatFileDir, "anniversary.yml");
List<File> toDelete = new ArrayList<>();
if (legacy.exists()) {
toDelete.add(legacy);
}
Pattern pattern = Pattern.compile("anniversary\\.(?:.+)\\.yml");
for (String fileName : FlatFileDir.list()) {
if (!pattern.matcher(fileName).matches() || fileName.equals("anniversary." + currentYear + ".yml")) {
continue;
}
File file = new File(FlatFileDir, fileName);
if (file.isDirectory()) {
continue;
}
toDelete.add(file);
}
for (File file : toDelete) {
if (file.delete()) {
mcMMO.p.debug("Deleted: " + file.getName());
}
}
}
// This gets called onDisable
public void saveAnniversaryFiles() {
mcMMO.p.debug("Saving anniversary files...");
String anniversaryFilePath = mcMMO.getFlatFileDirectory() + "anniversary." + currentYear + ".yml";
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(anniversaryFilePath));
for (String player : hasCelebrated) {
writer.write(player);
writer.newLine();
}
writer.close();
}
catch (Exception ex) {
mcMMO.p.getLogger().severe(ex.toString());
}
}
// This gets called from /mcmmo command
public void anniversaryCheck(final CommandSender sender) {
GregorianCalendar anniversaryStart = new GregorianCalendar(currentYear, Calendar.FEBRUARY, 3);
GregorianCalendar anniversaryEnd = new GregorianCalendar(currentYear, Calendar.FEBRUARY, 6);
GregorianCalendar day = new GregorianCalendar();
if (hasCelebrated.contains(sender.getName())) {
return;
}
if (!getDateRange(day.getTime(), anniversaryStart.getTime(), anniversaryEnd.getTime())) {
return;
}
sender.sendMessage(LocaleLoader.getString("Holiday.Anniversary", (currentYear - START_YEAR)));
/*if (sender instanceof Player) {
final int firework_amount = 10;
for (int i = 0; i < firework_amount; i++) {
int delay = (int) (Misc.getRandom().nextDouble() * 3 * Misc.TICK_CONVERSION_FACTOR) + 4;
mcMMO.p.getServer().getScheduler().runTaskLater(mcMMO.p, new Runnable() {
@Override
public void run() {
spawnFireworks((Player) sender);
}
}, delay);
}
}*/
// else {
/*
* Credit: http://www.geocities.com/spunk1111/
* (good luck finding that in 3 years heh)
* .''. . *''* :_\/_: .
* :_\/_: _\(/_ .:.*_\/_* : /\ : .'.:.'.
* .''.: /\ : /)\ ':'* /\ * : '..'. -=:o:=-
* :_\/_:'.:::. ' *''* * '.\'/.'_\(/_ '.':'.'
* : /\ : ::::: *_\/_* -= o =- /)\ '
* '..' ':::' * /\ * .'/.\'. ' *
* * *..* : *
* * * *
* * * *
*/
/*
* Color map
* AAAA D GGGG JJJJJJ K
* AAAAAA DDDDD EEEGGGGGG JJJJJJ KKKKKKK
* BBBBAAAAAA DDD EEEGGGGGG I JJJJJ KKKKKKK
* BBBBBBACCCCC D FFFF G IIIIIIIHHHHH KKKKKKK
* BBBBBB CCCCC FFFFFF IIIIIII HHH K
* BBBB CCCCC FFFFFF IIIIIII H k
* b FFFF I k
* b i k
* b i k
*/
Object[] colorParams = new Object[]{chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose()};
sender.sendMessage(String.format(" %1$s.''. %4$s. %7$s*''* %10$s:_\\/_: %11$s.", colorParams));
sender.sendMessage(String.format(" %1$s:_\\/_: %4$s_\\(/_ %5$s.:.%7$s*_\\/_* %10$s: /\\ : %11$s.'.:.'.", colorParams));
sender.sendMessage(String.format(" %2$s.''.%1$s: /\\ : %4$s/)\\ %5$s':'%7$s* /\\ * %9$s: %10$s'..'. %11$s-=:o:=-", colorParams));
sender.sendMessage(String.format("%2$s:_\\/_:%1$s'%3$s.:::. %4$s' %6$s*''* %7$s* %9$s'.\\'/.'%8$s_\\(/_ %11$s'.':'.'", colorParams));
sender.sendMessage(String.format("%2$s: /\\ : %3$s::::: %6$s*_\\/_* %9$s-= o =-%8$s /)\\ %11$s'", colorParams));
sender.sendMessage(String.format(" %2$s'..' %3$s':::' %6$s* /\\ * %9$s.'/.\\'. %8$s' %11$s*", colorParams));
sender.sendMessage(String.format(" %2$s* %6$s*..* %9$s: %11$s*", colorParams));
sender.sendMessage(String.format(" %2$s* %9$s* %11$s*", colorParams));
sender.sendMessage(String.format(" %2$s* %9$s* %11$s*", colorParams));
// }
hasCelebrated.add(sender.getName());
}
public boolean getDateRange(Date date, Date start, Date end) {
return !(date.before(start) || date.after(end));
}
// public void spawnFireworks(Player player) {
// int power = Misc.getRandom().nextInt(3) + 1;
// Type fireworkType = Type.values()[Misc.getRandom().nextInt(Type.values().length)];
// double varX = Misc.getRandom().nextGaussian() * 3;
// double varZ = Misc.getRandom().nextGaussian() * 3;
//package com.gmail.nossr50.util;
//
// Firework fireworks = (Firework) player.getWorld().spawnEntity(player.getLocation().add(varX, 0, varZ), EntityType.FIREWORK);
// FireworkMeta fireworkmeta = fireworks.getFireworkMeta();
// FireworkEffect effect = FireworkEffect.builder().flicker(Misc.getRandom().nextBoolean()).withColor(colorChoose()).withFade(colorChoose()).with(fireworkType).trail(Misc.getRandom().nextBoolean()).build();
// fireworkmeta.addEffect(effect);
// fireworkmeta.setPower(power);
// fireworks.setFireworkMeta(fireworkmeta);
//import com.gmail.nossr50.commands.skills.AprilCommand;
//import com.gmail.nossr50.config.Config;
//import com.gmail.nossr50.datatypes.interactions.NotificationType;
//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.util.player.NotificationManager;
//import com.gmail.nossr50.util.player.UserManager;
//import com.gmail.nossr50.util.sounds.SoundManager;
//import com.gmail.nossr50.util.sounds.SoundType;
//import com.gmail.nossr50.util.text.StringUtils;
//import com.google.common.collect.ImmutableList;
//import org.bukkit.ChatColor;
//import org.bukkit.Color;
//import org.bukkit.Statistic;
//import org.bukkit.command.CommandSender;
//import org.bukkit.command.PluginCommand;
//import org.bukkit.entity.Player;
//import org.bukkit.event.player.PlayerStatisticIncrementEvent;
//
//import java.io.*;
//import java.util.*;
//import java.util.regex.Pattern;
//
//public final class HolidayManager {
// private final ArrayList<String> hasCelebrated;
// private final int currentYear;
// private static final int START_YEAR = 2011;
//
// private static final List<Color> ALL_COLORS;
// private static final List<ChatColor> ALL_CHAT_COLORS;
// private static final List<ChatColor> CHAT_FORMATS;
//
// public enum FakeSkillType {
// MACHO,
// JUMPING,
// THROWING,
// WRECKING,
// CRAFTING,
// WALKING,
// SWIMMING,
// FALLING,
// CLIMBING,
// FLYING,
// DIVING,
// PIGGY,
// UNKNOWN;
//
// public static FakeSkillType getByName(String skillName) {
// for (FakeSkillType type : values()) {
// if (type.name().equalsIgnoreCase(skillName)) {
// return type;
// }
// }
// return null;
// }
//
// public static FakeSkillType getByStatistic(Statistic statistic) {
// switch (statistic) {
// case DAMAGE_TAKEN:
// return FakeSkillType.MACHO;
// case JUMP:
// return FakeSkillType.JUMPING;
// case DROP:
// return FakeSkillType.THROWING;
// case MINE_BLOCK:
// case BREAK_ITEM:
// return FakeSkillType.WRECKING;
// case CRAFT_ITEM:
// return FakeSkillType.CRAFTING;
// case WALK_ONE_CM:
// return FakeSkillType.WALKING;
// case SWIM_ONE_CM:
// return FakeSkillType.SWIMMING;
// case FALL_ONE_CM:
// return FakeSkillType.FALLING;
// case CLIMB_ONE_CM:
// return FakeSkillType.CLIMBING;
// case FLY_ONE_CM:
// return FakeSkillType.FLYING;
// case WALK_UNDER_WATER_ONE_CM:
// return FakeSkillType.DIVING;
// case PIG_ONE_CM:
// return FakeSkillType.PIGGY;
// default:
// return FakeSkillType.UNKNOWN;
// }
// }
// }
private static List<Color> colorChoose() {
return ALL_COLORS.subList(0, Math.max(Misc.getRandom().nextInt(ALL_COLORS.size() + 1), 1));
}
private static String chatColorChoose() {
StringBuilder ret = new StringBuilder(ALL_CHAT_COLORS.get(Misc.getRandom().nextInt(ALL_CHAT_COLORS.size())).toString());
for (ChatColor chatFormat : CHAT_FORMATS) {
if (Misc.getRandom().nextInt(CHAT_FORMATS.size()) == 0) {
ret.append(chatFormat);
}
}
return ret.toString();
}
public boolean isAprilFirst() {
if(!Config.getInstance().isAprilFoolsAllowed())
return false;
GregorianCalendar aprilFirst = new GregorianCalendar(currentYear, Calendar.APRIL, 1);
GregorianCalendar aprilSecond = new GregorianCalendar(currentYear, Calendar.APRIL, 2);
GregorianCalendar day = new GregorianCalendar();
return getDateRange(day.getTime(), aprilFirst.getTime(), aprilSecond.getTime());
}
public boolean nearingAprilFirst() {
if(!Config.getInstance().isAprilFoolsAllowed())
return false;
GregorianCalendar start = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.MARCH, 28);
GregorianCalendar end = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.APRIL, 2);
GregorianCalendar day = new GregorianCalendar();
return mcMMO.getHolidayManager().getDateRange(day.getTime(), start.getTime(), end.getTime());
}
public void handleStatisticEvent(PlayerStatisticIncrementEvent event) {
Player player = event.getPlayer();
Statistic statistic = event.getStatistic();
int newValue = event.getNewValue();
int modifier;
switch (statistic) {
case DAMAGE_TAKEN:
modifier = 500;
break;
case JUMP:
modifier = 500;
break;
case DROP:
modifier = 200;
break;
case MINE_BLOCK:
case BREAK_ITEM:
modifier = 500;
break;
case CRAFT_ITEM:
modifier = 100;
break;
default:
return;
}
if (newValue % modifier == 0) {
mcMMO.getHolidayManager().levelUpApril(player, FakeSkillType.getByStatistic(statistic));
}
}
public void levelUpApril(Player player, FakeSkillType fakeSkillType) {
if(!Config.getInstance().isAprilFoolsAllowed())
return;
final McMMOPlayer mmoPlayer = UserManager.getPlayer(player);
if (mmoPlayer == null) return;
int levelTotal = Misc.getRandom().nextInt(1 + mmoPlayer.getSkillLevel(PrimarySkillType.MINING)) + 1;
SoundManager.sendSound(player, player.getLocation(), SoundType.LEVEL_UP);
NotificationManager.sendPlayerInformation(player, NotificationType.HOLIDAY, "Holiday.AprilFools.Levelup", StringUtils.getCapitalized(fakeSkillType.toString()), String.valueOf(levelTotal));
// ParticleEffectUtils.fireworkParticleShower(player, ALL_COLORS.get(Misc.getRandom().nextInt(ALL_COLORS.size())));
}
public void registerAprilCommand() {
if(!Config.getInstance().isAprilFoolsAllowed())
return;
PluginCommand command = mcMMO.p.getCommand("crafting");
command.setExecutor(new AprilCommand());
}
}
//
// public final Set<Statistic> movementStatistics = EnumSet.of(
// Statistic.WALK_ONE_CM, Statistic.SWIM_ONE_CM, Statistic.FALL_ONE_CM,
// Statistic.CLIMB_ONE_CM, Statistic.FLY_ONE_CM, Statistic.WALK_UNDER_WATER_ONE_CM,
// Statistic.PIG_ONE_CM);
//
// static {
// List<Color> colors = new ArrayList<>();
// List<ChatColor> chatColors = new ArrayList<>();
// List<ChatColor> chatFormats = new ArrayList<>();
//
// for (ChatColor color : ChatColor.values()) {
// if (color.isColor()) {
// chatColors.add(color);
// }
// else {
// chatFormats.add(color);
// }
// }
//
//// for (DyeColor color : DyeColor.values()) {
//// colors.add(color.getFireworkColor());
//// }
//
// Collections.shuffle(chatColors, Misc.getRandom());
// Collections.shuffle(colors, Misc.getRandom());
// Collections.shuffle(chatFormats, Misc.getRandom());
//
// ALL_CHAT_COLORS = ImmutableList.copyOf(chatColors);
// ALL_COLORS = ImmutableList.copyOf(colors);
// CHAT_FORMATS = ImmutableList.copyOf(chatFormats);
// }
//
// // This gets called onEnable
// public HolidayManager() {
// currentYear = Calendar.getInstance().get(Calendar.YEAR);
//
// File anniversaryFile = new File(mcMMO.getFlatFileDirectory(), "anniversary." + currentYear + ".yml");
//
// if (!anniversaryFile.exists()) {
// try {
// anniversaryFile.createNewFile();
// }
// catch (IOException ex) {
// mcMMO.p.getLogger().severe(ex.toString());
// }
// }
//
// hasCelebrated = new ArrayList<>();
//
// try {
// hasCelebrated.clear();
// BufferedReader reader = new BufferedReader(new FileReader(anniversaryFile.getPath()));
// String line = reader.readLine();
//
// while (line != null) {
// hasCelebrated.add(line);
// line = reader.readLine();
// }
//
// reader.close();
// }
// catch (Exception ex) {
// mcMMO.p.getLogger().severe(ex.toString());
// }
//
// cleanupFiles();
// }
//
// private void cleanupFiles() {
// File FlatFileDir = new File(mcMMO.getFlatFileDirectory());
// File legacy = new File(FlatFileDir, "anniversary.yml");
// List<File> toDelete = new ArrayList<>();
//
// if (legacy.exists()) {
// toDelete.add(legacy);
// }
//
// Pattern pattern = Pattern.compile("anniversary\\.(?:.+)\\.yml");
//
// for (String fileName : FlatFileDir.list()) {
// if (!pattern.matcher(fileName).matches() || fileName.equals("anniversary." + currentYear + ".yml")) {
// continue;
// }
//
// File file = new File(FlatFileDir, fileName);
//
// if (file.isDirectory()) {
// continue;
// }
//
// toDelete.add(file);
// }
//
// for (File file : toDelete) {
// if (file.delete()) {
// mcMMO.p.debug("Deleted: " + file.getName());
// }
// }
// }
//
// // This gets called onDisable
// public void saveAnniversaryFiles() {
// mcMMO.p.debug("Saving anniversary files...");
// String anniversaryFilePath = mcMMO.getFlatFileDirectory() + "anniversary." + currentYear + ".yml";
//
// try {
// BufferedWriter writer = new BufferedWriter(new FileWriter(anniversaryFilePath));
// for (String player : hasCelebrated) {
// writer.write(player);
// writer.newLine();
// }
// writer.close();
// }
// catch (Exception ex) {
// mcMMO.p.getLogger().severe(ex.toString());
// }
// }
//
// // This gets called from /mcmmo command
// public void anniversaryCheck(final CommandSender sender) {
// GregorianCalendar anniversaryStart = new GregorianCalendar(currentYear, Calendar.FEBRUARY, 3);
// GregorianCalendar anniversaryEnd = new GregorianCalendar(currentYear, Calendar.FEBRUARY, 6);
// GregorianCalendar day = new GregorianCalendar();
//
// if (hasCelebrated.contains(sender.getName())) {
// return;
// }
//
// if (!getDateRange(day.getTime(), anniversaryStart.getTime(), anniversaryEnd.getTime())) {
// return;
// }
//
// sender.sendMessage(LocaleLoader.getString("Holiday.Anniversary", (currentYear - START_YEAR)));
// /*if (sender instanceof Player) {
// final int firework_amount = 10;
// for (int i = 0; i < firework_amount; i++) {
// int delay = (int) (Misc.getRandom().nextDouble() * 3 * Misc.TICK_CONVERSION_FACTOR) + 4;
// mcMMO.p.getServer().getScheduler().runTaskLater(mcMMO.p, new Runnable() {
// @Override
// public void run() {
// spawnFireworks((Player) sender);
// }
// }, delay);
// }
// }*/
//// else {
// /*
// * Credit: http://www.geocities.com/spunk1111/
// * (good luck finding that in 3 years heh)
// * .''. . *''* :_\/_: .
// * :_\/_: _\(/_ .:.*_\/_* : /\ : .'.:.'.
// * .''.: /\ : /)\ ':'* /\ * : '..'. -=:o:=-
// * :_\/_:'.:::. ' *''* * '.\'/.'_\(/_ '.':'.'
// * : /\ : ::::: *_\/_* -= o =- /)\ '
// * '..' ':::' * /\ * .'/.\'. ' *
// * * *..* : *
// * * * *
// * * * *
// */
//
// /*
// * Color map
// * AAAA D GGGG JJJJJJ K
// * AAAAAA DDDDD EEEGGGGGG JJJJJJ KKKKKKK
// * BBBBAAAAAA DDD EEEGGGGGG I JJJJJ KKKKKKK
// * BBBBBBACCCCC D FFFF G IIIIIIIHHHHH KKKKKKK
// * BBBBBB CCCCC FFFFFF IIIIIII HHH K
// * BBBB CCCCC FFFFFF IIIIIII H k
// * b FFFF I k
// * b i k
// * b i k
// */
// Object[] colorParams = new Object[]{chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose(), chatColorChoose()};
// sender.sendMessage(String.format(" %1$s.''. %4$s. %7$s*''* %10$s:_\\/_: %11$s.", colorParams));
// sender.sendMessage(String.format(" %1$s:_\\/_: %4$s_\\(/_ %5$s.:.%7$s*_\\/_* %10$s: /\\ : %11$s.'.:.'.", colorParams));
// sender.sendMessage(String.format(" %2$s.''.%1$s: /\\ : %4$s/)\\ %5$s':'%7$s* /\\ * %9$s: %10$s'..'. %11$s-=:o:=-", colorParams));
// sender.sendMessage(String.format("%2$s:_\\/_:%1$s'%3$s.:::. %4$s' %6$s*''* %7$s* %9$s'.\\'/.'%8$s_\\(/_ %11$s'.':'.'", colorParams));
// sender.sendMessage(String.format("%2$s: /\\ : %3$s::::: %6$s*_\\/_* %9$s-= o =-%8$s /)\\ %11$s'", colorParams));
// sender.sendMessage(String.format(" %2$s'..' %3$s':::' %6$s* /\\ * %9$s.'/.\\'. %8$s' %11$s*", colorParams));
// sender.sendMessage(String.format(" %2$s* %6$s*..* %9$s: %11$s*", colorParams));
// sender.sendMessage(String.format(" %2$s* %9$s* %11$s*", colorParams));
// sender.sendMessage(String.format(" %2$s* %9$s* %11$s*", colorParams));
//// }
//
// hasCelebrated.add(sender.getName());
// }
//
// public boolean getDateRange(Date date, Date start, Date end) {
// return !(date.before(start) || date.after(end));
// }
//
//// public void spawnFireworks(Player player) {
//// int power = Misc.getRandom().nextInt(3) + 1;
//// Type fireworkType = Type.values()[Misc.getRandom().nextInt(Type.values().length)];
//// double varX = Misc.getRandom().nextGaussian() * 3;
//// double varZ = Misc.getRandom().nextGaussian() * 3;
////
//// Firework fireworks = (Firework) player.getWorld().spawnEntity(player.getLocation().add(varX, 0, varZ), EntityType.FIREWORK);
//// FireworkMeta fireworkmeta = fireworks.getFireworkMeta();
//// FireworkEffect effect = FireworkEffect.builder().flicker(Misc.getRandom().nextBoolean()).withColor(colorChoose()).withFade(colorChoose()).with(fireworkType).trail(Misc.getRandom().nextBoolean()).build();
//// fireworkmeta.addEffect(effect);
//// fireworkmeta.setPower(power);
//// fireworks.setFireworkMeta(fireworkmeta);
//// }
//
// private static List<Color> colorChoose() {
// return ALL_COLORS.subList(0, Math.max(Misc.getRandom().nextInt(ALL_COLORS.size() + 1), 1));
// }
//
// private static String chatColorChoose() {
// StringBuilder ret = new StringBuilder(ALL_CHAT_COLORS.get(Misc.getRandom().nextInt(ALL_CHAT_COLORS.size())).toString());
//
// for (ChatColor chatFormat : CHAT_FORMATS) {
// if (Misc.getRandom().nextInt(CHAT_FORMATS.size()) == 0) {
// ret.append(chatFormat);
// }
// }
//
// return ret.toString();
// }
//
// public boolean isAprilFirst() {
// if(!Config.getInstance().isAprilFoolsAllowed())
// return false;
//
// GregorianCalendar aprilFirst = new GregorianCalendar(currentYear, Calendar.APRIL, 1);
// GregorianCalendar aprilSecond = new GregorianCalendar(currentYear, Calendar.APRIL, 2);
// GregorianCalendar day = new GregorianCalendar();
// return getDateRange(day.getTime(), aprilFirst.getTime(), aprilSecond.getTime());
// }
//
// public boolean nearingAprilFirst() {
// if(!Config.getInstance().isAprilFoolsAllowed())
// return false;
//
// GregorianCalendar start = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.MARCH, 28);
// GregorianCalendar end = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.APRIL, 2);
// GregorianCalendar day = new GregorianCalendar();
//
// return mcMMO.getHolidayManager().getDateRange(day.getTime(), start.getTime(), end.getTime());
// }
//
// public void handleStatisticEvent(PlayerStatisticIncrementEvent event) {
// Player player = event.getPlayer();
// Statistic statistic = event.getStatistic();
// int newValue = event.getNewValue();
//
// int modifier;
// switch (statistic) {
// case DAMAGE_TAKEN:
// modifier = 500;
// break;
// case JUMP:
// modifier = 500;
// break;
// case DROP:
// modifier = 200;
// break;
// case MINE_BLOCK:
// case BREAK_ITEM:
// modifier = 500;
// break;
// case CRAFT_ITEM:
// modifier = 100;
// break;
// default:
// return;
// }
//
// if (newValue % modifier == 0) {
// mcMMO.getHolidayManager().levelUpApril(player, FakeSkillType.getByStatistic(statistic));
// }
// }
//
// public void levelUpApril(Player player, FakeSkillType fakeSkillType) {
// if(!Config.getInstance().isAprilFoolsAllowed())
// return;
//
// final McMMOPlayer mmoPlayer = UserManager.getPlayer(player);
// if (mmoPlayer == null) return;
//
// int levelTotal = Misc.getRandom().nextInt(1 + mmoPlayer.getSkillLevel(PrimarySkillType.MINING)) + 1;
// SoundManager.sendSound(player, player.getLocation(), SoundType.LEVEL_UP);
// NotificationManager.sendPlayerInformation(player, NotificationType.HOLIDAY, "Holiday.AprilFools.Levelup", StringUtils.getCapitalized(fakeSkillType.toString()), String.valueOf(levelTotal));
//// ParticleEffectUtils.fireworkParticleShower(player, ALL_COLORS.get(Misc.getRandom().nextInt(ALL_COLORS.size())));
// }
//
// public void registerAprilCommand() {
// if(!Config.getInstance().isAprilFoolsAllowed())
// return;
//
// PluginCommand command = mcMMO.p.getCommand("crafting");
// command.setExecutor(new AprilCommand());
// }
//}

View File

@@ -1,13 +1,12 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.config.party.ItemWeightConfig;
import com.gmail.nossr50.datatypes.treasure.EnchantmentWrapper;
import com.gmail.nossr50.datatypes.treasure.FishingTreasureBook;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.smelting.Smelting;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
@@ -186,7 +185,7 @@ public final class ItemUtils {
* @return true if the item counts as unarmed, false otherwise
*/
public static boolean isUnarmed(ItemStack item) {
if (Config.getInstance().getUnarmedItemsAsUnarmed()) {
if (mcMMO.p.getGeneralConfig().getUnarmedItemsAsUnarmed()) {
return !isMinecraftTool(item);
}
@@ -342,7 +341,7 @@ public final class ItemUtils {
}
public static boolean isSmeltable(ItemStack item) {
return item != null && item.getType().isBlock() && MaterialUtils.isOre(item.getType());
return item != null && Smelting.getSmeltXP(item) >= 1;
}
public static boolean isSmelted(ItemStack item) {
@@ -422,6 +421,7 @@ public final class ItemUtils {
case CHORUS_FLOWER:
case POTATO:
case BEETROOT:
case BEETROOTS:
case BEETROOT_SEEDS:
case NETHER_WART:
case BROWN_MUSHROOM:
@@ -510,32 +510,34 @@ public final class ItemUtils {
* @return true if the item is a woodcutting drop, false otherwise
*/
public static boolean isWoodcuttingDrop(ItemStack item) {
switch (item.getType()) {
case ACACIA_LOG:
case BIRCH_LOG:
case DARK_OAK_LOG:
case JUNGLE_LOG:
case OAK_LOG:
case SPRUCE_LOG:
case STRIPPED_ACACIA_LOG:
case STRIPPED_BIRCH_LOG:
case STRIPPED_DARK_OAK_LOG:
case STRIPPED_JUNGLE_LOG:
case STRIPPED_OAK_LOG:
case STRIPPED_SPRUCE_LOG:
case ACACIA_SAPLING:
case SPRUCE_SAPLING:
case BIRCH_SAPLING:
case DARK_OAK_SAPLING:
case JUNGLE_SAPLING:
case OAK_SAPLING:
case ACACIA_LEAVES:
case BIRCH_LEAVES:
case DARK_OAK_LEAVES:
case JUNGLE_LEAVES:
case OAK_LEAVES:
case SPRUCE_LEAVES:
case APPLE:
switch (item.getType().toString()) {
case "ACACIA_LOG":
case "BIRCH_LOG":
case "DARK_OAK_LOG":
case "JUNGLE_LOG":
case "OAK_LOG":
case "SPRUCE_LOG":
case "STRIPPED_ACACIA_LOG":
case "STRIPPED_BIRCH_LOG":
case "STRIPPED_DARK_OAK_LOG":
case "STRIPPED_JUNGLE_LOG":
case "STRIPPED_OAK_LOG":
case "STRIPPED_SPRUCE_LOG":
case "STRIPPED_MANGROVE_LOG":
case "ACACIA_SAPLING":
case "SPRUCE_SAPLING":
case "BIRCH_SAPLING":
case "DARK_OAK_SAPLING":
case "JUNGLE_SAPLING":
case "OAK_SAPLING":
case "ACACIA_LEAVES":
case "BIRCH_LEAVES":
case "DARK_OAK_LEAVES":
case "JUNGLE_LEAVES":
case "OAK_LEAVES":
case "SPRUCE_LEAVES":
case "BEE_NEST":
case "APPLE":
return true;
default:
@@ -622,7 +624,7 @@ public final class ItemUtils {
if(itemMeta == null)
return;
itemMeta.addEnchant(Enchantment.DIG_SPEED, existingEnchantLevel + AdvancedConfig.getInstance().getEnchantBuff(), true);
itemMeta.addEnchant(Enchantment.DIG_SPEED, existingEnchantLevel + mcMMO.p.getAdvancedConfig().getEnchantBuff(), true);
itemStack.setItemMeta(itemMeta);
}

View File

@@ -24,6 +24,7 @@ public class MaterialMapStore {
private final @NotNull HashSet<String> blockCrackerWhiteList;
private final @NotNull HashSet<String> canMakeShroomyWhiteList;
private final @NotNull HashSet<String> multiBlockPlant;
private final @NotNull HashSet<String> multiBlockHangingPlant;
private final @NotNull HashSet<String> foodItemWhiteList;
private final @NotNull HashSet<String> glassBlocks;
@@ -71,6 +72,7 @@ public class MaterialMapStore {
blockCrackerWhiteList = new HashSet<>();
canMakeShroomyWhiteList = new HashSet<>();
multiBlockPlant = new HashSet<>();
multiBlockHangingPlant = new HashSet<>();
foodItemWhiteList = new HashSet<>();
glassBlocks = new HashSet<>();
@@ -121,6 +123,7 @@ public class MaterialMapStore {
fillBlockCrackerWhiteList();
fillShroomyWhiteList();
fillMultiBlockPlantSet();
fillMultiBlockHangingPlantSet();
fillFoodWhiteList();
fillGlassBlockWhiteList();
fillArmors();
@@ -137,6 +140,10 @@ public class MaterialMapStore {
return multiBlockPlant.contains(material.getKey().getKey());
}
public boolean isMultiBlockHangingPlant(@NotNull Material material) {
return multiBlockHangingPlant.contains(material.getKey().getKey());
}
public boolean isAbilityActivationBlackListed(@NotNull Material material)
{
return abilityBlackList.contains(material.getKey().getKey());
@@ -206,16 +213,33 @@ public class MaterialMapStore {
ores.add("gold_ore");
ores.add("iron_ore");
ores.add("lapis_ore");
ores.add("lapis_lazuli_ore");
ores.add("redstone_ore");
ores.add("emerald_ore");
ores.add("ancient_debris");
ores.add("nether_gold_ore");
ores.add("gilded_blackstone");
//1.17 Mining Ore Blocks
ores.add("deepslate_redstone_ore");
ores.add("deepslate_copper_ore");
ores.add("deepslate_coal_ore");
ores.add("deepslate_diamond_ore");
ores.add("deepslate_emerald_ore");
ores.add("deepslate_iron_ore");
ores.add("deepslate_gold_ore");
// ores.add("deepslate_lapis_lazuli_ore");
ores.add("deepslate_lapis_ore");
ores.add("copper_ore");
}
private void fillIntendedTools() {
intendedToolPickAxe.addAll(ores);
intendedToolPickAxe.add("lapis_lazuli_ore");
intendedToolPickAxe.add("packed_mud");
intendedToolPickAxe.add("mud_bricks");
intendedToolPickAxe.add("reinforced_deepslate");
intendedToolPickAxe.add("ice");
intendedToolPickAxe.add("packed_ice");
intendedToolPickAxe.add("blue_ice");
@@ -307,10 +331,6 @@ public class MaterialMapStore {
intendedToolPickAxe.add("stone_button");
intendedToolPickAxe.add("stone_pressure_plate");
intendedToolPickAxe.add("terracotta");
intendedToolPickAxe.add("amethyst_bud");
intendedToolPickAxe.add("amethyst_cluster");
intendedToolPickAxe.add("block_of_amethyst");
intendedToolPickAxe.add("budding_amethyst");
intendedToolPickAxe.add("ancient_debris");
intendedToolPickAxe.add("crying_obsidian");
intendedToolPickAxe.add("glowing_obsidian"); //be
@@ -395,6 +415,18 @@ public class MaterialMapStore {
intendedToolPickAxe.add("waxed_cut_copper_stairs");
intendedToolPickAxe.add("waxed_lightly_weathered_cut_copper_stairs");
//1.17 Mining (non-ores)
intendedToolPickAxe.add("calcite");
intendedToolPickAxe.add("smooth_basalt");
intendedToolPickAxe.add("block_of_amethyst");
intendedToolPickAxe.add("small_amethyst_bud");
intendedToolPickAxe.add("medium_amethyst_bud");
intendedToolPickAxe.add("large_amethyst_bud");
intendedToolPickAxe.add("amethyst_cluster");
intendedToolPickAxe.add("budding_amethyst");
intendedToolPickAxe.add("deepslate");
intendedToolPickAxe.add("cobbled_deepslate");
intendedToolPickAxe.add("tuff");
}
private void fillArmors() {
@@ -424,6 +456,7 @@ public class MaterialMapStore {
enchantables.addAll(pickAxes);
enchantables.addAll(tridents);
enchantables.addAll(bows);
enchantables.addAll(crossbows);
enchantables.add("shears");
enchantables.add("fishing_rod");
@@ -951,8 +984,12 @@ public class MaterialMapStore {
multiBlockPlant.add("large_fern");
multiBlockPlant.add("tall_grass");
multiBlockPlant.add("bamboo");
multiBlockPlant.add("weeping_vines_plant");
multiBlockPlant.add("twisted_vines_plant");
}
private void fillMultiBlockHangingPlantSet() {
multiBlockHangingPlant.add("weeping_vines_plant");
multiBlockHangingPlant.add("twisted_vines_plant");
multiBlockHangingPlant.add("cave_vines_plant");
}
private void fillShroomyWhiteList()
@@ -985,6 +1022,10 @@ public class MaterialMapStore {
treeFellerDestructibleWhiteList.add("dark_oak_leaves");
treeFellerDestructibleWhiteList.add("jungle_leaves");
treeFellerDestructibleWhiteList.add("spruce_leaves");
treeFellerDestructibleWhiteList.add("azalea_leaves");
treeFellerDestructibleWhiteList.add("flowering_azalea_leaves");
treeFellerDestructibleWhiteList.add("mangrove_leaves");
treeFellerDestructibleWhiteList.add("mangrove_roots");
treeFellerDestructibleWhiteList.add("nether_wart_block");
treeFellerDestructibleWhiteList.add("warped_wart_block");
treeFellerDestructibleWhiteList.add("brown_mushroom_block");
@@ -1130,8 +1171,6 @@ public class MaterialMapStore {
private void fillToolBlackList()
{
//TODO: Add anvils / missing logs
//TODO: Reorganize this list, can we also dynamically populate some of this?
toolBlackList.add("black_bed");
toolBlackList.add("blue_bed");
toolBlackList.add("brown_bed");
@@ -1240,6 +1279,9 @@ public class MaterialMapStore {
toolBlackList.add("stripped_oak_wood");
toolBlackList.add("stripped_spruce_log");
toolBlackList.add("stripped_spruce_wood");
toolBlackList.add("mangrove_wood");
toolBlackList.add("mangrove_log");
toolBlackList.add("stripped_mangrove_log");
toolBlackList.add("acacia_log");
toolBlackList.add("acacia_wood");
toolBlackList.add("birch_log");
@@ -1265,13 +1307,14 @@ public class MaterialMapStore {
toolBlackList.add("stonecutter");
toolBlackList.add("lodestone");
toolBlackList.add("respawn_anchor");
toolBlackList.add("sweet_berry_bush");
}
public boolean isIntendedToolPickaxe(Material material) {
public boolean isIntendedToolPickaxe(@NotNull Material material) {
return intendedToolPickAxe.contains(material.getKey().getKey());
}
public boolean isIntendedToolPickaxe(String string) {
public boolean isIntendedToolPickaxe(@NotNull String string) {
return intendedToolPickAxe.contains(string);
}

View File

@@ -0,0 +1,72 @@
package com.gmail.nossr50.util;
import com.google.common.collect.ImmutableSet;
import org.bukkit.metadata.FixedMetadataValue;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
/**
* Stores our constants related to metadata
*/
public class MetadataConstants {
/* Metadata Values
* Take great care if you ever modify the value of these keys
*/
public static final @NotNull String METADATA_KEY_REPLANT = "mcMMO: Recently Replanted";
public static final @NotNull String METADATA_KEY_EXPLOSION_FROM_RUPTURE = "mcMMO: Rupture Explosion";
public static final @NotNull String METADATA_KEY_FISH_HOOK_REF = "mcMMO: Fish Hook Tracker";
public static final @NotNull String METADATA_KEY_DODGE_TRACKER = "mcMMO: Dodge Tracker";
public static final @NotNull String METADATA_KEY_CUSTOM_DAMAGE = "mcMMO: Custom Damage";
public static final @NotNull String METADATA_KEY_TRAVELING_BLOCK = "mcMMO: Traveling Block";
public static final @NotNull String METADATA_KEY_PISTON_TRACKING = "mcMMO: Piston Tracking";
public static final @NotNull String METADATA_KEY_TRACKED_TNT = "mcMMO: Tracked TNT";
public static final @NotNull String METADATA_KEY_NAME_VISIBILITY = "mcMMO: Name Visibility";
public static final @NotNull String METADATA_KEY_TRACKED_ITEM = "mcMMO: Tracked Item";
public static final @NotNull String METADATA_KEY_INF_ARROW = "mcMMO: Infinite Arrow";
public static final @NotNull String METADATA_KEY_TRACKED_ARROW = "mcMMO: Tracked Arrow";
public static final @NotNull String METADATA_KEY_BOW_FORCE = "mcMMO: Bow Force";
public static final @NotNull String METADATA_KEY_ARROW_DISTANCE = "mcMMO: Arrow Distance";
public static final @NotNull String METADATA_KEY_BONUS_DROPS = "mcMMO: Double Drops";
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";
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";
public static final @NotNull String METADATA_KEY_NETHER_PORTAL_MOB = "mcmmo_nethergate_mob";
public static final @NotNull String METADATA_KEY_COTW_SUMMONED_MOB = "mcmmo_cotw_summoned_mob";
public static final @NotNull String METADATA_KEY_PLAYER_BRED_MOB = "mcmmo_player_bred_mob";
public static final @NotNull String METADATA_KEY_PLAYER_TAMED_MOB = "mcmmo_player_tamed_mob";
public static final @NotNull String METADATA_KEY_VILLAGER_TRADE_ORIGIN_ITEM = "mcmmo_villager_trade_origin_item";
public static final @NotNull String METADATA_KEY_EXPLOITED_ENDERMEN = "mcmmo_exploited_endermen";
public static final @NotNull String METADATA_KEY_CUSTOM_NAME = "mcmmo_custom_name";
public static final @NotNull String METADATA_KEY_OLD_NAME_KEY = "mcmmo_old_name";
public static final @NotNull String METADATA_KEY_RUPTURE = "mcmmo_rupture";
public static final byte SIMPLE_FLAG_VALUE = (byte) 0x1;
public static final @NotNull ImmutableSet<String> MOB_METADATA_KEYS;
public static FixedMetadataValue MCMMO_METADATA_VALUE;
static {
HashSet<String> temp = new HashSet<>();
temp.add(MetadataConstants.METADATA_KEY_MOB_SPAWNER_MOB);
temp.add(MetadataConstants.METADATA_KEY_EGG_MOB);
temp.add(MetadataConstants.METADATA_KEY_NETHER_PORTAL_MOB);
temp.add(MetadataConstants.METADATA_KEY_COTW_SUMMONED_MOB);
temp.add(MetadataConstants.METADATA_KEY_PLAYER_BRED_MOB);
temp.add(MetadataConstants.METADATA_KEY_PLAYER_TAMED_MOB);
temp.add(MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN);
temp.add(MetadataConstants.METADATA_KEY_CUSTOM_NAME);
temp.add(MetadataConstants.METADATA_KEY_RUPTURE);
temp.add(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE);
temp.add(MetadataConstants.METADATA_KEY_OLD_NAME_KEY);
temp.add(MetadataConstants.METADATA_KEY_DODGE_TRACKER);
MOB_METADATA_KEYS = ImmutableSet.copyOf(temp);
}
}

View File

@@ -9,7 +9,6 @@ import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableSet;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.BlockState;
import org.bukkit.entity.*;
import org.bukkit.inventory.ItemStack;
@@ -108,9 +107,9 @@ public final class Misc {
return blockState.getLocation().add(0.5, 0.5, 0.5);
}
public static void spawnItemsFromCollection(@NotNull Location location, @NotNull Collection<ItemStack> drops, @NotNull ItemSpawnReason itemSpawnReason) {
public static void spawnItemsFromCollection(@NotNull Player player, @NotNull Location location, @NotNull Collection<ItemStack> drops, @NotNull ItemSpawnReason itemSpawnReason) {
for (ItemStack drop : drops) {
spawnItem(location, drop, itemSpawnReason);
spawnItem(player, location, drop, itemSpawnReason);
}
}
@@ -122,11 +121,11 @@ public final class Misc {
* @param drops collection to iterate over
* @param sizeLimit the number of drops to process
*/
public static void spawnItemsFromCollection(@NotNull Location location, @NotNull Collection<ItemStack> drops, @NotNull ItemSpawnReason itemSpawnReason, int sizeLimit) {
public static void spawnItemsFromCollection(@Nullable Player player, @NotNull Location location, @NotNull Collection<ItemStack> drops, @NotNull ItemSpawnReason itemSpawnReason, int sizeLimit) {
ItemStack[] arrayDrops = drops.toArray(new ItemStack[0]);
for(int i = 0; i < sizeLimit-1; i++) {
spawnItem(location, arrayDrops[i], itemSpawnReason);
spawnItem(player, location, arrayDrops[i], itemSpawnReason);
}
}
@@ -137,9 +136,9 @@ public final class Misc {
* @param is The items to drop
* @param quantity The amount of items to drop
*/
public static void spawnItems(@NotNull Location location, @NotNull ItemStack is, int quantity, @NotNull ItemSpawnReason itemSpawnReason) {
public static void spawnItems(@Nullable Player player, @NotNull Location location, @NotNull ItemStack is, int quantity, @NotNull ItemSpawnReason itemSpawnReason) {
for (int i = 0; i < quantity; i++) {
spawnItem(location, is, itemSpawnReason);
spawnItem(player, location, is, itemSpawnReason);
}
}
@@ -151,13 +150,13 @@ public final class Misc {
* @param itemSpawnReason the reason for the item drop
* @return Dropped Item entity or null if invalid or cancelled
*/
public static @Nullable Item spawnItem(@NotNull Location location, @NotNull ItemStack itemStack, @NotNull ItemSpawnReason itemSpawnReason) {
public static @Nullable Item spawnItem(@Nullable Player player, @NotNull Location location, @NotNull ItemStack itemStack, @NotNull ItemSpawnReason itemSpawnReason) {
if (itemStack.getType() == Material.AIR || location.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.
McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack, itemSpawnReason);
McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack, itemSpawnReason, player);
mcMMO.p.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
@@ -175,13 +174,13 @@ public final class Misc {
* @param itemSpawnReason the reason for the item drop
* @return Dropped Item entity or null if invalid or cancelled
*/
public static @Nullable Item spawnItemNaturally(@NotNull Location location, @NotNull ItemStack itemStack, @NotNull ItemSpawnReason itemSpawnReason) {
public static @Nullable Item spawnItemNaturally(@Nullable Player player, @NotNull Location location, @NotNull ItemStack itemStack, @NotNull ItemSpawnReason itemSpawnReason) {
if (itemStack.getType() == Material.AIR || location.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.
McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack, itemSpawnReason);
McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(location, itemStack, itemSpawnReason, player);
mcMMO.p.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
@@ -199,9 +198,9 @@ public final class Misc {
* @param speed the speed that the item should travel
* @param quantity The amount of items to drop
*/
public static void spawnItemsTowardsLocation(@NotNull Location fromLocation, @NotNull Location toLocation, @NotNull ItemStack is, int quantity, double speed, @NotNull ItemSpawnReason itemSpawnReason) {
public static void spawnItemsTowardsLocation(@Nullable Player player, @NotNull Location fromLocation, @NotNull Location toLocation, @NotNull ItemStack is, int quantity, double speed, @NotNull ItemSpawnReason itemSpawnReason) {
for (int i = 0; i < quantity; i++) {
spawnItemTowardsLocation(fromLocation, toLocation, is, speed, itemSpawnReason);
spawnItemTowardsLocation(player, fromLocation, toLocation, is, speed, itemSpawnReason);
}
}
@@ -215,7 +214,7 @@ public final class Misc {
* @param speed the speed that the item should travel
* @return Dropped Item entity or null if invalid or cancelled
*/
public static @Nullable Item spawnItemTowardsLocation(@NotNull Location fromLocation, @NotNull Location toLocation, @NotNull ItemStack itemToSpawn, double speed, @NotNull ItemSpawnReason itemSpawnReason) {
public static @Nullable Item spawnItemTowardsLocation(@Nullable Player player, @NotNull Location fromLocation, @NotNull Location toLocation, @NotNull ItemStack itemToSpawn, double speed, @NotNull ItemSpawnReason itemSpawnReason) {
if (itemToSpawn.getType() == Material.AIR) {
return null;
}
@@ -229,7 +228,7 @@ public final class Misc {
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.
McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(spawnLocation, clonedItem, itemSpawnReason);
McMMOItemSpawnEvent event = new McMMOItemSpawnEvent(spawnLocation, clonedItem, itemSpawnReason, player);
mcMMO.p.getServer().getPluginManager().callEvent(event);
//Something cancelled the event so back out
@@ -260,12 +259,6 @@ public final class Misc {
}
}
public static int getWorldMinCompat(World world)
{
// TODO this method should access the world min variable in a version safe manner so that we don't restrict usage to new versions of spigot only
return 0;
}
public static void printProgress(int convertedUsers, int progressInterval, long startMillis) {
if ((convertedUsers % progressInterval) == 0) {
mcMMO.p.getLogger().info(String.format("Conversion progress: %d users at %.2f users/second", convertedUsers, convertedUsers / (double) ((System.currentTimeMillis() - startMillis) / TIME_CONVERSION_FACTOR)));

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.MobHealthbarType;
import com.gmail.nossr50.datatypes.meta.OldName;
import com.gmail.nossr50.mcMMO;
@@ -36,7 +35,7 @@ public final class MobHealthbarUtils {
* @param damage damage done by the attack triggering this
*/
public static void handleMobHealthbars(LivingEntity target, double damage, mcMMO plugin) {
if (mcMMO.isHealthBarPluginEnabled() || !Config.getInstance().getMobHealthbarEnabled()) {
if (mcMMO.isHealthBarPluginEnabled() || !mcMMO.p.getGeneralConfig().getMobHealthbarEnabled()) {
return;
}
@@ -55,34 +54,34 @@ public final class MobHealthbarUtils {
/*
* Store the name in metadata
*/
if(target.getMetadata(TransientMetadataTools.OLD_NAME_METAKEY).size() <= 0 && originalName != null)
target.setMetadata(TransientMetadataTools.OLD_NAME_METAKEY, new OldName(originalName, plugin));
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) {
oldName = "";
}
boolean oldNameVisible = target.isCustomNameVisible();
String newName = createHealthDisplay(Config.getInstance().getMobHealthbarDefault(), target, damage);
String newName = createHealthDisplay(mcMMO.p.getGeneralConfig().getMobHealthbarDefault(), target, damage);
target.setCustomName(newName);
target.setCustomNameVisible(true);
int displayTime = Config.getInstance().getMobHealthbarTime();
int displayTime = mcMMO.p.getGeneralConfig().getMobHealthbarTime();
if (displayTime != -1) {
boolean updateName = !ChatColor.stripColor(oldName).equalsIgnoreCase(ChatColor.stripColor(newName));
if (updateName) {
target.setMetadata(mcMMO.customNameKey, new FixedMetadataValue(mcMMO.p, oldName));
target.setMetadata(mcMMO.customVisibleKey, new FixedMetadataValue(mcMMO.p, oldNameVisible));
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(mcMMO.customNameKey)) {
target.setMetadata(mcMMO.customNameKey, new FixedMetadataValue(mcMMO.p, ""));
target.setMetadata(mcMMO.customVisibleKey, new FixedMetadataValue(mcMMO.p, false));
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));
}
new MobHealthDisplayUpdaterTask(target).runTaskLater(mcMMO.p, displayTime * Misc.TICK_CONVERSION_FACTOR); // Clear health display after 3 seconds
new MobHealthDisplayUpdaterTask(target).runTaskLater(mcMMO.p, (long) displayTime * Misc.TICK_CONVERSION_FACTOR); // Clear health display after 3 seconds
}
}
@@ -131,7 +130,7 @@ public final class MobHealthbarUtils {
return null;
}
int coloredDisplay = (int) Math.ceil(fullDisplay * (healthPercentage / 100.0D));
int coloredDisplay = (int) Math.max(Math.ceil(fullDisplay * (healthPercentage / 100.0D)), 0.5);
int grayDisplay = fullDisplay - coloredDisplay;
StringBuilder healthbar = new StringBuilder(color + "");

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.mods.CustomArmorConfig;
import com.gmail.nossr50.config.mods.CustomBlockConfig;
import com.gmail.nossr50.config.mods.CustomEntityConfig;
@@ -89,67 +88,67 @@ public class ModManager {
}
public boolean isCustomBoots(Material material) {
return Config.getInstance().getArmorModsEnabled() && customBoots.contains(material);
return mcMMO.p.getGeneralConfig().getArmorModsEnabled() && customBoots.contains(material);
}
public boolean isCustomChestplate(Material material) {
return Config.getInstance().getArmorModsEnabled() && customChestplates.contains(material);
return mcMMO.p.getGeneralConfig().getArmorModsEnabled() && customChestplates.contains(material);
}
public boolean isCustomHelmet(Material material) {
return Config.getInstance().getArmorModsEnabled() && customHelmets.contains(material);
return mcMMO.p.getGeneralConfig().getArmorModsEnabled() && customHelmets.contains(material);
}
public boolean isCustomLeggings(Material material) {
return Config.getInstance().getArmorModsEnabled() && customLeggings.contains(material);
return mcMMO.p.getGeneralConfig().getArmorModsEnabled() && customLeggings.contains(material);
}
public boolean isCustomAxe(Material material) {
return Config.getInstance().getToolModsEnabled() && customAxes.contains(material);
return mcMMO.p.getGeneralConfig().getToolModsEnabled() && customAxes.contains(material);
}
public boolean isCustomBow(Material material) {
return Config.getInstance().getToolModsEnabled() && customBows.contains(material);
return mcMMO.p.getGeneralConfig().getToolModsEnabled() && customBows.contains(material);
}
public boolean isCustomHoe(Material material) {
return Config.getInstance().getToolModsEnabled() && customHoes.contains(material);
return mcMMO.p.getGeneralConfig().getToolModsEnabled() && customHoes.contains(material);
}
public boolean isCustomPickaxe(Material material) {
return Config.getInstance().getToolModsEnabled() && customPickaxes.contains(material);
return mcMMO.p.getGeneralConfig().getToolModsEnabled() && customPickaxes.contains(material);
}
public boolean isCustomShovel(Material material) {
return Config.getInstance().getToolModsEnabled() && customShovels.contains(material);
return mcMMO.p.getGeneralConfig().getToolModsEnabled() && customShovels.contains(material);
}
public boolean isCustomSword(Material material) {
return Config.getInstance().getToolModsEnabled() && customSwords.contains(material);
return mcMMO.p.getGeneralConfig().getToolModsEnabled() && customSwords.contains(material);
}
public boolean isCustomOre(Material data) {
return Config.getInstance().getBlockModsEnabled() && customOres.contains(data);
return mcMMO.p.getGeneralConfig().getBlockModsEnabled() && customOres.contains(data);
}
public boolean isCustomLog(BlockState state) {
return Config.getInstance().getBlockModsEnabled() && customLogs.contains(state.getType());
return mcMMO.p.getGeneralConfig().getBlockModsEnabled() && customLogs.contains(state.getType());
}
public boolean isCustomAbilityBlock(BlockState state) {
return Config.getInstance().getBlockModsEnabled() && customAbilityBlocks.contains(state.getType());
return mcMMO.p.getGeneralConfig().getBlockModsEnabled() && customAbilityBlocks.contains(state.getType());
}
public boolean isCustomExcavationBlock(BlockState state) {
return Config.getInstance().getBlockModsEnabled() && customExcavationBlocks.contains(state.getType());
return mcMMO.p.getGeneralConfig().getBlockModsEnabled() && customExcavationBlocks.contains(state.getType());
}
public boolean isCustomHerbalismBlock(BlockState state) {
return Config.getInstance().getBlockModsEnabled() && customHerbalismBlocks.contains(state.getType());
return mcMMO.p.getGeneralConfig().getBlockModsEnabled() && customHerbalismBlocks.contains(state.getType());
}
public boolean isCustomMiningBlock(BlockState state) {
return Config.getInstance().getBlockModsEnabled() && customMiningBlocks.contains(state.getType());
return mcMMO.p.getGeneralConfig().getBlockModsEnabled() && customMiningBlocks.contains(state.getType());
}
public CustomBlock getBlock(BlockState state) {
@@ -167,7 +166,7 @@ public class ModManager {
* @return true if the item is a custom tool, false otherwise
*/
public boolean isCustomTool(ItemStack item) {
return Config.getInstance().getToolModsEnabled() && item != null && customToolMap.containsKey(item.getType());
return mcMMO.p.getGeneralConfig().getToolModsEnabled() && item != null && customToolMap.containsKey(item.getType());
}
/**
@@ -185,7 +184,7 @@ public class ModManager {
}
public boolean isCustomEntity(Entity entity) {
if (!Config.getInstance().getEntityModsEnabled()) {
if (!mcMMO.p.getGeneralConfig().getEntityModsEnabled()) {
return false;
}
@@ -227,7 +226,7 @@ public class ModManager {
}
public void addCustomEntity(Entity entity) {
if (!Config.getInstance().getEntityModsEnabled()) {
if (!mcMMO.p.getGeneralConfig().getEntityModsEnabled()) {
return;
}

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
@@ -70,11 +69,11 @@ public final class Motd {
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Enabled", statLossInfo + seperator + vampirismInfo));
if (deathStatLossEnabled) {
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.DeathStatLoss.Stats", Config.getInstance().getHardcoreDeathStatPenaltyPercentage()));
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.DeathStatLoss.Stats", mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyPercentage()));
}
if (vampirismEnabled) {
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Vampirism.Stats", Config.getInstance().getHardcoreVampirismStatLeechPercentage()));
player.sendMessage(LocaleLoader.getString("MOTD.Hardcore.Vampirism.Stats", mcMMO.p.getGeneralConfig().getHardcoreVampirismStatLeechPercentage()));
}
}

View File

@@ -29,7 +29,6 @@ public final class Permissions {
*/
public static boolean motd(Permissible permissible) { return permissible.hasPermission("mcmmo.motd"); }
public static boolean levelUpBroadcast(Permissible permissible) { return permissible.hasPermission("mcmmo.broadcast.levelup"); }
public static boolean mobHealthDisplay(Permissible permissible) { return permissible.hasPermission("mcmmo.mobhealthdisplay"); }
public static boolean updateNotifications(Permissible permissible) {return permissible.hasPermission("mcmmo.tools.updatecheck"); }
public static boolean chimaeraWing(Permissible permissible) { return permissible.hasPermission("mcmmo.item.chimaerawing"); }
public static boolean showversion(Permissible permissible) { return permissible.hasPermission("mcmmo.showversion"); }
@@ -37,8 +36,6 @@ public final class Permissions {
/* BYPASS */
public static boolean hardcoreBypass(Permissible permissible) { return permissible.hasPermission("mcmmo.bypass.hardcoremode"); }
public static boolean arcaneBypass(Permissible permissible) { return permissible.hasPermission("mcmmo.bypass.arcanebypass"); }
public static boolean krakenBypass(Permissible permissible) { return permissible.hasPermission("mcmmo.bypass.kraken"); }
public static boolean trapsBypass(Permissible permissible) { return permissible.hasPermission("mcmmo.bypass.fishingtraps"); }
/* CHAT */
public static boolean partyChat(Permissible permissible) { return permissible.hasPermission("mcmmo.chat.partychat"); }
@@ -63,9 +60,6 @@ public final class Permissions {
public static boolean inspectFar(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.far")); }
public static boolean inspectHidden(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.inspect.hidden")); }
public static boolean kraken(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.kraken"); }
public static boolean krakenOthers(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.kraken.others"); }
public static boolean mcability(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcability")); }
public static boolean mcabilityOthers(Permissible permissible) { return (permissible.hasPermission("mcmmo.commands.mcability.others")); }
@@ -101,9 +95,6 @@ public final class Permissions {
public static boolean xprateSet(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.xprate.set"); }
public static boolean xprateReset(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.xprate.reset"); }
public static boolean vampirismModify(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.vampirism.modify"); }
public static boolean vampirismToggle(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.vampirism.toggle"); }
public static boolean mcpurge(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcpurge"); }
public static boolean mcremove(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mcremove"); }
public static boolean mmoupdate(Permissible permissible) { return permissible.hasPermission("mcmmo.commands.mmoupdate"); }
@@ -121,13 +112,46 @@ public final class Permissions {
public static boolean lucky(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.lucky." + skill.toString().toLowerCase(Locale.ENGLISH)); }
/* XP PERKS */
public static boolean quadrupleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.quadruple." + skill.toString().toLowerCase(Locale.ENGLISH)); }
public static boolean tripleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.triple." + skill.toString().toLowerCase(Locale.ENGLISH)); }
public static boolean doubleAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.150percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); }
public static boolean doubleXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.double." + skill.toString().toLowerCase(Locale.ENGLISH)); }
public static boolean oneAndOneHalfXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.50percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); }
public static boolean oneAndOneTenthXp(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.10percentboost." + skill.toString().toLowerCase(Locale.ENGLISH)); }
public static boolean customXpBoost(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.perks.xp.customboost." + skill.toString().toLowerCase(Locale.ENGLISH)); }
public static boolean quadrupleXp(Permissible permissible, PrimarySkillType skill) {
return permissible.hasPermission("mcmmo.perks.xp.quadruple.all")
|| permissible.hasPermission("mcmmo.perks.xp.quadruple." + skill.toString().toLowerCase(Locale.ENGLISH));
}
public static boolean tripleXp(Permissible permissible, PrimarySkillType skill) {
return permissible.hasPermission("mcmmo.perks.xp.triple.all")
|| permissible.hasPermission("mcmmo.perks.xp.triple." + skill.toString().toLowerCase(Locale.ENGLISH));
}
public static boolean doubleAndOneHalfXp(Permissible permissible, PrimarySkillType skill) {
return permissible.hasPermission("mcmmo.perks.xp.150percentboost.all")
|| permissible.hasPermission("mcmmo.perks.xp.150percentboost." + skill.toString().toLowerCase(Locale.ENGLISH));
}
public static boolean doubleXp(Permissible permissible, PrimarySkillType skill) {
return permissible.hasPermission("mcmmo.perks.xp.double.all")
|| permissible.hasPermission("mcmmo.perks.xp.double." + skill.toString().toLowerCase(Locale.ENGLISH));
}
public static boolean oneAndOneHalfXp(Permissible permissible, PrimarySkillType skill) {
return permissible.hasPermission("mcmmo.perks.xp.50percentboost.all")
|| permissible.hasPermission("mcmmo.perks.xp.50percentboost." + skill.toString().toLowerCase(Locale.ENGLISH));
}
public static boolean oneAndAQuarterXp(Permissible permissible, PrimarySkillType skill) {
return permissible.hasPermission("mcmmo.perks.xp.25percentboost.all")
|| permissible.hasPermission("mcmmo.perks.xp.25percentboost." + skill.toString().toLowerCase(Locale.ENGLISH));
}
public static boolean oneAndOneTenthXp(Permissible permissible, PrimarySkillType skill) {
return permissible.hasPermission("mcmmo.perks.xp.10percentboost.all")
|| permissible.hasPermission("mcmmo.perks.xp.10percentboost." + skill.toString().toLowerCase(Locale.ENGLISH));
}
public static boolean customXpBoost(Permissible permissible, PrimarySkillType skill) {
return permissible.hasPermission("mcmmo.perks.xp.customboost.all")
|| permissible.hasPermission("mcmmo.perks.xp.customboost." + skill.toString().toLowerCase(Locale.ENGLISH));
}
/* ACTIVATION PERKS */
public static boolean twelveSecondActivationBoost(Permissible permissible) { return permissible.hasPermission("mcmmo.perks.activationtime.twelveseconds"); }
@@ -147,7 +171,6 @@ 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) { return permissible.hasPermission(subSkillType.getPermissionNodeAddress()); }
public static boolean isSubSkillEnabled(Permissible permissible, AbstractSubSkill abstractSubSkill) { return permissible.hasPermission(abstractSubSkill.getPermissionNode()); }
public static boolean bonusDamage(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase(Locale.ENGLISH) + ".bonusdamage"); }
/* ACROBATICS */
public static boolean dodge(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.acrobatics.dodge"); }
@@ -184,7 +207,6 @@ public final class Permissions {
public static boolean repairMaterialType(Permissible permissible, MaterialType repairMaterialType) { return permissible.hasPermission("mcmmo.ability.repair." + repairMaterialType.toString().toLowerCase(Locale.ENGLISH) + "repair"); }
/* SALVAGE */
public static boolean advancedSalvage(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.salvage.advancedsalvage"); }
public static boolean arcaneSalvage(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.salvage.arcanesalvage"); }
public static boolean salvageItemType(Permissible permissible, ItemType salvageItemType) { return permissible.hasPermission("mcmmo.ability.salvage." + salvageItemType.toString().toLowerCase(Locale.ENGLISH) + "salvage"); }

View File

@@ -92,7 +92,7 @@ public class TransientEntityTracker {
* @param playerUUID player to register
*/
private synchronized void registerPlayer(@NotNull UUID playerUUID) {
getPerPlayerTransientEntityMap().put(playerUUID, new HashMap<CallOfTheWildType, HashSet<TrackedTamingEntity>>());
getPerPlayerTransientEntityMap().put(playerUUID, new HashMap<>());
for(CallOfTheWildType callOfTheWildType : CallOfTheWildType.values()) {
getPerPlayerTransientEntityMap().get(playerUUID).put(callOfTheWildType, new HashSet<>());
@@ -273,7 +273,7 @@ public class TransientEntityTracker {
}
//Remove our metadata
mcMMO.getCompatibilityManager().getPersistentDataLayer().removeMobFlags(livingEntity);
mcMMO.getMetadataService().getMobMetadataService().removeMobFlags(livingEntity);
//Clean from trackers
unregisterEntity(livingEntity);

View File

@@ -2,38 +2,41 @@ package com.gmail.nossr50.util;
import com.gmail.nossr50.mcMMO;
import org.bukkit.entity.LivingEntity;
import org.jetbrains.annotations.NotNull;
public class TransientMetadataTools {
public static final String OLD_NAME_METAKEY = TransientMetadataTools.OLD_NAME_METAKEY;
private final mcMMO pluginRef;
public TransientMetadataTools(mcMMO pluginRef) {
public TransientMetadataTools(@NotNull mcMMO pluginRef) {
this.pluginRef = pluginRef;
}
public void cleanAllMobMetadata(LivingEntity livingEntity) {
//Since its not written anywhere, apparently the GC won't touch objects with metadata still present on them
if (livingEntity.hasMetadata(mcMMO.customNameKey)) {
livingEntity.setCustomName(livingEntity.getMetadata(mcMMO.customNameKey).get(0).asString());
livingEntity.removeMetadata(mcMMO.customNameKey, pluginRef);
}
if(livingEntity.hasMetadata(OLD_NAME_METAKEY)) {
livingEntity.removeMetadata(OLD_NAME_METAKEY, pluginRef);
public void cleanLivingEntityMetadata(@NotNull LivingEntity entity) {
//Since it's not written anywhere, apparently the GC won't touch objects with metadata still present on them
if (entity.hasMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME)) {
entity.setCustomName(entity.getMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME).get(0).asString());
entity.removeMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, pluginRef);
}
//Involved in changing mob names to hearts
if (livingEntity.hasMetadata(mcMMO.customVisibleKey)) {
livingEntity.setCustomNameVisible(livingEntity.getMetadata(mcMMO.customVisibleKey).get(0).asBoolean());
livingEntity.removeMetadata(mcMMO.customVisibleKey, pluginRef);
if (entity.hasMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY)) {
entity.setCustomNameVisible(entity.getMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY).get(0).asBoolean());
entity.removeMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, pluginRef);
}
//Gets assigned to endermen, potentially doesn't get cleared before this point
if(livingEntity.hasMetadata(mcMMO.travelingBlock)) {
livingEntity.removeMetadata(mcMMO.travelingBlock, pluginRef);
if(entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK)) {
entity.removeMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, pluginRef);
}
//Cleanup mob metadata
mcMMO.getCompatibilityManager().getPersistentDataLayer().removeMobFlags(livingEntity);
mcMMO.getMetadataService().getMobMetadataService().removeMobFlags(entity);
//TODO: This loop has some redundancy, this whole method needs to be rewritten
for(String key : MetadataConstants.MOB_METADATA_KEYS) {
if(entity.hasMetadata(key)) {
entity.removeMetadata(key, pluginRef);
}
}
}
}

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util.blockmeta;
import com.gmail.nossr50.util.Misc;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.jetbrains.annotations.NotNull;
@@ -25,7 +24,7 @@ public class BitSetChunkStore implements ChunkStore {
private transient boolean dirty = false;
public BitSetChunkStore(@NotNull World world, int cx, int cz) {
this(world.getUID(), Misc.getWorldMinCompat(world), world.getMaxHeight(), cx, cz);
this(world.getUID(), world.getMinHeight(), world.getMaxHeight(), cx, cz);
}
private BitSetChunkStore(@NotNull UUID worldUid, int worldMin, int worldMax, int cx, int cz) {
@@ -109,24 +108,23 @@ public class BitSetChunkStore implements ChunkStore {
return (z * 16 + x) + (256 * (y + yOffset));
}
private static int getWorldMin(@NotNull UUID worldUid, int storedWorldMin)
{
private static int getWorldMin(@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?
if (world == null)
return storedWorldMin;
throw new RuntimeException("Cannot grab a minimum world height for an unloaded world");
return Misc.getWorldMinCompat(world);
return world.getMinHeight();
}
private static int getWorldMax(@NotNull UUID worldUid, int storedWorldMax)
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?
if (world == null)
return storedWorldMax;
throw new RuntimeException("Cannot grab a maximum world height for an unloaded world");
return world.getMaxHeight();
}
@@ -172,8 +170,8 @@ public class BitSetChunkStore implements ChunkStore {
in.readFully(temp);
BitSet stored = BitSet.valueOf(temp);
int currentWorldMin = getWorldMin(worldUid, worldMin);
int currentWorldMax = getWorldMax(worldUid, worldMax);
int currentWorldMin = getWorldMin(worldUid);
int currentWorldMax = getWorldMax(worldUid);
// The order in which the world height update code occurs here is important, the world max truncate math only holds up if done before adjusting for min changes
// Lop off extra data if world max has shrunk
@@ -274,8 +272,8 @@ public class BitSetChunkStore implements ChunkStore {
public @NotNull BitSetChunkStore convert()
{
int currentWorldMin = getWorldMin(worldUid, 0);
int currentWorldMax = getWorldMax(worldUid, worldMax);
int currentWorldMin = getWorldMin(worldUid);
int currentWorldMax = getWorldMax(worldUid);
BitSetChunkStore converted = new BitSetChunkStore(worldUid, currentWorldMin, currentWorldMax, cx, cz);

View File

@@ -1,13 +1,12 @@
package com.gmail.nossr50.util.blockmeta;
import com.gmail.nossr50.config.HiddenConfig;
import com.gmail.nossr50.config.PersistentDataConfig;
import org.jetbrains.annotations.NotNull;
public class ChunkManagerFactory {
public static @NotNull ChunkManager getChunkManager() {
HiddenConfig hConfig = HiddenConfig.getInstance();
if (hConfig.getChunkletsEnabled()) {
if (PersistentDataConfig.getInstance().useBlockTracker()) {
return new HashChunkManager();
}

View File

@@ -132,7 +132,7 @@ public class McMMOSimpleRegionFile {
int oldSegmentIndex = chunkSegmentIndex[index]; // Get current segment index
markChunkSegments(index, false); // Clear our old segments
int newSegmentIndex = findContiguousSegments(oldSegmentIndex, size); // Find contiguous segments to save to
file.seek(newSegmentIndex << segmentExponent); // Seek to file location
file.seek((long) newSegmentIndex << segmentExponent); // Seek to file location
file.write(buffer, 0, size); // Write data
// update in memory info
chunkSegmentIndex[index] = newSegmentIndex;
@@ -141,9 +141,9 @@ public class McMMOSimpleRegionFile {
// Mark segments in use
markChunkSegments(index, true);
// Update header info
file.seek(SEEK_CHUNK_SEGMENT_INDICES + (4 * index));
file.seek(SEEK_CHUNK_SEGMENT_INDICES + (4L * index));
file.writeInt(chunkSegmentIndex[index]);
file.seek(SEEK_CHUNK_BYTE_LENGTHS + (4 * index));
file.seek(SEEK_CHUNK_BYTE_LENGTHS + (4L * index));
file.writeInt(chunkNumBytes[index]);
}
@@ -157,7 +157,7 @@ public class McMMOSimpleRegionFile {
byte[] data = new byte[byteLength];
file.seek(chunkSegmentIndex[index] << segmentExponent); // Seek to file location
file.seek((long) chunkSegmentIndex[index] << segmentExponent); // Seek to file location
file.readFully(data); // Read in the data
return new DataInputStream(new InflaterInputStream(new ByteArrayInputStream(data)));
}

View File

@@ -12,13 +12,10 @@ import com.gmail.nossr50.commands.experience.AddlevelsCommand;
import com.gmail.nossr50.commands.experience.AddxpCommand;
import com.gmail.nossr50.commands.experience.MmoeditCommand;
import com.gmail.nossr50.commands.experience.SkillresetCommand;
import com.gmail.nossr50.commands.hardcore.HardcoreCommand;
import com.gmail.nossr50.commands.hardcore.VampirismCommand;
import com.gmail.nossr50.commands.party.PartyCommand;
import com.gmail.nossr50.commands.party.teleport.PtpCommand;
import com.gmail.nossr50.commands.player.*;
import com.gmail.nossr50.commands.skills.*;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
@@ -37,7 +34,7 @@ public final class CommandRegistrationManager {
private static void registerSkillCommands() {
for (PrimarySkillType skill : PrimarySkillType.values()) {
String commandName = skill.toString().toLowerCase(Locale.ENGLISH);
String localizedName = skill.getName().toLowerCase(Locale.ENGLISH);
String localizedName = mcMMO.p.getSkillTools().getLocalizedSkillName(skill).toLowerCase(Locale.ENGLISH);
PluginCommand command;
@@ -285,7 +282,7 @@ public final class CommandRegistrationManager {
private static void registerMcpurgeCommand() {
PluginCommand command = mcMMO.p.getCommand("mcpurge");
command.setDescription(LocaleLoader.getString("Commands.Description.mcpurge", Config.getInstance().getOldUsersCutoff()));
command.setDescription(LocaleLoader.getString("Commands.Description.mcpurge", mcMMO.p.getGeneralConfig().getOldUsersCutoff()));
command.setPermission("mcmmo.commands.mcpurge");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcpurge"));
@@ -363,25 +360,25 @@ public final class CommandRegistrationManager {
command.setExecutor(new PtpCommand());
}
private static void registerHardcoreCommand() {
PluginCommand command = mcMMO.p.getCommand("hardcore");
command.setDescription(LocaleLoader.getString("Commands.Description.hardcore"));
command.setPermission("mcmmo.commands.hardcore;mcmmo.commands.hardcore.toggle;mcmmo.commands.hardcore.modify");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "hardcore", "[on|off]"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "hardcore", "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">"));
command.setExecutor(new HardcoreCommand());
}
private static void registerVampirismCommand() {
PluginCommand command = mcMMO.p.getCommand("vampirism");
command.setDescription(LocaleLoader.getString("Commands.Description.vampirism"));
command.setPermission("mcmmo.commands.vampirism;mcmmo.commands.vampirism.toggle;mcmmo.commands.vampirism.modify");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.1", "vampirism", "[on|off]"));
command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "vampirism", "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">"));
command.setExecutor(new VampirismCommand());
}
// private static void registerHardcoreCommand() {
// PluginCommand command = mcMMO.p.getCommand("hardcore");
// command.setDescription(LocaleLoader.getString("Commands.Description.hardcore"));
// command.setPermission("mcmmo.commands.hardcore;mcmmo.commands.hardcore.toggle;mcmmo.commands.hardcore.modify");
// command.setPermissionMessage(permissionsMessage);
// command.setUsage(LocaleLoader.getString("Commands.Usage.1", "hardcore", "[on|off]"));
// command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "hardcore", "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">"));
// command.setExecutor(new HardcoreCommand());
// }
//
// private static void registerVampirismCommand() {
// PluginCommand command = mcMMO.p.getCommand("vampirism");
// command.setDescription(LocaleLoader.getString("Commands.Description.vampirism"));
// command.setPermission("mcmmo.commands.vampirism;mcmmo.commands.vampirism.toggle;mcmmo.commands.vampirism.modify");
// command.setPermissionMessage(permissionsMessage);
// command.setUsage(LocaleLoader.getString("Commands.Usage.1", "vampirism", "[on|off]"));
// command.setUsage(command.getUsage() + "\n" + LocaleLoader.getString("Commands.Usage.1", "vampirism", "<" + LocaleLoader.getString("Commands.Usage.Rate") + ">"));
// command.setExecutor(new VampirismCommand());
// }
private static void registerMcnotifyCommand() {
PluginCommand command = mcMMO.p.getCommand("mcnotify");
@@ -391,15 +388,6 @@ public final class CommandRegistrationManager {
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mcnotify"));
command.setExecutor(new McnotifyCommand());
}
private static void registerMHDCommand() {
PluginCommand command = mcMMO.p.getCommand("mhd");
command.setDescription("Resets all mob health bar settings for all players to the default"); //TODO: Localize
command.setPermission("mcmmo.commands.mhd");
command.setPermissionMessage(permissionsMessage);
command.setUsage(LocaleLoader.getString("Commands.Usage.0", "mhd"));
command.setExecutor(new MHDCommand());
}
private static void registerMcscoreboardCommand() {
PluginCommand command = mcMMO.p.getCommand("mcscoreboard");
@@ -457,7 +445,6 @@ public final class CommandRegistrationManager {
registerMcnotifyCommand();
registerMcrefreshCommand();
registerMcscoreboardCommand();
registerMHDCommand();
registerXprateCommand();
// Database Commands
@@ -473,8 +460,8 @@ public final class CommandRegistrationManager {
registerSkillresetCommand();
// Hardcore Commands
registerHardcoreCommand();
registerVampirismCommand();
// registerHardcoreCommand();
// registerVampirismCommand();
// Party Commands
registerPartyCommand();

View File

@@ -1,13 +1,14 @@
package com.gmail.nossr50.util.commands;
import com.gmail.nossr50.config.Config;
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.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.MetadataConstants;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.skills.SkillTools;
import com.gmail.nossr50.util.skills.SkillUtils;
import com.gmail.nossr50.util.text.StringUtils;
import com.google.common.collect.ImmutableList;
@@ -26,7 +27,7 @@ public final class CommandUtils {
private CommandUtils() {}
public static boolean isChildSkill(CommandSender sender, PrimarySkillType skill) {
if (skill == null || !skill.isChildSkill()) {
if (skill == null || !SkillTools.isChildSkill(skill)) {
return false;
}
@@ -38,7 +39,7 @@ public final class CommandUtils {
if(!target.isOnline() && !hasPermission) {
sender.sendMessage(LocaleLoader.getString("Inspect.Offline"));
return true;
} else if (sender instanceof Player && !Misc.isNear(((Player) sender).getLocation(), target.getLocation(), Config.getInstance().getInspectDistance()) && !hasPermission) {
} else if (sender instanceof Player && !Misc.isNear(((Player) sender).getLocation(), target.getLocation(), mcMMO.p.getGeneralConfig().getInspectDistance()) && !hasPermission) {
sender.sendMessage(LocaleLoader.getString("Inspect.TooFar"));
return true;
}
@@ -86,7 +87,7 @@ public final class CommandUtils {
return true;
}
PlayerProfile profile = new PlayerProfile(playerName, false);
PlayerProfile profile = new PlayerProfile(playerName, false, 0);
if (unloadedProfile(sender, profile)) {
return false;
@@ -110,7 +111,7 @@ public final class CommandUtils {
return false;
}
boolean hasPlayerDataKey = ((Player) sender).hasMetadata(mcMMO.playerDataKey);
boolean hasPlayerDataKey = ((Player) sender).hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA);
if (!hasPlayerDataKey) {
sender.sendMessage(LocaleLoader.getString("Commands.NotLoaded"));
@@ -170,7 +171,7 @@ public final class CommandUtils {
* @param display The sender to display stats to
*/
public static void printGatheringSkills(Player inspect, CommandSender display) {
printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Gathering"), PrimarySkillType.GATHERING_SKILLS);
printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Gathering"), mcMMO.p.getSkillTools().GATHERING_SKILLS);
}
public static void printGatheringSkills(Player player) {
@@ -184,7 +185,7 @@ public final class CommandUtils {
* @param display The sender to display stats to
*/
public static void printCombatSkills(Player inspect, CommandSender display) {
printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Combat"), PrimarySkillType.COMBAT_SKILLS);
printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Combat"), mcMMO.p.getSkillTools().COMBAT_SKILLS);
}
public static void printCombatSkills(Player player) {
@@ -198,7 +199,7 @@ public final class CommandUtils {
* @param display The sender to display stats to
*/
public static void printMiscSkills(Player inspect, CommandSender display) {
printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Misc"), PrimarySkillType.MISC_SKILLS);
printGroupedSkillData(inspect, display, LocaleLoader.getString("Stats.Header.Misc"), mcMMO.p.getSkillTools().getMiscSkills());
}
public static void printMiscSkills(Player player) {
@@ -206,27 +207,27 @@ public final class CommandUtils {
}
public static String displaySkill(PlayerProfile profile, PrimarySkillType skill) {
if (skill.isChildSkill()) {
if (SkillTools.isChildSkill(skill)) {
return LocaleLoader.getString("Skills.ChildStats", LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".Listener") + " ", profile.getSkillLevel(skill));
}
if (profile.getSkillLevel(skill) == Config.getInstance().getLevelCap(skill)){
if (profile.getSkillLevel(skill) == mcMMO.p.getSkillTools().getLevelCap(skill)){
return LocaleLoader.getString("Skills.Stats", LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".Listener") + " ", profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), LocaleLoader.getString("Skills.MaxXP"));
}
return LocaleLoader.getString("Skills.Stats", LocaleLoader.getString(StringUtils.getCapitalized(skill.toString()) + ".Listener") + " ", profile.getSkillLevel(skill), profile.getSkillXpLevel(skill), profile.getXpToLevel(skill));
}
private static void printGroupedSkillData(Player inspect, CommandSender display, String header, List<PrimarySkillType> skillGroup) {
if(UserManager.getPlayer(inspect) == null)
private static void printGroupedSkillData(Player inspectTarget, CommandSender display, String header, List<PrimarySkillType> skillGroup) {
if(UserManager.getPlayer(inspectTarget) == null)
return;
PlayerProfile profile = UserManager.getPlayer(inspect).getProfile();
PlayerProfile profile = UserManager.getPlayer(inspectTarget).getProfile();
List<String> displayData = new ArrayList<>();
displayData.add(header);
for (PrimarySkillType skill : skillGroup) {
if (skill.getPermissions(inspect)) {
displayData.add(displaySkill(profile, skill));
for (PrimarySkillType primarySkillType : skillGroup) {
if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(inspectTarget, primarySkillType)) {
displayData.add(displaySkill(profile, primarySkillType));
}
}
@@ -258,7 +259,7 @@ public final class CommandUtils {
* @return Matched name or {@code partialName} if no match was found
*/
public static String getMatchedPlayerName(String partialName) {
if (Config.getInstance().getMatchOfflinePlayers()) {
if (mcMMO.p.getGeneralConfig().getMatchOfflinePlayers()) {
List<String> matches = matchPlayer(partialName);
if (matches.size() == 1) {

View File

@@ -8,5 +8,5 @@ public interface CompatibilityLayer {
* Whether or not this CompatibilityLayer successfully initialized and in theory should be functional
* @return true if this CompatibilityLayer is functional
*/
boolean noErrorsOnInitialize();
default boolean noErrorsOnInitialize() { return true; };
}

View File

@@ -5,9 +5,6 @@ import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.compat.layers.bungee.AbstractBungeeSerializerCompatibilityLayer;
import com.gmail.nossr50.util.compat.layers.bungee.BungeeLegacySerializerCompatibilityLayer;
import com.gmail.nossr50.util.compat.layers.bungee.BungeeModernSerializerCompatibilityLayer;
import com.gmail.nossr50.util.compat.layers.persistentdata.AbstractPersistentDataLayer;
import com.gmail.nossr50.util.compat.layers.persistentdata.SpigotPersistentDataLayer_1_13;
import com.gmail.nossr50.util.compat.layers.persistentdata.SpigotPersistentDataLayer_1_14;
import com.gmail.nossr50.util.compat.layers.skills.AbstractMasterAnglerCompatibility;
import com.gmail.nossr50.util.compat.layers.skills.MasterAnglerCompatibilityLayer;
import com.gmail.nossr50.util.nms.NMSVersion;
@@ -25,20 +22,18 @@ import java.util.HashMap;
* In 2.2 we are switching to modules and that will clean things up significantly
*
*/
//TODO: I need to rewrite this crap
//TODO: I need to delete this crap
public class CompatibilityManager {
private HashMap<CompatibilityType, Boolean> supportedLayers;
private @NotNull HashMap<CompatibilityType, Boolean> supportedLayers;
private boolean isFullyCompatibleServerSoftware = true; //true if all compatibility layers load successfully
private final MinecraftGameVersion minecraftGameVersion;
private final NMSVersion nmsVersion;
private final @NotNull MinecraftGameVersion minecraftGameVersion;
private final @NotNull NMSVersion nmsVersion;
/* Compatibility Layers */
// private PlayerAttackCooldownExploitPreventionLayer playerAttackCooldownExploitPreventionLayer;
private AbstractPersistentDataLayer persistentDataLayer;
private AbstractBungeeSerializerCompatibilityLayer bungeeSerializerCompatibilityLayer;
private AbstractMasterAnglerCompatibility masterAnglerCompatibility;
public CompatibilityManager(MinecraftGameVersion minecraftGameVersion) {
public CompatibilityManager(@NotNull MinecraftGameVersion minecraftGameVersion) {
mcMMO.p.getLogger().info("Loading compatibility layers...");
this.minecraftGameVersion = minecraftGameVersion;
this.nmsVersion = determineNMSVersion();
@@ -64,7 +59,6 @@ public class CompatibilityManager {
* For any unsupported layers, load a dummy layer
*/
private void initCompatibilityLayers() {
initPersistentDataLayer();
initBungeeSerializerLayer();
initMasterAnglerLayer();
@@ -72,27 +66,15 @@ public class CompatibilityManager {
}
private void initMasterAnglerLayer() {
if(minecraftGameVersion.getMinorVersion().asInt() >= 16 || minecraftGameVersion.getMajorVersion().asInt() >= 2) {
if(hasNewFishingHookAPI()) {
masterAnglerCompatibility = new MasterAnglerCompatibilityLayer();
}
if(minecraftGameVersion.isAtLeast(1, 16, 3)) {
masterAnglerCompatibility = new MasterAnglerCompatibilityLayer();
} else {
masterAnglerCompatibility = null;
}
}
private boolean hasNewFishingHookAPI() {
try {
Class<?> checkForClass = Class.forName("org.bukkit.entity.FishHook");
checkForClass.getMethod("getMinWaitTime");
return true;
} catch (ClassNotFoundException | NoSuchMethodException e) {
return false;
}
}
private void initBungeeSerializerLayer() {
if(minecraftGameVersion.getMinorVersion().asInt() >= 16) {
if(minecraftGameVersion.isAtLeast(1, 16, 0)) {
bungeeSerializerCompatibilityLayer = new BungeeModernSerializerCompatibilityLayer();
} else {
bungeeSerializerCompatibilityLayer = new BungeeLegacySerializerCompatibilityLayer();
@@ -101,19 +83,8 @@ public class CompatibilityManager {
supportedLayers.put(CompatibilityType.BUNGEE_SERIALIZER, true);
}
private void initPersistentDataLayer() {
if(minecraftGameVersion.getMinorVersion().asInt() >= 14 || minecraftGameVersion.getMajorVersion().asInt() >= 2) {
persistentDataLayer = new SpigotPersistentDataLayer_1_14();
} else {
persistentDataLayer = new SpigotPersistentDataLayer_1_13();
}
supportedLayers.put(CompatibilityType.PERSISTENT_DATA, true);
}
//TODO: move to text manager
public void reportCompatibilityStatus(CommandSender commandSender) {
public void reportCompatibilityStatus(@NotNull CommandSender commandSender) {
if(isFullyCompatibleServerSoftware) {
commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix",
"mcMMO is fully compatible with the currently running server software."));
@@ -130,7 +101,7 @@ public class CompatibilityManager {
commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix", "NMS Status - " + nmsVersion.toString()));
}
public boolean isCompatibilityLayerOperational(CompatibilityType compatibilityType) {
public boolean isCompatibilityLayerOperational(@NotNull CompatibilityType compatibilityType) {
return supportedLayers.get(compatibilityType);
}
@@ -143,6 +114,12 @@ 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)) {
return NMSVersion.NMS_1_17;
}
//Messy but it works
if (minecraftGameVersion.getMajorVersion().asInt() == 1) {
switch (minecraftGameVersion.getMinorVersion().asInt()) {
case 12:
@@ -165,6 +142,8 @@ public class CompatibilityManager {
} else if(minecraftGameVersion.getPatchVersion().asInt() >= 5) {
return NMSVersion.NMS_1_16_5;
}
case 17:
return NMSVersion.NMS_1_17;
}
}
@@ -175,11 +154,11 @@ public class CompatibilityManager {
return bungeeSerializerCompatibilityLayer;
}
public AbstractPersistentDataLayer getPersistentDataLayer() {
return persistentDataLayer;
}
public @Nullable AbstractMasterAnglerCompatibility getMasterAnglerCompatibilityLayer() {
return masterAnglerCompatibility;
}
public @Nullable MinecraftGameVersion getMinecraftGameVersion() {
return minecraftGameVersion;
}
}

View File

@@ -1,155 +0,0 @@
package com.gmail.nossr50.util.compat.layers.persistentdata;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.compat.layers.AbstractCompatibilityLayer;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Furnace;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.UUID;
public abstract class AbstractPersistentDataLayer extends AbstractCompatibilityLayer {
protected final @NotNull NamespacedKey NSK_SUPER_ABILITY_BOOSTED_ITEM;
protected final @NotNull NamespacedKey NSK_MOB_SPAWNER_MOB;
protected final @NotNull NamespacedKey NSK_EGG_MOB;
protected final @NotNull NamespacedKey NSK_NETHER_GATE_MOB;
protected final @NotNull NamespacedKey NSK_COTW_SUMMONED_MOB;
protected final @NotNull NamespacedKey NSK_PLAYER_BRED_MOB;
protected final @NotNull NamespacedKey NSK_PLAYER_TAMED_MOB;
protected final @NotNull NamespacedKey NSK_VILLAGER_TRADE_ORIGIN_ITEM;
protected final @NotNull NamespacedKey NSK_EXPLOITED_ENDERMEN;
//Never change these constants
public final @NotNull String STR_SUPER_ABILITY_BOOSTED_ITEM = "super_ability_boosted";
public final @NotNull String STR_MOB_SPAWNER_MOB = "mcmmo_mob_spawner_mob";
public final @NotNull String STR_EGG_MOB = "mcmmo_egg_mob";
public final @NotNull String STR_NETHER_PORTAL_MOB = "mcmmo_nethergate_mob";
public final @NotNull String STR_COTW_SUMMONED_MOB = "mcmmo_cotw_summoned_mob";
public final @NotNull String STR_PLAYER_BRED_MOB = "mcmmo_player_bred_mob";
public final @NotNull String STR_PLAYER_TAMED_MOB = "mcmmo_player_tamed_mob";
public final @NotNull String STR_VILLAGER_TRADE_ORIGIN_ITEM = "mcmmo_villager_trade_origin_item";
public final @NotNull String STR_EXPLOITED_ENDERMEN = "mcmmo_exploited_endermen";
/*
* Don't modify these keys
*/
public final @NotNull String STR_FURNACE_UUID_MOST_SIG = "furnace_uuid_most_sig";
public final @NotNull String STR_FURNACE_UUID_LEAST_SIG = "furnace_uuid_least_sig";
protected final @NotNull NamespacedKey NSK_FURNACE_UUID_MOST_SIG;
protected final @NotNull NamespacedKey NSK_FURNACE_UUID_LEAST_SIG;
public final @NotNull String LEGACY_ABILITY_TOOL_LORE = "mcMMO Ability Tool";
protected static final byte SIMPLE_FLAG_VALUE = (byte) 0x1;
public AbstractPersistentDataLayer() {
NSK_SUPER_ABILITY_BOOSTED_ITEM = getNamespacedKey(STR_SUPER_ABILITY_BOOSTED_ITEM);
NSK_MOB_SPAWNER_MOB = getNamespacedKey(STR_MOB_SPAWNER_MOB);
NSK_EGG_MOB = getNamespacedKey(STR_EGG_MOB);
NSK_NETHER_GATE_MOB = getNamespacedKey(STR_NETHER_PORTAL_MOB);
NSK_COTW_SUMMONED_MOB = getNamespacedKey(STR_COTW_SUMMONED_MOB);
NSK_PLAYER_BRED_MOB = getNamespacedKey(STR_PLAYER_BRED_MOB);
NSK_PLAYER_TAMED_MOB = getNamespacedKey(STR_PLAYER_TAMED_MOB);
NSK_VILLAGER_TRADE_ORIGIN_ITEM = getNamespacedKey(STR_VILLAGER_TRADE_ORIGIN_ITEM);
NSK_EXPLOITED_ENDERMEN = getNamespacedKey(STR_EXPLOITED_ENDERMEN);
NSK_FURNACE_UUID_MOST_SIG = getNamespacedKey(STR_FURNACE_UUID_MOST_SIG);
NSK_FURNACE_UUID_LEAST_SIG = getNamespacedKey(STR_FURNACE_UUID_LEAST_SIG);
initializeLayer();
}
/**
* Helper method to simplify generating namespaced keys
* @param key the {@link String} value of the key
* @return the generated {@link NamespacedKey}
*/
private @NotNull NamespacedKey getNamespacedKey(@NotNull String key) {
return new NamespacedKey(mcMMO.p, key);
}
/**
* Whether or not a target {@link LivingEntity} has a specific mcMMO mob flags
* @param flag the type of mob flag to check for
* @param livingEntity the living entity to check for metadata
* @return true if the mob has metadata values for target {@link MobMetaFlagType}
*/
public abstract boolean hasMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity);
/**
* Whether or not a target {@link LivingEntity} has any mcMMO mob flags
* @param livingEntity the living entity to check for metadata
* @return true if the mob has any mcMMO mob related metadata values
*/
public abstract boolean hasMobFlags(@NotNull LivingEntity livingEntity);
/**
* Copies all mcMMO mob flags from one {@link LivingEntity} to another {@link LivingEntity}
* This does not clear existing mcMMO mob flags on the target
* @param sourceEntity entity to copy from
* @param targetEntity entity to copy to
*/
public abstract void addMobFlags(@NotNull LivingEntity sourceEntity, @NotNull LivingEntity targetEntity);
/**
* Adds a mob flag to a {@link LivingEntity} which effectively acts a true/false boolean
* Existence of the flag can be considered a true value, non-existence can be considered false for all intents and purposes
* @param flag the desired flag to assign
* @param livingEntity the target living entity
*/
public abstract void flagMetadata(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity);
/**
* Removes a specific mob flag from target {@link LivingEntity}
* @param flag desired flag to remove
* @param livingEntity the target living entity
*/
public abstract void removeMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity);
/**
* Remove all mcMMO related mob flags from the target {@link LivingEntity}
* @param livingEntity target entity
*/
public void removeMobFlags(@NotNull LivingEntity livingEntity) {
for(MobMetaFlagType flag : MobMetaFlagType.values()) {
removeMobFlag(flag, livingEntity);
}
}
public abstract @Nullable UUID getFurnaceOwner(@NotNull Furnace furnace);
public abstract void setFurnaceOwner(@NotNull Furnace furnace, @NotNull UUID uuid);
public abstract void setSuperAbilityBoostedItem(@NotNull ItemStack itemStack, int originalDigSpeed);
public abstract boolean isSuperAbilityBoosted(@NotNull ItemStack itemStack);
public abstract int getSuperAbilityToolOriginalDigSpeed(@NotNull ItemStack itemStack);
public abstract void removeBonusDigSpeedOnSuperAbilityTool(@NotNull ItemStack itemStack);
public boolean isLegacyAbilityTool(@NotNull ItemStack itemStack) {
ItemMeta itemMeta = itemStack.getItemMeta();
if(itemMeta == null)
return false;
List<String> lore = itemMeta.getLore();
if(lore == null || lore.isEmpty())
return false;
return lore.contains(LEGACY_ABILITY_TOOL_LORE);
}
public @NotNull String getLegacyAbilityToolLore() {
return LEGACY_ABILITY_TOOL_LORE;
}
}

View File

@@ -1,11 +0,0 @@
package com.gmail.nossr50.util.compat.layers.persistentdata;
public enum MobMetaFlagType {
MOB_SPAWNER_MOB,
EGG_MOB,
NETHER_PORTAL_MOB,
COTW_SUMMONED_MOB,
PLAYER_BRED_MOB,
PLAYER_TAMED_MOB,
EXPLOITED_ENDERMEN,
}

View File

@@ -1,189 +0,0 @@
package com.gmail.nossr50.util.compat.layers.persistentdata;
import com.gmail.nossr50.api.exceptions.IncompleteNamespacedKeyRegister;
import com.gmail.nossr50.datatypes.meta.UUIDMeta;
import com.gmail.nossr50.mcMMO;
import org.bukkit.block.Furnace;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.tags.CustomItemTagContainer;
import org.bukkit.inventory.meta.tags.ItemTagType;
import org.bukkit.metadata.Metadatable;
import org.jetbrains.annotations.NotNull;
import java.util.EnumMap;
import java.util.UUID;
/**
* Persistent Data API is unavailable
*/
public class SpigotPersistentDataLayer_1_13 extends AbstractPersistentDataLayer {
private final @NotNull String KEY_FURNACE_OWNER = "mcMMO_furnace_owner";
private final @NotNull EnumMap<MobMetaFlagType, String> mobFlagKeyMap;
public SpigotPersistentDataLayer_1_13() {
mobFlagKeyMap = new EnumMap<>(MobMetaFlagType.class);
initMobFlagKeyMap();
}
@Override
public boolean initializeLayer() {
return true;
}
private void initMobFlagKeyMap() throws IncompleteNamespacedKeyRegister {
for(MobMetaFlagType flagType : MobMetaFlagType.values()) {
switch(flagType) {
case MOB_SPAWNER_MOB:
mobFlagKeyMap.put(flagType, STR_MOB_SPAWNER_MOB);
break;
case EGG_MOB:
mobFlagKeyMap.put(flagType, STR_EGG_MOB);
break;
case NETHER_PORTAL_MOB:
mobFlagKeyMap.put(flagType, STR_NETHER_PORTAL_MOB);
break;
case COTW_SUMMONED_MOB:
mobFlagKeyMap.put(flagType, STR_COTW_SUMMONED_MOB);
break;
case PLAYER_BRED_MOB:
mobFlagKeyMap.put(flagType, STR_PLAYER_BRED_MOB);
break;
case PLAYER_TAMED_MOB:
mobFlagKeyMap.put(flagType, STR_PLAYER_TAMED_MOB);
break;
case EXPLOITED_ENDERMEN:
mobFlagKeyMap.put(flagType, STR_EXPLOITED_ENDERMEN);
break;
default:
throw new IncompleteNamespacedKeyRegister("Missing flag register for: "+flagType.toString());
}
}
}
@Override
public boolean hasMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) {
return livingEntity.hasMetadata(mobFlagKeyMap.get(flag));
}
@Override
public boolean hasMobFlags(@NotNull LivingEntity livingEntity) {
for(String currentKey : mobFlagKeyMap.values()) {
if(livingEntity.hasMetadata(currentKey)) {
return true;
}
}
return false;
}
@Override
public void addMobFlags(@NotNull LivingEntity sourceEntity, @NotNull LivingEntity targetEntity) {
for(MobMetaFlagType flag : MobMetaFlagType.values()) {
if(hasMobFlag(flag, sourceEntity)) {
flagMetadata(flag, targetEntity);
}
}
}
@Override
public void flagMetadata(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) {
if(!hasMobFlag(flag, livingEntity)) {
livingEntity.setMetadata(mobFlagKeyMap.get(flag), mcMMO.metadataValue);
}
}
@Override
public void removeMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) {
if(hasMobFlag(flag, livingEntity)) {
livingEntity.removeMetadata(mobFlagKeyMap.get(flag), mcMMO.p);
}
}
@Override
public UUID getFurnaceOwner(@NotNull Furnace furnace) {
Metadatable metadatable = (Metadatable) furnace;
if(metadatable.getMetadata(KEY_FURNACE_OWNER).size() > 0) {
UUIDMeta uuidMeta = (UUIDMeta) metadatable.getMetadata(KEY_FURNACE_OWNER).get(0);
return (UUID) uuidMeta.value();
} else {
return null;
}
}
@Override
public void setFurnaceOwner(@NotNull Furnace furnace, @NotNull UUID uuid) {
Metadatable metadatable = (Metadatable) furnace;
if(metadatable.getMetadata(KEY_FURNACE_OWNER).size() > 0) {
metadatable.removeMetadata(KEY_FURNACE_OWNER, mcMMO.p);
}
metadatable.setMetadata(KEY_FURNACE_OWNER, new UUIDMeta(mcMMO.p, uuid));
}
@Override
public void setSuperAbilityBoostedItem(@NotNull ItemStack itemStack, int originalDigSpeed) {
ItemMeta itemMeta = itemStack.getItemMeta();
if(itemMeta == null) {
mcMMO.p.getLogger().severe("Item meta should never be null for a super boosted item!");
return;
}
itemMeta.getCustomTagContainer().setCustomTag(NSK_SUPER_ABILITY_BOOSTED_ITEM, ItemTagType.INTEGER, originalDigSpeed);
itemStack.setItemMeta(itemMeta);
}
@Override
public boolean isSuperAbilityBoosted(@NotNull ItemStack itemStack) {
ItemMeta itemMeta = itemStack.getItemMeta();
if(itemMeta == null)
return false;
CustomItemTagContainer tagContainer = itemMeta.getCustomTagContainer();
return tagContainer.hasCustomTag(NSK_SUPER_ABILITY_BOOSTED_ITEM, ItemTagType.INTEGER);
}
@Override
public int getSuperAbilityToolOriginalDigSpeed(@NotNull ItemStack itemStack) {
ItemMeta itemMeta = itemStack.getItemMeta();
if(itemMeta == null)
return 0;
CustomItemTagContainer tagContainer = itemMeta.getCustomTagContainer();
if(tagContainer.hasCustomTag(NSK_SUPER_ABILITY_BOOSTED_ITEM, ItemTagType.INTEGER)) {
return tagContainer.getCustomTag(NSK_SUPER_ABILITY_BOOSTED_ITEM, ItemTagType.INTEGER);
} else {
return 0;
}
}
@Override
public void removeBonusDigSpeedOnSuperAbilityTool(@NotNull ItemStack itemStack) {
int originalSpeed = getSuperAbilityToolOriginalDigSpeed(itemStack);
ItemMeta itemMeta = itemStack.getItemMeta();
if(itemMeta == null)
return;
if(itemMeta.hasEnchant(Enchantment.DIG_SPEED)) {
itemMeta.removeEnchant(Enchantment.DIG_SPEED);
}
if(originalSpeed > 0) {
itemMeta.addEnchant(Enchantment.DIG_SPEED, originalSpeed, true);
}
//TODO: needed?
itemStack.setItemMeta(itemMeta);
}
}

View File

@@ -1,219 +0,0 @@
package com.gmail.nossr50.util.compat.layers.persistentdata;
import com.gmail.nossr50.api.exceptions.IncompleteNamespacedKeyRegister;
import com.gmail.nossr50.config.PersistentDataConfig;
import com.gmail.nossr50.mcMMO;
import org.bukkit.NamespacedKey;
import org.bukkit.block.Furnace;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.LivingEntity;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
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.EnumMap;
import java.util.UUID;
public class SpigotPersistentDataLayer_1_14 extends AbstractPersistentDataLayer {
private final @NotNull EnumMap<MobMetaFlagType, NamespacedKey> mobFlagKeyMap;
private final @NotNull SpigotPersistentDataLayer_1_13 transientLayer;
public SpigotPersistentDataLayer_1_14() {
mobFlagKeyMap = new EnumMap<>(MobMetaFlagType.class);
initMobFlagKeyMap();
transientLayer = new SpigotPersistentDataLayer_1_13(); //For disabled persistent types
}
@Override
public boolean initializeLayer() {
return true;
}
/**
* Registers the namespaced keys required by the API (CB/Spigot)
*/
private void initMobFlagKeyMap() throws IncompleteNamespacedKeyRegister {
for(MobMetaFlagType mobMetaFlagType : MobMetaFlagType.values()) {
switch(mobMetaFlagType) {
case MOB_SPAWNER_MOB:
mobFlagKeyMap.put(mobMetaFlagType, NSK_MOB_SPAWNER_MOB);
break;
case EGG_MOB:
mobFlagKeyMap.put(mobMetaFlagType, NSK_EGG_MOB);
break;
case NETHER_PORTAL_MOB:
mobFlagKeyMap.put(mobMetaFlagType, NSK_NETHER_GATE_MOB);
break;
case COTW_SUMMONED_MOB:
mobFlagKeyMap.put(mobMetaFlagType, NSK_COTW_SUMMONED_MOB);
break;
case PLAYER_BRED_MOB:
mobFlagKeyMap.put(mobMetaFlagType, NSK_PLAYER_BRED_MOB);
break;
case EXPLOITED_ENDERMEN:
mobFlagKeyMap.put(mobMetaFlagType, NSK_EXPLOITED_ENDERMEN);
break;
case PLAYER_TAMED_MOB:
mobFlagKeyMap.put(mobMetaFlagType, NSK_PLAYER_TAMED_MOB);
break;
default:
throw new IncompleteNamespacedKeyRegister("missing namespaced key register for type: "+ mobMetaFlagType.toString());
}
}
}
@Override
public boolean hasMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) {
if(PersistentDataConfig.getInstance().isMobPersistent(flag)) {
return livingEntity.getPersistentDataContainer().has(mobFlagKeyMap.get(flag), PersistentDataType.BYTE);
} else {
return transientLayer.hasMobFlag(flag, livingEntity);
}
}
@Override
public boolean hasMobFlags(@NotNull LivingEntity livingEntity) {
for(MobMetaFlagType currentFlag : MobMetaFlagType.values()) {
if(hasMobFlag(currentFlag, livingEntity)) {
return true;
}
}
return false;
}
@Override
public void addMobFlags(@NotNull LivingEntity sourceEntity, @NotNull LivingEntity targetEntity) {
for(MobMetaFlagType flag : MobMetaFlagType.values()) {
if(hasMobFlag(flag, sourceEntity)) {
flagMetadata(flag, targetEntity);
}
}
}
@Override
public void flagMetadata(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) {
if(PersistentDataConfig.getInstance().isMobPersistent(flag)) {
if(!hasMobFlag(flag, livingEntity)) {
PersistentDataContainer persistentDataContainer = livingEntity.getPersistentDataContainer();
persistentDataContainer.set(mobFlagKeyMap.get(flag), PersistentDataType.BYTE, SIMPLE_FLAG_VALUE);
}
} else {
transientLayer.flagMetadata(flag, livingEntity);
}
}
@Override
public void removeMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) {
if(PersistentDataConfig.getInstance().isMobPersistent(flag)) {
if(hasMobFlag(flag, livingEntity)) {
PersistentDataContainer persistentDataContainer = livingEntity.getPersistentDataContainer();
persistentDataContainer.remove(mobFlagKeyMap.get(flag));
}
} else {
transientLayer.removeMobFlag(flag, livingEntity);
}
}
@Override
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;
}
}
@Override
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();
}
@Override
public 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;
}
ItemMeta itemMeta = itemStack.getItemMeta();
PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer();
dataContainer.set(NSK_SUPER_ABILITY_BOOSTED_ITEM, PersistentDataType.INTEGER, originalDigSpeed);
itemStack.setItemMeta(itemMeta);
}
@Override
public boolean isSuperAbilityBoosted(@NotNull ItemStack itemStack) {
if(itemStack.getItemMeta() == null)
return false;
ItemMeta itemMeta = itemStack.getItemMeta();
//Get container from entity
PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer();
//If this value isn't null, then the tool can be considered dig speed boosted
Integer boostValue = dataContainer.get(NSK_SUPER_ABILITY_BOOSTED_ITEM, PersistentDataType.INTEGER);
return boostValue != null;
}
@Override
public int getSuperAbilityToolOriginalDigSpeed(@NotNull ItemStack itemStack) {
//Get container from entity
ItemMeta itemMeta = itemStack.getItemMeta();
if(itemMeta == null)
return 0;
PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer();
if(dataContainer.get(NSK_SUPER_ABILITY_BOOSTED_ITEM, PersistentDataType.INTEGER) == null) {
mcMMO.p.getLogger().severe("Value should never be null for a boosted item");
return 0;
} else {
//Too lazy to make a custom data type for this stuff
Integer boostValue = dataContainer.get(NSK_SUPER_ABILITY_BOOSTED_ITEM, PersistentDataType.INTEGER);
return Math.max(boostValue, 0);
}
}
@Override
public void removeBonusDigSpeedOnSuperAbilityTool(@NotNull ItemStack itemStack) {
int originalSpeed = getSuperAbilityToolOriginalDigSpeed(itemStack);
ItemMeta itemMeta = itemStack.getItemMeta();
//TODO: can be optimized
if(itemMeta.hasEnchant(Enchantment.DIG_SPEED)) {
itemMeta.removeEnchant(Enchantment.DIG_SPEED);
}
if(originalSpeed > 0) {
itemMeta.addEnchant(Enchantment.DIG_SPEED, originalSpeed, true);
}
PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer();
dataContainer.remove(NSK_SUPER_ABILITY_BOOSTED_ITEM); //Remove persistent data
//TODO: needed?
itemStack.setItemMeta(itemMeta);
}
}

View File

@@ -77,7 +77,7 @@ public class ExperienceBarManager {
return;
ExperienceBarHideTask experienceBarHideTask = new ExperienceBarHideTask(this, mcMMOPlayer, primarySkillType);
experienceBarHideTask.runTaskLater(plugin, 20* delaySeconds);
experienceBarHideTask.runTaskLater(plugin, 20L * delaySeconds);
experienceBarHideTaskHashMap.put(primarySkillType, experienceBarHideTask);
}
@@ -146,10 +146,10 @@ public class ExperienceBarManager {
disabledBars.add(PrimarySkillType.SMELTING);
}
private void informPlayer(@NotNull ExperienceBarManager.@NotNull XPBarSettingTarget settingTarget, @Nullable PrimarySkillType skillType) {
private void informPlayer(@NotNull ExperienceBarManager.@NotNull XPBarSettingTarget settingTarget, @Nullable PrimarySkillType primarySkillType) {
//Inform player of setting change
if(settingTarget != XPBarSettingTarget.RESET) {
NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.SettingChanged", skillType.getName(), settingTarget.toString());
NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.SettingChanged", mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType), settingTarget.toString());
} else {
NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.Reset");
}

View File

@@ -14,7 +14,7 @@ import org.bukkit.entity.Player;
import java.util.List;
/**
* A visual representation of a players skill level progress for a PrimarySkillType
* A visual representation of a player's skill level progress for a PrimarySkillType
*/
public class ExperienceBarWrapper {

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util.experience;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.experience.FormulaType;
import com.gmail.nossr50.datatypes.skills.PrimarySkillType;
@@ -89,7 +88,7 @@ public class FormulaManager {
public int[] calculateNewLevel(PrimarySkillType primarySkillType, int experience, FormulaType formulaType) {
int newLevel = 0;
int remainder = 0;
int maxLevel = Config.getInstance().getLevelCap(primarySkillType);
int maxLevel = mcMMO.p.getSkillTools().getLevelCap(primarySkillType);
while (experience > 0 && newLevel < maxLevel) {
int experienceToNextLevel = getXPtoNextLevel(newLevel, formulaType);

View File

@@ -22,6 +22,7 @@ public enum NMSVersion {
NMS_1_16_3("1.16.3"),
NMS_1_16_4("1.16.4"),
NMS_1_16_5("1.16.5"),
NMS_1_17("1.17"),
//Version not known to this build of mcMMO
UNSUPPORTED("unsupported");

View File

@@ -32,11 +32,7 @@ public abstract class MajorMinorPatchVersion implements Versioned {
this.majorVersion = majorVersion;
this.minorVersion = minorVersion;
if(patchVersion == null) {
this.patchVersion = new SimpleNumericVersion(0);
} else {
this.patchVersion = patchVersion;
}
this.patchVersion = Objects.requireNonNullElseGet(patchVersion, () -> new SimpleNumericVersion(0));
}
public MajorMinorPatchVersion(int majorVerNumber, int minorVerNumber, int patchVerNumber) {

View File

@@ -27,4 +27,37 @@ public class MinecraftGameVersion extends MajorMinorPatchVersion {
super(majorVerNumber, minorVerNumber);
}
/**
* Returns whether or not the Minecraft version is at least equal to or higher than a target version
* @param majorVerNumber target major version number - for example 1.16.5 , the 1 is the major version
* @param minorVerNumber target minor version number - for example 1.16.5, the 16 is the minor version
* @param patchVerNumber target patch version number - for example 1.16.5, the 5 is the patch version number
*
* @return returns true if Minecraft is at least a certain version
*/
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) {
return true; //Major version is one higher and hierarchically more important than the other versions
}
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) {
return true; //Minor version is one higher and hierarchically more important than patch version, so exit here
}
if(getMinorVersion().asInt() < minorVerNumber) {
return false; //Minor version is at least one version behind, return false
}
//Minor version meets the requirement, check patch version
return getPatchVersion().asInt() >= patchVerNumber;
}
}

View File

@@ -6,9 +6,9 @@ import org.bukkit.Bukkit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
@@ -47,18 +47,19 @@ public class PlatformManager {
private @NotNull MinecraftGameVersion determineGameVersion(String platformVersionString) {
int major = 0, minor = 0, patch = 0;
String[] splitVersion = platformVersionString.split("\\.", 3);
mcMMO.p.getLogger().info("Platform String: " + platformVersionString);
//TODO: this is very hacky and probably isn't reliable
//Grab all consecutive digits
major = getSubsequentDigits(splitVersion[0].toCharArray(), 0);
minor = getSubsequentDigits(splitVersion[1].toCharArray(), 0);
//Not all versions of Minecraft have a patch digit
//If the first character isn't a digit it's not a patch number and its some crap we don't care about
if(splitVersion.length > 2 && Character.isDigit(splitVersion[2].toCharArray()[0]))
patch = getSubsequentDigits(splitVersion[2].toCharArray(), 0);
// Gets two numbers separated by . and optional third number after next dot. Must end with - or _
Matcher versionMatch = Pattern.compile("(\\d+)\\.(\\d+)(?:\\.(\\d+))?[-_].*").matcher(platformVersionString);
if (versionMatch.find()) {
major = Integer.parseInt(versionMatch.group(1));
minor = Integer.parseInt(versionMatch.group(2));
if (versionMatch.group(3) != null) {
patch = Integer.parseInt(versionMatch.group(3));
}
}
mcMMO.p.getLogger().info("Minecraft version determined to be - "
+ major + "."
@@ -68,34 +69,6 @@ public class PlatformManager {
return new MinecraftGameVersion(major, minor, patch);
}
/**
* Get all consecutive digits in a char array from position
* @param charArray target char array
* @param position starting position
* @return all consecutive digits from position
*/
private int getSubsequentDigits(char[] charArray, int position) {
ArrayList<Character> digitArrayList = new ArrayList<>();
do {
if(Character.isDigit(charArray[position])) {
digitArrayList.add(charArray[position]);
position++;
} else {
break;
}
} while (position < charArray.length);
//Convert List<Character> -> String
String digits = digitArrayList
.stream()
.map(String::valueOf)
.collect(Collectors.joining());
//Copy value
return Integer.parseInt(digits);
}
//TODO: Rewrite this properly once we actually support a not-bukkit platform
private @NotNull ServerSoftwareType determinePlatformType() {
if(Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("paper"))

View File

@@ -1,7 +1,5 @@
package com.gmail.nossr50.util.player;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.LevelUpBroadcastPredicate;
import com.gmail.nossr50.datatypes.PowerLevelUpBroadcastPredicate;
import com.gmail.nossr50.datatypes.interactions.NotificationType;
@@ -23,6 +21,7 @@ import net.kyori.adventure.identity.Identity;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Server;
@@ -50,7 +49,7 @@ public class NotificationManager {
if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications())
return;
McMMOMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
McMMOMessageType destination = mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
Component message = TextComponentFactory.getNotificationTextComponentFromLocale(key);
McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(player, notificationType, destination, message);
@@ -105,7 +104,7 @@ public class NotificationManager {
if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications())
return;
McMMOMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
McMMOMessageType destination = mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
Component message = TextComponentFactory.getNotificationMultipleValues(key, values);
McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(player, notificationType, destination, message);
@@ -137,7 +136,7 @@ public class NotificationManager {
private static McMMOPlayerNotificationEvent checkNotificationEvent(Player player, NotificationType notificationType, McMMOMessageType destination, Component message) {
//Init event
McMMOPlayerNotificationEvent customEvent = new McMMOPlayerNotificationEvent(player,
notificationType, message, destination, AdvancedConfig.getInstance().doesNotificationSendCopyToChat(notificationType));
notificationType, message, destination, mcMMO.p.getAdvancedConfig().doesNotificationSendCopyToChat(notificationType));
//Call event
Bukkit.getServer().getPluginManager().callEvent(customEvent);
@@ -155,7 +154,7 @@ public class NotificationManager {
if(!mcMMOPlayer.useChatNotifications())
return;
McMMOMessageType destination = AdvancedConfig.getInstance().doesNotificationUseActionBar(NotificationType.LEVEL_UP_MESSAGE) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
McMMOMessageType destination = mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(NotificationType.LEVEL_UP_MESSAGE) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM;
Component levelUpTextComponent = TextComponentFactory.getNotificationLevelUpTextComponent(skillName, levelsGained, newLevel);
McMMOPlayerNotificationEvent customEvent = checkNotificationEvent(mcMMOPlayer.getPlayer(), NotificationType.LEVEL_UP_MESSAGE, destination, levelUpTextComponent);
@@ -183,7 +182,7 @@ public class NotificationManager {
SoundManager.sendCategorizedSound(mcMMOPlayer.getPlayer(), mcMMOPlayer.getPlayer().getLocation(), SoundType.SKILL_UNLOCKED, SoundCategory.MASTER);
//ACTION BAR MESSAGE
/*if(AdvancedConfig.getInstance().doesNotificationUseActionBar(NotificationType.SUBSKILL_UNLOCKED))
/*if(mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(NotificationType.SUBSKILL_UNLOCKED))
mcMMOPlayer.getPlayer().spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(LocaleLoader.getString("JSON.SkillUnlockMessage",
subSkillType.getLocaleName(),
String.valueOf(RankUtils.getRank(mcMMOPlayer.getPlayer(),
@@ -197,7 +196,7 @@ public class NotificationManager {
*/
private static void sendAdminNotification(String msg) {
//If its not enabled exit
if(!Config.getInstance().adminNotifications())
if(!mcMMO.p.getGeneralConfig().adminNotifications())
return;
for(Player player : Bukkit.getServer().getOnlinePlayers())
@@ -274,13 +273,13 @@ public class NotificationManager {
return;
//Check if broadcasting is enabled
if(Config.getInstance().shouldLevelUpBroadcasts()) {
if(mcMMO.p.getGeneralConfig().shouldLevelUpBroadcasts()) {
//Permission check
if(!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) {
return;
}
int levelInterval = Config.getInstance().getLevelUpBroadcastInterval();
int levelInterval = mcMMO.p.getGeneralConfig().getLevelUpBroadcastInterval();
int remainder = level % levelInterval;
if(remainder == 0) {
@@ -291,11 +290,11 @@ public class NotificationManager {
.append(Component.newline())
.append(Component.text(LocalDate.now().toString()))
.append(Component.newline())
.append(Component.text(primarySkillType.getName()+" reached level "+level)).color(TextColor.fromHexString(HEX_BEIGE_COLOR))
.append(Component.text(mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType)+" reached level "+level)).color(TextColor.fromHexString(HEX_BEIGE_COLOR))
.asHoverEvent();
String localeMessage = LocaleLoader.getString("Broadcasts.LevelUpMilestone", mmoPlayer.getPlayer().getDisplayName(), level, primarySkillType.getName());
Component message = Component.text(localeMessage).hoverEvent(levelMilestoneHover);
String localeMessage = LocaleLoader.getString("Broadcasts.LevelUpMilestone", mmoPlayer.getPlayer().getDisplayName(), level, mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType));
Component message = LegacyComponentSerializer.legacySection().deserialize(localeMessage).hoverEvent(levelMilestoneHover);
Bukkit.getScheduler().runTaskLater(mcMMO.p, () -> audience.sendMessage(Identity.nil(), message), 0);
}
@@ -309,13 +308,13 @@ public class NotificationManager {
return;
//Check if broadcasting is enabled
if(Config.getInstance().shouldPowerLevelUpBroadcasts()) {
if(mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcasts()) {
//Permission check
if(!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) {
return;
}
int levelInterval = Config.getInstance().getPowerLevelUpBroadcastInterval();
int levelInterval = mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastInterval();
int remainder = powerLevel % levelInterval;
if(remainder == 0) {
@@ -330,7 +329,7 @@ public class NotificationManager {
.asHoverEvent();
String localeMessage = LocaleLoader.getString("Broadcasts.PowerLevelUpMilestone", mmoPlayer.getPlayer().getDisplayName(), powerLevel);
Component message = Component.text(localeMessage).hoverEvent(levelMilestoneHover);
Component message = LegacyComponentSerializer.legacySection().deserialize(localeMessage).hoverEvent(levelMilestoneHover);
Bukkit.getScheduler().runTaskLater(mcMMO.p, () -> audience.sendMessage(Identity.nil(), message), 0);
}

View File

@@ -2,11 +2,14 @@ package com.gmail.nossr50.util.player;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.MetadataConstants;
import com.google.common.collect.ImmutableList;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.metadata.FixedMetadataValue;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collection;
@@ -23,8 +26,8 @@ public final class UserManager {
*
* @param mcMMOPlayer the player profile to start tracking
*/
public static void track(McMMOPlayer mcMMOPlayer) {
mcMMOPlayer.getPlayer().setMetadata(mcMMO.playerDataKey, new FixedMetadataValue(mcMMO.p, mcMMOPlayer));
public static void track(@NotNull McMMOPlayer mcMMOPlayer) {
mcMMOPlayer.getPlayer().setMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, new FixedMetadataValue(mcMMO.p, mcMMOPlayer));
if(playerDataSet == null)
playerDataSet = new HashSet<>();
@@ -42,10 +45,14 @@ public final class UserManager {
*
* @param player The Player object
*/
public static void remove(Player player) {
public static void remove(@NotNull Player player) {
McMMOPlayer mcMMOPlayer = getPlayer(player);
if(mcMMOPlayer == null)
return;
mcMMOPlayer.cleanup();
player.removeMetadata(mcMMO.playerDataKey, mcMMO.p);
player.removeMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, mcMMO.p);
if(playerDataSet != null) {
playerDataSet.remove(mcMMOPlayer); //Clear sync save tracking
@@ -90,7 +97,7 @@ public final class UserManager {
mcMMO.p.getLogger().info("Finished save operation for "+trackedSyncData.size()+" players!");
}
public static Collection<McMMOPlayer> getPlayers() {
public static @NotNull Collection<McMMOPlayer> getPlayers() {
Collection<McMMOPlayer> playerCollection = new ArrayList<>();
for (Player player : mcMMO.p.getServer().getOnlinePlayers()) {
@@ -108,11 +115,11 @@ public final class UserManager {
* @param playerName The name of the player whose McMMOPlayer to retrieve
* @return the player's McMMOPlayer object
*/
public static McMMOPlayer getPlayer(String playerName) {
public static @Nullable McMMOPlayer getPlayer(String playerName) {
return retrieveMcMMOPlayer(playerName, false);
}
public static McMMOPlayer getOfflinePlayer(OfflinePlayer player) {
public static @Nullable McMMOPlayer getOfflinePlayer(OfflinePlayer player) {
if (player instanceof Player) {
return getPlayer((Player) player);
}
@@ -120,7 +127,7 @@ public final class UserManager {
return retrieveMcMMOPlayer(player.getName(), true);
}
public static McMMOPlayer getOfflinePlayer(String playerName) {
public static @Nullable McMMOPlayer getOfflinePlayer(String playerName) {
return retrieveMcMMOPlayer(playerName, true);
}
@@ -129,15 +136,18 @@ public final class UserManager {
* @param player target player
* @return McMMOPlayer object for this player, null if Player has not been loaded
*/
public static McMMOPlayer getPlayer(Player player) {
public static @Nullable McMMOPlayer getPlayer(@Nullable Player player) {
//Avoid Array Index out of bounds
if(player != null && player.hasMetadata(mcMMO.playerDataKey))
return (McMMOPlayer) player.getMetadata(mcMMO.playerDataKey).get(0).value();
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 McMMOPlayer retrieveMcMMOPlayer(String playerName, boolean offlineValid) {
private static @Nullable McMMOPlayer retrieveMcMMOPlayer(@Nullable String playerName, boolean offlineValid) {
if(playerName == null)
return null;
Player player = mcMMO.p.getServer().getPlayerExact(playerName);
if (player == null) {
@@ -151,7 +161,7 @@ public final class UserManager {
return getPlayer(player);
}
public static boolean hasPlayerDataKey(Entity entity) {
return entity != null && entity.hasMetadata(mcMMO.playerDataKey);
public static boolean hasPlayerDataKey(@Nullable Entity entity) {
return entity != null && entity.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA);
}
}

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util.scoreboards;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
@@ -21,6 +20,7 @@ import org.bukkit.entity.Player;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Scoreboard;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
@@ -71,7 +71,7 @@ public class ScoreboardManager {
* Stylizes the targetBoard in a Rainbow Pattern
* This is off by default
*/
if (Config.getInstance().getScoreboardRainbows()) {
if (mcMMO.p.getGeneralConfig().getScoreboardRainbows()) {
// Everything but black, gray, gold
List<ChatColor> colors = Lists.newArrayList(
ChatColor.WHITE,
@@ -91,14 +91,14 @@ public class ScoreboardManager {
Collections.shuffle(colors, Misc.getRandom());
int i = 0;
for (PrimarySkillType type : PrimarySkillType.values()) {
for (PrimarySkillType primarySkillType : PrimarySkillType.values()) {
// Include child skills
skillLabelBuilder.put(type, getShortenedName(colors.get(i) + type.getName(), false));
skillLabelBuilder.put(primarySkillType, getShortenedName(colors.get(i) + mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType), false));
if (type.getAbility() != null) {
abilityLabelBuilder.put(type.getAbility(), getShortenedName(colors.get(i) + type.getAbility().getLocalizedName()));
if (mcMMO.p.getSkillTools().getSuperAbility(primarySkillType) != null) {
abilityLabelBuilder.put(mcMMO.p.getSkillTools().getSuperAbility(primarySkillType), getShortenedName(colors.get(i) + mcMMO.p.getSkillTools().getSuperAbility(primarySkillType).getLocalizedName()));
if (type == PrimarySkillType.MINING) {
if (primarySkillType == PrimarySkillType.MINING) {
abilityLabelBuilder.put(SuperAbilityType.BLAST_MINING, getShortenedName(colors.get(i) + SuperAbilityType.BLAST_MINING.getLocalizedName()));
}
}
@@ -113,14 +113,14 @@ public class ScoreboardManager {
* Stylizes the targetBoard using our normal color scheme
*/
else {
for (PrimarySkillType type : PrimarySkillType.values()) {
for (PrimarySkillType primarySkillType : PrimarySkillType.values()) {
// Include child skills
skillLabelBuilder.put(type, getShortenedName(ChatColor.GREEN + type.getName()));
skillLabelBuilder.put(primarySkillType, getShortenedName(ChatColor.GREEN + mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType)));
if (type.getAbility() != null) {
abilityLabelBuilder.put(type.getAbility(), formatAbility(type.getAbility().getLocalizedName()));
if (mcMMO.p.getSkillTools().getSuperAbility(primarySkillType) != null) {
abilityLabelBuilder.put(mcMMO.p.getSkillTools().getSuperAbility(primarySkillType), formatAbility(mcMMO.p.getSkillTools().getSuperAbility(primarySkillType).getLocalizedName()));
if (type == PrimarySkillType.MINING) {
if (primarySkillType == PrimarySkillType.MINING) {
abilityLabelBuilder.put(SuperAbilityType.BLAST_MINING, formatAbility(SuperAbilityType.BLAST_MINING.getLocalizedName()));
}
}
@@ -152,7 +152,7 @@ public class ScoreboardManager {
}
private static String formatAbility(ChatColor color, String abilityName) {
if (Config.getInstance().getShowAbilityNames()) {
if (mcMMO.p.getGeneralConfig().getShowAbilityNames()) {
return getShortenedName(color + abilityName);
}
else {
@@ -243,11 +243,11 @@ public class ScoreboardManager {
}
}
if (Config.getInstance().getPowerLevelTagsEnabled() && !dirtyPowerLevels.contains(playerName)) {
if (mcMMO.p.getGeneralConfig().getPowerLevelTagsEnabled() && !dirtyPowerLevels.contains(playerName)) {
dirtyPowerLevels.add(playerName);
}
if (Config.getInstance().getSkillLevelUpBoard()) {
if (mcMMO.p.getGeneralConfig().getSkillLevelUpBoard()) {
enablePlayerSkillLevelUpScoreboard(player, skill);
}
@@ -284,6 +284,9 @@ public class ScoreboardManager {
// **** Setup methods **** //
public static void enablePlayerSkillScoreboard(Player player, PrimarySkillType skill) {
McMMOPlayer mmoPlayer = UserManager.getPlayer(player);
mmoPlayer.setLastSkillShownScoreboard(skill);
ScoreboardWrapper wrapper = getWrapper(player);
if(wrapper == null) {
@@ -295,7 +298,26 @@ public class ScoreboardManager {
wrapper.setOldScoreboard();
wrapper.setTypeSkill(skill);
changeScoreboard(wrapper, Config.getInstance().getSkillScoreboardTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getSkillScoreboardTime());
}
}
public static void retryLastSkillBoard(Player player) {
McMMOPlayer mmoPlayer = UserManager.getPlayer(player);
PrimarySkillType primarySkillType = mmoPlayer.getLastSkillShownScoreboard();
ScoreboardWrapper wrapper = getWrapper(player);
if(wrapper == null) {
setupPlayer(player);
wrapper = getWrapper(player);
}
if(wrapper != null) {
wrapper.setOldScoreboard();
wrapper.setTypeSkill(primarySkillType);
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getSkillScoreboardTime());
}
}
@@ -310,7 +332,7 @@ public class ScoreboardManager {
wrapper.setOldScoreboard();
wrapper.setTypeSkill(skill);
changeScoreboard(wrapper, Config.getInstance().getSkillLevelUpTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getSkillLevelUpTime());
}
}
@@ -324,10 +346,10 @@ public class ScoreboardManager {
wrapper.setOldScoreboard();
wrapper.setTypeSelfStats();
changeScoreboard(wrapper, Config.getInstance().getStatsScoreboardTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getStatsScoreboardTime());
}
public static void enablePlayerInspectScoreboard(Player player, PlayerProfile targetProfile) {
public static void enablePlayerInspectScoreboard(@NotNull Player player, @NotNull PlayerProfile targetProfile) {
ScoreboardWrapper wrapper = getWrapper(player);
if(wrapper == null) {
@@ -339,7 +361,23 @@ public class ScoreboardManager {
wrapper.setOldScoreboard();
wrapper.setTypeInspectStats(targetProfile);
changeScoreboard(wrapper, Config.getInstance().getInspectScoreboardTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getInspectScoreboardTime());
}
}
public static void enablePlayerInspectScoreboard(@NotNull Player player, @NotNull McMMOPlayer targetMcMMOPlayer) {
ScoreboardWrapper wrapper = getWrapper(player);
if(wrapper == null) {
setupPlayer(player);
wrapper = getWrapper(player);
}
if(wrapper != null) {
wrapper.setOldScoreboard();
wrapper.setTypeInspectStats(targetMcMMOPlayer);
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getInspectScoreboardTime());
}
}
@@ -355,7 +393,7 @@ public class ScoreboardManager {
wrapper.setOldScoreboard();
wrapper.setTypeCooldowns();
changeScoreboard(wrapper, Config.getInstance().getCooldownScoreboardTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getCooldownScoreboardTime());
}
}
@@ -372,7 +410,7 @@ public class ScoreboardManager {
wrapper.setTypeSelfRank();
wrapper.acceptRankData(rank);
changeScoreboard(wrapper, Config.getInstance().getRankScoreboardTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getRankScoreboardTime());
}
}
@@ -389,7 +427,7 @@ public class ScoreboardManager {
wrapper.setTypeInspectRank(targetName);
wrapper.acceptRankData(rank);
changeScoreboard(wrapper, Config.getInstance().getRankScoreboardTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getRankScoreboardTime());
}
}
@@ -407,7 +445,7 @@ public class ScoreboardManager {
wrapper.setTypeTop(skill, pageNumber);
wrapper.acceptLeaderboardData(stats);
changeScoreboard(wrapper, Config.getInstance().getTopScoreboardTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getTopScoreboardTime());
}
}
@@ -424,7 +462,7 @@ public class ScoreboardManager {
wrapper.setTypeTopPower(pageNumber);
wrapper.acceptLeaderboardData(stats);
changeScoreboard(wrapper, Config.getInstance().getTopScoreboardTime());
changeScoreboard(wrapper, mcMMO.p.getGeneralConfig().getTopScoreboardTime());
}
}
@@ -478,7 +516,7 @@ public class ScoreboardManager {
* @return the main targetBoard objective, or null if disabled
*/
public static @Nullable Objective getPowerLevelObjective() {
if (!Config.getInstance().getPowerLevelTagsEnabled()) {
if (!mcMMO.p.getGeneralConfig().getPowerLevelTagsEnabled()) {
if(getScoreboardManager() == null)
return null;
@@ -511,8 +549,7 @@ public class ScoreboardManager {
return mcMMO.p.getServer().getScoreboardManager();
}
private static void changeScoreboard(ScoreboardWrapper wrapper, int displayTime) {
public static void changeScoreboard(ScoreboardWrapper wrapper, int displayTime) {
if (displayTime == -1) {
wrapper.showBoardWithNoRevert();
}
@@ -537,6 +574,10 @@ public class ScoreboardManager {
PLAYER_SCOREBOARDS.get(playerName).showBoardAndScheduleRevert(seconds * Misc.TICK_CONVERSION_FACTOR);
}
public static boolean isPlayerBoardSetup(@NotNull String playerName) {
return PLAYER_SCOREBOARDS.get(playerName) != null;
}
public static @Nullable ScoreboardWrapper makeNewScoreboard(Player player) {
if(getScoreboardManager() == null)
return null;

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util.scoreboards;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.database.PlayerStat;
import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.datatypes.player.PlayerProfile;
@@ -14,9 +13,12 @@ import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.skills.child.FamilyTree;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.scoreboards.ScoreboardManager.SidebarType;
import com.gmail.nossr50.util.skills.SkillTools;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
@@ -25,6 +27,7 @@ import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Map;
@@ -42,7 +45,7 @@ public class ScoreboardWrapper {
// Internal usage variables (should exist)
private SidebarType sidebarType;
private Objective sidebarObjective;
private final Objective powerObjective;
private Objective powerObjective;
// Parameter variables (May be null / invalid)
private Scoreboard oldBoard = null;
@@ -50,16 +53,29 @@ public class ScoreboardWrapper {
public PrimarySkillType targetSkill = null;
private PlayerProfile targetProfile = null;
public int leaderboardPage = -1;
private boolean registered = false;
public ScoreboardWrapper(Player player, Scoreboard scoreboard) {
this.player = player;
this.playerName = player.getName();
this.scoreboard = scoreboard;
sidebarType = SidebarType.NONE;
sidebarObjective = this.scoreboard.registerNewObjective(ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy", SIDE_OBJECTIVE);
powerObjective = this.scoreboard.registerNewObjective(ScoreboardManager.POWER_OBJECTIVE, "dummy", POWER_OBJECTIVE);
initBoard();
}
if (Config.getInstance().getPowerLevelTagsEnabled()) {
private void initBoard() {
sidebarType = SidebarType.NONE;
if(registered) {
//Make sure our references are pointed at the right things
sidebarObjective = scoreboard.getObjective(ScoreboardManager.SIDEBAR_OBJECTIVE);
powerObjective = scoreboard.getObjective(ScoreboardManager.POWER_OBJECTIVE);
} else {
//Register Objectives
sidebarObjective = this.scoreboard.registerNewObjective(ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy", SIDE_OBJECTIVE);
powerObjective = this.scoreboard.registerNewObjective(ScoreboardManager.POWER_OBJECTIVE, "dummy", POWER_OBJECTIVE);
registered = true;
}
if (mcMMO.p.getGeneralConfig().getPowerLevelTagsEnabled()) {
powerObjective.setDisplayName(ScoreboardManager.TAG_POWER_LEVEL);
powerObjective.setDisplaySlot(DisplaySlot.BELOW_NAME);
@@ -125,7 +141,8 @@ public class ScoreboardWrapper {
try {
cooldownTask.cancel();
}
catch (Throwable ignored) {
catch (Exception e) {
e.printStackTrace();
}
cooldownTask = null;
@@ -208,7 +225,7 @@ public class ScoreboardWrapper {
PlayerProfile profile = UserManager.getPlayer(player).getProfile();
if (profile.getScoreboardTipsShown() >= Config.getInstance().getTipsAmount()) {
if (profile.getScoreboardTipsShown() >= mcMMO.p.getGeneralConfig().getTipsAmount()) {
return;
}
@@ -322,6 +339,17 @@ public class ScoreboardWrapper {
loadObjective(LocaleLoader.getString("Scoreboard.Header.PlayerInspect", targetPlayer));
}
public void setTypeInspectStats(@NotNull McMMOPlayer mcMMOPlayer) {
this.sidebarType = SidebarType.STATS_BOARD;
targetPlayer = mcMMOPlayer.getPlayer().getName();
targetProfile = mcMMOPlayer.getProfile();
targetSkill = null;
leaderboardPage = -1;
loadObjective(LocaleLoader.getString("Scoreboard.Header.PlayerInspect", targetPlayer));
}
public void setTypeCooldowns() {
this.sidebarType = SidebarType.COOLDOWNS_BOARD;
@@ -386,7 +414,19 @@ public class ScoreboardWrapper {
//Unregister objective
McMMOScoreboardObjectiveEvent unregisterEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.UNREGISTER_THIS_OBJECTIVE);
if(!unregisterEvent.isCancelled()) {
sidebarObjective.unregister();
try {
sidebarObjective.unregister();
} catch (IllegalStateException e) {
McMMOPlayer mmoPlayer = UserManager.getPlayer(player);
mcMMO.p.debug("Recovering scoreboard for player: " + player.getName());
if(mmoPlayer.isDebugMode())
NotificationManager.sendPlayerInformationChatOnlyPrefixed(player, "Scoreboard.Recovery");
initBoard(); //Start over
Bukkit.getScheduler().runTaskLater(mcMMO.p, () -> ScoreboardManager.retryLastSkillBoard(player), 0);
}
}
//Register objective
@@ -415,13 +455,16 @@ public class ScoreboardWrapper {
* Load new values into the sidebar.
*/
private void updateSidebar() {
try {
updateTask.cancel();
}
catch (Throwable ignored) {
} // catch NullPointerException and IllegalStateException and any Error; don't care
if(updateTask != null) {
try {
updateTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
updateTask = null;
}
updateTask = null;
if (sidebarType == SidebarType.NONE) {
return;
@@ -446,7 +489,7 @@ public class ScoreboardWrapper {
case SKILL_BOARD:
Validate.notNull(targetSkill);
if (!targetSkill.isChildSkill()) {
if (!SkillTools.isChildSkill(targetSkill)) {
int currentXP = mcMMOPlayer.getSkillXpLevel(targetSkill);
sidebarObjective.getScore(ScoreboardManager.LABEL_CURRENT_XP).setScore(currentXP);
@@ -460,7 +503,7 @@ public class ScoreboardWrapper {
sidebarObjective.getScore(ScoreboardManager.LABEL_LEVEL).setScore(mcMMOPlayer.getSkillLevel(targetSkill));
if (targetSkill.getAbility() != null) {
if (mcMMO.p.getSkillTools().getSuperAbility(targetSkill) != null) {
boolean stopUpdating;
if (targetSkill == PrimarySkillType.MINING) {
@@ -476,7 +519,7 @@ public class ScoreboardWrapper {
stopUpdating = (secondsSB == 0 && secondsBM == 0);
}
else {
SuperAbilityType ability = targetSkill.getAbility();
SuperAbilityType ability = mcMMO.p.getSkillTools().getSuperAbility(targetSkill);
Score cooldown = sidebarObjective.getScore(ScoreboardManager.abilityLabelsSkill.get(ability));
int seconds = Math.max(mcMMOPlayer.calculateTimeRemaining(ability), 0);
@@ -531,13 +574,13 @@ public class ScoreboardWrapper {
// Calculate power level here
int powerLevel = 0;
for (PrimarySkillType skill : PrimarySkillType.NON_CHILD_SKILLS) { // Don't include child skills, makes the list too long
for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) { // Don't include child skills, makes the list too long
int level = newProfile.getSkillLevel(skill);
powerLevel += level;
// TODO: Verify that this is what we want - calculated in power level but not displayed
if (!skill.getPermissions(player)) {
if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, skill)) {
continue;
}
@@ -564,8 +607,8 @@ public class ScoreboardWrapper {
Integer rank;
Player player = mcMMO.p.getServer().getPlayerExact(playerName);
for (PrimarySkillType skill : PrimarySkillType.NON_CHILD_SKILLS) {
if (!skill.getPermissions(player)) {
for (PrimarySkillType skill : SkillTools.NON_CHILD_SKILLS) {
if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, skill)) {
continue;
}
@@ -583,7 +626,7 @@ public class ScoreboardWrapper {
}
}
public void acceptLeaderboardData(List<PlayerStat> leaderboardData) {
public void acceptLeaderboardData(@NotNull List<PlayerStat> leaderboardData) {
for (PlayerStat stat : leaderboardData) {
String name = stat.name;

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util.skills;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.experience.ExperienceConfig;
import com.gmail.nossr50.datatypes.experience.XPGainReason;
import com.gmail.nossr50.datatypes.interactions.NotificationType;
@@ -9,8 +8,9 @@ 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.FakeEntityDamageByEntityEvent;
import com.gmail.nossr50.events.fake.FakeEntityDamageEvent;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.metadata.MobMetaFlagType;
import com.gmail.nossr50.metadata.MobMetadataService;
import com.gmail.nossr50.party.PartyManager;
import com.gmail.nossr50.runnables.skills.AwardCombatXpTask;
import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager;
@@ -20,11 +20,8 @@ import com.gmail.nossr50.skills.swords.SwordsManager;
import com.gmail.nossr50.skills.taming.TamingManager;
import com.gmail.nossr50.skills.unarmed.UnarmedManager;
import com.gmail.nossr50.util.*;
import com.gmail.nossr50.util.compat.layers.persistentdata.AbstractPersistentDataLayer;
import com.gmail.nossr50.util.compat.layers.persistentdata.MobMetaFlagType;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
import com.google.common.collect.ImmutableMap;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
@@ -34,7 +31,6 @@ import org.bukkit.entity.*;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDamageEvent.DamageModifier;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.potion.PotionEffectType;
@@ -42,29 +38,22 @@ import org.bukkit.projectiles.ProjectileSource;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class CombatUtils {
private CombatUtils() {}
private static @NotNull AbstractPersistentDataLayer getPersistentData() {
return mcMMO.getCompatibilityManager().getPersistentDataLayer();
private static @NotNull MobMetadataService getMobMetadataService() {
return mcMMO.getMetadataService().getMobMetadataService();
}
//Likely.. because who knows what plugins are throwing around
public static boolean isDamageLikelyFromNormalCombat(@NotNull DamageCause damageCause) {
switch (damageCause) {
case ENTITY_ATTACK:
case ENTITY_SWEEP_ATTACK:
case PROJECTILE:
return true;
default:
return false;
}
return switch (damageCause) {
case ENTITY_ATTACK, ENTITY_SWEEP_ATTACK, PROJECTILE -> true;
default -> false;
};
}
public static boolean hasWeakenedDamage(@NotNull LivingEntity livingEntity) {
@@ -84,38 +73,32 @@ public final class CombatUtils {
}
SwordsManager swordsManager = mcMMOPlayer.getSwordsManager();
double initialDamage = event.getDamage();
double finalDamage = initialDamage;
Map<DamageModifier, Double> modifiers = getModifiers(event);
double boostedDamage = event.getDamage();
if (swordsManager.canActivateAbility()) {
mcMMOPlayer.checkAbilityActivation(PrimarySkillType.SWORDS);
}
if(target.getHealth() - event.getFinalDamage() >= 1)
{
if (swordsManager.canUseRupture()) {
swordsManager.ruptureCheck(target);
}
if(target.getHealth() - event.getFinalDamage() > 0) {
swordsManager.processRupture(target);
}
//Add Stab Damage
if(swordsManager.canUseStab())
{
finalDamage+=(swordsManager.getStabDamage() * mcMMOPlayer.getAttackStrength());
boostedDamage += (swordsManager.getStabDamage() * mcMMOPlayer.getAttackStrength());
}
if (swordsManager.canUseSerratedStrike()) {
swordsManager.serratedStrikes(target, initialDamage, modifiers);
swordsManager.serratedStrikes(target, event.getDamage());
}
if(canUseLimitBreak(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK))
{
finalDamage+=(getLimitBreakDamage(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength());
boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength());
}
applyScaledModifiers(initialDamage, finalDamage, event);
event.setDamage(boostedDamage);
processCombatXP(mcMMOPlayer, target, PrimarySkillType.SWORDS);
printFinalDamageDebug(player, event, mcMMOPlayer);
@@ -137,10 +120,8 @@ public final class CombatUtils {
if (event.getCause() == DamageCause.THORNS) {
return;
}
double initialDamage = event.getDamage();
double finalDamage = initialDamage;
Map<DamageModifier, Double> modifiers = getModifiers(event);
double boostedDamage = event.getDamage();
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
@@ -156,30 +137,30 @@ public final class CombatUtils {
}
if (axesManager.canUseAxeMastery()) {
finalDamage+=axesManager.axeMastery();
boostedDamage+=axesManager.axeMastery();
}
if (axesManager.canImpact(target)) {
axesManager.impactCheck(target);
}
else if (axesManager.canGreaterImpact(target)) {
finalDamage+=axesManager.greaterImpact(target);
boostedDamage+=axesManager.greaterImpact(target);
}
if (axesManager.canUseSkullSplitter(target)) {
axesManager.skullSplitterCheck(target, initialDamage, modifiers);
axesManager.skullSplitterCheck(target, event.getDamage());
}
if (axesManager.canCriticalHit(target)) {
finalDamage+=(axesManager.criticalHit(target, finalDamage) * mcMMOPlayer.getAttackStrength());
boostedDamage+=(axesManager.criticalHit(target, boostedDamage) * mcMMOPlayer.getAttackStrength());
}
if(canUseLimitBreak(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK))
{
finalDamage+=(getLimitBreakDamage(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength());
boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength());
}
applyScaledModifiers(initialDamage, finalDamage, event);
event.setDamage(boostedDamage);
processCombatXP(mcMMOPlayer, target, PrimarySkillType.AXES);
printFinalDamageDebug(player, event, mcMMOPlayer);
@@ -190,8 +171,7 @@ public final class CombatUtils {
return;
}
double initialDamage = event.getDamage();
double finalDamage = initialDamage;
double boostedDamage = event.getDamage();
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
@@ -207,11 +187,11 @@ public final class CombatUtils {
}
if (unarmedManager.canUseSteelArm()) {
finalDamage+=(unarmedManager.calculateSteelArmStyleDamage() * mcMMOPlayer.getAttackStrength());
boostedDamage+=(unarmedManager.calculateSteelArmStyleDamage() * mcMMOPlayer.getAttackStrength());
}
if (unarmedManager.canUseBerserk()) {
finalDamage+=(unarmedManager.berserkDamage(finalDamage) * mcMMOPlayer.getAttackStrength());
boostedDamage+=(unarmedManager.berserkDamage(boostedDamage) * mcMMOPlayer.getAttackStrength());
}
if (unarmedManager.canDisarm(target)) {
@@ -220,10 +200,10 @@ public final class CombatUtils {
if(canUseLimitBreak(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK))
{
finalDamage+=(getLimitBreakDamage(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength());
boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength());
}
applyScaledModifiers(initialDamage, finalDamage, event);
event.setDamage(boostedDamage);
processCombatXP(mcMMOPlayer, target, PrimarySkillType.UNARMED);
printFinalDamageDebug(player, event, mcMMOPlayer);
@@ -231,7 +211,7 @@ public final class CombatUtils {
private static void processTamingCombat(@NotNull LivingEntity target, @Nullable Player master, @NotNull Wolf wolf, @NotNull EntityDamageByEntityEvent event) {
double initialDamage = event.getDamage();
double finalDamage = initialDamage;
double boostedDamage = initialDamage;
if(master != null && master.isOnline() && master.isValid()) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master);
@@ -250,14 +230,14 @@ public final class CombatUtils {
tamingManager.pummel(target, wolf);
if (tamingManager.canUseSharpenedClaws()) {
finalDamage+=tamingManager.sharpenedClaws();
boostedDamage+=tamingManager.sharpenedClaws();
}
if (tamingManager.canUseGore()) {
finalDamage+=tamingManager.gore(target, initialDamage);
boostedDamage+=tamingManager.gore(target, initialDamage);
}
applyScaledModifiers(initialDamage, finalDamage, event);
event.setDamage(boostedDamage);
processCombatXP(mcMMOPlayer, target, PrimarySkillType.TAMING, 3);
}
@@ -276,41 +256,40 @@ public final class CombatUtils {
ArcheryManager archeryManager = mcMMOPlayer.getArcheryManager();
double finalDamage = event.getDamage();
double boostedDamage = event.getDamage();
if (archeryManager.canSkillShot()) {
//Not Additive
finalDamage = archeryManager.skillShot(initialDamage);
boostedDamage = archeryManager.skillShot(initialDamage);
}
if (archeryManager.canDaze(target)) {
finalDamage+=archeryManager.daze((Player) target); //the cast is checked by the if condition
boostedDamage+=archeryManager.daze((Player) target); //the cast is checked by the if condition
}
if (!arrow.hasMetadata(mcMMO.infiniteArrowKey) && archeryManager.canRetrieveArrows()) {
if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW) && archeryManager.canRetrieveArrows()) {
archeryManager.retrieveArrows(target, arrow);
}
if(canUseLimitBreak(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK))
{
finalDamage+=getLimitBreakDamage(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK);
boostedDamage+=getLimitBreakDamage(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK);
}
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(mcMMO.bowForceKey))
forceMultiplier = arrow.getMetadata(mcMMO.bowForceKey).get(0).asDouble();
applyScaledModifiers(initialDamage, finalDamage, event);
if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE))
forceMultiplier = arrow.getMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE).get(0).asDouble();
event.setDamage(boostedDamage);
processCombatXP(mcMMOPlayer, target, PrimarySkillType.ARCHERY, forceMultiplier * distanceMultiplier);
printFinalDamageDebug(player, event, mcMMOPlayer,
"Distance Multiplier: "+distanceMultiplier,
"Force Multiplier: "+forceMultiplier,
"Initial Damage: "+initialDamage,
"Final Damage: "+finalDamage);
"Final Damage: "+boostedDamage);
//Clean data
cleanupArrowMetadata(arrow);
}
@@ -324,14 +303,13 @@ public final class CombatUtils {
Entity painSource = event.getDamager();
EntityType entityType = painSource.getType();
if (target instanceof Player) {
if (target instanceof Player player) {
if(ExperienceConfig.getInstance().isNPCInteractionPrevented()) {
if (Misc.isNPCEntityExcludingVillagers(target)) {
return;
}
}
Player player = (Player) target;
if (!UserManager.hasPlayerDataKey(player)) {
return;
}
@@ -344,7 +322,7 @@ public final class CombatUtils {
}
if (ItemUtils.isSword(player.getInventory().getItemInMainHand())) {
if (!PrimarySkillType.SWORDS.shouldProcess(target)) {
if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.SWORDS, target)) {
return;
}
@@ -356,8 +334,7 @@ public final class CombatUtils {
}
}
if (painSourceRoot instanceof Player && entityType == EntityType.PLAYER) {
Player player = (Player) painSourceRoot;
if (painSourceRoot instanceof Player player && entityType == EntityType.PLAYER) {
if (!UserManager.hasPlayerDataKey(player)) {
return;
@@ -382,30 +359,30 @@ public final class CombatUtils {
}
if (ItemUtils.isSword(heldItem)) {
if (!PrimarySkillType.SWORDS.shouldProcess(target)) {
if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.SWORDS, target)) {
return;
}
if (PrimarySkillType.SWORDS.getPermissions(player)) {
if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SWORDS)) {
processSwordCombat(target, player, event);
}
}
else if (ItemUtils.isAxe(heldItem)) {
if (!PrimarySkillType.AXES.shouldProcess(target)) {
if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.AXES, target)) {
return;
}
if (PrimarySkillType.AXES.getPermissions(player)) {
if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.AXES)) {
processAxeCombat(target, player, event);
}
}
else if (ItemUtils.isUnarmed(heldItem)) {
if (!PrimarySkillType.UNARMED.shouldProcess(target)) {
if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.UNARMED, target)) {
return;
}
if (PrimarySkillType.UNARMED.getPermissions(player)) {
if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.UNARMED)) {
processUnarmedCombat(target, player, event);
}
}
@@ -415,10 +392,9 @@ public final class CombatUtils {
Wolf wolf = (Wolf) painSource;
AnimalTamer tamer = wolf.getOwner();
if (tamer instanceof Player && PrimarySkillType.TAMING.shouldProcess(target)) {
Player master = (Player) tamer;
if (tamer instanceof Player master && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TAMING, target)) {
if (!Misc.isNPCEntityExcludingVillagers(master) && PrimarySkillType.TAMING.getPermissions(master)) {
if (!Misc.isNPCEntityExcludingVillagers(master) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(master, PrimarySkillType.TAMING)) {
processTamingCombat(target, master, wolf, event);
}
}
@@ -427,17 +403,16 @@ public final class CombatUtils {
Projectile arrow = (Projectile) painSource;
ProjectileSource projectileSource = arrow.getShooter();
if (projectileSource instanceof Player && PrimarySkillType.ARCHERY.shouldProcess(target)) {
Player player = (Player) projectileSource;
if (projectileSource instanceof Player player && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.ARCHERY, target)) {
if (!Misc.isNPCEntityExcludingVillagers(player) && PrimarySkillType.ARCHERY.getPermissions(player)) {
if (!Misc.isNPCEntityExcludingVillagers(player) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.ARCHERY)) {
processArcheryCombat(target, player, event, arrow);
} else {
//Cleanup Arrow
cleanupArrowMetadata(arrow);
}
if (target.getType() != EntityType.CREEPER && !Misc.isNPCEntityExcludingVillagers(player) && PrimarySkillType.TAMING.getPermissions(player)) {
if (target.getType() != EntityType.CREEPER && !Misc.isNPCEntityExcludingVillagers(player) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.TAMING)) {
McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player);
if(mcMMOPlayer == null)
@@ -457,7 +432,7 @@ public final class CombatUtils {
*/
public static void fixNames(@NotNull LivingEntity entity)
{
List<MetadataValue> metadataValue = entity.getMetadata(TransientMetadataTools.OLD_NAME_METAKEY);
List<MetadataValue> metadataValue = entity.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY);
if(metadataValue.size() <= 0)
return;
@@ -465,6 +440,8 @@ public final class CombatUtils {
OldName oldName = (OldName) metadataValue.get(0);
entity.setCustomName(oldName.asString());
entity.setCustomNameVisible(false);
entity.removeMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY, mcMMO.p);
}
/**
@@ -475,8 +452,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) {
Player playerDefender = (Player) defender;
if(defender instanceof Player playerDefender) {
return getLimitBreakDamageAgainstQuality(attacker, subSkillType, getArmorQualityLevel(playerDefender));
} else {
return getLimitBreakDamageAgainstQuality(attacker, subSkillType, 1000);
@@ -537,7 +513,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 || AdvancedConfig.getInstance().canApplyLimitBreakPVE()) {
if(target instanceof Player || mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) {
return RankUtils.hasUnlockedSubskill(player, subSkillType)
&& Permissions.isSubSkillEnabled(player, subSkillType);
} else {
@@ -636,15 +612,15 @@ public final class CombatUtils {
}
public static void removeIgnoreDamageMetadata(@NotNull LivingEntity target) {
target.removeMetadata(mcMMO.CUSTOM_DAMAGE_METAKEY, mcMMO.p);
target.removeMetadata(MetadataConstants.METADATA_KEY_CUSTOM_DAMAGE, mcMMO.p);
}
public static void applyIgnoreDamageMetadata(@NotNull LivingEntity target) {
target.setMetadata(mcMMO.CUSTOM_DAMAGE_METAKEY, mcMMO.metadataValue);
target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_DAMAGE, MetadataConstants.MCMMO_METADATA_VALUE);
}
public static boolean hasIgnoreDamageMetadata(@NotNull LivingEntity target) {
return target.getMetadata(mcMMO.CUSTOM_DAMAGE_METAKEY).size() != 0;
return target.getMetadata(MetadataConstants.METADATA_KEY_CUSTOM_DAMAGE).size() != 0;
}
public static void dealNoInvulnerabilityTickDamageRupture(@NotNull LivingEntity target, double damage, Entity attacker, int toolTier) {
@@ -686,13 +662,12 @@ public final class CombatUtils {
/**
* Apply Area-of-Effect ability actions.
*
* @param attacker The attacking player
* @param attacker The attacking player
* @param target The defending entity
* @param damage The initial damage amount
* @param type The type of skill being used
*/
public static void applyAbilityAoE(@NotNull Player attacker, @NotNull LivingEntity target, double damage, Map<DamageModifier, Double> modifiers, @NotNull PrimarySkillType type) {
public static void applyAbilityAoE(@NotNull Player attacker, @NotNull LivingEntity target, double damage, @NotNull PrimarySkillType type) {
int numberOfTargets = getTier(attacker.getInventory().getItemInMainHand()); // The higher the weapon tier, the more targets you hit
double damageAmount = Math.max(damage, 1);
@@ -701,12 +676,12 @@ public final class CombatUtils {
break;
}
if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(entity)) || !(entity instanceof LivingEntity) || !shouldBeAffected(attacker, entity)) {
if ((ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(entity))
|| !(entity instanceof LivingEntity livingEntity) || !shouldBeAffected(attacker, entity)) {
continue;
}
LivingEntity livingEntity = (LivingEntity) entity;
EventUtils.callFakeArmSwingEvent(attacker);
//EventUtils.callFakeArmSwingEvent(attacker);
switch (type) {
case SWORDS:
@@ -714,7 +689,12 @@ public final class CombatUtils {
NotificationManager.sendPlayerInformation((Player)entity, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.SS.Struck");
}
UserManager.getPlayer(attacker).getSwordsManager().ruptureCheck(target);
McMMOPlayer mmoAttacker = UserManager.getPlayer(attacker);
if(mmoAttacker != null) {
mmoAttacker.getSwordsManager().processRupture(livingEntity);
}
break;
case AXES:
@@ -740,7 +720,7 @@ public final class CombatUtils {
* @param target The defending entity
* @param primarySkillType The skill being used
*/
public static void processCombatXP(@NotNull McMMOPlayer mcMMOPlayer, LivingEntity target, PrimarySkillType primarySkillType) {
public static void processCombatXP(@NotNull McMMOPlayer mcMMOPlayer, @NotNull LivingEntity target, @NotNull PrimarySkillType primarySkillType) {
processCombatXP(mcMMOPlayer, target, primarySkillType, 1.0);
}
@@ -752,17 +732,19 @@ public final class CombatUtils {
* @param primarySkillType The skill being used
* @param multiplier final XP result will be multiplied by this
*/
public static void processCombatXP(@NotNull McMMOPlayer mcMMOPlayer, LivingEntity target, PrimarySkillType primarySkillType, double multiplier) {
public static void processCombatXP(@NotNull McMMOPlayer mcMMOPlayer,
@NotNull LivingEntity target,
@NotNull PrimarySkillType primarySkillType,
double multiplier) {
double baseXP = 0;
XPGainReason xpGainReason;
if (target instanceof Player) {
if (target instanceof Player defender) {
if (!ExperienceConfig.getInstance().getExperienceGainsPlayerVersusPlayerEnabled() || PartyManager.inSameParty(mcMMOPlayer.getPlayer(), (Player) target)) {
return;
}
xpGainReason = XPGainReason.PVP;
Player defender = (Player) target;
if (defender.isOnline() && SkillUtils.cooldownExpired(mcMMOPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) {
baseXP = 20 * ExperienceConfig.getInstance().getPlayerVersusPlayerXP();
@@ -803,17 +785,17 @@ public final class CombatUtils {
}
}
if(getPersistentData().hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) {
if(getMobMetadataService().hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) {
baseXP = 0;
} else if(getPersistentData().hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) {
} else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) {
baseXP *= ExperienceConfig.getInstance().getSpawnedMobXpMultiplier();
} else if(getPersistentData().hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) {
} else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) {
baseXP *= ExperienceConfig.getInstance().getNetherPortalXpMultiplier();
} else if(getPersistentData().hasMobFlag(MobMetaFlagType.EGG_MOB, target)) {
} else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.EGG_MOB, target)) {
baseXP *= ExperienceConfig.getInstance().getEggXpMultiplier();
} else if (getPersistentData().hasMobFlag(MobMetaFlagType.PLAYER_BRED_MOB, target)) {
} else if (getMobMetadataService().hasMobFlag(MobMetaFlagType.PLAYER_BRED_MOB, target)) {
baseXP *= ExperienceConfig.getInstance().getBredMobXpMultiplier();
} else if(getPersistentData().hasMobFlag(MobMetaFlagType.PLAYER_TAMED_MOB, target)) {
} else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.PLAYER_TAMED_MOB, target)) {
baseXP *= ExperienceConfig.getInstance().getTamedMobXpMultiplier();
}
@@ -836,9 +818,7 @@ public final class CombatUtils {
* @return true if the Entity should be damaged, false otherwise.
*/
private static boolean shouldBeAffected(@NotNull Player player, @NotNull Entity entity) {
if (entity instanceof Player) {
Player defender = (Player) entity;
if (entity instanceof Player defender) {
//TODO: NPC Interaction?
if(UserManager.getPlayer(defender) == null)
return true;
@@ -857,16 +837,8 @@ public final class CombatUtils {
}
// Spectators should not be affected
if (defender.getGameMode() == GameMode.SPECTATOR) {
return false;
}
// It may seem a bit redundant but we need a check here to prevent bleed from being applied in applyAbilityAoE()
return getFakeDamageFinalResult(player, entity, 1.0) != 0;
}
else if (entity instanceof Tameable) {
Tameable tameableEntity = (Tameable) entity;
return defender.getGameMode() != GameMode.SPECTATOR;
} else if (entity instanceof Tameable tameableEntity) {
if (isFriendlyPet(player, tameableEntity)) {
// isFriendlyPet ensures that the Tameable is: Tamed, owned by a player, and the owner is in the same party
// So we can make some assumptions here, about our casting and our check
@@ -904,8 +876,7 @@ public final class CombatUtils {
if (pet.isTamed()) {
AnimalTamer tamer = pet.getOwner();
if (tamer instanceof Player) {
Player owner = (Player) tamer;
if (tamer instanceof Player owner) {
return (owner == attacker || PartyManager.inSameParty(attacker, owner) || PartyManager.areAllies(attacker, owner));
}
@@ -914,99 +885,13 @@ public final class CombatUtils {
return false;
}
@Deprecated
public static double getFakeDamageFinalResult(@Nullable Entity attacker, @NotNull Entity target, double damage) {
return getFakeDamageFinalResult(attacker, target, DamageCause.ENTITY_ATTACK, new EnumMap<>(ImmutableMap.of(DamageModifier.BASE, damage)));
}
@Deprecated
public static double getFakeDamageFinalResult(@Nullable Entity attacker, @NotNull Entity target, @NotNull DamageCause damageCause, double damage) {
EntityDamageEvent damageEvent = sendEntityDamageEvent(attacker, target, damageCause, damage);
if (damageEvent.isCancelled()) {
return 0;
}
return damageEvent.getFinalDamage();
}
public static boolean canDamage(@NotNull Entity attacker, @NotNull Entity target, @NotNull DamageCause damageCause, double damage) {
EntityDamageEvent damageEvent = sendEntityDamageEvent(attacker, target, damageCause, damage);
EntityDamageEvent damageEvent = new FakeEntityDamageByEntityEvent(attacker, target, damageCause, damage);
mcMMO.p.getServer().getPluginManager().callEvent(damageEvent);
return !damageEvent.isCancelled();
}
public static @NotNull EntityDamageEvent sendEntityDamageEvent(@Nullable Entity attacker, @NotNull Entity target, @NotNull DamageCause damageCause, double damage) {
EntityDamageEvent damageEvent = attacker == null ? new FakeEntityDamageEvent(target, damageCause, damage) : new FakeEntityDamageByEntityEvent(attacker, target, damageCause, damage);
mcMMO.p.getServer().getPluginManager().callEvent(damageEvent);
return damageEvent;
}
public static double getFakeDamageFinalResult(@Nullable Entity attacker, @NotNull Entity target, @NotNull Map<DamageModifier, Double> modifiers) {
return getFakeDamageFinalResult(attacker, target, DamageCause.ENTITY_ATTACK, modifiers);
}
public static double getFakeDamageFinalResult(@Nullable Entity attacker, @NotNull Entity target, double damage, @NotNull Map<DamageModifier, Double> modifiers) {
return getFakeDamageFinalResult(attacker, target, DamageCause.ENTITY_ATTACK, getScaledModifiers(damage, modifiers));
}
public static double getFakeDamageFinalResult(@Nullable Entity attacker, @NotNull Entity target, @NotNull DamageCause cause, @NotNull Map<DamageModifier, Double> modifiers) {
EntityDamageEvent damageEvent = attacker == null ? new FakeEntityDamageEvent(target, cause, modifiers) : new FakeEntityDamageByEntityEvent(attacker, target, cause, modifiers);
mcMMO.p.getServer().getPluginManager().callEvent(damageEvent);
if (damageEvent.isCancelled()) {
return 0;
}
return damageEvent.getFinalDamage();
}
private static @NotNull Map<DamageModifier, Double> getModifiers(@NotNull EntityDamageEvent event) {
Map<DamageModifier, Double> modifiers = new HashMap<>();
for (DamageModifier modifier : DamageModifier.values()) {
modifiers.put(modifier, event.getDamage(modifier));
}
return modifiers;
}
private static @NotNull Map<DamageModifier, Double> getScaledModifiers(double damage, @NotNull Map<DamageModifier, Double> modifiers) {
Map<DamageModifier, Double> scaledModifiers = new HashMap<>();
for (DamageModifier modifier : modifiers.keySet()) {
if (modifier == DamageModifier.BASE) {
scaledModifiers.put(modifier, damage);
continue;
}
scaledModifiers.put(modifier, damage * modifiers.get(modifier));
}
return scaledModifiers;
}
public static @NotNull EntityDamageByEntityEvent applyScaledModifiers(double initialDamage, double finalDamage, @NotNull EntityDamageByEntityEvent event) {
// No additional damage
if (initialDamage == finalDamage) {
return event;
}
for (DamageModifier modifier : DamageModifier.values()) {
if (!event.isApplicable(modifier)) {
continue;
}
if (modifier == DamageModifier.BASE) {
event.setDamage(modifier, finalDamage);
continue;
}
event.setDamage(modifier, finalDamage / initialDamage * event.getDamage(modifier));
}
return event;
}
/**
* Get the upgrade tier of the item in hand.
*
@@ -1041,17 +926,15 @@ public final class CombatUtils {
}
public static void handleHealthbars(@NotNull Entity attacker, @NotNull LivingEntity target, double damage, @NotNull mcMMO plugin) {
if (!(attacker instanceof Player)) {
if (!(attacker instanceof Player player)) {
return;
}
Player player = (Player) attacker;
if (Misc.isNPCEntityExcludingVillagers(player) || Misc.isNPCEntityExcludingVillagers(target)) {
return;
}
if (!player.hasMetadata(mcMMO.playerDataKey)) {
if (!player.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA)) {
return;
}
@@ -1073,16 +956,16 @@ public final class CombatUtils {
* @param entity projectile
*/
public static void cleanupArrowMetadata(@NotNull Projectile entity) {
if(entity.hasMetadata(mcMMO.infiniteArrowKey)) {
entity.removeMetadata(mcMMO.infiniteArrowKey, mcMMO.p);
if(entity.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) {
entity.removeMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, mcMMO.p);
}
if(entity.hasMetadata(mcMMO.bowForceKey)) {
entity.removeMetadata(mcMMO.bowForceKey, mcMMO.p);
if(entity.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) {
entity.removeMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, mcMMO.p);
}
if(entity.hasMetadata(mcMMO.arrowDistanceKey)) {
entity.removeMetadata(mcMMO.arrowDistanceKey, mcMMO.p);
if(entity.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) {
entity.removeMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, mcMMO.p);
}
}
@@ -1092,6 +975,6 @@ public final class CombatUtils {
* @param entity the projectile
*/
public static void delayArrowMetaCleanup(@NotNull Projectile entity) {
Bukkit.getServer().getScheduler().runTaskLater(mcMMO.p, () -> { cleanupArrowMetadata(entity);}, 20*60);
Bukkit.getServer().getScheduler().runTaskLater(mcMMO.p, () -> cleanupArrowMetadata(entity), 20*60);
}
}

View File

@@ -1,8 +1,9 @@
package com.gmail.nossr50.util.skills;
import com.gmail.nossr50.config.Config;
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.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
@@ -11,6 +12,7 @@ import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
public final class ParticleEffectUtils {
@@ -22,16 +24,53 @@ public final class ParticleEffectUtils {
SoundManager.worldSendSoundMaxPitch(world, location, SoundType.POP);
}
public static void playBleedEffect(LivingEntity livingEntity) {
if (!Config.getInstance().getBleedEffectEnabled()) {
public static void playBleedEffect(@NotNull LivingEntity livingEntity) {
if (!mcMMO.p.getGeneralConfig().getBleedEffectEnabled()) {
return;
}
livingEntity.getWorld().playEffect(livingEntity.getEyeLocation(), Effect.STEP_SOUND, Material.REDSTONE_WIRE);
livingEntity.getWorld().playEffect(getParticleLocation(livingEntity), Effect.STEP_SOUND, Material.REDSTONE_WIRE);
}
private static @NotNull Location getParticleLocation(@NotNull LivingEntity livingEntity) {
Location origin = livingEntity.getEyeLocation().clone();
World world = origin.getWorld();
double x = origin.getX();
double y = origin.getY();
double z = origin.getZ();
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);
}
}
public static void playDodgeEffect(Player player) {
if (!Config.getInstance().getDodgeEffectEnabled()) {
if (!mcMMO.p.getGeneralConfig().getDodgeEffectEnabled()) {
return;
}
@@ -39,7 +78,7 @@ public final class ParticleEffectUtils {
}
public static void playFluxEffect(Location location) {
if (!Config.getInstance().getFluxEffectEnabled()) {
if (!mcMMO.p.getGeneralConfig().getFluxEffectEnabled()) {
return;
}
@@ -68,7 +107,7 @@ public final class ParticleEffectUtils {
}
public static void playGreaterImpactEffect(LivingEntity livingEntity) {
if (!Config.getInstance().getGreaterImpactEffectEnabled()) {
if (!mcMMO.p.getGeneralConfig().getGreaterImpactEffectEnabled()) {
return;
}
@@ -78,7 +117,7 @@ public final class ParticleEffectUtils {
}
public static void playCallOfTheWildEffect(LivingEntity livingEntity) {
if (!Config.getInstance().getCallOfTheWildEffectEnabled()) {
if (!mcMMO.p.getGeneralConfig().getCallOfTheWildEffectEnabled()) {
return;
}
@@ -86,7 +125,7 @@ public final class ParticleEffectUtils {
}
public static void playAbilityDisabledEffect(Player player) {
if (!Config.getInstance().getAbilityDeactivationEffectEnabled()) {
if (!mcMMO.p.getGeneralConfig().getAbilityDeactivationEffectEnabled()) {
}
/*if (hasHeadRoom(player)) {

View File

@@ -74,6 +74,9 @@ public final class PerksUtils {
else if (Permissions.oneAndOneHalfXp(player, skill)) {
modifier = 1.5;
}
else if (Permissions.oneAndAQuarterXp(player, skill)) {
modifier = 1.25;
}
else if (Permissions.oneAndOneTenthXp(player, skill)) {
modifier = 1.1;
}

View File

@@ -7,6 +7,7 @@ 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.listeners.InteractionManager;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.runnables.skills.SkillUnlockNotificationTask;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.player.UserManager;
@@ -28,7 +29,7 @@ public class RankUtils {
*/
public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, int newLevel)
{
for(SubSkillType subSkillType : primarySkillType.getSkillAbilities())
for(SubSkillType subSkillType : mcMMO.p.getSkillTools().getSubSkills(primarySkillType))
{
int playerRankInSkill = getRank(mcMMOPlayer.getPlayer(), subSkillType);
@@ -47,7 +48,7 @@ public class RankUtils {
{
SkillUnlockNotificationTask skillUnlockNotificationTask = new SkillUnlockNotificationTask(mcMMOPlayer, subSkillType, newLevel);
skillUnlockNotificationTask.runTaskLater(plugin, (count * 100));
skillUnlockNotificationTask.runTaskLater(plugin, (count * 100L));
count++;
}

View File

@@ -0,0 +1,453 @@
package com.gmail.nossr50.util.skills;
import com.gmail.nossr50.api.exceptions.InvalidSkillException;
import com.gmail.nossr50.config.experience.ExperienceConfig;
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.ToolType;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.text.StringUtils;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.VisibleForTesting;
import java.util.*;
public class SkillTools {
private final mcMMO pluginRef;
//TODO: Figure out which ones we don't need, this was copy pasted from a diff branch
public final @NotNull ImmutableList<String> LOCALIZED_SKILL_NAMES;
public final @NotNull ImmutableList<String> FORMATTED_SUBSKILL_NAMES;
public final @NotNull ImmutableSet<String> EXACT_SUBSKILL_NAMES;
public final @NotNull ImmutableList<PrimarySkillType> CHILD_SKILLS;
public final static @NotNull ImmutableList<PrimarySkillType> NON_CHILD_SKILLS;
public final @NotNull ImmutableList<PrimarySkillType> COMBAT_SKILLS;
public final @NotNull ImmutableList<PrimarySkillType> GATHERING_SKILLS;
public final @NotNull ImmutableList<PrimarySkillType> MISC_SKILLS;
private final @NotNull ImmutableMap<SubSkillType, PrimarySkillType> subSkillParentRelationshipMap;
private final @NotNull ImmutableMap<SuperAbilityType, PrimarySkillType> superAbilityParentRelationshipMap;
private final @NotNull ImmutableMap<PrimarySkillType, Set<SubSkillType>> primarySkillChildrenMap;
// The map below is for the super abilities which require readying a tool, its everything except blast mining
private final ImmutableMap<PrimarySkillType, SuperAbilityType> mainActivatedAbilityChildMap;
private final ImmutableMap<PrimarySkillType, ToolType> primarySkillToolMap;
static {
ArrayList<PrimarySkillType> tempNonChildSkills = new ArrayList<>();
for(PrimarySkillType primarySkillType : PrimarySkillType.values()) {
if (primarySkillType != PrimarySkillType.SALVAGE && primarySkillType != PrimarySkillType.SMELTING)
tempNonChildSkills.add(primarySkillType);
}
NON_CHILD_SKILLS = ImmutableList.copyOf(tempNonChildSkills);
}
public SkillTools(@NotNull mcMMO pluginRef) {
this.pluginRef = pluginRef;
/*
* Setup subskill -> parent relationship map
*/
EnumMap<SubSkillType, PrimarySkillType> tempSubParentMap = new EnumMap<>(SubSkillType.class);
//Super hacky and disgusting
for(PrimarySkillType primarySkillType1 : PrimarySkillType.values()) {
for(SubSkillType subSkillType : SubSkillType.values()) {
String[] splitSubSkillName = subSkillType.toString().split("_");
if(primarySkillType1.toString().equalsIgnoreCase(splitSubSkillName[0])) {
//Parent Skill Found
tempSubParentMap.put(subSkillType, primarySkillType1);
}
}
}
subSkillParentRelationshipMap = ImmutableMap.copyOf(tempSubParentMap);
/*
* Setup primary -> (collection) subskill map
*/
EnumMap<PrimarySkillType, Set<SubSkillType>> tempPrimaryChildMap = new EnumMap<>(PrimarySkillType.class);
//Init the empty Hash Sets
for(PrimarySkillType primarySkillType1 : PrimarySkillType.values()) {
tempPrimaryChildMap.put(primarySkillType1, new HashSet<>());
}
//Fill in the hash sets
for(SubSkillType subSkillType : SubSkillType.values()) {
PrimarySkillType parentSkill = subSkillParentRelationshipMap.get(subSkillType);
//Add this subskill as a child
tempPrimaryChildMap.get(parentSkill).add(subSkillType);
}
primarySkillChildrenMap = ImmutableMap.copyOf(tempPrimaryChildMap);
/*
* Setup primary -> tooltype map
*/
EnumMap<PrimarySkillType, ToolType> tempToolMap = new EnumMap<>(PrimarySkillType.class);
tempToolMap.put(PrimarySkillType.AXES, ToolType.AXE);
tempToolMap.put(PrimarySkillType.WOODCUTTING, ToolType.AXE);
tempToolMap.put(PrimarySkillType.UNARMED, ToolType.FISTS);
tempToolMap.put(PrimarySkillType.SWORDS, ToolType.SWORD);
tempToolMap.put(PrimarySkillType.EXCAVATION, ToolType.SHOVEL);
tempToolMap.put(PrimarySkillType.HERBALISM, ToolType.HOE);
tempToolMap.put(PrimarySkillType.MINING, ToolType.PICKAXE);
primarySkillToolMap = ImmutableMap.copyOf(tempToolMap);
/*
* Setup ability -> primary map
* Setup primary -> ability map
*/
EnumMap<SuperAbilityType, PrimarySkillType> tempAbilityParentRelationshipMap = new EnumMap<>(SuperAbilityType.class);
EnumMap<PrimarySkillType, SuperAbilityType> tempMainActivatedAbilityChildMap = new EnumMap<>(PrimarySkillType.class);
for(SuperAbilityType superAbilityType : SuperAbilityType.values()) {
try {
PrimarySkillType parent = getSuperAbilityParent(superAbilityType);
tempAbilityParentRelationshipMap.put(superAbilityType, parent);
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);
}
} catch (InvalidSkillException e) {
e.printStackTrace();
}
}
superAbilityParentRelationshipMap = ImmutableMap.copyOf(tempAbilityParentRelationshipMap);
mainActivatedAbilityChildMap = ImmutableMap.copyOf(tempMainActivatedAbilityChildMap);
/*
* Build child skill and nonchild skill lists
*/
List<PrimarySkillType> childSkills = new ArrayList<>();
// List<PrimarySkillType> nonChildSkills = new ArrayList<>();
for (PrimarySkillType primarySkillType : PrimarySkillType.values()) {
if (isChildSkill(primarySkillType))
childSkills.add(primarySkillType);
// } {
// nonChildSkills.add(primarySkillType);
// }
}
CHILD_SKILLS = ImmutableList.copyOf(childSkills);
// NON_CHILD_SKILLS = ImmutableList.copyOf(nonChildSkills);
/*
* Build categorized skill lists
*/
COMBAT_SKILLS = ImmutableList.of(PrimarySkillType.ARCHERY, PrimarySkillType.AXES, PrimarySkillType.SWORDS, PrimarySkillType.TAMING, PrimarySkillType.UNARMED);
GATHERING_SKILLS = ImmutableList.of(PrimarySkillType.EXCAVATION, PrimarySkillType.FISHING, PrimarySkillType.HERBALISM, PrimarySkillType.MINING, PrimarySkillType.WOODCUTTING);
MISC_SKILLS = ImmutableList.of(PrimarySkillType.ACROBATICS, PrimarySkillType.ALCHEMY, PrimarySkillType.REPAIR, PrimarySkillType.SALVAGE, PrimarySkillType.SMELTING);
/*
* Build formatted/localized/etc string lists
*/
LOCALIZED_SKILL_NAMES = ImmutableList.copyOf(buildLocalizedPrimarySkillNames());
FORMATTED_SUBSKILL_NAMES = ImmutableList.copyOf(buildFormattedSubSkillNameList());
EXACT_SUBSKILL_NAMES = ImmutableSet.copyOf(buildExactSubSkillNameList());
}
private @NotNull PrimarySkillType getSuperAbilityParent(SuperAbilityType superAbilityType) throws InvalidSkillException {
switch(superAbilityType) {
case BERSERK:
return PrimarySkillType.UNARMED;
case GREEN_TERRA:
return PrimarySkillType.HERBALISM;
case TREE_FELLER:
return PrimarySkillType.WOODCUTTING;
case SUPER_BREAKER:
case BLAST_MINING:
return PrimarySkillType.MINING;
case SKULL_SPLITTER:
return PrimarySkillType.AXES;
case SERRATED_STRIKES:
return PrimarySkillType.SWORDS;
case GIGA_DRILL_BREAKER:
return PrimarySkillType.EXCAVATION;
default:
throw new InvalidSkillException("No parent defined for super ability! "+superAbilityType.toString());
}
}
/**
* Makes a list of the "nice" version of sub skill names
* Used in tab completion mostly
* @return a list of formatted sub skill names
*/
private @NotNull ArrayList<String> buildFormattedSubSkillNameList() {
ArrayList<String> subSkillNameList = new ArrayList<>();
for(SubSkillType subSkillType : SubSkillType.values()) {
subSkillNameList.add(subSkillType.getNiceNameNoSpaces(subSkillType));
}
return subSkillNameList;
}
private @NotNull HashSet<String> buildExactSubSkillNameList() {
HashSet<String> subSkillNameExactSet = new HashSet<>();
for(SubSkillType subSkillType : SubSkillType.values()) {
subSkillNameExactSet.add(subSkillType.toString());
}
return subSkillNameExactSet;
}
/**
* Builds a list of localized {@link PrimarySkillType} names
* @return list of localized {@link PrimarySkillType} names
*/
@VisibleForTesting
private @NotNull ArrayList<String> buildLocalizedPrimarySkillNames() {
ArrayList<String> localizedSkillNameList = new ArrayList<>();
for(PrimarySkillType primarySkillType : PrimarySkillType.values()) {
localizedSkillNameList.add(getLocalizedSkillName(primarySkillType));
}
Collections.sort(localizedSkillNameList);
return localizedSkillNameList;
}
/**
* Matches a string of a skill to a skill
* This is NOT case sensitive
* First it checks the locale file and tries to match by the localized name of the skill
* Then if nothing is found it checks against the hard coded "name" of the skill, which is just its name in English
*
* @param skillName target skill name
* @return the matching PrimarySkillType if one is found, otherwise null
*/
public PrimarySkillType matchSkill(String skillName) {
if (!pluginRef.getGeneralConfig().getLocale().equalsIgnoreCase("en_US")) {
for (PrimarySkillType type : PrimarySkillType.values()) {
if (skillName.equalsIgnoreCase(LocaleLoader.getString(StringUtils.getCapitalized(type.name()) + ".SkillName"))) {
return type;
}
}
}
for (PrimarySkillType type : PrimarySkillType.values()) {
if (type.name().equalsIgnoreCase(skillName)) {
return type;
}
}
if (!skillName.equalsIgnoreCase("all")) {
pluginRef.getLogger().warning("Invalid mcMMO skill (" + skillName + ")"); //TODO: Localize
}
return null;
}
/**
* Gets the PrimarySkillStype to which a SubSkillType belongs
* Return null if it does not belong to one.. which should be impossible in most circumstances
* @param subSkillType target subskill
* @return the PrimarySkillType of this SubSkill, null if it doesn't exist
*/
public PrimarySkillType getPrimarySkillBySubSkill(SubSkillType subSkillType) {
return subSkillParentRelationshipMap.get(subSkillType);
}
/**
* Gets the PrimarySkillStype to which a SuperAbilityType belongs
* Return null if it does not belong to one.. which should be impossible in most circumstances
* @param superAbilityType target super ability
* @return the PrimarySkillType of this SuperAbilityType, null if it doesn't exist
*/
public PrimarySkillType getPrimarySkillBySuperAbility(SuperAbilityType superAbilityType) {
return superAbilityParentRelationshipMap.get(superAbilityType);
}
public SuperAbilityType getSuperAbility(PrimarySkillType primarySkillType) {
if(mainActivatedAbilityChildMap.get(primarySkillType) == null)
return null;
return mainActivatedAbilityChildMap.get(primarySkillType);
}
public boolean isSuperAbilityUnlocked(PrimarySkillType primarySkillType, Player player) {
SuperAbilityType superAbilityType = mcMMO.p.getSkillTools().getSuperAbility(primarySkillType);
SubSkillType subSkillType = superAbilityType.getSubSkillTypeDefinition();
return RankUtils.hasUnlockedSubskill(player, subSkillType);
}
public boolean getPVPEnabled(PrimarySkillType primarySkillType) {
return pluginRef.getGeneralConfig().getPVPEnabled(primarySkillType);
}
public boolean getPVEEnabled(PrimarySkillType primarySkillType) {
return pluginRef.getGeneralConfig().getPVEEnabled(primarySkillType);
}
public boolean getHardcoreStatLossEnabled(PrimarySkillType primarySkillType) {
return pluginRef.getGeneralConfig().getHardcoreStatLossEnabled(primarySkillType);
}
public boolean getHardcoreVampirismEnabled(PrimarySkillType primarySkillType) {
return pluginRef.getGeneralConfig().getHardcoreVampirismEnabled(primarySkillType);
}
public ToolType getPrimarySkillToolType(PrimarySkillType primarySkillType) {
return primarySkillToolMap.get(primarySkillType);
}
public Set<SubSkillType> getSubSkills(PrimarySkillType primarySkillType) {
//TODO: Cache this!
return primarySkillChildrenMap.get(primarySkillType);
}
public double getXpModifier(PrimarySkillType primarySkillType) {
return ExperienceConfig.getInstance().getFormulaSkillModifier(primarySkillType);
}
// TODO: This is a little "hacky", we probably need to add something to distinguish child skills in the enum, or to use another enum for them
public static boolean isChildSkill(PrimarySkillType primarySkillType) {
switch (primarySkillType) {
case SALVAGE:
case SMELTING:
return true;
default:
return false;
}
}
/**
* Get the localized name for a {@link PrimarySkillType}
* @param primarySkillType target {@link PrimarySkillType}
* @return the localized name for a {@link PrimarySkillType}
*/
public String getLocalizedSkillName(PrimarySkillType primarySkillType) {
//TODO: Replace with current impl
return StringUtils.getCapitalized(LocaleLoader.getString(StringUtils.getCapitalized(primarySkillType.toString()) + ".SkillName"));
}
public boolean doesPlayerHaveSkillPermission(Player player, PrimarySkillType primarySkillType) {
return Permissions.skillEnabled(player, primarySkillType);
}
public boolean canCombatSkillsTrigger(PrimarySkillType primarySkillType, Entity target) {
return (target instanceof Player || (target instanceof Tameable && ((Tameable) target).isTamed())) ? getPVPEnabled(primarySkillType) : getPVEEnabled(primarySkillType);
}
public String getCapitalizedPrimarySkillName(PrimarySkillType primarySkillType) {
return StringUtils.getCapitalized(primarySkillType.toString());
}
public int getSuperAbilityCooldown(SuperAbilityType superAbilityType) {
return pluginRef.getGeneralConfig().getCooldown(superAbilityType);
}
public int getSuperAbilityMaxLength(SuperAbilityType superAbilityType) {
return pluginRef.getGeneralConfig().getMaxLength(superAbilityType);
}
public String getSuperAbilityOnLocaleKey(SuperAbilityType superAbilityType) {
return "SuperAbility." + StringUtils.getPrettyCamelCaseName(superAbilityType) + ".On";
}
public String getSuperAbilityOffLocaleKey(SuperAbilityType superAbilityType) {
return "SuperAbility." + StringUtils.getPrettyCamelCaseName(superAbilityType) + ".Off";
}
public String getSuperAbilityOtherPlayerActivationLocaleKey(SuperAbilityType superAbilityType) {
return "SuperAbility." + StringUtils.getPrettyCamelCaseName(superAbilityType) + ".Other.On";
}
public String getSuperAbilityOtherPlayerDeactivationLocaleKey(SuperAbilityType superAbilityType) {
return "SuperAbility." + StringUtils.getPrettyCamelCaseName(superAbilityType) + "Other.Off";
}
public String getSuperAbilityRefreshedLocaleKey(SuperAbilityType superAbilityType) {
return "SuperAbility." + StringUtils.getPrettyCamelCaseName(superAbilityType) + ".Refresh";
}
public int getLevelCap(@NotNull PrimarySkillType primarySkillType) {
return mcMMO.p.getGeneralConfig().getLevelCap(primarySkillType);
}
/**
* Get the permissions for this ability.
*
* @param player Player to check permissions for
* @param superAbilityType target super ability
* @return true if the player has permissions, false otherwise
*/
public boolean superAbilityPermissionCheck(SuperAbilityType superAbilityType, Player player) {
switch (superAbilityType) {
case BERSERK:
return Permissions.berserk(player);
case BLAST_MINING:
return Permissions.remoteDetonation(player);
case GIGA_DRILL_BREAKER:
return Permissions.gigaDrillBreaker(player);
case GREEN_TERRA:
return Permissions.greenTerra(player);
case SERRATED_STRIKES:
return Permissions.serratedStrikes(player);
case SKULL_SPLITTER:
return Permissions.skullSplitter(player);
case SUPER_BREAKER:
return Permissions.superBreaker(player);
case TREE_FELLER:
return Permissions.treeFeller(player);
default:
return false;
}
}
public @NotNull List<PrimarySkillType> getChildSkills() {
return CHILD_SKILLS;
}
public @NotNull ImmutableList<PrimarySkillType> getNonChildSkills() {
return NON_CHILD_SKILLS;
}
public @NotNull ImmutableList<PrimarySkillType> getCombatSkills() {
return COMBAT_SKILLS;
}
public @NotNull ImmutableList<PrimarySkillType> getGatheringSkills() {
return GATHERING_SKILLS;
}
public @NotNull ImmutableList<PrimarySkillType> getMiscSkills() {
return MISC_SKILLS;
}
}

View File

@@ -1,7 +1,5 @@
package com.gmail.nossr50.util.skills;
import com.gmail.nossr50.config.AdvancedConfig;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.HiddenConfig;
import com.gmail.nossr50.datatypes.experience.XPGainReason;
import com.gmail.nossr50.datatypes.experience.XPGainSource;
@@ -13,11 +11,9 @@ import com.gmail.nossr50.datatypes.skills.SuperAbilityType;
import com.gmail.nossr50.events.skills.secondaryabilities.SubSkillEvent;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.util.EventUtils;
import com.gmail.nossr50.metadata.ItemMetadataService;
import com.gmail.nossr50.util.ItemUtils;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;
import com.gmail.nossr50.util.compat.layers.persistentdata.AbstractPersistentDataLayer;
import com.gmail.nossr50.util.player.NotificationManager;
import com.gmail.nossr50.util.player.UserManager;
import com.gmail.nossr50.util.random.*;
@@ -59,9 +55,9 @@ public final class SkillUtils {
*/
public static String[] calculateLengthDisplayValues(Player player, float skillValue, PrimarySkillType skill) {
int maxLength = skill.getAbility().getMaxLength();
int abilityLengthVar = AdvancedConfig.getInstance().getAbilityLength();
int abilityLengthCap = AdvancedConfig.getInstance().getAbilityLengthCap();
int maxLength = mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill));
int abilityLengthVar = mcMMO.p.getAdvancedConfig().getAbilityLength();
int abilityLengthCap = mcMMO.p.getAdvancedConfig().getAbilityLengthCap();
int length;
@@ -129,7 +125,7 @@ public final class SkillUtils {
* @return true if this is a valid skill, false otherwise
*/
public static boolean isSkill(String skillName) {
return Config.getInstance().getLocale().equalsIgnoreCase("en_US") ? PrimarySkillType.getSkill(skillName) != null : isLocalizedSkill(skillName);
return mcMMO.p.getGeneralConfig().getLocale().equalsIgnoreCase("en_US") ? mcMMO.p.getSkillTools().matchSkill(skillName) != null : isLocalizedSkill(skillName);
}
public static void sendSkillMessage(Player player, NotificationType notificationType, String key) {
@@ -162,10 +158,8 @@ public final class SkillUtils {
ItemUtils.addDigSpeedToItem(heldItem, heldItem.getEnchantmentLevel(Enchantment.DIG_SPEED));
//1.13.2+ will have persistent metadata for this item
AbstractPersistentDataLayer compatLayer = mcMMO.getCompatibilityManager().getPersistentDataLayer();
compatLayer.setSuperAbilityBoostedItem(heldItem, originalDigSpeed);
}
else {
mcMMO.getMetadataService().getItemMetadataService().setSuperAbilityBoostedItem(heldItem, originalDigSpeed);
} else {
int duration = 0;
int amplifier = 0;
@@ -187,18 +181,18 @@ public final class SkillUtils {
PrimarySkillType skill = mcMMOPlayer.getAbilityMode(SuperAbilityType.SUPER_BREAKER) ? PrimarySkillType.MINING : PrimarySkillType.EXCAVATION;
int abilityLengthVar = AdvancedConfig.getInstance().getAbilityLength();
int abilityLengthCap = AdvancedConfig.getInstance().getAbilityLengthCap();
int abilityLengthVar = mcMMO.p.getAdvancedConfig().getAbilityLength();
int abilityLengthCap = mcMMO.p.getAdvancedConfig().getAbilityLengthCap();
int ticks;
if(abilityLengthCap > 0)
{
ticks = PerksUtils.handleActivationPerks(player, Math.min(abilityLengthCap, 2 + (mcMMOPlayer.getSkillLevel(skill) / abilityLengthVar)),
skill.getAbility().getMaxLength()) * Misc.TICK_CONVERSION_FACTOR;
mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR;
} else {
ticks = PerksUtils.handleActivationPerks(player, 2 + ((mcMMOPlayer.getSkillLevel(skill)) / abilityLengthVar),
skill.getAbility().getMaxLength()) * Misc.TICK_CONVERSION_FACTOR;
mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR;
}
PotionEffect abilityBuff = new PotionEffect(PotionEffectType.FAST_DIGGING, duration + ticks, amplifier + 10);
@@ -221,20 +215,22 @@ public final class SkillUtils {
//1.13.2+ will have persistent metadata for this itemStack
AbstractPersistentDataLayer compatLayer = mcMMO.getCompatibilityManager().getPersistentDataLayer();
ItemMetadataService itemMetadataService = mcMMO.getMetadataService().getItemMetadataService();
if(compatLayer.isLegacyAbilityTool(itemStack)) {
if(itemMetadataService.isLegacyAbilityTool(itemStack)) {
ItemMeta itemMeta = itemStack.getItemMeta();
// This is safe to call without prior checks.
itemMeta.removeEnchant(Enchantment.DIG_SPEED);
if(itemMeta != null) {
// This is safe to call without prior checks.
itemMeta.removeEnchant(Enchantment.DIG_SPEED);
itemStack.setItemMeta(itemMeta);
ItemUtils.removeAbilityLore(itemStack);
itemStack.setItemMeta(itemMeta);
ItemUtils.removeAbilityLore(itemStack);
}
}
if(compatLayer.isSuperAbilityBoosted(itemStack)) {
compatLayer.removeBonusDigSpeedOnSuperAbilityTool(itemStack);
if(itemMetadataService.isSuperAbilityBoosted(itemStack)) {
itemMetadataService.removeBonusDigSpeedOnSuperAbilityTool(itemStack);
}
}
@@ -243,14 +239,14 @@ public final class SkillUtils {
}
/**
* Modify the durability of an ItemStack.
* Modify the durability of an ItemStack, using Tools specific formula for unbreaking enchant damage reduction
*
* @param itemStack The ItemStack which durability should be modified
* @param durabilityModifier the amount to modify the durability by
* @param maxDamageModifier the amount to adjust the max damage by
*/
public static void handleDurabilityChange(ItemStack itemStack, double durabilityModifier, double maxDamageModifier) {
if(itemStack.getItemMeta() != null && itemStack.getItemMeta().isUnbreakable()) {
if(itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) {
return;
}
@@ -271,6 +267,26 @@ public final class SkillUtils {
return false;
}
/**
* Modify the durability of an ItemStack, using Armor specific formula for unbreaking enchant damage reduction
*
* @param itemStack The ItemStack which durability should be modified
* @param durabilityModifier the amount to modify the durability by
* @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()) {
return;
}
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);
itemStack.setDurability((short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability));
}
@Nullable
public static Material getRepairAndSalvageItem(@NotNull ItemStack inHand) {
if (ItemUtils.isDiamondTool(inHand) || ItemUtils.isDiamondArmor(inHand)) {

View File

@@ -3,7 +3,6 @@ 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.Permissions;
import com.gmail.nossr50.util.player.UserManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@@ -35,7 +34,7 @@ public class SmeltingTracker {
}
private void setFurnaceOwner(Furnace furnace, Player player) {
mcMMO.getCompatibilityManager().getPersistentDataLayer().setFurnaceOwner(furnace, player.getUniqueId());
mcMMO.getMetadataService().getBlockMetadataService().setFurnaceOwner(furnace, player.getUniqueId());
}
private void printOwnershipGainDebug(Furnace furnace, McMMOPlayer mcMMOPlayer) {
@@ -66,7 +65,7 @@ public class SmeltingTracker {
}
public @Nullable OfflinePlayer getFurnaceOwner(Furnace furnace) {
UUID uuid = mcMMO.getCompatibilityManager().getPersistentDataLayer().getFurnaceOwner(furnace);
UUID uuid = mcMMO.getMetadataService().getBlockMetadataService().getFurnaceOwner(furnace);
if(uuid != null) {
return Bukkit.getOfflinePlayer(uuid);
@@ -89,7 +88,7 @@ public class SmeltingTracker {
}
public void processFurnaceOwnership(Furnace furnace, Player player) {
if(!Permissions.skillEnabled(player, PrimarySkillType.SMELTING))
if(!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING))
return;
//Don't swap ownership if its the same player

View File

@@ -66,43 +66,22 @@ public class SoundManager {
private static Sound getSound(SoundType soundType)
{
switch(soundType)
{
case ANVIL:
return Sound.BLOCK_ANVIL_PLACE;
case ITEM_BREAK:
return Sound.ENTITY_ITEM_BREAK;
case POP:
return Sound.ENTITY_ITEM_PICKUP;
case CHIMAERA_WING:
return Sound.ENTITY_BAT_TAKEOFF;
case LEVEL_UP:
return Sound.ENTITY_PLAYER_LEVELUP;
case FIZZ:
return Sound.BLOCK_FIRE_EXTINGUISH;
case TOOL_READY:
return Sound.ITEM_ARMOR_EQUIP_GOLD;
case ROLL_ACTIVATED:
return Sound.ENTITY_LLAMA_SWAG;
case SKILL_UNLOCKED:
return Sound.UI_TOAST_CHALLENGE_COMPLETE;
case ABILITY_ACTIVATED_BERSERK:
return Sound.BLOCK_CONDUIT_AMBIENT;
case ABILITY_ACTIVATED_GENERIC:
return Sound.ITEM_TRIDENT_RIPTIDE_3;
case DEFLECT_ARROWS:
return Sound.ENTITY_ENDER_EYE_DEATH;
case TIRED:
return Sound.BLOCK_CONDUIT_AMBIENT;
case BLEED:
return Sound.ENTITY_ENDER_EYE_DEATH;
case GLASS:
return Sound.BLOCK_GLASS_BREAK;
case ITEM_CONSUMED:
return Sound.ITEM_BOTTLE_EMPTY;
default:
return null;
}
return switch (soundType) {
case ANVIL -> Sound.BLOCK_ANVIL_PLACE;
case ITEM_BREAK -> Sound.ENTITY_ITEM_BREAK;
case POP -> Sound.ENTITY_ITEM_PICKUP;
case CHIMAERA_WING -> Sound.ENTITY_BAT_TAKEOFF;
case LEVEL_UP -> Sound.ENTITY_PLAYER_LEVELUP;
case FIZZ -> Sound.BLOCK_FIRE_EXTINGUISH;
case TOOL_READY -> Sound.ITEM_ARMOR_EQUIP_GOLD;
case ROLL_ACTIVATED -> Sound.ENTITY_LLAMA_SWAG;
case SKILL_UNLOCKED -> Sound.UI_TOAST_CHALLENGE_COMPLETE;
case ABILITY_ACTIVATED_BERSERK, TIRED -> Sound.BLOCK_CONDUIT_AMBIENT;
case ABILITY_ACTIVATED_GENERIC -> Sound.ITEM_TRIDENT_RIPTIDE_3;
case DEFLECT_ARROWS, BLEED -> Sound.ENTITY_ENDER_EYE_DEATH;
case GLASS -> Sound.BLOCK_GLASS_BREAK;
case ITEM_CONSUMED -> Sound.ITEM_BOTTLE_EMPTY;
};
}
public static float getFizzPitch() {

View File

@@ -31,6 +31,35 @@ public class StringUtils {
return shortDecimal.format(ticks / 20);
}
public static String convertToCamelCaseString(String baseString, String splitBy) {
String[] substrings = baseString.split(splitBy);
String prettyString = "";
int size = 1;
for (String string : substrings) {
prettyString = prettyString.concat(getCapitalized(string));
if (size < substrings.length) {
prettyString = prettyString.concat("");
}
size++;
}
return prettyString;
}
public static String getPrettyCamelCaseName(Object o) {
return StringUtils.convertToCamelCaseString(o.toString(), "_");
}
public static String getPrettySuperAbilityName(SuperAbilityType superAbilityType) {
return StringUtils.getPrettySuperAbilityString(superAbilityType);
}
public static String getPrettySuperAbilityString(SuperAbilityType ability) {
return createPrettyString(ability.toString());
}
/**
* Creates a string from an array skipping the first n elements
@@ -80,8 +109,7 @@ public class StringUtils {
case CARROTS:
case POTATOES:
case NETHER_WART: {
if (data instanceof Ageable) {
Ageable ageData = (Ageable) data;
if (data instanceof Ageable ageData) {
if (ageData.getAge() == ageData.getMaximumAge()) {
return getPrettyItemString(data.getMaterial()).replace(" ", "_") + "_Ripe";
}

View File

@@ -1,6 +1,5 @@
package com.gmail.nossr50.util.text;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.config.RankConfig;
import com.gmail.nossr50.datatypes.json.McMMOUrl;
import com.gmail.nossr50.datatypes.json.McMMOWebLinks;
@@ -64,7 +63,7 @@ public class TextComponentFactory {
public static void sendPlayerSubSkillWikiLink(Player player, String subskillformatted)
{
if(!Config.getInstance().getUrlLinksEnabled())
if(!mcMMO.p.getGeneralConfig().getUrlLinksEnabled())
return;
TextComponent.Builder wikiLinkComponent = Component.text().content(LocaleLoader.getString("Overhaul.mcMMO.MmoInfo.Wiki"));

View File

@@ -16,9 +16,12 @@ import org.jetbrains.annotations.Nullable;
import java.util.List;
public class TextUtils {
private static @Nullable LegacyComponentSerializer customLegacySerializer;
private TextUtils() {
// We don't want any instances of this class.
}
/**
* Makes a single component from an array of components, can optionally add prefixes and suffixes to come before and after each component
* @param componentsArray target array

View File

@@ -1,17 +1,18 @@
package com.gmail.nossr50.util.upgrade;
import com.gmail.nossr50.config.ConfigLoader;
import com.gmail.nossr50.config.BukkitConfig;
import com.gmail.nossr50.datatypes.database.UpgradeType;
import com.gmail.nossr50.mcMMO;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
public class UpgradeManager extends ConfigLoader {
public class UpgradeManager extends BukkitConfig {
private final Set<UpgradeType> setNeededUpgrades;
public UpgradeManager() {
super("upgrades.yml");
super("upgrades_overhaul.yml"); //overhaul is added so we don't have any issues with classic
setNeededUpgrades = EnumSet.allOf(UpgradeType.class);
@@ -40,7 +41,7 @@ public class UpgradeManager extends ConfigLoader {
return;
}
plugin.debug("Saving upgrade status for type " + type.toString() + "...");
mcMMO.p.debug("Saving upgrade status for type " + type.toString() + "...");
config.set("Upgrades_Finished." + type.toString(), true);
@@ -60,6 +61,6 @@ public class UpgradeManager extends ConfigLoader {
}
}
plugin.debug("Needed upgrades: " + Arrays.toString(setNeededUpgrades.toArray(new UpgradeType[setNeededUpgrades.size()])));
mcMMO.p.debug("Needed upgrades: " + Arrays.toString(setNeededUpgrades.toArray(new UpgradeType[setNeededUpgrades.size()])));
}
}