F map autoupdate during flying fixed.

This commit is contained in:
ProSavage 2018-07-12 11:11:07 -05:00
parent 2426142664
commit 143daad9e6
74 changed files with 3460 additions and 3659 deletions

View File

@ -11,11 +11,6 @@ import java.util.Set;
public abstract class Board { public abstract class Board {
protected static Board instance = getBoardImpl(); protected static Board instance = getBoardImpl();
//----------------------------------------------//
// Get and Set
//----------------------------------------------//
public abstract String getIdAt(FLocation flocation);
private static Board getBoardImpl() { private static Board getBoardImpl() {
switch (Conf.backEnd) { switch (Conf.backEnd) {
case JSON: case JSON:
@ -28,6 +23,11 @@ public abstract class Board {
return instance; return instance;
} }
//----------------------------------------------//
// Get and Set
//----------------------------------------------//
public abstract String getIdAt(FLocation flocation);
public abstract Faction getFactionAt(FLocation flocation); public abstract Faction getFactionAt(FLocation flocation);
public abstract void setIdAt(String id, FLocation flocation); public abstract void setIdAt(String id, FLocation flocation);

View File

@ -10,21 +10,26 @@ import java.util.*;
public class Conf { public class Conf {
// Region Style
public static final transient String DYNMAP_STYLE_LINE_COLOR = "#00FF00";
public static final transient double DYNMAP_STYLE_LINE_OPACITY = 0.8D;
public static final transient int DYNMAP_STYLE_LINE_WEIGHT = 3;
public static final transient String DYNMAP_STYLE_FILL_COLOR = "#00FF00";
public static final transient double DYNMAP_STYLE_FILL_OPACITY = 0.35D;
public static final transient String DYNMAP_STYLE_HOME_MARKER = "greenflag";
public static final transient boolean DYNMAP_STYLE_BOOST = false;
public static List<String> baseCommandAliases = new ArrayList<>(); public static List<String> baseCommandAliases = new ArrayList<>();
public static boolean allowNoSlashCommand = true; public static boolean allowNoSlashCommand = true;
// Colors // Colors
public static ChatColor colorMember = ChatColor.GREEN; public static ChatColor colorMember = ChatColor.GREEN;
public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE; public static ChatColor colorAlly = ChatColor.LIGHT_PURPLE;
public static ChatColor colorTruce = ChatColor.DARK_PURPLE; public static ChatColor colorTruce = ChatColor.DARK_PURPLE;
public static ChatColor colorNeutral = ChatColor.WHITE; public static ChatColor colorNeutral = ChatColor.WHITE;
public static ChatColor colorEnemy = ChatColor.RED; public static ChatColor colorEnemy = ChatColor.RED;
public static ChatColor colorPeaceful = ChatColor.GOLD; public static ChatColor colorPeaceful = ChatColor.GOLD;
public static ChatColor colorWilderness = ChatColor.GRAY; public static ChatColor colorWilderness = ChatColor.GRAY;
public static ChatColor colorSafezone = ChatColor.GOLD; public static ChatColor colorSafezone = ChatColor.GOLD;
public static ChatColor colorWar = ChatColor.DARK_RED; public static ChatColor colorWar = ChatColor.DARK_RED;
// Power // Power
public static double powerPlayerMax = 10.0; public static double powerPlayerMax = 10.0;
public static double powerPlayerMin = -10.0; public static double powerPlayerMin = -10.0;
@ -35,32 +40,24 @@ public class Conf {
public static double powerOfflineLossPerDay = 0.0; // players will lose this much power per day offline public static double powerOfflineLossPerDay = 0.0; // players will lose this much power per day offline
public static double powerOfflineLossLimit = 0.0; // players will no longer lose power from being offline once their power drops to this amount or less public static double powerOfflineLossLimit = 0.0; // players will no longer lose power from being offline once their power drops to this amount or less
public static double powerFactionMax = 0.0; // if greater than 0, the cap on how much power a faction can have (additional power from players beyond that will act as a "buffer" of sorts) public static double powerFactionMax = 0.0; // if greater than 0, the cap on how much power a faction can have (additional power from players beyond that will act as a "buffer" of sorts)
public static String prefixAdmin = "***"; public static String prefixAdmin = "***";
public static String prefixCoLeader = "**"; public static String prefixCoLeader = "**";
public static String prefixMod = "*"; public static String prefixMod = "*";
public static String prefixRecruit = "-"; public static String prefixRecruit = "-";
public static String prefixNormal = "+"; public static String prefixNormal = "+";
public static int factionTagLengthMin = 3; public static int factionTagLengthMin = 3;
public static int factionTagLengthMax = 10; public static int factionTagLengthMax = 10;
public static boolean factionTagForceUpperCase = false; public static boolean factionTagForceUpperCase = false;
public static boolean newFactionsDefaultOpen = false; public static boolean newFactionsDefaultOpen = false;
// when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit // when faction membership hits this limit, players will no longer be able to join using /f join; default is 0, no limit
public static int factionMemberLimit = 0; public static int factionMemberLimit = 0;
// what faction ID to start new players in when they first join the server; default is 0, "no faction" // what faction ID to start new players in when they first join the server; default is 0, "no faction"
public static String newPlayerStartingFactionID = "0"; public static String newPlayerStartingFactionID = "0";
public static boolean showMapFactionKey = true; public static boolean showMapFactionKey = true;
public static boolean showNeutralFactionsOnMap = true; public static boolean showNeutralFactionsOnMap = true;
public static boolean showEnemyFactionsOnMap = true; public static boolean showEnemyFactionsOnMap = true;
// Disallow joining/leaving/kicking while power is negative // Disallow joining/leaving/kicking while power is negative
public static boolean canLeaveWithNegativePower = true; public static boolean canLeaveWithNegativePower = true;
// Configuration for faction-only chat // Configuration for faction-only chat
public static boolean factionOnlyChat = true; public static boolean factionOnlyChat = true;
// Configuration on the Faction tag in chat messages. // Configuration on the Faction tag in chat messages.
@ -78,24 +75,18 @@ public class Conf {
public static String allianceChatFormat = ChatColor.LIGHT_PURPLE + "%s:" + ChatColor.WHITE + " %s"; public static String allianceChatFormat = ChatColor.LIGHT_PURPLE + "%s:" + ChatColor.WHITE + " %s";
public static String truceChatFormat = ChatColor.DARK_PURPLE + "%s:" + ChatColor.WHITE + " %s"; public static String truceChatFormat = ChatColor.DARK_PURPLE + "%s:" + ChatColor.WHITE + " %s";
public static String modChatFormat = ChatColor.RED + "%s:" + ChatColor.WHITE + " %s"; public static String modChatFormat = ChatColor.RED + "%s:" + ChatColor.WHITE + " %s";
public static int enemyFlyCheckRadius = 16; public static int enemyFlyCheckRadius = 16;
public static boolean noEnderpearlsInFly = false; public static boolean noEnderpearlsInFly = false;
public static boolean broadcastDescriptionChanges = false; public static boolean broadcastDescriptionChanges = false;
public static boolean broadcastTagChanges = false; public static boolean broadcastTagChanges = false;
public static double saveToFileEveryXMinutes = 30.0; public static double saveToFileEveryXMinutes = 30.0;
public static double autoLeaveAfterDaysOfInactivity = 10.0; public static double autoLeaveAfterDaysOfInactivity = 10.0;
public static double autoLeaveRoutineRunsEveryXMinutes = 5.0; public static double autoLeaveRoutineRunsEveryXMinutes = 5.0;
public static int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick public static int autoLeaveRoutineMaxMillisecondsPerTick = 5; // 1 server tick is roughly 50ms, so default max 10% of a tick
public static boolean removePlayerDataWhenBanned = true; public static boolean removePlayerDataWhenBanned = true;
public static boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction. public static boolean autoLeaveDeleteFPlayerData = true; // Let them just remove player from Faction.
public static boolean worldGuardChecking = false; public static boolean worldGuardChecking = false;
public static boolean worldGuardBuildPriority = false; public static boolean worldGuardBuildPriority = false;
// server logging options // server logging options
public static boolean logFactionCreate = true; public static boolean logFactionCreate = true;
public static boolean logFactionDisband = true; public static boolean logFactionDisband = true;
@ -106,14 +97,12 @@ public class Conf {
public static boolean logLandUnclaims = true; public static boolean logLandUnclaims = true;
public static boolean logMoneyTransactions = true; public static boolean logMoneyTransactions = true;
public static boolean logPlayerCommands = true; public static boolean logPlayerCommands = true;
// prevent some potential exploits // prevent some potential exploits
public static boolean handleExploitObsidianGenerators = true; public static boolean handleExploitObsidianGenerators = true;
public static boolean handleExploitEnderPearlClipping = true; public static boolean handleExploitEnderPearlClipping = true;
public static boolean handleExploitInteractionSpam = true; public static boolean handleExploitInteractionSpam = true;
public static boolean handleExploitTNTWaterlog = false; public static boolean handleExploitTNTWaterlog = false;
public static boolean handleExploitLiquidFlow = false; public static boolean handleExploitLiquidFlow = false;
public static boolean homesEnabled = true; public static boolean homesEnabled = true;
public static boolean homesMustBeInClaimedTerritory = true; public static boolean homesMustBeInClaimedTerritory = true;
public static boolean homesTeleportToOnDeath = true; public static boolean homesTeleportToOnDeath = true;
@ -126,43 +115,32 @@ public class Conf {
public static boolean homesTeleportAllowedFromDifferentWorld = true; public static boolean homesTeleportAllowedFromDifferentWorld = true;
public static double homesTeleportAllowedEnemyDistance = 32.0; public static double homesTeleportAllowedEnemyDistance = 32.0;
public static boolean homesTeleportIgnoreEnemiesIfInOwnTerritory = true; public static boolean homesTeleportIgnoreEnemiesIfInOwnTerritory = true;
public static boolean disablePVPBetweenNeutralFactions = false; public static boolean disablePVPBetweenNeutralFactions = false;
public static boolean disablePVPForFactionlessPlayers = false; public static boolean disablePVPForFactionlessPlayers = false;
public static boolean enablePVPAgainstFactionlessInAttackersLand = false; public static boolean enablePVPAgainstFactionlessInAttackersLand = false;
public static int noPVPDamageToOthersForXSecondsAfterLogin = 3; public static int noPVPDamageToOthersForXSecondsAfterLogin = 3;
public static boolean peacefulTerritoryDisablePVP = true; public static boolean peacefulTerritoryDisablePVP = true;
public static boolean peacefulTerritoryDisableMonsters = false; public static boolean peacefulTerritoryDisableMonsters = false;
public static boolean peacefulTerritoryDisableBoom = false; public static boolean peacefulTerritoryDisableBoom = false;
public static boolean peacefulMembersDisablePowerLoss = true; public static boolean peacefulMembersDisablePowerLoss = true;
public static boolean permanentFactionsDisableLeaderPromotion = false; public static boolean permanentFactionsDisableLeaderPromotion = false;
public static boolean claimsMustBeConnected = false; public static boolean claimsMustBeConnected = false;
public static boolean claimsCanBeUnconnectedIfOwnedByOtherFaction = true; public static boolean claimsCanBeUnconnectedIfOwnedByOtherFaction = true;
public static int claimsRequireMinFactionMembers = 1; public static int claimsRequireMinFactionMembers = 1;
public static int claimedLandsMax = 0; public static int claimedLandsMax = 0;
public static int lineClaimLimit = 5; public static int lineClaimLimit = 5;
// if someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit // if someone is doing a radius claim and the process fails to claim land this many times in a row, it will exit
public static int radiusClaimFailureLimit = 9; public static int radiusClaimFailureLimit = 9;
public static double considerFactionsReallyOfflineAfterXMinutes = 0.0; public static double considerFactionsReallyOfflineAfterXMinutes = 0.0;
public static int actionDeniedPainAmount = 1; public static int actionDeniedPainAmount = 1;
// commands which will be prevented if the player is a member of a permanent faction // commands which will be prevented if the player is a member of a permanent faction
public static Set<String> permanentFactionMemberDenyCommands = new LinkedHashSet<>(); public static Set<String> permanentFactionMemberDenyCommands = new LinkedHashSet<>();
// commands which will be prevented when in claimed territory of another faction // commands which will be prevented when in claimed territory of another faction
public static Set<String> territoryNeutralDenyCommands = new LinkedHashSet<>(); public static Set<String> territoryNeutralDenyCommands = new LinkedHashSet<>();
public static Set<String> territoryEnemyDenyCommands = new LinkedHashSet<>(); public static Set<String> territoryEnemyDenyCommands = new LinkedHashSet<>();
public static Set<String> territoryAllyDenyCommands = new LinkedHashSet<>(); public static Set<String> territoryAllyDenyCommands = new LinkedHashSet<>();
public static Set<String> warzoneDenyCommands = new LinkedHashSet<>(); public static Set<String> warzoneDenyCommands = new LinkedHashSet<>();
public static Set<String> wildernessDenyCommands = new LinkedHashSet<>(); public static Set<String> wildernessDenyCommands = new LinkedHashSet<>();
public static boolean territoryDenyBuild = true; public static boolean territoryDenyBuild = true;
public static boolean territoryDenyBuildWhenOffline = true; public static boolean territoryDenyBuildWhenOffline = true;
public static boolean territoryPainBuild = false; public static boolean territoryPainBuild = false;
@ -194,13 +172,11 @@ public class Conf {
public static boolean territoryBlockTNTWhenOffline = false; public static boolean territoryBlockTNTWhenOffline = false;
public static boolean territoryDenyEndermanBlocks = true; public static boolean territoryDenyEndermanBlocks = true;
public static boolean territoryDenyEndermanBlocksWhenOffline = true; public static boolean territoryDenyEndermanBlocksWhenOffline = true;
public static boolean safeZoneDenyBuild = true; public static boolean safeZoneDenyBuild = true;
public static boolean safeZoneDenyUseage = true; public static boolean safeZoneDenyUseage = true;
public static boolean safeZoneBlockTNT = true; public static boolean safeZoneBlockTNT = true;
public static boolean safeZonePreventAllDamageToPlayers = false; public static boolean safeZonePreventAllDamageToPlayers = false;
public static boolean safeZoneDenyEndermanBlocks = true; public static boolean safeZoneDenyEndermanBlocks = true;
public static boolean warZoneDenyBuild = true; public static boolean warZoneDenyBuild = true;
public static boolean warZoneDenyUseage = true; public static boolean warZoneDenyUseage = true;
public static boolean warZoneBlockCreepers = false; public static boolean warZoneBlockCreepers = false;
@ -209,7 +185,6 @@ public class Conf {
public static boolean warZonePowerLoss = true; public static boolean warZonePowerLoss = true;
public static boolean warZoneFriendlyFire = false; public static boolean warZoneFriendlyFire = false;
public static boolean warZoneDenyEndermanBlocks = true; public static boolean warZoneDenyEndermanBlocks = true;
public static boolean wildernessDenyBuild = false; public static boolean wildernessDenyBuild = false;
public static boolean wildernessDenyUseage = false; public static boolean wildernessDenyUseage = false;
public static boolean wildernessBlockCreepers = false; public static boolean wildernessBlockCreepers = false;
@ -217,7 +192,6 @@ public class Conf {
public static boolean wildernessBlockTNT = false; public static boolean wildernessBlockTNT = false;
public static boolean wildernessPowerLoss = true; public static boolean wildernessPowerLoss = true;
public static boolean wildernessDenyEndermanBlocks = false; public static boolean wildernessDenyEndermanBlocks = false;
// for claimed areas where further faction-member ownership can be defined // for claimed areas where further faction-member ownership can be defined
public static boolean ownedAreasEnabled = true; public static boolean ownedAreasEnabled = true;
public static int ownedAreasLimitPerFaction = 0; public static int ownedAreasLimitPerFaction = 0;
@ -227,18 +201,14 @@ public class Conf {
public static boolean ownedAreaPainBuild = false; public static boolean ownedAreaPainBuild = false;
public static boolean ownedAreaProtectMaterials = true; public static boolean ownedAreaProtectMaterials = true;
public static boolean ownedAreaDenyUseage = true; public static boolean ownedAreaDenyUseage = true;
public static boolean ownedMessageOnBorder = true; public static boolean ownedMessageOnBorder = true;
public static boolean ownedMessageInsideTerritory = true; public static boolean ownedMessageInsideTerritory = true;
public static boolean ownedMessageByChunk = false; public static boolean ownedMessageByChunk = false;
public static boolean pistonProtectionThroughDenyBuild = true; public static boolean pistonProtectionThroughDenyBuild = true;
public static Set<Material> territoryProtectedMaterials = EnumSet.noneOf(Material.class); public static Set<Material> territoryProtectedMaterials = EnumSet.noneOf(Material.class);
public static Set<Material> territoryDenyUseageMaterials = EnumSet.noneOf(Material.class); public static Set<Material> territoryDenyUseageMaterials = EnumSet.noneOf(Material.class);
public static Set<Material> territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class); public static Set<Material> territoryProtectedMaterialsWhenOffline = EnumSet.noneOf(Material.class);
public static Set<Material> territoryDenyUseageMaterialsWhenOffline = EnumSet.noneOf(Material.class); public static Set<Material> territoryDenyUseageMaterialsWhenOffline = EnumSet.noneOf(Material.class);
public static transient Set<EntityType> safeZoneNerfedCreatureTypes = EnumSet.noneOf(EntityType.class); public static transient Set<EntityType> safeZoneNerfedCreatureTypes = EnumSet.noneOf(EntityType.class);
// Economy settings // Economy settings
public static boolean econEnabled = false; public static boolean econEnabled = false;
@ -264,6 +234,11 @@ public class Conf {
public static double econCostMap = 0.0; public static double econCostMap = 0.0;
public static double econCostPower = 0.0; public static double econCostPower = 0.0;
public static double econCostShow = 0.0; public static double econCostShow = 0.0;
// -------------------------------------------- //
// INTEGRATION: DYNMAP
// -------------------------------------------- //
public static double econCostStuck = 0.0; public static double econCostStuck = 0.0;
public static double econCostOpen = 0.0; public static double econCostOpen = 0.0;
public static double econCostAlly = 0.0; public static double econCostAlly = 0.0;
@ -271,27 +246,16 @@ public class Conf {
public static double econCostEnemy = 0.0; public static double econCostEnemy = 0.0;
public static double econCostNeutral = 0.0; public static double econCostNeutral = 0.0;
public static double econCostNoBoom = 0.0; public static double econCostNoBoom = 0.0;
// -------------------------------------------- //
// INTEGRATION: DYNMAP
// -------------------------------------------- //
// Should the dynmap intagration be used? // Should the dynmap intagration be used?
public static boolean dynmapUse = false; public static boolean dynmapUse = false;
// Name of the Factions layer // Name of the Factions layer
public static String dynmapLayerName = "Factions"; public static String dynmapLayerName = "Factions";
// Should the layer be visible per default // Should the layer be visible per default
public static boolean dynmapLayerVisible = true; public static boolean dynmapLayerVisible = true;
// Ordering priority in layer menu (low goes before high - default is 0) // Ordering priority in layer menu (low goes before high - default is 0)
public static int dynmapLayerPriority = 2; public static int dynmapLayerPriority = 2;
// (optional) set minimum zoom level before layer is visible (0 = default, always visible) // (optional) set minimum zoom level before layer is visible (0 = default, always visible)
public static int dynmapLayerMinimumZoom = 0; public static int dynmapLayerMinimumZoom = 0;
// Format for popup - substitute values for macros // Format for popup - substitute values for macros
public static String dynmapDescription = public static String dynmapDescription =
"<div class=\"infowindow\">\n" "<div class=\"infowindow\">\n"
@ -307,33 +271,19 @@ public class Conf {
+ "<span style=\"font-weight: bold;\">Bank:</span> %money%<br>\n" + "<span style=\"font-weight: bold;\">Bank:</span> %money%<br>\n"
+ "<br>\n" + "<br>\n"
+ "</div>"; + "</div>";
// Enable the %money% macro. Only do this if you know your economy manager is thread-safe. // Enable the %money% macro. Only do this if you know your economy manager is thread-safe.
public static boolean dynmapDescriptionMoney = false; public static boolean dynmapDescriptionMoney = false;
// Allow players in faction to see one another on Dynmap (only relevant if Dynmap has 'player-info-protected' enabled) // Allow players in faction to see one another on Dynmap (only relevant if Dynmap has 'player-info-protected' enabled)
public static boolean dynmapVisibilityByFaction = true; public static boolean dynmapVisibilityByFaction = true;
// Optional setting to limit which regions to show. // Optional setting to limit which regions to show.
// If empty all regions are shown. // If empty all regions are shown.
// Specify Faction either by name or UUID. // Specify Faction either by name or UUID.
// To show all regions on a given world, add 'world:<worldname>' to the list. // To show all regions on a given world, add 'world:<worldname>' to the list.
public static Set<String> dynmapVisibleFactions = new HashSet<>(); public static Set<String> dynmapVisibleFactions = new HashSet<>();
// Optional setting to hide specific Factions. // Optional setting to hide specific Factions.
// Specify Faction either by name or UUID. // Specify Faction either by name or UUID.
// To hide all regions on a given world, add 'world:<worldname>' to the list. // To hide all regions on a given world, add 'world:<worldname>' to the list.
public static Set<String> dynmapHiddenFactions = new HashSet<>(); public static Set<String> dynmapHiddenFactions = new HashSet<>();
// Region Style
public static final transient String DYNMAP_STYLE_LINE_COLOR = "#00FF00";
public static final transient double DYNMAP_STYLE_LINE_OPACITY = 0.8D;
public static final transient int DYNMAP_STYLE_LINE_WEIGHT = 3;
public static final transient String DYNMAP_STYLE_FILL_COLOR = "#00FF00";
public static final transient double DYNMAP_STYLE_FILL_OPACITY = 0.35D;
public static final transient String DYNMAP_STYLE_HOME_MARKER = "greenflag";
public static final transient boolean DYNMAP_STYLE_BOOST = false;
public static DynmapStyle dynmapDefaultStyle = new DynmapStyle() public static DynmapStyle dynmapDefaultStyle = new DynmapStyle()
.setStrokeColor(DYNMAP_STYLE_LINE_COLOR) .setStrokeColor(DYNMAP_STYLE_LINE_COLOR)
.setLineOpacity(DYNMAP_STYLE_LINE_OPACITY) .setLineOpacity(DYNMAP_STYLE_LINE_OPACITY)
@ -375,6 +325,10 @@ public class Conf {
public static int mapHeight = 17; public static int mapHeight = 17;
public static int mapWidth = 49; public static int mapWidth = 49;
public static transient char[] mapKeyChrs = "\\/#$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz?".toCharArray(); public static transient char[] mapKeyChrs = "\\/#$%=&^ABCDEFGHJKLMNOPQRSTUVWXYZ1234567890abcdeghjmnopqrsuvwxyz?".toCharArray();
// -------------------------------------------- //
// Persistance
// -------------------------------------------- //
private static transient Conf i = new Conf();
static { static {
baseCommandAliases.add("f"); baseCommandAliases.add("f");
@ -455,11 +409,6 @@ public class Conf {
safeZoneNerfedCreatureTypes.add(EntityType.ZOMBIE); safeZoneNerfedCreatureTypes.add(EntityType.ZOMBIE);
} }
// -------------------------------------------- //
// Persistance
// -------------------------------------------- //
private static transient Conf i = new Conf();
public static void load() { public static void load() {
P.p.persist.loadOrSaveDefault(i, Conf.class, "conf"); P.p.persist.loadOrSaveDefault(i, Conf.class, "conf");
} }

View File

@ -13,9 +13,6 @@ import java.util.Set;
public class FLocation implements Serializable { public class FLocation implements Serializable {
private static final long serialVersionUID = -8292915234027387983L; private static final long serialVersionUID = -8292915234027387983L;
private static final boolean worldBorderSupport; private static final boolean worldBorderSupport;
private String worldName = "world";
private int x = 0;
private int z = 0;
static { static {
boolean worldBorderClassPresent = false; boolean worldBorderClassPresent = false;
@ -28,6 +25,10 @@ public class FLocation implements Serializable {
worldBorderSupport = worldBorderClassPresent; worldBorderSupport = worldBorderClassPresent;
} }
private String worldName = "world";
private int x = 0;
private int z = 0;
//----------------------------------------------// //----------------------------------------------//
// Constructors // Constructors
//----------------------------------------------// //----------------------------------------------//
@ -62,43 +63,6 @@ public class FLocation implements Serializable {
// Getters and Setters // Getters and Setters
//----------------------------------------------// //----------------------------------------------//
public String getWorldName() {
return worldName;
}
public World getWorld() {
return Bukkit.getWorld(worldName);
}
public void setWorldName(String worldName) {
this.worldName = worldName;
}
public long getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public long getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
public String getCoordString() {
return "" + x + "," + z;
}
@Override
public String toString() {
return "[" + this.getWorldName() + "," + this.getCoordString() + "]";
}
public static FLocation fromString(String string) { public static FLocation fromString(String string) {
int index = string.indexOf(",", 0); int index = string.indexOf(",", 0);
int start = 1; int start = 1;
@ -110,10 +74,6 @@ public class FLocation implements Serializable {
return new FLocation(worldName, x, y); return new FLocation(worldName, x, y);
} }
//----------------------------------------------//
// Block/Chunk/Region Value Transformation
//----------------------------------------------//
// bit-shifting is used because it's much faster than standard division and multiplication // bit-shifting is used because it's much faster than standard division and multiplication
public static int blockToChunk(int blockVal) { // 1 chunk is 16x16 blocks public static int blockToChunk(int blockVal) { // 1 chunk is 16x16 blocks
return blockVal >> 4; // ">> 4" == "/ 16" return blockVal >> 4; // ">> 4" == "/ 16"
@ -139,10 +99,63 @@ public class FLocation implements Serializable {
return regionVal << 5; // "<< 5" == "* 32" return regionVal << 5; // "<< 5" == "* 32"
} }
public static HashSet<FLocation> getArea(FLocation from, FLocation to) {
HashSet<FLocation> ret = new HashSet<>();
for (long x : MiscUtil.range(from.getX(), to.getX())) {
for (long z : MiscUtil.range(from.getZ(), to.getZ())) {
ret.add(new FLocation(from.getWorldName(), (int) x, (int) z));
}
}
return ret;
}
public String getWorldName() {
return worldName;
}
public void setWorldName(String worldName) {
this.worldName = worldName;
}
//----------------------------------------------//
// Block/Chunk/Region Value Transformation
//----------------------------------------------//
public World getWorld() {
return Bukkit.getWorld(worldName);
}
public long getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public long getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
public String getCoordString() {
return "" + x + "," + z;
}
//----------------------------------------------// //----------------------------------------------//
// Misc Geometry // Misc Geometry
//----------------------------------------------// //----------------------------------------------//
@Override
public String toString() {
return "[" + this.getWorldName() + "," + this.getCoordString() + "]";
}
public FLocation getRelative(int dx, int dz) { public FLocation getRelative(int dx, int dz) {
return new FLocation(this.worldName, this.x + dx, this.z + dz); return new FLocation(this.worldName, this.x + dx, this.z + dz);
} }
@ -215,18 +228,6 @@ public class FLocation implements Serializable {
return ret; return ret;
} }
public static HashSet<FLocation> getArea(FLocation from, FLocation to) {
HashSet<FLocation> ret = new HashSet<>();
for (long x : MiscUtil.range(from.getX(), to.getX())) {
for (long z : MiscUtil.range(from.getZ(), to.getZ())) {
ret.add(new FLocation(from.getWorldName(), (int) x, (int) z));
}
}
return ret;
}
//----------------------------------------------// //----------------------------------------------//
// Comparison // Comparison
//----------------------------------------------// //----------------------------------------------//

View File

@ -332,7 +332,4 @@ public interface FPlayer extends EconomyParticipator {
void clearWarmup(); void clearWarmup();
} }

View File

@ -9,8 +9,6 @@ import java.util.Collection;
public abstract class FPlayers { public abstract class FPlayers {
protected static FPlayers instance = getFPlayersImpl(); protected static FPlayers instance = getFPlayersImpl();
public abstract void clean();
public static FPlayers getInstance() { public static FPlayers getInstance() {
return instance; return instance;
} }
@ -23,6 +21,8 @@ public abstract class FPlayers {
return null; return null;
} }
public abstract void clean();
public abstract Collection<FPlayer> getOnlinePlayers(); public abstract Collection<FPlayer> getOnlinePlayers();
public abstract FPlayer getByPlayer(Player player); public abstract FPlayer getByPlayer(Player player);

View File

@ -8,6 +8,18 @@ import java.util.Set;
public abstract class Factions { public abstract class Factions {
protected static Factions instance = getFactionsImpl(); protected static Factions instance = getFactionsImpl();
public static Factions getInstance() {
return instance;
}
private static Factions getFactionsImpl() {
switch (Conf.backEnd) {
case JSON:
return new JSONFactions();
}
return null;
}
public abstract Faction getFactionById(String id); public abstract Faction getFactionById(String id);
public abstract Faction getByTag(String str); public abstract Faction getByTag(String str);
@ -39,17 +51,5 @@ public abstract class Factions {
public abstract void forceSave(boolean sync); public abstract void forceSave(boolean sync);
public static Factions getInstance() {
return instance;
}
private static Factions getFactionsImpl() {
switch (Conf.backEnd) {
case JSON:
return new JSONFactions();
}
return null;
}
public abstract void load(); public abstract void load();
} }

View File

@ -49,13 +49,24 @@ public class P extends MPlugin {
public static Permission perms = null; public static Permission perms = null;
public boolean PlaceholderApi; public boolean PlaceholderApi;
// Commands
public FCmdRoot cmdBase;
public CmdAutoHelp cmdAutoHelp;
public boolean mc17 = false;
public boolean mc18 = false;
public boolean factionsFlight = false;
ItemStack item = new ItemStack(Material.CAKE); ItemStack item = new ItemStack(Material.CAKE);
// Persistence related // Persistence related
private boolean locked = false; private boolean locked = false;
private Integer AutoLeaveTask = null;
private boolean hookedPlayervaults;
private ClipPlaceholderAPIManager clipPlaceholderAPIManager;
private boolean mvdwPlaceholderAPIManager = false;
public P() {
p = this;
}
public boolean getLocked() { public boolean getLocked() {
return this.locked; return this.locked;
@ -66,7 +77,6 @@ public class P extends MPlugin {
this.setAutoSave(val); this.setAutoSave(val);
} }
private Integer AutoLeaveTask = null;
public void playSoundForAll(String sound) { public void playSoundForAll(String sound) {
for (Player pl : Bukkit.getOnlinePlayers()) { for (Player pl : Bukkit.getOnlinePlayers()) {
playSound(pl, sound); playSound(pl, sound);
@ -90,22 +100,6 @@ public class P extends MPlugin {
sound = sound.split(":")[0]; sound = sound.split(":")[0];
p.playSound(p.getLocation(), Sound.valueOf(sound), pitch, 5.0F); p.playSound(p.getLocation(), Sound.valueOf(sound), pitch, 5.0F);
} }
// Commands
public FCmdRoot cmdBase;
public CmdAutoHelp cmdAutoHelp;
private boolean hookedPlayervaults;
private ClipPlaceholderAPIManager clipPlaceholderAPIManager;
private boolean mvdwPlaceholderAPIManager = false;
public P() {
p = this;
}
public boolean mc17 = false;
public boolean mc18 = false;
public boolean factionsFlight = false;
@Override @Override
public void onEnable() { public void onEnable() {
@ -176,16 +170,13 @@ public class P extends MPlugin {
getServer().getPluginManager().registerEvents(new FactionsExploitListener(), this); getServer().getPluginManager().registerEvents(new FactionsExploitListener(), this);
getServer().getPluginManager().registerEvents(new FactionsBlockListener(this), this); getServer().getPluginManager().registerEvents(new FactionsBlockListener(this), this);
getServer().getPluginManager().registerEvents(new FUpgradesGUI(), this); getServer().getPluginManager().registerEvents(new FUpgradesGUI(), this);
getServer().getPluginManager().registerEvents(new EXPUpgrade(),this); getServer().getPluginManager().registerEvents(new EXPUpgrade(), this);
getServer().getPluginManager().registerEvents(new CropUpgrades(),this); getServer().getPluginManager().registerEvents(new CropUpgrades(), this);
getServer().getPluginManager().registerEvents(new SpawnerUpgrades(),this); getServer().getPluginManager().registerEvents(new SpawnerUpgrades(), this);
// since some other plugins execute commands directly through this command interface, provide it // since some other plugins execute commands directly through this command interface, provide it
this.getCommand(this.refCommand).setExecutor(this); this.getCommand(this.refCommand).setExecutor(this);
setupPlaceholderAPI(); setupPlaceholderAPI();
postEnable(); postEnable();
this.loadSuccessful = true; this.loadSuccessful = true;
@ -245,7 +236,8 @@ public class P extends MPlugin {
Type accessTypeAdatper = new TypeToken<Map<Permissable, Map<PermissableAction, Access>>>() { Type accessTypeAdatper = new TypeToken<Map<Permissable, Map<PermissableAction, Access>>>() {
}.getType(); }.getType();
return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().enableComplexMapKeySerialization().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE).registerTypeAdapter(accessTypeAdatper, new PermissionsMapTypeAdapter()).registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()).registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()).registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY); } return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().enableComplexMapKeySerialization().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE).registerTypeAdapter(accessTypeAdatper, new PermissionsMapTypeAdapter()).registerTypeAdapter(LazyLocation.class, new MyLocationTypeAdapter()).registerTypeAdapter(mapFLocToStringSetType, new MapFLocToStringSetTypeAdapter()).registerTypeAdapterFactory(EnumTypeAdapter.ENUM_FACTORY);
}
@Override @Override
public void onDisable() { public void onDisable() {
@ -280,6 +272,7 @@ public class P extends MPlugin {
//Board.getInstance().forceSave(); Not sure why this was there as it's called after the board is already saved. //Board.getInstance().forceSave(); Not sure why this was there as it's called after the board is already saved.
Conf.save(); Conf.save();
} }
public ItemStack createItem(Material material, int amount, short datavalue, String name, List<String> lore) { public ItemStack createItem(Material material, int amount, short datavalue, String name, List<String> lore) {
ItemStack item = new ItemStack(material, amount, datavalue); ItemStack item = new ItemStack(material, amount, datavalue);
ItemMeta meta = item.getItemMeta(); ItemMeta meta = item.getItemMeta();
@ -303,6 +296,7 @@ public class P extends MPlugin {
Economy econ = rsp.getProvider(); Economy econ = rsp.getProvider();
return econ; return econ;
} }
@Override @Override
public boolean logPlayerCommands() { public boolean logPlayerCommands() {
return Conf.logPlayerCommands; return Conf.logPlayerCommands;
@ -324,8 +318,8 @@ public class P extends MPlugin {
return handleCommand(sender, cmd + " " + TextUtil.implode(Arrays.asList(split), " "), false); return handleCommand(sender, cmd + " " + TextUtil.implode(Arrays.asList(split), " "), false);
} }
public void createTimedHologram(final Location location, String text, Long timeout){ public void createTimedHologram(final Location location, String text, Long timeout) {
ArmorStand as = (ArmorStand) location.add(0.5,1,0.5).getWorld().spawnEntity(location, EntityType.ARMOR_STAND); //Spawn the ArmorStand ArmorStand as = (ArmorStand) location.add(0.5, 1, 0.5).getWorld().spawnEntity(location, EntityType.ARMOR_STAND); //Spawn the ArmorStand
as.setVisible(false); //Makes the ArmorStand invisible as.setVisible(false); //Makes the ArmorStand invisible
as.setGravity(false); //Make sure it doesn't fall as.setGravity(false); //Make sure it doesn't fall
as.setCanPickupItems(false); //I'm not sure what happens if you leave this as it is, but you might as well disable it as.setCanPickupItems(false); //I'm not sure what happens if you leave this as it is, but you might as well disable it
@ -338,7 +332,7 @@ public class P extends MPlugin {
Bukkit.broadcastMessage("removing stand"); Bukkit.broadcastMessage("removing stand");
armorStand.remove(); armorStand.remove();
} }
},timeout*20); }, timeout * 20);
} }
@ -442,8 +436,8 @@ public class P extends MPlugin {
//colors a string list //colors a string list
public List<String> colorList(List<String> lore) { public List<String> colorList(List<String> lore) {
for (int i = 0; i <= lore.size()-1;i++){ for (int i = 0; i <= lore.size() - 1; i++) {
lore.set(i,color(lore.get(i))); lore.set(i, color(lore.get(i)));
} }
return lore; return lore;
} }

View File

@ -75,7 +75,6 @@ public class CmdBan extends FCommand {
} }
// Ban the user. // Ban the user.
myFaction.ban(target, fme); myFaction.ban(target, fme);
myFaction.deinvite(target); // can't hurt myFaction.deinvite(target); // can't hurt

View File

@ -4,7 +4,6 @@ import com.massivecraft.factions.Conf;
import com.massivecraft.factions.struct.ChatMode; import com.massivecraft.factions.struct.ChatMode;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit;
public class CmdChat extends FCommand { public class CmdChat extends FCommand {
@ -38,7 +37,7 @@ public class CmdChat extends FCommand {
if (modeString != null) { if (modeString != null) {
modeString = modeString.toLowerCase(); modeString = modeString.toLowerCase();
if (modeString.startsWith("m")){ if (modeString.startsWith("m")) {
modeTarget = ChatMode.MOD; modeTarget = ChatMode.MOD;
} else if (modeString.startsWith("p")) { } else if (modeString.startsWith("p")) {
modeTarget = ChatMode.PUBLIC; modeTarget = ChatMode.PUBLIC;
@ -56,10 +55,9 @@ public class CmdChat extends FCommand {
fme.setChatMode(modeTarget); fme.setChatMode(modeTarget);
if (fme.getChatMode() == ChatMode.MOD) if (fme.getChatMode() == ChatMode.MOD) {
{
msg(TL.COMMAND_CHAT_MODE_MOD); msg(TL.COMMAND_CHAT_MODE_MOD);
}else if (fme.getChatMode() == ChatMode.PUBLIC) { } else if (fme.getChatMode() == ChatMode.PUBLIC) {
msg(TL.COMMAND_CHAT_MODE_PUBLIC); msg(TL.COMMAND_CHAT_MODE_PUBLIC);
} else if (fme.getChatMode() == ChatMode.ALLIANCE) { } else if (fme.getChatMode() == ChatMode.ALLIANCE) {
msg(TL.COMMAND_CHAT_MODE_ALLIANCE); msg(TL.COMMAND_CHAT_MODE_ALLIANCE);

View File

@ -50,8 +50,8 @@ public class CmdClaim extends FCommand {
} }
new SpiralTask(new FLocation(me), radius) { new SpiralTask(new FLocation(me), radius) {
private int failCount = 0;
private final int limit = Conf.radiusClaimFailureLimit - 1; private final int limit = Conf.radiusClaimFailureLimit - 1;
private int failCount = 0;
@Override @Override
public boolean work() { public boolean work() {

View File

@ -4,11 +4,10 @@ import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.plugin.java.JavaPlugin;
public class CmdCoords extends FCommand { public class CmdCoords extends FCommand {
public CmdCoords(){ public CmdCoords() {
super(); super();
this.aliases.add("coords"); this.aliases.add("coords");
this.aliases.add("coord"); this.aliases.add("coord");
@ -24,11 +23,11 @@ public class CmdCoords extends FCommand {
} }
@Override @Override
public void perform(){ public void perform() {
Location location = fme.getPlayer().getLocation(); Location location = fme.getPlayer().getLocation();
String message = TL.COMMAND_COORDS_MESSAGE.toString().replace("{player}",fme.getPlayer().getDisplayName()).replace("{x}",(int) location.getX() + "") String message = TL.COMMAND_COORDS_MESSAGE.toString().replace("{player}", fme.getPlayer().getDisplayName()).replace("{x}", (int) location.getX() + "")
.replace("{y}",(int) location.getY() + "").replace("{z}",(int) location.getZ() + "").replace("{world}",location.getWorld().getName()); .replace("{y}", (int) location.getY() + "").replace("{z}", (int) location.getZ() + "").replace("{world}", location.getWorld().getName());
for (FPlayer fPlayer : fme.getFaction().getFPlayers()){ for (FPlayer fPlayer : fme.getFaction().getFPlayers()) {
fPlayer.sendMessage(message); fPlayer.sendMessage(message);
} }
} }

View File

@ -24,6 +24,7 @@ public class CmdFly extends FCommand {
public static ConcurrentHashMap<String, Boolean> flyMap = new ConcurrentHashMap<String, Boolean>(); public static ConcurrentHashMap<String, Boolean> flyMap = new ConcurrentHashMap<String, Boolean>();
public static int id = -1; public static int id = -1;
public static int flyid = -1; public static int flyid = -1;
public CmdFly() { public CmdFly() {
super(); super();
this.aliases.add("fly"); this.aliases.add("fly");
@ -48,15 +49,15 @@ public class CmdFly extends FCommand {
continue; continue;
} }
if (!P.p.mc17) { if (!P.p.mc17) {
if (player.getGameMode() == GameMode.SPECTATOR){ if (player.getGameMode() == GameMode.SPECTATOR) {
continue; continue;
} }
} }
if (FPlayers.getInstance().getByPlayer(player).isVanished()){ if (FPlayers.getInstance().getByPlayer(player).isVanished()) {
continue; continue;
} }
ParticleEffect.CLOUD.display((float) 0, (float) 0, (float) 0, (float) 0, 3, player.getLocation().add(0, -0.35, 0), 16); ParticleEffect.CLOUD.display((float) 0, (float) 0, (float) 0, (float) 0, 3, player.getLocation().add(0, -0.35, 0), 16);
} }
if (flyMap.keySet().size() == 0) { if (flyMap.keySet().size() == 0) {
Bukkit.getScheduler().cancelTask(id); Bukkit.getScheduler().cancelTask(id);
@ -72,44 +73,44 @@ public class CmdFly extends FCommand {
public void run() throws ConcurrentModificationException { //threw the exception for now, until I recode fly :( Cringe. public void run() throws ConcurrentModificationException { //threw the exception for now, until I recode fly :( Cringe.
checkTaskState(); checkTaskState();
if (flyMap.keySet().size() != 0) { if (flyMap.keySet().size() != 0) {
for (String name : flyMap.keySet()) { for (String name : flyMap.keySet()) {
if (name == null) { if (name == null) {
continue; continue;
} }
Player player = Bukkit.getPlayer(name); Player player = Bukkit.getPlayer(name);
if (player == null) { if (player == null) {
continue; continue;
} }
if (!player.isFlying()) { if (!player.isFlying()) {
continue; continue;
} }
FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player); FPlayer fPlayer = FPlayers.getInstance().getByPlayer(player);
if (fPlayer == null) { if (fPlayer == null) {
continue; continue;
} }
if (player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR) { if (player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR) {
continue; continue;
} }
Faction myFaction = fPlayer.getFaction(); Faction myFaction = fPlayer.getFaction();
if (myFaction.isWilderness()) { if (myFaction.isWilderness()) {
fPlayer.setFlying(false);
flyMap.remove(name);
continue;
}
if (fPlayer.checkIfNearbyEnemies()) {
continue;
}
FLocation myFloc = new FLocation(player.getLocation());
Faction toFac = Board.getInstance().getFactionAt(myFloc);
if (Board.getInstance().getFactionAt(myFloc) != myFaction) {
if (!checkBypassPerms(fPlayer, player, toFac)) {
fPlayer.setFlying(false); fPlayer.setFlying(false);
flyMap.remove(name); flyMap.remove(name);
continue; continue;
} }
if (fPlayer.checkIfNearbyEnemies()) {
continue;
}
FLocation myFloc = new FLocation(player.getLocation());
Faction toFac = Board.getInstance().getFactionAt(myFloc);
if (Board.getInstance().getFactionAt(myFloc) != myFaction) {
if (!checkBypassPerms(fPlayer, player, toFac)) {
fPlayer.setFlying(false);
flyMap.remove(name);
continue;
}
}
} }
}
} }
} }
@ -139,16 +140,23 @@ public class CmdFly extends FCommand {
return ((player.hasPermission("factions.fly.neutral") || access == Access.ALLOW) && toFac.getRelationTo(fplayer.getFaction()) == Relation.NEUTRAL && !isSystemFaction(toFac)); return ((player.hasPermission("factions.fly.neutral") || access == Access.ALLOW) && toFac.getRelationTo(fplayer.getFaction()) == Relation.NEUTRAL && !isSystemFaction(toFac));
} }
public boolean isInFlightChecker(Player player) {
return flyMap.containsKey(player.getName());
}
public static Boolean isSystemFaction(Faction faction) { public static Boolean isSystemFaction(Faction faction) {
return faction.isSafeZone() || return faction.isSafeZone() ||
faction.isWarZone() || faction.isWarZone() ||
faction.isWilderness(); faction.isWilderness();
} }
public static void checkTaskState() {
if (flyMap.keySet().size() == 0) {
Bukkit.getScheduler().cancelTask(flyid);
flyid = -1;
}
}
public boolean isInFlightChecker(Player player) {
return flyMap.containsKey(player.getName());
}
@Override @Override
public void perform() { public void perform() {
// Disabled by default. // Disabled by default.
@ -159,7 +167,7 @@ public class CmdFly extends FCommand {
FLocation myfloc = new FLocation(me.getLocation()); FLocation myfloc = new FLocation(me.getLocation());
Faction toFac = Board.getInstance().getFactionAt(myfloc); Faction toFac = Board.getInstance().getFactionAt(myfloc);
if (Board.getInstance().getFactionAt(myfloc) != fme.getFaction()){ if (Board.getInstance().getFactionAt(myfloc) != fme.getFaction()) {
if (!me.hasPermission("factions.fly.wilderness") && toFac.isWilderness()) { if (!me.hasPermission("factions.fly.wilderness") && toFac.isWilderness()) {
fme.msg(TL.COMMAND_FLY_NO_ACCESS, Board.getInstance().getFactionAt(myfloc).getTag(fme)); fme.msg(TL.COMMAND_FLY_NO_ACCESS, Board.getInstance().getFactionAt(myfloc).getTag(fme));
return; return;
@ -193,17 +201,13 @@ public class CmdFly extends FCommand {
} }
List<Entity> entities = me.getNearbyEntities(16, 256, 16);
List<Entity> entities = me.getNearbyEntities(16,256,16); for (int i = 0; i <= entities.size() - 1; i++) {
for (int i = 0; i <= entities.size() -1;i++) if (entities.get(i) instanceof Player) {
{
if (entities.get(i) instanceof Player)
{
Player eplayer = (Player) entities.get(i); Player eplayer = (Player) entities.get(i);
FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer);
if (efplayer.getRelationTo(fme) == Relation.ENEMY) if (efplayer.getRelationTo(fme) == Relation.ENEMY) {
{ fme.msg(TL.COMMAND_FLY_CHECK_ENEMY);
fme.msg(TL.COMMAND_FLY_CHECK_ENEMY);
return; return;
} }
} }
@ -213,14 +217,7 @@ public class CmdFly extends FCommand {
if (args.size() == 0) { if (args.size() == 0) {
toggleFlight(!fme.isFlying(), me); toggleFlight(!fme.isFlying(), me);
} else if (args.size() == 1) { } else if (args.size() == 1) {
toggleFlight(argAsBool(0),me); toggleFlight(argAsBool(0), me);
}
}
public static void checkTaskState() {
if (flyMap.keySet().size() == 0) {
Bukkit.getScheduler().cancelTask(flyid);
flyid = -1;
} }
} }
@ -237,13 +234,13 @@ public class CmdFly extends FCommand {
@Override @Override
public void run() { public void run() {
fme.setFlying(true); fme.setFlying(true);
flyMap.put(player.getName(),true); flyMap.put(player.getName(), true);
if (id == -1){ if (id == -1) {
if (P.p.getConfig().getBoolean("ffly.Particles.Enabled")){ if (P.p.getConfig().getBoolean("ffly.Particles.Enabled")) {
startParticles(); startParticles();
} }
} }
if (flyid == -1){ if (flyid == -1) {
startFlyCheck(); startFlyCheck();
} }
} }

View File

@ -13,6 +13,8 @@ import java.util.List;
public class CmdHelp extends FCommand { public class CmdHelp extends FCommand {
public ArrayList<ArrayList<String>> helpPages;
public CmdHelp() { public CmdHelp() {
super(); super();
this.aliases.add("help"); this.aliases.add("help");
@ -32,6 +34,10 @@ public class CmdHelp extends FCommand {
senderMustBeAdmin = false; senderMustBeAdmin = false;
} }
//----------------------------------------------//
// Build the help pages
//----------------------------------------------//
@Override @Override
public void perform() { public void perform() {
if (P.p.getConfig().getBoolean("use-old-help", true)) { if (P.p.getConfig().getBoolean("use-old-help", true)) {
@ -70,12 +76,6 @@ public class CmdHelp extends FCommand {
} }
} }
//----------------------------------------------//
// Build the help pages
//----------------------------------------------//
public ArrayList<ArrayList<String>> helpPages;
public void updateHelp() { public void updateHelp() {
helpPages = new ArrayList<>(); helpPages = new ArrayList<>();
ArrayList<String> pageLines; ArrayList<String> pageLines;

View File

@ -3,9 +3,8 @@ package com.massivecraft.factions.cmd;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
public class CmdInspect extends FCommand public class CmdInspect extends FCommand {
{ public CmdInspect() {
public CmdInspect(){
super(); super();
this.aliases.add("inspect"); this.aliases.add("inspect");
this.aliases.add("ins"); this.aliases.add("ins");
@ -22,8 +21,8 @@ public class CmdInspect extends FCommand
@Override @Override
public void perform(){ public void perform() {
if (fme.isInspectMode()){ if (fme.isInspectMode()) {
fme.setInspectMode(false); fme.setInspectMode(false);
msg(TL.COMMAND_INSPECT_DISABLED_MSG); msg(TL.COMMAND_INSPECT_DISABLED_MSG);
} else { } else {

View File

@ -2,12 +2,11 @@ package com.massivecraft.factions.cmd;
import com.massivecraft.factions.Conf; import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FPlayer; import com.massivecraft.factions.FPlayer;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
public class CmdLowPower extends FCommand { public class CmdLowPower extends FCommand {
public CmdLowPower(){ public CmdLowPower() {
super(); super();
this.aliases.add("lowpower"); this.aliases.add("lowpower");
@ -23,13 +22,13 @@ public class CmdLowPower extends FCommand {
@Override @Override
public void perform(){ public void perform() {
double maxPower = Conf.powerPlayerMax; double maxPower = Conf.powerPlayerMax;
String format = TL.COMMAND_LOWPOWER_FORMAT.toString(); String format = TL.COMMAND_LOWPOWER_FORMAT.toString();
msg(TL.COMMAND_LOWPOWER_HEADER.toString().replace("{maxpower}",(int) maxPower + "")); msg(TL.COMMAND_LOWPOWER_HEADER.toString().replace("{maxpower}", (int) maxPower + ""));
for (FPlayer fPlayer : fme.getFaction().getFPlayers()){ for (FPlayer fPlayer : fme.getFaction().getFPlayers()) {
if (fPlayer.getPower() < maxPower){ if (fPlayer.getPower() < maxPower) {
sendMessage(format.replace("{player}",fPlayer.getName()).replace("{player_power}",(int) fPlayer.getPower() + "").replace("{maxpower}",(int) maxPower + "")); sendMessage(format.replace("{player}", fPlayer.getName()).replace("{player_power}", (int) fPlayer.getPower() + "").replace("{maxpower}", (int) maxPower + ""));
} }
} }
} }

View File

@ -1,6 +1,5 @@
package com.massivecraft.factions.cmd; package com.massivecraft.factions.cmd;
import com.earth2me.essentials.Console;
import com.massivecraft.factions.Faction; import com.massivecraft.factions.Faction;
import com.massivecraft.factions.integration.Econ; import com.massivecraft.factions.integration.Econ;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;

View File

@ -1,7 +1,6 @@
package com.massivecraft.factions.cmd; package com.massivecraft.factions.cmd;
import com.massivecraft.factions.P; import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.struct.Relation; import com.massivecraft.factions.struct.Relation;
import com.massivecraft.factions.struct.Role; import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.Access;

View File

@ -20,17 +20,15 @@ import java.util.List;
public class CmdSeeChunk extends FCommand { public class CmdSeeChunk extends FCommand {
private boolean useParticles;
private int length;
private ParticleEffect effect;
//Used a hashmap cuz imma make a particle selection gui later, will store it where the boolean is rn. //Used a hashmap cuz imma make a particle selection gui later, will store it where the boolean is rn.
public static HashMap<String, Boolean> seeChunkMap = new HashMap<>(); public static HashMap<String, Boolean> seeChunkMap = new HashMap<>();
Long interval = 10L; Long interval = 10L;
private boolean useParticles;
private int length;
private ParticleEffect effect;
private int taskID = -1; private int taskID = -1;
//I remade it cause of people getting mad that I had the same seechunk as drtshock //I remade it cause of people getting mad that I had the same seechunk as drtshock
@ -48,7 +46,7 @@ public class CmdSeeChunk extends FCommand {
this.useParticles = p.getConfig().getBoolean("see-chunk.particles", true); this.useParticles = p.getConfig().getBoolean("see-chunk.particles", true);
interval = P.p.getConfig().getLong("see-chunk.interval", 10L); interval = P.p.getConfig().getLong("see-chunk.interval", 10L);
if (effect == null){ if (effect == null) {
effect = ParticleEffect.REDSTONE; effect = ParticleEffect.REDSTONE;
} }

View File

@ -3,19 +3,12 @@ package com.massivecraft.factions.cmd;
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap; import com.google.common.collect.ListMultimap;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.Faction;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.World;
import java.util.Arrays; public class CmdShowClaims extends FCommand {
import java.util.HashMap;
import java.util.List;
import java.util.Set;
public class CmdShowClaims extends FCommand{ public CmdShowClaims() {
public CmdShowClaims(){
this.aliases.add("showclaims"); this.aliases.add("showclaims");
this.aliases.add("showclaim"); this.aliases.add("showclaim");
@ -31,20 +24,20 @@ public class CmdShowClaims extends FCommand{
} }
@Override @Override
public void perform(){ public void perform() {
sendMessage(TL.COMMAND_SHOWCLAIMS_HEADER.toString().replace("{faction}",fme.getFaction().describeTo(fme))); sendMessage(TL.COMMAND_SHOWCLAIMS_HEADER.toString().replace("{faction}", fme.getFaction().describeTo(fme)));
ListMultimap<String,String> chunkMap = ArrayListMultimap.create(); ListMultimap<String, String> chunkMap = ArrayListMultimap.create();
String format = TL.COMMAND_SHOWCLAIMS_CHUNKSFORMAT.toString(); String format = TL.COMMAND_SHOWCLAIMS_CHUNKSFORMAT.toString();
for (FLocation fLocation : fme.getFaction().getAllClaims()){ for (FLocation fLocation : fme.getFaction().getAllClaims()) {
chunkMap.put(fLocation.getWorldName(),format.replace("{x}",fLocation.getX() + "").replace("{z}",fLocation.getZ() + "")); chunkMap.put(fLocation.getWorldName(), format.replace("{x}", fLocation.getX() + "").replace("{z}", fLocation.getZ() + ""));
} }
for (String world : chunkMap.keySet()){ for (String world : chunkMap.keySet()) {
String message = TL.COMMAND_SHOWCLAIMS_FORMAT.toString().replace("{world}",world); String message = TL.COMMAND_SHOWCLAIMS_FORMAT.toString().replace("{world}", world);
sendMessage(message.replace("{chunks}","")); // made {chunks} blank as I removed the placeholder and people wont update their config :shrug: sendMessage(message.replace("{chunks}", "")); // made {chunks} blank as I removed the placeholder and people wont update their config :shrug:
StringBuilder chunks = new StringBuilder(""); StringBuilder chunks = new StringBuilder("");
for (String chunkString : chunkMap.get(world)){ for (String chunkString : chunkMap.get(world)) {
chunks.append(chunkString + ", "); chunks.append(chunkString + ", ");
if (chunks.toString().length() >= 2000 ) { if (chunks.toString().length() >= 2000) {
sendMessage(chunks.toString()); sendMessage(chunks.toString());
chunks.setLength(0); chunks.setLength(0);
} }
@ -54,10 +47,6 @@ public class CmdShowClaims extends FCommand{
} }
} }
@Override @Override

View File

@ -6,10 +6,8 @@ import com.massivecraft.factions.struct.Role;
import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.Access;
import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Dispenser; import org.bukkit.block.Dispenser;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
@ -18,7 +16,7 @@ import org.bukkit.inventory.PlayerInventory;
public class CmdTntFill extends FCommand { public class CmdTntFill extends FCommand {
public CmdTntFill(){ public CmdTntFill() {
super(); super();
this.aliases.add("tntfill"); this.aliases.add("tntfill");
@ -35,23 +33,22 @@ public class CmdTntFill extends FCommand {
} }
@Override @Override
public void perform(){ public void perform() {
Access access = fme.getFaction().getAccess(fme, PermissableAction.TNTFILL); Access access = fme.getFaction().getAccess(fme, PermissableAction.TNTFILL);
if (access.equals(Access.DENY)) { if (access.equals(Access.DENY)) {
fme.msg(TL.GENERIC_NOPERMISSION, "tntfill"); fme.msg(TL.GENERIC_NOPERMISSION, "tntfill");
} }
msg(TL.COMMAND_TNTFILL_HEADER); msg(TL.COMMAND_TNTFILL_HEADER);
int radius = argAsInt(0,16); int radius = argAsInt(0, 16);
int amount = argAsInt(1,16); int amount = argAsInt(1, 16);
if (radius > P.p.getConfig().getInt("Tntfill.max-radius")){ if (radius > P.p.getConfig().getInt("Tntfill.max-radius")) {
msg(TL.COMMAND_TNTFILL_RADIUSMAX.toString().replace("{max}",P.p.getConfig().getInt("Tntfill.max-radius") + "")); msg(TL.COMMAND_TNTFILL_RADIUSMAX.toString().replace("{max}", P.p.getConfig().getInt("Tntfill.max-radius") + ""));
return; return;
} }
if (amount > P.p.getConfig().getInt("Tntfill.max-amount")){ if (amount > P.p.getConfig().getInt("Tntfill.max-amount")) {
msg(TL.COMMAND_TNTFILL_AMOUNTMAX.toString().replace("{max}",P.p.getConfig().getInt("Tntfill.max-amount") + "")); msg(TL.COMMAND_TNTFILL_AMOUNTMAX.toString().replace("{max}", P.p.getConfig().getInt("Tntfill.max-amount") + ""));
return; return;
} }
int testNumber = -1; int testNumber = -1;
@ -72,61 +69,58 @@ public class CmdTntFill extends FCommand {
for (double y = start.getY() - radius; y <= start.getY() + radius; y++) { for (double y = start.getY() - radius; y <= start.getY() + radius; y++) {
for (double z = start.getZ() - radius; z <= start.getZ() + radius; z++) { for (double z = start.getZ() - radius; z <= start.getZ() + radius; z++) {
Location blockLoc = new Location(start.getWorld(), x, y, z); Location blockLoc = new Location(start.getWorld(), x, y, z);
if (blockLoc.getBlock().getState() instanceof Dispenser){ if (blockLoc.getBlock().getState() instanceof Dispenser) {
Dispenser disp = (Dispenser) blockLoc.getBlock().getState(); Dispenser disp = (Dispenser) blockLoc.getBlock().getState();
Inventory dispenser = disp.getInventory(); Inventory dispenser = disp.getInventory();
if (canHold(dispenser,amount)){ if (canHold(dispenser, amount)) {
int fullStacks = amount / 64; int fullStacks = amount / 64;
int remainderAmt = amount % 64; int remainderAmt = amount % 64;
if (!inventoryContains(me.getInventory(), new ItemStack(Material.TNT,amount))){ if (!inventoryContains(me.getInventory(), new ItemStack(Material.TNT, amount))) {
if (!fme.getRole().isAtLeast(Role.MODERATOR)){ if (!fme.getRole().isAtLeast(Role.MODERATOR)) {
msg(TL.COMMAND_TNTFILL_NOTENOUGH);
sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + ""));
me.updateInventory();
return;
} else if (bankMode) {
//msg(TL.COMMAND_TNTFILL_MOD.toString().replace("{role}",fme.getRole().nicename));
bankMode = true;
removeFromBank(amount);
if (!inventoryContains(me.getInventory(), new ItemStack(Material.TNT, amount))) {
msg(TL.COMMAND_TNTFILL_NOTENOUGH); msg(TL.COMMAND_TNTFILL_NOTENOUGH);
sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}",amount + "").replace("{dispensers}",counter+ "")); sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + ""));
me.updateInventory(); me.updateInventory();
return; return;
} else if (bankMode){
//msg(TL.COMMAND_TNTFILL_MOD.toString().replace("{role}",fme.getRole().nicename));
bankMode = true;
removeFromBank(amount);
if (!inventoryContains(me.getInventory(), new ItemStack(Material.TNT,amount))){
msg(TL.COMMAND_TNTFILL_NOTENOUGH);
sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}",amount + "").replace("{dispensers}",counter+ ""));
me.updateInventory();
return;
}
} }
} }
ItemStack tnt64 = new ItemStack(Material.TNT, 64);
for (int i = 0; i <= fullStacks - 1; i++) {
dispenser.addItem(tnt64);
takeTnt(64);
}
if (remainderAmt != 0) {
ItemStack tnt = new ItemStack(Material.TNT, remainderAmt);
dispenser.addItem(tnt);
takeTnt(remainderAmt);
}
//sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}",amount + "").replace("{x}",(int) x + "").replace("{y}",(int) y + "").replace("{z}",(int) z + ""));
counter++;
} }
ItemStack tnt64 = new ItemStack(Material.TNT, 64);
for (int i = 0; i <= fullStacks - 1; i++) {
dispenser.addItem(tnt64);
takeTnt(64);
}
if (remainderAmt != 0) {
ItemStack tnt = new ItemStack(Material.TNT, remainderAmt);
dispenser.addItem(tnt);
takeTnt(remainderAmt);
}
//sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}",amount + "").replace("{x}",(int) x + "").replace("{y}",(int) y + "").replace("{z}",(int) z + ""));
counter++;
}
} }
} }
} }
} }
if (bankMode) { if (bankMode) {
msg(TL.COMMAND_TNTFILL_MOD.toString().replace("{role}",fme.getRole().nicename)); msg(TL.COMMAND_TNTFILL_MOD.toString().replace("{role}", fme.getRole().nicename));
} }
sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}",amount + "").replace("{dispensers}",counter+ "")); sendMessage(TL.COMMAND_TNTFILL_SUCCESS.toString().replace("{amount}", amount + "").replace("{dispensers}", counter + ""));
me.updateInventory(); me.updateInventory();
} }
private void removeFromBank(int amount){ private void removeFromBank(int amount) {
int testNumber = -1; int testNumber = -1;
try { try {
testNumber = Integer.parseInt(args.get(1)); testNumber = Integer.parseInt(args.get(1));
@ -164,7 +158,7 @@ public class CmdTntFill extends FCommand {
me.updateInventory(); me.updateInventory();
} }
public void takeTnt(int amount){ public void takeTnt(int amount) {
Inventory inv = me.getInventory(); Inventory inv = me.getInventory();
int invTnt = 0; int invTnt = 0;
for (int i = 0; i <= inv.getSize(); i++) { for (int i = 0; i <= inv.getSize(); i++) {
@ -187,7 +181,7 @@ public class CmdTntFill extends FCommand {
removeFromInventory(me.getInventory(), tnt); removeFromInventory(me.getInventory(), tnt);
} }
public boolean canHold(Inventory inventory, int amount){ public boolean canHold(Inventory inventory, int amount) {
int fullStacks = amount / 64; int fullStacks = amount / 64;
int remainderAmt = amount % 64; int remainderAmt = amount % 64;
if ((remainderAmt == 0 && getEmptySlots(me) <= fullStacks)) { if ((remainderAmt == 0 && getEmptySlots(me) <= fullStacks)) {

View File

@ -49,8 +49,8 @@ public class CmdUnclaim extends FCommand {
} }
new SpiralTask(new FLocation(me), radius) { new SpiralTask(new FLocation(me), radius) {
private int failCount = 0;
private final int limit = Conf.radiusClaimFailureLimit - 1; private final int limit = Conf.radiusClaimFailureLimit - 1;
private int failCount = 0;
@Override @Override
public boolean work() { public boolean work() {

View File

@ -1,25 +1,15 @@
package com.massivecraft.factions.cmd; package com.massivecraft.factions.cmd;
import com.drtshock.playervaults.PlayerVaults;
import com.drtshock.playervaults.translations.Lang;
import com.drtshock.playervaults.vaultmanagement.UUIDVaultManager;
import com.drtshock.playervaults.vaultmanagement.VaultOperations;
import com.drtshock.playervaults.vaultmanagement.VaultViewInfo;
import com.massivecraft.factions.Board; import com.massivecraft.factions.Board;
import com.massivecraft.factions.Conf;
import com.massivecraft.factions.FLocation; import com.massivecraft.factions.FLocation;
import com.massivecraft.factions.P; import com.massivecraft.factions.P;
import com.massivecraft.factions.struct.Permission; import com.massivecraft.factions.struct.Permission;
import com.massivecraft.factions.zcore.fperms.Access; import com.massivecraft.factions.zcore.fperms.Access;
import com.massivecraft.factions.zcore.fperms.PermissableAction; import com.massivecraft.factions.zcore.fperms.PermissableAction;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
import org.bukkit.Bukkit;
import org.bukkit.Location; import org.bukkit.Location;
import org.bukkit.Material; import org.bukkit.Material;
import org.bukkit.block.Chest; import org.bukkit.block.Chest;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.inventory.Inventory; import org.bukkit.inventory.Inventory;
public class CmdVault extends FCommand { public class CmdVault extends FCommand {
@ -39,45 +29,44 @@ public class CmdVault extends FCommand {
senderMustBeAdmin = false; senderMustBeAdmin = false;
} }
@Override @Override
public void perform() { public void perform() {
if (!P.p.getConfig().getBoolean("fvault.Enabled")){ if (!P.p.getConfig().getBoolean("fvault.Enabled")) {
fme.sendMessage("This command is disabled!"); fme.sendMessage("This command is disabled!");
return; return;
} }
Access access = fme.getFaction().getAccess(fme, PermissableAction.VAULT); Access access = fme.getFaction().getAccess(fme, PermissableAction.VAULT);
if (access.equals(Access.DENY)) { if (access.equals(Access.DENY)) {
fme.msg(TL.GENERIC_NOPERMISSION, "vault"); fme.msg(TL.GENERIC_NOPERMISSION, "vault");
return; return;
} }
if (fme.isInVault()){ if (fme.isInVault()) {
me.closeInventory(); me.closeInventory();
return; return;
} }
fme.setInVault(true); fme.setInVault(true);
Location vaultLocation = fme.getFaction().getVault(); Location vaultLocation = fme.getFaction().getVault();
if (vaultLocation == null){ if (vaultLocation == null) {
fme.msg(TL.COMMAND_VAULT_INVALID); fme.msg(TL.COMMAND_VAULT_INVALID);
return; return;
} }
FLocation vaultFLocation = new FLocation(vaultLocation); FLocation vaultFLocation = new FLocation(vaultLocation);
if (Board.getInstance().getFactionAt(vaultFLocation) != fme.getFaction()){ if (Board.getInstance().getFactionAt(vaultFLocation) != fme.getFaction()) {
fme.getFaction().setVault(null); fme.getFaction().setVault(null);
fme.msg(TL.COMMAND_VAULT_INVALID); fme.msg(TL.COMMAND_VAULT_INVALID);
return; return;
} }
if (vaultLocation.getBlock().getType() != Material.CHEST){ if (vaultLocation.getBlock().getType() != Material.CHEST) {
fme.getFaction().setVault(null); fme.getFaction().setVault(null);
fme.msg(TL.COMMAND_VAULT_INVALID); fme.msg(TL.COMMAND_VAULT_INVALID);
return; return;
} }
Chest chest = (Chest) vaultLocation.getBlock().getState(); Chest chest = (Chest) vaultLocation.getBlock().getState();
Inventory chestInv = chest.getBlockInventory(); Inventory chestInv = chest.getBlockInventory();
fme.msg(TL.COMMAND_VAULT_OPENING); fme.msg(TL.COMMAND_VAULT_OPENING);
me.openInventory(chestInv); me.openInventory(chestInv);
} }

View File

@ -213,7 +213,7 @@ public class FCmdRoot extends FCommand {
this.addSubCommand(this.cmdSetBanner); this.addSubCommand(this.cmdSetBanner);
if (Bukkit.getServer().getPluginManager().getPlugin("CoreProtect") != null){ if (Bukkit.getServer().getPluginManager().getPlugin("CoreProtect") != null) {
P.p.log("Found CoreProtect, enabling Inspect"); P.p.log("Found CoreProtect, enabling Inspect");
this.addSubCommand(this.cmdInspect); this.addSubCommand(this.cmdInspect);
} else { } else {
@ -231,10 +231,10 @@ public class FCmdRoot extends FCommand {
} }
if (P.p.isHookedPlayervaults()) { if (P.p.isHookedPlayervaults()) {
P.p.log("Found playervaults hook, adding /f vault and /f setmaxvault commands."); P.p.log("Found playervaults hook, adding /f vault and /f setmaxvault commands.");
// this.addSubCommand(new CmdSetMaxVaults()); // this.addSubCommand(new CmdSetMaxVaults());
// this.addSubCommand(new CmdVault()); // this.addSubCommand(new CmdVault());
}else{ } else {
// this.addSubCommand(new CmdVault()); // this.addSubCommand(new CmdVault());
} }
} }

View File

@ -100,7 +100,7 @@ public abstract class FCommand extends MCommand<P> {
return false; return false;
} }
if (this.senderMustBeColeader && !fme.getRole().isAtLeast(Role.COLEADER)){ if (this.senderMustBeColeader && !fme.getRole().isAtLeast(Role.COLEADER)) {
sender.sendMessage(p.txt.parse("<b>Only faction coleaders can %s.", this.getHelpShort())); sender.sendMessage(p.txt.parse("<b>Only faction coleaders can %s.", this.getHelpShort()));
return false; return false;
} }
@ -111,7 +111,6 @@ public abstract class FCommand extends MCommand<P> {
} }
return true; return true;
} }
@ -266,14 +265,11 @@ public abstract class FCommand extends MCommand<P> {
return true; return true;
} }
if (you.getRole().equals(Role.ADMIN)) if (you.getRole().equals(Role.ADMIN)) {
{
i.sendMessage(p.txt.parse("<b>Only the faction admin can do that.")); i.sendMessage(p.txt.parse("<b>Only the faction admin can do that."));
} } else if ((you.getRole().equals(Role.COLEADER))) {
else if ((you.getRole().equals(Role.COLEADER))) if (i == you) {
{
if (i == you){
return true; return true;
} else { } else {
i.sendMessage(p.txt.parse("<b>Coleaders can't control each other...")); i.sendMessage(p.txt.parse("<b>Coleaders can't control each other..."));

View File

@ -12,10 +12,6 @@ public class FPlayerJoinEvent extends FactionPlayerEvent implements Cancellable
PlayerJoinReason reason; PlayerJoinReason reason;
boolean cancelled = false; boolean cancelled = false;
public enum PlayerJoinReason {
CREATE, LEADER, COMMAND
}
public FPlayerJoinEvent(FPlayer fp, Faction f, PlayerJoinReason r) { public FPlayerJoinEvent(FPlayer fp, Faction f, PlayerJoinReason r) {
super(f, fp); super(f, fp);
reason = r; reason = r;
@ -39,4 +35,8 @@ public class FPlayerJoinEvent extends FactionPlayerEvent implements Cancellable
public void setCancelled(boolean c) { public void setCancelled(boolean c) {
cancelled = c; cancelled = c;
} }
public enum PlayerJoinReason {
CREATE, LEADER, COMMAND
}
} }

View File

@ -6,12 +6,8 @@ import org.bukkit.event.Cancellable;
public class FPlayerLeaveEvent extends FactionPlayerEvent implements Cancellable { public class FPlayerLeaveEvent extends FactionPlayerEvent implements Cancellable {
private PlayerLeaveReason reason;
boolean cancelled = false; boolean cancelled = false;
private PlayerLeaveReason reason;
public enum PlayerLeaveReason {
KICKED, DISBAND, RESET, JOINOTHER, LEAVE, BANNED
}
public FPlayerLeaveEvent(FPlayer p, Faction f, PlayerLeaveReason r) { public FPlayerLeaveEvent(FPlayer p, Faction f, PlayerLeaveReason r) {
super(f, p); super(f, p);
@ -37,4 +33,8 @@ public class FPlayerLeaveEvent extends FactionPlayerEvent implements Cancellable
// Don't let them cancel factions disbanding. // Don't let them cancel factions disbanding.
cancelled = reason != PlayerLeaveReason.DISBAND && reason != PlayerLeaveReason.RESET && c; cancelled = reason != PlayerLeaveReason.DISBAND && reason != PlayerLeaveReason.RESET && c;
} }
public enum PlayerLeaveReason {
KICKED, DISBAND, RESET, JOINOTHER, LEAVE, BANNED
}
} }

View File

@ -24,6 +24,10 @@ public class FactionCreateEvent extends Event implements Cancellable {
this.cancelled = false; this.cancelled = false;
} }
public static HandlerList getHandlerList() {
return handlers;
}
public FPlayer getFPlayer() { public FPlayer getFPlayer() {
return FPlayers.getInstance().getByPlayer(sender); return FPlayers.getInstance().getByPlayer(sender);
} }
@ -36,10 +40,6 @@ public class FactionCreateEvent extends Event implements Cancellable {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() {
return handlers;
}
@Override @Override
public boolean isCancelled() { public boolean isCancelled() {
return cancelled; return cancelled;

View File

@ -16,6 +16,10 @@ public class FactionEvent extends Event {
this.faction = faction; this.faction = faction;
} }
public static HandlerList getHandlerList() {
return handlers;
}
/** /**
* Get the Faction involved in the event. * Get the Faction involved in the event.
* *
@ -29,8 +33,4 @@ public class FactionEvent extends Event {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() {
return handlers;
}
} }

View File

@ -24,11 +24,11 @@ public class FactionRelationEvent extends Event {
frel = rel; frel = rel;
} }
public HandlerList getHandlers() { public static HandlerList getHandlerList() {
return handlers; return handlers;
} }
public static HandlerList getHandlerList() { public HandlerList getHandlers() {
return handlers; return handlers;
} }

View File

@ -23,6 +23,7 @@ import java.util.logging.Level;
public class Econ { public class Econ {
private static final DecimalFormat format = new DecimalFormat(TL.ECON_FORMAT.toString());
private static Economy econ = null; private static Economy econ = null;
public static void setup() { public static void setup() {
@ -61,7 +62,6 @@ public class Econ {
return econ != null; return econ != null;
} }
public static void modifyUniverseMoney(double delta) { public static void modifyUniverseMoney(double delta) {
if (!shouldBeUsed()) { if (!shouldBeUsed()) {
return; return;
@ -369,16 +369,16 @@ public class Econ {
return amount; return amount;
} }
// calculate refund amount for all owned land
public static double calculateTotalLandRefund(int ownedLand) {
return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier;
}
// -------------------------------------------- // // -------------------------------------------- //
// Standard account management methods // Standard account management methods
// -------------------------------------------- // // -------------------------------------------- //
// calculate refund amount for all owned land
public static double calculateTotalLandRefund(int ownedLand) {
return calculateTotalLandValue(ownedLand) * Conf.econClaimRefundMultiplier;
}
public static boolean hasAccount(String name) { public static boolean hasAccount(String name) {
return econ.hasAccount(name); return econ.hasAccount(name);
} }
@ -387,8 +387,6 @@ public class Econ {
return econ.getBalance(account); return econ.getBalance(account);
} }
private static final DecimalFormat format = new DecimalFormat(TL.ECON_FORMAT.toString());
public static String getFriendlyBalance(UUID uuid) { public static String getFriendlyBalance(UUID uuid) {
OfflinePlayer offline = Bukkit.getOfflinePlayer(uuid); OfflinePlayer offline = Bukkit.getOfflinePlayer(uuid);
if (offline.getName() == null) { if (offline.getName() == null) {

View File

@ -8,89 +8,16 @@ public class DynmapStyle {
// -------------------------------------------- // // -------------------------------------------- //
public String lineColor = null; public String lineColor = null;
public int getLineColor() {
return getColor(coalesce(this.lineColor, Conf.dynmapDefaultStyle.lineColor, Conf.DYNMAP_STYLE_LINE_COLOR));
}
public DynmapStyle setStrokeColor(String strokeColor) {
this.lineColor = strokeColor;
return this;
}
public Double lineOpacity = null; public Double lineOpacity = null;
public double getLineOpacity() {
return coalesce(this.lineOpacity, Conf.dynmapDefaultStyle.lineOpacity, Conf.DYNMAP_STYLE_LINE_OPACITY);
}
public DynmapStyle setLineOpacity(Double strokeOpacity) {
this.lineOpacity = strokeOpacity;
return this;
}
public Integer lineWeight = null; public Integer lineWeight = null;
public int getLineWeight() {
return coalesce(this.lineWeight, Conf.dynmapDefaultStyle.lineWeight, Conf.DYNMAP_STYLE_LINE_WEIGHT);
}
public DynmapStyle setLineWeight(Integer strokeWeight) {
this.lineWeight = strokeWeight;
return this;
}
public String fillColor = null; public String fillColor = null;
public int getFillColor() {
return getColor(coalesce(this.fillColor, Conf.dynmapDefaultStyle.fillColor, Conf.DYNMAP_STYLE_FILL_COLOR));
}
public DynmapStyle setFillColor(String fillColor) {
this.fillColor = fillColor;
return this;
}
public Double fillOpacity = null; public Double fillOpacity = null;
public double getFillOpacity() {
return coalesce(this.fillOpacity, Conf.dynmapDefaultStyle.fillOpacity, Conf.DYNMAP_STYLE_FILL_OPACITY);
}
public DynmapStyle setFillOpacity(Double fillOpacity) {
this.fillOpacity = fillOpacity;
return this;
}
// NOTE: We just return the string here. We do not return the resolved Dynmap MarkerIcon object. // NOTE: We just return the string here. We do not return the resolved Dynmap MarkerIcon object.
// The reason is we use this class in the MConf. For serialization to work Dynmap would have to be loaded and we can't require that. // The reason is we use this class in the MConf. For serialization to work Dynmap would have to be loaded and we can't require that.
// Using dynmap is optional. // Using dynmap is optional.
public String homeMarker = null; public String homeMarker = null;
public String getHomeMarker() {
return coalesce(this.homeMarker, Conf.dynmapDefaultStyle.homeMarker, Conf.DYNMAP_STYLE_HOME_MARKER);
}
public DynmapStyle setHomeMarker(String homeMarker) {
this.homeMarker = homeMarker;
return this;
}
public Boolean boost = null; public Boolean boost = null;
public boolean getBoost() {
return coalesce(this.boost, Conf.dynmapDefaultStyle.boost, Conf.DYNMAP_STYLE_BOOST);
}
public DynmapStyle setBoost(Boolean boost) {
this.boost = boost;
return this;
}
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
@SafeVarargs @SafeVarargs
public static <T> T coalesce(T... items) { public static <T> T coalesce(T... items) {
for (T item : items) { for (T item : items) {
@ -110,4 +37,71 @@ public class DynmapStyle {
return ret; return ret;
} }
public int getLineColor() {
return getColor(coalesce(this.lineColor, Conf.dynmapDefaultStyle.lineColor, Conf.DYNMAP_STYLE_LINE_COLOR));
}
public DynmapStyle setStrokeColor(String strokeColor) {
this.lineColor = strokeColor;
return this;
}
public double getLineOpacity() {
return coalesce(this.lineOpacity, Conf.dynmapDefaultStyle.lineOpacity, Conf.DYNMAP_STYLE_LINE_OPACITY);
}
public DynmapStyle setLineOpacity(Double strokeOpacity) {
this.lineOpacity = strokeOpacity;
return this;
}
public int getLineWeight() {
return coalesce(this.lineWeight, Conf.dynmapDefaultStyle.lineWeight, Conf.DYNMAP_STYLE_LINE_WEIGHT);
}
public DynmapStyle setLineWeight(Integer strokeWeight) {
this.lineWeight = strokeWeight;
return this;
}
public int getFillColor() {
return getColor(coalesce(this.fillColor, Conf.dynmapDefaultStyle.fillColor, Conf.DYNMAP_STYLE_FILL_COLOR));
}
public DynmapStyle setFillColor(String fillColor) {
this.fillColor = fillColor;
return this;
}
public double getFillOpacity() {
return coalesce(this.fillOpacity, Conf.dynmapDefaultStyle.fillOpacity, Conf.DYNMAP_STYLE_FILL_OPACITY);
}
public DynmapStyle setFillOpacity(Double fillOpacity) {
this.fillOpacity = fillOpacity;
return this;
}
public String getHomeMarker() {
return coalesce(this.homeMarker, Conf.dynmapDefaultStyle.homeMarker, Conf.DYNMAP_STYLE_HOME_MARKER);
}
public DynmapStyle setHomeMarker(String homeMarker) {
this.homeMarker = homeMarker;
return this;
}
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
public boolean getBoost() {
return coalesce(this.boost, Conf.dynmapDefaultStyle.boost, Conf.DYNMAP_STYLE_BOOST);
}
public DynmapStyle setBoost(Boolean boost) {
this.boost = boost;
return this;
}
} }

View File

@ -41,17 +41,64 @@ public class EngineDynmap {
// -------------------------------------------- // // -------------------------------------------- //
private static EngineDynmap i = new EngineDynmap(); private static EngineDynmap i = new EngineDynmap();
public DynmapAPI dynmapApi;
public MarkerAPI markerApi;
public MarkerSet markerset;
private EngineDynmap() {
}
public static EngineDynmap getInstance() { public static EngineDynmap getInstance() {
return i; return i;
} }
private EngineDynmap() { public static String getHtmlPlayerString(Collection<FPlayer> playersOfficersList) {
StringBuilder ret = new StringBuilder();
for (FPlayer fplayer : playersOfficersList) {
if (ret.length() > 0) {
ret.append(", ");
}
ret.append(getHtmlPlayerName(fplayer));
}
return ret.toString();
} }
public DynmapAPI dynmapApi; public static String getHtmlPlayerName(FPlayer fplayer) {
public MarkerAPI markerApi; if (fplayer == null) {
public MarkerSet markerset; return "none";
}
return escapeHtml(fplayer.getName());
}
public static String escapeHtml(String string) {
StringBuilder out = new StringBuilder(Math.max(16, string.length()));
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
out.append("&#");
out.append((int) c);
out.append(';');
} else {
out.append(c);
}
}
return out.toString();
}
// Thread Safe / Asynchronous: Yes
public static void info(String msg) {
String message = DYNMAP_INTEGRATION + msg;
System.out.println(message);
}
// -------------------------------------------- //
// UPDATE: HOMES
// -------------------------------------------- //
// Thread Safe / Asynchronous: Yes
public static void severe(String msg) {
String message = DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg;
System.out.println(message);
}
public void init() { public void init() {
Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap"); Plugin dynmap = Bukkit.getServer().getPluginManager().getPlugin("dynmap");
@ -94,6 +141,10 @@ public class EngineDynmap {
}, 100L, 100L); }, 100L, 100L);
} }
// -------------------------------------------- //
// UPDATE: AREAS
// -------------------------------------------- //
// Thread Safe / Asynchronous: No // Thread Safe / Asynchronous: No
public boolean updateCore() { public boolean updateCore() {
// Get DynmapAPI // Get DynmapAPI
@ -138,10 +189,6 @@ public class EngineDynmap {
return true; return true;
} }
// -------------------------------------------- //
// UPDATE: HOMES
// -------------------------------------------- //
// Thread Safe / Asynchronous: Yes // Thread Safe / Asynchronous: Yes
public Map<String, TempMarker> createHomes() { public Map<String, TempMarker> createHomes() {
Map<String, TempMarker> ret = new HashMap<>(); Map<String, TempMarker> ret = new HashMap<>();
@ -208,7 +255,7 @@ public class EngineDynmap {
} }
// -------------------------------------------- // // -------------------------------------------- //
// UPDATE: AREAS // UPDATE: PLAYERSET
// -------------------------------------------- // // -------------------------------------------- //
// Thread Safe: YES // Thread Safe: YES
@ -449,6 +496,10 @@ public class EngineDynmap {
return ret; return ret;
} }
// -------------------------------------------- //
// UTIL & SHARED
// -------------------------------------------- //
// Thread Safe: NO // Thread Safe: NO
public void updateAreas(Map<String, TempAreaMarker> areas) { public void updateAreas(Map<String, TempAreaMarker> areas) {
// Map Current // Map Current
@ -482,10 +533,6 @@ public class EngineDynmap {
} }
} }
// -------------------------------------------- //
// UPDATE: PLAYERSET
// -------------------------------------------- //
// Thread Safe / Asynchronous: Yes // Thread Safe / Asynchronous: Yes
public String createPlayersetId(Faction faction) { public String createPlayersetId(Faction faction) {
if (faction == null) { if (faction == null) {
@ -589,10 +636,6 @@ public class EngineDynmap {
} }
} }
// -------------------------------------------- //
// UTIL & SHARED
// -------------------------------------------- //
// Thread Safe / Asynchronous: Yes // Thread Safe / Asynchronous: Yes
private String getDescription(Faction faction) { private String getDescription(Faction faction) {
String ret = "<div class=\"regioninfo\">" + Conf.dynmapDescription + "</div>"; String ret = "<div class=\"regioninfo\">" + Conf.dynmapDescription + "</div>";
@ -653,39 +696,6 @@ public class EngineDynmap {
return ret; return ret;
} }
public static String getHtmlPlayerString(Collection<FPlayer> playersOfficersList) {
StringBuilder ret = new StringBuilder();
for (FPlayer fplayer : playersOfficersList) {
if (ret.length() > 0) {
ret.append(", ");
}
ret.append(getHtmlPlayerName(fplayer));
}
return ret.toString();
}
public static String getHtmlPlayerName(FPlayer fplayer) {
if (fplayer == null) {
return "none";
}
return escapeHtml(fplayer.getName());
}
public static String escapeHtml(String string) {
StringBuilder out = new StringBuilder(Math.max(16, string.length()));
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (c > 127 || c == '"' || c == '<' || c == '>' || c == '&') {
out.append("&#");
out.append((int) c);
out.append(';');
} else {
out.append(c);
}
}
return out.toString();
}
// Thread Safe / Asynchronous: Yes // Thread Safe / Asynchronous: Yes
private boolean isVisible(Faction faction, String world) { private boolean isVisible(Faction faction, String world) {
if (faction == null) { if (faction == null) {
@ -727,22 +737,6 @@ public class EngineDynmap {
return Conf.dynmapDefaultStyle; return Conf.dynmapDefaultStyle;
} }
// Thread Safe / Asynchronous: Yes
public static void info(String msg) {
String message = DYNMAP_INTEGRATION + msg;
System.out.println(message);
}
// Thread Safe / Asynchronous: Yes
public static void severe(String msg) {
String message = DYNMAP_INTEGRATION + ChatColor.RED.toString() + msg;
System.out.println(message);
}
enum Direction {
XPLUS, ZPLUS, XMINUS, ZMINUS
}
// Find all contiguous blocks, set in target and clear in source // Find all contiguous blocks, set in target and clear in source
private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) { private int floodFillTarget(TileFlags source, TileFlags destination, int x, int y) {
int cnt = 0; int cnt = 0;
@ -773,4 +767,8 @@ public class EngineDynmap {
} }
return cnt; return cnt;
} }
enum Direction {
XPLUS, ZPLUS, XMINUS, ZMINUS
}
} }

View File

@ -27,6 +27,32 @@ public class TempAreaMarker {
// CREATE // CREATE
// -------------------------------------------- // // -------------------------------------------- //
public static boolean equals(AreaMarker marker, double x[], double z[]) {
int length = marker.getCornerCount();
if (x.length != length) {
return false;
}
if (z.length != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (marker.getCornerX(i) != x[i]) {
return false;
}
if (marker.getCornerZ(i) != z[i]) {
return false;
}
}
return true;
}
// -------------------------------------------- //
// UPDATE
// -------------------------------------------- //
public AreaMarker create(MarkerSet markerset, String markerId) { public AreaMarker create(MarkerSet markerset, String markerId) {
AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent AreaMarker ret = markerset.createAreaMarker(markerId, this.label, false, this.world, this.x, this.z, false // not persistent
); );
@ -51,7 +77,7 @@ public class TempAreaMarker {
} }
// -------------------------------------------- // // -------------------------------------------- //
// UPDATE // UTIL
// -------------------------------------------- // // -------------------------------------------- //
public void update(AreaMarker marker) { public void update(AreaMarker marker) {
@ -87,30 +113,4 @@ public class TempAreaMarker {
} }
} }
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
public static boolean equals(AreaMarker marker, double x[], double z[]) {
int length = marker.getCornerCount();
if (x.length != length) {
return false;
}
if (z.length != length) {
return false;
}
for (int i = 0; i < length; i++) {
if (marker.getCornerX(i) != x[i]) {
return false;
}
if (marker.getCornerZ(i) != z[i]) {
return false;
}
}
return true;
}
} }

View File

@ -23,6 +23,18 @@ public class TempMarker {
// CREATE // CREATE
// -------------------------------------------- // // -------------------------------------------- //
public static MarkerIcon getMarkerIcon(MarkerAPI markerApi, String name) {
MarkerIcon ret = markerApi.getMarkerIcon(name);
if (ret == null) {
ret = markerApi.getMarkerIcon(Conf.DYNMAP_STYLE_HOME_MARKER);
}
return ret;
}
// -------------------------------------------- //
// UPDATE
// -------------------------------------------- //
public Marker create(MarkerAPI markerApi, MarkerSet markerset, String markerId) { public Marker create(MarkerAPI markerApi, MarkerSet markerset, String markerId) {
Marker ret = markerset.createMarker(markerId, this.label, this.world, this.x, this.y, this.z, getMarkerIcon(markerApi, this.iconName), false // not persistent Marker ret = markerset.createMarker(markerId, this.label, this.world, this.x, this.y, this.z, getMarkerIcon(markerApi, this.iconName), false // not persistent
); );
@ -37,7 +49,7 @@ public class TempMarker {
} }
// -------------------------------------------- // // -------------------------------------------- //
// UPDATE // UTIL
// -------------------------------------------- // // -------------------------------------------- //
public void update(MarkerAPI markerApi, Marker marker) { public void update(MarkerAPI markerApi, Marker marker) {
@ -59,16 +71,4 @@ public class TempMarker {
} }
} }
// -------------------------------------------- //
// UTIL
// -------------------------------------------- //
public static MarkerIcon getMarkerIcon(MarkerAPI markerApi, String name) {
MarkerIcon ret = markerApi.getMarkerIcon(name);
if (ret == null) {
ret = markerApi.getMarkerIcon(Conf.DYNMAP_STYLE_HOME_MARKER);
}
return ret;
}
} }

View File

@ -26,6 +26,123 @@ public class FactionsBlockListener implements Listener {
this.p = p; this.p = p;
} }
public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) {
String name = player.getName();
if (Conf.playersWhoBypassAllProtection.contains(name)) {
return true;
}
FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString());
if (me.isAdminBypassing()) {
return true;
}
FLocation loc = new FLocation(location);
Faction otherFaction = Board.getInstance().getFactionAt(loc);
if (otherFaction.isWilderness()) {
if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) {
return true;
}
if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) {
return true; // This is not faction territory. Use whatever you like here.
}
if (!justCheck) {
me.msg("<b>You can't " + action + " in the wilderness.");
}
return false;
} else if (otherFaction.isSafeZone()) {
if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) {
return true;
}
if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) {
return true;
}
if (!justCheck) {
me.msg("<b>You can't " + action + " in a safe zone.");
}
return false;
} else if (otherFaction.isWarZone()) {
if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) {
return true;
}
if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) {
return true;
}
if (!justCheck) {
me.msg("<b>You can't " + action + " in a war zone.");
}
return false;
}
if (P.p.getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() >= otherFaction.getPowerRounded()) {
return true;
}
Faction myFaction = me.getFaction();
Relation rel = myFaction.getRelationTo(otherFaction);
boolean online = otherFaction.hasPlayersOnline();
boolean pain = !justCheck && rel.confPainBuild(online);
boolean deny = rel.confDenyBuild(online);
// hurt the player for building/destroying in other territory?
if (pain) {
player.damage(Conf.actionDeniedPainAmount);
if (!deny) {
me.msg("<b>It is painful to try to " + action + " in the territory of " + otherFaction.getTag(myFaction));
}
}
Access access = otherFaction.getAccess(me, PermissableAction.fromString(action));
if (access != null && access != Access.UNDEFINED) {
// TODO: Update this once new access values are added other than just allow / deny.
if (access == Access.DENY) {
me.msg(TL.GENERIC_NOPERMISSION, action);
return false;
}
return true; // has to be allow
}
// cancel building/destroying in other territory?
if (deny) {
if (!justCheck) {
me.msg("<b>You can't " + action + " in the territory of " + otherFaction.getTag(myFaction));
}
return false;
}
// Also cancel and/or cause pain if player doesn't have ownership rights for this claim
if (Conf.ownedAreasEnabled && (Conf.ownedAreaDenyBuild || Conf.ownedAreaPainBuild) && !otherFaction.playerHasOwnershipRights(me, loc)) {
if (!pain && Conf.ownedAreaPainBuild && !justCheck) {
player.damage(Conf.actionDeniedPainAmount);
if (!Conf.ownedAreaDenyBuild) {
me.msg("<b>It is painful to try to " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc));
}
}
if (Conf.ownedAreaDenyBuild) {
if (!justCheck) {
me.msg("<b>You can't " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc));
}
return false;
}
}
return true;
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) { public void onBlockPlace(BlockPlaceEvent event) {
if (!event.canBuild()) { if (!event.canBuild()) {
@ -189,121 +306,4 @@ public class FactionsBlockListener implements Listener {
return !rel.confDenyBuild(otherFaction.hasPlayersOnline()); return !rel.confDenyBuild(otherFaction.hasPlayersOnline());
} }
public static boolean playerCanBuildDestroyBlock(Player player, Location location, String action, boolean justCheck) {
String name = player.getName();
if (Conf.playersWhoBypassAllProtection.contains(name)) {
return true;
}
FPlayer me = FPlayers.getInstance().getById(player.getUniqueId().toString());
if (me.isAdminBypassing()) {
return true;
}
FLocation loc = new FLocation(location);
Faction otherFaction = Board.getInstance().getFactionAt(loc);
if (otherFaction.isWilderness()) {
if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) {
return true;
}
if (!Conf.wildernessDenyBuild || Conf.worldsNoWildernessProtection.contains(location.getWorld().getName())) {
return true; // This is not faction territory. Use whatever you like here.
}
if (!justCheck) {
me.msg("<b>You can't " + action + " in the wilderness.");
}
return false;
} else if (otherFaction.isSafeZone()) {
if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) {
return true;
}
if (!Conf.safeZoneDenyBuild || Permission.MANAGE_SAFE_ZONE.has(player)) {
return true;
}
if (!justCheck) {
me.msg("<b>You can't " + action + " in a safe zone.");
}
return false;
} else if (otherFaction.isWarZone()) {
if (Conf.worldGuardBuildPriority && Worldguard.playerCanBuild(player, location)) {
return true;
}
if (!Conf.warZoneDenyBuild || Permission.MANAGE_WAR_ZONE.has(player)) {
return true;
}
if (!justCheck) {
me.msg("<b>You can't " + action + " in a war zone.");
}
return false;
}
if (P.p.getConfig().getBoolean("hcf.raidable", false) && otherFaction.getLandRounded() >= otherFaction.getPowerRounded()) {
return true;
}
Faction myFaction = me.getFaction();
Relation rel = myFaction.getRelationTo(otherFaction);
boolean online = otherFaction.hasPlayersOnline();
boolean pain = !justCheck && rel.confPainBuild(online);
boolean deny = rel.confDenyBuild(online);
// hurt the player for building/destroying in other territory?
if (pain) {
player.damage(Conf.actionDeniedPainAmount);
if (!deny) {
me.msg("<b>It is painful to try to " + action + " in the territory of " + otherFaction.getTag(myFaction));
}
}
Access access = otherFaction.getAccess(me, PermissableAction.fromString(action));
if (access != null && access != Access.UNDEFINED) {
// TODO: Update this once new access values are added other than just allow / deny.
if (access == Access.DENY) {
me.msg(TL.GENERIC_NOPERMISSION, action);
return false;
}
return true; // has to be allow
}
// cancel building/destroying in other territory?
if (deny) {
if (!justCheck) {
me.msg("<b>You can't " + action + " in the territory of " + otherFaction.getTag(myFaction));
}
return false;
}
// Also cancel and/or cause pain if player doesn't have ownership rights for this claim
if (Conf.ownedAreasEnabled && (Conf.ownedAreaDenyBuild || Conf.ownedAreaPainBuild) && !otherFaction.playerHasOwnershipRights(me, loc)) {
if (!pain && Conf.ownedAreaPainBuild && !justCheck) {
player.damage(Conf.actionDeniedPainAmount);
if (!Conf.ownedAreaDenyBuild) {
me.msg("<b>It is painful to try to " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc));
}
}
if (Conf.ownedAreaDenyBuild) {
if (!justCheck) {
me.msg("<b>You can't " + action + " in this territory, it is owned by: " + otherFaction.getOwnerListString(loc));
}
return false;
}
}
return true;
}
} }

View File

@ -29,6 +29,7 @@ import java.util.*;
public class FactionsEntityListener implements Listener { public class FactionsEntityListener implements Listener {
private static final Set<PotionEffectType> badPotionEffects = new LinkedHashSet<>(Arrays.asList(PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER, PotionEffectType.POISON, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS, PotionEffectType.WITHER));
public P p; public P p;
public FactionsEntityListener(P p) { public FactionsEntityListener(P p) {
@ -142,7 +143,7 @@ public class FactionsEntityListener implements Listener {
cancelFStuckTeleport((Player) damagee); cancelFStuckTeleport((Player) damagee);
cancelFFly((Player) damagee); cancelFFly((Player) damagee);
FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) damagee); FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) damagee);
if (fplayer.isInspectMode()){ if (fplayer.isInspectMode()) {
fplayer.setInspectMode(false); fplayer.setInspectMode(false);
fplayer.msg(TL.COMMAND_INSPECT_DISABLED_MSG); fplayer.msg(TL.COMMAND_INSPECT_DISABLED_MSG);
} }
@ -151,7 +152,7 @@ public class FactionsEntityListener implements Listener {
cancelFStuckTeleport((Player) damager); cancelFStuckTeleport((Player) damager);
cancelFFly((Player) damager); cancelFFly((Player) damager);
FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) damager); FPlayer fplayer = FPlayers.getInstance().getByPlayer((Player) damager);
if (fplayer.isInspectMode()){ if (fplayer.isInspectMode()) {
fplayer.setInspectMode(false); fplayer.setInspectMode(false);
fplayer.msg(TL.COMMAND_INSPECT_DISABLED_MSG); fplayer.msg(TL.COMMAND_INSPECT_DISABLED_MSG);
} }
@ -288,7 +289,6 @@ public class FactionsEntityListener implements Listener {
// No condition retained, destroy the block! // No condition retained, destroy the block!
} }
// mainly for flaming arrows; don't want allies or people in safe zones to be ignited even after damage event is cancelled // mainly for flaming arrows; don't want allies or people in safe zones to be ignited even after damage event is cancelled
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onEntityCombustByEntity(EntityCombustByEntityEvent event) { public void onEntityCombustByEntity(EntityCombustByEntityEvent event) {
@ -298,8 +298,6 @@ public class FactionsEntityListener implements Listener {
} }
} }
private static final Set<PotionEffectType> badPotionEffects = new LinkedHashSet<>(Arrays.asList(PotionEffectType.BLINDNESS, PotionEffectType.CONFUSION, PotionEffectType.HARM, PotionEffectType.HUNGER, PotionEffectType.POISON, PotionEffectType.SLOW, PotionEffectType.SLOW_DIGGING, PotionEffectType.WEAKNESS, PotionEffectType.WITHER));
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onPotionSplashEvent(PotionSplashEvent event) { public void onPotionSplashEvent(PotionSplashEvent event) {
// see if the potion has a harmful effect // see if the potion has a harmful effect
@ -659,9 +657,9 @@ public class FactionsEntityListener implements Listener {
} }
@EventHandler @EventHandler
public void onBowHit(EntityDamageByEntityEvent e){ public void onBowHit(EntityDamageByEntityEvent e) {
if (e.getDamager() instanceof Projectile){ if (e.getDamager() instanceof Projectile) {
if (e.getEntity() instanceof Player){ if (e.getEntity() instanceof Player) {
Projectile arrow = ((Projectile) e.getDamager()); Projectile arrow = ((Projectile) e.getDamager());
if (arrow.getShooter() instanceof Player) { if (arrow.getShooter() instanceof Player) {
Player damager = (Player) ((Projectile) e.getDamager()).getShooter(); Player damager = (Player) ((Projectile) e.getDamager()).getShooter();

View File

@ -13,6 +13,10 @@ import org.bukkit.event.player.PlayerTeleportEvent;
public class FactionsExploitListener implements Listener { public class FactionsExploitListener implements Listener {
public static boolean clippingThrough(Location target, Location from, double thickness) {
return ((from.getX() > target.getX() && (from.getX() - target.getX() < thickness)) || (target.getX() > from.getX() && (target.getX() - from.getX() < thickness)) || (from.getZ() > target.getZ() && (from.getZ() - target.getZ() < thickness)) || (target.getZ() > from.getZ() && (target.getZ() - from.getZ() < thickness)));
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void obsidianGenerator(BlockFromToEvent event) { public void obsidianGenerator(BlockFromToEvent event) {
if (!Conf.handleExploitObsidianGenerators) { if (!Conf.handleExploitObsidianGenerators) {
@ -54,8 +58,4 @@ public class FactionsExploitListener implements Listener {
event.setTo(target); event.setTo(target);
} }
public static boolean clippingThrough(Location target, Location from, double thickness) {
return ((from.getX() > target.getX() && (from.getX() - target.getX() < thickness)) || (target.getX() > from.getX() && (target.getX() - from.getX() < thickness)) || (from.getZ() > target.getZ() && (from.getZ() - target.getZ() < thickness)) || (target.getZ() > from.getZ() && (target.getZ() - from.getZ() < thickness)));
}
} }

View File

@ -14,20 +14,6 @@ public class BufferedObjective {
private static final Method addEntryMethod; private static final Method addEntryMethod;
private static final int MAX_LINE_LENGTH; private static final int MAX_LINE_LENGTH;
private final Scoreboard scoreboard;
private final String baseName;
private Objective current;
private List<Team> currentTeams = new ArrayList<>();
private String title;
private DisplaySlot displaySlot;
private int objPtr;
private int teamPtr;
private boolean requiresUpdate = false;
private final Map<Integer, String> contents = new HashMap<>();
static { static {
// Check for long line support. // Check for long line support.
// We require use of Spigot's `addEntry(String)` method on // We require use of Spigot's `addEntry(String)` method on
@ -48,6 +34,17 @@ public class BufferedObjective {
} }
} }
private final Scoreboard scoreboard;
private final String baseName;
private final Map<Integer, String> contents = new HashMap<>();
private Objective current;
private List<Team> currentTeams = new ArrayList<>();
private String title;
private DisplaySlot displaySlot;
private int objPtr;
private int teamPtr;
private boolean requiresUpdate = false;
public BufferedObjective(Scoreboard scoreboard) { public BufferedObjective(Scoreboard scoreboard) {
this.scoreboard = scoreboard; this.scoreboard = scoreboard;
this.baseName = createBaseName(); this.baseName = createBaseName();

View File

@ -22,6 +22,20 @@ public class FScoreboard {
private FSidebarProvider temporaryProvider; private FSidebarProvider temporaryProvider;
private boolean removed = false; private boolean removed = false;
private FScoreboard(FPlayer fplayer) {
this.fplayer = fplayer;
if (isSupportedByServer()) {
this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
this.bufferedObjective = new BufferedObjective(scoreboard);
fplayer.getPlayer().setScoreboard(scoreboard);
} else {
this.scoreboard = null;
this.bufferedObjective = null;
}
}
// Glowstone doesn't support scoreboards. // Glowstone doesn't support scoreboards.
// All references to this and related workarounds can be safely // All references to this and related workarounds can be safely
// removed when scoreboards are supported. // removed when scoreboards are supported.
@ -56,20 +70,6 @@ public class FScoreboard {
return fscoreboards.get(FPlayers.getInstance().getByPlayer(player)); return fscoreboards.get(FPlayers.getInstance().getByPlayer(player));
} }
private FScoreboard(FPlayer fplayer) {
this.fplayer = fplayer;
if (isSupportedByServer()) {
this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();
this.bufferedObjective = new BufferedObjective(scoreboard);
fplayer.getPlayer().setScoreboard(scoreboard);
} else {
this.scoreboard = null;
this.bufferedObjective = null;
}
}
protected FPlayer getFPlayer() { protected FPlayer getFPlayer() {
return fplayer; return fplayer;
} }

View File

@ -13,14 +13,22 @@ import java.util.*;
public class FTeamWrapper { public class FTeamWrapper {
private static final Map<Faction, FTeamWrapper> wrappers = new HashMap<>(); private static final Map<Faction, FTeamWrapper> wrappers = new HashMap<>();
private static final List<FScoreboard> tracking = new ArrayList<>(); private static final List<FScoreboard> tracking = new ArrayList<>();
private static int factionTeamPtr;
private static final Set<Faction> updating = new HashSet<>(); private static final Set<Faction> updating = new HashSet<>();
private static int factionTeamPtr;
private final Map<FScoreboard, Team> teams = new HashMap<>(); private final Map<FScoreboard, Team> teams = new HashMap<>();
private final String teamName; private final String teamName;
private final Faction faction; private final Faction faction;
private final Set<OfflinePlayer> members = new HashSet<>(); private final Set<OfflinePlayer> members = new HashSet<>();
private FTeamWrapper(Faction faction) {
this.teamName = "faction_" + (factionTeamPtr++);
this.faction = faction;
for (FScoreboard fboard : tracking) {
add(fboard);
}
}
public static void applyUpdatesLater(final Faction faction) { public static void applyUpdatesLater(final Faction faction) {
if (!FScoreboard.isSupportedByServer()) { if (!FScoreboard.isSupportedByServer()) {
return; return;
@ -130,16 +138,6 @@ public class FTeamWrapper {
} }
} }
private FTeamWrapper(Faction faction) {
this.teamName = "faction_" + (factionTeamPtr++);
this.faction = faction;
for (FScoreboard fboard : tracking) {
add(fboard);
}
}
private void add(FScoreboard fboard) { private void add(FScoreboard fboard) {
Scoreboard board = fboard.getScoreboard(); Scoreboard board = fboard.getScoreboard();
Team team = board.registerNewTeam(teamName); Team team = board.registerNewTeam(teamName);
@ -171,8 +169,8 @@ public class FTeamWrapper {
String prefix = TL.DEFAULT_PREFIX.toString(); String prefix = TL.DEFAULT_PREFIX.toString();
if (P.p.PlaceholderApi) { if (P.p.PlaceholderApi) {
prefix = PlaceholderAPI.setPlaceholders(fplayer.getPlayer(),prefix); prefix = PlaceholderAPI.setPlaceholders(fplayer.getPlayer(), prefix);
prefix = PlaceholderAPI.setBracketPlaceholders(fplayer.getPlayer(),prefix); prefix = PlaceholderAPI.setBracketPlaceholders(fplayer.getPlayer(), prefix);
} }
prefix = prefix.replace("{relationcolor}", faction.getRelationTo(fplayer).getColor().toString()); prefix = prefix.replace("{relationcolor}", faction.getRelationTo(fplayer).getColor().toString());
prefix = prefix.replace("{faction}", faction.getTag().substring(0, Math.min("{faction}".length() + 16 - prefix.length(), faction.getTag().length()))); prefix = prefix.replace("{faction}", faction.getTag().substring(0, Math.min("{faction}".length() + 16 - prefix.length(), faction.getTag().length())));

View File

@ -3,7 +3,7 @@ package com.massivecraft.factions.struct;
import com.massivecraft.factions.zcore.util.TL; import com.massivecraft.factions.zcore.util.TL;
public enum ChatMode { public enum ChatMode {
MOD(4,TL.CHAT_MOD), MOD(4, TL.CHAT_MOD),
FACTION(3, TL.CHAT_FACTION), FACTION(3, TL.CHAT_FACTION),
ALLIANCE(2, TL.CHAT_ALLIANCE), ALLIANCE(2, TL.CHAT_ALLIANCE),
TRUCE(1, TL.CHAT_TRUCE), TRUCE(1, TL.CHAT_TRUCE),

View File

@ -16,7 +16,7 @@ import java.util.List;
public enum Role implements Permissable { public enum Role implements Permissable {
ADMIN(4, TL.ROLE_ADMIN), ADMIN(4, TL.ROLE_ADMIN),
COLEADER(3,TL.ROLE_COLEADER), COLEADER(3, TL.ROLE_COLEADER),
MODERATOR(2, TL.ROLE_MODERATOR), MODERATOR(2, TL.ROLE_MODERATOR),
NORMAL(1, TL.ROLE_NORMAL), NORMAL(1, TL.ROLE_NORMAL),
RECRUIT(0, TL.ROLE_RECRUIT); RECRUIT(0, TL.ROLE_RECRUIT);
@ -32,14 +32,6 @@ public enum Role implements Permissable {
this.translation = translation; this.translation = translation;
} }
public boolean isAtLeast(Role role) {
return this.value >= role.value;
}
public boolean isAtMost(Role role) {
return this.value <= role.value;
}
public static Role getRelative(Role role, int relative) { public static Role getRelative(Role role, int relative) {
return Role.getByValue(role.value + relative); return Role.getByValue(role.value + relative);
} }
@ -54,7 +46,7 @@ public enum Role implements Permissable {
return MODERATOR; return MODERATOR;
case 3: case 3:
return COLEADER; return COLEADER;
case 4: case 4:
return ADMIN; return ADMIN;
} }
@ -81,6 +73,14 @@ public enum Role implements Permissable {
return null; return null;
} }
public boolean isAtLeast(Role role) {
return this.value >= role.value;
}
public boolean isAtMost(Role role) {
return this.value <= role.value;
}
@Override @Override
public String toString() { public String toString() {
return this.nicename; return this.nicename;

View File

@ -7,49 +7,6 @@ import java.util.ArrayList;
public class AsciiCompass { public class AsciiCompass {
public enum Point {
N('N'),
NE('/'),
E('E'),
SE('\\'),
S('S'),
SW('/'),
W('W'),
NW('\\');
public final char asciiChar;
Point(final char asciiChar) {
this.asciiChar = asciiChar;
}
@Override
public String toString() {
return String.valueOf(this.asciiChar);
}
public String getTranslation() {
if (this == N) {
return TL.COMPASS_SHORT_NORTH.toString();
}
if (this == E) {
return TL.COMPASS_SHORT_EAST.toString();
}
if (this == S) {
return TL.COMPASS_SHORT_SOUTH.toString();
}
if (this == W) {
return TL.COMPASS_SHORT_WEST.toString();
}
return toString();
}
public String toString(boolean isActive, ChatColor colorActive, String colorDefault) {
return (isActive ? colorActive : colorDefault) + getTranslation();
}
}
public static Point getCompassPointForDirection(double inDegrees) { public static Point getCompassPointForDirection(double inDegrees) {
double degrees = (inDegrees - 180) % 360; double degrees = (inDegrees - 180) % 360;
if (degrees < 0) { if (degrees < 0) {
@ -107,4 +64,47 @@ public class AsciiCompass {
public static ArrayList<String> getAsciiCompass(double inDegrees, ChatColor colorActive, String colorDefault) { public static ArrayList<String> getAsciiCompass(double inDegrees, ChatColor colorActive, String colorDefault) {
return getAsciiCompass(getCompassPointForDirection(inDegrees), colorActive, colorDefault); return getAsciiCompass(getCompassPointForDirection(inDegrees), colorActive, colorDefault);
} }
public enum Point {
N('N'),
NE('/'),
E('E'),
SE('\\'),
S('S'),
SW('/'),
W('W'),
NW('\\');
public final char asciiChar;
Point(final char asciiChar) {
this.asciiChar = asciiChar;
}
@Override
public String toString() {
return String.valueOf(this.asciiChar);
}
public String getTranslation() {
if (this == N) {
return TL.COMPASS_SHORT_NORTH.toString();
}
if (this == E) {
return TL.COMPASS_SHORT_EAST.toString();
}
if (this == S) {
return TL.COMPASS_SHORT_SOUTH.toString();
}
if (this == W) {
return TL.COMPASS_SHORT_WEST.toString();
}
return toString();
}
public String toString(boolean isActive, ChatColor colorActive, String colorDefault) {
return (isActive ? colorActive : colorDefault) + getTranslation();
}
}
} }

View File

@ -39,8 +39,6 @@ public class ClipPlaceholderAPIManager extends PlaceholderExpansion implements R
} }
// Relational placeholders // Relational placeholders
@Override @Override
public String onPlaceholderRequest(Player p1, Player p2, String placeholder) { public String onPlaceholderRequest(Player p1, Player p2, String placeholder) {

View File

@ -15,6 +15,7 @@ import java.util.Map;
public final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> { public final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
public static final TypeAdapterFactory ENUM_FACTORY = newEnumTypeHierarchyFactory();
private final Map<String, T> nameToConstant = new HashMap<>(); private final Map<String, T> nameToConstant = new HashMap<>();
private final Map<T, String> constantToName = new HashMap<>(); private final Map<T, String> constantToName = new HashMap<>();
@ -34,20 +35,6 @@ public final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
} }
} }
public T read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return nameToConstant.get(in.nextString());
}
public void write(JsonWriter out, T value) throws IOException {
out.value(value == null ? null : constantToName.get(value));
}
public static final TypeAdapterFactory ENUM_FACTORY = newEnumTypeHierarchyFactory();
public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() { public static <TT> TypeAdapterFactory newEnumTypeHierarchyFactory() {
return new TypeAdapterFactory() { return new TypeAdapterFactory() {
@SuppressWarnings({"rawtypes", "unchecked"}) @SuppressWarnings({"rawtypes", "unchecked"})
@ -64,4 +51,16 @@ public final class EnumTypeAdapter<T extends Enum<T>> extends TypeAdapter<T> {
}; };
} }
public T read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
return nameToConstant.get(in.nextString());
}
public void write(JsonWriter out, T value) throws IOException {
out.value(value == null ? null : constantToName.get(value));
}
} }

View File

@ -1,12 +1,6 @@
package com.massivecraft.factions.util; package com.massivecraft.factions.util;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Item;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.util.io.BukkitObjectInputStream; import org.bukkit.util.io.BukkitObjectInputStream;
import org.bukkit.util.io.BukkitObjectOutputStream; import org.bukkit.util.io.BukkitObjectOutputStream;
import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
@ -14,7 +8,6 @@ import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Map;
public class InventoryUtil { public class InventoryUtil {
@ -24,7 +17,7 @@ public class InventoryUtil {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream);
dataOutput.writeInt(items.length); dataOutput.writeInt(items.length);
for (ItemStack item: items) { for (ItemStack item : items) {
dataOutput.writeObject(item); dataOutput.writeObject(item);
} }
dataOutput.close(); dataOutput.close();

View File

@ -18,6 +18,9 @@ import java.util.logging.Level;
public class MiscUtil { public class MiscUtil {
/// TODO create tag whitelist!!
public static HashSet<String> substanceChars = new HashSet<>(Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"));
public static EntityType creatureTypeFromEntity(Entity entity) { public static EntityType creatureTypeFromEntity(Entity entity) {
if (!(entity instanceof Creature)) { if (!(entity instanceof Creature)) {
return null; return null;
@ -46,9 +49,6 @@ public class MiscUtil {
return values; return values;
} }
/// TODO create tag whitelist!!
public static HashSet<String> substanceChars = new HashSet<>(Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"));
public static String getComparisonString(String str) { public static String getComparisonString(String str) {
StringBuilder ret = new StringBuilder(); StringBuilder ret = new StringBuilder();

View File

@ -15,8 +15,6 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level; import java.util.logging.Level;
import static com.massivecraft.factions.zcore.util.TL.ROLE_NORMAL;
public class PermissionsMapTypeAdapter implements JsonDeserializer<Map<Permissable, Map<PermissableAction, Access>>> { public class PermissionsMapTypeAdapter implements JsonDeserializer<Map<Permissable, Map<PermissableAction, Access>>> {
@Override @Override

View File

@ -59,6 +59,10 @@ public abstract class SpiralTask implements Runnable {
this.setTaskID(Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(P.p, this, 2, 2)); this.setTaskID(Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(P.p, this, 2, 2));
} }
private static long now() {
return System.currentTimeMillis();
}
/* /*
* This is where the necessary work is done; you'll need to override this method with whatever you want * This is where the necessary work is done; you'll need to override this method with whatever you want
* done at each chunk in the spiral pattern. * done at each chunk in the spiral pattern.
@ -88,16 +92,16 @@ public abstract class SpiralTask implements Runnable {
return x; return x;
} }
public final int getZ() {
return z;
}
/* /*
* Below are the guts of the class, which you normally wouldn't need to mess with. * Below are the guts of the class, which you normally wouldn't need to mess with.
*/ */
public final int getZ() {
return z;
}
public final void setTaskID(int ID) { public final void setTaskID(int ID) {
if (ID == -1) { if (ID == -1) {
this.stop(); this.stop();
@ -202,8 +206,4 @@ public abstract class SpiralTask implements Runnable {
public final boolean valid() { public final boolean valid() {
return taskID != -1; return taskID != -1;
} }
private static long now() {
return System.currentTimeMillis();
}
} }

View File

@ -24,18 +24,14 @@ import java.util.logging.Level;
public class WarpGUI implements InventoryHolder, FactionGUI { public class WarpGUI implements InventoryHolder, FactionGUI {
private final ConfigurationSection section;
int guiSize;
private Inventory warpGUI; private Inventory warpGUI;
private FPlayer fme; private FPlayer fme;
int guiSize;
private HashMap<Integer, String> warpSlots = new HashMap<>(); private HashMap<Integer, String> warpSlots = new HashMap<>();
private int maxWarps; private int maxWarps;
private List<Integer> dummySlots = new ArrayList<>(); private List<Integer> dummySlots = new ArrayList<>();
private final ConfigurationSection section;
public WarpGUI(FPlayer fme) { public WarpGUI(FPlayer fme) {
this.fme = fme; this.fme = fme;
this.section = P.p.getConfig().getConfigurationSection("fwarp-gui"); this.section = P.p.getConfig().getConfigurationSection("fwarp-gui");
@ -114,7 +110,7 @@ public class WarpGUI implements InventoryHolder, FactionGUI {
fme.setEnteringPassword(false, ""); fme.setEnteringPassword(false, "");
} }
} }
}, P.p.getConfig().getInt("fwarp-gui.password-timeout", 5)*20); }, P.p.getConfig().getInt("fwarp-gui.password-timeout", 5) * 20);
} }
} }
} }

View File

@ -26,55 +26,28 @@ public abstract class MCommand<T extends MPlugin> {
// The sub-commands to this command // The sub-commands to this command
public List<MCommand<?>> subCommands; public List<MCommand<?>> subCommands;
public void addSubCommand(MCommand<?> subCommand) {
subCommand.commandChain.addAll(this.commandChain);
subCommand.commandChain.add(this);
this.subCommands.add(subCommand);
}
// The different names this commands will react to // The different names this commands will react to
public List<String> aliases; public List<String> aliases;
public boolean allowNoSlashAccess; public boolean allowNoSlashAccess;
// Information on the args // Information on the args
public List<String> requiredArgs; public List<String> requiredArgs;
public LinkedHashMap<String, String> optionalArgs; public LinkedHashMap<String, String> optionalArgs;
public boolean errorOnToManyArgs = true; public boolean errorOnToManyArgs = true;
// FIELD: Help Short
// This field may be left blank and will in such case be loaded from the permissions node instead.
// Thus make sure the permissions node description is an action description like "eat hamburgers" or "do admin stuff".
private String helpShort;
public void setHelpShort(String val) {
this.helpShort = val;
}
public String getHelpShort() {
if (this.helpShort == null) {
return getUsageTranslation().toString();
}
return this.helpShort;
}
public abstract TL getUsageTranslation();
public List<String> helpLong; public List<String> helpLong;
public CommandVisibility visibility; public CommandVisibility visibility;
// Some information on permissions // Some information on permissions
public boolean senderMustBePlayer; public boolean senderMustBePlayer;
public String permission; public String permission;
// Information available on execution of the command // Information available on execution of the command
public CommandSender sender; // Will always be set public CommandSender sender; // Will always be set
public Player me; // Will only be set when the sender is a player public Player me; // Will only be set when the sender is a player
public boolean senderIsConsole; public boolean senderIsConsole;
public List<String> args; // Will contain the arguments, or and empty list if there are none. public List<String> args; // Will contain the arguments, or and empty list if there are none.
public List<MCommand<?>> commandChain = new ArrayList<>(); // The command chain used to execute this command public List<MCommand<?>> commandChain = new ArrayList<>(); // The command chain used to execute this command
// FIELD: Help Short
// This field may be left blank and will in such case be loaded from the permissions node instead.
// Thus make sure the permissions node description is an action description like "eat hamburgers" or "do admin stuff".
private String helpShort;
public MCommand(T p) { public MCommand(T p) {
this.p = p; this.p = p;
@ -93,6 +66,26 @@ public abstract class MCommand<T extends MPlugin> {
this.visibility = CommandVisibility.VISIBLE; this.visibility = CommandVisibility.VISIBLE;
} }
public void addSubCommand(MCommand<?> subCommand) {
subCommand.commandChain.addAll(this.commandChain);
subCommand.commandChain.add(this);
this.subCommands.add(subCommand);
}
public String getHelpShort() {
if (this.helpShort == null) {
return getUsageTranslation().toString();
}
return this.helpShort;
}
public void setHelpShort(String val) {
this.helpShort = val;
}
public abstract TL getUsageTranslation();
// The commandChain is a list of the parent command chain used to get to this command. // The commandChain is a list of the parent command chain used to get to this command.
public void execute(CommandSender sender, List<String> args, List<MCommand<?>> commandChain) { public void execute(CommandSender sender, List<String> args, List<MCommand<?>> commandChain) {
// Set the execution-time specific variables // Set the execution-time specific variables

View File

@ -27,16 +27,32 @@ import java.util.logging.Level;
public abstract class MPlugin extends JavaPlugin { public abstract class MPlugin extends JavaPlugin {
// Persist related
public final Gson gson = this.getGsonBuilder().create();
// Some utils // Some utils
public Persist persist; public Persist persist;
public TextUtil txt; public TextUtil txt;
public PermUtil perm; public PermUtil perm;
public String refCommand = "";
// Persist related //holds f stuck taskids
public final Gson gson = this.getGsonBuilder().create(); public Map<UUID, Integer> stuckMap = new HashMap<>();
// These are not supposed to be used directly.
// They are loaded and used through the TextUtil instance for the plugin.
public Map<String, String> rawTags = new LinkedHashMap<>();
protected boolean loadSuccessful = false;
private Integer saveTask = null; private Integer saveTask = null;
private boolean autoSave = true; private boolean autoSave = true;
protected boolean loadSuccessful = false; // Listeners
private MPluginSecretPlayerListener mPluginSecretPlayerListener;
// Our stored base commands
private List<MCommand<?>> baseCommands = new ArrayList<>();
// holds f stuck start times
private Map<UUID, Long> timers = new HashMap<>();
// -------------------------------------------- //
// ENABLE
// -------------------------------------------- //
private long timeEnableStart;
public boolean getAutoSave() { public boolean getAutoSave() {
return this.autoSave; return this.autoSave;
@ -46,29 +62,10 @@ public abstract class MPlugin extends JavaPlugin {
this.autoSave = val; this.autoSave = val;
} }
public String refCommand = "";
// Listeners
private MPluginSecretPlayerListener mPluginSecretPlayerListener;
// Our stored base commands
private List<MCommand<?>> baseCommands = new ArrayList<>();
public List<MCommand<?>> getBaseCommands() { public List<MCommand<?>> getBaseCommands() {
return this.baseCommands; return this.baseCommands;
} }
// holds f stuck start times
private Map<UUID, Long> timers = new HashMap<>();
//holds f stuck taskids
public Map<UUID, Integer> stuckMap = new HashMap<>();
// -------------------------------------------- //
// ENABLE
// -------------------------------------------- //
private long timeEnableStart;
public boolean preEnable() { public boolean preEnable() {
log("=== ENABLE START ==="); log("=== ENABLE START ===");
timeEnableStart = System.currentTimeMillis(); timeEnableStart = System.currentTimeMillis();
@ -193,28 +190,24 @@ public abstract class MPlugin extends JavaPlugin {
log("Disabled"); log("Disabled");
} }
public void suicide() {
log("Now I suicide!");
this.getServer().getPluginManager().disablePlugin(this);
}
// -------------------------------------------- // // -------------------------------------------- //
// Some inits... // Some inits...
// You are supposed to override these in the plugin if you aren't satisfied with the defaults // You are supposed to override these in the plugin if you aren't satisfied with the defaults
// The goal is that you always will be satisfied though. // The goal is that you always will be satisfied though.
// -------------------------------------------- // // -------------------------------------------- //
public GsonBuilder getGsonBuilder() { public void suicide() {
return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE); log("Now I suicide!");
this.getServer().getPluginManager().disablePlugin(this);
} }
// -------------------------------------------- // // -------------------------------------------- //
// LANG AND TAGS // LANG AND TAGS
// -------------------------------------------- // // -------------------------------------------- //
// These are not supposed to be used directly. public GsonBuilder getGsonBuilder() {
// They are loaded and used through the TextUtil instance for the plugin. return new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().serializeNulls().excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.VOLATILE);
public Map<String, String> rawTags = new LinkedHashMap<>(); }
public void addRawTags() { public void addRawTags() {
this.rawTags.put("l", "<green>"); // logo this.rawTags.put("l", "<green>"); // logo

View File

@ -39,7 +39,8 @@ public enum PermissableAction {
TNTFILL("tntfill"), TNTFILL("tntfill"),
WITHDRAW("withdraw"), WITHDRAW("withdraw"),
CHEST("chest"), CHEST("chest"),
SPAWNER("spawner"); SPAWNER("spawner"),
CLAIM("claim");
private String name; private String name;
@ -47,15 +48,6 @@ public enum PermissableAction {
this.name = name; this.name = name;
} }
/**
* Get the friendly name of this action. Used for editing in commands.
*
* @return friendly name of the action as a String.
*/
public String getName() {
return this.name;
}
/** /**
* Case insensitive check for action. * Case insensitive check for action.
* *
@ -72,6 +64,15 @@ public enum PermissableAction {
return null; return null;
} }
/**
* Get the friendly name of this action. Used for editing in commands.
*
* @return friendly name of the action as a String.
*/
public String getName() {
return this.name;
}
@Override @Override
public String toString() { public String toString() {
return name; return name;

View File

@ -24,19 +24,15 @@ import java.util.logging.Level;
public class PermissableActionGUI implements InventoryHolder, FactionGUI { public class PermissableActionGUI implements InventoryHolder, FactionGUI {
private final ConfigurationSection section;
private Inventory actionGUI; private Inventory actionGUI;
private FPlayer fme; private FPlayer fme;
private int guiSize; private int guiSize;
private Permissable permissable; private Permissable permissable;
private HashMap<Integer, PermissableAction> actionSlots = new HashMap<>(); private HashMap<Integer, PermissableAction> actionSlots = new HashMap<>();
private HashMap<Integer, SpecialItem> specialSlots = new HashMap<>(); private HashMap<Integer, SpecialItem> specialSlots = new HashMap<>();
private ArrayList<Integer> usedDummySlots = new ArrayList<>(); private ArrayList<Integer> usedDummySlots = new ArrayList<>();
private final ConfigurationSection section;
public PermissableActionGUI(FPlayer fme, Permissable permissable) { public PermissableActionGUI(FPlayer fme, Permissable permissable) {
this.fme = fme; this.fme = fme;
this.permissable = permissable; this.permissable = permissable;
@ -198,7 +194,7 @@ public class PermissableActionGUI implements InventoryHolder, FactionGUI {
} }
backButtonMeta.setLore(lore); backButtonMeta.setLore(lore);
if (!P.p.mc17){ if (!P.p.mc17) {
backButtonMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES); backButtonMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS, ItemFlag.HIDE_ATTRIBUTES);
} }

View File

@ -26,15 +26,12 @@ import java.util.logging.Level;
public class PermissableRelationGUI implements InventoryHolder, FactionGUI { public class PermissableRelationGUI implements InventoryHolder, FactionGUI {
private final ConfigurationSection section;
private Inventory relationGUI; private Inventory relationGUI;
private FPlayer fme; private FPlayer fme;
private int guiSize; private int guiSize;
private HashMap<Integer, Permissable> relationSlots = new HashMap<>(); private HashMap<Integer, Permissable> relationSlots = new HashMap<>();
private final ConfigurationSection section;
public PermissableRelationGUI(FPlayer fme) { public PermissableRelationGUI(FPlayer fme) {
this.fme = fme; this.fme = fme;

View File

@ -209,7 +209,6 @@ public class FUpgradesGUI implements Listener {
} }
} }
private void closeChests(Faction faction) { private void closeChests(Faction faction) {
@ -237,7 +236,9 @@ public class FUpgradesGUI implements Listener {
ItemStack expItem = P.p.createItem(expMaterial, expAmt, expData, expName, expLore); ItemStack expItem = P.p.createItem(expMaterial, expAmt, expData, expName, expLore);
if (expLevel >= 1) { if (expLevel >= 1) {
ItemMeta itemMeta = expItem.getItemMeta(); ItemMeta itemMeta = expItem.getItemMeta();
if (!P.p.mc17) { itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } if (!P.p.mc17) {
itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
}
itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); itemMeta.addEnchant(Enchantment.DURABILITY, 3, true);
expItem.setItemMeta(itemMeta); expItem.setItemMeta(itemMeta);
} }
@ -275,7 +276,9 @@ public class FUpgradesGUI implements Listener {
cropItem.getItemMeta().setLore(cropLore); cropItem.getItemMeta().setLore(cropLore);
if (cropLevel >= 1) { if (cropLevel >= 1) {
ItemMeta itemMeta = cropItem.getItemMeta(); ItemMeta itemMeta = cropItem.getItemMeta();
if (!P.p.mc17) { itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } if (!P.p.mc17) {
itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
}
itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); itemMeta.addEnchant(Enchantment.DURABILITY, 3, true);
cropItem.setItemMeta(itemMeta); cropItem.setItemMeta(itemMeta);
} }
@ -288,7 +291,9 @@ public class FUpgradesGUI implements Listener {
spawnerItem.getItemMeta().setLore(spawnerLore); spawnerItem.getItemMeta().setLore(spawnerLore);
if (spawnerLevel >= 1) { if (spawnerLevel >= 1) {
ItemMeta itemMeta = spawnerItem.getItemMeta(); ItemMeta itemMeta = spawnerItem.getItemMeta();
if (!P.p.mc17) { itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } if (!P.p.mc17) {
itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
}
itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); itemMeta.addEnchant(Enchantment.DURABILITY, 3, true);
spawnerItem.setItemMeta(itemMeta); spawnerItem.setItemMeta(itemMeta);
} }
@ -314,7 +319,9 @@ public class FUpgradesGUI implements Listener {
if (chestlevel >= 1) { if (chestlevel >= 1) {
ItemMeta itemMeta = chestItem.getItemMeta(); ItemMeta itemMeta = chestItem.getItemMeta();
if (!P.p.mc17) { itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } if (!P.p.mc17) {
itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
}
itemMeta.addEnchant(Enchantment.DURABILITY, 3, true); itemMeta.addEnchant(Enchantment.DURABILITY, 3, true);
chestItem.setItemMeta(itemMeta); chestItem.setItemMeta(itemMeta);
} }

View File

@ -1,9 +1,9 @@
package com.massivecraft.factions.zcore.nbtapi; package com.massivecraft.factions.zcore.nbtapi;
import java.util.Set;
import com.massivecraft.factions.zcore.nbtapi.utils.MinecraftVersion; import com.massivecraft.factions.zcore.nbtapi.utils.MinecraftVersion;
import java.util.Set;
public class NBTCompound { public class NBTCompound {
@ -31,10 +31,10 @@ public class NBTCompound {
return parent; return parent;
} }
public void mergeCompound(NBTCompound comp){ public void mergeCompound(NBTCompound comp) {
NBTReflectionUtil.addOtherNBTCompound(this, comp); NBTReflectionUtil.addOtherNBTCompound(this, comp);
} }
public void setString(String key, String value) { public void setString(String key, String value) {
NBTReflectionUtil.setString(this, key, value); NBTReflectionUtil.setString(this, key, value);
} }
@ -185,8 +185,8 @@ public class NBTCompound {
return result + "-" + key + ": " + getContent(key) + System.lineSeparator(); return result + "-" + key + ": " + getContent(key) + System.lineSeparator();
} }
} }
public String asNBTString(){ public String asNBTString() {
return NBTReflectionUtil.gettoCompount(getCompound(), this).toString(); return NBTReflectionUtil.gettoCompount(getCompound(), this).toString();
} }

View File

@ -1,6 +1,6 @@
package com.massivecraft.factions.zcore.nbtapi; package com.massivecraft.factions.zcore.nbtapi;
public class NBTContainer extends NBTCompound{ public class NBTContainer extends NBTCompound {
private Object nbt; private Object nbt;
@ -8,17 +8,17 @@ public class NBTContainer extends NBTCompound{
super(null, null); super(null, null);
nbt = NBTReflectionUtil.getNewNBTTag(); nbt = NBTReflectionUtil.getNewNBTTag();
} }
protected NBTContainer(Object nbt){ protected NBTContainer(Object nbt) {
super(null, null); super(null, null);
this.nbt = nbt; this.nbt = nbt;
} }
public NBTContainer(String nbtString) throws IllegalArgumentException { public NBTContainer(String nbtString) throws IllegalArgumentException {
super(null, null); super(null, null);
try{ try {
nbt = NBTReflectionUtil.parseNBT(nbtString); nbt = NBTReflectionUtil.parseNBT(nbtString);
}catch(Exception ex){ } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
throw new IllegalArgumentException("Malformed Json: " + ex.getMessage()); throw new IllegalArgumentException("Malformed Json: " + ex.getMessage());
} }

View File

@ -11,6 +11,14 @@ public class NBTItem extends NBTCompound {
bukkitItem = item.clone(); bukkitItem = item.clone();
} }
public static NBTContainer convertItemtoNBT(ItemStack item) {
return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item));
}
public static ItemStack convertNBTtoItem(NBTCompound comp) {
return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp));
}
protected Object getCompound() { protected Object getCompound() {
return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem)); return NBTReflectionUtil.getItemRootNBTTagCompound(NBTReflectionUtil.getNMSItemStack(bukkitItem));
} }
@ -26,13 +34,5 @@ public class NBTItem extends NBTCompound {
protected void setItem(ItemStack item) { protected void setItem(ItemStack item) {
bukkitItem = item; bukkitItem = item;
} }
public static NBTContainer convertItemtoNBT(ItemStack item){
return NBTReflectionUtil.convertNMSItemtoNBTCompound(NBTReflectionUtil.getNMSItemStack(item));
}
public static ItemStack convertNBTtoItem(NBTCompound comp){
return NBTReflectionUtil.getBukkitItemStack(NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp));
}
} }

View File

@ -1,5 +1,13 @@
package com.massivecraft.factions.zcore.nbtapi; package com.massivecraft.factions.zcore.nbtapi;
import com.massivecraft.factions.zcore.nbtapi.utils.GsonWrapper;
import com.massivecraft.factions.zcore.nbtapi.utils.MethodNames;
import com.massivecraft.factions.zcore.nbtapi.utils.MinecraftVersion;
import org.bukkit.Bukkit;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.InputStream; import java.io.InputStream;
@ -8,15 +16,6 @@ import java.lang.reflect.Method;
import java.util.Set; import java.util.Set;
import java.util.Stack; import java.util.Stack;
import org.bukkit.Bukkit;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.ItemStack;
import com.massivecraft.factions.zcore.nbtapi.utils.GsonWrapper;
import com.massivecraft.factions.zcore.nbtapi.utils.MethodNames;
import com.massivecraft.factions.zcore.nbtapi.utils.MinecraftVersion;
// TODO: finish codestyle cleanup -sgdc3 // TODO: finish codestyle cleanup -sgdc3
public class NBTReflectionUtil { public class NBTReflectionUtil {
@ -70,7 +69,7 @@ public class NBTReflectionUtil {
return null; return null;
} }
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected static Class getNMSItemStack() { protected static Class getNMSItemStack() {
try { try {
@ -106,7 +105,7 @@ public class NBTReflectionUtil {
return null; return null;
} }
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
protected static Class getMojangsonParser() { protected static Class getMojangsonParser() {
try { try {
@ -223,7 +222,7 @@ public class NBTReflectionUtil {
} }
return null; return null;
} }
@SuppressWarnings({"unchecked"}) @SuppressWarnings({"unchecked"})
public static Object readNBTFile(FileInputStream stream) { public static Object readNBTFile(FileInputStream stream) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -281,7 +280,7 @@ public class NBTReflectionUtil {
} }
return null; return null;
} }
@SuppressWarnings({"unchecked"}) @SuppressWarnings({"unchecked"})
public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) { public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -294,7 +293,7 @@ public class NBTReflectionUtil {
} }
return null; return null;
} }
@SuppressWarnings({"unchecked"}) @SuppressWarnings({"unchecked"})
public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) { public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) {
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@ -434,7 +433,7 @@ public class NBTReflectionUtil {
} }
return nbttag; return nbttag;
} }
public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) { public static void addOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompound) {
Object rootnbttag = comp.getCompound(); Object rootnbttag = comp.getCompound();
if (rootnbttag == null) { if (rootnbttag == null) {

View File

@ -14,14 +14,10 @@ public enum NBTType {
NBTTagList(9), NBTTagList(9),
NBTTagCompound(10); NBTTagCompound(10);
NBTType(int i) {
id = i;
}
private final int id; private final int id;
public int getId() { NBTType(int i) {
return id; id = i;
} }
public static NBTType valueOf(int id) { public static NBTType valueOf(int id) {
@ -31,4 +27,8 @@ public enum NBTType {
return NBTType.NBTTagEnd; return NBTType.NBTTagEnd;
} }
public int getId() {
return id;
}
} }

View File

@ -21,10 +21,6 @@ public enum MinecraftVersion {
this.versionId = versionId; this.versionId = versionId;
} }
public int getVersionId() {
return versionId;
}
public static MinecraftVersion getVersion() { public static MinecraftVersion getVersion() {
if (version != null) { if (version != null) {
return version; return version;
@ -57,4 +53,8 @@ public enum MinecraftVersion {
return hasGsonSupport; return hasGsonSupport;
} }
public int getVersionId() {
return versionId;
}
} }

View File

@ -20,51 +20,6 @@ import java.util.Map.Entry;
public abstract class MemoryBoard extends Board { public abstract class MemoryBoard extends Board {
public class MemoryBoardMap extends HashMap<FLocation, String> {
private static final long serialVersionUID = -6689617828610585368L;
Multimap<String, FLocation> factionToLandMap = HashMultimap.create();
@Override
public String put(FLocation floc, String factionId) {
String previousValue = super.put(floc, factionId);
if (previousValue != null) {
factionToLandMap.remove(previousValue, floc);
}
factionToLandMap.put(factionId, floc);
return previousValue;
}
@Override
public String remove(Object key) {
String result = super.remove(key);
if (result != null) {
FLocation floc = (FLocation) key;
factionToLandMap.remove(result, floc);
}
return result;
}
@Override
public void clear() {
super.clear();
factionToLandMap.clear();
}
public int getOwnedLandCount(String factionId) {
return factionToLandMap.get(factionId).size();
}
public void removeFaction(String factionId) {
Collection<FLocation> flocations = factionToLandMap.removeAll(factionId);
for (FLocation floc : flocations) {
super.remove(floc);
}
}
}
public MemoryBoardMap flocationIds = new MemoryBoardMap(); public MemoryBoardMap flocationIds = new MemoryBoardMap();
//----------------------------------------------// //----------------------------------------------//
@ -198,11 +153,6 @@ public abstract class MemoryBoard extends Board {
return false; return false;
} }
//----------------------------------------------//
// Cleaner. Remove orphaned foreign keys
//----------------------------------------------//
public void clean() { public void clean() {
Iterator<Entry<FLocation, String>> iter = flocationIds.entrySet().iterator(); Iterator<Entry<FLocation, String>> iter = flocationIds.entrySet().iterator();
while (iter.hasNext()) { while (iter.hasNext()) {
@ -214,14 +164,19 @@ public abstract class MemoryBoard extends Board {
} }
} }
//----------------------------------------------// //----------------------------------------------//
// Coord count // Cleaner. Remove orphaned foreign keys
//----------------------------------------------// //----------------------------------------------//
public int getFactionCoordCount(String factionId) { public int getFactionCoordCount(String factionId) {
return flocationIds.getOwnedLandCount(factionId); return flocationIds.getOwnedLandCount(factionId);
} }
//----------------------------------------------//
// Coord count
//----------------------------------------------//
public int getFactionCoordCount(Faction faction) { public int getFactionCoordCount(Faction faction) {
return getFactionCoordCount(faction.getId()); return getFactionCoordCount(faction.getId());
} }
@ -237,10 +192,6 @@ public abstract class MemoryBoard extends Board {
return ret; return ret;
} }
//----------------------------------------------//
// Map generation
//----------------------------------------------//
/** /**
* The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction * The map is relative to a coord and a faction north is in the direction of decreasing x east is in the direction
* of decreasing z * of decreasing z
@ -285,7 +236,7 @@ public abstract class MemoryBoard extends Board {
FLocation flocationHere = topLeft.getRelative(dx, dz); FLocation flocationHere = topLeft.getRelative(dx, dz);
Faction factionHere = getFactionAt(flocationHere); Faction factionHere = getFactionAt(flocationHere);
Relation relation = fplayer.getRelationTo(factionHere); Relation relation = fplayer.getRelationTo(factionHere);
if (flocationHere.isOutsideWorldBorder(buffer)){ if (flocationHere.isOutsideWorldBorder(buffer)) {
row.then("-").color(ChatColor.BLACK).tooltip(TL.CLAIM_MAP_OUTSIDEBORDER.toString()); row.then("-").color(ChatColor.BLACK).tooltip(TL.CLAIM_MAP_OUTSIDEBORDER.toString());
} else if (factionHere.isWilderness()) { } else if (factionHere.isWilderness()) {
row.then("-").color(Conf.colorWilderness); row.then("-").color(Conf.colorWilderness);
@ -329,6 +280,10 @@ public abstract class MemoryBoard extends Board {
return ret; return ret;
} }
//----------------------------------------------//
// Map generation
//----------------------------------------------//
private List<String> oneLineToolTip(Faction faction, FPlayer to) { private List<String> oneLineToolTip(Faction faction, FPlayer to) {
return Arrays.asList(faction.describeTo(to)); return Arrays.asList(faction.describeTo(to));
} }
@ -386,4 +341,49 @@ public abstract class MemoryBoard extends Board {
} }
public abstract void convertFrom(MemoryBoard old); public abstract void convertFrom(MemoryBoard old);
public class MemoryBoardMap extends HashMap<FLocation, String> {
private static final long serialVersionUID = -6689617828610585368L;
Multimap<String, FLocation> factionToLandMap = HashMultimap.create();
@Override
public String put(FLocation floc, String factionId) {
String previousValue = super.put(floc, factionId);
if (previousValue != null) {
factionToLandMap.remove(previousValue, floc);
}
factionToLandMap.put(factionId, floc);
return previousValue;
}
@Override
public String remove(Object key) {
String result = super.remove(key);
if (result != null) {
FLocation floc = (FLocation) key;
factionToLandMap.remove(result, floc);
}
return result;
}
@Override
public void clear() {
super.clear();
factionToLandMap.clear();
}
public int getOwnedLandCount(String factionId) {
return factionToLandMap.get(factionId).size();
}
public void removeFaction(String factionId) {
Collection<FLocation> flocations = factionToLandMap.removeAll(factionId);
for (FLocation floc : flocations) {
super.remove(floc);
}
}
}
} }

View File

@ -47,6 +47,7 @@ import java.util.UUID;
public abstract class MemoryFPlayer implements FPlayer { public abstract class MemoryFPlayer implements FPlayer {
public boolean inVault = false;
protected String factionId; protected String factionId;
protected Role role; protected Role role;
protected String title; protected String title;
@ -70,7 +71,6 @@ public abstract class MemoryFPlayer implements FPlayer {
protected boolean isFlying = false; protected boolean isFlying = false;
protected boolean enteringPassword = false; protected boolean enteringPassword = false;
protected String enteringPasswordWarp = ""; protected String enteringPasswordWarp = "";
protected transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked? protected transient FLocation lastStoodAt = new FLocation(); // Where did this player stand the last time we checked?
protected transient boolean mapAutoUpdating; protected transient boolean mapAutoUpdating;
protected transient Faction autoClaimFor; protected transient Faction autoClaimFor;
@ -79,6 +79,56 @@ public abstract class MemoryFPlayer implements FPlayer {
protected transient boolean loginPvpDisabled; protected transient boolean loginPvpDisabled;
protected transient long lastFrostwalkerMessage; protected transient long lastFrostwalkerMessage;
protected transient boolean shouldTakeFallDamage = true; protected transient boolean shouldTakeFallDamage = true;
boolean playerAlerts = false;
boolean inspectMode = false;
public MemoryFPlayer() {
}
public MemoryFPlayer(String id) {
this.id = id;
this.resetFactionData(false);
this.power = Conf.powerPlayerStarting;
this.lastPowerUpdateTime = System.currentTimeMillis();
this.lastLoginTime = System.currentTimeMillis();
this.mapAutoUpdating = false;
this.autoClaimFor = null;
this.autoSafeZoneEnabled = false;
this.autoWarZoneEnabled = false;
this.loginPvpDisabled = Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0;
this.powerBoost = 0.0;
this.showScoreboard = P.p.getConfig().getBoolean("scoreboard.default-enabled", false);
this.kills = 0;
this.deaths = 0;
this.mapHeight = Conf.mapHeight;
if (!Conf.newPlayerStartingFactionID.equals("0") && Factions.getInstance().isValidFactionId(Conf.newPlayerStartingFactionID)) {
this.factionId = Conf.newPlayerStartingFactionID;
}
}
public MemoryFPlayer(MemoryFPlayer other) {
this.factionId = other.factionId;
this.id = other.id;
this.power = other.power;
this.lastLoginTime = other.lastLoginTime;
this.mapAutoUpdating = other.mapAutoUpdating;
this.autoClaimFor = other.autoClaimFor;
this.autoSafeZoneEnabled = other.autoSafeZoneEnabled;
this.autoWarZoneEnabled = other.autoWarZoneEnabled;
this.loginPvpDisabled = other.loginPvpDisabled;
this.powerBoost = other.powerBoost;
this.role = other.role;
this.title = other.title;
this.chatMode = other.chatMode;
this.spyingChat = other.spyingChat;
this.lastStoodAt = other.lastStoodAt;
this.isAdminBypassing = other.isAdminBypassing;
this.showScoreboard = P.p.getConfig().getBoolean("scoreboard.default-enabled", true);
this.kills = other.kills;
this.deaths = other.deaths;
this.mapHeight = Conf.mapHeight;
}
public void login() { public void login() {
this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS); this.kills = getPlayer().getStatistic(Statistic.PLAYER_KILLS);
@ -97,14 +147,6 @@ public abstract class MemoryFPlayer implements FPlayer {
return Factions.getInstance().getFactionById(this.factionId); return Factions.getInstance().getFactionById(this.factionId);
} }
public String getFactionId() {
return this.factionId;
}
public boolean hasFaction() {
return !factionId.equals("0");
}
public void setFaction(Faction faction) { public void setFaction(Faction faction) {
Faction oldFaction = this.getFaction(); Faction oldFaction = this.getFaction();
if (oldFaction != null) { if (oldFaction != null) {
@ -114,6 +156,14 @@ public abstract class MemoryFPlayer implements FPlayer {
this.factionId = faction.getId(); this.factionId = faction.getId();
} }
public String getFactionId() {
return this.factionId;
}
public boolean hasFaction() {
return !factionId.equals("0");
}
public void setMonitorJoins(boolean monitor) { public void setMonitorJoins(boolean monitor) {
this.monitorJoins = monitor; this.monitorJoins = monitor;
} }
@ -209,10 +259,6 @@ public abstract class MemoryFPlayer implements FPlayer {
this.isAdminBypassing = val; this.isAdminBypassing = val;
} }
public void setChatMode(ChatMode chatMode) {
this.chatMode = chatMode;
}
public ChatMode getChatMode() { public ChatMode getChatMode() {
if (this.factionId.equals("0") || !Conf.factionOnlyChat) { if (this.factionId.equals("0") || !Conf.factionOnlyChat) {
this.chatMode = ChatMode.PUBLIC; this.chatMode = ChatMode.PUBLIC;
@ -220,75 +266,35 @@ public abstract class MemoryFPlayer implements FPlayer {
return chatMode; return chatMode;
} }
public void setIgnoreAllianceChat(boolean ignore) { public void setChatMode(ChatMode chatMode) {
this.ignoreAllianceChat = ignore; this.chatMode = chatMode;
} }
public boolean isIgnoreAllianceChat() { public boolean isIgnoreAllianceChat() {
return ignoreAllianceChat; return ignoreAllianceChat;
} }
public void setSpyingChat(boolean chatSpying) { public void setIgnoreAllianceChat(boolean ignore) {
this.spyingChat = chatSpying; this.ignoreAllianceChat = ignore;
} }
public boolean isSpyingChat() { public boolean isSpyingChat() {
return spyingChat; return spyingChat;
} }
public void setSpyingChat(boolean chatSpying) {
this.spyingChat = chatSpying;
}
// -------------------------------------------- //
// Getters And Setters
// -------------------------------------------- //
// FIELD: account // FIELD: account
public String getAccountId() { public String getAccountId() {
return this.getId(); return this.getId();
} }
public MemoryFPlayer() {
}
public MemoryFPlayer(String id) {
this.id = id;
this.resetFactionData(false);
this.power = Conf.powerPlayerStarting;
this.lastPowerUpdateTime = System.currentTimeMillis();
this.lastLoginTime = System.currentTimeMillis();
this.mapAutoUpdating = false;
this.autoClaimFor = null;
this.autoSafeZoneEnabled = false;
this.autoWarZoneEnabled = false;
this.loginPvpDisabled = Conf.noPVPDamageToOthersForXSecondsAfterLogin > 0;
this.powerBoost = 0.0;
this.showScoreboard = P.p.getConfig().getBoolean("scoreboard.default-enabled", false);
this.kills = 0;
this.deaths = 0;
this.mapHeight = Conf.mapHeight;
if (!Conf.newPlayerStartingFactionID.equals("0") && Factions.getInstance().isValidFactionId(Conf.newPlayerStartingFactionID)) {
this.factionId = Conf.newPlayerStartingFactionID;
}
}
public MemoryFPlayer(MemoryFPlayer other) {
this.factionId = other.factionId;
this.id = other.id;
this.power = other.power;
this.lastLoginTime = other.lastLoginTime;
this.mapAutoUpdating = other.mapAutoUpdating;
this.autoClaimFor = other.autoClaimFor;
this.autoSafeZoneEnabled = other.autoSafeZoneEnabled;
this.autoWarZoneEnabled = other.autoWarZoneEnabled;
this.loginPvpDisabled = other.loginPvpDisabled;
this.powerBoost = other.powerBoost;
this.role = other.role;
this.title = other.title;
this.chatMode = other.chatMode;
this.spyingChat = other.spyingChat;
this.lastStoodAt = other.lastStoodAt;
this.isAdminBypassing = other.isAdminBypassing;
this.showScoreboard = P.p.getConfig().getBoolean("scoreboard.default-enabled", true);
this.kills = other.kills;
this.deaths = other.deaths;
this.mapHeight = Conf.mapHeight;
}
public void resetFactionData(boolean doSpoutUpdate) { public void resetFactionData(boolean doSpoutUpdate) {
// clean up any territory ownership in old faction, if there is one // clean up any territory ownership in old faction, if there is one
if (factionId != null && Factions.getInstance().isValidFactionId(this.getFactionId())) { if (factionId != null && Factions.getInstance().isValidFactionId(this.getFactionId())) {
@ -310,11 +316,6 @@ public abstract class MemoryFPlayer implements FPlayer {
this.resetFactionData(true); this.resetFactionData(true);
} }
// -------------------------------------------- //
// Getters And Setters
// -------------------------------------------- //
public long getLastLoginTime() { public long getLastLoginTime() {
return lastLoginTime; return lastLoginTime;
} }
@ -336,6 +337,12 @@ public abstract class MemoryFPlayer implements FPlayer {
this.mapAutoUpdating = mapAutoUpdating; this.mapAutoUpdating = mapAutoUpdating;
} }
//----------------------------------------------//
// Title, Name, Faction Tag and Chat
//----------------------------------------------//
// Base:
public boolean hasLoginPvpDisabled() { public boolean hasLoginPvpDisabled() {
if (!loginPvpDisabled) { if (!loginPvpDisabled) {
return false; return false;
@ -355,12 +362,6 @@ public abstract class MemoryFPlayer implements FPlayer {
this.lastStoodAt = flocation; this.lastStoodAt = flocation;
} }
//----------------------------------------------//
// Title, Name, Faction Tag and Chat
//----------------------------------------------//
// Base:
public String getTitle() { public String getTitle() {
return this.hasFaction() ? title : TL.NOFACTION_PREFIX.toString(); return this.hasFaction() ? title : TL.NOFACTION_PREFIX.toString();
} }
@ -374,6 +375,8 @@ public abstract class MemoryFPlayer implements FPlayer {
this.title = title; this.title = title;
} }
// Base concatenations:
public String getName() { public String getName() {
if (this.name == null) { if (this.name == null) {
// Older versions of FactionsUUID don't save the name, // Older versions of FactionsUUID don't save the name,
@ -393,7 +396,8 @@ public abstract class MemoryFPlayer implements FPlayer {
return this.hasFaction() ? this.getFaction().getTag() : ""; return this.hasFaction() ? this.getFaction().getTag() : "";
} }
// Base concatenations: // Colored concatenations:
// These are used in information messages
public String getNameAndSomething(String something) { public String getNameAndSomething(String something) {
String ret = this.role.getPrefix(); String ret = this.role.getPrefix();
@ -408,13 +412,13 @@ public abstract class MemoryFPlayer implements FPlayer {
return this.getNameAndSomething(this.getTitle()); return this.getNameAndSomething(this.getTitle());
} }
// Chat Tag:
// These are injected into the format of global chat messages.
public String getNameAndTag() { public String getNameAndTag() {
return this.getNameAndSomething(this.getTag()); return this.getNameAndSomething(this.getTag());
} }
// Colored concatenations:
// These are used in information messages
public String getNameAndTitle(Faction faction) { public String getNameAndTitle(Faction faction) {
return this.getColorTo(faction) + this.getNameAndTitle(); return this.getColorTo(faction) + this.getNameAndTitle();
} }
@ -423,9 +427,6 @@ public abstract class MemoryFPlayer implements FPlayer {
return this.getColorTo(fplayer) + this.getNameAndTitle(); return this.getColorTo(fplayer) + this.getNameAndTitle();
} }
// Chat Tag:
// These are injected into the format of global chat messages.
public String getChatTag() { public String getChatTag() {
return this.hasFaction() ? String.format(Conf.chatTagFormat, this.getRole().getPrefix() + this.getTag()) : TL.NOFACTION_PREFIX.toString(); return this.hasFaction() ? String.format(Conf.chatTagFormat, this.getRole().getPrefix() + this.getTag()) : TL.NOFACTION_PREFIX.toString();
} }
@ -435,6 +436,10 @@ public abstract class MemoryFPlayer implements FPlayer {
return this.hasFaction() ? this.getRelationTo(faction).getColor() + getChatTag() : ""; return this.hasFaction() ? this.getRelationTo(faction).getColor() + getChatTag() : "";
} }
// -------------------------------
// Relation and relation colors
// -------------------------------
public String getChatTag(MemoryFPlayer fplayer) { public String getChatTag(MemoryFPlayer fplayer) {
return this.hasFaction() ? this.getColorTo(fplayer) + getChatTag() : ""; return this.hasFaction() ? this.getColorTo(fplayer) + getChatTag() : "";
} }
@ -448,10 +453,6 @@ public abstract class MemoryFPlayer implements FPlayer {
} }
// -------------------------------
// Relation and relation colors
// -------------------------------
@Override @Override
public String describeTo(RelationParticipator that, boolean ucfirst) { public String describeTo(RelationParticipator that, boolean ucfirst) {
return RelationUtil.describeThatToMe(this, that, ucfirst); return RelationUtil.describeThatToMe(this, that, ucfirst);
@ -492,7 +493,6 @@ public abstract class MemoryFPlayer implements FPlayer {
player.setHealth(player.getHealth() + amnt); player.setHealth(player.getHealth() + amnt);
} }
//----------------------------------------------// //----------------------------------------------//
// Power // Power
//----------------------------------------------// //----------------------------------------------//
@ -610,6 +610,10 @@ public abstract class MemoryFPlayer implements FPlayer {
} }
} }
// -------------------------------
// Actions
// -------------------------------
/** /**
* Check if the scoreboard should be shown. Simple method to be used by above method. * Check if the scoreboard should be shown. Simple method to be used by above method.
* *
@ -630,10 +634,6 @@ public abstract class MemoryFPlayer implements FPlayer {
this.showScoreboard = show; this.showScoreboard = show;
} }
// -------------------------------
// Actions
// -------------------------------
public void leave(boolean makePay) { public void leave(boolean makePay) {
Faction myFaction = this.getFaction(); Faction myFaction = this.getFaction();
makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing(); makePay = makePay && Econ.shouldBeUsed() && !this.isAdminBypassing();
@ -724,10 +724,9 @@ public abstract class MemoryFPlayer implements FPlayer {
if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(flocation)) { if (Conf.worldGuardChecking && Worldguard.checkForRegionsInChunk(flocation)) {
// Checks for WorldGuard regions in the chunk attempting to be claimed // Checks for WorldGuard regions in the chunk attempting to be claimed
error = P.p.txt.parse(TL.CLAIM_PROTECTED.toString()); error = P.p.txt.parse(TL.CLAIM_PROTECTED.toString());
} else if(flocation.isOutsideWorldBorder(P.p.getConfig().getInt("world-border.buffer", 0))){ } else if (flocation.isOutsideWorldBorder(P.p.getConfig().getInt("world-border.buffer", 0))) {
error = P.p.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString()); error = P.p.txt.parse(TL.CLAIM_OUTSIDEWORLDBORDER.toString());
} } else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) {
else if (Conf.worldsNoClaiming.contains(flocation.getWorldName())) {
error = P.p.txt.parse(TL.CLAIM_DISABLED.toString()); error = P.p.txt.parse(TL.CLAIM_DISABLED.toString());
} else if (this.isAdminBypassing()) { } else if (this.isAdminBypassing()) {
return true; return true;
@ -794,8 +793,6 @@ public abstract class MemoryFPlayer implements FPlayer {
return attemptClaim(forFaction, new FLocation(location), notifyFailure); return attemptClaim(forFaction, new FLocation(location), notifyFailure);
} }
boolean playerAlerts = false;
public boolean shouldBeSaved() { public boolean shouldBeSaved() {
return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting)); return this.hasFaction() || (this.getPowerRounded() != this.getPowerMaxRounded() && this.getPowerRounded() != (int) Math.round(Conf.powerPlayerStarting));
} }
@ -873,20 +870,11 @@ public abstract class MemoryFPlayer implements FPlayer {
isFlying = fly; isFlying = fly;
} }
public boolean isInVault() {
public boolean inVault = false;
public boolean isInVault(){
return inVault; return inVault;
} }
public void setInVault(boolean status){ public void setInVault(boolean status) {
inVault = status; inVault = status;
} }
@ -921,14 +909,14 @@ public abstract class MemoryFPlayer implements FPlayer {
enteringPasswordWarp = warp; enteringPasswordWarp = warp;
} }
public String getEnteringWarp() {
return enteringPasswordWarp;
}
// -------------------------------------------- // // -------------------------------------------- //
// Message Sending Helpers // Message Sending Helpers
// -------------------------------------------- // // -------------------------------------------- //
public String getEnteringWarp() {
return enteringPasswordWarp;
}
public void sendMessage(String msg) { public void sendMessage(String msg) {
if (msg.contains("{null}")) { if (msg.contains("{null}")) {
return; // user wants this message to not send return; // user wants this message to not send
@ -963,7 +951,7 @@ public abstract class MemoryFPlayer implements FPlayer {
public void sendFancyMessage(List<FancyMessage> messages) { public void sendFancyMessage(List<FancyMessage> messages) {
Player player = getPlayer(); Player player = getPlayer();
if (player == null || !player.isOnGround()) { if (player == null) {
return; return;
} }
@ -998,13 +986,13 @@ public abstract class MemoryFPlayer implements FPlayer {
return id; return id;
} }
public abstract void remove();
@Override @Override
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
public abstract void remove();
@Override @Override
public void clearWarmup() { public void clearWarmup() {
if (warmup != null) { if (warmup != null) {
@ -1038,16 +1026,22 @@ public abstract class MemoryFPlayer implements FPlayer {
} }
@Override @Override
public boolean checkIfNearbyEnemies(){ public boolean checkIfNearbyEnemies() {
Player me = this.getPlayer(); Player me = this.getPlayer();
int radius = Conf.enemyFlyCheckRadius; int radius = Conf.enemyFlyCheckRadius;
for (Entity e : me.getNearbyEntities(radius, 255, radius)) { for (Entity e : me.getNearbyEntities(radius, 255, radius)) {
if (e == null) { continue; } if (e == null) {
continue;
}
if (e instanceof Player) { if (e instanceof Player) {
Player eplayer = (((Player) e).getPlayer()); Player eplayer = (((Player) e).getPlayer());
if (eplayer == null) { continue; } if (eplayer == null) {
continue;
}
FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer); FPlayer efplayer = FPlayers.getInstance().getByPlayer(eplayer);
if (efplayer == null) { continue; } if (efplayer == null) {
continue;
}
if (this.getRelationTo(efplayer).equals(Relation.ENEMY)) { if (this.getRelationTo(efplayer).equals(Relation.ENEMY)) {
this.setFlying(false); this.setFlying(false);
@ -1071,7 +1065,6 @@ public abstract class MemoryFPlayer implements FPlayer {
} }
@Override @Override
public Boolean canflyinSafezone() { public Boolean canflyinSafezone() {
return getPlayer().hasPermission("factions.fly.safezone"); return getPlayer().hasPermission("factions.fly.safezone");
@ -1102,15 +1095,13 @@ public abstract class MemoryFPlayer implements FPlayer {
} }
boolean inspectMode = false;
@Override @Override
public boolean isInspectMode(){ public boolean isInspectMode() {
return inspectMode; return inspectMode;
} }
@Override @Override
public void setInspectMode( boolean status){ public void setInspectMode(boolean status) {
inspectMode = status; inspectMode = status;
} }

View File

@ -33,6 +33,11 @@ import static com.massivecraft.factions.util.InventoryUtil.InventoryToString;
import static com.massivecraft.factions.util.InventoryUtil.StringToInventory; import static com.massivecraft.factions.util.InventoryUtil.StringToInventory;
public abstract class MemoryFaction implements Faction, EconomyParticipator { public abstract class MemoryFaction implements Faction, EconomyParticipator {
public HashMap<Integer, String> rules = new HashMap<Integer, String>();
public int tnt;
public Location checkpoint;
public LazyLocation vault;
public HashMap<String, Integer> upgrades = new HashMap<>();
protected String id = null; protected String id = null;
protected boolean peacefulExplosionsEnabled; protected boolean peacefulExplosionsEnabled;
protected boolean permanent; protected boolean permanent;
@ -53,11 +58,61 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
protected HashMap<String, List<String>> announcements = new HashMap<>(); protected HashMap<String, List<String>> announcements = new HashMap<>();
protected ConcurrentHashMap<String, LazyLocation> warps = new ConcurrentHashMap<>(); protected ConcurrentHashMap<String, LazyLocation> warps = new ConcurrentHashMap<>();
protected ConcurrentHashMap<String, String> warpPasswords = new ConcurrentHashMap<>(); protected ConcurrentHashMap<String, String> warpPasswords = new ConcurrentHashMap<>();
private long lastDeath;
protected int maxVaults; protected int maxVaults;
protected Role defaultRole; protected Role defaultRole;
protected Map<Permissable, Map<PermissableAction, Access>> permissions = new HashMap<>(); protected Map<Permissable, Map<PermissableAction, Access>> permissions = new HashMap<>();
protected Set<BanInfo> bans = new HashSet<>(); protected Set<BanInfo> bans = new HashSet<>();
String chestSerialized = null;
Map<String, Object> bannerSerialized;
private long lastDeath;
// -------------------------------------------- //
// Construct
// -------------------------------------------- //
public MemoryFaction() {
}
public MemoryFaction(String id) {
this.id = id;
this.open = Conf.newFactionsDefaultOpen;
this.tag = "???";
this.description = TL.GENERIC_DEFAULTDESCRIPTION.toString();
this.lastPlayerLoggedOffTime = 0;
this.peaceful = false;
this.peacefulExplosionsEnabled = false;
this.permanent = false;
this.money = 0.0;
this.powerBoost = 0.0;
this.foundedDate = System.currentTimeMillis();
this.maxVaults = Conf.defaultMaxVaults;
this.defaultRole = Role.RECRUIT;
resetPerms(); // Reset on new Faction so it has default values.
}
public MemoryFaction(MemoryFaction old) {
id = old.id;
peacefulExplosionsEnabled = old.peacefulExplosionsEnabled;
permanent = old.permanent;
tag = old.tag;
description = old.description;
open = old.open;
foundedDate = old.foundedDate;
peaceful = old.peaceful;
permanentPower = old.permanentPower;
home = old.home;
lastPlayerLoggedOffTime = old.lastPlayerLoggedOffTime;
money = old.money;
powerBoost = old.powerBoost;
relationWish = old.relationWish;
claimOwnership = old.claimOwnership;
fplayers = new HashSet<>();
invites = old.invites;
announcements = old.announcements;
this.defaultRole = Role.NORMAL;
resetPerms(); // Reset on new Faction so it has default values.
}
public HashMap<String, List<String>> getAnnouncements() { public HashMap<String, List<String>> getAnnouncements() {
return this.announcements; return this.announcements;
@ -184,51 +239,46 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return this.bans; return this.bans;
} }
public HashMap<Integer,String> rules = new HashMap<Integer, String>(); public String getRule(int index) {
public String getRule(int index){
if (rules.size() == 0) return null; if (rules.size() == 0) return null;
return rules.get(index); return rules.get(index);
} }
public HashMap<Integer,String> getRulesMap(){ public HashMap<Integer, String> getRulesMap() {
return rules; return rules;
} }
public void setRule(int index,String rule) { public void setRule(int index, String rule) {
rules.put(index,rule); rules.put(index, rule);
} }
public void removeRule(int index){ public void removeRule(int index) {
HashMap<Integer,String> newRule = rules; HashMap<Integer, String> newRule = rules;
newRule.remove(index); newRule.remove(index);
rules = newRule; rules = newRule;
} }
public int tnt; public void addTnt(int amt) {
public void addTnt(int amt){
tnt += amt; tnt += amt;
} }
public void takeTnt(int amt){ public void takeTnt(int amt) {
tnt -=amt; tnt -= amt;
} }
public int getTnt() { return tnt; } public int getTnt() {
return tnt;
public Location checkpoint; }
public LazyLocation vault;
public Location getVault() { public Location getVault() {
if (vault == null){ if (vault == null) {
return null; return null;
} }
return vault.getLocation(); return vault.getLocation();
} }
public void setVault(Location vaultLocation){
if (vaultLocation == null){ public void setVault(Location vaultLocation) {
if (vaultLocation == null) {
vault = null; vault = null;
return; return;
} }
@ -236,16 +286,13 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
vault = newlocation; vault = newlocation;
} }
public HashMap<String,Integer> upgrades = new HashMap<>(); public int getUpgrade(String key) {
if (upgrades.keySet().contains(key)) {
public int getUpgrade(String key){ return upgrades.get(key);
if (upgrades.keySet().contains(key)) { return upgrades.get(key);} }
return 0; return 0;
} }
String chestSerialized = null;
Map<String, Object> bannerSerialized;
@Override @Override
public Inventory getChest() { public Inventory getChest() {
int level = getUpgrade("Chest"); int level = getUpgrade("Chest");
@ -278,8 +325,6 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
chestSerialized = InventoryToString(inventory.getContents()); chestSerialized = InventoryToString(inventory.getContents());
} }
@Override @Override
public void setBannerPattern(ItemStack banner) { public void setBannerPattern(ItemStack banner) {
bannerSerialized = banner.serialize(); bannerSerialized = banner.serialize();
@ -293,23 +338,24 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return ItemStack.deserialize(bannerSerialized); return ItemStack.deserialize(bannerSerialized);
} }
public void setUpgrades(String key,int level){ upgrades.put(key,level); } public void setUpgrades(String key, int level) {
upgrades.put(key, level);
public void setCheckpoint(Location location){
checkpoint = location;
} }
public Location getCheckpoint(){
public Location getCheckpoint() {
return checkpoint; return checkpoint;
} }
public void setCheckpoint(Location location) {
checkpoint = location;
}
public void clearRules(){ public void clearRules() {
rules.clear(); rules.clear();
} }
public void addRule(String rule){ public void addRule(String rule) {
rules.put(rules.size(),rule); rules.put(rules.size(), rule);
} }
public boolean getOpen() { public boolean getOpen() {
@ -328,14 +374,14 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
this.peaceful = isPeaceful; this.peaceful = isPeaceful;
} }
public void setPeacefulExplosionsEnabled(boolean val) {
peacefulExplosionsEnabled = val;
}
public boolean getPeacefulExplosionsEnabled() { public boolean getPeacefulExplosionsEnabled() {
return this.peacefulExplosionsEnabled; return this.peacefulExplosionsEnabled;
} }
public void setPeacefulExplosionsEnabled(boolean val) {
peacefulExplosionsEnabled = val;
}
public boolean noExplosionsInTerritory() { public boolean noExplosionsInTerritory() {
return this.peaceful && !peacefulExplosionsEnabled; return this.peaceful && !peacefulExplosionsEnabled;
} }
@ -352,6 +398,13 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return this.tag; return this.tag;
} }
public void setTag(String str) {
if (Conf.factionTagForceUpperCase) {
str = str.toUpperCase();
}
this.tag = str;
}
public String getTag(String prefix) { public String getTag(String prefix) {
return prefix + this.tag; return prefix + this.tag;
} }
@ -370,14 +423,6 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return this.getTag(this.getColorTo(otherFplayer).toString()); return this.getTag(this.getColorTo(otherFplayer).toString());
} }
public void setTag(String str) {
if (Conf.factionTagForceUpperCase) {
str = str.toUpperCase();
}
this.tag = str;
}
public String getComparisonTag() { public String getComparisonTag() {
return MiscUtil.getComparisonString(this.tag); return MiscUtil.getComparisonString(this.tag);
} }
@ -390,10 +435,6 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
this.description = value; this.description = value;
} }
public void setHome(Location home) {
this.home = new LazyLocation(home);
}
public boolean hasHome() { public boolean hasHome() {
return this.getHome() != null; return this.getHome() != null;
} }
@ -403,6 +444,10 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return (this.home != null) ? this.home.getLocation() : null; return (this.home != null) ? this.home.getLocation() : null;
} }
public void setHome(Location home) {
this.home = new LazyLocation(home);
}
public long getFoundedDate() { public long getFoundedDate() {
if (this.foundedDate == 0) { if (this.foundedDate == 0) {
setFoundedDate(System.currentTimeMillis()); setFoundedDate(System.currentTimeMillis());
@ -434,7 +479,6 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return aid; return aid;
} }
public Integer getPermanentPower() { public Integer getPermanentPower() {
return this.permanentPower; return this.permanentPower;
} }
@ -461,14 +505,18 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
} }
public void setLastDeath(long time) {
this.lastDeath = time;
}
public long getLastDeath() { public long getLastDeath() {
return this.lastDeath; return this.lastDeath;
} }
// -------------------------------------------- //
// F Permissions stuff
// -------------------------------------------- //
public void setLastDeath(long time) {
this.lastDeath = time;
}
public int getKills() { public int getKills() {
int kills = 0; int kills = 0;
for (FPlayer fp : getFPlayers()) { for (FPlayer fp : getFPlayers()) {
@ -487,11 +535,6 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return deaths; return deaths;
} }
// -------------------------------------------- //
// F Permissions stuff
// -------------------------------------------- //
public Access getAccess(Permissable permissable, PermissableAction permissableAction) { public Access getAccess(Permissable permissable, PermissableAction permissableAction) {
if (permissable == null || permissableAction == null) { if (permissable == null || permissableAction == null) {
return Access.UNDEFINED; return Access.UNDEFINED;
@ -533,8 +576,6 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
return Access.UNDEFINED; return Access.UNDEFINED;
} }
public void setPermission(Permissable permissable, PermissableAction permissableAction, Access access) { public void setPermission(Permissable permissable, PermissableAction permissableAction, Access access) {
Map<PermissableAction, Access> accessMap = permissions.get(permissable); Map<PermissableAction, Access> accessMap = permissions.get(permissable);
if (accessMap == null) { if (accessMap == null) {
@ -587,54 +628,6 @@ public abstract class MemoryFaction implements Faction, EconomyParticipator {
this.defaultRole = role; this.defaultRole = role;
} }
// -------------------------------------------- //
// Construct
// -------------------------------------------- //
public MemoryFaction() {
}
public MemoryFaction(String id) {
this.id = id;
this.open = Conf.newFactionsDefaultOpen;
this.tag = "???";
this.description = TL.GENERIC_DEFAULTDESCRIPTION.toString();
this.lastPlayerLoggedOffTime = 0;
this.peaceful = false;
this.peacefulExplosionsEnabled = false;
this.permanent = false;
this.money = 0.0;
this.powerBoost = 0.0;
this.foundedDate = System.currentTimeMillis();
this.maxVaults = Conf.defaultMaxVaults;
this.defaultRole = Role.RECRUIT;
resetPerms(); // Reset on new Faction so it has default values.
}
public MemoryFaction(MemoryFaction old) {
id = old.id;
peacefulExplosionsEnabled = old.peacefulExplosionsEnabled;
permanent = old.permanent;
tag = old.tag;
description = old.description;
open = old.open;
foundedDate = old.foundedDate;
peaceful = old.peaceful;
permanentPower = old.permanentPower;
home = old.home;
lastPlayerLoggedOffTime = old.lastPlayerLoggedOffTime;
money = old.money;
powerBoost = old.powerBoost;
relationWish = old.relationWish;
claimOwnership = old.claimOwnership;
fplayers = new HashSet<>();
invites = old.invites;
announcements = old.announcements;
this.defaultRole = Role.NORMAL;
resetPerms(); // Reset on new Faction so it has default values.
}
// -------------------------------------------- // // -------------------------------------------- //
// Extra Getters And Setters // Extra Getters And Setters
// -------------------------------------------- // // -------------------------------------------- //

View File

@ -23,6 +23,12 @@ import java.util.logging.Level;
public class JSONFPlayers extends MemoryFPlayers { public class JSONFPlayers extends MemoryFPlayers {
// Info on how to persist // Info on how to persist
private Gson gson; private Gson gson;
private File file;
public JSONFPlayers() {
file = new File(P.p.getDataFolder(), "players.json");
gson = P.p.gson;
}
public Gson getGson() { public Gson getGson() {
return gson; return gson;
@ -32,13 +38,6 @@ public class JSONFPlayers extends MemoryFPlayers {
this.gson = gson; this.gson = gson;
} }
private File file;
public JSONFPlayers() {
file = new File(P.p.getDataFolder(), "players.json");
gson = P.p.gson;
}
public void convertFrom(MemoryFPlayers old) { public void convertFrom(MemoryFPlayers old) {
this.fPlayers.putAll(Maps.transformValues(old.fPlayers, new Function<FPlayer, JSONFPlayer>() { this.fPlayers.putAll(Maps.transformValues(old.fPlayers, new Function<FPlayer, JSONFPlayer>() {
@Override @Override

View File

@ -23,25 +23,24 @@ import java.util.logging.Level;
public class JSONFactions extends MemoryFactions { public class JSONFactions extends MemoryFactions {
// Info on how to persist // Info on how to persist
private final Gson gson; private final Gson gson;
private final File file;
public JSONFactions() {
this.file = new File(P.p.getDataFolder(), "factions.json");
this.gson = P.p.gson;
this.nextId = 1;
}
public Gson getGson() { public Gson getGson() {
return gson; return gson;
} }
private final File file;
public File getFile() {
return file;
}
// -------------------------------------------- // // -------------------------------------------- //
// CONSTRUCTORS // CONSTRUCTORS
// -------------------------------------------- // // -------------------------------------------- //
public JSONFactions() { public File getFile() {
this.file = new File(P.p.getDataFolder(), "factions.json"); return file;
this.gson = P.p.gson;
this.nextId = 1;
} }
public void forceSave() { public void forceSave() {

View File

@ -20,7 +20,7 @@ public class DiscUtil {
// -------------------------------------------- // // -------------------------------------------- //
// BYTE // BYTE
// -------------------------------------------- // // -------------------------------------------- //
private static HashMap<String, Lock> locks = new HashMap<>();
public static byte[] readBytes(File file) throws IOException { public static byte[] readBytes(File file) throws IOException {
int length = (int) file.length(); int length = (int) file.length();
@ -34,29 +34,27 @@ public class DiscUtil {
return output; return output;
} }
// -------------------------------------------- //
// STRING
// -------------------------------------------- //
public static void writeBytes(File file, byte[] bytes) throws IOException { public static void writeBytes(File file, byte[] bytes) throws IOException {
FileOutputStream out = new FileOutputStream(file); FileOutputStream out = new FileOutputStream(file);
out.write(bytes); out.write(bytes);
out.close(); out.close();
} }
// -------------------------------------------- //
// STRING
// -------------------------------------------- //
public static void write(File file, String content) throws IOException { public static void write(File file, String content) throws IOException {
writeBytes(file, utf8(content)); writeBytes(file, utf8(content));
} }
public static String read(File file) throws IOException {
return utf8(readBytes(file));
}
// -------------------------------------------- // // -------------------------------------------- //
// CATCH // CATCH
// -------------------------------------------- // // -------------------------------------------- //
private static HashMap<String, Lock> locks = new HashMap<>(); public static String read(File file) throws IOException {
return utf8(readBytes(file));
}
public static boolean writeCatch(final File file, final String content, boolean sync) { public static boolean writeCatch(final File file, final String content, boolean sync) {
String name = file.getName(); String name = file.getName();

View File

@ -730,7 +730,6 @@ public enum TL {
COMMAND_RULES_CLEAR_SUCCESS("&cRule cleared successfully!"), COMMAND_RULES_CLEAR_SUCCESS("&cRule cleared successfully!"),
/** /**
* Leaving - This is accessed through a command, and so it MAY need a COMMAND_* slug :s * Leaving - This is accessed through a command, and so it MAY need a COMMAND_* slug :s
*/ */
@ -811,7 +810,6 @@ public enum TL {
GENERIC_PLACEHOLDER("<This is a placeholder for a message you should not see>"), GENERIC_PLACEHOLDER("<This is a placeholder for a message you should not see>"),
WARBANNER_NOFACTION("&cYou need a faction to use a warbanner!"), WARBANNER_NOFACTION("&cYou need a faction to use a warbanner!"),
WARBANNER_COOLDOWN("&cThe warbanner is on cooldown for your faction!"), WARBANNER_COOLDOWN("&cThe warbanner is on cooldown for your faction!"),
WARBANNER_INVALIDLOC("&cYou can only use warbanners in enemy land or the warzone"), WARBANNER_INVALIDLOC("&cYou can only use warbanners in enemy land or the warzone"),
@ -945,10 +943,10 @@ public enum TL {
WARMUPS_ALREADY("&cYou are already warming up."), WARMUPS_ALREADY("&cYou are already warming up."),
WARMUPS_CANCELLED("&cYou have cancelled your warmup."); WARMUPS_CANCELLED("&cYou have cancelled your warmup.");
public static SimpleDateFormat sdf;
private static YamlConfiguration LANG;
private String path; private String path;
private String def; private String def;
private static YamlConfiguration LANG;
public static SimpleDateFormat sdf;
/** /**
* Lang enum constructor. * Lang enum constructor.

View File

@ -86,20 +86,31 @@ public enum TagReplacer {
private TagType type; private TagType type;
private String tag; private String tag;
protected enum TagType {
FANCY(0), PLAYER(1), FACTION(2), GENERAL(3);
public int id;
TagType(int id) {
this.id = id;
}
}
TagReplacer(TagType type, String tag) { TagReplacer(TagType type, String tag) {
this.type = type; this.type = type;
this.tag = tag; this.tag = tag;
} }
/**
* Returns a list of all the variables we can use for this type<br>
*
* @param type the type we want
* @return a list of all the variables with this type
*/
protected static List<TagReplacer> getByType(TagType type) {
List<TagReplacer> tagReplacers = new ArrayList<>();
for (TagReplacer tagReplacer : TagReplacer.values()) {
if (type == TagType.FANCY) {
if (tagReplacer.type == TagType.FANCY) {
tagReplacers.add(tagReplacer);
}
} else if (tagReplacer.type.id >= type.id) {
tagReplacers.add(tagReplacer);
}
}
return tagReplacers;
}
/** /**
* Protected access to this generic server related variable * Protected access to this generic server related variable
* *
@ -245,26 +256,6 @@ public enum TagReplacer {
return null; return null;
} }
/**
* Returns a list of all the variables we can use for this type<br>
*
* @param type the type we want
* @return a list of all the variables with this type
*/
protected static List<TagReplacer> getByType(TagType type) {
List<TagReplacer> tagReplacers = new ArrayList<>();
for (TagReplacer tagReplacer : TagReplacer.values()) {
if (type == TagType.FANCY) {
if (tagReplacer.type == TagType.FANCY) {
tagReplacers.add(tagReplacer);
}
} else if (tagReplacer.type.id >= type.id) {
tagReplacers.add(tagReplacer);
}
}
return tagReplacers;
}
/** /**
* @param original raw line with variables * @param original raw line with variables
* @param value what to replace var in raw line with * @param value what to replace var in raw line with
@ -293,4 +284,13 @@ public enum TagReplacer {
public String getTag() { public String getTag() {
return this.tag; return this.tag;
} }
protected enum TagType {
FANCY(0), PLAYER(1), FACTION(2), GENERAL(3);
public int id;
TagType(int id) {
this.id = id;
}
}
} }

View File

@ -10,34 +10,23 @@ import java.util.regex.Pattern;
public class TextUtil { public class TextUtil {
public Map<String, String> tags; public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>");
private final static String titleizeLine = repeat("-", 52);
public TextUtil() {
this.tags = new HashMap<>();
}
// -------------------------------------------- // // -------------------------------------------- //
// Top-level parsing functions. // Top-level parsing functions.
// -------------------------------------------- // // -------------------------------------------- //
private final static int titleizeBalance = -1;
public String parse(String str, Object... args) { public Map<String, String> tags;
return String.format(this.parse(str), args);
}
public String parse(String str) {
return this.parseTags(parseColor(str));
}
// -------------------------------------------- // // -------------------------------------------- //
// Tag parsing // Tag parsing
// -------------------------------------------- // // -------------------------------------------- //
public String parseTags(String str) { public TextUtil() {
return replaceTags(str, this.tags); this.tags = new HashMap<>();
} }
public static final transient Pattern patternTag = Pattern.compile("<([a-zA-Z0-9_]*)>");
public static String replaceTags(String str, Map<String, String> tags) { public static String replaceTags(String str, Map<String, String> tags) {
StringBuffer ret = new StringBuffer(); StringBuffer ret = new StringBuffer();
Matcher matcher = patternTag.matcher(str); Matcher matcher = patternTag.matcher(str);
@ -54,14 +43,6 @@ public class TextUtil {
return ret.toString(); return ret.toString();
} }
// -------------------------------------------- //
// Fancy parsing
// -------------------------------------------- //
public FancyMessage parseFancy(String prefix) {
return toFancy(parse(prefix));
}
public static FancyMessage toFancy(String first) { public static FancyMessage toFancy(String first) {
String text = ""; String text = "";
FancyMessage message = new FancyMessage(text); FancyMessage message = new FancyMessage(text);
@ -101,7 +82,7 @@ public class TextUtil {
} }
// -------------------------------------------- // // -------------------------------------------- //
// Color parsing // Fancy parsing
// -------------------------------------------- // // -------------------------------------------- //
public static String parseColor(String string) { public static String parseColor(String string) {
@ -118,6 +99,10 @@ public class TextUtil {
return string; return string;
} }
// -------------------------------------------- //
// Color parsing
// -------------------------------------------- //
public static String parseColorAcc(String string) { public static String parseColorAcc(String string) {
return string.replace("`e", "").replace("`r", ChatColor.RED.toString()).replace("`R", ChatColor.DARK_RED.toString()).replace("`y", ChatColor.YELLOW.toString()).replace("`Y", ChatColor.GOLD.toString()).replace("`g", ChatColor.GREEN.toString()).replace("`G", ChatColor.DARK_GREEN.toString()).replace("`a", ChatColor.AQUA.toString()).replace("`A", ChatColor.DARK_AQUA.toString()).replace("`b", ChatColor.BLUE.toString()).replace("`B", ChatColor.DARK_BLUE.toString()).replace("`p", ChatColor.LIGHT_PURPLE.toString()).replace("`P", ChatColor.DARK_PURPLE.toString()).replace("`k", ChatColor.BLACK.toString()).replace("`s", ChatColor.GRAY.toString()).replace("`S", ChatColor.DARK_GRAY.toString()).replace("`w", ChatColor.WHITE.toString()); return string.replace("`e", "").replace("`r", ChatColor.RED.toString()).replace("`R", ChatColor.DARK_RED.toString()).replace("`y", ChatColor.YELLOW.toString()).replace("`Y", ChatColor.GOLD.toString()).replace("`g", ChatColor.GREEN.toString()).replace("`G", ChatColor.DARK_GREEN.toString()).replace("`a", ChatColor.AQUA.toString()).replace("`A", ChatColor.DARK_AQUA.toString()).replace("`b", ChatColor.BLUE.toString()).replace("`B", ChatColor.DARK_BLUE.toString()).replace("`p", ChatColor.LIGHT_PURPLE.toString()).replace("`P", ChatColor.DARK_PURPLE.toString()).replace("`k", ChatColor.BLACK.toString()).replace("`s", ChatColor.GRAY.toString()).replace("`S", ChatColor.DARK_GRAY.toString()).replace("`w", ChatColor.WHITE.toString());
} }
@ -126,10 +111,6 @@ public class TextUtil {
return string.replace("<empty>", "").replace("<black>", "\u00A70").replace("<navy>", "\u00A71").replace("<green>", "\u00A72").replace("<teal>", "\u00A73").replace("<red>", "\u00A74").replace("<purple>", "\u00A75").replace("<gold>", "\u00A76").replace("<silver>", "\u00A77").replace("<gray>", "\u00A78").replace("<blue>", "\u00A79").replace("<lime>", "\u00A7a").replace("<aqua>", "\u00A7b").replace("<rose>", "\u00A7c").replace("<pink>", "\u00A7d").replace("<yellow>", "\u00A7e").replace("<white>", "\u00A7f"); return string.replace("<empty>", "").replace("<black>", "\u00A70").replace("<navy>", "\u00A71").replace("<green>", "\u00A72").replace("<teal>", "\u00A73").replace("<red>", "\u00A74").replace("<purple>", "\u00A75").replace("<gold>", "\u00A76").replace("<silver>", "\u00A77").replace("<gray>", "\u00A78").replace("<blue>", "\u00A79").replace("<lime>", "\u00A7a").replace("<aqua>", "\u00A7b").replace("<rose>", "\u00A7c").replace("<pink>", "\u00A7d").replace("<yellow>", "\u00A7e").replace("<white>", "\u00A7f");
} }
// -------------------------------------------- //
// Standard utils like UCFirst, implode and repeat.
// -------------------------------------------- //
public static String upperCaseFirst(String string) { public static String upperCaseFirst(String string) {
return string.substring(0, 1).toUpperCase() + string.substring(1); return string.substring(0, 1).toUpperCase() + string.substring(1);
} }
@ -145,6 +126,10 @@ public class TextUtil {
return ret.toString(); return ret.toString();
} }
// -------------------------------------------- //
// Standard utils like UCFirst, implode and repeat.
// -------------------------------------------- //
public static String repeat(String s, int times) { public static String repeat(String s, int times) {
if (times <= 0) { if (times <= 0) {
return ""; return "";
@ -153,10 +138,6 @@ public class TextUtil {
} }
} }
// -------------------------------------------- //
// Material name tools
// -------------------------------------------- //
public static String getMaterialName(Material material) { public static String getMaterialName(Material material) {
return material.toString().replace('_', ' ').toLowerCase(); return material.toString().replace('_', ' ').toLowerCase();
} }
@ -165,12 +146,56 @@ public class TextUtil {
return getMaterialName(Material.getMaterial(materialId)); return getMaterialName(Material.getMaterial(materialId));
} }
// -------------------------------------------- //
// Material name tools
// -------------------------------------------- //
public static String getBestStartWithCI(Collection<String> candidates, String start) {
String ret = null;
int best = 0;
start = start.toLowerCase();
int minlength = start.length();
for (String candidate : candidates) {
if (candidate.length() < minlength) {
continue;
}
if (!candidate.toLowerCase().startsWith(start)) {
continue;
}
// The closer to zero the better
int lendiff = candidate.length() - minlength;
if (lendiff == 0) {
return candidate;
}
if (lendiff < best || best == 0) {
best = lendiff;
ret = candidate;
}
}
return ret;
}
public String parse(String str, Object... args) {
return String.format(this.parse(str), args);
}
// -------------------------------------------- // // -------------------------------------------- //
// Paging and chrome-tools like titleize // Paging and chrome-tools like titleize
// -------------------------------------------- // // -------------------------------------------- //
private final static String titleizeLine = repeat("-", 52); public String parse(String str) {
private final static int titleizeBalance = -1; return this.parseTags(parseColor(str));
}
public String parseTags(String str) {
return replaceTags(str, this.tags);
}
public FancyMessage parseFancy(String prefix) {
return toFancy(parse(prefix));
}
public String titleize(String str) { public String titleize(String str) {
String center = ChatColor.DARK_GRAY + "< " + parseTags("<l>") + str + parseTags("<a>") + ChatColor.DARK_GRAY + " >"; String center = ChatColor.DARK_GRAY + "< " + parseTags("<l>") + str + parseTags("<a>") + ChatColor.DARK_GRAY + " >";
@ -212,31 +237,4 @@ public class TextUtil {
return ret; return ret;
} }
public static String getBestStartWithCI(Collection<String> candidates, String start) {
String ret = null;
int best = 0;
start = start.toLowerCase();
int minlength = start.length();
for (String candidate : candidates) {
if (candidate.length() < minlength) {
continue;
}
if (!candidate.toLowerCase().startsWith(start)) {
continue;
}
// The closer to zero the better
int lendiff = candidate.length() - minlength;
if (lendiff == 0) {
return candidate;
}
if (lendiff < best || best == 0) {
best = lendiff;
ret = candidate;
}
}
return ret;
}
} }

View File

@ -33,28 +33,6 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
this(names, true); this(names, true);
} }
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
private static void writeBody(HttpURLConnection connection, String body) throws Exception { private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream(); OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes()); stream.write(body.getBytes());
@ -97,4 +75,26 @@ public class UUIDFetcher implements Callable<Map<String, UUID>> {
public static UUID getUUIDOf(String name) throws Exception { public static UUID getUUIDOf(String name) throws Exception {
return new UUIDFetcher(Collections.singletonList(name)).call().get(name); return new UUIDFetcher(Collections.singletonList(name)).call().get(name);
} }
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
} }